@tinkerlandai/longplay-sdk 0.10.44 → 0.10.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/check-response-5ZLFYMPK.js +1 -0
- package/dist/{chunk-CWD36SJO.js → chunk-4LIM2ZQR.js} +1 -1
- package/dist/chunk-6RNLPMMJ.js +1 -0
- package/dist/{chunk-LZ3OJYBY.js → chunk-7MTQQIGR.js} +1 -1
- package/dist/{chunk-MPD3UIY4.js → chunk-A37ZU2AP.js} +1 -1
- package/dist/{chunk-WSGTKHYR.js → chunk-AAILPAL5.js} +1 -1
- package/dist/{chunk-4MBJTEA6.js → chunk-AKBF7TGD.js} +1 -1
- package/dist/{chunk-LU7AMQCJ.js → chunk-ANTKNFC6.js} +1 -1
- package/dist/{chunk-MKLZPUKJ.js → chunk-ASCVMPXG.js} +1 -1
- package/dist/{chunk-AV2WZSII.js → chunk-CI7UPAWD.js} +1 -1
- package/dist/{chunk-B4AELNLE.js → chunk-CRCAYVV5.js} +1 -1
- package/dist/{chunk-JK2IZQQK.js → chunk-D3WC3T4U.js} +1 -1
- package/dist/{chunk-5JRBCW6V.js → chunk-DTOYPMAW.js} +1 -1
- package/dist/{chunk-EEQRGIPH.js → chunk-EIVFBGI5.js} +1 -1
- package/dist/{chunk-AQONMY2H.js → chunk-EQKTKITL.js} +1 -1
- package/dist/{chunk-7MYS52FL.js → chunk-GFSAWDV2.js} +1 -1
- package/dist/{chunk-MWICFZUF.js → chunk-GJLCTQJN.js} +1 -1
- package/dist/chunk-HIUSHWDK.js +1 -0
- package/dist/{chunk-CSLTAXC7.js → chunk-HMPIUYZ2.js} +1 -1
- package/dist/{chunk-5TJISOWN.js → chunk-JDUB4T4P.js} +1 -1
- package/dist/{chunk-ASL7TJFU.js → chunk-JZ73DRHT.js} +1 -1
- package/dist/{chunk-3SXPCVIP.js → chunk-KAMYLHAT.js} +1 -1
- package/dist/{chunk-MEDW4N3F.js → chunk-L42A5KVA.js} +1 -1
- package/dist/{chunk-DCZWNTG2.js → chunk-L7OMFH4O.js} +1 -1
- package/dist/{chunk-HLCDAU5A.js → chunk-MBWUIYCH.js} +1 -1
- package/dist/{chunk-TL67SYPH.js → chunk-MFAEHTOH.js} +1 -1
- package/dist/{chunk-2HU3HWGB.js → chunk-MMJBC6PW.js} +1 -1
- package/dist/chunk-N3C57R2I.js +1 -0
- package/dist/chunk-N3TAZ7HB.js +1 -0
- package/dist/{chunk-TK2DKYFK.js → chunk-PE5Y524X.js} +1 -1
- package/dist/{chunk-IT5DIE6G.js → chunk-POOXIM6Q.js} +1 -1
- package/dist/{chunk-NVF54BDR.js → chunk-PPOPJTHA.js} +1 -1
- package/dist/{chunk-RJY5CUTB.js → chunk-R2OJIXYE.js} +1 -1
- package/dist/{chunk-4DRJAICV.js → chunk-SIJY35EE.js} +1 -1
- package/dist/{chunk-FTGRTYBL.js → chunk-SWULFBRF.js} +1 -1
- package/dist/chunk-TWQB35B7.js +318 -0
- package/dist/{chunk-PBZSOTKZ.js → chunk-UBUFXGS7.js} +1 -1
- package/dist/{chunk-UJMP7AMY.js → chunk-UHT5DGAJ.js} +1 -1
- package/dist/{chunk-LSVTH3TS.js → chunk-UIKMEVXM.js} +1 -1
- package/dist/{chunk-DGZCD3AY.js → chunk-W55G3VGB.js} +1 -1
- package/dist/{chunk-KP4QI4RX.js → chunk-WQN2D5FZ.js} +1 -1
- package/dist/{chunk-CALDEF4M.js → chunk-X2ON6QRA.js} +1 -1
- package/dist/{chunk-6XRXHFM6.js → chunk-XB24ATBA.js} +1 -1
- package/dist/{chunk-V65FSNYO.js → chunk-XQN7MLP5.js} +1 -1
- package/dist/{chunk-C4NG6RVA.js → chunk-XWD4N2QI.js} +1 -1
- package/dist/{chunk-6GEAXL7F.js → chunk-YHC5WAVP.js} +1 -1
- package/dist/{chunk-2TTDF4ZM.js → chunk-YPN2ZL2V.js} +1 -1
- package/dist/{chunk-VDMM6LNJ.js → chunk-ZNTV6TU7.js} +1 -1
- package/dist/{chunk-RDUKCMST.js → chunk-ZQAAZ7Q4.js} +1 -1
- package/dist/{content-2E2QSSJ5.js → content-4Y57QHWP.js} +1 -1
- package/dist/funnel-host-purchase-UWTK3C7Q.js +1 -0
- package/dist/funnel-paywall-prerender-MQWJONN5.js +1 -0
- package/dist/funnel-route-prediction-O7XGFYHS.js +1 -0
- package/dist/funnel-route-source-MYKZJIXG.js +1 -0
- package/dist/funnel-runtime-host-66OPNY4C.js +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-Z5PJ2P6H.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-OSBKHIVO.js +1 -0
- package/dist/page.js +1 -1
- package/dist/{paywall-4STK4AB4.js → paywall-QMYTDELU.js} +1 -1
- package/dist/paywall-content-LLRPWEZD.js +1 -0
- package/dist/paywall-session-P6NIFMKG.js +1 -0
- package/dist/popup.d.ts +3 -3
- package/dist/popup.js +1 -1
- package/dist/{presentation-loading-B2OeFzRN.d.ts → presentation-loading-mEA1iohf.d.ts} +2 -2
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-AQXCFML3.js +1 -0
- package/dist/server.js +1 -1
- package/dist/{visual-dom-IN6DRNX3.js → visual-dom-KUABNJV6.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/check-response-OIBVUP72.js +0 -1
- package/dist/chunk-6L652ZLP.js +0 -1
- package/dist/chunk-A4O2UDJP.js +0 -1
- package/dist/chunk-AVPJK4NU.js +0 -1
- package/dist/chunk-P6TNBX2S.js +0 -1
- package/dist/chunk-W7DI47LO.js +0 -10
- package/dist/funnel-host-purchase-P57U3SLX.js +0 -1
- package/dist/funnel-paywall-prerender-NB6DIIPJ.js +0 -1
- package/dist/funnel-route-prediction-XGCMCIKA.js +0 -1
- package/dist/funnel-route-source-O76QSUYU.js +0 -1
- package/dist/funnel-runtime-host-LVYYWHZ5.js +0 -1
- package/dist/merchant-bridge-contracts-FB63H7NE.js +0 -1
- package/dist/operation-contracts-YSFIINLK.js +0 -1
- package/dist/paywall-content-ITCPYRUZ.js +0 -1
- package/dist/paywall-session-W4JSVFCR.js +0 -1
- package/dist/screen-renderer-QFI7D6QJ.js +0 -1
- /package/dist/{chunk-GPJF3T43.js → chunk-6RGARS6I.js} +0 -0
- /package/dist/{chunk-WPFTSHP2.js → chunk-FRK6322O.js} +0 -0
- /package/dist/{chunk-RA7GZ67U.js → chunk-KV5MZ4NI.js} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.46
|
|
4
|
+
|
|
5
|
+
- Stop polling an original Funnel Run after `409 / STATE_CHANGED / recover_operation`; recover the original Run and purchase without starting another attempt.
|
|
6
|
+
- Replace stale presentations and controllers atomically. Keep pending Checkout recovery available and fence late replies after dismissal or identity changes.
|
|
7
|
+
- Wire protocol remains `0.10`.
|
|
8
|
+
|
|
9
|
+
## 0.10.45
|
|
10
|
+
|
|
11
|
+
- Render a compact static Paywall loading shell from the initial published document, with at most four plan placeholders on desktop and two on mobile. Keep loading text and Close visible without mounting authored controls.
|
|
12
|
+
- Replace the loading shell atomically when the first screen is ready. SDK loading reveals content once with a 160 ms fade, respecting reduced motion.
|
|
13
|
+
- Preserve cancellation, late-response handling and the Paywall’s outer presentation. Wire protocol remains `0.10`.
|
|
14
|
+
|
|
3
15
|
## 0.10.44
|
|
4
16
|
|
|
5
17
|
- Add optional `FunnelHostOptions.mountPaywallControls(container, run)` for merchant-owned Paywall controls and their teardown.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b}from"./chunk-A37ZU2AP.js";import"./chunk-4LIM2ZQR.js";import"./chunk-DTOYPMAW.js";import"./chunk-MFAEHTOH.js";import"./chunk-XB24ATBA.js";import"./chunk-6RGARS6I.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s,b as c,c as u}from"./chunk-
|
|
1
|
+
import{a as s,b as c,c as u}from"./chunk-DTOYPMAW.js";import{j as m,m as p}from"./chunk-XB24ATBA.js";import{b as e}from"./chunk-6RGARS6I.js";var y=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],i=e.enum(y);function x(t){let n=i.parse(t.toUpperCase());return["JPY","KRW","VND"].includes(n)?0:2}function I(t,n,r="en",f={}){let a=i.parse(n.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...f}).format(t/10**x(a))}var l=e.enum(["stripe","apple","google","merchant"]),w=e.enum(["membership","credit_pack","lifetime"]),v=e.enum(["active","grace","suspended","inactive","revoked"]),z=e.strictObject({currency:e.string().regex(/^[A-Z]{3}$/),micros:e.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var d=e.object({provider:l,currency:i,intent:e.literal("subscription_change").optional()}).strict();var o=e.strictObject({internal_feature_id:e.uuid(),quantity:m.refine(t=>/[1-9]/.test(t)),properties:p,entityId:e.uuid().optional()}),B=e.strictObject({requirement:o,commerce:d.optional(),paywallId:e.uuid().optional()}),g=e.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),b=e.strictObject({productId:e.string().min(1),productVersionId:e.string().min(1),name:e.string().min(1).max(120),action:e.enum(["purchase","upgrade","addon","topup"]),membershipId:e.string().min(1).nullable(),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),currency:i,amountMinor:e.string().regex(/^(0|[1-9]\d{0,8})$/),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(156)}),h=e.strictObject({subject:c,authority:e.enum(["longplay","merchant"]),observedAt:e.iso.datetime({offset:!0}),sourceRevision:e.string().min(1).max(128),requirementDigest:s});function S(t,n){return u({subject:c.parse(t),requirement:o.parse(n)})}var C=e.strictObject({internal_feature_id:e.string().min(1),name:e.string().min(1).max(120),kind:e.enum(["access","metered","credit"]),quantity:m,allowed:e.boolean(),observation:h.optional(),reason:g.nullable(),preview:e.strictObject({scenario:e.enum(["feature_flag","usage_limit"]),candidates:e.array(b).max(20)}).nullable()}).superRefine((t,n)=>{(t.allowed!==(t.reason===null)||t.allowed&&t.preview!==null||new Set(t.preview?.candidates.map(r=>r.productVersionId)).size!==(t.preview?.candidates.length??0)||t.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&n.addIssue({code:"custom",message:"Invalid access recommendation"})}),T=e.strictObject({paywallId:e.uuid(),requirement:o}),U=e.strictObject({subject:c,requirement:o}),$=C.safeExtend({observation:h.extend({authority:e.literal("merchant")})});function F(t,n){let r=o.parse(t);return n.internal_feature_id===r.internal_feature_id&&n.quantity===r.quantity&&(!n.observation||n.observation.requirementDigest===S(n.observation.subject,r))}export{i as a,x as b,I as c,w as d,d as e,o as f,B as g,b as h,S as i,C as j,U as k,$ as l,F as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as n,r as t}from"./chunk-YHC5WAVP.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as p,c as d}from"./chunk-
|
|
1
|
+
import{b as p,c as d}from"./chunk-L7OMFH4O.js";import{t as a,w as u,z as m}from"./chunk-GJLCTQJN.js";import{b as e}from"./chunk-6RGARS6I.js";var s=e.enum(["page","popup","banner"]),y=3e5,f=e.strictObject({type:e.enum(["string","number","boolean","strings","json"]),nullable:e.boolean()}),h=e.strictObject({inputs:e.record(a,f.extend({required:e.boolean()})).refine(t=>Object.keys(t).length<=40,"Too many content inputs"),outputs:e.record(a,f).refine(t=>Object.keys(t).length<=40,"Too many content outputs")}),g=e.strictObject({kind:s,schemaVersion:e.literal(1),name:e.string().trim().min(1).max(80),screen:u,contract:h}),c=g.superRefine((t,r)=>{let n=(o,b)=>r.addIssue({code:"custom",message:o,path:b});t.screen.surface!==t.kind&&n("Content surface must match its domain",["screen","surface"]),t.screen.name!==t.name&&n("Content has one editable name",["screen","name"]),t.kind==="banner"&&t.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),t.kind!=="banner"&&t.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),t.screen.actions.some(o=>o.type!=="event"&&o.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let i=new Set(t.screen.actions.filter(o=>o.type==="event").map(o=>o.id));(Object.keys(t.contract.outputs).some(o=>!i.has(o))||[...i].some(o=>!Object.hasOwn(t.contract.outputs,o)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),d(t)>y&&n("Content document exceeds its byte budget",[])});function S(t,r){if(t===null)return r.nullable;switch(r.type){case"json":return!0;case"string":return typeof t=="string";case"number":return typeof t=="number"&&Number.isFinite(t);case"boolean":return typeof t=="boolean";case"strings":return Array.isArray(t)&&t.every(n=>typeof n=="string")}}var x=c.superRefine((t,r)=>{for(let n of p(t.screen))Object.keys(t.contract.inputs).some(i=>n===i||n.startsWith(i+"."))||r.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of t.screen.actions){if(n.type!=="event")continue;let i=t.contract.outputs[n.id],o=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;i&&!S(o,i)&&r.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}m(t.screen).some(n=>!n.complete)&&r.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),l=e.strictObject({id:e.uuid(),kind:s,projectId:e.uuid(),environmentId:e.uuid(),name:e.string(),revision:e.number().int().nonnegative(),status:e.enum(["draft","published","archived"]),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})}),D=l.extend({draft:c}),I=e.strictObject({rows:e.array(l).max(200),nextCursor:e.uuid().nullable()}),v=e.strictObject({id:e.uuid(),kind:s,resourceId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),sourceRevision:e.number().int().nonnegative(),document:x,createdAt:e.iso.datetime({offset:!0})}),z=v.omit({document:!0}),V=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),kind:s,id:e.uuid(),document:c}),e.strictObject({action:e.literal("save"),kind:s,id:e.uuid(),revision:e.number().int().nonnegative(),document:c}),e.strictObject({action:e.enum(["publish","archive"]),kind:s,id:e.uuid(),revision:e.number().int().nonnegative()})]).superRefine((t,r)=>{"document"in t&&t.document.kind!==t.kind&&r.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});export{s as a,v as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as o}from"./chunk-
|
|
1
|
+
import{m as o}from"./chunk-4LIM2ZQR.js";import{a as i}from"./chunk-MFAEHTOH.js";function m(t,e,n,r){if(!o(t,e)||n!==void 0&&e.observation&&e.observation.subject.customerId!==n||r!==void 0&&e.observation!==void 0&&(e.observation.subject.scope.projectId!==r.projectId||e.observation.subject.scope.environment!==r.environment))throw new i("INVALID_RESPONSE","The access requirement or Customer changed");return e}function d(t,e,n){if(t.requirement){if(!e)throw new i("INVALID_RESPONSE","The requested access check is missing");m(t.requirement,e,t.customerId,n)}}export{m as a,d as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as d}from"./chunk-
|
|
1
|
+
import{b as d}from"./chunk-YPN2ZL2V.js";import{a as u}from"./chunk-DSPLGTQI.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-6GEAXL7F.js";import{a as tt}from"./chunk-EEQRGIPH.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-HLCDAU5A.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-DCZWNTG2.js";import{a as fe,b as Ze}from"./chunk-JK2IZQQK.js";import{a as le}from"./chunk-LSVTH3TS.js";import{e as de}from"./chunk-3SXPCVIP.js";import{a as D}from"./chunk-TL67SYPH.js";import{h as ie}from"./chunk-6XRXHFM6.js";import{b as et}from"./chunk-3VUPVXAV.js";import{b as Qe}from"./chunk-2TTDF4ZM.js";import{b as e}from"./chunk-GPJF3T43.js";import{c as Fe,f as Pe}from"./chunk-C4NG6RVA.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-O76QSUYU.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-O76QSUYU.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
|
|
1
|
+
import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-YHC5WAVP.js";import{a as tt}from"./chunk-EIVFBGI5.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-MBWUIYCH.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-L7OMFH4O.js";import{a as fe,b as Ze}from"./chunk-D3WC3T4U.js";import{a as le}from"./chunk-UIKMEVXM.js";import{e as de}from"./chunk-KAMYLHAT.js";import{a as D}from"./chunk-MFAEHTOH.js";import{h as ie}from"./chunk-XB24ATBA.js";import{b as et}from"./chunk-3VUPVXAV.js";import{b as Qe}from"./chunk-YPN2ZL2V.js";import{b as e}from"./chunk-6RGARS6I.js";import{c as Fe,f as Pe}from"./chunk-XWD4N2QI.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-MYKZJIXG.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-MYKZJIXG.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as _e}from"./chunk-RJY5CUTB.js";import{a as M}from"./chunk-V65FSNYO.js";import{D as ee,F as Ne,c as Re,e as D,j as Ee,u as ke,v as qe,x as Fe,z as Ae}from"./chunk-6GEAXL7F.js";import{a as Se,b as Ce,c as ve}from"./chunk-NVF54BDR.js";import{K as x}from"./chunk-DCZWNTG2.js";import{a as te}from"./chunk-B4AELNLE.js";import{i as ne}from"./chunk-AQONMY2H.js";import{A as X,C as Z,E as Pe}from"./chunk-KP4QI4RX.js";import{w as de}from"./chunk-5TJISOWN.js";import{b as Oe}from"./chunk-JK2IZQQK.js";import{a as l}from"./chunk-TL67SYPH.js";import{h as W}from"./chunk-6XRXHFM6.js";import{b as be}from"./chunk-2TTDF4ZM.js";import{b as n}from"./chunk-GPJF3T43.js";import{a as pe}from"./chunk-DSPLGTQI.js";var g=x.options,Qe=n.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),Ee.omit({customerToken:!0})]),me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),nt=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume","start"]),start:n.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),n.strictObject({operation:n.literal("recover_run"),runId:n.uuid(),funnelId:n.uuid()}),n.strictObject({operation:n.literal("recover_purchase"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("settle_command"),runId:n.uuid(),funnelId:n.uuid(),requestId:n.uuid(),command:n.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),n.strictObject({operation:n.literal("run_command"),runId:n.uuid(),funnelId:n.uuid(),command:Qe})]),re=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:D.shape.run.shape.status}),j={scope:W,customerId:n.uuid()},je=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...j,outcome:n.literal("resolved"),target:re,view:D.shape.run.nullable(),access:n.discriminatedUnion("type",[n.strictObject({type:n.literal("customer")}),n.strictObject({type:n.literal("operation_only"),cause:n.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,d)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Te=n.strictObject({...j,target:re,view:D.shape.run.nullable(),settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),acceptance:n.enum(["accepted","not_accepted","unknown"]),receiptPhase:n.enum(["accepted","processing","done"]).nullable(),basis:n.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:n.uuid().nullable(),operationId:n.uuid().nullable()}),purchase:D.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let m=a.settlement;(m.acceptance==="accepted"!=(m.receiptPhase!==null)||m.acceptance==="accepted"&&m.basis!=="receipt"||m.acceptance==="unknown"&&(m.state!=="unknown"||m.basis!=="none")||m.acceptance!=="accepted"&&(m.operationId!==null||m.receiptId!==null)||m.acceptance==="not_accepted"&&(m.state!=="settled"||!["run_terminal","position_advanced"].includes(m.basis))||a.purchase&&(a.purchase.receiptId!==m.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==m.operationId||a.purchase.quote&&a.purchase.quote.operationId!==m.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ue=n.strictObject({...j,target:re,purchase:D.shape.purchase.unwrap()}).superRefine((a,d)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),xe=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("none")}),n.strictObject({...j,outcome:n.literal("blocked")}),n.strictObject({...j,outcome:n.literal("found"),target:re,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:me})]);var Ye=x.options[0].refine(a=>!a.customer&&!a.customerData),Je=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),De=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:W,customerId:n.uuid(),sessionId:n.uuid(),start:Ye,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Re.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Je).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:ke.nullable()})});function He(a){return Fe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Le(a){let d=new URL(a.baseUrl??be).href,m=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function P(){a.assertCurrent();try{let v=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(v.revision)||v.revision<0)throw m();let s=v.entry===null?null:De.parse(v.entry);if(s&&(s.baseUrl!==d||s.customerId!==a.customerId||s.scope.projectId!==a.scope.projectId||s.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(s?.journal.entry&&(s.journal.entry.scope.projectId!==s.scope.projectId||s.journal.entry.scope.environment!==s.scope.environment||s.journal.entry.funnelId!==s.start.funnelId||s.journal.entry.runId!==s.run?.id||s.journal.entry.versionId!==s.run?.versionId)||s?.operationCommand&&!s.purchases.some(E=>E.operationId===s.operationCommand?.operationId))throw m();return{revision:v.revision,entry:s}}catch(v){throw v instanceof l?v:m()}}async function z(v){for(let s=0;s<8;s++){let E=await P(),O=v(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&De.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw m()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw m();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:P,update:z,baseUrl:d}}var Ke=5*6e4;function $e(a,d){let m=a.purchases.find(P=>P.type==="checkout");if(!a.actions.includes("continue_checkout")||m?.type!=="checkout"||d!==void 0&&m.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return m.checkoutUrl}function kt(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},m=d.session.snapshot();if(!m)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:P,sessionId:z}=m,v=!1,s=null,E,O=null,R=!1,F,B,Q,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},S=new Map,T=new Map,fe=new AbortController,Y=new Set,H=Oe(d),J=_e(H.request);function L(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function y(){if(v||d.session.snapshot()?.customerId!==P)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let h=Le({...d,customerId:P,assertCurrent:y,storage:d.storage??He({baseUrl:d.baseUrl,scope:d.scope,customerId:P})}),Ve=d.session.subscribeIdentity(he);function he(){v||(v=!0,clearTimeout(Q),fe.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),Ve(),s?.reset(),s=null,O=null,H.dispose(),Y.clear(),S.clear(),T.clear())}function C(e){y();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(Q),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Q=setTimeout(()=>{U().catch(()=>{})},5e3)),t&&pe(d.onRecovery,structuredClone(e));for(let r of t?Y:[]){if(v)break;pe(r,structuredClone(e))}return structuredClone(e)}function I(e){if(y(),!e||e.start.requestId!==E)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function b(e){let t=[...e.purchases],r=e.journal.entry?.purchase;return r&&!t.some(o=>o.operationId===r.operationId)&&t.push({receiptId:r.receiptId,operationId:r.operationId,terminal:null}),t}function A(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&b(e).every(t=>t.terminal!==null)}function _(e,t){let r=e.journal.entry?.command??e.journal.entry?.closeCommand,o=b(e).map(w=>{let le=S.get(w.operationId);return w.terminal&&!le?{type:w.terminal,operationId:w.operationId}:te({quote:le?.quote??null,operation:le??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(w.operationId)===!0})}),u=o.filter(w=>!["complete","native"].includes(w.type)),i=u[0],c=u.length===1&&i?.operationId?S.get(i.operationId):void 0;if(c&&(i?.type==="checkout"||i?.type==="cancel"))try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote)}catch(w){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:L(w)}}let f;if(t==="operation"&&!r&&i?.type==="cancel"&&c?.quote&&!c.problem&&!c.confirmedAt)try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote),Date.parse(c.quote.expiresAt)>Date.now()&&(f={operationId:c.operationId,quote:c.quote})}catch{}let p=o.length>0&&u.length===0,N=A(e)||t==="operation"&&p&&!r&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":r||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!f?"waiting_result":"ready";return{mode:t,status:N,purchases:o,...f?{confirmation:structuredClone(f)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:f?["confirm"]:[],...u.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function oe(e){let t=te({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ae(e){if(!e.operation)return;let t=X.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=ne(S.get(t.operationId)??null,t);S.set(t.operationId,r),r===t&&T.set(t.operationId,e.canReselect===!0)}async function Ge(e){y();for(let r of[e.purchase,e.run.paywall])r&&ae(r);let t=await h.update(r=>{if(I(r),r.run&&(r.run.id!==e.run.id||r.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=b(r);for(let u of[e.purchase,e.run.paywall]){let i=u?.operation?.operationId??u?.quote?.operationId;if(!u||!i)continue;let c=o.find(p=>p.operationId===i);if(c&&c.receiptId!==u.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let f=oe(S.get(i));c?c.terminal??=f:o.push({receiptId:u.receiptId,operationId:i,terminal:f})}return{...r,purchases:o,run:r.run&&(r.run.revision>e.run.revision||!["running","waiting"].includes(r.run.status)&&["running","waiting"].includes(e.run.status))?r.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});I(t),t.run&&!["running","waiting"].includes(t.run.status)&&b(t).some(r=>!r.terminal)&&(t=await V(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(r=>!!r)))),I(t),C(_(t,"run"))}function Me(){return{async read(){let{entry:e}=await h.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await h.update(o=>{if(I(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return r=null,o.journal.revision!==e?o:(r=e+1,{...o,journal:{revision:r,entry:t}})}),r}}}async function V(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let c=r.has(i.operationId)?S.get(i.operationId):void 0;if(c??=await se(e,i),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(c.merchantExecution&&c.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&te({quote:c.quote??null,operation:c,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let f=Z(c)?await J.update({operationId:i.operationId,intent:"cancel"}):await J.attach({operationId:i.operationId,intent:"cancel"});if(c=X.parse(f.operation),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");c=await se(e,i)}S.set(i.operationId,ne(S.get(i.operationId)??null,c))}let u=await h.update(i=>{I(i);let c=i.operationCommand&&S.get(i.operationCommand.operationId);return{...i,...c&&(c.confirmedAt||c.merchantExecution||!Pe(c))?{operationCommand:void 0}:{},purchases:b(i).map(f=>({...f,terminal:f.terminal??oe(S.get(f.operationId))}))}});return I(u),u}async function G(e){y();let t=await H.request("funnels",e);return y(),t}async function ze(e){try{return await G(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return G({...e,intent:"resume"})}}async function Be(){let e=M(xe,await G({operation:"find_purchase"}));if(e.customerId!==P||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:r}=e;return await h.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...r,terminal:null}],journal:{revision:0,entry:null}}),"found"}let K;function ie(e){let t=K;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<Ke))return t.job;let r={at:Date.now(),job:Be().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw K===r&&(K=void 0),o})};return K=r,r.job}async function se(e,t,r="recover_purchase"){let o=M(Ue,await G({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ue(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ae(o.purchase),S.get(t.operationId)}async function Ie(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=M(Te,await G({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ue(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ae(r.purchase);let o=await h.update(u=>{I(u);let i=b(u),{receiptId:c,operationId:f}=r.settlement;if(c&&f){let N=i.find(w=>w.operationId===f);if(N&&N.receiptId!==c)throw new l("INVALID_RESPONSE","Original Receipt changed");N||i.push({receiptId:c,operationId:f,terminal:oe(S.get(f))})}let p=r.settlement.state==="settled"?qe(u.journal.entry,t.requestId):u.journal.entry;return{...u,purchases:i,journal:p===u.journal.entry?u.journal:{revision:u.journal.revision+1,entry:p}}});I(o),e=o}return e}function ue(e,t){if(t.customerId!==P||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function ce(e,t){if(I(e),e.run&&(e=await Ie(e)),!b(e).length&&A(e))return C(_(e,"operation"));if(!b(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(t)});R=!0;let r=await V(e);return C(_(r,"operation"))}async function $(e,t=!1,r=!0){if(E=e.start.requestId,O=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!s){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ze(o)}catch(p){if(!e.run&&p instanceof l&&(p.status===void 0||p.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:L(p)});throw p}let i=M(je,u);if(i.customerId!==P||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ue(e,i);let c=await h.update(p=>(I(p),{...p,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??p.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(c),e=c,i.access.type==="operation_only")return ce(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ie(e);let f=i.view;if(f.locale!==e.start.locale||!Ae(f.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");s=Ne({...d,customerRun:{runId:i.target.runId,customerId:P,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},funnelCommandStorage:Me(),onAcceptedResponse:Ge},{scope:i.scope,run:f})}try{await s.get(),s.view?.pendingRequest?.requestId===e.start.requestId&&!s.pendingCommands?.length&&await s.resume(s.view.pendingRequest.requestId);for(let u of s.pendingCommands??[])u.operation!=="close"&&await s.settle?.(u.requestId);s.pendingCommands?.length&&await s.retry(),y();let o=(await h.read()).entry;return I(o),C(_(o,"run"))}catch(o){if(y(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){s.reset(),s=null;let u=(await h.read()).entry;return I(u),$(u,!1,!1)}throw o}}function q(e,t="read",r){if(y(),F)return t==="read"||t===B?F:F.then(()=>q(e,t,r),()=>q(e,t,r));clearTimeout(Q);let o=e().catch(u=>{throw!v&&!r?.(u)&&C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:L(u)}),u});return F=o,B=t,o.then(()=>{F===o&&(F=void 0,B=void 0)},()=>{F===o&&(F=void 0,B=void 0)}),o}function U(){return q(async()=>{let{entry:e}=await h.read();if(!e||A(e)){if(await ie(!1)==="blocked")return we();({entry:e}=await h.read())}return e?(E&&e.start.requestId!==E&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R&&E===e.start.requestId?ce(e,k.error):$(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function we(){return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function ye(){let e=await U();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:q(async()=>{let t=(await h.read()).entry;if(I(t),!R){if(!s?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=s.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(Z(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return C(_(t,"run"));if(s.pendingCommands?.length)await s.retry();else{let w=s.view;await s.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:w.nodeId,visit:w.visit,revision:w.revision,input:{type:"paywall_confirm",operationId:w.paywall.quote.operationId,...w.paywall.quote.merchantTerms?{merchantConfirmation:de(w.paywall.quote.merchantTerms)}:{}}})}let N=(await h.read()).entry;return I(N),C(_(N,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&S.get(r);if(!r||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");ee({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await h.update(p=>{if(I(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:r,intent:"confirm"}}});let u={operationId:r,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:de(o.quote.merchantTerms)}:{}},i=Z(o)?await J.update(u):await J.attach(u),c=X.parse(i.operation);if(y(),i.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");S.set(r,ne(o,c));let f=(await h.read()).entry;return I(f),C(_(await V(f,!1,new Set([r])),"operation"))},"confirm")}async function ge(){y();let{entry:e}=await h.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return s},get recovery(){return structuredClone(k)},get attempt(){return y(),structuredClone(O)},get identitySignal(){return fe.signal},get customerId(){return P},retained:ge,async findPurchase(){let e=await ge();if(e==="pending")return e;let t=await ie(!0);return y(),t==="none"?e:t},async readPaywall(e){y();let t=Se(e),[r,{readPaywallContent:o},{validateResourceCheck:u}]=await Promise.all([Ce(H.request,"resolvePaywall"),import("./paywall-content-ITCPYRUZ.js"),import("./check-response-OIBVUP72.js")]);y();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),c=await ve(H.request,r,i);u(i,c.paywall.check,c.scope);let f=await o(d,c.paywall);if(y(),t.paywallVersionId?f.id!==t.paywallVersionId:f.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return f},start(e){let t=x.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return q(async()=>{let r=(await h.read()).entry;if((!r||A(r))&&await ie(!0)==="blocked")return we();let o=await h.update(u=>{if(u&&!A(u)){if(u.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return E!==o.start.requestId&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R?ce(o,k.error):$(o,!0)},`start:${t.funnelId}`)},refresh:U,confirm:ye,retry:()=>R?ye():q(async()=>{let{entry:e}=await h.read();return e?$(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return s?.view?q(async()=>{if(!s?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(s.pendingCommands?.find(r=>r.operation==="close"))await s.retry();else if(["running","waiting"].includes(s.view.status)){let r=s.view;await s.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await h.read()).entry;return I(t),C(_(t,"run"))},"close"):U()},async continueCheckout(e,t){let r=t?await q(async()=>{let{entry:o}=await h.read();if(I(o),!o.run||!b(o).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let u=await V(o);return C(_(u,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await U();y(),await e($e(r,t))},async terminateCheckout(e){let t=await U();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return q(async()=>{let{entry:o}=await h.read();I(o);let u=b(o).find(c=>c.operationId===e&&!c.terminal);if(!u||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await se(o,u,"terminate_checkout");let i=await V(o,!1,new Set([e]));return C(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Y.add(e),()=>{Y.delete(e)}},destroy:he}}export{He as a,$e as b,kt as c};
|
|
1
|
+
import{b as _e}from"./chunk-R2OJIXYE.js";import{a as M}from"./chunk-XQN7MLP5.js";import{D as ee,F as Ne,c as Re,e as D,j as Ee,u as ke,v as qe,x as Fe,z as Ae}from"./chunk-YHC5WAVP.js";import{a as Se,b as Ce,c as ve}from"./chunk-PPOPJTHA.js";import{K as x}from"./chunk-L7OMFH4O.js";import{a as te}from"./chunk-CRCAYVV5.js";import{i as ne}from"./chunk-EQKTKITL.js";import{A as X,C as Z,E as Pe}from"./chunk-WQN2D5FZ.js";import{w as de}from"./chunk-JDUB4T4P.js";import{b as Oe}from"./chunk-D3WC3T4U.js";import{a as l}from"./chunk-MFAEHTOH.js";import{h as W}from"./chunk-XB24ATBA.js";import{b as be}from"./chunk-YPN2ZL2V.js";import{b as n}from"./chunk-6RGARS6I.js";import{a as pe}from"./chunk-DSPLGTQI.js";var g=x.options,Qe=n.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),Ee.omit({customerToken:!0})]),me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),nt=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume","start"]),start:n.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),n.strictObject({operation:n.literal("recover_run"),runId:n.uuid(),funnelId:n.uuid()}),n.strictObject({operation:n.literal("recover_purchase"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("settle_command"),runId:n.uuid(),funnelId:n.uuid(),requestId:n.uuid(),command:n.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),n.strictObject({operation:n.literal("run_command"),runId:n.uuid(),funnelId:n.uuid(),command:Qe})]),re=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:D.shape.run.shape.status}),j={scope:W,customerId:n.uuid()},je=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...j,outcome:n.literal("resolved"),target:re,view:D.shape.run.nullable(),access:n.discriminatedUnion("type",[n.strictObject({type:n.literal("customer")}),n.strictObject({type:n.literal("operation_only"),cause:n.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,d)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Te=n.strictObject({...j,target:re,view:D.shape.run.nullable(),settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),acceptance:n.enum(["accepted","not_accepted","unknown"]),receiptPhase:n.enum(["accepted","processing","done"]).nullable(),basis:n.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:n.uuid().nullable(),operationId:n.uuid().nullable()}),purchase:D.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let m=a.settlement;(m.acceptance==="accepted"!=(m.receiptPhase!==null)||m.acceptance==="accepted"&&m.basis!=="receipt"||m.acceptance==="unknown"&&(m.state!=="unknown"||m.basis!=="none")||m.acceptance!=="accepted"&&(m.operationId!==null||m.receiptId!==null)||m.acceptance==="not_accepted"&&(m.state!=="settled"||!["run_terminal","position_advanced"].includes(m.basis))||a.purchase&&(a.purchase.receiptId!==m.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==m.operationId||a.purchase.quote&&a.purchase.quote.operationId!==m.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ue=n.strictObject({...j,target:re,purchase:D.shape.purchase.unwrap()}).superRefine((a,d)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),xe=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("none")}),n.strictObject({...j,outcome:n.literal("blocked")}),n.strictObject({...j,outcome:n.literal("found"),target:re,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:me})]);var Ye=x.options[0].refine(a=>!a.customer&&!a.customerData),Je=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),De=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:W,customerId:n.uuid(),sessionId:n.uuid(),start:Ye,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Re.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Je).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:ke.nullable()})});function He(a){return Fe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Le(a){let d=new URL(a.baseUrl??be).href,m=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function P(){a.assertCurrent();try{let v=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(v.revision)||v.revision<0)throw m();let s=v.entry===null?null:De.parse(v.entry);if(s&&(s.baseUrl!==d||s.customerId!==a.customerId||s.scope.projectId!==a.scope.projectId||s.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(s?.journal.entry&&(s.journal.entry.scope.projectId!==s.scope.projectId||s.journal.entry.scope.environment!==s.scope.environment||s.journal.entry.funnelId!==s.start.funnelId||s.journal.entry.runId!==s.run?.id||s.journal.entry.versionId!==s.run?.versionId)||s?.operationCommand&&!s.purchases.some(E=>E.operationId===s.operationCommand?.operationId))throw m();return{revision:v.revision,entry:s}}catch(v){throw v instanceof l?v:m()}}async function z(v){for(let s=0;s<8;s++){let E=await P(),O=v(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&De.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw m()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw m();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:P,update:z,baseUrl:d}}var Ke=5*6e4;function $e(a,d){let m=a.purchases.find(P=>P.type==="checkout");if(!a.actions.includes("continue_checkout")||m?.type!=="checkout"||d!==void 0&&m.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return m.checkoutUrl}function kt(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},m=d.session.snapshot();if(!m)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:P,sessionId:z}=m,v=!1,s=null,E,O=null,R=!1,F,B,Q,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},S=new Map,T=new Map,fe=new AbortController,Y=new Set,H=Oe(d),J=_e(H.request);function L(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function y(){if(v||d.session.snapshot()?.customerId!==P)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let h=Le({...d,customerId:P,assertCurrent:y,storage:d.storage??He({baseUrl:d.baseUrl,scope:d.scope,customerId:P})}),Ve=d.session.subscribeIdentity(he);function he(){v||(v=!0,clearTimeout(Q),fe.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),Ve(),s?.reset(),s=null,O=null,H.dispose(),Y.clear(),S.clear(),T.clear())}function C(e){y();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(Q),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Q=setTimeout(()=>{U().catch(()=>{})},5e3)),t&&pe(d.onRecovery,structuredClone(e));for(let r of t?Y:[]){if(v)break;pe(r,structuredClone(e))}return structuredClone(e)}function I(e){if(y(),!e||e.start.requestId!==E)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function b(e){let t=[...e.purchases],r=e.journal.entry?.purchase;return r&&!t.some(o=>o.operationId===r.operationId)&&t.push({receiptId:r.receiptId,operationId:r.operationId,terminal:null}),t}function A(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&b(e).every(t=>t.terminal!==null)}function _(e,t){let r=e.journal.entry?.command??e.journal.entry?.closeCommand,o=b(e).map(w=>{let le=S.get(w.operationId);return w.terminal&&!le?{type:w.terminal,operationId:w.operationId}:te({quote:le?.quote??null,operation:le??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(w.operationId)===!0})}),u=o.filter(w=>!["complete","native"].includes(w.type)),i=u[0],c=u.length===1&&i?.operationId?S.get(i.operationId):void 0;if(c&&(i?.type==="checkout"||i?.type==="cancel"))try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote)}catch(w){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:L(w)}}let f;if(t==="operation"&&!r&&i?.type==="cancel"&&c?.quote&&!c.problem&&!c.confirmedAt)try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote),Date.parse(c.quote.expiresAt)>Date.now()&&(f={operationId:c.operationId,quote:c.quote})}catch{}let p=o.length>0&&u.length===0,N=A(e)||t==="operation"&&p&&!r&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":r||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!f?"waiting_result":"ready";return{mode:t,status:N,purchases:o,...f?{confirmation:structuredClone(f)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:f?["confirm"]:[],...u.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function oe(e){let t=te({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ae(e){if(!e.operation)return;let t=X.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=ne(S.get(t.operationId)??null,t);S.set(t.operationId,r),r===t&&T.set(t.operationId,e.canReselect===!0)}async function Ge(e){y();for(let r of[e.purchase,e.run.paywall])r&&ae(r);let t=await h.update(r=>{if(I(r),r.run&&(r.run.id!==e.run.id||r.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=b(r);for(let u of[e.purchase,e.run.paywall]){let i=u?.operation?.operationId??u?.quote?.operationId;if(!u||!i)continue;let c=o.find(p=>p.operationId===i);if(c&&c.receiptId!==u.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let f=oe(S.get(i));c?c.terminal??=f:o.push({receiptId:u.receiptId,operationId:i,terminal:f})}return{...r,purchases:o,run:r.run&&(r.run.revision>e.run.revision||!["running","waiting"].includes(r.run.status)&&["running","waiting"].includes(e.run.status))?r.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});I(t),t.run&&!["running","waiting"].includes(t.run.status)&&b(t).some(r=>!r.terminal)&&(t=await V(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(r=>!!r)))),I(t),C(_(t,"run"))}function Me(){return{async read(){let{entry:e}=await h.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await h.update(o=>{if(I(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return r=null,o.journal.revision!==e?o:(r=e+1,{...o,journal:{revision:r,entry:t}})}),r}}}async function V(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let c=r.has(i.operationId)?S.get(i.operationId):void 0;if(c??=await se(e,i),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(c.merchantExecution&&c.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&te({quote:c.quote??null,operation:c,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let f=Z(c)?await J.update({operationId:i.operationId,intent:"cancel"}):await J.attach({operationId:i.operationId,intent:"cancel"});if(c=X.parse(f.operation),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");c=await se(e,i)}S.set(i.operationId,ne(S.get(i.operationId)??null,c))}let u=await h.update(i=>{I(i);let c=i.operationCommand&&S.get(i.operationCommand.operationId);return{...i,...c&&(c.confirmedAt||c.merchantExecution||!Pe(c))?{operationCommand:void 0}:{},purchases:b(i).map(f=>({...f,terminal:f.terminal??oe(S.get(f.operationId))}))}});return I(u),u}async function G(e){y();let t=await H.request("funnels",e);return y(),t}async function ze(e){try{return await G(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return G({...e,intent:"resume"})}}async function Be(){let e=M(xe,await G({operation:"find_purchase"}));if(e.customerId!==P||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:r}=e;return await h.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...r,terminal:null}],journal:{revision:0,entry:null}}),"found"}let K;function ie(e){let t=K;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<Ke))return t.job;let r={at:Date.now(),job:Be().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw K===r&&(K=void 0),o})};return K=r,r.job}async function se(e,t,r="recover_purchase"){let o=M(Ue,await G({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ue(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ae(o.purchase),S.get(t.operationId)}async function Ie(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=M(Te,await G({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ue(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ae(r.purchase);let o=await h.update(u=>{I(u);let i=b(u),{receiptId:c,operationId:f}=r.settlement;if(c&&f){let N=i.find(w=>w.operationId===f);if(N&&N.receiptId!==c)throw new l("INVALID_RESPONSE","Original Receipt changed");N||i.push({receiptId:c,operationId:f,terminal:oe(S.get(f))})}let p=r.settlement.state==="settled"?qe(u.journal.entry,t.requestId):u.journal.entry;return{...u,purchases:i,journal:p===u.journal.entry?u.journal:{revision:u.journal.revision+1,entry:p}}});I(o),e=o}return e}function ue(e,t){if(t.customerId!==P||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function ce(e,t){if(I(e),e.run&&(e=await Ie(e)),!b(e).length&&A(e))return C(_(e,"operation"));if(!b(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(t)});R=!0;let r=await V(e);return C(_(r,"operation"))}async function $(e,t=!1,r=!0){if(E=e.start.requestId,O=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!s){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ze(o)}catch(p){if(!e.run&&p instanceof l&&(p.status===void 0||p.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:L(p)});throw p}let i=M(je,u);if(i.customerId!==P||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ue(e,i);let c=await h.update(p=>(I(p),{...p,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??p.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(c),e=c,i.access.type==="operation_only")return ce(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ie(e);let f=i.view;if(f.locale!==e.start.locale||!Ae(f.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");s=Ne({...d,customerRun:{runId:i.target.runId,customerId:P,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},funnelCommandStorage:Me(),onAcceptedResponse:Ge},{scope:i.scope,run:f})}try{await s.get(),s.view?.pendingRequest?.requestId===e.start.requestId&&!s.pendingCommands?.length&&await s.resume(s.view.pendingRequest.requestId);for(let u of s.pendingCommands??[])u.operation!=="close"&&await s.settle?.(u.requestId);s.pendingCommands?.length&&await s.retry(),y();let o=(await h.read()).entry;return I(o),C(_(o,"run"))}catch(o){if(y(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){s.reset(),s=null;let u=(await h.read()).entry;return I(u),$(u,!1,!1)}throw o}}function q(e,t="read",r){if(y(),F)return t==="read"||t===B?F:F.then(()=>q(e,t,r),()=>q(e,t,r));clearTimeout(Q);let o=e().catch(u=>{throw!v&&!r?.(u)&&C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:L(u)}),u});return F=o,B=t,o.then(()=>{F===o&&(F=void 0,B=void 0)},()=>{F===o&&(F=void 0,B=void 0)}),o}function U(){return q(async()=>{let{entry:e}=await h.read();if(!e||A(e)){if(await ie(!1)==="blocked")return we();({entry:e}=await h.read())}return e?(E&&e.start.requestId!==E&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R&&E===e.start.requestId?ce(e,k.error):$(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function we(){return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function ye(){let e=await U();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:q(async()=>{let t=(await h.read()).entry;if(I(t),!R){if(!s?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=s.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(Z(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return C(_(t,"run"));if(s.pendingCommands?.length)await s.retry();else{let w=s.view;await s.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:w.nodeId,visit:w.visit,revision:w.revision,input:{type:"paywall_confirm",operationId:w.paywall.quote.operationId,...w.paywall.quote.merchantTerms?{merchantConfirmation:de(w.paywall.quote.merchantTerms)}:{}}})}let N=(await h.read()).entry;return I(N),C(_(N,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&S.get(r);if(!r||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");ee({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await h.update(p=>{if(I(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:r,intent:"confirm"}}});let u={operationId:r,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:de(o.quote.merchantTerms)}:{}},i=Z(o)?await J.update(u):await J.attach(u),c=X.parse(i.operation);if(y(),i.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");S.set(r,ne(o,c));let f=(await h.read()).entry;return I(f),C(_(await V(f,!1,new Set([r])),"operation"))},"confirm")}async function ge(){y();let{entry:e}=await h.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return s},get recovery(){return structuredClone(k)},get attempt(){return y(),structuredClone(O)},get identitySignal(){return fe.signal},get customerId(){return P},retained:ge,async findPurchase(){let e=await ge();if(e==="pending")return e;let t=await ie(!0);return y(),t==="none"?e:t},async readPaywall(e){y();let t=Se(e),[r,{readPaywallContent:o},{validateResourceCheck:u}]=await Promise.all([Ce(H.request,"resolvePaywall"),import("./paywall-content-LLRPWEZD.js"),import("./check-response-5ZLFYMPK.js")]);y();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),c=await ve(H.request,r,i);u(i,c.paywall.check,c.scope);let f=await o(d,c.paywall);if(y(),t.paywallVersionId?f.id!==t.paywallVersionId:f.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return f},start(e){let t=x.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return q(async()=>{let r=(await h.read()).entry;if((!r||A(r))&&await ie(!0)==="blocked")return we();let o=await h.update(u=>{if(u&&!A(u)){if(u.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return E!==o.start.requestId&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R?ce(o,k.error):$(o,!0)},`start:${t.funnelId}`)},refresh:U,confirm:ye,retry:()=>R?ye():q(async()=>{let{entry:e}=await h.read();return e?$(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return s?.view?q(async()=>{if(!s?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(s.pendingCommands?.find(r=>r.operation==="close"))await s.retry();else if(["running","waiting"].includes(s.view.status)){let r=s.view;await s.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await h.read()).entry;return I(t),C(_(t,"run"))},"close"):U()},async continueCheckout(e,t){let r=t?await q(async()=>{let{entry:o}=await h.read();if(I(o),!o.run||!b(o).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let u=await V(o);return C(_(u,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await U();y(),await e($e(r,t))},async terminateCheckout(e){let t=await U();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return q(async()=>{let{entry:o}=await h.read();I(o);let u=b(o).find(c=>c.operationId===e&&!c.terminal);if(!u||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await se(o,u,"terminate_checkout");let i=await V(o,!1,new Set([e]));return C(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Y.add(e),()=>{Y.delete(e)}},destroy:he}}export{He as a,$e as b,kt as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as p}from"./chunk-
|
|
1
|
+
import{e as p}from"./chunk-L42A5KVA.js";import{c as g}from"./chunk-PPOPJTHA.js";import{b as B}from"./chunk-A37ZU2AP.js";import{b as F}from"./chunk-EIVFBGI5.js";import{a as $}from"./chunk-CRCAYVV5.js";import{e as Y,f as X,g as Z,h as ee,i as re}from"./chunk-EQKTKITL.js";import{b as j}from"./chunk-ZQAAZ7Q4.js";import{A as x,B as R,E as K,z as J}from"./chunk-WQN2D5FZ.js";import{w as G}from"./chunk-JDUB4T4P.js";import{b as W}from"./chunk-D3WC3T4U.js";import{a as M}from"./chunk-UIKMEVXM.js";import{t as H}from"./chunk-GFSAWDV2.js";import{a}from"./chunk-MFAEHTOH.js";import{a as z}from"./chunk-DSPLGTQI.js";function ae(I){let t=[...new Set(I.map(({path:s})=>{let c=s.map(String).join(".");return c.startsWith("selector")?"paywallId or paywallVersionId":c||"input"}))],O=t.includes("locale")?` Pass locale, the Customer's language such as "en" or "zh-CN".`:"";return new a("INVALID_REQUEST",`createPaywallSession input is invalid: ${t.join(", ")}.${O}`)}async function Ie(I,t){if(!M.test(t.customerToken))throw new a("INVALID_TOKEN","A verified Customer credential is required");if(I.session&&I.session.peek()!==t.customerToken)throw new a("SCOPE_MISMATCH","Paywall credential does not match the shared session");let O=p.resolvePaywall.request.safeParse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}});if(!O.success)throw ae(O.error.issues);let s=O.data,c=W(I);I.session||c.identify(t.customerToken);let n=null,v=!1,U=new AbortController,u=null,d=null,b=null,P=null,T=null,y=null,m=null,A=0,q=null,k="",D=0,C=new Map,E=new Set;function S(){if(v)throw new a("IDENTITY_CHANGED","Paywall is closed")}function L(){let e=JSON.stringify([A,m!==null]);if(!q||e!==k){k=e;let r=te(++D);q=r;let i=()=>{q===r&&(q=null)};r.then(i,i)}return q.then(r=>structuredClone(r))}async function te(e){S();let r=p.resolvePaywall,i=await g(c.request,r,{...s,selector:n?{type:"version",versionId:n.id}:s.selector});B(s,i.paywall.check,i.scope);let l=await F(I,i.paywall);if(S(),t.paywallVersionId?l.id!==t.paywallVersionId:l.paywallId!==t.paywallId)throw new a("INVALID_RESPONSE","The requested Paywall changed");if(n&&(!Y(l,n)||l.paywallId!==n.paywallId))throw new a("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==D)return structuredClone(n??l);n=l;for(let h of E)z(h,structuredClone(n));return structuredClone(n)}async function Q(e){if(S(),P&&e!=="read")throw new a("COMMAND_PENDING","Wait for the original quote");if(!u)throw new a("INVALID_REQUEST","A quoted purchase is required");let r=u;if(e!=="read"){if(m){if(y===e)return m;throw new a("COMMAND_PENDING","Wait for the original purchase command")}if(y&&y!==e)throw new a("COMMAND_PENDING","Read the original purchase before changing an uncertain command");y=e,A++,D++}let i=y,l=A,h=e==="read"&&m===null,f=JSON.stringify([r.operationId,l,m!==null]);if(e==="read"&&C.has(f))return C.get(f).then(o=>structuredClone(o));let w=(async()=>{let o={operationId:r.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&r.merchantTerms?{merchantConfirmation:G(r.merchantTerms)}:{}},V=R(r)?e==="read"?await g(c.request,p.readSubscriptionUpdate,o):await g(c.request,p.update,o):e==="read"?await g(c.request,p.readSubscriptionOperation,o):await g(c.request,p.attach,o),N=x.parse(V.operation);return N.quote&&ee(r,N.quote),X(N,{operationId:r.operationId,currency:s.commerce.currency,membershipId:R(r)?r.membershipId:null,...R(r)?{featureQuantities:r.featureQuantities??{}}:{}},"The purchase operation changed"),S(),u?.operationId!==r.operationId?structuredClone(N):(d=re(d,N),(e!=="read"||h&&m===null)&&A===l&&y===i&&(y=null),structuredClone(d))})();if(e!=="read"){m=w;let o=()=>{m===w&&(m=null)};w.then(o,o)}else{C.set(f,w);let o=()=>{C.get(f)===w&&C.delete(f)};w.then(o,o)}return w.then(o=>structuredClone(o))}let _={signal:U.signal,get view(){return n?structuredClone(n):null},get quote(){return u?structuredClone(u):null},get operation(){return d?structuredClone(d):null},get webViewUrl(){return"bundled"},get locale(){return s.locale},get recovery(){return $({quote:u,operation:d,requestId:T,pending:P!==null||y!==null,destroyed:v})},get pendingCancellation(){return!v&&y==="cancel"},refresh:L,subscribe(e){return v?()=>{}:(E.add(e),()=>E.delete(e))},async preview(e){if(S(),!n)throw new a("INVALID_REQUEST","Load the Paywall first");let r=n.document.buttons[e.actionId];if(r?.type!=="checkout")throw new a("INVALID_REQUEST","Choose an authored purchase action");let i=j(r.product,e.selection,n.capabilities);if(!i)throw new a("PRODUCT_UNAVAILABLE","Choose an available Product");let l=H(n.document.screen,i,e.selection,n.capabilities);if(s.commerce.intent==="subscription_change"&&!e.subscriptionChange)throw new a("INVALID_REQUEST","Choose the existing membership for this subscription change");if(e.subscriptionChange&&e.nativeOffer)throw new a("INVALID_REQUEST","A web membership change cannot include a store offer");let h=e.subscriptionChange?p.previewUpdate.request.parse({requestId:e.requestId,...e.subscriptionChange,change:{type:"plan",productVersionId:i,...Object.keys(l).length?{featureQuantities:l}:{}},...e.offerId?{offerId:e.offerId}:{}}):p.previewAttach.request.parse({funnelId:s.funnelId,funnelVersionId:s.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:i,...Object.keys(l).length?{featureQuantities:l}:{}}],provider:s.commerce.provider,currency:s.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),f=JSON.stringify(h);if(b&&b!==f&&(P||y||!d||K(d)))throw new a("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(b===f){if(P)return P;if(u)return structuredClone(u)}b!==f&&(u=null,d=null),b=f,T=h.requestId;let w=(async()=>{let o="membershipId"in h?await g(c.request,p.previewUpdate,h):await g(c.request,p.previewAttach,h),V=J.parse(o.quote);return S(),Z(V,{productVersionId:i,featureQuantities:l,currency:s.commerce.currency,provider:s.commerce.provider,subscriptionChange:e.subscriptionChange},"The purchase quote changed its selected Product or presentment"),u=V,d=null,structuredClone(u)})();P=w;try{return await w}finally{P===w&&(P=null)}},confirm:()=>Q("confirm"),cancel:()=>Q("cancel"),read:()=>Q("read"),destroy(){v||(v=!0,U.abort(),E.clear(),C.clear(),ne?.(),c.dispose(),n=null,u=null,d=null,b=null,T=null)}},ne=I.session?.subscribeIdentity(_.destroy);try{return await L(),_}catch(e){throw _.destroy(),e}}export{Ie as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e}from"./chunk-
|
|
1
|
+
import{b as e}from"./chunk-6RGARS6I.js";var r=e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),m=e.enum(["unknown","denied","provisional","granted"]),d=e.enum(["ios","android"]),i=e.strictObject({installationId:e.uuid(),publicKey:e.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:e.iso.datetime({offset:!0}),signature:e.string().regex(/^[A-Za-z0-9_-]{86}$/)}),a=e.string().regex(/^[a-f0-9]{64}$/),p=i.extend({sequence:r,platform:d,credentialDigest:a}),f=i.extend({credentialDigest:a}),x=i.extend({sequence:r,platform:d}),l=i.extend({sequence:r,credentialDigest:a,connectionId:e.uuid().nullable(),kind:e.enum(["fcm_token","apns_token"]).nullable(),token:e.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:m}),g=l,b=l.extend({challenge:e.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),S=e.strictObject({requested:e.literal(!0),expiresAt:e.iso.datetime({offset:!0})}),A=e.strictObject({installationId:e.uuid(),bound:e.boolean(),identitySeq:r,bindingGeneration:r,addressSeq:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:e.uuid().nullable(),addressStatus:e.enum(["active","invalid"]).nullable(),permission:m}),I=e.strictObject({channel:e.enum(["email","sms","voice","push"]),state:e.enum(["unknown","allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}),P=e.strictObject({state:e.enum(["allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function y(s,c,t){let n=["indiana_push_v1",s,c.projectId,c.environment,t.installationId,t.publicKey,t.issuedAt];s==="bind"?n.push(t.sequence,t.platform,t.credentialDigest):s==="detach"?n.push(t.sequence,t.platform):s==="read"?n.push(t.credentialDigest):n.push(t.sequence,t.credentialDigest,t.connectionId,t.kind,t.token,t.permission),s==="recovery_confirm"&&n.push(t.challenge);let u=JSON.stringify(n);if([...u].some(o=>o.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(u,o=>o.charCodeAt(0))}export{p as a,f as b,x as c,l as d,g as e,b as f,S as g,A as h,I as i,y as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as d,D as u}from"./chunk-
|
|
1
|
+
import{C as d,D as u}from"./chunk-WQN2D5FZ.js";function f(r){let{quote:o,operation:e,requestId:s}=r,a={type:"recover",operationId:e?.operationId??o?.operationId??null,requestId:s};if(r.destroyed||r.pending)return a;if(!e)return o?{type:"cancel",operationId:o.operationId}:a;let t=e.merchantExecution;if(d(e)){if(t&&t.type!=="subscription_change")return a;if(t?.type==="subscription_change"){if(["applied","scheduled"].includes(t.status))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&u(e)&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&!e.problem&&!t.problem&&t.nextAction?.type==="redirect"&&(!e.checkoutUrl||t.nextAction.url===e.checkoutUrl)&&Date.parse(t.nextAction.expiresAt)>Date.now()&&t.status==="pending")return{type:"checkout",operationId:e.operationId,checkoutUrl:t.nextAction.url}}if(!e.problem&&!t?.problem&&u(e)&&e.executor!=="merchant")return{type:"complete",operationId:e.operationId};if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let n=p=>!p||p.phase==="execution"&&p.reason==="STATE_CHANGED";return r.canReselect===!0&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&n(e.problem)&&n(t?.problem)&&(!t||t.status==="failed"&&t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable")?{type:"native",operationId:e.operationId}:["prepared","quoted"].includes(e.status)&&!e.confirmedAt&&!t&&!e.checkoutUrl&&!e.problem?{type:"cancel",operationId:e.operationId}:a}if(t?.type==="purchase"){if(["succeeded","not_required"].includes(t.paymentStatus))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&!e.problem&&!t.problem&&t.checkoutUrl===e.checkoutUrl&&t.checkoutExpiresAt&&Date.parse(t.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(t.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let c=[e.problem,t?.problem],i=c.every(n=>!n||n.phase==="execution"&&n.reason!=="RESULT_UNKNOWN"),y=e.status==="cancelled"&&!c.some(Boolean)&&t?.type==="purchase"&&["pending","not_started","expired"].includes(t.paymentStatus)&&["not_started","not_applicable"].includes(t.fulfillmentStatus);return r.canReselect===!0&&i&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"||!t||t.type==="purchase"&&!["succeeded","not_required"].includes(t.paymentStatus)&&(y||t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable"))?{type:"native",operationId:e.operationId}:!c.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:i&&r.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!t&&!e.quoteFinalized||t?.type==="purchase"&&["failed","expired"].includes(t.paymentStatus)&&t.fulfillmentStatus==="not_applicable"&&t.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&i&&!e.quoteFinalized&&!t&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:a}function h(r,o=!0){if(!r)return!1;let e=f({quote:r.quote??null,operation:r,requestId:null,pending:!1,destroyed:!1,canReselect:o});return e.type==="complete"||e.type==="native"}function l(r){return r.recovery??{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null}}function b(r){return!!(r?.operationId&&(r.type==="checkout"||r.type==="recover"||r.type==="fulfillment"||r.type==="recording"))}async function g(r){let o=l(r);if(o.type==="recover"&&r.quote)try{await r.read(),o=l(r)}catch{return o}if(o.type!=="cancel"&&!(o.type==="recover"&&r.pendingCancellation))return o;try{await r.cancel();let e=l(r);return e.type==="cancel"?{type:"recover",operationId:o.operationId,requestId:null}:e}catch{let e=l(r);return e.type==="recover"?e:{type:"recover",operationId:o.operationId,requestId:null}}}export{f as a,h as b,l as c,b as d,g as e};
|