@tinkerlandai/longplay-sdk 0.10.18 → 0.10.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +9 -3
  3. package/README.zh-CN.md +1 -1
  4. package/dist/{ai-usage-D7BUuP1H.d.ts → ai-usage-DPGx5otD.d.ts} +3 -3
  5. package/dist/{api-CIbhe8RY.d.ts → api-G8EA_ueL.d.ts} +3596 -200
  6. package/dist/chunk-2JBNOE2D.js +1 -0
  7. package/dist/chunk-4SWGHICJ.js +17 -0
  8. package/dist/chunk-5OD42XQS.js +1 -0
  9. package/dist/{chunk-OMHZBCS3.js → chunk-A7U4Z6EH.js} +1 -1
  10. package/dist/{chunk-LHBBSD77.js → chunk-CCRBXW4M.js} +1 -1
  11. package/dist/chunk-DVKZLOS7.js +1 -0
  12. package/dist/{chunk-ML6EHT43.js → chunk-EDVR7FPD.js} +1 -1
  13. package/dist/chunk-FISFN5IY.js +1 -0
  14. package/dist/chunk-GSFNAB3W.js +6 -0
  15. package/dist/{chunk-26HU2HXU.js → chunk-KHIQQNTR.js} +1 -1
  16. package/dist/{chunk-6HWNW6FJ.js → chunk-LNSFRQ6G.js} +1 -1
  17. package/dist/chunk-W2Z3UVW3.js +1 -0
  18. package/dist/{chunk-T5COWMDA.js → chunk-XIYNQHN7.js} +1 -1
  19. package/dist/{chunk-P6HCD5OQ.js → chunk-XXBN76NP.js} +1 -1
  20. package/dist/{chunk-E4LUW6KP.js → chunk-YNMSSQQY.js} +1 -1
  21. package/dist/{content-DLYNJIEB.js → content-E2OWWKDG.js} +1 -1
  22. package/dist/{customer-page-km5f1PJZ.d.ts → customer-page-BV5EvCUY.d.ts} +20 -0
  23. package/dist/{funnel-local-client-CAuNpJ-e.d.ts → funnel-local-client-DjvVzCfH.d.ts} +14039 -312
  24. package/dist/{funnel-node-evaluation-BLnJp8vj.d.ts → funnel-node-evaluation-D9FwkMa3.d.ts} +425 -1
  25. package/dist/funnel-process-client-bO9Wfumi.d.ts +62372 -0
  26. package/dist/funnel-runtime-host-FOM4Z7ZK.js +1 -0
  27. package/dist/index.d.ts +322 -23334
  28. package/dist/index.js +1 -1
  29. package/dist/native-shell.js +1 -1
  30. package/dist/openrouter.d.ts +2 -2
  31. package/dist/openrouter.js +1 -1
  32. package/dist/page.js +1 -1
  33. package/dist/paywall-OUIB7SVI.js +1 -0
  34. package/dist/popup.d.ts +2 -2
  35. package/dist/popup.js +1 -1
  36. package/dist/react-native.d.ts +41 -38098
  37. package/dist/react-native.js +1 -1
  38. package/dist/screen-renderer-ZNELQB64.js +1 -0
  39. package/dist/server.d.ts +6860 -298
  40. package/dist/server.js +1 -1
  41. package/dist/visual.js +1 -1
  42. package/package.json +1 -1
  43. package/dist/chunk-4ZUMMPHV.js +0 -1
  44. package/dist/chunk-EEZLS2YP.js +0 -1
  45. package/dist/chunk-JVQVQHV2.js +0 -6
  46. package/dist/chunk-KYXX676W.js +0 -1
  47. package/dist/chunk-LC2VUKYM.js +0 -1
  48. package/dist/chunk-N4HZ55YU.js +0 -1
  49. package/dist/chunk-PFHS7HK3.js +0 -17
  50. package/dist/chunk-VVW2J2GL.js +0 -1
  51. package/dist/funnel-process-client-C9EIwNTr.d.ts +0 -20575
  52. package/dist/funnel-runtime-host-FVOUCR35.js +0 -1
  53. package/dist/paywall-6Q3VLXXL.js +0 -1
  54. package/dist/screen-renderer-IZ3VJGU6.js +0 -1
  55. package/dist/{coupon-fA1QujHt.d.ts → coupon-Btz_KFKp.d.ts} +1 -1
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import{a as wn}from"./chunk-4ZUMMPHV.js";import{a as En,b as Rn,c as Cn,d as An}from"./chunk-P6HCD5OQ.js";import{a as l,b as ye,c as We,d as Xe,e as Ze,f as en,h as W,i as nn,j as B,k as D,m as tn,n as hn,o as vn,p as Sn}from"./chunk-N4HZ55YU.js";import"./chunk-LC2VUKYM.js";import"./chunk-EEZLS2YP.js";import"./chunk-E4LUW6KP.js";import{a as o}from"./chunk-26HU2HXU.js";import"./chunk-LHBBSD77.js";import{$ as Me,A as J,B as Ce,E as ae,F as Ae,Fa as Ue,G as Oe,Ga as le,H as ie,Ha as z,I as se,Ia as Be,J as ce,Ja as Ge,Ka as Ve,La as me,Ma as He,N as ue,Na as qe,O as be,Oa as je,P as Pe,Pa as fe,Qa as Ke,Ra as Q,Sa as ze,T as Ne,Va as Qe,Wa as Ye,X as G,Y as ke,Z as de,_ as De,_a as Je,a as he,aa as $,ab as $e,ba as j,ca as Le,k as we,l as ve,m as te,o as Se,p as re,q as Ee,s as oe,u as Re,ua as i,va as pe,z as Y}from"./chunk-JVQVQHV2.js";import{Aa as xe,B as Fe,E as _e,r as Te}from"./chunk-PFHS7HK3.js";function X(e){return{async getCustomer(t){let n=i.getCustomer;return l(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=i.listCustomers;return l(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=i.updateCustomer;return l(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=i.createGuestCustomer;return l(e,n,t)},async resumeGuestSession(t){let n=i.resumeGuestSession;return l(e,n,t)},async claimGuestCustomer(t){let n=i.claimGuestCustomer;return l(e,n,t)},async revokeCustomerSessions(t){let n=i.revokeSessions;return l(e,n,t)},async createCustomerSession(t){return l(e,i.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return l(e,i.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function f(e,t){try{return e.parse(t)}catch{throw new o("INVALID_RESPONSE","Invalid gateway response")}}function rn(e){return{async checkEntitlement(t){let n=i.checkEntitlement;return l(e,n,t,f)},async readHoldings(t){let n=i.readHoldings;return l(e,n,t,f)},async readSeats(t){let n=i.readSeats;return l(e,n,t,f)},async manageSeat(t){let n=i.manageSeat;return l(e,n,t,f)}}}function on(e){return{async readAiPricing(t){let n=i.readAiPricing;return l(e,n,t,f)},async readUsage(t){let n=i.readUsage;return l(e,n,t,f)},async setUsage(t){let n=i.setUsage;return l(e,n,t,f)},async manageBalanceGrant(t){let n=i.manageBalanceGrant;return l(e,n,t,f)},async readBalanceSource(t){let n=i.readBalanceSource;return l(e,n,t,f)},async adjustBalance(t){let n=i.adjustBalance;return l(e,n,t,f)},async listBalanceGrants(t){let n=i.listBalanceGrants;return l(e,n,t,f)},async manageBillingLimits(t){let n=i.manageBillingLimits;return l(e,n,t,f)},async manageUsageEntity(t){let n=i.manageUsageEntity;return l(e,n,t,f)},async readUsageAnalytics(t){let n=i.readUsageAnalytics;return l(e,n,t,f)},async readCreditAnalytics(t){let n=i.readCreditAnalytics;return l(e,n,t,f)},async submitUsageBatch(t){let n=i.submitUsageBatch;return l(e,n,t,f)},async readUsageBatch(t){let n=i.readUsageBatch;return l(e,n,t,f)},async readLedger(t){let n=i.readLedger;return l(e,n,t,f)},async readCreditStatement(t){let n=i.readCreditStatement;return l(e,n,t,f)},async quoteBalance(t){let n=i.quoteBalance;return l(e,n,t,f)},async trackUsage(t){let n=i.trackUsage;return l(e,n,t,f)},async mutateBalance(t){let n=i.mutateBalance;return l(e,n,t,f)}}}function an(e){return{async listInvoiceTemplates(t={}){let n=i.listInvoiceTemplates;return l(e,n,t,f)},async previewInvoice(t){let n=i.previewInvoice;return l(e,n,t,f)},async createInvoice(t){let n=i.createInvoice;return l(e,n,t,f)},async prepareBillingAdjustment(t){let n=i.prepareBillingAdjustment;return l(e,n,t,f)},async manageInvoice(t){let n=i.manageInvoice;return l(e,n,t,f)},async readInvoiceOperation(t){let n=i.readInvoiceOperation;return l(e,n,t,f)},async listInvoices(t){let n=i.listInvoices;return l(e,n,t,f)},async getInvoice(t){let n=i.getInvoice;return l(e,n,t,f)},async setupPayment(t){let n=i.setupPayment;return l(e,n,t,f)},async readPaymentSetup(t){let n=i.readPaymentSetup;return l(e,n,t,f)},async readBillingInvoice(t){let n=i.readBillingInvoice;return l(e,n,t,f)},async previewRefund(t){let n=i.previewRefund;return l(e,n,t,f)},async refund(t){let n=i.refund;return l(e,n,t,f)},async readRefund(t){let n=i.readRefund;return l(e,n,t,f)}}}function sn(e){return{async previewSubscriptionBatch(t){let n=i.previewSubscriptionBatch;return l(e,n,t,f)},async confirmSubscriptionBatch(t){let n=i.confirmSubscriptionBatch;return l(e,n,t,f)},async readSubscriptionBatch(t){let n=i.readSubscriptionBatch;return l(e,n,t,f)},async abandonSubscriptionBatch(t){let n=i.abandonSubscriptionBatch;return l(e,n,t,f)},async manageSubscriptionTrial(t){let n=i.manageSubscriptionTrial;return l(e,n,t,f)},async readSubscriptionTrial(t){let n=i.readSubscriptionTrial;return l(e,n,t,f)},async listSubscriptions(t){let n=i.listSubscriptions;return l(e,n,t,f)},async listPurchases(t){let n=i.listPurchases;return l(e,n,t,f)},async listSubscriptionConflicts(t){let n=i.listSubscriptionConflicts;return l(e,n,t,f)},async retrySubscriptionConflict(t){let n=i.retrySubscriptionConflict;return l(e,n,t,f)},async previewUpdate(t){let n=i.previewUpdate;return l(e,n,t,f)},async update(t){let n=i.update;return l(e,n,t,f)},async readSubscriptionUpdate(t){let n=i.readSubscriptionUpdate;return l(e,n,t,f)},async restoreNativePurchase(t){let n=i.restoreNativePurchase;return l(e,n,t,f)},async verifySubscriptions(t){let n=i.verifySubscriptions;return l(e,n,t,f)},async previewAttach(t){let n=i.previewAttach;return l(e,n,t,f)},async recordMerchantEvent(t){return l(e,i.recordMerchantEvent,t,{request:"Invalid merchant event",parseResponse:f})},async attach(t){let n=i.attach;return l(e,n,t,f)},async readSubscriptionOperation(t){let n=i.readSubscriptionOperation;return l(e,n,t,f)}}}function cn(e){return{async grantOffer(t){let n=i.grantOffer;return l(e,{...n,request:n.request.refine(u=>!!u.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function un(e){return{...rn(e),...on(e),...an(e),...sn(e),...cn(e)}}function dn(e){return{async getFeatures(t={}){let n=i.getFeatures;return l(e,n,t,f)},async evaluateFeatures(t){let n=i.evaluateFeatures;return l(e,n,t,f)}}}function pn(e){return{async trackEvents(t){let n=i.trackEvents;return l(e,n,t,f)}}}function ln(e){return{async resolveContent(t){let n=i.resolveContent;return l(e,n,t,f)},async resolvePaywall(t){let n=i.resolvePaywall;return l(e,n,t,f)},async resolveOffering(t){let n=i.resolveOffering;return l(e,n,t,f)}}}function On(e){B(e.apiKey,"Secret API keys must stay on your backend");let n=D(e).request;return{async sendMessage(u){let a=i.sendMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},async readMessage(u){let a=i.readMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},...X(n),...un(n),...dn(n),...pn(n),...ln(n)}}function Ie(){if(typeof window<"u")throw new o("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var mn=()=>new o("CONFLICT","Process synchronization is in progress",425),M=()=>new o("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),Tn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Z=class extends o{constructor(n){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:n.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=n}result};function Fn(e){if(B(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new o("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let t=D(e),n=X(t.request),u=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function a(m){let r=await e.resolveUser(m);if(r!==null&&(typeof r?.externalUserId!="string"||!r.externalUserId||r.externalUserId!==r.externalUserId.trim()||r.externalUserId.startsWith("gg_guest_")))throw new o("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return r}async function c(m){let r=await e.resolveContext(m);if(r?.confirmed!==!0||!r.processKey||!r.guestKey)throw new o("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:u+"run:"+r.processKey,guest:u+"guest:"+r.guestKey}}async function d(m,r){for(let y=0;y<8;y++){let h=await e.store.read(m),I=r(h?structuredClone(h.value):null);if(h&&Tn(h.value,I)||await e.store.compareAndSwap(m,h?.revision??null,I))return I}throw mn()}async function p(m){let r=await e.store.read(m);if(!r)throw new o("NOT_FOUND","Open the process before continuing",404);return r.value}async function s(m){let r=await p(m);for(let y of r.revocations??[])await n.revokeCustomerSessions(y),await d(m,h=>{if(!h)throw M();return h.revocations=h.revocations?.filter(I=>I.sessionId!==y.sessionId),h})}async function g(m,r){let y=le.parse(m);return r?t.requestWithCredential("funnel-processes",y,r):t.request("funnel-processes",y)}function w(m,r){if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment||m.run&&(m.run.id!==r.run.id||m.run.source.versionId!==r.run.source.versionId||m.run.source.id!==r.run.source.id||m.run.runExpiresAt!==r.run.runExpiresAt||m.run.identity.startedAs!==r.run.identity.startedAs||m.run.identity.participantId!==r.run.identity.participantId||m.run.identity.binding&&m.run.identity.binding.id!==r.run.identity.binding?.id)||m.runToken&&r.runToken&&m.runToken!==r.runToken)throw new o("INVALID_RESPONSE","Process identity or Run changed")}async function E(m,r,y){return d(m,h=>{if(!h)throw new o("NOT_FOUND","Process handle is missing",404);return w(h,r),(!h.run||r.run.revision>=h.run.revision)&&(h.run=r.run),h.runToken??=r.runToken,y!==void 0&&(h.target=y),h})}async function S(m,r){if(r.detached)throw new o("UNAUTHENTICATED","The process is detached",401);let y=r.run?.identity.binding?.customerId??r.run?.identity.participantId;if(!y)throw new o("INVALID_RESPONSE","Process participant is missing");if(r.session?.customerId===y&&Date.parse(r.session.expiresAt)>Date.now()+3e4)return r.session;let h={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},I=await d(m,A=>{if(!A||A.detached||A.run?.id!==r.run?.id)throw M();if(A.sessionLease&&A.sessionLease.until>Date.now())throw mn();return A.sessionLease=h,A}),C;try{if(I.session?.customerId===y&&Date.parse(I.session.refreshExpiresAt)>Date.now())try{if(C=Se.parse(await t.requestWithCredential("customer-sessions/refresh",{},I.session.refreshToken)),C.sessionId!==I.session.sessionId)throw new o("INVALID_RESPONSE","Refresh changed the logical session")}catch(b){if(!(b instanceof o)||b.status!==401)throw b}if(C??=I.run?.identity.binding?await n.createCustomerSession(y):await n.resumeGuestSession({guestToken:I.guest.token}),C.customerId!==y)throw new o("INVALID_RESPONSE","Session Customer changed");let A=C;return await d(m,b=>{if(!b||b.detached||b.sessionLease?.id!==h.id||b.run?.identity.binding?.id!==r.run?.identity.binding?.id)throw new o("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return b.session=A,delete b.sessionLease,b}),C}catch(A){throw C&&C.sessionId!==I.session?.sessionId&&await n.revokeCustomerSessions({customerId:C.customerId,sessionId:C.sessionId}).catch(()=>{}),await d(m,b=>{if(!b)throw M();return b.sessionLease?.id===h.id&&delete b.sessionLease,b}).catch(()=>{}),A}}let R;async function O(){if(R??=He.parse(await g({contract:G,operation:"describe"})),R.scope.projectId!==e.scope.projectId||R.scope.environment!==e.scope.environment)throw M();return R}async function v(m,r,y=!1){let h=await a(m),I=await p(r);if(I.issuingKeyId!==(await O()).keyId)throw new o("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!I.runToken||!I.run)throw new o("CONFLICT","Recover the original start first",425);if(I.detached){if(!y)throw new o("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(I.run.identity.binding&&(!h||I.target&&I.target!==h.externalUserId))throw M();await s(r),I=await d(r,C=>{if(!C||C.run?.id!==I.run?.id)throw M();return delete C.detached,C})}if(!I.runToken||!I.run)throw new o("INVALID_RESPONSE","Process identity is missing");if(I.run.identity.binding){if(h&&!I.target){let C=me.parse(await g({contract:G,operation:"binding_status",runToken:I.runToken,requestId:I.bindingIntent?.requestId??I.start.requestId,externalUserId:h.externalUserId}));if(C.state!=="bound"||C.binding.id!==I.run.identity.binding.id)throw M();I=await d(r,A=>{if(!A)throw M();return A.target=h.externalUserId,A})}if(!h||I.target!==h.externalUserId)throw M()}else if(h){if(!I.guest)throw M();I=await d(r,A=>{if(!A||A.bindingIntent&&A.bindingIntent.externalUserId!==h.externalUserId)throw M();return A.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:h.externalUserId},A});let C=I.bindingIntent;try{let A=Ve.parse(await g({contract:G,operation:"bind_customer",...C,runToken:I.runToken,guestToken:I.guest.token,claimRequestId:I.guest.claimRequestId,expectedBindingId:null}));I=await E(r,A,h.externalUserId)}catch(A){let b=me.parse(await g({contract:G,operation:"binding_status",...C,runToken:I.runToken,guestToken:I.guest.token}));if(b.state!=="bound")throw A;I=await d(r,x=>{if(!x?.run||x.run.id!==b.binding.runId)throw M();return x.run.identity.binding={id:b.binding.id,customerId:b.binding.customerId,acceptedAt:b.binding.acceptedAt},x.target=h.externalUserId,x})}}return{state:I,session:await S(r,I)}}async function k(m,r,y,h){try{return await h(y)}catch(I){if(!(I instanceof o)||I.status!==401)throw I;return await d(r,C=>{if(!C||C.detached)throw I;return C.session?.accessToken===y.session.accessToken&&(C.session.expiresAt=new Date(0).toISOString()),C}),h(await v(m,r))}}async function L(m,r,y=!1){let h=await c(m),I=await v(m,h.process,y),C=z.parse(await k(m,h.process,I,A=>g({...r,customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C}return{async open(m,r){r=Ge.parse(r);let y=await c(m),h=await O(),I=y.guest+":"+h.keyId,C=await e.store.read(y.process);if(!C){let P=await a(m),T,_,N;if(P)T={type:"customer",customer:{type:"externalUserId",value:P.externalUserId}};else{let V=await e.store.read(I);if(V)try{N=await n.resumeGuestSession({guestToken:V.value.token}),_=V.value}catch(U){if(!(U instanceof o)||U.status!==401)throw U}let H={token:Ie(),claimRequestId:crypto.randomUUID()};_=await d(I,U=>_??(U&&U.token!==V?.value.token?U:H)),T={type:"guest",guestToken:_.token}}await d(y.process,V=>V??{issuingKeyId:h.keyId,start:le.parse({...r,contract:G,requestId:crypto.randomUUID(),source:T}),..._?{guest:_}:{},...P?{target:P.externalUserId}:{},...N?{session:N}:{}}),C=await e.store.read(y.process)}let A=C.value;if(A.issuingKeyId!==h.keyId)throw new o("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(A.start.funnelId!==r.funnelId||A.start.operation!==r.operation)throw new o("CONFLICT","This handle already owns another process",409);if(!A.runToken){if(A.start.source.type==="customer"){let N=await a(m);if(!N||N.externalUserId!==A.target)throw M()}let P=await g(A.start),T=Be.safeParse(P);if(T.success)throw new Z(T.data);let _=z.parse(P);if(!_.runToken)throw new o("INVALID_RESPONSE","Process credential is missing");A=await E(y.process,_)}let b=await v(m,y.process,!0),x=z.parse(await k(m,y.process,b,P=>g({contract:G,operation:"get",customerToken:P.session.accessToken},P.state.runToken)));return await E(y.process,x),{...x,runToken:A.runToken}},async syncIdentity(m){return L(m,{contract:G,operation:"get",customerToken:""},!0)},async get(m,r={}){return L(m,{...r,contract:G,operation:"get",customerToken:""})},async review(m,r){return L(m,{contract:G,operation:"review",customerToken:"",...r?{receiptId:r}:{}})},async command(m,r,y){let h=await c(m),I=await v(m,h.process),C=z.parse(await k(m,h.process,I,A=>g({contract:G,operation:"command",command:r,identity:{bindingId:y},customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C},async pageExperiments(m,r,y=[]){let h=await c(m),I=await v(m,h.process);return Ue.parse(await k(m,h.process,I,C=>g({contract:G,operation:"page_experiments",release:r,usedReceiptIds:y,customerToken:C.session.accessToken},C.state.runToken)))},async detach(m){let r=await c(m);await d(r.process,y=>{if(!y)throw M();return y.session&&!y.revocations?.some(h=>h.sessionId===y.session.sessionId)&&(y.revocations??=[]).push({customerId:y.session.customerId,sessionId:y.session.sessionId}),y.detached=!0,delete y.session,delete y.sessionLease,y}),await s(r.process)},destroy(){t.dispose()}}}async function _n(e,t){B(e.apiKey,"Renewal requires your backend");let n=D(e),u=je.parse(We(e,await n.request("funnels",qe.parse({...t,operation:"renew_run"}))));if(u.run.id!==t.runId)throw new o("INVALID_RESPONSE","Run renewal identity changed");return u}function fn(e){let t=Ze(e),n=p=>{throw new o("INVALID_RESPONSE",p)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let u=new Set(["entry","condition","feature","split","end","output"]);for(let p of t.nodes.values()){if(!u.has(p.type))throw new o("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(p.type==="entry"&&p.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(p.type)&&!p.outputs.next&&n("Local next exit is unavailable"),p.type==="feature"){let s=p.resources.featureKey;(!s||!Object.hasOwn(e.evaluation.variables,p.writes.value)||!Object.hasOwn(t.features,s))&&n("Local Feature definition or declaration is unavailable")}if(p.type==="condition"){let s=e.conditions[p.id];(!s||!p.outputs.default||s.some((g,w)=>g.port!==`case:${w}`||!p.outputs[g.port]))&&n("Local Condition exits are unavailable")}if(p.type==="split"&&(!p.resources.experimentId||!Object.hasOwn(e.growth.experiments,p.resources.experimentId)||!p.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),p.type==="end"||p.type==="output"){let s=e.evaluation.terminals[p.id];if(!s)throw new o("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(p.outputs).length&&n("A terminal cannot have outgoing edges"),s.output?.type==="feature"&&!Object.hasOwn(t.features,s.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let s of Object.values(p.outputs))t.nodes.has(s)||n("Local target is unavailable")}let a=new Set,c=new Set;function d(p){if(c.has(p)&&n("Local graph contains a cycle"),!a.has(p)){c.add(p);for(let s of Object.values(t.nodes.get(p).outputs))d(s);c.delete(p),a.add(p)}}return d(e.topology.entry),a.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(p){let s={},g=p.context;g.features=t.features,g.savedGroups=t.savedGroups;let w=()=>{g.attributes=ke({declarations:e.evaluation.variables,attributes:p.attributes,parameters:p.parameters,answers:{},results:s,savedGroups:t.savedGroups})};w();let E=e.topology.entry,S=0;for(;;){let R=t.nodes.get(E);if(R.type==="end"||R.type==="output"){let O=e.evaluation.terminals[E],v=O.output,k=v?.type==="feature"?t.feature(v.featureKey,g):v?.type==="variable"?Pe({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:e.evaluation.variables,answers:{},results:s,parameters:p.parameters,attributes:p.attributes,savedGroups:t.savedGroups}):v?.value??null;return ue(e.evaluation.outputSchema,k)||n("Local output does not match its declaration"),{outcome:O.outcome,value:k}}if(S++>=e.evaluation.maxTransitions)throw new o("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(R.type==="entry")E=R.outputs.next;else{let O=t.evaluate(E,g);if(R.type==="feature"){let v=R.writes.value,k=O.value??null;ue(e.evaluation.variables[v],k)||n("Local Feature value does not match its declaration"),be(e.evaluation.variables,{writes:R.writes},{[v]:k}),s[v]=k,w()}E=O.target}}}}}import{z as yn}from"zod";function In(e,t,n){let u=Fe.parse(e.attributes);if(["parameters","answers","results"].some(m=>Object.hasOwn(u,m)))throw new o("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let a=xe.parse(e.parameters??{}),c=yn.record(yn.string(),_e).parse(e.stickyBucketAssignmentDocs??{});for(let[m,r]of Object.entries(c))if(m!==`${r.attributeName}||${r.attributeValue}`||!Object.hasOwn(u,r.attributeName)||Te(u[r.attributeName])!==r.attributeValue)throw new o("INVALID_REQUEST","Sticky document identity does not match this session");let d=e.saveStickyBucketAssignmentDoc,p=e.onFeatureUsage,s=e.onExperimentViewed,g=e.onError,w=new Map,E=new Set,S={},R=Promise.resolve();function O(m){let r=R.then(()=>(n(),m()));return R=r.catch(()=>{}),r}function v(m){try{g?.(m)}catch{}}function k(m){try{let r=m();r&&typeof r.catch=="function"&&r.catch(v)}catch(r){v(r)}}async function L(){for(let[m,r]of w){if(n(),d)try{await d(structuredClone(r))}catch{throw new o("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),w.delete(m)}}return{evaluate(m={}){let r=m.track===!0;return O(async()=>{let y=await t();n(y);let h=new Set(E),I={...S},C=new Map,A=[],b={stickyBucketAssignmentDocs:structuredClone(c),saveStickyBucketAssignmentDoc(T){C.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...r?{trackedExperiments:h,trackedFeatureUsage:I,onExperimentViewed(T,_){let N=structuredClone(T),V=structuredClone(_);s&&A.push(()=>s(structuredClone(N),structuredClone(V)))},onFeatureUsage(T,_){let N=structuredClone(_);p&&A.push(()=>p(T,structuredClone(N)))}}:{}},x=y.program.evaluate({attributes:u,parameters:a,context:b});n(y);for(let[T,_]of C)c[T]=_,w.set(T,_);await L(),n(y),r&&(E=h,S=I);for(let T of A)k(T);let P=y.configuration;return structuredClone({evaluationMode:"local",scope:P.scope,funnelId:P.funnelId,versionId:P.versionId,evaluationRevision:P.evaluationRevision,generation:P.growth.generation,...x})})},flush:()=>O(L),get stickyBucketAssignmentDocs(){return n(),structuredClone(c)}}}var bn=6e4;function ee(e){if(typeof window<"u")throw new o("SERVER_ONLY","Local Funnel sessions run on your backend");let t=he.parse(e.scope),n=e.funnelId,u=e.load,a,c,d,p=0,s=E=>Date.now()>=E.expiresAt;async function g(){if(c)return c;let E=p;a=void 0;let S=(async()=>{let R=await u();if(E!==p)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&typeof R=="object"&&"evaluationMode"in R&&R.evaluationMode==="remote")throw f(Q,R),new o("EVALUATION_MODE","This Funnel requires remote decide");let O=f(ze,R);if(E!==p)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(O.scope.projectId!==t.projectId||O.scope.environment!==t.environment||O.funnelId!==n)throw new o("SCOPE_MISMATCH","Local configuration scope changed");if(O.growth.scope.projectId!==t.projectId||O.growth.scope.environment!==t.environment||O.growth.expiresAt!==O.expiresAt)throw new o("INVALID_RESPONSE","GB configuration scope or expiry changed");let v=Math.min(Date.now()+bn,O.expiresAt?Date.parse(O.expiresAt):1/0);if(Date.now()>=v)throw new o("CONFIGURATION_EXPIRED","Refresh expired local rules");let k=JSON.stringify([t.projectId,t.environment,n,O.versionId,O.evaluationRevision,O.growth.generation]),L=[O.topology,O.conditions,O.evaluation,O.growth.features,O.growth.experiments,O.growth.savedGroups];if(d?.key===k&&!nn(d.body,L))throw new o("INVALID_RESPONSE","Immutable local configuration identity changed");return d?.key!==k&&(d={key:k,body:L,program:fn(O)}),a={key:k,configuration:O,expiresAt:v,program:d.program},a})();c=S;try{return await S}finally{c===S&&(c=void 0)}}function w(){return c??(a&&!s(a)?Promise.resolve(a):g())}return{session(E){let S=p;return In(E,w,R=>{if(e.assertUsable?.(),S!==p)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&(s(R)||a?.key!==R.key))throw new o("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await g()).configuration)},reset(){p++,a=void 0,c=void 0,d=void 0}}}function Pn(e,t){let n=e.snapshot?.generation,u=ee({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),a=e.subscribe(()=>{let d=e.snapshot?.generation;e.fresh&&d!==n&&(n=d,u.refresh().catch(()=>{}))}),c=u.session;return Object.assign(u,{session(d){let p=c(d),s=p.evaluate;return Object.assign(p,{async evaluate(...g){return e.fresh||await e.refresh(),s(...g)}})},destroy(){a(),u.reset()}})}function Nn(e){if(typeof window<"u")throw new o("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>tn(e,t)}}var K=class extends o{constructor(n,u){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,u);this.decisionId=n;this.decisionRequestId=u}decisionId;decisionRequestId};async function ne(e,t,n,u){let{decisionId:a,requestId:c}=e,d=e,p=250,s=0;for(;;){if(d.decisionId!==a||d.requestId!==c||d.decision&&!W(d.decision,t))throw new o("INVALID_RESPONSE","Decision request or customer changed");if(d.decision)return d.decision;if(d.status==="failed")throw new o("DECISION_FAILED","Decision execution failed",503,c);if(Date.now()>=n)throw new K(a,c);if(await new Promise(g=>setTimeout(g,Math.min(Math.max(p,s-Date.now()),n-Date.now()))),Date.now()>=n)throw new K(a,c);p=Math.min(1e3,p*2);try{d=await u(a,n)}catch(g){if(g instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(g.code)){s=Date.now()+(g.retryAfterSeconds??0)*1e3;continue}throw g}}}function ge(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");B(e.apiKey,"Funnel decisions are requested by your backend");let t,n,u=new Map;async function a(s,g){let w=s;w.status!=="pending"&&u.delete(w.decisionId);for(let E=0;E<32&&w.evaluation;E++){let S=w.evaluation;if(S.runId!==w.decisionId)throw new o("INVALID_RESPONSE","Local evaluation Run changed");let R=u.get(w.decisionId);if(!R&&S.type==="evaluate_segment"){let v=$e.parse(await c({operation:"segment_configuration",funnelId:e.funnelId,versionId:S.versionId},g));if(v.configuration.scope.projectId!==e.scope.projectId||v.configuration.scope.environment!==e.scope.environment||v.configuration.funnelId!==e.funnelId||v.configuration.versionId!==S.versionId||v.configuration.evaluationRevision!==S.policyRevision)throw new o("SCOPE_MISMATCH","Original decision segment configuration changed");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding decisions first");R={operation:"commit_decision_segment",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,policyRevision:S.policyRevision,generation:v.configuration.growth.generation,...en(v.configuration,v.document,S)},u.set(w.decisionId,R)}if(!R){if(S.type!=="evaluate")throw new o("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=Q.parse(await c({operation:"configuration",funnelId:e.funnelId,versionId:S.versionId},g))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision)throw new o("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding Local decisions first");R={operation:"evaluate_decision",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,"evaluation"),nodeId:S.nodeId,visit:S.visit,revision:S.revision,receiptId:S.receiptId,policyRevision:S.policyRevision,generation:n.growth.generation,result:Je(n,S.nodeId,S,Xe)},u.set(w.decisionId,R)}let O=j.parse(await c(R,g));if(O.decisionId!==s.decisionId||O.requestId!==s.requestId)throw new o("INVALID_RESPONSE","Decision identity changed during local evaluation");u.delete(w.decisionId),w=O}return w}async function c(s,g,w=!1){return D({...e,fetch:(S,R)=>{let O=new Headers(R?.headers);return O.set("Accept-Encoding","identity"),w&&O.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(S,{...R,headers:O})},timeoutMs:Math.min(e.timeoutMs??1e4,g?Math.max(1,g-Date.now()):12e4)}).request("funnels",s)}async function d(s,g){let w=j.parse(await c($.parse({operation:"read_decision",decisionId:s}),g));if(w.decisionId!==s)throw new o("INVALID_RESPONSE","Decision identity changed");return a(w,g)}async function p(s,g,w=!1){let E=$.options[0].parse({...s,operation:"decide",funnelId:e.funnelId}),S;try{S=j.parse(await c(E,g,w))}catch(R){throw R instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(R.code)?new o("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",R.status,s.requestId):R}if(S.requestId!==s.requestId||S.decision&&!W(S.decision,E.customer))throw new o("INVALID_RESPONSE","Decision request or customer changed");return{response:await a(S,g),customer:E.customer}}return{local(){return t??=ee({scope:e.scope,funnelId:e.funnelId,load:()=>c({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let s=Q.parse(await c({operation:"configuration",funnelId:e.funnelId}));if(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment||s.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Configuration scope changed");return s},features(s={}){return ye({...s,scope:e.scope,load:async()=>Ne.parse(await c({operation:"feature_config",funnelId:e.funnelId}))})},read:s=>d(s),async submit(s){return(await p(s,void 0,!0)).response},async decide(s){let g=Date.now()+3e4,w=await p(s,g);return ne(w.response,w.customer,g,d)},async reportUsed(s){let g=Le.parse(await c($.parse({...s,operation:"report_used"})));if(g.decisionId!==s.decisionId||g.eventId!==s.eventId)throw new o("INVALID_RESPONSE","Usage receipt identity changed");return g}}}function kn(e){B(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let u=Qe.parse(n);if(u.orderId!==u.receiptId)throw new o("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let a=u.nativeEvidence,c={requestId:u.requestId,customerToken:u.customerToken,purchaseIntentId:u.orderId,...a===null?{intent:"read"}:a.provider==="apple"?{provider:"apple",signedTransaction:a.signedTransaction}:{provider:"google",purchaseToken:a.purchaseToken}},d=i.restoreNativePurchase.response.parse(await t.request(i.restoreNativePurchase.path,c));if(d.operation.requestId!==u.requestId||d.operation.purchaseIntentId!==u.orderId)throw new o("INVALID_RESPONSE","Native receipt request identity changed");let p=Ye.parse({scope:d.scope,requestId:u.requestId,orderId:d.operation.orderId,receiptId:d.operation.orderId,orderStatus:d.operation.status,refunded:d.operation.refunded,...d.operation.completion===null?{}:{nativeCompletion:{orderId:d.operation.orderId,receiptId:d.operation.orderId,...d.operation.completion}}});if(p.requestId!==u.requestId||p.orderId!==u.orderId||p.receiptId!==u.receiptId||p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Current order receipt scope changed");return p}}}import{z as xn}from"zod";var q=xn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function Dn(e,t){let n=q.parse(e.inputTokens.total),u=q.parse(e.outputTokens.total),a=q.parse(e.inputTokens.cacheRead??0),c=q.parse(e.inputTokens.cacheWrite??0),d=q.parse(e.outputTokens.reasoning??0);if(a+c>n||d>u||e.inputTokens.noCache!==void 0&&q.parse(e.inputTokens.noCache)!==n-a-c||e.outputTokens.text!==void 0&&q.parse(e.outputTokens.text)!==u-d)throw new o("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-a-c,cache_read:a,cache_write:c,output:t==="output"?u:u-d,reasoning:t==="separate"?d:0,input_audio:0,output_audio:0}}function Mn(e){if(typeof window<"u")throw new o("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new o("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(u){await e.persist({context:u,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(u,a){let c={context:u,modelId:e.modelId,usage:a,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(c);let d=e.mapTokens?e.mapTokens(a):Dn(a,e.reasoning),p=await e.pricing.quoteTokens({modelId:e.modelId,tokens:d});await e.persist({...c,tokens:d,quote:p,phase:"quoted"});let s=await e.pricing.trackTokens(e.client,{...u,quote:p});if(!s.receipt.accepted)throw new o("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...c,tokens:d,quote:p,receipt:s,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:u}){let a=await e.context(),c;try{c=await u()}catch(d){throw await t(a),d}return await n(a,c.usage),c},async wrapStream({doStream:u}){let a=await e.context(),c;try{c=await u()}catch(w){throw await t(a),w}let d=!1,p=!1,s=c.stream.getReader();async function g(){d||p||(p=!0,await t(a))}return{...c,stream:new ReadableStream({async pull(w){try{let{value:E,done:S}=await s.read();if(S){if(!d)throw await g(),new o("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");w.close();return}if(E.type==="finish"){if(d)throw new o("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");d=!0,await n(a,E.usage)}w.enqueue(E)}catch(E){try{await g()}finally{w.error(E),await s.cancel(E)}}},async cancel(w){try{await g()}finally{await s.cancel(w)}}})}}}}function Ln(e){B(e.apiKey,"Funnel receipts are sent by your backend");let t=D(e);return{async signal(n){let u=de.parse({...n,operation:"signal"}),a=De.parse(await t.request("funnels",u));if(a.runId!==n.runId||a.eventId!==n.eventId||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Receipt identity changed");return a},async readResults(n){let u=de.parse({operation:"read_results",runId:n}),a=Me.parse(await t.request("funnels",u));if(a.runId!==n||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Result identity changed");return a}}}function Un(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");B(e.apiKey,"Campaign entry requires your backend");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let u=Date.now()+(e.timeoutMs??3e4),a=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),c=D({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,u-Date.now()))}),d=j.parse(await c.request("funnels",a));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");return ne(d,a.customer,u,(p,s)=>ge({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,s-Date.now()))}).read(p))},async start(n){let u=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),a=Ke.parse(await t.request("funnels",u));if(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in a)&&(a.run.source.id!==e.funnelId||!a.customerId||u.customer.type==="id"&&a.customerId!==u.customer.value))throw new o("INVALID_RESPONSE","Campaign Funnel or Customer changed");return a}}}import{z as Bn}from"zod";var F=class extends Error{constructor(n,u=409,a=!1,c="fix_request"){super(n);this.code=n;this.status=u;this.retryable=a;this.recovery=c}code;status;retryable;recovery};function Gn(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=Re.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},u=t.capabilities.some(a=>["purchases","subscription_changes","refunds","operation_status"].includes(a));for(let[a,c]of Object.entries(oe))if(c.command&&t.capabilities.includes(a)&&!(a==="catalog"&&t.catalog==="static")&&!e.handlers[c.command])throw new Error(`Missing merchant command handler: ${c.command}`);if(u&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!t.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(c){let d=crypto.randomUUID(),p="bridge.ping",s,g=async(w,E,S=!1)=>{let R=JSON.stringify({bridgeVersion:re,requestId:d,command:p,scope:n,[S?"error":"data"]:w});if(new TextEncoder().encode(R).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(R,{status:E,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":d,...s?await se(R,s,"response"):{}}})};try{if(c.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(re)||c.method!=="POST"||new URL(c.url).pathname!==Ee)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(c.headers.get("Content-Type")??""))throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let w=c.body?.getReader();if(!w)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=new TextDecoder("utf-8",{fatal:!0}),S="",R=0;try{for(;;){let _=await w.read();if(_.done)break;if(R+=_.value.byteLength,R>16384)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",413);S+=E.decode(_.value,{stream:!0})}S+=E.decode()}finally{await w.cancel().catch(()=>{}),w.releaseLock()}let O=Oe.safeParse(JSON.parse(S));if(!O.success)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let v=O.data;if(d=v.requestId,p=v.command,Object.keys(n).some(_=>v.scope[_]!==n[_]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let k=v.command==="bridge.ping"||v.command==="bridge.describe",L=v.command==="catalog.read";if((k||L||c.headers.has(ie))&&(s=e.authentication.find(_=>_.keyId===c.headers.get(ie)),!s||!await ce(S,c.headers,s,"request")))throw s=void 0,new F("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(v.command==="bridge.ping")return g(ae["bridge.ping"].parse(v.data),200);if(v.command==="bridge.describe")return g(t,200);let m=Object.entries(oe).find(([,_])=>_.command===v.command);if(!m||!t.capabilities.includes(m[0]))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let r=e.handlers[v.command];if(!r)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!L&&c.headers.has("Cookie")&&(c.headers.get("Origin")!==new URL(c.url).origin||["cross-site","same-site"].includes(c.headers.get("Sec-Fetch-Site")??"")))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);let y=L?{kind:"service"}:await e.authorize(c,v),h=y.kind,I=["purchase.execute","subscription.change","refund.execute"].includes(v.command),C=I||v.command==="operation.read";if(!(C&&s!==void 0&&h==="service")&&(v.command==="refund.execute"?h!=="administrator":!L&&h!=="user"))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);if(y.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(v.command)&&!Bn.uuid().safeParse(y.customerId).success)throw new F("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let b=r,x=ae[v.command].parse(v.data),P={request:c,command:v.command,scope:n,principal:y},T;if(C){let _=Y.parse(x);if(y.kind==="user"&&y.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let N=J.parse(await e.resolveOperationAuthority(_,P));if(N.operationId!==_.operationId||N.customerId!==_.customerId||Object.keys(n).some(H=>N.scope[H]!==n[H]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);P.authority=N;let V=v.command==="purchase.execute"?"purchase":v.command==="subscription.change"?"subscription_change":v.command==="refund.execute"?"refund":N.instruction.type;if(N.instruction.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!I)T=te.parse(await b(x,P));else{if(N.confirmedAt===null)throw new F("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let H=te.parse(await e.handlers["operation.read"](_,{...P,command:"operation.read"}));if(H.operationId!==_.operationId||H.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(H.lookup==="found")T=H.execution;else{if(!N.initialExecutionAllowed)throw new F("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(N.instruction.expiresAt)<=Date.now())throw new F("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||ve(N.instruction).some(U=>!t.billingEvents.some(gn=>gn===U))||we(N.instruction).some(U=>!t.profiles.includes(U)))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=Ce.parse(await b(x,P))}catch(U){throw U instanceof F?U:new F("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=Ae[v.command].parse(await b(x,P));if(y.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==y.nativeUserId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&y.customerId&&T.session.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&y.customerId&&T.presentation.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==Y.parse(v.data).operationId||T.customerId!==Y.parse(v.data).customerId))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return g(T,I&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(w){let E=w instanceof F?w:w instanceof SyntaxError?new F("MERCHANT_BRIDGE_INVALID_REQUEST",400):new F("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return g({code:E.code,message:E.code,retryable:E.retryable,recovery:E.recovery},E.status,!0)}}}function Vn(e){return async(t,n)=>{let u=()=>e.readSubscriptionOperation(t),a=()=>e.readSubscriptionUpdate(t),c=()=>e.readRefund(t),d=n.command==="purchase.execute"?[u]:n.command==="subscription.change"?[a]:n.command==="refund.execute"?[c]:[u,a,c];for(let p of d)try{let s=await p(),g="authority"in s.operation?s.operation.authority:void 0;if(!g)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let w=J.parse(g);if(w.customerId!==t.customerId||w.operationId!==t.operationId||Object.keys(n.scope).some(E=>w.scope[E]!==n.scope[E]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return w}catch(s){if(n.command==="operation.read"&&s instanceof o&&s.code==="NOT_FOUND")continue;throw s}throw new F("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}export{K as FunnelDecisionTimeoutError,Z as FunnelProcessEntrySuppressedError,o as LongplayError,F as MerchantBridgeHandlerError,En as aiPriceSnapshotSchema,Rn as aiTokenQuoteSchema,Cn as createAiPricing,Mn as createAiUsageMiddleware,hn as createConfigurationSync,An as createConfiguredAiPricing,ye as createFeatureClient,Un as createFunnelCampaignClient,ge as createFunnelDecisionClient,ee as createFunnelLocalEvaluator,Ln as createFunnelOrchestrationClient,Fn as createFunnelProcessAdapter,vn as createFunnelStartClient,Ie as createGuestToken,Sn as createLocalFunnelClient,On as createLongplayServer,Vn as createMerchantBridgeAuthorityResolver,Gn as createMerchantBridgeHandler,kn as createNativeReceiptClient,Nn as createPaywallStartClient,Pn as createSynchronizedFunnelLocalEvaluator,wn as evaluateFunnelNode,_n as renewFunnelRun,se as signMerchantBridgeMessage,ce as verifyMerchantBridgeMessage};
1
+ import{a as xn}from"./chunk-DVKZLOS7.js";import{a as Bn,b as Ln,c as Un,d as Vn}from"./chunk-XXBN76NP.js";import{a as m,b as cn,c as we,d as ve,e as un,f as dn,g as pn,h as ln,j as te,k as mn,l as U,m as N,o as fn,p as kn,q as Dn,r as Nn}from"./chunk-2JBNOE2D.js";import"./chunk-FISFN5IY.js";import"./chunk-YNMSSQQY.js";import{a as s}from"./chunk-KHIQQNTR.js";import"./chunk-CCRBXW4M.js";import{$ as He,Ca as p,D as Z,Da as he,E as ee,F as Me,I as le,J as Pe,K as _e,L as ke,M as xe,N as De,Na as Je,O as Ne,Oa as ge,P as Y,Pa as $,Q as j,Qa as Ye,R as z,Ra as $e,Sa as We,Ta as ye,Ua as Xe,V as me,Va as Ze,W as Ve,Wa as en,X as qe,Xa as Ie,Ya as nn,Za as W,_a as tn,bb as rn,cb as on,da as V,ea as Ge,fa as fe,ga as ze,gb as an,ha as Ke,ia as ne,ib as sn,j as Ce,ja as K,k as Ae,ka as Qe,l as ce,m as Mn,n as Pn,p as _n,r as Oe,s as de,t as X,u as J,v as pe,w as Te,y as be}from"./chunk-GSFNAB3W.js";import{C as Fe,H as Be,Ia as je,P as Le,S as Ue,a as Re,o as ue,y as Fn}from"./chunk-4SWGHICJ.js";function re(e){return{async getCustomer(t){let n=p.getCustomer;return m(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=p.listCustomers;return m(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=p.updateCustomer;return m(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=p.createGuestCustomer;return m(e,n,t)},async resumeGuestSession(t){let n=p.resumeGuestSession;return m(e,n,t)},async claimGuestCustomer(t){let n=p.claimGuestCustomer;return m(e,n,t)},async revokeCustomerSessions(t){let n=p.revokeSessions;return m(e,n,t)},async createCustomerSession(t){return m(e,p.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return m(e,p.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function y(e,t){try{return e.parse(t)}catch{throw new s("INVALID_RESPONSE","Invalid gateway response")}}function hn(e){return{async checkEntitlement(t){let n=p.checkEntitlement,a=n.request.parse(t),r=await m(e,n,a,y);return cn(a.requirement,r.check,a.customerId,r.scope),r},async readHoldings(t){let n=p.readHoldings;return m(e,n,t,y)},async readSeats(t){let n=p.readSeats;return m(e,n,t,y)},async manageSeat(t){let n=p.manageSeat;return m(e,n,t,y)}}}function gn(e){return{async readAiPricing(t){let n=p.readAiPricing;return m(e,n,t,y)},async readUsage(t){let n=p.readUsage;return m(e,n,t,y)},async setUsage(t){let n=p.setUsage;return m(e,n,t,y)},async manageBalanceGrant(t){let n=p.manageBalanceGrant;return m(e,n,t,y)},async readBalanceSource(t){let n=p.readBalanceSource;return m(e,n,t,y)},async adjustBalance(t){let n=p.adjustBalance;return m(e,n,t,y)},async listBalanceGrants(t){let n=p.listBalanceGrants;return m(e,n,t,y)},async manageBillingLimits(t){let n=p.manageBillingLimits;return m(e,n,t,y)},async manageUsageEntity(t){let n=p.manageUsageEntity;return m(e,n,t,y)},async readUsageAnalytics(t){let n=p.readUsageAnalytics;return m(e,n,t,y)},async readCreditAnalytics(t){let n=p.readCreditAnalytics;return m(e,n,t,y)},async submitUsageBatch(t){let n=p.submitUsageBatch;return m(e,n,t,y)},async readUsageBatch(t){let n=p.readUsageBatch;return m(e,n,t,y)},async readLedger(t){let n=p.readLedger;return m(e,n,t,y)},async readCreditStatement(t){let n=p.readCreditStatement;return m(e,n,t,y)},async quoteBalance(t){let n=p.quoteBalance;return m(e,n,t,y)},async trackUsage(t){let n=p.trackUsage;return m(e,n,t,y)},async mutateBalance(t){let n=p.mutateBalance;return m(e,n,t,y)}}}function yn(e){return{async listInvoiceTemplates(t={}){let n=p.listInvoiceTemplates;return m(e,n,t,y)},async previewInvoice(t){let n=p.previewInvoice;return m(e,n,t,y)},async createInvoice(t){let n=p.createInvoice;return m(e,n,t,y)},async prepareBillingAdjustment(t){let n=p.prepareBillingAdjustment;return m(e,n,t,y)},async manageInvoice(t){let n=p.manageInvoice;return m(e,n,t,y)},async readInvoiceOperation(t){let n=p.readInvoiceOperation;return m(e,n,t,y)},async listInvoices(t){let n=p.listInvoices;return m(e,n,t,y)},async getInvoice(t){let n=p.getInvoice;return m(e,n,t,y)},async setupPayment(t){let n=p.setupPayment;return m(e,n,t,y)},async readPaymentSetup(t){let n=p.readPaymentSetup;return m(e,n,t,y)},async readBillingInvoice(t){let n=p.readBillingInvoice;return m(e,n,t,y)},async previewRefund(t){let n=p.previewRefund;return m(e,n,t,y)},async refund(t){let n=p.refund;return m(e,n,t,y)},async readRefund(t){let n=p.readRefund;return m(e,n,t,y)}}}function In(e){return{async previewSubscriptionBatch(t){let n=p.previewSubscriptionBatch;return m(e,n,t,y)},async confirmSubscriptionBatch(t){let n=p.confirmSubscriptionBatch;return m(e,n,t,y)},async readSubscriptionBatch(t){let n=p.readSubscriptionBatch;return m(e,n,t,y)},async abandonSubscriptionBatch(t){let n=p.abandonSubscriptionBatch;return m(e,n,t,y)},async manageSubscriptionTrial(t){let n=p.manageSubscriptionTrial;return m(e,n,t,y)},async readSubscriptionTrial(t){let n=p.readSubscriptionTrial;return m(e,n,t,y)},async listSubscriptions(t){let n=p.listSubscriptions;return m(e,n,t,y)},async listPurchases(t){let n=p.listPurchases;return m(e,n,t,y)},async listSubscriptionConflicts(t){let n=p.listSubscriptionConflicts;return m(e,n,t,y)},async retrySubscriptionConflict(t){let n=p.retrySubscriptionConflict;return m(e,n,t,y)},async previewUpdate(t){let n=p.previewUpdate;return m(e,n,t,y)},async update(t){let n=p.update;return m(e,n,t,y)},async readSubscriptionUpdate(t){let n=p.readSubscriptionUpdate;return m(e,n,t,y)},async restoreNativePurchase(t){let n=p.restoreNativePurchase;return m(e,n,t,y)},async verifySubscriptions(t){let n=p.verifySubscriptions;return m(e,n,t,y)},async previewAttach(t){let n=p.previewAttach;return m(e,n,t,y)},async recordMerchantEvent(t){return m(e,p.recordMerchantEvent,t,{request:"Invalid merchant event",parseResponse:y})},async attach(t){let n=p.attach;return m(e,n,t,y)},async readSubscriptionOperation(t){let n=p.readSubscriptionOperation;return m(e,n,t,y)}}}function wn(e){return{async grantModelBenefit(t){return m(e,p.grantModelBenefit,t,{request:"Invalid model benefit grant",response:"Invalid model benefit response"})},async readModelBenefit(t){return m(e,p.readModelBenefit,t,{request:"Invalid model benefit operation",response:"Invalid model benefit response"})},async grantOffer(t){let n=p.grantOffer;return m(e,{...n,request:n.request.refine(a=>!!a.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function vn(e){return{...hn(e),...gn(e),...yn(e),...In(e),...wn(e)}}function Sn(e){return{async getFeatures(t={}){let n=p.getFeatures;return m(e,n,t,y)},async evaluateFeatures(t){let n=p.evaluateFeatures;return m(e,n,t,y)}}}function En(e){return{async trackEvents(t){let n=p.trackEvents;return m(e,n,t,y)}}}function Rn(e){return{async resolveContent(t){let n=p.resolveContent;return m(e,n,t,y)},async resolvePaywall(t){let n=p.resolvePaywall,a=n.request.parse(t),r=await m(e,n,a,y);return we(a,r.paywall.check,r.scope),r},async resolveOffering(t){let n=p.resolveOffering,a=n.request.parse(t),r=await m(e,n,a,y);return we(a,r.check,r.scope),r}}}function qn(e){U(e.apiKey,"Secret API keys must stay on your backend");let n=N(e).request;return{async sendMessage(a){let r=p.sendMessage;return r.response.parse(await n(r.path,r.request.parse(a)))},async readMessage(a){let r=p.readMessage;return r.response.parse(await n(r.path,r.request.parse(a)))},...re(n),...vn(n),...Sn(n),...En(n),...Rn(n)}}function Se(){if(typeof window<"u")throw new s("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var Cn=()=>new s("CONFLICT","Process synchronization is in progress",425),B=()=>new s("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),Hn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),oe=class extends s{constructor(n){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:n.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=n}result};function Gn(e){if(U(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new s("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let t=N(e),n=re(t.request),a=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function r(h){let o=await e.resolveUser(h);if(o!==null&&(typeof o?.externalUserId!="string"||!o.externalUserId||o.externalUserId!==o.externalUserId.trim()||o.externalUserId.startsWith("gg_guest_")))throw new s("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return o}async function i(h){let o=await e.resolveContext(h);if(o?.confirmed!==!0||!o.processKey||!o.guestKey)throw new s("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:a+"run:"+o.processKey,guest:a+"guest:"+o.guestKey}}async function u(h,o){for(let I=0;I<8;I++){let R=await e.store.read(h),S=o(R?structuredClone(R.value):null);if(R&&Hn(R.value,S)||await e.store.compareAndSwap(h,R?.revision??null,S))return S}throw Cn()}async function l(h){let o=await e.store.read(h);if(!o)throw new s("NOT_FOUND","Open the process before continuing",404);return o.value}async function d(h){let o=await l(h);for(let I of o.revocations??[])await n.revokeCustomerSessions(I),await u(h,R=>{if(!R)throw B();return R.revocations=R.revocations?.filter(S=>S.sessionId!==I.sessionId),R})}async function w(h,o){let I=ge.parse(h);return o?t.requestWithCredential("funnel-processes",I,o):t.request("funnel-processes",I)}function E(h,o){if(o.scope.projectId!==e.scope.projectId||o.scope.environment!==e.scope.environment||h.run&&(h.run.id!==o.run.id||h.run.source.versionId!==o.run.source.versionId||h.run.source.id!==o.run.source.id||h.run.runExpiresAt!==o.run.runExpiresAt||h.run.identity.startedAs!==o.run.identity.startedAs||h.run.identity.participantId!==o.run.identity.participantId||h.run.identity.binding&&h.run.identity.binding.id!==o.run.identity.binding?.id)||h.runToken&&o.runToken&&h.runToken!==o.runToken)throw new s("INVALID_RESPONSE","Process identity or Run changed")}async function C(h,o,I){return u(h,R=>{if(!R)throw new s("NOT_FOUND","Process handle is missing",404);return E(R,o),(!R.run||o.run.revision>=R.run.revision)&&(R.run=o.run),R.runToken??=o.runToken,I!==void 0&&(R.target=I),R})}async function c(h,o){if(o.detached)throw new s("UNAUTHENTICATED","The process is detached",401);let I=o.run?.identity.binding?.customerId??o.run?.identity.participantId;if(!I)throw new s("INVALID_RESPONSE","Process participant is missing");if(o.session?.customerId===I&&Date.parse(o.session.expiresAt)>Date.now()+3e4)return o.session;let R={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},S=await u(h,O=>{if(!O||O.detached||O.run?.id!==o.run?.id)throw B();if(O.sessionLease&&O.sessionLease.until>Date.now())throw Cn();return O.sessionLease=R,O}),A;try{if(S.session?.customerId===I&&Date.parse(S.session.refreshExpiresAt)>Date.now())try{if(A=Oe.parse(await t.requestWithCredential("customer-sessions/refresh",{},S.session.refreshToken)),A.sessionId!==S.session.sessionId)throw new s("INVALID_RESPONSE","Refresh changed the logical session")}catch(P){if(!(P instanceof s)||P.status!==401)throw P}if(A??=S.run?.identity.binding?await n.createCustomerSession(I):await n.resumeGuestSession({guestToken:S.guest.token}),A.customerId!==I)throw new s("INVALID_RESPONSE","Session Customer changed");let O=A;return await u(h,P=>{if(!P||P.detached||P.sessionLease?.id!==R.id||P.run?.identity.binding?.id!==o.run?.identity.binding?.id)throw new s("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return P.session=O,delete P.sessionLease,P}),A}catch(O){throw A&&A.sessionId!==S.session?.sessionId&&await n.revokeCustomerSessions({customerId:A.customerId,sessionId:A.sessionId}).catch(()=>{}),await u(h,P=>{if(!P)throw B();return P.sessionLease?.id===R.id&&delete P.sessionLease,P}).catch(()=>{}),O}}let f;async function g(){if(f??=Xe.parse(await w({contract:V,operation:"describe"})),f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment)throw B();return f}async function v(h,o,I=!1){let R=await r(h),S=await l(o);if(S.issuingKeyId!==(await g()).keyId)throw new s("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!S.runToken||!S.run)throw new s("CONFLICT","Recover the original start first",425);if(S.detached){if(!I)throw new s("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(S.run.identity.binding&&(!R||S.target&&S.target!==R.externalUserId))throw B();await d(o),S=await u(o,A=>{if(!A||A.run?.id!==S.run?.id)throw B();return delete A.detached,A})}if(!S.runToken||!S.run)throw new s("INVALID_RESPONSE","Process identity is missing");if(S.run.identity.binding){if(R&&!S.target){let A=ye.parse(await w({contract:V,operation:"binding_status",runToken:S.runToken,requestId:S.bindingIntent?.requestId??S.start.requestId,externalUserId:R.externalUserId}));if(A.state!=="bound"||A.binding.id!==S.run.identity.binding.id)throw B();S=await u(o,O=>{if(!O)throw B();return O.target=R.externalUserId,O})}if(!R||S.target!==R.externalUserId)throw B()}else if(R){if(!S.guest)throw B();S=await u(o,O=>{if(!O||O.bindingIntent&&O.bindingIntent.externalUserId!==R.externalUserId)throw B();return O.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:R.externalUserId},O});let A=S.bindingIntent;try{let O=We.parse(await w({contract:V,operation:"bind_customer",...A,runToken:S.runToken,guestToken:S.guest.token,claimRequestId:S.guest.claimRequestId,expectedBindingId:null}));S=await C(o,O,R.externalUserId)}catch(O){let P=ye.parse(await w({contract:V,operation:"binding_status",...A,runToken:S.runToken,guestToken:S.guest.token}));if(P.state!=="bound")throw O;S=await u(o,D=>{if(!D?.run||D.run.id!==P.binding.runId)throw B();return D.run.identity.binding={id:P.binding.id,customerId:P.binding.customerId,acceptedAt:P.binding.acceptedAt},D.target=R.externalUserId,D})}}return{state:S,session:await c(o,S)}}async function _(h,o,I,R){try{return await R(I)}catch(S){if(!(S instanceof s)||S.status!==401)throw S;return await u(o,A=>{if(!A||A.detached)throw S;return A.session?.accessToken===I.session.accessToken&&(A.session.expiresAt=new Date(0).toISOString()),A}),R(await v(h,o))}}async function x(h,o,I=!1){let R=await i(h),S=await v(h,R.process,I),A=$.parse(await _(h,R.process,S,O=>w({...o,customerToken:O.session.accessToken},O.state.runToken)));return await C(R.process,A),A}return{async open(h,o){o=$e.parse(o);let I=await i(h),R=await g(),S=I.guest+":"+R.keyId,A=await e.store.read(I.process);if(!A){let F=await r(h),T,M,k;if(F)T={type:"customer",customer:{type:"externalUserId",value:F.externalUserId}};else{let q=await e.store.read(S);if(q)try{k=await n.resumeGuestSession({guestToken:q.value.token}),M=q.value}catch(L){if(!(L instanceof s)||L.status!==401)throw L}let H={token:Se(),claimRequestId:crypto.randomUUID()};M=await u(S,L=>M??(L&&L.token!==q?.value.token?L:H)),T={type:"guest",guestToken:M.token}}await u(I.process,q=>q??{issuingKeyId:R.keyId,start:ge.parse({...o,contract:V,requestId:crypto.randomUUID(),source:T}),...M?{guest:M}:{},...F?{target:F.externalUserId}:{},...k?{session:k}:{}}),A=await e.store.read(I.process)}let O=A.value;if(O.issuingKeyId!==R.keyId)throw new s("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(O.start.funnelId!==o.funnelId||O.start.operation!==o.operation)throw new s("CONFLICT","This handle already owns another process",409);if(!O.runToken){if(O.start.source.type==="customer"){let k=await r(h);if(!k||k.externalUserId!==O.target)throw B()}let F=await w(O.start),T=Ye.safeParse(F);if(T.success)throw new oe(T.data);let M=$.parse(F);if(!M.runToken)throw new s("INVALID_RESPONSE","Process credential is missing");O=await C(I.process,M)}let P=await v(h,I.process,!0),D=$.parse(await _(h,I.process,P,F=>w({contract:V,operation:"get",customerToken:F.session.accessToken},F.state.runToken)));return await C(I.process,D),{...D,runToken:O.runToken}},async syncIdentity(h){return x(h,{contract:V,operation:"get",customerToken:""},!0)},async get(h,o={}){return x(h,{...o,contract:V,operation:"get",customerToken:""})},async review(h,o){return x(h,{contract:V,operation:"review",customerToken:"",...o?{receiptId:o}:{}})},async command(h,o,I){let R=await i(h),S=await v(h,R.process),A=$.parse(await _(h,R.process,S,O=>w({contract:V,operation:"command",command:o,identity:{bindingId:I},customerToken:O.session.accessToken},O.state.runToken)));return await C(R.process,A),A},async pageExperiments(h,o,I=[]){let R=await i(h),S=await v(h,R.process);return Je.parse(await _(h,R.process,S,A=>w({contract:V,operation:"page_experiments",release:o,usedReceiptIds:I,customerToken:A.session.accessToken},A.state.runToken)))},async detach(h){let o=await i(h);await u(o.process,I=>{if(!I)throw B();return I.session&&!I.revocations?.some(R=>R.sessionId===I.session.sessionId)&&(I.revocations??=[]).push({customerId:I.session.customerId,sessionId:I.session.sessionId}),I.detached=!0,delete I.session,delete I.sessionLease,I}),await d(o.process)},destroy(){t.dispose()}}}async function jn(e,t){U(e.apiKey,"Renewal requires your backend");let n=N(e),a=en.parse(un(e,await n.request("funnels",Ze.parse({...t,operation:"renew_run"}))));if(a.run.id!==t.runId)throw new s("INVALID_RESPONSE","Run renewal identity changed");return a}function An(e){let t=pn(e),n=l=>{throw new s("INVALID_RESPONSE",l)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let a=new Set(["entry","condition","feature","split","end","output"]);for(let l of t.nodes.values()){if(!a.has(l.type))throw new s("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(l.type==="entry"&&l.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(l.type)&&!l.outputs.next&&n("Local next exit is unavailable"),l.type==="feature"){let d=l.resources.featureKey;(!d||!Object.hasOwn(e.evaluation.variables,l.writes.value)||!Object.hasOwn(t.features,d))&&n("Local Feature definition or declaration is unavailable")}if(l.type==="condition"){let d=e.conditions[l.id];(!d||!l.outputs.default||d.some((w,E)=>w.port!==`case:${E}`||!l.outputs[w.port]))&&n("Local Condition exits are unavailable")}if(l.type==="split"&&(!l.resources.experimentId||!Object.hasOwn(e.growth.experiments,l.resources.experimentId)||!l.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),l.type==="end"||l.type==="output"){let d=e.evaluation.terminals[l.id];if(!d)throw new s("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(l.outputs).length&&n("A terminal cannot have outgoing edges"),d.output?.type==="feature"&&!Object.hasOwn(t.features,d.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let d of Object.values(l.outputs))t.nodes.has(d)||n("Local target is unavailable")}let r=new Set,i=new Set;function u(l){if(i.has(l)&&n("Local graph contains a cycle"),!r.has(l)){i.add(l);for(let d of Object.values(t.nodes.get(l).outputs))u(d);i.delete(l),r.add(l)}}return u(e.topology.entry),r.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(l){let d={},w=l.context;w.features=t.features,w.savedGroups=t.savedGroups;let E=()=>{w.attributes=Ge({declarations:e.evaluation.variables,attributes:l.attributes,parameters:l.parameters,answers:{},results:d,savedGroups:t.savedGroups})};E();let C=e.topology.entry,c=0;for(;;){let f=t.nodes.get(C);if(f.type==="end"||f.type==="output"){let g=e.evaluation.terminals[C],v=g.output,_=v?.type==="feature"?t.feature(v.featureKey,w):v?.type==="variable"?qe({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:e.evaluation.variables,answers:{},results:d,parameters:l.parameters,attributes:l.attributes,savedGroups:t.savedGroups}):v?.value??null;return me(e.evaluation.outputSchema,_)||n("Local output does not match its declaration"),{outcome:g.outcome,value:_}}if(c++>=e.evaluation.maxTransitions)throw new s("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(f.type==="entry")C=f.outputs.next;else{let g=t.evaluate(C,w);if(f.type==="feature"){let v=f.writes.value,_=g.value??null;me(e.evaluation.variables[v],_)||n("Local Feature value does not match its declaration"),Ve(e.evaluation.variables,{writes:f.writes},{[v]:_}),d[v]=_,E()}C=g.target}}}}}import{z as On}from"zod";function Tn(e,t,n){let a=Le.parse(e.attributes);if(["parameters","answers","results"].some(h=>Object.hasOwn(a,h)))throw new s("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let r=je.parse(e.parameters??{}),i=On.record(On.string(),Ue).parse(e.stickyBucketAssignmentDocs??{});for(let[h,o]of Object.entries(i))if(h!==`${o.attributeName}||${o.attributeValue}`||!Object.hasOwn(a,o.attributeName)||Be(a[o.attributeName])!==o.attributeValue)throw new s("INVALID_REQUEST","Sticky document identity does not match this session");let u=e.saveStickyBucketAssignmentDoc,l=e.onFeatureUsage,d=e.onExperimentViewed,w=e.onError,E=new Map,C=new Set,c={},f=Promise.resolve();function g(h){let o=f.then(()=>(n(),h()));return f=o.catch(()=>{}),o}function v(h){try{w?.(h)}catch{}}function _(h){try{let o=h();o&&typeof o.catch=="function"&&o.catch(v)}catch(o){v(o)}}async function x(){for(let[h,o]of E){if(n(),u)try{await u(structuredClone(o))}catch{throw new s("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),E.delete(h)}}return{evaluate(h={}){let o=h.track===!0;return g(async()=>{let I=await t();n(I);let R=new Set(C),S={...c},A=new Map,O=[],P={stickyBucketAssignmentDocs:structuredClone(i),saveStickyBucketAssignmentDoc(T){A.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...o?{trackedExperiments:R,trackedFeatureUsage:S,onExperimentViewed(T,M){let k=structuredClone(T),q=structuredClone(M);d&&O.push(()=>d(structuredClone(k),structuredClone(q)))},onFeatureUsage(T,M){let k=structuredClone(M);l&&O.push(()=>l(T,structuredClone(k)))}}:{}},D=I.program.evaluate({attributes:a,parameters:r,context:P});n(I);for(let[T,M]of A)i[T]=M,E.set(T,M);await x(),n(I),o&&(C=R,c=S);for(let T of O)_(T);let F=I.configuration;return structuredClone({evaluationMode:"local",scope:F.scope,funnelId:F.funnelId,versionId:F.versionId,evaluationRevision:F.evaluationRevision,generation:F.growth.generation,...D})})},flush:()=>g(x),get stickyBucketAssignmentDocs(){return n(),structuredClone(i)}}}var zn=6e4;function ae(e){if(typeof window<"u")throw new s("SERVER_ONLY","Local Funnel sessions run on your backend");let t=Re.parse(e.scope),n=e.funnelId,a=e.load,r,i,u,l=0,d=C=>Date.now()>=C.expiresAt;async function w(){if(i)return i;let C=l;r=void 0;let c=(async()=>{let f=await a();if(C!==l)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(f&&typeof f=="object"&&"evaluationMode"in f&&f.evaluationMode==="remote")throw y(W,f),new s("EVALUATION_MODE","This Funnel requires remote decide");let g=y(tn,f);if(C!==l)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(g.scope.projectId!==t.projectId||g.scope.environment!==t.environment||g.funnelId!==n)throw new s("SCOPE_MISMATCH","Local configuration scope changed");if(g.growth.scope.projectId!==t.projectId||g.growth.scope.environment!==t.environment||g.growth.expiresAt!==g.expiresAt)throw new s("INVALID_RESPONSE","GB configuration scope or expiry changed");let v=Math.min(Date.now()+zn,g.expiresAt?Date.parse(g.expiresAt):1/0);if(Date.now()>=v)throw new s("CONFIGURATION_EXPIRED","Refresh expired local rules");let _=JSON.stringify([t.projectId,t.environment,n,g.versionId,g.evaluationRevision,g.growth.generation]),x=[g.topology,g.conditions,g.evaluation,g.growth.features,g.growth.experiments,g.growth.savedGroups];if(u?.key===_&&!mn(u.body,x))throw new s("INVALID_RESPONSE","Immutable local configuration identity changed");return u?.key!==_&&(u={key:_,body:x,program:An(g)}),r={key:_,configuration:g,expiresAt:v,program:u.program},r})();i=c;try{return await c}finally{i===c&&(i=void 0)}}function E(){return i??(r&&!d(r)?Promise.resolve(r):w())}return{session(C){let c=l;return Tn(C,E,f=>{if(e.assertUsable?.(),c!==l)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(f&&(d(f)||r?.key!==f.key))throw new s("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await w()).configuration)},reset(){l++,r=void 0,i=void 0,u=void 0}}}function Kn(e,t){let n=e.snapshot?.generation,a=ae({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),r=e.subscribe(()=>{let u=e.snapshot?.generation;e.fresh&&u!==n&&(n=u,a.refresh().catch(()=>{}))}),i=a.session;return Object.assign(a,{session(u){let l=i(u),d=l.evaluate;return Object.assign(l,{async evaluate(...w){return e.fresh||await e.refresh(),d(...w)}})},destroy(){r(),a.reset()}})}function Qn(e){if(typeof window<"u")throw new s("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>fn(e,t)}}var Q=class extends s{constructor(n,a){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,a);this.decisionId=n;this.decisionRequestId=a}decisionId;decisionRequestId};async function ie(e,t,n,a){let{decisionId:r,requestId:i}=e,u=e,l=250,d=0;for(;;){if(u.decisionId!==r||u.requestId!==i||u.decision&&!te(u.decision,t))throw new s("INVALID_RESPONSE","Decision request or customer changed");if(u.decision)return u.decision;if(u.status==="failed")throw new s("DECISION_FAILED","Decision execution failed",503,i);if(Date.now()>=n)throw new Q(r,i);if(await new Promise(w=>setTimeout(w,Math.min(Math.max(l,d-Date.now()),n-Date.now()))),Date.now()>=n)throw new Q(r,i);l=Math.min(1e3,l*2);try{u=await a(r,n)}catch(w){if(w instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(w.code)){d=Date.now()+(w.retryAfterSeconds??0)*1e3;continue}throw w}}}function Ee(e){if("remoteEval"in e)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Funnel decisions are requested by your backend");let t,n,a=new Map;async function r(d,w){let E=d;E.status!=="pending"&&a.delete(E.decisionId);for(let C=0;C<32&&E.evaluation;C++){let c=E.evaluation;if(c.runId!==E.decisionId)throw new s("INVALID_RESPONSE","Local evaluation Run changed");let f=a.get(E.decisionId);if(!f&&c.type==="evaluate_segment"){let v=sn.parse(await i({operation:"segment_configuration",funnelId:e.funnelId,versionId:c.versionId},w));if(v.configuration.scope.projectId!==e.scope.projectId||v.configuration.scope.environment!==e.scope.environment||v.configuration.funnelId!==e.funnelId||v.configuration.versionId!==c.versionId||v.configuration.evaluationRevision!==c.policyRevision)throw new s("SCOPE_MISMATCH","Original decision segment configuration changed");if(a.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding decisions first");f={operation:"commit_decision_segment",decisionId:E.decisionId,requestId:he(E.decisionId,c.visit,`segment:${c.revision}`),nodeId:c.nodeId,visit:c.visit,revision:c.revision,policyRevision:c.policyRevision,generation:v.configuration.growth.generation,...ln(v.configuration,v.document,c)},a.set(E.decisionId,f)}if(!f){if(c.type!=="evaluate")throw new s("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==c.versionId||n.evaluationRevision!==c.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=W.parse(await i({operation:"configuration",funnelId:e.funnelId,versionId:c.versionId},w))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new s("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==c.versionId||n.evaluationRevision!==c.policyRevision)throw new s("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(a.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding Local decisions first");f={operation:"evaluate_decision",decisionId:E.decisionId,requestId:he(E.decisionId,c.visit,"evaluation"),nodeId:c.nodeId,visit:c.visit,revision:c.revision,receiptId:c.receiptId,policyRevision:c.policyRevision,generation:n.growth.generation,result:an(n,c.nodeId,c,dn)},a.set(E.decisionId,f)}let g=K.parse(await i(f,w));if(g.decisionId!==d.decisionId||g.requestId!==d.requestId)throw new s("INVALID_RESPONSE","Decision identity changed during local evaluation");a.delete(E.decisionId),E=g}return E}async function i(d,w,E=!1){return N({...e,fetch:(c,f)=>{let g=new Headers(f?.headers);return g.set("Accept-Encoding","identity"),E&&g.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(c,{...f,headers:g})},timeoutMs:Math.min(e.timeoutMs??1e4,w?Math.max(1,w-Date.now()):12e4)}).request("funnels",d)}async function u(d,w){let E=K.parse(await i(ne.parse({operation:"read_decision",decisionId:d}),w));if(E.decisionId!==d)throw new s("INVALID_RESPONSE","Decision identity changed");return r(E,w)}async function l(d,w,E=!1){let C=ne.options[0].parse({...d,operation:"decide",funnelId:e.funnelId}),c;try{c=K.parse(await i(C,w,E))}catch(f){throw f instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(f.code)?new s("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",f.status,d.requestId):f}if(c.requestId!==d.requestId||c.decision&&!te(c.decision,C.customer))throw new s("INVALID_RESPONSE","Decision request or customer changed");return{response:await r(c,w),customer:C.customer}}return{local(){return t??=ae({scope:e.scope,funnelId:e.funnelId,load:()=>i({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let d=W.parse(await i({operation:"configuration",funnelId:e.funnelId}));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment||d.funnelId!==e.funnelId)throw new s("SCOPE_MISMATCH","Configuration scope changed");return d},features(d={}){return ve({...d,scope:e.scope,load:async()=>He.parse(await i({operation:"feature_config",funnelId:e.funnelId}))})},read:d=>u(d),async submit(d){return(await l(d,void 0,!0)).response},async decide(d){let w=Date.now()+3e4,E=await l(d,w);return ie(E.response,E.customer,w,u)},async reportUsed(d){let w=Qe.parse(await i(ne.parse({...d,operation:"report_used"})));if(w.decisionId!==d.decisionId||w.eventId!==d.eventId)throw new s("INVALID_RESPONSE","Usage receipt identity changed");return w}}}function Jn(e){U(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=N({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let a=rn.parse(n);if(a.orderId!==a.receiptId)throw new s("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let r=a.nativeEvidence,i={requestId:a.requestId,customerToken:a.customerToken,purchaseIntentId:a.orderId,...r===null?{intent:"read"}:r.provider==="apple"?{provider:"apple",signedTransaction:r.signedTransaction}:{provider:"google",purchaseToken:r.purchaseToken}},u=p.restoreNativePurchase.response.parse(await t.request(p.restoreNativePurchase.path,i));if(u.operation.requestId!==a.requestId||u.operation.purchaseIntentId!==a.orderId)throw new s("INVALID_RESPONSE","Native receipt request identity changed");let l=on.parse({scope:u.scope,requestId:a.requestId,orderId:u.operation.orderId,receiptId:u.operation.orderId,orderStatus:u.operation.status,refunded:u.operation.refunded,...u.operation.completion===null?{}:{nativeCompletion:{orderId:u.operation.orderId,receiptId:u.operation.orderId,...u.operation.completion}}});if(l.requestId!==a.requestId||l.orderId!==a.orderId||l.receiptId!==a.receiptId||l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new s("INVALID_RESPONSE","Current order receipt scope changed");return l}}}import{z as Yn}from"zod";var G=Yn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function $n(e,t){let n=G.parse(e.inputTokens.total),a=G.parse(e.outputTokens.total),r=G.parse(e.inputTokens.cacheRead??0),i=G.parse(e.inputTokens.cacheWrite??0),u=G.parse(e.outputTokens.reasoning??0);if(r+i>n||u>a||e.inputTokens.noCache!==void 0&&G.parse(e.inputTokens.noCache)!==n-r-i||e.outputTokens.text!==void 0&&G.parse(e.outputTokens.text)!==a-u)throw new s("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-r-i,cache_read:r,cache_write:i,output:t==="output"?a:a-u,reasoning:t==="separate"?u:0,input_audio:0,output_audio:0}}function Wn(e){if(typeof window<"u")throw new s("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new s("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(a){await e.persist({context:a,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(a,r){let i={context:a,modelId:e.modelId,usage:r,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(i);let u=e.mapTokens?e.mapTokens(r):$n(r,e.reasoning),l=await e.pricing.quoteTokens({modelId:e.modelId,tokens:u});await e.persist({...i,tokens:u,quote:l,phase:"quoted"});let d=await e.pricing.trackTokens(e.client,{...a,quote:l});if(!d.receipt.accepted)throw new s("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...i,tokens:u,quote:l,receipt:d,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:a}){let r=await e.context(),i;try{i=await a()}catch(u){throw await t(r),u}return await n(r,i.usage),i},async wrapStream({doStream:a}){let r=await e.context(),i;try{i=await a()}catch(E){throw await t(r),E}let u=!1,l=!1,d=i.stream.getReader();async function w(){u||l||(l=!0,await t(r))}return{...i,stream:new ReadableStream({async pull(E){try{let{value:C,done:c}=await d.read();if(c){if(!u)throw await w(),new s("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");E.close();return}if(C.type==="finish"){if(u)throw new s("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");u=!0,await n(r,C.usage)}E.enqueue(C)}catch(C){try{await w()}finally{E.error(C),await d.cancel(C)}}},async cancel(E){try{await w()}finally{await d.cancel(E)}}})}}}}function Xn(e){U(e.apiKey,"Funnel receipts are sent by your backend");let t=N(e);return{async signal(n){let a=fe.parse({...n,operation:"signal"}),r=ze.parse(await t.request("funnels",a));if(r.runId!==n.runId||r.eventId!==n.eventId||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new s("INVALID_RESPONSE","Receipt identity changed");return r},async readResults(n){let a=fe.parse({operation:"read_results",runId:n}),r=Ke.parse(await t.request("funnels",a));if(r.runId!==n||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new s("INVALID_RESPONSE","Result identity changed");return r}}}function Zn(e){if("remoteEval"in e)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Campaign entry requires your backend");let t=N({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let a=Date.now()+(e.timeoutMs??3e4),r=Ie.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),i=N({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,a-Date.now()))}),u=K.parse(await i.request("funnels",r));if(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");return ie(u,r.customer,a,(l,d)=>Ee({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,d-Date.now()))}).read(l))},async start(n){let a=Ie.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),r=nn.parse(await t.request("funnels",a));if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in r)&&(r.run.source.id!==e.funnelId||!r.customerId||a.customer.type==="id"&&r.customerId!==a.customer.value))throw new s("INVALID_RESPONSE","Campaign Funnel or Customer changed");return r}}}import{z as et}from"zod";var b=class extends Error{constructor(n,a=409,r=!1,i="fix_request"){super(n);this.code=n;this.status=a;this.retryable=r;this.recovery=i}code;status;retryable;recovery};function nt(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=be.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},a=t.capabilities.some(r=>["purchases","subscription_changes","refunds","operation_status"].includes(r));for(let[r,i]of Object.entries(pe))if(i.command&&t.capabilities.includes(r)&&!(r==="catalog"&&t.catalog==="static")&&!e.handlers[i.command])throw new Error(`Missing merchant command handler: ${i.command}`);if(a&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!t.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(i){let u=crypto.randomUUID(),l="bridge.ping",d,w=async(E,C,c=!1)=>{let f=JSON.stringify({bridgeVersion:de,requestId:u,command:l,scope:n,[c?"error":"data"]:E});if(new TextEncoder().encode(f).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(f,{status:C,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":u,...d?await j(f,d,"response"):{}}})};try{if(i.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(de)||i.method!=="POST"||new URL(i.url).pathname!==X)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(i.headers.get("Content-Type")??""))throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=i.body?.getReader();if(!E)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);let C=new TextDecoder("utf-8",{fatal:!0}),c="",f=0;try{for(;;){let M=await E.read();if(M.done)break;if(f+=M.value.byteLength,f>16384)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",413);c+=C.decode(M.value,{stream:!0})}c+=C.decode()}finally{await E.cancel().catch(()=>{}),E.releaseLock()}let g=_e.safeParse(JSON.parse(c));if(!g.success)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);let v=g.data;if(u=v.requestId,l=v.command,Object.keys(n).some(M=>v.scope[M]!==n[M]))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let _=v.command==="bridge.ping"||v.command==="bridge.describe",x=v.command==="catalog.read";if((_||x||i.headers.has(Y))&&(d=e.authentication.find(M=>M.keyId===i.headers.get(Y)),!d||!await z(c,i.headers,d,"request")))throw d=void 0,new b("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(v.command==="bridge.ping")return w(le["bridge.ping"].parse(v.data),200);if(v.command==="bridge.describe")return w(t,200);let h=Object.entries(pe).find(([,M])=>M.command===v.command);if(!h||!t.capabilities.includes(h[0]))throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let o=e.handlers[v.command];if(!o)throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!x&&i.headers.has("Cookie")&&(i.headers.get("Origin")!==new URL(i.url).origin||["cross-site","same-site"].includes(i.headers.get("Sec-Fetch-Site")??"")))throw new b("MERCHANT_BRIDGE_FORBIDDEN",403);let I=x?{kind:"service"}:await e.authorize(i,v),R=I.kind,S=["purchase.execute","subscription.change","refund.execute"].includes(v.command),A=S||v.command==="operation.read";if(!(A&&d!==void 0&&R==="service")&&(v.command==="refund.execute"?R!=="administrator":!x&&R!=="user"))throw new b("MERCHANT_BRIDGE_FORBIDDEN",403);if(I.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(v.command)&&!et.uuid().safeParse(I.customerId).success)throw new b("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let P=o,D=le[v.command].parse(v.data),F={request:i,command:v.command,scope:n,principal:I},T;if(A){let M=Z.parse(D);if(I.kind==="user"&&I.customerId!==M.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let k=ee.parse(await e.resolveOperationAuthority(M,F));if(k.operationId!==M.operationId||k.customerId!==M.customerId||Object.keys(n).some(H=>k.scope[H]!==n[H]))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);F.authority=k;let q=v.command==="purchase.execute"?"purchase":v.command==="subscription.change"?"subscription_change":v.command==="refund.execute"?"refund":k.instruction.type;if(k.instruction.type!==q)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!S)T=ce.parse(await P(D,F));else{if(k.confirmedAt===null)throw new b("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let H=ce.parse(await e.handlers["operation.read"](M,{...F,command:"operation.read"}));if(H.operationId!==M.operationId||H.customerId!==M.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(H.lookup==="found")T=H.execution;else{if(!k.initialExecutionAllowed)throw new b("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(k.instruction.expiresAt)<=Date.now())throw new b("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||Ae(k.instruction).some(L=>!t.billingEvents.some(bn=>bn===L))||Ce(k.instruction).some(L=>!t.profiles.includes(L)))throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=Me.parse(await P(D,F))}catch(L){throw L instanceof b?L:new b("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==q)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=Pe[v.command].parse(await P(D,F));if(I.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==I.nativeUserId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==I.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&I.customerId&&T.session.customerId!==I.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&I.customerId&&T.presentation.customerId!==I.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==Z.parse(v.data).operationId||T.customerId!==Z.parse(v.data).customerId))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return w(T,S&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(E){let C=E instanceof b?E:E instanceof SyntaxError?new b("MERCHANT_BRIDGE_INVALID_REQUEST",400):new b("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return w({code:C.code,message:C.code,retryable:C.retryable,recovery:C.recovery},C.status,!0)}}}function tt(e){return async(t,n)=>{let a=()=>e.readSubscriptionOperation(t),r=()=>e.readSubscriptionUpdate(t),i=()=>e.readRefund(t),u=n.command==="purchase.execute"?[a]:n.command==="subscription.change"?[r]:n.command==="refund.execute"?[i]:[a,r,i];for(let l of u)try{let d=await l(),w="authority"in d.operation?d.operation.authority:void 0;if(!w)throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let E=ee.parse(w);if(E.customerId!==t.customerId||E.operationId!==t.operationId||Object.keys(n.scope).some(C=>E.scope[C]!==n.scope[C]))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return E}catch(d){if(n.command==="operation.read"&&d instanceof s&&d.code==="NOT_FOUND")continue;throw d}throw new b("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}import"zod";function rt(e){if(typeof window<"u")throw new Error("Merchant protocol credentials require a trusted server");let t=ke.parse(e.manifest),n=Te.parse(e.authentication),a={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},r=e.now??Date.now,i=c=>{throw new s("INVALID_RESPONSE",c)},u=(c,f)=>ue(c)===ue(f);function l(c){new TextEncoder().encode(c).byteLength>262144&&i("Merchant protocol body exceeds limit");try{return JSON.parse(c)}catch{return i("Invalid merchant protocol JSON")}}function d(c){let f=xe.parse(c);return u(f.scope,a)||i("Merchant protocol scope mismatch"),f.command==="requirement.check"&&(t.capabilities.includes("requirement_checks")||i("Merchant Check capability unavailable"),u(f.data.subject.scope,a)||i("Merchant Check subject crosses scope")),f.command==="operation.prepare"&&(!t.capabilities.includes("preparations")||!u(f.data.request.subject.scope,a))&&i("Merchant preparation capability unavailable"),f}function w(c){if(c.command!=="operation.prepare")return;let f=c.data;return(!u(f.request.subject.scope,a)||!f.preparationAllowed||Date.parse(f.requestedAt)>r()||Date.parse(f.request.expiresAt)<=r()||!t.preparationActions.includes(f.request.action))&&i("Merchant preparation requires fresh scoped authority"),f}function E(c,f){let g=Ne(c.command).parse(f);if((g.requestId!==c.requestId||!u(g.scope,a))&&i("Merchant reply correlation mismatch"),"error"in g)return g;if(c.command==="bridge.ping"&&"challenge"in g.data&&g.data.challenge!==c.data.challenge&&i("Merchant ping challenge mismatch"),c.command==="bridge.describe"&&"bridgeVersion"in g.data&&!u({projectId:g.data.projectId,environmentId:g.data.environmentId,environment:g.data.environment},a)&&i("Merchant declaration crosses scope"),c.command==="requirement.check"&&"observation"in g.data&&(!u(g.data.observation.subject,c.data.subject)||!Fe(c.data.requirement,g.data)||!t.checkKinds.includes(g.data.kind))&&i("Merchant Check changed the original requirement or subject"),c.command==="operation.prepare"&&"quoteTermsDigest"in g.data){let v=w(c);(!u(g.data.request,v.request)||Date.parse(g.data.expiresAt)<=r()||Date.parse(g.data.observedAt)<Date.parse(v.requestedAt)||Date.parse(g.data.observedAt)>r())&&i("Merchant quote changed its authorized request or validity")}return g}let C=async c=>{let f=JSON.stringify(c);return l(f),{body:f,headers:new Headers({"Content-Type":"application/json","Cache-Control":"private, no-store",[J]:"4",...await j(f,n,"response",r(),4)})}};return{version:4,path:X,async encodeRequest(c,f){let g=d({bridgeVersion:4,requestId:crypto.randomUUID(),scope:a,command:c,data:f});w(g);let v=JSON.stringify(g);l(v);let _=new Headers({"Content-Type":"application/json",[J]:"4",...await j(v,n,"request",r(),4)});return{body:v,headers:_,async readResponse(x,h){l(x),(h.get(J)!=="4"||!await z(x,h,n,"response",r(),4))&&i("Merchant response authentication failed");let o=E(g,l(x));if("error"in o)throw new se(o.error);return o.data}}},async decodeRequest(c,f){l(c),(f.get(J)!=="4"||f.get(Y)!==n.keyId||!await z(c,f,n,"request",r(),4))&&i("Merchant request authentication failed");let g=d(l(c));return w(g),g},async encodeResponse(c,f){let g=d(c),v=E(g,{...g,data:f});return C(v)},async encodeError(c,f){let g=d(c),{data:v,..._}=g;return C(E(g,{..._,error:De.parse(f)}))}}}var se=class extends Error{constructor(n){super(n.message);this.problem=n}problem};export{Q as FunnelDecisionTimeoutError,oe as FunnelProcessEntrySuppressedError,s as LongplayError,b as MerchantBridgeHandlerError,se as MerchantBridgeProtocolError,Bn as aiPriceSnapshotSchema,Ln as aiTokenQuoteSchema,Un as createAiPricing,Wn as createAiUsageMiddleware,kn as createConfigurationSync,Vn as createConfiguredAiPricing,ve as createFeatureClient,Zn as createFunnelCampaignClient,Ee as createFunnelDecisionClient,ae as createFunnelLocalEvaluator,Xn as createFunnelOrchestrationClient,Gn as createFunnelProcessAdapter,Dn as createFunnelStartClient,Se as createGuestToken,Nn as createLocalFunnelClient,qn as createLongplayServer,tt as createMerchantBridgeAuthorityResolver,nt as createMerchantBridgeHandler,rt as createMerchantBridgeProtocol,Jn as createNativeReceiptClient,Qn as createPaywallStartClient,Kn as createSynchronizedFunnelLocalEvaluator,Fn as entitlementRequirementDigest,xn as evaluateFunnelNode,_n as merchantConfirmationMatchesTerms,Mn as merchantPreparationRequestDigest,Pn as merchantQuoteTermsDigest,jn as renewFunnelRun,j as signMerchantBridgeMessage,z as verifyMerchantBridgeMessage};
package/dist/visual.js CHANGED
@@ -1 +1 @@
1
- import{a as pe,c as fe}from"./chunk-OJM6ORHE.js";import{b as ue}from"./chunk-J6KIN4RH.js";import{a as Ve,b as re,c as ce,d as de}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-OMHZBCS3.js";import{a as ae,b as se,c as oe,d as le}from"./chunk-6HWNW6FJ.js";import"./chunk-DSPLGTQI.js";import"./chunk-LHBBSD77.js";import"./chunk-JVQVQHV2.js";import{v as te,x as ie,z as M}from"./chunk-PFHS7HK3.js";import{z as o}from"zod";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:ue(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=oe(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=ae(e.deviceIdCookie??"indiana_did"),T=se(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(ce(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=le(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=de(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=re(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
1
+ import{a as pe,c as fe}from"./chunk-OJM6ORHE.js";import{b as ue}from"./chunk-J6KIN4RH.js";import{a as Ve,b as re,c as ce,d as de}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-A7U4Z6EH.js";import{a as ae,b as se,c as oe,d as le}from"./chunk-LNSFRQ6G.js";import"./chunk-DSPLGTQI.js";import"./chunk-CCRBXW4M.js";import"./chunk-GSFNAB3W.js";import{J as te,L as ie,N as M}from"./chunk-4SWGHICJ.js";import{z as o}from"zod";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:ue(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=oe(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=ae(e.deviceIdCookie??"indiana_did"),T=se(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(ce(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=le(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=de(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=re(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkerlandai/longplay-sdk",
3
- "version": "0.10.18",
3
+ "version": "0.10.19",
4
4
  "description": "Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{d as t}from"./chunk-N4HZ55YU.js";import{Za as n}from"./chunk-JVQVQHV2.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
@@ -1 +0,0 @@
1
- function d(t){let{quote:o,operation:e,requestId:p}=t,a={type:"recover",operationId:e?.operationId??o?.operationId??null,requestId:p};if(t.destroyed||t.pending)return a;if(!e)return o?{type:"cancel",operationId:o.operationId}:a;let r=e.merchantExecution;if(r?.type==="purchase"){if(["succeeded","not_required"].includes(r.paymentStatus))return!["applied","not_applicable"].includes(r.fulfillmentStatus)||e.problem?.phase==="fulfillment"||r.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:r.recordingStatus==="accepted"&&e.status==="complete"?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&r.checkoutUrl===e.checkoutUrl&&r.checkoutExpiresAt&&Date.parse(r.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(r.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}let l=[e.problem,r?.problem],i=l.every(c=>!c||c.phase==="execution"&&c.reason!=="RESULT_UNKNOWN");return!l.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:i&&t.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!r&&!e.quoteFinalized||r?.type==="purchase"&&["failed","expired"].includes(r.paymentStatus)&&r.fulfillmentStatus==="not_applicable"&&r.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&i&&!e.quoteFinalized&&!r&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:a}function n(t){return t.recovery??{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null}}async function s(t){let o=n(t);if(o.type==="recover"&&t.quote)try{await t.read(),o=n(t)}catch{return o}if(o.type!=="cancel"&&!(o.type==="recover"&&t.pendingCancellation))return o;try{await t.cancel();let e=n(t);return e.type==="cancel"?{type:"recover",operationId:o.operationId,requestId:null}:e}catch{let e=n(t);return e.type==="recover"?e:{type:"recover",operationId:o.operationId,requestId:null}}}export{d as a,n as b,s as c};