@tinkerlandai/indiana-sdk 0.6.3 → 0.6.4
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 +14 -2
- package/README.md +8 -4
- package/README.zh-CN.md +7 -3
- package/THIRD_PARTY_NOTICES.md +28 -0
- package/dist/{chunk-QG4GM4RI.js → chunk-2EJSV6BA.js} +1 -1
- package/dist/{chunk-YAMBRNJ2.js → chunk-63BWE27V.js} +1 -1
- package/dist/{chunk-FF3LWJ26.js → chunk-HTRQPMJO.js} +3 -3
- package/dist/chunk-QG3WUJG5.js +1 -0
- package/dist/errors-DrdTlPwf.d.ts +57 -0
- package/dist/{funnel-runtime-host-KPYLOYYN.js → funnel-runtime-host-NWS3URFA.js} +1 -1
- package/dist/{funnel-runtime-start-CVb2YonU.d.ts → funnel-runtime-start-sZ8ZCNlq.d.ts} +2 -55
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/{paywall-5WU6PX5C.js → paywall-4XZ6NDMY.js} +1 -1
- package/dist/react-native.d.ts +327 -0
- package/dist/react-native.js +1 -0
- package/dist/server.d.ts +3 -2
- package/dist/server.js +1 -1
- package/dist/{src-U7PBAUBN.js → src-WV6GZYWA.js} +1 -1
- package/package.json +10 -3
- package/dist/chunk-FVUPV6YE.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{kb as T,lb as P,ob as v}from"./chunk-HTRQPMJO.js";import{a as j}from"./chunk-S5TVMQRC.js";import{b as E}from"./chunk-ISUXYPYL.js";import{a as e}from"./chunk-5TEZEOHX.js";import{D as _,G as C,J as k,v as O}from"./chunk-RMJJOSVZ.js";var L={name:"@tinkerlandai/indiana-sdk",version:"0.6.4",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"},"./iam":{types:"./dist/iam.d.ts",import:"./dist/iam.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.5"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@rrweb/types":"2.1.7","@types/css-tree":"^3.2.0",ai:"7.0.136","rrweb-snapshot":"2.1.7",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var $=Symbol("IndianaNoContent");function Z(a,U,V=URL){let S=a.webView??"hosted";if(!["hosted","embedded"].includes(S))throw new e("INVALID_REQUEST","Invalid Web View mode");let d=a.scope?E.parse(a.scope):void 0,s=new V(a.baseUrl??j);if(s.username||s.password||s.search||s.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(s.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let M=a.fetch??globalThis.fetch.bind(globalThis),u=a.timeoutMs??1e4;if(!Number.isFinite(u)||u<=0||u>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,g,c=0,l=null,m=new Set;function R(){c+=1,p=null,l=null;for(let i of m)i.abort();m.clear()}async function H(i,q={},N="POST",K={}){if(!p)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let y=c,n=new AbortController;m.add(n);let h=()=>y!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),I,x=new Promise((t,o)=>{I=()=>o(h()),n.signal.addEventListener("abort",I,{once:!0})}),F=setTimeout(()=>n.abort(),u),G=async()=>{let t=await M(`${s.href.replace(/\/$/,"")}/api/v1/${i}`,{method:N,headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`,[T]:v.current,[P]:L.version,...d?{"X-Indiana-Project":d.projectId,"X-Indiana-Environment":d.environment}:{}},body:N==="POST"?JSON.stringify(q):void 0,signal:n.signal,credentials:"omit",cache:"no-store",redirect:"error",...K.keepalive?{keepalive:!0}:{}});if(n.signal.aborted)throw h();let o;try{o=t.status===204?$:await t.json()}catch{throw n.signal.aborted?h():new e(t.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",t.status,t.headers.get("X-Request-Id")??void 0)}if(n.signal.aborted)throw h();if(y!==c)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!t.ok){let r=C.safeParse(o),w=r.success&&(!O.safeParse(r.data.error.code).success||_(r.data.error.code,t.status)),A=w?r.data.error.code:"HTTP_ERROR",D=k(A,t.status,{retryAfter:t.headers.get("Retry-After"),recovery:w?r.data.error.recovery:void 0,reason:w?r.data.error.reason:void 0});throw new e(A,w?r.data.error.message:"Indiana request failed",t.status,t.headers.get("X-Request-Id")??(r.success?r.data.requestId:void 0),{...D,...r.success&&r.data.error.retryable===!1?{retryable:!1}:{},...D.retryAfterSeconds===void 0&&r.success&&r.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:r.data.error.retryAfterSeconds}:{}})}if(t.headers.get(T)!==v.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(d&&o&&typeof o=="object"&&"scope"in o){let r=E.safeParse(o.scope);if(!r.success||r.data.projectId!==d.projectId||r.data.environment!==d.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let b=t.headers.get("X-Indiana-Web-View");if(b){if(!/^\/web-view\/renderer\/[a-f0-9]{64}$/.test(b))throw new e("INVALID_RESPONSE","Invalid Web View renderer metadata");g=b}let f=t.headers.get("X-Indiana-Telemetry-Subject");if(f){if(!/^[a-f0-9]{64}$/.test(f))throw new e("INVALID_RESPONSE","Invalid telemetry identity");l!==f&&(l=f,U?.(l))}return o};try{return await Promise.race([G(),x])}catch(t){throw y!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):t instanceof e?t:new e(n.signal.aborted?"TIMEOUT":"NETWORK_ERROR",n.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(F),n.signal.removeEventListener("abort",I),m.delete(n)}}return{subjectKey:()=>l,webViewUrl(){if(S!=="embedded"){if(!g)throw new e("INVALID_RESPONSE","The gateway did not provide a hosted Web View renderer");return new URL(g,s.href).href}},identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");R(),p=i},reset:R,request:H}}export{Z as a};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
declare const scopeSchema: z.ZodObject<{
|
|
4
|
+
projectId: z.ZodString;
|
|
5
|
+
environment: z.ZodEnum<{
|
|
6
|
+
sandbox: "sandbox";
|
|
7
|
+
live: "live";
|
|
8
|
+
}>;
|
|
9
|
+
}, z.core.$strict>;
|
|
10
|
+
type Scope = z.infer<typeof scopeSchema>;
|
|
11
|
+
|
|
12
|
+
declare const errorRecoverySchema: z.ZodEnum<{
|
|
13
|
+
fix_request: "fix_request";
|
|
14
|
+
authenticate: "authenticate";
|
|
15
|
+
check_permissions: "check_permissions";
|
|
16
|
+
check_scope: "check_scope";
|
|
17
|
+
resolve_conflict: "resolve_conflict";
|
|
18
|
+
reload_state: "reload_state";
|
|
19
|
+
retry_same_request: "retry_same_request";
|
|
20
|
+
configure_integration: "configure_integration";
|
|
21
|
+
check_availability: "check_availability";
|
|
22
|
+
upgrade_sdk: "upgrade_sdk";
|
|
23
|
+
recover_operation: "recover_operation";
|
|
24
|
+
contact_support: "contact_support";
|
|
25
|
+
}>;
|
|
26
|
+
type ErrorRecovery = z.infer<typeof errorRecoverySchema>;
|
|
27
|
+
/** Safe business reasons; never SQL text, resource IDs or provider responses. */
|
|
28
|
+
declare const errorReasonSchema: z.ZodEnum<{
|
|
29
|
+
CAPABILITY_NOT_ENABLED: "CAPABILITY_NOT_ENABLED";
|
|
30
|
+
INTEGRATION_MISSING: "INTEGRATION_MISSING";
|
|
31
|
+
PROVIDER_CREDENTIAL_REJECTED: "PROVIDER_CREDENTIAL_REJECTED";
|
|
32
|
+
PRICE_BINDING_REQUIRED: "PRICE_BINDING_REQUIRED";
|
|
33
|
+
IDEMPOTENCY_CONFLICT: "IDEMPOTENCY_CONFLICT";
|
|
34
|
+
RESULT_UNKNOWN: "RESULT_UNKNOWN";
|
|
35
|
+
STATE_CHANGED: "STATE_CHANGED";
|
|
36
|
+
OPERATION_IN_PROGRESS: "OPERATION_IN_PROGRESS";
|
|
37
|
+
FUNNEL_VERSION_RETIRED: "FUNNEL_VERSION_RETIRED";
|
|
38
|
+
}>;
|
|
39
|
+
type ErrorReason = z.infer<typeof errorReasonSchema>;
|
|
40
|
+
|
|
41
|
+
declare class IndianaError extends Error {
|
|
42
|
+
readonly code: string;
|
|
43
|
+
readonly status?: number | undefined;
|
|
44
|
+
readonly requestId?: string | undefined;
|
|
45
|
+
readonly retryable: boolean;
|
|
46
|
+
readonly recovery: ErrorRecovery;
|
|
47
|
+
readonly retryAfterSeconds?: number;
|
|
48
|
+
readonly reason?: ErrorReason;
|
|
49
|
+
constructor(code: string, message: string, status?: number | undefined, requestId?: string | undefined, metadata?: {
|
|
50
|
+
retryable?: boolean;
|
|
51
|
+
recovery?: ErrorRecovery;
|
|
52
|
+
retryAfterSeconds?: number;
|
|
53
|
+
reason?: ErrorReason;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export { IndianaError as I, type Scope as S };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as ne}from"./chunk-6X42DWOM.js";import"./chunk-FVUPV6YE.js";import{Gd as ve,ui as me}from"./chunk-FF3LWJ26.js";import{a as w}from"./chunk-5TEZEOHX.js";import{Gb as Ce}from"./chunk-RMJJOSVZ.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import"./chunk-S2MSIA57.js";function be(E){let F=E.view;if(!F?.paywall)throw new w("INVALID_REQUEST","The current node is not a Paywall");let n=F.paywall.receiptId,Z=F.nodeId,te=F.visit,m=F.paywall.resolution,R=F.paywall.quote,g=F.paywall.operation,S=!1,V=new AbortController,v=F.paywall.purchaseRequestId,k=0,U=F.paywall.selectionGeneration??0,L=F.paywall.canReselect===!0,T=null,j=new Map,$=new Map;function D(t){if(t.purchase&&t.purchase.receiptId!==n)throw new w("INVALID_RESPONSE","Purchase receipt changed");let i=t.run.paywall;return t.purchase??(i?.receiptId===n?i:null)}function b(){if(S)throw new w("IDENTITY_CHANGED","Paywall presentation has closed")}function O(t,i,s){if(b(),i!==k||s!==void 0&&R?.operationId!==s)return!1;let h=U,a=t.run.paywall;if(a?.receiptId===n){if((a.selectionGeneration??0)<U)return!1;if(U=a.selectionGeneration??0,L=a.canReselect===!0,a.resolution.id!==m.id||a.resolution.offering.id!==m.offering.id)throw new w("INVALID_RESPONSE","The pinned Paywall binding changed")}let c=D(t),l=U>h,P=l?c?.quote??null:c?.quote??R,N=c?.operation??(P?.operationId===R?.operationId?g:null);if(P&&N&&P.operationId!==N.operationId)throw new w("INVALID_RESPONSE","Purchase operation changed");return a?.receiptId===n&&(m=a.resolution),(l||P?.operationId!==R?.operationId)&&(k++,a?.receiptId===n&&(v=a.purchaseRequestId)),R=P,(g?.operationId!==N?.operationId||g?.status==="pending"||N?.status==="complete")&&(g=N),!0}function z(t,i,s){return new Promise((h,a)=>{let c=!1,l=()=>{clearTimeout(ie),V.signal.removeEventListener("abort",M)},P=ee=>{c||(c=!0,l(),h(ee))},N=ee=>{c||(c=!0,l(),a(ee))},M=()=>N(new w("IDENTITY_CHANGED","Paywall presentation has closed")),ie=setTimeout(()=>N(new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s)),Math.max(0,i-Date.now()));V.signal.addEventListener("abort",M,{once:!0}),V.signal.aborted&&M(),t.then(P,N)})}function x(t){return new Promise(i=>{let s=()=>{clearTimeout(h),V.signal.removeEventListener("abort",s),i()},h=setTimeout(s,t);V.signal.addEventListener("abort",s,{once:!0}),V.signal.aborted&&s()})}async function W(t,i,s){b();let h=j.get(t);if(!h){let l=E.pendingCommands?.find(P=>P.requestId===t)??E.pendingCommand;if(l?.operation==="submit"&&l.requestId===t&&l.nodeId===Z&&l.visit===te){i.type==="paywall_quote"&&l.input.type==="paywall_quote"&&l.input.predecessor&&!i.predecessor&&(i={...i,predecessor:l.input.predecessor});let P=me.parse(l),N=me.parse({...l,input:i});if(N.operation!=="submit"||P.operation!=="submit"||JSON.stringify(N.input)!==JSON.stringify(P.input))throw new w("CONFLICT","A restored purchase request cannot change its input");i=N.input,h=P,j.set(t,h)}}if(h){if(JSON.stringify(h.input)!==JSON.stringify(i))throw new w("CONFLICT","A purchase request cannot change its input")}else{let l=E.view;if(!l||l.nodeId!==Z||l.visit!==te||l.paywall?.receiptId!==n)throw new w("PRECONDITION_FAILED","The Paywall visit has changed");h={operation:"submit",requestId:t,nodeId:Z,visit:te,revision:l.revision,input:i},j.set(t,h)}let a=Date.now()+3e4,c=await z(E.submit(h),a,t);for(;c.run.pendingRequest?.requestId===t&&Date.now()<a&&!S&&(await x(Math.min(1e3,a-Date.now())),!(S||Date.now()>=a));)c=await z(E.resume(t),a,t);if(S)throw new w("IDENTITY_CHANGED","Paywall presentation has closed");if(c.run.pendingRequest?.requestId===t)throw new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!O(c,s,i.type==="paywall_confirm"||i.type==="paywall_cancel"?i.operationId:void 0))throw new w("PRECONDITION_FAILED","The purchase selection has changed")}async function K(t){if(!R)throw new w("INVALID_REQUEST","A quoted purchase is required");let i=`${t}:${R.operationId}`,s=$.get(i);if(!s){let h=t==="confirm"?"paywall_confirm":"paywall_cancel",a=E.pendingCommands?.find(c=>c.operation==="submit"&&c.input.type===h&&"operationId"in c.input&&c.input.operationId===R.operationId)??E.pendingCommand;s=a?.operation==="submit"&&a.input.type===h&&"operationId"in a.input&&a.input.operationId===R.operationId?a.requestId:crypto.randomUUID(),$.set(i,s)}if(await W(s,{type:t==="confirm"?"paywall_confirm":"paywall_cancel",operationId:R.operationId},k),!g)throw new w("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(g)}return{get view(){return structuredClone(m)},get quote(){return R?structuredClone(R):null},get operation(){return g?structuredClone(g):null},get webViewUrl(){return E.webViewUrl},get canReselect(){return L},async refresh(){b();let t=k;return O(await E.get(),t),structuredClone(m)},preview(t){if(v&&v!==t.requestId&&(T||!L))return Promise.reject(new w("COMMAND_PENDING","Retry the original purchase before starting another"));if(v===t.requestId&&T)return T;let i=m.document.buttons[t.actionId],s=i?.type==="checkout"?ve(i.product,t.selection,m.capabilities):null;if(!s)return Promise.reject(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let h=v!==t.requestId&&U>0?{operationId:R?.operationId??null,generation:U}:void 0;if(h&&(!L||U<=0))return Promise.reject(new w("COMMAND_PENDING","Original purchase requires authoritative termination"));v!==t.requestId&&k++;let a=k;v=t.requestId;let c=(async()=>{if(await W(t.requestId,{type:"paywall_quote",actionId:t.actionId,productVersionId:s,...h?{predecessor:h}:{},...t.offerId?{offerId:t.offerId}:{},...t.nativeOffer?{nativeOffer:t.nativeOffer}:{}},a),!R)throw new w("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(R)})();return T=c,c.then(()=>{T===c&&(T=null)},l=>{T===c&&(T=null),v===t.requestId&&E.pendingCommand?.requestId!==t.requestId&&l instanceof w&&l.status!==void 0&&l.status<500&&![401,425].includes(l.status)&&(v=null)}),c},confirm:()=>K("confirm"),cancel:()=>K("cancel"),async read(){if(b(),!R)throw new w("INVALID_REQUEST","A quoted purchase is required");let t=R.operationId,i=k,s=E.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===t)??E.pendingCommand;s?.operation==="submit"&&(s.input.type==="paywall_confirm"||s.input.type==="paywall_cancel")&&s.input.operationId===t&&await E.settle?.(s.requestId);let h=await E.get(void 0,{receiptId:n,operationId:t});b();let a=D(h);if(a?.quote&&a.quote.operationId!==t||a?.operation&&a.operation.operationId!==t)throw new w("INVALID_RESPONSE","Purchase operation changed");let c=O(h,i,t)?g:a?.operation;if(!c)throw new w("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(c)},destroy(){S=!0,V.abort(),j.clear(),$.clear()}}}async function Fe(E,F){let n=F,{mountScreenPreview:Z}=await import("./popup.js"),{showPaywall:te}=await import("./paywall-5WU6PX5C.js"),m=E.ownerDocument,R=m.activeElement,g=m.createElement("section"),S=m.createElement("div"),V=m.createElement("div"),v=m.createElement("div"),k=m.createElement("button");v.hidden=!0,k.type="button";let U=m.createElement("p"),L=m.createElement("p"),T=m.createElement("button"),j=m.createElement("button"),$=m.createElement("button"),D=m.createElement("dialog");g.dataset.indianaFunnel="",g.setAttribute("aria-busy","false"),g.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",V.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",U.setAttribute("role","status"),L.setAttribute("role","alert"),L.hidden=!0,T.type=j.type=$.type="button",V.append(T,U,L,$,k,j),g.append(S,v,V),E.append(g);let b=null,O=null,z=null,x="",W="",K="",t="",i=!1,s=0,h=!1,a="",c=null,l=Promise.resolve(),P=null,N=null,M={},ie=new Map,ee=new Set,se=new Set,ae=new Set,oe=null,H={},C=!1,he,G=0,q=null,re="",le=new Map,ye=e=>e?`${e.id}:${e.nodeId}:${e.visit}:${e.revision}:${e.paywall?.quote?.operationId??""}`:"",J=(e,o=null)=>{i||(N=o,L.textContent=e instanceof Error?e.message:"Request failed",L.hidden=!1,$.hidden=n.client.pendingCommand===null,ne(n.onError,e))};function B(){let e=n.client.view;if(!e)throw new w("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}async function Y(e,o=!1){if(!(s&&!o||i||(C||n.client.view?.recoveryRestricted)&&!o)){s++,g.setAttribute("aria-busy","true"),L.hidden=!0,N=null;try{if(!o&&oe){let r=n.client.view;await oe;let y=n.client.view;if(!r||!y||y.id!==r.id||y.nodeId!==r.nodeId||y.visit!==r.visit||y.stopped||!["running","waiting"].includes(y.status))throw new w("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(i)return;let d=await e();i||await X(n.client.view??d.run)}catch(d){J(d,n.client.pendingCommand?.requestId??null)}finally{s=Math.max(0,s-1),g.setAttribute("aria-busy",String(s>0)),i||($.hidden=n.client.pendingCommand===null,T.disabled=s>0||!!n.client.pendingCommand||!n.client.view?.canBack)}}}function ge(e){if(C||ee.has(e)||se.has(e)||i)return;se.add(e);let o=async()=>{if(C||i||x!==e){se.delete(e);return}if(s||n.client.pendingCommand){setTimeout(()=>{o()},250);return}let d=(async()=>{let y=n.client.view,p=B(),A=p.requestId,u=!1;try{await n.client.submit({operation:"shown",...p})}catch(I){if(!(I instanceof w)||I.code!=="CONFLICT"||I.status!==409||n.client.pendingCommand)throw I;await n.client.get();let f=n.client.view;if(i||C||x!==e||!f||!y||f.id!==y.id||f.source.versionId!==y.source.versionId||f.nodeId!==p.nodeId||f.visit!==p.visit||f.revision<=p.revision||f.stopped||!f.screen||!["running","waiting"].includes(f.status)||n.client.pendingCommand)throw I;let _=B();A=_.requestId,await n.client.submit({operation:"shown",..._})}for(;!i&&x===e&&n.client.pendingCommand?.requestId===A;){if(!n.client.settle)throw new w("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(A),u=!0,n.client.pendingCommand?.requestId===A&&await new Promise(I=>setTimeout(I,1500))}i||x!==e||(u&&await n.client.get(),!(i||x!==e)&&ee.add(e))})();oe=d;let r=()=>{oe===d&&(oe=null),se.delete(e)};d.then(r,y=>{r(),s||J(y)})};o()}function ue(){c&&clearTimeout(c),!(i||!z||!["running","waiting"].includes(z.status)&&!n.client.pendingCommand)&&(c=setTimeout(()=>{c=null,Ie().finally(ue)},z.pendingRequest||n.client.pendingCommand?1500:5e3))}async function Ie(){if(!(i||h||s)){if(C){await ce(he);return}h=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let o=n.client.view,d=M,r=await n.client.get(o?.screen&&Object.keys(d).length?{nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:d}:void 0);!i&&d===M&&await X(n.client.view??r.run)}catch(e){J(e)}finally{h=!1}}}async function Ee(e){let o=n.client.view,d=o?.screen,r=d?.customerData.nodes[e.nodeId];if(i||s||!o||!d||!r)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(e.action)){let _=b?.document,Q=_?Ce(_,e.nodeId):null,we=Q?.type==="customer_data"?Q.data.outputs?.[e.action]:void 0;we&&d.outputs.includes(we)?await Y(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:we,answers:H,selection:e.value?{[e.nodeId]:e.value}:{}}})):await n.onCustomerDataIntent?.(e,o);return}let p=e.action.startsWith("sources_")?r.resources.find(_=>_.key===e.value):null;if(e.action.startsWith("sources_")&&!p)throw new w("INVALID_REQUEST","Choose a current resource");let A=`${o.visit}:${e.nodeId}:${p?.key??""}`,u=ie.get(A)??[null],f=M[e.nodeId]??{page:1,after:null,filter:"all",...p?{resourceKey:p.key}:{}};if(e.action==="filter"){let _=e.value;if(!_||!(r.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(_))throw new w("INVALID_REQUEST","Unknown data filter");f={page:1,after:null,filter:_},u.splice(0,u.length,null)}else if(e.action==="next"||e.action==="sources_next"){let _=p?.sources.at(-1),Q=p?_?{kind:"ledger",cursor:{at:_.detail[0],id:_.id,type:"source"}}:null:d.dataCursors[e.nodeId];if(!Q||!p&&!r.hasNext)return;u[f.page]=Q,f={...f,page:f.page+1,after:Q}}else if(e.action==="previous"||e.action==="sources_previous"){if(f.page<=1)return;f={...f,page:f.page-1,after:u[f.page-2]??null}}ie.set(A,u),M={...M,[e.nodeId]:f},await Y(()=>n.client.get({nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:M}))}function Re(e){let o=e.screen?.presentation;if(!o||o.type==="inline"){D.open&&D.close(),g.parentElement!==E&&E.append(g);return}g.parentElement!==D&&(D.append(g),E.append(D));let d={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?d[o.size]+"px":"100vw"}`,D.setAttribute("aria-label",b?.document?.name??e.screen?.content.document.name??"Funnel"),D.open||D.showModal()}async function De(e){if(i)return;z=e,N&&n.client.pendingCommand?.requestId!==N&&(L.hidden=!0,N=null);let o=e.locale.startsWith("zh");if(k.textContent=o?"\u56DE\u770B":"History",k.hidden=!n.client.review,T.textContent=C?o?"\u8FD4\u56DE\u5F53\u524D":"Return to current":o?"\u8FD4\u56DE":"Back",j.textContent=o?"\u5173\u95ED":"Close",$.textContent=o?"\u91CD\u8BD5":"Retry",T.disabled=!C&&(s>0||!!n.client.pendingCommand||!e.canBack),$.hidden=n.client.pendingCommand===null,U.textContent=e.pendingRequest?o?"\u6B63\u5728\u5904\u7406":"Processing":e.instruction?.type==="wait"?o?"\u7B49\u5F85\u4E2D":"Waiting":"",a!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(a=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,ne(n.onState,structuredClone(e))),e.stopped||n.client.configurationReady===!1){C=!1,G++,q?.destroy(),q=null,v.replaceChildren(),v.hidden=!0,S.hidden=!1,b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x="",W="",t="",D.open&&D.close(),g.hidden=!0,ue();return}if(g.hidden=!1,C){ue();return}if(e.recoveryRestricted){b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x="",U.textContent=o?"\u539F\u8BB0\u5F55\u9700\u8981\u6838\u5BF9\uFF0C\u53EF\u53EA\u8BFB\u56DE\u770B":"Original records require reconciliation; read-only history is available";return}let d=e.screen||e.paywall?`${e.id}:${e.nodeId}:${e.visit}`:"";if(d!==x&&(b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x=d,W="",t="",H={...e.answers},M={},ie.clear()),Re(e),e.screen){let y=e.screen.content;b||(b=Z(S,{mode:"live",rendererUrl:n.client.webViewUrl,title:y.document.name,onAction(u,I={},f={}){if(C)return;H={...H,...f};let _=Object.fromEntries((e.screen?.inputs??[]).filter(({variable:Q})=>Object.hasOwn(H,Q)).map(({variable:Q})=>[Q,H[Q]]));Y(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:u,answers:_,selection:I}}))},onAnswers:u=>{C||(H={...H,...u})},onCustomerDataIntent:u=>{C||Ee(u).catch(J)},onEscape:()=>{C||de()},onError:u=>J(new Error(u)),onRendered:()=>ge(d)}));let p={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:H,values:e.screen.values}},A=JSON.stringify([y,e.locale,p.parameters,e.screen.inputs,e.screen.values]);if(A!==W)b.update(y.document,e.locale,p),W=A,K=JSON.stringify(p.capabilities),t=JSON.stringify(p.customerData);else{let u=JSON.stringify(p.capabilities);u!==K&&(b.updateCapabilities(p.capabilities),K=u),JSON.stringify(p.customerData)!==t&&(b.updateCustomerData(p.customerData),t=JSON.stringify(p.customerData))}await b.ready}else if(e.paywall&&!O){let y=await te(S,{canInteract:()=>!C&&!i&&!n.client.view?.recoveryRestricted,start:async()=>be(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:p=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:p,openIn:"same_window"}):m.defaultView?.location.assign(p),onAction:async p=>{if(C)return;let A=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision,input:{type:"screen",output:p,answers:{}}});await X(n.client.view??A.run)},onError:J,onDismiss:()=>{!C&&!i&&n.client.view?.visit===e.visit&&de()}});i?y.host?.destroy():(O=y.host,O?.setSuspended(C)),ge(d)}let r=e.instruction;if(r&&(r.type==="open_url"||r.type==="event")&&!ae.has(r.receiptId)){let y=m.createElement("button");y.type="button",y.textContent=r.type==="open_url"?`${o?"\u524D\u5F80":"Continue to"} ${new URL(r.url).host}`:o?"\u7EE7\u7EED":"Continue",y.onclick=()=>{let p=B(),A=r.type==="open_url"&&!n.onOpenUrl&&r.openIn==="new_window"?Pe(r.url):null;Y(async()=>{let u="success";if(r.type==="open_url")if(n.onOpenUrl)try{u=await n.onOpenUrl({receiptId:r.receiptId,url:r.url,openIn:r.openIn})===!1?"failed":"opened"}catch(f){ne(n.onError,f),u="failed"}else u=r.openIn==="new_window"&&!A?"failed":"opened";if(r.type==="event"){if(!n.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(r.event)}if(i||n.client.view?.nodeId!==p.nodeId||n.client.view.visit!==p.visit)throw new w("PRECONDITION_FAILED","The client action visit changed");let I=await n.client.submit({operation:"submit",...p,input:{type:"client_action",receiptId:r.receiptId,outcome:u}});return ae.add(r.receiptId),r.type==="open_url"&&!n.onOpenUrl&&r.openIn==="same_window"&&m.defaultView?.location.assign(r.url),I})},S.replaceChildren(y)}!e.pendingRequest&&e.status==="completed"&&!ae.has(`complete:${e.id}`)&&(ae.add(`complete:${e.id}`),ne(n.onComplete,structuredClone(e))),ue()}function Pe(e){let o=m.defaultView?.open(e,"_blank")??null;return o&&(o.opener=null),o}function X(e){return l=l.catch(()=>{}).then(()=>De(e)),l}async function ce(e){if(i||!n.client.review)return;C||(re=ye(n.client.view),le.set(re,structuredClone(H))),C=!0,he=e,S.hidden=!0,O?.setSuspended(!0),v.hidden=!1;let o=++G;try{let d=await n.client.review(e);if(i||o!==G||!C)return;if(!d.review)throw new w("INVALID_RESPONSE","Historical projection is missing");q?.destroy(),q=null,v.replaceChildren();let r=d.run.locale.startsWith("zh"),y=m.createElement("p");y.textContent=r?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",v.append(y);for(let[u,I]of d.review.pages.entries()){let f=m.createElement("button");f.type="button",f.textContent=r?`\u7B2C ${u+1} \u9875`:`Page ${u+1}`,f.onclick=()=>{ce(I.receiptId)},v.append(f)}if(d.review.page){let u=d.review.page,I=m.createElement("div");if(I.inert=!0,v.append(I),q=Z(I,{mode:"live",rendererUrl:n.client.webViewUrl,title:u.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{fe()}}),q.update(u.document,d.run.locale,{serverInput:{bindings:u.inputs,answers:u.answers,values:u.values}}),await q.ready,i||o!==G||!C)return}let p=r?{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"},A=r?{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 u of[...d.review.coupons.map((I,f)=>`${r?"\u4F18\u60E0\u5238":"Coupon"} ${f+1}: ${p[I.status]}`),...d.review.purchases.map((I,f)=>`${r?"\u8D2D\u4E70":"Purchase"} ${f+1}: ${A[I.status]}`)]){let I=m.createElement("p");I.textContent=u,v.append(I)}n.client.view&&await X(n.client.view)}catch(d){if(o!==G||i)return;q?.destroy(),q=null,v.replaceChildren(),J(d)}}async function fe(){if(!C||i||!n.client.review)return;let e=++G;try{if(await n.client.review(),i||e!==G)return;C=!1,G++,q?.destroy(),q=null,v.replaceChildren(),v.hidden=!0,S.hidden=!1;let o=n.client.view;ye(o)!==re?(le.set(re,structuredClone(H)),x="",W=""):(le.delete(re),O?.setSuspended(!1)),o&&await X(o)}catch(o){if(e!==G||i)return;q?.destroy(),q=null,v.replaceChildren(),J(o)}}let Ne=n.client.subscribe(e=>{n.client.configurationReady===!1&&(g.hidden=!0,b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x="",W="",t="",D.open&&D.close()),X(e).catch(J)}),Oe=n.client.subscribeError?.(J);function de(){return P||(i?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(pe(),Promise.resolve()):(P=Y(()=>n.client.submit({operation:"close",...B()}),!0).then(()=>{n.client.view?.status==="closed"&&pe()}).finally(()=>{P=null}),P))}function pe(){i||(i=!0,c&&clearTimeout(c),Ne(),Oe?.(),b?.destroy(),G++,q?.destroy(),O?.destroy(),D.close(),D.remove(),g.remove(),R instanceof HTMLElement&&R.isConnected&&R.focus(),ne(n.onDismiss,z?structuredClone(z):null))}T.onclick=()=>{if(C){fe();return}Y(()=>n.client.submit({operation:"back",...B()}))},k.onclick=()=>{ce()},j.onclick=()=>{de()},$.onclick=()=>{Y(()=>n.client.retry())},D.addEventListener("cancel",e=>{e.preventDefault(),de()});try{let e=await n.client.get();await X(n.client.view??e.run)}catch(e){throw pe(),e}return{destroy:pe,refresh:Ie,review:ce,exitReview:fe,get unappliedDrafts(){return new Map([...le].map(([e,o])=>[e,structuredClone(o)]))}}}export{Fe as showFunnelRun};
|
|
1
|
+
import{a as ne}from"./chunk-6X42DWOM.js";import"./chunk-QG3WUJG5.js";import{Gd as ve,ui as me}from"./chunk-HTRQPMJO.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import{a as w}from"./chunk-5TEZEOHX.js";import{Gb as Ce}from"./chunk-RMJJOSVZ.js";import"./chunk-S2MSIA57.js";function be(E){let F=E.view;if(!F?.paywall)throw new w("INVALID_REQUEST","The current node is not a Paywall");let n=F.paywall.receiptId,Z=F.nodeId,te=F.visit,m=F.paywall.resolution,R=F.paywall.quote,g=F.paywall.operation,S=!1,V=new AbortController,v=F.paywall.purchaseRequestId,k=0,U=F.paywall.selectionGeneration??0,L=F.paywall.canReselect===!0,T=null,j=new Map,$=new Map;function D(t){if(t.purchase&&t.purchase.receiptId!==n)throw new w("INVALID_RESPONSE","Purchase receipt changed");let i=t.run.paywall;return t.purchase??(i?.receiptId===n?i:null)}function b(){if(S)throw new w("IDENTITY_CHANGED","Paywall presentation has closed")}function O(t,i,s){if(b(),i!==k||s!==void 0&&R?.operationId!==s)return!1;let h=U,a=t.run.paywall;if(a?.receiptId===n){if((a.selectionGeneration??0)<U)return!1;if(U=a.selectionGeneration??0,L=a.canReselect===!0,a.resolution.id!==m.id||a.resolution.offering.id!==m.offering.id)throw new w("INVALID_RESPONSE","The pinned Paywall binding changed")}let c=D(t),l=U>h,P=l?c?.quote??null:c?.quote??R,N=c?.operation??(P?.operationId===R?.operationId?g:null);if(P&&N&&P.operationId!==N.operationId)throw new w("INVALID_RESPONSE","Purchase operation changed");return a?.receiptId===n&&(m=a.resolution),(l||P?.operationId!==R?.operationId)&&(k++,a?.receiptId===n&&(v=a.purchaseRequestId)),R=P,(g?.operationId!==N?.operationId||g?.status==="pending"||N?.status==="complete")&&(g=N),!0}function z(t,i,s){return new Promise((h,a)=>{let c=!1,l=()=>{clearTimeout(ie),V.signal.removeEventListener("abort",M)},P=ee=>{c||(c=!0,l(),h(ee))},N=ee=>{c||(c=!0,l(),a(ee))},M=()=>N(new w("IDENTITY_CHANGED","Paywall presentation has closed")),ie=setTimeout(()=>N(new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s)),Math.max(0,i-Date.now()));V.signal.addEventListener("abort",M,{once:!0}),V.signal.aborted&&M(),t.then(P,N)})}function x(t){return new Promise(i=>{let s=()=>{clearTimeout(h),V.signal.removeEventListener("abort",s),i()},h=setTimeout(s,t);V.signal.addEventListener("abort",s,{once:!0}),V.signal.aborted&&s()})}async function W(t,i,s){b();let h=j.get(t);if(!h){let l=E.pendingCommands?.find(P=>P.requestId===t)??E.pendingCommand;if(l?.operation==="submit"&&l.requestId===t&&l.nodeId===Z&&l.visit===te){i.type==="paywall_quote"&&l.input.type==="paywall_quote"&&l.input.predecessor&&!i.predecessor&&(i={...i,predecessor:l.input.predecessor});let P=me.parse(l),N=me.parse({...l,input:i});if(N.operation!=="submit"||P.operation!=="submit"||JSON.stringify(N.input)!==JSON.stringify(P.input))throw new w("CONFLICT","A restored purchase request cannot change its input");i=N.input,h=P,j.set(t,h)}}if(h){if(JSON.stringify(h.input)!==JSON.stringify(i))throw new w("CONFLICT","A purchase request cannot change its input")}else{let l=E.view;if(!l||l.nodeId!==Z||l.visit!==te||l.paywall?.receiptId!==n)throw new w("PRECONDITION_FAILED","The Paywall visit has changed");h={operation:"submit",requestId:t,nodeId:Z,visit:te,revision:l.revision,input:i},j.set(t,h)}let a=Date.now()+3e4,c=await z(E.submit(h),a,t);for(;c.run.pendingRequest?.requestId===t&&Date.now()<a&&!S&&(await x(Math.min(1e3,a-Date.now())),!(S||Date.now()>=a));)c=await z(E.resume(t),a,t);if(S)throw new w("IDENTITY_CHANGED","Paywall presentation has closed");if(c.run.pendingRequest?.requestId===t)throw new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!O(c,s,i.type==="paywall_confirm"||i.type==="paywall_cancel"?i.operationId:void 0))throw new w("PRECONDITION_FAILED","The purchase selection has changed")}async function K(t){if(!R)throw new w("INVALID_REQUEST","A quoted purchase is required");let i=`${t}:${R.operationId}`,s=$.get(i);if(!s){let h=t==="confirm"?"paywall_confirm":"paywall_cancel",a=E.pendingCommands?.find(c=>c.operation==="submit"&&c.input.type===h&&"operationId"in c.input&&c.input.operationId===R.operationId)??E.pendingCommand;s=a?.operation==="submit"&&a.input.type===h&&"operationId"in a.input&&a.input.operationId===R.operationId?a.requestId:crypto.randomUUID(),$.set(i,s)}if(await W(s,{type:t==="confirm"?"paywall_confirm":"paywall_cancel",operationId:R.operationId},k),!g)throw new w("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(g)}return{get view(){return structuredClone(m)},get quote(){return R?structuredClone(R):null},get operation(){return g?structuredClone(g):null},get webViewUrl(){return E.webViewUrl},get canReselect(){return L},async refresh(){b();let t=k;return O(await E.get(),t),structuredClone(m)},preview(t){if(v&&v!==t.requestId&&(T||!L))return Promise.reject(new w("COMMAND_PENDING","Retry the original purchase before starting another"));if(v===t.requestId&&T)return T;let i=m.document.buttons[t.actionId],s=i?.type==="checkout"?ve(i.product,t.selection,m.capabilities):null;if(!s)return Promise.reject(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let h=v!==t.requestId&&U>0?{operationId:R?.operationId??null,generation:U}:void 0;if(h&&(!L||U<=0))return Promise.reject(new w("COMMAND_PENDING","Original purchase requires authoritative termination"));v!==t.requestId&&k++;let a=k;v=t.requestId;let c=(async()=>{if(await W(t.requestId,{type:"paywall_quote",actionId:t.actionId,productVersionId:s,...h?{predecessor:h}:{},...t.offerId?{offerId:t.offerId}:{},...t.nativeOffer?{nativeOffer:t.nativeOffer}:{}},a),!R)throw new w("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(R)})();return T=c,c.then(()=>{T===c&&(T=null)},l=>{T===c&&(T=null),v===t.requestId&&E.pendingCommand?.requestId!==t.requestId&&l instanceof w&&l.status!==void 0&&l.status<500&&![401,425].includes(l.status)&&(v=null)}),c},confirm:()=>K("confirm"),cancel:()=>K("cancel"),async read(){if(b(),!R)throw new w("INVALID_REQUEST","A quoted purchase is required");let t=R.operationId,i=k,s=E.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===t)??E.pendingCommand;s?.operation==="submit"&&(s.input.type==="paywall_confirm"||s.input.type==="paywall_cancel")&&s.input.operationId===t&&await E.settle?.(s.requestId);let h=await E.get(void 0,{receiptId:n,operationId:t});b();let a=D(h);if(a?.quote&&a.quote.operationId!==t||a?.operation&&a.operation.operationId!==t)throw new w("INVALID_RESPONSE","Purchase operation changed");let c=O(h,i,t)?g:a?.operation;if(!c)throw new w("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(c)},destroy(){S=!0,V.abort(),j.clear(),$.clear()}}}async function Fe(E,F){let n=F,{mountScreenPreview:Z}=await import("./popup.js"),{showPaywall:te}=await import("./paywall-4XZ6NDMY.js"),m=E.ownerDocument,R=m.activeElement,g=m.createElement("section"),S=m.createElement("div"),V=m.createElement("div"),v=m.createElement("div"),k=m.createElement("button");v.hidden=!0,k.type="button";let U=m.createElement("p"),L=m.createElement("p"),T=m.createElement("button"),j=m.createElement("button"),$=m.createElement("button"),D=m.createElement("dialog");g.dataset.indianaFunnel="",g.setAttribute("aria-busy","false"),g.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",V.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",U.setAttribute("role","status"),L.setAttribute("role","alert"),L.hidden=!0,T.type=j.type=$.type="button",V.append(T,U,L,$,k,j),g.append(S,v,V),E.append(g);let b=null,O=null,z=null,x="",W="",K="",t="",i=!1,s=0,h=!1,a="",c=null,l=Promise.resolve(),P=null,N=null,M={},ie=new Map,ee=new Set,se=new Set,ae=new Set,oe=null,H={},C=!1,he,G=0,q=null,re="",le=new Map,ye=e=>e?`${e.id}:${e.nodeId}:${e.visit}:${e.revision}:${e.paywall?.quote?.operationId??""}`:"",J=(e,o=null)=>{i||(N=o,L.textContent=e instanceof Error?e.message:"Request failed",L.hidden=!1,$.hidden=n.client.pendingCommand===null,ne(n.onError,e))};function B(){let e=n.client.view;if(!e)throw new w("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}async function Y(e,o=!1){if(!(s&&!o||i||(C||n.client.view?.recoveryRestricted)&&!o)){s++,g.setAttribute("aria-busy","true"),L.hidden=!0,N=null;try{if(!o&&oe){let r=n.client.view;await oe;let y=n.client.view;if(!r||!y||y.id!==r.id||y.nodeId!==r.nodeId||y.visit!==r.visit||y.stopped||!["running","waiting"].includes(y.status))throw new w("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(i)return;let d=await e();i||await X(n.client.view??d.run)}catch(d){J(d,n.client.pendingCommand?.requestId??null)}finally{s=Math.max(0,s-1),g.setAttribute("aria-busy",String(s>0)),i||($.hidden=n.client.pendingCommand===null,T.disabled=s>0||!!n.client.pendingCommand||!n.client.view?.canBack)}}}function ge(e){if(C||ee.has(e)||se.has(e)||i)return;se.add(e);let o=async()=>{if(C||i||x!==e){se.delete(e);return}if(s||n.client.pendingCommand){setTimeout(()=>{o()},250);return}let d=(async()=>{let y=n.client.view,p=B(),A=p.requestId,u=!1;try{await n.client.submit({operation:"shown",...p})}catch(I){if(!(I instanceof w)||I.code!=="CONFLICT"||I.status!==409||n.client.pendingCommand)throw I;await n.client.get();let f=n.client.view;if(i||C||x!==e||!f||!y||f.id!==y.id||f.source.versionId!==y.source.versionId||f.nodeId!==p.nodeId||f.visit!==p.visit||f.revision<=p.revision||f.stopped||!f.screen||!["running","waiting"].includes(f.status)||n.client.pendingCommand)throw I;let _=B();A=_.requestId,await n.client.submit({operation:"shown",..._})}for(;!i&&x===e&&n.client.pendingCommand?.requestId===A;){if(!n.client.settle)throw new w("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(A),u=!0,n.client.pendingCommand?.requestId===A&&await new Promise(I=>setTimeout(I,1500))}i||x!==e||(u&&await n.client.get(),!(i||x!==e)&&ee.add(e))})();oe=d;let r=()=>{oe===d&&(oe=null),se.delete(e)};d.then(r,y=>{r(),s||J(y)})};o()}function ue(){c&&clearTimeout(c),!(i||!z||!["running","waiting"].includes(z.status)&&!n.client.pendingCommand)&&(c=setTimeout(()=>{c=null,Ie().finally(ue)},z.pendingRequest||n.client.pendingCommand?1500:5e3))}async function Ie(){if(!(i||h||s)){if(C){await ce(he);return}h=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let o=n.client.view,d=M,r=await n.client.get(o?.screen&&Object.keys(d).length?{nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:d}:void 0);!i&&d===M&&await X(n.client.view??r.run)}catch(e){J(e)}finally{h=!1}}}async function Ee(e){let o=n.client.view,d=o?.screen,r=d?.customerData.nodes[e.nodeId];if(i||s||!o||!d||!r)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(e.action)){let _=b?.document,Q=_?Ce(_,e.nodeId):null,we=Q?.type==="customer_data"?Q.data.outputs?.[e.action]:void 0;we&&d.outputs.includes(we)?await Y(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:we,answers:H,selection:e.value?{[e.nodeId]:e.value}:{}}})):await n.onCustomerDataIntent?.(e,o);return}let p=e.action.startsWith("sources_")?r.resources.find(_=>_.key===e.value):null;if(e.action.startsWith("sources_")&&!p)throw new w("INVALID_REQUEST","Choose a current resource");let A=`${o.visit}:${e.nodeId}:${p?.key??""}`,u=ie.get(A)??[null],f=M[e.nodeId]??{page:1,after:null,filter:"all",...p?{resourceKey:p.key}:{}};if(e.action==="filter"){let _=e.value;if(!_||!(r.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(_))throw new w("INVALID_REQUEST","Unknown data filter");f={page:1,after:null,filter:_},u.splice(0,u.length,null)}else if(e.action==="next"||e.action==="sources_next"){let _=p?.sources.at(-1),Q=p?_?{kind:"ledger",cursor:{at:_.detail[0],id:_.id,type:"source"}}:null:d.dataCursors[e.nodeId];if(!Q||!p&&!r.hasNext)return;u[f.page]=Q,f={...f,page:f.page+1,after:Q}}else if(e.action==="previous"||e.action==="sources_previous"){if(f.page<=1)return;f={...f,page:f.page-1,after:u[f.page-2]??null}}ie.set(A,u),M={...M,[e.nodeId]:f},await Y(()=>n.client.get({nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:M}))}function Re(e){let o=e.screen?.presentation;if(!o||o.type==="inline"){D.open&&D.close(),g.parentElement!==E&&E.append(g);return}g.parentElement!==D&&(D.append(g),E.append(D));let d={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?d[o.size]+"px":"100vw"}`,D.setAttribute("aria-label",b?.document?.name??e.screen?.content.document.name??"Funnel"),D.open||D.showModal()}async function De(e){if(i)return;z=e,N&&n.client.pendingCommand?.requestId!==N&&(L.hidden=!0,N=null);let o=e.locale.startsWith("zh");if(k.textContent=o?"\u56DE\u770B":"History",k.hidden=!n.client.review,T.textContent=C?o?"\u8FD4\u56DE\u5F53\u524D":"Return to current":o?"\u8FD4\u56DE":"Back",j.textContent=o?"\u5173\u95ED":"Close",$.textContent=o?"\u91CD\u8BD5":"Retry",T.disabled=!C&&(s>0||!!n.client.pendingCommand||!e.canBack),$.hidden=n.client.pendingCommand===null,U.textContent=e.pendingRequest?o?"\u6B63\u5728\u5904\u7406":"Processing":e.instruction?.type==="wait"?o?"\u7B49\u5F85\u4E2D":"Waiting":"",a!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(a=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,ne(n.onState,structuredClone(e))),e.stopped||n.client.configurationReady===!1){C=!1,G++,q?.destroy(),q=null,v.replaceChildren(),v.hidden=!0,S.hidden=!1,b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x="",W="",t="",D.open&&D.close(),g.hidden=!0,ue();return}if(g.hidden=!1,C){ue();return}if(e.recoveryRestricted){b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x="",U.textContent=o?"\u539F\u8BB0\u5F55\u9700\u8981\u6838\u5BF9\uFF0C\u53EF\u53EA\u8BFB\u56DE\u770B":"Original records require reconciliation; read-only history is available";return}let d=e.screen||e.paywall?`${e.id}:${e.nodeId}:${e.visit}`:"";if(d!==x&&(b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x=d,W="",t="",H={...e.answers},M={},ie.clear()),Re(e),e.screen){let y=e.screen.content;b||(b=Z(S,{mode:"live",rendererUrl:n.client.webViewUrl,title:y.document.name,onAction(u,I={},f={}){if(C)return;H={...H,...f};let _=Object.fromEntries((e.screen?.inputs??[]).filter(({variable:Q})=>Object.hasOwn(H,Q)).map(({variable:Q})=>[Q,H[Q]]));Y(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:u,answers:_,selection:I}}))},onAnswers:u=>{C||(H={...H,...u})},onCustomerDataIntent:u=>{C||Ee(u).catch(J)},onEscape:()=>{C||de()},onError:u=>J(new Error(u)),onRendered:()=>ge(d)}));let p={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:H,values:e.screen.values}},A=JSON.stringify([y,e.locale,p.parameters,e.screen.inputs,e.screen.values]);if(A!==W)b.update(y.document,e.locale,p),W=A,K=JSON.stringify(p.capabilities),t=JSON.stringify(p.customerData);else{let u=JSON.stringify(p.capabilities);u!==K&&(b.updateCapabilities(p.capabilities),K=u),JSON.stringify(p.customerData)!==t&&(b.updateCustomerData(p.customerData),t=JSON.stringify(p.customerData))}await b.ready}else if(e.paywall&&!O){let y=await te(S,{canInteract:()=>!C&&!i&&!n.client.view?.recoveryRestricted,start:async()=>be(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:p=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:p,openIn:"same_window"}):m.defaultView?.location.assign(p),onAction:async p=>{if(C)return;let A=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision,input:{type:"screen",output:p,answers:{}}});await X(n.client.view??A.run)},onError:J,onDismiss:()=>{!C&&!i&&n.client.view?.visit===e.visit&&de()}});i?y.host?.destroy():(O=y.host,O?.setSuspended(C)),ge(d)}let r=e.instruction;if(r&&(r.type==="open_url"||r.type==="event")&&!ae.has(r.receiptId)){let y=m.createElement("button");y.type="button",y.textContent=r.type==="open_url"?`${o?"\u524D\u5F80":"Continue to"} ${new URL(r.url).host}`:o?"\u7EE7\u7EED":"Continue",y.onclick=()=>{let p=B(),A=r.type==="open_url"&&!n.onOpenUrl&&r.openIn==="new_window"?Pe(r.url):null;Y(async()=>{let u="success";if(r.type==="open_url")if(n.onOpenUrl)try{u=await n.onOpenUrl({receiptId:r.receiptId,url:r.url,openIn:r.openIn})===!1?"failed":"opened"}catch(f){ne(n.onError,f),u="failed"}else u=r.openIn==="new_window"&&!A?"failed":"opened";if(r.type==="event"){if(!n.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(r.event)}if(i||n.client.view?.nodeId!==p.nodeId||n.client.view.visit!==p.visit)throw new w("PRECONDITION_FAILED","The client action visit changed");let I=await n.client.submit({operation:"submit",...p,input:{type:"client_action",receiptId:r.receiptId,outcome:u}});return ae.add(r.receiptId),r.type==="open_url"&&!n.onOpenUrl&&r.openIn==="same_window"&&m.defaultView?.location.assign(r.url),I})},S.replaceChildren(y)}!e.pendingRequest&&e.status==="completed"&&!ae.has(`complete:${e.id}`)&&(ae.add(`complete:${e.id}`),ne(n.onComplete,structuredClone(e))),ue()}function Pe(e){let o=m.defaultView?.open(e,"_blank")??null;return o&&(o.opener=null),o}function X(e){return l=l.catch(()=>{}).then(()=>De(e)),l}async function ce(e){if(i||!n.client.review)return;C||(re=ye(n.client.view),le.set(re,structuredClone(H))),C=!0,he=e,S.hidden=!0,O?.setSuspended(!0),v.hidden=!1;let o=++G;try{let d=await n.client.review(e);if(i||o!==G||!C)return;if(!d.review)throw new w("INVALID_RESPONSE","Historical projection is missing");q?.destroy(),q=null,v.replaceChildren();let r=d.run.locale.startsWith("zh"),y=m.createElement("p");y.textContent=r?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",v.append(y);for(let[u,I]of d.review.pages.entries()){let f=m.createElement("button");f.type="button",f.textContent=r?`\u7B2C ${u+1} \u9875`:`Page ${u+1}`,f.onclick=()=>{ce(I.receiptId)},v.append(f)}if(d.review.page){let u=d.review.page,I=m.createElement("div");if(I.inert=!0,v.append(I),q=Z(I,{mode:"live",rendererUrl:n.client.webViewUrl,title:u.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{fe()}}),q.update(u.document,d.run.locale,{serverInput:{bindings:u.inputs,answers:u.answers,values:u.values}}),await q.ready,i||o!==G||!C)return}let p=r?{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"},A=r?{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 u of[...d.review.coupons.map((I,f)=>`${r?"\u4F18\u60E0\u5238":"Coupon"} ${f+1}: ${p[I.status]}`),...d.review.purchases.map((I,f)=>`${r?"\u8D2D\u4E70":"Purchase"} ${f+1}: ${A[I.status]}`)]){let I=m.createElement("p");I.textContent=u,v.append(I)}n.client.view&&await X(n.client.view)}catch(d){if(o!==G||i)return;q?.destroy(),q=null,v.replaceChildren(),J(d)}}async function fe(){if(!C||i||!n.client.review)return;let e=++G;try{if(await n.client.review(),i||e!==G)return;C=!1,G++,q?.destroy(),q=null,v.replaceChildren(),v.hidden=!0,S.hidden=!1;let o=n.client.view;ye(o)!==re?(le.set(re,structuredClone(H)),x="",W=""):(le.delete(re),O?.setSuspended(!1)),o&&await X(o)}catch(o){if(e!==G||i)return;q?.destroy(),q=null,v.replaceChildren(),J(o)}}let Ne=n.client.subscribe(e=>{n.client.configurationReady===!1&&(g.hidden=!0,b?.destroy(),b=null,O?.destroy(),O=null,S.replaceChildren(),x="",W="",t="",D.open&&D.close()),X(e).catch(J)}),Oe=n.client.subscribeError?.(J);function de(){return P||(i?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(pe(),Promise.resolve()):(P=Y(()=>n.client.submit({operation:"close",...B()}),!0).then(()=>{n.client.view?.status==="closed"&&pe()}).finally(()=>{P=null}),P))}function pe(){i||(i=!0,c&&clearTimeout(c),Ne(),Oe?.(),b?.destroy(),G++,q?.destroy(),O?.destroy(),D.close(),D.remove(),g.remove(),R instanceof HTMLElement&&R.isConnected&&R.focus(),ne(n.onDismiss,z?structuredClone(z):null))}T.onclick=()=>{if(C){fe();return}Y(()=>n.client.submit({operation:"back",...B()}))},k.onclick=()=>{ce()},j.onclick=()=>{de()},$.onclick=()=>{Y(()=>n.client.retry())},D.addEventListener("cancel",e=>{e.preventDefault(),de()});try{let e=await n.client.get();await X(n.client.view??e.run)}catch(e){throw pe(),e}return{destroy:pe,refresh:Ie,review:ce,exitReview:fe,get unappliedDrafts(){return new Map([...le].map(([e,o])=>[e,structuredClone(o)]))}}}export{Fe as showFunnelRun};
|
|
@@ -2,47 +2,10 @@ import * as zod from 'zod';
|
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { O as OfferingItem, I as InvoiceModeParams, e as InvoiceModeParamsInput, A as ApiInput, F as FoundationApi } from './ai-usage-B4W5m4Ie.js';
|
|
4
4
|
import { S as StackNode, d as ScreenSelection } from './screen-16d-xADb.js';
|
|
5
|
+
import { S as Scope, I as IndianaError } from './errors-DrdTlPwf.js';
|
|
5
6
|
import { E as EvaluationContext, J as JsonValue, F as FeatureResult, s as stickyAssignmentDocumentSchema } from './growth-rules-B4YYy64R.js';
|
|
6
7
|
import { C as ConfigurationSync } from './configuration-sync-C2mytNwU.js';
|
|
7
8
|
|
|
8
|
-
declare const scopeSchema: z.ZodObject<{
|
|
9
|
-
projectId: z.ZodString;
|
|
10
|
-
environment: z.ZodEnum<{
|
|
11
|
-
sandbox: "sandbox";
|
|
12
|
-
live: "live";
|
|
13
|
-
}>;
|
|
14
|
-
}, z.core.$strict>;
|
|
15
|
-
type Scope = z.infer<typeof scopeSchema>;
|
|
16
|
-
|
|
17
|
-
declare const errorRecoverySchema: z.ZodEnum<{
|
|
18
|
-
fix_request: "fix_request";
|
|
19
|
-
authenticate: "authenticate";
|
|
20
|
-
check_permissions: "check_permissions";
|
|
21
|
-
check_scope: "check_scope";
|
|
22
|
-
resolve_conflict: "resolve_conflict";
|
|
23
|
-
reload_state: "reload_state";
|
|
24
|
-
retry_same_request: "retry_same_request";
|
|
25
|
-
configure_integration: "configure_integration";
|
|
26
|
-
check_availability: "check_availability";
|
|
27
|
-
upgrade_sdk: "upgrade_sdk";
|
|
28
|
-
recover_operation: "recover_operation";
|
|
29
|
-
contact_support: "contact_support";
|
|
30
|
-
}>;
|
|
31
|
-
type ErrorRecovery = z.infer<typeof errorRecoverySchema>;
|
|
32
|
-
/** Safe business reasons; never SQL text, resource IDs or provider responses. */
|
|
33
|
-
declare const errorReasonSchema: z.ZodEnum<{
|
|
34
|
-
CAPABILITY_NOT_ENABLED: "CAPABILITY_NOT_ENABLED";
|
|
35
|
-
INTEGRATION_MISSING: "INTEGRATION_MISSING";
|
|
36
|
-
PROVIDER_CREDENTIAL_REJECTED: "PROVIDER_CREDENTIAL_REJECTED";
|
|
37
|
-
PRICE_BINDING_REQUIRED: "PRICE_BINDING_REQUIRED";
|
|
38
|
-
IDEMPOTENCY_CONFLICT: "IDEMPOTENCY_CONFLICT";
|
|
39
|
-
RESULT_UNKNOWN: "RESULT_UNKNOWN";
|
|
40
|
-
STATE_CHANGED: "STATE_CHANGED";
|
|
41
|
-
OPERATION_IN_PROGRESS: "OPERATION_IN_PROGRESS";
|
|
42
|
-
FUNNEL_VERSION_RETIRED: "FUNNEL_VERSION_RETIRED";
|
|
43
|
-
}>;
|
|
44
|
-
type ErrorReason = z.infer<typeof errorReasonSchema>;
|
|
45
|
-
|
|
46
9
|
declare const currencySchema: z.ZodEnum<{
|
|
47
10
|
USD: "USD";
|
|
48
11
|
EUR: "EUR";
|
|
@@ -8114,22 +8077,6 @@ interface FunnelCommandStorage {
|
|
|
8114
8077
|
write(expectedRevision: number, entry: FunnelPendingEntry | null): Promise<number | null>;
|
|
8115
8078
|
}
|
|
8116
8079
|
|
|
8117
|
-
declare class IndianaError extends Error {
|
|
8118
|
-
readonly code: string;
|
|
8119
|
-
readonly status?: number | undefined;
|
|
8120
|
-
readonly requestId?: string | undefined;
|
|
8121
|
-
readonly retryable: boolean;
|
|
8122
|
-
readonly recovery: ErrorRecovery;
|
|
8123
|
-
readonly retryAfterSeconds?: number;
|
|
8124
|
-
readonly reason?: ErrorReason;
|
|
8125
|
-
constructor(code: string, message: string, status?: number | undefined, requestId?: string | undefined, metadata?: {
|
|
8126
|
-
retryable?: boolean;
|
|
8127
|
-
recovery?: ErrorRecovery;
|
|
8128
|
-
retryAfterSeconds?: number;
|
|
8129
|
-
reason?: ErrorReason;
|
|
8130
|
-
});
|
|
8131
|
-
}
|
|
8132
|
-
|
|
8133
8080
|
interface IndianaOptions {
|
|
8134
8081
|
/** Override the per-Run CAS adapter. Secure browser hosts use Web Locks/localStorage by default; non-browser hosts supply their own adapter. */
|
|
8135
8082
|
funnelCommandStorage?: FunnelCommandStorage;
|
|
@@ -30954,4 +30901,4 @@ declare function createFunnelStartClient(options: IndianaServerOptions): {
|
|
|
30954
30901
|
}>;
|
|
30955
30902
|
};
|
|
30956
30903
|
|
|
30957
|
-
export { type
|
|
30904
|
+
export { type IndianaServerOptions as A, createFunnelCampaignClient as B, createFunnelDecisionClient as C, createFunnelLocalEvaluator as D, createFunnelOrchestrationClient as E, type FunnelRuntimeResponse as F, createFunnelStartClient as G, createGuestToken as H, type IndianaOptions as I, createIndianaServer as J, createNativeReceiptClient as K, type LocalFunnelClient as L, createPaywallStartClient as M, createSynchronizedFunnelLocalEvaluator as N, renewFunnelRun as O, type PaywallSession as P, type RemoteFeatureResult as R, type SubscriptionOperation as S, type FunnelRunView as a, type FunnelCommand as b, type FunnelPurchaseRecovery as c, type FunnelDataQueries as d, type FeatureClientOptions as e, type FunnelCommandStorage as f, type FunnelStartInput as g, type FeatureClient as h, type FunnelNodeEvaluationContext as i, type FunnelPendingEntry as j, type LocalFunnelClientOptions as k, type PaywallPurchaseInput as l, type PaywallStartInput as m, createFeatureClient as n, createLocalFunnelClient as o, createPaywallSession as p, evaluateFunnelNode as q, type FunnelDecisionInput as r, FunnelDecisionTimeoutError as s, type FunnelDecisionUsedInput as t, type FunnelLocalEvaluation as u, type FunnelLocalEvaluator as v, type FunnelLocalEvaluatorOptions as w, type FunnelLocalSession as x, type FunnelLocalSessionOptions as y, type FunnelSignalInput as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as zod from 'zod';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import { F as FunnelRuntimeResponse, a as FunnelRunView, b as FunnelCommand, c as FunnelPurchaseRecovery, d as FunnelDataQueries, I as IndianaOptions, P as PaywallSession, S as SubscriptionOperation, e as FeatureClientOptions, f as FunnelCommandStorage, g as FunnelStartInput, R as RemoteFeatureResult } from './funnel-runtime-start-
|
|
4
|
-
export { h as FeatureClient, i as FunnelNodeEvaluationContext, j as FunnelPendingEntry,
|
|
3
|
+
import { F as FunnelRuntimeResponse, a as FunnelRunView, b as FunnelCommand, c as FunnelPurchaseRecovery, d as FunnelDataQueries, I as IndianaOptions, P as PaywallSession, S as SubscriptionOperation, e as FeatureClientOptions, f as FunnelCommandStorage, g as FunnelStartInput, R as RemoteFeatureResult } from './funnel-runtime-start-sZ8ZCNlq.js';
|
|
4
|
+
export { h as FeatureClient, i as FunnelNodeEvaluationContext, j as FunnelPendingEntry, L as LocalFunnelClient, k as LocalFunnelClientOptions, l as PaywallPurchaseInput, m as PaywallStartInput, n as createFeatureClient, o as createLocalFunnelClient, p as createPaywallSession, q as evaluateFunnelNode } from './funnel-runtime-start-sZ8ZCNlq.js';
|
|
5
5
|
import { C as CouponInput, a as CustomerDataIntent, O as Offer } from './customer-page-B4FGCVpt.js';
|
|
6
6
|
export { b as OfferUnavailableReason } from './customer-page-B4FGCVpt.js';
|
|
7
7
|
import { O as OfferingItem, I as InvoiceModeParams, A as ApiInput } from './ai-usage-B4W5m4Ie.js';
|
|
@@ -9,6 +9,7 @@ import { S as StackNode } from './screen-16d-xADb.js';
|
|
|
9
9
|
import { C as ConfigurationSync } from './configuration-sync-C2mytNwU.js';
|
|
10
10
|
export { a as ConfigurationStorage, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-C2mytNwU.js';
|
|
11
11
|
import { J as JsonValue, F as FeatureResult } from './growth-rules-B4YYy64R.js';
|
|
12
|
+
export { I as IndianaError } from './errors-DrdTlPwf.js';
|
|
12
13
|
import '@ai-sdk/provider';
|
|
13
14
|
import 'zod/v4';
|
|
14
15
|
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as _,g as X,h as V,i as ee,j as te,k as re,l as j,m as ne}from"./chunk-YAMBRNJ2.js";import{a as B}from"./chunk-FVUPV6YE.js";import{Vf as n,W as Z,X as $,Y as W,wf as L}from"./chunk-FF3LWJ26.js";import{a as s}from"./chunk-5TEZEOHX.js";import"./chunk-RMJJOSVZ.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import"./chunk-S2MSIA57.js";var z=o=>new TextEncoder().encode(JSON.stringify(o)).length,Q=16384;function H(o,f,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let p=0,I,c=m=>{I={config:structuredClone(m),until:Date.now()+3e4}},t=[],e=null,a,l=new Set;function E(){if(!f())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function P(){a||!t.length||(a=setTimeout(()=>{a=void 0,N().catch(()=>{}).finally(P)},5e3),typeof a=="object"&&"unref"in a&&a.unref())}function x(m,v={}){if(E(),I&&Date.now()<I.until&&!L(I.config,m))return;k();let h=n.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:m,properties:v}]}).events[0];if(z({events:[h]})>Q)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(t.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");t.push(structuredClone(h)),P()}async function N(m=!1){if(E(),e)return e;let v=p,h=(async()=>{let O={inserted:0,duplicates:0,rejected:0,skipped:0},C=t.length;for(;C&&v===p;){let A=[];for(let F of t.slice(0,Math.min(C,100))){if(A.length&&z({events:[...A,F]})>Q)break;A.push(F)}let g=n.trackEvents,w=g.response.parse(await o(g.path,g.request.parse({events:A}),g.method,{keepalive:m}));if(v!==p)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==A.length)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement");c(w.analyticsConfig),t.splice(0,A.length),C-=A.length,O.inserted+=w.inserted,O.duplicates+=w.duplicates,O.rejected+=w.rejected,O.skipped+=w.skipped}return O})();e=h;try{return await h}finally{e===h&&(e=null)}}async function J(m={}){i||E();let v=p,h=!1,O=async()=>{if(h||v!==p)throw new s("IDENTITY_CHANGED","Feature identity changed");let y=n.getFeatures,d=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:y.response.parse(await o(y.path,y.request.parse({}),y.method));if(v!==p)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(d.scope.projectId!==r.projectId||d.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return c(d.payload.analyticsConfig),d},C=await O(),A=!0,g,w=y=>{try{m.onError?.(y)}catch{}},F=(y,d)=>{try{x(y,d)}catch(S){w(S)}},R=_({assertUsable:i?.assertFeatures,scope:C.scope,attributes:m.attributes,onError:m.onError,load:async()=>A?(A=!1,C.payload):(await O()).payload,evaluateRemote:async y=>{if(v!==p)throw new s("IDENTITY_CHANGED","Feature identity changed");let d=n.evaluateFeatures,S=d.response.parse(await o(d.path,d.request.parse(y),d.method));if(S.scope.projectId!==C.scope.projectId||S.scope.environment!==C.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:S.generation,evaluatedAt:S.evaluatedAt,expiresAt:S.expiresAt,features:S.features}},onExperimentViewed:(y,d)=>F("Experiment Viewed",{experimentId:y.key,variationId:d.key}),onFeatureUsage:(y,d)=>F("Feature Evaluated",{feature:y,value:d.value,source:d.source,ruleId:d.ruleId,...d.experimentResult?{variationId:d.experimentResult.key}:{}})}),M=R.refresh;function D(){clearTimeout(g),!i&&(h||v!==p||!R.expiresAt||(g=setTimeout(()=>{b().catch(w)},Math.min(2147483647,Math.max(1e3,Date.parse(R.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function b(){try{return await M()}finally{D()}}let U=()=>{h||b().catch(w)},Y=R.subscribe(D),K=i?.subscribe(()=>{!h&&i.fresh&&b().catch(w)});function q(){h||(h=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",U),Y(),K?.(),R.reset(),l.delete(q))}l.add(q);try{await R.init()}catch(y){throw q(),y}return D(),!i&&typeof window<"u"&&window.addEventListener("focus",U),Object.assign(R,{refresh:b,destroy:q})}let T;function k(){if(T||typeof document>"u")return;let m=()=>{document.visibilityState==="hidden"&&f()&&t.length&&N(!0).catch(()=>{})};document.addEventListener("visibilitychange",m),T=()=>document.removeEventListener("visibilitychange",m)}return{features:J,track(m,v){return k(),x(m,v)},flush:N,reset(){p++,I=void 0,clearTimeout(a),a=void 0,t=[],e=null;for(let m of l)m();T?.(),T=void 0}}}function G(o,f){let r="source"in f?{funnelId:f.source.id,funnelVersionId:f.source.versionId}:"versionId"in f?{funnelId:f.funnelId,funnelVersionId:f.versionId}:f,i=n.grantOffer.request.pick({funnelId:!0,funnelVersionId:!0}).required({funnelId:!0}).safeParse(r);if(!i.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let p=Object.freeze(i.data);function I(c){if("customerId"in c)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in c&&c.funnelId!==void 0&&c.funnelId!==p.funnelId||"funnelVersionId"in c&&c.funnelVersionId!==void 0&&c.funnelVersionId!==p.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...c,...p}}return{async claimCoupon(c,t=crypto.randomUUID()){let e=n.grantOffer,a=e.response.parse(await o(e.path,e.request.parse(I({couponId:c,requestId:t}))));return{offer:a.offer,reason:a.reason}},async resolveOffering(c){let t=n.resolveOffering;return t.response.parse(await o(t.path,t.request.parse(I(c))))},async resolvePaywall(c){let t=n.resolvePaywall;return t.response.parse(await o(t.path,t.request.parse(I(c))))},async previewAttach(c){let t=n.previewAttach;return t.response.parse(await o(t.path,t.request.parse(I(c))))}}}function se(o){if(!/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(o.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!o.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let f=j({...o,scope:o.scope,apiKey:o.customerToken});return{async start(r){let i=await f.start(r),p=V({...o,runToken:i.runToken});p.identify(o.customerToken);let I=i.run.instruction?.type==="evaluate"?await p.get():i;return{...i,...I,controller:p}}}}function u(o){if(o!==null&&typeof o=="object"&&"customerId"in o)throw new s("INVALID_REQUEST","Customer requests use the verified session identity")}function ge(o){let f=B(o),r=f.request,i=!1,p=H(r,()=>i,o.scope,o.configuration),I=new Set,c=t=>{for(let e of I)try{e(t)}catch{}};return{forFunnel(t){return G(r,t)},async features(t={}){return p.features(t)},track(t,e){return p.track(t,e)},flush(){return p.flush()},async setupPayment(t){u(t);let e=n.setupPayment;return e.response.parse(await r(e.path,e.request.parse(t)))},async readPaymentSetup(t){u(t);let e=n.readPaymentSetup;return e.response.parse(await r(e.path,e.request.parse(t)))},async previewUpdate(t){u(t);let e=n.previewUpdate;return e.response.parse(await r(e.path,e.request.parse(t)))},async update(t){u(t);let e=n.update;return e.response.parse(await r(e.path,e.request.parse(t)))},async readSubscriptionUpdate(t){u(t);let e=n.readSubscriptionUpdate;return e.response.parse(await r(e.path,e.request.parse(t)))},async restoreNativePurchase(t){u(t);let e=n.restoreNativePurchase;return e.response.parse(await r(e.path,e.request.parse(t)))},async previewAttach(t){u(t);let e=n.previewAttach;return e.response.parse(await r(e.path,e.request.parse(t)))},async attach(t){u(t);let e=n.attach;return e.response.parse(await r(e.path,e.request.parse(t)))},async readSubscriptionOperation(t){u(t);let e=n.readSubscriptionOperation;return e.response.parse(await r(e.path,e.request.parse(t)))},async checkEntitlement(t){u(t);let e=n.checkEntitlement;return e.response.parse(await r(e.path,e.request.parse(t)))},async resolvePaywall(t){u(t);let e=n.resolvePaywall;return e.response.parse(await r(e.path,e.request.parse(t)))},async resolveOffering(t){u(t);let e=n.resolveOffering;return e.response.parse(await r(e.path,e.request.parse(t)))},async readHoldings(t={}){let e=n.readHoldings;return e.response.parse(await r(e.path,e.request.omit({customerId:!0}).parse(t)))},async readLedger(t){let e=n.readLedger;return e.response.parse(await r(e.path,e.request.parse({query:t})))},async readBillingInvoice(t){u(t);let e=n.readBillingInvoice;return e.response.parse(await r(e.path,e.request.parse(t)))},async readCreditStatement(t){u(t);let e=n.readCreditStatement;return e.response.parse(await r(e.path,e.request.parse(t)))},async quoteBalance(t){u(t);let e=n.quoteBalance;return e.response.parse(await r(e.path,e.request.parse({command:t})))},async readBillingControls(t={}){u(t);let e=n.readBillingControls;return e.response.parse(await r(e.path,e.request.parse(t)))},async prepareBillingAuthorization(t){u(t);let e=n.prepareBillingAuthorization;return e.response.parse(await r(e.path,e.request.parse(t)))},async confirmBillingAuthorization(t){u(t);let e=n.confirmBillingAuthorization;return e.response.parse(await r(e.path,e.request.parse(t)))},async setBillingCoupons(t){u(t);let e=n.setBillingCoupons,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid billing coupon list");let l=e.response.safeParse(await r(e.path,a.data));if(!l.success)throw new s("INVALID_RESPONSE","Invalid billing coupon receipt");return l.data},async revokeBillingAuthorization(t){u(t);let e=n.revokeBillingAuthorization;return e.response.parse(await r(e.path,e.request.parse(t)))},async listBillingInvoices(t={after:null,limit:25}){u(t);let e=n.listBillingInvoices;return e.response.parse(await r(e.path,e.request.parse(t)))},async confirmBillingAdjustment(t){u(t);let e=n.confirmBillingAdjustment;return e.response.parse(await r(e.path,e.request.parse(t)))},subscribeIdentity(t){return I.add(t),()=>{I.delete(t)}},identify(t){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(t))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");p.reset(),f.identify(t),i=!0,c(!0)},reset(){i=!1,p.reset(),f.reset(),c(!1)},async redeemReward(t){u(t);let e=n.redeemReward,a=e.request.safeParse({...t,requestId:t.requestId??crypto.randomUUID()});if(!a.success)throw new s("INVALID_REQUEST","Invalid reward redemption");let l=e.response.safeParse(await r(e.path,a.data));if(!l.success)throw new s("INVALID_RESPONSE","Invalid reward receipt");return l.data.redemption},async claimRewardProduct(t){u(t);let e=n.claimRewardProduct,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid reward product claim");let l=e.response.safeParse(await r(e.path,a.data));if(!l.success)throw new s("INVALID_RESPONSE","Invalid reward product checkout");return l.data.checkout},async createReferralCode(t){u(t);let e=n.createReferralCode,a=e.request.safeParse({...t,requestId:t.requestId??crypto.randomUUID()});if(!a.success)throw new s("INVALID_REQUEST","Invalid referral program");let l=e.response.safeParse(await r(e.path,a.data));if(!l.success)throw new s("INVALID_RESPONSE","Invalid referral code");return l.data.referralCode},async redeemCoupon(t,e=crypto.randomUUID()){let a=n.redeemCoupon,l=a.request.safeParse({code:t,requestId:e});if(!l.success)throw new s("INVALID_REQUEST","Invalid coupon code");let E=a.response.safeParse(await r(a.path,l.data));if(!E.success)throw new s("INVALID_RESPONSE","Invalid Coupon receipt");let P=E.data;return{offer:P.offer,reason:P.reason}},async claimCoupon(t,e=crypto.randomUUID()){let a=n.grantOffer,l=a.request.safeParse({couponId:t,requestId:e});if(!l.success)throw new s("INVALID_REQUEST","Invalid Coupon claim");let E=a.response.safeParse(await r(a.path,l.data));if(!E.success)throw new s("INVALID_RESPONSE","Invalid Coupon receipt");return{offer:E.data.offer,reason:E.data.reason}},async listOffers(){let t=n.listOffers.response.safeParse(await r("offers",{},"GET"));if(!t.success)throw new s("INVALID_RESPONSE","Invalid offers response");return t.data.offers}}}async function Ee(...o){return(await import("./paywall-5WU6PX5C.js")).showPaywall(...o)}async function Ae(...o){return(await import("./funnel-runtime-host-KPYLOYYN.js")).showFunnelRun(...o)}export{s as IndianaError,X as createBrowserFunnelCommandStorage,te as createConfigurationSync,_ as createFeatureClient,se as createFunnelClient,V as createFunnelRunController,ge as createIndiana,ne as createLocalFunnelClient,ee as createPaywallSession,re as evaluateFunnelNode,$ as formatCouponDiscount,Z as formatCouponMoney,W as formatCouponTerms,Ae as showFunnelRun,Ee as showPaywall};
|
|
1
|
+
import{a as _,g as X,h as V,i as ee,j as te,k as re,l as j,m as ne}from"./chunk-63BWE27V.js";import{a as B}from"./chunk-QG3WUJG5.js";import{Vf as n,W as Z,X as $,Y as W,wf as L}from"./chunk-HTRQPMJO.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import{a as s}from"./chunk-5TEZEOHX.js";import"./chunk-RMJJOSVZ.js";import"./chunk-S2MSIA57.js";var z=o=>new TextEncoder().encode(JSON.stringify(o)).length,Q=16384;function H(o,f,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let p=0,I,c=m=>{I={config:structuredClone(m),until:Date.now()+3e4}},t=[],e=null,a,l=new Set;function E(){if(!f())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function P(){a||!t.length||(a=setTimeout(()=>{a=void 0,N().catch(()=>{}).finally(P)},5e3),typeof a=="object"&&"unref"in a&&a.unref())}function x(m,v={}){if(E(),I&&Date.now()<I.until&&!L(I.config,m))return;k();let h=n.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:m,properties:v}]}).events[0];if(z({events:[h]})>Q)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(t.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");t.push(structuredClone(h)),P()}async function N(m=!1){if(E(),e)return e;let v=p,h=(async()=>{let O={inserted:0,duplicates:0,rejected:0,skipped:0},C=t.length;for(;C&&v===p;){let A=[];for(let F of t.slice(0,Math.min(C,100))){if(A.length&&z({events:[...A,F]})>Q)break;A.push(F)}let g=n.trackEvents,w=g.response.parse(await o(g.path,g.request.parse({events:A}),g.method,{keepalive:m}));if(v!==p)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==A.length)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement");c(w.analyticsConfig),t.splice(0,A.length),C-=A.length,O.inserted+=w.inserted,O.duplicates+=w.duplicates,O.rejected+=w.rejected,O.skipped+=w.skipped}return O})();e=h;try{return await h}finally{e===h&&(e=null)}}async function J(m={}){i||E();let v=p,h=!1,O=async()=>{if(h||v!==p)throw new s("IDENTITY_CHANGED","Feature identity changed");let y=n.getFeatures,d=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:y.response.parse(await o(y.path,y.request.parse({}),y.method));if(v!==p)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(d.scope.projectId!==r.projectId||d.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return c(d.payload.analyticsConfig),d},C=await O(),A=!0,g,w=y=>{try{m.onError?.(y)}catch{}},F=(y,d)=>{try{x(y,d)}catch(S){w(S)}},R=_({assertUsable:i?.assertFeatures,scope:C.scope,attributes:m.attributes,onError:m.onError,load:async()=>A?(A=!1,C.payload):(await O()).payload,evaluateRemote:async y=>{if(v!==p)throw new s("IDENTITY_CHANGED","Feature identity changed");let d=n.evaluateFeatures,S=d.response.parse(await o(d.path,d.request.parse(y),d.method));if(S.scope.projectId!==C.scope.projectId||S.scope.environment!==C.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:S.generation,evaluatedAt:S.evaluatedAt,expiresAt:S.expiresAt,features:S.features}},onExperimentViewed:(y,d)=>F("Experiment Viewed",{experimentId:y.key,variationId:d.key}),onFeatureUsage:(y,d)=>F("Feature Evaluated",{feature:y,value:d.value,source:d.source,ruleId:d.ruleId,...d.experimentResult?{variationId:d.experimentResult.key}:{}})}),M=R.refresh;function D(){clearTimeout(g),!i&&(h||v!==p||!R.expiresAt||(g=setTimeout(()=>{b().catch(w)},Math.min(2147483647,Math.max(1e3,Date.parse(R.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function b(){try{return await M()}finally{D()}}let U=()=>{h||b().catch(w)},Y=R.subscribe(D),K=i?.subscribe(()=>{!h&&i.fresh&&b().catch(w)});function q(){h||(h=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",U),Y(),K?.(),R.reset(),l.delete(q))}l.add(q);try{await R.init()}catch(y){throw q(),y}return D(),!i&&typeof window<"u"&&window.addEventListener("focus",U),Object.assign(R,{refresh:b,destroy:q})}let T;function k(){if(T||typeof document>"u")return;let m=()=>{document.visibilityState==="hidden"&&f()&&t.length&&N(!0).catch(()=>{})};document.addEventListener("visibilitychange",m),T=()=>document.removeEventListener("visibilitychange",m)}return{features:J,track(m,v){return k(),x(m,v)},flush:N,reset(){p++,I=void 0,clearTimeout(a),a=void 0,t=[],e=null;for(let m of l)m();T?.(),T=void 0}}}function G(o,f){let r="source"in f?{funnelId:f.source.id,funnelVersionId:f.source.versionId}:"versionId"in f?{funnelId:f.funnelId,funnelVersionId:f.versionId}:f,i=n.grantOffer.request.pick({funnelId:!0,funnelVersionId:!0}).required({funnelId:!0}).safeParse(r);if(!i.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let p=Object.freeze(i.data);function I(c){if("customerId"in c)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in c&&c.funnelId!==void 0&&c.funnelId!==p.funnelId||"funnelVersionId"in c&&c.funnelVersionId!==void 0&&c.funnelVersionId!==p.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...c,...p}}return{async claimCoupon(c,t=crypto.randomUUID()){let e=n.grantOffer,a=e.response.parse(await o(e.path,e.request.parse(I({couponId:c,requestId:t}))));return{offer:a.offer,reason:a.reason}},async resolveOffering(c){let t=n.resolveOffering;return t.response.parse(await o(t.path,t.request.parse(I(c))))},async resolvePaywall(c){let t=n.resolvePaywall;return t.response.parse(await o(t.path,t.request.parse(I(c))))},async previewAttach(c){let t=n.previewAttach;return t.response.parse(await o(t.path,t.request.parse(I(c))))}}}function se(o){if(!/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(o.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!o.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let f=j({...o,scope:o.scope,apiKey:o.customerToken});return{async start(r){let i=await f.start(r),p=V({...o,runToken:i.runToken});p.identify(o.customerToken);let I=i.run.instruction?.type==="evaluate"?await p.get():i;return{...i,...I,controller:p}}}}function u(o){if(o!==null&&typeof o=="object"&&"customerId"in o)throw new s("INVALID_REQUEST","Customer requests use the verified session identity")}function ge(o){let f=B(o),r=f.request,i=!1,p=H(r,()=>i,o.scope,o.configuration),I=new Set,c=t=>{for(let e of I)try{e(t)}catch{}};return{forFunnel(t){return G(r,t)},async features(t={}){return p.features(t)},track(t,e){return p.track(t,e)},flush(){return p.flush()},async setupPayment(t){u(t);let e=n.setupPayment;return e.response.parse(await r(e.path,e.request.parse(t)))},async readPaymentSetup(t){u(t);let e=n.readPaymentSetup;return e.response.parse(await r(e.path,e.request.parse(t)))},async previewUpdate(t){u(t);let e=n.previewUpdate;return e.response.parse(await r(e.path,e.request.parse(t)))},async update(t){u(t);let e=n.update;return e.response.parse(await r(e.path,e.request.parse(t)))},async readSubscriptionUpdate(t){u(t);let e=n.readSubscriptionUpdate;return e.response.parse(await r(e.path,e.request.parse(t)))},async restoreNativePurchase(t){u(t);let e=n.restoreNativePurchase;return e.response.parse(await r(e.path,e.request.parse(t)))},async previewAttach(t){u(t);let e=n.previewAttach;return e.response.parse(await r(e.path,e.request.parse(t)))},async attach(t){u(t);let e=n.attach;return e.response.parse(await r(e.path,e.request.parse(t)))},async readSubscriptionOperation(t){u(t);let e=n.readSubscriptionOperation;return e.response.parse(await r(e.path,e.request.parse(t)))},async checkEntitlement(t){u(t);let e=n.checkEntitlement;return e.response.parse(await r(e.path,e.request.parse(t)))},async resolvePaywall(t){u(t);let e=n.resolvePaywall;return e.response.parse(await r(e.path,e.request.parse(t)))},async resolveOffering(t){u(t);let e=n.resolveOffering;return e.response.parse(await r(e.path,e.request.parse(t)))},async readHoldings(t={}){let e=n.readHoldings;return e.response.parse(await r(e.path,e.request.omit({customerId:!0}).parse(t)))},async readLedger(t){let e=n.readLedger;return e.response.parse(await r(e.path,e.request.parse({query:t})))},async readBillingInvoice(t){u(t);let e=n.readBillingInvoice;return e.response.parse(await r(e.path,e.request.parse(t)))},async readCreditStatement(t){u(t);let e=n.readCreditStatement;return e.response.parse(await r(e.path,e.request.parse(t)))},async quoteBalance(t){u(t);let e=n.quoteBalance;return e.response.parse(await r(e.path,e.request.parse({command:t})))},async readBillingControls(t={}){u(t);let e=n.readBillingControls;return e.response.parse(await r(e.path,e.request.parse(t)))},async prepareBillingAuthorization(t){u(t);let e=n.prepareBillingAuthorization;return e.response.parse(await r(e.path,e.request.parse(t)))},async confirmBillingAuthorization(t){u(t);let e=n.confirmBillingAuthorization;return e.response.parse(await r(e.path,e.request.parse(t)))},async setBillingCoupons(t){u(t);let e=n.setBillingCoupons,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid billing coupon list");let l=e.response.safeParse(await r(e.path,a.data));if(!l.success)throw new s("INVALID_RESPONSE","Invalid billing coupon receipt");return l.data},async revokeBillingAuthorization(t){u(t);let e=n.revokeBillingAuthorization;return e.response.parse(await r(e.path,e.request.parse(t)))},async listBillingInvoices(t={after:null,limit:25}){u(t);let e=n.listBillingInvoices;return e.response.parse(await r(e.path,e.request.parse(t)))},async confirmBillingAdjustment(t){u(t);let e=n.confirmBillingAdjustment;return e.response.parse(await r(e.path,e.request.parse(t)))},subscribeIdentity(t){return I.add(t),()=>{I.delete(t)}},identify(t){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(t))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");p.reset(),f.identify(t),i=!0,c(!0)},reset(){i=!1,p.reset(),f.reset(),c(!1)},async redeemReward(t){u(t);let e=n.redeemReward,a=e.request.safeParse({...t,requestId:t.requestId??crypto.randomUUID()});if(!a.success)throw new s("INVALID_REQUEST","Invalid reward redemption");let l=e.response.safeParse(await r(e.path,a.data));if(!l.success)throw new s("INVALID_RESPONSE","Invalid reward receipt");return l.data.redemption},async claimRewardProduct(t){u(t);let e=n.claimRewardProduct,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid reward product claim");let l=e.response.safeParse(await r(e.path,a.data));if(!l.success)throw new s("INVALID_RESPONSE","Invalid reward product checkout");return l.data.checkout},async createReferralCode(t){u(t);let e=n.createReferralCode,a=e.request.safeParse({...t,requestId:t.requestId??crypto.randomUUID()});if(!a.success)throw new s("INVALID_REQUEST","Invalid referral program");let l=e.response.safeParse(await r(e.path,a.data));if(!l.success)throw new s("INVALID_RESPONSE","Invalid referral code");return l.data.referralCode},async redeemCoupon(t,e=crypto.randomUUID()){let a=n.redeemCoupon,l=a.request.safeParse({code:t,requestId:e});if(!l.success)throw new s("INVALID_REQUEST","Invalid coupon code");let E=a.response.safeParse(await r(a.path,l.data));if(!E.success)throw new s("INVALID_RESPONSE","Invalid Coupon receipt");let P=E.data;return{offer:P.offer,reason:P.reason}},async claimCoupon(t,e=crypto.randomUUID()){let a=n.grantOffer,l=a.request.safeParse({couponId:t,requestId:e});if(!l.success)throw new s("INVALID_REQUEST","Invalid Coupon claim");let E=a.response.safeParse(await r(a.path,l.data));if(!E.success)throw new s("INVALID_RESPONSE","Invalid Coupon receipt");return{offer:E.data.offer,reason:E.data.reason}},async listOffers(){let t=n.listOffers.response.safeParse(await r("offers",{},"GET"));if(!t.success)throw new s("INVALID_RESPONSE","Invalid offers response");return t.data.offers}}}async function Ee(...o){return(await import("./paywall-4XZ6NDMY.js")).showPaywall(...o)}async function Ae(...o){return(await import("./funnel-runtime-host-NWS3URFA.js")).showFunnelRun(...o)}export{s as IndianaError,X as createBrowserFunnelCommandStorage,te as createConfigurationSync,_ as createFeatureClient,se as createFunnelClient,V as createFunnelRunController,ge as createIndiana,ne as createLocalFunnelClient,ee as createPaywallSession,re as evaluateFunnelNode,$ as formatCouponDiscount,Z as formatCouponMoney,W as formatCouponTerms,Ae as showFunnelRun,Ee as showPaywall};
|
package/dist/openrouter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-2EJSV6BA.js";import"./chunk-QG3WUJG5.js";import"./chunk-HTRQPMJO.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import{a as i}from"./chunk-5TEZEOHX.js";import"./chunk-RMJJOSVZ.js";import"./chunk-S2MSIA57.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 h(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 h({...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,h as trackOpenRouterUsage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as z}from"./chunk-6X42DWOM.js";import"./chunk-
|
|
1
|
+
import{a as z}from"./chunk-6X42DWOM.js";import"./chunk-QG3WUJG5.js";import{Gd as q,bk as j}from"./chunk-HTRQPMJO.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import{a as w}from"./chunk-5TEZEOHX.js";import{f as $,ja as N}from"./chunk-RMJJOSVZ.js";import"./chunk-S2MSIA57.js";async function W(b,n,h){if(n.status!=="complete")throw new w("INVALID_RESPONSE","A verified completed purchase is required");if(await h.onComplete?.(n),!b||!h.check)return;let t=N.parse(await h.check());if(t.internal_feature_id!==b.internal_feature_id||t.quantity!==b.quantity)throw new w("INVALID_RESPONSE","The access requirement changed");t.allowed&&await h.onAccessGranted?.(t)}async function ie(b,n){let h=n.check?N.parse(await n.check()):null;if(h?.allowed)return await n.onAccessGranted?.(h),{check:h,host:null};let t=await n.start(),y=t.view;if(!y)throw new w("INVALID_RESPONSE","Paywall presentation is missing");let{mountScreenPreview:J}=await import("./popup.js"),a=b.ownerDocument,S=new AbortController,v=a.createElement("section"),Q=a.createElement("div"),O=a.createElement("div"),P=a.createElement("p"),c=a.createElement("button"),L=a.createElement("button"),u=a.createElement("dialog"),_=a.activeElement,p=y.document.screen.strings.defaultLocale.startsWith("zh");v.dataset.indianaPaywall="",v.setAttribute("aria-label",y.document.name),v.style.cssText="width:100%;box-sizing:border-box;background:#fff;color:#172033;font:14px/1.5 system-ui,sans-serif",O.style.cssText="display:flex;gap:12px;padding:12px 20px;align-items:center;flex-wrap:wrap",P.setAttribute("role","status"),L.textContent=p?"\u5173\u95ED":"Close",c.textContent=p?"\u91CD\u8BD5":"Retry",c.hidden=!0,O.append(P,c,L),v.append(Q,O);let D=y.document.presentation,A,d=!1,T=!1,f=null,G=!1,m=()=>!G&&n.canInteract?.()!==!1,M=!1,r=null,I=null,U=e=>{P.textContent=e instanceof Error?e.message:p?"\u8BF7\u6C42\u5931\u8D25":"Request failed",z(n.onError,e),c.hidden=r===null};async function k(e){if(!(T||d||!m())){T=!0,c.hidden=!0,P.textContent="";try{await e()}catch(s){d||U(s)}finally{T=!1}}}async function K(e){await W(h,e,n)}async function E(e){if(d)return;if(!m()){r=async()=>E(await t.read()),c.hidden=!1;return}if(P.textContent=e.status,e.status==="complete"){r=null,await K(e);return}if(e.status!=="pending"){if(t.canReselect===!1){P.textContent=p?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",c.textContent=p?"\u67E5\u8BE2\u7ED3\u679C":"Check result",r=async()=>E(await t.read()),c.hidden=!1;return}c.textContent=p?"\u91CD\u8BD5":"Retry",r=null,f=null;return}let s=Date.now()+6e5,l=2e3;for(;!d&&Date.now()<s;){if(await new Promise(C=>{let R=()=>{clearTimeout(x),C()},x=setTimeout(()=>{S.signal.removeEventListener("abort",R),C()},l);S.signal.addEventListener("abort",R,{once:!0})}),d)return;if(!m()){r=async()=>E(await t.read()),c.hidden=!1;return}let i=await t.read();if(i.status!=="pending"){await E(i);return}l=Math.min(l*1.5,3e4)}r=async()=>E(await t.read()),c.hidden=!1}async function V(){I?.remove(),I=null,r=V;let e=await t.confirm();if(!m()){r=V,c.hidden=!1;return}if(e.status==="pending"){if(e.checkoutUrl)n.onCheckoutUrl?await n.onCheckoutUrl(e.checkoutUrl):a.defaultView?.location.assign(e.checkoutUrl);else if(e.execution||e.nativePurchase){if(!n.onPurchase)throw new w("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await n.onPurchase({operation:e,signal:S.signal})}}r=async()=>E(await t.read()),await E(e)}function X(e){I?.remove();let s=a.createElement("div"),l=a.createElement("button"),i=a.createElement("button"),C=a.createElement("p");C.textContent=e.lines.map(o=>o.productName).join(", ")+" \xB7 "+$(e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),e.currency),l.textContent=p?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",i.textContent=p?"\u53D6\u6D88":"Cancel",l.onclick=()=>{k(V)};let R=async()=>{let o=await t.cancel();d||(s.remove(),I=null,await E(o))};i.onclick=()=>{r=R,k(R)};let x=a.createElement("div");for(let o of e.lines){let B=a.createElement("p");if(B.textContent=`${o.productName} \xB7 ${$(o.catalogAmountMinor,e.currency)}${j(o.interval,p?"zh-CN":"en",o.intervalCount??1)}`,x.append(B),o.trial){let F=a.createElement("p");F.textContent=p?`\u8BD5\u7528 ${o.trial.days} \u5929\uFF1B${o.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${o.trial.days}; ${o.trial.cardRequired?"a payment method is required":"no payment method is required"}`,x.append(F)}}if(!e.charge){let o=a.createElement("p");o.textContent=p?"\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(o)}s.append(C,x,l,i),O.prepend(s),I=s,r=null}async function H(){if(!f)return;if(r=H,!M){let s=t.view,l=s?.document.buttons[f.actionId],i=s&&l?.type==="checkout"?q(l.product,f.selection,s.capabilities):null;if(!i)throw new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let C=await n.resolveOfferId?.({actionId:f.actionId,productVersionId:i});if(d)return;C!==void 0&&(f.offerId=C),M=!0}if(!m()){c.hidden=!1;return}let e=await t.preview(f);d||X(e)}function g(e="destroy"){d||(d=!0,S.abort(),A?.destroy(),t.destroy(),u.open&&u.close(),u.remove(),v.remove(),_ instanceof HTMLElement&&_.isConnected&&_.focus(),e==="dismiss"&&z(n.onDismiss))}L.onclick=()=>{m()&&g("dismiss")},u.addEventListener("cancel",e=>{e.preventDefault(),m()&&g("dismiss")}),c.onclick=()=>{r&&k(r)};try{if(D.type==="inline")b.append(v);else{let e={sm:420,md:640,lg:900};u.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in D?e[D.size]+"px":"100vw"}`,u.setAttribute("aria-label",y.document.name),u.append(v),b.append(u),m()&&u.showModal()}A=J(Q,{mode:"live",rendererUrl:t.webViewUrl,title:y.document.name,onAction(e,s={}){if(!m())return;let l=t.view,i=l?.document.buttons[e];if(i){if(i.type==="close"){k(async()=>{await n.onAction?.(e),g(n.onAction?"action":"dismiss")});return}if(i.type==="action"){r=async()=>{if(i.action.type==="event"){if(!n.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(i.action.event)}else n.onOpenUrl?await n.onOpenUrl(i.action.url):a.defaultView?.location.assign(i.action.url);await n.onAction?.(e),r=null},k(r);return}if((t.quote||f)&&t.canReselect===!1){r=t.quote?async()=>E(await t.read()):H,k(r);return}if(!l||!q(i.product,s,l.capabilities)){U(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(f&&f.actionId!==e){U(new w("COMMAND_PENDING","Finish the current purchase"));return}f||(f={requestId:crypto.randomUUID(),actionId:e,selection:s},M=!1),k(H)}},onEscape:()=>{m()&&g("dismiss")},onError:e=>U(new Error(e))}),A.update(y.document.screen,y.document.screen.strings.defaultLocale,{capabilities:y.capabilities,serverInput:{bindings:[],answers:{}}}),await A.ready}catch(e){throw g(),e}return{check:h,host:{setSuspended(e){G=e,v.hidden=e,e&&u.open?u.close():!e&&!d&&D.type!=="inline"&&!u.open&&u.showModal()},destroy:g,refresh:async()=>{if(!m()){if(t.view)return t.view;throw new w("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await t.refresh();return d||A?.updateCapabilities(e.capabilities),e}}}}export{ie as showPaywall};
|