@tinkerlandai/longplay-sdk 0.10.11 → 0.10.13
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 +13 -0
- package/README.md +2 -2
- package/README.zh-CN.md +1 -1
- package/dist/chunk-3JDJD4NY.js +1 -0
- package/dist/{chunk-GDFBOM3V.js → chunk-ADSQZ7T3.js} +1 -1
- package/dist/{chunk-ZYQPKGJM.js → chunk-AHDMDMHB.js} +1 -1
- package/dist/{chunk-4B5G3ZVV.js → chunk-AY3DAC2V.js} +1 -1
- package/dist/{chunk-7DUOIHRD.js → chunk-KQ4MS4LR.js} +1 -1
- package/dist/{chunk-CDG7GM4C.js → chunk-OBZSDWLC.js} +1 -1
- package/dist/{chunk-QHJAF5T2.js → chunk-RGWFBLW4.js} +1 -1
- package/dist/{chunk-4C5XH3T3.js → chunk-RK6UEQF2.js} +1 -1
- package/dist/{chunk-JGFAFQKK.js → chunk-VQBQAKJD.js} +1 -1
- package/dist/chunk-YT7TSF3I.js +1 -0
- package/dist/{content-YQ7IJ47M.js → content-6JUK2IAJ.js} +1 -1
- package/dist/funnel-runtime-host-X5AMUCP2.js +1 -0
- 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-KSTKKKEA.js +1 -0
- package/dist/react-native.js +1 -1
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-7RDYCTR4.js +0 -1
- package/dist/chunk-PYIHBK7E.js +0 -1
- package/dist/funnel-runtime-host-K2SXD2R2.js +0 -1
- package/dist/paywall-PJEMTVSZ.js +0 -1
package/dist/openrouter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-AHDMDMHB.js";import"./chunk-OBZSDWLC.js";import{a as i}from"./chunk-OZZMZH7X.js";import"./chunk-KQ4MS4LR.js";import"./chunk-VSJOHWDL.js";import{z as k}from"zod";var c=k.number().int().min(0).max(1e9);function R(e,o){let a=c.parse(e.promptTokens),p=c.parse(e.completionTokens),s=c.parse(e.promptTokensDetails?.cachedTokens??0),t=c.parse(e.promptTokensDetails?.cacheWriteTokens??0),r=c.parse(e.promptTokensDetails?.audioTokens??0),l=c.parse(e.completionTokensDetails?.audioTokens??0),n=c.parse(e.completionTokensDetails?.reasoningTokens??0);if(c.parse(e.totalTokens)!==a+p||s+t+r>a||n+l>p||(e.promptTokensDetails?.videoTokens??0)>0)throw new i("AI_USAGE_UNAVAILABLE","Token pools must conserve usage; video needs an explicit token mapper");return{input:a-s-t-r,output:p-l-(o==="separate"?n:0),cache_read:s,cache_write:t,input_audio:r,output_audio:l,reasoning:o==="separate"?n:0}}function I(e){if(!Number.isFinite(e)||e<0)throw new i("AI_USAGE_UNAVAILABLE","Provider cost must be a nonnegative USD amount");let o=String(e),a=o.includes("e")?e.toFixed(18).replace(/0+$/,"").replace(/\.$/,""):o;if(!/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/.test(a)||Number(a)!==e)throw new i("AI_USAGE_UNAVAILABLE","Provider cost exceeds the supported precision");return a}async function f(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning)||!e.modelId||!e.generationId)throw new i("INVALID_REQUEST","Actual model, generation ID and reasoning pricing are required");let o={context:e.context,generationId:e.generationId,modelId:`openrouter/${e.modelId}`,usage:e.usage,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let a=e.mapTokens?e.mapTokens(e.usage):R(e.usage,e.reasoning),p=e.usage.cost==null?void 0:I(e.usage.cost),s=e.quote??await e.pricing.quoteTokens({modelId:o.modelId,tokens:a});if(s.pricing.modelId!==o.modelId||Object.keys(a).some(l=>a[l]!==s.tokens[l]))throw new i("INVALID_REQUEST","Saved quote must match the provider model and token pools");await e.persist({...o,tokens:a,quote:s,phase:"quoted"});let t=await e.pricing.trackTokens(e.client,{...e.context,quote:s,providerCostUsd:p,generationId:e.generationId});if(!t.receipt.accepted)throw new i("AI_BALANCE_REJECTED","OpenRouter usage was saved but the balance request was rejected");let r={...o,tokens:a,quote:s,receipt:t,phase:"settled"};return await e.persist(r),r}function T(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning))throw new i("INVALID_REQUEST","Reasoning pricing is required");let o=e.openRouter.chat;async function a(t){if(!t.usage||!t.modelId||!t.generationId)throw new i("AI_USAGE_UNAVAILABLE","OpenRouter did not return final usage and the actual model");await f({...e,context:t.context,generationId:t.generationId,modelId:t.modelId.slice(11),usage:t.usage})}let p=async(t,r)=>{let n={context:await e.context(),generationId:null,modelId:null,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"},d;try{d=await o.send(t,r)}catch(g){throw await e.persist(n),g}if(!(d instanceof ReadableStream)){if(n={...n,generationId:d.id,modelId:d.model?`openrouter/${d.model}`:null,usage:d.usage??null},!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter omitted final accounting");return await a(n),d}let w=d.getReader(),m=!1;return new ReadableStream({async pull(g){try{let{value:u,done:A}=await w.read();if(A){if(m=!0,!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter stream ended without final accounting");await a(n),g.close();return}if(u.error)throw new i("AI_PROVIDER_ERROR",u.error.message);u.usage&&(n={...n,generationId:u.id,modelId:u.model?`openrouter/${u.model}`:null,usage:u.usage}),g.enqueue(u)}catch(u){m||(m=!0,await e.persist(n)),await w.cancel(u),g.error(u)}},async cancel(g){m||(m=!0,await e.persist(n)),await w.cancel(g)}})},s=new Proxy(o,{get(t,r){return r==="send"?p:Reflect.get(t,r,t)}});return new Proxy(e.openRouter,{get(t,r){return r==="chat"?s:Reflect.get(t,r,t)}})}export{T as createOpenRouterUsageClient,f as trackOpenRouterUsage};
|
package/dist/page.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as o,e as r,f as e,g as f}from"./chunk-
|
|
1
|
+
import{d as o,e as r,f as e,g as f}from"./chunk-AY3DAC2V.js";import"./chunk-RGWFBLW4.js";import"./chunk-DSPLGTQI.js";import"./chunk-RK6UEQF2.js";import"./chunk-KQ4MS4LR.js";import"./chunk-VSJOHWDL.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as ae}from"./chunk-SSLZKIIU.js";import{a as re}from"./chunk-MOWYD2TV.js";import"./chunk-OBZSDWLC.js";import{a as v}from"./chunk-OZZMZH7X.js";import{a as Y}from"./chunk-DSPLGTQI.js";import{R as M}from"./chunk-KQ4MS4LR.js";import{Aa as K,Ca as ne,Z as $,i as W,la as te}from"./chunk-VSJOHWDL.js";async function ie(y,a,l){if(a.status!=="complete")throw new v("INVALID_RESPONSE","A verified completed purchase is required");if(await l.onComplete?.(a),!y||!l.check)return;let k=$.parse(await l.check());if(k.internal_feature_id!==y.internal_feature_id||k.quantity!==y.quantity)throw new v("INVALID_RESPONSE","The access requirement changed");k.allowed&&await l.onAccessGranted?.(k)}function J(y,a){let l=structuredClone(y.capabilities),k=new Set(Object.entries(y.document.buttons).filter(([,t])=>t.type==="checkout"&&t.product.type==="fixed"&&!M(t.product,{},l)).map(([t])=>t));if(!k.size)return l;let V=t=>{let d=a.createElement("template");d.innerHTML=t;let r=!1;for(let f of d.content.querySelectorAll("button[data-grow-action]"))k.has(f.getAttribute("data-grow-action"))&&(f.disabled=!0,r=!0);return r?d.innerHTML:t};return te(y.document.screen,t=>{if(t.type==="custom_html"){let f=l.nodes[t.id],w=f?.base.html??t.html[y.document.screen.strings.defaultLocale]??"",U=V(w),R=f?.byPlan&&Object.fromEntries(Object.entries(f.byPlan).map(([g,c])=>[g,c.html===void 0?c:{...c,html:V(c.html)}]));(U!==w||R)&&(l.nodes[t.id]={...f,base:{...f?.base,...U!==w?{html:U}:{}},...R?{byPlan:R}:{}});return}let d=t.type==="button"?t.action:t.type==="stack"?t.purchaseAction:void 0;if(!d||!k.has(d))return;let r=l.nodes[t.id];l.nodes[t.id]={...r,base:{...r?.base,unavailable:!0},...r?.byPlan?{byPlan:Object.fromEntries(Object.entries(r.byPlan).map(([f,w])=>[f,{...w,unavailable:!0}]))}:{}}}),l}async function ve(y,a){let l=a.check?$.parse(await a.check()):null;if(l?.allowed)return await a.onAccessGranted?.(l),{check:l,host:null};let k=ae(y.ownerDocument),{mountScreenPreview:V}=await import("./screen-renderer-NHJ6OQTF.js"),t=await a.start(),d;try{let e=t.view??await t.refresh();if(!e)throw new v("INVALID_RESPONSE","Paywall presentation is missing");d=e}catch(e){throw t.destroy(),k(),e}let r=y.ownerDocument,f=new AbortController,w=r.createElement("section"),U=r.createElement("div"),R=r.createElement("div"),g=r.createElement("p"),c=r.createElement("button"),q=r.createElement("button"),h=r.createElement("dialog"),s=d.document.screen.strings.defaultLocale.startsWith("zh");w.dataset.indianaPaywall="",w.setAttribute("aria-label",d.document.name),w.style.cssText="width:100%;box-sizing:border-box;background:#fff;color:#172033;font:14px/1.5 system-ui,sans-serif",R.style.cssText="display:flex;gap:12px;padding:12px 20px;align-items:center;flex-wrap:wrap",g.setAttribute("role","status"),q.textContent=s?"\u5173\u95ED":"Close",c.textContent=s?"\u91CD\u8BD5":"Retry",c.hidden=!0,R.append(g,c,q),w.append(U,R);let _=d.document.presentation,D,b=!1,Q=!1,P=null,X=!1,E=()=>!X&&a.canInteract?.()!==!1,z=!1,o=null,L=null;function Z(e){t.quote||t.operation||(g.textContent=Object.values(e.capabilities.plans).some(n=>n.available)?"":s?"\u5F53\u524D\u8D26\u53F7\u6682\u65E0\u53EF\u8D2D\u4E70\u7684\u65B9\u6848\u3002":"No plans are currently available for this account.")}let j=new Map;async function B(e){if(!(!E()||!e.checkoutUrl||j.get(e.operationId)===e.checkoutUrl)){j.set(e.operationId,e.checkoutUrl);try{a.onCheckoutUrl?await a.onCheckoutUrl(e.checkoutUrl):r.defaultView?.location.assign(e.checkoutUrl)}catch(n){throw j.delete(e.operationId),n}}}let T=e=>{g.textContent=e instanceof Error?e.message:s?"\u8BF7\u6C42\u5931\u8D25":"Request failed",Y(a.onError,e),c.hidden=o===null};async function x(e){if(!(Q||b||!E())){Q=!0,c.hidden=!0,g.textContent="";try{await e()}catch(n){b||T(n)}finally{Q=!1}}}async function oe(e){await ie(l,e,a)}async function C(e){if(b)return;if(!E()){o=async()=>C(await t.read()),c.hidden=!1;return}if(g.textContent=e.status,e.problem){let i=e.problem;o=H,c.textContent=s?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",T(new v(i.code,i.reason==="RESULT_UNKNOWN"?s?"\u4ED8\u6B3E\u7ED3\u679C\u5C1A\u672A\u786E\u5B9A\uFF0C\u8BF7\u6062\u590D\u539F\u64CD\u4F5C\uFF0C\u6682\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"The payment result is unknown. Recover the original purchase before buying again.":i.phase==="fulfillment"?s?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":i.code==="CAPABILITY_UNAVAILABLE"?s?"\u5546\u6237\u5C1A\u4E0D\u652F\u6301\u672C\u6B21\u8D2D\u4E70\u6240\u9700\u7684\u5B8C\u6574\u80FD\u529B\uFF0C\u8BF7\u5904\u7406\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":i.code==="NOT_CONFIGURED"?s?"\u4ED8\u6B3E\u670D\u52A1\u8FDE\u63A5\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u8054\u7CFB\u5546\u6237\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":s?"\u539F\u8D2D\u4E70\u64CD\u4F5C\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u67E5\u8BE2\u6216\u6062\u590D\u6B64\u64CD\u4F5C\u3002":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,i));return}if(e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(g.textContent=s?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u6B63\u5728\u7B49\u5F85\u5546\u6237\u5B8C\u6210\u5904\u7406\u3002":"Payment was recorded. Waiting for merchant fulfillment."),e.status==="complete"){o=null,await oe(e);return}if(e.status!=="pending"){if(t.canReselect===!1){g.textContent=s?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",c.textContent=s?"\u67E5\u8BE2\u7ED3\u679C":"Check result",o=async()=>C(await t.read()),c.hidden=!1;return}c.textContent=s?"\u91CD\u8BD5":"Retry",o=null,P=null;return}await B(e);let n=Date.now()+6e5,m=2e3;for(;!b&&Date.now()<n;){if(await new Promise(p=>{let I=()=>{clearTimeout(A),p()},A=setTimeout(()=>{f.signal.removeEventListener("abort",I),p()},m);f.signal.addEventListener("abort",I,{once:!0})}),b)return;if(!E()){o=async()=>C(await t.read()),c.hidden=!1;return}let i=await t.read();if(!i.problem&&i.status==="pending"&&await B(i),i.status!=="pending"||i.problem){await C(i);return}m=Math.min(m*1.5,3e4)}o=async()=>C(await t.read()),c.hidden=!1}async function H(){L?.remove(),L=null,o=H;let e=await t.confirm();if(!E()){o=H,c.hidden=!1;return}if(e.problem){await C(e);return}if(e.status==="pending"){if(e.checkoutUrl)await B(e);else if(e.execution&&e.execution.provider!=="merchant"||e.nativePurchase){if(!a.onPurchase)throw new v("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:e,signal:f.signal})}}o=async()=>C(await t.read()),await C(e)}function se(e){L?.remove();let n=r.createElement("div"),m=r.createElement("button"),i=r.createElement("button"),p=r.createElement("p");p.textContent=e.lines.map(u=>u.productName).join(", ")+" \xB7 "+W(e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),e.currency),m.textContent=s?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",i.textContent=s?"\u53D6\u6D88":"Cancel",m.onclick=()=>{x(H)};let I=async()=>{let u=await t.cancel();b||(n.remove(),L=null,await C(u))};i.onclick=()=>{o=I,x(I)};let A=r.createElement("div");for(let u of e.lines){let ee=r.createElement("p");ee.textContent=`${u.productName} \xB7 ${W(u.catalogAmountMinor,e.currency)}${K(u.interval,s?"zh-CN":"en",u.intervalCount??1)}`,A.append(ee);for(let S of u.prepaid??[]){let G=r.createElement("p"),O=t.view?.capabilities.plans[u.productVersionId]?.prepaid?.find(ce=>ce.internalFeatureId===S.internal_feature_id);G.textContent=`${O?.name??S.internal_feature_id} \xB7 ${S.quantity} ${s?"\u4EFD":"packs"} \xD7 ${S.terms.units}`,O&&(G.textContent+=K(O.reset==="week"||O.reset==="month"||O.reset==="year"?O.reset:"one_time",s?"zh-CN":"en",O.resetCount)),A.append(G)}if(u.trial){let S=r.createElement("p");S.textContent=s?`\u8BD5\u7528 ${u.trial.days} \u5929\uFF1B${u.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${u.trial.days}; ${u.trial.cardRequired?"a payment method is required":"no payment method is required"}`,A.append(S)}}if(!e.charge){let u=r.createElement("p");u.textContent=s?"\u76EE\u5F55\u4EF7\u683C\uFF1B\u6700\u7EC8\u91D1\u989D\u4EE5\u7ED3\u8D26\u65F6\u7A0E\u8D39\u548C\u8BD5\u7528\u89C4\u5219\u4E3A\u51C6\u3002":"Catalog price; the final charge depends on checkout taxes and trial terms.",A.append(u)}n.append(p,A,m,i),R.prepend(n),n.scrollIntoView?.({block:"nearest"}),m.focus({preventScroll:!0}),L=n,o=null}async function F(){if(!P)return;if(o=F,!z){let n=t.view,m=n?.document.buttons[P.actionId],i=n&&m?.type==="checkout"?M(m.product,P.selection,n.capabilities):null;if(!i)throw new v("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let p=await a.resolveOfferId?.({actionId:P.actionId,productVersionId:i});if(b)return;p!==void 0&&(P.offerId=p),z=!0}if(!E()){c.hidden=!1;return}let e=await t.preview(P);b||se(e)}function N(e="destroy"){b||(b=!0,f.abort(),D?.destroy(),t.destroy(),h.open&&h.close(),h.remove(),w.remove(),k(),e==="dismiss"&&Y(a.onDismiss))}q.onclick=()=>{E()&&N("dismiss")},h.addEventListener("cancel",e=>{e.preventDefault(),E()&&N("dismiss")}),c.onclick=()=>{o&&x(o)};try{if(_.type==="inline")y.append(w);else{let n={sm:420,md:640,lg:900};h.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in _?n[_.size]+"px":"100vw"}`,h.setAttribute("aria-label",d.document.name),h.append(w),y.append(h),E()&&(h.showModal(),re(h,_.type))}D=V(U,{mode:"live",rendererUrl:t.webViewUrl,title:d.document.name,onAction(n,m={}){if(!E())return;let i=t.view,p=i?.document.buttons[n];if(!p)return;if(p.type==="close"){x(async()=>{await a.onAction?.(n),N(a.onAction?"action":"dismiss")});return}if(p.type==="action"){o=async()=>{if(p.action.type==="event"){if(!a.onEvent)throw new v("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(p.action.event)}else a.onOpenUrl?await a.onOpenUrl(p.action.url):r.defaultView?.location.assign(p.action.url);await a.onAction?.(n),o=null},x(o);return}if((t.quote||P)&&t.canReselect===!1){o=t.quote?async()=>C(await t.read()):F,x(o);return}let I=i&&M(p.product,m,i.capabilities);if(!i||!I){T(new v("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){o=null,x(async()=>{let A={actionId:n,productVersionId:I,selection:structuredClone(m),featureQuantities:ne(i.document.screen,I,m,i.capabilities)};await a.onPurchaseIntent(A)});return}if(P&&P.actionId!==n){T(new v("COMMAND_PENDING","Finish the current purchase"));return}P||(P={requestId:crypto.randomUUID(),actionId:n,selection:m},z=!1),x(F)},onEscape:()=>{E()&&N("dismiss")},onError:n=>T(new Error(n)),onRendered:n=>{n&&h.setAttribute("aria-label",n)}}),D.update(d.document.screen,d.document.screen.strings.defaultLocale,{capabilities:J(d,r),serverInput:{bindings:[],answers:{}}}),await D.ready,Z(d);let e=t.operation;e&&(e.confirmedAt||e.checkoutUrl||e.status==="complete")&&(o=async()=>C(await t.read()),x(o))}catch(e){throw N(),e}return{check:l,host:{setSuspended(e){X=e,w.hidden=e,e&&h.open?h.close():!e&&!b&&_.type!=="inline"&&!h.open&&h.showModal()},destroy:N,refresh:async()=>{if(!E()){if(t.view)return t.view;throw new v("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await t.refresh();return b||(D?.updateCapabilities(J(e,r)),Z(e)),e}}}}export{ve as showPaywall};
|
package/dist/react-native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as C,c as A,d as L}from"./chunk-
|
|
1
|
+
import{b as C,c as A,d as L}from"./chunk-ADSQZ7T3.js";import{b as O,l as R,m as E,n as x,p as M}from"./chunk-VQBQAKJD.js";import"./chunk-VSMITXQD.js";import"./chunk-OBZSDWLC.js";import{a as i}from"./chunk-OZZMZH7X.js";import"./chunk-DSPLGTQI.js";import"./chunk-RK6UEQF2.js";import{a as S,ua as P}from"./chunk-KQ4MS4LR.js";import"./chunk-VSJOHWDL.js";function k(t,d){let n,a=0,m=-1,l,r=!1,g=()=>{if(r)throw new i("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new i("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new i("IDENTITY_CHANGED","Customer identity changed during the native operation"),h=d.subscribeIdentity(()=>{a++,m=-1;let e=a;n&&t.nativeModule&&n.then(c=>t.nativeModule.reset(c,e)).catch(()=>{})}),I=t.nativeEvents?.(e=>{!n||!t.nativeModule||typeof e?.requestId!="string"||(async()=>{let c=await n;if(e.instanceId!==c)return;if(e.kind==="credential"){let w=a,y=null;try{if(!r&&e.revision===w){let N=await d.access();!r&&a===w&&(y=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,y)}return}let s=!1,u=a;try{if(r||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!r&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=g();if(d.snapshot()&&!t.nativeEvents)throw new i("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(r||a!==u)throw o();if(!n){let v=s.create(JSON.stringify({baseUrl:t.baseUrl??"https://api.longplayai.com",scope:t.scope,timeout:(t.timeoutMs??15e3)/1e3,credentialEvents:!!t.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let y=await n;if(r||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let b=(async()=>{if(await s.identify(y,JSON.stringify({revision:u,credentials:w})),r||a!==u)throw await s.reset(y,u),o();m=u})();l={epoch:u,task:b}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(y,e,JSON.stringify(c));if(r||a!==u)throw o();try{return JSON.parse(N)}catch{throw new i("INVALID_RESPONSE","Native host returned invalid JSON")}}async function f(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new i("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return f("showFunnel",{runToken:e})},showPaywall(e){return f("showPaywall",e)},showContent(e){return f("showContent",e)},purchaseSubscription(e,c){return p("purchaseSubscription",{operationId:e,accepted:c})},switchSubscription(e,c){return p("switchSubscription",{operationId:e,accepted:c})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(e){return p("manageSubscriptions",e?{productId:e}:{})},async dismiss(){a++,m=-1,n&&await g().reset(await n,a)},async destroy(){r||(r=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var J=P.trackUsage.request.shape.command,V=P.trackUsage.response;function T(t){let d=S.parse(t.scope),n=C({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,r=!1;n.subscribeIdentity(()=>{l++});let g=()=>{if(r)throw new i("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new i("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){r||(r=!0,l++,n.destroy(),await m.destroy())},funnel(){return A({...a,customerToken:g()})},resumeFunnel(o){return g(),R({...a,runToken:o})},paywall(o){return E(a,{...o,customerToken:g()})},async trackUsage(o){if(g(),!t.usageReporter)throw new i("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=J.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new i("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new i("IDENTITY_CHANGED","Customer identity changed during usage reporting");let f=V.parse(p);if(f.scope.projectId!==d.projectId||f.scope.environment!==d.environment)throw new i("INVALID_RESPONSE","Usage response scope differs");return f}}}export{i as LongplayError,x as createConfigurationSync,O as createFeatureClient,L as createFunnelProcess,M as createLocalFunnelClient,T as createLongplayReactNative};
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as wn}from"./chunk-PYIHBK7E.js";import{a as En,b as Rn,c as Cn,d as An}from"./chunk-ZYQPKGJM.js";import{a as p,b as ye,c as We,d as Xe,e as Ze,f as en,h as W,i as nn,j as U,k as D,m as tn,n as hn,o as vn,p as Sn}from"./chunk-JGFAFQKK.js";import"./chunk-VSMITXQD.js";import"./chunk-CDG7GM4C.js";import{a as o}from"./chunk-OZZMZH7X.js";import"./chunk-4C5XH3T3.js";import{$ as Me,A as J,B as Ce,E as ae,F as Ae,Fa as Be,G as Oe,Ga as le,H as ie,Ha as z,I as se,Ia as Ue,J as ce,Ja as Ge,Ka as Ve,La as me,Ma as He,N as ue,Na as qe,O as be,Oa as je,P as Pe,Pa as fe,Qa as Ke,Ra as Q,Sa as ze,T as Ne,Va as Qe,Wa as Ye,X as G,Y as ke,Z as de,_ as De,_a as Je,a as he,aa as $,ab as $e,ba as j,ca as Le,k as we,l as ve,m as te,o as Se,p as re,q as Ee,s as oe,u as Re,ua as i,va as pe,z as Y}from"./chunk-7DUOIHRD.js";import{B as Fe,E as _e,r as Te,xa as xe}from"./chunk-VSJOHWDL.js";function X(e){return{async getCustomer(t){let n=i.getCustomer;return p(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=i.listCustomers;return p(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=i.updateCustomer;return p(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=i.createGuestCustomer;return p(e,n,t)},async resumeGuestSession(t){let n=i.resumeGuestSession;return p(e,n,t)},async claimGuestCustomer(t){let n=i.claimGuestCustomer;return p(e,n,t)},async revokeCustomerSessions(t){let n=i.revokeSessions;return p(e,n,t)},async createCustomerSession(t){return p(e,i.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return p(e,i.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function f(e,t){try{return e.parse(t)}catch{throw new o("INVALID_RESPONSE","Invalid gateway response")}}function rn(e){return{async checkEntitlement(t){let n=i.checkEntitlement;return p(e,n,t,f)},async readHoldings(t){let n=i.readHoldings;return p(e,n,t,f)},async readSeats(t){let n=i.readSeats;return p(e,n,t,f)},async manageSeat(t){let n=i.manageSeat;return p(e,n,t,f)}}}function on(e){return{async readAiPricing(t){let n=i.readAiPricing;return p(e,n,t,f)},async readUsage(t){let n=i.readUsage;return p(e,n,t,f)},async setUsage(t){let n=i.setUsage;return p(e,n,t,f)},async manageBalanceGrant(t){let n=i.manageBalanceGrant;return p(e,n,t,f)},async readBalanceSource(t){let n=i.readBalanceSource;return p(e,n,t,f)},async adjustBalance(t){let n=i.adjustBalance;return p(e,n,t,f)},async listBalanceGrants(t){let n=i.listBalanceGrants;return p(e,n,t,f)},async manageBillingLimits(t){let n=i.manageBillingLimits;return p(e,n,t,f)},async manageUsageEntity(t){let n=i.manageUsageEntity;return p(e,n,t,f)},async readUsageAnalytics(t){let n=i.readUsageAnalytics;return p(e,n,t,f)},async readCreditAnalytics(t){let n=i.readCreditAnalytics;return p(e,n,t,f)},async submitUsageBatch(t){let n=i.submitUsageBatch;return p(e,n,t,f)},async readUsageBatch(t){let n=i.readUsageBatch;return p(e,n,t,f)},async readLedger(t){let n=i.readLedger;return p(e,n,t,f)},async readCreditStatement(t){let n=i.readCreditStatement;return p(e,n,t,f)},async quoteBalance(t){let n=i.quoteBalance;return p(e,n,t,f)},async trackUsage(t){let n=i.trackUsage;return p(e,n,t,f)},async mutateBalance(t){let n=i.mutateBalance;return p(e,n,t,f)}}}function an(e){return{async listInvoiceTemplates(t={}){let n=i.listInvoiceTemplates;return p(e,n,t,f)},async previewInvoice(t){let n=i.previewInvoice;return p(e,n,t,f)},async createInvoice(t){let n=i.createInvoice;return p(e,n,t,f)},async prepareBillingAdjustment(t){let n=i.prepareBillingAdjustment;return p(e,n,t,f)},async manageInvoice(t){let n=i.manageInvoice;return p(e,n,t,f)},async readInvoiceOperation(t){let n=i.readInvoiceOperation;return p(e,n,t,f)},async listInvoices(t){let n=i.listInvoices;return p(e,n,t,f)},async getInvoice(t){let n=i.getInvoice;return p(e,n,t,f)},async setupPayment(t){let n=i.setupPayment;return p(e,n,t,f)},async readPaymentSetup(t){let n=i.readPaymentSetup;return p(e,n,t,f)},async readBillingInvoice(t){let n=i.readBillingInvoice;return p(e,n,t,f)},async previewRefund(t){let n=i.previewRefund;return p(e,n,t,f)},async refund(t){let n=i.refund;return p(e,n,t,f)},async readRefund(t){let n=i.readRefund;return p(e,n,t,f)}}}function sn(e){return{async previewSubscriptionBatch(t){let n=i.previewSubscriptionBatch;return p(e,n,t,f)},async confirmSubscriptionBatch(t){let n=i.confirmSubscriptionBatch;return p(e,n,t,f)},async readSubscriptionBatch(t){let n=i.readSubscriptionBatch;return p(e,n,t,f)},async abandonSubscriptionBatch(t){let n=i.abandonSubscriptionBatch;return p(e,n,t,f)},async manageSubscriptionTrial(t){let n=i.manageSubscriptionTrial;return p(e,n,t,f)},async readSubscriptionTrial(t){let n=i.readSubscriptionTrial;return p(e,n,t,f)},async listSubscriptions(t){let n=i.listSubscriptions;return p(e,n,t,f)},async listPurchases(t){let n=i.listPurchases;return p(e,n,t,f)},async listSubscriptionConflicts(t){let n=i.listSubscriptionConflicts;return p(e,n,t,f)},async retrySubscriptionConflict(t){let n=i.retrySubscriptionConflict;return p(e,n,t,f)},async previewUpdate(t){let n=i.previewUpdate;return p(e,n,t,f)},async update(t){let n=i.update;return p(e,n,t,f)},async readSubscriptionUpdate(t){let n=i.readSubscriptionUpdate;return p(e,n,t,f)},async restoreNativePurchase(t){let n=i.restoreNativePurchase;return p(e,n,t,f)},async verifySubscriptions(t){let n=i.verifySubscriptions;return p(e,n,t,f)},async previewAttach(t){let n=i.previewAttach;return p(e,n,t,f)},async recordBillingEvent(t){let n=i.recordBillingEvent;return p(e,n,t,f)},async attach(t){let n=i.attach;return p(e,n,t,f)},async readSubscriptionOperation(t){let n=i.readSubscriptionOperation;return p(e,n,t,f)}}}function cn(e){return{async recordCouponRedemption(t){return p(e,i.recordCouponRedemption,t,{request:"Invalid Coupon redemption facts",parseResponse:f})},async grantOffer(t){let n=i.grantOffer;return p(e,{...n,request:n.request.refine(u=>!!u.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function un(e){return{...rn(e),...on(e),...an(e),...sn(e),...cn(e)}}function dn(e){return{async getFeatures(t={}){let n=i.getFeatures;return p(e,n,t,f)},async evaluateFeatures(t){let n=i.evaluateFeatures;return p(e,n,t,f)}}}function pn(e){return{async trackEvents(t){let n=i.trackEvents;return p(e,n,t,f)}}}function ln(e){return{async resolveContent(t){let n=i.resolveContent;return p(e,n,t,f)},async resolvePaywall(t){let n=i.resolvePaywall;return p(e,n,t,f)},async resolveOffering(t){let n=i.resolveOffering;return p(e,n,t,f)}}}function On(e){U(e.apiKey,"Secret API keys must stay on your backend");let n=D(e).request;return{async sendMessage(u){let a=i.sendMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},async readMessage(u){let a=i.readMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},...X(n),...un(n),...dn(n),...pn(n),...ln(n)}}function Ie(){if(typeof window<"u")throw new o("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var mn=()=>new o("CONFLICT","Process synchronization is in progress",425),M=()=>new o("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),Tn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Z=class extends o{constructor(n){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:n.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=n}result};function Fn(e){if(U(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new o("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let t=D(e),n=X(t.request),u=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function a(m){let r=await e.resolveUser(m);if(r!==null&&(typeof r?.externalUserId!="string"||!r.externalUserId||r.externalUserId!==r.externalUserId.trim()||r.externalUserId.startsWith("gg_guest_")))throw new o("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return r}async function c(m){let r=await e.resolveContext(m);if(r?.confirmed!==!0||!r.processKey||!r.guestKey)throw new o("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:u+"run:"+r.processKey,guest:u+"guest:"+r.guestKey}}async function d(m,r){for(let y=0;y<8;y++){let h=await e.store.read(m),I=r(h?structuredClone(h.value):null);if(h&&Tn(h.value,I)||await e.store.compareAndSwap(m,h?.revision??null,I))return I}throw mn()}async function l(m){let r=await e.store.read(m);if(!r)throw new o("NOT_FOUND","Open the process before continuing",404);return r.value}async function s(m){let r=await l(m);for(let y of r.revocations??[])await n.revokeCustomerSessions(y),await d(m,h=>{if(!h)throw M();return h.revocations=h.revocations?.filter(I=>I.sessionId!==y.sessionId),h})}async function g(m,r){let y=le.parse(m);return r?t.requestWithCredential("funnel-processes",y,r):t.request("funnel-processes",y)}function w(m,r){if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment||m.run&&(m.run.id!==r.run.id||m.run.source.versionId!==r.run.source.versionId||m.run.source.id!==r.run.source.id||m.run.runExpiresAt!==r.run.runExpiresAt||m.run.identity.startedAs!==r.run.identity.startedAs||m.run.identity.participantId!==r.run.identity.participantId||m.run.identity.binding&&m.run.identity.binding.id!==r.run.identity.binding?.id)||m.runToken&&r.runToken&&m.runToken!==r.runToken)throw new o("INVALID_RESPONSE","Process identity or Run changed")}async function E(m,r,y){return d(m,h=>{if(!h)throw new o("NOT_FOUND","Process handle is missing",404);return w(h,r),(!h.run||r.run.revision>=h.run.revision)&&(h.run=r.run),h.runToken??=r.runToken,y!==void 0&&(h.target=y),h})}async function S(m,r){if(r.detached)throw new o("UNAUTHENTICATED","The process is detached",401);let y=r.run?.identity.binding?.customerId??r.run?.identity.participantId;if(!y)throw new o("INVALID_RESPONSE","Process participant is missing");if(r.session?.customerId===y&&Date.parse(r.session.expiresAt)>Date.now()+3e4)return r.session;let h={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},I=await d(m,A=>{if(!A||A.detached||A.run?.id!==r.run?.id)throw M();if(A.sessionLease&&A.sessionLease.until>Date.now())throw mn();return A.sessionLease=h,A}),C;try{if(I.session?.customerId===y&&Date.parse(I.session.refreshExpiresAt)>Date.now())try{if(C=Se.parse(await t.requestWithCredential("customer-sessions/refresh",{},I.session.refreshToken)),C.sessionId!==I.session.sessionId)throw new o("INVALID_RESPONSE","Refresh changed the logical session")}catch(b){if(!(b instanceof o)||b.status!==401)throw b}if(C??=I.run?.identity.binding?await n.createCustomerSession(y):await n.resumeGuestSession({guestToken:I.guest.token}),C.customerId!==y)throw new o("INVALID_RESPONSE","Session Customer changed");let A=C;return await d(m,b=>{if(!b||b.detached||b.sessionLease?.id!==h.id||b.run?.identity.binding?.id!==r.run?.identity.binding?.id)throw new o("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return b.session=A,delete b.sessionLease,b}),C}catch(A){throw C&&C.sessionId!==I.session?.sessionId&&await n.revokeCustomerSessions({customerId:C.customerId,sessionId:C.sessionId}).catch(()=>{}),await d(m,b=>{if(!b)throw M();return b.sessionLease?.id===h.id&&delete b.sessionLease,b}).catch(()=>{}),A}}let R;async function O(){if(R??=He.parse(await g({contract:G,operation:"describe"})),R.scope.projectId!==e.scope.projectId||R.scope.environment!==e.scope.environment)throw M();return R}async function v(m,r,y=!1){let h=await a(m),I=await l(r);if(I.issuingKeyId!==(await O()).keyId)throw new o("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!I.runToken||!I.run)throw new o("CONFLICT","Recover the original start first",425);if(I.detached){if(!y)throw new o("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(I.run.identity.binding&&(!h||I.target&&I.target!==h.externalUserId))throw M();await s(r),I=await d(r,C=>{if(!C||C.run?.id!==I.run?.id)throw M();return delete C.detached,C})}if(!I.runToken||!I.run)throw new o("INVALID_RESPONSE","Process identity is missing");if(I.run.identity.binding){if(h&&!I.target){let C=me.parse(await g({contract:G,operation:"binding_status",runToken:I.runToken,requestId:I.bindingIntent?.requestId??I.start.requestId,externalUserId:h.externalUserId}));if(C.state!=="bound"||C.binding.id!==I.run.identity.binding.id)throw M();I=await d(r,A=>{if(!A)throw M();return A.target=h.externalUserId,A})}if(!h||I.target!==h.externalUserId)throw M()}else if(h){if(!I.guest)throw M();I=await d(r,A=>{if(!A||A.bindingIntent&&A.bindingIntent.externalUserId!==h.externalUserId)throw M();return A.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:h.externalUserId},A});let C=I.bindingIntent;try{let A=Ve.parse(await g({contract:G,operation:"bind_customer",...C,runToken:I.runToken,guestToken:I.guest.token,claimRequestId:I.guest.claimRequestId,expectedBindingId:null}));I=await E(r,A,h.externalUserId)}catch(A){let b=me.parse(await g({contract:G,operation:"binding_status",...C,runToken:I.runToken,guestToken:I.guest.token}));if(b.state!=="bound")throw A;I=await d(r,x=>{if(!x?.run||x.run.id!==b.binding.runId)throw M();return x.run.identity.binding={id:b.binding.id,customerId:b.binding.customerId,acceptedAt:b.binding.acceptedAt},x.target=h.externalUserId,x})}}return{state:I,session:await S(r,I)}}async function k(m,r,y,h){try{return await h(y)}catch(I){if(!(I instanceof o)||I.status!==401)throw I;return await d(r,C=>{if(!C||C.detached)throw I;return C.session?.accessToken===y.session.accessToken&&(C.session.expiresAt=new Date(0).toISOString()),C}),h(await v(m,r))}}async function L(m,r,y=!1){let h=await c(m),I=await v(m,h.process,y),C=z.parse(await k(m,h.process,I,A=>g({...r,customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C}return{async open(m,r){r=Ge.parse(r);let y=await c(m),h=await O(),I=y.guest+":"+h.keyId,C=await e.store.read(y.process);if(!C){let P=await a(m),T,_,N;if(P)T={type:"customer",customer:{type:"externalUserId",value:P.externalUserId}};else{let V=await e.store.read(I);if(V)try{N=await n.resumeGuestSession({guestToken:V.value.token}),_=V.value}catch(B){if(!(B instanceof o)||B.status!==401)throw B}let H={token:Ie(),claimRequestId:crypto.randomUUID()};_=await d(I,B=>_??(B&&B.token!==V?.value.token?B:H)),T={type:"guest",guestToken:_.token}}await d(y.process,V=>V??{issuingKeyId:h.keyId,start:le.parse({...r,contract:G,requestId:crypto.randomUUID(),source:T}),..._?{guest:_}:{},...P?{target:P.externalUserId}:{},...N?{session:N}:{}}),C=await e.store.read(y.process)}let A=C.value;if(A.issuingKeyId!==h.keyId)throw new o("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(A.start.funnelId!==r.funnelId||A.start.operation!==r.operation)throw new o("CONFLICT","This handle already owns another process",409);if(!A.runToken){if(A.start.source.type==="customer"){let N=await a(m);if(!N||N.externalUserId!==A.target)throw M()}let P=await g(A.start),T=Ue.safeParse(P);if(T.success)throw new Z(T.data);let _=z.parse(P);if(!_.runToken)throw new o("INVALID_RESPONSE","Process credential is missing");A=await E(y.process,_)}let b=await v(m,y.process,!0),x=z.parse(await k(m,y.process,b,P=>g({contract:G,operation:"get",customerToken:P.session.accessToken},P.state.runToken)));return await E(y.process,x),{...x,runToken:A.runToken}},async syncIdentity(m){return L(m,{contract:G,operation:"get",customerToken:""},!0)},async get(m,r={}){return L(m,{...r,contract:G,operation:"get",customerToken:""})},async review(m,r){return L(m,{contract:G,operation:"review",customerToken:"",...r?{receiptId:r}:{}})},async command(m,r,y){let h=await c(m),I=await v(m,h.process),C=z.parse(await k(m,h.process,I,A=>g({contract:G,operation:"command",command:r,identity:{bindingId:y},customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C},async pageExperiments(m,r,y=[]){let h=await c(m),I=await v(m,h.process);return Be.parse(await k(m,h.process,I,C=>g({contract:G,operation:"page_experiments",release:r,usedReceiptIds:y,customerToken:C.session.accessToken},C.state.runToken)))},async detach(m){let r=await c(m);await d(r.process,y=>{if(!y)throw M();return y.session&&!y.revocations?.some(h=>h.sessionId===y.session.sessionId)&&(y.revocations??=[]).push({customerId:y.session.customerId,sessionId:y.session.sessionId}),y.detached=!0,delete y.session,delete y.sessionLease,y}),await s(r.process)},destroy(){t.dispose()}}}async function _n(e,t){U(e.apiKey,"Renewal requires your backend");let n=D(e),u=je.parse(We(e,await n.request("funnels",qe.parse({...t,operation:"renew_run"}))));if(u.run.id!==t.runId)throw new o("INVALID_RESPONSE","Run renewal identity changed");return u}function fn(e){let t=Ze(e),n=l=>{throw new o("INVALID_RESPONSE",l)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let u=new Set(["entry","condition","feature","split","end","output"]);for(let l of t.nodes.values()){if(!u.has(l.type))throw new o("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(l.type==="entry"&&l.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(l.type)&&!l.outputs.next&&n("Local next exit is unavailable"),l.type==="feature"){let s=l.resources.featureKey;(!s||!Object.hasOwn(e.evaluation.variables,l.writes.value)||!Object.hasOwn(t.features,s))&&n("Local Feature definition or declaration is unavailable")}if(l.type==="condition"){let s=e.conditions[l.id];(!s||!l.outputs.default||s.some((g,w)=>g.port!==`case:${w}`||!l.outputs[g.port]))&&n("Local Condition exits are unavailable")}if(l.type==="split"&&(!l.resources.experimentId||!Object.hasOwn(e.growth.experiments,l.resources.experimentId)||!l.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),l.type==="end"||l.type==="output"){let s=e.evaluation.terminals[l.id];if(!s)throw new o("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(l.outputs).length&&n("A terminal cannot have outgoing edges"),s.output?.type==="feature"&&!Object.hasOwn(t.features,s.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let s of Object.values(l.outputs))t.nodes.has(s)||n("Local target is unavailable")}let a=new Set,c=new Set;function d(l){if(c.has(l)&&n("Local graph contains a cycle"),!a.has(l)){c.add(l);for(let s of Object.values(t.nodes.get(l).outputs))d(s);c.delete(l),a.add(l)}}return d(e.topology.entry),a.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(l){let s={},g=l.context;g.features=t.features,g.savedGroups=t.savedGroups;let w=()=>{g.attributes=ke({declarations:e.evaluation.variables,attributes:l.attributes,parameters:l.parameters,answers:{},results:s,savedGroups:t.savedGroups})};w();let E=e.topology.entry,S=0;for(;;){let R=t.nodes.get(E);if(R.type==="end"||R.type==="output"){let O=e.evaluation.terminals[E],v=O.output,k=v?.type==="feature"?t.feature(v.featureKey,g):v?.type==="variable"?Pe({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:e.evaluation.variables,answers:{},results:s,parameters:l.parameters,attributes:l.attributes,savedGroups:t.savedGroups}):v?.value??null;return ue(e.evaluation.outputSchema,k)||n("Local output does not match its declaration"),{outcome:O.outcome,value:k}}if(S++>=e.evaluation.maxTransitions)throw new o("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(R.type==="entry")E=R.outputs.next;else{let O=t.evaluate(E,g);if(R.type==="feature"){let v=R.writes.value,k=O.value??null;ue(e.evaluation.variables[v],k)||n("Local Feature value does not match its declaration"),be(e.evaluation.variables,{writes:R.writes},{[v]:k}),s[v]=k,w()}E=O.target}}}}}import{z as yn}from"zod";function In(e,t,n){let u=Fe.parse(e.attributes);if(["parameters","answers","results"].some(m=>Object.hasOwn(u,m)))throw new o("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let a=xe.parse(e.parameters??{}),c=yn.record(yn.string(),_e).parse(e.stickyBucketAssignmentDocs??{});for(let[m,r]of Object.entries(c))if(m!==`${r.attributeName}||${r.attributeValue}`||!Object.hasOwn(u,r.attributeName)||Te(u[r.attributeName])!==r.attributeValue)throw new o("INVALID_REQUEST","Sticky document identity does not match this session");let d=e.saveStickyBucketAssignmentDoc,l=e.onFeatureUsage,s=e.onExperimentViewed,g=e.onError,w=new Map,E=new Set,S={},R=Promise.resolve();function O(m){let r=R.then(()=>(n(),m()));return R=r.catch(()=>{}),r}function v(m){try{g?.(m)}catch{}}function k(m){try{let r=m();r&&typeof r.catch=="function"&&r.catch(v)}catch(r){v(r)}}async function L(){for(let[m,r]of w){if(n(),d)try{await d(structuredClone(r))}catch{throw new o("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),w.delete(m)}}return{evaluate(m={}){let r=m.track===!0;return O(async()=>{let y=await t();n(y);let h=new Set(E),I={...S},C=new Map,A=[],b={stickyBucketAssignmentDocs:structuredClone(c),saveStickyBucketAssignmentDoc(T){C.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...r?{trackedExperiments:h,trackedFeatureUsage:I,onExperimentViewed(T,_){let N=structuredClone(T),V=structuredClone(_);s&&A.push(()=>s(structuredClone(N),structuredClone(V)))},onFeatureUsage(T,_){let N=structuredClone(_);l&&A.push(()=>l(T,structuredClone(N)))}}:{}},x=y.program.evaluate({attributes:u,parameters:a,context:b});n(y);for(let[T,_]of C)c[T]=_,w.set(T,_);await L(),n(y),r&&(E=h,S=I);for(let T of A)k(T);let P=y.configuration;return structuredClone({evaluationMode:"local",scope:P.scope,funnelId:P.funnelId,versionId:P.versionId,evaluationRevision:P.evaluationRevision,generation:P.growth.generation,...x})})},flush:()=>O(L),get stickyBucketAssignmentDocs(){return n(),structuredClone(c)}}}var bn=6e4;function ee(e){if(typeof window<"u")throw new o("SERVER_ONLY","Local Funnel sessions run on your backend");let t=he.parse(e.scope),n=e.funnelId,u=e.load,a,c,d,l=0,s=E=>Date.now()>=E.expiresAt;async function g(){if(c)return c;let E=l;a=void 0;let S=(async()=>{let R=await u();if(E!==l)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&typeof R=="object"&&"evaluationMode"in R&&R.evaluationMode==="remote")throw f(Q,R),new o("EVALUATION_MODE","This Funnel requires remote decide");let O=f(ze,R);if(E!==l)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(O.scope.projectId!==t.projectId||O.scope.environment!==t.environment||O.funnelId!==n)throw new o("SCOPE_MISMATCH","Local configuration scope changed");if(O.growth.scope.projectId!==t.projectId||O.growth.scope.environment!==t.environment||O.growth.expiresAt!==O.expiresAt)throw new o("INVALID_RESPONSE","GB configuration scope or expiry changed");let v=Math.min(Date.now()+bn,O.expiresAt?Date.parse(O.expiresAt):1/0);if(Date.now()>=v)throw new o("CONFIGURATION_EXPIRED","Refresh expired local rules");let k=JSON.stringify([t.projectId,t.environment,n,O.versionId,O.evaluationRevision,O.growth.generation]),L=[O.topology,O.conditions,O.evaluation,O.growth.features,O.growth.experiments,O.growth.savedGroups];if(d?.key===k&&!nn(d.body,L))throw new o("INVALID_RESPONSE","Immutable local configuration identity changed");return d?.key!==k&&(d={key:k,body:L,program:fn(O)}),a={key:k,configuration:O,expiresAt:v,program:d.program},a})();c=S;try{return await S}finally{c===S&&(c=void 0)}}function w(){return c??(a&&!s(a)?Promise.resolve(a):g())}return{session(E){let S=l;return In(E,w,R=>{if(e.assertUsable?.(),S!==l)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&(s(R)||a?.key!==R.key))throw new o("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await g()).configuration)},reset(){l++,a=void 0,c=void 0,d=void 0}}}function Pn(e,t){let n=e.snapshot?.generation,u=ee({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),a=e.subscribe(()=>{let d=e.snapshot?.generation;e.fresh&&d!==n&&(n=d,u.refresh().catch(()=>{}))}),c=u.session;return Object.assign(u,{session(d){let l=c(d),s=l.evaluate;return Object.assign(l,{async evaluate(...g){return e.fresh||await e.refresh(),s(...g)}})},destroy(){a(),u.reset()}})}function Nn(e){if(typeof window<"u")throw new o("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>tn(e,t)}}var K=class extends o{constructor(n,u){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,u);this.decisionId=n;this.decisionRequestId=u}decisionId;decisionRequestId};async function ne(e,t,n,u){let{decisionId:a,requestId:c}=e,d=e,l=250,s=0;for(;;){if(d.decisionId!==a||d.requestId!==c||d.decision&&!W(d.decision,t))throw new o("INVALID_RESPONSE","Decision request or customer changed");if(d.decision)return d.decision;if(d.status==="failed")throw new o("DECISION_FAILED","Decision execution failed",503,c);if(Date.now()>=n)throw new K(a,c);if(await new Promise(g=>setTimeout(g,Math.min(Math.max(l,s-Date.now()),n-Date.now()))),Date.now()>=n)throw new K(a,c);l=Math.min(1e3,l*2);try{d=await u(a,n)}catch(g){if(g instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(g.code)){s=Date.now()+(g.retryAfterSeconds??0)*1e3;continue}throw g}}}function ge(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Funnel decisions are requested by your backend");let t,n,u=new Map;async function a(s,g){let w=s;w.status!=="pending"&&u.delete(w.decisionId);for(let E=0;E<32&&w.evaluation;E++){let S=w.evaluation;if(S.runId!==w.decisionId)throw new o("INVALID_RESPONSE","Local evaluation Run changed");let R=u.get(w.decisionId);if(!R&&S.type==="evaluate_segment"){let v=$e.parse(await c({operation:"segment_configuration",funnelId:e.funnelId,versionId:S.versionId},g));if(v.configuration.scope.projectId!==e.scope.projectId||v.configuration.scope.environment!==e.scope.environment||v.configuration.funnelId!==e.funnelId||v.configuration.versionId!==S.versionId||v.configuration.evaluationRevision!==S.policyRevision)throw new o("SCOPE_MISMATCH","Original decision segment configuration changed");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding decisions first");R={operation:"commit_decision_segment",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,policyRevision:S.policyRevision,generation:v.configuration.growth.generation,...en(v.configuration,v.document,S)},u.set(w.decisionId,R)}if(!R){if(S.type!=="evaluate")throw new o("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=Q.parse(await c({operation:"configuration",funnelId:e.funnelId,versionId:S.versionId},g))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision)throw new o("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding Local decisions first");R={operation:"evaluate_decision",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,"evaluation"),nodeId:S.nodeId,visit:S.visit,revision:S.revision,receiptId:S.receiptId,policyRevision:S.policyRevision,generation:n.growth.generation,result:Je(n,S.nodeId,S,Xe)},u.set(w.decisionId,R)}let O=j.parse(await c(R,g));if(O.decisionId!==s.decisionId||O.requestId!==s.requestId)throw new o("INVALID_RESPONSE","Decision identity changed during local evaluation");u.delete(w.decisionId),w=O}return w}async function c(s,g,w=!1){return D({...e,fetch:(S,R)=>{let O=new Headers(R?.headers);return O.set("Accept-Encoding","identity"),w&&O.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(S,{...R,headers:O})},timeoutMs:Math.min(e.timeoutMs??1e4,g?Math.max(1,g-Date.now()):12e4)}).request("funnels",s)}async function d(s,g){let w=j.parse(await c($.parse({operation:"read_decision",decisionId:s}),g));if(w.decisionId!==s)throw new o("INVALID_RESPONSE","Decision identity changed");return a(w,g)}async function l(s,g,w=!1){let E=$.options[0].parse({...s,operation:"decide",funnelId:e.funnelId}),S;try{S=j.parse(await c(E,g,w))}catch(R){throw R instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(R.code)?new o("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",R.status,s.requestId):R}if(S.requestId!==s.requestId||S.decision&&!W(S.decision,E.customer))throw new o("INVALID_RESPONSE","Decision request or customer changed");return{response:await a(S,g),customer:E.customer}}return{local(){return t??=ee({scope:e.scope,funnelId:e.funnelId,load:()=>c({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let s=Q.parse(await c({operation:"configuration",funnelId:e.funnelId}));if(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment||s.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Configuration scope changed");return s},features(s={}){return ye({...s,scope:e.scope,load:async()=>Ne.parse(await c({operation:"feature_config",funnelId:e.funnelId}))})},read:s=>d(s),async submit(s){return(await l(s,void 0,!0)).response},async decide(s){let g=Date.now()+3e4,w=await l(s,g);return ne(w.response,w.customer,g,d)},async reportUsed(s){let g=Le.parse(await c($.parse({...s,operation:"report_used"})));if(g.decisionId!==s.decisionId||g.eventId!==s.eventId)throw new o("INVALID_RESPONSE","Usage receipt identity changed");return g}}}function kn(e){U(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let u=Qe.parse(n);if(u.orderId!==u.receiptId)throw new o("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let a=u.nativeEvidence,c={requestId:u.requestId,customerToken:u.customerToken,purchaseIntentId:u.orderId,...a===null?{intent:"read"}:a.provider==="apple"?{provider:"apple",signedTransaction:a.signedTransaction}:{provider:"google",purchaseToken:a.purchaseToken}},d=i.restoreNativePurchase.response.parse(await t.request(i.restoreNativePurchase.path,c));if(d.operation.requestId!==u.requestId||d.operation.purchaseIntentId!==u.orderId)throw new o("INVALID_RESPONSE","Native receipt request identity changed");let l=Ye.parse({scope:d.scope,requestId:u.requestId,orderId:d.operation.orderId,receiptId:d.operation.orderId,orderStatus:d.operation.status,refunded:d.operation.refunded,...d.operation.completion===null?{}:{nativeCompletion:{orderId:d.operation.orderId,receiptId:d.operation.orderId,...d.operation.completion}}});if(l.requestId!==u.requestId||l.orderId!==u.orderId||l.receiptId!==u.receiptId||l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Current order receipt scope changed");return l}}}import{z as xn}from"zod";var q=xn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function Dn(e,t){let n=q.parse(e.inputTokens.total),u=q.parse(e.outputTokens.total),a=q.parse(e.inputTokens.cacheRead??0),c=q.parse(e.inputTokens.cacheWrite??0),d=q.parse(e.outputTokens.reasoning??0);if(a+c>n||d>u||e.inputTokens.noCache!==void 0&&q.parse(e.inputTokens.noCache)!==n-a-c||e.outputTokens.text!==void 0&&q.parse(e.outputTokens.text)!==u-d)throw new o("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-a-c,cache_read:a,cache_write:c,output:t==="output"?u:u-d,reasoning:t==="separate"?d:0,input_audio:0,output_audio:0}}function Mn(e){if(typeof window<"u")throw new o("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new o("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(u){await e.persist({context:u,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(u,a){let c={context:u,modelId:e.modelId,usage:a,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(c);let d=e.mapTokens?e.mapTokens(a):Dn(a,e.reasoning),l=await e.pricing.quoteTokens({modelId:e.modelId,tokens:d});await e.persist({...c,tokens:d,quote:l,phase:"quoted"});let s=await e.pricing.trackTokens(e.client,{...u,quote:l});if(!s.receipt.accepted)throw new o("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...c,tokens:d,quote:l,receipt:s,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:u}){let a=await e.context(),c;try{c=await u()}catch(d){throw await t(a),d}return await n(a,c.usage),c},async wrapStream({doStream:u}){let a=await e.context(),c;try{c=await u()}catch(w){throw await t(a),w}let d=!1,l=!1,s=c.stream.getReader();async function g(){d||l||(l=!0,await t(a))}return{...c,stream:new ReadableStream({async pull(w){try{let{value:E,done:S}=await s.read();if(S){if(!d)throw await g(),new o("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");w.close();return}if(E.type==="finish"){if(d)throw new o("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");d=!0,await n(a,E.usage)}w.enqueue(E)}catch(E){try{await g()}finally{w.error(E),await s.cancel(E)}}},async cancel(w){try{await g()}finally{await s.cancel(w)}}})}}}}function Ln(e){U(e.apiKey,"Funnel receipts are sent by your backend");let t=D(e);return{async signal(n){let u=de.parse({...n,operation:"signal"}),a=De.parse(await t.request("funnels",u));if(a.runId!==n.runId||a.eventId!==n.eventId||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Receipt identity changed");return a},async readResults(n){let u=de.parse({operation:"read_results",runId:n}),a=Me.parse(await t.request("funnels",u));if(a.runId!==n||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Result identity changed");return a}}}function Bn(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Campaign entry requires your backend");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let u=Date.now()+(e.timeoutMs??3e4),a=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),c=D({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,u-Date.now()))}),d=j.parse(await c.request("funnels",a));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");return ne(d,a.customer,u,(l,s)=>ge({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,s-Date.now()))}).read(l))},async start(n){let u=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),a=Ke.parse(await t.request("funnels",u));if(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in a)&&(a.run.source.id!==e.funnelId||!a.customerId||u.customer.type==="id"&&a.customerId!==u.customer.value))throw new o("INVALID_RESPONSE","Campaign Funnel or Customer changed");return a}}}import{z as Un}from"zod";var F=class extends Error{constructor(n,u=409,a=!1,c="fix_request"){super(n);this.code=n;this.status=u;this.retryable=a;this.recovery=c}code;status;retryable;recovery};function Gn(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=Re.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},u=t.capabilities.some(a=>["purchases","subscription_changes","refunds","operation_status"].includes(a));for(let[a,c]of Object.entries(oe))if(c.command&&t.capabilities.includes(a)&&!(a==="catalog"&&t.catalog==="static")&&!e.handlers[c.command])throw new Error(`Missing merchant command handler: ${c.command}`);if(u&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!t.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(c){let d=crypto.randomUUID(),l="bridge.ping",s,g=async(w,E,S=!1)=>{let R=JSON.stringify({bridgeVersion:re,requestId:d,command:l,scope:n,[S?"error":"data"]:w});if(new TextEncoder().encode(R).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(R,{status:E,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":d,...s?await se(R,s,"response"):{}}})};try{if(c.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(re)||c.method!=="POST"||new URL(c.url).pathname!==Ee)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(c.headers.get("Content-Type")??""))throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let w=c.body?.getReader();if(!w)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=new TextDecoder("utf-8",{fatal:!0}),S="",R=0;try{for(;;){let _=await w.read();if(_.done)break;if(R+=_.value.byteLength,R>16384)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",413);S+=E.decode(_.value,{stream:!0})}S+=E.decode()}finally{await w.cancel().catch(()=>{}),w.releaseLock()}let O=Oe.safeParse(JSON.parse(S));if(!O.success)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let v=O.data;if(d=v.requestId,l=v.command,Object.keys(n).some(_=>v.scope[_]!==n[_]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let k=v.command==="bridge.ping"||v.command==="bridge.describe",L=v.command==="catalog.read";if((k||L||c.headers.has(ie))&&(s=e.authentication.find(_=>_.keyId===c.headers.get(ie)),!s||!await ce(S,c.headers,s,"request")))throw s=void 0,new F("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(v.command==="bridge.ping")return g(ae["bridge.ping"].parse(v.data),200);if(v.command==="bridge.describe")return g(t,200);let m=Object.entries(oe).find(([,_])=>_.command===v.command);if(!m||!t.capabilities.includes(m[0]))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let r=e.handlers[v.command];if(!r)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!L&&c.headers.has("Cookie")&&(c.headers.get("Origin")!==new URL(c.url).origin||["cross-site","same-site"].includes(c.headers.get("Sec-Fetch-Site")??"")))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);let y=L?{kind:"service"}:await e.authorize(c,v),h=y.kind,I=["purchase.execute","subscription.change","refund.execute"].includes(v.command),C=I||v.command==="operation.read";if(!(C&&s!==void 0&&h==="service")&&(v.command==="refund.execute"?h!=="administrator":!L&&h!=="user"))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);if(y.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(v.command)&&!Un.uuid().safeParse(y.customerId).success)throw new F("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let b=r,x=ae[v.command].parse(v.data),P={request:c,command:v.command,scope:n,principal:y},T;if(C){let _=Y.parse(x);if(y.kind==="user"&&y.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let N=J.parse(await e.resolveOperationAuthority(_,P));if(N.operationId!==_.operationId||N.customerId!==_.customerId||Object.keys(n).some(H=>N.scope[H]!==n[H]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);P.authority=N;let V=v.command==="purchase.execute"?"purchase":v.command==="subscription.change"?"subscription_change":v.command==="refund.execute"?"refund":N.instruction.type;if(N.instruction.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!I)T=te.parse(await b(x,P));else{if(N.confirmedAt===null)throw new F("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let H=te.parse(await e.handlers["operation.read"](_,{...P,command:"operation.read"}));if(H.operationId!==_.operationId||H.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(H.lookup==="found")T=H.execution;else{if(!N.initialExecutionAllowed)throw new F("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(N.instruction.expiresAt)<=Date.now())throw new F("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||ve(N.instruction).some(B=>!t.billingEvents.some(gn=>gn===B))||we(N.instruction).some(B=>!t.profiles.includes(B)))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=Ce.parse(await b(x,P))}catch(B){throw B instanceof F?B:new F("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=Ae[v.command].parse(await b(x,P));if(y.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==y.nativeUserId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&y.customerId&&T.session.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&y.customerId&&T.presentation.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==Y.parse(v.data).operationId||T.customerId!==Y.parse(v.data).customerId))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return g(T,I&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(w){let E=w instanceof F?w:w instanceof SyntaxError?new F("MERCHANT_BRIDGE_INVALID_REQUEST",400):new F("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return g({code:E.code,message:E.code,retryable:E.retryable,recovery:E.recovery},E.status,!0)}}}function Vn(e){return async(t,n)=>{let u=()=>e.readSubscriptionOperation(t),a=()=>e.readSubscriptionUpdate(t),c=()=>e.readRefund(t),d=n.command==="purchase.execute"?[u]:n.command==="subscription.change"?[a]:n.command==="refund.execute"?[c]:[u,a,c];for(let l of d)try{let s=await l(),g="authority"in s.operation?s.operation.authority:void 0;if(!g)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let w=J.parse(g);if(w.customerId!==t.customerId||w.operationId!==t.operationId||Object.keys(n.scope).some(E=>w.scope[E]!==n.scope[E]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return w}catch(s){if(n.command==="operation.read"&&s instanceof o&&s.code==="NOT_FOUND")continue;throw s}throw new F("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}export{K as FunnelDecisionTimeoutError,Z as FunnelProcessEntrySuppressedError,o as LongplayError,F as MerchantBridgeHandlerError,En as aiPriceSnapshotSchema,Rn as aiTokenQuoteSchema,Cn as createAiPricing,Mn as createAiUsageMiddleware,hn as createConfigurationSync,An as createConfiguredAiPricing,ye as createFeatureClient,Bn as createFunnelCampaignClient,ge as createFunnelDecisionClient,ee as createFunnelLocalEvaluator,Ln as createFunnelOrchestrationClient,Fn as createFunnelProcessAdapter,vn as createFunnelStartClient,Ie as createGuestToken,Sn as createLocalFunnelClient,On as createLongplayServer,Vn as createMerchantBridgeAuthorityResolver,Gn as createMerchantBridgeHandler,kn as createNativeReceiptClient,Nn as createPaywallStartClient,Pn as createSynchronizedFunnelLocalEvaluator,wn as evaluateFunnelNode,_n as renewFunnelRun,se as signMerchantBridgeMessage,ce as verifyMerchantBridgeMessage};
|
|
1
|
+
import{a as wn}from"./chunk-YT7TSF3I.js";import{a as En,b as Rn,c as Cn,d as An}from"./chunk-AHDMDMHB.js";import{a as p,b as ye,c as We,d as Xe,e as Ze,f as en,h as W,i as nn,j as U,k as D,m as tn,n as hn,o as vn,p as Sn}from"./chunk-VQBQAKJD.js";import"./chunk-VSMITXQD.js";import"./chunk-OBZSDWLC.js";import{a as o}from"./chunk-OZZMZH7X.js";import"./chunk-RK6UEQF2.js";import{$ as Me,A as J,B as Ce,E as ae,F as Ae,Fa as Be,G as Oe,Ga as le,H as ie,Ha as z,I as se,Ia as Ue,J as ce,Ja as Ge,Ka as Ve,La as me,Ma as He,N as ue,Na as qe,O as be,Oa as je,P as Pe,Pa as fe,Qa as Ke,Ra as Q,Sa as ze,T as Ne,Va as Qe,Wa as Ye,X as G,Y as ke,Z as de,_ as De,_a as Je,a as he,aa as $,ab as $e,ba as j,ca as Le,k as we,l as ve,m as te,o as Se,p as re,q as Ee,s as oe,u as Re,ua as i,va as pe,z as Y}from"./chunk-KQ4MS4LR.js";import{B as Fe,E as _e,r as Te,xa as xe}from"./chunk-VSJOHWDL.js";function X(e){return{async getCustomer(t){let n=i.getCustomer;return p(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=i.listCustomers;return p(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=i.updateCustomer;return p(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=i.createGuestCustomer;return p(e,n,t)},async resumeGuestSession(t){let n=i.resumeGuestSession;return p(e,n,t)},async claimGuestCustomer(t){let n=i.claimGuestCustomer;return p(e,n,t)},async revokeCustomerSessions(t){let n=i.revokeSessions;return p(e,n,t)},async createCustomerSession(t){return p(e,i.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return p(e,i.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function f(e,t){try{return e.parse(t)}catch{throw new o("INVALID_RESPONSE","Invalid gateway response")}}function rn(e){return{async checkEntitlement(t){let n=i.checkEntitlement;return p(e,n,t,f)},async readHoldings(t){let n=i.readHoldings;return p(e,n,t,f)},async readSeats(t){let n=i.readSeats;return p(e,n,t,f)},async manageSeat(t){let n=i.manageSeat;return p(e,n,t,f)}}}function on(e){return{async readAiPricing(t){let n=i.readAiPricing;return p(e,n,t,f)},async readUsage(t){let n=i.readUsage;return p(e,n,t,f)},async setUsage(t){let n=i.setUsage;return p(e,n,t,f)},async manageBalanceGrant(t){let n=i.manageBalanceGrant;return p(e,n,t,f)},async readBalanceSource(t){let n=i.readBalanceSource;return p(e,n,t,f)},async adjustBalance(t){let n=i.adjustBalance;return p(e,n,t,f)},async listBalanceGrants(t){let n=i.listBalanceGrants;return p(e,n,t,f)},async manageBillingLimits(t){let n=i.manageBillingLimits;return p(e,n,t,f)},async manageUsageEntity(t){let n=i.manageUsageEntity;return p(e,n,t,f)},async readUsageAnalytics(t){let n=i.readUsageAnalytics;return p(e,n,t,f)},async readCreditAnalytics(t){let n=i.readCreditAnalytics;return p(e,n,t,f)},async submitUsageBatch(t){let n=i.submitUsageBatch;return p(e,n,t,f)},async readUsageBatch(t){let n=i.readUsageBatch;return p(e,n,t,f)},async readLedger(t){let n=i.readLedger;return p(e,n,t,f)},async readCreditStatement(t){let n=i.readCreditStatement;return p(e,n,t,f)},async quoteBalance(t){let n=i.quoteBalance;return p(e,n,t,f)},async trackUsage(t){let n=i.trackUsage;return p(e,n,t,f)},async mutateBalance(t){let n=i.mutateBalance;return p(e,n,t,f)}}}function an(e){return{async listInvoiceTemplates(t={}){let n=i.listInvoiceTemplates;return p(e,n,t,f)},async previewInvoice(t){let n=i.previewInvoice;return p(e,n,t,f)},async createInvoice(t){let n=i.createInvoice;return p(e,n,t,f)},async prepareBillingAdjustment(t){let n=i.prepareBillingAdjustment;return p(e,n,t,f)},async manageInvoice(t){let n=i.manageInvoice;return p(e,n,t,f)},async readInvoiceOperation(t){let n=i.readInvoiceOperation;return p(e,n,t,f)},async listInvoices(t){let n=i.listInvoices;return p(e,n,t,f)},async getInvoice(t){let n=i.getInvoice;return p(e,n,t,f)},async setupPayment(t){let n=i.setupPayment;return p(e,n,t,f)},async readPaymentSetup(t){let n=i.readPaymentSetup;return p(e,n,t,f)},async readBillingInvoice(t){let n=i.readBillingInvoice;return p(e,n,t,f)},async previewRefund(t){let n=i.previewRefund;return p(e,n,t,f)},async refund(t){let n=i.refund;return p(e,n,t,f)},async readRefund(t){let n=i.readRefund;return p(e,n,t,f)}}}function sn(e){return{async previewSubscriptionBatch(t){let n=i.previewSubscriptionBatch;return p(e,n,t,f)},async confirmSubscriptionBatch(t){let n=i.confirmSubscriptionBatch;return p(e,n,t,f)},async readSubscriptionBatch(t){let n=i.readSubscriptionBatch;return p(e,n,t,f)},async abandonSubscriptionBatch(t){let n=i.abandonSubscriptionBatch;return p(e,n,t,f)},async manageSubscriptionTrial(t){let n=i.manageSubscriptionTrial;return p(e,n,t,f)},async readSubscriptionTrial(t){let n=i.readSubscriptionTrial;return p(e,n,t,f)},async listSubscriptions(t){let n=i.listSubscriptions;return p(e,n,t,f)},async listPurchases(t){let n=i.listPurchases;return p(e,n,t,f)},async listSubscriptionConflicts(t){let n=i.listSubscriptionConflicts;return p(e,n,t,f)},async retrySubscriptionConflict(t){let n=i.retrySubscriptionConflict;return p(e,n,t,f)},async previewUpdate(t){let n=i.previewUpdate;return p(e,n,t,f)},async update(t){let n=i.update;return p(e,n,t,f)},async readSubscriptionUpdate(t){let n=i.readSubscriptionUpdate;return p(e,n,t,f)},async restoreNativePurchase(t){let n=i.restoreNativePurchase;return p(e,n,t,f)},async verifySubscriptions(t){let n=i.verifySubscriptions;return p(e,n,t,f)},async previewAttach(t){let n=i.previewAttach;return p(e,n,t,f)},async recordBillingEvent(t){let n=i.recordBillingEvent;return p(e,n,t,f)},async attach(t){let n=i.attach;return p(e,n,t,f)},async readSubscriptionOperation(t){let n=i.readSubscriptionOperation;return p(e,n,t,f)}}}function cn(e){return{async recordCouponRedemption(t){return p(e,i.recordCouponRedemption,t,{request:"Invalid Coupon redemption facts",parseResponse:f})},async grantOffer(t){let n=i.grantOffer;return p(e,{...n,request:n.request.refine(u=>!!u.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function un(e){return{...rn(e),...on(e),...an(e),...sn(e),...cn(e)}}function dn(e){return{async getFeatures(t={}){let n=i.getFeatures;return p(e,n,t,f)},async evaluateFeatures(t){let n=i.evaluateFeatures;return p(e,n,t,f)}}}function pn(e){return{async trackEvents(t){let n=i.trackEvents;return p(e,n,t,f)}}}function ln(e){return{async resolveContent(t){let n=i.resolveContent;return p(e,n,t,f)},async resolvePaywall(t){let n=i.resolvePaywall;return p(e,n,t,f)},async resolveOffering(t){let n=i.resolveOffering;return p(e,n,t,f)}}}function On(e){U(e.apiKey,"Secret API keys must stay on your backend");let n=D(e).request;return{async sendMessage(u){let a=i.sendMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},async readMessage(u){let a=i.readMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},...X(n),...un(n),...dn(n),...pn(n),...ln(n)}}function Ie(){if(typeof window<"u")throw new o("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var mn=()=>new o("CONFLICT","Process synchronization is in progress",425),M=()=>new o("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),Tn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Z=class extends o{constructor(n){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:n.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=n}result};function Fn(e){if(U(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new o("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let t=D(e),n=X(t.request),u=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function a(m){let r=await e.resolveUser(m);if(r!==null&&(typeof r?.externalUserId!="string"||!r.externalUserId||r.externalUserId!==r.externalUserId.trim()||r.externalUserId.startsWith("gg_guest_")))throw new o("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return r}async function c(m){let r=await e.resolveContext(m);if(r?.confirmed!==!0||!r.processKey||!r.guestKey)throw new o("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:u+"run:"+r.processKey,guest:u+"guest:"+r.guestKey}}async function d(m,r){for(let y=0;y<8;y++){let h=await e.store.read(m),I=r(h?structuredClone(h.value):null);if(h&&Tn(h.value,I)||await e.store.compareAndSwap(m,h?.revision??null,I))return I}throw mn()}async function l(m){let r=await e.store.read(m);if(!r)throw new o("NOT_FOUND","Open the process before continuing",404);return r.value}async function s(m){let r=await l(m);for(let y of r.revocations??[])await n.revokeCustomerSessions(y),await d(m,h=>{if(!h)throw M();return h.revocations=h.revocations?.filter(I=>I.sessionId!==y.sessionId),h})}async function g(m,r){let y=le.parse(m);return r?t.requestWithCredential("funnel-processes",y,r):t.request("funnel-processes",y)}function w(m,r){if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment||m.run&&(m.run.id!==r.run.id||m.run.source.versionId!==r.run.source.versionId||m.run.source.id!==r.run.source.id||m.run.runExpiresAt!==r.run.runExpiresAt||m.run.identity.startedAs!==r.run.identity.startedAs||m.run.identity.participantId!==r.run.identity.participantId||m.run.identity.binding&&m.run.identity.binding.id!==r.run.identity.binding?.id)||m.runToken&&r.runToken&&m.runToken!==r.runToken)throw new o("INVALID_RESPONSE","Process identity or Run changed")}async function E(m,r,y){return d(m,h=>{if(!h)throw new o("NOT_FOUND","Process handle is missing",404);return w(h,r),(!h.run||r.run.revision>=h.run.revision)&&(h.run=r.run),h.runToken??=r.runToken,y!==void 0&&(h.target=y),h})}async function S(m,r){if(r.detached)throw new o("UNAUTHENTICATED","The process is detached",401);let y=r.run?.identity.binding?.customerId??r.run?.identity.participantId;if(!y)throw new o("INVALID_RESPONSE","Process participant is missing");if(r.session?.customerId===y&&Date.parse(r.session.expiresAt)>Date.now()+3e4)return r.session;let h={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},I=await d(m,A=>{if(!A||A.detached||A.run?.id!==r.run?.id)throw M();if(A.sessionLease&&A.sessionLease.until>Date.now())throw mn();return A.sessionLease=h,A}),C;try{if(I.session?.customerId===y&&Date.parse(I.session.refreshExpiresAt)>Date.now())try{if(C=Se.parse(await t.requestWithCredential("customer-sessions/refresh",{},I.session.refreshToken)),C.sessionId!==I.session.sessionId)throw new o("INVALID_RESPONSE","Refresh changed the logical session")}catch(b){if(!(b instanceof o)||b.status!==401)throw b}if(C??=I.run?.identity.binding?await n.createCustomerSession(y):await n.resumeGuestSession({guestToken:I.guest.token}),C.customerId!==y)throw new o("INVALID_RESPONSE","Session Customer changed");let A=C;return await d(m,b=>{if(!b||b.detached||b.sessionLease?.id!==h.id||b.run?.identity.binding?.id!==r.run?.identity.binding?.id)throw new o("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return b.session=A,delete b.sessionLease,b}),C}catch(A){throw C&&C.sessionId!==I.session?.sessionId&&await n.revokeCustomerSessions({customerId:C.customerId,sessionId:C.sessionId}).catch(()=>{}),await d(m,b=>{if(!b)throw M();return b.sessionLease?.id===h.id&&delete b.sessionLease,b}).catch(()=>{}),A}}let R;async function O(){if(R??=He.parse(await g({contract:G,operation:"describe"})),R.scope.projectId!==e.scope.projectId||R.scope.environment!==e.scope.environment)throw M();return R}async function v(m,r,y=!1){let h=await a(m),I=await l(r);if(I.issuingKeyId!==(await O()).keyId)throw new o("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!I.runToken||!I.run)throw new o("CONFLICT","Recover the original start first",425);if(I.detached){if(!y)throw new o("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(I.run.identity.binding&&(!h||I.target&&I.target!==h.externalUserId))throw M();await s(r),I=await d(r,C=>{if(!C||C.run?.id!==I.run?.id)throw M();return delete C.detached,C})}if(!I.runToken||!I.run)throw new o("INVALID_RESPONSE","Process identity is missing");if(I.run.identity.binding){if(h&&!I.target){let C=me.parse(await g({contract:G,operation:"binding_status",runToken:I.runToken,requestId:I.bindingIntent?.requestId??I.start.requestId,externalUserId:h.externalUserId}));if(C.state!=="bound"||C.binding.id!==I.run.identity.binding.id)throw M();I=await d(r,A=>{if(!A)throw M();return A.target=h.externalUserId,A})}if(!h||I.target!==h.externalUserId)throw M()}else if(h){if(!I.guest)throw M();I=await d(r,A=>{if(!A||A.bindingIntent&&A.bindingIntent.externalUserId!==h.externalUserId)throw M();return A.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:h.externalUserId},A});let C=I.bindingIntent;try{let A=Ve.parse(await g({contract:G,operation:"bind_customer",...C,runToken:I.runToken,guestToken:I.guest.token,claimRequestId:I.guest.claimRequestId,expectedBindingId:null}));I=await E(r,A,h.externalUserId)}catch(A){let b=me.parse(await g({contract:G,operation:"binding_status",...C,runToken:I.runToken,guestToken:I.guest.token}));if(b.state!=="bound")throw A;I=await d(r,x=>{if(!x?.run||x.run.id!==b.binding.runId)throw M();return x.run.identity.binding={id:b.binding.id,customerId:b.binding.customerId,acceptedAt:b.binding.acceptedAt},x.target=h.externalUserId,x})}}return{state:I,session:await S(r,I)}}async function k(m,r,y,h){try{return await h(y)}catch(I){if(!(I instanceof o)||I.status!==401)throw I;return await d(r,C=>{if(!C||C.detached)throw I;return C.session?.accessToken===y.session.accessToken&&(C.session.expiresAt=new Date(0).toISOString()),C}),h(await v(m,r))}}async function L(m,r,y=!1){let h=await c(m),I=await v(m,h.process,y),C=z.parse(await k(m,h.process,I,A=>g({...r,customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C}return{async open(m,r){r=Ge.parse(r);let y=await c(m),h=await O(),I=y.guest+":"+h.keyId,C=await e.store.read(y.process);if(!C){let P=await a(m),T,_,N;if(P)T={type:"customer",customer:{type:"externalUserId",value:P.externalUserId}};else{let V=await e.store.read(I);if(V)try{N=await n.resumeGuestSession({guestToken:V.value.token}),_=V.value}catch(B){if(!(B instanceof o)||B.status!==401)throw B}let H={token:Ie(),claimRequestId:crypto.randomUUID()};_=await d(I,B=>_??(B&&B.token!==V?.value.token?B:H)),T={type:"guest",guestToken:_.token}}await d(y.process,V=>V??{issuingKeyId:h.keyId,start:le.parse({...r,contract:G,requestId:crypto.randomUUID(),source:T}),..._?{guest:_}:{},...P?{target:P.externalUserId}:{},...N?{session:N}:{}}),C=await e.store.read(y.process)}let A=C.value;if(A.issuingKeyId!==h.keyId)throw new o("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(A.start.funnelId!==r.funnelId||A.start.operation!==r.operation)throw new o("CONFLICT","This handle already owns another process",409);if(!A.runToken){if(A.start.source.type==="customer"){let N=await a(m);if(!N||N.externalUserId!==A.target)throw M()}let P=await g(A.start),T=Ue.safeParse(P);if(T.success)throw new Z(T.data);let _=z.parse(P);if(!_.runToken)throw new o("INVALID_RESPONSE","Process credential is missing");A=await E(y.process,_)}let b=await v(m,y.process,!0),x=z.parse(await k(m,y.process,b,P=>g({contract:G,operation:"get",customerToken:P.session.accessToken},P.state.runToken)));return await E(y.process,x),{...x,runToken:A.runToken}},async syncIdentity(m){return L(m,{contract:G,operation:"get",customerToken:""},!0)},async get(m,r={}){return L(m,{...r,contract:G,operation:"get",customerToken:""})},async review(m,r){return L(m,{contract:G,operation:"review",customerToken:"",...r?{receiptId:r}:{}})},async command(m,r,y){let h=await c(m),I=await v(m,h.process),C=z.parse(await k(m,h.process,I,A=>g({contract:G,operation:"command",command:r,identity:{bindingId:y},customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C},async pageExperiments(m,r,y=[]){let h=await c(m),I=await v(m,h.process);return Be.parse(await k(m,h.process,I,C=>g({contract:G,operation:"page_experiments",release:r,usedReceiptIds:y,customerToken:C.session.accessToken},C.state.runToken)))},async detach(m){let r=await c(m);await d(r.process,y=>{if(!y)throw M();return y.session&&!y.revocations?.some(h=>h.sessionId===y.session.sessionId)&&(y.revocations??=[]).push({customerId:y.session.customerId,sessionId:y.session.sessionId}),y.detached=!0,delete y.session,delete y.sessionLease,y}),await s(r.process)},destroy(){t.dispose()}}}async function _n(e,t){U(e.apiKey,"Renewal requires your backend");let n=D(e),u=je.parse(We(e,await n.request("funnels",qe.parse({...t,operation:"renew_run"}))));if(u.run.id!==t.runId)throw new o("INVALID_RESPONSE","Run renewal identity changed");return u}function fn(e){let t=Ze(e),n=l=>{throw new o("INVALID_RESPONSE",l)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let u=new Set(["entry","condition","feature","split","end","output"]);for(let l of t.nodes.values()){if(!u.has(l.type))throw new o("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(l.type==="entry"&&l.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(l.type)&&!l.outputs.next&&n("Local next exit is unavailable"),l.type==="feature"){let s=l.resources.featureKey;(!s||!Object.hasOwn(e.evaluation.variables,l.writes.value)||!Object.hasOwn(t.features,s))&&n("Local Feature definition or declaration is unavailable")}if(l.type==="condition"){let s=e.conditions[l.id];(!s||!l.outputs.default||s.some((g,w)=>g.port!==`case:${w}`||!l.outputs[g.port]))&&n("Local Condition exits are unavailable")}if(l.type==="split"&&(!l.resources.experimentId||!Object.hasOwn(e.growth.experiments,l.resources.experimentId)||!l.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),l.type==="end"||l.type==="output"){let s=e.evaluation.terminals[l.id];if(!s)throw new o("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(l.outputs).length&&n("A terminal cannot have outgoing edges"),s.output?.type==="feature"&&!Object.hasOwn(t.features,s.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let s of Object.values(l.outputs))t.nodes.has(s)||n("Local target is unavailable")}let a=new Set,c=new Set;function d(l){if(c.has(l)&&n("Local graph contains a cycle"),!a.has(l)){c.add(l);for(let s of Object.values(t.nodes.get(l).outputs))d(s);c.delete(l),a.add(l)}}return d(e.topology.entry),a.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(l){let s={},g=l.context;g.features=t.features,g.savedGroups=t.savedGroups;let w=()=>{g.attributes=ke({declarations:e.evaluation.variables,attributes:l.attributes,parameters:l.parameters,answers:{},results:s,savedGroups:t.savedGroups})};w();let E=e.topology.entry,S=0;for(;;){let R=t.nodes.get(E);if(R.type==="end"||R.type==="output"){let O=e.evaluation.terminals[E],v=O.output,k=v?.type==="feature"?t.feature(v.featureKey,g):v?.type==="variable"?Pe({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:e.evaluation.variables,answers:{},results:s,parameters:l.parameters,attributes:l.attributes,savedGroups:t.savedGroups}):v?.value??null;return ue(e.evaluation.outputSchema,k)||n("Local output does not match its declaration"),{outcome:O.outcome,value:k}}if(S++>=e.evaluation.maxTransitions)throw new o("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(R.type==="entry")E=R.outputs.next;else{let O=t.evaluate(E,g);if(R.type==="feature"){let v=R.writes.value,k=O.value??null;ue(e.evaluation.variables[v],k)||n("Local Feature value does not match its declaration"),be(e.evaluation.variables,{writes:R.writes},{[v]:k}),s[v]=k,w()}E=O.target}}}}}import{z as yn}from"zod";function In(e,t,n){let u=Fe.parse(e.attributes);if(["parameters","answers","results"].some(m=>Object.hasOwn(u,m)))throw new o("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let a=xe.parse(e.parameters??{}),c=yn.record(yn.string(),_e).parse(e.stickyBucketAssignmentDocs??{});for(let[m,r]of Object.entries(c))if(m!==`${r.attributeName}||${r.attributeValue}`||!Object.hasOwn(u,r.attributeName)||Te(u[r.attributeName])!==r.attributeValue)throw new o("INVALID_REQUEST","Sticky document identity does not match this session");let d=e.saveStickyBucketAssignmentDoc,l=e.onFeatureUsage,s=e.onExperimentViewed,g=e.onError,w=new Map,E=new Set,S={},R=Promise.resolve();function O(m){let r=R.then(()=>(n(),m()));return R=r.catch(()=>{}),r}function v(m){try{g?.(m)}catch{}}function k(m){try{let r=m();r&&typeof r.catch=="function"&&r.catch(v)}catch(r){v(r)}}async function L(){for(let[m,r]of w){if(n(),d)try{await d(structuredClone(r))}catch{throw new o("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),w.delete(m)}}return{evaluate(m={}){let r=m.track===!0;return O(async()=>{let y=await t();n(y);let h=new Set(E),I={...S},C=new Map,A=[],b={stickyBucketAssignmentDocs:structuredClone(c),saveStickyBucketAssignmentDoc(T){C.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...r?{trackedExperiments:h,trackedFeatureUsage:I,onExperimentViewed(T,_){let N=structuredClone(T),V=structuredClone(_);s&&A.push(()=>s(structuredClone(N),structuredClone(V)))},onFeatureUsage(T,_){let N=structuredClone(_);l&&A.push(()=>l(T,structuredClone(N)))}}:{}},x=y.program.evaluate({attributes:u,parameters:a,context:b});n(y);for(let[T,_]of C)c[T]=_,w.set(T,_);await L(),n(y),r&&(E=h,S=I);for(let T of A)k(T);let P=y.configuration;return structuredClone({evaluationMode:"local",scope:P.scope,funnelId:P.funnelId,versionId:P.versionId,evaluationRevision:P.evaluationRevision,generation:P.growth.generation,...x})})},flush:()=>O(L),get stickyBucketAssignmentDocs(){return n(),structuredClone(c)}}}var bn=6e4;function ee(e){if(typeof window<"u")throw new o("SERVER_ONLY","Local Funnel sessions run on your backend");let t=he.parse(e.scope),n=e.funnelId,u=e.load,a,c,d,l=0,s=E=>Date.now()>=E.expiresAt;async function g(){if(c)return c;let E=l;a=void 0;let S=(async()=>{let R=await u();if(E!==l)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&typeof R=="object"&&"evaluationMode"in R&&R.evaluationMode==="remote")throw f(Q,R),new o("EVALUATION_MODE","This Funnel requires remote decide");let O=f(ze,R);if(E!==l)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(O.scope.projectId!==t.projectId||O.scope.environment!==t.environment||O.funnelId!==n)throw new o("SCOPE_MISMATCH","Local configuration scope changed");if(O.growth.scope.projectId!==t.projectId||O.growth.scope.environment!==t.environment||O.growth.expiresAt!==O.expiresAt)throw new o("INVALID_RESPONSE","GB configuration scope or expiry changed");let v=Math.min(Date.now()+bn,O.expiresAt?Date.parse(O.expiresAt):1/0);if(Date.now()>=v)throw new o("CONFIGURATION_EXPIRED","Refresh expired local rules");let k=JSON.stringify([t.projectId,t.environment,n,O.versionId,O.evaluationRevision,O.growth.generation]),L=[O.topology,O.conditions,O.evaluation,O.growth.features,O.growth.experiments,O.growth.savedGroups];if(d?.key===k&&!nn(d.body,L))throw new o("INVALID_RESPONSE","Immutable local configuration identity changed");return d?.key!==k&&(d={key:k,body:L,program:fn(O)}),a={key:k,configuration:O,expiresAt:v,program:d.program},a})();c=S;try{return await S}finally{c===S&&(c=void 0)}}function w(){return c??(a&&!s(a)?Promise.resolve(a):g())}return{session(E){let S=l;return In(E,w,R=>{if(e.assertUsable?.(),S!==l)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&(s(R)||a?.key!==R.key))throw new o("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await g()).configuration)},reset(){l++,a=void 0,c=void 0,d=void 0}}}function Pn(e,t){let n=e.snapshot?.generation,u=ee({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),a=e.subscribe(()=>{let d=e.snapshot?.generation;e.fresh&&d!==n&&(n=d,u.refresh().catch(()=>{}))}),c=u.session;return Object.assign(u,{session(d){let l=c(d),s=l.evaluate;return Object.assign(l,{async evaluate(...g){return e.fresh||await e.refresh(),s(...g)}})},destroy(){a(),u.reset()}})}function Nn(e){if(typeof window<"u")throw new o("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>tn(e,t)}}var K=class extends o{constructor(n,u){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,u);this.decisionId=n;this.decisionRequestId=u}decisionId;decisionRequestId};async function ne(e,t,n,u){let{decisionId:a,requestId:c}=e,d=e,l=250,s=0;for(;;){if(d.decisionId!==a||d.requestId!==c||d.decision&&!W(d.decision,t))throw new o("INVALID_RESPONSE","Decision request or customer changed");if(d.decision)return d.decision;if(d.status==="failed")throw new o("DECISION_FAILED","Decision execution failed",503,c);if(Date.now()>=n)throw new K(a,c);if(await new Promise(g=>setTimeout(g,Math.min(Math.max(l,s-Date.now()),n-Date.now()))),Date.now()>=n)throw new K(a,c);l=Math.min(1e3,l*2);try{d=await u(a,n)}catch(g){if(g instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(g.code)){s=Date.now()+(g.retryAfterSeconds??0)*1e3;continue}throw g}}}function ge(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Funnel decisions are requested by your backend");let t,n,u=new Map;async function a(s,g){let w=s;w.status!=="pending"&&u.delete(w.decisionId);for(let E=0;E<32&&w.evaluation;E++){let S=w.evaluation;if(S.runId!==w.decisionId)throw new o("INVALID_RESPONSE","Local evaluation Run changed");let R=u.get(w.decisionId);if(!R&&S.type==="evaluate_segment"){let v=$e.parse(await c({operation:"segment_configuration",funnelId:e.funnelId,versionId:S.versionId},g));if(v.configuration.scope.projectId!==e.scope.projectId||v.configuration.scope.environment!==e.scope.environment||v.configuration.funnelId!==e.funnelId||v.configuration.versionId!==S.versionId||v.configuration.evaluationRevision!==S.policyRevision)throw new o("SCOPE_MISMATCH","Original decision segment configuration changed");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding decisions first");R={operation:"commit_decision_segment",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,policyRevision:S.policyRevision,generation:v.configuration.growth.generation,...en(v.configuration,v.document,S)},u.set(w.decisionId,R)}if(!R){if(S.type!=="evaluate")throw new o("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=Q.parse(await c({operation:"configuration",funnelId:e.funnelId,versionId:S.versionId},g))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision)throw new o("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding Local decisions first");R={operation:"evaluate_decision",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,"evaluation"),nodeId:S.nodeId,visit:S.visit,revision:S.revision,receiptId:S.receiptId,policyRevision:S.policyRevision,generation:n.growth.generation,result:Je(n,S.nodeId,S,Xe)},u.set(w.decisionId,R)}let O=j.parse(await c(R,g));if(O.decisionId!==s.decisionId||O.requestId!==s.requestId)throw new o("INVALID_RESPONSE","Decision identity changed during local evaluation");u.delete(w.decisionId),w=O}return w}async function c(s,g,w=!1){return D({...e,fetch:(S,R)=>{let O=new Headers(R?.headers);return O.set("Accept-Encoding","identity"),w&&O.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(S,{...R,headers:O})},timeoutMs:Math.min(e.timeoutMs??1e4,g?Math.max(1,g-Date.now()):12e4)}).request("funnels",s)}async function d(s,g){let w=j.parse(await c($.parse({operation:"read_decision",decisionId:s}),g));if(w.decisionId!==s)throw new o("INVALID_RESPONSE","Decision identity changed");return a(w,g)}async function l(s,g,w=!1){let E=$.options[0].parse({...s,operation:"decide",funnelId:e.funnelId}),S;try{S=j.parse(await c(E,g,w))}catch(R){throw R instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(R.code)?new o("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",R.status,s.requestId):R}if(S.requestId!==s.requestId||S.decision&&!W(S.decision,E.customer))throw new o("INVALID_RESPONSE","Decision request or customer changed");return{response:await a(S,g),customer:E.customer}}return{local(){return t??=ee({scope:e.scope,funnelId:e.funnelId,load:()=>c({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let s=Q.parse(await c({operation:"configuration",funnelId:e.funnelId}));if(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment||s.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Configuration scope changed");return s},features(s={}){return ye({...s,scope:e.scope,load:async()=>Ne.parse(await c({operation:"feature_config",funnelId:e.funnelId}))})},read:s=>d(s),async submit(s){return(await l(s,void 0,!0)).response},async decide(s){let g=Date.now()+3e4,w=await l(s,g);return ne(w.response,w.customer,g,d)},async reportUsed(s){let g=Le.parse(await c($.parse({...s,operation:"report_used"})));if(g.decisionId!==s.decisionId||g.eventId!==s.eventId)throw new o("INVALID_RESPONSE","Usage receipt identity changed");return g}}}function kn(e){U(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let u=Qe.parse(n);if(u.orderId!==u.receiptId)throw new o("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let a=u.nativeEvidence,c={requestId:u.requestId,customerToken:u.customerToken,purchaseIntentId:u.orderId,...a===null?{intent:"read"}:a.provider==="apple"?{provider:"apple",signedTransaction:a.signedTransaction}:{provider:"google",purchaseToken:a.purchaseToken}},d=i.restoreNativePurchase.response.parse(await t.request(i.restoreNativePurchase.path,c));if(d.operation.requestId!==u.requestId||d.operation.purchaseIntentId!==u.orderId)throw new o("INVALID_RESPONSE","Native receipt request identity changed");let l=Ye.parse({scope:d.scope,requestId:u.requestId,orderId:d.operation.orderId,receiptId:d.operation.orderId,orderStatus:d.operation.status,refunded:d.operation.refunded,...d.operation.completion===null?{}:{nativeCompletion:{orderId:d.operation.orderId,receiptId:d.operation.orderId,...d.operation.completion}}});if(l.requestId!==u.requestId||l.orderId!==u.orderId||l.receiptId!==u.receiptId||l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Current order receipt scope changed");return l}}}import{z as xn}from"zod";var q=xn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function Dn(e,t){let n=q.parse(e.inputTokens.total),u=q.parse(e.outputTokens.total),a=q.parse(e.inputTokens.cacheRead??0),c=q.parse(e.inputTokens.cacheWrite??0),d=q.parse(e.outputTokens.reasoning??0);if(a+c>n||d>u||e.inputTokens.noCache!==void 0&&q.parse(e.inputTokens.noCache)!==n-a-c||e.outputTokens.text!==void 0&&q.parse(e.outputTokens.text)!==u-d)throw new o("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-a-c,cache_read:a,cache_write:c,output:t==="output"?u:u-d,reasoning:t==="separate"?d:0,input_audio:0,output_audio:0}}function Mn(e){if(typeof window<"u")throw new o("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new o("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(u){await e.persist({context:u,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(u,a){let c={context:u,modelId:e.modelId,usage:a,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(c);let d=e.mapTokens?e.mapTokens(a):Dn(a,e.reasoning),l=await e.pricing.quoteTokens({modelId:e.modelId,tokens:d});await e.persist({...c,tokens:d,quote:l,phase:"quoted"});let s=await e.pricing.trackTokens(e.client,{...u,quote:l});if(!s.receipt.accepted)throw new o("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...c,tokens:d,quote:l,receipt:s,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:u}){let a=await e.context(),c;try{c=await u()}catch(d){throw await t(a),d}return await n(a,c.usage),c},async wrapStream({doStream:u}){let a=await e.context(),c;try{c=await u()}catch(w){throw await t(a),w}let d=!1,l=!1,s=c.stream.getReader();async function g(){d||l||(l=!0,await t(a))}return{...c,stream:new ReadableStream({async pull(w){try{let{value:E,done:S}=await s.read();if(S){if(!d)throw await g(),new o("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");w.close();return}if(E.type==="finish"){if(d)throw new o("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");d=!0,await n(a,E.usage)}w.enqueue(E)}catch(E){try{await g()}finally{w.error(E),await s.cancel(E)}}},async cancel(w){try{await g()}finally{await s.cancel(w)}}})}}}}function Ln(e){U(e.apiKey,"Funnel receipts are sent by your backend");let t=D(e);return{async signal(n){let u=de.parse({...n,operation:"signal"}),a=De.parse(await t.request("funnels",u));if(a.runId!==n.runId||a.eventId!==n.eventId||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Receipt identity changed");return a},async readResults(n){let u=de.parse({operation:"read_results",runId:n}),a=Me.parse(await t.request("funnels",u));if(a.runId!==n||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Result identity changed");return a}}}function Bn(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Campaign entry requires your backend");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let u=Date.now()+(e.timeoutMs??3e4),a=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),c=D({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,u-Date.now()))}),d=j.parse(await c.request("funnels",a));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");return ne(d,a.customer,u,(l,s)=>ge({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,s-Date.now()))}).read(l))},async start(n){let u=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),a=Ke.parse(await t.request("funnels",u));if(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in a)&&(a.run.source.id!==e.funnelId||!a.customerId||u.customer.type==="id"&&a.customerId!==u.customer.value))throw new o("INVALID_RESPONSE","Campaign Funnel or Customer changed");return a}}}import{z as Un}from"zod";var F=class extends Error{constructor(n,u=409,a=!1,c="fix_request"){super(n);this.code=n;this.status=u;this.retryable=a;this.recovery=c}code;status;retryable;recovery};function Gn(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=Re.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},u=t.capabilities.some(a=>["purchases","subscription_changes","refunds","operation_status"].includes(a));for(let[a,c]of Object.entries(oe))if(c.command&&t.capabilities.includes(a)&&!(a==="catalog"&&t.catalog==="static")&&!e.handlers[c.command])throw new Error(`Missing merchant command handler: ${c.command}`);if(u&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!t.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(c){let d=crypto.randomUUID(),l="bridge.ping",s,g=async(w,E,S=!1)=>{let R=JSON.stringify({bridgeVersion:re,requestId:d,command:l,scope:n,[S?"error":"data"]:w});if(new TextEncoder().encode(R).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(R,{status:E,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":d,...s?await se(R,s,"response"):{}}})};try{if(c.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(re)||c.method!=="POST"||new URL(c.url).pathname!==Ee)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(c.headers.get("Content-Type")??""))throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let w=c.body?.getReader();if(!w)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=new TextDecoder("utf-8",{fatal:!0}),S="",R=0;try{for(;;){let _=await w.read();if(_.done)break;if(R+=_.value.byteLength,R>16384)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",413);S+=E.decode(_.value,{stream:!0})}S+=E.decode()}finally{await w.cancel().catch(()=>{}),w.releaseLock()}let O=Oe.safeParse(JSON.parse(S));if(!O.success)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let v=O.data;if(d=v.requestId,l=v.command,Object.keys(n).some(_=>v.scope[_]!==n[_]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let k=v.command==="bridge.ping"||v.command==="bridge.describe",L=v.command==="catalog.read";if((k||L||c.headers.has(ie))&&(s=e.authentication.find(_=>_.keyId===c.headers.get(ie)),!s||!await ce(S,c.headers,s,"request")))throw s=void 0,new F("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(v.command==="bridge.ping")return g(ae["bridge.ping"].parse(v.data),200);if(v.command==="bridge.describe")return g(t,200);let m=Object.entries(oe).find(([,_])=>_.command===v.command);if(!m||!t.capabilities.includes(m[0]))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let r=e.handlers[v.command];if(!r)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!L&&c.headers.has("Cookie")&&(c.headers.get("Origin")!==new URL(c.url).origin||["cross-site","same-site"].includes(c.headers.get("Sec-Fetch-Site")??"")))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);let y=L?{kind:"service"}:await e.authorize(c,v),h=y.kind,I=["purchase.execute","subscription.change","refund.execute"].includes(v.command),C=I||v.command==="operation.read";if(!(C&&s!==void 0&&h==="service")&&(v.command==="refund.execute"?h!=="administrator":!L&&h!=="user"))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);if(y.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(v.command)&&!Un.uuid().safeParse(y.customerId).success)throw new F("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let b=r,x=ae[v.command].parse(v.data),P={request:c,command:v.command,scope:n,principal:y},T;if(C){let _=Y.parse(x);if(y.kind==="user"&&y.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let N=J.parse(await e.resolveOperationAuthority(_,P));if(N.operationId!==_.operationId||N.customerId!==_.customerId||Object.keys(n).some(H=>N.scope[H]!==n[H]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);P.authority=N;let V=v.command==="purchase.execute"?"purchase":v.command==="subscription.change"?"subscription_change":v.command==="refund.execute"?"refund":N.instruction.type;if(N.instruction.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!I)T=te.parse(await b(x,P));else{if(N.confirmedAt===null)throw new F("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let H=te.parse(await e.handlers["operation.read"](_,{...P,command:"operation.read"}));if(H.operationId!==_.operationId||H.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(H.lookup==="found")T=H.execution;else{if(!N.initialExecutionAllowed)throw new F("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(N.instruction.expiresAt)<=Date.now())throw new F("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||ve(N.instruction).some(B=>!t.billingEvents.some(gn=>gn===B))||we(N.instruction).some(B=>!t.profiles.includes(B)))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=Ce.parse(await b(x,P))}catch(B){throw B instanceof F?B:new F("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=Ae[v.command].parse(await b(x,P));if(y.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==y.nativeUserId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&y.customerId&&T.session.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&y.customerId&&T.presentation.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==Y.parse(v.data).operationId||T.customerId!==Y.parse(v.data).customerId))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return g(T,I&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(w){let E=w instanceof F?w:w instanceof SyntaxError?new F("MERCHANT_BRIDGE_INVALID_REQUEST",400):new F("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return g({code:E.code,message:E.code,retryable:E.retryable,recovery:E.recovery},E.status,!0)}}}function Vn(e){return async(t,n)=>{let u=()=>e.readSubscriptionOperation(t),a=()=>e.readSubscriptionUpdate(t),c=()=>e.readRefund(t),d=n.command==="purchase.execute"?[u]:n.command==="subscription.change"?[a]:n.command==="refund.execute"?[c]:[u,a,c];for(let l of d)try{let s=await l(),g="authority"in s.operation?s.operation.authority:void 0;if(!g)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let w=J.parse(g);if(w.customerId!==t.customerId||w.operationId!==t.operationId||Object.keys(n.scope).some(E=>w.scope[E]!==n.scope[E]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return w}catch(s){if(n.command==="operation.read"&&s instanceof o&&s.code==="NOT_FOUND")continue;throw s}throw new F("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}export{K as FunnelDecisionTimeoutError,Z as FunnelProcessEntrySuppressedError,o as LongplayError,F as MerchantBridgeHandlerError,En as aiPriceSnapshotSchema,Rn as aiTokenQuoteSchema,Cn as createAiPricing,Mn as createAiUsageMiddleware,hn as createConfigurationSync,An as createConfiguredAiPricing,ye as createFeatureClient,Bn as createFunnelCampaignClient,ge as createFunnelDecisionClient,ee as createFunnelLocalEvaluator,Ln as createFunnelOrchestrationClient,Fn as createFunnelProcessAdapter,vn as createFunnelStartClient,Ie as createGuestToken,Sn as createLocalFunnelClient,On as createLongplayServer,Vn as createMerchantBridgeAuthorityResolver,Gn as createMerchantBridgeHandler,kn as createNativeReceiptClient,Nn as createPaywallStartClient,Pn as createSynchronizedFunnelLocalEvaluator,wn as evaluateFunnelNode,_n as renewFunnelRun,se as signMerchantBridgeMessage,ce as verifyMerchantBridgeMessage};
|
package/dist/visual.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as pe,c as fe}from"./chunk-OJM6ORHE.js";import{b as ue}from"./chunk-J6KIN4RH.js";import{a as Ve,b as re,c as ce,d as de}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-
|
|
1
|
+
import{a as pe,c as fe}from"./chunk-OJM6ORHE.js";import{b as ue}from"./chunk-J6KIN4RH.js";import{a as Ve,b as re,c as ce,d as de}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-AY3DAC2V.js";import{a as ae,b as se,c as oe,d as le}from"./chunk-RGWFBLW4.js";import"./chunk-DSPLGTQI.js";import"./chunk-RK6UEQF2.js";import"./chunk-KQ4MS4LR.js";import{v as te,x as ie,z as M}from"./chunk-VSJOHWDL.js";import{z as o}from"zod";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://${n}`,`https://app.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:ue(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=oe(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=ae(e.deviceIdCookie??"indiana_did"),T=se(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(ce(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=le(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=de(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=re(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tinkerlandai/longplay-sdk",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.13",
|
|
4
4
|
"description": "Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"repository": {
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"scripts": {
|
|
64
64
|
"build": "tsup",
|
|
65
65
|
"prepack": "pnpm run build",
|
|
66
|
-
"typecheck": "tsc --noEmit",
|
|
66
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
|
|
67
67
|
"lint": "node ../../scripts/ci/lint.mjs --workspace packages/sdk"
|
|
68
68
|
},
|
|
69
69
|
"dependencies": {
|
package/dist/chunk-7RDYCTR4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as Ie}from"./chunk-MOWYD2TV.js";import{a as we,b as ye,c as ge,d as ve,e as he}from"./chunk-VSMITXQD.js";import{a as w}from"./chunk-OZZMZH7X.js";import{b as be,e as Ee}from"./chunk-SLUA7ABW.js";import{d as Ce}from"./chunk-QHJAF5T2.js";import{a as J}from"./chunk-DSPLGTQI.js";import{R as fe,da as se}from"./chunk-7DUOIHRD.js";import{Ca as me,s as de,sa as pe}from"./chunk-VSJOHWDL.js";function Pe(e){let R=e.view;if(!R?.paywall)throw new w("INVALID_REQUEST","The current node is not a Paywall");let n=R.paywall.receiptId,b=R.nodeId,d=R.visit,p=R.paywall.resolution,r=R.paywall,h="document"in p?{document:p.document,offering:p.offering,capabilities:p.capabilities}:null;function l(){let o=r.resolution;return"document"in o?o:h&&{...o,document:h.document,offering:h.offering,capabilities:we(o.capabilities,h.capabilities)}}function y(o){if(!ye(o,p))throw new w("INVALID_RESPONSE","The pinned Paywall binding changed")}let q=!1,v=new AbortController,S=R.paywall.purchaseRequestId,m=0,s=null,f=new Map;function N(o){if(o.purchase&&o.purchase.receiptId!==n)throw new w("INVALID_RESPONSE","Purchase receipt changed");let c=o.run.paywall;return o.purchase??(c?.receiptId===n?c:null)}function k(){if(q)throw new w("IDENTITY_CHANGED","Paywall presentation has closed")}function C(o,c,a){if(k(),c!==m||a!==void 0&&r.quote?.operationId!==a)return!1;let g=r.selectionGeneration??0,i=o.run.paywall;if(i?.receiptId===n){if((i.selectionGeneration??0)<(r.selectionGeneration??0))return!1;y(i.resolution)}let u=N(o),D=i?.receiptId===n&&(i.selectionGeneration??0)>g,Q=D?u?.quote??null:u?.quote??r.quote,A=u?.operation??(Q?.operationId===r.quote?.operationId?r.operation:null);return Q&&A&&ge(A,{operationId:Q.operationId},"Purchase operation changed"),(D||Q?.operationId!==r.quote?.operationId)&&(m++,i?.receiptId===n&&(S=i.purchaseRequestId)),r={...r,...i?.receiptId===n?i:{},quote:Q,operation:he(r.operation,A,!0)},!0}function O(o,c,a){return new Promise((g,i)=>{let u=!1,D=()=>{clearTimeout(j),v.signal.removeEventListener("abort",L)},Q=x=>{u||(u=!0,D(),g(x))},A=x=>{u||(u=!0,D(),i(x))},L=()=>A(new w("IDENTITY_CHANGED","Paywall presentation has closed")),j=setTimeout(()=>A(new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,c-Date.now()));v.signal.addEventListener("abort",L,{once:!0}),v.signal.aborted&&L(),o.then(Q,A)})}function F(o){return new Promise(c=>{let a=()=>{clearTimeout(g),v.signal.removeEventListener("abort",a),c()},g=setTimeout(a,o);v.signal.addEventListener("abort",a,{once:!0}),v.signal.aborted&&a()})}function E(o,c){k();let a=f.get(o)??e.pendingCommands?.find(u=>u.requestId===o)??e.pendingCommand;if(a?.operation==="submit"&&a.requestId===o&&a.nodeId===b&&a.visit===d){c.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!c.predecessor&&(c={...c,predecessor:a.input.predecessor});let u=se.parse(a),D=se.parse({...a,input:c});if(u.operation!=="submit"||D.operation!=="submit"||JSON.stringify(u.input)!==JSON.stringify(D.input))throw new w("CONFLICT","A purchase request cannot change its input");return f.set(o,u),u}let g=e.view;if(!g||g.nodeId!==b||g.visit!==d||g.paywall?.receiptId!==n)throw new w("PRECONDITION_FAILED","The Paywall visit has changed");let i=se.parse({operation:"submit",requestId:o,nodeId:b,visit:d,revision:g.revision,input:structuredClone(c)});if(i.operation!=="submit")throw new w("INVALID_REQUEST","A purchase submission is required");return f.set(o,i),i}async function T(o,c){k();let{requestId:a,input:g}=o,i=Date.now()+3e4,u=await O(e.submit(o),i,a);for(;u.run.pendingRequest?.requestId===a&&Date.now()<i&&!q&&(await F(Math.min(1e3,i-Date.now())),!(q||Date.now()>=i));)u=await O(e.resume(a),i,a);if(q)throw new w("IDENTITY_CHANGED","Paywall presentation has closed");if(u.run.pendingRequest?.requestId===a)throw new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!C(u,c,g.type==="paywall_confirm"||g.type==="paywall_cancel"?g.operationId:void 0))throw new w("PRECONDITION_FAILED","The purchase selection has changed")}async function _(o){if(!r.quote)throw new w("INVALID_REQUEST","A quoted purchase is required");let c=o==="confirm"?"paywall_confirm":"paywall_cancel",a=[...f.values(),...e.pendingCommands??(e.pendingCommand?[e.pendingCommand]:[])].find(i=>i.operation==="submit"&&i.input.type===c&&"operationId"in i.input&&i.input.operationId===r.quote.operationId),g=a?.operation==="submit"&&a.input.type===c&&"operationId"in a.input&&a.input.operationId===r.quote.operationId?a.requestId:crypto.randomUUID();if(await T(E(g,{type:o==="confirm"?"paywall_confirm":"paywall_cancel",operationId:r.quote.operationId}),m),!r.operation)throw new w("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(r.operation)}return{get view(){return structuredClone(l())},get quote(){return r.quote?structuredClone(r.quote):null},get operation(){return r.operation?structuredClone(r.operation):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return r.canReselect===!0},async refresh(){k();let o=m,c=await e.get();if(C(c,o),c.run.paywall?.receiptId!==n)throw new w("PRECONDITION_FAILED","Paywall presentation has changed");if(!l()){if("document"in r.resolution||!e.resolvePaywall)throw new w("INVALID_RESPONSE","Public Paywall reader is unavailable");let a=await e.resolvePaywall(r.resolution);k(),y(a),h={document:a.document,offering:a.offering,capabilities:a.capabilities}}return structuredClone(l())},preview(o){let c=l();if(!c)return Promise.reject(new w("PRECONDITION_FAILED","Load the Paywall presentation first"));if(S&&S!==o.requestId&&(s||r.canReselect!==!0))return Promise.reject(new w("COMMAND_PENDING","Retry the original purchase before starting another"));let a=c.document.buttons[o.actionId],g=a?.type==="checkout"?fe(a.product,o.selection,c.capabilities):null;if(!g)return Promise.reject(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let i=me(c.document.screen,g,o.selection,c.capabilities),u=S!==o.requestId&&(r.selectionGeneration??0)>0?{operationId:r.quote?.operationId??null,generation:r.selectionGeneration??0}:void 0;if(u&&r.canReselect!==!0)return Promise.reject(new w("COMMAND_PENDING","Original purchase requires authoritative termination"));let D;try{D=E(o.requestId,{type:"paywall_quote",actionId:o.actionId,productVersionId:g,...Object.keys(i).length?{featureQuantities:i}:{},...u?{predecessor:u}:{},...o.offerId?{offerId:o.offerId}:{},...o.nativeOffer?{nativeOffer:o.nativeOffer}:{}})}catch(L){return Promise.reject(L)}if(S===o.requestId&&s)return s;S!==o.requestId&&m++;let Q=m;S=o.requestId;let A=(async()=>{if(await T(D,Q),!r.quote)throw new w("INVALID_RESPONSE","The accepted quote is missing");return ve(r.quote,{productVersionId:g,featureQuantities:i},"The selected purchase changed"),structuredClone(r.quote)})();return s=A,A.then(()=>{s===A&&(s=null)},L=>{s===A&&(s=null),S===o.requestId&&e.pendingCommand?.requestId!==o.requestId&&L instanceof w&&L.status!==void 0&&L.status<500&&![401,425].includes(L.status)&&(S=null)}),A},confirm:()=>_("confirm"),cancel:()=>_("cancel"),async read(){if(k(),!r.quote)throw new w("INVALID_REQUEST","A quoted purchase is required");let o=r.quote.operationId,c=m,a=e.pendingCommands?.find(D=>D.operation==="submit"&&(D.input.type==="paywall_confirm"||D.input.type==="paywall_cancel")&&D.input.operationId===o)??e.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===o&&await e.settle?.(a.requestId);let g=await e.get(void 0,{receiptId:n,operationId:o});k();let i=N(g);if(i?.quote&&i.quote.operationId!==o||i?.operation&&i.operation.operationId!==o)throw new w("INVALID_RESPONSE","Purchase operation changed");let u=C(g,c,o)?r.operation:i?.operation;if(!u)throw new w("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(u)},destroy(){q=!0,v.abort(),f.clear()}}}function Re(e){let R=new Set,n=new Set,b=null;function d(p){if(e.reviewing||R.has(p)||n.has(p)||e.stopped)return;n.add(p);let r=async()=>{if(e.reviewing||e.stopped||e.key!==p){n.delete(p);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{r()},250);return}let h=(async()=>{let y=e.client.view,q=e.expected(),v=q.requestId,S=!1;try{await e.client.submit({operation:"shown",...q})}catch(m){if(!(m instanceof w)||m.code!=="CONFLICT"||m.status!==409||e.client.pendingCommand)throw m;await e.client.get();let s=e.client.view;if(e.stopped||e.reviewing||e.key!==p||!s||!y||s.id!==y.id||s.source.versionId!==y.source.versionId||s.nodeId!==q.nodeId||s.visit!==q.visit||s.revision<=q.revision||s.stopped||!s.screen||!["running","waiting"].includes(s.status)||e.client.pendingCommand)throw m;let f=e.expected();v=f.requestId,await e.client.submit({operation:"shown",...f})}for(;!e.stopped&&e.key===p&&e.client.pendingCommand?.requestId===v;){if(!e.client.settle)throw new w("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(v),S=!0,e.client.pendingCommand?.requestId===v&&await new Promise(m=>setTimeout(m,1500))}e.stopped||e.key!==p||(S&&await e.client.get(),!(e.stopped||e.key!==p)&&R.add(p))})();b=h;let l=()=>{b===h&&(b=null),n.delete(p)};h.then(l,y=>{l(),e.busy||e.fail(y)})};r()}return{report:d,get inFlight(){return b}}}function De(e){let R={},n=new Map;async function b(d){let p=e.client.view,r=p?.screen,h=r?.customerData.nodes[d.nodeId];if(e.stopped||e.busy||!p||!r||!h)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(d.action)){let s=e.document,f=s?pe(s,d.nodeId):null,N=f?.type==="customer_data"?f.data.outputs?.[d.action]:void 0;N&&r.outputs.includes(N)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:N,answers:e.answers,selection:d.value?{[d.nodeId]:d.value}:{}}})):await e.onIntent?.(d,p);return}let y=d.action.startsWith("sources_")?h.resources.find(s=>s.key===d.value):null;if(d.action.startsWith("sources_")&&!y)throw new w("INVALID_REQUEST","Choose a current resource");let q=`${p.visit}:${d.nodeId}:${y?.key??""}`,v=n.get(q)??[null],m=R[d.nodeId]??{page:1,after:null,filter:"all",...y?{resourceKey:y.key}:{}};if(d.action==="filter"){let s=d.value;if(!s||!(h.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(s))throw new w("INVALID_REQUEST","Unknown data filter");m={page:1,after:null,filter:s},v.splice(0,v.length,null)}else if(d.action==="next"||d.action==="sources_next"){let s=y?.sources.at(-1),f=y?s?{kind:"ledger",cursor:{at:s.detail[0],id:s.id,type:"source"}}:null:r.dataCursors[d.nodeId];if(!f||!y&&!h.hasNext)return;v[m.page]=f,m={...m,page:m.page+1,after:f}}else if(d.action==="previous"||d.action==="sources_previous"){if(m.page<=1)return;m={...m,page:m.page-1,after:v[m.page-2]??null}}n.set(q,v),R={...R,[d.nodeId]:m},await e.perform(()=>e.client.get({nodeId:p.nodeId,visit:p.visit,revision:p.revision,components:R}))}return{get queries(){return R},intent:b,reset(){R={},n.clear()}}}function qe(e){let{doc:R,holder:n,reviewHolder:b,mountScreenPreview:d}=e,p=!1,r,h=0,l=null,y="",q=new Map,v=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function S(s){if(e.stopped||!e.client.review)return;p||(y=v(e.client.view),q.set(y,structuredClone(e.answers))),p=!0,r=s,n.hidden=!0,e.suspend(!0),b.hidden=!1;let f=++h;try{let N=await e.client.review(s);if(e.stopped||f!==h||!p)return;if(!N.review)throw new w("INVALID_RESPONSE","Historical projection is missing");l?.destroy(),l=null,b.replaceChildren();let k=N.run.locale.startsWith("zh"),C=R.createElement("p");C.textContent=k?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",b.append(C);for(let[E,T]of N.review.pages.entries()){let _=R.createElement("button");_.type="button",_.textContent=k?`\u7B2C ${E+1} \u9875`:`Page ${E+1}`,_.onclick=()=>{S(T.receiptId)},b.append(_)}if(N.review.page){let E=N.review.page,T=R.createElement("div");if(T.inert=!0,b.append(T),l=d(T,{mode:"live",rendererUrl:e.client.webViewUrl,title:E.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{m()}}),l.update(E.document,N.run.locale,{serverInput:{bindings:E.inputs,answers:E.answers,values:E.values}}),await l.ready,e.stopped||f!==h||!p)return}let O=k?{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"},F=k?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let E of[...N.review.coupons.map((T,_)=>`${k?"\u4F18\u60E0\u5238":"Coupon"} ${_+1}: ${O[T.status]}`),...N.review.purchases.map((T,_)=>`${k?"\u8D2D\u4E70":"Purchase"} ${_+1}: ${F[T.status]}`)]){let T=R.createElement("p");T.textContent=E,b.append(T)}e.client.view&&await e.enqueue(e.client.view)}catch(N){if(f!==h||e.stopped)return;l?.destroy(),l=null,b.replaceChildren(),e.fail(N)}}async function m(){if(!p||e.stopped||!e.client.review)return;let s=++h;try{if(await e.client.review(),e.stopped||s!==h)return;p=!1,h++,l?.destroy(),l=null,b.replaceChildren(),b.hidden=!0,n.hidden=!1;let f=e.client.view;v(f)!==y?(q.set(y,structuredClone(e.answers)),e.resetScreen()):(q.delete(y),e.suspend(!1)),f&&await e.enqueue(f)}catch(f){if(s!==h||e.stopped)return;l?.destroy(),l=null,b.replaceChildren(),e.fail(f)}}return{get active(){return p},get receipt(){return r},open:S,exit:m,get drafts(){return new Map([...q].map(([s,f])=>[s,structuredClone(f)]))},stop(){p=!1,h++,l?.destroy(),l=null,b.replaceChildren(),b.hidden=!0,n.hidden=!1}}}function Fe(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let R=e.client.pageExperiments.bind(e.client),n=!1,b=!1,d=0,p=!1,r=!1,h,l=new Map,y=new Set,q={},v=new Map,S=be(e.appManifestRelease),m=()=>{for(let O of l.values())O.effect.revert();l.clear();for(let O of v.values())O();v.clear()};function s(O){if(n||y.has(O))return;y.add(O);let F=d;R(e.appManifestRelease,[O]).catch(E=>{y.delete(O),!n&&F===d&&J(e.onError,E)})}async function f(){if(n)return;let O=e.client.view;if(!O||O.stopped||!["running","waiting"].includes(O.status)){d++,m();return}if(p){r=!0;return}p=!0;let F=++d,E=`${O.id}:${O.visit}:${O.revision}`,T=location.href;try{let[_,{applyVisualVariation:o}]=await Promise.all([R(e.appManifestRelease),import("./visual-dom-7IF7ITAK.js")]),c=e.client.view;if(n||F!==d||!c||c.stopped||!["running","waiting"].includes(c.status)||`${c.id}:${c.visit}:${c.revision}`!==E||location.href!==T)return;let a=new Set,g=new Set;for(let i of _.assignments){let u=`${_.payload.environmentId}:${i.experimentKey}`;if(g.add(u),v.has(u)||v.set(u,Ee(u,q)),!!i.inExperiment)for(let D of _.payload.experiments){if(D.key!==i.experimentKey||!de(location.href,D.urlPatterns??[]))continue;let Q=D.meta?.findIndex(G=>G.key===i.variationKey)??-1,A=D.variations[Q];if(!A?.renderGuard)continue;let L=i.receiptId+":"+D.changeId,j=JSON.stringify([i.variationKey,A]);a.add(L);let x=l.get(L);if(x?.signature===j){x.effect.applied&&s(i.receiptId);continue}l.get(L)?.effect.revert(),l.delete(L);let B=o(A,{requireUniqueTargets:!0,boundVariations:D.variations,allowJs:!1,onApplied:()=>s(i.receiptId),onError:G=>J(e.onError,G)});l.set(L,{signature:j,effect:B}),B.applied&&s(i.receiptId)}}for(let[i,u]of l)a.has(i)||(u.effect.revert(),l.delete(i));for(let[i,u]of v)g.has(i)||(u(),v.delete(i))}catch(_){F===d&&m(),!n&&F===d&&J(e.onError,_)}finally{p=!1,r&&!n&&(r=!1,f())}}let N=e.client.subscribe(()=>{d++,f()}),k=Ce(()=>{d++,m(),f()}),C=async()=>{await f(),n||(h=setTimeout(()=>{C()},15e3))};return{async start(){b||n||(b=!0,await C())},refresh:f,destroy(){n=!0,d++,clearTimeout(h),N(),k(),m(),S.destroy()}}}async function an(e,R){let n=R,{mountScreenPreview:b}=await import("./screen-renderer-NHJ6OQTF.js"),{showPaywall:d}=await import("./paywall-PJEMTVSZ.js"),p=n.appManifestRelease?Fe({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;p?.start();let r=e.ownerDocument,h=r.activeElement,l=r.createElement("section"),y=r.createElement("div"),q=r.createElement("div"),v=r.createElement("div"),S=r.createElement("button");v.hidden=!0,S.type="button";let m=r.createElement("p"),s=r.createElement("p"),f=r.createElement("button"),N=r.createElement("button"),k=r.createElement("button"),C=r.createElement("dialog"),O;l.dataset.indianaFunnel="",l.setAttribute("aria-busy","false"),l.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",q.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",m.setAttribute("role","status"),s.setAttribute("role","alert"),s.hidden=!0,f.type=N.type=k.type="button",q.append(f,m,s,k,S,N),l.append(y,v,q),e.append(l);let F=null,E=null,T=null,_="",o="",c="",a="",g="",i=!1,u=0,D=!1,Q="",A=null,L=Promise.resolve(),j=null,x=null,B=new Set,G={},z=(t,I=null)=>{i||(x=I,s.textContent=t instanceof Error?t.message:"Request failed",s.hidden=!1,k.hidden=n.client.pendingCommand===null,J(n.onError,t))};function W(){let t=n.client.view;if(!t)throw new w("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let V=qe({client:n.client,doc:r,holder:y,reviewHolder:v,mountScreenPreview:b,get stopped(){return i},get answers(){return G},suspend(t){E?.setSuspended(t)},resetScreen(){_="",o="",c=""},enqueue:K,fail:z}),Z=Re({client:n.client,expected:W,fail:z,get stopped(){return i},get reviewing(){return V.active},get key(){return _},get busy(){return u}}),te=De({client:n.client,expected:W,perform:Y,onIntent:n.onCustomerDataIntent,get stopped(){return i},get busy(){return u},get document(){return F?.document},get answers(){return G}}),ae=t=>t&&(t.screen||t.paywall)?`${t.id}:${t.nodeId}:${t.visit}`:"";function ee(){let t=n.client.view;f.disabled=!V.active&&(u>0||!!n.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!ae(t)||o!==ae(t))}async function Y(t,I=!1){if(!(u&&!I||i||V.active&&!I)){u++,l.setAttribute("aria-busy","true"),ee(),s.hidden=!0,x=null;try{if(!I&&Z.inFlight){let P=n.client.view;await Z.inFlight;let $=n.client.view;if(!P||!$||$.id!==P.id||$.nodeId!==P.nodeId||$.visit!==P.visit||$.stopped||!["running","waiting"].includes($.status))throw new w("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(i)return;let H=await t();i||await K(n.client.view??H.run)}catch(H){z(H,n.client.pendingCommand?.requestId??null)}finally{u=Math.max(0,u-1),l.setAttribute("aria-busy",String(u>0)),i||(k.hidden=n.client.pendingCommand===null,ee())}}}function ie(){A&&clearTimeout(A),!(i||!T||!["running","waiting"].includes(T.status)&&!n.client.pendingCommand)&&(A=setTimeout(()=>{A=null,ce().finally(ie)},T.pendingRequest||n.client.pendingCommand?1500:5e3))}async function ce(){if(!(i||D||u)){if(V.active){await V.open(V.receipt);return}D=!0;try{let t=n.client.pendingCommand;t&&n.client.settle&&await n.client.settle(t.requestId);let I=n.client.view,H=te.queries,P=await n.client.get(I?.screen&&Object.keys(H).length?{nodeId:I.nodeId,visit:I.visit,revision:I.revision,components:H}:void 0);!i&&H===te.queries&&await K(n.client.view??P.run)}catch(t){z(t)}finally{D=!1}}}function Se(t){let I=t.screen?.presentation;if(!I||I.type==="inline"){C.open&&C.close(),l.parentElement!==e&&e.append(l);return}l.parentElement!==C&&(C.append(l),e.append(C));let H={sm:420,md:640,lg:900};C.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in I?H[I.size]+"px":"100vw"}`,C.setAttribute("aria-label",(O?.screen===t.screen?.content.document.name?O?.label:void 0)??F?.document?.name??t.screen?.content.document.name??"Funnel"),C.open||(C.showModal(),Ie(C,I.type))}async function Ne(t){if(i)return;T=t,x&&n.client.pendingCommand?.requestId!==x&&(s.hidden=!0,x=null);let I=t.locale.startsWith("zh");if(S.textContent=I?"\u56DE\u770B":"History",S.hidden=!n.client.review,f.textContent=V.active?I?"\u8FD4\u56DE\u5F53\u524D":"Return to current":I?"\u8FD4\u56DE":"Back",N.textContent=I?"\u5173\u95ED":"Close",k.textContent=I?"\u91CD\u8BD5":"Retry",ee(),k.hidden=n.client.pendingCommand===null,m.textContent=t.pendingRequest?I?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?I?"\u7B49\u5F85\u4E2D":"Waiting":"",Q!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(Q=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,J(n.onState,structuredClone(t))),!t.pendingRequest&&["closed","ineligible","failed"].includes(t.status)){ne();return}if(t.stopped||n.client.configurationReady===!1){V.stop(),F?.destroy(),F=null,E?.destroy(),E=null,y.replaceChildren(),_="",o="",c="",g="",C.open&&C.close(),l.hidden=!0,ie();return}if(l.hidden=!1,V.active){ie();return}let H=ae(t);if(H!==_&&(o="",F?.destroy(),F=null,E?.destroy(),E=null,y.replaceChildren(),_=H,c="",g="",G={...t.answers},te.reset()),Se(t),t.screen){let $=t.screen.content;F||(F=b(y,{mode:"live",rendererUrl:n.client.webViewUrl,title:$.document.name,onAction(U,le={},ue={}){if(V.active)return;G={...G,...ue};let _e=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:oe})=>Object.hasOwn(G,oe)).map(({variable:oe})=>[oe,G[oe]]));Y(()=>n.client.submit({operation:"submit",...W(),input:{type:"screen",output:U,answers:_e,selection:le}}))},onAnswers:U=>{V.active||(G={...G,...U})},onCustomerDataIntent:U=>{V.active||te.intent(U).catch(z)},onEscape:()=>{V.active||re()},onError:U=>z(new Error(U)),onRendered:U=>{if(!U)return Z.report(H);O={screen:$.document.name,label:U},C.open&&C.setAttribute("aria-label",U),Z.report(H)}}));let M={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:G,values:t.screen.values}},X=JSON.stringify([$,t.locale,M.parameters,t.screen.inputs,t.screen.values]);if(X!==c)F.update($.document,t.locale,M),c=X,a=JSON.stringify(M.capabilities),g=JSON.stringify(M.customerData);else{let U=JSON.stringify(M.capabilities);U!==a&&(F.updateCapabilities(M.capabilities),a=U),JSON.stringify(M.customerData)!==g&&(F.updateCustomerData(M.customerData),g=JSON.stringify(M.customerData))}await F.ready}else if(t.paywall&&!E){let $=await d(y,{canInteract:()=>!V.active&&!i,start:async()=>Pe(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:M=>n.onOpenUrl?n.onOpenUrl({receiptId:t.paywall.receiptId,url:M,openIn:"same_window"}):r.defaultView?.location.assign(M),onAction:async M=>{if(V.active)return;let X=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision,input:{type:"screen",output:M,answers:{}}});await K(n.client.view??X.run)},onError:z,onDismiss:()=>{!V.active&&!i&&n.client.view?.visit===t.visit&&re()}});i?$.host?.destroy():(E=$.host,E?.setSuspended(V.active)),Z.report(H)}if(i)return;o=H,ee();let P=t.instruction;if(P&&(P.type==="open_url"||P.type==="event")&&!B.has(P.receiptId)){let $=r.createElement("button");$.type="button",$.textContent=P.type==="open_url"?`${I?"\u524D\u5F80":"Continue to"} ${new URL(P.url).host}`:I?"\u7EE7\u7EED":"Continue",$.onclick=()=>{let M=W(),X=P.type==="open_url"&&!n.onOpenUrl&&P.openIn==="new_window"?ke(P.url):null;Y(async()=>{let U="success";if(P.type==="open_url")if(n.onOpenUrl)try{U=await n.onOpenUrl({receiptId:P.receiptId,url:P.url,openIn:P.openIn})===!1?"failed":"opened"}catch(ue){J(n.onError,ue),U="failed"}else U=P.openIn==="new_window"&&!X?"failed":"opened";if(P.type==="event"){if(!n.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(P.event)}if(i||n.client.view?.nodeId!==M.nodeId||n.client.view.visit!==M.visit)throw new w("PRECONDITION_FAILED","The client action visit changed");let le=await n.client.submit({operation:"submit",...M,input:{type:"client_action",receiptId:P.receiptId,outcome:U}});return B.add(P.receiptId),P.type==="open_url"&&!n.onOpenUrl&&P.openIn==="same_window"&&r.defaultView?.location.assign(P.url),le})},y.replaceChildren($)}!t.pendingRequest&&t.status==="completed"&&!B.has(`complete:${t.id}`)&&(B.add(`complete:${t.id}`),J(n.onComplete,structuredClone(t))),ie()}function ke(t){let I=r.defaultView?.open(t,"_blank")??null;return I&&(I.opener=null),I}function K(t){return ee(),L=L.catch(()=>{}).then(()=>Ne(t)),L}let Oe=n.client.subscribe(t=>{n.client.configurationReady===!1&&(l.hidden=!0,F?.destroy(),F=null,E?.destroy(),E=null,y.replaceChildren(),_="",o="",c="",g="",C.open&&C.close()),K(t).catch(z)}),Te=n.client.subscribeError?.(z);function re(){return j||(i?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ne(),Promise.resolve()):(j=Y(()=>n.client.submit({operation:"close",...W()}),!0).then(()=>{n.client.view?.status==="closed"&&ne()}).finally(()=>{j=null}),j))}function ne(){p?.destroy(),!i&&(i=!0,A&&clearTimeout(A),Oe(),Te?.(),F?.destroy(),V.stop(),E?.destroy(),C.close(),C.remove(),l.remove(),h instanceof HTMLElement&&h.isConnected&&h.focus(),J(n.onDismiss,T?structuredClone(T):null))}f.onclick=()=>{if(!f.disabled){if(V.active){V.exit();return}Y(()=>n.client.submit({operation:"back",...W()}))}},S.onclick=()=>{V.open()},N.onclick=()=>{re()},k.onclick=()=>{Y(()=>n.client.retry())},C.addEventListener("cancel",t=>{t.preventDefault(),re()});try{let t=await n.client.get();await K(n.client.view??t.run)}catch(t){throw ne(),t}return{destroy:ne,refresh:ce,review:V.open,exitReview:V.exit,get unappliedDrafts(){return V.drafts}}}export{Fe as a,an as b};
|
package/dist/chunk-PYIHBK7E.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as t}from"./chunk-JGFAFQKK.js";import{Za as n}from"./chunk-7DUOIHRD.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a}from"./chunk-7RDYCTR4.js";import"./chunk-MOWYD2TV.js";import"./chunk-VSMITXQD.js";import"./chunk-CDG7GM4C.js";import"./chunk-OZZMZH7X.js";import"./chunk-SLUA7ABW.js";import"./chunk-QHJAF5T2.js";import"./chunk-DSPLGTQI.js";import"./chunk-7DUOIHRD.js";import"./chunk-VSJOHWDL.js";export{a as showFunnelRun};
|
package/dist/paywall-PJEMTVSZ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as ee}from"./chunk-SSLZKIIU.js";import{a as Z}from"./chunk-MOWYD2TV.js";import"./chunk-CDG7GM4C.js";import{a as w}from"./chunk-OZZMZH7X.js";import{a as j}from"./chunk-DSPLGTQI.js";import{R as B}from"./chunk-7DUOIHRD.js";import{Aa as W,Ca as X,Z as V,i as G}from"./chunk-VSJOHWDL.js";async function te(b,n,y){if(n.status!=="complete")throw new w("INVALID_RESPONSE","A verified completed purchase is required");if(await y.onComplete?.(n),!b||!y.check)return;let P=V.parse(await y.check());if(P.internal_feature_id!==b.internal_feature_id||P.quantity!==b.quantity)throw new w("INVALID_RESPONSE","The access requirement changed");P.allowed&&await y.onAccessGranted?.(P)}async function he(b,n){let y=n.check?V.parse(await n.check()):null;if(y?.allowed)return await n.onAccessGranted?.(y),{check:y,host:null};let P=ee(b.ownerDocument),{mountScreenPreview:ne}=await import("./screen-renderer-NHJ6OQTF.js"),r=await n.start(),E;try{let e=r.view??await r.refresh();if(!e)throw new w("INVALID_RESPONSE","Paywall presentation is missing");E=e}catch(e){throw r.destroy(),P(),e}let c=b.ownerDocument,D=new AbortController,C=c.createElement("section"),K=c.createElement("div"),L=c.createElement("div"),g=c.createElement("p"),u=c.createElement("button"),M=c.createElement("button"),d=c.createElement("dialog"),i=E.document.screen.strings.defaultLocale.startsWith("zh");C.dataset.indianaPaywall="",C.setAttribute("aria-label",E.document.name),C.style.cssText="width:100%;box-sizing:border-box;background:#fff;color:#172033;font:14px/1.5 system-ui,sans-serif",L.style.cssText="display:flex;gap:12px;padding:12px 20px;align-items:center;flex-wrap:wrap",g.setAttribute("role","status"),M.textContent=i?"\u5173\u95ED":"Close",u.textContent=i?"\u91CD\u8BD5":"Retry",u.hidden=!0,L.append(g,u,M),C.append(K,L);let O=E.document.presentation,U,p=!1,$=!1,f=null,Y=!1,m=()=>!Y&&n.canInteract?.()!==!1,q=!1,a=null,N=null,Q=new Map;async function H(e){if(!(!m()||!e.checkoutUrl||Q.get(e.operationId)===e.checkoutUrl)){Q.set(e.operationId,e.checkoutUrl);try{n.onCheckoutUrl?await n.onCheckoutUrl(e.checkoutUrl):c.defaultView?.location.assign(e.checkoutUrl)}catch(o){throw Q.delete(e.operationId),o}}}let _=e=>{g.textContent=e instanceof Error?e.message:i?"\u8BF7\u6C42\u5931\u8D25":"Request failed",j(n.onError,e),u.hidden=a===null};async function k(e){if(!($||p||!m())){$=!0,u.hidden=!0,g.textContent="";try{await e()}catch(o){p||_(o)}finally{$=!1}}}async function re(e){await te(y,e,n)}async function v(e){if(p)return;if(!m()){a=async()=>v(await r.read()),u.hidden=!1;return}if(g.textContent=e.status,e.problem){let t=e.problem;a=T,u.textContent=i?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",_(new w(t.code,t.reason==="RESULT_UNKNOWN"?i?"\u4ED8\u6B3E\u7ED3\u679C\u5C1A\u672A\u786E\u5B9A\uFF0C\u8BF7\u6062\u590D\u539F\u64CD\u4F5C\uFF0C\u6682\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"The payment result is unknown. Recover the original purchase before buying again.":t.phase==="fulfillment"?i?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":t.code==="CAPABILITY_UNAVAILABLE"?i?"\u5546\u6237\u5C1A\u4E0D\u652F\u6301\u672C\u6B21\u8D2D\u4E70\u6240\u9700\u7684\u5B8C\u6574\u80FD\u529B\uFF0C\u8BF7\u5904\u7406\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":t.code==="NOT_CONFIGURED"?i?"\u4ED8\u6B3E\u670D\u52A1\u8FDE\u63A5\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u8054\u7CFB\u5546\u6237\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":i?"\u539F\u8D2D\u4E70\u64CD\u4F5C\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u67E5\u8BE2\u6216\u6062\u590D\u6B64\u64CD\u4F5C\u3002":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,t));return}if(e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(g.textContent=i?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u6B63\u5728\u7B49\u5F85\u5546\u6237\u5B8C\u6210\u5904\u7406\u3002":"Payment was recorded. Waiting for merchant fulfillment."),e.status==="complete"){a=null,await re(e);return}if(e.status!=="pending"){if(r.canReselect===!1){g.textContent=i?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",u.textContent=i?"\u67E5\u8BE2\u7ED3\u679C":"Check result",a=async()=>v(await r.read()),u.hidden=!1;return}u.textContent=i?"\u91CD\u8BD5":"Retry",a=null,f=null;return}await H(e);let o=Date.now()+6e5,l=2e3;for(;!p&&Date.now()<o;){if(await new Promise(h=>{let I=()=>{clearTimeout(x),h()},x=setTimeout(()=>{D.signal.removeEventListener("abort",I),h()},l);D.signal.addEventListener("abort",I,{once:!0})}),p)return;if(!m()){a=async()=>v(await r.read()),u.hidden=!1;return}let t=await r.read();if(!t.problem&&t.status==="pending"&&await H(t),t.status!=="pending"||t.problem){await v(t);return}l=Math.min(l*1.5,3e4)}a=async()=>v(await r.read()),u.hidden=!1}async function T(){N?.remove(),N=null,a=T;let e=await r.confirm();if(!m()){a=T,u.hidden=!1;return}if(e.problem){await v(e);return}if(e.status==="pending"){if(e.checkoutUrl)await H(e);else if(e.execution&&e.execution.provider!=="merchant"||e.nativePurchase){if(!n.onPurchase)throw new w("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await n.onPurchase({operation:e,signal:D.signal})}}a=async()=>v(await r.read()),await v(e)}function ae(e){N?.remove();let o=c.createElement("div"),l=c.createElement("button"),t=c.createElement("button"),h=c.createElement("p");h.textContent=e.lines.map(s=>s.productName).join(", ")+" \xB7 "+G(e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),e.currency),l.textContent=i?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",t.textContent=i?"\u53D6\u6D88":"Cancel",l.onclick=()=>{k(T)};let I=async()=>{let s=await r.cancel();p||(o.remove(),N=null,await v(s))};t.onclick=()=>{a=I,k(I)};let x=c.createElement("div");for(let s of e.lines){let J=c.createElement("p");J.textContent=`${s.productName} \xB7 ${G(s.catalogAmountMinor,e.currency)}${W(s.interval,i?"zh-CN":"en",s.intervalCount??1)}`,x.append(J);for(let A of s.prepaid??[]){let F=c.createElement("p"),R=r.view?.capabilities.plans[s.productVersionId]?.prepaid?.find(ie=>ie.internalFeatureId===A.internal_feature_id);F.textContent=`${R?.name??A.internal_feature_id} \xB7 ${A.quantity} ${i?"\u4EFD":"packs"} \xD7 ${A.terms.units}`,R&&(F.textContent+=W(R.reset==="week"||R.reset==="month"||R.reset==="year"?R.reset:"one_time",i?"zh-CN":"en",R.resetCount)),x.append(F)}if(s.trial){let A=c.createElement("p");A.textContent=i?`\u8BD5\u7528 ${s.trial.days} \u5929\uFF1B${s.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${s.trial.days}; ${s.trial.cardRequired?"a payment method is required":"no payment method is required"}`,x.append(A)}}if(!e.charge){let s=c.createElement("p");s.textContent=i?"\u76EE\u5F55\u4EF7\u683C\uFF1B\u6700\u7EC8\u91D1\u989D\u4EE5\u7ED3\u8D26\u65F6\u7A0E\u8D39\u548C\u8BD5\u7528\u89C4\u5219\u4E3A\u51C6\u3002":"Catalog price; the final charge depends on checkout taxes and trial terms.",x.append(s)}o.append(h,x,l,t),L.prepend(o),N=o,a=null}async function z(){if(!f)return;if(a=z,!q){let o=r.view,l=o?.document.buttons[f.actionId],t=o&&l?.type==="checkout"?B(l.product,f.selection,o.capabilities):null;if(!t)throw new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let h=await n.resolveOfferId?.({actionId:f.actionId,productVersionId:t});if(p)return;h!==void 0&&(f.offerId=h),q=!0}if(!m()){u.hidden=!1;return}let e=await r.preview(f);p||ae(e)}function S(e="destroy"){p||(p=!0,D.abort(),U?.destroy(),r.destroy(),d.open&&d.close(),d.remove(),C.remove(),P(),e==="dismiss"&&j(n.onDismiss))}M.onclick=()=>{m()&&S("dismiss")},d.addEventListener("cancel",e=>{e.preventDefault(),m()&&S("dismiss")}),u.onclick=()=>{a&&k(a)};try{if(O.type==="inline")b.append(C);else{let e={sm:420,md:640,lg:900};d.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in O?e[O.size]+"px":"100vw"}`,d.setAttribute("aria-label",E.document.name),d.append(C),b.append(d),m()&&(d.showModal(),Z(d,O.type))}U=ne(K,{mode:"live",rendererUrl:r.webViewUrl,title:E.document.name,onAction(e,o={}){if(!m())return;let l=r.view,t=l?.document.buttons[e];if(!t)return;if(t.type==="close"){k(async()=>{await n.onAction?.(e),S(n.onAction?"action":"dismiss")});return}if(t.type==="action"){a=async()=>{if(t.action.type==="event"){if(!n.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(t.action.event)}else n.onOpenUrl?await n.onOpenUrl(t.action.url):c.defaultView?.location.assign(t.action.url);await n.onAction?.(e),a=null},k(a);return}if((r.quote||f)&&r.canReselect===!1){a=r.quote?async()=>v(await r.read()):z,k(a);return}let h=l&&B(t.product,o,l.capabilities);if(!l||!h){_(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(n.onPurchaseIntent){a=null,k(async()=>{let I={actionId:e,productVersionId:h,selection:structuredClone(o),featureQuantities:X(l.document.screen,h,o,l.capabilities)};await n.onPurchaseIntent(I)});return}if(f&&f.actionId!==e){_(new w("COMMAND_PENDING","Finish the current purchase"));return}f||(f={requestId:crypto.randomUUID(),actionId:e,selection:o},q=!1),k(z)},onEscape:()=>{m()&&S("dismiss")},onError:e=>_(new Error(e)),onRendered:e=>{e&&d.setAttribute("aria-label",e)}}),U.update(E.document.screen,E.document.screen.strings.defaultLocale,{capabilities:E.capabilities,serverInput:{bindings:[],answers:{}}}),await U.ready}catch(e){throw S(),e}return{check:y,host:{setSuspended(e){Y=e,C.hidden=e,e&&d.open?d.close():!e&&!p&&O.type!=="inline"&&!d.open&&d.showModal()},destroy:S,refresh:async()=>{if(!m()){if(r.view)return r.view;throw new w("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await r.refresh();return p||U?.updateCapabilities(e.capabilities),e}}}}export{he as showPaywall};
|