@tinkerlandai/indiana-react-native 0.9.5 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var Zg=Object.defineProperty;var Wg=(e,t,n)=>t in e?Zg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qe=(e,t,n)=>Wg(e,typeof t!="symbol"?t+"":t,n);import{z as Ba}from"zod";var Yg=Ba.enum(["sandbox","live"]),Ve=Ba.object({projectId:Ba.string().min(1),environment:Yg}).strict();import{z as Ue}from"zod";var gi=Ue.number().int().min(1).max(Number.MAX_SAFE_INTEGER),bu=Ue.enum(["unknown","denied","provisional","granted"]),Su=Ue.enum(["ios","android"]),uo=Ue.strictObject({installationId:Ue.uuid(),publicKey:Ue.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:Ue.iso.datetime({offset:!0}),signature:Ue.string().regex(/^[A-Za-z0-9_-]{86}$/)}),za=Ue.string().regex(/^[a-f0-9]{64}$/),xu=uo.extend({sequence:gi,platform:Su,credentialDigest:za}),Iu=uo.extend({credentialDigest:za}),vu=uo.extend({sequence:gi,platform:Su}),lo=uo.extend({sequence:gi,credentialDigest:za,connectionId:Ue.uuid().nullable(),kind:Ue.enum(["fcm_token","apns_token"]).nullable(),token:Ue.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:bu}),wu=lo,Ou=lo.extend({challenge:Ue.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),$a=Ue.strictObject({requested:Ue.literal(!0),expiresAt:Ue.iso.datetime({offset:!0})}),sr=Ue.strictObject({installationId:Ue.uuid(),bound:Ue.boolean(),identitySeq:gi,bindingGeneration:gi,addressSeq:Ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:Ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:Ue.uuid().nullable(),addressStatus:Ue.enum(["active","invalid"]).nullable(),permission:bu}),Ga=Ue.strictObject({channel:Ue.enum(["email","sms","voice","push"]),state:Ue.enum(["unknown","allowed","denied"]),revision:Ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Ue.iso.datetime({offset:!0}).nullable()}),O0=Ue.strictObject({state:Ue.enum(["allowed","denied"]),revision:Ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Cu(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 yt}from"zod";var cr=yt.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"]),_0=yt.enum([...cr.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),E0=yt.enum([...cr.options,"stale_revision"]),Xg=yt.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"]),eh=yt.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),_u={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 Pu={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 th(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(Pu,e)){let r=Pu[e];return{retryable:r==="retry_same_request",recovery:r}}let n=cr.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:_u[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Eu(e,t){let n=cr.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):_u[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 nh(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 Ru=yt.object({retryable:yt.boolean(),recovery:Xg,reason:eh.optional(),retryAfterSeconds:yt.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Ka=yt.object({requestId:yt.uuid().optional(),error:yt.object({code:yt.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:yt.string(),...Ru.partial().shape})}),R0=yt.object({error:Ka.shape.error.extend({requestId:yt.uuid().optional()})}),k0=yt.object({error:yt.string(),code:yt.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:yt.uuid(),...Ru.shape});function po(e,t,n={}){let r=th(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?nh(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var Ha="X-Indiana-Protocol",ku="X-Indiana-SDK-Version";var Qa={current:"0.9"};import{z as rh}from"zod";var ih=["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"],fe=rh.enum(ih);import{z as bt}from"zod";var oh=bt.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"]),ju=bt.strictObject({provider:bt.literal("stripe"),accountId:bt.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:bt.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:oh,occurredAt:bt.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:bt.record(bt.string(),bt.unknown()).and(bt.object({id:bt.string().min(1).max(255),object:bt.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:bt.boolean()}))}),Tu=bt.strictObject({id:bt.uuid(),eventId:bt.string().min(1).max(200),source:bt.literal("merchant"),providerVerified:bt.literal(!1),outcome:bt.string().min(1).max(100)});import{z as ur}from"zod";var jt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,kr=ur.object({customerId:ur.uuid(),sessionId:ur.uuid(),accessToken:ur.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:ur.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:ur.iso.datetime(),refreshExpiresAt:ur.iso.datetime()});import{z as jr}from"zod";var mo=jr.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"),B0=jr.object({amountCents:jr.number().int().min(0).max(1e8),currency:fe,interval:jr.enum(["free","month","year"]),currencyOptions:jr.partialRecord(fe,jr.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 T}from"zod";var ah=T.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Fu=T.enum(["single_use","continuous_use"]),Ja=T.record(T.string(),T.union([T.string(),T.number(),T.boolean()]).transform(String).pipe(T.string())),Nu=T.string().min(1).max(64).refine(e=>!e.includes("::")),Mu={credit_amount:T.number(),tier_behavior:T.never().optional(),tiers:T.never().optional()},qu={credit_amount:T.never().optional(),tier_behavior:T.literal("graduated"),tiers:T.array(T.strictObject({to:T.union([T.number(),T.literal("inf")]),credit_amount:T.number()}))},sh=T.union([T.strictObject({match:Ja,priority:T.number().int().optional(),...Mu}),T.strictObject({match:Ja,priority:T.number().int().optional(),...qu})]),ch=T.strictObject({match:Ja,factor:T.number().positive().optional(),add:T.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Du={metered_feature_id:T.string(),feature_amount:T.number().optional(),dimensions:T.record(Nu,sh).optional(),multipliers:T.record(Nu,ch).optional()},Za=T.union([T.strictObject({...Du,...Mu}),T.strictObject({...Du,...qu})]),go=T.number().min(-100),Vu=T.record(T.string(),T.strictObject({markup:go})).nullish(),ho=T.record(T.string().regex(/.+\/.+/),T.strictObject({markup:go.optional(),input_cost:T.number().min(0).optional(),output_cost:T.number().min(0).optional()})).nullish(),uh=T.strictObject({default_markup:go.optional(),provider_markups:Vu,model_markups:ho}),G0=T.strictObject({schema:T.array(Za).optional(),markups:uh.optional()}),lh=T.strictObject({filters:T.array(T.strictObject({property:T.string(),operator:T.string(),value:T.array(T.string())})),aggregate:T.strictObject({type:T.string(),property:T.string().nullable()}),usage_type:Fu}),Uu=T.strictObject({schema:T.array(Za).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:T.boolean().optional(),usage_type:Fu.default("single_use").overwrite(()=>"single_use"),default_markup:go.optional(),provider_markups:Vu}),Wa=Uu.safeExtend({schema:T.array(Za).length(0)}),fo={id:ah,name:T.string().min(1),display:T.strictObject({singular:T.string().optional(),plural:T.string().optional()}).nullish(),event_names:T.array(T.string()).default([]),model_markups:ho,stripe_meter:T.strictObject({id:T.string(),event_name:T.string()}).nullish(),stripe_product_id:T.string().nullish()},Ya=e=>T.discriminatedUnion("type",[T.strictObject({...fo,...e,type:T.literal("boolean"),config:T.null()}),T.strictObject({...fo,...e,type:T.literal("metered"),config:lh}),T.strictObject({...fo,...e,type:T.literal("credit_system"),config:Uu}),T.strictObject({...fo,...e,type:T.literal("ai_credit_system"),config:Wa})]),K0=Ya({}),dh=T.strictObject({id:T.boolean(),type:T.boolean(),usage_type:T.boolean()}),ph={internal_id:T.uuid(),org_id:T.uuid(),created_at:T.number(),env:T.enum(["sandbox","live"]),archived:T.boolean(),project_id:T.uuid(),environment_id:T.uuid(),revision:T.number().int().nonnegative(),update_rules:dh},Lu=Ya(ph),H0=T.strictObject({rows:T.array(Lu).max(200),nextCursor:T.uuid().nullable()}),Q0=T.strictObject({features:T.array(Lu).max(500),limited:T.boolean()}),J0=T.union([Ya({action:T.literal("save"),internal_id:T.uuid().nullable(),revision:T.number().int().nonnegative()}),T.strictObject({action:T.enum(["archive","restore","delete"]),internal_id:T.uuid(),revision:T.number().int().nonnegative()})]);import{z as Dr}from"zod";import{z as rt}from"zod";var Lt=rt.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),me=rt.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Ao=rt.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}),Xa=me.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Bu=rt.string().min(1).max(64),lr=rt.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),zu=rt.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),pt=rt.record(Bu,rt.union([rt.string().max(120),rt.number().finite(),rt.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)]))),$u=rt.record(Bu,rt.union([rt.string().max(120),rt.number().finite(),rt.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Tr=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},Gu=rt.array(rt.object({upTo:Xa.nullable(),cost:me}).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&&Tr(t.upTo)>Tr(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),mh=rt.object({key:zu,match:$u,priority:rt.number().int().default(0),cost:me.optional(),tiers:Gu.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),fh=rt.object({key:zu,match:$u,factor:Xa.optional(),add:Ao.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"})),gh=rt.object({units:Xa.default("1"),cost:me,tiers:Gu.optional(),dimensions:rt.array(mh).max(12).optional(),multipliers:rt.array(fh).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=Tr(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((p,g)=>s&1<<g);if(c.some((p,g)=>c.slice(g+1).some(f=>Object.keys(p.match).some(S=>f.match[S]!==void 0&&f.match[S]!==p.match[S]))))continue;let u=Tr(o),d=BigInt("1"),m=BigInt("0");for(let[p,g]of r.entries())s&1<<p&&(u*=Tr(g.factor??"1"),d*=BigInt("1000000"),m+=Tr(g.add??"0"));let w=(u+m*d)*BigInt("1000000"),I=d*a;(w<BigInt("0")||w%I!==BigInt("0")||w/I>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),Y0=gh.safeExtend({featureKey:lr});import{z as Nr}from"zod";var Ku=Nr.number().int().min(0).max(1e8),hi=Nr.strictObject({kind:Nr.enum(["graduated","volume"]),tiers:Nr.array(Nr.strictObject({upTo:Nr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Ku,flatAmountMinor:Ku.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function es(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?hi.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 yo(e){return es({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var hh=me.refine(e=>/[1-9]/.test(e)),bo=Dr.strictObject({units:hh,prices:Dr.array(Dr.strictObject({currency:fe,amountMinor:Dr.number().int().min(0).max(1e8),pricing:hi.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:Dr.number().int().min(0).max(1e4),maximumQuantity:Dr.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&es({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function Hu(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 Qu(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Hu(e)+Hu(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 A}from"zod";import{z as W}from"zod";import{z as wt}from"zod";import{z as R}from"zod";function Ju(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 So(e,t,n){return n===2?Ju(Ju(e+t)+"")%1e4/1e4:null}function Ah(e){return e<=0?[]:new Array(e).fill(1/e)}function xo(e,t){return e>=t[0]&&e<t[1]}function Zu(e,t){for(let[n,r]of t.entries())if(xo(e,r))return n;return-1}function Wu(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=Ah(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 Yu(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 Xu(e){try{return e()}catch{return!1}}function Ai(e){return typeof e=="string"?e:JSON.stringify(e)}function Qt(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 yh(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function el(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=xh(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function bh(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 Sh(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=>!bh(i[0],i[1],i[2]))}catch{return!1}}function xh(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=yh(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return Sh(r,n);return!1}catch{return!1}}function ts(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 Io(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 tl(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);Io(e.savedGroups??{})}var Ih=e=>e/2**32|0,vh=e=>e>>>0;function nl(e,t,n,r){let i=Ih(n),a=vh(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function rl(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var ns=e=>e?`"${e}" `:"";function wh(e,t=""){if(typeof e!="number")throw new TypeError(ns(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ns(t)+"expected integer >= 0, got "+e);return e}function vo(e,t,n=""){if(rl(e)&&(t===void 0||e.length===t))return e;t!==void 0&&wh(t,"length");let r=rl(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=ns(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var Oh=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},il=(e,t)=>{Oh(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 rs(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function ol(e,t){vo(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function is(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function wo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function un(e,t){return e<<32-t|e>>>t}var Ch=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ph=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Fr(e){if(vo(e),Ch)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ph[e[n]];return t}function _h(e,t,n="opts"){return il(e,"defaults"),t!==void 0&&il(t,n),Object.assign(Object.create(null),e,t)}function al(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=_h({},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 sl=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function cl(e,t,n){return e&t^~e&n}function ul(e,t,n){return e&t^e&n^t&n}var Oo=class{constructor(t,n,r,i){qe(this,"blockLen");qe(this,"outputLen");qe(this,"canXOF",!1);qe(this,"padOffset");qe(this,"isLE");qe(this,"buffer");qe(this,"view");qe(this,"finished",!1);qe(this,"length",0);qe(this,"pos",0);qe(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=wo(this.buffer)}update(t){rs(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=wo(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){rs(this),ol(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)),nl(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:wo(t),c=this.outputLen,u=c/4,d=this.get();if(c%4||u>d.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)s.setUint32(4*m,d[m],a)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return t.destroyed=a,t.finished=i,t.length=r,t.pos=o,o&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ll=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Eh=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]),Mn=new Uint32Array(64),os=class extends Oo{constructor(n,r){super(64,n,8,!1);qe(this,"A",0);qe(this,"B",0);qe(this,"C",0);qe(this,"D",0);qe(this,"E",0);qe(this,"F",0);qe(this,"G",0);qe(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:u}=this;return[n,r,i,a,o,s,c,u]}set(n,r,i,a,o,s,c,u){this.A=n|0,this.B=r|0,this.C=i|0,this.D=a|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=u|0}_cloneInto(n){return(n||(n=new this.constructor)).set(...this.get()),this._cloneIntoMeta(n)}process(n,r){for(let w=0;w<16;w++,r+=4)Mn[w]=n.getUint32(r,!1);for(let w=16;w<64;w++){let I=Mn[w-15],p=Mn[w-2],g=un(I,7)^un(I,18)^I>>>3,f=un(p,17)^un(p,19)^p>>>10;Mn[w]=f+Mn[w-7]+g+Mn[w-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:d,H:m}=this;for(let w=0;w<64;w++){let I=un(c,6)^un(c,11)^un(c,25),p=m+I+cl(c,u,d)+Eh[w]+Mn[w]|0,f=(un(i,2)^un(i,13)^un(i,22))+ul(i,a,o)|0;m=d,d=u,u=c,c=s+p|0,s=o,o=a,a=i,i=p+f|0}i=i+this.A|0,a=a+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,u=u+this.F|0,d=d+this.G|0,m=m+this.H|0,this.set(i,a,o,s,c,u,d,m)}roundClean(){is(Mn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),is(this.buffer)}},as=class extends os{constructor(){super(32,ll)}};var Mr=al(()=>new as,sl(1));var dl=new Map,ss=32,pl=new WeakMap,ml=new WeakMap;function Rh(e){return Fr(Mr(new TextEncoder().encode(String(e))))}var Po=e=>Array.isArray(e)?e.map(Po):typeof e=="string"||typeof e=="number"?Rh(e):null,Co=e=>typeof e=="string"?e.toLowerCase():e;function yl(e){let t=pl.get(e);return t||(t=new Set(e),pl.set(e,t)),t}function kh(e){let t=ml.get(e);return t||(t=new Set(e.map(Co)),ml.set(e,t)),t}function qr(e){Io(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=ss&&yl(n)}return e}function zt(e,t,n,r){n=n||{},r||Io(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Al(e,a,n,r))return!1;break;case"$nor":if(Al(e,a,n,r))return!1;break;case"$and":if(!Fh(e,a,n,r))return!1;break;case"$not":if(zt(e,a,n,r))return!1;break;case"$savedGroup":if(!jh(e,a,n,r))return!1;break;default:if(!yi(a,bl(e,i),n,!1,r))return!1}return!0}function jh(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=bl(e,c);return dr(o.type==="hashed"?Po(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:zt(e,o.condition,n,s):!1}function bl(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 fl(e,t=!1){let n=`${e}${t?"/i":""}`,r=dl.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),dl.set(n,r)),r}function yi(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)||!Sl(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!Dh(o,t,a[o],n,i))return!1;return!0}function Sl(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function Th(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 Nh(e,t,n,r){if(!Array.isArray(e))return!1;let i=Sl(t)?a=>yi(t,a,n,!1,r):a=>zt(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 dr(e,t,n=!1){if(n){let i;if(t.length>=ss){let a=kh(t);i=o=>{let s=Co(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Co(a)===Co(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=ss?(i=>a=>i.has(a))(yl(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function gl(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function hl(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(yi(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function Dh(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return Qt(t)===Qt(n);case"$vne":return Qt(t)!==Qt(n);case"$vgt":return Qt(t)>Qt(n);case"$vgte":return Qt(t)>=Qt(n);case"$vlt":return Qt(t)<Qt(n);case"$vlte":return Qt(t)<=Qt(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)?dr(t,n):!1;case"$ini":return Array.isArray(n)?dr(t,n,!0):!1;case"$inGroup":{let s=r[n],c=gl(s);return c===null?!1:dr(s?.type==="hashed"?Po(t):t,c)}case"$notInGroup":{let s=r[n],c=gl(s);return c===null?!1:!dr(s?.type==="hashed"?Po(t):t,c)}case"$nin":return Array.isArray(n)?!dr(t,n):!1;case"$nini":return Array.isArray(n)?!dr(t,n,!0):!1;case"$not":return!yi(n,t,r,!1,i);case"$size":return Array.isArray(t)?yi(n,t.length,r,!1,i):!1;case"$elemMatch":return Nh(t,n,r,i);case"$all":return Array.isArray(n)?hl(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?hl(t,n,r,!0,i):!1;case"$regex":try{return fl(n).test(t)}catch{return!1}case"$regexi":try{return fl(n,!0).test(t)}catch{return!1}case"$type":return Th(t)===n;default:return!1}}function Al(e,t,n,r){if(!t.length)return!0;for(let i of t)if(zt(e,i,n,r))return!0;return!1}function Fh(e,t,n,r){for(let i of t)if(!zt(e,i,n,r))return!1;return!0}function cs(e){return tl(e),{context:e,stack:{evaluatedFeatures:new Set}}}function us(e){return{...e.attributes,...e.attributeOverrides}}function qn(e,t,n){let r=t||"id",i="",a=us(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Ge(e,t,n){e.context.log?.(t,n)}function _o(e,t){return t=t||0,`${e}__${t}`}function ls(e,t){return`${e}||${t}`}function Mh(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=qn(e,t),o=ls(i,Ai(a)),{hashAttribute:s,hashValue:c}=qn(e,n),u=c?ls(s,Ai(c)):null,d={};return u&&r[u]&&Object.assign(d,r[u].assignments||{}),r[o]&&Object.assign(d,r[o].assignments||{}),d}function xl({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=Mh(e,r,i);if(a>0)for(let m=0;m<a;m++){let w=_o(t,m);if(c[w]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let d=o.findIndex(m=>m.key===u);return d<0?{variation:-1}:{variation:d}}function Il(e,t,n,r){let i=ls(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 vl(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Eo(e,t){let n=cs(t),r=Ol(e,null,n);return t.onExperimentEval?.(e,r),r}function _n(e,t){return ps(e,cs(t))}function qh(e){return e.forcedVariations||{}}function wl(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=_l(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}ds(()=>r.onExperimentViewed?.(t,n))}function Vh(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}ds(()=>r.onFeatureUsage?.(t,n))}function ds(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function ps(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Ge(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),Vn(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])ts(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Ge(t,"Global override",{id:e,value:i.get(e)}),Vn(t,e,i.get(e),"override");if(!r)return Ge(t,"Unknown feature",{id:e}),Vn(t,e,null,"unknownFeature");if(r.rules){let a=new Set(t.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let u of o.parentConditions){t.stack.evaluatedFeatures=new Set(a);let d=ps(u.id,t);if(d.source==="cyclicPrerequisite")return Vn(t,e,null,"cyclicPrerequisite");let m={value:d.value};if(!zt(m,u.condition||{},n.savedGroups||{})){if(u.gate)return Ge(t,"Feature blocked by prerequisite",{id:e,rule:o}),Vn(t,e,null,"prerequisite");Ge(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&Pl(o.filters,t)){Ge(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!Cl(o.condition,t)){Ge(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!Uh(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Ge(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Ge(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{wl(t,u.experiment,u.result)}),Vn(t,e,o.force,"force",o.id)}if(!o.variations){Ge(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=Ol(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return Vn(t,e,c.value,"experiment",o.id,s,c)}}return Ge(t,"Use default value",{id:e,value:r.defaultValue}),Vn(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Ol(e,t,n){let{context:r}=n;ts(e);let i=e.key,a=e.variations.length;if(a<2)return Ge(n,"Invalid experiment",{id:i}),vt(n,e,-1,!1,t);if(r.enabled===!1)return Ge(n,"Context disabled",{id:i}),vt(n,e,-1,!1,t);if(e.urlPatterns&&!el(r.url||"",e.urlPatterns))return Ge(n,"Skip because of url targeting",{id:i}),vt(n,e,-1,!1,t);let o=Yu(i,r.url||"",a);if(o!==null)return Ge(n,"Force via querystring",{id:i,variation:o}),vt(n,e,o,!1,t);let c=qh(r)[i];if(c!==void 0)return Ge(n,"Force via dev tools",{id:i,variation:c}),vt(n,e,c,!1,t);if(e.active===!1)return Ge(n,"Skip because inactive",{id:i}),vt(n,e,-1,!1,t);let{hashAttribute:u,hashValue:d}=qn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return Ge(n,"Skip because missing hashAttribute",{id:i}),vt(n,e,-1,!1,t);let m=-1,w=!1,I=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:f,versionIsBlocked:S}=xl(vl({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));w=f>=0,m=f,I=!!S}if(!w){if(e.filters&&Pl(e.filters,n))return Ge(n,"Skip because of filters",{id:i}),vt(n,e,-1,!1,t);if(e.include&&!Xu(e.include))return Ge(n,"Skip because of include function",{id:i}),vt(n,e,-1,!1,t);if(e.condition&&!Cl(e.condition,n))return Ge(n,"Skip because of condition exp",{id:i}),vt(n,e,-1,!1,t);if(e.parentConditions){let f=new Set(n.stack.evaluatedFeatures);for(let S of e.parentConditions){n.stack.evaluatedFeatures=new Set(f);let h=ps(S.id,n);if(h.source==="cyclicPrerequisite")return vt(n,e,-1,!1,t);let P={value:h.value};if(!zt(P,S.condition||{},r.savedGroups||{}))return Ge(n,"Skip because prerequisite evaluation fails",{id:i}),vt(n,e,-1,!1,t)}}}let p=So(e.seed||i,d,e.hashVersion??2);if(p===null)return Ge(n,"Skip because of invalid hash version",{id:i}),vt(n,e,-1,!1,t);if(!w){let f=e.ranges||Wu(a,e.coverage===void 0?1:e.coverage,e.weights);m=Zu(p,f)}if(I)return Ge(n,"Skip because sticky bucket version is blocked",{id:i}),vt(n,e,-1,!1,t,void 0,!0);if(m<0)return Ge(n,"Skip because of coverage",{id:i}),vt(n,e,-1,!1,t);if("force"in e)return Ge(n,"Force variation",{id:i,variation:e.force}),vt(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Ge(n,"Skip because QA mode",{id:i}),vt(n,e,-1,!1,t);let g=vt(n,e,m,!0,t,p,w);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:f,key:S,doc:h}=Il(r,u,Ai(d),{[_o(e.key,e.bucketVersion)]:g.key});if(f){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[S]=h;let P=r.saveStickyBucketAssignmentDoc;ds(()=>P(h))}}return wl(n,e,g),Ge(n,"In experiment",{id:i,variation:g.variationId}),g}function Vn(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"&&Vh(e,t,s),s}function Cl(e,t){return zt(us(t.context),e,t.context.savedGroups||{})}function Pl(e,t){return e.some(n=>{let{hashValue:r}=qn(t.context,n.attribute);if(!r)return!0;let i=So(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>xo(i,a))})}function Uh(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=So(t,s,o??2);return c===null?!1:i?xo(c,i):a!==void 0?c<=a:!0}function vt(e,t,n,r,i,a,o){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:c,hashValue:u}=qn(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},m=t.variations[0];for(let[I,p]of t.variations.entries())if(I===n){m=p;break}let w={key:d.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return d.name&&(w.name=d.name),a!==void 0&&(w.bucket=a),d.passthrough&&(w.passthrough=d.passthrough),w}function _l(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
1
+ var Th=Object.defineProperty;var Nh=(e,t,n)=>t in e?Th(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Be=(e,t,n)=>Nh(e,typeof t!="symbol"?t+"":t,n);import{z as os}from"zod";var Dh=os.enum(["sandbox","live"]),Ue=os.object({projectId:os.string().min(1),environment:Dh}).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()}),vI=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"]),_I=It.enum([...Tn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),CI=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 Fh(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 Mh(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})}),PI=It.object({error:ds.shape.error.extend({requestId:It.uuid().optional()})}),EI=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=Fh(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?Mh(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 qh}from"zod";var Vh=["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=qh.enum(Vh);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}$/),Bh=["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(Bh),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()}),Uh=_.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:Uh.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 R}from"zod";import{z as Ar}from"zod";var Ft=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,$n=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 Lh=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],zh=R.enum(Lh);var $h=R.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=R.string().regex(/^[A-Za-z0-9_-]{1,64}$/),Gh=R.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Kh=R.strictObject({keyId:dl,signingSecret:Gh}),Hh=R.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=R.array(zh).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),ml=R.strictObject({bridgeVersion:R.literal(bs),projectId:R.uuid(),environmentId:R.uuid(),environment:R.enum(["sandbox","live"]),capabilities:pl,catalog:R.enum(["endpoint","static","none"]),billingEvents:R.array(cl).max(6),profiles:R.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=R.strictObject({origin:Hh,requiredCapabilities:pl}),Qh=R.strictObject({revision:R.number().int().nonnegative(),checkedAt:R.iso.datetime(),outcome:R.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:R.strictObject({ping:R.enum(["passed","failed","not_checked"]),authentication:R.enum(["passed","failed","not_checked"]),catalog:R.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"})}),LI=R.strictObject({projectId:R.uuid(),environmentId:R.uuid(),environment:R.enum(["sandbox","live"]),execution:R.enum(["indiana","record_only"]),accountId:R.string().nullable(),revision:R.number().int().nonnegative(),authentication:R.strictObject({keyId:dl}).nullable(),secretStoreConfigured:R.boolean().optional(),connection:fl.nullable(),check:Qh.nullable()});var ll=R.strictObject({projectId:R.uuid(),environmentId:R.uuid()}),zI=R.discriminatedUnion("action",[ll.extend({action:R.literal("save"),revision:R.number().int().nonnegative(),connection:fl,authentication:Kh.optional()}),ll.extend({action:R.literal("check"),revision:R.number().int().nonnegative()})]),Ss=R.strictObject({projectId:R.uuid(),environmentId:R.uuid(),environment:R.enum(["sandbox","live"])});var Jh=R.strictObject({nativeUserId:R.string().min(1).max(128),session:$n.strict()}),Zh=R.strictObject({nativeUserId:R.string().min(1).max(128),presentation:R.strictObject({customerId:R.uuid(),decisionId:R.uuid(),offeringVersionId:R.uuid(),paywallVersionId:R.uuid(),variant:R.string().min(1).max(128)}).nullable()}),Wh=R.strictObject({decisionId:R.uuid(),eventId:R.uuid()}),Co=R.strictObject({operationId:R.uuid(),customerId:R.uuid()}),Po=R.strictObject({scope:Ss,operationId:R.uuid(),customerId:R.uuid(),confirmedAt:R.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:R.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=R.string().min(1).max(120),Yh=R.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Xh=R.strictObject({revision:Nn,updatedAt:R.iso.datetime(),provider:R.literal("merchant"),items:R.array(R.strictObject({merchantProductId:Nn,productVersionId:R.uuid(),name:R.string().min(1).max(255),kind:R.enum(["subscription","credit_pack"]),merchantPriceId:Nn,currency:R.string().regex(/^[a-z]{3}$/),amountMinor:R.number().int().nonnegative().max(1e8),interval:R.enum(["one_time","month","year"]),intervalCount:R.literal(1),includedCredits:R.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:R.enum(["none","month"]),creditPolicyId:Nn,available:R.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)}),eA=R.strictObject({customerId:R.uuid(),revision:R.string().min(1).max(128),observedAt:R.iso.datetime(),subscriptions:R.array(R.strictObject({merchantSubscriptionId:Nn,merchantProductId:Nn,productVersionId:R.uuid().nullable(),status:R.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:R.iso.datetime().nullable(),currentPeriodEndsAt:R.iso.datetime().nullable(),cancelAtPeriodEnd:R.boolean(),scheduledChange:R.strictObject({effectiveAt:R.iso.datetime(),merchantProductId:Nn}).nullable()})).max(100),purchaseHistory:R.strictObject({complete:R.boolean(),hasPaidPurchase:R.boolean(),lastPaidAt:R.iso.datetime().nullable()}),balances:R.array(R.strictObject({bucketId:Nn,key:Nn,available:Yh,expiresAt:R.iso.datetime().nullable(),nextResetAt:R.iso.datetime().nullable()})).max(100)}),$I=R.strictObject({bridgeVersion:R.literal(bs),requestId:R.uuid(),command:R.string().min(1).max(64),scope:Ss,error:R.strictObject({code:R.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:R.string().min(1).max(500),retryable:R.boolean(),recovery:R.string().min(1).max(80)})}),Ci=R.strictObject({}),tA={"bridge.ping":R.strictObject({challenge:R.uuid()}),"bridge.describe":Ci,"session.create":Ci,"catalog.read":Ci,"customer.commerce.read":Ci,"presentation.resolve":Ci,"presentation.report":Wh,"purchase.execute":Co,"operation.read":Co,"subscription.change":Co,"refund.execute":Co},GI={"bridge.ping":R.strictObject({challenge:R.uuid()}),"bridge.describe":ml,"session.create":Jh,"catalog.read":Xh,"customer.commerce.read":eA,"presentation.resolve":Zh,"presentation.report":R.strictObject({queued:R.literal(!0)}),"purchase.execute":ys,"operation.read":sl,"subscription.change":ys,"refund.execute":ys},KI=R.strictObject({bridgeVersion:R.literal(bs),requestId:R.uuid(),scope:Ss,command:$h,data:R.unknown()}).superRefine((e,t)=>{tA[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"),ZI=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 nA=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()}))},rA=D.union([D.strictObject({match:xs,priority:D.number().int().optional(),...yl}),D.strictObject({match:xs,priority:D.number().int().optional(),...bl})]),iA=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,rA).optional(),multipliers:D.record(gl,iA).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(),oA=D.strictObject({default_markup:ko.optional(),provider_markups:Sl,model_markups:jo}),XI=D.strictObject({schema:D.array(Is).optional(),markups:oA.optional()}),aA=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:nA,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:aA}),D.strictObject({...Ro,...e,type:D.literal("credit_system"),config:xl}),D.strictObject({...Ro,...e,type:D.literal("ai_credit_system"),config:vs})]),ev=ws({}),sA=D.strictObject({id:D.boolean(),type:D.boolean(),usage_type:D.boolean()}),cA={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:sA},Il=ws(cA),tv=D.strictObject({rows:D.array(Il).max(200),nextCursor:D.uuid().nullable()}),nv=D.strictObject({features:D.array(Il).max(500),limited:D.boolean()}),rv=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"),uA=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"),lA=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"})),dA=ot.object({units:Os.default("1"),cost:ge,tiers:_l.optional(),dimensions:ot.array(uA).max(12).optional(),multipliers:ot.array(lA).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(S=>f.match[S]!==void 0&&f.match[S]!==p.match[S]))))continue;let u=Ur(o),d=BigInt("1"),m=BigInt("0");for(let[p,g]of r.entries())s&1<<p&&(u*=Ur(g.factor??"1"),d*=BigInt("1000000"),m+=Ur(g.add??"0"));let w=(u+m*d)*BigInt("1000000"),I=d*a;(w<BigInt("0")||w%I!==BigInt("0")||w/I>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),av=dA.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 pA=ge.refine(e=>/[1-9]/.test(e)),Do=zr.strictObject({units:pA,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 mA(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=mA(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 fA(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=AA(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function gA(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 hA(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=>!gA(i[0],i[1],i[2]))}catch{return!1}}function AA(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=fA(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return hA(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 yA=e=>e/2**32|0,bA=e=>e>>>0;function Ml(e,t,n,r){let i=yA(n),a=bA(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 SA(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&&SA(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 xA=(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)=>{xA(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 IA=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",vA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function $r(e){if(Vo(e),IA)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=vA[e[n]];return t}function wA(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=wA({},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){Be(this,"blockLen");Be(this,"outputLen");Be(this,"canXOF",!1);Be(this,"padOffset");Be(this,"isLE");Be(this,"buffer");Be(this,"view");Be(this,"finished",!1);Be(this,"length",0);Be(this,"pos",0);Be(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,d=this.get();if(c%4||u>d.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)s.setUint32(4*m,d[m],a)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return t.destroyed=a,t.finished=i,t.length=r,t.pos=o,o&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Gl=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var OA=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]),Gn=new Uint32Array(64),ks=class extends Uo{constructor(n,r){super(64,n,8,!1);Be(this,"A",0);Be(this,"B",0);Be(this,"C",0);Be(this,"D",0);Be(this,"E",0);Be(this,"F",0);Be(this,"G",0);Be(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:u}=this;return[n,r,i,a,o,s,c,u]}set(n,r,i,a,o,s,c,u){this.A=n|0,this.B=r|0,this.C=i|0,this.D=a|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=u|0}_cloneInto(n){return(n||(n=new this.constructor)).set(...this.get()),this._cloneIntoMeta(n)}process(n,r){for(let w=0;w<16;w++,r+=4)Gn[w]=n.getUint32(r,!1);for(let w=16;w<64;w++){let I=Gn[w-15],p=Gn[w-2],g=fn(I,7)^fn(I,18)^I>>>3,f=fn(p,17)^fn(p,19)^p>>>10;Gn[w]=f+Gn[w-7]+g+Gn[w-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:d,H:m}=this;for(let w=0;w<64;w++){let I=fn(c,6)^fn(c,11)^fn(c,25),p=m+I+zl(c,u,d)+OA[w]+Gn[w]|0,f=(fn(i,2)^fn(i,13)^fn(i,22))+$l(i,a,o)|0;m=d,d=u,u=c,c=s+p|0,s=o,o=a,a=i,i=p+f|0}i=i+this.A|0,a=a+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,u=u+this.F|0,d=d+this.G|0,m=m+this.H|0,this.set(i,a,o,s,c,u,d,m)}roundClean(){Rs(Gn)}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 _A(e){return $r(Gr(new TextEncoder().encode(String(e))))}var zo=e=>Array.isArray(e)?e.map(zo):typeof e=="string"||typeof e=="number"?_A(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 CA(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(!jA(e,a,n,r))return!1;break;case"$not":if(Qt(e,a,n,r))return!1;break;case"$savedGroup":if(!PA(e,a,n,r))return!1;break;default:if(!Ri(a,ed(e,i),n,!1,r))return!1}return!0}function PA(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(!kA(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 EA(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 RA(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=CA(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 kA(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 RA(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 EA(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 jA(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 Kn(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 TA(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=Kn(e,t),o=Fs(i,Ei(a)),{hashAttribute:s,hashValue:c}=Kn(e,n),u=c?Fs(s,Ei(c)):null,d={};return u&&r[u]&&Object.assign(d,r[u].assignments||{}),r[o]&&Object.assign(d,r[o].assignments||{}),d}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=TA(e,r,i);if(a>0)for(let m=0;m<a;m++){let w=$o(t,m);if(c[w]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let d=o.findIndex(m=>m.key===u);return d<0?{variation:-1}:{variation:d}}function 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 NA(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 DA(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}),Hn(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)}),Hn(t,e,i.get(e),"override");if(!r)return He(t,"Unknown feature",{id:e}),Hn(t,e,null,"unknownFeature");if(r.rules){let a=new Set(t.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let u of o.parentConditions){t.stack.evaluatedFeatures=new Set(a);let d=qs(u.id,t);if(d.source==="cyclicPrerequisite")return Hn(t,e,null,"cyclicPrerequisite");let m={value:d.value};if(!Qt(m,u.condition||{},n.savedGroups||{})){if(u.gate)return He(t,"Feature blocked by prerequisite",{id:e,rule:o}),Hn(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(!FA(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)}),Hn(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 Hn(t,e,c.value,"experiment",o.id,s,c)}}return He(t,"Use default value",{id:e,value:r.defaultValue}),Hn(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=NA(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:d}=Kn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return He(n,"Skip because missing hashAttribute",{id:i}),_t(n,e,-1,!1,t);let m=-1,w=!1,I=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:f,versionIsBlocked:S}=nd(id({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));w=f>=0,m=f,I=!!S}if(!w){if(e.filters&&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 S of e.parentConditions){n.stack.evaluatedFeatures=new Set(f);let A=qs(S.id,n);if(A.source==="cyclicPrerequisite")return _t(n,e,-1,!1,t);let P={value:A.value};if(!Qt(P,S.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,d,e.hashVersion??2);if(p===null)return He(n,"Skip because of invalid hash version",{id:i}),_t(n,e,-1,!1,t);if(!w){let f=e.ranges||jl(a,e.coverage===void 0?1:e.coverage,e.weights);m=kl(p,f)}if(I)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,w);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:f,key:S,doc:A}=rd(r,u,Ei(d),{[$o(e.key,e.bucketVersion)]:g.key});if(f){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[S]=A;let P=r.saveStickyBucketAssignmentDoc;Ms(()=>P(A))}}return od(n,e,g),He(n,"In experiment",{id:i,variation:g.variationId}),g}function Hn(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"&&DA(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}=Kn(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 FA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=Kn(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}=Kn(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},m=t.variations[0];for(let[I,p]of t.variations.entries())if(I===n){m=p;break}let w={key:d.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return d.name&&(w.name=d.name),a!==void 0&&(w.bucket=a),d.passthrough&&(w.passthrough=d.passthrough),w}function ud(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 ge=R.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"})}),mt=R.record(R.string().min(1).max(128),ge).superRefine((e,t)=>{(!ge.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"})}),Lh=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"]),Bt=mt.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"&&!R.strictObject({id:R.uuid(),attributeKey:R.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("$")&&!Lh.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)}),Bh=R.discriminatedUnion("type",[R.strictObject({type:R.literal("condition"),condition:Bt}),R.strictObject({type:R.literal("list"),attributeKey:R.string().min(1).max(128),values:R.array(R.union([R.string(),R.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 En(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 zh=R.record(R.uuid(),Bh).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"&&En(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),fs=R.tuple([R.number().min(0).max(1),R.number().min(0).max(1)]).refine(([e,t])=>e<=t),El=R.strictObject({attribute:R.string().optional(),seed:R.string().min(1),hashVersion:R.literal(2),ranges:R.array(fs).min(1).max(100)}),$h=R.strictObject({id:R.string().min(1).max(128),condition:Bt,gate:R.boolean().optional()}),ms={id:R.string().max(128).optional(),condition:Bt.optional(),parentConditions:R.array($h).max(50).optional(),filters:R.array(El).max(20).optional()},Gh=R.union([R.strictObject({...ms}),R.strictObject({...ms,force:ge,coverage:R.number().min(0).max(1).optional(),range:fs.optional(),seed:R.string().min(1).optional(),hashAttribute:R.string().optional(),hashVersion:R.literal(2).optional()}),R.strictObject({...ms,type:R.literal("experiment-ref"),experimentId:R.uuid(),values:R.record(R.string().min(1),ge),meta:R.record(R.string().min(1),R.strictObject({passthrough:R.boolean()})).optional()})]),Kh=R.strictObject({defaultValue:ge,rules:R.array(Gh).max(100)}),QI=R.record(R.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Kh).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)}),Hh=R.strictObject({name:R.string().max(80),reason:R.string().max(500),dateStarted:R.iso.datetime({offset:!0}),dateEnded:R.iso.datetime({offset:!0}).nullable(),coverage:R.number().min(0).max(1),variationWeights:R.array(R.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Bt,savedGroups:R.array(R.strictObject({match:R.enum(["any","all","none"]),ids:R.array(R.uuid()).min(1)})).max(50),namespace:R.strictObject({id:R.uuid(),ranges:R.array(fs).min(1)}).nullable(),seed:R.string().min(1).max(128)}),Qh=R.strictObject({key:R.string().min(1).max(128),name:R.string().min(1).max(80),hypothesis:R.string().max(2e3),status:R.enum(["draft","running","stopped"]),hashAttribute:R.string().min(1).max(128),fallbackAttribute:R.string().max(128).nullable(),hashVersion:R.literal(2),disableStickyBucketing:R.boolean(),bucketVersion:R.number().int().min(0).max(1e3),minBucketVersion:R.number().int().min(0).max(1e3),variations:R.array(R.strictObject({id:R.string().min(1),key:R.string().min(1),name:R.string().max(80),description:R.string().max(500)})).min(2).max(20),phases:R.array(Hh).min(1).max(100),releasedVariationId:R.string().nullable(),excludeFromPayload:R.boolean(),statusSchedule:R.strictObject({startAt:R.iso.datetime({offset:!0}).nullable(),stopAt:R.iso.datetime({offset:!0}).nullable(),stopAfter:R.strictObject({value:R.number().int().positive().max(36500),unit:R.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 Jh=Qh.safeExtend({filters:R.array(El).optional()}),Zh=R.strictObject({experiments:R.record(R.uuid(),Jh),savedGroups:zh}),bi=R.strictObject({attributeName:R.string(),attributeValue:R.string(),assignments:R.record(R.string(),R.string())}),JI=R.strictObject({snapshot:Zh,attributes:mt,results:mt,stickyBucketAssignmentDocs:R.record(R.string(),bi)}),ZI=R.strictObject({variantKey:R.string().nullable(),bucketVersion:R.number().int().min(0),source:R.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:R.number().min(0).max(1).optional(),stickyBucketUsed:R.boolean().optional(),hashUsed:R.boolean().optional()});function Un(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 Wh=wt.enum(["active","inactive"]),Yh=wt.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},mt),Xh=wt.strictObject({id:wt.string().trim().min(1).max(255),name:wt.string().trim().min(1).max(255),status:Wh,metadata:Yh}),nv=Xh.extend({internal_id:wt.uuid(),project_id:wt.uuid(),environment_id:wt.uuid(),created_at:wt.iso.datetime({offset:!0}),updated_at:wt.iso.datetime({offset:!0})}),kl=wt.union([wt.strictObject({id:wt.string().trim().min(1).max(255)}),wt.strictObject({internalId:wt.uuid()})]),rv=wt.enum(["customer","merchandise","context"]),iv=wt.enum(["system","stored","request"]),ov=wt.enum(["customer","merchandise","mixed"]),Rl=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function gs(e,t={},n=new Set){if(Un(e).some(Rl))return!0;for(let r of En(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Rl(i.attributeKey)||i?.type==="condition"&&gs(i.condition,t,n))return!0}return!1}import{z as eA}from"zod";var tA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,ln=eA.string().max(16).regex(tA,"\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 mv=W.enum(["draft","active","paused","archived"]),Ln=W.discriminatedUnion("type",[W.object({type:W.literal("percent"),percentOff:W.number().min(1).max(100).multipleOf(.01)}).strict(),W.object({type:W.literal("amount"),amountOffCents:W.number().int().min(1).max(1e8),currency:fe}).strict()]),Jt=W.discriminatedUnion("type",[W.object({type:W.literal("once")}).strict(),W.object({type:W.literal("repeating"),months:W.number().int().min(1).max(36)}).strict(),W.object({type:W.literal("forever")}).strict()]),jl=[W.object({type:W.literal("all")}).strict(),W.object({type:W.literal("plans"),planIds:W.array(W.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],nA=W.discriminatedUnion("type",[...jl,W.strictObject({type:W.literal("merchandise"),scope:W.discriminatedUnion("type",[W.strictObject({type:W.literal("all")}),W.strictObject({type:W.literal("selected"),merchandiseIds:W.array(W.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),W.strictObject({type:W.literal("condition"),condition:Bt})])})]),hs=W.discriminatedUnion("type",[...jl,W.strictObject({type:W.literal("merchandise"),scope:W.strictObject({type:W.enum(["all","selected","condition"])})})]),rA=W.strictObject({firstPurchaseOnly:W.boolean(),condition:Bt}),fv=W.object({name:W.string().trim().min(1).max(80),description:W.string().max(500),discount:Ln,duration:Jt,appliesTo:nA,eligibility:rA,selfClaimEnabled:W.boolean().default(!1),startsAt:W.iso.datetime().nullable(),endsAt:W.iso.datetime().nullable(),totalLimit:W.number().int().min(1).max(1e6).nullable(),perCustomerLimit:W.number().int().min(1).max(10),grantWindowHours:W.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=>!gs(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"]}),gv=W.object({code:W.string().trim().transform(e=>e.toUpperCase()).pipe(W.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:W.number().int().min(1).max(1e6).nullable(),expiresAt:W.iso.datetime().nullable(),firstPurchaseOnly:W.boolean(),minimumAmountCents:W.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:fe.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Si=W.object({id:W.uuid(),couponId:W.uuid(),status:W.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:W.iso.datetime(),expiresAt:W.iso.datetime(),coupon:W.object({name:W.string(),discount:Ln,duration:Jt,appliesTo:hs}).strict()}).strict(),Tl=W.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var ql=A.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),As=A.string().regex(/^(0|[1-9]\d{0,14})$/),Vr=A.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),iA=A.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),xi=iA,Rn=me.refine(e=>/[1-9]/.test(e)),Tt=A.iso.datetime({offset:!0}),Ro=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"))},oA=A.array(A.object({upTo:Rn.nullable(),unitAmountMinor:ql,flatAmountMinor:A.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&&Ro(t.upTo)>Ro(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),aA=A.discriminatedUnion("kind",[A.object({kind:A.literal("flat"),units:Rn,unitAmountMinor:ql}).strict(),A.object({kind:A.enum(["graduated","volume"]),units:Rn,tiers:oA}).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"),sA=A.strictObject({interval:A.enum(["month","year"]),count:A.number().int().min(1).max(12),anchor:A.enum(["membership","calendar"])}),Ii=A.object({currency:fe,pricing:aA,billingCycle:sA.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Nl={requestId:A.uuid(),productVersionId:A.uuid(),internal_feature_id:A.uuid(),currency:fe},Vl=A.strictObject({interval:A.enum(["hour","day","week","month"]),intervalCount:A.number().int().min(1).max(12),limit:A.number().int().min(1).max(1e6)}),Ul=A.discriminatedUnion("kind",[A.object({...Nl,kind:A.literal("auto_topup"),threshold:Ao,quantity:Rn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Vl.optional()}).strict(),A.object({...Nl,kind:A.literal("postpaid"),maxAmountMinorPerPeriod:xi,maxOutstandingMinor:xi}).strict()]),Dl={productVersionId:A.uuid(),internal_feature_id:A.uuid(),currency:fe},Ll=A.discriminatedUnion("kind",[A.object({...Dl,kind:A.literal("auto_topup"),threshold:Ao,quantity:Rn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Vl.optional(),purchaseAmountMinor:xi,purchaseUnits:Rn}).strict(),A.object({...Dl,kind:A.literal("postpaid"),maxAmountMinorPerPeriod:xi,maxOutstandingMinor:xi,cashPrice:Ii}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),ko=A.object({id:A.uuid(),terms:Ll,status:A.enum(["prepared","active","revoked","blocked"]),createdAt:Tt,acceptedAt:Tt.nullable(),effectiveAt:Tt.nullable(),revokedAt:Tt.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"),Bl=A.object({authorizationId:A.uuid(),terms:Ll,setupUrl:A.url().nullable()}).strict(),zl=A.object({authorizationId:A.uuid(),accepted:A.literal(!0)}).strict(),$l=A.object({authorizationId:A.uuid(),requestId:A.uuid()}).strict(),Gl=A.object({internal_feature_id:A.uuid(),entityId:A.uuid().nullable(),interval:A.enum(["day","week","month","year"]),anchor:A.enum(["billing_cycle","utc"]).optional(),basis:A.enum(["usage","credits"]),filter:pt.optional(),limit:me.nullable(),thresholds:A.array(A.number().positive().max(1)).max(8),includedThresholds:A.array(A.number().positive().max(1)).max(8).optional(),absoluteThresholds:A.array(Rn).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&&Ro(t)>Ro(i)}),"Notification thresholds must increase"),cA=Gl.safeExtend({requestId:A.uuid()}),Fl={control:A.literal("overage"),requestId:A.uuid(),internal_feature_id:A.uuid(),entityId:A.uuid().nullable()},uA=A.discriminatedUnion("action",[A.strictObject({...Fl,action:A.literal("set"),allowed:A.boolean().nullable(),overageLimit:me.nullable(),skipOverageBilling:A.boolean()}),A.strictObject({...Fl,action:A.literal("remove")})]),Kl=A.union([cA,uA]),lA=A.strictObject({internal_feature_id:A.uuid(),entityId:A.uuid().nullable(),allowed:A.boolean().nullable(),overageLimit:me.nullable(),skipOverageBilling:A.boolean(),interval:A.enum(["day","week","month","year"]),startsAt:Tt,endsAt:Tt,used:A.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:A.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:A.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),dA=A.object({internal_feature_id:A.uuid(),entityId:A.uuid().nullable(),interval:A.enum(["day","week","month","year"]),anchor:A.enum(["billing_cycle","utc"]).optional(),basis:A.enum(["usage","credits"]),filter:pt.optional(),startsAt:Tt,endsAt:Tt,used:Lt,reserved:Lt,limit:me.nullable(),thresholds:A.array(A.number().positive().max(1)).max(8),notifiedThresholds:A.array(A.number().positive().max(1)).max(1024),includedThresholds:A.array(A.number().positive().max(1)).max(8).optional(),includedAllowance:A.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:A.array(A.number().positive().max(1)).max(1024).optional(),absoluteThresholds:A.array(Rn).max(8).optional(),notifiedAbsoluteThresholds:A.array(Rn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||me.safeParse(e.used).success&&me.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),pA=A.object({authorizationId:A.uuid(),status:A.enum(["idle","pending","blocked"]),taskId:A.uuid().nullable(),invoiceId:A.uuid().nullable(),hostedInvoiceUrl:A.url().nullable(),purchaseCount:A.number().int().nonnegative(),purchaseWindowEndsAt:Tt.nullable(),attemptCount:A.number().int().nonnegative(),failedAttemptCount:A.number().int().nonnegative(),suspendedAt:Tt.nullable(),nextAttemptAt:Tt.nullable(),failureReason:A.string().min(1).max(240).nullable()}).strict(),Hl=A.object({internal_feature_id:A.uuid().optional(),entityId:A.uuid().optional()}).strict(),ys=A.object({authorizations:A.array(ko).max(100),limits:A.array(Gl).max(100),overages:A.array(lA).max(100).optional(),windows:A.array(dA).max(200),autoTopups:A.array(pA).max(100),limited:A.boolean()}).strict(),mA=A.object({id:A.uuid(),internal_feature_id:A.uuid(),productVersionId:A.uuid(),authorizationId:A.uuid(),entityId:A.uuid().nullable(),units:me,amountMinor:Vr,cashPrice:Ii}).strict(),vi=A.object({id:A.uuid(),sourceKind:A.enum(["product","usage","manual"]),providerInvoiceId:A.string().min(1).max(240).nullable(),status:A.enum(["accruing","open","pending","paid","failed","void"]),currency:fe,startsAt:Tt.nullable(),endsAt:Tt.nullable(),amountMinor:A.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:A.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:As,paidAmountMinor:As,refundedAmountMinor:As,createdAt:Tt,hostedInvoiceUrl:A.url().nullable(),adjustment:A.object({originalInvoiceId:A.uuid(),amountMinor:A.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:Tt.nullable()}).strict().nullable(),lines:A.array(mA).max(100),linesLimited:A.boolean()}).strict(),Ql=A.object({invoiceId:A.uuid(),accepted:A.literal(!0)}).strict(),Jl=A.object({after:A.uuid().nullable(),limit:A.number().int().min(1).max(100)}).strict(),Zl=A.object({rows:A.array(vi).max(100),nextCursor:A.uuid().nullable()}).strict(),Ml=A.strictObject({id:A.string(),coupon:A.string(),start:A.number().nonnegative(),end:A.number().nullable()}),fA=A.strictObject({subscriptionId:A.string(),customerId:A.string(),accountId:A.string(),sourceItems:A.array(A.strictObject({id:A.string(),price_id:A.string(),quantity:A.number().int(),discounts:A.array(Ml).optional()})).max(100),items:A.array(A.strictObject({id:A.string(),price:A.string(),quantity:A.number().int(),discounts:A.array(A.strictObject({coupon:A.string().optional(),terms:A.strictObject({id:A.string(),name:A.string().optional(),percent_off:A.number().optional(),amount_off:A.number().optional(),currency:A.string().optional(),duration:A.enum(["once","forever","repeating"]),duration_in_months:A.number().optional()}).optional(),discount:A.string().optional(),receipt:Ml.optional()})).max(20)})).max(100)}),Wl=A.strictObject({membershipId:A.uuid(),requestId:A.uuid(),grantIds:A.array(A.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Yl=A.strictObject({membershipId:A.uuid(),operationId:A.uuid(),status:A.enum(["pending","effective"]),execution:fA.nullable(),grants:A.array(A.strictObject({id:A.uuid(),couponId:A.uuid(),name:A.string(),discount:Ln,duration:Jt,startedAt:Tt.nullable()})).max(20)});import{z as wi}from"zod";var Xl=wi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),ed=wi.number().int().min(1).max(1e3),jo=wi.object({cap:me.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:wi.number().positive().max(1e4).nullable(),cycles:wi.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 Bn}from"zod";var td=Bn.strictObject({itemKey:Bn.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:Bn.uuid(),includedAmount:Bn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Bn.number().int().min(0).max(1e4),terms:bo,pricing:hi.optional(),unitAmountMinor:Bn.number().int().min(0).max(1e8),productId:Bn.string().min(1).max(255).nullable(),priceId:Bn.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{Qu(e.includedAmount,e.terms.units,e.quantity),yo({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 Y}from"zod";var pr=me.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Oi=Y.string().min(1).max(120),To=Y.enum(["cap","overflow"]),Zt=(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"))},Ci=e=>{try{return e()}catch{return!1}},Pi=Y.discriminatedUnion("operation",[Y.object({operation:Y.literal("quote"),overageBehavior:To.optional(),internal_feature_id:Y.uuid(),entityId:Y.uuid().optional(),quantity:pr,properties:pt}).strict(),Y.object({operation:Y.literal("consume"),overageBehavior:To.optional(),occurredAt:Y.iso.datetime({offset:!0}).optional(),internal_feature_id:Y.uuid(),entityId:Y.uuid().optional(),quantity:me,properties:pt,idempotencyKey:Oi}).strict(),Y.object({operation:Y.literal("reserve"),occurredAt:Y.iso.datetime({offset:!0}).optional(),internal_feature_id:Y.uuid(),entityId:Y.uuid().optional(),quantity:pr,properties:pt,idempotencyKey:Oi,expiresInSeconds:Y.number().int().min(1).max(86400)}).strict(),Y.object({operation:Y.literal("confirm"),operationId:Y.uuid(),quantity:pr,properties:pt.optional(),idempotencyKey:Oi}).strict(),Y.object({operation:Y.literal("refund"),operationId:Y.uuid(),quantity:pr,idempotencyKey:Oi}).strict(),Y.object({operation:Y.literal("release"),operationId:Y.uuid(),idempotencyKey:Oi}).strict()]),bs=Y.object({internal_credit_feature_id:Y.uuid().nullable(),internal_metered_feature_id:Y.uuid(),dimension:Y.string().min(1).max(64),counterKey:Y.string().min(1).max(240),cycleStart:Y.iso.datetime({offset:!0}),unitCost:me,units:pr,amount:Lt,tier:Y.number().int().min(1).max(12).nullable()}).strict(),mr=Y.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function nd(e,t){let n=e.reduce((r,i)=>r+Zt(i.units,12),0n)-Zt(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var rd=Y.discriminatedUnion("funding",[Y.strictObject({funding:Y.literal("balance"),sourceId:Y.uuid(),rolloverId:Y.uuid().nullable(),units:mr.refine(e=>/[1-9]/.test(e)),amount:Lt}),Y.strictObject({funding:Y.literal("unbilled"),units:mr.refine(e=>/[1-9]/.test(e))}),Y.object({funding:Y.literal("prepaid"),sourceId:Y.uuid(),units:pr,amount:Lt,pricing:Y.array(bs).min(1).max(12)}).strict().refine(e=>Ci(()=>e.pricing.reduce((t,n)=>t+Zt(n.units,6),0n)===Zt(e.units,6)&&e.pricing.reduce((t,n)=>t+Zt(n.amount,12),0n)===Zt(e.amount,12)&&e.pricing.every(t=>Zt(t.unitCost,6)*Zt(t.units,6)===Zt(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),Y.object({funding:Y.literal("postpaid"),invoiceLineId:Y.uuid().nullable(),units:pr,authorizationId:Y.uuid()}).strict()]),No=Y.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),id=Y.object({allowed:Y.boolean(),internal_feature_id:Y.uuid(),quantity:me,requestedQuantity:me.optional(),overageBehavior:To.optional(),reason:No.nullable(),allocations:Y.array(rd).max(500)}).strict().refine(e=>Ci(()=>e.allowed?e.reason===null&&nd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Ci(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&Zt(e.requestedQuantity,6)>=Zt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),_i=Y.object({id:Y.uuid(),internal_feature_id:Y.uuid(),kind:Y.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:Y.uuid().nullable(),quantity:me,requestedQuantity:me.optional(),overageBehavior:To.optional(),accepted:Y.boolean(),reason:Y.enum([...No.options,"expired"]).nullable(),createdAt:Y.iso.datetime({offset:!0}),reservationStatus:Y.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Y.iso.datetime({offset:!0}).nullable(),allocations:Y.array(rd).max(500)}).strict().refine(e=>Ci(()=>e.accepted?e.reason===null&&nd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Ci(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&Zt(e.requestedQuantity,6)>=Zt(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 _e}from"zod";var fr=_e.iso.datetime({offset:!0}),od=me.refine(e=>/[1-9]/.test(e)),ad=_e.strictObject({interval:Xl.exclude(["lifetime"]),count:ed}),gA=_e.strictObject({action:_e.literal("create"),requestId:_e.uuid(),internal_feature_id:_e.uuid(),entityId:_e.uuid().nullable(),amount:od.nullable(),expiresAt:fr.nullable(),reset:ad.nullable(),rollover:jo.nullable(),nextResetAt:fr.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"),sd=_e.discriminatedUnion("action",[gA,_e.strictObject({action:_e.literal("update"),requestId:_e.uuid(),grantId:_e.uuid(),revision:_e.number().int().nonnegative(),amount:od.nullable(),expiresAt:fr.nullable(),rollover:jo.nullable(),nextResetAt:fr.nullable()}),_e.strictObject({action:_e.enum(["add","subtract","set_remaining"]),requestId:_e.uuid(),grantId:_e.uuid(),revision:_e.number().int().nonnegative(),amount:me}),_e.strictObject({action:_e.literal("revoke"),requestId:_e.uuid(),grantId:_e.uuid(),revision:_e.number().int().nonnegative()})]),Ss=_e.strictObject({id:_e.uuid(),internal_feature_id:_e.uuid(),entityId:_e.uuid().nullable(),amount:me.nullable(),reset:ad.nullable(),rollover:jo.nullable(),nextResetAt:fr.nullable(),startsAt:fr,expiresAt:fr.nullable(),revision:_e.number().int().nonnegative(),revoked:_e.boolean(),available:Lt,held:Lt,spent:Lt}),cd=_e.strictObject({customerId:_e.uuid(),after:_e.uuid().nullable(),limit:_e.number().int().min(1).max(100)}),ud=_e.strictObject({rows:_e.array(Ss).max(100),nextCursor:_e.uuid().nullable()});import{z as ee}from"zod";var Sn=ee.iso.datetime({offset:!0}),ld=ee.strictObject({invoiceId:ee.uuid(),after:ee.string().min(1).max(180).nullable(),limit:ee.number().int().min(1).max(100)}),hA=ee.strictObject({kind:ee.literal("product"),key:ee.string(),productVersionId:ee.uuid(),productName:ee.string(),itemKey:ee.string(),entityId:ee.uuid().nullable(),quantity:ee.number().positive(),subtotalMinor:ee.string().regex(/^-?\d+$/),discountMinor:ee.string().regex(/^\d+$/),taxMinor:ee.string().regex(/^-?\d+$/).nullable(),totalMinor:ee.string().regex(/^-?\d+$/),startsAt:Sn.nullable(),endsAt:Sn.nullable(),providerLineId:ee.string().nullable(),providerItemId:ee.string()}),dd=ee.strictObject({invoice:vi,items:ee.array(ee.discriminatedUnion("kind",[hA,ee.strictObject({kind:ee.literal("invoice_credit"),key:ee.string(),internal_feature_id:ee.uuid(),internal_credit_feature_id:ee.uuid(),name:ee.string(),units:me,reserved:me,amountMinor:Vr,grossAmountMinor:Vr,creditsAppliedMinor:Vr,properties:pt,cashPrice:Ii,providerItemId:ee.string().nullable(),creditProviderItemId:ee.string().nullable()}),ee.strictObject({kind:ee.literal("usage"),key:ee.string(),internal_feature_id:ee.uuid(),name:ee.string(),units:me,reserved:me,amountMinor:Vr,cashPrice:Ii})])).max(100),nextCursor:ee.string().min(1).max(180).nullable()}),AA=ee.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),xs=ee.strictObject({from:Sn,to:Sn,entityId:ee.uuid().optional(),snapshotAt:Sn.nullable(),after:ee.strictObject({at:Sn,id:ee.uuid(),position:ee.number().int().nonnegative()}).nullable(),limit:ee.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"),pd=ee.strictObject({customerId:ee.uuid(),entityId:ee.uuid().nullable(),from:Sn,to:Sn,snapshotAt:Sn,totals:ee.array(ee.strictObject({internal_credit_feature_id:ee.uuid(),name:ee.string(),consumed:Lt,refunded:Lt,net:AA})).max(1e3),rows:ee.array(ee.strictObject({operationId:ee.uuid(),position:ee.number().int().nonnegative(),kind:ee.enum(["consume","confirm","refund"]),originalId:ee.uuid().nullable(),occurredAt:Sn,internal_feature_id:ee.uuid(),entitlementName:ee.string(),sourceId:ee.uuid(),internal_credit_feature_id:ee.uuid(),creditName:ee.string(),units:mr,amount:Lt,pricing:ee.array(bs).max(12),properties:pt})).max(100),nextCursor:xs.shape.after});import{z as k}from"zod";import{z as dn}from"zod";var yA=dn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),bA=dn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Do=dn.strictObject({internal_feature_id:dn.uuid(),entityId:dn.uuid().nullable()}),md=Do.extend({quantity:me,expectedRevision:dn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:dn.string().min(1).max(120),properties:pt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Ei=Do.extend({operationId:dn.uuid().nullable(),usage:me,capacity:yA.nullable(),remaining:bA.nullable(),withinLimit:dn.boolean(),revision:dn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:dn.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 Nt=k.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),pn=k.iso.datetime({offset:!0}),SA=k.enum(["access","metered","credit"]),Ri={internal_feature_id:k.uuid(),key:lr,name:k.string().min(1).max(120),kind:SA},fd=k.object({customerId:k.uuid(),snapshotAt:pn,memberships:k.array(k.object({id:k.uuid(),productId:k.string().min(1).max(255),productVersionId:k.uuid(),billingProductVersionId:k.uuid(),version:k.number().int().positive(),key:k.string().min(1).max(64),name:k.string().min(1).max(120),groupId:k.string().max(255).nullable(),membershipType:k.enum(["main","addon"]),status:k.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:k.boolean(),accessEnabled:k.boolean(),renewalChange:k.object({productVersionId:k.uuid(),name:k.string().min(1).max(120),version:k.number().int().positive(),effectiveAt:pn,benefitsAppliedAt:pn.nullable(),timing:k.enum(["immediate","renewal"]),changeKind:k.enum(["plan","seats","quantity"]),feature:k.strictObject({internal_feature_id:k.uuid(),name:k.string().min(1).max(80),fromQuantity:k.number().int().min(0).max(1e4),toQuantity:k.number().int().min(0).max(1e4)}).optional(),seat:k.object({key:k.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:k.number().int().min(0).max(1e4),toQuantity:k.number().int().min(0).max(1e4)}).strict().nullable(),status:k.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:k.object({phase:k.enum(["paid","trial"]),startsAt:pn,endsAt:pn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:k.boolean(),balances:k.array(k.object({...Ri,usageType:k.enum(["consumable","non_consumable"]).nullable(),accessible:k.boolean(),unlimited:k.boolean(),available:Nt,held:Nt,debt:Nt,nextExpiresAt:pn.nullable(),usage:Ei.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:k.boolean()}).strict(),gd=k.enum(["source","usage","transaction","invoice","debt","settlement"]),Fo=k.object({at:pn,id:k.uuid(),type:gd}).strict(),hd=k.object({type:gd.nullable(),resourceKey:lr.optional(),kind:k.enum(["purchase","refund"]).optional(),topup:k.boolean().optional(),from:k.iso.date().nullable(),to:k.iso.date().nullable(),after:Fo.nullable(),limit:k.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Ur={id:k.uuid(),occurredAt:pn},xA=k.discriminatedUnion("type",[k.strictObject({...Ur,type:k.literal("invoice"),status:k.string().min(1).max(80),paid:Nt,refunded:Nt,currency:fe,externalId:k.string().nullable()}),k.object({...Ur,...Ri,type:k.literal("source"),reason:k.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Nt,unlimited:k.boolean(),status:k.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:pn,expiresAt:pn.nullable(),orderId:k.uuid().nullable(),parentSourceId:k.uuid().nullable()}).strict(),k.object({...Ur,type:k.literal("usage"),internal_feature_id:k.uuid(),name:k.string().min(1).max(120),kind:k.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:k.uuid().nullable(),quantity:me,accepted:k.boolean(),reason:k.enum([...No.options,"expired"]).nullable(),properties:pt,reservationStatus:k.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:pn.nullable(),charges:k.array(k.discriminatedUnion("funding",[k.strictObject({funding:k.literal("balance"),sourceId:k.uuid(),rolloverId:k.uuid().nullable(),units:mr,amount:Nt}),k.strictObject({funding:k.literal("unbilled"),units:mr}),k.object({...Ri,funding:k.literal("prepaid"),amount:Nt}).strict(),k.object({funding:k.literal("postpaid"),invoiceId:k.uuid(),invoiceLineId:k.uuid(),authorizationId:k.uuid(),units:me,currency:fe}).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"),k.object({...Ur,type:k.literal("transaction"),purpose:k.enum(["product","invoice"]),productVersionId:k.uuid().nullable(),productName:k.string().min(1).max(120).nullable(),productVersion:k.number().int().positive().nullable(),invoiceId:k.uuid().nullable(),orderId:k.uuid(),originalId:k.uuid().nullable(),kind:k.enum(["purchase","refund"]),amountMinor:k.number().int().nonnegative().max(2e8).nullable(),currency:fe.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"),k.object({...Ur,...Ri,type:k.literal("debt"),sourceId:k.uuid(),transactionId:k.uuid(),amount:Nt}).strict(),k.object({...Ur,...Ri,type:k.literal("settlement"),sourceId:k.uuid(),debtId:k.uuid(),kind:k.enum(["payment","usage_refund","payment_return"]),amount:Nt}).strict()]),Ad=k.object({customerId:k.uuid(),rows:k.array(xA).max(50),nextCursor:Fo.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 ce}from"zod";var bd=ce.object({customerId:ce.uuid()}).strict(),Sd=ce.discriminatedUnion("action",[ce.object({customerId:ce.uuid(),requestId:ce.uuid(),action:ce.literal("assign"),poolId:ce.uuid(),memberCustomerId:ce.uuid()}).strict(),ce.strictObject({customerId:ce.uuid(),requestId:ce.uuid(),action:ce.literal("assign_entity"),poolId:ce.uuid(),entityId:ce.uuid()}),ce.object({customerId:ce.uuid(),requestId:ce.uuid(),action:ce.literal("release"),poolId:ce.uuid(),slotId:ce.uuid()}).strict()]),ki=ce.number().int().nonnegative(),Is=ce.iso.datetime({offset:!0}),vs=ce.strictObject({internalId:ce.uuid(),id:ce.string(),name:ce.string().nullable(),version:ce.number().int().positive()}),yd=ce.enum(["active","past_due"]),ws=ce.strictObject({customerId:ce.uuid(),licenses:ce.array(ce.strictObject({id:ce.uuid(),linkId:ce.uuid(),parent:ce.strictObject({customerProductId:ce.uuid(),status:yd,product:vs}),product:vs,planLicense:ce.strictObject({id:ce.uuid(),prepaidOnly:ce.boolean(),isCustom:ce.boolean()}).nullable(),granted:ki,included:ki,paidQuantity:ki,usage:ki,remaining:ki,createdAt:Is}).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:ce.array(ce.strictObject({id:ce.uuid(),linkId:ce.uuid(),status:yd,product:vs,entity:ce.strictObject({internalId:ce.uuid(),id:ce.string().nullable(),name:ce.string().nullable()}).nullable(),beneficiary:ce.strictObject({internalId:ce.uuid(),id:ce.string().nullable(),name:ce.string().nullable()}).nullable(),startedAt:Is.nullable(),endedAt:Is.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:ce.boolean()});import{z as se}from"zod";var ji=se.enum(["email","sms","voice","push"]),ew=se.enum(["resend","twilio","fcm","apns"]);var tw=se.string().regex(/^\+[1-9]\d{1,14}$/),IA=se.enum(["email_recipient","sms_segment","voice_second","push_device"]);var vA=se.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),wA=se.strictObject({subject:vA,html:se.string().min(1).max(131072).optional(),text:se.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),OA=se.strictObject({body:se.string().min(1).max(1600).refine(e=>e.trim().length>0)}),CA=se.strictObject({text:se.string().trim().min(1).max(4e3),language:se.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:se.number().int().min(1).max(900)}),PA=se.record(se.string().min(1).max(64),se.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"),_A=se.strictObject({title:se.string().trim().min(1).max(200),body:se.string().trim().min(1).max(2e3),url:se.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:PA.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),xd=se.discriminatedUnion("channel",[se.strictObject({channel:se.literal("email"),content:wA}),se.strictObject({channel:se.literal("sms"),content:OA}),se.strictObject({channel:se.literal("voice"),content:CA}),se.strictObject({channel:se.literal("push"),content:_A})]),Id=se.strictObject({requestId:se.uuid(),customerId:se.uuid(),connectionId:se.uuid().optional(),message:xd,expiresAt:se.iso.datetime({offset:!0})}),EA=se.array(se.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),RA=se.discriminatedUnion("kind",[se.strictObject({kind:se.literal("all")}),se.strictObject({kind:se.literal("customers"),customerIds:EA})]),nw=se.strictObject({name:se.string().trim().min(1).max(120),connectionId:se.uuid().optional(),message:xd,audience:RA,frequencyLimit:se.number().int().min(1).max(100)}),vd=se.strictObject({requestId:se.uuid(),channel:ji,state:se.enum(["allowed","denied"]),expectedRevision:se.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),wd=se.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Od=se.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),rw=se.strictObject({meter:IA,estimatedUnits:se.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:se.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as xe}from"zod";import{z as X}from"zod";import{z as Lr}from"zod";var Ti=Lr.strictObject({internalFeatureId:Lr.uuid(),name:Lr.string().min(1).max(120),includedAmount:Lr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Lr.enum(["hour","day","week","month","year","lifetime"]),resetCount:Lr.number().int().min(1).max(100),terms:bo});import{z as et}from"zod";import{z as kA}from"zod";import{z as Br}from"zod";var Cd=Br.enum(["stripe","apple","google"]),Pd=Br.enum(["membership","credit_pack","lifetime"]),uw=Br.enum(["active","grace","suspended","inactive","revoked"]),lw=Br.strictObject({currency:Br.string().regex(/^[A-Z]{3}$/),micros:Br.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var zr=kA.object({provider:Cd,currency:fe}).strict();var zn=et.strictObject({internal_feature_id:et.uuid(),quantity:me.refine(e=>/[1-9]/.test(e)),properties:pt,entityId:et.uuid().optional()}),_d=et.strictObject({requirement:zn,commerce:zr.optional(),paywallId:et.uuid().optional()}),jA=et.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Os=et.strictObject({productId:et.string().min(1),productVersionId:et.string().min(1),name:et.string().min(1).max(120),action:et.enum(["purchase","upgrade","addon","topup"]),membershipId:et.string().min(1).nullable(),currency:fe,amountMinor:et.string().regex(/^(0|[1-9]\d{0,8})$/),interval:et.enum(["free","week","month","year","one_time"]),intervalCount:et.number().int().min(1).max(156)}),gr=et.strictObject({internal_feature_id:et.string().min(1),name:et.string().min(1).max(120),kind:et.enum(["access","metered","credit"]),quantity:me,allowed:et.boolean(),reason:jA.nullable(),preview:et.strictObject({scenario:et.enum(["feature_flag","usage_limit"]),candidates:et.array(Os).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"})}),Sw=et.strictObject({paywallId:et.uuid(),requirement:zn});var qo=X.object({plan:X.string().min(1).max(200).optional(),coupon:X.uuid().optional(),promotionCode:X.uuid().optional(),picker:X.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Mo=X.object({text:X.string().optional(),label:X.string().optional(),alt:X.string().optional(),html:X.string().max(32768).optional(),price:X.object({current:X.string(),original:X.string().nullable(),period:X.string()}).optional(),code:X.string().optional(),countdownAt:X.iso.datetime().optional(),planId:X.string().min(1).max(200).optional(),planVersionId:X.string().min(1).max(200).optional(),currency:fe.optional(),couponId:X.uuid().optional(),offerId:X.uuid().optional(),unavailable:X.boolean().optional(),unavailableReason:X.string().optional(),missing:X.array(X.string()).optional()}).strict(),$r=X.object({paywall:gr.optional(),nodes:X.record(X.string(),X.object({base:Mo,picker:X.string().optional(),byPlan:X.record(X.string(),Mo).optional()}).strict()),plans:X.record(X.string(),X.object({id:X.string().min(1).max(200),versionId:X.string().min(1).max(200),available:X.boolean(),name:X.string(),price:X.string(),period:X.string(),currency:fe.optional(),amountMinor:X.number().int().nonnegative().optional(),interval:X.enum(["free","week","month","year","one_time"]).optional(),intervalCount:X.number().int().positive().optional(),prepaid:X.array(Ti).max(100).optional()}).strict()),pickers:X.record(X.string(),X.object({options:X.array(X.string().min(1).max(200)).max(20),selected:X.string().min(1).max(200).nullable()}).strict()),quantities:X.record(X.string(),X.strictObject({minimum:X.number().int().nonnegative(),maximum:X.number().int().nonnegative(),step:X.number().int().positive(),value:X.number().int().nonnegative(),label:X.string(),available:X.boolean()})).optional(),diagnostics:X.array(X.object({nodeId:X.string(),message:X.string()}).strict())}).strict();function Ed(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as b}from"zod";function TA(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Rd(e){let t={};function n(r){var i;if(TA(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 kn}from"zod";var kd=kn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Vo=kn.strictObject({tiers:kn.array(kn.strictObject({id:kd,name:kn.string().trim().min(1).max(80)})).min(1).max(8),assignments:kn.array(kn.strictObject({productVersionId:kn.string().min(1).max(200),tierId:kd,period:kn.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 Uo(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as re}from"zod";var NA=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],jd=re.enum(NA),Td=re.object({source:jd,layout:re.enum(["full","compact"]),resourceKey:lr.optional(),pageSize:re.number().int().min(1).max(50),showSources:re.boolean(),allowPurchase:re.boolean(),outputs:re.object({billing_adjustment:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:re.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"})}),St=re.string().max(2e3),Nd=re.object({id:re.string().max(100),label:St,detail:re.array(St).max(12),value:St.optional(),status:St.optional(),facts:re.array(re.object({label:St,value:St}).strict()).max(1e3),purchaseId:re.uuid().optional(),invoiceUrl:re.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:re.array(re.strictObject({action:re.literal("invoice_open"),label:St})).max(1).optional(),membershipActions:re.array(re.object({value:re.string().max(100),label:St}).strict()).max(3).optional()}).strict(),DA=re.object({key:lr,name:St,spendable:St,reserved:St,available:St,expiry:St.nullable(),sources:re.array(Nd).max(50),sourceCount:re.number().int().nonnegative(),sourcePage:re.number().int().positive(),hasNextSources:re.boolean(),hasPreviousSources:re.boolean()}).strict(),FA=re.object({source:jd,status:re.enum(["idle","loading","ready","error"]),stale:re.boolean(),preview:re.boolean(),errorCode:re.string().max(80).optional(),errorMessage:St.optional(),resources:re.array(DA).max(500),rows:re.array(Nd).max(50),hasNext:re.boolean(),hasPrevious:re.boolean(),page:re.number().int().positive(),filter:re.string().max(40),updatedAt:re.iso.datetime().optional(),buyingId:re.uuid().optional(),membershipBusy:re.boolean().optional(),billingBusy:re.boolean().optional(),membershipReview:re.object({title:St,note:St,facts:re.array(re.object({label:St,value:St}).strict()).max(100)}).strict().optional(),membershipResult:St.optional()}).strict(),Dd=re.object({nodes:re.record(re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),FA)}).strict(),jw=re.object({nodeId:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:re.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:re.string().max(100).optional()}).strict();var qA=4,fn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Di=b.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ke=b.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),VA=b.enum(["none","xs","sm","md","lg","xl"]),UA=b.enum(["none","sm","md","lg","full"]),Cs=b.string().regex(/^#[0-9a-fA-F]{6}$/),qd=b.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"),Ps=b.union([qd,b.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),b.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),b.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Fd=b.object({primary:Cs,background:Cs,text:Cs,radius:UA,font:b.enum(["system","serif","rounded","mono"])}).strict(),Fi=b.union([b.enum(["primary","text","muted","background","surface"]),b.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Re=(e,t)=>b.number().int().min(e).max(t),Md=b.union([b.enum(["fit","fill"]),Re(1,1200)]),LA=b.object({top:Re(0,200),right:Re(0,200),bottom:Re(0,200),left:Re(0,200)}).strict(),BA=b.object({top:Re(-100,200),right:Re(-100,200),bottom:Re(-100,200),left:Re(-100,200)}).strict(),Vd=b.object({x:Re(0,100),y:Re(0,100)}).strict(),zA=b.discriminatedUnion("type",[b.object({type:b.literal("color"),color:Fi}).strict(),b.object({type:b.literal("linear"),angle:Re(0,360),stops:b.array(b.object({color:Fi,at:Re(0,100)}).strict()).min(2).max(4)}).strict(),b.object({type:b.literal("image"),src:Ps,fit:b.enum(["cover","contain"]),position:Vd.optional()}).strict()]),$A=b.discriminatedUnion("type",[b.object({type:b.literal("rect"),radius:b.union([Re(0,200),b.object({topLeft:Re(0,200),topRight:Re(0,200),bottomRight:Re(0,200),bottomLeft:Re(0,200)}).strict()])}).strict(),b.object({type:b.literal("pill")}).strict()]),GA=b.object({width:Re(0,12),color:Fi,style:b.enum(["solid","dashed"])}).strict(),KA=b.object({x:Re(-40,40),y:Re(-40,40),blur:Re(0,80),spread:Re(-20,40),color:Fi}).strict(),HA=b.object({font:b.enum(["system","serif","rounded","mono"]),size:Re(8,96),weight:b.number().int().min(100).max(900).multipleOf(100),lineHeight:b.number().min(.8).max(3),letterSpacing:b.number().min(-5).max(20),color:Fi,align:b.enum(["start","center","end"]),italic:b.boolean(),decoration:b.enum(["none","underline","line-through"]),transform:b.enum(["none","uppercase"])}).strict().partial(),hr=b.object({width:Md,height:Md,padding:LA,margin:BA,gap:Re(0,120),grow:b.union([b.boolean(),b.number().min(0).max(12)]),background:zA,opacity:b.number().min(0).max(1),clipContent:b.boolean(),shape:$A,border:GA,shadow:KA,text:HA}).strict().partial(),$t={id:Di,name:b.string().trim().min(1).max(60).optional(),hidden:b.boolean().optional(),style:hr.optional(),fallback:ke.optional()},QA=b.object({...$t,type:b.literal("text"),productField:b.enum(["name","price","trial","period"]).optional(),feature:b.object({id:b.uuid(),field:b.enum(["name","allowance"])}).strict().optional(),text:ke,variant:b.enum(["title","heading","body","caption"])}).strict(),JA=b.object({...$t,type:b.literal("image"),src:Ps,localizedSrc:b.record(ln,Ps).optional(),alt:ke,aspect:b.enum(["auto","1:1","4:3","16:9","3:1"]),fit:b.enum(["cover","contain"]),position:Vd.optional()}).strict(),ZA=b.object({...$t,type:b.literal("button"),label:ke,variant:b.enum(["primary","secondary","link"]),action:ke,purpose:b.enum(["purchase","navigation","close"]).optional(),bind:qo.optional()}).strict(),WA=b.object({...$t,type:b.literal("divider")}).strict(),YA=b.object({...$t,type:b.literal("customer_data"),title:ke,data:Td}).strict(),XA=b.object({...$t,type:b.literal("spacer"),size:VA}).strict(),ey=b.object({...$t,type:b.literal("custom_html"),html:b.record(ln,b.string().max(fn.customHtml)),css:b.string().max(fn.customCss)}).strict(),ty=b.object({...$t,type:b.literal("price"),fallback:ke,parts:b.object({current:hr.optional(),original:hr.optional(),period:hr.optional()}).strict().optional()}).strict(),ny=b.object({...$t,type:b.literal("coupon_code"),label:ke,fallback:ke}).strict(),ry=b.object({...$t,type:b.literal("countdown"),source:b.enum(["offer.ends_at","offer.expires_at","fixed"]),at:b.iso.datetime().optional(),granularity:b.enum(["day","hour","minute","second"]),expired:ke,fallback:ke}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),iy=b.object({...$t,type:b.literal("plan_picker"),label:ke,fallback:ke,planIds:b.array(b.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:b.string().min(1).max(200).optional(),grouping:Vo.safeExtend({monthLabel:ke,yearLabel:ke,unavailableLabel:ke}).optional(),states:b.object({selected:hr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Uo(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),oy=b.object({...$t,type:b.literal("quantity_picker"),bind:qo.optional(),label:ke,fallback:ke,internalFeatureId:b.uuid(),minimumQuantity:Re(0,1e4),maximumQuantity:Re(0,1e4),defaultQuantity:Re(0,1e4),step:Re(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"),ay=b.discriminatedUnion("type",[b.object({type:b.literal("input"),label:ke,keyboard:b.enum(["text","email","tel","url"]),maxLength:Re(1,500)}).strict(),b.object({type:b.literal("multiselect"),label:ke,min:Re(0,50),max:Re(1,50)}).strict(),b.object({type:b.literal("select"),label:ke,defaultIndex:Re(0,49),purpose:b.enum(["option","product","tier"]).optional(),pickerId:Di.optional(),selectedStyle:hr.optional()}).strict(),b.object({type:b.literal("tabs"),label:ke,defaultIndex:Re(0,49),purpose:b.literal("tier").optional()}).strict(),b.object({type:b.literal("toggle"),label:ke,defaultEnabled:b.boolean()}).strict(),b.object({type:b.literal("carousel"),label:ke}).strict()]),mn={...$t,type:b.literal("stack"),direction:b.enum(["vertical","horizontal","overlay"]),align:b.enum(["start","center","end","stretch"]),justify:b.enum(["start","center","end","between"]),productSlot:b.object({index:Re(0,19),period:b.enum(["month","year"]).optional(),requireBinding:b.boolean().optional()}).strict().optional(),interaction:ay.optional(),states:b.object({selected:hr.optional()}).strict().optional(),purpose:b.literal("benefits").optional(),purchaseAction:ke.optional(),buttonVariant:b.enum(["primary","secondary","link"]).optional(),bind:qo.optional()},Ud=b.lazy(()=>b.object({...$t,type:mn.type,direction:mn.direction,align:mn.align,justify:mn.justify,children:b.array(sy).max(fn.children),productSlot:mn.productSlot,interaction:mn.interaction,states:mn.states,purpose:mn.purpose,purchaseAction:mn.purchaseAction,buttonVariant:mn.buttonVariant,bind:mn.bind}).strict()),sy=b.lazy(()=>b.union([Ud,QA,JA,ZA,WA,XA,ey,ty,ny,ry,iy,oy,YA])),cy=b.union([b.string().max(500),b.number().finite(),b.boolean(),b.null()]),Ni={id:ke,event:ke,properties:b.record(ke,cy).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},uy=b.discriminatedUnion("type",[b.object({...Ni,type:b.literal("navigate"),close:b.literal(!1),pageId:Di}).strict(),b.object({...Ni,type:b.literal("event"),close:b.boolean()}).strict(),b.object({...Ni,type:b.literal("close"),close:b.literal(!0)}).strict(),b.object({...Ni,type:b.literal("open_url"),close:b.boolean(),url:qd}).strict(),b.object({...Ni,type:b.literal("claim_offer"),close:b.boolean(),couponId:b.uuid()}).strict()]),ly=b.object({defaultLocale:ln,locales:b.record(ln,b.record(ke,b.string().max(fn.stringLength)))}).strict(),dy=b.enum(["popup","paywall","onboarding","page","banner"]);var py=b.discriminatedUnion("type",[b.object({type:b.literal("modal"),size:b.enum(["sm","md","lg"])}).strict(),b.object({type:b.literal("sheet"),size:b.enum(["sm","md","lg"])}).strict(),b.object({type:b.literal("fullscreen")}).strict(),b.object({type:b.literal("inline")}).strict()]);var my=b.object({kind:b.literal("screen"),schemaVersion:b.literal(qA),name:b.string().trim().min(1).max(80),surface:dy,initialPageId:Di.optional(),presentation:py,theme:Fd,pages:b.array(b.object({id:Di,name:b.string().trim().min(1).max(60),root:Ud,theme:Fd.optional(),editorPosition:b.object({x:b.number().finite().min(-1e5).max(1e5),y:b.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(fn.pages),strings:ly,actions:b.array(uy).max(fn.actions)}).strict();function Dt(e,t){for(let n of e.pages)$n(n.root,t)}var Wt=my.superRefine((e,t)=>{let n=fn;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(d=>d.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let d of e.actions)d.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===d.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=d=>t.addIssue({code:"custom",message:d}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>fn.locales&&r(`\u6700\u591A ${fn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let d of e.actions)a.has(d.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${d.id}`),a.add(d.id);let o=new Set;for(let d of e.pages)["next","back"].includes(d.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${d.id}`),o.has(d.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${d.id}`),o.add(d.id);let s=new Set,c=0,u=!1;Dt(e,(d,m)=>{if(c++,m>fn.depth&&(u=!0),s.has(d.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${d.id}`),s.add(d.id),d.type==="button"&&!a.has(d.action)&&r(`\u6309\u94AE ${d.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${d.action}`),d.type==="custom_html")for(let w of Object.keys(d.html))i.includes(w)||r(`\u81EA\u5B9A\u4E49 HTML ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`);if(d.type==="image")for(let w of Object.keys(d.localizedSrc??{}))i.includes(w)||r(`\u56FE\u7247 ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${fn.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 Lo(e){let t=[],n=new Set;return Dt(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 fy(e,t,n){if(t.field==="html"){let r;return Dt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Mi(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 Gn(e){let t=Lo(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=>!fy(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 gy(e,t){let n=null;return $n(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Mi(e,t){for(let n of e.pages){let r=gy(n.root,t);if(r)return r}return null}import{z as Et}from"zod";var dt=Et.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"),_s=Et.strictObject({type:Et.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Et.boolean(),enum:Et.array(Et.string().max(255)).min(1).max(100).optional()}),Gr=_s.extend({type:Et.enum([..._s.shape.type.options,"array"]),items:_s.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"})}),Kr=Gr.safeExtend({source:Et.discriminatedUnion("type",[Et.strictObject({type:Et.literal("input")}),Et.strictObject({type:Et.literal("node")}),Et.strictObject({type:Et.enum(["parameter","attribute"]),key:dt})])}),zw=Et.record(dt,Kr),Es=Et.record(dt,dt).refine(e=>Object.keys(e).length<=20);function rn(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=>rn(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&&Et.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 Rs(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&&Rs(e.items,t.items)}function Bo(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let d of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,d)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(d)||Number(d)>=u.length)){c=!1;break}u=u[d]}}if(!(!c||u===void 0)){if(!rn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function Hr(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 Ld(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"||!rn(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 Ar}from"zod";var gn=Ar.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"),xn=Ar.discriminatedUnion("source",[Ar.strictObject({source:Ar.literal("literal"),value:ge}),Ar.strictObject({source:Ar.literal("variable"),key:Ar.string().min(1).max(255),path:gn.optional()})]);function Bd(e,t){if(!t)return e;for(let n of gn.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 ks(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Bo(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ge.parse(Bd(n[e.key],e.path)))}function js(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&&!gn.safeParse(r).success?null:{key:n,path:r}}function Ts(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Dt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Ed))]}function zo(e){return Ts(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function Yt(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),d=c.replace(/^-/,""),m=d.replace(".","").length,w=(d.includes(".")?d.indexOf("."):m)+Number(u),I=w<=0?2-w+m:w>=m?w:m+1;n+=I+(c.startsWith("-")?1:0)-s.length}}return n}var Kn=xe.enum(["page","popup","banner"]),hy=3e5,zd=xe.strictObject({type:xe.enum(["string","number","boolean","strings","json"]),nullable:xe.boolean()}),Ay=xe.strictObject({inputs:xe.record(ke,zd.extend({required:xe.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:xe.record(ke,zd).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),yy=xe.strictObject({kind:Kn,schemaVersion:xe.literal(1),name:xe.string().trim().min(1).max(80),screen:Wt,contract:Ay}),$o=yy.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"]),Yt(e)>hy&&n("Content document exceeds its byte budget",[])});function by(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 Sy=$o.superRefine((e,t)=>{for(let n of zo(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&&!by(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}Gn(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),$d=xe.strictObject({id:xe.uuid(),kind:Kn,projectId:xe.uuid(),environmentId:xe.uuid(),name:xe.string(),revision:xe.number().int().nonnegative(),status:xe.enum(["draft","published","archived"]),publishedVersionId:xe.uuid().nullable(),createdAt:xe.iso.datetime({offset:!0}),updatedAt:xe.iso.datetime({offset:!0})}),iO=$d.extend({draft:$o}),oO=xe.strictObject({rows:xe.array($d).max(200),nextCursor:xe.uuid().nullable()}),Ns=xe.strictObject({id:xe.uuid(),kind:Kn,resourceId:xe.uuid(),projectId:xe.uuid(),environmentId:xe.uuid(),version:xe.number().int().positive(),sourceRevision:xe.number().int().nonnegative(),document:Sy,createdAt:xe.iso.datetime({offset:!0})}),aO=Ns.omit({document:!0}),sO=xe.discriminatedUnion("action",[xe.strictObject({action:xe.literal("create"),kind:Kn,id:xe.uuid(),document:$o}),xe.strictObject({action:xe.literal("save"),kind:Kn,id:xe.uuid(),revision:xe.number().int().nonnegative(),document:$o}),xe.strictObject({action:xe.enum(["publish","archive"]),kind:Kn,id:xe.uuid(),revision:xe.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 Gd}from"zod";var Qr={funnelId:Gd.uuid().optional(),funnelVersionId:Gd.uuid().optional()};import{z as Ye}from"zod";import{z as Ne}from"zod";import{z as Qe}from"zod";var pO=Qe.discriminatedUnion("action",[Qe.strictObject({action:Qe.literal("create"),couponId:Qe.uuid(),productBindingId:Qe.uuid(),storeOfferId:Qe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Qe.enum(["introductory","promotional"])}),Qe.strictObject({action:Qe.literal("set_enabled"),id:Qe.uuid(),revision:Qe.number().int().nonnegative(),enabled:Qe.boolean()})]),mO=Qe.array(Qe.strictObject({id:Qe.uuid(),couponId:Qe.uuid(),productBindingId:Qe.uuid(),storeOfferId:Qe.string().min(1).max(255).nullable(),storeOfferType:Qe.enum(["introductory","promotional"]),enabled:Qe.boolean(),revision:Qe.number().int().nonnegative()})).max(500),Jr=Qe.strictObject({offerKind:Qe.enum(["none","introductory","promotional"]),offerId:Qe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Qe.number().int().min(0).max(1e8),trialDays:Qe.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"})}),fO=Qe.record(Qe.uuid(),Jr).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Ds=Ne.object({type:Ne.literal("native_purchase"),receiptId:Ne.uuid(),orderId:Ne.uuid(),productVersionId:Ne.uuid(),provider:Ne.enum(["apple","google"]),productId:Ne.string().min(1).max(255),productKind:Pd,replacement:Ne.strictObject({sourceOrderId:Ne.uuid(),sourceProductId:Ne.string().min(1).max(255),policy:Ne.enum(["apple_store","google_full_price"]),sourceAccountTokens:Ne.array(Ne.uuid()).max(50)}).nullable(),appAccountToken:Ne.uuid().optional(),obfuscatedAccountId:Ne.string().min(1).max(64).optional(),obfuscatedProfileId:Ne.uuid().optional(),basePlanId:Ne.string().min(1).max(255).optional(),offerId:Ne.string().min(1).max(255).optional(),offerKind:Ne.enum(["none","introductory","promotional"]),currency:fe,catalogAmountMinor:Ne.number().int().nonnegative().max(1e8),discountMinor:Ne.number().int().nonnegative().max(1e8),trialDays:Ne.number().int().min(1).max(730).nullable(),seatBundle:Ne.array(Ne.strictObject({key:Ne.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Ne.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Ne.strictObject({offerId:Ne.string().min(1).max(255),keyId:Ne.string().min(1).max(255),nonce:Ne.uuid(),signature:Ne.string().min(1).max(1024),timestamp:Ne.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 l}from"zod";import{z as Ie}from"zod/v4";import{z as xy}from"zod/v4";var Iy=xy.registry(),{BillingInterval:Kd}=(()=>{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:vy}=(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')."})})}))(Ie),{withSpecDefault:wy}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Iy),{COMMON:Hd}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Oy}={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:Cy}=(e=>({COMMON_SET:new Set(e)}))(Hd),{hasNoDuplicateCurrencies:Qd}={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:Jd}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Py}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Ie),{Infinite:_y}={Infinite:"inf"},{TierBehavior:Ey}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Zd}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Ry}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:ky}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:jy}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Ty}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ie),{ApiCreditTierSchema:Wd}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(Ie),{VIOLATION_MESSAGES:Ny}={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:Yd}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ie),{ModelMarkupsSchema:Dy}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(Ie,Yd),{InvoiceUsageEntrySchema:Fy}=(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()}))(Ie),{AttachDiscountSchema:Xd}=(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."})}))(Ie),{CustomLineItemSchema:My}=(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."})})}))(Ie),{UnixMsTimestampSchema:qy}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Ie),{CreateInvoicePreviewLineSchema:Vy}=(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()})}))(Ie),{ReissueInvoiceParamsSchema:Fs}=(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."})})}))(Ie),{InvoiceModeParamsSchema:yr}=(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."})}))(Ie),{InvoiceTemplateSchema:Uy}=(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."})})}))(Ie),{BasePriceSchema:Ly}=((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."})})}))(Ie,Kd,vy),{CURRENCY_CODES:By}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Hd,Oy,Cy),{ApiPriceProcessorsSchema:ep}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Ie,Py),{AllocatedBillingFieldSchema:zy}=((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'."})}))(Ie,Ry),{CreditDimensionNameSchema:$y}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ie,ky,jy),{ApiCreditMatchSchema:tp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Ty),{findCreditTierViolations:Gy}=(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}}))(Ny),{ApiCreditMultiplierSchema:Ky}=((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."})}))(Ie,tp),{ProviderMarkupsSchema:Hy}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ie,Yd),{InvoiceFeatureQuantitySchema:np}=((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."})}))(Ie,Zd,Fy),{CreateInvoicePreviewSchema:Ms}=((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()})}))(Ie,Vy),{SUPPORTED_SET:Qy}=(e=>({SUPPORTED_SET:new Set(e)}))(By),{ApiCreditDimensionBaseSchema:Jy}=((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."})})}))(Ie,tp),{refineGraduatedTiers:rp}=(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"]})}}))(Gy),{ApiFeatureMarkupsOverrideSchema:Zy}=((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."})})}))(Ie,Hy,Dy),{isValidCurrencyCode:Wy}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Qy),{ApiCreditDimensionSchema:Yy}=((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()])}))(Ie,Jy,Wd,rp),{CurrencyCodeSchema:ip}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(Ie,Wy),{AdditionalCurrencyTierSchema:Xy}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(Ie,ip),{ApiCreditSchemaItemBaseSchema:op}=((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."})})}))(Ie,$y,Yy,Ky),{ApiFlatCreditSchemaItemSchema:eb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(op,Ie),{AdditionalCurrencyPriceSchema:tb}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(Ie,ip),{AdditionalCurrencyTierArraySchema:nb}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ie,Xy,Qd,Jd),{ApiGraduatedCreditSchemaItemSchema:rb}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(op,Ie,Wd,rp),{AdditionalCurrencyPriceArraySchema:ap}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ie,tb,Qd,Jd),{ApiUsageTierWithCurrenciesSchema:ib}=((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()}))}))(Ie,_y,nb),{ApiCreditSchemaItemSchema:ob}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Ie,rb,eb),{BasePriceParamsSchema:ab}=((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."})}))(Ly,wy,Ie,ap),{PlanItemPriceParamsSchema:sb}=((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."})})}))(Ie,ap,ib,Ey,Kd,Zd,zy),{ApiFeatureOverrideSchema:cb}=((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."})})}))(Ie,ob,Zy),{InvoiceBasePriceParamsSchema:sp}=((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()}))(ab,ep),{InvoiceItemPriceParamsSchema:ub}=((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()}))(sb,ep),{InvoiceLicenseQuantitySchema:lb}=((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()}))(Ie,sp,np),{InvoiceCustomizeItemSchema:db}=((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()}))(Ie,ub,cb),{InvoiceCustomizeSchema:pb}=((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."})}))(Ie,sp,db),{InvoicePlanParamsSchema:mb}=((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()}))(Ie,pb,np,lb,Xd),{CreateInvoiceParamsSchema:Zr}=((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."})}))(Ie,mb,My,Xd,qy);var lp=l.strictObject({requestId:l.uuid(),predecessorOperationId:l.uuid().optional(),invoiceMode:yr.optional(),entityId:l.uuid().optional(),billingSubscriptionId:l.uuid().optional(),newBillingSubscription:l.literal(!0).optional(),offerId:l.uuid().optional(),nativeOffer:Jr.optional(),plans:l.array(l.strictObject({productVersionId:l.uuid(),seatQuantities:l.record(mo,l.number().int().min(0).max(1e4)).optional(),featureQuantities:l.record(l.uuid(),l.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:l.enum(["stripe","apple","google"]),currency:fe}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(e.provider==="stripe"||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||e.provider!=="stripe"&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||e.provider==="stripe"&&!e.billingSubscriptionId,"A new billing subscription requires Stripe and no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Sr=l.strictObject({operationId:l.uuid()}),Ot=l.number().int().min(0).max(1e8),fb=l.strictObject({lineId:l.uuid(),productVersionId:l.uuid(),productName:l.string().min(1).max(80),interval:l.enum(["free","week","month","year","one_time"]),intervalCount:l.number().int().min(1).max(156).optional(),baseAmountMinor:Ot,seats:l.array(l.strictObject({key:mo,quantity:l.number().int().min(0).max(1e4),includedQuantity:l.number().int().min(0).max(1e4),maximumQuantity:l.number().int().min(0).max(1e4),unitAmountMinor:Ot})).max(20),prepaid:l.array(td).max(100).optional(),catalogAmountMinor:Ot,trial:l.strictObject({days:l.number().int().min(1).max(730),cardRequired:l.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+yo({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"),dp=l.string().regex(/^[A-Za-z0-9_-]{1,200}$/),gb=l.strictObject({id:dp,name:l.string().min(1).max(40),percent_off:l.number().gt(0).max(100).optional(),amount_off:l.number().int().positive().optional(),currency:l.string().regex(/^[a-z]{3}$/).optional(),duration:l.enum(["once","repeating","forever"]),duration_in_months:l.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"),hb=l.strictObject({subscriptionId:l.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:l.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:l.array(l.strictObject({id:l.string(),price_id:l.string(),quantity:l.number().int().nonnegative(),discounts:l.array(l.strictObject({id:l.string(),coupon:l.string(),start:l.number(),end:l.number().nullable()})).optional()})).min(1).max(100),prorationDate:l.number().int().nonnegative(),amountMinor:l.number().int().positive(),periodStartMs:l.number(),periodEndMs:l.number()}),pp=l.strictObject({invoiceMode:yr.optional(),append:hb.optional(),provider:l.literal("stripe"),executor:l.enum(["indiana","merchant"]),accountId:l.string().regex(/^acct_[A-Za-z0-9]+$/),mode:l.enum(["payment","subscription"]),lineItems:l.array(l.strictObject({price:l.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:l.number().int().min(1).max(1e4),priceId:l.uuid(),productName:l.string().min(1).max(80),amountMinor:l.number().int().min(0).max(1e8),currency:l.string().regex(/^[a-z]{3}$/),interval:l.enum(["week","month","year","one_off"]),intervalCount:l.number().int().min(1).max(52),slot:l.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:l.strictObject({mode:l.enum(["graduated","volume"]),tiers:l.array(l.strictObject({upTo:l.number().int().min(1).max(1e6).nullable(),unitAmountMinor:l.number().int().min(0).max(1e8),flatAmountMinor:l.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:l.array(l.strictObject({coupon:dp,terms:gb})).max(1),trialPeriodDays:l.number().int().min(1).max(730).nullable(),metadata:l.strictObject({grooveCheckoutId:l.uuid(),grooveCustomerId:l.uuid()}),expiresAt:l.iso.datetime({offset:!0})}),qi=l.strictObject({operationId:l.uuid(),entityId:l.uuid().nullable(),billingSubscriptionId:l.uuid().nullable(),discount:l.strictObject({offerId:l.uuid(),couponId:l.uuid(),discount:Ln,duration:Jt,amountMinor:Ot,allocations:l.array(l.strictObject({productVersionId:l.uuid(),amountMinor:Ot})).min(1).max(20),expiresAt:l.iso.datetime({offset:!0})}).nullable(),charge:l.strictObject({effectiveAt:l.iso.datetime({offset:!0}),periodEndsAt:l.iso.datetime({offset:!0}),debitMinor:Ot,discountMinor:Ot,taxMinor:Ot,totalMinor:Ot}).nullable(),expiresAt:l.iso.datetime({offset:!0}),provider:l.enum(["stripe","apple","google"]),nativeOffer:Jr.optional(),currency:fe,lines:l.array(fb).min(1).max(20),catalogAmountMinor:Ot,automaticTax:l.boolean(),execution:pp.nullable()}).refine(e=>e.provider==="stripe"?e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once")):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(e.provider==="stripe"||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(e.provider==="stripe"?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Wr=l.strictObject({operationId:l.uuid(),orderId:l.uuid(),append:l.boolean().optional(),invoiceMode:l.boolean().optional(),status:l.enum(["pending","complete","cancelled","failed"]),executor:l.enum(["indiana","merchant"]),checkoutUrl:l.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:pp.nullable(),currency:fe,catalogAmountMinor:Ot,taxMinor:Ot,totalMinor:l.number().int().min(0).max(2e8).nullable(),quoteFinalized:l.boolean(),nativePurchase:Ds.nullable()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),Ko=l.strictObject({enabled:l.literal(!0),featureIds:l.array(l.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),mp=l.strictObject({requestId:l.uuid(),invoiceMode:yr.optional(),membershipId:l.uuid(),carryOverBalances:Ko.optional(),carryOverUsages:Ko.optional(),membershipIds:l.array(l.uuid()).min(1).max(20).optional(),prorationBehavior:l.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:l.enum(["immediate","renewal","store"]),change:l.discriminatedUnion("type",[l.strictObject({type:l.literal("plan"),productVersionId:l.uuid()}),l.strictObject({type:l.literal("seats"),licenseKey:mo,quantity:l.number().int().min(0).max(1e4)}),l.strictObject({type:l.literal("quantity"),internal_feature_id:l.uuid(),quantity:l.number().int().min(0).max(1e4)}),l.strictObject({type:l.literal("cancel")}),l.strictObject({type:l.literal("uncancel")}),l.strictObject({type:l.literal("billing_cycle"),billingCycleAnchor:l.union([l.literal("now"),l.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"),Go=l.string().regex(/^price_[A-Za-z0-9]+$/),cp=l.strictObject({grooveUpdateId:l.uuid(),grooveCustomerId:l.uuid()}),up=l.strictObject({price:Go.nullable(),priceId:l.uuid().optional(),quantity:l.number().int().min(0).max(1e4)}),fp=l.strictObject({provider:l.literal("stripe"),invoiceMode:yr.optional(),executor:l.enum(["indiana","merchant"]),accountId:l.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:l.string().regex(/^sub_[A-Za-z0-9]+$/),action:l.enum(["update","cancel","schedule","release"]),update:l.strictObject({items:l.array(up).max(20),remove:l.array(Go).max(20),restoreItems:l.array(l.strictObject({price:Go,quantity:l.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:l.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:l.number().int().positive().optional(),paymentBehavior:l.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:l.boolean().optional(),clearCancelAt:l.literal(!0).optional(),billingCycleAnchorNow:l.literal(!0).optional(),metadata:cp}).nullable(),cancel:l.strictObject({prorate:l.literal(!1),invoiceNow:l.literal(!1)}).nullable(),schedule:l.strictObject({currentItems:l.array(l.strictObject({price:Go,quantity:l.number().int().min(0).max(1e4)})).max(20),nextItems:l.array(up).min(1).max(20),switchAt:l.number().int().positive(),interval:l.enum(["week","month","year"]),intervalCount:l.number().int().min(1).max(52),resetBillingCycleAnchor:l.literal(!0).optional(),metadata:cp}).nullable(),release:l.strictObject({schedule:l.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:l.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"),qs=l.strictObject({carryOverBalances:Ko.optional(),carryOverUsages:Ko.optional(),operationId:l.uuid(),membershipId:l.uuid(),productVersionId:l.uuid(),timing:l.enum(["immediate","renewal"]),effectiveAt:l.iso.datetime({offset:!0}),expiresAt:l.iso.datetime({offset:!0}),currency:fe,creditMinor:Ot,debitMinor:Ot,discountMinor:Ot,taxMinor:Ot,totalMinor:Ot,retainedProductVersionIds:l.array(l.uuid()).max(19),execution:fp}),Ab=l.strictObject({operationId:l.uuid(),invoiceMode:l.boolean().optional(),membershipId:l.uuid(),productVersionId:l.uuid(),status:l.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:l.enum(["immediate","renewal"]),effectiveAt:l.iso.datetime({offset:!0}),checkoutUrl:l.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:l.enum(["indiana","merchant"]),execution:fp.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),yb=l.strictObject({operationId:l.uuid(),membershipId:l.uuid(),productVersionId:l.uuid(),timing:l.literal("store"),effectiveAt:l.null(),expiresAt:l.iso.datetime({offset:!0}),currency:fe,creditMinor:l.null(),debitMinor:l.null(),discountMinor:l.null(),taxMinor:l.null(),totalMinor:l.null(),retainedProductVersionIds:l.array(l.uuid()).max(19),store:l.strictObject({provider:l.enum(["apple","google"]),productId:l.string().min(1).max(255),catalogAmountMinor:Ot,policy:l.enum(["apple_store","google_full_price"])})}),bb=l.strictObject({operationId:l.uuid(),membershipId:l.uuid(),productVersionId:l.uuid(),status:l.enum(["prepared","pending","effective","cancelled","failed"]),timing:l.literal("store"),effectiveAt:l.iso.datetime({offset:!0}).nullable(),checkoutUrl:l.null(),nativePurchase:Ds.nullable()}),gp=l.union([qs,yb]),Vs=l.union([Ab,bb]),Vi=l.number().int().positive().max(2e8),br=l.number().int().min(0).max(2e8),hp=l.strictObject({requestId:l.uuid(),invoiceId:l.uuid(),mode:l.enum(["full","partial"]),amountMinor:Vi.optional(),entitlementAction:l.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Ap=l.strictObject({provider:l.literal("stripe"),executor:l.enum(["indiana","merchant"]),accountId:l.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:l.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Vi,currency:l.string().regex(/^[a-z]{3}$/),metadata:l.strictObject({indianaRefundId:l.uuid()}),idempotencyKey:l.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:l.array(l.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),yp=l.strictObject({operationId:l.uuid(),invoiceId:l.uuid(),providerInvoiceId:l.string().regex(/^in_[A-Za-z0-9]+$/),currency:fe,paidMinor:br,refundedMinor:br,pendingMinor:br,amountMinor:Vi,mode:l.enum(["full","partial"]),entitlementAction:l.enum(["retain","revoke"]),revokes:l.strictObject({customerProductIds:l.array(l.uuid()).max(100),subscriptionIds:l.array(l.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:Ap,expiresAt:l.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase()&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ho=l.strictObject({operationId:l.uuid(),invoiceId:l.uuid(),providerInvoiceId:l.string().regex(/^in_[A-Za-z0-9]+$/),status:l.enum(["quoted","pending","succeeded","failed","expired"]),executor:l.enum(["indiana","merchant"]),currency:fe,amountMinor:Vi,mode:l.enum(["full","partial"]),entitlementAction:l.enum(["retain","revoke"]),refundId:l.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:Ap.nullable(),failureReason:l.string().min(1).max(200).nullable(),createdAt:l.iso.datetime({offset:!0}),completedAt:l.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"),jO=l.strictObject({invoiceId:l.uuid(),currency:fe,paidMinor:br,refundedMinor:br,pendingMinor:br,refundableMinor:br,executor:l.enum(["indiana","merchant"]).nullable(),canRefund:l.boolean(),operations:l.array(Ho).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),TO=l.strictObject({requestId:l.uuid(),mode:l.enum(["full","partial"]),amountMinor:Vi.optional(),entitlementAction:l.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 bp=Ye.strictObject({requestId:Ye.uuid(),targets:Ye.array(Ye.strictObject({membershipId:Ye.uuid(),action:Ye.enum(["cancel","uncancel"]),timing:Ye.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"),Qo=Ye.strictObject({batchId:Ye.uuid()}),Sb=Ye.strictObject({operationId:Ye.uuid(),membershipIds:Ye.array(Ye.uuid()).min(1).max(20),provider:Ye.enum(["stripe","apple","google"]),action:Ye.enum(["cancel","uncancel"]),timing:Ye.enum(["immediate","renewal"]),status:Ye.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:qs.nullable(),managementUrl:Ye.url().nullable(),failureCode:Ye.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Ui=Ye.strictObject({batchId:Ye.uuid(),ready:Ye.boolean(),status:Ye.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:Ye.iso.datetime({offset:!0}),acceptedAt:Ye.iso.datetime({offset:!0}).nullable(),groups:Ye.array(Sb).min(1).max(100)});import{z as Ce}from"zod";var xb=Ce.string().trim().min(1).max(240),Us={requestId:Ce.uuid(),reason:xb},Jo=Ce.discriminatedUnion("action",[Ce.strictObject({...Us,action:Ce.literal("start"),productVersionId:Ce.uuid(),entityId:Ce.uuid().optional(),days:Ce.number().int().min(1).max(730).optional()}),Ce.strictObject({...Us,action:Ce.literal("extend"),membershipId:Ce.uuid(),days:Ce.number().int().min(1).max(730)}),Ce.strictObject({...Us,action:Ce.literal("end"),membershipId:Ce.uuid()})]),Sp=Ce.strictObject({operationId:Ce.uuid()}),xp=Ce.iso.datetime({offset:!0}),Ib=Ce.strictObject({provider:Ce.literal("stripe"),executor:Ce.enum(["indiana","merchant"]),accountId:Ce.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Ce.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Ce.union([Ce.literal("now"),xp]),prorationBehavior:Ce.literal("none")}),Ls=Ce.strictObject({operationId:Ce.uuid(),action:Ce.enum(["start","extend","end"]),status:Ce.enum(["pending","effective"]),managedBy:Ce.enum(["indiana","stripe"]),membershipIds:Ce.array(Ce.uuid()).min(1).max(20),endsAt:xp.nullable(),execution:Ib.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"),VO=Ce.strictObject({groupId:Ce.uuid(),productVersionId:Ce.uuid(),enabled:Ce.boolean()});import{z as Ke}from"zod";var Ip=Ke.strictObject({requestId:Ke.uuid(),currency:fe,makeDefault:Ke.boolean()}),vp=Ke.strictObject({setupId:Ke.uuid()}),vb=Ke.strictObject({provider:Ke.literal("stripe"),executor:Ke.literal("merchant"),accountId:Ke.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Ke.literal("setup"),currency:Ke.string().regex(/^[a-z]{3}$/),customer:Ke.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Ke.uuid(),metadata:Ke.strictObject({grooveProjectId:Ke.uuid(),grooveEnvironmentId:Ke.uuid(),grooveCustomerId:Ke.uuid(),groovePaymentSetupId:Ke.uuid()}),setDefaultPaymentMethod:Ke.boolean(),expiresAt:Ke.iso.datetime({offset:!0})}),Bs=Ke.strictObject({id:Ke.uuid(),provider:Ke.literal("stripe"),status:Ke.enum(["prepared","complete","expired"]),currency:fe,makeDefault:Ke.boolean(),url:Ke.url().nullable(),createdAt:Ke.iso.datetime({offset:!0}),expiresAt:Ke.iso.datetime({offset:!0}),completedAt:Ke.iso.datetime({offset:!0}).nullable(),execution:vb.nullable()});import{z as Ct}from"zod";var wp=Ct.union([Ct.string(),Ct.number(),Ct.boolean(),Ct.null()]),Op=Ct.strictObject({customerId:Ct.uuid()}),Cp=Ct.strictObject({customerId:Ct.uuid(),provider:Ct.literal("stripe"),checkedAt:Ct.iso.datetime({offset:!0}),status:Ct.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ct.number().int().nonnegative(),differences:Ct.array(Ct.strictObject({subscriptionId:Ct.string().startsWith("sub_"),itemId:Ct.string().nullable(),field:Ct.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:wp,actual:wp})).max(1e4)});import{z as he}from"zod";var Zo=he.iso.datetime({offset:!0}),Wo=he.strictObject({createdAt:Zo,id:he.uuid()}),Yo=he.strictObject({customerId:he.uuid().optional(),entityId:he.uuid().optional(),productId:he.string().min(1).max(256).optional(),provider:he.enum(["stripe","apple","google","free"]).optional(),status:he.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Wo.optional(),limit:he.number().int().min(1).max(100).optional()}),zs={id:he.uuid(),customerId:he.uuid(),entityId:he.uuid().nullable(),productId:he.string().min(1).max(256),productVersionId:he.uuid(),name:he.string().min(1).max(120),provider:he.enum(["stripe","apple","google","free"]),createdAt:Zo},wb=he.strictObject({...zs,status:he.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:he.boolean(),billingSubscriptionId:he.uuid().nullable()}),Ob=he.strictObject({...zs,status:he.enum(["active","ended","refunded"]),orderId:he.uuid().nullable(),transactionId:he.uuid().nullable(),currency:fe.nullable(),amountMinor:he.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),Cb=he.strictObject({...zs,status:he.enum(["blocked","resolved"]),conflict:he.strictObject({detectedAt:Zo,blockingMembershipIds:he.array(he.uuid()).min(1).max(100),transactionId:he.uuid()}),resolvedAt:Zo.nullable()}),Pp=Yo.extend({status:he.enum(["blocked","resolved"]).optional()}),_p=he.strictObject({customerId:he.uuid(),orderId:he.uuid()}),Ep=he.strictObject({orderId:he.uuid(),status:he.enum(["blocked","resolved"])}),Rp=he.strictObject({items:he.array(wb).max(100),nextCursor:Wo.nullable()}),kp=he.strictObject({items:he.array(Ob).max(100),nextCursor:Wo.nullable()}),jp=he.strictObject({items:he.array(Cb).max(100),nextCursor:Wo.nullable()});import{z as Ze}from"zod";var Tp=Ze.union([Ze.strictObject({intent:Ze.literal("read"),requestId:Ze.uuid(),purchaseIntentId:Ze.uuid()}),Ze.strictObject({requestId:Ze.uuid(),provider:Ze.literal("apple"),purchaseIntentId:Ze.uuid(),productId:Ze.string().min(1).max(255).optional(),signedTransaction:Ze.string().min(1).max(131072)}),Ze.strictObject({requestId:Ze.uuid(),provider:Ze.literal("google"),purchaseIntentId:Ze.uuid(),productId:Ze.string().min(1).max(255).optional(),purchaseToken:Ze.string().min(1).max(16384)})]),Np=Ze.strictObject({requestId:Ze.uuid(),orderId:Ze.uuid(),purchaseIntentId:Ze.uuid(),status:Ze.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:fe,refunded:Ze.boolean(),completion:Ze.strictObject({transactionIds:Ze.array(Ze.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ze.boolean()}).nullable()});import{z as V}from"zod";var Gs=V.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),Pb=V.record(V.string(),V.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),_b=3,Li=20,Eb=_b*Li,$s=V.strictObject({type:V.literal("product"),productId:Gs}),Dp={type:V.literal("group"),key:V.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:V.string().trim().min(1).max(80)},Rb=V.discriminatedUnion("type",[$s,V.strictObject({...Dp,items:V.array($s).max(Li)})]),kb=V.discriminatedUnion("type",[$s,V.strictObject({...Dp,items:V.array(Rb).max(Li)})]),jb=V.array(kb).max(Li).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>Li||i>Eb)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Ks(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Ks(t))}var Yr=V.strictObject({lookupKey:V.string().trim().min(1).max(200),displayName:V.string().trim().min(1).max(1500),items:jb,metadata:Pb}),Tb=V.strictObject({product:V.record(V.string(),V.json()),prices:V.array(V.record(V.string(),V.json())),entitlements:V.array(V.record(V.string(),V.json())),freeTrials:V.array(V.record(V.string(),V.json())),licenses:V.array(V.record(V.string(),V.json()))}),Fp=Yr.extend({id:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),state:V.enum(["active","archived"]),isCurrent:V.boolean(),revision:V.number().int().nonnegative(),publishedVersionId:V.uuid().nullable(),createdAt:V.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"})}),Mp=V.strictObject({id:V.uuid(),offeringId:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),version:V.number().int().positive(),document:Yr,productEvidence:V.record(Gs,Tb),createdAt:V.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Ks(e.document);(!n.length||Fb(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"})}),Nb=V.strictObject({rows:V.array(Fp).max(200),versions:V.array(Mp).max(500)}),XO=V.discriminatedUnion("action",[V.strictObject({action:V.literal("create"),document:Yr}),V.strictObject({action:V.literal("save"),id:V.uuid(),revision:V.number().int().nonnegative(),document:Yr}),V.strictObject({action:V.enum(["publish","set_current","archive","restore"]),id:V.uuid(),revision:V.number().int().nonnegative()})]),eC=V.strictObject({record:Fp,version:Mp.nullable()}),qp=V.discriminatedUnion("type",[V.strictObject({type:V.literal("current")}),V.strictObject({type:V.literal("id"),id:V.uuid()}),V.strictObject({type:V.literal("lookup_key"),lookupKey:V.string().min(1).max(200)}),V.strictObject({type:V.literal("version"),versionId:V.uuid()})]),Db=V.strictObject({internalId:Gs,id:V.string(),name:V.string().nullable(),version:V.number().int().positive(),archived:V.boolean()}),tC=Nb.extend({products:V.array(Db).max(500),pagination:V.strictObject({rows:V.string().nullable(),versions:V.string().nullable(),products:V.string().nullable()}).optional()});function Fb(e){let t=[];Ks(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 Xo}from"zod";var Vp=Xo.strictObject({id:Xo.uuid(),offeringId:Xo.uuid(),version:Xo.number().int().positive(),document:Yr});import{z as ht}from"zod";import{z as ue}from"zod";import{z as Xr}from"zod";var ea=Xr.strictObject({items:Xr.array(Xr.strictObject({productVersionId:Xr.string().min(1).max(200),label:Xr.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Xr.string().min(1).max(200).nullable(),grouping:Vo.optional()});function Up(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 ft}from"zod";var Mb=ft.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ta=ft.discriminatedUnion("type",[ft.object({type:ft.literal("fixed"),productVersionId:ft.string().min(1).max(200)}).strict(),ft.object({type:ft.literal("picker"),pickerId:Mb,allowedProductVersionIds:ft.array(ft.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")]),jn=ft.discriminatedUnion("type",[ft.object({type:ft.literal("modal"),size:ft.enum(["sm","md","lg"])}).strict(),ft.object({type:ft.literal("sheet"),size:ft.enum(["sm","md","lg"])}).strict(),ft.object({type:ft.literal("fullscreen")}).strict(),ft.object({type:ft.literal("inline")}).strict()]);var Hs=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("event"),event:ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ue.strictObject({type:ue.literal("open_url"),url:ue.url().refine(e=>new URL(e).protocol==="https:")})]),qb=Wt,Vb=ue.discriminatedUnion("type",[ue.object({type:ue.literal("checkout"),product:ta}).strict(),ue.object({type:ue.literal("close")}).strict(),ue.object({type:ue.literal("action"),action:Hs}).strict()]),ei=ue.object({schemaVersion:ue.literal(3),kind:ue.literal("paywall"),name:ue.string().trim().min(1).max(80),presentation:jn,requirement:zn.optional(),products:ea,offeringVersionId:ue.uuid().nullable(),offeringId:ue.uuid(),screen:qb,buttons:ue.record(ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Vb)}).strict(),yC=ei.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 Lb(e))t.addIssue({code:"custom",message:r});for(let r of Ub(e))t.addIssue({code:"custom",message:r});Gn(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 Ub(e){let t=e.products.items.map(a=>a.productVersionId),n=Rd(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&&(!Uo(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")),Dt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let d=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(d)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Dt(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 Lb(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 d=e.screen.actions.find(w=>w.id===u);d?.type==="navigate"&&r.get(s.id).push(d.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Lp=ue.object({id:ue.uuid(),projectId:ue.uuid(),environmentId:ue.uuid(),revision:ue.number().int().nonnegative(),state:ue.enum(["active","archived"]),publishedVersionId:ue.uuid().nullable(),updatedAt:ue.iso.datetime({offset:!0}),draft:ei}).strict(),bC=ue.object({rows:ue.array(Lp).max(200),nextCursor:ue.uuid().nullable()}).strict(),SC=Lp.omit({draft:!0}).extend({name:ue.string(),productCount:ue.number().int().nonnegative()}).strict(),xC=ue.discriminatedUnion("action",[ue.object({action:ue.literal("save"),id:ue.uuid().nullable(),revision:ue.number().int().nonnegative(),document:ei}).strict(),ue.object({action:ue.enum(["publish","archive"]),id:ue.uuid(),revision:ue.number().int().nonnegative()}).strict()]),IC=ue.object({paywalls:ue.array(ue.object({id:ue.uuid(),paywallId:ue.uuid(),version:ue.number().int().positive(),name:ue.string().min(1).max(80),presentation:jn,buttons:ei.shape.buttons}).strict()).max(500),limited:ue.boolean()}).strict();import{z as ve}from"zod";import{z as Ft}from"zod";var ti=Ft.string().regex(/^[a-f0-9]{64}$/),Bb=Mo.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Bp=Ft.strictObject({couponDigests:Ft.record(Ft.uuid(),ti),variables:Ft.record(ln,Ft.record(Ft.uuid(),Ft.partialRecord(Ft.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Ft.string()))),locales:Ft.record(ln,$r.extend({nodes:Ft.record(Ft.string(),Ft.strictObject({base:Bb})),plans:Ft.object({}).strict(),pickers:Ft.object({}).strict()}).omit({paywall:!0}))});import{z as De}from"zod";import{z as na}from"zod";var Qs=na.strictObject({eventsEnabled:na.boolean(),experimentViewsEnabled:na.boolean(),featureUsageEnabled:na.boolean()}),EC=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function zp(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as B}from"zod";var Js=B.tuple([B.number().min(0).max(1),B.number().min(0).max(1)]).refine(([e,t])=>e<=t),zb=B.strictObject({attribute:B.string().optional(),seed:B.string(),hashVersion:B.literal(2),ranges:B.array(Js).max(100)}),$b=B.strictObject({id:B.string().min(1).max(255),condition:Bt,gate:B.boolean().optional()}),Gb=B.strictObject({key:B.string().optional(),name:B.string().optional(),passthrough:B.boolean().optional()}),$p={condition:Bt.optional(),parentConditions:B.array($b).max(100).optional(),weights:B.array(B.number().min(0).max(1)).max(20).optional(),coverage:B.number().min(0).max(1).optional(),hashAttribute:B.string().optional(),fallbackAttribute:B.string().optional(),hashVersion:B.literal(2).optional(),disableStickyBucketing:B.boolean().optional(),bucketVersion:B.number().int().nonnegative().optional(),minBucketVersion:B.number().int().nonnegative().optional(),filters:B.array(zb).max(100).optional(),ranges:B.array(Js).max(20).optional(),meta:B.array(Gb).max(20).optional(),seed:B.string().optional(),name:B.string().optional(),phase:B.string().optional()},ni=B.strictObject({...$p,key:B.string().min(1).max(255),variations:B.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20),urlPatterns:B.array(B.strictObject({include:B.boolean(),type:B.enum(["regex","simple"]),pattern:B.string()})).max(100).optional(),force:B.number().int().nonnegative().optional(),active:B.boolean().optional(),persistQueryString:B.boolean().optional()}),Zs=B.strictObject({value:ge,variationId:B.number().int(),key:B.string(),name:B.string().optional(),bucket:B.number().optional(),passthrough:B.boolean().optional(),inExperiment:B.boolean(),hashUsed:B.boolean().optional(),hashAttribute:B.string(),hashValue:B.string(),featureId:B.string().nullable(),stickyBucketUsed:B.boolean().optional()}),Kb=B.strictObject({...$p,id:B.string().max(255).optional(),force:ge.optional(),variations:B.array(ge).min(2).max(20).optional(),key:B.string().optional(),range:Js.optional(),tracks:B.array(B.strictObject({experiment:ni,result:Zs})).max(100).optional()}),Hb=B.strictObject({defaultValue:ge.optional(),rules:B.array(Kb).max(500).optional()}),Bi=B.record(B.string(),B.union([B.strictObject({type:B.literal("hashed"),attributeKey:B.string(),values:B.array(B.string().regex(/^[a-f0-9]{64}$/))}),B.strictObject({type:B.literal("list"),attributeKey:B.string(),values:B.array(B.union([B.string(),B.number()]))}),B.strictObject({type:B.literal("condition"),condition:Bt})])),on=B.strictObject({scope:Ve,generation:B.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:B.iso.datetime({offset:!0}),expiresAt:B.iso.datetime({offset:!0}).nullable(),features:B.record(B.string(),Hb),savedGroups:Bi,experiments:B.record(B.uuid(),ni)});var zi=on.extend({analyticsConfig:Qs,remoteFeatures:De.array(De.string().min(1).max(255)).max(500)}),Ws=zi.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"})}),Gp=De.strictObject({attributes:mt,features:De.array(De.string().min(1).max(255)).max(500).optional(),customerId:De.uuid().optional()}),Qb=De.strictObject({value:ge,source:De.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:De.boolean(),off:De.boolean(),ruleId:De.string(),experimentResult:Zs.optional()}),ra=De.strictObject({generation:on.shape.generation,evaluatedAt:on.shape.evaluatedAt,expiresAt:on.shape.expiresAt,features:De.record(De.string(),Qb),merchandiseContext:De.strictObject({merchandiseId:De.uuid(),merchandise:mt}).optional()}),Kp=De.strictObject({customerId:De.uuid().optional(),events:De.array(De.strictObject({eventUuid:De.uuid(),timestamp:De.iso.datetime({offset:!0}),name:De.string().min(1).max(255),merchandise:kl.optional(),properties:De.record(De.string(),ge).default({}),deviceId:De.string().min(1).max(255).optional(),sessionId:De.string().min(1).max(255).optional()})).min(1).max(100)}),Hp=De.strictObject({inserted:De.number().int().nonnegative(),duplicates:De.number().int().nonnegative(),rejected:De.number().int().nonnegative(),skipped:De.number().int().nonnegative(),analyticsConfig:Qs});import{z as U}from"zod";function Ys(e,t=[]){let n=[];Dt(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(Lo(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 Qp(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Qp(t)??[])}}function Jb(e){let t=e.pages.map(i=>{let a=Qp(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(Lo({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 Jp(e,t=[]){let n=Wt.parse(structuredClone(Jb(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=Ys(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as K}from"zod";import{z as N}from"zod";import{z as ot}from"zod";var ia=ot.strictObject({schemaVersion:ot.literal(1),renderKey:ot.string().min(1).max(256),routeTemplate:ot.string().startsWith("/").max(2048),selectors:ot.array(ot.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:ot.array(ot.number().int().min(0)).min(1),absent:ot.array(ot.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"})}),Zp=ot.strictObject({renderKey:ot.string().min(1).max(256),routeKey:ot.string().min(1).max(256),stateKey:ot.string().min(1).max(256),documentKey:ot.string().min(1).max(256),documentHash:ot.string().regex(/^[a-f0-9]{64}$/),compositionKey:ot.string().min(1).max(256),entryMode:ot.enum(["hard","soft"]),match:ot.strictObject({present:ot.array(ot.number().int().min(0)),absent:ot.array(ot.number().int().min(0))})});import{z as xr}from"zod";var Zb=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Xs="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Wb=xr.string().regex(new RegExp(`^${Xs}/${Xs}/${Xs}/manifest\\.json$`)),Wp=xr.strictObject({kind:xr.literal("gcs-resumable"),url:xr.url(),bucket:xr.enum(Zb),objectKey:Wb,byteLength:xr.number().int().positive(),expiresAt:xr.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 ct=N.string().min(1).max(256),Xt=N.string().regex(/^[a-f0-9]{64}$/),oa=N.strictObject({versionId:N.uuid(),manifestDigest:Xt,sourceGraphDigest:Xt,pageKey:ct,stateKey:ct,documentKey:ct,documentHash:Xt,elementKey:ct.optional(),nodeId:ct.optional(),contentHash:Xt.optional(),renderKey:ct.optional()}),Yp=N.strictObject({pageKey:ct,documentKey:ct,expectedDocumentHash:Xt,renderKey:ct.optional(),nodeId:ct,elementKey:ct,expectedContentHash:Xt,property:N.enum(["text","fontSize","color"]),value:N.union([N.string().max(4e3),N.number().finite()])}),Xp=N.strictObject({versionId:N.uuid(),manifestDigest:Xt,sourceGraphDigest:Xt,pageKey:ct,stateKey:ct,documentKey:ct,documentHash:Xt,renderKey:ct.optional(),patches:N.array(Yp.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),Yb=/^[a-z][a-z0-9-]{0,39}$/,$i=N.string().regex(Yb),tc=N.enum(["web","ios","android"]),ZC=N.discriminatedUnion("action",[N.strictObject({action:N.literal("register"),requestId:N.uuid(),client:$i,platform:tc,label:N.string().trim().min(1).max(100),sha256:Xt,bytes:N.number().int().min(1),transferBytes:N.number().int().min(1)}),N.strictObject({action:N.literal("complete"),versionId:N.uuid()}),N.strictObject({action:N.literal("current"),versionId:N.uuid(),expectedCurrent:N.uuid().nullable()}),N.strictObject({action:N.literal("delivery"),enabled:N.boolean()}),N.strictObject({action:N.literal("changes"),versionId:N.uuid(),experimentId:N.uuid(),variationId:ct,changesetId:N.uuid().nullable(),expectedRevision:Xt.nullable(),editorUrl:N.string().url().max(2048),patches:N.array(Yp).max(200)})]),nc=N.strictObject({id:N.uuid(),projectId:N.uuid(),environmentId:N.uuid(),clientKey:$i,platform:tc,label:N.string(),sha256:Xt,bytes:N.number().int().positive(),objectKey:N.string(),state:N.enum(["uploading","ready","rejected"]),isCurrent:N.boolean(),revision:N.number().int().nonnegative(),createdAt:N.string(),expiresAt:N.string(),readyAt:N.string().nullable(),summary:N.record(N.string(),N.json()),routeTree:N.json().nullable(),validation:N.record(N.string(),N.json())}),Xb=N.strictObject({key:$i,platform:tc,currentId:N.uuid().nullable()}),WC=N.strictObject({rows:N.array(nc).max(100),nextCursor:N.uuid().nullable(),clients:N.array(Xb).max(20)}),ec=N.strictObject({storedBytes:N.number().int().nonnegative(),reservedBytes:N.number().int().nonnegative(),chargedBytes:N.number().int().nonnegative(),versions:N.number().int().nonnegative(),objects:N.number().int().nonnegative(),orphanObjects:N.number().int().nonnegative(),missingReadyObjects:N.number().int().nonnegative(),unknownObjectSizes:N.number().int().nonnegative(),byteLimit:N.number().int().positive(),versionLimit:N.number().int().positive(),remainingBytes:N.number().int().nonnegative()}),YC=N.strictObject({asOf:N.iso.datetime({offset:!0}),reclamation:N.literal("manual-review-required"),buckets:N.strictObject({source:ec,runtime:ec,previews:ec})}),XC=N.strictObject({version:nc,actorId:N.uuid(),claims:N.record(N.string(),N.json())}),eP=N.strictObject({version:nc,upload:Wp.nullable()}),tP=N.object({format:N.literal("indiana-route-state-index"),schemaVersion:N.literal(3),routes:N.array(N.object({routeKey:ct,path:N.string(),documentKey:ct,documentHash:Xt,initialStateKey:ct,initialRenderKey:ct})),renders:N.array(Zp)}).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"})}),nP=N.strictObject({rows:N.array(N.object({id:N.uuid(),name:N.string(),status:N.string(),variations:N.array(N.object({id:ct,key:ct,name:N.string().optional()}).loose())}).loose()),limited:N.boolean()}),rP=N.strictObject({enabled:N.boolean(),allowedOrigins:N.array(N.string())});import{z as ri}from"zod";var em=ri.strictObject({id:ri.uuid(),name:ri.string().trim().min(1).max(80),client:$i,source:oa,event:ri.enum(["screen_enter","button_click"]),cooldownSeconds:ri.number().int().min(0).max(2592e3),behavior:ri.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 Le}from"zod";var rc=ge,eS=["parameters","answers","results","variables"];function ic(e){return eS.some(t=>e===t||e.startsWith(t+"."))}function oc(e){let t={};for(let[r,i]of Object.entries(Bo(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])=>!ic(r))),variables:t}}import{z as ut}from"zod";var aa=ut.discriminatedUnion("kind",[ut.object({kind:ut.literal("ledger"),cursor:Fo}).strict(),ut.object({kind:ut.literal("billing"),cursor:ut.uuid()}).strict()]),tS=ut.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Hn=ut.record(ut.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ut.union([ut.string().max(500),ut.boolean(),ut.array(ut.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),nS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function ac(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>ac(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||nS.test(n)||ac(r,t+1)))}var rS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,Qn=ut.record(tS,ge).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!ac(e)&&!rS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var tm=ut.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),sa=ut.array(ut.object({variable:tm,componentId:tm,required:ut.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"),gP=ut.object({bindings:sa,answers:Hn,values:ut.record(ut.string(),ge).optional()}).strict();import{z as iS}from"zod";var ca=iS.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var sc=Le.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),nm=Le.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),rm=Qn.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),cc=Le.record(sc,Le.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),oS=xn,im=Le.strictObject({type:Le.literal("external_task"),endpointId:Le.uuid(),taskKey:sc,inputs:Le.record(sc,oS).refine(e=>Object.keys(e).length<=20),outputs:cc}),om=Le.strictObject({maxAttempts:Le.number().int().min(1).max(5),retryDelaySeconds:Le.number().int().min(1).max(30),backoff:Le.enum(["fixed","exponential"]),requestTimeoutSeconds:Le.number().int().min(1).max(10),timeoutSeconds:Le.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var OP=Le.strictObject({outcome:Le.enum(["success","failure"]),data:rm});var CP=Le.discriminatedUnion("operation",[Le.strictObject({operation:Le.literal("signal"),runId:Le.uuid(),nodeId:nm,eventName:ca,eventId:Le.uuid(),data:rm}),Le.strictObject({operation:Le.literal("read_results"),runId:Le.uuid()})]),PP=Le.strictObject({scope:Ve,runId:Le.uuid(),eventId:Le.uuid(),accepted:Le.boolean()}),aS=Le.record(nm,rc),_P=Le.strictObject({scope:Ve,runId:Le.uuid(),results:aS});var hn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},am="00000000-0000-0000-0000-000000000000";import{z as H}from"zod";import{z as He}from"zod";var NP=He.enum(["local","remote"]),uc=He.strictObject({port:He.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ge.optional(),sticky:He.array(He.strictObject({expected:bi.nullable(),next:bi})).max(100),exposures:He.array(ge).max(100),features:He.array(ge).max(100)}),sm=He.strictObject({type:He.literal("evaluate"),receiptId:He.uuid(),environmentId:He.uuid(),policyRevision:He.number().int().nonnegative(),attributes:mt,sticky:He.record(He.string(),bi)}),cm=sm.extend({runId:He.uuid(),versionId:He.uuid(),nodeId:He.string().min(1).max(64),visit:He.number().int().nonnegative(),revision:He.number().int().nonnegative()}),lc=sm.omit({type:!0,receiptId:!0}).extend({type:He.literal("evaluate_segment")}),um=He.strictObject({nodeId:He.string().min(1).max(64),result:uc}),lm=lc.extend({runId:He.uuid(),versionId:He.uuid(),nodeId:He.string().min(1).max(64),visit:He.number().int().nonnegative(),revision:He.number().int().nonnegative(),parameters:Qn,answers:Hn,variables:He.record(He.string(),ge)});import{z as ie}from"zod";var dc=ie.array(ie.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"),ua=ie.intersection(mt,ie.looseObject({tags:dc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),la=ie.string().trim().max(80),da=ie.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),pa=ie.union([ie.email().max(254),ie.literal("")]),ma=ie.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),dm=ie.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),pm=ie.object({externalUserId:dm.optional(),name:la.default(""),email:pa.default(""),phone:da.optional(),attributes:ua.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),fa=ie.discriminatedUnion("type",[ie.strictObject({type:ie.literal("id"),value:ie.uuid()}),ie.strictObject({type:ie.literal("externalUserId"),value:dm})]),ga=ie.strictObject({name:la.optional(),email:pa.optional(),phone:da.optional(),attributes:ua.optional(),fingerprint:ma.optional()}),ha=e=>!e.customerData||e.customer?.type==="externalUserId",Aa="customerData requires an externalUserId customer",ii=ie.object({id:ie.uuid(),externalUserId:ie.string().min(1).max(255).nullable(),name:la,email:pa,phone:da.optional(),attributes:ua,createdAt:ie.iso.datetime()}).strict(),mm=ie.object({customer:ii,changed:ie.boolean(),replayed:ie.boolean()}).strict(),sS=ie.discriminatedUnion("type",[ie.object({type:ie.literal("id"),value:ie.uuid()}).strict(),ie.object({type:ie.literal("externalUserId"),value:ie.string().trim().min(1).max(255)}).strict()]),cS=ie.object({name:la.optional(),email:pa.optional(),phone:da.optional(),attributes:ua.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ie.array(ie.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ie.strictObject({add:dc,remove:dc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),pc=ie.object({lookup:sS}).strict(),fm=pc.extend({requestId:ie.uuid(),patch:cS}).strict(),gm=ie.object({search:ie.string().trim().max(200).default(""),tag:ie.string().trim().max(40).default(""),planId:ie.string().max(200).default(""),versionId:ie.string().max(200).default(""),holdingStatus:ie.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ie.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ie.union([ie.iso.datetime(),ie.literal("")]).default(""),createdUntil:ie.union([ie.iso.datetime(),ie.literal("")]).default(""),offset:ie.coerce.number().int().min(0).max(1e5).default(0),limit:ie.coerce.number().int().min(1).max(100).default(50)}).strict(),hm=ie.object({customers:ii.array(),hasMore:ie.boolean(),total:ie.number().int().nonnegative().nullable(),evaluatedAt:ie.iso.datetime()}).strict();var Gi=H.discriminatedUnion("type",[H.strictObject({type:H.literal("literal"),value:ge}),H.strictObject({type:H.literal("variable"),key:dt,path:gn.optional()}),H.strictObject({type:H.literal("feature"),featureKey:H.string().min(1).max(128)})]),uS=H.strictObject({requestId:H.uuid(),decisionId:H.uuid(),customerId:H.uuid(),externalUserId:H.string().min(1).max(255).nullable(),versionId:H.uuid(),receiptId:H.uuid(),value:ge}),lS={funnelId:H.uuid(),requestId:H.uuid(),customer:fa,customerData:ga.optional(),attributes:mt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},KP=H.discriminatedUnion("operation",[H.strictObject({operation:H.literal("decide"),...lS}).refine(ha,Aa),H.strictObject({operation:H.literal("read_decision"),decisionId:H.uuid()}),H.strictObject({operation:H.literal("evaluate_decision"),decisionId:H.uuid(),requestId:H.uuid(),nodeId:H.string().min(1).max(64),visit:H.number().int().nonnegative(),revision:H.number().int().nonnegative(),receiptId:H.uuid(),policyRevision:H.number().int().nonnegative(),generation:H.string().min(1).max(256),result:uc}),H.strictObject({operation:H.literal("feature_config"),funnelId:H.uuid()}),H.strictObject({operation:H.literal("commit_decision_segment"),decisionId:H.uuid(),requestId:H.uuid(),nodeId:H.string().min(1).max(64),visit:H.number().int().nonnegative(),revision:H.number().int().nonnegative(),policyRevision:H.number().int().nonnegative(),generation:H.string().min(1).max(256),steps:H.array(um).max(32),boundary:H.strictObject({nodeId:H.string().min(1).max(64),visit:H.number().int().nonnegative()}).optional()}),H.strictObject({operation:H.literal("segment_configuration"),funnelId:H.uuid(),versionId:H.uuid()}),H.strictObject({operation:H.literal("configuration"),funnelId:H.uuid(),versionId:H.uuid().optional()}),H.strictObject({operation:H.literal("local_configuration"),funnelId:H.uuid()}),H.strictObject({operation:H.literal("report_used"),decisionId:H.uuid(),eventId:H.uuid(),occurredAt:H.iso.datetime({offset:!0}),reference:H.string().min(1).max(128).optional()})]),HP=H.strictObject({scope:Ve,decisionId:H.uuid(),requestId:H.uuid(),status:H.enum(["pending","completed","failed"]),decision:uS.nullable(),evaluation:H.discriminatedUnion("type",[cm,lm]).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"),QP=H.strictObject({scope:Ve,decisionId:H.uuid(),eventId:H.uuid(),source:H.literal("caller_reported")});import{z as Pt}from"zod";var Am=Pt.strictObject({type:Pt.literal("bundle"),paywall:xn.optional(),offering:xn.optional(),coupons:xn,data:xn}),dS=e=>Pt.strictObject({type:Pt.literal(e),id:Pt.uuid()}),e1=Pt.strictObject({type:Pt.literal("bundle"),paywallVersionId:Pt.uuid().optional(),offeringVersionId:Pt.uuid().optional(),couponIds:Pt.array(Pt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ge});var t1=Pt.strictObject({type:Pt.literal("bundle"),offering:dS("offering_version").nullable(),paywall:Pt.strictObject({versionId:Pt.uuid(),paywallId:Pt.uuid(),offeringVersionId:Pt.uuid()}).nullable(),coupons:Pt.array(Si).max(20),data:ge});import{z as An}from"zod";import{z as an}from"zod";var ym=an.union([an.string(),an.number().finite(),an.boolean(),an.null()]),pS=an.union([ym,an.array(ym).min(1).max(20)]),mS=an.record(gn,pS).refine(e=>Object.keys(e).length<=10),bm=an.strictObject({path:gn,type:an.enum(["string","number","boolean","strings"]),nullable:an.boolean().optional(),aggregation:an.enum(["count","exists"]).optional(),where:mS.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 fS=["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"],Sm=An.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),gS=xn,xm=An.discriminatedUnion("type",[im,An.strictObject({type:An.literal("claim_offer"),coupon:xn}),An.strictObject({type:An.literal("event"),event:Sm}),An.strictObject({type:An.literal("api"),operation:An.enum(fS),inputs:An.record(gn,gS).refine(e=>Object.keys(e).length<=40),outputs:An.record(Sm,bm).refine(e=>Object.keys(e).length<=20)})]);var tt=ca,hS=K.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),en={id:tt,name:K.string().trim().min(1).max(80),position:K.strictObject({x:K.number().finite(),y:K.number().finite()}).optional()},AS={success:tt,cancel:tt,unavailable:tt,failure:tt},mc=K.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),fc=K.enum(["same_window","new_window"]),yS=K.discriminatedUnion("type",[K.strictObject({...en,type:K.literal("entry"),next:tt,triggers:K.array(em).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),K.strictObject({...en,type:K.literal("screen"),screenId:tt,presentation:jn,outputs:K.record(tt,tt),offering:K.discriminatedUnion("source",[K.strictObject({source:K.literal("variable"),key:dt}),K.strictObject({source:K.literal("fixed"),versionId:K.uuid()})]).optional()}),K.strictObject({...en,type:K.literal("offering"),configuration:K.discriminatedUnion("source",[K.strictObject({source:K.literal("fixed"),versionId:K.uuid()}),K.strictObject({source:K.literal("feature"),featureKey:K.string().min(1).max(128)})]),writes:K.strictObject({value:dt}),next:tt}),K.strictObject({...en,type:K.literal("coupon"),couponId:K.uuid(),writes:K.strictObject({value:dt}),next:tt}),K.strictObject({...en,type:K.literal("coupons"),couponIds:K.array(K.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:K.strictObject({value:dt}),next:tt}),K.strictObject({...en,type:K.literal("output"),value:K.discriminatedUnion("type",[...Gi.options,Am,K.strictObject({type:K.literal("selection"),screenId:tt,offeringKey:dt})])}),K.strictObject({...en,type:K.literal("condition"),cases:K.array(K.strictObject({condition:Bt,target:tt})).min(1).max(50),default:tt}),K.strictObject({...en,type:K.literal("feature"),featureKey:K.string().min(1).max(128),writes:K.strictObject({value:dt}),next:tt}),K.strictObject({...en,type:K.literal("split"),experimentId:K.uuid(),applyPageExperiment:K.literal(!0).optional(),routes:K.record(hS,tt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:tt}),K.strictObject({...en,type:K.literal("action"),...AS,execution:om,action:xm,writes:Es.optional()}),K.strictObject({...en,type:K.literal("external_page"),appManifest:oa.optional(),url:mc,openIn:fc,opened:tt,failed:tt}),K.strictObject({...en,type:K.literal("end"),outcome:K.enum(["completed","closed","ineligible","failed"]),output:Gi.optional()}),K.strictObject({...en,type:K.literal("wait"),writes:Es.optional(),wait:K.discriminatedUnion("type",[K.strictObject({type:K.literal("duration"),delaySeconds:K.number().int().min(1).max(2592e3),elapsed:tt}),K.strictObject({type:K.literal("event"),eventName:tt,outputs:cc,timeoutSeconds:K.number().int().min(1).max(2592e3),received:tt,timeout:tt})])})]),gc=K.strictObject({version:K.literal(5),entry:tt,nodes:K.array(yS).min(1).max(hn.flowNodes)}),hc=gc.superRefine((e,t)=>{bS(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function ya(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 bS(e,t){let n=[],r=new Map(e.nodes.map(d=>[d.id,d])),i=(d,m,w)=>{n.push(d),t?.({message:d,reason:m,path:w?["nodes",e.nodes.indexOf(w)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(d=>d.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(d=>d.type==="screen").length>hn.pages||e.nodes.filter(d=>!["screen","entry","end","output"].includes(d.type)).length>hn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let d of e.nodes){for(let m of ya(d))m===e.entry&&i("An entry cannot be a transition target","entryTarget",d),r.has(m)||i(`Missing target ${m}`,"missingTarget",d);d.type==="screen"&&(a.has(d.screenId)&&i("Every screen has exactly one node owner","screenOwner",d),a.add(d.screenId))}let o=new Set,s=new Set,c=new Set;function u(d){if(o.has(d)){i("Flow edges must not form a cycle","cycle",r.get(d));return}if(!(s.has(d)||!r.has(d))){o.add(d),c.add(d);for(let m of ya(r.get(d)))u(m);o.delete(d),s.add(d)}}u(e.entry);for(let d of e.nodes)c.has(d.id)||i("Every node must be reachable from Entry","unreachable",d);return[...new Set(n)]}var Ac={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Im(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(d=>s===d||c&&s.startsWith(d+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of Un(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 D}from"zod";var oi=D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ba=e=>D.record(D.string(),ge).refine(t=>Yt(t)<=e,"Funnel evidence exceeds its byte budget"),j1=D.enum(["local_segment","evaluation","presentation","timer","event","operation"]),bc=D.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Sc=D.discriminatedUnion("type",[D.strictObject({type:D.literal("flag"),key:D.string().min(1).max(128)}),D.strictObject({type:D.literal("experiment"),id:D.uuid()}),D.strictObject({type:D.literal("saved_group"),id:D.uuid()}),D.strictObject({type:D.literal("config"),key:D.string().min(1).max(128)}),D.strictObject({type:D.literal("constant"),key:D.string().min(1).max(128)}),D.strictObject({type:D.literal("paywall_version"),id:D.uuid()}),D.strictObject({type:D.literal("offering_version"),id:D.uuid()}),D.strictObject({type:D.literal("reward"),id:D.uuid()})]),Ki=D.strictObject({schemaVersion:D.literal(1),kind:bc,selector:Sc.nullable(),context:ba(131072),contract:D.strictObject({version:D.number().int().positive(),evaluator:D.string().min(1).max(128),policyRevision:D.number().int().nonnegative()})}).refine(e=>Yt(e)<=131072,"Node input exceeds its byte budget"),vm=D.strictObject({schemaVersion:D.literal(1),kind:bc,outcome:D.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ba(131072),route:D.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ba(131072)}).refine(e=>Yt(e)<=131072,"Node result exceeds its byte budget"),T1=D.strictObject({schemaVersion:D.literal(1),operations:D.record(oi,D.strictObject({attempts:D.number().int().nonnegative(),maxAttempts:D.number().int().min(1).max(5),deadlineAt:D.iso.datetime({offset:!0}),retryAt:D.iso.datetime({offset:!0}).nullable(),error:D.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:D.strictObject({type:oi,id:D.uuid()}).nullable()}))}).refine(e=>Yt(e)<=65536,"Execution state exceeds its byte budget"),Ir={receiptId:D.uuid()},yc=D.iso.datetime({offset:!0}),N1=D.discriminatedUnion("type",[D.strictObject({type:D.literal("node_entered"),details:D.strictObject({kind:bc})}),D.strictObject({type:D.literal("presentation_shown"),details:D.strictObject({...Ir,source:D.literal("client"),occurredAt:yc.optional()})}),D.strictObject({type:D.literal("decision_accepted"),details:D.strictObject(Ir)}),D.strictObject({type:D.literal("signal_received"),details:D.strictObject({signalId:D.uuid(),nodeId:oi,eventName:oi,data:ba(8192),source:D.literal("server"),occurredAt:yc})}),D.strictObject({type:D.literal("signal_consumed"),details:D.strictObject({...Ir,signalId:D.uuid()})}),D.strictObject({type:D.literal("wait_elapsed"),details:D.strictObject(Ir)}),D.strictObject({type:D.literal("wait_timeout"),details:D.strictObject(Ir)}),D.strictObject({type:D.literal("operation_completed"),details:D.strictObject({...Ir,operation:oi,reference:D.strictObject({type:oi,id:D.uuid()}).nullable()})}),D.strictObject({type:D.literal("execution_recovered"),details:D.strictObject({generation:D.number().int().positive(),reason:D.enum(["interrupted","expired_lease","delivery_failed"])})}),D.strictObject({type:D.literal("execution_failed"),details:D.strictObject({generation:D.number().int().positive(),code:D.string().regex(/^[a-z_]{1,64}$/)})}),D.strictObject({type:D.literal("run_completed"),details:D.strictObject({outcome:D.enum(["completed","ineligible","failed"])})}),D.strictObject({type:D.literal("run_closed"),details:D.strictObject({source:D.enum(["client","server","expiry"])})}),D.strictObject({type:D.literal("treatment_used"),details:D.strictObject({...Ir,source:D.enum(["client","server"]),occurredAt:yc,reference:D.string().min(1).max(128).optional()})})]);var sn=U.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),SS=U.discriminatedUnion("type",[U.strictObject({id:sn,type:U.literal("owned"),publicData:Bp.optional(),document:Wt.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")}),U.strictObject({id:sn,type:U.literal("paywall"),paywallVersionId:U.uuid()})]),xc={kind:U.literal("funnel"),schemaVersion:U.literal(4),screens:U.array(SS).max(hn.pages),references:U.record(sn,Sc).refine(e=>Object.keys(e).length<=500),inputs:U.array(U.strictObject({variable:sn,screenId:sn,componentId:sn,required:U.boolean()})).max(hn.questions),variables:U.record(dt,Kr).refine(e=>Object.keys(e).length<=hn.logicNodes),outputSchema:Gr,execution:U.strictObject({runTimeoutSeconds:U.number().int().min(1).max(Ac.runTimeoutSeconds),maxTransitions:U.number().int().min(1).max(Ac.maxTransitions)})},X1=U.strictObject({...xc,graph:gc});function xS(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 xa(e){return Array.isArray(e)?e.some(xa):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===am:xa(n))}function IS(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=Jp(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&&!Mi(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}),xS(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"&&xa(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&xa(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function wm(e,t){for(let{message:n,reason:r,path:i}of IS(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Om(e,t){let n=(I,p,g=[])=>t.addIssue({code:"custom",message:I,path:g,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(I=>[I.id,I])),a=(I,p)=>r.some(g=>g.type===I&&("id"in g?g.id:g.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(I=>I.type==="screen");(o.length!==i.size||o.some(I=>!i.has(I.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(I=>c.some(p=>I!==p&&p.startsWith(I+".")))&&n("Variable paths must not overlap","variable");function u(I,p){Object.hasOwn(e.variables,I)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let g=s.get(I)??new Set;g.add(p.id),s.set(I,g)}for(let[I,p]of e.graph.nodes.entries()){let g=["graph","nodes",I],f=p.type==="feature"?p.featureKey:p.type==="offering"&&p.configuration.source==="feature"?p.configuration.featureKey:p.type==="output"&&p.value.type==="feature"?p.value.featureKey:p.type==="end"&&p.output?.type==="feature"?p.output.featureKey:null;f&&!a("flag",f)&&n("Flag selectors require an explicit GB resource reference","feature",g);let S=p.type==="feature"||p.type==="offering"||p.type==="coupon"||p.type==="coupons"||p.type==="action"&&p.action.type==="api"?["value"]:p.type==="action"&&p.action.type==="external_task"?Object.keys(p.action.outputs):p.type==="wait"&&p.wait.type==="event"?Object.keys(p.wait.outputs):[],h="writes"in p?p.writes??{}:{};(S.length!==Object.keys(h).length||S.some(v=>!Object.hasOwn(h,v))||new Set(Object.values(h)).size!==Object.values(h).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[v,E]of Object.entries(h)){u(E,p);let j=e.variables[E],q=p.type==="offering"?"offering_version":p.type==="coupon"?"reward":p.type==="action"&&p.action.type==="api"?"json":p.type==="action"&&p.action.type==="external_task"?p.action.outputs[v]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[v]:void 0;(j?.source.type!=="node"||q&&j.type!==q)&&n("Node writer source or output type does not match declaration","variable",g)}if(p.type==="coupons"){let v=e.variables[p.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let E of p.couponIds)a("reward",E)||n("Coupons require Reward references","coupon",g)}if(p.type==="split"&&!a("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),p.type==="coupon"&&!a("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let v=p.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!a("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),p.type==="screen"&&p.offering?.source==="variable"&&e.variables[p.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="variable"&&(e.variables[p.action.coupon.key]?.type!=="reward"||p.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",g),p.type==="screen"){let v=i.get(p.screenId);if(p.offering?.source==="fixed"&&!a("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),v?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",g),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),v?.type==="owned"){let E=v.document.pages[0];if(!E){n("Owned screen requires a page","screen",g);continue}Gn(v.document).some(q=>!q.complete)&&n("Owned screens require complete local content","translations",g);let j=new Set(v.document.actions.map(q=>q.id));(j.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(q=>!j.has(q)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),$n(E.root,q=>{!p.offering&&(q.type==="plan_picker"||(q.type==="stack"||q.type==="button")&&q.bind?.plan||q.type==="customer_data"&&["customer_plans","credit_packs"].includes(q.data.source))&&n("Product presentation requires an Offering Version","offering",g),q.type==="customer_data"&&Object.values(q.data.outputs??{}).some(de=>de!==void 0&&!j.has(de))&&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"&&!rn(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",g),p.type==="output"&&p.value.type==="literal"&&!rn(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",g);let P=p.type==="output"?p.value:p.type==="end"?p.output:void 0;if(P?.type==="variable"&&!P.path){let v=e.variables[P.key];v&&!Rs(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(p.type==="screen"){let v=i.get(p.screenId);if(v?.type==="owned")for(let E of Ts(v.document))(/^(input|params)\./.test(E)||E.startsWith("variables.")&&!js(E.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(p.type==="condition")for(let v of p.cases){for(let E of En(v.condition))a("saved_group",E)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let E of Un(v.condition))E.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[v,E]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=p.value[v];if(j)if(j.source==="literal"){let q=v==="coupons"?j.value:[j.value];(!Array.isArray(q)||q.length>20||q.some(de=>!rn({type:E,nullable:!1},de)||!a(E,de.id))||v==="coupons"&&new Set(q.map(de=>de.id)).size!==q.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...g,"value",v])}else{let q=e.variables[j.key];(j.path||!q||q.nullable||(v==="coupons"?q.type!=="array"||q.items?.type!=="reward"||q.items.nullable:q.type!==E))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[I,p]of e.graph.nodes.entries()){let g=p.type==="screen"?i.get(p.screenId):void 0,f=[...Im(p,c),...g?.type==="owned"?zo(g.document).map(S=>js(S,c)?.key??S):[]];for(let S of new Set(f)){let E=function(j){if(j===p.id)return!0;if(v.has(j))return!1;v.add(j);let q=e.graph.nodes.find(be=>be.id===j);return q?(P.has(j)?q.type==="action"?[q.cancel,q.unavailable,q.failure]:q.type==="wait"&&q.wait.type==="event"?[q.wait.timeout]:[]:ya(q)).some(E):!1};var w=E;if(!Object.hasOwn(e.variables,S)){n("Consumed variable is undeclared","variable",["graph","nodes",I]);continue}let h=e.variables[S];if(p.type==="screen"&&h.source.type==="input"&&e.inputs.some(j=>j.screenId===p.screenId&&j.variable===S)||h.source.type==="parameter"||h.source.type==="attribute")continue;let P=h.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===S&&j.required).flatMap(j=>o.filter(q=>q.screenId===j.screenId).map(q=>q.id))):s.get(S)??new Set,v=new Set;(!P.size||E(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",I])}}(new Set(e.inputs.map(I=>I.variable)).size!==e.inputs.length||new Set(e.inputs.map(I=>`${I.screenId}:${I.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[I,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",I]);let g=i.get(p.screenId),f=g?.type==="owned"?Mi(g.document,p.componentId):null;if((f?.type!=="stack"||!f.interaction||!["input","toggle","select","multiselect","tabs"].includes(f.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",I]),f?.type==="stack"&&f.interaction){let S=f.interaction.type==="toggle"?"boolean":f.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==S&&n("Input variable type does not match component","inputBinding",["inputs",I]);let h=e.variables[p.variable]?.enum;h&&!f.children.filter(P=>!P.hidden).every(P=>h.includes(P.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",I])}}for(let[I,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",I]),p.source.type==="input"&&!e.inputs.some(g=>g.variable===I)&&n("Input variable requires a component binding","inputBinding",["variables",I]);let d=0,m=0;for(let I of e.screens)if(I.type==="owned"){for(let p of I.document.pages)$n(p.root,()=>{d++});m+=I.document.actions.length}(d>hn.components||m>hn.actions||Yt(e)>hn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var vS=U.strictObject({...xc,graph:hc}).superRefine(Om),ai=U.strictObject({...xc,graph:hc,displayName:U.string().trim().min(1).max(80)}).superRefine(Om),e_=ai.superRefine(wm),t_=vS.superRefine(wm),Sa=U.string().regex(jt),Hi={requestId:U.uuid(),nodeId:sn,visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),customerToken:Sa.optional()},wS=U.discriminatedUnion("type",[U.strictObject({type:U.literal("screen"),output:sn,answers:Hn,selection:U.record(sn,U.union([U.string().max(200),U.boolean(),U.number().int().min(0).max(1e4)])).optional()}),U.strictObject({type:U.literal("paywall_quote"),featureQuantities:U.record(U.uuid(),U.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:sn,productVersionId:U.uuid(),offerId:U.uuid().optional(),nativeOffer:Jr.optional(),predecessor:U.strictObject({operationId:U.uuid().nullable(),generation:U.number().int().positive()}).optional()}),U.strictObject({type:U.literal("paywall_confirm"),operationId:U.uuid()}),U.strictObject({type:U.literal("paywall_cancel"),operationId:U.uuid()}),U.strictObject({type:U.literal("client_action"),receiptId:U.uuid(),outcome:U.enum(["success","cancel","failure","opened","failed"])})]),OS=U.object({nodeId:sn,visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),components:U.record(sn,U.object({resourceKey:U.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:U.number().int().min(1).max(1e5),after:aa.nullable(),filter:U.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Tn=U.discriminatedUnion("operation",[U.strictObject({operation:U.literal("start"),funnelId:U.uuid(),requestId:U.uuid(),customer:fa.optional(),customerData:ga.optional(),locale:U.string().min(1).max(35),parameters:Qn}).refine(ha,Aa),U.strictObject({operation:U.literal("get"),settlementRequestId:U.uuid().optional(),data:OS.optional(),purchase:U.strictObject({receiptId:U.uuid(),operationId:U.uuid()}).optional(),customerToken:Sa.optional()}),U.strictObject({operation:U.literal("resume"),requestId:U.uuid(),customerToken:Sa.optional()}),U.strictObject({operation:U.literal("submit"),...Hi,input:wS}),U.strictObject({operation:U.literal("back"),...Hi}),U.strictObject({operation:U.literal("shown"),...Hi}),U.strictObject({operation:U.literal("close"),...Hi}),U.strictObject({operation:U.literal("commit_segment"),...Hi,policyRevision:U.number().int().nonnegative(),generation:U.string().min(1).max(256)}),U.strictObject({operation:U.literal("review"),receiptId:U.uuid().optional(),customerToken:Sa.optional()})]);function Ia(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 En(p))d(g)}function d(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let g=t.savedGroups[p];g&&(i.add(p),c.set(p,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function m(p){for(let g of["hashAttribute","fallbackAttribute"])if(p[g]!==void 0&&ic(p[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(p.condition);for(let g of p.parentConditions??[])w(g.id),u(g.condition)}function w(p,g=!1){let f=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!f){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),o.set(p,f),a.push(()=>{for(let S of f.rules??[]){m(S);for(let h of S.tracks??[])m(h.experiment)}}))}function I(p){let g=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),s.set(p,g),a.push(()=>m(g)))}for(let p of e.graph.nodes){p.type==="feature"&&w(p.featureKey,!0),p.type==="split"&&I(p.experimentId),p.type==="condition"&&p.cases.forEach(f=>u(f.condition)),p.type==="offering"&&p.configuration.source==="feature"&&w(p.configuration.featureKey,!0);let g=p.type==="output"?p.value:p.type==="end"?p.output:null;g?.type==="feature"&&w(g.featureKey,!0)}for(let p of a)p();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ne}from"zod";function Cm(e,t){let n=[],r={};Dt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Dt(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 Pm(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Dt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(d=>d.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}import{z as Qi}from"zod";var _m=Qi.object({defaultLocale:ln,locales:Qi.record(ln,Qi.object({name:Qi.string().max(80),description:Qi.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 CS=["customer_data","coupon_code"],PS=ne.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Em=ne.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),va=(e,t)=>new Set(e.map(t)).size===e.length,_S=ne.strictObject({currency:fe,amountMinor:ne.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),ES=ne.strictObject({featureId:ne.uuid(),name:ne.string().trim().min(1).max(120),allowance:ne.string().max(40).nullable(),access:ne.boolean()}),RS=ne.strictObject({stripe:ne.strictObject({prices:ne.array(_S).min(1).max(50)}).optional(),apple:ne.strictObject({productIds:ne.array(PS).min(1).max(10)}).optional(),google:ne.strictObject({products:ne.array(ne.strictObject({productId:Em,basePlanId:Em.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!va(e.stripe.prices,n=>n.currency)||e.apple&&!va(e.apple.productIds,n=>n)||e.google&&!va(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),kS=ne.strictObject({name:ne.string().trim().min(1).max(80),interval:ne.enum(["free","week","month","year","one_time"]),intervalCount:ne.number().int().min(1).max(100),trial:ne.strictObject({days:ne.number().int().min(1).max(730),cardRequired:ne.boolean()}).nullable(),benefits:ne.array(ES).max(50).refine(e=>va(e,t=>t.featureId),"Duplicate benefit"),channels:RS,prepaid:ne.array(Ti).max(100).optional()}),jS=ne.strictObject({digest:ti,content:ne.strictObject({discount:Ln,duration:Jt,appliesTo:hs,displayCopy:_m.nullable(),firstPurchaseOnly:ne.boolean(),qualificationRequired:ne.boolean(),startsAt:ne.iso.datetime().nullable(),endsAt:ne.iso.datetime().nullable(),grantWindowHours:ne.number().int().positive(),perCustomerLimit:ne.number().int().positive()})}),TS=ne.discriminatedUnion("type",[ne.strictObject({type:ne.literal("checkout"),product:ta}),ne.strictObject({type:ne.literal("close")}),ne.strictObject({type:ne.literal("action"),action:Hs})]),wa=ne.strictObject({kind:ne.literal("paywall"),formatVersion:ne.literal(1),name:ne.string().trim().min(1).max(80),offeringVersionId:ne.uuid(),presentation:jn,screen:Wt,products:ea,catalog:ne.record(ne.uuid(),kS),buttons:ne.record(ke,TS),coupons:ne.record(ne.uuid(),jS)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;Cm(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Ys(r,CS).forEach(n),Gn(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Dt(r,g=>{let f="bind"in g?g.bind:void 0;f?.promotionCode&&n("Promotion codes must not be published"),f?.plan&&i.add(f.plan),f?.coupon&&a.add(f.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(S=>i.add(S)),g.defaultPlan&&i.add(g.defaultPlan)),g.type==="text"&&g.feature&&o.add(g.feature.id)});let s=e.products.items.map(g=>g.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(g=>!Object.hasOwn(e.catalog,g)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let g of i)u.has(g)||n("Screen references a Product that is not displayed");for(let g of Object.values(e.catalog))!g.channels.stripe&&!g.channels.apple&&!g.channels.google&&n("A displayed Product needs at least one sales channel");let d=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(f=>f.featureId)));for(let g of o)d.has(g)||n("Feature text must read a displayed benefit");let m=r.actions.filter(g=>g.type!=="navigate");r.actions.some(g=>g.type!=="event"&&g.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let I=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;I=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(S=>!u.has(S))&&n("Checkout may only sell displayed Products")}I||n("A Paywall needs a checkout button");let p=Object.keys(e.coupons);(p.length!==a.size||p.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),Rm=ne.strictObject({state:ne.enum(["published","archived"]),controlRevision:ne.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ne.uuid(),versions:ne.record(ne.uuid(),ne.strictObject({version:ne.number().int().positive(),artifact:ne.string().min(1),sourceDigest:ne.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Gt={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Ic=ve.string().regex(/^[a-f0-9]{64}$/),vc=ve.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),wc=Ve.extend({environmentId:ve.uuid()}),km=ve.strictObject({features:ve.array(ve.string()).max(500),experiments:ve.record(ve.uuid(),ve.array(ve.string()).max(20)),savedGroups:ve.array(ve.string()).max(1e3)}),Oc=ve.strictObject({kind:ve.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:ve.number().int().positive(),url:ve.string().min(1).max(2048),sha256:Ic,byteLength:ve.number().int().positive().max(Gt.maxArtifactBytes),generation:Ic.optional()}),NS=ve.strictObject({state:ve.enum(["active","paused","archived"]),controlRevision:vc,evaluationMode:ve.enum(["local","remote"]),evaluationRevision:vc,currentVersionId:ve.uuid(),versions:ve.record(ve.uuid(),ve.strictObject({artifact:ve.string(),dependencies:km,definitionDigest:ti.optional(),couponDigests:ve.record(ve.uuid(),ti).optional()}))}),Cc=ve.strictObject({kind:ve.literal("sdk_configuration"),schemaVersion:ve.literal(1),scope:wc,revision:vc,generation:Ic,policy:ve.strictObject({refreshIntervalSeconds:ve.number().positive().max(15),maxControlAgeSeconds:ve.number().positive().max(60)}),gb:ve.strictObject({features:ve.string().nullable(),pageExperiments:ve.string().nullable()}),artifacts:ve.record(ve.string(),Oc),funnels:ve.record(ve.uuid(),NS),paywalls:ve.record(ve.uuid(),Rm).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 gt(e){if(Array.isArray(e))return`[${e.map(gt).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)}:${gt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Pc(e){return Fr(Mr(typeof e=="string"?new TextEncoder().encode(e):e))}function jm(e){return Pc(gt(e))}function Tm(e,t){for(let o of Object.values(e.references))if(o.type==="flag"&&(!Object.hasOwn(t.features,o.key)||t.remoteFeatures.includes(o.key))||o.type==="experiment"&&!Object.hasOwn(t.experiments,o.id)||o.type==="saved_group"&&!Object.hasOwn(t.savedGroups,o.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=Ia(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let o of e.graph.nodes){let s=o.type==="feature"?o.featureKey:o.type==="end"&&o.output?.type==="feature"?o.output.featureKey:o.type==="output"&&o.value.type==="feature"?o.value.featureKey:void 0;if(!s)continue;let c=n.features[s],u=o.type==="feature"?e.variables[o.writes.value]:e.outputSchema;if(!c||!u)throw new Error("Required public Feature declaration is unavailable");if([c.defaultValue,...(c.rules??[]).flatMap(m=>[...Object.hasOwn(m,"force")?[m.force]:[],...m.variations??[],...(m.tracks??[]).flatMap(w=>w.experiment.variations)])].some(m=>m===void 0||!rn(u,m)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,a=o=>{for(let s of En(o)){if(i.has(s))continue;let c=t.savedGroups[s];if(!c)throw new Error("Required public Saved Group is unavailable");i.add(s),!Array.isArray(c)&&c.type==="condition"&&a(c.condition)}};for(let o of e.graph.nodes)if(o.type==="condition")for(let s of o.cases)a(s.condition);for(let o of Object.values(n.features))for(let s of o.rules??[]){a(s.condition);for(let c of[...s.parentConditions??[],...(s.tracks??[]).flatMap(u=>u.experiment.parentConditions??[])]){if(r.has(c.id)||!t.features[c.id])throw new Error("Local Funnel requires public Local prerequisites");a(c.condition)}for(let c of s.tracks??[])a(c.experiment.condition)}for(let o of Object.values(n.experiments)){a(o.condition);for(let s of o.parentConditions??[]){if(r.has(s.id)||!t.features[s.id])throw new Error("Local Funnel requires public Local prerequisites");a(s.condition)}}for(let o of e.graph.nodes)if(o.type==="split"){let s=n.experiments[o.experimentId];if(!s)throw new Error("Local Funnel requires a public Experiment");for(let c=0;c<s.variations.length;c++){let u=s.meta?.[c]?.key??String(c);if(!o.routes[u])throw new Error("Experiment variation has no declared Funnel route")}}return km.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([o,s])=>[o,s.variations.map((c,u)=>s.meta?.[u]?.key??String(u))])),savedGroups:[...i].sort()})}function Nm(e){return ai.parse(e)}var Dm=ht.strictObject({...Qr,selector:ht.discriminatedUnion("type",[ht.strictObject({type:ht.literal("paywall"),paywallId:ht.uuid()}),ht.strictObject({type:ht.literal("version"),versionId:ht.uuid()})]),customerId:ht.uuid().optional(),commerce:zr,locale:ht.string().min(1).max(35),requirement:zn.optional()}),Ji=ht.strictObject({id:ht.uuid(),paywallId:ht.uuid(),version:ht.number().int().positive(),document:ei.omit({requirement:!0,offeringId:!0}),offering:ht.strictObject({id:ht.uuid()}),content:ht.strictObject({environmentId:ht.uuid(),offeringVersionId:ht.uuid(),artifact:Oc.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:$r,check:gr.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),vr=ht.strictObject(Ji.shape).omit({document:!0,offering:!0}).extend({content:Ji.shape.content.unwrap()});function Fm(e,t){let n=wa.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 Ji.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 Mt}from"zod";var Mm={requestId:Mt.uuid(),sourceId:Mt.uuid(),expectedAvailable:Nt},qm=Mt.discriminatedUnion("action",[Mt.strictObject({...Mm,action:Mt.enum(["add","subtract","set_remaining"]),amount:me}),Mt.strictObject({...Mm,action:Mt.literal("edit"),granted:me,expiresAt:Mt.iso.datetime({offset:!0}).nullable(),nextResetAt:Mt.iso.datetime({offset:!0}).nullable(),expectedRevision:Mt.number().int().nonnegative()})]),_c=Mt.strictObject({sourceId:Mt.uuid(),available:Nt,held:Nt,spent:Nt,adjustmentGrantId:Mt.uuid().nullable()}),Vm=_c.extend({granted:Nt,expiresAt:Mt.iso.datetime({offset:!0}).nullable(),nextResetAt:Mt.iso.datetime({offset:!0}).nullable(),revision:Mt.number().int().nonnegative()});import{z as tn}from"zod";var Um=tn.discriminatedUnion("action",[tn.object({action:tn.literal("upsert"),externalId:tn.string().min(1).max(128),name:tn.string().trim().min(1).max(80)}).strict(),tn.object({action:tn.literal("archive"),entityId:tn.uuid()}).strict()]),Lm=tn.object({id:tn.uuid(),externalId:tn.string().min(1).max(128),name:tn.string().min(1).max(80),archived:tn.boolean()}).strict();import{z as Rt}from"zod";import{z as Or}from"zod";var zm=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Bm=Or.string().regex(/.+\/.+/),Ec=Or.number().min(-100),wr=Or.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),DS=Or.strictObject({input:wr,output:wr,cache_read:wr.optional(),cache_write:wr.optional(),reasoning:wr.optional(),input_audio:wr.optional(),output_audio:wr.optional()}),Rc=(e,t)=>Or.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),Y_=Or.strictObject({defaultMarkup:Ec,providerMarkups:Rc(Or.string().min(1),Ec),modelMarkups:Rc(Bm,Ec),customModels:Rc(Bm,DS.partial())});import{z as pe}from"zod";var Cr=pe.iso.datetime({offset:!0}),Jn=pe.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),FS=pe.discriminatedUnion("kind",[pe.object({kind:pe.literal("absolute"),from:Cr,to:Cr}).strict(),pe.object({kind:pe.literal("last_days"),days:pe.union([pe.literal(1),pe.literal(7),pe.literal(30),pe.literal(90)])}).strict(),pe.object({kind:pe.literal("billing_cycles"),membershipId:pe.uuid(),count:pe.number().int().min(1).max(12),includeCurrent:pe.boolean()}).strict()]),$m=pe.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),MS=pe.object({key:pe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:pe.array(pe.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Pr=pe.object({range:FS,timezone:$m,filterBy:pe.array(MS).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:pe.enum(["hour","day","week","month"]),internal_feature_id:pe.uuid().nullable(),entityId:pe.uuid().nullable(),topN:pe.number().int().min(1).max(50).nullable(),groupBy:pe.union([pe.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),pe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:pe.object({bucket:Cr,group:pe.string().max(240),isOther:pe.boolean(),internal_feature_id:pe.uuid(),resourceId:pe.uuid()}).strict().nullable(),limit:pe.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)"})}),Gm=pe.object({from:Cr,to:Cr,interval:pe.enum(["hour","day","week","month"]),timezone:$m,rows:pe.array(pe.object({bucket:Cr,group:pe.string().max(240),isOther:pe.boolean(),internal_feature_id:pe.uuid(),resourceId:pe.uuid(),consumedUnits:Jn,refundedUnits:Jn,reservedUnits:Jn,charged:Jn,refunded:Jn,reserved:Jn,netUnits:Jn,netCharged:Jn}).strict()).max(100),nextCursor:pe.object({bucket:Cr,group:pe.string().max(240),isOther:pe.boolean(),internal_feature_id:pe.uuid(),resourceId:pe.uuid()}).strict().nullable()}).strict();var si=Rt.string().regex(/^(0|[1-9]\d{0,29})$/),Km=Rt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),kc=Rt.strictObject({bucket:Rt.iso.datetime({offset:!0}),group:Rt.string().max(240),isOther:Rt.boolean(),internal_feature_id:Rt.uuid()}),Hm=Rt.strictObject({...Pr.shape,groupBy:Rt.union([Rt.enum(["customer","entity","entitlement"]),Rt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:kc.nullable()}).superRefine((e,t)=>{let n=Pr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Qm=Rt.strictObject({from:Rt.iso.datetime({offset:!0}),to:Rt.iso.datetime({offset:!0}),interval:Pr.shape.interval,timezone:Pr.shape.timezone,rows:Rt.array(Rt.strictObject({...kc.shape,eventCount:si,units:Km,tokenEventCount:si,tokens:Rt.strictObject(Object.fromEntries(zm.map(e=>[e,si]))),totalTokens:si,providerCostEventCount:si,providerCostUsd:Km,invalidTelemetryEventCount:si})).max(100),nextCursor:kc.nullable()});import{z as lt}from"zod";var Jm=lt.object({requestId:lt.uuid(),items:lt.array(lt.object({customerId:lt.uuid(),command:Pi.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"),Zm=lt.object({batchId:lt.uuid(),after:lt.number().int().min(-1).max(999),limit:lt.number().int().min(1).max(100)}).strict(),Wm=lt.object({batchId:lt.uuid(),status:lt.enum(["queued","complete"]),total:lt.number().int().min(1).max(1e3),processed:lt.number().int().min(0).max(1e3),items:lt.array(lt.object({position:lt.number().int().min(0).max(999),customerId:lt.uuid(),idempotencyKey:lt.string().min(1).max(120),status:lt.enum(["queued","accepted","rejected","failed"]),receipt:_i.nullable(),errorCode:lt.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:lt.number().int().min(0).max(999).nullable()}).strict();import{z as _}from"zod";var qS=_.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Ym=_.enum(["draft","active","paused","archived"]),Xm=_.string().min(1).max(256),ef=_.array(Xm).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),VS=_.strictObject({duration:_.enum(["day","week","month","year"]),length:_.number().int().min(1).max(3660)}),US=_.strictObject({internal_feature_id:_.uuid(),allowance:_.number().nonnegative().max(1e15).nullable(),expiry:VS.nullable()}),LS=_.discriminatedUnion("type",[_.strictObject({type:_.literal("feature_grant"),grants:_.array(US).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),_.strictObject({type:_.literal("free_product"),productId:Xm,duration:Jt}),_.strictObject({type:_.literal("invoice_credits"),amount:_.number().positive().max(1e8),duration:Jt,rollover:_.boolean(),productIds:ef})]),BS=_.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),tf=_.object({key:BS,name:_.string().trim().min(1).max(80),configuration:LS}).strict(),nf=_.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),jc=_.object({code:nf,maxUses:_.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:_.boolean()}).strict(),rf=_.object({key:_.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:_.string().trim().min(1).max(80),rewardId:_.uuid(),redeemOn:_.enum(["customer_creation","checkout"]),receivedBy:_.enum(["referrer","all"]),maxRedemptions:_.number().int().min(1).max(1e6).nullable(),productIds:ef,excludeTrial:_.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),of={id:_.uuid(),projectId:_.uuid(),environmentId:_.uuid(),revision:_.number().int().nonnegative(),status:Ym,createdAt:_.iso.datetime({offset:!0}),updatedAt:_.iso.datetime({offset:!0})},zS=tf.extend(of).strict(),$S=rf.safeExtend(of).strict(),pE=_.strictObject({id:_.uuid(),key:_.string(),name:_.string(),type:qS,status:Ym}),mE=_.discriminatedUnion("action",[_.object({action:_.literal("save"),id:_.uuid().nullable(),revision:_.number().int().nonnegative(),input:tf}).strict(),_.object({action:_.enum(["activate","pause","resume","archive","delete"]),id:_.uuid(),revision:_.number().int().nonnegative()}).strict()]),fE=_.discriminatedUnion("action",[_.object({action:_.literal("save"),id:_.uuid().nullable(),revision:_.number().int().nonnegative(),input:rf}).strict(),_.object({action:_.enum(["activate","pause","resume","archive","delete"]),id:_.uuid(),revision:_.number().int().nonnegative()}).strict()]),af=_.object({id:_.uuid(),rewardId:_.uuid(),programId:_.uuid().nullable(),customerId:_.uuid(),referrerId:_.uuid().nullable(),status:_.enum(["pending","applied","unavailable"]),result:_.record(_.string(),_.unknown()).nullable(),createdAt:_.iso.datetime({offset:!0})}).strict(),sf=_.object({code:nf,requestId:_.uuid()}).strict(),cf=_.strictObject({redemptionId:_.uuid(),currency:fe,requestId:_.uuid(),accepted:_.literal(!0)}),GS=_.strictObject({type:_.literal("checkout"),orderId:_.uuid(),productVersionId:_.uuid(),currency:fe,duration:Jt,renewalAmountMinor:_.number().int().positive().max(1e8),status:_.enum(["created","pending","trialing","paid","cancelled","failed"]),url:_.url().nullable()}),uf=_.discriminatedUnion("type",[GS,_.strictObject({type:_.literal("subscription"),operationId:_.uuid(),membershipId:_.uuid(),productVersionId:_.uuid(),currency:fe,duration:Jt,renewalAmountMinor:_.number().int().positive().max(1e8),status:_.enum(["pending","running","applied","failed"])})]),lf=_.object({programId:_.uuid(),requestId:_.uuid()}).strict(),df=_.object({id:_.uuid(),programId:_.uuid(),code:jc.shape.code,createdAt:_.iso.datetime({offset:!0})}).strict(),gE=_.object({rows:_.array(zS).max(100),nextCursor:_.uuid().nullable()}).strict(),hE=_.object({rows:_.array($S).max(100),nextCursor:_.uuid().nullable()}).strict(),KS=jc.extend({id:_.uuid(),redemptions:_.number().int().nonnegative()}).strict(),HS=_.strictObject({id:_.uuid(),programId:_.uuid().nullable(),customerId:_.uuid().nullable(),referrerId:_.uuid().nullable(),code:_.string().nullable(),status:_.enum(["pending","triggered","applied"]),createdAt:_.iso.datetime({offset:!0})}),AE=_.object({codes:_.array(KS).max(100),redemptions:_.array(HS).max(100),customers:_.record(_.uuid(),_.string()),codesCursor:_.uuid().nullable(),redemptionsCursor:_.uuid().nullable()}).strict(),yE=_.discriminatedUnion("action",[_.object({action:_.literal("create"),rewardId:_.uuid(),revision:_.number().int().nonnegative(),input:jc}).strict(),_.object({action:_.literal("remove"),rewardId:_.uuid(),revision:_.number().int().nonnegative(),codeId:_.uuid()}).strict()]);import{z as x}from"zod";import{z as Q}from"zod";var In={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Zi=e=>new Set(e).size===e.length,Tc=Q.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),QS=Q.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Wi=Q.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"))),JS=Q.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),pf=Q.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var mf=Q.strictObject({id:Q.uuid(),repo:QS,platform:Q.enum(["github","gitlab","bitbucket"]),branches:Q.array(Wi).min(1).max(4).refine(Zi),workflow:Q.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Q.array(Q.uuid()).min(1).max(4).refine(Zi),include:Q.array(pf).min(1).max(16),exclude:Q.array(pf).max(16),methods:Q.array(Q.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Zi),maxAgeHours:Q.number().int().min(1).max(720)}),ff=mf.extend({revision:Q.number().int().positive()}),xE=Q.strictObject({repository:mf,expectedRevision:Q.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),gf=Q.strictObject({repositoryId:Q.uuid(),branch:Wi}),ZS=Q.array(Tc).max(In.keys).refine(Zi),hf=Q.strictObject({repository:ff.omit({keyIds:!0}),branch:Wi,keys:ZS,keySetHash:Q.string().regex(/^[a-f0-9]{64}$/)}),WS=Q.strictObject({filePath:JS,startingLineNumber:Q.number().int().min(1).max(1e7)}),Nc=Q.strictObject({protocol:Q.literal(1),repositoryId:Q.uuid(),branch:Wi,workflow:Q.string().max(200),configurationRevision:Q.number().int().positive(),keySetHash:Q.string().regex(/^[a-f0-9]{64}$/),commit:Q.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Q.uuid(),runNumber:Q.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Q.number().int().min(1).max(1e4),scannerVersion:Q.literal("1"),scannedAt:Q.iso.datetime({offset:!0}),coverage:Q.strictObject({complete:Q.literal(!0),files:Q.number().int().min(0).max(In.files),sourceBytes:Q.number().int().min(0).max(In.sourceBytes),unresolvedCalls:Q.number().int().min(0).max(1e6),unsupportedFiles:Q.number().int().min(0).max(In.files)}),features:Q.array(Q.strictObject({key:Tc,refs:Q.array(WS).max(In.referencesPerKey)})).max(In.keys)}).superRefine((e,t)=>{Zi(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)>In.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Dc=Q.strictObject({scanId:Q.uuid(),commit:Q.string(),receivedAt:Q.string(),references:Q.number().int().nonnegative(),removedReferences:Q.number().int().nonnegative()}),YS=Dc.extend({repositoryId:Q.uuid(),branch:Wi,workflow:Q.string(),digest:Q.string(),configurationRevision:Q.number().int().positive(),runNumber:Q.number().int().positive(),runAttempt:Q.number().int().positive(),scannedAt:Q.string(),keySetHash:Q.string(),coverage:Nc.shape.coverage}),XS=Q.strictObject({repositories:Q.array(ff).max(In.repositories),scans:Q.array(YS).max(In.repositories*In.branches)}),ex=Q.strictObject({key:Tc,references:Q.number().int().nonnegative(),coveredTargets:Q.number().int().nonnegative(),expiredTargets:Q.number().int().nonnegative(),uncertainTargets:Q.number().int().nonnegative()}),IE=Q.strictObject({available:Q.boolean().default(!0),settings:XS,expectedTargets:Q.number().int().min(0).max(80),features:Q.array(ex).max(2001),truncated:Q.boolean()});import{z as qt}from"zod";var yf={customerId:qt.uuid(),eventId:qt.string().trim().min(1).max(200),grantId:qt.uuid(),occurredAt:qt.iso.datetime({offset:!0})},bf=qt.strictObject({...yf,productVersionId:qt.uuid(),subscriptionId:qt.string().trim().min(1).max(255)}),Sf=qt.strictObject({...yf,merchandiseId:qt.uuid()}),xf=qt.union([bf,Sf]),Af={id:qt.uuid(),couponId:qt.uuid(),status:qt.literal("redeemed"),source:qt.literal("merchant"),recordedAt:qt.iso.datetime({offset:!0})},If=qt.union([bf.extend(Af),Sf.extend(Af)]);import{z as te}from"zod";var Fc=te.strictObject({name:te.string().trim().min(1).max(255),memo:te.string().max(1e4).nullable().optional(),footer:te.string().max(1e4).nullable().optional(),net_terms_days:te.number().int().positive().nullable().optional()}),tx=Fc.extend({id:te.string().min(1).max(255),created_at:te.number().nullable()}),vf=te.strictObject({items:te.array(tx).max(50),nextCursor:te.uuid().nullable()}),_E=te.discriminatedUnion("action",[te.strictObject({action:te.literal("create"),requestId:te.uuid(),values:Fc}),te.strictObject({action:te.literal("update"),id:te.string().min(1).max(255),values:Fc}),te.strictObject({action:te.literal("delete"),id:te.string().min(1).max(255)})]),wf=te.discriminatedUnion("action",[te.strictObject({action:te.literal("create"),requestId:te.uuid(),params:Zr}),te.strictObject({action:te.enum(["finalize","send","pay","void"]),requestId:te.uuid(),invoiceId:te.uuid()}),te.strictObject({action:te.literal("reissue"),requestId:te.uuid(),invoiceId:te.uuid(),params:Fs})]),Mc=te.strictObject({id:te.uuid(),customerId:te.uuid(),providerInvoiceId:te.string().nullable(),status:te.enum(["draft","open","paid","void","uncollectible"]),currency:te.string(),totalMinor:te.string().regex(/^-?\d+$/),paidMinor:te.string().regex(/^\d+$/),refundedMinor:te.string().regex(/^\d+$/),hostedInvoiceUrl:te.url().nullable(),createdAt:te.number(),collectionMethod:te.enum(["send_invoice","charge_automatically"]).nullable()}),Of=Mc.extend({lines:te.array(te.strictObject({id:te.uuid(),description:te.string(),amountMinor:te.string().regex(/^-?\d+$/),netAmountMinor:te.string().regex(/^-?\d+$/),quantity:te.number().nullable(),periodStart:te.number().nullable(),periodEnd:te.number().nullable()})).max(1e3)}),Yi=te.strictObject({taskId:te.uuid(),status:te.enum(["ready","running","done","dead"]),invoice:Mc.nullable(),errorCode:te.string().nullable()}),Cf=te.strictObject({items:te.array(Mc).max(50),nextCursor:te.uuid().nullable(),operations:te.array(Yi).max(50),operationsLimited:te.boolean()});var nx=x.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"]),Pf={scope:Ve,permissions:x.array(nx),expiresAt:x.iso.datetime().nullable()},bR=x.discriminatedUnion("kind",[x.object({...Pf,kind:x.literal("server"),keyId:x.string().min(1)}),x.object({...Pf,kind:x.literal("customer"),customerId:x.string().min(1),identityKind:x.enum(["identified","guest"]),expiresAt:x.iso.datetime()})]),L=x.object({requestId:x.uuid(),scope:Ve}).strict(),rx=pm.safeExtend({fingerprint:ma.optional()}).strict(),ix=L.extend({customer:ii,created:x.boolean()});function _f(){return L.extend({offer:Si.nullable(),reason:Tl.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Id,response:L.extend({message:x.object({messageId:x.uuid(),channel:ji,acceptedAt:x.iso.datetime({offset:!0}),status:x.enum(["accepted","sending","completed","canceled"]),replayed:x.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:x.strictObject({messageId:x.uuid()}),response:L.extend({message:x.object({id:x.uuid(),channel:ji,status:x.enum(["accepted","sending","completed","canceled"]),deliveries:x.array(x.object({id:x.uuid(),status:wd,attempts:x.number().int().nonnegative(),receipts:x.array(x.object({kind:Od,occurredAt:x.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:xu,response:L.extend({installation:sr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Iu,response:L.extend({installation:sr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:lo,response:L.extend({installation:sr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:x.strictObject({channel:ji}),response:L.extend({preference:Ga})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:vd,response:L.extend({preference:Ga})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:x.strictObject({cursor:x.uuid().optional()}),response:L.extend({templates:vf})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:x.strictObject({customerId:x.uuid(),params:Zr}),response:L.extend({preview:Ms})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:x.strictObject({customerId:x.uuid(),requestId:x.uuid(),params:Zr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:L.extend({operation:Yi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:x.strictObject({customerId:x.uuid(),command:wf}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:L.extend({operation:Yi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:x.strictObject({customerId:x.uuid(),taskId:x.uuid()}),response:L.extend({operation:Yi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:x.strictObject({customerId:x.uuid(),cursor:x.uuid().optional()}),response:L.extend({invoices:Cf})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:x.strictObject({customerId:x.uuid(),invoiceId:x.uuid()}),response:L.extend({invoice:Of})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:gf,response:L.extend({config:hf})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Nc,response:L.extend({receipt:Dc})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:x.strictObject({}),response:L.extend({payload:zi})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Gp,response:L.merge(ra)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Kp,response:L.merge(Hp)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:x.strictObject({customerId:x.uuid(),sourceId:x.uuid()}),response:L.extend({balance:Vm})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:x.strictObject({customerId:x.uuid(),command:qm}),response:L.extend({balance:_c})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:x.strictObject({internal_feature_id:x.uuid(),customerId:x.uuid().optional(),entityId:x.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:L.extend({internal_feature_id:x.uuid(),config:Wa,model_markups:ho})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:x.strictObject({customerId:x.uuid(),query:Do}),response:L.extend({usage:Ei})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:x.strictObject({customerId:x.uuid(),command:md}),response:L.extend({usage:Ei})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:x.strictObject({customerId:x.uuid(),command:sd}),response:L.extend({grant:Ss})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:cd,response:L.extend({grants:ud})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:x.union(Tp.options.map(e=>e.extend({customerId:x.uuid().optional(),customerToken:x.string().regex(jt).optional()}))),response:L.extend({operation:Np})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Ip.extend({customerId:x.uuid().optional()}),response:L.extend({setup:Bs})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:vp.extend({customerId:x.uuid().optional()}),response:L.extend({setup:Bs})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:bp.safeExtend({customerId:x.uuid()}),response:L.extend({batch:Ui})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Qo.extend({customerId:x.uuid()}),response:L.extend({batch:Ui})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Qo.extend({customerId:x.uuid()}),response:L.extend({batch:Ui})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Qo.extend({customerId:x.uuid()}),response:L.extend({batch:Ui})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:x.discriminatedUnion("action",[Jo.options[0].extend({customerId:x.uuid()}),Jo.options[1].extend({customerId:x.uuid()}),Jo.options[2].extend({customerId:x.uuid()})]),response:L.extend({trial:Ls})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Sp.extend({customerId:x.uuid()}),response:L.extend({trial:Ls})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Yo,response:L.extend({subscriptions:Rp})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Yo,response:L.extend({purchases:kp})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Pp,response:L.extend({conflicts:jp})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:_p,response:L.extend({resolution:Ep})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Op,response:L.extend({verification:Cp})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:lp.safeExtend({...Qr,customerId:x.uuid().optional()}),response:L.extend({quote:qi})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:ju,response:L.extend({record:Tu})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Sr.extend({customerId:x.uuid().optional(),intent:x.enum(["confirm","cancel"]).optional()}),response:L.extend({operation:Wr})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Sr.extend({customerId:x.uuid().optional()}),response:L.extend({operation:Wr})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:mp.safeExtend({customerId:x.uuid().optional()}),response:L.extend({quote:gp})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Sr.extend({customerId:x.uuid().optional(),intent:x.enum(["confirm","cancel"]).optional()}),response:L.extend({operation:Vs})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Sr.extend({customerId:x.uuid().optional()}),response:L.extend({operation:Vs})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:hp.safeExtend({customerId:x.uuid()}),response:L.extend({quote:yp})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Sr.extend({customerId:x.uuid()}),response:L.extend({operation:Ho})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Sr.extend({customerId:x.uuid()}),response:L.extend({operation:Ho})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Hl,response:L.extend({controls:ys})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Ul,response:L.extend({prepared:Bl})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:zl,response:L.extend({authorization:ko})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Wl,response:L.extend({coupons:Yl})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:$l,response:L.extend({authorization:ko})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Jl,response:L.extend({invoices:Zl})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Ql,response:L.extend({invoice:vi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:x.object({customerId:x.uuid(),command:Kl}).strict(),response:L.extend({controls:ys})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:x.object({customerId:x.uuid(),command:Um}).strict(),response:L.extend({entity:Lm})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:x.strictObject({customerId:x.uuid().nullable(),query:Hm}),response:L.extend({analytics:Qm})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:x.object({customerId:x.uuid().nullable(),query:Pr}).strict(),response:L.extend({analytics:Gm})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Jm,response:L.extend({batchId:x.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Zm,response:L.extend({batch:Wm})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:_d.extend({customerId:x.string().min(1).optional()}),response:L.extend({check:gr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:x.strictObject({kind:Kn,selector:x.discriminatedUnion("type",[x.strictObject({type:x.literal("resource"),id:x.uuid()}),x.strictObject({type:x.literal("version"),id:x.uuid()})]),customerId:x.string().min(1).optional()}),response:L.extend({content:Ns})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Dm,response:L.extend({paywall:vr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:x.strictObject({...Qr,selector:qp,customerId:x.string().min(1).optional(),commerce:zr,requirement:zn.optional()}),response:L.extend({offering:Vp,candidates:x.array(Os).max(20),availability:x.array(x.strictObject({productVersionId:x.uuid(),available:x.boolean(),reason:x.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:gr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:x.object({customerId:x.uuid().optional(),entityId:x.uuid().optional()}).strict(),response:L.extend({holdings:fd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:x.object({customerId:x.uuid().optional(),query:hd}).strict(),response:L.extend({ledger:Ad})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:ld.extend({customerId:x.uuid().optional()}),response:L.extend({detail:dd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:xs.safeExtend({customerId:x.uuid().optional()}),response:L.extend({statement:pd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:x.object({customerId:x.uuid().optional(),command:Pi.options[0]}).strict(),response:L.extend({quote:id})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:x.strictObject({customerId:x.uuid(),command:x.union([x.strictObject({eventName:x.string().min(1),quantity:me.optional(),properties:pt.optional(),entityId:x.uuid().optional(),idempotencyKey:x.string().min(1).max(120)}),x.strictObject({internal_feature_id:x.uuid(),quantity:me.optional(),properties:pt.optional(),entityId:x.uuid().optional(),idempotencyKey:x.string().min(1).max(120)})])}),response:L.extend({receipts:x.array(_i).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:x.object({customerId:x.uuid(),command:Pi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:L.extend({receipt:_i})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:sf,response:L.extend({redemption:af})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:lf,response:L.extend({referralCode:df})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:cf,response:L.extend({checkout:uf})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:bd,response:L.extend({seats:ws})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Sd,response:L.extend({seats:ws})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:rx,response:ix},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:pc,response:L.extend({customer:ii})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:gm,response:L.extend(hm.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:fm,response:L.extend(mm.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:x.object({customerId:x.uuid()}).strict(),response:L.extend(kr.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:x.strictObject({}),response:L.extend(kr.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:x.strictObject({customerId:x.uuid(),sessionId:x.uuid().optional()}),response:L.extend({revoked:x.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:x.strictObject({guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ma.optional()}),response:L.extend({customerId:x.uuid(),guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:x.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:x.strictObject({guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:L.extend(kr.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:x.strictObject({guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:x.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:x.uuid()}),response:L.extend({customer:ii,switched:x.boolean(),replayed:x.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:x.strictObject({code:x.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:x.uuid()}),response:_f()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:x.object({}).strict(),response:L.extend({offers:x.array(Si)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:x.object({customerId:x.string().min(1).max(255).optional(),couponId:x.uuid(),...Qr,requestId:x.uuid(),couponContentDigest:x.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:_f()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:xf,response:L.extend({receipt:If})}},SR={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,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 qc}from"zod";var Xi=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Vc(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(d=>zt(t.attributes??{},d.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new Xi("Required GB Feature is unavailable");i=_n(e.featureKey,t),o=i.value,Object.assign(r,Hr(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new Xi("Required GB Experiment is unavailable");if(a=Eo(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 Xi("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:_n(e.configuration.featureKey,t).value;o={type:"offering_version",id:qc.uuid().parse(u)},Object.assign(r,Hr(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,Hr(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 Ef(e,t,n){qc.uuid().parse(e),qc.number().int().nonnegative().parse(t);let r=Fr(Mr(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 $}from"zod";var Zn=$.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ox=$.enum(["running","waiting","completed","closed","ineligible","failed"]),ax=$.discriminatedUnion("type",[lc,$.strictObject({type:$.literal("wait"),receiptId:$.uuid(),kind:$.enum(["timer","event","operation"]),deadline:$.iso.datetime({offset:!0}).nullable(),eventName:Zn.optional()}),$.strictObject({type:$.literal("open_url"),receiptId:$.uuid(),url:mc,openIn:fc}),$.strictObject({type:$.literal("event"),receiptId:$.uuid(),event:Zn})]),Oa=$.strictObject({type:$.literal("funnel"),id:$.uuid(),versionId:$.uuid()}),sx={id:Zn,presentation:jn,outputs:$.array(Zn).max(250),inputs:sa,values:$.record($.string(),ge).optional(),offeringKey:dt.optional(),capabilities:$r,customerData:Dd,dataCursors:$.record(Zn,aa.nullable())},cx=$.strictObject({...sx,content:$.strictObject({type:$.literal("document"),document:Wt})}),Uc=$.strictObject({id:$.uuid(),source:Oa,revision:$.number().int().nonnegative(),visit:$.number().int().nonnegative(),nodeId:Zn,nodeType:$.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:ox,stopped:$.boolean(),canBack:$.boolean(),authenticated:$.boolean(),locale:$.string().min(1).max(35),answers:Hn,parameters:Qn,variables:$.record($.string(),ge),output:ge.nullable(),screen:cx.nullable(),paywall:$.strictObject({receiptId:$.uuid(),resolution:$.union([Ji,vr]),quote:qi.nullable(),operation:Wr.nullable(),purchaseRequestId:$.uuid().nullable(),selectionGeneration:$.number().int().nonnegative().optional(),canReselect:$.boolean().optional()}).nullable(),instruction:ax.nullable(),pendingRequest:$.strictObject({requestId:$.uuid(),authenticationRequired:$.boolean()}).nullable(),runExpiresAt:$.iso.datetime({offset:!0}),credentialExpiresAt:$.iso.datetime({offset:!0}).nullable()}),eo=$.strictObject({scope:Ve,run:Uc,settlement:$.strictObject({requestId:$.uuid(),state:$.enum(["pending","unknown","settled"]),operationId:$.uuid().nullable(),receiptId:$.uuid().nullable().optional()}).optional(),purchase:$.strictObject({receiptId:$.uuid(),quote:qi.nullable(),operation:Wr.nullable(),canReselect:$.boolean().optional()}).optional(),review:$.strictObject({activeOperationId:$.uuid().nullable(),pages:$.array($.strictObject({receiptId:$.uuid(),nodeId:Zn,visit:$.number().int().nonnegative()})).max(100),page:$.strictObject({receiptId:$.uuid(),nodeId:Zn,visit:$.number().int().nonnegative(),document:Wt,answers:Hn,inputs:sa,values:$.record($.string(),ge).optional()}).nullable(),coupons:$.array($.strictObject({grantId:$.uuid(),status:$.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:$.string().nullable()})).max(100),purchases:$.array($.strictObject({receiptId:$.uuid(),operationId:$.uuid(),status:$.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:$.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:$.uuid().optional()}),Rf=eo.extend({run:Uc.extend({paywall:Uc.shape.paywall.unwrap().extend({resolution:vr}).nullable()})});var kf="X-Indiana-Server-Key";import{z as Ee}from"zod";var ci=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Tf=Ee.strictObject({entry:ci,nodes:Ee.array(Ee.strictObject({id:ci,type:Ee.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Ee.record(Ee.string(),ci),writes:Ee.record(dt,dt),resources:Ee.strictObject({screenId:ci.optional(),paywallVersionId:Ee.uuid().optional(),couponId:Ee.uuid().optional(),couponIds:Ee.array(Ee.uuid()).max(20).optional(),experimentId:Ee.uuid().optional(),featureKey:Ee.string().optional(),offeringVersionId:Ee.uuid().optional()})})).min(1).max(500)}),jf={scope:Ve,funnelId:Ee.uuid(),versionId:Ee.uuid(),evaluationRevision:Ee.number().int().nonnegative(),expiresAt:Ee.iso.datetime({offset:!0}).nullable(),topology:Tf},Ca=Ee.discriminatedUnion("evaluationMode",[Ee.strictObject({...jf,evaluationMode:Ee.literal("local"),growth:on,conditions:Ee.record(ci,Ee.array(Ee.strictObject({condition:Bt,port:Ee.string()})))}),Ee.strictObject({...jf,evaluationMode:Ee.literal("remote")})]),ux=Ca.options[0].extend({evaluation:Ee.strictObject({maxTransitions:Ee.number().int().min(1).max(1e4),variables:Ee.record(dt,Kr),outputSchema:Gr,terminals:Ee.record(ci,Ee.strictObject({outcome:Ee.enum(["completed","closed","ineligible","failed"]),output:Gi.nullable()}))})});function lx(e){return Tf.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=Ee.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 Lc(e){let t=ai.parse(e.document),n=e.evaluationMode==="local"?on.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:lx(t)};return Ca.parse(e.evaluationMode==="remote"?r:{...r,growth:Ia(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 Nf(e){let t=Lc(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=ai.parse(e.document);return ux.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 We}from"zod";var Df=We.string().regex(/^[a-f0-9]{64}$/),dx=ni.omit({variations:!0,active:!0}).extend({changeId:Df,variations:We.array(We.strictObject({urlRedirect:We.string().max(2048)})).min(2).max(20)}),Ff=We.strictObject({environmentId:We.uuid(),trackExposures:We.boolean(),generation:Df,experiments:We.array(dx).max(100),savedGroups:Bi}),px=We.strictObject({eventUuid:We.uuid(),timestamp:We.iso.datetime({offset:!0}).optional(),deviceId:We.string().min(1).max(128),sessionId:We.string().min(1).max(128).optional(),url:We.url().max(2048),pageTitle:We.string().max(512).optional(),experimentKey:We.string().min(1).max(255),variationKey:We.string().min(1).max(64)}),tk=We.strictObject({events:We.array(px).min(1).max(20)}),nk=We.strictObject({inserted:We.number().int().nonnegative(),duplicates:We.number().int().nonnegative(),skipped:We.number().int().nonnegative(),rejected:We.array(We.strictObject({index:We.number().int().nonnegative(),reason:We.string()}))});import{z as At}from"zod";var mx=At.strictObject({selector:At.string().min(1).max(2048),action:At.enum(["set","append","remove"]),attribute:At.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:At.string().max(5e4).optional(),parentSelector:At.string().max(2048).optional(),insertBeforeSelector:At.string().max(2048).optional()}),fx=At.strictObject({variation:At.string().min(1).max(128),description:At.string().max(2e3).default(""),css:At.string().max(1e5).default(""),js:At.string().max(1e5).default(""),domMutations:At.array(mx).max(200).default([]),iam:Xp.optional(),renderGuard:ia.optional()}),Bc=fx.omit({variation:!0,description:!0,iam:!0}),gx=ni.omit({variations:!0,active:!0}).extend({changeId:At.string().regex(/^[a-f0-9]{64}$/),variations:At.tuple([Bc,Bc]).rest(Bc).refine(e=>e.length<=20)}),Mf=At.strictObject({trackExposures:At.boolean(),environmentId:At.uuid(),generation:At.string().regex(/^[a-f0-9]{64}$/),experiments:At.array(gx).max(100),savedGroups:Bi});import{z as nt}from"zod";var $c=32,hx=522240;function Gc(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 Ax=nt.strictObject({nodeId:nt.string().min(1).max(64),visit:nt.number().int().nonnegative(),revision:nt.number().int().nonnegative()}),zc=nt.record(nt.string(),ge),yx=nt.strictObject({id:nt.uuid(),nodeId:nt.string().min(1).max(64),visit:nt.number().int().nonnegative(),input:nt.strictObject({schemaVersion:Ki.shape.schemaVersion,kind:Ki.shape.kind,selector:Ki.shape.selector,contract:Ki.shape.contract}),context:zc,removed:nt.array(nt.string()).max(100),attributes:zc,removedAttributes:nt.array(nt.string()).max(100),result:vm,offeringVersionId:nt.uuid().nullable(),events:nt.strictObject({entered:nt.string().regex(/^[1-9][0-9]{0,18}$/),decision:nt.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),mk=nt.strictObject({schemaVersion:nt.literal(1),mode:nt.enum(["local","remote"]),versionId:nt.uuid(),generation:nt.number().int().positive(),base:Ax,context:zc,steps:nt.array(yx).min(1).max($c)}).refine(e=>Yt(e)<=hx,"Segment exceeds its byte budget");var Kc=class extends Error{constructor(n,r){super(r);qe(this,"code",n);this.name="FunnelLocalCalculationError"}},qf=(e,t)=>new Kc(e,t),bx=e=>({experiments:e.experiments,features:e.features});function Sx(e,t=qf){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=qr(e.growth.savedGroups),i=bx(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return _n(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,d;if(c.type==="condition"){let w=e.conditions[c.id];if(!w)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=Vc({id:c.id,name:c.id,type:"condition",cases:w.map(I=>({condition:I.condition,target:c.outputs[I.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");d=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let I=Vc({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);d=I.value,u=I.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)d=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...d===void 0?{}:{value:d}}}}}function xx(e,t){let n=Ca.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=Sx(n,t);return(o,s)=>(i(),Ix(a,o,s))}function Ix(e,t,n){let r=mt.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 vx(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,d={expected:n.sticky[u]??null,next:s};c<0?r.push(d):r[c]=d},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ge.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ge.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 Vf(e,t,n,r=qf){let i=n,a=new Map(t.graph.nodes.map(g=>[g.id,g])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,d=n.visit,m=!1,w,I=g=>(w??(w=xx(e,r)),vx(w,g,{attributes:oc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let g=0;g<$c;g++){let f=a.get(u);if(!f||!Gc(f))break;if(d>=t.execution.maxTransitions&&(d>t.execution.maxTransitions||f.type!=="end"&&f.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let S,h;if(["condition","feature","split"].includes(f.type)||f.type==="offering"&&f.configuration.source==="feature")S=I(f.id),f.type==="offering"&&(S.value={type:"offering_version",id:String(S.value)}),f.type==="condition"?h=S.port==="default"?f.default:f.cases[Number(S.port.slice(5))]?.target:f.type==="split"?h=S.port==="notParticipating"?f.notParticipating:f.routes[S.port]:(f.type==="feature"||f.type==="offering")&&(h=f.next);else if(S={port:"next",sticky:[],exposures:[],features:[]},(f.type==="entry"||f.type==="coupon"||f.type==="coupons")&&(h=f.next),f.type==="offering"&&f.configuration.source==="fixed"&&(S.value={type:"offering_version",id:f.configuration.versionId},h=f.next),f.type==="end"||f.type==="output"){let v=f.type==="end"?f.output:f.value;if(S=v?.type==="feature"?I(f.id):{...S,port:"value",value:v?.type==="literal"?v.value:v?.type==="variable"?ks({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},v&&(S.value===void 0||!rn(t.outputSchema,S.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let P=[...c,{nodeId:u,result:S}];if(Yt({steps:P})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:S}),f.type==="feature"||f.type==="offering"||f.type==="coupon"||f.type==="coupons"){let v=f.type==="coupons"?f.couponIds.map(j=>({type:"reward",id:j})):f.type==="coupon"?{type:"reward",id:f.couponId}:S.value;if(v===void 0)throw r("INVALID_RESPONSE","Node output is missing");let E=Hr(f,{value:v});Ld(t.variables,f,E),Object.assign(o,E)}for(let v of S.sticky)s[`${v.next.attributeName}||${v.next.attributeValue}`]=structuredClone(v.next);if(f.type==="end"||f.type==="output"){m=!0;break}if(!h)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=h,d++}let p=a.get(u);return{steps:c,...!m&&p&&!Gc(p)?{boundary:{nodeId:u,visit:d}}:{}}}import{z as Ae}from"zod";var Pa=Ae.string().regex(/^[a-f0-9]{64}$/),wx=Ae.strictObject({release:Pa,render:ia,button:Ae.strictObject({selector:Ae.string().min(1).max(512),elementKey:Ae.string().min(1).max(256),tag:Ae.enum(["button","a","input"])}).nullable()}),kk=Ae.strictObject({scope:Ve.extend({environmentId:Ae.uuid()}),release:Pa,validatedAt:Ae.iso.datetime({offset:!0}),validUntil:Ae.iso.datetime({offset:!0}),entries:Ae.array(Ae.strictObject({id:Ae.uuid(),funnelId:Ae.uuid(),versionId:Ae.uuid(),event:Ae.enum(["screen_enter","button_click"]),target:wx})).max(4e3)}),jk=Ae.strictObject({operation:Ae.literal("entry_start"),funnelId:Ae.uuid(),versionId:Ae.uuid(),entryId:Ae.uuid(),release:Pa,requestId:Ae.uuid(),locale:Ae.string().min(1).max(35).default("en")}),Tk=Ae.strictObject({scope:Ve,suppressed:Ae.literal(!0),reason:Ae.enum(["frequency","in_progress"]),retryAt:Ae.iso.datetime({offset:!0}).nullable()}),Nk=Ae.strictObject({experimentId:Ae.uuid(),splitNodeId:Ae.string().min(1).max(128)}),Ox=Ae.strictObject({experimentId:Ae.uuid(),experimentKey:Ae.string().min(1).max(128),variationKey:Ae.string().min(1).max(128),inExperiment:Ae.boolean(),generation:Ae.string().min(1).max(256)}),Uf=Ae.strictObject({operation:Ae.literal("page_experiments"),release:Pa,usedReceiptIds:Ae.array(Ae.uuid()).max(20).default([]),customerToken:Ae.string().regex(jt).optional()}),Lf=Ae.strictObject({scope:Ve,runId:Ae.uuid(),assignments:Ae.array(Ox.extend({receiptId:Ae.uuid()})).max(20),payload:Mf});var y=class extends Error{constructor(n,r,i,a,o){super(r);qe(this,"code",n);qe(this,"status",i);qe(this,"requestId",a);qe(this,"retryable");qe(this,"recovery");qe(this,"retryAfterSeconds");qe(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=po(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 to=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new y("INVALID_STATE","Installation sequence exhausted");return e+1},Cx=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 Nn(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new y("INVALID_STATE","Installation journal is invalid");return t({...n})})}function Bf(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve();if(e&&(!n||Ve.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new y("SCOPE_MISMATCH","Push installation belongs to another scope");let c=()=>{if(!e)throw new y("NOT_CONFIGURED","Configure this client's native Push host first");return e},u=h=>{if(h!==i)throw new y("IDENTITY_CHANGED","Identity changed during Push operation")};async function d(h){let P=c();if(!P.sha256&&!globalThis.crypto?.subtle)throw new y("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let v=P.sha256?await P.sha256(Uint8Array.from(h,E=>E.charCodeAt(0))):await Cx(h);if(!/^[a-f0-9]{64}$/.test(v))throw new y("INVALID_STATE","Push credential digest is invalid");return v}function m(h){let P=sr.parse(h);if(P.installationId.toLowerCase()!==c().installationId.toLowerCase())throw new y("INVALID_RESPONSE","Push response belongs to another installation");return P}async function w(h,P){let v=c(),E={installationId:v.installationId,publicKey:v.publicKey,issuedAt:new Date().toISOString(),...P},j=await v.sign(Cu(h,v.scope,E));return{...E,signature:j}}let I=(h,P,v)=>t.requestWithCredential?t.requestWithCredential(h,P,v):t.request(h,P);async function p(){let h=c(),P=i,v=r?await(t.session?.access()??r):null,E=Nn(h,Se=>Se),j;if(E.detachSeq!==null){let Se=E.detachSeq,Te=vu.parse(await w("detach",{sequence:Se,platform:h.platform}));try{let Pe=await t.request("push/installations/detach",{...h.scope,...Te},"POST",{installationDetach:!0});if(!Pe||typeof Pe!="object"||!("installation"in Pe))throw new y("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Vt=m(Pe.installation);if(Vt.bound||Vt.identitySeq!==Se)throw new y("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Pe){if(Pe instanceof y&&Pe.status===404)j=Pe;else if(!(Pe instanceof y)||Pe.status!==412)throw Pe}j||Nn(h,Pe=>({...Pe,detachSeq:Pe.detachSeq===Se?null:Pe.detachSeq}))}if(u(P),!v){if(j)throw j;return null}let q=O.bindPushInstallation,de=q.request.parse(await w("bind",{sequence:o,platform:h.platform,credentialDigest:await d(v)}));u(P);let be=q.response.parse(await I(q.path,de,v));u(P);let Oe=m(be.installation);if(!Oe.bound||Oe.identitySeq!==o)throw new y("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return j&&E.detachSeq!==null&&o>E.detachSeq&&Nn(h,Se=>({...Se,detachSeq:Se.detachSeq===E.detachSeq?null:Se.detachSeq})),Oe}async function g(){c();let h=i,P=r?await(t.session?.access()??r):null;if(!P)throw new y("NOT_IDENTIFIED","Identify before reading this installation");let v=O.readPushInstallation,E=v.request.parse(await w("read",{credentialDigest:await d(P)}));u(h);let j=v.response.parse(await I(v.path,E,P));return u(h),m(j.installation)}function f(h=p){let P=s.catch(()=>{}).then(h);return s=P,P.catch(v=>{try{e?.onError?.(v instanceof Error?v:new Error("Push synchronization failed"))}catch{}}),P}async function S(h,P,v){let E=c(),j=P.identity,q=P.observation,de=r?await(t.session?.access()??r):null;if(u(j),q!==a)throw new y("INVALID_STATE","Push observation changed during recovery");if(!de)throw new y("NOT_IDENTIFIED","Identify before recovering a Push address");if(!h.connectionId||!h.kind||!h.token||!["granted","provisional"].includes(h.permission))throw new y("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await f(async()=>{if(u(j),await p(),u(j),q!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let be=Nn(E,Vt=>v?Vt:{...Vt,addressSeq:to(Vt.addressSeq)}),Se=await w(v?"recovery_confirm":"recovery_request",{...h,sequence:be.addressSeq,credentialDigest:await d(de),...v?{challenge:v}:{}}),Te=v?Ou.parse(Se):wu.parse(Se);if(u(j),q!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let Pe=await I(`push/installations/recovery/${v?"confirm":"request"}`,Te,de);if(u(j),q!==a||Nn(E,Vt=>Vt).addressSeq!==be.addressSeq)throw new y("INVALID_STATE","Push observation changed during recovery");if(v){let Vt=O.updatePushAddress.response.parse(Pe),Je=m(Vt.installation);if(!Je.bound||Je.identitySeq!==o||Je.addressSeq!==be.addressSeq||Je.connectionId!==h.connectionId||Je.addressStatus!=="active")throw new y("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return Je}if(!Pe||typeof Pe!="object"||!("recovery"in Pe))throw new y("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return $a.parse(Pe.recovery)})}return{recoveryObserver(){c();let h={identity:i,observation:++a};return{async request(P){return $a.parse(await S(P,h))},async confirm(P,v){return sr.parse(await S(v,h,P))}}},identify(h){if(!e)return;o=Nn(e,v=>({...v,identitySeq:to(v.identitySeq)})).identitySeq,r=h,i++,a++},reset(){if(e)try{Nn(e,h=>{let P=to(h.identitySeq);return{...h,identitySeq:P,detachSeq:P}})}finally{r=null,i++,a++}},start(){e&&f()},async sync(){return await f()},read:g,async recover(){let h=c(),P=i,v=o;return a++,await f(async()=>{u(P);let E=await g();return u(P),o=Nn(h,q=>{if(q.identitySeq!==v)throw new y("IDENTITY_CHANGED","A newer installation intent exists");return{...q,identitySeq:to(Math.max(q.identitySeq,E.identitySeq)),addressSeq:Math.max(q.addressSeq,E.addressSeq)}}).identitySeq,await p()})},tokenObserver(){c();let h=++a,P=i;return async v=>{if(h!==a||P!==i)return null;let E=c(),j=r?await(t.session?.access()??r):null;if(!j)throw new y("NOT_IDENTIFIED","Identify before registering a Push token");if(await f(),u(P),h!==a)return null;let q=Nn(E,Se=>({...Se,addressSeq:to(Se.addressSeq)})),de=O.updatePushAddress,be=de.request.parse(await w("address",{...v,sequence:q.addressSeq,credentialDigest:await d(j)}));if(u(P),h!==a)return null;let Oe=de.response.parse(await I(de.path,be,j));return u(P),m(Oe.installation)}}}}function zf(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 $f={name:"@tinkerlandai/indiana-sdk",version:"0.9.5",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function ze(e){return typeof e=="string"?e:String(e)}var _x=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Ex(e){return e.replace(_x,"$1\uFFFD")}function Zc(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 Xf(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 Gf(e){let t;if(Array.isArray(e)){let n=e.map(ze);if(n.length===2)return n}else if((t=Xf(e))!=null){let n=Zc(t.next()),r=Zc(t.next());if(!n.done&&!r.done)return[ze(n.value),ze(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Kf="0123456789ABCDEF",Rx=/(?:%[0-9A-Fa-f]{2})+/g;function vn(e){return`%${Kf[e>>4&15]}${Kf[15&e]}`}function eg(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?vn(e):String.fromCharCode(e):e<=2047?vn(192|e>>6)+vn(128|63&e):e<=65535?vn(224|e>>12)+vn(128|e>>6&63)+vn(128|63&e):vn(240|e>>18)+vn(128|e>>12&63)+vn(128|e>>6&63)+vn(128|63&e)}function Wc(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Yc(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(Rx,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function io(e){return e<=31||e>126}function kx(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return io(e)}}function ou(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return io(e)}}function jx(e){return ou(e)||e===39}function Xc(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return ou(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 Xc(e)}}function Hf(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 tg(e,t){return eg(e=e||0,t)}function wn(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+=eg(o,t,n)}return i}function au(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([Yc(i.slice(0,a),!0),Yc(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function eu(e){let t="";for(let n=0;n<e.length;n++){let r=wn(e[n][0],Hf,!0),i=wn(e[n][1],Hf,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var Tx=[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],Nx=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Dx=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],Fx=[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 Mx(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[qx,Vx,Ux,Qf]=[[[],"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 Lx(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 ng(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function no(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 Bx(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&&ng(Fx,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&no(Qf,t[i]);)i--;let a=n+1;for(;a<t.length&&no(Qf,t[a]);)a++;if(!(i>=0&&a<t.length&&no(Vx,t[i])&&no(Ux,t[a])))return!1}return!0}var zx=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,$x=/\p{Script=Latin}/u;function Gx(e){return!zx.test(e)||!$x.test(e)}var Wn=36,Ea=1,tu=26,Kx=38,Hx=700,Qx=72,Jx=128,Zx=2147483647;function Jf(e){return String.fromCharCode(e+22+75*+(e<26))}function Wx(e,t,n){let r=0;for(e=n?Math.floor(e/Hx):e>>1,e+=Math.floor(e/t);e>(Wn-Ea)*tu>>1;r+=Wn)e=Math.floor(e/(Wn-Ea));return Math.floor(r+(Wn-Ea+1)*e/(e+Kx))}function Yx(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=Jx,o=0,s=Qx;for(;r<t.length;){let c=Zx;for(let u=0;u<t.length;u++){let d=t[u];d>=a&&d<c&&(c=d)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let d=t[u];if(d<a&&o++,d===a){let m=o;for(let w=Wn;;w+=Wn){let I=w<=s?Ea:w>=s+tu?tu:w-s;if(m<I)break;n+=Jf(I+(m-I)%(Wn-I)),m=Math.floor((m-I)/(Wn-I))}n+=Jf(m),s=Wx(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Hc(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=Wc(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Zf(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function rg(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function ig(e){return e.length===2&&rg(e.codePointAt(0),e.codePointAt(1))}function Wf(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function at(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function og(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function nu(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,d=0,m=0;for(;m<4&&(u=Wc(c[s]))>=0;)d=(d<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let w=0;for(;c[s]!==void 0;){let I=0;if(w>0)if(c[s]===46&&w<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(I=10*I+Wc(c[s]),I>255)return null;s++}i[o]=256*i[o]+I,w++,w%2==0&&o++}if(w!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=d,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let d=i[a+u-1];i[a+u-1]=i[o],i[o]=d,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Wf(r)?null:wn(r,io)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let d of u){let m=d.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(d)&&!ng(Tx,m)||no(qx,m))return!0}return!1})(i))return null;let s=(i=(function(u){let d="";for(let m of u){let w=m.codePointAt(0);if(w!==8204&&w!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let I=Lx(m,w);if(I){d+=I;continue}let p=Nx.indexOf(w);d+=p<0?m:Dx[p]}return d})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let d=/[^\0-\x7f]/.test(u);if(Mx(u)||d&&(/^\p{Mark}/u.test(u)||!Bx(u)||!Gx(u)||u.startsWith("xn--")))return null;d&&(s[c]=`xn--${Yx(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Yc(e));return n===null||Wf(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(Hc(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let d=Hc(a[u]);if(d<0||d>255)return null;s+=d*(1<<8*(3-u))}let c=Hc(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function ru(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,d=1,m=0;for(let w=0;w<s.length;++w)s[w]!==0?(m>d&&(c=u,d=m),u=-1,m=0):(u===-1&&(u=w),++m);return m>d?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function ag(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 sg(e){return e.username!==""||e.password!==""}function Qc(e){return e.host===null||e.host===""||e.scheme==="file"}var C=0,F="",ye="",Fe=null,M,Ra=!1,ka=!1,_r=!1,st;function nn(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,F=e,ye="",Fe=n||null,M=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Ra=!1,ka=!1,_r=!1,st=r||0;let i=Xx;switch(r){case 3:case 4:i=Ta;break;case 5:i=cu;break;case 6:i=Er;break;case 7:i=Yn;break;case 8:i=On}return i(z(e,C))!==1?M:null}function J(e,t){return C+=C===e?yn(t):1,C<=F.length}function z(e,t){return t<e.length?e.codePointAt(t):void 0}function yn(e){return e!=null&&e>65535?2:1}function cg(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var Xx=e=>{let t=C;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=C+1;for(e=F.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=F.charCodeAt(n);return ye=F.slice(C,n).toLowerCase(),C=n,e0(n<F.length?e:void 0)}else return st?1:(--C,J(t,e)?ug(z(F,C)):0)},e0=e=>{let t=C;if(e===58){if(st){if(at(M.scheme)!==at(ye))return 0;if((sg(M)||M.port!==null)&&ye==="file")return 0;if(M.scheme==="file"&&M.host==="")return 0}return M.scheme=ye,st?(M.port===og(M.scheme)&&(M.port=null),0):(ye="",M.scheme==="file"?J(t,e)?uu(z(F,C)):0:at(M.scheme)&&Fe!==null&&Fe.scheme===M.scheme?J(t,e)?t0(z(F,C)):0:at(M.scheme)?J(t,e)?r0(z(F,C)):0:z(F,C+1)===47?(C++,J(t,e)?n0(z(F,C)):0):(M.path=[""],M.opaquePath=!0,J(t,e)?dg(z(F,C)):0))}else return st?1:(ye="",C=-1,J(t,e)?ug(z(F,C)):0)},ug=e=>{let t=C;return Fe===null||Fe.opaquePath&&e!==35?1:Fe.opaquePath&&e===35?(M.scheme=Fe.scheme,M.path=Fe.path.slice(),M.opaquePath=Fe.opaquePath,M.query=Fe.query,M.fragment="",J(t,e)?On(z(F,C)):0):Fe.scheme==="file"?(C--,J(t,e)?uu(z(F,C)):0):(C--,J(t,e)?su(z(F,C)):0)},t0=e=>{let t=C;return e===47&&z(F,C+1)===47?(++C,J(t,e)?Da(z(F,C)):0):(C--,J(t,e)?su(z(F,C)):0)},n0=e=>{let t=C;return e===47?J(t,e)?ui(z(F,C)):0:(C--,J(t,e)?bn(z(F,C)):0)},su=e=>{let t=C;return M.scheme=Fe.scheme,e===47||at(M.scheme)&&e===92?J(t,e)?Yf(z(F,C)):0:(M.username=Fe.username,M.password=Fe.password,M.host=Fe.host,M.port=Fe.port,M.path=Fe.path.slice(),M.query=Fe.query,e===63?(M.query="",J(t,e)?Yn(z(F,C)):0):e===35?(M.fragment="",J(t,e)?On(z(F,C)):0):e!=null?(M.query=null,M.path.pop(),C--,J(t,e)?bn(z(F,C)):0):J(t,e)?su(z(F,C)):0)},Yf=e=>{let t=C;return at(M.scheme)&&(e===47||e===92)?J(t,e)?Da(z(F,C)):0:e===47?J(t,e)?ui(z(F,C)):0:(M.username=Fe.username,M.password=Fe.password,M.host=Fe.host,M.port=Fe.port,C--,J(t,e)?bn(z(F,C)):0)},r0=e=>{let t=C;return e===47&&z(F,C+1)===47?C++:C--,J(t,e)?Da(z(F,C)):0},Da=e=>{let t=C;return e!==47&&e!==92?(C--,J(t,e)?ui(z(F,C)):0):J(t,e)?Da(z(F,C)):0},ui=e=>{let t=C;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!at(M.scheme))){let n=C+yn(e);for(;n<F.length;){let r=z(F,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&at(M.scheme))break;n+=yn(r)}return ye+=F.slice(C,n),C=n-1,J(t,e)?ui(z(F,C)):0}if(e===64){Ra&&(ye=`%40${ye}`),Ra=!0;for(let n=0;n<ye.length;n++){let r=ye.codePointAt(n);if(r===58&&!ka){ka=!0;continue}let i=tg(r,ja);ka?M.password+=i:M.username+=i,r!=null&&r>65535&&n++}return ye="",J(t,e)?ui(z(F,C)):0}else return e==null||e===35||e===47||e===63||e===92&&at(M.scheme)?Ra&&ye===""?1:(C-=ye.length+1,ye="",J(t,e)?Ta(z(F,C)):0):(ye+=cg(e),J(t,e)?ui(z(F,C)):0)},Ta=e=>{let t=C;if(st&&M.scheme==="file")return C--,J(t,e)?lu(z(F,C)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!at(M.scheme))){let n=C+yn(e);for(e===91?_r=!0:e===93&&(_r=!1);n<F.length;){let r=z(F,n);if(r==null||!_r&&r===58||r===35||r===47||r===63||r===92&&at(M.scheme))break;r===91?_r=!0:r===93&&(_r=!1),n+=yn(r)}return ye+=F.slice(C,n),C=n-1,J(t,e)?Ta(z(F,C)):0}else if(e===58&&!_r){if(ye===""||st===4)return 1;let n=nu(ye,!at(M.scheme));return n===null?1:(M.host=ru(n),ye="",J(t,e)?cu(z(F,C)):0)}else if(e==null||e===35||e===47||e===63||e===92&&at(M.scheme)){if(C--,at(M.scheme)&&ye==="")return 1;if(st&&ye===""&&(sg(M)||M.port!==null))return 1;let n=nu(ye,!at(M.scheme));return n===null?1:(M.host=ru(n),ye="",st?0:J(t,e)?Er(z(F,C)):0)}else return ye+=cg(e),J(t,e)?Ta(z(F,C)):0},cu=e=>{let t=C;if(e!=null&&e>=48&&e<=57){let n=C+1;for(;n<F.length;){let r=F.charCodeAt(n);if(r<48||r>57)break;n++}return ye+=F.slice(C,n),C=n-1,J(t,e)?cu(z(F,C)):0}else if(st||e==null||e===35||e===47||e===63||e===92&&at(M.scheme)){if(ye!==""){let n=parseInt(ye,10);if(n>65535)return 1;if(M.port=n===og(M.scheme)?null:n,ye="",st)return 0}return st?1:(C--,J(t,e)?Er(z(F,C)):0)}else return 1};function lg(e,t){let n=e.length-t;if(n<2)return!1;if(rg(z(e,t),z(e,t+1))){if(n===2)return!0;{let r=z(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var uu=e=>{let t=C;return M.scheme="file",M.host="",e===47||e===92?J(t,e)?i0(z(F,C)):0:Fe?.scheme==="file"?(M.host=Fe.host,M.path=Fe.path.slice(),M.opaquePath=Fe.opaquePath,M.query=Fe.query,e===63?(M.query="",J(t,e)?Yn(z(F,C)):0):e===35?(M.fragment="",J(t,e)?On(z(F,C)):0):e!=null?(M.query=null,lg(F,C)?M.path=[]:ag(M),C--,J(t,e)?bn(z(F,C)):0):J(t,e)?uu(z(F,C)):0):(C--,J(t,e)?bn(z(F,C)):0)},i0=e=>{let t=C;return e===47||e===92?J(t,e)?lu(z(F,C)):0:(Fe!==null&&Fe.scheme==="file"&&(!lg(F,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})(Fe.path[0])&&M.path.push(Fe.path[0]),M.host=Fe.host),C--,J(t,e)?bn(z(F,C)):0)},lu=e=>{let t=C;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=C+yn(e);for(;n<F.length;){let r=z(F,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=yn(r)}return ye+=F.slice(C,n),C=n-1,J(t,e)?lu(z(F,C)):0}else if(e==null||e===47||e===92||e===63||e===35){if(C--,!st&&ig(ye))return J(t,e)?bn(z(F,C)):0;if(ye==="")return M.host="",st?0:J(t,e)?Er(z(F,C)):0;{let n=nu(ye,!at(M.scheme));return n===null?1:(n==="localhost"&&(n=""),M.host=ru(n),ye="",st?0:J(t,e)?Er(z(F,C)):0)}}return 1},Er=e=>{let t=C;return at(M.scheme)?(e!==92&&e!==47&&C--,J(t,e)?bn(z(F,C)):0):!st&&e===63?(M.query="",J(t,e)?Yn(z(F,C)):0):!st&&e===35?(M.fragment="",J(t,e)?On(z(F,C)):0):e!=null?(e!==47&&C--,J(t,e)?bn(z(F,C)):0):(st&&M.host===null&&M.path.push(""),J(t,e)?Er(z(F,C)):0)},bn=e=>{let t=C;if(e!=null&&e!==47&&(!at(M.scheme)||e!==92)&&(st||e!==63&&e!==35)){let n=C+yn(e);for(;n<F.length;){let r=z(F,n);if(r==null||r===47||at(M.scheme)&&r===92||!st&&(r===63||r===35))break;n+=yn(r)}ye+=wn(F.slice(C,n),Xc),C=n,e=z(F,n)}if(e==null||e===47||at(M.scheme)&&e===92||!st&&(e===63||e===35)){let n=at(M.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}})(ye)?(ag(M),e!==47&&!n&&M.path.push("")):Zf(ye)&&e!==47&&!n?M.path.push(""):Zf(ye)||(M.scheme==="file"&&M.path.length===0&&ig(ye)&&(ye=`${ye[0]}:`),M.path.push(ye)),ye="",e===63?(M.query="",J(t,e)?Yn(z(F,C)):0):e===35?(M.fragment="",J(t,e)?On(z(F,C)):0):J(t,e)?bn(z(F,C)):0}else return ye+=tg(e,Xc),J(t,e)?bn(z(F,C)):0},dg=e=>{let t=C;if(e===63)return M.query="",J(t,e)?Yn(z(F,C)):0;if(e===35)return M.fragment="",J(t,e)?On(z(F,C)):0;if(e!=null){let n=C+yn(e);for(;n<F.length;){let i=z(F,n);if(i===63||i===35)break;n+=yn(i)}let r=F.slice(C,n);if(n<F.length&&r.charCodeAt(r.length-1)===32?M.path[0]+=wn(r.slice(0,-1),io)+"%20":M.path[0]+=wn(r,io),C=n,(e=z(F,n))===63)return M.query="",J(t,e)?Yn(z(F,C)):0;if(e===35)return M.fragment="",J(t,e)?On(z(F,C)):0}return J(t,e)?dg(z(F,C)):0},Yn=e=>{let t=C,n=C;if(e!=null){if(st)n=F.length;else{let i=F.indexOf("#",C);n=i===-1?F.length:i}let r=at(M.scheme)?jx:ou;M.query+=wn(F.slice(C,n),r)}return C=n,z(F,n)===35&&!st?(M.fragment="",J(t,e)?On(z(F,C)):0):J(t,e)?Yn(z(F,C)):0},On=e=>{let t=C;return e!=null&&(M.fragment+=wn(F.slice(C),kx),C=F.length),J(t,e)?On(z(F,C)):0};function iu(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function pg(e){switch(e.scheme){case"blob":{let t=nn(iu(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":pg(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 Be=Symbol("URLImpl"),cn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=ze(t),n!=null&&(n=ze(n));let r=null;if(n!=null&&(r=nn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=nn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Be]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=ze(t),n!==void 0&&(n=ze(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=ze(t),n!==void 0&&(n=ze(n));let r=null;return n!=null&&(r=nn(n,null,null,0),r==null)?!1:nn(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+=iu(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Be].url)}set href(t){let n=nn(t=ze(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Be].url=n,this[Be].query&&Jc(this[Be].query,n.query)}get origin(){return pg(this[Be].url)}get protocol(){return`${this[Be].url.scheme}:`}set protocol(t){nn(`${t=ze(t)}:`,this[Be].url,null,2)}get username(){return this[Be].url.username}set username(t){t=ze(t),Qc(this[Be].url)||(function(r,i){r.username=wn(i,ja)})(this[Be].url,t)}get password(){return this[Be].url.password}set password(t){t=ze(t),Qc(this[Be].url)||(function(r,i){r.password=wn(i,ja)})(this[Be].url,t)}get host(){let{url:t}=this[Be];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=ze(t),this[Be].url.opaquePath||nn(t,this[Be].url,null,3)}get hostname(){let{url:t}=this[Be];return t.host!=null?t.host:""}set hostname(t){t=ze(t),this[Be].url.opaquePath||nn(t,this[Be].url,null,4)}get port(){let{url:t}=this[Be];return t.port!=null?`${t.port}`:""}set port(t){t=ze(t);let{url:n}=this[Be];Qc(n)||(t?nn(t,n,null,5):n.port=null)}get pathname(){return iu(this[Be].url)}set pathname(t){t=ze(t);let{url:n}=this[Be];n.opaquePath||(n.path=[],nn(t,n,null,6))}get search(){let{url:t}=this[Be];return t.query?`?${t.query}`:""}set search(t){t=ze(t);let{url:n,query:r}=this[Be];if(!t)n.query=null,r&&Jc(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",nn(i,n,null,7),r&&Jc(r,n.query)}}get searchParams(){let t=this[Be],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Na;return o[Xe].url=i,o[Xe].serialized=a==null,a&&(o[Xe].list=au(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Be];return t.fragment?`#${t.fragment}`:""}set hash(t){t=ze(t);let{url:n}=this[Be];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",nn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(cn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var Xe=Symbol("URLSearchParamsImpl"),o0=Symbol.dispose||Symbol.for("dispose");function Jc(e,t){t?e[Xe].list=au(t):e[Xe].list.length=0,e[Xe].serialized=t==null}function _a(e){if(e.url){let t=eu(e.list);(function(r,i){r[Be].url.query=i})(e.url,t||null),e.serialized=!0}}var a0=typeof Iterator<"u"?Iterator:Object,ro=class extends a0{constructor(t,n){super(),this[Xe]={ptr:t,map:n,index:0}}next(){let t=this[Xe];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}[o0](){}},Na=class{constructor(t){let n=this[Xe]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Gf(t[i]));else if((r=Xf(t))!=null){let i;for(;!(i=Zc(r.next())).done;)n.list.push(Gf(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=Ex(o),c=ze(t[o]),u=n.list.find(d=>d[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=ze(t);i=i[0]==="?"?i.substring(1):i,n.list=au(i)}}get size(){return this[Xe].list.length}append(t,n){t=ze(t),n=ze(n),this[Xe].list.push([t,n]);let r=this[Xe];r.url&&r.serialized?(function(a,o){let s=a[Be].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,eu([[t,n]])):_a(r)}delete(t,n){t=ze(t),n=n!=null?ze(n):void 0;let{list:r}=this[Xe],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;_a(this[Xe])}get(t){t=ze(t);let{list:n}=this[Xe];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=ze(t);let n=[],{list:r}=this[Xe];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=ze(t),n=n!=null?ze(n):void 0;let{list:r}=this[Xe];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=ze(t),n=ze(n);let{list:r}=this[Xe],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&&_a(this[Xe])}sort(){this[Xe].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),_a(this[Xe])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[Xe];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new ro(this[Xe],t=>t)}keys(){return new ro(this[Xe],t=>t[0])}values(){return new ro(this[Xe],t=>t[1])}toString(){return eu(this[Xe].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Na.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var Xn="https://api.tinker.cash";function mg(e){let t,n,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m,w){let I=++r;i=void 0,t=void 0,n=void 0;for(let p of[...a.values()])try{p?.()}catch{}I===r&&(t=m,n=w,o())}let c=()=>s();function u(m,w=!1){let I=kr.safeParse(m);if(!I.success||w&&Date.parse(I.data.expiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<Date.parse(I.data.expiresAt))throw new y("INVALID_RESPONSE","Invalid customer session credentials");return I.data}async function d(){if(i)return i;let m=t,w=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new y("UNAUTHENTICATED","Customer authentication is required",401);let I=(async()=>{try{let p=await e(m.refreshToken);if(w!==r)throw new y("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(p,!0);if(g.customerId!==m.customerId||g.sessionId!==m.sessionId)throw new y("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,n=g.accessToken,{...g}}catch(p){throw w!==r?new y("IDENTITY_CHANGED","Customer identity changed during refresh"):(p instanceof y&&p.status===401&&c(),p)}})();i=I;try{return await I}finally{i===I&&(i=void 0)}}return{identify(m){let w=typeof m=="string"?void 0:u(m),I=typeof m=="string"?m:w.accessToken;if(!I.trim()||/\s/.test(I)||I.length>4096)throw new y("INVALID_TOKEN","A server-issued token is required");s(w,I)},reset:c,subscribeIdentity(m,w){return a.set(m,w),()=>{a.delete(m)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return d().then(()=>{if(!n)throw new y("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new y("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:d}}var fg=Symbol("IndianaNoContent");function er(e,t,n=cn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Ve.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new y("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??Xn);if(o.username||o.password||o.search||o.hash)throw new y("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new y("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new y("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=null,d=0,m=null,w=new Set,I=e.session??mg(async h=>{let P=await S("customer-sessions/refresh",{},"POST",{},h);if(!P||typeof P!="object")throw new y("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:E,...j}=P;return j});function p(){d+=1,u=null,m=null;for(let h of w)h.abort();w.clear()}let g=I.subscribeIdentity(p);function f(){I.reset()}async function S(h,P={},v="POST",E={},j){let q=E.installationDetach===!0;if(q&&(h!=="push/installations/detach"||v!=="POST"))throw new y("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!u&&!q)throw new y("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let de=d,be=new AbortController;q||w.add(be);let Oe=()=>!q&&de!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new y("TIMEOUT","Indiana request timed out"),Se,Te=new Promise((Je,_t)=>{Se=()=>_t(Oe()),be.signal.addEventListener("abort",Se,{once:!0})}),Pe=setTimeout(()=>be.abort(),c),Vt=async()=>{let Je=await s(`${o.href.replace(/\/$/,"")}/api/v1/${h}`,{method:v,headers:{"Content-Type":"application/json",...q?{}:{Authorization:`Bearer ${j??u}`},[Ha]:Qa.current,[ku]:$f.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(P):void 0,signal:be.signal,credentials:"omit",cache:"no-store",redirect:"error",...E.keepalive?{keepalive:!0}:{}});if(be.signal.aborted)throw Oe();let _t;try{_t=Je.status===204?fg:await Je.json()}catch{throw be.signal.aborted?Oe():new y(Je.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Je.status,Je.headers.get("X-Request-Id")??void 0)}if(be.signal.aborted)throw Oe();if(!q&&de!==d)throw new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Je.ok){let it=Ka.safeParse(_t),Ut=it.success&&(!cr.safeParse(it.data.error.code).success||Eu(it.data.error.code,Je.status)),rr=Ut?it.data.error.code:"HTTP_ERROR",ir=po(rr,Je.status,{retryAfter:Je.headers.get("Retry-After"),recovery:Ut?it.data.error.recovery:void 0,reason:Ut?it.data.error.reason:void 0});throw new y(rr,Ut?it.data.error.message:"Indiana request failed",Je.status,Je.headers.get("X-Request-Id")??(it.success?it.data.requestId:void 0),{...ir,...it.success&&it.data.error.retryable===!1?{retryable:!1}:{},...ir.retryAfterSeconds===void 0&&it.success&&it.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:it.data.error.retryAfterSeconds}:{}})}if(Je.headers.get(Ha)!==Qa.current)throw new y("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&_t!==fg){let it=_t&&typeof _t=="object"&&"scope"in _t?_t:_t&&typeof _t=="object"&&"configuration"in _t?_t.configuration:null;if(!it||typeof it!="object"||!("scope"in it))throw new y("INVALID_RESPONSE","Response is missing its App/environment scope");let Ut=Ve.safeParse(it.scope);if(!Ut.success||Ut.data.projectId!==a.projectId||Ut.data.environment!==a.environment)throw new y("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Rr=Je.headers.get("X-Indiana-Telemetry-Subject");if(Rr){if(!/^[a-f0-9]{64}$/.test(Rr))throw new y("INVALID_RESPONSE","Invalid telemetry identity");m!==Rr&&(m=Rr,t?.(m))}return _t};try{return await Promise.race([Vt(),Te])}catch(Je){throw!q&&de!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Je instanceof y?Je:new y(be.signal.aborted?"TIMEOUT":"NETWORK_ERROR",be.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(Pe),be.signal.removeEventListener("abort",Se),w.delete(be)}}return{session:I,requestWithCredential(h,P,v){return S(h,P,"POST",{},v)},subjectKey:()=>m,identify(h){if(a&&typeof h=="object"&&"scope"in h){let P=Ve.safeParse(h.scope);if(!P.success||P.data.projectId!==a.projectId||P.data.environment!==a.environment)throw new y("SCOPE_MISMATCH","Customer session belongs to another App/environment")}I.identify(h),u=I.peek()??null},reset:f,dispose(){g(),p()},request(h,P={},v="POST",E={}){if(E.installationDetach)return S(h,P,v,E);let j=d;try{let q=I.access(),de=be=>{if(j!==d)throw new y("IDENTITY_CHANGED","Customer identity changed before dispatch");return S(h,P,v,E,be)};return typeof q=="string"?de(q):q.then(de)}catch(q){return Promise.reject(q)}}}}function gg(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(!jt.test(s))throw new y("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(s),e.identify(o)},reset(){try{n.beforeReset?.()}finally{e.reset()}}}}}import{ZodError as s0}from"zod";function hg(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof s0?new y(n,r):i}}async function le(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=hg(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):hg(t.response,s,"INVALID_RESPONSE",a.response)}function Me(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new y("INVALID_REQUEST","Customer requests use the verified session identity")}function Ag(e){return{async checkEntitlement(t){Me(t);let n=O.checkEntitlement;return le(e,n,t)},async readHoldings(t={}){let n=O.readHoldings;return le(e,{...n,request:n.request.omit({customerId:!0})},t)}}}function yg(e){return{async readLedger(t){let n=O.readLedger;return le(e,n,{query:t})},async readCreditStatement(t){Me(t);let n=O.readCreditStatement;return le(e,n,t)},async quoteBalance(t){Me(t);let n=O.quoteBalance;return le(e,n,{command:t})}}}function bg(e){return{async setupPayment(t){Me(t);let n=O.setupPayment;return le(e,n,t)},async readPaymentSetup(t){Me(t);let n=O.readPaymentSetup;return le(e,n,t)},async readBillingInvoice(t){Me(t);let n=O.readBillingInvoice;return le(e,n,t)},async readBillingControls(t={}){Me(t);let n=O.readBillingControls;return le(e,n,t)},async prepareBillingAuthorization(t){Me(t);let n=O.prepareBillingAuthorization;return le(e,n,t)},async confirmBillingAuthorization(t){Me(t);let n=O.confirmBillingAuthorization;return le(e,n,t)},async setBillingCoupons(t){Me(t);let n=O.setBillingCoupons;return le(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Me(t);let n=O.revokeBillingAuthorization;return le(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Me(t);let n=O.listBillingInvoices;return le(e,n,t)},async confirmBillingAdjustment(t){Me(t);let n=O.confirmBillingAdjustment;return le(e,n,t)}}}function Sg(e){return{async previewUpdate(t){Me(t);let n=O.previewUpdate;return le(e,n,t)},async update(t){Me(t);let n=O.update;return le(e,n,t)},async readSubscriptionUpdate(t){Me(t);let n=O.readSubscriptionUpdate;return le(e,n,t)},async restoreNativePurchase(t){Me(t);let n=O.restoreNativePurchase;return le(e,n,t)},async previewAttach(t){Me(t);let n=O.previewAttach;return le(e,n,t)},async attach(t){Me(t);let n=O.attach;return le(e,n,t)},async readSubscriptionOperation(t){Me(t);let n=O.readSubscriptionOperation;return le(e,n,t)}}}function xg(e){return{async redeemReward(t){return Me(t),(await le(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Me(t),(await le(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Me(t),(await le(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 le(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 le(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 le(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Ig(e){return{...Ag(e),...yg(e),...bg(e),...Sg(e),...xg(e)}}function vg(e){return{async resolveContent(t){Me(t);let n=O.resolveContent;return le(e,n,t)},async resolvePaywall(t){Me(t);let n=O.resolvePaywall;return le(e,n,t)},async resolveOffering(t){Me(t);let n=O.resolveOffering;return le(e,n,t)}}}var wg=e=>new TextEncoder().encode(JSON.stringify(e)).length,Og=16384;function Cg(e,t){let n=0,r,i=p=>{r={config:structuredClone(p),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function d(p,g={},f={}){if(c(),r&&Date.now()<r.until&&!zp(r.config,p))return;I();let S=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:p,properties:g,...f}]}).events[0];if(wg({events:[S]})>Og)throw new y("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new y("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(S)),u()}async function m(p=!1){if(c(),o)return o;let g=n,f=(async()=>{let S={inserted:0,duplicates:0,rejected:0,skipped:0},h=a.length;for(;h&&g===n;){let P=[];for(let j of a.slice(0,Math.min(h,100))){if(P.length&&wg({events:[...P,j]})>Og)break;P.push(j)}let v=O.trackEvents,E=await le(e,v,{events:P},void 0,{keepalive:p});if(g!==n)throw new y("IDENTITY_CHANGED","Event identity changed during delivery");if(E.inserted+E.duplicates+E.rejected+E.skipped!==P.length)throw new y("INVALID_RESPONSE","Incomplete event acknowledgement");i(E.analyticsConfig),a.splice(0,P.length),h-=P.length,S.inserted+=E.inserted,S.duplicates+=E.duplicates,S.rejected+=E.rejected,S.skipped+=E.skipped}return S})();o=f;try{return await f}finally{o===f&&(o=null)}}let w;function I(){if(w||typeof document>"u")return;let p=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",p),w=()=>document.removeEventListener("visibilitychange",p)}return{rememberConfiguration:i,track(p,g,f={}){return I(),d(p,g,f)},flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){w?.(),w=void 0}}}function du(e){let t=null,n=null,r=0,i=0,a=!1,o=new Set,s=null,c=null,u=new Set,d=()=>{for(let h of u)try{h()}catch{}},m={attributes:mt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(h,P)=>{!o.has(h)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(h,structuredClone(P),structuredClone(m.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(h,P)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(h),structuredClone(P),structuredClone(m.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?h=>e.saveStickyBucketAssignmentDoc(structuredClone(h)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function I(h,P=new Set){return o.has(h)?!s||!s.features[h]||["unknownFeature","cyclicPrerequisite"].includes(s.features[h].source):P.has(h)?!1:(P.add(h),(t?.features[h]?.rules??[]).some(v=>[...v.parentConditions??[],...(v.tracks??[]).flatMap(E=>E.experiment.parentConditions??[])].some(E=>I(E.id,P))))}let p=h=>{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(h)?!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?w():structuredClone(s.features[h]??w()):e.evaluateRemote&&(m.attributes?.merchandise||m.attributes?.merchandiseId)&&!a||I(h)?w():structuredClone(_n(h,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 h=i;if(c?.revision===h)return c.loading;let P=r,v=t,E=[...o],j=(async()=>{let q=ra.parse(await e.evaluateRemote({attributes:structuredClone(m.attributes),features:E}));if(!(P!==r||h!==i||v!==t)){if(e.assertUsable?.(v.generation),q.generation!==v.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(E.some(de=>!Object.hasOwn(q.features,de))||Object.keys(q.features).some(de=>!o.has(de)))throw new Error("Invalid remote Feature results");if(m.attributes?.merchandise||m.attributes?.merchandiseId){if(!q.merchandiseContext)throw new Error("Server did not resolve merchandise context");m.attributes=mt.parse({...m.attributes,...q.merchandiseContext}),a=!0}s=structuredClone(q),m.features={...v.features,...Object.fromEntries(Object.entries(s.features).map(([de,be])=>[de,{defaultValue:be.value}]))},d()}})();c={revision:h,loading:j};try{await j}finally{c?.loading===j&&(c=null)}}function f(){g().catch(h=>{try{e.onError?.(h)}catch{}})}async function S(){if(n)return n;let h=r,P=(async()=>{let v=await e.load(),E="remoteFeatures"in v?zi.parse(v):null,j=E??on.parse(v);if(j.scope.projectId!==e.scope.projectId||j.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(h!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===j.generation){let{evaluatedAt:de,expiresAt:be,...Oe}=t,{evaluatedAt:Se,expiresAt:Te,...Pe}=j;if(gt(Oe)!==gt(Pe))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=j.evaluatedAt,t.expiresAt=j.expiresAt,d(),(!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now())&&f(),structuredClone(t)}let q=new Set(E?.remoteFeatures??[]);if([...q].some(de=>Object.hasOwn(j.features,de)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in j&&!t.analyticsConfig.experimentViewsEnabled&&E?.analyticsConfig.experimentViewsEnabled&&m.trackedExperiments?.clear(),t=structuredClone(j),o=q,s=null,c=null,i++,m.features=t.features,m.savedGroups=qr(t.savedGroups),m.trackedFeatureUsage={},d(),f(),structuredClone(t)})();n=P;try{return await P}finally{n===P&&(n=null)}}return{init:S,refresh:S,refreshRemote:g,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(h){return u.add(h),()=>{u.delete(h)}},setAttributes(h){let P=mt.parse(h);(m.attributes?.merchandise||m.attributes?.merchandiseId||h.merchandise||h.merchandiseId)&&m.trackedExperiments?.clear(),m.attributes=P,i++,a=!1,s=null,c=null,m.features=t?.features??{},m.trackedFeatureUsage={},d(),f()},evalFeature:p,isOn(h){return p(h).on},isOff(h){return p(h).off},getFeatureValue(h,P){let v=p(h).value;return structuredClone(v===null?P:v)},reset(){r++,i++,n=null,c=null,t=null,s=null,o.clear(),m.features={},m.savedGroups={},m.stickyBucketAssignmentDocs={},m.attributes={},m.trackedFeatureUsage={},m.trackedExperiments?.clear(),d()}}}function Pg(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 c0(e){let t=Pg(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function _g(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new y("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let d=a,m=!1,w=async()=>{if(m||d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let Oe=O.getFeatures,Se=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await le(e,Oe,{});if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");if(r&&(Se.scope.projectId!==r.projectId||Se.scope.environment!==r.environment))throw new y("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Se.payload.analyticsConfig),Se},I=await w(),p=!0,g,f=Oe=>{try{u.onError?.(Oe)}catch{}},S=(Oe,Se,Te)=>{try{let Pe=Pg(Te);n.track(Oe,Se,Pe?{merchandise:Pe}:{})}catch(Pe){f(Pe)}},h=du({assertUsable:i?.assertFeatures,scope:I.scope,attributes:u.attributes,onError:u.onError,load:async()=>p?(p=!1,I.payload):(await w()).payload,evaluateRemote:async Oe=>{if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let Se=O.evaluateFeatures,Te=await le(e,Se,{...Oe,attributes:c0(Oe.attributes)});if(Te.scope.projectId!==I.scope.projectId||Te.scope.environment!==I.scope.environment)throw new y("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Te.generation,evaluatedAt:Te.evaluatedAt,expiresAt:Te.expiresAt,features:Te.features,...Te.merchandiseContext?{merchandiseContext:Te.merchandiseContext}:{}}},onExperimentViewed:(Oe,Se,Te)=>S("Experiment Viewed",{experimentId:Oe.key,variationId:Se.key},Te),onFeatureUsage:(Oe,Se,Te)=>S("Feature Evaluated",{feature:Oe,value:Se.value,source:Se.source,ruleId:Se.ruleId,...Se.experimentResult?{variationId:Se.experimentResult.key}:{}},Te)}),P=h.refresh;function v(){clearTimeout(g),!i&&(m||d!==a||!h.expiresAt||(g=setTimeout(()=>{E().catch(f)},Math.min(2147483647,Math.max(1e3,Date.parse(h.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function E(){try{return await P()}finally{v()}}let j=()=>{m||E().catch(f)},q=h.subscribe(v),de=i?.subscribe(()=>{!m&&i.fresh&&E().catch(f)});function be(){m||(m=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",j),q(),de?.(),h.reset(),o.delete(be))}o.add(be);try{await h.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await h.refreshRemote()}catch(Oe){throw be(),Oe}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(h,{refresh:E,destroy:be})}return{features:c,reset(u){a++,u();for(let d of o)d()}}}import{z as u0}from"zod";function Eg(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=u0.object({funnelId:Oa.shape.id,funnelVersionId:Oa.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new y("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new y("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new y("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await le(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return le(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return le(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return le(e,s,a(o))}}}function Rg(e){let t=er(e),n=t.request,r=Bf(e.push,t,e.scope??e.configuration?.scope),i=gg(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),a=Cg(n,i.isIdentified),o=_g(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...zf(n,r),...Ig(n),...vg(n),forFunnel(s){return Eg(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 li(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)=>li(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)&&li(a,Reflect.get(t,i)))}async function Fa(e,t){let n=Rf.safeParse(t);if(!n.success)throw new y("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Funnel scope changed");return r}var di=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Ma(e){let t=jt.test(e.apiKey);if(typeof window<"u"&&!t)throw new y("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!di.test(e.apiKey))throw new y("INVALID_TOKEN","A customer credential or server API key is required");let n=er({...e,timeoutMs:e.timeoutMs??35e3});return e.session||n.identify(e.apiKey),{async start(r){let i=Tn.safeParse({...r,operation:"start"});if(!i.success||i.data.operation!=="start"||(t?i.data.customer!==void 0:i.data.customer===void 0))throw new y("INVALID_REQUEST","Invalid current Funnel start");let a=i.data,o=eo.safeParse(await Fa(e,await n.request("funnels",a)));if(!o.success||!o.data.runToken)throw new y("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==a.funnelId||s.run.locale!==(a.locale??"en")||!li(s.run.parameters,a.parameters??{})||(a.customer?!s.customerId||a.customer.type==="id"&&s.customerId!==a.customer.value:s.customerId!==void 0))throw new y("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function pu(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 kg(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await pu(e,t,n))}function qa(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Pc(n)===t.sha256}async function Va(e,t){let n=vr.parse(t),{artifact:r,environmentId:i}=n.content,a=new cn(e.baseUrl??Xn).origin,o=new cn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new y("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c=setTimeout(()=>s.abort(),Gt.initializationMs);try{let u=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>r.byteLength)throw new y("INVALID_RESPONSE","Public Paywall is unavailable");let d=await pu(u,r.byteLength,{signal:s.signal,error:m=>new y("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!qa(d,r))throw new y("INVALID_RESPONSE","Public Paywall digest or size changed");return Fm(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))}finally{clearTimeout(c)}}var jg=(e,t)=>new y(e,t);async function mu(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new y("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new y("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=l0(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 l0(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=Lc({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:on.parse(o)}),c=d0(s,n.document,{...t,...r}),u=c.steps.at(-1),d=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return d?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:d.nodeId,visit:d.visit,terminal:!c.boundary}:null}function d0(e,t,n){return Vf(e,t,n,jg)}import{z as Cn}from"zod";var Tg=Tn.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new y("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Ng=Cn.strictObject({schemaVersion:Cn.literal(1),scope:Ve,runId:Cn.uuid(),funnelId:Cn.uuid(),versionId:Cn.uuid(),command:Tg.optional(),closeCommand:Tg.refine(e=>e.operation==="close").optional(),purchase:Cn.strictObject({receiptId:Cn.uuid(),operationId:Cn.uuid(),generation:Cn.number().int().nonnegative()}).optional(),closed:Cn.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"),Kt=()=>new y("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Ua=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Dg(e){let t=0,n=null,r=c=>JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]),i=Promise.resolve();async function a(){let c=await e.read();if(!Number.isSafeInteger(c.revision)||c.revision<0)throw new y("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:c.revision,entry:c.entry===null?null:Ng.parse(c.entry)}}function o(c){let u=i.then(c);return i=u.catch(()=>{}),u}async function s(c){for(let u=0;u<4;u++){let d=await a();if(d.entry&&n!==null&&r(d.entry)!==n)throw Kt();let m=c(d.entry,d.revision);if(Ua(d.entry,m)){t=d.revision;return}let w=await e.write(d.revision,m);if(w!==null){if(!Number.isSafeInteger(w)||w<=d.revision)throw Kt();t=w;return}}throw Kt()}return{bind(c){let u=JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]);if(n!==null&&n!==u)throw Kt();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=Ng.parse(c),d=u.command;return!d||n!==null&&r(u)!==n?Promise.reject(Kt()):(n??(n=r(u)),o(()=>s((m,w)=>{if(m&&!Ua(r(m),r(u)))throw Kt();if(!m){if(w!==t&&d.operation!=="close")throw Kt();return u}if(!m.command)return{...m,command:d,...d.operation==="close"?{closed:!0}:{}};if(d.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===d.requestId||m.closeCommand&&!Ua(m.closeCommand,d))throw Kt();return{...m,closeCommand:d,closed:!0}}if(!Ua(m.command,d))throw Kt();return m})))},observePurchase(c,u,d){return o(()=>s((m,w)=>{if(!m&&w!==t||m&&r(m)!==r({...c,schemaVersion:1}))throw Kt();if(m?.purchase&&m.purchase.generation>u.generation)return m;if(m?.purchase&&m.purchase.generation===u.generation&&m.purchase.operationId!==u.operationId)throw Kt();return d?!m?.purchase||m.purchase.operationId!==u.operationId?m:m.command?{...m,purchase:void 0}:null:{schemaVersion:1,...c,...m,purchase:u}}))},settle(c){return o(()=>s(u=>u?u.command&&"requestId"in u.command&&u.command.requestId===c?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand&&"requestId"in u.closeCommand&&u.closeCommand.requestId===c?{...u,closeCommand:void 0}:u:null))}}}function Fg(e){let t,n,r=()=>new y("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??Xn).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof y?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function Mg(e){let t=null,n=0,r=!1,i,a=0,o=new Set;return{get view(){return t},get generation(){return n},get disposed(){return r},get customerToken(){return i},get readSequence(){return a},nextRead(){return++a},assertCurrent(s,c="Run identity changed during the request"){if(s!==n||r)throw new y("IDENTITY_CHANGED",c)},assertRun(s){if(t&&(s.id!==t.id||s.source.type!==t.source.type||s.source.id!==t.source.id||s.source.versionId!==t.source.versionId||s.locale!==t.locale||!li(s.parameters,t.parameters)))throw new y("INVALID_RESPONSE","Run version changed");if(e&&s.source.id!==e)throw new y("INVALID_RESPONSE","Run belongs to another Funnel")},publish(s,c,u,d,m){if(!(s.operation==="review"&&t&&t!==u&&c.run.revision<=t.revision)&&!(t&&c.run.revision===t.revision&&d!==void 0&&d<a)&&(s.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&t&&c.run.nodeId===t.nodeId&&c.run.visit===t.visit&&c.run.revision===t.revision&&(c.run.screen=t.screen,(t.paywall?.quote?.operationId===c.review?.activeOperationId||!t.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=t.paywall)),!(t?.paywall&&c.run.paywall&&t.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||c.run.revision>=t.revision)t=c.run;else if(!m)return;if(t)for(let w of o)try{w(structuredClone(t))}catch{}}},identify(s){if(!jt.test(s))throw new y("INVALID_TOKEN","Customer credential required");n++,i=s},subscribe(s){return o.add(s),()=>o.delete(s)},reset(){r=!0,n++,i=void 0,t=null,o.clear()}}}function tr(e){let{customerToken:t,...n}=e;return n}var p0=e=>!(e instanceof y)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function qg({options:e,journal:t,state:n,call:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=!1,u,d=null,m=t?t.load().then(f=>{if(n.disposed)throw new y("IDENTITY_CHANGED","Controller was reset during command restoration");if(d=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=f.purchase,o=f.closed===!0,!f.command)return;let S=Tn.parse(f.command);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("COMMAND_STORAGE_INVALID","Stored mutation required");i=S,f.closeCommand&&(a=f.closeCommand,o=!0),S.operation==="close"&&(o=!0),c=!0}):Promise.resolve();m.catch(()=>{});async function w(f=i){if(t&&await m,!f)throw new y("INVALID_REQUEST","No command is pending");let S=f,h=n.generation;if(t){if(!n.view||!e.scope)throw new y("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await t.retain({schemaVersion:1,scope:e.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:tr(S)})}if(h!==n.generation||i!==S&&a!==S)throw new y("IDENTITY_CHANGED","Run changed before command dispatch");let P={...S,...n.customerToken?{customerToken:n.customerToken}:{}},v=c;c=!0;try{return await r(P,E=>{if(!E.settlement)throw new y("INVALID_RESPONSE","Exact command settlement is missing");if(E.settlement.requestId!==S.requestId)throw new y("INVALID_RESPONSE","Command settlement identity changed");if(h===n.generation&&(i===S||a===S)&&E.run.pendingRequest?.requestId!==S.requestId&&E.settlement.state==="settled"&&(!o||S.operation==="close"||E.settlement?.state==="settled"&&!["running","waiting"].includes(E.run.status))){let j=()=>h!==n.generation||i!==S&&a!==S?!1:(i===S&&(i=null),a===S&&(a=null),c=i!==null,d=null,!0);return t?t.settle(S.requestId).then(j):j()}return!1})}catch(E){throw h===n.generation&&i===S&&!v&&!p0(E)&&(t&&await t.settle(S.requestId),h===n.generation&&i===S&&(i=null,c=!1,d=null)),E}}function I(f){let S=Tn.parse(f);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("INVALID_REQUEST","Mutation required");if(o&&S.operation!=="close"){if(i?.requestId===S.requestId)return g(S.requestId);throw new y("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(S.operation==="close"&&i?.operation!=="close"){if(o=!0,a&&JSON.stringify(tr(a))!==JSON.stringify(tr(S)))throw new y("COMMAND_PENDING","Retry the original Close");return a??(a=S),s.close?s.close:p(a,"close")}if(i){if(JSON.stringify(tr(i))!==JSON.stringify(tr(S)))throw new y("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=S,c=!1;return p(i,"command")}function p(f,S){let h=w(f);s[S]=h;let P=()=>{s[S]===h&&(s[S]=null)};return h.then(P,P),h}async function g(f){let S=await r({operation:"get",settlementRequestId:f,...n.customerToken?{customerToken:n.customerToken}:{}});if(S.settlement?.requestId!==f)throw new y("INVALID_RESPONSE","Exact command settlement is missing");return S.settlement.state==="settled"&&(t&&await t.settle(f),i?.requestId===f&&(i=null,c=!1),a?.requestId===f&&(a=null)),S}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(f){if(d&&(f.run.id!==d.runId||f.run.source.id!==d.funnelId||f.run.source.versionId!==d.versionId))throw new y("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(f,S,h,P){t?.bind({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId}),t&&!e.scope&&(e.scope=S.scope);let v=S.run.paywall,E=v??S.purchase,j=E?.operation,q=S.settlement&&(!v||v.purchaseRequestId===S.settlement.requestId)&&(!u||u.operationId===S.settlement.operationId)?S.settlement:void 0,de=j?.operationId??E?.quote?.operationId??q?.operationId,be=E?.receiptId??q?.receiptId,Oe=v?.selectionGeneration??u?.generation??0;if(t&&de&&be&&f.operation!=="review"&&(!n.view||S.run.revision>=n.view.revision)&&(P===void 0||P>=n.readSequence)&&(!u||Oe>=u.generation)){let Se={receiptId:be,operationId:de,generation:Oe},Te=j?.status==="complete"||E?.canReselect===!0;return t.observePurchase({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId},Se,Te).then(()=>{n.assertCurrent(h),Te?u?.operationId===Se.operationId&&(u=void 0):u=Se})}},stop(){o=!0},submit:I,executePending:w,settle:g,reset(){i=null,a=null,s.close=null,c=!1,s.command=null}}}function pi(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new y("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!di.test(e.serverKey)))throw new y("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new y("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=er({...e,session:void 0,...e.serverKey?{fetch:(f,S)=>{let h=new Headers(S?.headers),P=typeof S?.body=="string"?JSON.parse(S.body):null;return P!==null&&typeof P=="object"&&"customerToken"in P&&typeof P.customerToken=="string"&&P.customerToken.length>0||h.set(kf,e.serverKey),(e.fetch??globalThis.fetch)(f,{...S,headers:h})}}:{},...e.session?{fetch:async(f,S)=>{let h=await e.session.access(),P=typeof S?.body=="string"?JSON.parse(S.body):{};if(!P||typeof P!="object"||Array.isArray(P))throw new y("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(f,{...S,body:JSON.stringify({...P,customerToken:h})})}}:{},timeoutMs:e.timeoutMs??35e3});t.identify(e.runToken);let n=Mg(e.funnelId),r=e.session?.subscribeIdentity(()=>{n.reset(),t.reset()}),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Fg(e):void 0),o=a&&Dg(a),s=qg({options:e,journal:o,state:n,call:c});async function c(f,S,h){let P=n.generation,v=()=>n.assertCurrent(P);o&&await s.ready,v();let E=n.view,j=eo.parse(await Fa(e,await t.request("funnels",Tn.parse(f))));if(f.operation==="review"&&!j.review)throw new y("INVALID_RESPONSE","Historical projection is missing");if(v(),j.runToken&&j.runToken!==e.runToken)throw new y("INVALID_RESPONSE","Run credential changed");let q=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(q&&j.settlement?.requestId!==q)throw new y("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(j),n.assertRun(j.run);let de=s.observePurchase(f,j,P,h);if(de&&await de,!j.run.stopped&&["running","waiting"].includes(j.run.status)&&f.operation==="get"&&f.settlementRequestId)return j;let be=S?.(j),Oe=typeof be=="boolean"?be:be?await be:!1;return v(),["running","waiting"].includes(j.run.status)||s.stop(),n.publish(f,j,E,h,Oe),j}let u=s.submit,d=null,m=new WeakMap;function w(f){let S=m.get(f);if(S)return S;let h=p(f);return m.set(f,h),h}let I=!1;async function p(f){let S=await f;if(S.run.instruction?.type!=="evaluate_segment")return S;if(d)return d;I=!0;let h=n.generation,P=(async()=>{for(let v=0;v<32&&S.run.instruction?.type==="evaluate_segment";v++){if(s.pending||s.closeRequested)return S;let E=S.run;if(S.run.instruction?.type==="evaluate_segment"){let{advance:q}=await mu(e.configuration,E,{predict:!1});if(h!==n.generation)throw new y("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return S;if(n.view&&(n.view.revision!==E.revision||n.view.visit!==E.visit||n.view.nodeId!==E.nodeId))return c({operation:"get",...n.customerToken?{customerToken:n.customerToken}:{}});let de=!0;mu(e.configuration,E).then(({prediction:be})=>{de&&h===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=be)}).catch(()=>{});try{S=await u({operation:"commit_segment",requestId:Ef(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...q})}finally{de=!1,i=null}}}return S})();d=P;try{return await P}finally{d===P&&(d=null)}}let g={get configuration(){return I?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let f=s.closing??s.pending;return f?structuredClone(tr(f)):null},get pendingCommands(){return[s.pending,s.closing].filter(f=>f!==null).map(f=>structuredClone(tr(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 Va(e,f)},async pageExperiments(f,S=[]){let h=n.generation;n.assertCurrent(h);let P=n.view?.id;if(!P)throw new y("INVALID_REQUEST","Read the Run before its page experiments");let v=Lf.parse(await t.request("funnels",Uf.parse({operation:"page_experiments",release:f,usedReceiptIds:S,...n.customerToken?{customerToken:n.customerToken}:{}})));if(n.assertCurrent(h),v.runId!==P||v.scope.projectId!==e.scope?.projectId||v.scope.environment!==e.scope?.environment)throw new y("SCOPE_MISMATCH","Page experiment Run changed");return v},review(f){return c({operation:"review",...f?{receiptId:f}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,n.nextRead())},async get(f,S){o&&await s.ready,S??(S=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let h=n.nextRead();return w(c({operation:"get",...f?{data:f}:{},...S?{purchase:S}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,h))},resume(f=n.view?.pendingRequest?.requestId){return f?s.closeRequested?g.settle(f):s.pending?.requestId===f?w(u(s.pending)):w(u({operation:"resume",requestId:f})):Promise.reject(new y("INVALID_REQUEST","No interrupted command is available"))},submit(f){return w(u(f))},retry(){return s.closeFlight?s.closeFlight:s.closing?s.executePending(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?w(s.inFlight):s.pending?w(u(s.pending)):Promise.reject(new y("INVALID_REQUEST","No command is pending"))},identify(f){n.identify(f),i=null,t.identify(e.runToken)},subscribe:n.subscribe,reset(){r?.(),n.reset(),s.reset(),i=null,t.reset()}};return g}function Vg(e){if(!jt.test(e.customerToken))throw new y("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new y("INVALID_REQUEST","An explicit App and environment scope is required");let t=Ma({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=pi({...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 Ug(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 Lg(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new y("INVALID_RESPONSE",n)}function Bg(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new y("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider)throw new y("INVALID_RESPONSE",n)}function zg(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 $g(e,t){if(!jt.test(t.customerToken))throw new y("INVALID_TOKEN","A verified Customer credential is required");let n=er(e);if(!e.session)n.identify(t.customerToken);else if(e.session.peek()!==t.customerToken)throw new y("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),i=null,a=!1,o=null,s=null,c=null,u=null,d=e.session?.subscribeIdentity(()=>{a=!0,n.dispose(),i=null,o=null,s=null,c=null});async function m(){if(a)throw new y("IDENTITY_CHANGED","Paywall is closed");let p=O.resolvePaywall,g=await le(n.request,p,{...r,selector:i?{type:"version",versionId:i.id}:r.selector}),f={paywall:await Va(e,g.paywall)};if(a)throw new y("IDENTITY_CHANGED","Paywall is closed");if(t.paywallVersionId?f.paywall.id!==t.paywallVersionId:f.paywall.paywallId!==t.paywallId)throw new y("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!Ug(f.paywall,i)||f.paywall.paywallId!==i.paywallId))throw new y("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=f.paywall,structuredClone(i)}async function w(p){if(!o)throw new y("INVALID_REQUEST","A quoted purchase is required");let g=p==="read"?O.readSubscriptionOperation:O.attach,f=await le(n.request,g,{operationId:o.operationId,...p==="read"?{}:{intent:p}});return Lg(f.operation,{operationId:o.operationId,currency:r.commerce.currency},"The purchase operation changed"),s=zg(s,f.operation),structuredClone(s)}let I={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:m,async preview(p){if(!i)throw new y("INVALID_REQUEST","Load the Paywall first");let g=i.document.buttons[p.actionId];if(g?.type!=="checkout")throw new y("INVALID_REQUEST","Choose an authored purchase action");let f=Up(g.product,p.selection,i.capabilities);if(!f)throw new y("PRODUCT_UNAVAILABLE","Choose an available Product");let S=Pm(i.document.screen,f,p.selection,i.capabilities),h=O.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:f,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),P=JSON.stringify(h);if(c&&c!==P&&(!s||s.status==="pending"))throw new y("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===P){if(u)return u;if(o)return structuredClone(o)}c=P;let v=(async()=>{let E=O.previewAttach,j=await le(n.request,E,h);return Bg(j.quote,{productVersionId:f,featureQuantities:S,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=j.quote,s=null,structuredClone(o)})();u=v;try{return await v}finally{u===v&&(u=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){d?.(),a=!0,n.dispose(),i=null,o=null,s=null,c=null}};return await m(),I}function Gg(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new y("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new y("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new y("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let I=r;n&&e.nativeModule&&n.then(p=>e.nativeModule.reset(p,I)).catch(()=>{})}),d=e.nativeEvents?.(I=>{!n||!e.nativeModule||typeof I?.requestId!="string"||(async()=>{let p=await n;if(I.instanceId!==p)return;if(I.kind==="credential"){let S=r,h=null;try{if(!o&&I.revision===S){let P=await t.access();!o&&r===S&&(h=P)}}finally{await e.nativeModule.provideCredential(p,I.requestId,h)}return}let g=!1,f=r;try{if(o||I.revision!==f||!e.onNativeAction)throw c();await e.onNativeAction(I.action),g=!o&&r===f}finally{await e.nativeModule.acknowledge(p,I.requestId,g)}})().catch(()=>{})});async function m(I,p={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new y("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let f=r,S=await t.access();if(o||r!==f)throw c();if(!n){let v=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.tinker.cash",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let h=await n;if(o||r!==f)throw c();if(i!==f){if(!a||a.epoch!==f){let E=(async()=>{if(await g.identify(h,JSON.stringify({revision:f,credentials:S})),o||r!==f)throw await g.reset(h,f),c();i=f})();a={epoch:f,task:E}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let P=await g.invoke(h,I,JSON.stringify(p));if(o||r!==f)throw c();try{return JSON.parse(P)}catch{throw new y("INVALID_RESPONSE","Native host returned invalid JSON")}}async function w(I,p){let g=await m(I,p);if(!g||typeof g!="object"||Array.isArray(g)||g.status!=="complete"&&g.status!=="dismissed")throw new y("INVALID_RESPONSE","Native presentation returned an invalid result");return g}return{showFunnel(I){return w("showFunnel",{runToken:I})},showPaywall(I){return w("showPaywall",I)},showContent(I){return w("showContent",I)},purchaseSubscription(I,p){return m("purchaseSubscription",{operationId:I,accepted:p})},switchSubscription(I,p){return m("switchSubscription",{operationId:I,accepted:p})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(I){return m("manageSubscriptions",I?{productId:I}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),d?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var m0=O.trackUsage.request.shape.command,f0=O.trackUsage.response;function NN(e){let t=Ve.parse(e.scope),n=Rg({...e,scope:t}),r={...e,scope:t,session:n.session},i=0;n.subscribeIdentity(()=>{i++});let a=()=>{let o=n.session.peek();if(!o)throw new y("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:Gg(e,n.session),funnel(){return Vg({...r,customerToken:a()})},resumeFunnel(o){return a(),pi({...r,runToken:o})},paywall(o){return $g(r,{...o,customerToken:a()})},async trackUsage(o){if(!n.session.peek())throw new y("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new y("INVALID_REQUEST","Configure your authenticated backend usageReporter");let s=m0.parse(o),c=i,u;try{u=await e.usageReporter(s)}catch(m){throw c!==i?new y("IDENTITY_CHANGED","Customer identity changed during usage reporting"):m}if(c!==i)throw new y("IDENTITY_CHANGED","Customer identity changed during usage reporting");let d=f0.parse(u);if(d.scope.projectId!==t.projectId||d.scope.environment!==t.environment)throw new y("INVALID_RESPONSE","Usage response scope differs");return d}}}import{z as y0}from"zod";import{z as oo}from"zod";var g0=oo.record(oo.string().regex(/^[a-f0-9]{64}$/),oo.strictObject({at:oo.number(),text:oo.string()})),Kg=2*1048576,h0=100;function A0(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Hg(e,t){let n=t===void 0?A0():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),h0)})])}catch{return null}finally{clearTimeout(s)}}async function a(){try{let o=await i(`${e}:artifacts`);if(o&&o.length<=Kg)return g0.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<=Gt.retentionMs?s.text:void 0},writeArtifact(o,s){n&&(r=r.catch(()=>{}).then(async()=>{let c=await a(),u=Date.now();c[o]={at:u,text:s};let d={},m=2,w=0;for(let[I,p]of Object.entries(c).sort(([,g],[,f])=>f.at-g.at)){if(p.at>u||u-p.at>Gt.retentionMs)continue;let g=new TextEncoder().encode(JSON.stringify({[I]:p})).byteLength;m+g>Kg||w>=128||(d[I]=p,m+=g,w++)}await n.setItem(`${e}:artifacts`,JSON.stringify(d))}).catch(()=>{}))}}}var we=(e,t)=>new y(e,t),nr=()=>performance.now(),Qg=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function b0(e){let t=wc.parse(e.scope),n=new cn(e.origin??Xn);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(Z=>{let G=new cn(Z);if(G.protocol!=="https:"||G.username||G.password||G.search||G.hash||G.pathname!=="/")throw we("INVALID_URL","Invalid configuration asset origin");return G.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${gt(t)}`,s=Hg(o,e.storage),c,u=0,d=0,m=!1,w=!1,I=0,p=0,g,f,S,h,P=0,v=new Set,E=new Set,j=new Map,q=new Map,de=0,be=!1;function Oe(){for(let Z of v)try{Z()}catch{}}function Se(Z){try{e.onError?.(Z)}catch{}}let Te=()=>!w&&!m&&!!c&&nr()<u&&Date.now()<d;function Pe(){if(!Te())throw we("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Vt(Z,G){let oe=new TextEncoder().encode(G).byteLength;if(!j.has(Z)){for(;j.size&&(j.size>=128||de+oe>Gt.maxCacheBytes);){let ae=j.entries().next().value;de-=new TextEncoder().encode(ae[1]).byteLength,j.delete(ae[0])}j.set(Z,G),de+=oe}}function Je(Z,G,oe){return kg(Z,G,{signal:oe,error:ae=>we("INVALID_RESPONSE",ae==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function _t(Z){let G=new cn(Z,n);if(!r.has(G.origin)||G.username||G.password||G.hash||G.search)throw we("INVALID_URL","Configuration artifact origin is not trusted");return G.href}async function ao(Z,G,oe=!1){let ae=await i(_t(Z),{method:"GET",credentials:"omit",redirect:"error",cache:oe?"default":"no-cache",signal:G,headers:{}});if(ae.status===429){let je=ae.headers.get("retry-after")??"";P=/^\d+$/.test(je)?Number(je)*1e3:Math.max(0,Date.parse(je)-Date.now())||15e3}if(!ae.ok&&ae.status!==304)throw we(`CONFIGURATION_HTTP_${ae.status}`,"Configuration synchronization failed");return ae}function Rr(Z,G,oe){let ae=Date.parse(Z.headers.get("x-indiana-config-validated-at")??""),je=Date.parse(Z.headers.get("x-indiana-config-valid-until")??""),xt=Date.parse(Z.headers.get("date")??""),$e=Z.headers.get("age"),Ht=$e!==null&&/^\d+(\.\d+)?$/.test($e)?Number($e)*1e3:NaN;if(![ae,je,xt,Ht].every(Number.isFinite)||je<=ae||je-ae>Gt.maxControlAgeMs||ae>xt+1e3)throw we("INVALID_RESPONSE","Configuration freshness evidence is invalid");let It=Math.min(je-ae,oe.maxControlAgeSeconds*1e3,Gt.maxControlAgeMs)-Math.max(Ht,xt-ae,0)-(nr()-G);if(It<=0)throw we("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return nr()+It}function it(){if(clearTimeout(S),clearTimeout(h),w||!v.size)return;Te()&&(h=setTimeout(()=>{Te()?it():Oe()},Math.max(1,u-nr())),Qg(h));let Z=p?Math.min(15e3,1e3*2**Math.min(p-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);S=setTimeout(()=>{Ut().catch(Se)},Math.max(P,Z*(.8+Math.random()*.2))),Qg(S)}async function Ut(){if(w)throw we("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Z=I,G=new AbortController;f=G;let oe=(async()=>{if(!be){be=!0;try{let co=await s.readManifest();if(co&&!c){let Pn=Cc.parse(JSON.parse(co));gt(Pn.scope)===gt(t)&&(c=Pn)}}catch{}}G.signal.throwIfAborted();let $e=c,Ht=nr(),kt=await ao(a,G.signal);kt.status===304&&(!$e||!kt.headers.has("x-indiana-config-validated-at")||!kt.headers.has("x-indiana-config-valid-until")||!kt.headers.has("age"))&&(kt=await ao(a,G.signal));let It=kt.status===304?$e:Cc.parse(JSON.parse(await Je(kt,Gt.maxManifestBytes,G.signal))),{generation:Dn,...Fn}=It,or=kt.headers.get("etag");if(gt(It.scope)!==gt(t)||jm(Fn)!==Dn||or!==`"${Dn}"`&&or!==`W/"${Dn}"`)throw we("INVALID_RESPONSE","Configuration scope or content identity changed");if($e&&(It.revision<$e.revision||It.revision===$e.revision&&It.generation!==$e.generation))throw we("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[co,Pn]of Object.entries($e?.funnels??{})){let ar=It.funnels[co];if(ar&&(ar.controlRevision<Pn.controlRevision||ar.evaluationRevision<Pn.evaluationRevision||ar.controlRevision===Pn.controlRevision&&ar.state!==Pn.state||ar.evaluationRevision===Pn.evaluationRevision&&ar.evaluationMode!==Pn.evaluationMode))throw we("INVALID_RESPONSE","Funnel control revision changed identity")}let yu=Rr(kt,Ht,It.policy);if(G.signal.throwIfAborted(),Z!==I)throw we("CONFIGURATION_DISPOSED","Configuration scope changed");return c=It,u=yu,d=Date.now()+Math.max(0,yu-nr()),m=!1,p=0,P=0,s.writeManifest(gt(It)),Oe(),structuredClone(It)})(),ae=setTimeout(()=>G.abort(we("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Gt.initializationMs),je=new Promise(($e,Ht)=>G.signal.addEventListener("abort",()=>Ht(G.signal.reason),{once:!0})),xt=Promise.race([oe,je]).catch($e=>{throw p++,($e instanceof y0.ZodError||$e instanceof SyntaxError||$e instanceof y&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes($e.code))&&(u=0,m=!0,Oe()),$e}).finally(()=>{clearTimeout(ae),g===xt&&(g=void 0),it()});return g=xt,xt}async function rr(Z){let G=Z.sha256,oe=Dn=>qa(Dn,Z);_t(Z.url);let ae=j.get(G);if(ae&&oe(ae))return j.delete(G),j.set(G,ae),ae;if(q.has(G))return q.get(G);let je=new AbortController;E.add(je);let xt=I,$e=(async()=>{try{let or=await s.readArtifact(G);if(or&&oe(or))return Vt(G,or),or}catch{}je.signal.throwIfAborted();let Dn=await ao(Z.url,je.signal,!0),Fn=await Je(Dn,Z.byteLength,je.signal);if(!oe(Fn))throw we("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(w||xt!==I)throw we("CONFIGURATION_DISPOSED","Configuration scope changed");return Vt(G,Fn),s.writeArtifact(G,Fn),Fn})(),Ht=setTimeout(()=>je.abort(we("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Gt.initializationMs),kt=new Promise((Dn,Fn)=>je.signal.addEventListener("abort",()=>Fn(je.signal.reason),{once:!0})),It=Promise.race([$e,kt]).finally(()=>{clearTimeout(Ht),E.delete(je),q.delete(G)});return q.set(G,It),It}async function ir(){return Te()||await Ut(),Pe(),c}async function mi(Z){let G,oe=new Promise((ae,je)=>{G=setTimeout(()=>je(we("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Gt.initializationMs)});try{return await Promise.race([Z(),oe])}finally{clearTimeout(G)}}function fi(Z,G){if(Pe(),c?.generation!==Z.generation)throw we("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(G&&c.funnels[G]?.state!=="active")throw we("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function fu(Z){let G=Z.gb.features;if(!G)throw we("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let oe=Z.artifacts[G];if(oe.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let ae=Ws.parse(JSON.parse(await rr(oe)));if(gt(ae.scope)!==gt({projectId:t.projectId,environment:t.environment})||ae.generation!==oe.generation||ae.remoteFeatures.some(je=>Object.hasOwn(ae.features,je)))throw we("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return fi(Z),{...ae,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-nr())).toISOString()}}async function gu(Z,G){let oe=await ir(),ae=oe.funnels[Z];G&&(!ae||ae.evaluationMode==="local"&&!ae.versions[G])&&(g&&await g,oe=await Ut()),fi(oe,Z);let je=oe.funnels[Z];if(je.evaluationMode!=="local")throw we("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let xt=G??je.currentVersionId,$e=je.versions[xt];if(!$e)throw we("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(oe.artifacts[$e.artifact].formatVersion!==3)throw we("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Ht,kt]=await Promise.all([rr(oe.artifacts[$e.artifact]).then(It=>Nm(JSON.parse(It))),je.evaluationMode==="local"?fu(oe):void 0]);if(kt&&gt(Tm(Ht,kt))!==gt($e.dependencies))throw we("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return fi(oe,Z),{document:Ht,growth:kt,versionId:xt,control:structuredClone(je),manifest:structuredClone(oe)}}async function hu(Z,G){try{return await gu(Z,G)}catch(oe){if(!(oe instanceof y)||!(oe.code==="CONFIGURATION_CHANGED"||oe.code==="CONFIGURATION_HTTP_404"&&Te()))throw oe;let ae=c?.generation;if(g&&await g,await Ut(),oe.code!=="CONFIGURATION_CHANGED"&&c?.generation===ae)throw oe;return gu(Z,G)}}function La(){m=!0,Oe(),Ut().catch(Se)}let so=()=>{(typeof document>"u"||document.visibilityState==="visible")&&La()};function Jg(Z){if(w)throw we("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Z),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",La),window.addEventListener("focus",so),document.addEventListener("visibilitychange",so)),it()),()=>{v.delete(Z),v.size||(clearTimeout(S),clearTimeout(h),Au())}}function Au(){typeof window<"u"&&(window.removeEventListener("online",La),window.removeEventListener("focus",so),document.removeEventListener("visibilitychange",so))}return{scope:Object.freeze({...t}),refresh:Ut,subscribe:Jg,assertFresh:Pe,assertFeatures(Z){Pe();let G=c.gb.features;if(!G)throw we("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Z!==void 0&&c.artifacts[G].generation!==Z)throw we("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Te()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Te()?Math.max(0,u-nr()):0},async features(){return mi(async()=>fu(await ir()))},pageExperiments:()=>mi(async()=>{let Z=await ir(),G=Z.gb.pageExperiments;if(!G)throw we("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let oe=Z.artifacts[G];if(oe.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let ae=Ff.parse(JSON.parse(await rr(oe)));if(ae.environmentId!==t.environmentId||ae.generation!==oe.generation)throw we("INVALID_RESPONSE","Page experiment scope or generation changed");return fi(Z),ae}),funnel:(Z,G)=>mi(()=>hu(Z,G)),paywall:(Z,G)=>mi(async()=>{let oe=await ir(),ae=oe.paywalls?.[Z];if(!ae||!G&&ae.state!=="published")throw we("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let je=G??ae.currentVersionId,xt=ae.versions[je],$e=xt&&oe.artifacts[xt.artifact];if(!$e||$e.kind!=="paywall"||$e.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Ht=wa.parse(JSON.parse(await rr($e)));return fi(oe),{document:Ht,versionId:je,version:xt.version,control:structuredClone(ae),manifest:structuredClone(oe)}}),async localFunnel(Z,G){let oe=await mi(()=>hu(Z,G));if(!oe.growth)throw we("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:ae,remoteFeatures:je,...xt}=oe.growth;return Nf({scope:{projectId:t.projectId,environment:t.environment},funnelId:Z,versionId:oe.versionId,evaluationMode:"local",evaluationRevision:oe.control.evaluationRevision,document:oe.document,payload:xt})},assertFunnel(Z,G,oe){Pe();let ae=c.funnels[Z];if(!ae||ae.state!=="active")throw we("FUNNEL_STOPPED","Funnel is paused or unavailable");if(ae.evaluationMode!=="local")throw we("EVALUATION_MODE","This Funnel now executes at Indiana");if(G!==void 0&&ae.controlRevision!==G)throw we("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(oe!==void 0&&!ae.versions[oe])throw we("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!w){w=!0,I++,u=0,f?.abort(we("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(S),clearTimeout(h),Au(),Oe(),v.clear();for(let Z of E)Z.abort(we("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),de=0}}}}async function S0(e){e={...e};let t=e.configuration;if(!t)throw new y("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&gt(n)!==gt(e.scope))throw new y("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new y("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=di.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new y("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=Ma({...e,scope:n,apiKey:e.credential}),o=s=>{let c=pi({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),d=await u.get();return{...c,...d,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new y("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}export{y as IndianaError,b0 as createConfigurationSync,du as createFeatureClient,NN as createIndianaReactNative,S0 as createLocalFunnelClient};
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"})}),MA=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("$")&&!MA.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)}),qA=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 VA=j.record(j.uuid(),qA).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)}),BA=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(BA).max(50).optional(),filters:j.array(ld).max(20).optional()},UA=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()})]),LA=j.strictObject({defaultValue:Ae,rules:j.array(UA).max(100)}),nw=j.record(j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),LA).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)}),zA=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)}),$A=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(zA).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 GA=$A.safeExtend({filters:j.array(ld).optional()}),KA=j.strictObject({experiments:j.record(j.uuid(),GA),savedGroups:VA}),ki=j.strictObject({attributeName:j.string(),attributeValue:j.string(),assignments:j.record(j.string(),j.string())}),rw=j.strictObject({snapshot:KA,attributes:ht,results:ht,stickyBucketAssignmentDocs:j.record(j.string(),ki)}),iw=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 Qn(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 HA=Ct.enum(["active","inactive"]),QA=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),JA=Ct.strictObject({id:Ct.string().trim().min(1).max(255),name:Ct.string().trim().min(1).max(255),status:HA,metadata:QA}),lw=JA.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()})]),dw=Ct.enum(["customer","merchandise","context"]),pw=Ct.enum(["system","stored","request"]),mw=Ct.enum(["customer","merchandise","mixed"]),dd=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Us(e,t={},n=new Set){if(Qn(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 ZA}from"zod";var WA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,gn=ZA.string().max(16).regex(WA,"\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 xw=X.enum(["draft","active","paused","archived"]),Jn=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()],YA=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"])})})]),XA=X.strictObject({firstPurchaseOnly:X.boolean(),condition:Ht}),Iw=X.object({name:X.string().trim().min(1).max(80),description:X.string().max(500),discount:Jn,duration:en,appliesTo:YA,eligibility:XA,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"]}),vw=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:Jn,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})?$/),ey=h.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ti=ey,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"))},ty=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"),ny=h.discriminatedUnion("kind",[h.object({kind:h.literal("flat"),units:Mn,unitAmountMinor:bd}).strict(),h.object({kind:h.enum(["graduated","volume"]),units:Mn,tiers:ty}).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"),ry=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:ny,billingCycle:ry.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"),iy=_d.safeExtend({requestId:h.uuid()}),Ad={control:h.literal("overage"),requestId:h.uuid(),internal_feature_id:h.uuid(),entityId:h.uuid().nullable()},oy=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([iy,oy]),ay=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()}),sy=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"),cy=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(ay).max(100).optional(),windows:h.array(sy).max(200),autoTopups:h.array(cy).max(100),limited:h.boolean()}).strict(),uy=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(uy).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()}),ly=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:ly.nullable(),grants:h.array(h.strictObject({id:h.uuid(),couponId:h.uuid(),name:h.string(),discount:Jn,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 Zn}from"zod";var Md=Zn.strictObject({itemKey:Zn.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:Zn.uuid(),includedAmount:Zn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Zn.number().int().min(0).max(1e4),terms:Do,pricing:Pi.optional(),unitAmountMinor:Zn.number().int().min(0).max(1e8),productId:Zn.string().min(1).max(255).nullable(),priceId:Zn.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}),dy=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",[dy,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)}),py=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",[py,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()}),my=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:my})).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 fy=hn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),gy=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:fy.nullable(),remaining:gy.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}),hy=T.enum(["access","metered","credit"]),Li={internal_feature_id:T.uuid(),key:yr,name:T.string().min(1).max(120),kind:hy},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},Ay=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(Ay).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"]),cO=ue.enum(["resend","twilio","fcm","apns"]);var uO=ue.string().regex(/^\+[1-9]\d{1,14}$/),yy=ue.enum(["email_recipient","sms_segment","voice_second","push_device"]);var by=ue.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Sy=ue.strictObject({subject:by,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"}),xy=ue.strictObject({body:ue.string().min(1).max(1600).refine(e=>e.trim().length>0)}),Iy=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)}),vy=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"),wy=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:vy.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:Sy}),ue.strictObject({channel:ue.literal("sms"),content:xy}),ue.strictObject({channel:ue.literal("voice"),content:Iy}),ue.strictObject({channel:ue.literal("push"),content:wy})]),ip=ue.strictObject({requestId:ue.uuid(),customerId:ue.uuid(),connectionId:ue.uuid().optional(),message:rp,expiresAt:ue.iso.datetime({offset:!0})}),Oy=ue.array(ue.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),_y=ue.discriminatedUnion("kind",[ue.strictObject({kind:ue.literal("all")}),ue.strictObject({kind:ue.literal("customers"),customerIds:Oy})]),lO=ue.strictObject({name:ue.string().trim().min(1).max(120),connectionId:ue.uuid().optional(),message:rp,audience:_y,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"]),dO=ue.strictObject({meter:yy,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 Cy}from"zod";import{z as Zr}from"zod";var cp=Zr.enum(["stripe","apple","google","merchant"]),up=Zr.enum(["membership","credit_pack","lifetime"]),AO=Zr.enum(["active","grace","suspended","inactive","revoked"]),yO=Zr.strictObject({currency:Zr.string().regex(/^[A-Z]{3}$/),micros:Zr.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var Wr=Cy.object({provider:cp,currency:he}).strict();var Wn=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:Wn,commerce:Wr.optional(),paywallId:nt.uuid().optional()}),Py=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:Py.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"})}),PO=nt.strictObject({paywallId:nt.uuid(),requirement:Wn});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 b}from"zod";function Ey(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(Ey(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 Ry=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],fp=oe.enum(Ry),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(),ky=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(),jy=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(ky).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}$/),jy)}).strict(),BO=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 Ny=4,bn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Hi=b.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Te=b.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Dy=b.enum(["none","xs","sm","md","lg","xl"]),Fy=b.enum(["none","sm","md","lg","full"]),Ys=b.string().regex(/^#[0-9a-fA-F]{6}$/),Sp=b.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=b.union([Sp,b.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),b.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),b.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),yp=b.object({primary:Ys,background:Ys,text:Ys,radius:Fy,font:b.enum(["system","serif","rounded","mono"])}).strict(),Qi=b.union([b.enum(["primary","text","muted","background","surface"]),b.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),je=(e,t)=>b.number().int().min(e).max(t),bp=b.union([b.enum(["fit","fill"]),je(1,1200)]),My=b.object({top:je(0,200),right:je(0,200),bottom:je(0,200),left:je(0,200)}).strict(),qy=b.object({top:je(-100,200),right:je(-100,200),bottom:je(-100,200),left:je(-100,200)}).strict(),xp=b.object({x:je(0,100),y:je(0,100)}).strict(),Vy=b.discriminatedUnion("type",[b.object({type:b.literal("color"),color:Qi}).strict(),b.object({type:b.literal("linear"),angle:je(0,360),stops:b.array(b.object({color:Qi,at:je(0,100)}).strict()).min(2).max(4)}).strict(),b.object({type:b.literal("image"),src:Xs,fit:b.enum(["cover","contain"]),position:xp.optional()}).strict()]),By=b.discriminatedUnion("type",[b.object({type:b.literal("rect"),radius:b.union([je(0,200),b.object({topLeft:je(0,200),topRight:je(0,200),bottomRight:je(0,200),bottomLeft:je(0,200)}).strict()])}).strict(),b.object({type:b.literal("pill")}).strict()]),Uy=b.object({width:je(0,12),color:Qi,style:b.enum(["solid","dashed"])}).strict(),Ly=b.object({x:je(-40,40),y:je(-40,40),blur:je(0,80),spread:je(-20,40),color:Qi}).strict(),zy=b.object({font:b.enum(["system","serif","rounded","mono"]),size:je(8,96),weight:b.number().int().min(100).max(900).multipleOf(100),lineHeight:b.number().min(.8).max(3),letterSpacing:b.number().min(-5).max(20),color:Qi,align:b.enum(["start","center","end"]),italic:b.boolean(),decoration:b.enum(["none","underline","line-through"]),transform:b.enum(["none","uppercase"])}).strict().partial(),wr=b.object({width:bp,height:bp,padding:My,margin:qy,gap:je(0,120),grow:b.union([b.boolean(),b.number().min(0).max(12)]),background:Vy,opacity:b.number().min(0).max(1),clipContent:b.boolean(),shape:By,border:Uy,shadow:Ly,text:zy}).strict().partial(),Jt={id:Hi,name:b.string().trim().min(1).max(60).optional(),hidden:b.boolean().optional(),style:wr.optional(),fallback:Te.optional()},$y=b.object({...Jt,type:b.literal("text"),productField:b.enum(["name","price","trial","period"]).optional(),feature:b.object({id:b.uuid(),field:b.enum(["name","allowance"])}).strict().optional(),text:Te,variant:b.enum(["title","heading","body","caption"])}).strict(),Gy=b.object({...Jt,type:b.literal("image"),src:Xs,localizedSrc:b.record(gn,Xs).optional(),alt:Te,aspect:b.enum(["auto","1:1","4:3","16:9","3:1"]),fit:b.enum(["cover","contain"]),position:xp.optional()}).strict(),Ky=b.object({...Jt,type:b.literal("button"),label:Te,variant:b.enum(["primary","secondary","link"]),action:Te,purpose:b.enum(["purchase","navigation","close"]).optional(),bind:ea.optional()}).strict(),Hy=b.object({...Jt,type:b.literal("divider")}).strict(),Qy=b.object({...Jt,type:b.literal("customer_data"),title:Te,data:gp}).strict(),Jy=b.object({...Jt,type:b.literal("spacer"),size:Dy}).strict(),Zy=b.object({...Jt,type:b.literal("custom_html"),html:b.record(gn,b.string().max(bn.customHtml)),css:b.string().max(bn.customCss)}).strict(),Wy=b.object({...Jt,type:b.literal("price"),fallback:Te,parts:b.object({current:wr.optional(),original:wr.optional(),period:wr.optional()}).strict().optional()}).strict(),Yy=b.object({...Jt,type:b.literal("coupon_code"),label:Te,fallback:Te}).strict(),Xy=b.object({...Jt,type:b.literal("countdown"),source:b.enum(["offer.ends_at","offer.expires_at","fixed"]),at:b.iso.datetime().optional(),granularity:b.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"),eb=b.object({...Jt,type:b.literal("plan_picker"),label:Te,fallback:Te,planIds:b.array(b.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:b.string().min(1).max(200).optional(),grouping:ta.safeExtend({monthLabel:Te,yearLabel:Te,unavailableLabel:Te}).optional(),states:b.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"})}),tb=b.object({...Jt,type:b.literal("quantity_picker"),bind:ea.optional(),label:Te,fallback:Te,internalFeatureId:b.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"),nb=b.discriminatedUnion("type",[b.object({type:b.literal("input"),label:Te,keyboard:b.enum(["text","email","tel","url"]),maxLength:je(1,500)}).strict(),b.object({type:b.literal("multiselect"),label:Te,min:je(0,50),max:je(1,50)}).strict(),b.object({type:b.literal("select"),label:Te,defaultIndex:je(0,49),purpose:b.enum(["option","product","tier"]).optional(),pickerId:Hi.optional(),selectedStyle:wr.optional()}).strict(),b.object({type:b.literal("tabs"),label:Te,defaultIndex:je(0,49),purpose:b.literal("tier").optional()}).strict(),b.object({type:b.literal("toggle"),label:Te,defaultEnabled:b.boolean()}).strict(),b.object({type:b.literal("carousel"),label:Te}).strict()]),yn={...Jt,type:b.literal("stack"),direction:b.enum(["vertical","horizontal","overlay"]),align:b.enum(["start","center","end","stretch"]),justify:b.enum(["start","center","end","between"]),productSlot:b.object({index:je(0,19),period:b.enum(["month","year"]).optional(),requireBinding:b.boolean().optional()}).strict().optional(),interaction:nb.optional(),states:b.object({selected:wr.optional()}).strict().optional(),purpose:b.literal("benefits").optional(),purchaseAction:Te.optional(),buttonVariant:b.enum(["primary","secondary","link"]).optional(),bind:ea.optional()},Ip=b.lazy(()=>b.object({...Jt,type:yn.type,direction:yn.direction,align:yn.align,justify:yn.justify,children:b.array(rb).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()),rb=b.lazy(()=>b.union([Ip,$y,Gy,Ky,Hy,Jy,Zy,Wy,Yy,Xy,eb,tb,Qy])),ib=b.union([b.string().max(500),b.number().finite(),b.boolean(),b.null()]),Ki={id:Te,event:Te,properties:b.record(Te,ib).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ob=b.discriminatedUnion("type",[b.object({...Ki,type:b.literal("navigate"),close:b.literal(!1),pageId:Hi}).strict(),b.object({...Ki,type:b.literal("event"),close:b.boolean()}).strict(),b.object({...Ki,type:b.literal("close"),close:b.literal(!0)}).strict(),b.object({...Ki,type:b.literal("open_url"),close:b.boolean(),url:Sp}).strict(),b.object({...Ki,type:b.literal("claim_offer"),close:b.boolean(),couponId:b.uuid()}).strict()]),ab=b.object({defaultLocale:gn,locales:b.record(gn,b.record(Te,b.string().max(bn.stringLength)))}).strict(),sb=b.enum(["popup","paywall","onboarding","page","banner"]);var cb=b.discriminatedUnion("type",[b.object({type:b.literal("modal"),size:b.enum(["sm","md","lg"])}).strict(),b.object({type:b.literal("sheet"),size:b.enum(["sm","md","lg"])}).strict(),b.object({type:b.literal("fullscreen")}).strict(),b.object({type:b.literal("inline")}).strict()]);var ub=b.object({kind:b.literal("screen"),schemaVersion:b.literal(Ny),name:b.string().trim().min(1).max(80),surface:sb,initialPageId:Hi.optional(),presentation:cb,theme:yp,pages:b.array(b.object({id:Hi,name:b.string().trim().min(1).max(60),root:Ip,theme:yp.optional(),editorPosition:b.object({x:b.number().finite().min(-1e5).max(1e5),y:b.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(bn.pages),strings:ab,actions:b.array(ob).max(bn.actions)}).strict();function Vt(e,t){for(let n of e.pages)Yn(n.root,t)}var nn=ub.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(d=>d.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let d of e.actions)d.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===d.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=d=>t.addIssue({code:"custom",message:d}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>bn.locales&&r(`\u6700\u591A ${bn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let d of e.actions)a.has(d.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${d.id}`),a.add(d.id);let o=new Set;for(let d of e.pages)["next","back"].includes(d.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${d.id}`),o.has(d.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${d.id}`),o.add(d.id);let s=new Set,c=0,u=!1;Vt(e,(d,m)=>{if(c++,m>bn.depth&&(u=!0),s.has(d.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${d.id}`),s.add(d.id),d.type==="button"&&!a.has(d.action)&&r(`\u6309\u94AE ${d.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${d.action}`),d.type==="custom_html")for(let w of Object.keys(d.html))i.includes(w)||r(`\u81EA\u5B9A\u4E49 HTML ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`);if(d.type==="image")for(let w of Object.keys(d.localizedSrc??{}))i.includes(w)||r(`\u56FE\u7247 ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${bn.depth} \u5C42`)});function Yn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Yn(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 lb(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=>!lb(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 db(e,t){let n=null;return Yn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Ji(e,t){for(let n of e.pages){let r=db(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})])}),WO=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 d of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,d)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(d)||Number(d)>=u.length)){c=!1;break}u=u[d]}}if(!(!c||u===void 0)){if(!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]/),d=c.replace(/^-/,""),m=d.replace(".","").length,w=(d.includes(".")?d.indexOf("."):m)+Number(u),I=w<=0?2-w+m:w>=m?w:m+1;n+=I+(c.startsWith("-")?1:0)-s.length}}return n}var er=ve.enum(["page","popup","banner"]),pb=3e5,Op=ve.strictObject({type:ve.enum(["string","number","boolean","strings","json"]),nullable:ve.boolean()}),mb=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")}),fb=ve.strictObject({kind:er,schemaVersion:ve.literal(1),name:ve.string().trim().min(1).max(80),screen:nn,contract:mb}),aa=fb.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)>pb&&n("Content document exceeds its byte budget",[])});function gb(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 hb=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&&!gb(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})}),p_=_p.extend({draft:aa}),m_=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:hb,createdAt:ve.iso.datetime({offset:!0})}),f_=ac.omit({document:!0}),g_=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 Fe}from"zod";import{z as Ze}from"zod";var S_=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()})]),x_=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"})}),I_=Ze.record(Ze.uuid(),ri).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var sc=Fe.object({type:Fe.literal("native_purchase"),receiptId:Fe.uuid(),orderId:Fe.uuid(),productVersionId:Fe.uuid(),provider:Fe.enum(["apple","google"]),productId:Fe.string().min(1).max(255),productKind:up,replacement:Fe.strictObject({sourceOrderId:Fe.uuid(),sourceProductId:Fe.string().min(1).max(255),policy:Fe.enum(["apple_store","google_full_price"]),sourceAccountTokens:Fe.array(Fe.uuid()).max(50)}).nullable(),appAccountToken:Fe.uuid().optional(),obfuscatedAccountId:Fe.string().min(1).max(64).optional(),obfuscatedProfileId:Fe.uuid().optional(),basePlanId:Fe.string().min(1).max(255).optional(),offerId:Fe.string().min(1).max(255).optional(),offerKind:Fe.enum(["none","introductory","promotional"]),currency:he,catalogAmountMinor:Fe.number().int().nonnegative().max(1e8),discountMinor:Fe.number().int().nonnegative().max(1e8),trialDays:Fe.number().int().min(1).max(730).nullable(),seatBundle:Fe.array(Fe.strictObject({key:Fe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Fe.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Fe.strictObject({offerId:Fe.string().min(1).max(255),keyId:Fe.string().min(1).max(255),nonce:Fe.uuid(),signature:Fe.string().min(1).max(1024),timestamp:Fe.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 l}from"zod";import{z as we}from"zod/v4";import{z as Ab}from"zod/v4";var yb=Ab.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:bb}=(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:Sb}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(yb),{COMMON:Ep}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:xb}={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:Ib}=(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:vb}=(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:wb}={Infinite:"inf"},{TierBehavior:Ob}=(()=>{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:_b}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Cb}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Pb}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Eb}=(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:Rb}={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:kb}=((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:jb}=(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:Tb}=(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:Nb}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(we),{CreateInvoicePreviewLineSchema:Db}=(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:cc}=(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:Fb}=(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:Mb}=((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,bb),{CURRENCY_CODES:qb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Ep,xb,Ib),{ApiPriceProcessorsSchema:Fp}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(we,vb),{AllocatedBillingFieldSchema:Vb}=((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,_b),{CreditDimensionNameSchema:Bb}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(we,Cb,Pb),{ApiCreditMatchSchema:Mp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Eb),{findCreditTierViolations:Ub}=(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}}))(Rb),{ApiCreditMultiplierSchema:Lb}=((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,Mp),{ProviderMarkupsSchema:zb}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(we,Np),{InvoiceFeatureQuantitySchema:qp}=((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,jb),{CreateInvoicePreviewSchema:uc}=((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,Db),{SUPPORTED_SET:$b}=(e=>({SUPPORTED_SET:new Set(e)}))(qb),{ApiCreditDimensionBaseSchema:Gb}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(we,Mp),{refineGraduatedTiers:Vp}=(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"]})}}))(Ub),{ApiFeatureMarkupsOverrideSchema:Kb}=((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,zb,kb),{isValidCurrencyCode:Hb}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))($b),{ApiCreditDimensionSchema:Qb}=((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,Gb,Tp,Vp),{CurrencyCodeSchema:Bp}=((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,Hb),{AdditionalCurrencyTierSchema:Jb}=((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,Bp),{ApiCreditSchemaItemBaseSchema:Up}=((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,Bb,Qb,Lb),{ApiFlatCreditSchemaItemSchema:Zb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Up,we),{AdditionalCurrencyPriceSchema:Wb}=((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,Bp),{AdditionalCurrencyTierArraySchema:Yb}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(we,Jb,Rp,kp),{ApiGraduatedCreditSchemaItemSchema:Xb}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Up,we,Tp,Vp),{AdditionalCurrencyPriceArraySchema:Lp}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(we,Wb,Rp,kp),{ApiUsageTierWithCurrenciesSchema:eS}=((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,wb,Yb),{ApiCreditSchemaItemSchema:tS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(we,Xb,Zb),{BasePriceParamsSchema:nS}=((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."})}))(Mb,Sb,we,Lp),{PlanItemPriceParamsSchema:rS}=((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,Lp,eS,Ob,Pp,jp,Vb),{ApiFeatureOverrideSchema:iS}=((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,tS,Kb),{InvoiceBasePriceParamsSchema:zp}=((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()}))(nS,Fp),{InvoiceItemPriceParamsSchema:oS}=((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()}))(rS,Fp),{InvoiceLicenseQuantitySchema:aS}=((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,zp,qp),{InvoiceCustomizeItemSchema:sS}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(we,oS,iS),{InvoiceCustomizeSchema:cS}=((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,zp,sS),{InvoicePlanParamsSchema:uS}=((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,cS,qp,aS,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,uS,Tb,Dp,Nb);var Kp=l.strictObject({requestId:l.uuid(),predecessorOperationId:l.uuid().optional(),invoiceMode:_r.optional(),entityId:l.uuid().optional(),billingSubscriptionId:l.uuid().optional(),newBillingSubscription:l.literal(!0).optional(),offerId:l.uuid().optional(),nativeOffer:ri.optional(),plans:l.array(l.strictObject({productVersionId:l.uuid(),seatQuantities:l.record(Eo,l.number().int().min(0).max(1e4)).optional(),featureQuantities:l.record(l.uuid(),l.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:l.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=l.strictObject({operationId:l.uuid()}),Pt=l.number().int().min(0).max(1e8),lS=l.strictObject({lineId:l.uuid(),productVersionId:l.uuid(),productName:l.string().min(1).max(80),interval:l.enum(["free","week","month","year","one_time"]),intervalCount:l.number().int().min(1).max(156).optional(),baseAmountMinor:Pt,seats:l.array(l.strictObject({key:Eo,quantity:l.number().int().min(0).max(1e4),includedQuantity:l.number().int().min(0).max(1e4),maximumQuantity:l.number().int().min(0).max(1e4),unitAmountMinor:Pt})).max(20),prepaid:l.array(Md).max(100).optional(),catalogAmountMinor:Pt,trial:l.strictObject({days:l.number().int().min(1).max(730),cardRequired:l.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"),Hp=l.string().regex(/^[A-Za-z0-9_-]{1,200}$/),dS=l.strictObject({id:Hp,name:l.string().min(1).max(40),percent_off:l.number().gt(0).max(100).optional(),amount_off:l.number().int().positive().optional(),currency:l.string().regex(/^[a-z]{3}$/).optional(),duration:l.enum(["once","repeating","forever"]),duration_in_months:l.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"),pS=l.strictObject({subscriptionId:l.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:l.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:l.array(l.strictObject({id:l.string(),price_id:l.string(),quantity:l.number().int().nonnegative(),discounts:l.array(l.strictObject({id:l.string(),coupon:l.string(),start:l.number(),end:l.number().nullable()})).optional()})).min(1).max(100),prorationDate:l.number().int().nonnegative(),amountMinor:l.number().int().positive(),periodStartMs:l.number(),periodEndMs:l.number()}),Qp=l.strictObject({invoiceMode:_r.optional(),append:pS.optional(),provider:l.literal("stripe"),executor:l.enum(["indiana","merchant"]),accountId:l.string().regex(/^acct_[A-Za-z0-9]+$/),mode:l.enum(["payment","subscription"]),lineItems:l.array(l.strictObject({price:l.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:l.number().int().min(1).max(1e4),priceId:l.uuid(),productName:l.string().min(1).max(80),amountMinor:l.number().int().min(0).max(1e8),currency:l.string().regex(/^[a-z]{3}$/),interval:l.enum(["week","month","year","one_off"]),intervalCount:l.number().int().min(1).max(52),slot:l.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:l.strictObject({mode:l.enum(["graduated","volume"]),tiers:l.array(l.strictObject({upTo:l.number().int().min(1).max(1e6).nullable(),unitAmountMinor:l.number().int().min(0).max(1e8),flatAmountMinor:l.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:l.array(l.strictObject({coupon:Hp,terms:dS})).max(1),trialPeriodDays:l.number().int().min(1).max(730).nullable(),metadata:l.strictObject({grooveCheckoutId:l.uuid(),grooveCustomerId:l.uuid()}),expiresAt:l.iso.datetime({offset:!0})}),oi=l.strictObject({operationId:l.uuid(),entityId:l.uuid().nullable(),billingSubscriptionId:l.uuid().nullable(),discount:l.strictObject({offerId:l.uuid(),couponId:l.uuid(),discount:Jn,duration:en,amountMinor:Pt,allocations:l.array(l.strictObject({productVersionId:l.uuid(),amountMinor:Pt})).min(1).max(20),expiresAt:l.iso.datetime({offset:!0})}).nullable(),charge:l.strictObject({effectiveAt:l.iso.datetime({offset:!0}),periodEndsAt:l.iso.datetime({offset:!0}),debitMinor:Pt,discountMinor:Pt,taxMinor:Pt,totalMinor:Pt}).nullable(),expiresAt:l.iso.datetime({offset:!0}),provider:l.enum(["stripe","apple","google","merchant"]),nativeOffer:ri.optional(),currency:he,lines:l.array(lS).min(1).max(20),catalogAmountMinor:Pt,automaticTax:l.boolean(),execution:l.union([Qp,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=l.strictObject({operationId:l.uuid(),orderId:l.uuid(),append:l.boolean().optional(),invoiceMode:l.boolean().optional(),status:l.enum(["pending","complete","cancelled","failed"]),executor:l.enum(["indiana","merchant"]),checkoutUrl:l.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:l.union([Qp,wo]).nullable(),currency:he,catalogAmountMinor:Pt,taxMinor:Pt,totalMinor:l.number().int().min(0).max(2e8).nullable(),quoteFinalized:l.boolean(),nativePurchase:sc.nullable(),confirmedAt:l.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=l.strictObject({enabled:l.literal(!0),featureIds:l.array(l.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Jp=l.strictObject({requestId:l.uuid(),invoiceMode:_r.optional(),membershipId:l.uuid(),carryOverBalances:ca.optional(),carryOverUsages:ca.optional(),membershipIds:l.array(l.uuid()).min(1).max(20).optional(),prorationBehavior:l.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:l.enum(["immediate","renewal","store"]),change:l.discriminatedUnion("type",[l.strictObject({type:l.literal("plan"),productVersionId:l.uuid()}),l.strictObject({type:l.literal("seats"),licenseKey:Eo,quantity:l.number().int().min(0).max(1e4)}),l.strictObject({type:l.literal("quantity"),internal_feature_id:l.uuid(),quantity:l.number().int().min(0).max(1e4)}),l.strictObject({type:l.literal("cancel")}),l.strictObject({type:l.literal("uncancel")}),l.strictObject({type:l.literal("billing_cycle"),billingCycleAnchor:l.union([l.literal("now"),l.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=l.string().regex(/^price_[A-Za-z0-9]+$/),$p=l.strictObject({grooveUpdateId:l.uuid(),grooveCustomerId:l.uuid()}),Gp=l.strictObject({price:sa.nullable(),priceId:l.uuid().optional(),quantity:l.number().int().min(0).max(1e4)}),Zp=l.strictObject({provider:l.literal("stripe"),invoiceMode:_r.optional(),executor:l.enum(["indiana","merchant"]),accountId:l.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:l.string().regex(/^sub_[A-Za-z0-9]+$/),action:l.enum(["update","cancel","schedule","release"]),update:l.strictObject({items:l.array(Gp).max(20),remove:l.array(sa).max(20),restoreItems:l.array(l.strictObject({price:sa,quantity:l.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:l.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:l.number().int().positive().optional(),paymentBehavior:l.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:l.boolean().optional(),clearCancelAt:l.literal(!0).optional(),billingCycleAnchorNow:l.literal(!0).optional(),metadata:$p}).nullable(),cancel:l.strictObject({prorate:l.literal(!1),invoiceNow:l.literal(!1)}).nullable(),schedule:l.strictObject({currentItems:l.array(l.strictObject({price:sa,quantity:l.number().int().min(0).max(1e4)})).max(20),nextItems:l.array(Gp).min(1).max(20),switchAt:l.number().int().positive(),interval:l.enum(["week","month","year"]),intervalCount:l.number().int().min(1).max(52),resetBillingCycleAnchor:l.literal(!0).optional(),metadata:$p}).nullable(),release:l.strictObject({schedule:l.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:l.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=l.strictObject({carryOverBalances:ca.optional(),carryOverUsages:ca.optional(),operationId:l.uuid(),membershipId:l.uuid(),productVersionId:l.uuid(),timing:l.enum(["immediate","renewal"]),effectiveAt:l.iso.datetime({offset:!0}),expiresAt:l.iso.datetime({offset:!0}),currency:he,creditMinor:Pt,debitMinor:Pt,discountMinor:Pt,taxMinor:Pt,totalMinor:Pt,retainedProductVersionIds:l.array(l.uuid()).max(19),execution:l.union([Zp,Oo])}),mS=l.strictObject({operationId:l.uuid(),invoiceMode:l.boolean().optional(),membershipId:l.uuid(),productVersionId:l.uuid(),status:l.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:l.enum(["immediate","renewal"]),effectiveAt:l.iso.datetime({offset:!0}),checkoutUrl:l.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:l.enum(["indiana","merchant"]),execution:l.union([Zp,Oo]).nullable(),confirmedAt:l.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"),fS=l.strictObject({operationId:l.uuid(),membershipId:l.uuid(),productVersionId:l.uuid(),timing:l.literal("store"),effectiveAt:l.null(),expiresAt:l.iso.datetime({offset:!0}),currency:he,creditMinor:l.null(),debitMinor:l.null(),discountMinor:l.null(),taxMinor:l.null(),totalMinor:l.null(),retainedProductVersionIds:l.array(l.uuid()).max(19),store:l.strictObject({provider:l.enum(["apple","google"]),productId:l.string().min(1).max(255),catalogAmountMinor:Pt,policy:l.enum(["apple_store","google_full_price"])})}),gS=l.strictObject({operationId:l.uuid(),membershipId:l.uuid(),productVersionId:l.uuid(),status:l.enum(["prepared","pending","effective","cancelled","failed"]),timing:l.literal("store"),effectiveAt:l.iso.datetime({offset:!0}).nullable(),checkoutUrl:l.null(),nativePurchase:sc.nullable()}),Wp=l.union([ua,fS]),lc=l.union([mS,gS]),Zi=l.number().int().positive().max(2e8),Cr=l.number().int().min(0).max(2e8),Yp=l.strictObject({requestId:l.uuid(),invoiceId:l.uuid(),mode:l.enum(["full","partial"]),amountMinor:Zi.optional(),entitlementAction:l.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Xp=l.strictObject({provider:l.literal("stripe"),executor:l.enum(["indiana","merchant"]),accountId:l.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:l.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Zi,currency:l.string().regex(/^[a-z]{3}$/),metadata:l.strictObject({indianaRefundId:l.uuid()}),idempotencyKey:l.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:l.array(l.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),dc=l.strictObject({operationId:l.uuid(),invoiceId:l.uuid(),providerInvoiceId:l.string().min(1).max(200),currency:he,paidMinor:Cr,refundedMinor:Cr,pendingMinor:Cr,amountMinor:Zi,mode:l.enum(["full","partial"]),entitlementAction:l.enum(["retain","revoke"]),revokes:l.strictObject({customerProductIds:l.array(l.uuid()).max(100),subscriptionIds:l.array(l.string().min(1).max(200)).max(20)}),execution:l.union([Xp,_o]),expiresAt:l.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=l.strictObject({operationId:l.uuid(),invoiceId:l.uuid(),providerInvoiceId:l.string().min(1).max(200),status:l.enum(["quoted","pending","succeeded","failed","expired"]),executor:l.enum(["indiana","merchant"]),currency:he,amountMinor:Zi,mode:l.enum(["full","partial"]),entitlementAction:l.enum(["retain","revoke"]),refundId:l.string().min(1).max(200).nullable(),quote:dc.optional(),execution:l.union([Xp,_o]).nullable(),confirmedAt:l.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:hr.nullable().optional(),problem:_i.nullable().optional(),authority:Po.optional(),failureReason:l.string().min(1).max(200).nullable(),createdAt:l.iso.datetime({offset:!0}),completedAt:l.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"),L_=l.strictObject({invoiceId:l.uuid(),currency:he,paidMinor:Cr,refundedMinor:Cr,pendingMinor:Cr,refundableMinor:Cr,executor:l.enum(["indiana","merchant"]).nullable(),canRefund:l.boolean(),operations:l.array(la).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),z_=l.strictObject({requestId:l.uuid(),mode:l.enum(["full","partial"]),amountMinor:Zi.optional(),entitlementAction:l.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 em=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()}),hS=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(hS).min(1).max(100)});import{z as Pe}from"zod";var AS=Pe.string().trim().min(1).max(240),pc={requestId:Pe.uuid(),reason:AS},pa=Pe.discriminatedUnion("action",[Pe.strictObject({...pc,action:Pe.literal("start"),productVersionId:Pe.uuid(),entityId:Pe.uuid().optional(),days:Pe.number().int().min(1).max(730).optional()}),Pe.strictObject({...pc,action:Pe.literal("extend"),membershipId:Pe.uuid(),days:Pe.number().int().min(1).max(730)}),Pe.strictObject({...pc,action:Pe.literal("end"),membershipId:Pe.uuid()})]),tm=Pe.strictObject({operationId:Pe.uuid()}),nm=Pe.iso.datetime({offset:!0}),yS=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"),nm]),prorationBehavior:Pe.literal("none")}),mc=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:nm.nullable(),execution:yS.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"),J_=Pe.strictObject({groupId:Pe.uuid(),productVersionId:Pe.uuid(),enabled:Pe.boolean()});import{z as Qe}from"zod";var rm=Qe.strictObject({requestId:Qe.uuid(),currency:he,makeDefault:Qe.boolean()}),im=Qe.strictObject({setupId:Qe.uuid()}),bS=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})}),fc=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:bS.nullable()});import{z as Et}from"zod";var om=Et.union([Et.string(),Et.number(),Et.boolean(),Et.null()]),am=Et.strictObject({customerId:Et.uuid()}),sm=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:om,actual:om})).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()}),gc={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},SS=ye.strictObject({...gc,status:ye.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:ye.boolean(),billingSubscriptionId:ye.uuid().nullable()}),xS=ye.strictObject({...gc,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()}),IS=ye.strictObject({...gc,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()}),cm=ga.extend({status:ye.enum(["blocked","resolved"]).optional()}),um=ye.strictObject({customerId:ye.uuid(),orderId:ye.uuid()}),lm=ye.strictObject({orderId:ye.uuid(),status:ye.enum(["blocked","resolved"])}),dm=ye.strictObject({items:ye.array(SS).max(100),nextCursor:fa.nullable()}),pm=ye.strictObject({items:ye.array(xS).max(100),nextCursor:fa.nullable()}),mm=ye.strictObject({items:ye.array(IS).max(100),nextCursor:fa.nullable()});import{z as Ye}from"zod";var fm=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)})]),gm=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 Ac=L.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),vS=L.record(L.string(),L.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),wS=3,Yi=20,OS=wS*Yi,hc=L.strictObject({type:L.literal("product"),productId:Ac}),hm={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)},_S=L.discriminatedUnion("type",[hc,L.strictObject({...hm,items:L.array(hc).max(Yi)})]),CS=L.discriminatedUnion("type",[hc,L.strictObject({...hm,items:L.array(_S).max(Yi)})]),PS=L.array(CS).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>OS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function yc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:yc(t))}var si=L.strictObject({lookupKey:L.string().trim().min(1).max(200),displayName:L.string().trim().min(1).max(1500),items:PS,metadata:vS}),ES=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()))}),Am=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"})}),ym=L.strictObject({id:L.uuid(),offeringId:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),version:L.number().int().positive(),document:si,productEvidence:L.record(Ac,ES),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=yc(e.document);(!n.length||jS(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"})}),RS=L.strictObject({rows:L.array(Am).max(200),versions:L.array(ym).max(500)}),u1=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()})]),l1=L.strictObject({record:Am,version:ym.nullable()}),bm=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()})]),kS=L.strictObject({internalId:Ac,id:L.string(),name:L.string().nullable(),version:L.number().int().positive(),archived:L.boolean()}),d1=RS.extend({products:L.array(kS).max(500),pagination:L.strictObject({rows:L.string().nullable(),versions:L.string().nullable(),products:L.string().nullable()}).optional()});function jS(e){let t=[];yc(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 Sm=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 xm(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 TS=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:TS,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")]),Vn=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 bc=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:")})]),NS=nn,DS=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:bc}).strict()]),ui=de.object({schemaVersion:de.literal(3),kind:de.literal("paywall"),name:de.string().trim().min(1).max(80),presentation:Vn,requirement:Wn.optional(),products:Aa,offeringVersionId:de.uuid().nullable(),offeringId:de.uuid(),screen:NS,buttons:de.record(de.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),DS)}).strict(),P1=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 MS(e))t.addIssue({code:"custom",message:r});for(let r of FS(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 FS(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 d=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(d)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),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 MS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Yn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let d=e.screen.actions.find(w=>w.id===u);d?.type==="navigate"&&r.get(s.id).push(d.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Im=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(),E1=de.object({rows:de.array(Im).max(200),nextCursor:de.uuid().nullable()}).strict(),R1=Im.omit({draft:!0}).extend({name:de.string(),productCount:de.number().int().nonnegative()}).strict(),k1=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()]),j1=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:Vn,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}$/),qS=Xo.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),vm=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:qS})),plans:Bt.object({}).strict(),pickers:Bt.object({}).strict()}).omit({paywall:!0}))});import{z as Me}from"zod";import{z as ba}from"zod";var Sc=ba.strictObject({eventsEnabled:ba.boolean(),experimentViewsEnabled:ba.boolean(),featureUsageEnabled:ba.boolean()}),V1=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function wm(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var xc=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),VS=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(xc).max(100)}),BS=$.strictObject({id:$.string().min(1).max(255),condition:Ht,gate:$.boolean().optional()}),US=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),Om={condition:Ht.optional(),parentConditions:$.array(BS).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(VS).max(100).optional(),ranges:$.array(xc).max(20).optional(),meta:$.array(US).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},di=$.strictObject({...Om,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()}),Ic=$.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()}),LS=$.strictObject({...Om,id:$.string().max(255).optional(),force:Ae.optional(),variations:$.array(Ae).min(2).max(20).optional(),key:$.string().optional(),range:xc.optional(),tracks:$.array($.strictObject({experiment:di,result:Ic})).max(100).optional()}),zS=$.strictObject({defaultValue:Ae.optional(),rules:$.array(LS).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(),zS),savedGroups:Xi,experiments:$.record($.uuid(),di)});var eo=ln.extend({analyticsConfig:Sc,remoteFeatures:Me.array(Me.string().min(1).max(255)).max(500)}),vc=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"})}),_m=Me.strictObject({attributes:ht,features:Me.array(Me.string().min(1).max(255)).max(500).optional(),customerId:Me.uuid().optional()}),$S=Me.strictObject({value:Ae,source:Me.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Me.boolean(),off:Me.boolean(),ruleId:Me.string(),experimentResult:Ic.optional()}),Sa=Me.strictObject({generation:ln.shape.generation,evaluatedAt:ln.shape.evaluatedAt,expiresAt:ln.shape.expiresAt,features:Me.record(Me.string(),$S),merchandiseContext:Me.strictObject({merchandiseId:Me.uuid(),merchandise:ht}).optional()}),Cm=Me.strictObject({customerId:Me.uuid().optional(),events:Me.array(Me.strictObject({eventUuid:Me.uuid(),timestamp:Me.iso.datetime({offset:!0}),name:Me.string().min(1).max(255),merchandise:pd.optional(),properties:Me.record(Me.string(),Ae).default({}),deviceId:Me.string().min(1).max(255).optional(),sessionId:Me.string().min(1).max(255).optional()})).min(1).max(100)}),Pm=Me.strictObject({inserted:Me.number().int().nonnegative(),duplicates:Me.number().int().nonnegative(),rejected:Me.number().int().nonnegative(),skipped:Me.number().int().nonnegative(),analyticsConfig:Sc});import{z}from"zod";function wc(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 Em(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Em(t)??[])}}function GS(e){let t=e.pages.map(i=>{let a=Em(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 Rm(e,t=[]){let n=nn.parse(structuredClone(GS(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=wc(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"})}),km=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 KS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Oc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",HS=Er.string().regex(new RegExp(`^${Oc}/${Oc}/${Oc}/manifest\\.json$`)),jm=Er.strictObject({kind:Er.literal("gcs-resumable"),url:Er.url(),bucket:Er.enum(KS),objectKey:HS,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()}),Tm=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()])}),Nm=F.strictObject({versionId:F.uuid(),manifestDigest:on,sourceGraphDigest:on,pageKey:lt,stateKey:lt,documentKey:lt,documentHash:on,renderKey:lt.optional(),patches:F.array(Tm.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),QS=/^[a-z][a-z0-9-]{0,39}$/,to=F.string().regex(QS),Cc=F.enum(["web","ios","android"]),aC=F.discriminatedUnion("action",[F.strictObject({action:F.literal("register"),requestId:F.uuid(),client:to,platform:Cc,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(Tm).max(200)})]),Pc=F.strictObject({id:F.uuid(),projectId:F.uuid(),environmentId:F.uuid(),clientKey:to,platform:Cc,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())}),JS=F.strictObject({key:to,platform:Cc,currentId:F.uuid().nullable()}),sC=F.strictObject({rows:F.array(Pc).max(100),nextCursor:F.uuid().nullable(),clients:F.array(JS).max(20)}),_c=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()}),cC=F.strictObject({asOf:F.iso.datetime({offset:!0}),reclamation:F.literal("manual-review-required"),buckets:F.strictObject({source:_c,runtime:_c,previews:_c})}),uC=F.strictObject({version:Pc,actorId:F.uuid(),claims:F.record(F.string(),F.json())}),lC=F.strictObject({version:Pc,upload:jm.nullable()}),dC=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(km)}).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"})}),pC=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()}),mC=F.strictObject({enabled:F.boolean(),allowedOrigins:F.array(F.string())});import{z as pi}from"zod";var Dm=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 Ec=Ae,ZS=["parameters","answers","results","variables"];function Rc(e){return ZS.some(t=>e===t||e.startsWith(t+"."))}function kc(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])=>!Rc(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()]),WS=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"),YS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function jc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>jc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||YS.test(n)||jc(r,t+1)))}var XS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,nr=dt.record(WS,Ae).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!jc(e)&&!XS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var Fm=dt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),wa=dt.array(dt.object({variable:Fm,componentId:Fm,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"),OC=dt.object({bindings:wa,answers:tr,values:dt.record(dt.string(),Ae).optional()}).strict();import{z as ex}from"zod";var Oa=ex.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var Tc=ze.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Mm=ze.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),qm=nr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Nc=ze.record(Tc,ze.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),tx=_n,Vm=ze.strictObject({type:ze.literal("external_task"),endpointId:ze.uuid(),taskKey:Tc,inputs:ze.record(Tc,tx).refine(e=>Object.keys(e).length<=20),outputs:Nc}),Bm=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 DC=ze.strictObject({outcome:ze.enum(["success","failure"]),data:qm});var FC=ze.discriminatedUnion("operation",[ze.strictObject({operation:ze.literal("signal"),runId:ze.uuid(),nodeId:Mm,eventName:Oa,eventId:ze.uuid(),data:qm}),ze.strictObject({operation:ze.literal("read_results"),runId:ze.uuid()})]),MC=ze.strictObject({scope:Ue,runId:ze.uuid(),eventId:ze.uuid(),accepted:ze.boolean()}),nx=ze.record(Mm,Ec),qC=ze.strictObject({scope:Ue,runId:ze.uuid(),results:nx});var xn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},Um="00000000-0000-0000-0000-000000000000";import{z as J}from"zod";import{z as Je}from"zod";var $C=Je.enum(["local","remote"]),Dc=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)}),Lm=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)}),zm=Lm.extend({runId:Je.uuid(),versionId:Je.uuid(),nodeId:Je.string().min(1).max(64),visit:Je.number().int().nonnegative(),revision:Je.number().int().nonnegative()}),Fc=Lm.omit({type:!0,receiptId:!0}).extend({type:Je.literal("evaluate_segment")}),$m=Je.strictObject({nodeId:Je.string().min(1).max(64),result:Dc}),Gm=Fc.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 Mc=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:Mc.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"),Km=ae.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Hm=ae.object({externalUserId:Km.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:Km})]),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(),Qm=ae.object({customer:mi,changed:ae.boolean(),replayed:ae.boolean()}).strict(),rx=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()]),ix=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:Mc,remove:Mc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),qc=ae.object({lookup:rx}).strict(),Jm=qc.extend({requestId:ae.uuid(),patch:ix}).strict(),Zm=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(),Wm=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)})]),ox=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}),ax={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")},nP=J.discriminatedUnion("operation",[J.strictObject({operation:J.literal("decide"),...ax}).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:Dc}),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($m).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()})]),rP=J.strictObject({scope:Ue,decisionId:J.uuid(),requestId:J.uuid(),status:J.enum(["pending","completed","failed"]),decision:ox.nullable(),evaluation:J.discriminatedUnion("type",[zm,Gm]).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"),iP=J.strictObject({scope:Ue,decisionId:J.uuid(),eventId:J.uuid(),source:J.literal("caller_reported")});import{z as Rt}from"zod";var Ym=Rt.strictObject({type:Rt.literal("bundle"),paywall:_n.optional(),offering:_n.optional(),coupons:_n,data:_n}),sx=e=>Rt.strictObject({type:Rt.literal(e),id:Rt.uuid()}),lP=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 dP=Rt.strictObject({type:Rt.literal("bundle"),offering:sx("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 Xm=dn.union([dn.string(),dn.number().finite(),dn.boolean(),dn.null()]),cx=dn.union([Xm,dn.array(Xm).min(1).max(20)]),ux=dn.record(Sn,cx).refine(e=>Object.keys(e).length<=10),ef=dn.strictObject({path:Sn,type:dn.enum(["string","number","boolean","strings"]),nullable:dn.boolean().optional(),aggregation:dn.enum(["count","exists"]).optional(),where:ux.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 lx=["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"],tf=In.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),dx=_n,nf=In.discriminatedUnion("type",[Vm,In.strictObject({type:In.literal("claim_offer"),coupon:_n}),In.strictObject({type:In.literal("event"),event:tf}),In.strictObject({type:In.literal("api"),operation:In.enum(lx),inputs:In.record(Sn,dx).refine(e=>Object.keys(e).length<=40),outputs:In.record(tf,ef).refine(e=>Object.keys(e).length<=20)})]);var rt=Oa,px=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()},mx={success:rt,cancel:rt,unavailable:rt,failure:rt},Vc=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Bc=Q.enum(["same_window","new_window"]),fx=Q.discriminatedUnion("type",[Q.strictObject({...an,type:Q.literal("entry"),next:rt,triggers:Q.array(Dm).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:Vn,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,Ym,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(px,rt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:rt}),Q.strictObject({...an,type:Q.literal("action"),...mx,execution:Bm,action:nf,writes:tc.optional()}),Q.strictObject({...an,type:Q.literal("external_page"),appManifest:Ia.optional(),url:Vc,openIn:Bc,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:Nc,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:rt,timeout:rt})])})]),Uc=Q.strictObject({version:Q.literal(5),entry:rt,nodes:Q.array(fx).min(1).max(xn.flowNodes)}),Lc=Uc.superRefine((e,t)=>{gx(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 gx(e,t){let n=[],r=new Map(e.nodes.map(d=>[d.id,d])),i=(d,m,w)=>{n.push(d),t?.({message:d,reason:m,path:w?["nodes",e.nodes.indexOf(w)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(d=>d.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(d=>d.type==="screen").length>xn.pages||e.nodes.filter(d=>!["screen","entry","end","output"].includes(d.type)).length>xn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let d of e.nodes){for(let m of Da(d))m===e.entry&&i("An entry cannot be a transition target","entryTarget",d),r.has(m)||i(`Missing target ${m}`,"missingTarget",d);d.type==="screen"&&(a.has(d.screenId)&&i("Every screen has exactly one node owner","screenOwner",d),a.add(d.screenId))}let o=new Set,s=new Set,c=new Set;function u(d){if(o.has(d)){i("Flow edges must not form a cycle","cycle",r.get(d));return}if(!(s.has(d)||!r.has(d))){o.add(d),c.add(d);for(let m of Da(r.get(d)))u(m);o.delete(d),s.add(d)}}u(e.entry);for(let d of e.nodes)c.has(d.id)||i("Every node must be reachable from Entry","unreachable",d);return[...new Set(n)]}var zc={maxTransitions:1e4,runTimeoutSeconds:2592e3};function rf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(d=>s===d||c&&s.startsWith(d+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of Qn(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"),LP=M.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Gc=M.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Kc=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:Gc,selector:Kc.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"),of=M.strictObject({schemaVersion:M.literal(1),kind:Gc,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"),zP=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()},$c=M.iso.datetime({offset:!0}),$P=M.discriminatedUnion("type",[M.strictObject({type:M.literal("node_entered"),details:M.strictObject({kind:Gc})}),M.strictObject({type:M.literal("presentation_shown"),details:M.strictObject({...Rr,source:M.literal("client"),occurredAt:$c.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:$c})}),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:$c,reference:M.string().min(1).max(128).optional()})})]);var pn=z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),hx=z.discriminatedUnion("type",[z.strictObject({id:pn,type:z.literal("owned"),publicData:vm.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()})]),Hc={kind:z.literal("funnel"),schemaVersion:z.literal(4),screens:z.array(hx).max(xn.pages),references:z.record(pn,Kc).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(zc.runTimeoutSeconds),maxTransitions:z.number().int().min(1).max(zc.maxTransitions)})},uE=z.strictObject({...Hc,graph:Uc});function Ax(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===Um:qa(n))}function yx(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=Rm(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}),Ax(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 af(e,t){for(let{message:n,reason:r,path:i}of yx(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function sf(e,t){let n=(I,p,g=[])=>t.addIssue({code:"custom",message:I,path:g,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(I=>[I.id,I])),a=(I,p)=>r.some(g=>g.type===I&&("id"in g?g.id:g.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(I=>I.type==="screen");(o.length!==i.size||o.some(I=>!i.has(I.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(I=>c.some(p=>I!==p&&p.startsWith(I+".")))&&n("Variable paths must not overlap","variable");function u(I,p){Object.hasOwn(e.variables,I)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let g=s.get(I)??new Set;g.add(p.id),s.set(I,g)}for(let[I,p]of e.graph.nodes.entries()){let g=["graph","nodes",I],f=p.type==="feature"?p.featureKey:p.type==="offering"&&p.configuration.source==="feature"?p.configuration.featureKey:p.type==="output"&&p.value.type==="feature"?p.value.featureKey:p.type==="end"&&p.output?.type==="feature"?p.output.featureKey:null;f&&!a("flag",f)&&n("Flag selectors require an explicit GB resource reference","feature",g);let S=p.type==="feature"||p.type==="offering"||p.type==="coupon"||p.type==="coupons"||p.type==="action"&&p.action.type==="api"?["value"]:p.type==="action"&&p.action.type==="external_task"?Object.keys(p.action.outputs):p.type==="wait"&&p.wait.type==="event"?Object.keys(p.wait.outputs):[],A="writes"in p?p.writes??{}:{};(S.length!==Object.keys(A).length||S.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[v,k]of Object.entries(A)){u(k,p);let N=e.variables[k],B=p.type==="offering"?"offering_version":p.type==="coupon"?"reward":p.type==="action"&&p.action.type==="api"?"json":p.type==="action"&&p.action.type==="external_task"?p.action.outputs[v]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[v]:void 0;(N?.source.type!=="node"||B&&N.type!==B)&&n("Node writer source or output type does not match declaration","variable",g)}if(p.type==="coupons"){let v=e.variables[p.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let k of p.couponIds)a("reward",k)||n("Coupons require Reward references","coupon",g)}if(p.type==="split"&&!a("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),p.type==="coupon"&&!a("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let v=p.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!a("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),p.type==="screen"&&p.offering?.source==="variable"&&e.variables[p.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="variable"&&(e.variables[p.action.coupon.key]?.type!=="reward"||p.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",g),p.type==="screen"){let v=i.get(p.screenId);if(p.offering?.source==="fixed"&&!a("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),v?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",g),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),v?.type==="owned"){let k=v.document.pages[0];if(!k){n("Owned screen requires a page","screen",g);continue}Xn(v.document).some(B=>!B.complete)&&n("Owned screens require complete local content","translations",g);let N=new Set(v.document.actions.map(B=>B.id));(N.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(B=>!N.has(B)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),Yn(k.root,B=>{!p.offering&&(B.type==="plan_picker"||(B.type==="stack"||B.type==="button")&&B.bind?.plan||B.type==="customer_data"&&["customer_plans","credit_packs"].includes(B.data.source))&&n("Product presentation requires an Offering Version","offering",g),B.type==="customer_data"&&Object.values(B.data.outputs??{}).some(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 v=e.variables[P.key];v&&!nc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(p.type==="screen"){let v=i.get(p.screenId);if(v?.type==="owned")for(let k of oc(v.document))(/^(input|params)\./.test(k)||k.startsWith("variables.")&&!ic(k.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(p.type==="condition")for(let v of p.cases){for(let k of Fn(v.condition))a("saved_group",k)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let k of Qn(v.condition))k.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[v,k]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let N=p.value[v];if(N)if(N.source==="literal"){let B=v==="coupons"?N.value:[N.value];(!Array.isArray(B)||B.length>20||B.some(me=>!un({type:k,nullable:!1},me)||!a(k,me.id))||v==="coupons"&&new Set(B.map(me=>me.id)).size!==B.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...g,"value",v])}else{let B=e.variables[N.key];(N.path||!B||B.nullable||(v==="coupons"?B.type!=="array"||B.items?.type!=="reward"||B.items.nullable:B.type!==k))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[I,p]of e.graph.nodes.entries()){let g=p.type==="screen"?i.get(p.screenId):void 0,f=[...rf(p,c),...g?.type==="owned"?oa(g.document).map(S=>ic(S,c)?.key??S):[]];for(let S of new Set(f)){let k=function(N){if(N===p.id)return!0;if(v.has(N))return!1;v.add(N);let B=e.graph.nodes.find(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(k):!1};var w=k;if(!Object.hasOwn(e.variables,S)){n("Consumed variable is undeclared","variable",["graph","nodes",I]);continue}let A=e.variables[S];if(p.type==="screen"&&A.source.type==="input"&&e.inputs.some(N=>N.screenId===p.screenId&&N.variable===S)||A.source.type==="parameter"||A.source.type==="attribute")continue;let P=A.source.type==="input"?new Set(e.inputs.filter(N=>N.variable===S&&N.required).flatMap(N=>o.filter(B=>B.screenId===N.screenId).map(B=>B.id))):s.get(S)??new Set,v=new Set;(!P.size||k(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",I])}}(new Set(e.inputs.map(I=>I.variable)).size!==e.inputs.length||new Set(e.inputs.map(I=>`${I.screenId}:${I.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[I,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",I]);let g=i.get(p.screenId),f=g?.type==="owned"?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",I]),f?.type==="stack"&&f.interaction){let S=f.interaction.type==="toggle"?"boolean":f.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==S&&n("Input variable type does not match component","inputBinding",["inputs",I]);let A=e.variables[p.variable]?.enum;A&&!f.children.filter(P=>!P.hidden).every(P=>A.includes(P.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",I])}}for(let[I,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",I]),p.source.type==="input"&&!e.inputs.some(g=>g.variable===I)&&n("Input variable requires a component binding","inputBinding",["variables",I]);let d=0,m=0;for(let I of e.screens)if(I.type==="owned"){for(let p of I.document.pages)Yn(p.root,()=>{d++});m+=I.document.actions.length}(d>xn.components||m>xn.actions||rn(e)>xn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var bx=z.strictObject({...Hc,graph:Lc}).superRefine(sf),gi=z.strictObject({...Hc,graph:Lc,displayName:z.string().trim().min(1).max(80)}).superRefine(sf),lE=gi.superRefine(af),dE=bx.superRefine(af),Ma=z.string().regex(Ft),io={requestId:z.uuid(),nodeId:pn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),customerToken:Ma.optional()},Sx=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"])})]),xx=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(),Bn=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:xx.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:Sx}),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))d(g)}function d(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let g=t.savedGroups[p];g&&(i.add(p),c.set(p,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function m(p){for(let g of["hashAttribute","fallbackAttribute"])if(p[g]!==void 0&&Rc(p[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(p.condition);for(let g of p.parentConditions??[])w(g.id),u(g.condition)}function w(p,g=!1){let f=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!f){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),o.set(p,f),a.push(()=>{for(let S of f.rules??[]){m(S);for(let A of S.tracks??[])m(A.experiment)}}))}function I(p){let g=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),s.set(p,g),a.push(()=>m(g)))}for(let p of e.graph.nodes){p.type==="feature"&&w(p.featureKey,!0),p.type==="split"&&I(p.experimentId),p.type==="condition"&&p.cases.forEach(f=>u(f.condition)),p.type==="offering"&&p.configuration.source==="feature"&&w(p.configuration.featureKey,!0);let g=p.type==="output"?p.value:p.type==="end"?p.output:null;g?.type==="feature"&&w(g.featureKey,!0)}for(let p of a)p();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ie}from"zod";function cf(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 uf(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(d=>d.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}import{z as oo}from"zod";var lf=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 Ix=["customer_data","coupon_code"],vx=ie.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),df=ie.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Ba=(e,t)=>new Set(e.map(t)).size===e.length,wx=ie.strictObject({currency:he,amountMinor:ie.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Ox=ie.strictObject({featureId:ie.uuid(),name:ie.string().trim().min(1).max(120),allowance:ie.string().max(40).nullable(),access:ie.boolean()}),_x=ie.strictObject({stripe:ie.strictObject({prices:ie.array(wx).min(1).max(50)}).optional(),apple:ie.strictObject({productIds:ie.array(vx).min(1).max(10)}).optional(),google:ie.strictObject({products:ie.array(ie.strictObject({productId:df,basePlanId:df.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"})}),Cx=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(Ox).max(50).refine(e=>Ba(e,t=>t.featureId),"Duplicate benefit"),channels:_x,prepaid:ie.array(Gi).max(100).optional()}),Px=ie.strictObject({digest:li,content:ie.strictObject({discount:Jn,duration:en,appliesTo:Ls,displayCopy:lf.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()})}),Ex=ie.discriminatedUnion("type",[ie.strictObject({type:ie.literal("checkout"),product:ya}),ie.strictObject({type:ie.literal("close")}),ie.strictObject({type:ie.literal("action"),action:bc})]),Ua=ie.strictObject({kind:ie.literal("paywall"),formatVersion:ie.literal(1),name:ie.string().trim().min(1).max(80),offeringVersionId:ie.uuid(),presentation:Vn,screen:nn,products:Aa,catalog:ie.record(ie.uuid(),Cx),buttons:ie.record(Te,Ex),coupons:ie.record(ie.uuid(),Px)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;cf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),wc(r,Ix).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(S=>i.add(S)),g.defaultPlan&&i.add(g.defaultPlan)),g.type==="text"&&g.feature&&o.add(g.feature.id)});let s=e.products.items.map(g=>g.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(g=>!Object.hasOwn(e.catalog,g)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let g of i)u.has(g)||n("Screen references a Product that is not displayed");for(let g of Object.values(e.catalog))!g.channels.stripe&&!g.channels.apple&&!g.channels.google&&n("A displayed Product needs at least one sales channel");let d=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(f=>f.featureId)));for(let g of o)d.has(g)||n("Feature text must read a displayed benefit");let m=r.actions.filter(g=>g.type!=="navigate");r.actions.some(g=>g.type!=="event"&&g.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let I=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;I=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(S=>!u.has(S))&&n("Checkout may only sell displayed Products")}I||n("A Paywall needs a checkout button");let p=Object.keys(e.coupons);(p.length!==a.size||p.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),pf=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},Qc=Oe.string().regex(/^[a-f0-9]{64}$/),Jc=Oe.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Zc=Ue.extend({environmentId:Oe.uuid()}),mf=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:Qc,byteLength:Oe.number().int().positive().max(Zt.maxArtifactBytes),generation:Qc.optional()}),Rx=Oe.strictObject({state:Oe.enum(["active","paused","archived"]),controlRevision:Jc,evaluationMode:Oe.enum(["local","remote"]),evaluationRevision:Jc,currentVersionId:Oe.uuid(),versions:Oe.record(Oe.uuid(),Oe.strictObject({artifact:Oe.string(),dependencies:mf,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:Jc,generation:Qc,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(),Rx),paywalls:Oe.record(Oe.uuid(),pf).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 ff(e){return Xc(yt(e))}function gf(e,t){for(let o of Object.values(e.references))if(o.type==="flag"&&(!Object.hasOwn(t.features,o.key)||t.remoteFeatures.includes(o.key))||o.type==="experiment"&&!Object.hasOwn(t.experiments,o.id)||o.type==="saved_group"&&!Object.hasOwn(t.savedGroups,o.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=Va(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let o of e.graph.nodes){let s=o.type==="feature"?o.featureKey:o.type==="end"&&o.output?.type==="feature"?o.output.featureKey:o.type==="output"&&o.value.type==="feature"?o.value.featureKey:void 0;if(!s)continue;let c=n.features[s],u=o.type==="feature"?e.variables[o.writes.value]:e.outputSchema;if(!c||!u)throw new Error("Required public Feature declaration is unavailable");if([c.defaultValue,...(c.rules??[]).flatMap(m=>[...Object.hasOwn(m,"force")?[m.force]:[],...m.variations??[],...(m.tracks??[]).flatMap(w=>w.experiment.variations)])].some(m=>m===void 0||!un(u,m)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,a=o=>{for(let s of Fn(o)){if(i.has(s))continue;let c=t.savedGroups[s];if(!c)throw new Error("Required public Saved Group is unavailable");i.add(s),!Array.isArray(c)&&c.type==="condition"&&a(c.condition)}};for(let o of e.graph.nodes)if(o.type==="condition")for(let s of o.cases)a(s.condition);for(let o of Object.values(n.features))for(let s of o.rules??[]){a(s.condition);for(let c of[...s.parentConditions??[],...(s.tracks??[]).flatMap(u=>u.experiment.parentConditions??[])]){if(r.has(c.id)||!t.features[c.id])throw new Error("Local Funnel requires public Local prerequisites");a(c.condition)}for(let c of s.tracks??[])a(c.experiment.condition)}for(let o of Object.values(n.experiments)){a(o.condition);for(let s of o.parentConditions??[]){if(r.has(s.id)||!t.features[s.id])throw new Error("Local Funnel requires public Local prerequisites");a(s.condition)}}for(let o of e.graph.nodes)if(o.type==="split"){let s=n.experiments[o.experimentId];if(!s)throw new Error("Local Funnel requires a public Experiment");for(let c=0;c<s.variations.length;c++){let u=s.meta?.[c]?.key??String(c);if(!o.routes[u])throw new Error("Experiment variation has no declared Funnel route")}}return mf.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([o,s])=>[o,s.variations.map((c,u)=>s.meta?.[u]?.key??String(u))])),savedGroups:[...i].sort()})}function hf(e){return gi.parse(e)}var Af=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:Wn.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 yf(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 bf={requestId:Ut.uuid(),sourceId:Ut.uuid(),expectedAvailable:qt},Sf=Ut.discriminatedUnion("action",[Ut.strictObject({...bf,action:Ut.enum(["add","subtract","set_remaining"]),amount:ge}),Ut.strictObject({...bf,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()}),xf=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 If=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()]),vf=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 Of=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],wf=Tr.string().regex(/.+\/.+/),tu=Tr.number().min(-100),jr=Tr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),kx=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"),cR=Tr.strictObject({defaultMarkup:tu,providerMarkups:nu(Tr.string().min(1),tu),modelMarkups:nu(wf,tu),customModels:nu(wf,kx.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})?$/),jx=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()]),_f=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"),Tx=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:jx,timezone:_f,filterBy:fe.array(Tx).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)"})}),Cf=fe.object({from:Nr,to:Nr,interval:fe.enum(["hour","day","week","month"]),timezone:_f,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})$/),Pf=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()}),Ef=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})}),Rf=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:Pf,tokenEventCount:hi,tokens:Tt.strictObject(Object.fromEntries(Of.map(e=>[e,hi]))),totalTokens:hi,providerCostEventCount:hi,providerCostUsd:Pf,invalidTelemetryEventCount:hi})).max(100),nextCursor:ru.nullable()});import{z as pt}from"zod";var kf=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"),jf=pt.object({batchId:pt.uuid(),after:pt.number().int().min(-1).max(999),limit:pt.number().int().min(1).max(100)}).strict(),Tf=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 Nx=E.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Nf=E.enum(["draft","active","paused","archived"]),Df=E.string().min(1).max(256),Ff=E.array(Df).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Dx=E.strictObject({duration:E.enum(["day","week","month","year"]),length:E.number().int().min(1).max(3660)}),Fx=E.strictObject({internal_feature_id:E.uuid(),allowance:E.number().nonnegative().max(1e15).nullable(),expiry:Dx.nullable()}),Mx=E.discriminatedUnion("type",[E.strictObject({type:E.literal("feature_grant"),grants:E.array(Fx).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:Df,duration:en}),E.strictObject({type:E.literal("invoice_credits"),amount:E.number().positive().max(1e8),duration:en,rollover:E.boolean(),productIds:Ff})]),qx=E.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Mf=E.object({key:qx,name:E.string().trim().min(1).max(80),configuration:Mx}).strict(),qf=E.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),iu=E.object({code:qf,maxUses:E.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:E.boolean()}).strict(),Vf=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:Ff,excludeTrial:E.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Bf={id:E.uuid(),projectId:E.uuid(),environmentId:E.uuid(),revision:E.number().int().nonnegative(),status:Nf,createdAt:E.iso.datetime({offset:!0}),updatedAt:E.iso.datetime({offset:!0})},Vx=Mf.extend(Bf).strict(),Bx=Vf.safeExtend(Bf).strict(),IR=E.strictObject({id:E.uuid(),key:E.string(),name:E.string(),type:Nx,status:Nf}),vR=E.discriminatedUnion("action",[E.object({action:E.literal("save"),id:E.uuid().nullable(),revision:E.number().int().nonnegative(),input:Mf}).strict(),E.object({action:E.enum(["activate","pause","resume","archive","delete"]),id:E.uuid(),revision:E.number().int().nonnegative()}).strict()]),wR=E.discriminatedUnion("action",[E.object({action:E.literal("save"),id:E.uuid().nullable(),revision:E.number().int().nonnegative(),input:Vf}).strict(),E.object({action:E.enum(["activate","pause","resume","archive","delete"]),id:E.uuid(),revision:E.number().int().nonnegative()}).strict()]),Uf=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(),Lf=E.object({code:qf,requestId:E.uuid()}).strict(),zf=E.strictObject({redemptionId:E.uuid(),currency:he,requestId:E.uuid(),accepted:E.literal(!0)}),Ux=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()}),$f=E.discriminatedUnion("type",[Ux,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"])})]),Gf=E.object({programId:E.uuid(),requestId:E.uuid()}).strict(),Kf=E.object({id:E.uuid(),programId:E.uuid(),code:iu.shape.code,createdAt:E.iso.datetime({offset:!0})}).strict(),OR=E.object({rows:E.array(Vx).max(100),nextCursor:E.uuid().nullable()}).strict(),_R=E.object({rows:E.array(Bx).max(100),nextCursor:E.uuid().nullable()}).strict(),Lx=iu.extend({id:E.uuid(),redemptions:E.number().int().nonnegative()}).strict(),zx=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})}),CR=E.object({codes:E.array(Lx).max(100),redemptions:E.array(zx).max(100),customers:E.record(E.uuid(),E.string()),codesCursor:E.uuid().nullable(),redemptionsCursor:E.uuid().nullable()}).strict(),PR=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 x}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}$/),$x=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"))),Gx=Z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Hf=Z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Qf=Z.strictObject({id:Z.uuid(),repo:$x,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(Hf).min(1).max(16),exclude:Z.array(Hf).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)}),Jf=Qf.extend({revision:Z.number().int().positive()}),kR=Z.strictObject({repository:Qf,expectedRevision:Z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Zf=Z.strictObject({repositoryId:Z.uuid(),branch:co}),Kx=Z.array(ou).max(Cn.keys).refine(so),Wf=Z.strictObject({repository:Jf.omit({keyIds:!0}),branch:co,keys:Kx,keySetHash:Z.string().regex(/^[a-f0-9]{64}$/)}),Hx=Z.strictObject({filePath:Gx,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(Hx).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()}),Qx=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}),Jx=Z.strictObject({repositories:Z.array(Jf).max(Cn.repositories),scans:Z.array(Qx).max(Cn.repositories*Cn.branches)}),Zx=Z.strictObject({key:ou,references:Z.number().int().nonnegative(),coveredTargets:Z.number().int().nonnegative(),expiredTargets:Z.number().int().nonnegative(),uncertainTargets:Z.number().int().nonnegative()}),jR=Z.strictObject({available:Z.boolean().default(!0),settings:Jx,expectedTargets:Z.number().int().min(0).max(80),features:Z.array(Zx).max(2001),truncated:Z.boolean()});import{z as St}from"zod";var Wx=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"]),Yx=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:Wx,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()}))}),Yf=St.union([Yx,ul]),Xf=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 tg={customerId:Lt.uuid(),eventId:Lt.string().trim().min(1).max(200),grantId:Lt.uuid(),occurredAt:Lt.iso.datetime({offset:!0})},ng=Lt.strictObject({...tg,productVersionId:Lt.uuid(),subscriptionId:Lt.string().trim().min(1).max(255)}),rg=Lt.strictObject({...tg,merchandiseId:Lt.uuid()}),ig=Lt.union([ng,rg]),eg={id:Lt.uuid(),couponId:Lt.uuid(),status:Lt.literal("redeemed"),source:Lt.literal("merchant"),recordedAt:Lt.iso.datetime({offset:!0})},og=Lt.union([ng.extend(eg),rg.extend(eg)]);import{z as re}from"zod";var 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()}),Xx=cu.extend({id:re.string().min(1).max(255),created_at:re.number().nullable()}),ag=re.strictObject({items:re.array(Xx).max(50),nextCursor:re.uuid().nullable()}),UR=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)})]),sg=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:cc})]),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()}),cg=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()}),ug=re.strictObject({items:re.array(uu).max(50),nextCursor:re.uuid().nullable(),operations:re.array(Ai).max(50),operationsLimited:re.boolean()});var e0=x.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"]),lg={scope:Ue,permissions:x.array(e0),expiresAt:x.iso.datetime().nullable()},jk=x.discriminatedUnion("kind",[x.object({...lg,kind:x.literal("server"),keyId:x.string().min(1)}),x.object({...lg,kind:x.literal("customer"),customerId:x.string().min(1),identityKind:x.enum(["identified","guest"]),expiresAt:x.iso.datetime()})]),U=x.object({requestId:x.uuid(),scope:Ue}).strict(),t0=Hm.safeExtend({fingerprint:Ra.optional()}).strict(),n0=U.extend({customer:mi,created:x.boolean()});function dg(){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:x.object({messageId:x.uuid(),channel:$i,acceptedAt:x.iso.datetime({offset:!0}),status:x.enum(["accepted","sending","completed","canceled"]),replayed:x.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:x.strictObject({messageId:x.uuid()}),response:U.extend({message:x.object({id:x.uuid(),channel:$i,status:x.enum(["accepted","sending","completed","canceled"]),deliveries:x.array(x.object({id:x.uuid(),status:ap,attempts:x.number().int().nonnegative(),receipts:x.array(x.object({kind:sp,occurredAt:x.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:x.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:x.strictObject({cursor:x.uuid().optional()}),response:U.extend({templates:ag})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:x.strictObject({customerId:x.uuid(),params:ii}),response:U.extend({preview:uc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:x.strictObject({customerId:x.uuid(),requestId:x.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:x.strictObject({customerId:x.uuid(),command:sg}).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:x.strictObject({customerId:x.uuid(),taskId:x.uuid()}),response:U.extend({operation:Ai})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:x.strictObject({customerId:x.uuid(),cursor:x.uuid().optional()}),response:U.extend({invoices:ug})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:x.strictObject({customerId:x.uuid(),invoiceId:x.uuid()}),response:U.extend({invoice:cg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Zf,response:U.extend({config:Wf})},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:x.strictObject({}),response:U.extend({payload:eo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:_m,response:U.merge(Sa)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Cm,response:U.merge(Pm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:x.strictObject({customerId:x.uuid(),sourceId:x.uuid()}),response:U.extend({balance:xf})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:x.strictObject({customerId:x.uuid(),command:Sf}),response:U.extend({balance:eu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:x.strictObject({internal_feature_id:x.uuid(),customerId:x.uuid().optional(),entityId:x.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:U.extend({internal_feature_id:x.uuid(),config:vs,model_markups:jo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:x.strictObject({customerId:x.uuid(),query:Wo}),response:U.extend({usage:Ui})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:x.strictObject({customerId:x.uuid(),command:Jd}),response:U.extend({usage:Ui})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:x.strictObject({customerId:x.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:x.union(fm.options.map(e=>e.extend({customerId:x.uuid().optional(),customerToken:x.string().regex(Ft).optional()}))),response:U.extend({operation:gm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:rm.extend({customerId:x.uuid().optional()}),response:U.extend({setup:fc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:im.extend({customerId:x.uuid().optional()}),response:U.extend({setup:fc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:em.safeExtend({customerId:x.uuid()}),response:U.extend({batch:Wi})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:da.extend({customerId:x.uuid()}),response:U.extend({batch:Wi})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:da.extend({customerId:x.uuid()}),response:U.extend({batch:Wi})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:da.extend({customerId:x.uuid()}),response:U.extend({batch:Wi})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:x.discriminatedUnion("action",[pa.options[0].extend({customerId:x.uuid()}),pa.options[1].extend({customerId:x.uuid()}),pa.options[2].extend({customerId:x.uuid()})]),response:U.extend({trial:mc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:tm.extend({customerId:x.uuid()}),response:U.extend({trial:mc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ga,response:U.extend({subscriptions:dm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ga,response:U.extend({purchases:pm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:cm,response:U.extend({conflicts:mm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:um,response:U.extend({resolution:lm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:am,response:U.extend({verification:sm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Kp.safeExtend({...ni,customerId:x.uuid().optional()}),response:U.extend({quote:oi})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:Yf,response:U.extend({record:Xf})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Pr.extend({customerId:x.uuid().optional(),intent:x.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:x.uuid().optional()}),response:U.extend({operation:ai})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Jp.safeExtend({customerId:x.uuid().optional()}),response:U.extend({quote:Wp})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Pr.extend({customerId:x.uuid().optional(),intent:x.enum(["confirm","cancel"]).optional()}),response:U.extend({operation:lc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Pr.extend({customerId:x.uuid().optional()}),response:U.extend({operation:lc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Yp.safeExtend({customerId:x.uuid()}),response:U.extend({quote:dc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Pr.extend({customerId:x.uuid()}),response:U.extend({operation:la})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Pr.extend({customerId:x.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:x.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:x.object({customerId:x.uuid(),command:Cd}).strict(),response:U.extend({controls:$s})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:x.object({customerId:x.uuid(),command:If}).strict(),response:U.extend({entity:vf})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:x.strictObject({customerId:x.uuid().nullable(),query:Ef}),response:U.extend({analytics:Rf})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:x.object({customerId:x.uuid().nullable(),query:Dr}).strict(),response:U.extend({analytics:Cf})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:kf,response:U.extend({batchId:x.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:jf,response:U.extend({batch:Tf})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:lp.extend({customerId:x.string().min(1).optional()}),response:U.extend({check:vr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:x.strictObject({kind:er,selector:x.discriminatedUnion("type",[x.strictObject({type:x.literal("resource"),id:x.uuid()}),x.strictObject({type:x.literal("version"),id:x.uuid()})]),customerId:x.string().min(1).optional()}),response:U.extend({content:ac})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Af,response:U.extend({paywall:kr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:x.strictObject({...ni,selector:bm,customerId:x.string().min(1).optional(),commerce:Wr,requirement:Wn.optional()}),response:U.extend({offering:Sm,candidates:x.array(Ws).max(20),availability:x.array(x.strictObject({productVersionId:x.uuid(),available:x.boolean(),reason:x.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:x.object({customerId:x.uuid().optional(),entityId:x.uuid().optional()}).strict(),response:U.extend({holdings:Zd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:x.object({customerId:x.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:x.uuid().optional()}),response:U.extend({detail:Hd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Hs.safeExtend({customerId:x.uuid().optional()}),response:U.extend({statement:Qd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:x.object({customerId:x.uuid().optional(),command:Vi.options[0]}).strict(),response:U.extend({quote:Bd})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:x.strictObject({customerId:x.uuid(),command:x.union([x.strictObject({eventName:x.string().min(1),quantity:ge.optional(),properties:gt.optional(),entityId:x.uuid().optional(),idempotencyKey:x.string().min(1).max(120)}),x.strictObject({internal_feature_id:x.uuid(),quantity:ge.optional(),properties:gt.optional(),entityId:x.uuid().optional(),idempotencyKey:x.string().min(1).max(120)})])}),response:U.extend({receipts:x.array(Bi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:x.object({customerId:x.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:Lf,response:U.extend({redemption:Uf})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Gf,response:U.extend({referralCode:Kf})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:zf,response:U.extend({checkout:$f})},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:t0,response:n0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:qc,response:U.extend({customer:mi})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Zm,response:U.extend(Wm.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Jm,response:U.extend(Qm.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:x.object({customerId:x.uuid()}).strict(),response:U.extend($n.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:x.strictObject({}),response:U.extend($n.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:x.strictObject({customerId:x.uuid(),sessionId:x.uuid().optional()}),response:U.extend({revoked:x.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:x.strictObject({guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ra.optional()}),response:U.extend({customerId:x.uuid(),guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:x.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:x.strictObject({guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:U.extend($n.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:x.strictObject({guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:x.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:x.uuid()}),response:U.extend({customer:mi,switched:x.boolean(),replayed:x.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:x.strictObject({code:x.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:x.uuid()}),response:dg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:x.object({}).strict(),response:U.extend({offers:x.array(ji)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:x.object({customerId:x.string().min(1).max(255).optional(),couponId:x.uuid(),...ni,requestId:x.uuid(),couponContentDigest:x.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:dg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:ig,response:U.extend({receipt:og})}},Tk={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(d=>Qt(t.attributes??{},d.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new 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 pg(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}$/),r0=K.enum(["running","waiting","completed","closed","ineligible","failed"]),i0=K.discriminatedUnion("type",[Fc,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:Vc,openIn:Bc}),K.strictObject({type:K.literal("event"),receiptId:K.uuid(),event:ir})]),La=K.strictObject({type:K.literal("funnel"),id:K.uuid(),versionId:K.uuid()}),o0={id:ir,presentation:Vn,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())},a0=K.strictObject({...o0,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:r0,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:a0.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:i0.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()}),mg=lo.extend({run:pu.extend({paywall:pu.shape.paywall.unwrap().extend({resolution:kr}).nullable()})});var fg="X-Indiana-Server-Key";import{z as ke}from"zod";var yi=ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),hg=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)}),gg={scope:Ue,funnelId:ke.uuid(),versionId:ke.uuid(),evaluationRevision:ke.number().int().nonnegative(),expiresAt:ke.iso.datetime({offset:!0}).nullable(),topology:hg},za=ke.discriminatedUnion("evaluationMode",[ke.strictObject({...gg,evaluationMode:ke.literal("local"),growth:ln,conditions:ke.record(yi,ke.array(ke.strictObject({condition:Ht,port:ke.string()})))}),ke.strictObject({...gg,evaluationMode:ke.literal("remote")})]),s0=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 c0(e){return hg.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:c0(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 Ag(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 s0.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as Xe}from"zod";var yg=Xe.string().regex(/^[a-f0-9]{64}$/),u0=di.omit({variations:!0,active:!0}).extend({changeId:yg,variations:Xe.array(Xe.strictObject({urlRedirect:Xe.string().max(2048)})).min(2).max(20)}),bg=Xe.strictObject({environmentId:Xe.uuid(),trackExposures:Xe.boolean(),generation:yg,experiments:Xe.array(u0).max(100),savedGroups:Xi}),l0=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)}),fj=Xe.strictObject({events:Xe.array(l0).min(1).max(20)}),gj=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 d0=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()}),p0=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(d0).max(200).default([]),iam:Nm.optional(),renderGuard:xa.optional()}),fu=p0.omit({variation:!0,description:!0,iam:!0}),m0=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)}),Sg=xt.strictObject({trackExposures:xt.boolean(),environmentId:xt.uuid(),generation:xt.string().regex(/^[a-f0-9]{64}$/),experiments:xt.array(m0).max(100),savedGroups:Xi});import{z as it}from"zod";var hu=32,f0=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 g0=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),h0=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:of,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()})}),_j=it.strictObject({schemaVersion:it.literal(1),mode:it.enum(["local","remote"]),versionId:it.uuid(),generation:it.number().int().positive(),base:g0,context:gu,steps:it.array(h0).min(1).max(hu)}).refine(e=>rn(e)<=f0,"Segment exceeds its byte budget");var yu=class extends Error{constructor(n,r){super(r);Be(this,"code",n);this.name="FunnelLocalCalculationError"}},xg=(e,t)=>new yu(e,t),A0=e=>({experiments:e.experiments,features:e.features});function y0(e,t=xg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Kr(e.growth.savedGroups),i=A0(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,d;if(c.type==="condition"){let w=e.conditions[c.id];if(!w)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=du({id:c.id,name:c.id,type:"condition",cases:w.map(I=>({condition:I.condition,target:c.outputs[I.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");d=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let I=du({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);d=I.value,u=I.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)d=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...d===void 0?{}:{value:d}}}}}function b0(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=y0(n,t);return(o,s)=>(i(),S0(a,o,s))}function S0(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 x0(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,d={expected:n.sticky[u]??null,next:s};c<0?r.push(d):r[c]=d},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(Ae.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(Ae.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function Ig(e,t,n,r=xg){let i=n,a=new Map(t.graph.nodes.map(g=>[g.id,g])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,d=n.visit,m=!1,w,I=g=>(w??(w=b0(e,r)),x0(w,g,{attributes:kc({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(d>=t.execution.maxTransitions&&(d>t.execution.maxTransitions||f.type!=="end"&&f.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let S,A;if(["condition","feature","split"].includes(f.type)||f.type==="offering"&&f.configuration.source==="feature")S=I(f.id),f.type==="offering"&&(S.value={type:"offering_version",id:String(S.value)}),f.type==="condition"?A=S.port==="default"?f.default:f.cases[Number(S.port.slice(5))]?.target:f.type==="split"?A=S.port==="notParticipating"?f.notParticipating:f.routes[S.port]:(f.type==="feature"||f.type==="offering")&&(A=f.next);else if(S={port:"next",sticky:[],exposures:[],features:[]},(f.type==="entry"||f.type==="coupon"||f.type==="coupons")&&(A=f.next),f.type==="offering"&&f.configuration.source==="fixed"&&(S.value={type:"offering_version",id:f.configuration.versionId},A=f.next),f.type==="end"||f.type==="output"){let v=f.type==="end"?f.output:f.value;if(S=v?.type==="feature"?I(f.id):{...S,port:"value",value:v?.type==="literal"?v.value:v?.type==="variable"?rc({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},v&&(S.value===void 0||!un(t.outputSchema,S.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let P=[...c,{nodeId:u,result:S}];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:S}),f.type==="feature"||f.type==="offering"||f.type==="coupon"||f.type==="coupons"){let v=f.type==="coupons"?f.couponIds.map(N=>({type:"reward",id:N})):f.type==="coupon"?{type:"reward",id:f.couponId}:S.value;if(v===void 0)throw r("INVALID_RESPONSE","Node output is missing");let k=ti(f,{value:v});vp(t.variables,f,k),Object.assign(o,k)}for(let v of S.sticky)s[`${v.next.attributeName}||${v.next.attributeValue}`]=structuredClone(v.next);if(f.type==="end"||f.type==="output"){m=!0;break}if(!A)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=A,d++}let p=a.get(u);return{steps:c,...!m&&p&&!Au(p)?{boundary:{nodeId:u,visit:d}}:{}}}import{z as be}from"zod";var $a=be.string().regex(/^[a-f0-9]{64}$/),I0=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()}),$j=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:I0})).max(4e3)}),Gj=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")}),Kj=be.strictObject({scope:Ue,suppressed:be.literal(!0),reason:be.enum(["frequency","in_progress"]),retryAt:be.iso.datetime({offset:!0}).nullable()}),Hj=be.strictObject({experimentId:be.uuid(),splitNodeId:be.string().min(1).max(128)}),v0=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)}),vg=be.strictObject({operation:be.literal("page_experiments"),release:$a,usedReceiptIds:be.array(be.uuid()).max(20).default([]),customerToken:be.string().regex(Ft).optional()}),wg=be.strictObject({scope:Ue,runId:be.uuid(),assignments:be.array(v0.extend({receiptId:be.uuid()})).max(20),payload:Sg});var y=class extends Error{constructor(n,r,i,a,o){super(r);Be(this,"code",n);Be(this,"status",i);Be(this,"requestId",a);Be(this,"retryable");Be(this,"recovery");Be(this,"retryAfterSeconds");Be(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 y("INVALID_STATE","Installation sequence exhausted");return e+1},w0=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 Un(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new y("INVALID_STATE","Installation journal is invalid");return t({...n})})}function Og(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 y("SCOPE_MISMATCH","Push installation belongs to another scope");let c=()=>{if(!e)throw new y("NOT_CONFIGURED","Configure this client's native Push host first");return e},u=A=>{if(A!==i)throw new y("IDENTITY_CHANGED","Identity changed during Push operation")};async function d(A){let P=c();if(!P.sha256&&!globalThis.crypto?.subtle)throw new y("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let v=P.sha256?await P.sha256(Uint8Array.from(A,k=>k.charCodeAt(0))):await w0(A);if(!/^[a-f0-9]{64}$/.test(v))throw new y("INVALID_STATE","Push credential digest is invalid");return v}function m(A){let P=gr.parse(A);if(P.installationId.toLowerCase()!==c().installationId.toLowerCase())throw new y("INVALID_RESPONSE","Push response belongs to another installation");return P}async function w(A,P){let v=c(),k={installationId:v.installationId,publicKey:v.publicKey,issuedAt:new Date().toISOString(),...P},N=await v.sign(Yu(A,v.scope,k));return{...k,signature:N}}let I=(A,P,v)=>t.requestWithCredential?t.requestWithCredential(A,P,v):t.request(A,P);async function p(){let A=c(),P=i,v=r?await(t.session?.access()??r):null,k=Un(A,Ie=>Ie),N;if(k.detachSeq!==null){let Ie=k.detachSeq,De=Ju.parse(await w("detach",{sequence:Ie,platform:A.platform}));try{let Ee=await t.request("push/installations/detach",{...A.scope,...De},"POST",{installationDetach:!0});if(!Ee||typeof Ee!="object"||!("installation"in Ee))throw new y("INVALID_RESPONSE","Push detach acknowledgement is invalid");let zt=m(Ee.installation);if(zt.bound||zt.identitySeq!==Ie)throw new y("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Ee){if(Ee instanceof y&&Ee.status===404)N=Ee;else if(!(Ee instanceof y)||Ee.status!==412)throw Ee}N||Un(A,Ee=>({...Ee,detachSeq:Ee.detachSeq===Ie?null:Ee.detachSeq}))}if(u(P),!v){if(N)throw N;return null}let B=O.bindPushInstallation,me=B.request.parse(await w("bind",{sequence:o,platform:A.platform,credentialDigest:await d(v)}));u(P);let xe=B.response.parse(await I(B.path,me,v));u(P);let Ce=m(xe.installation);if(!Ce.bound||Ce.identitySeq!==o)throw new y("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return N&&k.detachSeq!==null&&o>k.detachSeq&&Un(A,Ie=>({...Ie,detachSeq:Ie.detachSeq===k.detachSeq?null:Ie.detachSeq})),Ce}async function g(){c();let A=i,P=r?await(t.session?.access()??r):null;if(!P)throw new y("NOT_IDENTIFIED","Identify before reading this installation");let v=O.readPushInstallation,k=v.request.parse(await w("read",{credentialDigest:await d(P)}));u(A);let N=v.response.parse(await I(v.path,k,P));return u(A),m(N.installation)}function f(A=p){let P=s.catch(()=>{}).then(A);return s=P,P.catch(v=>{try{e?.onError?.(v instanceof Error?v:new Error("Push synchronization failed"))}catch{}}),P}async function S(A,P,v){let k=c(),N=P.identity,B=P.observation,me=r?await(t.session?.access()??r):null;if(u(N),B!==a)throw new y("INVALID_STATE","Push observation changed during recovery");if(!me)throw new y("NOT_IDENTIFIED","Identify before recovering a Push address");if(!A.connectionId||!A.kind||!A.token||!["granted","provisional"].includes(A.permission))throw new y("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await f(async()=>{if(u(N),await p(),u(N),B!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let xe=Un(k,zt=>v?zt:{...zt,addressSeq:po(zt.addressSeq)}),Ie=await w(v?"recovery_confirm":"recovery_request",{...A,sequence:xe.addressSeq,credentialDigest:await d(me),...v?{challenge:v}:{}}),De=v?Wu.parse(Ie):Zu.parse(Ie);if(u(N),B!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let Ee=await I(`push/installations/recovery/${v?"confirm":"request"}`,De,me);if(u(N),B!==a||Un(k,zt=>zt).addressSeq!==xe.addressSeq)throw new y("INVALID_STATE","Push observation changed during recovery");if(v){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 y("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return We}if(!Ee||typeof Ee!="object"||!("recovery"in Ee))throw new y("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 S(P,A))},async confirm(P,v){return gr.parse(await S(v,A,P))}}},identify(A){if(!e)return;o=Un(e,v=>({...v,identitySeq:po(v.identitySeq)})).identitySeq,r=A,i++,a++},reset(){if(e)try{Un(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,v=o;return a++,await f(async()=>{u(P);let k=await g();return u(P),o=Un(A,B=>{if(B.identitySeq!==v)throw new y("IDENTITY_CHANGED","A newer installation intent exists");return{...B,identitySeq:po(Math.max(B.identitySeq,k.identitySeq)),addressSeq:Math.max(B.addressSeq,k.addressSeq)}}).identitySeq,await p()})},tokenObserver(){c();let A=++a,P=i;return async v=>{if(A!==a||P!==i)return null;let k=c(),N=r?await(t.session?.access()??r):null;if(!N)throw new y("NOT_IDENTIFIED","Identify before registering a Push token");if(await f(),u(P),A!==a)return null;let B=Un(k,Ie=>({...Ie,addressSeq:po(Ie.addressSeq)})),me=O.updatePushAddress,xe=me.request.parse(await w("address",{...v,sequence:B.addressSeq,credentialDigest:await d(N)}));if(u(P),A!==a)return null;let Ce=me.response.parse(await I(me.path,xe,N));return u(P),m(Ce.installation)}}}}function _g(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 Cg={name:"@tinkerlandai/indiana-sdk",version:"0.10.1",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function Ge(e){return typeof e=="string"?e:String(e)}var _0=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function C0(e){return e.replace(_0,"$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 Fg(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 Pg(e){let t;if(Array.isArray(e)){let n=e.map(Ge);if(n.length===2)return n}else if((t=Fg(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 Eg="0123456789ABCDEF",P0=/(?:%[0-9A-Fa-f]{2})+/g;function Pn(e){return`%${Eg[e>>4&15]}${Eg[15&e]}`}function Mg(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(P0,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function go(e){return e<=31||e>126}function E0(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 R0(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 Rg(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 qg(e,t){return Mg(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+=Mg(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],Rg,!0),i=En(e[n][1],Rg,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var k0=[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],j0=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],T0=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],N0=[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 D0(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[F0,M0,q0,kg]=[[[],"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 V0(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 Vg(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 B0(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&&Vg(N0,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&mo(kg,t[i]);)i--;let a=n+1;for(;a<t.length&&mo(kg,t[a]);)a++;if(!(i>=0&&a<t.length&&mo(M0,t[i])&&mo(q0,t[a])))return!1}return!0}var U0=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,L0=/\p{Script=Latin}/u;function z0(e){return!U0.test(e)||!L0.test(e)}var or=36,Ka=1,Cu=26,$0=38,G0=700,K0=72,H0=128,Q0=2147483647;function jg(e){return String.fromCharCode(e+22+75*+(e<26))}function J0(e,t,n){let r=0;for(e=n?Math.floor(e/G0):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+$0))}function Z0(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=H0,o=0,s=K0;for(;r<t.length;){let c=Q0;for(let u=0;u<t.length;u++){let d=t[u];d>=a&&d<c&&(c=d)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let d=t[u];if(d<a&&o++,d===a){let m=o;for(let w=or;;w+=or){let I=w<=s?Ka:w>=s+Cu?Cu:w-s;if(m<I)break;n+=jg(I+(m-I)%(or-I)),m=Math.floor((m-I)/(or-I))}n+=jg(m),s=J0(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 Tg(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function Bg(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Ug(e){return e.length===2&&Bg(e.codePointAt(0),e.codePointAt(1))}function Ng(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 Lg(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,d=0,m=0;for(;m<4&&(u=vu(c[s]))>=0;)d=(d<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let w=0;for(;c[s]!==void 0;){let I=0;if(w>0)if(c[s]===46&&w<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(I=10*I+vu(c[s]),I>255)return null;s++}i[o]=256*i[o]+I,w++,w%2==0&&o++}if(w!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=d,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let d=i[a+u-1];i[a+u-1]=i[o],i[o]=d,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Ng(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 d of u){let m=d.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(d)&&!Vg(k0,m)||mo(F0,m))return!0}return!1})(i))return null;let s=(i=(function(u){let d="";for(let m of u){let w=m.codePointAt(0);if(w!==8204&&w!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let I=V0(m,w);if(I){d+=I;continue}let p=j0.indexOf(w);d+=p<0?m:T0[p]}return d})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let d=/[^\0-\x7f]/.test(u);if(D0(u)||d&&(/^\p{Mark}/u.test(u)||!B0(u)||!z0(u)||u.startsWith("xn--")))return null;d&&(s[c]=`xn--${Z0(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:wu(e));return n===null||Ng(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 d=bu(a[u]);if(d<0||d>255)return null;s+=d*(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,d=1,m=0;for(let w=0;w<s.length;++w)s[w]!==0?(m>d&&(c=u,d=m),u=-1,m=0):(u===-1&&(u=w),++m);return m>d?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function zg(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function $g(e){return e.username!==""||e.password!==""}function Su(e){return e.host===null||e.host===""||e.scheme==="file"}var C=0,q="",Se="",qe=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="",qe=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=W0;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 Gg(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var W0=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,Y0(n<q.length?e:void 0)}else return ut?1:(--C,W(t,e)?Kg(G(q,C)):0)},Y0=e=>{let t=C;if(e===58){if(ut){if(ct(V.scheme)!==ct(Se))return 0;if(($g(V)||V.port!==null)&&Se==="file")return 0;if(V.scheme==="file"&&V.host==="")return 0}return V.scheme=Se,ut?(V.port===Lg(V.scheme)&&(V.port=null),0):(Se="",V.scheme==="file"?W(t,e)?Du(G(q,C)):0:ct(V.scheme)&&qe!==null&&qe.scheme===V.scheme?W(t,e)?X0(G(q,C)):0:ct(V.scheme)?W(t,e)?tI(G(q,C)):0:G(q,C+1)===47?(C++,W(t,e)?eI(G(q,C)):0):(V.path=[""],V.opaquePath=!0,W(t,e)?Qg(G(q,C)):0))}else return ut?1:(Se="",C=-1,W(t,e)?Kg(G(q,C)):0)},Kg=e=>{let t=C;return qe===null||qe.opaquePath&&e!==35?1:qe.opaquePath&&e===35?(V.scheme=qe.scheme,V.path=qe.path.slice(),V.opaquePath=qe.opaquePath,V.query=qe.query,V.fragment="",W(t,e)?Rn(G(q,C)):0):qe.scheme==="file"?(C--,W(t,e)?Du(G(q,C)):0):(C--,W(t,e)?Tu(G(q,C)):0)},X0=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)},eI=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=qe.scheme,e===47||ct(V.scheme)&&e===92?W(t,e)?Dg(G(q,C)):0:(V.username=qe.username,V.password=qe.password,V.host=qe.host,V.port=qe.port,V.path=qe.path.slice(),V.query=qe.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)},Dg=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=qe.username,V.password=qe.password,V.host=qe.host,V.port=qe.port,C--,W(t,e)?wn(G(q,C)):0)},tI=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=qg(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+=Gg(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===""&&($g(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+=Gg(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===Lg(V.scheme)?null:n,Se="",ut)return 0}return ut?1:(C--,W(t,e)?Mr(G(q,C)):0)}else return 1};function Hg(e,t){let n=e.length-t;if(n<2)return!1;if(Bg(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)?nI(G(q,C)):0:qe?.scheme==="file"?(V.host=qe.host,V.path=qe.path.slice(),V.opaquePath=qe.opaquePath,V.query=qe.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,Hg(q,C)?V.path=[]:zg(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)},nI=e=>{let t=C;return e===47||e===92?W(t,e)?Fu(G(q,C)):0:(qe!==null&&qe.scheme==="file"&&(!Hg(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})(qe.path[0])&&V.path.push(qe.path[0]),V.host=qe.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&&Ug(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)?(zg(V),e!==47&&!n&&V.path.push("")):Tg(Se)&&e!==47&&!n?V.path.push(""):Tg(Se)||(V.scheme==="file"&&V.path.length===0&&Ug(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+=qg(e,Ou),W(t,e)?wn(G(q,C)):0},Qg=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)?Qg(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)?R0: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),E0),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 Jg(e){switch(e.scheme){case"blob":{let t=cn(Ru(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Jg(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 Jg(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"),rI=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 iI=typeof Iterator<"u"?Iterator:Object,fo=class extends iI{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}[rI](){}},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(Pg(t[i]));else if((r=Fg(t))!=null){let i;for(;!(i=Iu(r.next())).done;)n.list.push(Pg(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=C0(o),c=Ge(t[o]),u=n.list.find(d=>d[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=Ge(t);i=i[0]==="?"?i.substring(1):i,n.list=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.tinker.cash";function Zg(e){let t,n,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m,w){let I=++r;i=void 0,t=void 0,n=void 0;for(let p of[...a.values()])try{p?.()}catch{}I===r&&(t=m,n=w,o())}let c=()=>s();function u(m,w=!1){let I=$n.safeParse(m);if(!I.success||w&&Date.parse(I.data.expiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<Date.parse(I.data.expiresAt))throw new y("INVALID_RESPONSE","Invalid customer session credentials");return I.data}async function d(){if(i)return i;let m=t,w=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new y("UNAUTHENTICATED","Customer authentication is required",401);let I=(async()=>{try{let p=await e(m.refreshToken);if(w!==r)throw new y("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(p,!0);if(g.customerId!==m.customerId||g.sessionId!==m.sessionId)throw new y("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,n=g.accessToken,{...g}}catch(p){throw w!==r?new y("IDENTITY_CHANGED","Customer identity changed during refresh"):(p instanceof y&&p.status===401&&c(),p)}})();i=I;try{return await I}finally{i===I&&(i=void 0)}}return{identify(m){let w=typeof m=="string"?void 0:u(m),I=typeof m=="string"?m:w.accessToken;if(!I.trim()||/\s/.test(I)||I.length>4096)throw new y("INVALID_TOKEN","A server-issued token is required");s(w,I)},reset:c,subscribeIdentity(m,w){return a.set(m,w),()=>{a.delete(m)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return d().then(()=>{if(!n)throw new y("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new y("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:d}}var Wg=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 y("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 y("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new y("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new y("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=null,d=0,m=null,w=new Set,I=e.session??Zg(async A=>{let P=await S("customer-sessions/refresh",{},"POST",{},A);if(!P||typeof P!="object")throw new y("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:k,...N}=P;return N});function p(){d+=1,u=null,m=null;for(let A of w)A.abort();w.clear()}let g=I.subscribeIdentity(p);function f(){I.reset()}async function S(A,P={},v="POST",k={},N){let B=k.installationDetach===!0;if(B&&(A!=="push/installations/detach"||v!=="POST"))throw new y("INVALID_REQUEST","Installation authority only detaches this installation");if(!N&&!u&&!B)throw new y("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let me=d,xe=new AbortController;B||w.add(xe);let Ce=()=>!B&&me!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new y("TIMEOUT","Indiana request timed out"),Ie,De=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:v,headers:{"Content-Type":"application/json",...B?{}:{Authorization:`Bearer ${N??u}`},[ps]:ms.current,[rl]:Cg.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(P):void 0,signal:xe.signal,credentials:"omit",cache:"no-store",redirect:"error",...k.keepalive?{keepalive:!0}:{}});if(xe.signal.aborted)throw Ce();let kt;try{kt=We.status===204?Wg:await We.json()}catch{throw xe.signal.aborted?Ce():new y(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!==d)throw new y("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 y(dr,$t?at.data.error.message:"Indiana 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 y("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&kt!==Wg){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 y("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 y("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 y("INVALID_RESPONSE","Invalid telemetry identity");m!==qr&&(m=qr,t?.(m))}return kt};try{return await Promise.race([zt(),De])}catch(We){throw!B&&me!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):We instanceof y?We:new y(xe.signal.aborted?"TIMEOUT":"NETWORK_ERROR",xe.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(Ee),xe.signal.removeEventListener("abort",Ie),w.delete(xe)}}return{session:I,requestWithCredential(A,P,v){return S(A,P,"POST",{},v)},subjectKey:()=>m,identify(A){if(a&&typeof A=="object"&&"scope"in A){let P=Ue.safeParse(A.scope);if(!P.success||P.data.projectId!==a.projectId||P.data.environment!==a.environment)throw new y("SCOPE_MISMATCH","Customer session belongs to another App/environment")}I.identify(A),u=I.peek()??null},reset:f,dispose(){g(),p()},request(A,P={},v="POST",k={}){if(k.installationDetach)return S(A,P,v,k);let N=d;try{let B=I.access(),me=xe=>{if(N!==d)throw new y("IDENTITY_CHANGED","Customer identity changed before dispatch");return S(A,P,v,k,xe)};return typeof B=="string"?me(B):B.then(me)}catch(B){return Promise.reject(B)}}}}function Yg(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 y("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(s),e.identify(o)},reset(){try{n.beforeReset?.()}finally{e.reset()}}}}}import{ZodError as oI}from"zod";function Xg(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof oI?new y(n,r):i}}async function pe(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=Xg(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):Xg(t.response,s,"INVALID_RESPONSE",a.response)}function Ve(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new y("INVALID_REQUEST","Customer requests use the verified session identity")}function eh(e){return{async checkEntitlement(t){Ve(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 th(e){return{async readLedger(t){let n=O.readLedger;return pe(e,n,{query:t})},async readCreditStatement(t){Ve(t);let n=O.readCreditStatement;return pe(e,n,t)},async quoteBalance(t){Ve(t);let n=O.quoteBalance;return pe(e,n,{command:t})}}}function nh(e){return{async setupPayment(t){Ve(t);let n=O.setupPayment;return pe(e,n,t)},async readPaymentSetup(t){Ve(t);let n=O.readPaymentSetup;return pe(e,n,t)},async readBillingInvoice(t){Ve(t);let n=O.readBillingInvoice;return pe(e,n,t)},async readBillingControls(t={}){Ve(t);let n=O.readBillingControls;return pe(e,n,t)},async prepareBillingAuthorization(t){Ve(t);let n=O.prepareBillingAuthorization;return pe(e,n,t)},async confirmBillingAuthorization(t){Ve(t);let n=O.confirmBillingAuthorization;return pe(e,n,t)},async setBillingCoupons(t){Ve(t);let n=O.setBillingCoupons;return pe(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Ve(t);let n=O.revokeBillingAuthorization;return pe(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Ve(t);let n=O.listBillingInvoices;return pe(e,n,t)},async confirmBillingAdjustment(t){Ve(t);let n=O.confirmBillingAdjustment;return pe(e,n,t)}}}function rh(e){return{async previewUpdate(t){Ve(t);let n=O.previewUpdate;return pe(e,n,t)},async update(t){Ve(t);let n=O.update;return pe(e,n,t)},async readSubscriptionUpdate(t){Ve(t);let n=O.readSubscriptionUpdate;return pe(e,n,t)},async restoreNativePurchase(t){Ve(t);let n=O.restoreNativePurchase;return pe(e,n,t)},async previewAttach(t){Ve(t);let n=O.previewAttach;return pe(e,n,t)},async attach(t){Ve(t);let n=O.attach;return pe(e,n,t)},async readSubscriptionOperation(t){Ve(t);let n=O.readSubscriptionOperation;return pe(e,n,t)}}}function ih(e){return{async redeemReward(t){return Ve(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 Ve(t),(await pe(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Ve(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 oh(e){return{...eh(e),...th(e),...nh(e),...rh(e),...ih(e)}}function ah(e){return{async resolveContent(t){Ve(t);let n=O.resolveContent;return pe(e,n,t)},async resolvePaywall(t){Ve(t);let n=O.resolvePaywall;return pe(e,n,t)},async resolveOffering(t){Ve(t);let n=O.resolveOffering;return pe(e,n,t)}}}var sh=e=>new TextEncoder().encode(JSON.stringify(e)).length,ch=16384;function uh(e,t){let n=0,r,i=p=>{r={config:structuredClone(p),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function d(p,g={},f={}){if(c(),r&&Date.now()<r.until&&!wm(r.config,p))return;I();let S=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:p,properties:g,...f}]}).events[0];if(sh({events:[S]})>ch)throw new y("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new y("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(S)),u()}async function m(p=!1){if(c(),o)return o;let g=n,f=(async()=>{let S={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&g===n;){let P=[];for(let N of a.slice(0,Math.min(A,100))){if(P.length&&sh({events:[...P,N]})>ch)break;P.push(N)}let v=O.trackEvents,k=await pe(e,v,{events:P},void 0,{keepalive:p});if(g!==n)throw new y("IDENTITY_CHANGED","Event identity changed during delivery");if(k.inserted+k.duplicates+k.rejected+k.skipped!==P.length)throw new y("INVALID_RESPONSE","Incomplete event acknowledgement");i(k.analyticsConfig),a.splice(0,P.length),A-=P.length,S.inserted+=k.inserted,S.duplicates+=k.duplicates,S.rejected+=k.rejected,S.skipped+=k.skipped}return S})();o=f;try{return await f}finally{o===f&&(o=null)}}let w;function I(){if(w||typeof document>"u")return;let p=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",p),w=()=>document.removeEventListener("visibilitychange",p)}return{rememberConfiguration:i,track(p,g,f={}){return I(),d(p,g,f)},flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){w?.(),w=void 0}}}function Mu(e){let t=null,n=null,r=0,i=0,a=!1,o=new Set,s=null,c=null,u=new Set,d=()=>{for(let A of u)try{A()}catch{}},m={attributes: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},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function I(A,P=new Set){return o.has(A)?!s||!s.features[A]||["unknownFeature","cyclicPrerequisite"].includes(s.features[A].source):P.has(A)?!1:(P.add(A),(t?.features[A]?.rules??[]).some(v=>[...v.parentConditions??[],...(v.tracks??[]).flatMap(k=>k.experiment.parentConditions??[])].some(k=>I(k.id,P))))}let p=A=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return s?.expiresAt&&Date.parse(s.expiresAt)<=Date.now()&&(s=null,m.features=t.features),o.has(A)?!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?w():structuredClone(s.features[A]??w()):e.evaluateRemote&&(m.attributes?.merchandise||m.attributes?.merchandiseId)&&!a||I(A)?w():structuredClone(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,v=t,k=[...o],N=(async()=>{let B=Sa.parse(await e.evaluateRemote({attributes:structuredClone(m.attributes),features:k}));if(!(P!==r||A!==i||v!==t)){if(e.assertUsable?.(v.generation),B.generation!==v.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(k.some(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={...v.features,...Object.fromEntries(Object.entries(s.features).map(([me,xe])=>[me,{defaultValue:xe.value}]))},d()}})();c={revision:A,loading:N};try{await N}finally{c?.loading===N&&(c=null)}}function f(){g().catch(A=>{try{e.onError?.(A)}catch{}})}async function S(){if(n)return n;let A=r,P=(async()=>{let v=await e.load(),k="remoteFeatures"in v?eo.parse(v):null,N=k??ln.parse(v);if(N.scope.projectId!==e.scope.projectId||N.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(A!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===N.generation){let{evaluatedAt:me,expiresAt:xe,...Ce}=t,{evaluatedAt:Ie,expiresAt:De,...Ee}=N;if(yt(Ce)!==yt(Ee))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=N.evaluatedAt,t.expiresAt=N.expiresAt,d(),(!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now())&&f(),structuredClone(t)}let B=new Set(k?.remoteFeatures??[]);if([...B].some(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&&k?.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={},d(),f(),structuredClone(t)})();n=P;try{return await P}finally{n===P&&(n=null)}}return{init:S,refresh:S,refreshRemote:g,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(A){return u.add(A),()=>{u.delete(A)}},setAttributes(A){let P=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={},d(),f()},evalFeature:p,isOn(A){return p(A).on},isOff(A){return p(A).off},getFeatureValue(A,P){let v=p(A).value;return structuredClone(v===null?P:v)},reset(){r++,i++,n=null,c=null,t=null,s=null,o.clear(),m.features={},m.savedGroups={},m.stickyBucketAssignmentDocs={},m.attributes={},m.trackedFeatureUsage={},m.trackedExperiments?.clear(),d()}}}function lh(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 aI(e){let t=lh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function dh(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new y("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let d=a,m=!1,w=async()=>{if(m||d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let Ce=O.getFeatures,Ie=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await pe(e,Ce,{});if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");if(r&&(Ie.scope.projectId!==r.projectId||Ie.scope.environment!==r.environment))throw new y("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Ie.payload.analyticsConfig),Ie},I=await w(),p=!0,g,f=Ce=>{try{u.onError?.(Ce)}catch{}},S=(Ce,Ie,De)=>{try{let Ee=lh(De);n.track(Ce,Ie,Ee?{merchandise:Ee}:{})}catch(Ee){f(Ee)}},A=Mu({assertUsable:i?.assertFeatures,scope:I.scope,attributes:u.attributes,onError:u.onError,load:async()=>p?(p=!1,I.payload):(await w()).payload,evaluateRemote:async Ce=>{if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let Ie=O.evaluateFeatures,De=await pe(e,Ie,{...Ce,attributes:aI(Ce.attributes)});if(De.scope.projectId!==I.scope.projectId||De.scope.environment!==I.scope.environment)throw new y("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:De.generation,evaluatedAt:De.evaluatedAt,expiresAt:De.expiresAt,features:De.features,...De.merchandiseContext?{merchandiseContext:De.merchandiseContext}:{}}},onExperimentViewed:(Ce,Ie,De)=>S("Experiment Viewed",{experimentId:Ce.key,variationId:Ie.key},De),onFeatureUsage:(Ce,Ie,De)=>S("Feature Evaluated",{feature:Ce,value:Ie.value,source:Ie.source,ruleId:Ie.ruleId,...Ie.experimentResult?{variationId:Ie.experimentResult.key}:{}},De)}),P=A.refresh;function v(){clearTimeout(g),!i&&(m||d!==a||!A.expiresAt||(g=setTimeout(()=>{k().catch(f)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function k(){try{return await P()}finally{v()}}let N=()=>{m||k().catch(f)},B=A.subscribe(v),me=i?.subscribe(()=>{!m&&i.fresh&&k().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 v(),!i&&typeof window<"u"&&window.addEventListener("focus",N),Object.assign(A,{refresh:k,destroy:xe})}return{features:c,reset(u){a++,u();for(let d of o)d()}}}import{z as sI}from"zod";function ph(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=sI.object({funnelId:La.shape.id,funnelVersionId:La.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new y("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new y("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new y("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await 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 mh(e){let t=cr(e),n=t.request,r=Og(e.push,t,e.scope??e.configuration?.scope),i=Yg(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),a=uh(n,i.isIdentified),o=dh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,..._g(n,r),...oh(n),...ah(n),forFunnel(s){return ph(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=mg.safeParse(t);if(!n.success)throw new y("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Funnel scope changed");return r}var 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 y("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!xi.test(e.apiKey))throw new y("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=Bn.safeParse({...r,operation:"start"});if(!i.success||i.data.operation!=="start"||(t?i.data.customer!==void 0:i.data.customer===void 0))throw new y("INVALID_REQUEST","Invalid current Funnel start");let a=i.data,o=lo.safeParse(await Xa(e,await n.request("funnels",a)));if(!o.success||!o.data.runToken)throw new y("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==a.funnelId||s.run.locale!==(a.locale??"en")||!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 y("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 fh(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 y("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c=setTimeout(()=>s.abort(),Zt.initializationMs);try{let u=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>r.byteLength)throw new y("INVALID_RESPONSE","Public Paywall is unavailable");let d=await qu(u,r.byteLength,{signal:s.signal,error:m=>new y("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!ts(d,r))throw new y("INVALID_RESPONSE","Public Paywall digest or size changed");return yf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))}finally{clearTimeout(c)}}var gh=(e,t)=>new y(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 y("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new y("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=cI(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 cI(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=uI(s,n.document,{...t,...r}),u=c.steps.at(-1),d=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return d?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:d.nodeId,visit:d.visit,terminal:!c.boundary}:null}function uI(e,t,n){return Ig(e,t,n,gh)}import{z as kn}from"zod";var hh=Bn.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new y("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Ah=kn.strictObject({schemaVersion:kn.literal(1),scope:Ue,runId:kn.uuid(),funnelId:kn.uuid(),versionId:kn.uuid(),command:hh.optional(),closeCommand:hh.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 y("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),rs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function yh(e){let t=0,n=null,r=c=>JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]),i=Promise.resolve();async function a(){let c=await e.read();if(!Number.isSafeInteger(c.revision)||c.revision<0)throw new y("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:c.revision,entry:c.entry===null?null:Ah.parse(c.entry)}}function o(c){let u=i.then(c);return i=u.catch(()=>{}),u}async function s(c){for(let u=0;u<4;u++){let d=await a();if(d.entry&&n!==null&&r(d.entry)!==n)throw Wt();let m=c(d.entry,d.revision);if(rs(d.entry,m)){t=d.revision;return}let w=await e.write(d.revision,m);if(w!==null){if(!Number.isSafeInteger(w)||w<=d.revision)throw Wt();t=w;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=Ah.parse(c),d=u.command;return!d||n!==null&&r(u)!==n?Promise.reject(Wt()):(n??(n=r(u)),o(()=>s((m,w)=>{if(m&&!rs(r(m),r(u)))throw Wt();if(!m){if(w!==t&&d.operation!=="close")throw Wt();return u}if(!m.command)return{...m,command:d,...d.operation==="close"?{closed:!0}:{}};if(d.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===d.requestId||m.closeCommand&&!rs(m.closeCommand,d))throw Wt();return{...m,closeCommand:d,closed:!0}}if(!rs(m.command,d))throw Wt();return m})))},observePurchase(c,u,d){return o(()=>s((m,w)=>{if(!m&&w!==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 d?!m?.purchase||m.purchase.operationId!==u.operationId?m:m.command?{...m,purchase:void 0}:null:{schemaVersion:1,...c,...m,purchase:u}}))},settle(c){return o(()=>s(u=>u?u.command&&"requestId"in u.command&&u.command.requestId===c?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand&&"requestId"in u.closeCommand&&u.closeCommand.requestId===c?{...u,closeCommand:void 0}:u:null))}}}function bh(e){let t,n,r=()=>new y("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??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 y?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function Sh(e){let t=null,n=0,r=!1,i,a=0,o=new Set;return{get view(){return t},get generation(){return n},get disposed(){return r},get customerToken(){return i},get readSequence(){return a},nextRead(){return++a},assertCurrent(s,c="Run identity changed during the request"){if(s!==n||r)throw new y("IDENTITY_CHANGED",c)},assertRun(s){if(t&&(s.id!==t.id||s.source.type!==t.source.type||s.source.id!==t.source.id||s.source.versionId!==t.source.versionId||s.locale!==t.locale||!Si(s.parameters,t.parameters)))throw new y("INVALID_RESPONSE","Run version changed");if(e&&s.source.id!==e)throw new y("INVALID_RESPONSE","Run belongs to another Funnel")},publish(s,c,u,d,m){if(!(s.operation==="review"&&t&&t!==u&&c.run.revision<=t.revision)&&!(t&&c.run.revision===t.revision&&d!==void 0&&d<a)&&(s.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&t&&c.run.nodeId===t.nodeId&&c.run.visit===t.visit&&c.run.revision===t.revision&&(c.run.screen=t.screen,(t.paywall?.quote?.operationId===c.review?.activeOperationId||!t.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=t.paywall)),!(t?.paywall&&c.run.paywall&&t.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||c.run.revision>=t.revision)t=c.run;else if(!m)return;if(t)for(let w of o)try{w(structuredClone(t))}catch{}}},identify(s){if(!Ft.test(s))throw new y("INVALID_TOKEN","Customer credential required");n++,i=s},subscribe(s){return o.add(s),()=>o.delete(s)},reset(){r=!0,n++,i=void 0,t=null,o.clear()}}}function ur(e){let{customerToken:t,...n}=e;return n}var lI=e=>!(e instanceof y)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function xh({options:e,journal:t,state:n,call:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=!1,u,d=null,m=t?t.load().then(f=>{if(n.disposed)throw new y("IDENTITY_CHANGED","Controller was reset during command restoration");if(d=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=f.purchase,o=f.closed===!0,!f.command)return;let S=Bn.parse(f.command);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("COMMAND_STORAGE_INVALID","Stored mutation required");i=S,f.closeCommand&&(a=f.closeCommand,o=!0),S.operation==="close"&&(o=!0),c=!0}):Promise.resolve();m.catch(()=>{});async function w(f=i){if(t&&await m,!f)throw new y("INVALID_REQUEST","No command is pending");let S=f,A=n.generation;if(t){if(!n.view||!e.scope)throw new y("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await t.retain({schemaVersion:1,scope:e.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:ur(S)})}if(A!==n.generation||i!==S&&a!==S)throw new y("IDENTITY_CHANGED","Run changed before command dispatch");let P={...S,...n.customerToken?{customerToken:n.customerToken}:{}},v=c;c=!0;try{return await r(P,k=>{if(!k.settlement)throw new y("INVALID_RESPONSE","Exact command settlement is missing");if(k.settlement.requestId!==S.requestId)throw new y("INVALID_RESPONSE","Command settlement identity changed");if(A===n.generation&&(i===S||a===S)&&k.run.pendingRequest?.requestId!==S.requestId&&k.settlement.state==="settled"&&(!o||S.operation==="close"||k.settlement?.state==="settled"&&!["running","waiting"].includes(k.run.status))){let N=()=>A!==n.generation||i!==S&&a!==S?!1:(i===S&&(i=null),a===S&&(a=null),c=i!==null,d=null,!0);return t?t.settle(S.requestId).then(N):N()}return!1})}catch(k){throw A===n.generation&&i===S&&!v&&!lI(k)&&(t&&await t.settle(S.requestId),A===n.generation&&i===S&&(i=null,c=!1,d=null)),k}}function I(f){let S=Bn.parse(f);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("INVALID_REQUEST","Mutation required");if(o&&S.operation!=="close"){if(i?.requestId===S.requestId)return g(S.requestId);throw new y("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(S.operation==="close"&&i?.operation!=="close"){if(o=!0,a&&JSON.stringify(ur(a))!==JSON.stringify(ur(S)))throw new y("COMMAND_PENDING","Retry the original Close");return a??(a=S),s.close?s.close:p(a,"close")}if(i){if(JSON.stringify(ur(i))!==JSON.stringify(ur(S)))throw new y("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=S,c=!1;return p(i,"command")}function p(f,S){let A=w(f);s[S]=A;let P=()=>{s[S]===A&&(s[S]=null)};return A.then(P,P),A}async function g(f){let S=await r({operation:"get",settlementRequestId:f,...n.customerToken?{customerToken:n.customerToken}:{}});if(S.settlement?.requestId!==f)throw new y("INVALID_RESPONSE","Exact command settlement is missing");return S.settlement.state==="settled"&&(t&&await t.settle(f),i?.requestId===f&&(i=null,c=!1),a?.requestId===f&&(a=null)),S}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(f){if(d&&(f.run.id!==d.runId||f.run.source.id!==d.funnelId||f.run.source.versionId!==d.versionId))throw new y("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(f,S,A,P){t?.bind({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId}),t&&!e.scope&&(e.scope=S.scope);let v=S.run.paywall,k=v??S.purchase,N=k?.operation,B=S.settlement&&(!v||v.purchaseRequestId===S.settlement.requestId)&&(!u||u.operationId===S.settlement.operationId)?S.settlement:void 0,me=N?.operationId??k?.quote?.operationId??B?.operationId,xe=k?.receiptId??B?.receiptId,Ce=v?.selectionGeneration??u?.generation??0;if(t&&me&&xe&&f.operation!=="review"&&(!n.view||S.run.revision>=n.view.revision)&&(P===void 0||P>=n.readSequence)&&(!u||Ce>=u.generation)){let Ie={receiptId:xe,operationId:me,generation:Ce},De=N?.status==="complete"||k?.canReselect===!0;return t.observePurchase({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId},Ie,De).then(()=>{n.assertCurrent(A),De?u?.operationId===Ie.operationId&&(u=void 0):u=Ie})}},stop(){o=!0},submit:I,executePending:w,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 y("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!xi.test(e.serverKey)))throw new y("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new y("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=cr({...e,session:void 0,...e.serverKey?{fetch:(f,S)=>{let A=new Headers(S?.headers),P=typeof S?.body=="string"?JSON.parse(S.body):null;return P!==null&&typeof P=="object"&&"customerToken"in P&&typeof P.customerToken=="string"&&P.customerToken.length>0||A.set(fg,e.serverKey),(e.fetch??globalThis.fetch)(f,{...S,headers:A})}}:{},...e.session?{fetch:async(f,S)=>{let A=await e.session.access(),P=typeof S?.body=="string"?JSON.parse(S.body):{};if(!P||typeof P!="object"||Array.isArray(P))throw new y("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(f,{...S,body:JSON.stringify({...P,customerToken:A})})}}:{},timeoutMs:e.timeoutMs??35e3});t.identify(e.runToken);let n=Sh(e.funnelId),r=e.session?.subscribeIdentity(()=>{n.reset(),t.reset()}),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?bh(e):void 0),o=a&&yh(a),s=xh({options:e,journal:o,state:n,call:c});async function c(f,S,A){let P=n.generation,v=()=>n.assertCurrent(P);o&&await s.ready,v();let k=n.view,N=lo.parse(await Xa(e,await t.request("funnels",Bn.parse(f))));if(f.operation==="review"&&!N.review)throw new y("INVALID_RESPONSE","Historical projection is missing");if(v(),N.runToken&&N.runToken!==e.runToken)throw new y("INVALID_RESPONSE","Run credential changed");let B=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(B&&N.settlement?.requestId!==B)throw new y("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(N),n.assertRun(N.run);let 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=S?.(N),Ce=typeof xe=="boolean"?xe:xe?await xe:!1;return v(),["running","waiting"].includes(N.run.status)||s.stop(),n.publish(f,N,k,A,Ce),N}let u=s.submit,d=null,m=new WeakMap;function w(f){let S=m.get(f);if(S)return S;let A=p(f);return m.set(f,A),A}let I=!1;async function p(f){let S=await f;if(S.run.instruction?.type!=="evaluate_segment")return S;if(d)return d;I=!0;let A=n.generation,P=(async()=>{for(let v=0;v<32&&S.run.instruction?.type==="evaluate_segment";v++){if(s.pending||s.closeRequested)return S;let k=S.run;if(S.run.instruction?.type==="evaluate_segment"){let{advance:B}=await Vu(e.configuration,k,{predict:!1});if(A!==n.generation)throw new y("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return S;if(n.view&&(n.view.revision!==k.revision||n.view.visit!==k.visit||n.view.nodeId!==k.nodeId))return c({operation:"get",...n.customerToken?{customerToken:n.customerToken}:{}});let me=!0;Vu(e.configuration,k).then(({prediction:xe})=>{me&&A===n.generation&&!s.closeRequested&&n.view?.id===k.id&&!n.view.stopped&&n.view.nodeId===k.nodeId&&n.view.visit===k.visit&&n.view.revision===k.revision&&(i=xe)}).catch(()=>{});try{S=await u({operation:"commit_segment",requestId:pg(k.id,k.visit,`segment:${k.revision}`),nodeId:k.nodeId,visit:k.visit,revision:k.revision,...B})}finally{me=!1,i=null}}}return S})();d=P;try{return await P}finally{d===P&&(d=null)}}let g={get configuration(){return I?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let f=s.closing??s.pending;return f?structuredClone(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,S=[]){let A=n.generation;n.assertCurrent(A);let P=n.view?.id;if(!P)throw new y("INVALID_REQUEST","Read the Run before its page experiments");let v=wg.parse(await t.request("funnels",vg.parse({operation:"page_experiments",release:f,usedReceiptIds:S,...n.customerToken?{customerToken:n.customerToken}:{}})));if(n.assertCurrent(A),v.runId!==P||v.scope.projectId!==e.scope?.projectId||v.scope.environment!==e.scope?.environment)throw new y("SCOPE_MISMATCH","Page experiment Run changed");return v},review(f){return c({operation:"review",...f?{receiptId:f}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,n.nextRead())},async get(f,S){o&&await s.ready,S??(S=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let A=n.nextRead();return w(c({operation:"get",...f?{data:f}:{},...S?{purchase:S}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,A))},resume(f=n.view?.pendingRequest?.requestId){return f?s.closeRequested?g.settle(f):s.pending?.requestId===f?w(u(s.pending)):w(u({operation:"resume",requestId:f})):Promise.reject(new y("INVALID_REQUEST","No interrupted command is available"))},submit(f){return w(u(f))},retry(){return s.closeFlight?s.closeFlight:s.closing?s.executePending(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?w(s.inFlight):s.pending?w(u(s.pending)):Promise.reject(new y("INVALID_REQUEST","No command is pending"))},identify(f){n.identify(f),i=null,t.identify(e.runToken)},subscribe:n.subscribe,reset(){r?.(),n.reset(),s.reset(),i=null,t.reset()}};return g}function Ih(e){if(!Ft.test(e.customerToken))throw new y("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new y("INVALID_REQUEST","An explicit App and environment scope is required");let t=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 vh(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 wh(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new y("INVALID_RESPONSE",n)}function Oh(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new y("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new y("INVALID_RESPONSE",n)}function _h(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 Ch(e,t){if(!Ft.test(t.customerToken))throw new y("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 y("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),i=null,a=!1,o=null,s=null,c=null,u=null,d=e.session?.subscribeIdentity(()=>{a=!0,n.dispose(),i=null,o=null,s=null,c=null});async function m(){if(a)throw new y("IDENTITY_CHANGED","Paywall is closed");let p=O.resolvePaywall,g=await 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 y("IDENTITY_CHANGED","Paywall is closed");if(t.paywallVersionId?f.paywall.id!==t.paywallVersionId:f.paywall.paywallId!==t.paywallId)throw new y("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!vh(f.paywall,i)||f.paywall.paywallId!==i.paywallId))throw new y("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=f.paywall,structuredClone(i)}async function w(p){if(!o)throw new y("INVALID_REQUEST","A quoted purchase is required");let g=p==="read"?O.readSubscriptionOperation:O.attach,f=await pe(n.request,g,{operationId:o.operationId,...p==="read"?{}:{intent:p}});return wh(f.operation,{operationId:o.operationId,currency:r.commerce.currency},"The purchase operation changed"),s=_h(s,f.operation),structuredClone(s)}let I={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:m,async preview(p){if(!i)throw new y("INVALID_REQUEST","Load the Paywall first");let g=i.document.buttons[p.actionId];if(g?.type!=="checkout")throw new y("INVALID_REQUEST","Choose an authored purchase action");let f=xm(g.product,p.selection,i.capabilities);if(!f)throw new y("PRODUCT_UNAVAILABLE","Choose an available Product");let S=uf(i.document.screen,f,p.selection,i.capabilities),A=O.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:f,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),P=JSON.stringify(A);if(c&&c!==P&&(!s||s.status==="pending"))throw new y("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===P){if(u)return u;if(o)return structuredClone(o)}c=P;let v=(async()=>{let k=O.previewAttach,N=await pe(n.request,k,A);return Oh(N.quote,{productVersionId:f,featureQuantities:S,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=N.quote,s=null,structuredClone(o)})();u=v;try{return await v}finally{u===v&&(u=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){d?.(),a=!0,n.dispose(),i=null,o=null,s=null,c=null}};return await m(),I}function Ph(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new y("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new y("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new y("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let I=r;n&&e.nativeModule&&n.then(p=>e.nativeModule.reset(p,I)).catch(()=>{})}),d=e.nativeEvents?.(I=>{!n||!e.nativeModule||typeof I?.requestId!="string"||(async()=>{let p=await n;if(I.instanceId!==p)return;if(I.kind==="credential"){let S=r,A=null;try{if(!o&&I.revision===S){let P=await t.access();!o&&r===S&&(A=P)}}finally{await e.nativeModule.provideCredential(p,I.requestId,A)}return}let g=!1,f=r;try{if(o||I.revision!==f||!e.onNativeAction)throw c();await e.onNativeAction(I.action),g=!o&&r===f}finally{await e.nativeModule.acknowledge(p,I.requestId,g)}})().catch(()=>{})});async function m(I,p={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new y("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let f=r,S=await t.access();if(o||r!==f)throw c();if(!n){let v=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.tinker.cash",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==f)throw c();if(i!==f){if(!a||a.epoch!==f){let k=(async()=>{if(await g.identify(A,JSON.stringify({revision:f,credentials:S})),o||r!==f)throw await g.reset(A,f),c();i=f})();a={epoch:f,task:k}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let P=await g.invoke(A,I,JSON.stringify(p));if(o||r!==f)throw c();try{return JSON.parse(P)}catch{throw new y("INVALID_RESPONSE","Native host returned invalid JSON")}}async function w(I,p){let g=await m(I,p);if(!g||typeof g!="object"||Array.isArray(g)||g.status!=="complete"&&g.status!=="dismissed")throw new y("INVALID_RESPONSE","Native presentation returned an invalid result");return g}return{showFunnel(I){return w("showFunnel",{runToken:I})},showPaywall(I){return w("showPaywall",I)},showContent(I){return w("showContent",I)},purchaseSubscription(I,p){return m("purchaseSubscription",{operationId:I,accepted:p})},switchSubscription(I,p){return m("switchSubscription",{operationId:I,accepted:p})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(I){return m("manageSubscriptions",I?{productId:I}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),d?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var dI=O.trackUsage.request.shape.command,pI=O.trackUsage.response;function HD(e){let t=Ue.parse(e.scope),n=mh({...e,scope:t}),r={...e,scope:t,session:n.session},i=0;n.subscribeIdentity(()=>{i++});let a=()=>{let o=n.session.peek();if(!o)throw new y("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:Ph(e,n.session),funnel(){return Ih({...r,customerToken:a()})},resumeFunnel(o){return a(),Ii({...r,runToken:o})},paywall(o){return Ch(r,{...o,customerToken:a()})},async trackUsage(o){if(!n.session.peek())throw new y("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new y("INVALID_REQUEST","Configure your authenticated backend usageReporter");let s=dI.parse(o),c=i,u;try{u=await e.usageReporter(s)}catch(m){throw c!==i?new y("IDENTITY_CHANGED","Customer identity changed during usage reporting"):m}if(c!==i)throw new y("IDENTITY_CHANGED","Customer identity changed during usage reporting");let d=pI.parse(u);if(d.scope.projectId!==t.projectId||d.scope.environment!==t.environment)throw new y("INVALID_RESPONSE","Usage response scope differs");return d}}}import{z as hI}from"zod";import{z as ho}from"zod";var mI=ho.record(ho.string().regex(/^[a-f0-9]{64}$/),ho.strictObject({at:ho.number(),text:ho.string()})),Eh=2*1048576,fI=100;function gI(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Rh(e,t){let n=t===void 0?gI():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),fI)})])}catch{return null}finally{clearTimeout(s)}}async function a(){try{let o=await i(`${e}:artifacts`);if(o&&o.length<=Eh)return mI.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return i(e)},writeManifest(o){Promise.resolve().then(()=>n?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let s=(await a())[o];return s&&Date.now()>=s.at&&Date.now()-s.at<=Zt.retentionMs?s.text:void 0},writeArtifact(o,s){n&&(r=r.catch(()=>{}).then(async()=>{let c=await a(),u=Date.now();c[o]={at:u,text:s};let d={},m=2,w=0;for(let[I,p]of Object.entries(c).sort(([,g],[,f])=>f.at-g.at)){if(p.at>u||u-p.at>Zt.retentionMs)continue;let g=new TextEncoder().encode(JSON.stringify({[I]:p})).byteLength;m+g>Eh||w>=128||(d[I]=p,m+=g,w++)}await n.setItem(`${e}:artifacts`,JSON.stringify(d))}).catch(()=>{}))}}}var _e=(e,t)=>new y(e,t),lr=()=>performance.now(),kh=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function AI(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=Rh(o,e.storage),c,u=0,d=0,m=!1,w=!1,I=0,p=0,g,f,S,A,P=0,v=new Set,k=new Set,N=new Map,B=new Map,me=0,xe=!1;function Ce(){for(let Y of v)try{Y()}catch{}}function Ie(Y){try{e.onError?.(Y)}catch{}}let De=()=>!w&&!m&&!!c&&lr()<u&&Date.now()<d;function Ee(){if(!De())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 fh(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(S),clearTimeout(A),w||!v.size)return;De()&&(A=setTimeout(()=>{De()?at():Ce()},Math.max(1,u-lr())),kh(A));let Y=p?Math.min(15e3,1e3*2**Math.min(p-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);S=setTimeout(()=>{$t().catch(Ie)},Math.max(P,Y*(.8+Math.random()*.2))),kh(S)}async function $t(){if(w)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Y=I,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:Ln,...zn}=Ot,mr=Nt.headers.get("etag");if(yt(Ot.scope)!==yt(t)||ff(zn)!==Ln||mr!==`"${Ln}"`&&mr!==`W/"${Ln}"`)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!==I)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Ot,u=$u,d=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 hI.ZodError||Ke instanceof SyntaxError||Ke instanceof y&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,m=!0,Ce()),Ke}).finally(()=>{clearTimeout(ce),g===wt&&(g=void 0),at()});return g=wt,wt}async function dr(Y){let H=Y.sha256,se=Ln=>ts(Ln,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;k.add(Ne);let wt=I,Ke=(async()=>{try{let mr=await s.readArtifact(H);if(mr&&se(mr))return zt(H,mr),mr}catch{}Ne.signal.throwIfAborted();let Ln=await Ao(Y.url,Ne.signal,!0),zn=await We(Ln,Y.byteLength,Ne.signal);if(!se(zn))throw _e("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(w||wt!==I)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return zt(H,zn),s.writeArtifact(H,zn),zn})(),Yt=setTimeout(()=>Ne.abort(_e("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Zt.initializationMs),Nt=new Promise((Ln,zn)=>Ne.signal.addEventListener("abort",()=>zn(Ne.signal.reason),{once:!0})),Ot=Promise.race([Ke,Nt]).finally(()=>{clearTimeout(Yt),k.delete(Ne),B.delete(H)});return B.set(H,Ot),Ot}async function pr(){return De()||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=vc.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 Indiana; 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=>hf(JSON.parse(Ot))),Ne.evaluationMode==="local"?Bu(se):void 0]);if(Nt&&yt(gf(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 y)||!(se.code==="CONFIGURATION_CHANGED"||se.code==="CONFIGURATION_HTTP_404"&&De()))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 jh(Y){if(w)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",is),window.addEventListener("focus",yo),document.addEventListener("visibilitychange",yo)),at()),()=>{v.delete(Y),v.size||(clearTimeout(S),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:jh,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 De()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return De()?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=bg.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 Ag({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 Indiana");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(!w){w=!0,I++,u=0,f?.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(S),clearTimeout(A),zu(),Ce(),v.clear();for(let Y of k)Y.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));N.clear(),me=0}}}}async function yI(e){e={...e};let t=e.configuration;if(!t)throw new y("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&yt(n)!==yt(e.scope))throw new y("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new y("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=xi.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new y("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=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),d=await u.get();return{...c,...d,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new y("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}export{y as IndianaError,AI as createConfigurationSync,Mu as createFeatureClient,HD as createIndianaReactNative,yI as createLocalFunnelClient};