@tinkerlandai/longplay-sdk 0.10.37 → 0.10.38
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 +6 -0
- package/dist/check-response-Q7GOBUGJ.js +1 -0
- package/dist/chunk-2LND3R7K.js +1 -0
- package/dist/{chunk-XJRDO3NI.js → chunk-4E326NPY.js} +1 -1
- package/dist/{chunk-DDLSQSWO.js → chunk-5IGASP6C.js} +1 -1
- package/dist/{chunk-AB7GEGZ2.js → chunk-64ETX3AY.js} +1 -1
- package/dist/{chunk-OX2A3UD2.js → chunk-6QOJRLVM.js} +1 -1
- package/dist/{chunk-PW5PIBSO.js → chunk-6WEHTOED.js} +1 -1
- package/dist/{chunk-E7CCHUSO.js → chunk-7PXJUHDS.js} +1 -1
- package/dist/{chunk-T2KWLYCW.js → chunk-BDC7B4KM.js} +1 -1
- package/dist/{chunk-ZYOZSUZS.js → chunk-DK5PHPSO.js} +1 -1
- package/dist/{chunk-OQRMAU2B.js → chunk-DSLJUN3P.js} +1 -1
- package/dist/{chunk-AOGDCT4T.js → chunk-DTWSDNYI.js} +1 -1
- package/dist/{chunk-AHUYZ6IW.js → chunk-EEYDOVVS.js} +1 -1
- package/dist/{chunk-KFIL73QY.js → chunk-G7Y7LPOB.js} +1 -1
- package/dist/{chunk-W74JLL2O.js → chunk-GEPX4AUR.js} +1 -1
- package/dist/{chunk-ZZIBLQCJ.js → chunk-H2I37CQ4.js} +1 -1
- package/dist/{chunk-WZMZMJCK.js → chunk-HJVEVJXS.js} +1 -1
- package/dist/chunk-I7QTCEYR.js +1 -0
- package/dist/{chunk-CY7OKV7E.js → chunk-IHB275C3.js} +1 -1
- package/dist/{chunk-VIBJNB5B.js → chunk-IV6LKRYM.js} +1 -1
- package/dist/{chunk-TASEZY5T.js → chunk-JBDNNV3P.js} +1 -1
- package/dist/{chunk-XGNXZWZL.js → chunk-JXTJT2EW.js} +1 -1
- package/dist/{chunk-HEHLFHW7.js → chunk-K3VQKR4G.js} +1 -1
- package/dist/{chunk-YV6UFESO.js → chunk-KQF4BVOL.js} +1 -1
- package/dist/{chunk-4KLXQKNO.js → chunk-KTBXAATX.js} +1 -1
- package/dist/{chunk-2KJLN65C.js → chunk-L54MODP5.js} +1 -1
- package/dist/{chunk-UV4H6VCS.js → chunk-NK55HFFF.js} +1 -1
- package/dist/{chunk-U7NX5ET2.js → chunk-O5VA3E5D.js} +1 -1
- package/dist/{chunk-LC6UCDWE.js → chunk-PLOUC66F.js} +1 -1
- package/dist/{chunk-VLSP3LRH.js → chunk-Q7K66FTS.js} +1 -1
- package/dist/{chunk-OCWSWXCW.js → chunk-QZRJ3ZXU.js} +1 -1
- package/dist/{chunk-2VMEDQHT.js → chunk-RK7XOT3F.js} +1 -1
- package/dist/{chunk-Q676H74B.js → chunk-SY7AYEDO.js} +1 -1
- package/dist/{chunk-ECKVJGXQ.js → chunk-TLV3NVUU.js} +1 -1
- package/dist/{chunk-S43TYW3V.js → chunk-UAJTQ23E.js} +1 -1
- package/dist/{chunk-LOLMUXHW.js → chunk-UD7XPHE4.js} +1 -1
- package/dist/{chunk-6F4JS3RK.js → chunk-UFTLA3ZI.js} +1 -1
- package/dist/{chunk-7XDQKZYA.js → chunk-WP3SZU24.js} +1 -1
- package/dist/chunk-WQZOT22S.js +1 -0
- package/dist/{chunk-RE4OLOOT.js → chunk-XBCKVHOT.js} +1 -1
- package/dist/{chunk-GH6FM44P.js → chunk-Y5RT7PAD.js} +1 -1
- package/dist/{chunk-D3OYXTMC.js → chunk-YYXINZ4A.js} +1 -1
- package/dist/{content-QNBATPA2.js → content-B4CC4O23.js} +1 -1
- package/dist/{funnel-host-purchase-FVYPBPET.js → funnel-host-purchase-AGBJG3RK.js} +1 -1
- package/dist/funnel-paywall-prerender-HHAQBIIB.js +1 -0
- package/dist/funnel-runtime-host-IJDKXLST.js +1 -0
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-KVOFRPKV.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-G4C7ZLEH.js +1 -0
- package/dist/page.js +1 -1
- package/dist/{paywall-OAVC654P.js → paywall-TVCH6VQT.js} +1 -1
- package/dist/paywall-content-QSTCRYU5.js +1 -0
- package/dist/paywall-session-UBQYU5XD.js +1 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-Q3VSMB2N.js +1 -0
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/check-response-N22NNTIT.js +0 -1
- package/dist/chunk-2HBIBIOF.js +0 -1
- package/dist/chunk-HKXFCRVT.js +0 -1
- package/dist/chunk-WQ3O5RXN.js +0 -1
- package/dist/funnel-paywall-prerender-Z7RA4YDY.js +0 -1
- package/dist/funnel-runtime-host-TJPF3FJS.js +0 -1
- package/dist/merchant-bridge-contracts-67AYXZFI.js +0 -1
- package/dist/operation-contracts-EK4RCUWJ.js +0 -1
- package/dist/paywall-content-75XEM7K3.js +0 -1
- package/dist/paywall-session-U6SPRJRS.js +0 -1
- package/dist/screen-renderer-YIIT742O.js +0 -1
- /package/dist/{chunk-CR2XJ2CX.js → chunk-42UXYMRZ.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as c}from"./chunk-
|
|
1
|
+
import{k as c}from"./chunk-HJVEVJXS.js";import{b as r}from"./chunk-42UXYMRZ.js";var s=r.strictObject({items:r.array(r.strictObject({productVersionId:r.string().min(1).max(200),label:r.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:r.string().min(1).max(200).nullable(),grouping:c.optional()});function p(e,t,n){let i=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof i!="string"||!Object.values(n.plans).some(o=>o.versionId===i&&o.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(i)||!n.pickers[e.pickerId]?.options.includes(i))?null:i}export{s as a,p as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as E,b as M,c as j,d as O,e as T}from"./chunk-
|
|
1
|
+
import{a as E,b as M,c as j,d as O,e as T}from"./chunk-7PXJUHDS.js";import{d as w}from"./chunk-K3VQKR4G.js";import{a as u}from"./chunk-O5VA3E5D.js";import{b as t}from"./chunk-42UXYMRZ.js";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Z(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Z as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as o}from"./chunk-
|
|
1
|
+
import{m as o}from"./chunk-BDC7B4KM.js";import{a as i}from"./chunk-O5VA3E5D.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 o}from"./chunk-
|
|
1
|
+
import{b as o}from"./chunk-42UXYMRZ.js";var s=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],n=o.string().regex(/.+\/.+/),e=o.number().min(-100),t=o.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),p=o.strictObject({input:t,output:t,cache_read:t.optional(),cache_write:t.optional(),reasoning:t.optional(),input_audio:t.optional(),output_audio:t.optional()}),i=(r,a)=>o.record(r,a).refine(c=>Object.keys(c).length<=100,"At most 100 AI overrides"),d=o.strictObject({defaultMarkup:e,providerMarkups:i(o.string().min(1),e),modelMarkups:i(n,e),customModels:i(n,p.partial())});export{s as a,n as b,e as c,p as d,d as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s,b as o,c as u}from"./chunk-
|
|
1
|
+
import{a as s,b as o,c as u}from"./chunk-UD7XPHE4.js";import{d as m,g as p}from"./chunk-K3VQKR4G.js";import{b as e}from"./chunk-42UXYMRZ.js";var f=["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(f);function x(t){let r=i.parse(t.toUpperCase());return["JPY","KRW","VND"].includes(r)?0:2}function I(t,r,n="en",y={}){let a=i.parse(r.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:a,...y}).format(t/10**x(a))}var d=e.enum(["stripe","apple","google","merchant"]),_=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 l=e.object({provider:d,currency:i}).strict();var c=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:c,commerce:l.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"]),S=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(),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:o,authority:e.enum(["longplay","merchant"]),observedAt:e.iso.datetime({offset:!0}),sourceRevision:e.string().min(1).max(128),requirementDigest:s});function b(t,r){return u({subject:o.parse(t),requirement:c.parse(r)})}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(S).max(20)}).nullable()}).superRefine((t,r)=>{(t.allowed!==(t.reason===null)||t.allowed&&t.preview!==null||new Set(t.preview?.candidates.map(n=>n.productVersionId)).size!==(t.preview?.candidates.length??0)||t.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&r.addIssue({code:"custom",message:"Invalid access recommendation"})}),T=e.strictObject({paywallId:e.uuid(),requirement:c}),U=e.strictObject({subject:o,requirement:c}),$=C.safeExtend({observation:h.extend({authority:e.literal("merchant")})});function F(t,r){let n=c.parse(t);return r.internal_feature_id===n.internal_feature_id&&r.quantity===n.quantity&&(!r.observation||r.observation.requirementDigest===b(r.observation.subject,n))}export{i as a,x as b,I as c,_ as d,l as e,c as f,B as g,S as h,b as i,C as j,U as k,$ as l,F as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b as o,c as i}from"./chunk-
|
|
1
|
+
import{a,b as o,c as i}from"./chunk-IHB275C3.js";import{a as p}from"./chunk-O5VA3E5D.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as Re}from"./chunk-ZYOZSUZS.js";import{a as G}from"./chunk-VIBJNB5B.js";import{A as _e,E as W,G as ke,d as Pe,f as x,k as Se,v as Ee,w as be,y as Oe}from"./chunk-KFIL73QY.js";import{a as we,b as ge,c as ye}from"./chunk-CY7OKV7E.js";import{aa as U}from"./chunk-YV6UFESO.js";import{a as X}from"./chunk-3NCMYTNG.js";import{g as Z}from"./chunk-Q676H74B.js";import{b as ve}from"./chunk-7XDQKZYA.js";import{b as $}from"./chunk-HEHLFHW7.js";import{a as l}from"./chunk-U7NX5ET2.js";import{b as Ce}from"./chunk-AHUYZ6IW.js";import{b as n}from"./chunk-CR2XJ2CX.js";import{a as ue}from"./chunk-DSPLGTQI.js";var g=U.options,Ve=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}),Se.omit({customerToken:!0})]),ce=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),We=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume"]),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:ce}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:ce}),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:Ve})]),ee=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:x.shape.run.shape.status}),N={scope:$,customerId:n.uuid()},Fe=n.discriminatedUnion("outcome",[n.strictObject({...N,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...N,outcome:n.literal("resolved"),target:ee,view:x.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"})}),qe=n.strictObject({...N,target:ee,view:x.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:x.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let p=a.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||a.purchase&&(a.purchase.receiptId!==p.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==p.operationId||a.purchase.quote&&a.purchase.quote.operationId!==p.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"})}),Ae=n.strictObject({...N,target:ee,purchase:x.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"})}),Ne=n.discriminatedUnion("outcome",[n.strictObject({...N,outcome:n.literal("none")}),n.strictObject({...N,outcome:n.literal("blocked")}),n.strictObject({...N,outcome:n.literal("found"),target:ee,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:ce})]);var Ge=U.options[0].refine(a=>!a.customer&&!a.customerData),Me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),je=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:$,customerId:n.uuid(),sessionId:n.uuid(),start:Ge,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Pe.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Me).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:Ee.nullable()})});function Te(a){return Oe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Ue(a){let d=new URL(a.baseUrl??Ce).href,p=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){a.assertCurrent();try{let C=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw p();let u=C.entry===null?null:je.parse(C.entry);if(u&&(u.baseUrl!==d||u.customerId!==a.customerId||u.scope.projectId!==a.scope.projectId||u.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(u?.journal.entry&&(u.journal.entry.scope.projectId!==u.scope.projectId||u.journal.entry.scope.environment!==u.scope.environment||u.journal.entry.funnelId!==u.start.funnelId||u.journal.entry.runId!==u.run?.id||u.journal.entry.versionId!==u.run?.versionId)||u?.operationCommand&&!u.purchases.some(E=>E.operationId===u.operationCommand?.operationId))throw p();return{revision:C.revision,entry:u}}catch(C){throw C instanceof l?C:p()}}async function M(C){for(let u=0;u<8;u++){let E=await S(),O=C(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&je.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw p()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw p();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:M,baseUrl:d}}var ze=5*6e4;function Be(a,d){let p=a.purchases.find(S=>S.type==="checkout");if(!a.actions.includes("continue_checkout")||p?.type!=="checkout"||d!==void 0&&p.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return p.checkoutUrl}function Ct(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},p=d.session.snapshot();if(!p)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:M}=p,C=!1,u=null,E,O=null,R=!1,q,z,B,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},y=new Map,j=new Map,le=new AbortController,Q=new Set,D=ve(d),de=Re(D.request);function H(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 w(){if(C||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let f=Ue({...d,customerId:S,assertCurrent:w,storage:d.storage??Te({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),xe=d.session.subscribeIdentity(pe);function pe(){C||(C=!0,clearTimeout(B),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),xe(),u?.reset(),u=null,O=null,D.dispose(),Q.clear(),y.clear(),j.clear())}function P(e){w();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(B),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(B=setTimeout(()=>{T().catch(()=>{})},5e3)),t&&ue(d.onRecovery,structuredClone(e));for(let r of t?Q:[]){if(C)break;ue(r,structuredClone(e))}return structuredClone(e)}function I(e){if(w(),!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(v=>{let se=y.get(v.operationId);return v.terminal&&!se?{type:v.terminal,operationId:v.operationId}:X({quote:se?.quote??null,operation:se??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(v.operationId)===!0})}),c=o.filter(v=>!["complete","native"].includes(v.type)),i=c[0],s=c.length===1&&i?.operationId?y.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{W({allowed:e.allowed.filter(v=>d.executionPolicy.allowed.includes(v))},s.quote)}catch(v){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:H(v)}}let m;if(t==="operation"&&!r&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{W({allowed:e.allowed.filter(v=>d.executionPolicy.allowed.includes(v))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let h=o.length>0&&c.length===0,V=A(e)||t==="operation"&&h&&!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"&&!m?"waiting_result":"ready";return{mode:t,status:V,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...c.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function te(e){let t=X({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ne(e){if(!e.operation)return;let t={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=Z(y.get(t.operationId)??null,t);y.set(t.operationId,r),r===t&&j.set(t.operationId,e.canReselect===!0)}async function De(e){w();for(let r of[e.purchase,e.run.paywall])r&&ne(r);let t=await f.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 c of[e.purchase,e.run.paywall]){let i=c?.operation?.operationId??c?.quote?.operationId;if(!c||!i)continue;let s=o.find(h=>h.operationId===i);if(s&&s.receiptId!==c.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=te(y.get(i));s?s.terminal??=m:o.push({receiptId:c.receiptId,operationId:i,terminal:m})}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 L(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),P(_(t,"run"))}function He(){return{async read(){let{entry:e}=await f.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await f.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 L(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let s=r.has(i.operationId)?y.get(i.operationId):void 0;if(s??=await oe(e,i),w(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&X({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await de.attach({operationId:i.operationId,intent:"cancel"}),w(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");s=await oe(e,i)}y.set(i.operationId,Z(y.get(i.operationId)??null,s))}let c=await f.update(i=>{I(i);let s=i.operationCommand&&y.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:b(i).map(m=>({...m,terminal:m.terminal??te(y.get(m.operationId))}))}});return I(c),c}async function Y(e){w();let t=await D.request("funnels",e);return w(),t}async function Le(){let e=G(Ne,await Y({operation:"find_purchase"}));if(e.customerId!==S||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 f.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:f.baseUrl,scope:d.scope,customerId:S,sessionId:M,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 J;function re(e){let t=J;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<ze))return t.job;let r={at:Date.now(),job:Le().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw J===r&&(J=void 0),o})};return J=r,r.job}async function oe(e,t,r="recover_purchase"){let o=G(Ae,await Y({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ae(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ne(o.purchase),y.get(t.operationId)}async function me(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=G(qe,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ae(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ne(r.purchase);let o=await f.update(c=>{I(c);let i=b(c),{receiptId:s,operationId:m}=r.settlement;if(s&&m){let V=i.find(v=>v.operationId===m);if(V&&V.receiptId!==s)throw new l("INVALID_RESPONSE","Original Receipt changed");V||i.push({receiptId:s,operationId:m,terminal:te(y.get(m))})}let h=r.settlement.state==="settled"?be(c.journal.entry,t.requestId):c.journal.entry;return{...c,purchases:i,journal:h===c.journal.entry?c.journal:{revision:c.journal.revision+1,entry:h}}});I(o),e=o}return e}function ae(e,t){if(t.customerId!==S||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 ie(e,t){if(I(e),e.run&&(e=await me(e)),!b(e).length&&A(e))return P(_(e,"operation"));if(!b(e).length)return P({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:H(t)});R=!0;let r=await L(e);return P(_(r,"operation"))}async function K(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}),!u){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},c;try{c=await Y(o)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return P({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:H(h)});throw h}let i=G(Fe,c);if(i.customerId!==S||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 P({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"}});ae(e,i);let s=await f.update(h=>(I(h),{...h,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??h.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(s),e=s,i.access.type==="operation_only")return ie(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await me(e);let m=i.view;if(m.locale!==e.start.locale||!_e(m.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");u=ke({...d,customerRun:{runId:i.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:He(),onAcceptedResponse:De},{scope:i.scope,run:m})}try{await u.get(),u.view?.pendingRequest?.requestId===e.start.requestId&&!u.pendingCommands?.length&&await u.resume(u.view.pendingRequest.requestId);for(let c of u.pendingCommands??[])c.operation!=="close"&&await u.settle?.(c.requestId);u.pendingCommands?.length&&await u.retry(),w();let o=(await f.read()).entry;return I(o),P(_(o,"run"))}catch(o){if(w(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){u.reset(),u=null;let c=(await f.read()).entry;return I(c),K(c,!1,!1)}throw o}}function F(e,t="read",r){if(w(),q)return t==="read"||t===z?q:q.then(()=>F(e,t,r),()=>F(e,t,r));clearTimeout(B);let o=e().catch(c=>{throw!C&&!r?.(c)&&P({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:H(c)}),c});return q=o,z=t,o.then(()=>{q===o&&(q=void 0,z=void 0)},()=>{q===o&&(q=void 0,z=void 0)}),o}function T(){return F(async()=>{let{entry:e}=await f.read();if(!e||A(e)){if(await re(!1)==="blocked")return fe();({entry:e}=await f.read())}return e?(E&&e.start.requestId!==E&&(u?.reset(),u=null,y.clear(),j.clear(),R=!1),R&&E===e.start.requestId?ie(e,k.error):K(e)):P({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function fe(){return P({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:H(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function he(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:F(async()=>{let t=(await f.read()).entry;if(I(t),!R){if(!u?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let s=u.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return P(_(t,"run"));if(u.pendingCommands?.length)await u.retry();else{let h=u.view;await u.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:h.nodeId,visit:h.visit,revision:h.revision,input:{type:"paywall_confirm",operationId:h.paywall.quote.operationId}})}let m=(await f.read()).entry;return I(m),P(_(m,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&y.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");W({allowed:t.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},o.quote),await f.update(s=>{if(I(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:r,intent:"confirm"}}});let c=await de.attach({operationId:r,intent:"confirm"});if(w(),c.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");y.set(r,Z(o,c.operation));let i=(await f.read()).entry;return I(i),P(_(await L(i,!1,new Set([r])),"operation"))},"confirm")}async function Ie(){w();let{entry:e}=await f.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return u},get recovery(){return structuredClone(k)},get attempt(){return w(),structuredClone(O)},get identitySignal(){return le.signal},retained:Ie,async findPurchase(){let e=await Ie();if(e==="pending")return e;let t=await re(!0);return w(),t==="none"?e:t},async readPaywall(e){w();let t=we(e),[r,{readPaywallContent:o},{validateResourceCheck:c}]=await Promise.all([ge(D.request,"resolvePaywall"),import("./paywall-content-75XEM7K3.js"),import("./check-response-N22NNTIT.js")]);w();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),s=await ye(D.request,r,i);c(i,s.paywall.check,s.scope);let m=await o(d,s.paywall);if(w(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},start(e){let t=U.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 F(async()=>{let r=(await f.read()).entry;if((!r||A(r))&&await re(!0)==="blocked")return fe();let o=await f.update(c=>{if(c&&!A(c)){if(c.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return c}return{schemaVersion:1,baseUrl:f.baseUrl,scope:d.scope,customerId:S,sessionId:M,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&&(u?.reset(),u=null,y.clear(),j.clear(),R=!1),R?ie(o,k.error):K(o,!0)},`start:${t.funnelId}`)},refresh:T,confirm:he,retry:()=>R?he():F(async()=>{let{entry:e}=await f.read();return e?K(e,!0):P({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return u?.view?F(async()=>{if(!u?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(u.pendingCommands?.find(r=>r.operation==="close"))await u.retry();else if(["running","waiting"].includes(u.view.status)){let r=u.view;await u.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await f.read()).entry;return I(t),P(_(t,"run"))},"close"):T()},async continueCheckout(e,t){let r=t?await F(async()=>{let{entry:o}=await f.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 c=await L(o);return P(_(c,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await T();w(),await e(Be(r,t))},async terminateCheckout(e){let t=await T();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 F(async()=>{let{entry:o}=await f.read();I(o);let c=b(o).find(s=>s.operationId===e&&!s.terminal);if(!c||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await oe(o,c,"terminate_checkout");let i=await L(o,!1,new Set([e]));return P(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Q.add(e),()=>{Q.delete(e)}},destroy:pe}}export{Te as a,Be as b,Ct as c};
|
|
1
|
+
import{b as Re}from"./chunk-DK5PHPSO.js";import{a as G}from"./chunk-IV6LKRYM.js";import{A as _e,E as W,G as ke,d as Pe,f as x,k as Se,v as Ee,w as be,y as Oe}from"./chunk-G7Y7LPOB.js";import{a as we,b as ge,c as ye}from"./chunk-IHB275C3.js";import{aa as U}from"./chunk-KQF4BVOL.js";import{a as X}from"./chunk-3NCMYTNG.js";import{g as Z}from"./chunk-SY7AYEDO.js";import{b as ve}from"./chunk-WP3SZU24.js";import{b as $}from"./chunk-K3VQKR4G.js";import{a as l}from"./chunk-O5VA3E5D.js";import{b as Ce}from"./chunk-EEYDOVVS.js";import{b as n}from"./chunk-42UXYMRZ.js";import{a as ue}from"./chunk-DSPLGTQI.js";var g=U.options,Ve=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}),Se.omit({customerToken:!0})]),ce=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),We=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume"]),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:ce}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:ce}),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:Ve})]),ee=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:x.shape.run.shape.status}),N={scope:$,customerId:n.uuid()},Fe=n.discriminatedUnion("outcome",[n.strictObject({...N,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...N,outcome:n.literal("resolved"),target:ee,view:x.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"})}),qe=n.strictObject({...N,target:ee,view:x.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:x.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let p=a.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||a.purchase&&(a.purchase.receiptId!==p.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==p.operationId||a.purchase.quote&&a.purchase.quote.operationId!==p.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"})}),Ae=n.strictObject({...N,target:ee,purchase:x.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"})}),Ne=n.discriminatedUnion("outcome",[n.strictObject({...N,outcome:n.literal("none")}),n.strictObject({...N,outcome:n.literal("blocked")}),n.strictObject({...N,outcome:n.literal("found"),target:ee,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:ce})]);var Ge=U.options[0].refine(a=>!a.customer&&!a.customerData),Me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),je=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:$,customerId:n.uuid(),sessionId:n.uuid(),start:Ge,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Pe.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Me).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:Ee.nullable()})});function Te(a){return Oe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Ue(a){let d=new URL(a.baseUrl??Ce).href,p=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){a.assertCurrent();try{let C=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw p();let u=C.entry===null?null:je.parse(C.entry);if(u&&(u.baseUrl!==d||u.customerId!==a.customerId||u.scope.projectId!==a.scope.projectId||u.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(u?.journal.entry&&(u.journal.entry.scope.projectId!==u.scope.projectId||u.journal.entry.scope.environment!==u.scope.environment||u.journal.entry.funnelId!==u.start.funnelId||u.journal.entry.runId!==u.run?.id||u.journal.entry.versionId!==u.run?.versionId)||u?.operationCommand&&!u.purchases.some(E=>E.operationId===u.operationCommand?.operationId))throw p();return{revision:C.revision,entry:u}}catch(C){throw C instanceof l?C:p()}}async function M(C){for(let u=0;u<8;u++){let E=await S(),O=C(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&je.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw p()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw p();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:M,baseUrl:d}}var ze=5*6e4;function Be(a,d){let p=a.purchases.find(S=>S.type==="checkout");if(!a.actions.includes("continue_checkout")||p?.type!=="checkout"||d!==void 0&&p.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return p.checkoutUrl}function Ct(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},p=d.session.snapshot();if(!p)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:M}=p,C=!1,u=null,E,O=null,R=!1,q,z,B,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},y=new Map,j=new Map,le=new AbortController,Q=new Set,D=ve(d),de=Re(D.request);function H(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 w(){if(C||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let f=Ue({...d,customerId:S,assertCurrent:w,storage:d.storage??Te({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),xe=d.session.subscribeIdentity(pe);function pe(){C||(C=!0,clearTimeout(B),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),xe(),u?.reset(),u=null,O=null,D.dispose(),Q.clear(),y.clear(),j.clear())}function P(e){w();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(B),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(B=setTimeout(()=>{T().catch(()=>{})},5e3)),t&&ue(d.onRecovery,structuredClone(e));for(let r of t?Q:[]){if(C)break;ue(r,structuredClone(e))}return structuredClone(e)}function I(e){if(w(),!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(v=>{let se=y.get(v.operationId);return v.terminal&&!se?{type:v.terminal,operationId:v.operationId}:X({quote:se?.quote??null,operation:se??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(v.operationId)===!0})}),c=o.filter(v=>!["complete","native"].includes(v.type)),i=c[0],s=c.length===1&&i?.operationId?y.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{W({allowed:e.allowed.filter(v=>d.executionPolicy.allowed.includes(v))},s.quote)}catch(v){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:H(v)}}let m;if(t==="operation"&&!r&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{W({allowed:e.allowed.filter(v=>d.executionPolicy.allowed.includes(v))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let h=o.length>0&&c.length===0,V=A(e)||t==="operation"&&h&&!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"&&!m?"waiting_result":"ready";return{mode:t,status:V,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...c.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function te(e){let t=X({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ne(e){if(!e.operation)return;let t={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=Z(y.get(t.operationId)??null,t);y.set(t.operationId,r),r===t&&j.set(t.operationId,e.canReselect===!0)}async function De(e){w();for(let r of[e.purchase,e.run.paywall])r&&ne(r);let t=await f.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 c of[e.purchase,e.run.paywall]){let i=c?.operation?.operationId??c?.quote?.operationId;if(!c||!i)continue;let s=o.find(h=>h.operationId===i);if(s&&s.receiptId!==c.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=te(y.get(i));s?s.terminal??=m:o.push({receiptId:c.receiptId,operationId:i,terminal:m})}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 L(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),P(_(t,"run"))}function He(){return{async read(){let{entry:e}=await f.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await f.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 L(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let s=r.has(i.operationId)?y.get(i.operationId):void 0;if(s??=await oe(e,i),w(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&X({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await de.attach({operationId:i.operationId,intent:"cancel"}),w(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");s=await oe(e,i)}y.set(i.operationId,Z(y.get(i.operationId)??null,s))}let c=await f.update(i=>{I(i);let s=i.operationCommand&&y.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:b(i).map(m=>({...m,terminal:m.terminal??te(y.get(m.operationId))}))}});return I(c),c}async function Y(e){w();let t=await D.request("funnels",e);return w(),t}async function Le(){let e=G(Ne,await Y({operation:"find_purchase"}));if(e.customerId!==S||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 f.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:f.baseUrl,scope:d.scope,customerId:S,sessionId:M,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 J;function re(e){let t=J;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<ze))return t.job;let r={at:Date.now(),job:Le().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw J===r&&(J=void 0),o})};return J=r,r.job}async function oe(e,t,r="recover_purchase"){let o=G(Ae,await Y({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ae(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ne(o.purchase),y.get(t.operationId)}async function me(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=G(qe,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ae(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ne(r.purchase);let o=await f.update(c=>{I(c);let i=b(c),{receiptId:s,operationId:m}=r.settlement;if(s&&m){let V=i.find(v=>v.operationId===m);if(V&&V.receiptId!==s)throw new l("INVALID_RESPONSE","Original Receipt changed");V||i.push({receiptId:s,operationId:m,terminal:te(y.get(m))})}let h=r.settlement.state==="settled"?be(c.journal.entry,t.requestId):c.journal.entry;return{...c,purchases:i,journal:h===c.journal.entry?c.journal:{revision:c.journal.revision+1,entry:h}}});I(o),e=o}return e}function ae(e,t){if(t.customerId!==S||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 ie(e,t){if(I(e),e.run&&(e=await me(e)),!b(e).length&&A(e))return P(_(e,"operation"));if(!b(e).length)return P({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:H(t)});R=!0;let r=await L(e);return P(_(r,"operation"))}async function K(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}),!u){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},c;try{c=await Y(o)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return P({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:H(h)});throw h}let i=G(Fe,c);if(i.customerId!==S||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 P({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"}});ae(e,i);let s=await f.update(h=>(I(h),{...h,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??h.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(s),e=s,i.access.type==="operation_only")return ie(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await me(e);let m=i.view;if(m.locale!==e.start.locale||!_e(m.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");u=ke({...d,customerRun:{runId:i.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:He(),onAcceptedResponse:De},{scope:i.scope,run:m})}try{await u.get(),u.view?.pendingRequest?.requestId===e.start.requestId&&!u.pendingCommands?.length&&await u.resume(u.view.pendingRequest.requestId);for(let c of u.pendingCommands??[])c.operation!=="close"&&await u.settle?.(c.requestId);u.pendingCommands?.length&&await u.retry(),w();let o=(await f.read()).entry;return I(o),P(_(o,"run"))}catch(o){if(w(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){u.reset(),u=null;let c=(await f.read()).entry;return I(c),K(c,!1,!1)}throw o}}function F(e,t="read",r){if(w(),q)return t==="read"||t===z?q:q.then(()=>F(e,t,r),()=>F(e,t,r));clearTimeout(B);let o=e().catch(c=>{throw!C&&!r?.(c)&&P({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:H(c)}),c});return q=o,z=t,o.then(()=>{q===o&&(q=void 0,z=void 0)},()=>{q===o&&(q=void 0,z=void 0)}),o}function T(){return F(async()=>{let{entry:e}=await f.read();if(!e||A(e)){if(await re(!1)==="blocked")return fe();({entry:e}=await f.read())}return e?(E&&e.start.requestId!==E&&(u?.reset(),u=null,y.clear(),j.clear(),R=!1),R&&E===e.start.requestId?ie(e,k.error):K(e)):P({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function fe(){return P({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:H(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function he(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:F(async()=>{let t=(await f.read()).entry;if(I(t),!R){if(!u?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let s=u.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return P(_(t,"run"));if(u.pendingCommands?.length)await u.retry();else{let h=u.view;await u.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:h.nodeId,visit:h.visit,revision:h.revision,input:{type:"paywall_confirm",operationId:h.paywall.quote.operationId}})}let m=(await f.read()).entry;return I(m),P(_(m,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&y.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");W({allowed:t.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},o.quote),await f.update(s=>{if(I(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:r,intent:"confirm"}}});let c=await de.attach({operationId:r,intent:"confirm"});if(w(),c.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");y.set(r,Z(o,c.operation));let i=(await f.read()).entry;return I(i),P(_(await L(i,!1,new Set([r])),"operation"))},"confirm")}async function Ie(){w();let{entry:e}=await f.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return u},get recovery(){return structuredClone(k)},get attempt(){return w(),structuredClone(O)},get identitySignal(){return le.signal},retained:Ie,async findPurchase(){let e=await Ie();if(e==="pending")return e;let t=await re(!0);return w(),t==="none"?e:t},async readPaywall(e){w();let t=we(e),[r,{readPaywallContent:o},{validateResourceCheck:c}]=await Promise.all([ge(D.request,"resolvePaywall"),import("./paywall-content-QSTCRYU5.js"),import("./check-response-Q7GOBUGJ.js")]);w();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),s=await ye(D.request,r,i);c(i,s.paywall.check,s.scope);let m=await o(d,s.paywall);if(w(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},start(e){let t=U.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 F(async()=>{let r=(await f.read()).entry;if((!r||A(r))&&await re(!0)==="blocked")return fe();let o=await f.update(c=>{if(c&&!A(c)){if(c.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return c}return{schemaVersion:1,baseUrl:f.baseUrl,scope:d.scope,customerId:S,sessionId:M,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&&(u?.reset(),u=null,y.clear(),j.clear(),R=!1),R?ie(o,k.error):K(o,!0)},`start:${t.funnelId}`)},refresh:T,confirm:he,retry:()=>R?he():F(async()=>{let{entry:e}=await f.read();return e?K(e,!0):P({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return u?.view?F(async()=>{if(!u?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(u.pendingCommands?.find(r=>r.operation==="close"))await u.retry();else if(["running","waiting"].includes(u.view.status)){let r=u.view;await u.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await f.read()).entry;return I(t),P(_(t,"run"))},"close"):T()},async continueCheckout(e,t){let r=t?await F(async()=>{let{entry:o}=await f.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 c=await L(o);return P(_(c,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await T();w(),await e(Be(r,t))},async terminateCheckout(e){let t=await T();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 F(async()=>{let{entry:o}=await f.read();I(o);let c=b(o).find(s=>s.operationId===e&&!s.terminal);if(!c||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await oe(o,c,"terminate_checkout");let i=await L(o,!1,new Set([e]));return P(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Q.add(e),()=>{Q.delete(e)}},destroy:pe}}export{Te as a,Be as b,Ct as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as k}from"./chunk-
|
|
1
|
+
import{r as k}from"./chunk-HJVEVJXS.js";import{a as M}from"./chunk-DSPLGTQI.js";var z={sm:420,md:640,lg:900},A=767;function le(e,r,o=()=>!0,c="Close"){let n=e.ownerDocument.defaultView,i=e.ownerDocument.createElement("button");i.type="button",i.setAttribute("aria-label",c),i.style.cssText="position:absolute;inset:0 48px auto;z-index:2;height:24px;border:0;padding:0;background:transparent;touch-action:none;cursor:grab";let d=e.ownerDocument.createElement("span");d.style.cssText="display:block;width:36px;height:4px;border-radius:4px;margin:8px auto 12px;background:currentColor;opacity:.22;pointer-events:none",i.append(d),e.prepend(i);let p,s=0,a=!1,f=()=>{i.hidden=e.dataset.presentation!=="sheet",i.setAttribute("aria-disabled",String(!o()))},v=t=>{f(),!(i.hidden||!o()||t.button!==0)&&(p={y:t.clientY,time:Date.now(),id:t.pointerId},s=0,a=!1,i.setPointerCapture?.(t.pointerId))},y=t=>{!p||t.pointerId!==p.id||(s=Math.max(0,t.clientY-p.y),e.style.transform=`translateY(${s}px)`)},g=t=>{if(!p||t.pointerId!==p.id)return;let u=Math.max(1,Date.now()-p.time),x=t.type!=="pointercancel"&&o()&&(s>120||s>40&&s/u>.5);a=s>6,p=void 0,i.releasePointerCapture?.(t.pointerId),e.style.transform="",x?r():s&&typeof e.animate=="function"&&!n?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&e.animate([{transform:`translateY(${s}px)`},{transform:"none"}],{duration:200,easing:"cubic-bezier(.2,.8,.2,1)"}),s=0},m=()=>{if(a){a=!1;return}!p&&s===0&&o()&&r()};i.addEventListener("pointerdown",v),i.addEventListener("pointermove",y),i.addEventListener("pointerup",g),i.addEventListener("pointercancel",g),i.addEventListener("click",m);let l=typeof MutationObserver=="function"?new MutationObserver(f):void 0;return l?.observe(e,{attributes:!0,attributeFilter:["data-presentation"]}),n?.addEventListener("resize",f),f(),()=>{l?.disconnect(),n?.removeEventListener("resize",f),i.remove(),e.style.transform=""}}function O(e,r,o=!1){return(e.type==="modal"||e.type==="sheet")&&e.mobile&&o&&r<=A?e.mobile:e.type}function W(e,r,o){let c=e.ownerDocument.defaultView,n=r.presentation,i;if((n.type==="modal"||n.type==="sheet")&&n.backdrop){let t=`lp-backdrop-${crypto.randomUUID()}`,u={none:"transparent",scrim:"#f2f2f2cc",dim:"#0006","strong-dim":"#000000bf",blur:"#0006"};e.dataset.indianaBackdrop=t,i=e.ownerDocument.createElement("style"),i.textContent=`dialog[data-indiana-backdrop="${t}"]::backdrop{background:${u[n.backdrop]};backdrop-filter:${n.backdrop==="blur"?"blur(16px)":"none"}}`,e.append(i)}let d=r.pages?.[0]?.root.style?.shape,p=d?.type==="pill"?"9999px":d?.type==="rect"?typeof d.radius=="number"?`${d.radius}px`:[d.radius.topLeft,d.radius.topRight,d.radius.bottomRight,d.radius.bottomLeft].map(t=>`${t}px`).join(" "):void 0,s=(n.type==="modal"||n.type==="sheet")&&(n.desktopWidth!==void 0||n.mobile!==void 0||n.type==="modal"&&n.position!==void 0),a=n.type,f,v,y=!1,g=t=>{y||!Number.isFinite(t)||t<0||(v=t,a!=="fullscreen"&&a!=="inline"&&(e.style.height=`min(${Math.max(t,40)}px, calc(100dvh - ${a==="sheet"?0:32}px))`))},m=()=>{if(!y&&(a=f??O(n,c?.innerWidth??1024,c?.matchMedia?.("(pointer: coarse)").matches===!0),e.dataset.presentation=a,!(!s||n.type!=="modal"&&n.type!=="sheet"))){if(e.style.boxSizing="border-box",e.style.padding="0",e.style.border="0",e.style.overflow="hidden",e.style.outline="none",e.tabIndex=-1,e.style.background=r.theme.background,e.style.color=r.theme.text,a==="fullscreen")e.style.width="100vw",e.style.height="100dvh",e.style.maxWidth="100vw",e.style.maxHeight="100dvh",e.style.margin="0",e.style.borderRadius="0";else{let t=n.mobile==="sheet"&&a==="sheet",u=n.desktopWidth,x=c?.innerWidth??1024;e.style.width=t?`${x}px`:u?`${Math.min(u.max,Math.max(x*u.viewport/100,u.min))}px`:`${k[n.size]}px`,e.style.maxWidth=`${Math.max(0,x-(a==="sheet"?0:32))}px`,e.style.maxHeight=a==="sheet"?"100dvh":"calc(100dvh - 32px)",e.style.margin=a==="sheet"?"auto auto 0":n.type==="modal"&&n.position==="top"?"16px auto auto":n.type==="modal"&&n.position==="bottom"?"auto auto 16px":"auto",e.style.borderRadius=p??(a==="sheet"?"16px 16px 0 0":"24px"),e.style.height="",v!==void 0&&g(v)}o?.(a)}},l=s?[c?.matchMedia?.(`(max-width: ${A}px)`),c?.matchMedia?.("(pointer: coarse)")].filter(t=>t!==void 0):[];if(s){c?.addEventListener("resize",m);for(let t of l)t.addEventListener?t.addEventListener("change",m):t.addListener?.(m)}return m(),{responsive:s,get type(){return a},latch(){y||f!==void 0||(m(),f=a)},setContentHeight:g,destroy(){if(!y){y=!0,i?.remove(),delete e.dataset.indianaBackdrop,c?.removeEventListener("resize",m);for(let t of l)t.removeEventListener?t.removeEventListener("change",m):t.removeListener?.(m)}}}}function ue(e,r,o){let{presentation:c}=r,n="size"in c?`${z[c.size]}px`:"100vw";return e.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${n}`,W(e,r,o)}function me(e,r,o=!1){let c=e.ownerDocument.defaultView;if(typeof e.animate!="function"||c?.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let n=o?{duration:300,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}:{duration:240,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)"};e.animate(r==="sheet"?[{transform:"translateY(100%)"},{transform:"none"}]:r==="modal"?[{opacity:0,transform:o?"translateY(12px) scale(0.96)":"translateY(8px) scale(0.98)"},{opacity:1,transform:"none"}]:[{opacity:0},{opacity:1}],n);try{e.animate([{opacity:0},{opacity:1}],{...n,pseudoElement:"::backdrop"})}catch{}}function $(e,r){e.style.cssText=["position:absolute","z-index:1","top:calc(4px + env(safe-area-inset-top, 0px))","inset-inline-end:calc(4px + env(safe-area-inset-right, 0px))","width:44px","height:44px","padding:0","border:0","border-radius:50%","font:400 20px/1 system-ui,sans-serif","cursor:pointer","touch-action:manipulation"].join(";"),e.style.background=`radial-gradient(circle, ${r.background} 0 15px, color-mix(in srgb, ${r.text} 22%, ${r.background}) 15px 16px, transparent 16.5px)`,e.style.color=r.text}var C=new WeakMap;function he(e,r){return C.set(e,r),()=>C.delete(e)}function xe(e){let r=e.defaultView?.HTMLElement,o=e.activeElement;for(let n=0;n<16&&o?.shadowRoot?.activeElement;n++)o=o.shadowRoot.activeElement;let c=o?C.get(o)?.():void 0;return()=>{!o?.isConnected||!r||!(o instanceof r)||(o.focus({preventScroll:!0}),c?.())}}var ge=15e3;function we(e,r,o,c,n){let i=e.ownerDocument,d=new AbortController,p=!1,s=!1,a,f;function v(){f?.(),f=void 0,a?.tagName==="DIALOG"&&a.close?.(),a?.remove(),a=void 0}function y(l,t){s||(s=!0,v(),(l==="dismissed"||l==="error")&&d.abort(t??new DOMException("Presentation cancelled","AbortError")),!(!p&&l!=="ready")&&M(r.onPresentationState,l==="error"?{surface:o,state:l,error:t}:{surface:o,state:l}))}let g=c,m=()=>{s||g()};return{setDismissHandler(l){g=l},get active(){return p&&!s},get cancelled(){return d.signal.aborted},start(l,t,u){if(!(p||s)){if(p=!0,r.loading!=="host"){let x=(t??i.documentElement.lang)||"en",b=l&&u?.presentation?.type!=="inline",E=u!==void 0,h=i.createElement(b?"dialog":"div");a=h,h.dataset.longplayLoading=o;let S=x.startsWith("zh"),I=E?S?"\u6B63\u5728\u52A0\u8F7D\u5957\u9910":"Loading plans":S?"\u6B63\u5728\u52A0\u8F7D":"Loading",R=u?.screen.theme??{background:"Canvas",text:"CanvasText"};h.setAttribute("aria-label",I);let P=i.createElement("div");P.setAttribute("role","status");let L=i.createElement("div");L.setAttribute("aria-hidden","true");let H=()=>{P.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)"};E?P.style.cssText="padding:24px 60px 24px 24px;font:500 16px/1.5 system-ui,sans-serif":H(),P.textContent=I;let w=i.createElement("button");w.type="button",w.textContent="\xD7",w.setAttribute("aria-label",S?"\u53D6\u6D88\u52A0\u8F7D":"Cancel loading"),$(w,R),w.addEventListener("click",m),h.addEventListener("cancel",D=>{D.preventDefault(),m()}),h.append(P,L,w),e.append(h);let T=()=>{if(!s&&b){let D=h;D.showModal?D.showModal():D.open=!0,w.focus({preventScroll:!0})}};u&&n?(f=n(h,L,u,x,()=>{s||(L.style.visibility="",H())}),T()):E?(h.style.cssText=b?"padding:0;border:0;border-radius:24px;background:Canvas;color:CanvasText;width:min(420px,calc(100vw - 32px))":"position:relative;background:Canvas;color:CanvasText;width:100%",T()):(_(h,L,b,o),T())}M(r.onPresentationState,{surface:o,state:"loading",dismiss:m})}},present(l){if(s)return;let t=!!a;v(),l(t),y("ready")},dismiss:m,finish:y,async wait(l,t){let u=d.signal,x,b,E=new Promise((h,S)=>{b=()=>S(u.reason),u.aborted?b():u.addEventListener("abort",b,{once:!0}),t!==void 0&&(x=setTimeout(()=>S(new Error("Presentation data timed out")),t))});try{let h=await Promise.race([E,l]);return u.throwIfAborted(),h}finally{u.removeEventListener("abort",b),clearTimeout(x)}}}}function _(e,r,o,c){e.style.cssText="position:relative;box-sizing:border-box;background:Canvas;color:CanvasText;padding:24px 48px 24px 24px;"+(o?"position:fixed;width:min(480px,calc(100% - 32px));border:0;border-radius:16px;max-height:calc(100dvh - 32px)":"width:100%"),r.style.cssText="display:grid;gap:12px";let n=c==="banner"?[["72%",12],["44%",10]]:[["46%",20],["84%",12],["65%",12],["100%",64]];for(let[i,d]of n){let p=e.ownerDocument.createElement("div");p.style.cssText=`width:${i};height:${d}px;background:currentColor;opacity:.11;border-radius:6px`,r.append(p)}}function F(e){let r={display:"block",position:"fixed",top:"0",left:"0",opacity:"0",pointerEvents:"none",zIndex:"-1"},o=Object.keys(r).map(i=>{let d=i,p=e.style[d];return e.style[d]=r[d],[d,p]}),c=e.inert??!1,n=e.getAttribute("aria-hidden");return e.inert=!0,e.setAttribute("aria-hidden","true"),()=>{for(let[i,d]of o)e.style[i]=d;e.inert=c,n===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",n)}}function Ee(e,r){let o=e.style.width;e.style.width=`${r.getBoundingClientRect().width||r.ownerDocument.defaultView?.innerWidth||800}px`;let c=F(e);return()=>{c(),e.style.width=o}}export{le as a,O as b,W as c,ue as d,me as e,$ as f,he as g,xe as h,ge as i,we as j,F as k,Ee as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var t="https://api.longplayai.com";var p={name:"@tinkerlandai/longplay-sdk",version:"0.10.
|
|
1
|
+
var t="https://api.longplayai.com";var p={name:"@tinkerlandai/longplay-sdk",version:"0.10.38",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};export{p as a,t as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as ue,g as se}from"./chunk-4KLXQKNO.js";import{b as on}from"./chunk-W74JLL2O.js";import{d as tn,e as pe}from"./chunk-ECKVJGXQ.js";import{c as Be,d as Ke,e as J,l as nn}from"./chunk-GH6FM44P.js";import{$ as de,A as $e,E as Ye,S as Ze,X as We,Y as Xe,Z as $,_ as en,a as j,aa as U,b as qe,c as Me,d as je,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,y as Je}from"./chunk-YV6UFESO.js";import{b as an}from"./chunk-3NCMYTNG.js";import{b as ne}from"./chunk-7XDQKZYA.js";import{a as W}from"./chunk-XJRDO3NI.js";import{$ as Qe,I as L,J as De,K as Le,Z as He,_ as le,aa as ce,g as Oe,m as Ae,q as Te,z as ae}from"./chunk-WZMZMJCK.js";import{b as D}from"./chunk-HEHLFHW7.js";import{a as f}from"./chunk-U7NX5ET2.js";import{b as rn}from"./chunk-AHUYZ6IW.js";import{b as n}from"./chunk-CR2XJ2CX.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-O4KXODTJ.js";import{a as Pe,b as Ne}from"./chunk-CILM5XMH.js";function un(e){return Cn({...e,namespace:"commands",identity:[e.runToken]})}function Cn(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??rn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var sn=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Pn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Nn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:q.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:We,openIn:Xe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),On={id:q,presentation:Te,outputs:n.array(q).max(250),inputs:ce,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(q,He.nullable())},An=n.strictObject({...On,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:sn,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Pn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:Qe,variables:n.record(n.string(),L),output:L.nullable(),screen:An.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([tn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Nn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),Tn=n.strictObject({scope:D,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),ln=Tn.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var cn="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function dn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var _n=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),kn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(_n).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=kn.omit({variation:!0,description:!0,iam:!0}),Vn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),pn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(Vn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Q,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Dn=n.strictObject({release:Q,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Gt=n.strictObject({scope:D.extend({environmentId:n.uuid()}),release:Q,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Je.optional(),target:Dn})).max(4e3)}),Ut=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Q,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Bt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Kt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Ln=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),mn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Ln.extend({receiptId:n.uuid()})).max(100),payload:pn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(j,j),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),fn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:gn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...fn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...fn,evaluationMode:n.literal("remote")})]),qn=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ze.nullable()}))})});function Mn(e){return gn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Mn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:nn(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function er(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return qn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,jn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var Gn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),L),Un=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:en,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),ar=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:Gn,context:Ie,steps:n.array(Un).min(1).max(he)}).refine(e=>X(e)<=jn,"Segment exceeds its byte budget");var Bn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Y(e){return Array.isArray(e)?e.some(Y):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Y(u):!Bn.test(t))}function yn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Y(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Y(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Y(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Kn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Kn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let I=e.conditions[a.id];if(!I)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:I.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=h.value,o=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function hr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),zn(p,c,d))}function zn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function wr(e,t,u,r=re){return vn(Re(e,r),t,u)}function vn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(L.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(L.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function In(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>yn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),vn(I,O,{attributes:$e({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let R=s.type==="end"?s.output:s.value;if(m=R?.type==="feature"?b(s.id):{...m,port:"value",value:R?.type==="literal"?R.value:R?.type==="variable"?Ue({source:"variable",key:R.key,...R.path?{path:R.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},R&&(m.value===void 0||!je(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:o,result:m}];if(X({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let R=s.type==="coupons"?s.couponIds.map(V=>({type:"reward",id:V})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(R===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=G(s,{value:R});Ge(t.variables,s,_),Object.assign(c,_)}for(let R of m.sticky)d[`${R.next.attributeName}||${R.next.attributeValue}`]=structuredClone(R.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let T=p.get(o);return{steps:a,...!y&&T&&(!we(T)||h(T))?{boundary:{nodeId:o,visit:g}}:{}}}function hn(e,t){let u=ln.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Cr(e){return xe(e,Se)}var Jn=3,$n=2e3;function Hn(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Qn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Jn||!Hn(u))throw u;await new Promise(r=>setTimeout(r,t*$n))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Qn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Zn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Zn(e,t,u){return In(e,t,u,Se)}var wn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),bn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function xn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:bn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let I=await e.write(g.revision,y);if(I!==null){if(!Number.isSafeInteger(I)||I<=g.revision)throw A();t=I;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=bn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,I)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[h,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(I!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((I,h)=>{if(!I&&h!==t||I&&r(I)!==r({...a,schemaVersion:1}))throw A();if(I?.purchase&&I.purchase.generation>o.generation)return Z(I,y);if(I?.purchase&&I.purchase.generation===o.generation&&I.purchase.operationId!==o.operationId)throw A();return g?!I?.purchase||I.purchase.operationId!==o.operationId?Z(I,y):Z(I.command?{...I,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...I,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function Rn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,I=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!ie(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of I)try{m(structuredClone(r))}catch{}}},identify(h){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return I.add(h),()=>I.delete(h)},reset(){o||(o=!0,a(),g=void 0,r=null,I.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function $r(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Hr(e){let t=ne(e);return t.identify(e.apiKey),t}function Sn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Wn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Fn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function I(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:M(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let R=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Wn(C),V=!1;if(R&&_&&m===t.generation&&i===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});V=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw m===t.generation&&(i===s||p===s)&&_&&(!R||!(C instanceof f)||C.status===void 0||V)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),C}}function h(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return T(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(M(p))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(M(i))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=I(s);d[m]=x;let C=()=>{d[m]===x&&(d[m]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,C){let R=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=R&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==R&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?R:void 0,V=i?.requestId===_?i:p?.requestId===_?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,v=l??m.purchase,P=v?.operation,E=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,S=P?.operationId??v?.quote?.operationId??E?.operationId,F=v?.receiptId??E?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!o||w>=o.generation)){let N={receiptId:F,operationId:S,generation:w},k=an(P,v?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},N,k,_),t.assertCurrent(x),(!o||N.generation>=o.generation)&&(C===void 0||C>=t.readSequence)&&(k?o?.operationId===N.operationId&&(o=void 0):o=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(V):!1},stop(){c=!0},submit:h,settle:T,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Xn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=Rn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?un(e):void 0),a=d&&xn(d),o=Fn({journal:a,state:i,call:T,processIdentity:e.process}),g=0,y=new Map;function I(){g++,y.clear(),t=void 0}async function h(l){let v=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!v&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(v?.operation==="submit"&&v.input.type==="paywall_confirm"){let N=i.view?.paywall;Sn(u,N?.quote?.operationId===v.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=i.generation;i.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),S=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=i.signal,k,K=()=>{},En=new Promise((et,Ce)=>{K=()=>Ce(N.reason),N.addEventListener("abort",K,{once:!0}),k=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(P),e.session.access())),En])}finally{clearTimeout(k),N.removeEventListener("abort",K)}}i.assertCurrent(P);let F={...l,...S?{customerToken:S}:{}},w=l.operation==="page_experiments"?ye.parse(F):U.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!S?{[cn]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){I(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function T(l,v){let P=t;t=void 0;let E=i.generation,S=()=>i.assertCurrent(E);a&&await o.ready,S();let F=i.view,w=hn(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(S(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let k=await o.observe(l,w,E,v);return(!i.view||w.run.revision>=i.view.revision)&&(v===void 0||v>=i.readSequence)&&(await e.onAcceptedResponse?.(w),S()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,F,v,k)),w}function O(l){let v=i.generation;I();let P=l(),E=()=>{i.generation===v&&I()};return P.then(E,E),P}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function C(l){let v=x.get(l);if(v)return v;let P=_(l);return x.set(l,P),P}let R=!1;async function _(l){let v=await l;if(v.run.instruction?.type!=="evaluate_segment")return v;if(m)return m;R=!0;let P=i.generation,E=(async()=>{for(let S=0;S<32&&v.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return v;let F=v.run;if(v.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Fe(e.configuration,F,{predict:!1});if(P!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return v;if(i.view&&(i.view.revision!==F.revision||i.view.visit!==F.visit||i.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Fe(e.configuration,F).then(({prediction:K})=>{k&&P===i.generation&&!o.closeRequested&&i.view?.id===F.id&&!i.view.stopped&&i.view.nodeId===F.nodeId&&i.view.visit===F.visit&&i.view.revision===F.revision&&(c=K)}).catch(()=>{});try{v=await s({operation:"commit_segment",requestId:dn(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,c=null}}}return v})();m=E;try{return await E}finally{m===E&&(m=null)}}let V={get configuration(){return R?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(M(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(M(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return on(e,l)},async pageExperiments(l,v=[]){let P=i.generation;i.assertCurrent(P);let E=i.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let S=mn.parse(await h(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:v})));if(i.assertCurrent(P),S.runId!==E||S.scope.projectId!==i.scope?.projectId||S.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,v){let P=i.generation;l=l&&structuredClone(l),v=v&&{...v},a&&await o.ready,i.assertCurrent(P),v??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let E=JSON.stringify([i.generation,g,l??null,v??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=i.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...v?{purchase:v}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?V.settle(l):o.pending?.requestId===l?C(s(o.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(o.closeFlight)return o.closeFlight;if(o.closing)return s(o.closing);if(o.closeRequested&&o.pending)return V.settle(o.pending.requestId);if(o.inFlight)return C(o.inFlight);if(!o.pending)throw new f("INVALID_REQUEST","No command is pending");let l=o.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let v=i.generation;if(await V.settle(l.requestId),i.assertCurrent(v),!o.pending)return V.get();if(o.pending!==l||o.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let v=i.customerToken?void 0:t;I(),i.identify(l),t=v,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return V}function vo(e,t){return Xn({...e,runToken:"",initialResponse:t})}export{dn as a,sn as b,Nn as c,me as d,Tn as e,ln as f,Dn as g,Gt as h,Ut as i,Bt as j,ye as k,mn as l,te as m,qn as n,er as o,hr as p,wr as q,hn as r,Se as s,Cr as t,Zn as u,bn as v,Z as w,un as x,Cn as y,jr as z,ie as A,Ee as B,$r as C,Hr as D,Sn as E,Xn as F,vo as G};
|
|
1
|
+
import{f as ue,g as se}from"./chunk-KTBXAATX.js";import{b as on}from"./chunk-GEPX4AUR.js";import{d as tn,e as pe}from"./chunk-TLV3NVUU.js";import{c as Be,d as Ke,e as J,l as nn}from"./chunk-Y5RT7PAD.js";import{$ as de,A as $e,E as Ye,S as Ze,X as We,Y as Xe,Z as $,_ as en,a as j,aa as U,b as qe,c as Me,d as je,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,y as Je}from"./chunk-KQF4BVOL.js";import{b as an}from"./chunk-3NCMYTNG.js";import{b as ne}from"./chunk-WP3SZU24.js";import{a as W}from"./chunk-4E326NPY.js";import{$ as Qe,I as L,J as De,K as Le,Z as He,_ as le,aa as ce,g as Oe,m as Ae,q as Te,z as ae}from"./chunk-HJVEVJXS.js";import{b as D}from"./chunk-K3VQKR4G.js";import{a as f}from"./chunk-O5VA3E5D.js";import{b as rn}from"./chunk-EEYDOVVS.js";import{b as n}from"./chunk-42UXYMRZ.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-O4KXODTJ.js";import{a as Pe,b as Ne}from"./chunk-CILM5XMH.js";function un(e){return Cn({...e,namespace:"commands",identity:[e.runToken]})}function Cn(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??rn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var sn=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Pn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Nn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:q.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:We,openIn:Xe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),On={id:q,presentation:Te,outputs:n.array(q).max(250),inputs:ce,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(q,He.nullable())},An=n.strictObject({...On,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:sn,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Pn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:Qe,variables:n.record(n.string(),L),output:L.nullable(),screen:An.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([tn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Nn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),Tn=n.strictObject({scope:D,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),ln=Tn.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var cn="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function dn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var _n=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),kn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(_n).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=kn.omit({variation:!0,description:!0,iam:!0}),Vn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),pn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(Vn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Q,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Dn=n.strictObject({release:Q,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Gt=n.strictObject({scope:D.extend({environmentId:n.uuid()}),release:Q,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Je.optional(),target:Dn})).max(4e3)}),Ut=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Q,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Bt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Kt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Ln=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),mn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Ln.extend({receiptId:n.uuid()})).max(100),payload:pn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(j,j),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),fn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:gn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...fn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...fn,evaluationMode:n.literal("remote")})]),qn=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ze.nullable()}))})});function Mn(e){return gn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Mn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:nn(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function er(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return qn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,jn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var Gn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),L),Un=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:en,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),ar=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:Gn,context:Ie,steps:n.array(Un).min(1).max(he)}).refine(e=>X(e)<=jn,"Segment exceeds its byte budget");var Bn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Y(e){return Array.isArray(e)?e.some(Y):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Y(u):!Bn.test(t))}function yn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Y(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Y(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Y(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Kn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Kn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let I=e.conditions[a.id];if(!I)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:I.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=h.value,o=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function hr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),zn(p,c,d))}function zn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function wr(e,t,u,r=re){return vn(Re(e,r),t,u)}function vn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(L.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(L.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function In(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>yn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),vn(I,O,{attributes:$e({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let R=s.type==="end"?s.output:s.value;if(m=R?.type==="feature"?b(s.id):{...m,port:"value",value:R?.type==="literal"?R.value:R?.type==="variable"?Ue({source:"variable",key:R.key,...R.path?{path:R.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},R&&(m.value===void 0||!je(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:o,result:m}];if(X({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let R=s.type==="coupons"?s.couponIds.map(V=>({type:"reward",id:V})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(R===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=G(s,{value:R});Ge(t.variables,s,_),Object.assign(c,_)}for(let R of m.sticky)d[`${R.next.attributeName}||${R.next.attributeValue}`]=structuredClone(R.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let T=p.get(o);return{steps:a,...!y&&T&&(!we(T)||h(T))?{boundary:{nodeId:o,visit:g}}:{}}}function hn(e,t){let u=ln.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Cr(e){return xe(e,Se)}var Jn=3,$n=2e3;function Hn(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Qn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Jn||!Hn(u))throw u;await new Promise(r=>setTimeout(r,t*$n))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Qn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Zn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Zn(e,t,u){return In(e,t,u,Se)}var wn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),bn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function xn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:bn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let I=await e.write(g.revision,y);if(I!==null){if(!Number.isSafeInteger(I)||I<=g.revision)throw A();t=I;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=bn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,I)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[h,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(I!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((I,h)=>{if(!I&&h!==t||I&&r(I)!==r({...a,schemaVersion:1}))throw A();if(I?.purchase&&I.purchase.generation>o.generation)return Z(I,y);if(I?.purchase&&I.purchase.generation===o.generation&&I.purchase.operationId!==o.operationId)throw A();return g?!I?.purchase||I.purchase.operationId!==o.operationId?Z(I,y):Z(I.command?{...I,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...I,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function Rn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,I=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!ie(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of I)try{m(structuredClone(r))}catch{}}},identify(h){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return I.add(h),()=>I.delete(h)},reset(){o||(o=!0,a(),g=void 0,r=null,I.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function $r(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Hr(e){let t=ne(e);return t.identify(e.apiKey),t}function Sn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Wn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Fn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function I(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:M(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let R=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Wn(C),V=!1;if(R&&_&&m===t.generation&&i===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});V=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw m===t.generation&&(i===s||p===s)&&_&&(!R||!(C instanceof f)||C.status===void 0||V)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),C}}function h(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return T(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(M(p))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(M(i))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=I(s);d[m]=x;let C=()=>{d[m]===x&&(d[m]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,C){let R=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=R&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==R&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?R:void 0,V=i?.requestId===_?i:p?.requestId===_?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,v=l??m.purchase,P=v?.operation,E=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,S=P?.operationId??v?.quote?.operationId??E?.operationId,F=v?.receiptId??E?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!o||w>=o.generation)){let N={receiptId:F,operationId:S,generation:w},k=an(P,v?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},N,k,_),t.assertCurrent(x),(!o||N.generation>=o.generation)&&(C===void 0||C>=t.readSequence)&&(k?o?.operationId===N.operationId&&(o=void 0):o=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(V):!1},stop(){c=!0},submit:h,settle:T,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Xn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=Rn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?un(e):void 0),a=d&&xn(d),o=Fn({journal:a,state:i,call:T,processIdentity:e.process}),g=0,y=new Map;function I(){g++,y.clear(),t=void 0}async function h(l){let v=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!v&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(v?.operation==="submit"&&v.input.type==="paywall_confirm"){let N=i.view?.paywall;Sn(u,N?.quote?.operationId===v.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=i.generation;i.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),S=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=i.signal,k,K=()=>{},En=new Promise((et,Ce)=>{K=()=>Ce(N.reason),N.addEventListener("abort",K,{once:!0}),k=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(P),e.session.access())),En])}finally{clearTimeout(k),N.removeEventListener("abort",K)}}i.assertCurrent(P);let F={...l,...S?{customerToken:S}:{}},w=l.operation==="page_experiments"?ye.parse(F):U.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!S?{[cn]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){I(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function T(l,v){let P=t;t=void 0;let E=i.generation,S=()=>i.assertCurrent(E);a&&await o.ready,S();let F=i.view,w=hn(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(S(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let k=await o.observe(l,w,E,v);return(!i.view||w.run.revision>=i.view.revision)&&(v===void 0||v>=i.readSequence)&&(await e.onAcceptedResponse?.(w),S()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,F,v,k)),w}function O(l){let v=i.generation;I();let P=l(),E=()=>{i.generation===v&&I()};return P.then(E,E),P}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function C(l){let v=x.get(l);if(v)return v;let P=_(l);return x.set(l,P),P}let R=!1;async function _(l){let v=await l;if(v.run.instruction?.type!=="evaluate_segment")return v;if(m)return m;R=!0;let P=i.generation,E=(async()=>{for(let S=0;S<32&&v.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return v;let F=v.run;if(v.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Fe(e.configuration,F,{predict:!1});if(P!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return v;if(i.view&&(i.view.revision!==F.revision||i.view.visit!==F.visit||i.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Fe(e.configuration,F).then(({prediction:K})=>{k&&P===i.generation&&!o.closeRequested&&i.view?.id===F.id&&!i.view.stopped&&i.view.nodeId===F.nodeId&&i.view.visit===F.visit&&i.view.revision===F.revision&&(c=K)}).catch(()=>{});try{v=await s({operation:"commit_segment",requestId:dn(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,c=null}}}return v})();m=E;try{return await E}finally{m===E&&(m=null)}}let V={get configuration(){return R?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(M(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(M(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return on(e,l)},async pageExperiments(l,v=[]){let P=i.generation;i.assertCurrent(P);let E=i.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let S=mn.parse(await h(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:v})));if(i.assertCurrent(P),S.runId!==E||S.scope.projectId!==i.scope?.projectId||S.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,v){let P=i.generation;l=l&&structuredClone(l),v=v&&{...v},a&&await o.ready,i.assertCurrent(P),v??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let E=JSON.stringify([i.generation,g,l??null,v??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=i.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...v?{purchase:v}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?V.settle(l):o.pending?.requestId===l?C(s(o.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(o.closeFlight)return o.closeFlight;if(o.closing)return s(o.closing);if(o.closeRequested&&o.pending)return V.settle(o.pending.requestId);if(o.inFlight)return C(o.inFlight);if(!o.pending)throw new f("INVALID_REQUEST","No command is pending");let l=o.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let v=i.generation;if(await V.settle(l.requestId),i.assertCurrent(v),!o.pending)return V.get();if(o.pending!==l||o.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let v=i.customerToken?void 0:t;I(),i.identify(l),t=v,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return V}function vo(e,t){return Xn({...e,runToken:"",initialResponse:t})}export{dn as a,sn as b,Nn as c,me as d,Tn as e,ln as f,Dn as g,Gt as h,Ut as i,Bt as j,ye as k,mn as l,te as m,qn as n,er as o,hr as p,wr as q,hn as r,Se as s,Cr as t,Zn as u,bn as v,Z as w,un as x,Cn as y,jr as z,ie as A,Ee as B,$r as C,Hr as D,Sn as E,Xn as F,vo as G};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as w,f as b}from"./chunk-
|
|
1
|
+
import{e as w,f as b}from"./chunk-TLV3NVUU.js";import{n as h,s as u}from"./chunk-Y5RT7PAD.js";import{a as y}from"./chunk-WP3SZU24.js";import{a as n}from"./chunk-O5VA3E5D.js";import{a as g}from"./chunk-3VUPVXAV.js";import{b as f}from"./chunk-EEYDOVVS.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
|