@tinkerlandai/longplay-sdk 0.10.27 → 0.10.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/chunk-2AKQWIK6.js +1 -0
- package/dist/chunk-3JQPCIKN.js +1 -0
- package/dist/{chunk-FB7X4MFC.js → chunk-4GZKK2RE.js} +1 -1
- package/dist/{chunk-WU4SDY27.js → chunk-5KB452HB.js} +1 -1
- package/dist/{chunk-VTZHKUZO.js → chunk-5SL2JQU3.js} +1 -1
- package/dist/{chunk-2GMWNOOE.js → chunk-6KAADDQL.js} +1 -1
- package/dist/{chunk-LI4B43FT.js → chunk-6O4IBSE3.js} +1 -1
- package/dist/{chunk-D4CDG535.js → chunk-6YJ3CFPM.js} +1 -1
- package/dist/{chunk-5M536ISX.js → chunk-ARIVUZUH.js} +1 -1
- package/dist/{chunk-67JOPO63.js → chunk-BSBHQVHH.js} +1 -1
- package/dist/{chunk-LHXRT32T.js → chunk-CK4QMCWN.js} +1 -1
- package/dist/{chunk-WKH23DZE.js → chunk-CTSSHAV7.js} +1 -1
- package/dist/{chunk-TJMODHSS.js → chunk-DVOYXRVB.js} +1 -1
- package/dist/{chunk-S4X6YX5D.js → chunk-FCBTTR5W.js} +1 -1
- package/dist/{chunk-26YREQNF.js → chunk-FKDUXXGT.js} +1 -1
- package/dist/{chunk-2TQEJ6GM.js → chunk-FODM46LT.js} +1 -1
- package/dist/{chunk-AEERSTTW.js → chunk-FVM4JJBA.js} +1 -1
- package/dist/{chunk-MTKM26F7.js → chunk-GRNHBOSS.js} +1 -1
- package/dist/{chunk-SYQMGS6O.js → chunk-IVDXTPNR.js} +2 -2
- package/dist/{chunk-XZMM34BS.js → chunk-JOI5ZUBO.js} +1 -1
- package/dist/{chunk-VRCN5YLM.js → chunk-JPBLMVZR.js} +1 -1
- package/dist/{chunk-EBXWLW4D.js → chunk-LS4XNIXR.js} +1 -1
- package/dist/{chunk-DC7UHEC6.js → chunk-NROHBY3P.js} +1 -1
- package/dist/{chunk-5OJVM7Q4.js → chunk-O4KXODTJ.js} +1 -1
- package/dist/{chunk-MBLWCMAI.js → chunk-O7HHYO3I.js} +1 -1
- package/dist/{chunk-G2QO6ZWP.js → chunk-P3PXFIMG.js} +1 -1
- package/dist/{chunk-S67P7ZQ6.js → chunk-QE6T6NX6.js} +1 -1
- package/dist/chunk-QONPVFRV.js +1 -0
- package/dist/{chunk-COMWJEMO.js → chunk-QQ43HZVT.js} +1 -1
- package/dist/{chunk-7CFSTOTX.js → chunk-RCUBJJ7K.js} +1 -1
- package/dist/{chunk-WCKOWAIL.js → chunk-TEMI3X5X.js} +1 -1
- package/dist/{chunk-HWQVZL7I.js → chunk-UIYOW47V.js} +1 -1
- package/dist/{chunk-LHOSUSTZ.js → chunk-VGLBSYPV.js} +1 -1
- package/dist/{chunk-2ZPCWVFU.js → chunk-W5KG2IWX.js} +1 -1
- package/dist/{chunk-ANZB6OLR.js → chunk-WYMP6O5B.js} +1 -1
- package/dist/{content-4V7YBP3O.js → content-VNX6YOVO.js} +1 -1
- package/dist/{funnel-host-purchase-LJYQF6AX.js → funnel-host-purchase-WRJIUARR.js} +1 -1
- package/dist/funnel-runtime-host-CHE2WGKE.js +1 -0
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-M3V6MBVB.js +1 -0
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-ROG5DVKX.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-OATK5XFF.js +1 -0
- package/dist/paywall-session-ABEEADOM.js +1 -0
- package/dist/popup.d.ts +2 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-EHGDVWEV.js +1 -0
- package/dist/server.js +1 -1
- package/dist/{visual-dom-CAOVBSVC.js → visual-dom-5LUN4AHO.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-WPLSGFYT.js +0 -1
- package/dist/chunk-XBVJHXSP.js +0 -1
- package/dist/chunk-Z6RZQ5KJ.js +0 -1
- package/dist/funnel-runtime-host-XWXG4SIU.js +0 -1
- package/dist/merchant-bridge-contracts-OL3ME2AL.js +0 -1
- package/dist/operation-contracts-NJPUHGUM.js +0 -1
- package/dist/paywall-INF4ZZ7J.js +0 -1
- package/dist/paywall-session-3JV2JMUI.js +0 -1
- package/dist/screen-renderer-ZRSVFBLQ.js +0 -1
- /package/dist/{chunk-QENDBHBQ.js → chunk-CILM5XMH.js} +0 -0
- /package/dist/{chunk-D6SDVDXZ.js → chunk-OJM6ORHE.js} +0 -0
- /package/dist/{chunk-ZGBSTK22.js → chunk-Z43N7U4U.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as rn}from"./chunk-EBXWLW4D.js";import{h as ue,i as se,r as nn,s as pe}from"./chunk-5M536ISX.js";import{c as Be,d as Ke,e as J,l as en}from"./chunk-2GMWNOOE.js";import{$ as U,D as Ye,R as Qe,W as Ze,X as We,Y as $,Z as Xe,_ as de,a as q,b as je,c as Me,d as qe,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,z as Je}from"./chunk-XZMM34BS.js";import{b as on}from"./chunk-26YREQNF.js";import{b as ne}from"./chunk-MTKM26F7.js";import{a as W}from"./chunk-S67P7ZQ6.js";import{D as Te,L as ae,U as D,V as De,W as Le,ja as $e,ka as le,la as He,ma as ce,t as Oe,z as Ae}from"./chunk-TJMODHSS.js";import{a as f}from"./chunk-S4X6YX5D.js";import{h as V}from"./chunk-2ZPCWVFU.js";import{b as tn}from"./chunk-AEERSTTW.js";import{b as n}from"./chunk-ZGBSTK22.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-5OJVM7Q4.js";import{a as Pe,b as Ne}from"./chunk-QENDBHBQ.js";function an(e){return En({...e,namespace:"commands",identity:[e.runToken]})}function En(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??tn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var L=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Pn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:L.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:Ze,openIn:We}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:L})]),Nn={id:L,presentation:Te,outputs:n.array(L).max(250),inputs:ce,values:n.record(n.string(),D).optional(),offeringKey:q.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(L,$e.nullable())},On=n.strictObject({...Nn,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:L,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Cn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:He,variables:n.record(n.string(),D),output:D.nullable(),screen:On.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([nn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Pn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),An=n.strictObject({scope:V,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:L,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:L,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),D).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),sn=An.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var ln="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function cn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var Tn=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.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:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),_n=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(Tn).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=_n.omit({variation:!0,description:!0,iam:!0}),kn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),dn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(kn).max(100),savedGroups:Ke});var Y=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Y,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Vn=n.strictObject({release:Y,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Mt=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:Y,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),target:Vn})).max(4e3)}),qt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Y,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Gt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Ut=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Y,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),pn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:dn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(q,q),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),mn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:fn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...mn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...mn,evaluationMode:n.literal("remote")})]),Ln=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(q,Me),outputSchema:je,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Qe.nullable()}))})});function jn(e){return fn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];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=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.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:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.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:u?.expiresAt??null,topology:jn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:en(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function Wt(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return Ln.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,Mn=522240;function we(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 qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),D),Gn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:Xe,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),or=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:Ie,steps:n.array(Gn).min(1).max(he)}).refine(e=>X(e)<=Mn,"Segment exceeds its byte budget");var Un=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Q(e){return Array.isArray(e)?e.some(Q):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Q(u):!Un.test(t))}function gn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Q(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Q(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Q(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Bn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Bn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:v.map(I=>({condition:I.condition,target:a.outputs[I.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let I=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=I.value,o=I.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function vr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),Kn(p,c,d))}function Kn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function Ir(e,t,u,r=re){return yn(Re(e,r),t,u)}function yn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(D.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(D.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function vn(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,v,I=O=>gn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(v??=Re(e,r),yn(v,O,{attributes:Je({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||I(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let P=s.type==="end"?s.output:s.value;if(m=P?.type==="feature"?b(s.id):{...m,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?Ue({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(m.value===void 0||!qe(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:o,result:m}];if(X({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let P=s.type==="coupons"?s.couponIds.map(M=>({type:"reward",id:M})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let k=G(s,{value:P});Ge(t.variables,s,k),Object.assign(c,k)}for(let P of m.sticky)d[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let _=p.get(o);return{steps:a,...!y&&_&&(!we(_)||I(_))?{boundary:{nodeId:o,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Fr(e){return xe(e,Se)}var zn=3,Jn=2e3;function $n(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Hn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===zn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*Jn))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Hn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Qn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Qn(e,t,u){return vn(e,t,u,Se)}var hn=U.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 f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.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"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function bn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=wn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,v)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[I,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,I)&&y.processBindingIds[I]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((v,I)=>{if(!v&&I!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>o.generation)return Z(v,y);if(v?.purchase&&v.purchase.generation===o.generation&&v.purchase.operationId!==o.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==o.operationId?Z(v,y):Z(v.command?{...v,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...v,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(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,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function xn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(I){if(u&&(u.projectId!==I.projectId||u.environment!==I.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...I}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(I,b="Run identity changed during the request"){if(I!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(I){if(r&&(I.id!==r.id||I.source.type!==r.source.type||I.source.id!==r.source.id||I.source.versionId!==r.source.versionId||I.locale!==r.locale||!ie(I.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&I.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(I,b,_,O,s){if(!(I.operation==="review"&&r&&r!==_&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(I.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of v)try{m(structuredClone(r))}catch{}}},identify(I){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(I))throw new f("INVALID_TOKEN","Customer credential required");a(),g=I},subscribe(I){return v.add(I),()=>v.delete(I)},reset(){o||(o=!0,a(),g=void 0,r=null,v.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function zr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Jr(e){let t=ne(e);return t.identify(e.apiKey),t}function Rn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function j(e){let{customerToken:t,...u}=e;return u}var Zn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Sn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:j(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(N){throw m===t.generation&&(i===s||p===s)&&!x&&!Zn(N)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),N}}function I(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return _(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(j(p))!==JSON.stringify(j(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(j(i))!==JSON.stringify(j(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=v(s);d[m]=x;let N=()=>{d[m]===x&&(d[m]=null)};return x.then(N,N),x}function _(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,N){let P=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,k=P&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==P&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?P:void 0,M=i?.requestId===k?i:p?.requestId===k?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,h=l??m.purchase,E=h?.operation,F=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,R=E?.operationId??h?.quote?.operationId??F?.operationId,S=h?.receiptId??F?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&R&&S&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!o||w>=o.generation)){let C={receiptId:S,operationId:R,generation:w},T=on(E,h?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},C,T,k),t.assertCurrent(x),(!o||C.generation>=o.generation)&&(N===void 0||N>=t.readSequence)&&(T?o?.operationId===C.operationId&&(o=void 0):o=C)}else e&&k&&await e.settle(k);return t.assertCurrent(x),k?O(M):!1},stop(){c=!0},submit:I,settle:_,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Wn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=xn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=d&&bn(d),o=Sn({journal:a,state:i,call:_,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function I(l){let h=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!h&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(h?.operation==="submit"&&h.input.type==="paywall_confirm"){let C=i.view?.paywall;Rn(u,C?.quote?.operationId===h.input.operationId?C.quote:void 0)}if(e.process)return e.process.request(l);let E=i.generation;i.assertCurrent(E);let F=performance.now()+(e.timeoutMs??35e3),R=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let C=i.signal,T,K=()=>{},Fn=new Promise((Xn,Ce)=>{K=()=>Ce(C.reason),C.addEventListener("abort",K,{once:!0}),T=setTimeout(()=>Ce(new f("TIMEOUT","Longplay request timed out")),Math.max(1,F-performance.now()))});try{R=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(E),e.session.access())),Fn])}finally{clearTimeout(T),C.removeEventListener("abort",K)}}i.assertCurrent(E);let S={...l,...R?{customerToken:R}:{}},w=l.operation==="page_experiments"?ye.parse(S):U.parse(S);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!R)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let C={...w};return"customerToken"in C&&delete C.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:C},R,{timeoutMs:Math.max(1,F-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!R?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,F-performance.now())})}function b(){v(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function _(l,h){let E=t;t=void 0;let F=i.generation,R=()=>i.assertCurrent(F);a&&await o.ready,R();let S=i.view,w=In(e,E!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?E:await I(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(R(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let C=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(C&&w.settlement?.requestId!==C)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let T=await o.observe(l,w,F,h);return(!i.view||w.run.revision>=i.view.revision)&&(h===void 0||h>=i.readSequence)&&(await e.onAcceptedResponse?.(w),R()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(R(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,S,h,T)),w}function O(l){let h=i.generation;v();let E=l(),F=()=>{i.generation===h&&v()};return E.then(F,F),E}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function N(l){let h=x.get(l);if(h)return h;let E=k(l);return x.set(l,E),E}let P=!1;async function k(l){let h=await l;if(h.run.instruction?.type!=="evaluate_segment")return h;if(m)return m;P=!0;let E=i.generation,F=(async()=>{for(let R=0;R<32&&h.run.instruction?.type==="evaluate_segment";R++){if(o.pending||o.closeRequested)return h;let S=h.run;if(h.run.instruction?.type==="evaluate_segment"){let{advance:C}=await Fe(e.configuration,S,{predict:!1});if(E!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return h;if(i.view&&(i.view.revision!==S.revision||i.view.visit!==S.visit||i.view.nodeId!==S.nodeId))return _({operation:"get"});let T=!0;Fe(e.configuration,S).then(({prediction:K})=>{T&&E===i.generation&&!o.closeRequested&&i.view?.id===S.id&&!i.view.stopped&&i.view.nodeId===S.nodeId&&i.view.visit===S.visit&&i.view.revision===S.revision&&(c=K)}).catch(()=>{});try{h=await s({operation:"commit_segment",requestId:cn(S.id,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,...C})}finally{T=!1,c=null}}}return h})();m=F;try{return await F}finally{m===F&&(m=null)}}let M={get configuration(){return P?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(j(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(j(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return rn(e,l)},async pageExperiments(l,h=[]){let E=i.generation;i.assertCurrent(E);let F=i.view?.id;if(!F)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let R=pn.parse(await I(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:h})));if(i.assertCurrent(E),R.runId!==F||R.scope.projectId!==i.scope?.projectId||R.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return R},review(l){return _({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,h){let E=i.generation;l=l&&structuredClone(l),h=h&&{...h},a&&await o.ready,i.assertCurrent(E),h??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let F=JSON.stringify([i.generation,g,l??null,h??null]),R=y.get(F);if(R)return R.then(T=>structuredClone(T));let S=i.nextRead(),w=N(_({operation:"get",...l?{data:l}:{},...h?{purchase:h}:{}},S));y.set(F,w);let C=()=>{y.get(F)===w&&y.delete(F)};return w.then(C,C),w.then(T=>structuredClone(T))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?M.settle(l):o.pending?.requestId===l?N(s(o.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},retry(){return o.closeFlight?o.closeFlight:o.closing?s(o.closing):o.closeRequested&&o.pending?M.settle(o.pending.requestId):o.inFlight?N(o.inFlight):o.pending?N(s(o.pending)):Promise.reject(new f("INVALID_REQUEST","No command is pending"))},identify(l){let h=i.customerToken?void 0:t;v(),i.identify(l),t=h,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return M}function go(e,t){return Wn({...e,runToken:"",initialResponse:t})}export{cn as a,un as b,Pn as c,me as d,An as e,sn as f,Vn as g,Mt as h,qt as i,Gt as j,ye as k,pn as l,te as m,Ln as n,Wt as o,vr as p,Ir as q,In as r,Se as s,Fr as t,Qn as u,wn as v,Z as w,an as x,En as y,jr as z,ie as A,Ee as B,zr as C,Jr as D,Rn as E,Wn as F,go as G};
|
|
1
|
+
import{e as rn}from"./chunk-LS4XNIXR.js";import{h as ue,i as se,r as nn,s as pe}from"./chunk-ARIVUZUH.js";import{c as Be,d as Ke,e as J,l as en}from"./chunk-6KAADDQL.js";import{$ as U,D as Ye,R as Qe,W as Ze,X as We,Y as $,Z as Xe,_ as de,a as q,b as je,c as Me,d as qe,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,z as Je}from"./chunk-JOI5ZUBO.js";import{b as on}from"./chunk-FKDUXXGT.js";import{b as ne}from"./chunk-GRNHBOSS.js";import{a as W}from"./chunk-QE6T6NX6.js";import{D as Te,L as ae,U as D,V as De,W as Le,ja as $e,ka as le,la as He,ma as ce,t as Oe,z as Ae}from"./chunk-DVOYXRVB.js";import{a as f}from"./chunk-FCBTTR5W.js";import{h as V}from"./chunk-W5KG2IWX.js";import{b as tn}from"./chunk-FVM4JJBA.js";import{b as n}from"./chunk-Z43N7U4U.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-O4KXODTJ.js";import{a as Pe,b as Ne}from"./chunk-CILM5XMH.js";function an(e){return En({...e,namespace:"commands",identity:[e.runToken]})}function En(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??tn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var L=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Pn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:L.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:Ze,openIn:We}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:L})]),Nn={id:L,presentation:Te,outputs:n.array(L).max(250),inputs:ce,values:n.record(n.string(),D).optional(),offeringKey:q.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(L,$e.nullable())},On=n.strictObject({...Nn,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:L,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Cn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:He,variables:n.record(n.string(),D),output:D.nullable(),screen:On.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([nn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Pn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),An=n.strictObject({scope:V,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:L,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:L,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),D).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),sn=An.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var ln="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function cn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var Tn=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.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:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),_n=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(Tn).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=_n.omit({variation:!0,description:!0,iam:!0}),kn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),dn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(kn).max(100),savedGroups:Ke});var Y=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Y,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Vn=n.strictObject({release:Y,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Mt=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:Y,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),target:Vn})).max(4e3)}),qt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Y,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Gt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Ut=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Y,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),pn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:dn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(q,q),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),mn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:fn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...mn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...mn,evaluationMode:n.literal("remote")})]),Ln=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(q,Me),outputSchema:je,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Qe.nullable()}))})});function jn(e){return fn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];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=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.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:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.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:u?.expiresAt??null,topology:jn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:en(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function Wt(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return Ln.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,Mn=522240;function we(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 qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),D),Gn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:Xe,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),or=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:Ie,steps:n.array(Gn).min(1).max(he)}).refine(e=>X(e)<=Mn,"Segment exceeds its byte budget");var Un=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Q(e){return Array.isArray(e)?e.some(Q):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Q(u):!Un.test(t))}function gn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Q(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Q(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Q(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Bn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Bn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:v.map(I=>({condition:I.condition,target:a.outputs[I.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let I=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=I.value,o=I.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function vr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),Kn(p,c,d))}function Kn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function Ir(e,t,u,r=re){return yn(Re(e,r),t,u)}function yn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(D.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(D.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function vn(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,v,I=O=>gn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(v??=Re(e,r),yn(v,O,{attributes:Je({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||I(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let P=s.type==="end"?s.output:s.value;if(m=P?.type==="feature"?b(s.id):{...m,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?Ue({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(m.value===void 0||!qe(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:o,result:m}];if(X({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let P=s.type==="coupons"?s.couponIds.map(M=>({type:"reward",id:M})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let k=G(s,{value:P});Ge(t.variables,s,k),Object.assign(c,k)}for(let P of m.sticky)d[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let _=p.get(o);return{steps:a,...!y&&_&&(!we(_)||I(_))?{boundary:{nodeId:o,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Fr(e){return xe(e,Se)}var zn=3,Jn=2e3;function $n(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Hn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===zn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*Jn))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Hn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Qn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Qn(e,t,u){return vn(e,t,u,Se)}var hn=U.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 f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.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"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function bn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=wn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,v)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[I,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,I)&&y.processBindingIds[I]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((v,I)=>{if(!v&&I!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>o.generation)return Z(v,y);if(v?.purchase&&v.purchase.generation===o.generation&&v.purchase.operationId!==o.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==o.operationId?Z(v,y):Z(v.command?{...v,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...v,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(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,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function xn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(I){if(u&&(u.projectId!==I.projectId||u.environment!==I.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...I}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(I,b="Run identity changed during the request"){if(I!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(I){if(r&&(I.id!==r.id||I.source.type!==r.source.type||I.source.id!==r.source.id||I.source.versionId!==r.source.versionId||I.locale!==r.locale||!ie(I.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&I.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(I,b,_,O,s){if(!(I.operation==="review"&&r&&r!==_&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(I.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of v)try{m(structuredClone(r))}catch{}}},identify(I){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(I))throw new f("INVALID_TOKEN","Customer credential required");a(),g=I},subscribe(I){return v.add(I),()=>v.delete(I)},reset(){o||(o=!0,a(),g=void 0,r=null,v.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function zr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Jr(e){let t=ne(e);return t.identify(e.apiKey),t}function Rn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function j(e){let{customerToken:t,...u}=e;return u}var Zn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Sn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:j(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(N){throw m===t.generation&&(i===s||p===s)&&!x&&!Zn(N)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),N}}function I(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return _(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(j(p))!==JSON.stringify(j(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(j(i))!==JSON.stringify(j(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=v(s);d[m]=x;let N=()=>{d[m]===x&&(d[m]=null)};return x.then(N,N),x}function _(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,N){let P=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,k=P&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==P&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?P:void 0,M=i?.requestId===k?i:p?.requestId===k?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,h=l??m.purchase,E=h?.operation,F=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,R=E?.operationId??h?.quote?.operationId??F?.operationId,S=h?.receiptId??F?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&R&&S&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!o||w>=o.generation)){let C={receiptId:S,operationId:R,generation:w},T=on(E,h?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},C,T,k),t.assertCurrent(x),(!o||C.generation>=o.generation)&&(N===void 0||N>=t.readSequence)&&(T?o?.operationId===C.operationId&&(o=void 0):o=C)}else e&&k&&await e.settle(k);return t.assertCurrent(x),k?O(M):!1},stop(){c=!0},submit:I,settle:_,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Wn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=xn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=d&&bn(d),o=Sn({journal:a,state:i,call:_,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function I(l){let h=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!h&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(h?.operation==="submit"&&h.input.type==="paywall_confirm"){let C=i.view?.paywall;Rn(u,C?.quote?.operationId===h.input.operationId?C.quote:void 0)}if(e.process)return e.process.request(l);let E=i.generation;i.assertCurrent(E);let F=performance.now()+(e.timeoutMs??35e3),R=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let C=i.signal,T,K=()=>{},Fn=new Promise((Xn,Ce)=>{K=()=>Ce(C.reason),C.addEventListener("abort",K,{once:!0}),T=setTimeout(()=>Ce(new f("TIMEOUT","Longplay request timed out")),Math.max(1,F-performance.now()))});try{R=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(E),e.session.access())),Fn])}finally{clearTimeout(T),C.removeEventListener("abort",K)}}i.assertCurrent(E);let S={...l,...R?{customerToken:R}:{}},w=l.operation==="page_experiments"?ye.parse(S):U.parse(S);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!R)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let C={...w};return"customerToken"in C&&delete C.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:C},R,{timeoutMs:Math.max(1,F-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!R?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,F-performance.now())})}function b(){v(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function _(l,h){let E=t;t=void 0;let F=i.generation,R=()=>i.assertCurrent(F);a&&await o.ready,R();let S=i.view,w=In(e,E!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?E:await I(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(R(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let C=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(C&&w.settlement?.requestId!==C)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let T=await o.observe(l,w,F,h);return(!i.view||w.run.revision>=i.view.revision)&&(h===void 0||h>=i.readSequence)&&(await e.onAcceptedResponse?.(w),R()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(R(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,S,h,T)),w}function O(l){let h=i.generation;v();let E=l(),F=()=>{i.generation===h&&v()};return E.then(F,F),E}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function N(l){let h=x.get(l);if(h)return h;let E=k(l);return x.set(l,E),E}let P=!1;async function k(l){let h=await l;if(h.run.instruction?.type!=="evaluate_segment")return h;if(m)return m;P=!0;let E=i.generation,F=(async()=>{for(let R=0;R<32&&h.run.instruction?.type==="evaluate_segment";R++){if(o.pending||o.closeRequested)return h;let S=h.run;if(h.run.instruction?.type==="evaluate_segment"){let{advance:C}=await Fe(e.configuration,S,{predict:!1});if(E!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return h;if(i.view&&(i.view.revision!==S.revision||i.view.visit!==S.visit||i.view.nodeId!==S.nodeId))return _({operation:"get"});let T=!0;Fe(e.configuration,S).then(({prediction:K})=>{T&&E===i.generation&&!o.closeRequested&&i.view?.id===S.id&&!i.view.stopped&&i.view.nodeId===S.nodeId&&i.view.visit===S.visit&&i.view.revision===S.revision&&(c=K)}).catch(()=>{});try{h=await s({operation:"commit_segment",requestId:cn(S.id,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,...C})}finally{T=!1,c=null}}}return h})();m=F;try{return await F}finally{m===F&&(m=null)}}let M={get configuration(){return P?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(j(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(j(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return rn(e,l)},async pageExperiments(l,h=[]){let E=i.generation;i.assertCurrent(E);let F=i.view?.id;if(!F)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let R=pn.parse(await I(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:h})));if(i.assertCurrent(E),R.runId!==F||R.scope.projectId!==i.scope?.projectId||R.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return R},review(l){return _({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,h){let E=i.generation;l=l&&structuredClone(l),h=h&&{...h},a&&await o.ready,i.assertCurrent(E),h??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let F=JSON.stringify([i.generation,g,l??null,h??null]),R=y.get(F);if(R)return R.then(T=>structuredClone(T));let S=i.nextRead(),w=N(_({operation:"get",...l?{data:l}:{},...h?{purchase:h}:{}},S));y.set(F,w);let C=()=>{y.get(F)===w&&y.delete(F)};return w.then(C,C),w.then(T=>structuredClone(T))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?M.settle(l):o.pending?.requestId===l?N(s(o.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},retry(){return o.closeFlight?o.closeFlight:o.closing?s(o.closing):o.closeRequested&&o.pending?M.settle(o.pending.requestId):o.inFlight?N(o.inFlight):o.pending?N(s(o.pending)):Promise.reject(new f("INVALID_REQUEST","No command is pending"))},identify(l){let h=i.customerToken?void 0:t;v(),i.identify(l),t=h,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return M}function go(e,t){return Wn({...e,runToken:"",initialResponse:t})}export{cn as a,un as b,Pn as c,me as d,An as e,sn as f,Vn as g,Mt as h,qt as i,Gt as j,ye as k,pn as l,te as m,Ln as n,Wt as o,vr as p,Ir as q,In as r,Se as s,Fr as t,Qn as u,wn as v,Z as w,an as x,En as y,jr as z,ie as A,Ee as B,zr as C,Jr as D,Rn as E,Wn as F,go as G};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as $,m as K,p as Z}from"./chunk-2GMWNOOE.js";import{M as S,a as v,b as A,c as C,f as h,g as f,k as j,l as R,m as D,n as P,o as M,q as b,r as y}from"./chunk-FB7X4MFC.js";import{j as O,o as Q,p as G}from"./chunk-XZMM34BS.js";import{a as u,d as k,e as g,f as N,g as U,i as q,j as B,k as V,o as F,t as L}from"./chunk-TJMODHSS.js";import{b as t}from"./chunk-ZGBSTK22.js";var W={funnelId:t.uuid().optional(),funnelVersionId:t.uuid().optional()};var Y=t.strictObject({runId:t.uuid(),bindingId:t.uuid(),receiptId:t.uuid()});var _e=t.registry(),{BillingInterval:H}=(()=>{var e;return(function(i){i.OneOff="one_off",i.Week="week",i.Month="month",i.Quarter="quarter",i.SemiAnnual="semi_annual",i.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Ie}=(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')."})})}))(t),{withSpecDefault:xe}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:a})=>(e.add(n,{description:a,default:r}),n)}))(_e),{COMMON:X}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:ve}={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:Ae}=(e=>({COMMON_SET:new Set(e)}))(X),{hasNoDuplicateCurrencies:J}={hasNoDuplicateCurrencies:i=>{let n=new Set;for(let{currency:r}of i){let a=r.toLowerCase();if(n.has(a))return!1;n.add(a)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:z}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ce}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(t),{Infinite:Pe}={Infinite:"inf"},{TierBehavior:Me}=(()=>{var e;return(function(i){i.Graduated="graduated",i.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:ee}=(()=>{var e;return(function(i){i.Prepaid="prepaid",i.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Oe}=(()=>{var e;return(function(i){i.Arrear="arrear",i.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:we}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ee}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Te}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(t),{ApiCreditTierSchema:te}=(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."})})}))(t),{VIOLATION_MESSAGES:je}={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:ie}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(t),{ModelMarkupsSchema:Re}=((e,i)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),i.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(t,ie),{InvoiceUsageEntrySchema:De}=(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()}))(t),{AttachDiscountSchema:ne}=(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."})}))(t),{CustomLineItemSchema:ke}=(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."})})}))(t),{UnixMsTimestampSchema:Ne}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(t),{CreateInvoicePreviewLineSchema:Ue}=(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()})}))(t),{ReissueInvoiceParamsSchema:Ot}=(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."})})}))(t),{InvoiceModeParamsSchema:l}=(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."})}))(t),{InvoiceTemplateSchema:wt}=(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."})})}))(t),{BasePriceSchema:qe}=((e,i,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(i).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."})})}))(t,H,Ie),{CURRENCY_CODES:Be}=((e,i,n)=>({CURRENCY_CODES:[...e,...i.filter(a=>!n.has(a)).sort()]}))(X,ve,Ae),{ApiPriceProcessorsSchema:re}=((e,i)=>({ApiPriceProcessorsSchema:e.object({stripe:i.nullish()}).meta({"x-atmn-mapping":!0})}))(t,Ce),{AllocatedBillingFieldSchema:Ve}=((e,i)=>({AllocatedBillingFieldSchema:e.enum(i).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'."})}))(t,Oe),{CreditDimensionNameSchema:Fe}=((e,i,n)=>({CreditDimensionNameSchema:e.string().min(1).max(i).refine(a=>!a.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(t,we,Ee),{ApiCreditMatchSchema:ae}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Te),{findCreditTierViolations:Le}=(e=>({findCreditTierViolations:n=>{let r=[],a=(o,m)=>r.push({index:o,reason:m,message:e[m]}),s=0;for(let[o,m]of n.entries()){let p=o===n.length-1;if(m==="inf"){p||a(o,"non_final_infinity");continue}(!Number.isFinite(m)||m<=s)&&a(o,"not_increasing"),s=m,p&&a(o,"final_not_infinity")}return r}}))(je),{ApiCreditMultiplierSchema:Qe}=((e,i)=>({ApiCreditMultiplierSchema:e.object({match:i,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."})}))(t,ae),{ProviderMarkupsSchema:Ge}=((e,i)=>({ProviderMarkupsSchema:e.record(e.string(),i).nullish()}))(t,ie),{InvoiceFeatureQuantitySchema:oe}=((e,i,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(i).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(a=>a.quantity!==void 0!=(a.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(t,ee,De),{CreateInvoicePreviewSchema:Et}=((e,i)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(i),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()})}))(t,Ue),{SUPPORTED_SET:$e}=(e=>({SUPPORTED_SET:new Set(e)}))(Be),{ApiCreditDimensionBaseSchema:Ke}=((e,i)=>({ApiCreditDimensionBaseSchema:e.object({match:i,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(t,ae),{refineGraduatedTiers:ce}=(e=>({refineGraduatedTiers:(n,r)=>{let a=e(n.tiers.map(s=>s.to));for(let{index:s,message:o}of a)r.addIssue({code:"custom",message:o,path:["tiers",s,"to"]})}}))(Le),{ApiFeatureMarkupsOverrideSchema:Ze}=((e,i,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:i.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."})})}))(t,Ge,Re),{isValidCurrencyCode:We}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))($e),{ApiCreditDimensionSchema:Ye}=((e,i,n,r)=>({ApiCreditDimensionSchema:e.union([i.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),i.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(t,Ke,te,ce),{CurrencyCodeSchema:se}=((e,i)=>({CurrencyCodeSchema:e.string().refine(i,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(t,We),{AdditionalCurrencyTierSchema:He}=((e,i)=>({AdditionalCurrencyTierSchema:e.object({currency:i,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"]})}))(t,se),{ApiCreditSchemaItemBaseSchema:ue}=((e,i,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(i,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(i,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(t,Fe,Ye,Qe),{ApiFlatCreditSchemaItemSchema:Xe}=((e,i)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:i.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(ue,t),{AdditionalCurrencyPriceSchema:Je}=((e,i)=>({AdditionalCurrencyPriceSchema:e.object({currency:i,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(t,se),{AdditionalCurrencyTierArraySchema:ze}=((e,i,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(i).refine(n,{message:r})}))(t,He,J,z),{ApiGraduatedCreditSchemaItemSchema:et}=((e,i,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:i.literal("graduated"),tiers:i.array(n).min(1)}).strict().superRefine(r)}))(ue,t,te,ce),{AdditionalCurrencyPriceArraySchema:me}=((e,i,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(i).refine(n,{message:r})}))(t,Je,J,z),{ApiUsageTierWithCurrenciesSchema:tt}=((e,i,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(i)),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(a=>a.amount!==void 0||a.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(a=>({...a,amount:a.amount??0})).pipe(e.object({to:e.number().or(e.literal(i)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(t,Pe,ze),{ApiCreditSchemaItemSchema:it}=((e,i,n)=>({ApiCreditSchemaItemSchema:e.union([i,n])}))(t,et,Xe),{BasePriceParamsSchema:nt}=((e,i,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:i({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."})}))(qe,xe,t,me),{PlanItemPriceParamsSchema:rt}=((e,i,n,r,a,s,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(p=>p??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:i.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(a).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(s).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."})})}))(t,me,tt,Me,H,ee,Ve),{ApiFeatureOverrideSchema:at}=((e,i,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(i).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."})})}))(t,it,Ze),{InvoiceBasePriceParamsSchema:de}=((e,i)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(nt,re),{InvoiceItemPriceParamsSchema:ot}=((e,i)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(rt,re),{InvoiceLicenseQuantitySchema:ct}=((e,i,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:i.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()}))(t,de,oe),{InvoiceCustomizeItemSchema:st}=((e,i,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:i.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()}))(t,ot,at),{InvoiceCustomizeSchema:ut}=((e,i,n)=>({InvoiceCustomizeSchema:e.object({price:i.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."})}))(t,de,st),{InvoicePlanParamsSchema:mt}=((e,i,n,r,a)=>({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:i.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(a).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()}))(t,ut,oe,ct,ne),{CreateInvoiceParamsSchema:Tt}=((e,i,n,r,a)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(i).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:a.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:a.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."})}))(t,mt,ke,ne,Ne);var w=t.object({type:t.literal("native_purchase"),receiptId:t.uuid(),orderId:t.uuid(),productVersionId:t.uuid(),provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),productKind:q,replacement:t.strictObject({sourceOrderId:t.uuid(),sourceProductId:t.string().min(1).max(255),policy:t.enum(["apple_store","google_full_price"]),sourceAccountTokens:t.array(t.uuid()).max(50)}).nullable(),appAccountToken:t.uuid().optional(),obfuscatedAccountId:t.string().min(1).max(64).optional(),obfuscatedProfileId:t.uuid().optional(),basePlanId:t.string().min(1).max(255).optional(),offerId:t.string().min(1).max(255).optional(),offerKind:t.enum(["none","introductory","promotional"]),currency:u,catalogAmountMinor:t.number().int().nonnegative().max(1e8),discountMinor:t.number().int().nonnegative().max(1e8),trialDays:t.number().int().min(1).max(730).nullable(),seatBundle:t.array(t.strictObject({key:t.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:t.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:t.strictObject({offerId:t.string().min(1).max(255),keyId:t.string().min(1).max(255),nonce:t.uuid(),signature:t.string().min(1).max(1024),timestamp:t.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,i)=>{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(a=>a.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)))&&i.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var pe=t.strictObject({itemKey:t.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:t.uuid(),includedAmount:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:t.number().int().min(0).max(1e4),terms:N,pricing:k.optional(),unitAmountMinor:t.number().int().min(0).max(1e8),productId:t.string().min(1).max(255).nullable(),priceId:t.string().min(1).max(255).nullable()}).superRefine((e,i)=>{(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)&&i.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{U(e.includedAmount,e.terms.units,e.quantity),g({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{i.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var _=t.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"),Qt=t.object({amountCents:t.number().int().min(0).max(1e8),currency:u,interval:t.enum(["free","month","year"]),currencyOptions:t.partialRecord(u,t.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");var ai=t.strictObject({requestId:t.uuid(),predecessorOperationId:t.uuid().optional(),invoiceMode:l.optional(),entityId:t.uuid().optional(),billingSubscriptionId:t.uuid().optional(),newBillingSubscription:t.literal(!0).optional(),offerId:t.uuid().optional(),nativeOffer:O.optional(),plans:t.array(t.strictObject({productVersionId:t.uuid(),seatQuantities:t.record(_,t.number().int().min(0).max(1e4)).optional(),featureQuantities:t.record(t.uuid(),t.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(i=>i.productVersionId)).size===e.length,"Plan versions must be unique"),provider:t.enum(["stripe","apple","google","merchant"]),currency:u}).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"),oi=t.strictObject({operationId:t.uuid()}),c=t.number().int().min(0).max(1e8),dt=t.strictObject({lineId:t.uuid(),productVersionId:t.uuid(),productName:t.string().min(1).max(80),interval:t.enum(["free","week","month","year","one_time"]),intervalCount:t.number().int().min(1).max(156).optional(),baseAmountMinor:c,seats:t.array(t.strictObject({key:_,quantity:t.number().int().min(0).max(1e4),includedQuantity:t.number().int().min(0).max(1e4),maximumQuantity:t.number().int().min(0).max(1e4),unitAmountMinor:c})).max(20),prepaid:t.array(pe).max(100).optional(),catalogAmountMinor:c,trial:j.nullable()}).refine(e=>new Set(e.seats.map(i=>i.key)).size===e.seats.length&&e.seats.every(i=>i.quantity>=i.includedQuantity&&i.quantity<=i.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((i,n)=>i+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((i,n)=>i+g({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"),fe=t.string().regex(/^[A-Za-z0-9_-]{1,200}$/),pt=t.strictObject({id:fe,name:t.string().min(1).max(40),percent_off:t.number().gt(0).max(100).optional(),amount_off:t.number().int().positive().optional(),currency:t.string().regex(/^[a-z]{3}$/).optional(),duration:t.enum(["once","repeating","forever"]),duration_in_months:t.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"),lt=t.strictObject({subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:t.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:t.array(t.strictObject({id:t.string(),price_id:t.string(),quantity:t.number().int().nonnegative(),discounts:t.array(t.strictObject({id:t.string(),coupon:t.string(),start:t.number(),end:t.number().nullable()})).optional()})).min(1).max(100),prorationDate:t.number().int().nonnegative(),amountMinor:t.number().int().positive(),periodStartMs:t.number(),periodEndMs:t.number()}),be=t.strictObject({invoiceMode:l.optional(),append:lt.optional(),provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),mode:t.enum(["payment","subscription"]),lineItems:t.array(t.strictObject({price:t.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:t.number().int().min(1).max(1e4),priceId:t.uuid(),productName:t.string().min(1).max(80),amountMinor:t.number().int().min(0).max(1e8),currency:t.string().regex(/^[a-z]{3}$/),interval:t.enum(["week","month","year","one_off"]),intervalCount:t.number().int().min(1).max(52),slot:t.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:t.strictObject({mode:t.enum(["graduated","volume"]),tiers:t.array(t.strictObject({upTo:t.number().int().min(1).max(1e6).nullable(),unitAmountMinor:t.number().int().min(0).max(1e8),flatAmountMinor:t.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:t.array(t.strictObject({coupon:fe,terms:pt})).max(1),trialPeriodDays:t.number().int().min(1).max(730).nullable(),metadata:t.strictObject({grooveCheckoutId:t.uuid(),grooveCustomerId:t.uuid()}),expiresAt:t.iso.datetime({offset:!0})}),ht=t.strictObject({operationId:t.uuid(),merchantTerms:b.optional(),entityId:t.uuid().nullable(),billingSubscriptionId:t.uuid().nullable(),discount:t.strictObject({offerId:t.uuid(),couponId:t.uuid(),discount:Q,duration:G,amountMinor:c,allocations:t.array(t.strictObject({productVersionId:t.uuid(),amountMinor:c})).min(1).max(20),expiresAt:t.iso.datetime({offset:!0})}).nullable(),charge:t.strictObject({effectiveAt:t.iso.datetime({offset:!0}),periodEndsAt:t.iso.datetime({offset:!0}),debitMinor:c,discountMinor:c,taxMinor:c,totalMinor:c}).nullable(),expiresAt:t.iso.datetime({offset:!0}),provider:t.enum(["stripe","apple","google","merchant"]),nativeOffer:O.optional(),currency:u,lines:t.array(dt).min(1).max(20),catalogAmountMinor:c,nativeDiscountMinor:c.optional(),automaticTax:t.boolean(),execution:t.union([be,v]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&y(e.merchantTerms,e.operationId,"purchase",e.currency)).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(i=>!["one_time","free"].includes(i.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(i=>i.price!==null))&&e.execution.discounts.every(i=>i.coupon===i.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(i=>e.discount!==null&&(i.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&i.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${i.terms.amount_off}`&&i.terms.amount_off===e.discount.discount.amountOffCents&&i.terms.currency?.toUpperCase()===e.currency&&i.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((i,n)=>{let r=e.lines[n];return r!==void 0&&i.productVersionId===r.productVersionId&&i.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((i,n)=>i+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(i=>i.lineId)).size===e.lines.length&&e.lines.reduce((i,n)=>i+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),ci=t.strictObject({operationId:t.uuid(),orderId:t.uuid(),append:t.boolean().optional(),invoiceMode:t.boolean().optional(),status:t.enum(["pending","complete","cancelled","failed"]),executor:t.enum(["indiana","merchant"]),checkoutUrl:t.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:t.union([be,v]).nullable(),currency:u,catalogAmountMinor:c,taxMinor:c,totalMinor:t.number().int().min(0).max(2e8).nullable(),quoteFinalized:t.boolean(),nativePurchase:w.nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),quote:ht.optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),authority:S.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"),x=t.strictObject({enabled:t.literal(!0),featureIds:t.array(t.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),si=t.strictObject({requestId:t.uuid(),offerId:t.uuid().optional(),invoiceMode:l.optional(),membershipId:t.uuid(),carryOverBalances:x.optional(),carryOverUsages:x.optional(),membershipIds:t.array(t.uuid()).min(1).max(20).optional(),prorationBehavior:t.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:t.enum(["immediate","renewal","store"]),change:t.discriminatedUnion("type",[t.strictObject({type:t.literal("plan"),productVersionId:t.uuid()}),t.strictObject({type:t.literal("seats"),licenseKey:_,quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("quantity"),internal_feature_id:t.uuid(),quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("cancel")}),t.strictObject({type:t.literal("uncancel")}),t.strictObject({type:t.literal("billing_cycle"),billingCycleAnchor:t.union([t.literal("now"),t.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>!e.offerId||e.change.type==="plan"&&e.timing!=="store","A selected plan-change offer requires a merchant target Product").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"),I=t.string().regex(/^price_[A-Za-z0-9]+$/),le=t.strictObject({grooveUpdateId:t.uuid(),grooveCustomerId:t.uuid()}),he=t.strictObject({price:I.nullable(),priceId:t.uuid().optional(),quantity:t.number().int().min(0).max(1e4)}),ye=t.strictObject({provider:t.literal("stripe"),invoiceMode:l.optional(),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),action:t.enum(["update","cancel","schedule","release"]),update:t.strictObject({items:t.array(he).max(20),remove:t.array(I).max(20),restoreItems:t.array(t.strictObject({price:I,quantity:t.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:t.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:t.number().int().positive().optional(),paymentBehavior:t.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:t.boolean().optional(),clearCancelAt:t.literal(!0).optional(),billingCycleAnchorNow:t.literal(!0).optional(),metadata:le}).nullable(),cancel:t.strictObject({prorate:t.literal(!1),invoiceNow:t.literal(!1)}).nullable(),schedule:t.strictObject({currentItems:t.array(t.strictObject({price:I,quantity:t.number().int().min(0).max(1e4)})).max(20),nextItems:t.array(he).min(1).max(20),switchAt:t.number().int().positive(),interval:t.enum(["week","month","year"]),intervalCount:t.number().int().min(1).max(52),resetBillingCycleAnchor:t.literal(!0).optional(),metadata:le}).nullable(),release:t.strictObject({schedule:t.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:t.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(i=>e[i]!==null==(e.action===i))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(i=>i.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),ge=t.strictObject({merchantTerms:b.optional(),carryOverBalances:x.optional(),carryOverUsages:x.optional(),operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.enum(["immediate","renewal"]),effectiveAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}),currency:u,creditMinor:c,debitMinor:c,discountMinor:c,taxMinor:c,totalMinor:c,retainedProductVersionIds:t.array(t.uuid()).max(19),execution:t.union([ye,A])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&y(e.merchantTerms,e.operationId,"subscription_change",e.currency)),ft=t.strictObject({operationId:t.uuid(),invoiceMode:t.boolean().optional(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:t.enum(["immediate","renewal"]),effectiveAt:t.iso.datetime({offset:!0}),checkoutUrl:t.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:t.enum(["indiana","merchant"]),execution:t.union([ye,A]).nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),quote:ge.optional(),authority:S.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),bt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.literal("store"),effectiveAt:t.null(),expiresAt:t.iso.datetime({offset:!0}),currency:u,creditMinor:t.null(),debitMinor:t.null(),discountMinor:t.null(),taxMinor:t.null(),totalMinor:t.null(),retainedProductVersionIds:t.array(t.uuid()).max(19),store:t.strictObject({provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),catalogAmountMinor:c,policy:t.enum(["apple_store","google_full_price"])})}),yt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","pending","effective","cancelled","failed"]),timing:t.literal("store"),effectiveAt:t.iso.datetime({offset:!0}).nullable(),checkoutUrl:t.null(),nativePurchase:w.nullable()}),ui=t.union([ge,bt]),mi=t.union([ft,yt]),E=R,d=D,di=t.strictObject({requestId:t.uuid(),invoiceId:t.uuid(),...M.shape}).refine(P,"A partial refund states amountMinor; a full refund refunds the remaining amount"),Se=t.strictObject({provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:t.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:E,currency:t.string().regex(/^[a-z]{3}$/),metadata:t.strictObject({indianaRefundId:t.uuid()}),idempotencyKey:t.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:t.array(t.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),gt=t.strictObject({operationId:t.uuid(),merchantTerms:b.optional(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),currency:u,paidMinor:d,refundedMinor:d,pendingMinor:d,amountMinor:E,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),revokes:t.strictObject({customerProductIds:t.array(t.uuid()).max(100),subscriptionIds:t.array(t.string().min(1).max(200)).max(20)}),execution:t.union([Se,C]),expiresAt:t.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&y(e.merchantTerms,e.operationId,"refund",e.currency)).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"),St=t.strictObject({operationId:t.uuid(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),status:t.enum(["quoted","pending","succeeded","failed","expired"]),executor:t.enum(["indiana","merchant"]),currency:u,amountMinor:E,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),refundId:t.string().min(1).max(200).nullable(),quote:gt.optional(),execution:t.union([Se,C]).nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),authority:S.optional(),failureReason:t.string().min(1).max(200).nullable(),createdAt:t.iso.datetime({offset:!0}),completedAt:t.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"),pi=t.strictObject({invoiceId:t.uuid(),currency:u,paidMinor:d,refundedMinor:d,pendingMinor:d,refundableMinor:d,executor:t.enum(["indiana","merchant"]).nullable(),canRefund:t.boolean(),operations:t.array(St).max(50)}).refine(e=>e.operations.every(i=>i.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),li=t.strictObject({requestId:t.uuid(),...M.shape}).refine(P,"A partial refund states amountMinor; a full refund refunds the remaining amount");var Ai=t.strictObject({processContext:Y.optional(),...W,selector:t.discriminatedUnion("type",[t.strictObject({type:t.literal("paywall"),paywallId:t.uuid()}),t.strictObject({type:t.literal("version"),versionId:t.uuid()})]),customerId:t.uuid().optional(),commerce:B,locale:t.string().min(1).max(35),requirement:V.optional()}),T=t.strictObject({id:t.uuid(),paywallId:t.uuid(),version:t.number().int().positive(),document:$.omit({requirement:!0,offeringId:!0}),offering:t.strictObject({id:t.uuid()}),content:t.strictObject({environmentId:t.uuid(),offeringVersionId:t.uuid(),artifact:Z.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:L,check:F.nullable()}).superRefine((e,i)=>{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)))&&i.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Ci=t.strictObject(T.shape).omit({document:!0,offering:!0}).extend({content:T.shape.content.unwrap()});function Pi(e,i){let n=K.parse(i);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[a,s]of Object.entries(n.catalog)){let o=r.plans[a],m=s.channels.stripe?.prices.find(p=>p.currency===o?.currency);o&&m&&Object.assign(o,{amountMinor:m.amountMinor,interval:s.interval,intervalCount:s.intervalCount,...s.prepaid?.length?{prepaid:s.prepaid}:{}})}return T.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}})}export{W as a,Y as b,Ot as c,Et as d,Tt as e,ai as f,oi as g,ht as h,ci as i,si as j,ge as k,ui as l,mi as m,di as n,gt as o,St as p,Ai as q,T as r,Ci as s,Pi as t};
|
|
1
|
+
import{a as $,m as K,p as Z}from"./chunk-6KAADDQL.js";import{M as S,a as v,b as A,c as C,f as h,g as f,k as j,l as R,m as D,n as P,o as M,q as b,r as y}from"./chunk-4GZKK2RE.js";import{j as O,o as Q,p as G}from"./chunk-JOI5ZUBO.js";import{a as u,d as k,e as g,f as N,g as U,i as q,j as B,k as V,o as F,t as L}from"./chunk-DVOYXRVB.js";import{b as t}from"./chunk-Z43N7U4U.js";var W={funnelId:t.uuid().optional(),funnelVersionId:t.uuid().optional()};var Y=t.strictObject({runId:t.uuid(),bindingId:t.uuid(),receiptId:t.uuid()});var _e=t.registry(),{BillingInterval:H}=(()=>{var e;return(function(i){i.OneOff="one_off",i.Week="week",i.Month="month",i.Quarter="quarter",i.SemiAnnual="semi_annual",i.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Ie}=(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')."})})}))(t),{withSpecDefault:xe}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:a})=>(e.add(n,{description:a,default:r}),n)}))(_e),{COMMON:X}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:ve}={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:Ae}=(e=>({COMMON_SET:new Set(e)}))(X),{hasNoDuplicateCurrencies:J}={hasNoDuplicateCurrencies:i=>{let n=new Set;for(let{currency:r}of i){let a=r.toLowerCase();if(n.has(a))return!1;n.add(a)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:z}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ce}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(t),{Infinite:Pe}={Infinite:"inf"},{TierBehavior:Me}=(()=>{var e;return(function(i){i.Graduated="graduated",i.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:ee}=(()=>{var e;return(function(i){i.Prepaid="prepaid",i.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Oe}=(()=>{var e;return(function(i){i.Arrear="arrear",i.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:we}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ee}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Te}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(t),{ApiCreditTierSchema:te}=(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."})})}))(t),{VIOLATION_MESSAGES:je}={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:ie}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(t),{ModelMarkupsSchema:Re}=((e,i)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),i.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(t,ie),{InvoiceUsageEntrySchema:De}=(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()}))(t),{AttachDiscountSchema:ne}=(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."})}))(t),{CustomLineItemSchema:ke}=(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."})})}))(t),{UnixMsTimestampSchema:Ne}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(t),{CreateInvoicePreviewLineSchema:Ue}=(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()})}))(t),{ReissueInvoiceParamsSchema:Ot}=(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."})})}))(t),{InvoiceModeParamsSchema:l}=(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."})}))(t),{InvoiceTemplateSchema:wt}=(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."})})}))(t),{BasePriceSchema:qe}=((e,i,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(i).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."})})}))(t,H,Ie),{CURRENCY_CODES:Be}=((e,i,n)=>({CURRENCY_CODES:[...e,...i.filter(a=>!n.has(a)).sort()]}))(X,ve,Ae),{ApiPriceProcessorsSchema:re}=((e,i)=>({ApiPriceProcessorsSchema:e.object({stripe:i.nullish()}).meta({"x-atmn-mapping":!0})}))(t,Ce),{AllocatedBillingFieldSchema:Ve}=((e,i)=>({AllocatedBillingFieldSchema:e.enum(i).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'."})}))(t,Oe),{CreditDimensionNameSchema:Fe}=((e,i,n)=>({CreditDimensionNameSchema:e.string().min(1).max(i).refine(a=>!a.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(t,we,Ee),{ApiCreditMatchSchema:ae}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Te),{findCreditTierViolations:Le}=(e=>({findCreditTierViolations:n=>{let r=[],a=(o,m)=>r.push({index:o,reason:m,message:e[m]}),s=0;for(let[o,m]of n.entries()){let p=o===n.length-1;if(m==="inf"){p||a(o,"non_final_infinity");continue}(!Number.isFinite(m)||m<=s)&&a(o,"not_increasing"),s=m,p&&a(o,"final_not_infinity")}return r}}))(je),{ApiCreditMultiplierSchema:Qe}=((e,i)=>({ApiCreditMultiplierSchema:e.object({match:i,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."})}))(t,ae),{ProviderMarkupsSchema:Ge}=((e,i)=>({ProviderMarkupsSchema:e.record(e.string(),i).nullish()}))(t,ie),{InvoiceFeatureQuantitySchema:oe}=((e,i,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(i).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(a=>a.quantity!==void 0!=(a.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(t,ee,De),{CreateInvoicePreviewSchema:Et}=((e,i)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(i),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()})}))(t,Ue),{SUPPORTED_SET:$e}=(e=>({SUPPORTED_SET:new Set(e)}))(Be),{ApiCreditDimensionBaseSchema:Ke}=((e,i)=>({ApiCreditDimensionBaseSchema:e.object({match:i,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(t,ae),{refineGraduatedTiers:ce}=(e=>({refineGraduatedTiers:(n,r)=>{let a=e(n.tiers.map(s=>s.to));for(let{index:s,message:o}of a)r.addIssue({code:"custom",message:o,path:["tiers",s,"to"]})}}))(Le),{ApiFeatureMarkupsOverrideSchema:Ze}=((e,i,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:i.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."})})}))(t,Ge,Re),{isValidCurrencyCode:We}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))($e),{ApiCreditDimensionSchema:Ye}=((e,i,n,r)=>({ApiCreditDimensionSchema:e.union([i.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),i.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(t,Ke,te,ce),{CurrencyCodeSchema:se}=((e,i)=>({CurrencyCodeSchema:e.string().refine(i,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(t,We),{AdditionalCurrencyTierSchema:He}=((e,i)=>({AdditionalCurrencyTierSchema:e.object({currency:i,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"]})}))(t,se),{ApiCreditSchemaItemBaseSchema:ue}=((e,i,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(i,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(i,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(t,Fe,Ye,Qe),{ApiFlatCreditSchemaItemSchema:Xe}=((e,i)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:i.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(ue,t),{AdditionalCurrencyPriceSchema:Je}=((e,i)=>({AdditionalCurrencyPriceSchema:e.object({currency:i,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(t,se),{AdditionalCurrencyTierArraySchema:ze}=((e,i,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(i).refine(n,{message:r})}))(t,He,J,z),{ApiGraduatedCreditSchemaItemSchema:et}=((e,i,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:i.literal("graduated"),tiers:i.array(n).min(1)}).strict().superRefine(r)}))(ue,t,te,ce),{AdditionalCurrencyPriceArraySchema:me}=((e,i,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(i).refine(n,{message:r})}))(t,Je,J,z),{ApiUsageTierWithCurrenciesSchema:tt}=((e,i,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(i)),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(a=>a.amount!==void 0||a.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(a=>({...a,amount:a.amount??0})).pipe(e.object({to:e.number().or(e.literal(i)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(t,Pe,ze),{ApiCreditSchemaItemSchema:it}=((e,i,n)=>({ApiCreditSchemaItemSchema:e.union([i,n])}))(t,et,Xe),{BasePriceParamsSchema:nt}=((e,i,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:i({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."})}))(qe,xe,t,me),{PlanItemPriceParamsSchema:rt}=((e,i,n,r,a,s,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(p=>p??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:i.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(a).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(s).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."})})}))(t,me,tt,Me,H,ee,Ve),{ApiFeatureOverrideSchema:at}=((e,i,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(i).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."})})}))(t,it,Ze),{InvoiceBasePriceParamsSchema:de}=((e,i)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(nt,re),{InvoiceItemPriceParamsSchema:ot}=((e,i)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(rt,re),{InvoiceLicenseQuantitySchema:ct}=((e,i,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:i.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()}))(t,de,oe),{InvoiceCustomizeItemSchema:st}=((e,i,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:i.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()}))(t,ot,at),{InvoiceCustomizeSchema:ut}=((e,i,n)=>({InvoiceCustomizeSchema:e.object({price:i.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."})}))(t,de,st),{InvoicePlanParamsSchema:mt}=((e,i,n,r,a)=>({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:i.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(a).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()}))(t,ut,oe,ct,ne),{CreateInvoiceParamsSchema:Tt}=((e,i,n,r,a)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(i).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:a.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:a.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."})}))(t,mt,ke,ne,Ne);var w=t.object({type:t.literal("native_purchase"),receiptId:t.uuid(),orderId:t.uuid(),productVersionId:t.uuid(),provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),productKind:q,replacement:t.strictObject({sourceOrderId:t.uuid(),sourceProductId:t.string().min(1).max(255),policy:t.enum(["apple_store","google_full_price"]),sourceAccountTokens:t.array(t.uuid()).max(50)}).nullable(),appAccountToken:t.uuid().optional(),obfuscatedAccountId:t.string().min(1).max(64).optional(),obfuscatedProfileId:t.uuid().optional(),basePlanId:t.string().min(1).max(255).optional(),offerId:t.string().min(1).max(255).optional(),offerKind:t.enum(["none","introductory","promotional"]),currency:u,catalogAmountMinor:t.number().int().nonnegative().max(1e8),discountMinor:t.number().int().nonnegative().max(1e8),trialDays:t.number().int().min(1).max(730).nullable(),seatBundle:t.array(t.strictObject({key:t.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:t.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:t.strictObject({offerId:t.string().min(1).max(255),keyId:t.string().min(1).max(255),nonce:t.uuid(),signature:t.string().min(1).max(1024),timestamp:t.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,i)=>{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(a=>a.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)))&&i.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var pe=t.strictObject({itemKey:t.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:t.uuid(),includedAmount:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:t.number().int().min(0).max(1e4),terms:N,pricing:k.optional(),unitAmountMinor:t.number().int().min(0).max(1e8),productId:t.string().min(1).max(255).nullable(),priceId:t.string().min(1).max(255).nullable()}).superRefine((e,i)=>{(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)&&i.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{U(e.includedAmount,e.terms.units,e.quantity),g({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{i.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var _=t.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"),Qt=t.object({amountCents:t.number().int().min(0).max(1e8),currency:u,interval:t.enum(["free","month","year"]),currencyOptions:t.partialRecord(u,t.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");var ai=t.strictObject({requestId:t.uuid(),predecessorOperationId:t.uuid().optional(),invoiceMode:l.optional(),entityId:t.uuid().optional(),billingSubscriptionId:t.uuid().optional(),newBillingSubscription:t.literal(!0).optional(),offerId:t.uuid().optional(),nativeOffer:O.optional(),plans:t.array(t.strictObject({productVersionId:t.uuid(),seatQuantities:t.record(_,t.number().int().min(0).max(1e4)).optional(),featureQuantities:t.record(t.uuid(),t.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(i=>i.productVersionId)).size===e.length,"Plan versions must be unique"),provider:t.enum(["stripe","apple","google","merchant"]),currency:u}).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"),oi=t.strictObject({operationId:t.uuid()}),c=t.number().int().min(0).max(1e8),dt=t.strictObject({lineId:t.uuid(),productVersionId:t.uuid(),productName:t.string().min(1).max(80),interval:t.enum(["free","week","month","year","one_time"]),intervalCount:t.number().int().min(1).max(156).optional(),baseAmountMinor:c,seats:t.array(t.strictObject({key:_,quantity:t.number().int().min(0).max(1e4),includedQuantity:t.number().int().min(0).max(1e4),maximumQuantity:t.number().int().min(0).max(1e4),unitAmountMinor:c})).max(20),prepaid:t.array(pe).max(100).optional(),catalogAmountMinor:c,trial:j.nullable()}).refine(e=>new Set(e.seats.map(i=>i.key)).size===e.seats.length&&e.seats.every(i=>i.quantity>=i.includedQuantity&&i.quantity<=i.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((i,n)=>i+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((i,n)=>i+g({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"),fe=t.string().regex(/^[A-Za-z0-9_-]{1,200}$/),pt=t.strictObject({id:fe,name:t.string().min(1).max(40),percent_off:t.number().gt(0).max(100).optional(),amount_off:t.number().int().positive().optional(),currency:t.string().regex(/^[a-z]{3}$/).optional(),duration:t.enum(["once","repeating","forever"]),duration_in_months:t.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"),lt=t.strictObject({subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:t.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:t.array(t.strictObject({id:t.string(),price_id:t.string(),quantity:t.number().int().nonnegative(),discounts:t.array(t.strictObject({id:t.string(),coupon:t.string(),start:t.number(),end:t.number().nullable()})).optional()})).min(1).max(100),prorationDate:t.number().int().nonnegative(),amountMinor:t.number().int().positive(),periodStartMs:t.number(),periodEndMs:t.number()}),be=t.strictObject({invoiceMode:l.optional(),append:lt.optional(),provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),mode:t.enum(["payment","subscription"]),lineItems:t.array(t.strictObject({price:t.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:t.number().int().min(1).max(1e4),priceId:t.uuid(),productName:t.string().min(1).max(80),amountMinor:t.number().int().min(0).max(1e8),currency:t.string().regex(/^[a-z]{3}$/),interval:t.enum(["week","month","year","one_off"]),intervalCount:t.number().int().min(1).max(52),slot:t.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:t.strictObject({mode:t.enum(["graduated","volume"]),tiers:t.array(t.strictObject({upTo:t.number().int().min(1).max(1e6).nullable(),unitAmountMinor:t.number().int().min(0).max(1e8),flatAmountMinor:t.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:t.array(t.strictObject({coupon:fe,terms:pt})).max(1),trialPeriodDays:t.number().int().min(1).max(730).nullable(),metadata:t.strictObject({grooveCheckoutId:t.uuid(),grooveCustomerId:t.uuid()}),expiresAt:t.iso.datetime({offset:!0})}),ht=t.strictObject({operationId:t.uuid(),merchantTerms:b.optional(),entityId:t.uuid().nullable(),billingSubscriptionId:t.uuid().nullable(),discount:t.strictObject({offerId:t.uuid(),couponId:t.uuid(),discount:Q,duration:G,amountMinor:c,allocations:t.array(t.strictObject({productVersionId:t.uuid(),amountMinor:c})).min(1).max(20),expiresAt:t.iso.datetime({offset:!0})}).nullable(),charge:t.strictObject({effectiveAt:t.iso.datetime({offset:!0}),periodEndsAt:t.iso.datetime({offset:!0}),debitMinor:c,discountMinor:c,taxMinor:c,totalMinor:c}).nullable(),expiresAt:t.iso.datetime({offset:!0}),provider:t.enum(["stripe","apple","google","merchant"]),nativeOffer:O.optional(),currency:u,lines:t.array(dt).min(1).max(20),catalogAmountMinor:c,nativeDiscountMinor:c.optional(),automaticTax:t.boolean(),execution:t.union([be,v]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&y(e.merchantTerms,e.operationId,"purchase",e.currency)).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(i=>!["one_time","free"].includes(i.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(i=>i.price!==null))&&e.execution.discounts.every(i=>i.coupon===i.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(i=>e.discount!==null&&(i.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&i.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${i.terms.amount_off}`&&i.terms.amount_off===e.discount.discount.amountOffCents&&i.terms.currency?.toUpperCase()===e.currency&&i.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((i,n)=>{let r=e.lines[n];return r!==void 0&&i.productVersionId===r.productVersionId&&i.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((i,n)=>i+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(i=>i.lineId)).size===e.lines.length&&e.lines.reduce((i,n)=>i+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),ci=t.strictObject({operationId:t.uuid(),orderId:t.uuid(),append:t.boolean().optional(),invoiceMode:t.boolean().optional(),status:t.enum(["pending","complete","cancelled","failed"]),executor:t.enum(["indiana","merchant"]),checkoutUrl:t.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:t.union([be,v]).nullable(),currency:u,catalogAmountMinor:c,taxMinor:c,totalMinor:t.number().int().min(0).max(2e8).nullable(),quoteFinalized:t.boolean(),nativePurchase:w.nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),quote:ht.optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),authority:S.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"),x=t.strictObject({enabled:t.literal(!0),featureIds:t.array(t.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),si=t.strictObject({requestId:t.uuid(),offerId:t.uuid().optional(),invoiceMode:l.optional(),membershipId:t.uuid(),carryOverBalances:x.optional(),carryOverUsages:x.optional(),membershipIds:t.array(t.uuid()).min(1).max(20).optional(),prorationBehavior:t.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:t.enum(["immediate","renewal","store"]),change:t.discriminatedUnion("type",[t.strictObject({type:t.literal("plan"),productVersionId:t.uuid()}),t.strictObject({type:t.literal("seats"),licenseKey:_,quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("quantity"),internal_feature_id:t.uuid(),quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("cancel")}),t.strictObject({type:t.literal("uncancel")}),t.strictObject({type:t.literal("billing_cycle"),billingCycleAnchor:t.union([t.literal("now"),t.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>!e.offerId||e.change.type==="plan"&&e.timing!=="store","A selected plan-change offer requires a merchant target Product").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"),I=t.string().regex(/^price_[A-Za-z0-9]+$/),le=t.strictObject({grooveUpdateId:t.uuid(),grooveCustomerId:t.uuid()}),he=t.strictObject({price:I.nullable(),priceId:t.uuid().optional(),quantity:t.number().int().min(0).max(1e4)}),ye=t.strictObject({provider:t.literal("stripe"),invoiceMode:l.optional(),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),action:t.enum(["update","cancel","schedule","release"]),update:t.strictObject({items:t.array(he).max(20),remove:t.array(I).max(20),restoreItems:t.array(t.strictObject({price:I,quantity:t.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:t.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:t.number().int().positive().optional(),paymentBehavior:t.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:t.boolean().optional(),clearCancelAt:t.literal(!0).optional(),billingCycleAnchorNow:t.literal(!0).optional(),metadata:le}).nullable(),cancel:t.strictObject({prorate:t.literal(!1),invoiceNow:t.literal(!1)}).nullable(),schedule:t.strictObject({currentItems:t.array(t.strictObject({price:I,quantity:t.number().int().min(0).max(1e4)})).max(20),nextItems:t.array(he).min(1).max(20),switchAt:t.number().int().positive(),interval:t.enum(["week","month","year"]),intervalCount:t.number().int().min(1).max(52),resetBillingCycleAnchor:t.literal(!0).optional(),metadata:le}).nullable(),release:t.strictObject({schedule:t.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:t.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(i=>e[i]!==null==(e.action===i))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(i=>i.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),ge=t.strictObject({merchantTerms:b.optional(),carryOverBalances:x.optional(),carryOverUsages:x.optional(),operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.enum(["immediate","renewal"]),effectiveAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}),currency:u,creditMinor:c,debitMinor:c,discountMinor:c,taxMinor:c,totalMinor:c,retainedProductVersionIds:t.array(t.uuid()).max(19),execution:t.union([ye,A])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&y(e.merchantTerms,e.operationId,"subscription_change",e.currency)),ft=t.strictObject({operationId:t.uuid(),invoiceMode:t.boolean().optional(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:t.enum(["immediate","renewal"]),effectiveAt:t.iso.datetime({offset:!0}),checkoutUrl:t.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:t.enum(["indiana","merchant"]),execution:t.union([ye,A]).nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),quote:ge.optional(),authority:S.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),bt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.literal("store"),effectiveAt:t.null(),expiresAt:t.iso.datetime({offset:!0}),currency:u,creditMinor:t.null(),debitMinor:t.null(),discountMinor:t.null(),taxMinor:t.null(),totalMinor:t.null(),retainedProductVersionIds:t.array(t.uuid()).max(19),store:t.strictObject({provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),catalogAmountMinor:c,policy:t.enum(["apple_store","google_full_price"])})}),yt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","pending","effective","cancelled","failed"]),timing:t.literal("store"),effectiveAt:t.iso.datetime({offset:!0}).nullable(),checkoutUrl:t.null(),nativePurchase:w.nullable()}),ui=t.union([ge,bt]),mi=t.union([ft,yt]),E=R,d=D,di=t.strictObject({requestId:t.uuid(),invoiceId:t.uuid(),...M.shape}).refine(P,"A partial refund states amountMinor; a full refund refunds the remaining amount"),Se=t.strictObject({provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:t.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:E,currency:t.string().regex(/^[a-z]{3}$/),metadata:t.strictObject({indianaRefundId:t.uuid()}),idempotencyKey:t.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:t.array(t.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),gt=t.strictObject({operationId:t.uuid(),merchantTerms:b.optional(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),currency:u,paidMinor:d,refundedMinor:d,pendingMinor:d,amountMinor:E,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),revokes:t.strictObject({customerProductIds:t.array(t.uuid()).max(100),subscriptionIds:t.array(t.string().min(1).max(200)).max(20)}),execution:t.union([Se,C]),expiresAt:t.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&y(e.merchantTerms,e.operationId,"refund",e.currency)).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"),St=t.strictObject({operationId:t.uuid(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),status:t.enum(["quoted","pending","succeeded","failed","expired"]),executor:t.enum(["indiana","merchant"]),currency:u,amountMinor:E,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),refundId:t.string().min(1).max(200).nullable(),quote:gt.optional(),execution:t.union([Se,C]).nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),authority:S.optional(),failureReason:t.string().min(1).max(200).nullable(),createdAt:t.iso.datetime({offset:!0}),completedAt:t.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"),pi=t.strictObject({invoiceId:t.uuid(),currency:u,paidMinor:d,refundedMinor:d,pendingMinor:d,refundableMinor:d,executor:t.enum(["indiana","merchant"]).nullable(),canRefund:t.boolean(),operations:t.array(St).max(50)}).refine(e=>e.operations.every(i=>i.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),li=t.strictObject({requestId:t.uuid(),...M.shape}).refine(P,"A partial refund states amountMinor; a full refund refunds the remaining amount");var Ai=t.strictObject({processContext:Y.optional(),...W,selector:t.discriminatedUnion("type",[t.strictObject({type:t.literal("paywall"),paywallId:t.uuid()}),t.strictObject({type:t.literal("version"),versionId:t.uuid()})]),customerId:t.uuid().optional(),commerce:B,locale:t.string().min(1).max(35),requirement:V.optional()}),T=t.strictObject({id:t.uuid(),paywallId:t.uuid(),version:t.number().int().positive(),document:$.omit({requirement:!0,offeringId:!0}),offering:t.strictObject({id:t.uuid()}),content:t.strictObject({environmentId:t.uuid(),offeringVersionId:t.uuid(),artifact:Z.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:L,check:F.nullable()}).superRefine((e,i)=>{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)))&&i.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Ci=t.strictObject(T.shape).omit({document:!0,offering:!0}).extend({content:T.shape.content.unwrap()});function Pi(e,i){let n=K.parse(i);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[a,s]of Object.entries(n.catalog)){let o=r.plans[a],m=s.channels.stripe?.prices.find(p=>p.currency===o?.currency);o&&m&&Object.assign(o,{amountMinor:m.amountMinor,interval:s.interval,intervalCount:s.intervalCount,...s.prepaid?.length?{prepaid:s.prepaid}:{}})}return T.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}})}export{W as a,Y as b,Ot as c,Et as d,Tt as e,ai as f,oi as g,ht as h,ci as i,si as j,ge as k,ui as l,mi as m,di as n,gt as o,St as p,Ai as q,T as r,Ci as s,Pi as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as h}from"./chunk-
|
|
1
|
+
import{e as h}from"./chunk-5SL2JQU3.js";import{b as J}from"./chunk-6O4IBSE3.js";import{c as N,e as x}from"./chunk-LS4XNIXR.js";import{v as Q}from"./chunk-4GZKK2RE.js";import{a as j,f as H,g as K,h as B,i as F}from"./chunk-FKDUXXGT.js";import{b as L}from"./chunk-WYMP6O5B.js";import{b as U}from"./chunk-GRNHBOSS.js";import{a as M}from"./chunk-QE6T6NX6.js";import{qa as G}from"./chunk-DVOYXRVB.js";import{a as l}from"./chunk-FCBTTR5W.js";import{a as W}from"./chunk-DSPLGTQI.js";async function ce(I,o){if(!M.test(o.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(I.session&&I.session.peek()!==o.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let u=h.resolvePaywall.request.parse({funnelId:o.funnelId,funnelVersionId:o.funnelVersionId,selector:o.paywallVersionId?{type:"version",versionId:o.paywallVersionId}:{type:"paywall",paywallId:o.paywallId},commerce:o.commerce,locale:o.locale,...o.requirement?{requirement:o.requirement}:{}}),S=U(I);I.session||S.identify(o.customerToken);let r=null,P=!1,D=new AbortController,s=null,c=null,v=null,w=null,R=null,d=null,f=null,A=0,O=null,_="",V=0,b=new Map,q=new Set;function g(){if(P)throw new l("IDENTITY_CHANGED","Paywall is closed")}function k(){let e=JSON.stringify([A,f!==null]);if(!O||e!==_){_=e;let t=Y(++V);O=t;let a=()=>{O===t&&(O=null)};t.then(a,a)}return O.then(t=>structuredClone(t))}async function Y(e){g();let t=h.resolvePaywall,a=await N(S.request,t,{...u,selector:r?{type:"version",versionId:r.id}:u.selector});J(u,a.paywall.check,a.scope);let i=await x(I,a.paywall);if(g(),o.paywallVersionId?i.id!==o.paywallVersionId:i.paywallId!==o.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(r&&(!H(i,r)||i.paywallId!==r.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==V)return structuredClone(r??i);r=i;for(let m of q)W(m,structuredClone(r));return structuredClone(r)}async function E(e){if(g(),w&&e!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!s)throw new l("INVALID_REQUEST","A quoted purchase is required");let t=s;if(e!=="read"){if(f){if(d===e)return f;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(d&&d!==e)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");d=e,A++,V++}let a=d,i=A,m=e==="read"&&f===null,p=JSON.stringify([t.operationId,i,f!==null]);if(e==="read"&&b.has(p))return b.get(p).then(n=>structuredClone(n));let C=e==="read"?h.readSubscriptionOperation:h.attach,y=(async()=>{let n=await N(S.request,C,{operationId:t.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&t.merchantTerms?{merchantConfirmation:Q(t.merchantTerms)}:{}});return K(n.operation,{operationId:t.operationId,currency:u.commerce.currency},"The purchase operation changed"),g(),s?.operationId!==t.operationId?structuredClone(n.operation):(c=F(c,n.operation),(e!=="read"||m&&f===null)&&A===i&&d===a&&(d=null),structuredClone(c))})();if(e!=="read"){f=y;let n=()=>{f===y&&(f=null)};y.then(n,n)}else{b.set(p,y);let n=()=>{b.get(p)===y&&b.delete(p)};y.then(n,n)}return y.then(n=>structuredClone(n))}let T={signal:D.signal,get view(){return r?structuredClone(r):null},get quote(){return s?structuredClone(s):null},get operation(){return c?structuredClone(c):null},get webViewUrl(){return"bundled"},get recovery(){return j({quote:s,operation:c,requestId:R,pending:w!==null||d!==null,destroyed:P})},get pendingCancellation(){return!P&&d==="cancel"},refresh:k,subscribe(e){return P?()=>{}:(q.add(e),()=>q.delete(e))},async preview(e){if(g(),!r)throw new l("INVALID_REQUEST","Load the Paywall first");let t=r.document.buttons[e.actionId];if(t?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let a=L(t.product,e.selection,r.capabilities);if(!a)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let i=G(r.document.screen,a,e.selection,r.capabilities),m=h.previewAttach.request.parse({funnelId:u.funnelId,funnelVersionId:u.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:a,...Object.keys(i).length?{featureQuantities:i}:{}}],provider:u.commerce.provider,currency:u.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),p=JSON.stringify(m);if(v&&v!==p&&(w||d||!c||c.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(v===p){if(w)return w;if(s)return structuredClone(s)}v!==p&&(s=null,c=null),v=p,R=m.requestId;let C=(async()=>{let y=h.previewAttach,n=await N(S.request,y,m);return g(),B(n.quote,{productVersionId:a,featureQuantities:i,currency:u.commerce.currency,provider:u.commerce.provider},"The purchase quote changed its selected Product or presentment"),s=n.quote,c=null,structuredClone(s)})();w=C;try{return await C}finally{w===C&&(w=null)}},confirm:()=>E("confirm"),cancel:()=>E("cancel"),read:()=>E("read"),destroy(){P||(P=!0,D.abort(),q.clear(),b.clear(),z?.(),S.dispose(),r=null,s=null,c=null,v=null,R=null)}},z=I.session?.subscribeIdentity(T.destroy);try{return await k(),T}catch(e){throw T.destroy(),e}}export{ce as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as $,b as N,c as J,d as q}from"./chunk-
|
|
1
|
+
import{a as $,b as N,c as J,d as q}from"./chunk-RCUBJJ7K.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-FVM4JJBA.js";import{a as _}from"./chunk-DSPLGTQI.js";import{b as C,c as O,e as j}from"./chunk-O4KXODTJ.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
|
|
2
2
|
Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
|
|
3
3
|
plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
|
|
4
4
|
*/function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
|