@tinkerlandai/longplay-sdk 0.10.33 → 0.10.34
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 +5 -3
- package/README.md +10 -8
- package/README.zh-CN.md +2 -2
- package/dist/chunk-3JJYWRA3.js +1 -0
- package/dist/chunk-4WZVC4TM.js +1 -0
- package/dist/chunk-5JWMP4YD.js +1 -0
- package/dist/{chunk-KIMX3OIV.js → chunk-6T575JKD.js} +1 -1
- package/dist/{chunk-XLSDL4D3.js → chunk-7NELM6EH.js} +1 -1
- package/dist/{chunk-KR3KDTVD.js → chunk-7VRZYSTR.js} +1 -1
- package/dist/{chunk-YTZQ5BMP.js → chunk-ERJP2GBD.js} +1 -1
- package/dist/{chunk-GGRDM54V.js → chunk-I6TSQQ5N.js} +1 -1
- package/dist/{chunk-JN6JEKWN.js → chunk-ITGERPCJ.js} +1 -1
- package/dist/{chunk-U6E6CM7Z.js → chunk-QBA3B4YK.js} +1 -1
- package/dist/chunk-RKPAIF6U.js +1 -0
- package/dist/{chunk-MPYJRLKB.js → chunk-TDSATEGE.js} +2 -2
- package/dist/{chunk-NVHIGAO3.js → chunk-TYY3MUTF.js} +1 -1
- package/dist/chunk-U6UHASIB.js +1 -0
- package/dist/{chunk-UHQGO6OR.js → chunk-WKIR2EQG.js} +1 -1
- package/dist/{chunk-U2R7MG3J.js → chunk-WTVLNUMS.js} +1 -1
- package/dist/{content-CFX2L2BP.js → content-ORU4ODJQ.js} +1 -1
- package/dist/funnel-host-purchase-BEFE3N3E.js +1 -0
- package/dist/{funnel-runtime-host-ATOA7MGC.js → funnel-runtime-host-V6TYIDX3.js} +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/paywall-HO4PS472.js +1 -0
- package/dist/{paywall-session-MB7BD2XP.js → paywall-session-MZXFOPTR.js} +1 -1
- package/dist/popup.d.ts +2 -2
- package/dist/popup.js +1 -1
- package/dist/{presentation-loading-CiEQbUDk.d.ts → presentation-loading-CFSiS0VX.d.ts} +3 -1
- package/dist/react-native.js +1 -1
- package/dist/{screen-renderer-3CBREMIS.js → screen-renderer-W7ZGBFIR.js} +1 -1
- package/dist/server.d.ts +30 -0
- package/dist/server.js +3 -3
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-BRAVNBCC.js +0 -1
- package/dist/chunk-ENZBWR3Y.js +0 -1
- package/dist/chunk-HQPP76BS.js +0 -1
- package/dist/chunk-NVIHK5GE.js +0 -1
- package/dist/chunk-U6GWWCUS.js +0 -1
- package/dist/funnel-host-purchase-MSPLT3ZV.js +0 -1
- package/dist/paywall-XAXSMLDU.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as rn}from"./chunk-JN6JEKWN.js";import{h as ue,i as se,r as nn,s as pe}from"./chunk-THMGTRXP.js";import{c as Be,d as Ke,e as J,l as en}from"./chunk-NAZU3EEJ.js";import{$ as U,D as Qe,R as Ye,W as Ze,X as We,Y as $,Z as Xe,_ as de,a as j,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,z as Je}from"./chunk-R23IGK5U.js";import{b as on}from"./chunk-EHDHWYVJ.js";import{b as ne}from"./chunk-U2R7MG3J.js";import{a as W}from"./chunk-VYFSRHXM.js";import{D as Te,L as ae,U as L,V as De,W as Le,ja as $e,ka as le,la as He,ma as ce,t as Oe,z as Ae}from"./chunk-N7YXDSQL.js";import{a as f}from"./chunk-X4W22IH6.js";import{h as D}from"./chunk-R4FDIYMN.js";import{b as tn}from"./chunk-UHQGO6OR.js";import{b as n}from"./chunk-VF6QMMEA.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-7QL4GF4C.js";import{a as Pe,b as Ne}from"./chunk-BID4UGWB.js";function an(e){return En({...e,namespace:"commands",identity:[e.runToken]})}function En(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??tn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Pn=n.discriminatedUnion("type",[Qe,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:Ze,openIn:We}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),Nn={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,$e.nullable())},On=n.strictObject({...Nn,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Cn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:He,variables:n.record(n.string(),L),output:L.nullable(),screen:On.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([nn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Pn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),An=n.strictObject({scope: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()}),sn=An.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var ln="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function cn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var Tn=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),_n=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(Tn).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=_n.omit({variation:!0,description:!0,iam:!0}),kn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),dn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(kn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),qt=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"])}),Vn=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()}),Mt=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"]),target:Vn})).max(4e3)}),jt=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")}),Gt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Ut=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),pn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:dn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(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)}),mn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:fn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...mn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...mn,evaluationMode:n.literal("remote")})]),Ln=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ye.nullable()}))})});function qn(e){return fn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:qn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:en(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function Wt(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return Ln.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,Mn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var jn=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),Gn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:Xe,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),or=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:jn,context:Ie,steps:n.array(Gn).min(1).max(he)}).refine(e=>X(e)<=Mn,"Segment exceeds its byte budget");var Un=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function 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):!Un.test(t))}function gn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>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),Bn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Bn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let 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 vr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),Kn(p,c,d))}function Kn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function Ir(e,t,u,r=re){return yn(Re(e,r),t,u)}function yn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(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 vn(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>gn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),yn(I,O,{attributes:Je({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||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 In(e,t){let u=sn.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Fr(e){return xe(e,Se)}var zn=3,Jn=2e3;function $n(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Hn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===zn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*Jn))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Qn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Hn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Qn(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=Yn(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 Yn(e,t,u){return vn(e,t,u,Se)}var hn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function bn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let 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=wn.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 qr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function xn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,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 zr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Jr(e){let t=ne(e);return t.identify(e.apiKey),t}function Rn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Zn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Sn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function 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&&!Zn(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=on(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 Wn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=xn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=d&&bn(d),o=Sn({journal:a,state:i,call: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;Rn(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=()=>{},Fn=new Promise((Xn,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())),Fn])}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?{[ln]: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=In(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:cn(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 rn(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=pn.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 go(e,t){return Wn({...e,runToken:"",initialResponse:t})}export{cn as a,un as b,Pn as c,me as d,An as e,sn as f,Vn as g,Mt as h,jt as i,Gt as j,ye as k,pn as l,te as m,Ln as n,Wt as o,vr as p,Ir as q,In as r,Se as s,Fr as t,Yn as u,wn as v,Z as w,an as x,En as y,qr as z,ie as A,Ee as B,zr as C,Jr as D,Rn as E,Wn as F,go as G};
|
|
1
|
+
import{e as rn}from"./chunk-ITGERPCJ.js";import{h as ue,i as se,r as nn,s as pe}from"./chunk-THMGTRXP.js";import{c as Be,d as Ke,e as J,l as en}from"./chunk-NAZU3EEJ.js";import{$ as U,D as Qe,R as Ye,W as Ze,X as We,Y as $,Z as Xe,_ as de,a as j,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,z as Je}from"./chunk-R23IGK5U.js";import{b as on}from"./chunk-EHDHWYVJ.js";import{b as ne}from"./chunk-WTVLNUMS.js";import{a as W}from"./chunk-VYFSRHXM.js";import{D as Te,L as ae,U as L,V as De,W as Le,ja as $e,ka as le,la as He,ma as ce,t as Oe,z as Ae}from"./chunk-N7YXDSQL.js";import{a as f}from"./chunk-X4W22IH6.js";import{h as D}from"./chunk-R4FDIYMN.js";import{b as tn}from"./chunk-WKIR2EQG.js";import{b as n}from"./chunk-VF6QMMEA.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-7QL4GF4C.js";import{a as Pe,b as Ne}from"./chunk-BID4UGWB.js";function an(e){return En({...e,namespace:"commands",identity:[e.runToken]})}function En(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??tn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Pn=n.discriminatedUnion("type",[Qe,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:Ze,openIn:We}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),Nn={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,$e.nullable())},On=n.strictObject({...Nn,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Cn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:He,variables:n.record(n.string(),L),output:L.nullable(),screen:On.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([nn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Pn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),An=n.strictObject({scope: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()}),sn=An.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var ln="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function cn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var Tn=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),_n=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(Tn).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=_n.omit({variation:!0,description:!0,iam:!0}),kn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),dn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(kn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),qt=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"])}),Vn=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()}),Mt=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"]),target:Vn})).max(4e3)}),jt=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")}),Gt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Ut=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),pn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:dn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(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)}),mn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:fn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...mn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...mn,evaluationMode:n.literal("remote")})]),Ln=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ye.nullable()}))})});function qn(e){return fn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:qn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:en(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function Wt(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return Ln.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,Mn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var jn=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),Gn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:Xe,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),or=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:jn,context:Ie,steps:n.array(Gn).min(1).max(he)}).refine(e=>X(e)<=Mn,"Segment exceeds its byte budget");var Un=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function 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):!Un.test(t))}function gn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>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),Bn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Bn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let 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 vr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),Kn(p,c,d))}function Kn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function Ir(e,t,u,r=re){return yn(Re(e,r),t,u)}function yn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(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 vn(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>gn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),yn(I,O,{attributes:Je({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||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 In(e,t){let u=sn.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Fr(e){return xe(e,Se)}var zn=3,Jn=2e3;function $n(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Hn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===zn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*Jn))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Qn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Hn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Qn(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=Yn(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 Yn(e,t,u){return vn(e,t,u,Se)}var hn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function bn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let 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=wn.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 qr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function xn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,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 zr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Jr(e){let t=ne(e);return t.identify(e.apiKey),t}function Rn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Zn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Sn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function 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&&!Zn(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=on(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 Wn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=xn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=d&&bn(d),o=Sn({journal:a,state:i,call: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;Rn(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=()=>{},Fn=new Promise((Xn,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())),Fn])}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?{[ln]: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=In(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:cn(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 rn(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=pn.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 go(e,t){return Wn({...e,runToken:"",initialResponse:t})}export{cn as a,un as b,Pn as c,me as d,An as e,sn as f,Vn as g,Mt as h,jt as i,Gt as j,ye as k,pn as l,te as m,Ln as n,Wt as o,vr as p,Ir as q,In as r,Se as s,Fr as t,Yn as u,wn as v,Z as w,an as x,En as y,qr as z,ie as A,Ee as B,zr as C,Jr as D,Rn as E,Wn as F,go as G};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as kn,b as Dn,c as rn,d as on,e as _e,f as Fn,g as We,i as Sn}from"./chunk-4WZVC4TM.js";import{c as Cn,e as Pn,f as Rn,h as En,i as Ae,j as Be,k as qn,l as je}from"./chunk-U6UHASIB.js";import{$ as Qe}from"./chunk-R23IGK5U.js";import{a as ze,e as gn,f as vn,g as hn,h as In,i as bn}from"./chunk-EHDHWYVJ.js";import{b as wn}from"./chunk-BXPXJARS.js";import{R as fn,qa as yn}from"./chunk-N7YXDSQL.js";import{a as C}from"./chunk-X4W22IH6.js";import{b as Tn,e as Nn}from"./chunk-SLUA7ABW.js";import{d as On}from"./chunk-6T575JKD.js";import{a as ue}from"./chunk-DSPLGTQI.js";import{b as mn}from"./chunk-7QL4GF4C.js";var Te=new WeakMap;function jn(n){let y=n.view,f=y?.paywall?.resolution;if(!y||!["running","waiting"].includes(y.status)||y.stopped||!f||"document"in f||!n.resolvePaywall||n.identitySignal?.aborted)return;let e=JSON.stringify(f);if(Te.get(n)?.key===e)return;let p=JSON.parse(e),F=n.identitySignal,a=Promise.resolve().then(async()=>{F?.throwIfAborted();let s=await n.resolvePaywall(p);return F?.throwIfAborted(),s}),S={key:e,content:a};return Te.set(n,S),a.catch(()=>{}),()=>{Te.get(n)===S&&Te.delete(n)}}function An(n,y){let f=Te.get(n);return Te.delete(n),f?.key===JSON.stringify(y)?f.content:n.resolvePaywall(y)}async function _n(n){let{session:y,load:f}=zn(n);try{return await f(),y}catch(e){throw y.destroy(),e}}function zn(n){let y=n.view;if(!y?.paywall)throw new C("INVALID_REQUEST","The current node is not a Paywall");let f=y.paywall.receiptId,e=y.nodeId,p=y.visit,F=y.paywall.resolution,a=y.paywall,S="document"in F?{document:F.document,offering:F.offering,capabilities:F.capabilities}:null;function s(){let i=a.resolution;return"document"in i?i:S&&{...i,document:S.document,offering:S.offering,capabilities:gn(i.capabilities,S.capabilities)}}function g(i){if(!vn(i,F))throw new C("INVALID_RESPONSE","The pinned Paywall binding changed")}let u=!1,q=new Set,A=null;function M(){let i=s();if(i&&!u)for(let l of q)ue(l,structuredClone(i))}async function k(){Q();let i=s();if(i)return structuredClone(i);if(!A){let l=(async()=>{if("document"in a.resolution||!n.resolvePaywall)throw new C("INVALID_RESPONSE","Public Paywall reader is unavailable");let c=await An(n,a.resolution);return Q(),g(c),S={document:c.document,offering:c.offering,capabilities:c.capabilities},M(),s()})();A=l;let o=()=>{A===l&&(A=null)};l.then(o,o)}return A.then(l=>structuredClone(l))}let d=new AbortController,D=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===p&&i.input.type==="paywall_quote")?.requestId??y.paywall.purchaseRequestId,R=0,H=null,b=new Set,$=null,v=new Map;function _(i){if(i.purchase&&i.purchase.receiptId!==f)throw new C("INVALID_RESPONSE","Purchase receipt changed");let l=i.run.paywall;return i.purchase??(l?.receiptId===f?l:null)}function Q(){if(u)throw new C("IDENTITY_CHANGED","Paywall presentation has closed")}function B(i,l,o){if(Q(),l!==R||o!==void 0&&a.quote?.operationId!==o)return!1;let c=a.selectionGeneration??0,m=i.run.paywall;if(m?.receiptId===f){if((m.selectionGeneration??0)<(a.selectionGeneration??0))return!1;g(m.resolution)}let h=_(i),j=m?.receiptId===f&&(m.selectionGeneration??0)>c,G=j?h?.quote??null:h?.quote??a.quote,I=h?.operation??(G?.operationId===a.quote?.operationId?a.operation:null);return G&&I&&hn(I,{operationId:G.operationId},"Purchase operation changed"),(j||G?.operationId!==a.quote?.operationId)&&(R++,m?.receiptId===f&&(D=m.purchaseRequestId)),m?.canReselect===!0&&m.purchaseRequestId===$&&!(n.pendingCommands??[n.pendingCommand]).some(U=>U?.requestId===$)&&($=null),a={...a,...m?.receiptId===f?m:{},quote:G,operation:bn(a.operation,I,!0)},M(),!0}function L(i,l,o){return new Promise((c,m)=>{let h=!1,j=()=>{clearTimeout(Re),d.signal.removeEventListener("abort",U)},G=Ee=>{h||(h=!0,j(),c(Ee))},I=Ee=>{h||(h=!0,j(),m(Ee))},U=()=>I(new C("IDENTITY_CHANGED","Paywall presentation has closed")),Re=setTimeout(()=>I(new C("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,o)),Math.max(0,l-Date.now()));d.signal.addEventListener("abort",U,{once:!0}),d.signal.aborted&&U(),i.then(G,I)})}function ce(i){return new Promise(l=>{let o=()=>{clearTimeout(c),d.signal.removeEventListener("abort",o),l()},c=setTimeout(o,i);d.signal.addEventListener("abort",o,{once:!0}),d.signal.aborted&&o()})}function Y(i,l){Q();let o=v.get(i)??n.pendingCommands?.find(h=>h.requestId===i)??n.pendingCommand;if(o?.operation==="submit"&&o.requestId===i&&o.nodeId===e&&o.visit===p){l.type==="paywall_quote"&&o.input.type==="paywall_quote"&&o.input.predecessor&&!l.predecessor&&(l={...l,predecessor:o.input.predecessor});let h=Qe.parse(o),j=Qe.parse({...o,input:l});if(h.operation!=="submit"||j.operation!=="submit"||JSON.stringify(h.input)!==JSON.stringify(j.input))throw new C("CONFLICT","A purchase request cannot change its input");return v.set(i,h),h}let c=n.view;if(!c||c.nodeId!==e||c.visit!==p||c.paywall?.receiptId!==f)throw new C("PRECONDITION_FAILED","The Paywall visit has changed");let m=Qe.parse({operation:"submit",requestId:i,nodeId:e,visit:p,revision:c.revision,input:structuredClone(l)});if(m.operation!=="submit")throw new C("INVALID_REQUEST","A purchase submission is required");return v.set(i,m),m}async function pe(i,l){Q();let{requestId:o,input:c}=i,m=Date.now()+3e4;b.add(o);try{let h=await L(n.submit(i),m,o);for(;h.run.pendingRequest?.requestId===o&&Date.now()<m&&!u&&(await ce(Math.min(1e3,m-Date.now())),!(u||Date.now()>=m));)h=await L(n.resume(o),m,o);if(u)throw new C("IDENTITY_CHANGED","Paywall presentation has closed");if(h.run.pendingRequest?.requestId===o)throw new C("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,o);if(!B(h,l,c.type==="paywall_confirm"||c.type==="paywall_cancel"?c.operationId:void 0))throw new C("PRECONDITION_FAILED","The purchase selection has changed");$===o&&($=null)}catch(h){if($=o,c.type==="paywall_quote"&&n.settle&&!u&&h instanceof C&&h.status!==void 0&&![401,425].includes(h.status)&&!h.retryable&&h.recovery!=="recover_operation")try{if((await L(n.settle(o),m,o)).settlement?.state==="settled"){let G=await L(n.get(),m,o);B(G,l)&&G.run.paywall?.purchaseRequestId===o&&a.canReselect===!0&&v.delete(o)}}catch{}throw h instanceof C&&h.code==="COMMAND_PENDING"&&h.status===void 0&&v.delete(o),h}finally{b.delete(o)}}async function oe(i){if(!a.quote)throw new C("INVALID_REQUEST","A quoted purchase is required");let l=i==="confirm"?"paywall_confirm":"paywall_cancel",o=[...v.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(m=>m.operation==="submit"&&m.input.type===l&&"operationId"in m.input&&m.input.operationId===a.quote.operationId),c=o?.operation==="submit"&&o.input.type===l&&"operationId"in o.input&&o.input.operationId===a.quote.operationId?o.requestId:crypto.randomUUID();if(await pe(Y(c,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:a.quote.operationId}),R),!a.operation)throw new C("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(a.operation)}let T={get view(){return structuredClone(s())},get quote(){return a.quote?structuredClone(a.quote):null},get operation(){return a.operation?structuredClone(a.operation):null},get webViewUrl(){return n.webViewUrl},get canReselect(){return a.canReselect===!0&&$===null},get recovery(){let i=n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[]),l=n.pendingPurchase;if(l&&(l.receiptId!==f||l.operationId!==a.quote?.operationId))return{type:"recover",operationId:l.operationId,requestId:i[0]?.requestId??null};let o=ze({quote:a.quote,operation:a.operation,requestId:i[0]?.requestId??$??D,pending:b.size>0||i.length>0||$!==null,destroyed:u,canReselect:a.canReselect});return o.type==="recover"&&o.requestId===null&&!u&&n.hasDurableJournal===!0&&!a.quote&&!a.operation&&(a.selectionGeneration??0)===0&&!l&&!i.length&&!b.size&&!D?{type:"native",operationId:null}:o},get pendingCancellation(){return!u&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===p&&i.input.type==="paywall_cancel"&&i.input.operationId===a.quote?.operationId)},subscribe(i){return u?()=>{}:(q.add(i),()=>q.delete(i))},async refresh(){Q();let i=R,l=await n.get();if(B(l,i),l.run.paywall?.receiptId!==f)throw new C("PRECONDITION_FAILED","Paywall presentation has changed");return k()},preview(i){let l=s();if(!l)return Promise.reject(new C("PRECONDITION_FAILED","Load the Paywall presentation first"));if(D&&D!==i.requestId&&(H||a.canReselect!==!0))return Promise.reject(new C("COMMAND_PENDING","Retry the original purchase before starting another"));let o=l.document.buttons[i.actionId],c=o?.type==="checkout"?wn(o.product,i.selection,l.capabilities):null;if(!c)return Promise.reject(new C("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let m=yn(l.document.screen,c,i.selection,l.capabilities),h=D!==i.requestId&&(a.selectionGeneration??0)>0?{operationId:a.quote?.operationId??null,generation:a.selectionGeneration??0}:void 0;if(h&&a.canReselect!==!0)return Promise.reject(new C("COMMAND_PENDING","Original purchase requires authoritative termination"));let j;try{j=Y(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:c,...Object.keys(m).length?{featureQuantities:m}:{},...h?{predecessor:h}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(U){return Promise.reject(U)}if(D===i.requestId&&H)return H;D!==i.requestId&&R++;let G=R;D=i.requestId;let I=(async()=>{if(await pe(j,G),!a.quote)throw new C("INVALID_RESPONSE","The accepted quote is missing");return In(a.quote,{productVersionId:c,featureQuantities:m},"The selected purchase changed"),structuredClone(a.quote)})();return H=I,I.then(()=>{H===I&&(H=null)},U=>{H===I&&(H=null),D===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&U instanceof C&&U.status!==void 0&&U.status<500&&![401,425].includes(U.status)&&(D=null)}),I},confirm:()=>oe("confirm"),cancel:()=>oe("cancel"),async read(){if(Q(),!a.quote)throw new C("INVALID_REQUEST","A quoted purchase is required");let i=a.quote.operationId,l=R,o=n.pendingCommands?.find(G=>G.operation==="submit"&&(G.input.type==="paywall_confirm"||G.input.type==="paywall_cancel")&&G.input.operationId===i)??n.pendingCommand;o?.operation==="submit"&&(o.input.type==="paywall_confirm"||o.input.type==="paywall_cancel")&&o.input.operationId===i&&await n.settle?.(o.requestId);let c=await n.get(void 0,{receiptId:f,operationId:i});Q();let m=_(c);if(m?.quote&&m.quote.operationId!==i||m?.operation&&m.operation.operationId!==i)throw new C("INVALID_RESPONSE","Purchase operation changed");let h=B(c,l,i),j=h?a.operation:m?.operation;if(!j)throw new C("INVALID_RESPONSE","The current purchase result is missing");return h&&b.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&($=null),structuredClone(j)},destroy(){u=!0,E(),q.clear(),d.abort(),v.clear()}},E=n.subscribe(i=>{u||i.nodeId!==e||i.visit!==p||i.paywall?.receiptId!==f||(i.paywall.selectionGeneration??0)<(a.selectionGeneration??0)||(g(i.paywall.resolution),a={...a,resolution:i.paywall.resolution},M())});return{session:T,load:k}}function Ln(n){let y=new Set,f=new Set,e=null;async function p(s,g){let u=!1;for(;!n.stopped&&n.key===s&&n.client.pendingCommand?.requestId===g;){if(!n.client.settle)throw new C("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(g),u=!0,n.client.pendingCommand?.requestId===g&&await new Promise(q=>setTimeout(q,1500))}n.stopped||n.key!==s||(u&&await n.client.get(),!(n.stopped||n.key!==s)&&y.add(s))}function F(s,g){e=g;let u=()=>{e===g&&(e=null),f.delete(s)};return g.then(u,q=>{u(),n.busy||n.fail(q)}),g}function a(s){if(n.reviewing||y.has(s)||f.has(s)||n.stopped)return;f.add(s);let g=async()=>{if(n.reviewing||n.stopped||n.key!==s||y.has(s)){f.delete(s);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{g()},250);return}let u=(async()=>{if(n.staleRead){if(await n.staleRead,n.stopped||n.key!==s)return;if(n.client.pendingCommand){setTimeout(()=>{g()},250);return}}let q=n.client.view,A=n.expected(),M=A.requestId;try{await n.client.submit({operation:"shown",...A})}catch(k){if(!(k instanceof C)||k.code!=="CONFLICT"||k.status!==409||n.client.pendingCommand)throw k;await n.client.get();let d=n.client.view;if(n.stopped||n.reviewing||n.key!==s||!d||!q||d.id!==q.id||d.source.versionId!==q.source.versionId||d.nodeId!==A.nodeId||d.visit!==A.visit||d.revision<=A.revision||d.stopped||!d.screen&&(!d.paywall||d.paywall.receiptId!==q.paywall?.receiptId)||!["running","waiting"].includes(d.status)||n.client.pendingCommand)throw k;let O=n.expected();M=O.requestId,await n.client.submit({operation:"shown",...O})}await p(s,M)})();F(s,u)};g()}function S(){if(e)return e;let s=n.client.pendingCommand;if(s?.operation!=="shown")return null;let g=n.key;return f.add(g),F(g,(async()=>{await n.client.retry(),await p(g,s.requestId)})())}return{report:a,settled:S,get inFlight(){return e}}}function Vn(n){let y={},f=new Map;async function e(p){let F=n.client.view,a=F?.screen,S=a?.customerData.nodes[p.nodeId];if(n.stopped||n.busy||!F||!a||!S)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let k=n.document,d=k?fn(k,p.nodeId):null,O=d?.type==="customer_data"?d.data.outputs?.[p.action]:void 0;O&&a.outputs.includes(O)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:O,answers:n.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await n.onIntent?.(p,F);return}let g=p.action.startsWith("sources_")?S.resources.find(k=>k.key===p.value):null;if(p.action.startsWith("sources_")&&!g)throw new C("INVALID_REQUEST","Choose a current resource");let u=`${F.visit}:${p.nodeId}:${g?.key??""}`,q=f.get(u)??[null],M=y[p.nodeId]??{page:1,after:null,filter:"all",...g?{resourceKey:g.key}:{}};if(p.action==="filter"){let k=p.value;if(!k||!(S.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(k))throw new C("INVALID_REQUEST","Unknown data filter");M={page:1,after:null,filter:k},q.splice(0,q.length,null)}else if(p.action==="next"||p.action==="sources_next"){let k=g?.sources.at(-1),d=g?k?{kind:"ledger",cursor:{at:k.detail[0],id:k.id,type:"source"}}:null:a.dataCursors[p.nodeId];if(!d||!g&&!S.hasNext)return;q[M.page]=d,M={...M,page:M.page+1,after:d}}else if(p.action==="previous"||p.action==="sources_previous"){if(M.page<=1)return;M={...M,page:M.page-1,after:q[M.page-2]??null}}f.set(u,q),y={...y,[p.nodeId]:M},await n.perform(()=>n.client.get({nodeId:F.nodeId,visit:F.visit,revision:F.revision,components:y}))}return{get queries(){return y},intent:e,reset(){y={},f.clear()}}}function Mn(n){let{doc:y,holder:f,reviewHolder:e,mountScreenPreview:p}=n,F=!1,a,S=0,s=null,g="",u,q=new Map,A=d=>d?`${d.id}:${d.nodeId}:${d.visit}:${d.revision}:${d.paywall?.quote?.operationId??""}`:"";async function M(d){if(n.stopped||!n.client.review||F&&d===a&&u?.active)return;let O=!F||d!==a;F||(g=A(n.client.view),q.set(g,structuredClone(n.answers))),F=!0,a=d,f.hidden=!0,n.suspend(!0),e.hidden=!1;let D=++S;O&&(u?.finish("dismissed"),s?.destroy(),s=null,e.replaceChildren(),u=Be(e,n.loadingOptions,"funnel",()=>{k()}));let R=O?u:void 0;try{if(R?.start(!1,n.client.view?.locale),D!==S||n.stopped)return;let H=n.client.review(d),b=await(R?.wait(H,Ae)??H);if(n.stopped||D!==S||!F)return;if(!b.review)throw new C("INVALID_RESPONSE","Historical projection is missing");s?.destroy(),s=null,R||e.replaceChildren();let $=y.createElement("div"),v=R?je($,e):()=>{};e.append($);let _=b.run.locale.startsWith("zh"),Q=n.chrome;$.style.cssText=Q.history;let B=y.createElement("p");B.textContent=_?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",B.style.cssText=Q.historyTitle,$.append(B);let L=y.createElement("p");L.style.cssText=Q.historyNote,L.textContent=b.review.pages.length?_?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":_?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",$.append(L);let ce=b.review.page?.receiptId,Y=y.createElement("div");Y.style.cssText=Q.historyPages;for(let[T,E]of b.review.pages.entries()){let i=y.createElement("button");i.type="button",i.textContent=_?`\u7B2C ${T+1} \u9875`:`Page ${T+1}`;let l=ce!==void 0&&E.receiptId===ce;i.style.cssText=l?Q.primary:Q.secondary,l&&i.setAttribute("aria-current","page"),_e(i,()=>n.chrome.focus),i.onclick=()=>{M(E.receiptId)},Y.append(i)}if(Y.childElementCount&&$.append(Y),b.review.page){let T=b.review.page,E=y.createElement("div");E.inert=!0,E.style.cssText=Q.historyPage,$.append(E),s=p(E,{mode:"live",rendererUrl:n.client.webViewUrl,title:T.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{D===S&&!n.stopped&&R?.present(v)},onError:l=>{if(D!==S||n.stopped)return;let o=new Error(l);R?.finish("error",o),s?.destroy(),s=null,$.remove(),n.fail(o)},onEscape:()=>{k()}});let i=s;if(i.update(T.document,b.run.locale,{serverInput:{bindings:T.inputs,answers:T.answers,values:T.values}}),await i.ready,n.stopped||D!==S||!F)return}let pe=_?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},oe=y.createElement("div");oe.style.cssText=Q.historyRecords;for(let T of[...b.review.coupons.map((E,i)=>`${_?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${pe[E.status]}`),...b.review.purchases.map((E,i)=>`${_?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Sn(E.status,_)}`)]){let E=y.createElement("p");E.textContent=T,E.style.margin="0",oe.append(E)}oe.childElementCount&&$.append(oe),b.review.page||R?.present(v),n.client.view&&await n.enqueue(n.client.view)}catch(H){if(D!==S||n.stopped)return;R?.finish("error",H),s?.destroy(),s=null,e.replaceChildren(),n.fail(H)}}async function k(){if(!F||n.stopped||!n.client.review)return;let d=++S;u?.finish("dismissed");try{if(await n.client.review(),n.stopped||d!==S)return;F=!1,S++,u?.finish("dismissed"),s?.destroy(),s=null,e.replaceChildren(),e.hidden=!0,f.hidden=!1;let O=n.client.view;A(O)!==g?(q.set(g,structuredClone(n.answers)),n.resetScreen()):(q.delete(g),n.suspend(!1)),O&&await n.enqueue(O)}catch(O){if(d!==S||n.stopped)return;s?.destroy(),s=null,e.replaceChildren(),n.fail(O)}}return{get active(){return F},get receipt(){return a},open:M,exit:k,get drafts(){return new Map([...q].map(([d,O])=>[d,structuredClone(O)]))},stop(){F=!1,S++,u?.finish("dismissed"),s?.destroy(),s=null,e.replaceChildren(),e.hidden=!0,f.hidden=!1}}}function Hn(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let y=n.client.pageExperiments.bind(n.client),f=!1,e=!1,p=0,F=!1,a=!1,S="",s=()=>{let v=n.client.view;return JSON.stringify([v?.id,v?.source.versionId,v?.visit,v?.revision,v?.status,v?.stopped])},g=new Map,u=new Set,q={},A=new Map,M=Tn(n.appManifestRelease),k=()=>{for(let v of g.values())v.effect.revert();g.clear()},d=()=>{k();for(let v of A.values())v();A.clear()};function O(v){if(f||u.has(v))return;u.add(v);let _=p;y(n.appManifestRelease,[v]).catch(Q=>{u.delete(v),!f&&_===p&&ue(n.onError,Q)})}async function D(){if(f)return;S=s();let v=n.client.view;if(!v||v.stopped||!["running","waiting"].includes(v.status)){p++,d();return}if(document.visibilityState==="hidden")return;if(F){a=!0;return}F=!0;let _=++p,Q=`${v.id}:${v.visit}:${v.revision}`,B=location.href;try{let[L,{applyVisualVariation:ce}]=await Promise.all([y(n.appManifestRelease),import("./visual-dom-6DCUZGPB.js")]),Y=n.client.view;if(f||_!==p||!Y||Y.stopped||!["running","waiting"].includes(Y.status)||`${Y.id}:${Y.visit}:${Y.revision}`!==Q||location.href!==B)return;let pe=new Set,oe=new Set;for(let T of L.assignments){let E=`${L.payload.environmentId}:${T.experimentKey}`;if(oe.add(E),A.has(E)||A.set(E,Nn(E,q)),!!T.inExperiment)for(let i of L.payload.experiments){if(i.key!==T.experimentKey||!mn(location.href,i.urlPatterns??[]))continue;let l=i.meta?.findIndex(G=>G.key===T.variationKey)??-1,o=i.variations[l];if(!o?.renderGuard)continue;let c=T.receiptId+":"+i.changeId,m=JSON.stringify([T.variationKey,o]);pe.add(c);let h=g.get(c);if(h?.signature===m){h.effect.applied&&O(T.receiptId);continue}g.get(c)?.effect.revert(),g.delete(c);let j=ce(o,{requireUniqueTargets:!0,boundVariations:i.variations,allowJs:!1,onApplied:()=>O(T.receiptId),onError:G=>ue(n.onError,G)});g.set(c,{signature:m,effect:j}),j.applied&&O(T.receiptId)}}for(let[T,E]of g)pe.has(T)||(E.effect.revert(),g.delete(T));for(let[T,E]of A)oe.has(T)||(E(),A.delete(T))}catch(L){_===p&&d(),!f&&_===p&&ue(n.onError,L)}finally{F=!1,a&&!f&&(a=!1,D())}}let R=n.client.subscribe(()=>{if(s()===S)return;S=s(),p++;let v=n.client.view;(!v||v.stopped||!["running","waiting"].includes(v.status))&&d(),e&&D()}),H=On(()=>{p++,d(),e&&D()}),b=()=>{p++,k()};document.addEventListener("visibilitychange",b);let $=We({document,run:async()=>{e&&await D()},delay:()=>e&&!f?15e3:void 0});return{async start(){e||f||(e=!0,await $.refresh())},refresh:D,destroy(){f=!0,p++,$.destroy(),document.removeEventListener("visibilitychange",b),R(),H(),d(),M.destroy()}}}var sn=5e3;async function Bn(n,y,f){let e=y,[{mountScreenPreview:p},{showPaywall:F}]=await Promise.all([import("./screen-renderer-W7ZGBFIR.js"),import("./paywall-HO4PS472.js")]),a=e.client.identitySignal;e.signal?.throwIfAborted(),a?.throwIfAborted();let S=e.appManifestRelease?Hn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;S?.start();let s=n.ownerDocument,g=En(s),u=s.createElement("section"),q=s.createElement("div"),A=s.createElement("div"),M=s.createElement("div"),k=s.createElement("button");M.hidden=!0,k.type="button";let d=s.createElement("p"),O=s.createElement("p"),D=s.createElement("button"),R=s.createElement("button"),H=s.createElement("button"),b=s.createElement("dialog"),$;u.dataset.indianaFunnel="",u.setAttribute("aria-busy","false"),d.setAttribute("role","status"),O.setAttribute("role","alert"),O.hidden=!0,D.type=R.type=H.type="button",A.append(D,k,d,O,H,R),u.append(q,M,A),n.append(u);let v=Dn,_=rn(v),Q="",B=(s.documentElement.lang||"").startsWith("zh"),L,ce="",Y;for(let t of[D,k,H,R])_e(t,()=>_.focus);function pe(){let t=B?"\u5173\u95ED":"Close";R.parentElement===b?(R.textContent="\xD7",R.setAttribute("aria-label",t),Rn(R,v)):(R.textContent=t,R.removeAttribute("aria-label"),R.style.cssText=_.link+";margin-inline-start:auto")}function oe(t){let r=t?.screen?.content.document.theme??v,w=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,R.parentElement===b]);w!==Q&&(Q=w,v=r,_=rn(v,R.parentElement===b),u.style.cssText=_.root+";min-width:0",A.style.cssText=_.bar,D.style.cssText=k.style.cssText=_.secondary,H.style.cssText=_.primary,d.style.cssText=_.status,O.style.cssText=_.alert,pe(),on(D))}function T(){A.hidden=D.hidden&&k.hidden&&H.hidden&&O.hidden&&!d.textContent&&(R.hidden||R.parentElement!==A),L?.responsive&&Y!==void 0&&L.setContentHeight(Y+A.getBoundingClientRect().height)}oe();let E=null,i=null,l=null,o="",c="",m=!1,h="",j="",G="",I=!1,U=0,Re=!1,Ee="",Ke=null,Ye=Promise.resolve(),an=!e.client.view,W=f,qe,Oe,Le="",Ve,fe=!1,Ie=null,ge=!1,Me=()=>e.client.pendingCommand?.operation==="close",se=null,K=null,ln=We({document:s,run:async()=>{(!i?.observing||e.client.pendingCommand)&&await Ze()},delay:()=>{if(!(I||!l||!["running","waiting"].includes(l.status)&&!e.client.pendingCommand)&&!(i?.observing&&!e.client.pendingCommand))return l.pendingRequest||e.client.pendingCommand?1500:sn},hiddenDelay:()=>!I&&e.client.pendingCommand?15e3:void 0}),X=null;function Xe(){return K&&e.client.hasDurableJournal===!0&&X?.acknowledged===!0&&X.operationId===K.operationId&&e.client.view?.id===X.runId&&e.client.view?.status==="closed"&&e.client.view.revision===X.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?K:null}function un(t){let r=t.run.paywall;if(X&&t.settlement?.requestId===X.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===X.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===X.revision+1&&t.run.nodeId===X.nodeId&&t.run.visit===X.visit&&r?.receiptId===X.receiptId&&r.selectionGeneration===X.selectionGeneration&&(r.quote?.operationId??null)===X.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===X.operationId){let w=X.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,ie=ze({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(w||r.canReselect===!0&&ie.type==="native")&&(X.acknowledged=!0)}}let ke=null,He=new Set,me={},De=!1,de=(t,r=null)=>{I||(ke=r,De=!1,O.textContent=Fn(t,B),O.hidden=!1,H.hidden=e.client.pendingCommand===null,T(),ue(e.onError,t))};function be(){let t=e.client.view;if(!t)throw new C("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let x=Mn({client:e.client,doc:s,holder:q,reviewHolder:M,mountScreenPreview:p,loadingOptions:e,get chrome(){return _},get stopped(){return I},get answers(){return me},suspend(t){i?.setSuspended(t)},resetScreen(){o="",c="",h=""},enqueue:we,fail:de}),$e=Ln({client:e.client,expected:be,fail:de,get stopped(){return I},get reviewing(){return x.active},get key(){return o},get busy(){return U},get staleRead(){return Ke}}),Ue=Vn({client:e.client,expected:be,perform:Se,onIntent:e.onCustomerDataIntent,get stopped(){return I},get busy(){return U},get document(){return E?.document},get answers(){return me}}),xe=t=>`${t.id}:${t.nodeId}:${t.visit}`,Fe=t=>t&&(t.screen||t.paywall)?xe(t):"";function Ce(){let t=e.client.view;D.disabled=!x.active&&(U>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!Fe(t)||c!==Fe(t)),D.hidden=!x.active&&!t?.canBack,on(D);let r=!!i&&!x.active;R.hidden=r&&!W?.active,k.hidden=!e.client.review||r&&!t?.canBack,r&&(d.textContent=""),T()}async function dn(t){if(!t)return;let r=e.client.view;await t;let w=e.client.view;if(!r||!w||w.id!==r.id||w.nodeId!==r.nodeId||w.visit!==r.visit||w.stopped||!["running","waiting"].includes(w.status))throw new C("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Se(t,r=!1){if(!((U||ge||se||K)&&!r||I||x.active&&!r)){U++,u.setAttribute("aria-busy","true"),O.hidden=!0,ke=null,De=!1,Ce();try{if(r||await dn($e.inFlight),I)return;let w=await t();I||await we(e.client.view??w.run)}catch(w){de(w,e.client.pendingCommand?.requestId??null)}finally{U=Math.max(0,U-1),u.setAttribute("aria-busy",String(U>0)),I||(H.hidden=e.client.pendingCommand===null,Ce())}}}function Ne(){ln.schedule()}async function Ze(){if(!(I||Re||U)){if(x.active){await x.open(x.receipt);return}Re=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let r=e.client.view,w=Ue.queries,ie=await e.client.get(r?.screen&&Object.keys(w).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:w}:void 0);De&&!I&&(De=!1,O.hidden=!0,T()),!I&&w===Ue.queries&&await we(e.client.view??ie.run)}catch(t){de(t),De=!I}finally{Re=!1}}}function Ge(t,r,w){if(W?.active){let le=W;return le.setDismissHandler(()=>cn(le)),le}let ie=Be(n,e,"funnel",()=>cn(ie),kn);return W=ie,ie.start(t,r,w),ie}function cn(t){I||fe||(fe=!0,t.finish("dismissed"),ve(),u.hidden=!0,e.client.view?Pe().finally(ae):ae())}function en(){clearTimeout(Ve?.timeout),Ve=void 0}function ve(){en(),qe?.abort(),qe=void 0,E?.destroy(),E=null,i?.destroy(),i=null,Oe?.(),Oe=void 0,b.open&&b.close(),q.replaceChildren(),q.style.cssText="",Y=void 0,o="",c="",m=!1,h="",G=""}function pn(){let t=s.defaultView;L?.responsive&&t&&E?.resizeViewport?.(t.innerHeight,t.innerWidth)}function nn(){L?.destroy(),L=void 0,ce=""}function tn(t){let r=t.screen?.presentation;if(!r||r.type==="inline"){b.open&&b.close(),nn(),R.parentElement!==A&&A.append(R),u.parentElement!==n&&n.append(u),oe(t),T();return}u.parentElement!==b&&(b.append(R,u),n.append(b)),oe(t);let w=t.screen.content.document,ie=JSON.stringify([r,Q]);if(ie!==ce){nn(),ce=ie;let le={sm:420,md:640,lg:900},ye="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";b.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${v.background};color:${v.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${le[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${ye};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),L=Cn(b,{presentation:r,theme:w.theme,pages:w.pages},pn),L.latch()}T(),b.setAttribute("aria-label",($?.screen===t.screen?.content.document.name?$?.label:void 0)??E?.document?.name??t.screen?.content.document.name??"Funnel")}async function $n(t){if(I||fe||ge&&(Me()||["running","waiting"].includes(t.status))||(l=t,ke&&e.client.pendingCommand?.requestId!==ke&&(O.hidden=!0,ke=null),B=t.locale.startsWith("zh"),k.textContent=B?"\u56DE\u770B":"History",D.textContent=x.active?B?"\u8FD4\u56DE\u5F53\u524D":"Return to current":B?"\u8FD4\u56DE":"Back",pe(),H.textContent=B?"\u91CD\u8BD5":"Retry",H.hidden=e.client.pendingCommand===null,d.textContent=t.pendingRequest?B?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?B?"\u7B49\u5F85\u4E2D":"Waiting":"",Ce(),Ee!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(Ee=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,ue(e.onState,structuredClone(t))),I||fe))return;if((!t.pendingRequest||ge&&t.status==="closed")&&["closed","ineligible","failed"].includes(t.status)){ae();return}if(t.stopped||e.client.configurationReady===!1){x.stop(),ve(),W?.finish("skipped"),u.hidden=!0,Ne();return}if(u.hidden=!1,x.active){Ne();return}let r=Fe(t),w=e.client.view;if(w&&w.revision>t.revision&&Fe(w)!==r)return;let ie=!t.instruction&&!t.pendingRequest&&t.nodeType==="screen"&&["running","waiting"].includes(t.status);r!==o&&(o&&W?.finish("dismissed"),ve(),o=r,me={...t.answers},Ue.reset());let le=xe(t);if(Le===le){u.hidden=!0;return}if(ie&&!r){u.hidden=!0;let J=Ge(!0,t.locale);!I&&!fe&&Ve?.key!==le&&(en(),Ve={key:le,timeout:setTimeout(()=>{let P=e.client.view;if(!J.active||!P||xe(P)!==le)return;Le=le;let Z=new Error("Funnel screen preparation timed out");J.finish("error",Z),ve(),de(Z)},Ae)}),Ne();return}en();let ee=J=>{let P=e.client.view;return!I&&!fe&&!Ie&&!J.aborted&&e.client.configurationReady!==!1&&!!P&&!P.stopped&&!["closed","ineligible","failed"].includes(P.status)&&Fe(P)===r},ye=(J,P)=>{ee(P)&&(Le=r,W?.finish("error",J),ve(),u.hidden=!0,de(J))};if(r||(tn(t),t.instruction?.type!=="event"&&t.instruction?.type!=="open_url"&&W?.finish("skipped")),t.screen){let J=t.screen.content;if(!E){let ne=t.screen.presentation.type!=="inline",V=Ge(ne,t.locale);if(I||fe)return;let re=(qe=new AbortController).signal;tn(t),Oe=ne?qn(b):je(u,n),E=p(q,{mode:"live",rendererUrl:e.client.webViewUrl,title:J.document.name,...ne?{hostPresentation:()=>L?.type??t.screen.presentation.type}:{},onResize:te=>{Y=te,L?.responsive&&L.setContentHeight(te+A.getBoundingClientRect().height)},onAction(te,he={},Jn={}){if(x.active||!ee(re)||c!==r)return;me={...me,...Jn};let Qn=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:Je})=>Object.hasOwn(me,Je)).map(({variable:Je})=>[Je,me[Je]]));Se(()=>e.client.submit({operation:"submit",...be(),input:{type:"screen",output:te,answers:Qn,selection:he}}))},onAnswers:te=>{x.active||!ee(re)||c!==r||(me={...me,...te})},onCustomerDataIntent:te=>{x.active||!ee(re)||c!==r||Ue.intent(te).catch(de)},onEscape:()=>{!ee(re)||c!==r||x.active||se||K||Pe()},onError:te=>{let he=new Error(te);c===r?de(he):ye(he,re)},onRendered:te=>{if(!(!ee(re)||c===r))try{V.present(he=>{Oe?.(),Oe=void 0,te&&($={screen:J.document.name,label:te},b.setAttribute("aria-label",te)),ne&&(b.showModal(),L?.responsive&&b.focus({preventScroll:!0}),!he&&e.loading!=="host"&&Pn(b,L?.type??t.screen.presentation.type,L?.responsive)),c=r,m=ne,Ce()}),ee(re)&&$e.report(r)}catch(he){ye(he,re)}}}),pn()}let P={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:me,values:t.screen.values}},Z=JSON.stringify([J,t.locale,P.parameters,t.screen.inputs,t.screen.values]);if(Z!==h)E.update(J.document,t.locale,P),h=Z,j=JSON.stringify(P.capabilities),G=JSON.stringify(P.customerData);else{let ne=JSON.stringify(P.capabilities);ne!==j&&(E.updateCapabilities(P.capabilities),j=ne),JSON.stringify(P.customerData)!==G&&(E.updateCustomerData(P.customerData),G=JSON.stringify(P.customerData))}let z=E;if(z)try{await(W?.wait(z.ready)??z.ready)}catch(ne){qe&&ye(ne,qe.signal)}}else if(t.paywall&&!i){let J=t.paywall.resolution,P="document"in J?J.document:null,Z=Ge(!0,t.locale,P);if(I||fe)return;let z=(qe=new AbortController).signal;tn(t);let ne=await F(q,{loading:"host",signal:z,canInteract:()=>ee(z)&&!x.active&&!se&&!K,beforeAction:async()=>{U++;try{await dn($e.settled()),O.hidden=!0,ke=null,De=!1,T()}finally{U=Math.max(0,U-1)}},start:()=>_n(e.client),onObservationChange:Ne,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,checkoutNavigation:e.checkoutNavigation,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:V=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:V,openIn:"same_window"}):s.defaultView?.location.assign(V),onAction:async V=>{if(x.active)return;let re=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:e.client.view?.revision??t.revision,input:{type:"screen",output:V,answers:{}}});await we(e.client.view??re.run)},onError:V=>{c===r?de(V):ye(V,z)}},{quoteError:V=>ue(e.onError,V),present(V){ee(z)&&(Z.present(()=>{V(),c=r,m=!!q.querySelector("dialog[open]"),Ce()}),ee(z)&&$e.report(r))},async dismiss(){I||z.aborted||x.active||se||K||!ge&&!ee(z)||(ge=!0,await Pe())}}).catch(V=>(ye(V,z),null));!ee(z)&&!(ge&&!I&&!z.aborted)?ne?.host?.destroy():ne&&(i=ne.host,i?.setSuspended(x.active))}if(I||fe)return;Ce();let N=t.instruction;if(N&&(N.type==="open_url"||N.type==="event")&&!He.has(N.receiptId)){let J=s.createElement("button");J.type="button",J.style.cssText=_.primary,_e(J,()=>_.focus),q.style.cssText=_.stage,J.textContent=N.type==="open_url"?`${B?"\u524D\u5F80":"Continue to"} ${new URL(N.url).host}`:B?"\u7EE7\u7EED":"Continue",J.onclick=()=>{let P=be(),Z=N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="new_window"?Un(N.url):null;Se(async()=>{let z="success";if(N.type==="open_url")if(e.onOpenUrl)try{z=await e.onOpenUrl({receiptId:N.receiptId,url:N.url,openIn:N.openIn})===!1?"failed":"opened"}catch(V){ue(e.onError,V),z="failed"}else z=N.openIn==="new_window"&&!Z?"failed":"opened";if(N.type==="event"){if(!e.onEvent)throw new C("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(N.event)}if(I||e.client.view?.nodeId!==P.nodeId||e.client.view.visit!==P.visit)throw new C("PRECONDITION_FAILED","The client action visit changed");let ne=await e.client.submit({operation:"submit",...P,input:{type:"client_action",receiptId:N.receiptId,outcome:z}});return He.add(N.receiptId),N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="same_window"&&s.defaultView?.location.assign(N.url),ne})},W?.active?W.present(()=>q.replaceChildren(J)):q.replaceChildren(J)}!t.pendingRequest&&t.status==="completed"&&!He.has(`complete:${t.id}`)&&(He.add(`complete:${t.id}`),ue(e.onComplete,structuredClone(t))),Ne()}function Un(t){let r=s.defaultView?.open(t,"_blank")??null;return r&&(r.opener=null),r}function we(t){return Ce(),Ye=Ye.catch(()=>{}).then(async()=>{try{await $n(t)}catch(r){throw W?.active&&(Le=xe(t),W.finish("error",r),ve(),u.hidden=!0),r}}),Ye}let xn=e.client.subscribe(t=>{if(!an){if(t.stopped&&m&&!ge){l=t,ae();return}!ge&&(t.stopped||e.client.configurationReady===!1||o&&c!==o&&(Fe(t)!==o||["closed","ineligible","failed"].includes(t.status)))&&(ve(),W?.finish("dismissed"),u.hidden=!0),we(t).catch(de)}}),Gn=e.client.subscribeError?.(de);function Pe(t){if(Ie)return Ie;if(I||!t&&(se||K))return Promise.resolve();let r=!t&&Me();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(l=e.client.view,ae(),Promise.resolve()):(Ie=Se(async()=>{let w=r?await e.client.retry():await e.client.submit({operation:"close",...t??be()});return t&&un(w),w},!0).then(()=>{let w=e.client.view;w?.status==="closed"&&!Me()&&(l=w,ae())}).finally(()=>{Ie=null}),Ie)}function ae(){S?.destroy(),!I&&(I=!0,e.signal?.removeEventListener("abort",ae),a?.removeEventListener("abort",ae),W?.finish("dismissed"),ln.destroy(),xn(),Gn?.(),ve(),nn(),x.stop(),b.remove(),u.remove(),g(),ue(e.onDismiss,l?structuredClone(l):null))}D.onclick=()=>{if(!D.disabled){if(x.active){x.exit();return}Se(()=>e.client.submit({operation:"back",...be()}))}},k.onclick=()=>{x.open()},R.onclick=()=>{W?.active?W.dismiss():se||Pe()},H.onclick=()=>{Me()?Pe():Se(()=>e.client.retry())},b.addEventListener("cancel",t=>{t.preventDefault(),W?.active?W.dismiss():se||Pe()}),e.signal?.addEventListener("abort",ae,{once:!0}),a?.addEventListener("abort",ae,{once:!0});try{let t=e.client.view;if(t)((e.client.viewAgeMs??sn)>=sn||t.instruction?.type==="evaluate_segment")&&(Ke=Ze().finally(()=>{Ke=null})),await we(t);else{u.hidden=!0;let r=Ge(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(I||fe)throw new DOMException("Presentation cancelled","AbortError");let w=await r.wait(e.client.get(),Ae);an=!1,await we(e.client.view??w.run)}}catch(t){throw W?.finish("error",t),ae(),t}return{destroy:ae,refresh:Ze,get recovery(){let t=Xe();if(t)return t;if(!I&&!U&&!ge&&!se&&i){let r=i.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(se)return se;let t=Xe();if(t)return Promise.resolve(t);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,w=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let N=i?.recovery;return Promise.resolve(N&&N.type!=="native"&&N.type!=="cancel"?N:w())}let ie=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(N=>N.operation==="close");if(I&&!(ie||K&&e.client.view?.status==="closed")||U||Re||Ie||x.active||!i&&!K&&!ie)return Promise.resolve(w());let le=i,ee=(async()=>{try{if(!K&&ie){let P=await e.client.retry();return await we(e.client.view??P.run),w()}if(!K){let P=await le.prepareFallback();if(P.type!=="native")return P;if(e.client.hasDurableJournal!==!0)return w();K=P}let N=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(N.length){let P=N.find(z=>z.operation==="close");if(!P||!X||P.requestId!==X.requestId)return w();let Z=await e.client.retry();un(Z),await we(e.client.view??Z.run)}else{let P=e.client.view,Z=P?.paywall;if(!P||!Z||Z.selectionGeneration===void 0||(Z.quote?.operationId??null)!==K.operationId||K.operationId!==null&&Z.canReselect!==!0)return w();let z=Z.selectionGeneration,ne=await e.client.get();await we(e.client.view??ne.run);let V=e.client.view,re=V?.paywall;if(!V||!re||!["running","waiting"].includes(V.status)||V.stopped||V.id!==P.id||V.nodeId!==P.nodeId||V.visit!==P.visit||re.receiptId!==Z.receiptId||re.selectionGeneration!==z||(re.quote?.operationId??null)!==K.operationId||K.operationId!==null&&re.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return w();let te=be();X={runId:V.id,operationId:K.operationId,revision:te.revision,requestId:te.requestId,nodeId:V.nodeId,visit:V.visit,receiptId:re.receiptId,selectionGeneration:z,acknowledged:!1},await Pe(te)}let J=Xe();return J?(ae(),J):w()}catch(N){return de(N),w()}})();se=ee;let ye=()=>{se===ee&&(se=null)};return ee.then(ye,ye),ee},review:x.open,exitReview:x.exit,get unappliedDrafts(){return x.drafts}}}function Ht(n,y,f){return Bn(n,y,f)}export{jn as a,Hn as b,Bn as c,Ht as d};
|