@tinkerlandai/indiana-sdk 0.8.5 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +20 -41
- package/README.zh-CN.md +17 -17
- package/dist/{ai-usage-DUlre7JC.d.ts → ai-usage-DMNKvCiq.d.ts} +3 -3
- package/dist/{api-XDc4pRlN.d.ts → api--Zf0gxfj.d.ts} +128 -124
- package/dist/chunk-3PZ4Y6UD.js +17 -0
- package/dist/chunk-5O667MKA.js +1 -0
- package/dist/chunk-65TBYVCS.js +1 -0
- package/dist/chunk-67A7I6MB.js +1 -0
- package/dist/chunk-7DXL3LHT.js +1 -0
- package/dist/chunk-CCQHYQ4P.js +1 -0
- package/dist/chunk-CPLLMISZ.js +1 -0
- package/dist/chunk-G23YNWWI.js +1 -0
- package/dist/chunk-G56XGVMS.js +1 -0
- package/dist/chunk-L7LKE3MG.js +173 -0
- package/dist/chunk-NH2PTTNK.js +2 -0
- package/dist/chunk-PK5HYUHD.js +1 -0
- package/dist/chunk-SEW4YVR7.js +1 -0
- package/dist/chunk-UYSOTMY3.js +1 -0
- package/dist/{chunk-WWUUVURR.js → chunk-WSVH6IQA.js} +1 -1
- package/dist/chunk-YZSQDZXW.js +4 -0
- package/dist/{configuration-sync-Ce3dShy7.d.ts → configuration-sync-E98CqVwh.d.ts} +6 -5
- package/dist/content-3LOJVYQO.js +1 -0
- package/dist/{errors-C8lRYZ0n.d.ts → errors-0TSUIbUi.d.ts} +12 -1
- package/dist/{funnel-local-client-CUGavICI.d.ts → funnel-local-client-BjPwXlQb.d.ts} +550 -260
- package/dist/funnel-runtime-host-NYHKQT6T.js +1 -0
- package/dist/index.d.ts +689 -223
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +3 -3
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +6 -6
- package/dist/page.js +1 -1
- package/dist/paywall-ISCYOGPZ.js +1 -0
- package/dist/popup.d.ts +1 -1
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +122 -99
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-A6VYE2QL.js +1 -0
- package/dist/server.d.ts +58 -58
- package/dist/server.js +1 -1
- package/dist/visual.d.ts +36 -1
- package/dist/visual.js +1 -2
- package/package.json +1 -1
- package/dist/chunk-3KQHKRZJ.js +0 -1
- package/dist/chunk-6A5WWFNS.js +0 -10
- package/dist/chunk-A3XRIG53.js +0 -1
- package/dist/chunk-BUDTHBFF.js +0 -173
- package/dist/chunk-FGIGKO7A.js +0 -1
- package/dist/chunk-GRLMT5PR.js +0 -1
- package/dist/chunk-HEBQUICQ.js +0 -4
- package/dist/chunk-KQCTDXVD.js +0 -17
- package/dist/chunk-LMR2TM3X.js +0 -1
- package/dist/chunk-OBYJWIRB.js +0 -1
- package/dist/chunk-RRII2DMC.js +0 -1
- package/dist/chunk-SOQO2RDZ.js +0 -1
- package/dist/chunk-SUXAWRR6.js +0 -1
- package/dist/chunk-VVV3JNS3.js +0 -1
- package/dist/content-DDMDNRCV.js +0 -1
- package/dist/funnel-runtime-host-QK6WDRPS.js +0 -1
- package/dist/paywall-4QT3JYD4.js +0 -1
- package/dist/screen-renderer-DLXDQQKK.js +0 -1
- package/dist/src-EG7RWDDY.js +0 -1
- package/dist/{screen-BpAejkn0.d.ts → screen-BITZ11jn.d.ts} +18 -18
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as fe,b as we,d as me}from"./chunk-CPLLMISZ.js";import{A as le,o as pe}from"./chunk-PK5HYUHD.js";import{Z as de,fa as m}from"./chunk-G23YNWWI.js";import{d as ye,f as ge,i as he}from"./chunk-NH2PTTNK.js";import{d as ve}from"./chunk-65TBYVCS.js";import{a as K}from"./chunk-DSPLGTQI.js";import{b as ce}from"./chunk-3PZ4Y6UD.js";function Ie(e){let E=e.view;if(!E?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let n=E.paywall.receiptId,h=E.nodeId,g=E.visit,p=E.paywall.resolution,f=p,l="document"in p?p:null;function u(i){if(!fe(i,p))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let o=E.paywall.quote,b=E.paywall.operation,k=!1,T=new AbortController,w=E.paywall.purchaseRequestId,r=0,y=E.paywall.selectionGeneration??0,S=E.paywall.canReselect===!0,F=null,c=new Map,N=new Map;function $(i){if(i.purchase&&i.purchase.receiptId!==n)throw new m("INVALID_RESPONSE","Purchase receipt changed");let s=i.run.paywall;return i.purchase??(s?.receiptId===n?s:null)}function O(){if(k)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function R(i,s,v){if(O(),s!==r||v!==void 0&&o?.operationId!==v)return!1;let C=y,a=i.run.paywall;if(a?.receiptId===n){if((a.selectionGeneration??0)<y)return!1;y=a.selectionGeneration??0,S=a.canReselect===!0,u(a.resolution)}let I=$(i),d=y>C,V=d?I?.quote??null:I?.quote??o,M=I?.operation??(V?.operationId===o?.operationId?b:null);return V&&M&&we(M,{operationId:V.operationId},"Purchase operation changed"),a?.receiptId===n&&(f=a.resolution,l="document"in f?f:l?{...f,document:l.document,offering:l.offering}:null),(d||V?.operationId!==o?.operationId)&&(r++,a?.receiptId===n&&(w=a.purchaseRequestId)),o=V,b=me(b,M,!0),!0}function _(i,s,v){return new Promise((C,a)=>{let I=!1,d=()=>{clearTimeout(x),T.signal.removeEventListener("abort",G)},V=j=>{I||(I=!0,d(),C(j))},M=j=>{I||(I=!0,d(),a(j))},G=()=>M(new m("IDENTITY_CHANGED","Paywall presentation has closed")),x=setTimeout(()=>M(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,v)),Math.max(0,s-Date.now()));T.signal.addEventListener("abort",G,{once:!0}),T.signal.aborted&&G(),i.then(V,M)})}function J(i){return new Promise(s=>{let v=()=>{clearTimeout(C),T.signal.removeEventListener("abort",v),s()},C=setTimeout(v,i);T.signal.addEventListener("abort",v,{once:!0}),T.signal.aborted&&v()})}async function z(i,s,v){O();let C=c.get(i);if(!C){let d=e.pendingCommands?.find(V=>V.requestId===i)??e.pendingCommand;if(d?.operation==="submit"&&d.requestId===i&&d.nodeId===h&&d.visit===g){s.type==="paywall_quote"&&d.input.type==="paywall_quote"&&d.input.predecessor&&!s.predecessor&&(s={...s,predecessor:d.input.predecessor});let V=le.parse(d),M=le.parse({...d,input:s});if(M.operation!=="submit"||V.operation!=="submit"||JSON.stringify(M.input)!==JSON.stringify(V.input))throw new m("CONFLICT","A restored purchase request cannot change its input");s=M.input,C=V,c.set(i,C)}}if(C){if(JSON.stringify(C.input)!==JSON.stringify(s))throw new m("CONFLICT","A purchase request cannot change its input")}else{let d=e.view;if(!d||d.nodeId!==h||d.visit!==g||d.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");C={operation:"submit",requestId:i,nodeId:h,visit:g,revision:d.revision,input:s},c.set(i,C)}let a=Date.now()+3e4,I=await _(e.submit(C),a,i);for(;I.run.pendingRequest?.requestId===i&&Date.now()<a&&!k&&(await J(Math.min(1e3,a-Date.now())),!(k||Date.now()>=a));)I=await _(e.resume(i),a,i);if(k)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(I.run.pendingRequest?.requestId===i)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,i);if(!R(I,v,s.type==="paywall_confirm"||s.type==="paywall_cancel"?s.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed")}async function A(i){if(!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let s=`${i}:${o.operationId}`,v=N.get(s);if(!v){let C=i==="confirm"?"paywall_confirm":"paywall_cancel",a=e.pendingCommands?.find(I=>I.operation==="submit"&&I.input.type===C&&"operationId"in I.input&&I.input.operationId===o.operationId)??e.pendingCommand;v=a?.operation==="submit"&&a.input.type===C&&"operationId"in a.input&&a.input.operationId===o.operationId?a.requestId:crypto.randomUUID(),N.set(s,v)}if(await z(v,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.operationId},r),!b)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(b)}return{get view(){return structuredClone(l)},get quote(){return o?structuredClone(o):null},get operation(){return b?structuredClone(b):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return S},async refresh(){O();let i=r,s=await e.get();if(R(s,i),s.run.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");if(!l){if("document"in f||!e.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let v=await e.resolvePaywall(f);O(),u(v),l={...f,document:v.document,offering:v.offering}}return structuredClone(l)},preview(i){if(!l)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(w&&w!==i.requestId&&(F||!S))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));if(w===i.requestId&&F)return F;let s=l.document.buttons[i.actionId],v=s?.type==="checkout"?pe(s.product,i.selection,l.capabilities):null;if(!v)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let C=w!==i.requestId&&y>0?{operationId:o?.operationId??null,generation:y}:void 0;if(C&&(!S||y<=0))return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));w!==i.requestId&&r++;let a=r;w=i.requestId;let I=(async()=>{if(await z(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:v,...C?{predecessor:C}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}},a),!o)throw new m("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(o)})();return F=I,I.then(()=>{F===I&&(F=null)},d=>{F===I&&(F=null),w===i.requestId&&e.pendingCommand?.requestId!==i.requestId&&d instanceof m&&d.status!==void 0&&d.status<500&&![401,425].includes(d.status)&&(w=null)}),I},confirm:()=>A("confirm"),cancel:()=>A("cancel"),async read(){if(O(),!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.operationId,s=r,v=e.pendingCommands?.find(d=>d.operation==="submit"&&(d.input.type==="paywall_confirm"||d.input.type==="paywall_cancel")&&d.input.operationId===i)??e.pendingCommand;v?.operation==="submit"&&(v.input.type==="paywall_confirm"||v.input.type==="paywall_cancel")&&v.input.operationId===i&&await e.settle?.(v.requestId);let C=await e.get(void 0,{receiptId:n,operationId:i});O();let a=$(C);if(a?.quote&&a.quote.operationId!==i||a?.operation&&a.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let I=R(C,s,i)?b:a?.operation;if(!I)throw new m("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(I)},destroy(){k=!0,T.abort(),c.clear(),N.clear()}}}function be(e){let E=new Set,n=new Set,h=null;function g(p){if(e.reviewing||E.has(p)||n.has(p)||e.stopped)return;n.add(p);let f=async()=>{if(e.reviewing||e.stopped||e.key!==p){n.delete(p);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{f()},250);return}let l=(async()=>{let o=e.client.view,b=e.expected(),k=b.requestId,T=!1;try{await e.client.submit({operation:"shown",...b})}catch(w){if(!(w instanceof m)||w.code!=="CONFLICT"||w.status!==409||e.client.pendingCommand)throw w;await e.client.get();let r=e.client.view;if(e.stopped||e.reviewing||e.key!==p||!r||!o||r.id!==o.id||r.source.versionId!==o.source.versionId||r.nodeId!==b.nodeId||r.visit!==b.visit||r.revision<=b.revision||r.stopped||!r.screen||!["running","waiting"].includes(r.status)||e.client.pendingCommand)throw w;let y=e.expected();k=y.requestId,await e.client.submit({operation:"shown",...y})}for(;!e.stopped&&e.key===p&&e.client.pendingCommand?.requestId===k;){if(!e.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(k),T=!0,e.client.pendingCommand?.requestId===k&&await new Promise(w=>setTimeout(w,1500))}e.stopped||e.key!==p||(T&&await e.client.get(),!(e.stopped||e.key!==p)&&E.add(p))})();h=l;let u=()=>{h===l&&(h=null),n.delete(p)};l.then(u,o=>{u(),e.busy||e.fail(o)})};f()}return{report:g,get inFlight(){return h}}}function Ce(e){let E={},n=new Map;async function h(g){let p=e.client.view,f=p?.screen,l=f?.customerData.nodes[g.nodeId];if(e.stopped||e.busy||!p||!f||!l)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(g.action)){let r=e.document,y=r?de(r,g.nodeId):null,S=y?.type==="customer_data"?y.data.outputs?.[g.action]:void 0;S&&f.outputs.includes(S)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:S,answers:e.answers,selection:g.value?{[g.nodeId]:g.value}:{}}})):await e.onIntent?.(g,p);return}let o=g.action.startsWith("sources_")?l.resources.find(r=>r.key===g.value):null;if(g.action.startsWith("sources_")&&!o)throw new m("INVALID_REQUEST","Choose a current resource");let b=`${p.visit}:${g.nodeId}:${o?.key??""}`,k=n.get(b)??[null],w=E[g.nodeId]??{page:1,after:null,filter:"all",...o?{resourceKey:o.key}:{}};if(g.action==="filter"){let r=g.value;if(!r||!(l.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(r))throw new m("INVALID_REQUEST","Unknown data filter");w={page:1,after:null,filter:r},k.splice(0,k.length,null)}else if(g.action==="next"||g.action==="sources_next"){let r=o?.sources.at(-1),y=o?r?{kind:"ledger",cursor:{at:r.detail[0],id:r.id,type:"source"}}:null:f.dataCursors[g.nodeId];if(!y||!o&&!l.hasNext)return;k[w.page]=y,w={...w,page:w.page+1,after:y}}else if(g.action==="previous"||g.action==="sources_previous"){if(w.page<=1)return;w={...w,page:w.page-1,after:k[w.page-2]??null}}n.set(b,k),E={...E,[g.nodeId]:w},await e.perform(()=>e.client.get({nodeId:p.nodeId,visit:p.visit,revision:p.revision,components:E}))}return{get queries(){return E},intent:h,reset(){E={},n.clear()}}}function Ee(e){let{doc:E,holder:n,reviewHolder:h,mountScreenPreview:g}=e,p=!1,f,l=0,u=null,o="",b=new Map,k=r=>r?`${r.id}:${r.nodeId}:${r.visit}:${r.revision}:${r.paywall?.quote?.operationId??""}`:"";async function T(r){if(e.stopped||!e.client.review)return;p||(o=k(e.client.view),b.set(o,structuredClone(e.answers))),p=!0,f=r,n.hidden=!0,e.suspend(!0),h.hidden=!1;let y=++l;try{let S=await e.client.review(r);if(e.stopped||y!==l||!p)return;if(!S.review)throw new m("INVALID_RESPONSE","Historical projection is missing");u?.destroy(),u=null,h.replaceChildren();let F=S.run.locale.startsWith("zh"),c=E.createElement("p");c.textContent=F?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",h.append(c);for(let[O,R]of S.review.pages.entries()){let _=E.createElement("button");_.type="button",_.textContent=F?`\u7B2C ${O+1} \u9875`:`Page ${O+1}`,_.onclick=()=>{T(R.receiptId)},h.append(_)}if(S.review.page){let O=S.review.page,R=E.createElement("div");if(R.inert=!0,h.append(R),u=g(R,{mode:"live",rendererUrl:e.client.webViewUrl,title:O.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{w()}}),u.update(O.document,S.run.locale,{serverInput:{bindings:O.inputs,answers:O.answers,values:O.values}}),await u.ready,e.stopped||y!==l||!p)return}let N=F?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},$=F?{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 O of[...S.review.coupons.map((R,_)=>`${F?"\u4F18\u60E0\u5238":"Coupon"} ${_+1}: ${N[R.status]}`),...S.review.purchases.map((R,_)=>`${F?"\u8D2D\u4E70":"Purchase"} ${_+1}: ${$[R.status]}`)]){let R=E.createElement("p");R.textContent=O,h.append(R)}e.client.view&&await e.enqueue(e.client.view)}catch(S){if(y!==l||e.stopped)return;u?.destroy(),u=null,h.replaceChildren(),e.fail(S)}}async function w(){if(!p||e.stopped||!e.client.review)return;let r=++l;try{if(await e.client.review(),e.stopped||r!==l)return;p=!1,l++,u?.destroy(),u=null,h.replaceChildren(),h.hidden=!0,n.hidden=!1;let y=e.client.view;k(y)!==o?(b.set(o,structuredClone(e.answers)),e.resetScreen()):(b.delete(o),e.suspend(!1)),y&&await e.enqueue(y)}catch(y){if(r!==l||e.stopped)return;u?.destroy(),u=null,h.replaceChildren(),e.fail(y)}}return{get active(){return p},get receipt(){return f},open:T,exit:w,get drafts(){return new Map([...b].map(([r,y])=>[r,structuredClone(y)]))},stop(){p=!1,l++,u?.destroy(),u=null,h.replaceChildren(),h.hidden=!0,n.hidden=!1}}}function Re(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let E=e.client.pageExperiments.bind(e.client),n=!1,h=0,g=!1,p=!1,f,l=new Map,u=new Set,o={},b=new Map,k=ge(e.appManifestRelease),T=()=>{for(let c of l.values())c.effect.revert();l.clear();for(let c of b.values())c();b.clear()};function w(c){n||u.has(c)||(u.add(c),E(e.appManifestRelease,[c]).catch(N=>{u.delete(c),e.onError?.(N)}))}async function r(){if(n)return;let c=e.client.view;if(!c||c.stopped||!["running","waiting"].includes(c.status)){h++,T();return}if(g){p=!0;return}g=!0;let N=++h,$=`${c.id}:${c.visit}:${c.revision}`,O=location.href;try{let R=await E(e.appManifestRelease),_=e.client.view;if(n||N!==h||!_||_.stopped||!["running","waiting"].includes(_.status)||`${_.id}:${_.visit}:${_.revision}`!==$||location.href!==O)return;let J=new Set,z=new Set;for(let A of R.assignments){let i=`${R.payload.environmentId}:${A.experimentKey}`;if(z.add(i),b.has(i)||b.set(i,he(i,o)),!!A.inExperiment)for(let s of R.payload.experiments){if(s.key!==A.experimentKey||!ce(location.href,s.urlPatterns??[]))continue;let v=s.meta?.findIndex(V=>V.key===A.variationKey)??-1,C=s.variations[v];if(!C?.renderGuard)continue;let a=A.receiptId+":"+s.changeId,I=JSON.stringify([A.variationKey,C]);if(J.add(a),l.get(a)?.signature===I)continue;l.get(a)?.effect.revert(),l.delete(a);let d=ye(C,{requireUniqueTargets:!0,boundVariations:s.variations,allowJs:!1,onApplied:()=>w(A.receiptId),onError:e.onError});l.set(a,{signature:I,effect:d}),d.applied&&w(A.receiptId)}}for(let[A,i]of l)J.has(A)||(i.effect.revert(),l.delete(A));for(let[A,i]of b)z.has(A)||(i(),b.delete(A))}catch(R){N===h&&T(),e.onError?.(R)}finally{g=!1,p&&!n&&(p=!1,r())}}let y=e.client.subscribe(()=>{h++,r()}),S=ve(()=>{h++,T(),r()}),F=async()=>{await r(),n||(f=setTimeout(()=>{F()},15e3))};return{start:()=>F(),refresh:r,destroy(){n=!0,h++,clearTimeout(f),y(),S(),T(),k.destroy()}}}async function nn(e,E){let n=E,h=n.appManifestRelease?Re({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;h?.start();let{mountScreenPreview:g}=await import("./screen-renderer-A6VYE2QL.js"),{showPaywall:p}=await import("./paywall-ISCYOGPZ.js"),f=e.ownerDocument,l=f.activeElement,u=f.createElement("section"),o=f.createElement("div"),b=f.createElement("div"),k=f.createElement("div"),T=f.createElement("button");k.hidden=!0,T.type="button";let w=f.createElement("p"),r=f.createElement("p"),y=f.createElement("button"),S=f.createElement("button"),F=f.createElement("button"),c=f.createElement("dialog");u.dataset.indianaFunnel="",u.setAttribute("aria-busy","false"),u.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",b.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",w.setAttribute("role","status"),r.setAttribute("role","alert"),r.hidden=!0,y.type=S.type=F.type="button",b.append(y,w,r,F,T,S),u.append(o,k,b),e.append(u);let N=null,$=null,O=null,R="",_="",J="",z="",A="",i=!1,s=0,v=!1,C="",a=null,I=Promise.resolve(),d=null,V=null,M=new Set,G={},x=(t,P=null)=>{i||(V=P,r.textContent=t instanceof Error?t.message:"Request failed",r.hidden=!1,F.hidden=n.client.pendingCommand===null,K(n.onError,t))};function j(){let t=n.client.view;if(!t)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let q=Ee({client:n.client,doc:f,holder:o,reviewHolder:k,mountScreenPreview:g,get stopped(){return i},get answers(){return G},suspend(t){$?.setSuspended(t)},resetScreen(){R="",_="",J=""},enqueue:W,fail:x}),Z=be({client:n.client,expected:j,fail:x,get stopped(){return i},get reviewing(){return q.active},get key(){return R},get busy(){return s}}),ee=Ce({client:n.client,expected:j,perform:B,onIntent:n.onCustomerDataIntent,get stopped(){return i},get busy(){return s},get document(){return N?.document},get answers(){return G}}),oe=t=>t&&(t.screen||t.paywall)?`${t.id}:${t.nodeId}:${t.visit}`:"";function X(){let t=n.client.view;y.disabled=!q.active&&(s>0||!!n.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!oe(t)||_!==oe(t))}async function B(t,P=!1){if(!(s&&!P||i||q.active&&!P)){s++,u.setAttribute("aria-busy","true"),X(),r.hidden=!0,V=null;try{if(!P&&Z.inFlight){let D=n.client.view;await Z.inFlight;let L=n.client.view;if(!D||!L||L.id!==D.id||L.nodeId!==D.nodeId||L.visit!==D.visit||L.stopped||!["running","waiting"].includes(L.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(i)return;let H=await t();i||await W(n.client.view??H.run)}catch(H){x(H,n.client.pendingCommand?.requestId??null)}finally{s=Math.max(0,s-1),u.setAttribute("aria-busy",String(s>0)),i||(F.hidden=n.client.pendingCommand===null,X())}}}function ne(){a&&clearTimeout(a),!(i||!O||!["running","waiting"].includes(O.status)&&!n.client.pendingCommand)&&(a=setTimeout(()=>{a=null,ue().finally(ne)},O.pendingRequest||n.client.pendingCommand?1500:5e3))}async function ue(){if(!(i||v||s)){if(q.active){await q.open(q.receipt);return}v=!0;try{let t=n.client.pendingCommand;t&&n.client.settle&&await n.client.settle(t.requestId);let P=n.client.view,H=ee.queries,D=await n.client.get(P?.screen&&Object.keys(H).length?{nodeId:P.nodeId,visit:P.visit,revision:P.revision,components:H}:void 0);!i&&H===ee.queries&&await W(n.client.view??D.run)}catch(t){x(t)}finally{v=!1}}}function Pe(t){let P=t.screen?.presentation;if(!P||P.type==="inline"){c.open&&c.close(),u.parentElement!==e&&e.append(u);return}u.parentElement!==c&&(c.append(u),e.append(c));let H={sm:420,md:640,lg:900};c.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in P?H[P.size]+"px":"100vw"}`,c.setAttribute("aria-label",N?.document?.name??t.screen?.content.document.name??"Funnel"),c.open||c.showModal()}async function De(t){if(i)return;O=t,V&&n.client.pendingCommand?.requestId!==V&&(r.hidden=!0,V=null);let P=t.locale.startsWith("zh");if(T.textContent=P?"\u56DE\u770B":"History",T.hidden=!n.client.review,y.textContent=q.active?P?"\u8FD4\u56DE\u5F53\u524D":"Return to current":P?"\u8FD4\u56DE":"Back",S.textContent=P?"\u5173\u95ED":"Close",F.textContent=P?"\u91CD\u8BD5":"Retry",X(),F.hidden=n.client.pendingCommand===null,w.textContent=t.pendingRequest?P?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?P?"\u7B49\u5F85\u4E2D":"Waiting":"",C!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(C=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,K(n.onState,structuredClone(t))),t.stopped||n.client.configurationReady===!1){q.stop(),N?.destroy(),N=null,$?.destroy(),$=null,o.replaceChildren(),R="",_="",J="",A="",c.open&&c.close(),u.hidden=!0,ne();return}if(u.hidden=!1,q.active){ne();return}let H=oe(t);if(H!==R&&(_="",N?.destroy(),N=null,$?.destroy(),$=null,o.replaceChildren(),R=H,J="",A="",G={...t.answers},ee.reset()),Pe(t),t.screen){let L=t.screen.content;N||(N=g(o,{mode:"live",rendererUrl:n.client.webViewUrl,title:L.document.name,onAction(Q,se={},ae={}){if(q.active)return;G={...G,...ae};let Oe=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:re})=>Object.hasOwn(G,re)).map(({variable:re})=>[re,G[re]]));B(()=>n.client.submit({operation:"submit",...j(),input:{type:"screen",output:Q,answers:Oe,selection:se}}))},onAnswers:Q=>{q.active||(G={...G,...Q})},onCustomerDataIntent:Q=>{q.active||ee.intent(Q).catch(x)},onEscape:()=>{q.active||te()},onError:Q=>x(new Error(Q)),onRendered:()=>Z.report(H)}));let U={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:G,values:t.screen.values}},Y=JSON.stringify([L,t.locale,U.parameters,t.screen.inputs,t.screen.values]);if(Y!==J)N.update(L.document,t.locale,U),J=Y,z=JSON.stringify(U.capabilities),A=JSON.stringify(U.customerData);else{let Q=JSON.stringify(U.capabilities);Q!==z&&(N.updateCapabilities(U.capabilities),z=Q),JSON.stringify(U.customerData)!==A&&(N.updateCustomerData(U.customerData),A=JSON.stringify(U.customerData))}await N.ready}else if(t.paywall&&!$){let L=await p(o,{canInteract:()=>!q.active&&!i,start:async()=>Ie(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:U=>n.onOpenUrl?n.onOpenUrl({receiptId:t.paywall.receiptId,url:U,openIn:"same_window"}):f.defaultView?.location.assign(U),onAction:async U=>{if(q.active)return;let Y=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision,input:{type:"screen",output:U,answers:{}}});await W(n.client.view??Y.run)},onError:x,onDismiss:()=>{!q.active&&!i&&n.client.view?.visit===t.visit&&te()}});i?L.host?.destroy():($=L.host,$?.setSuspended(q.active)),Z.report(H)}if(i)return;_=H,X();let D=t.instruction;if(D&&(D.type==="open_url"||D.type==="event")&&!M.has(D.receiptId)){let L=f.createElement("button");L.type="button",L.textContent=D.type==="open_url"?`${P?"\u524D\u5F80":"Continue to"} ${new URL(D.url).host}`:P?"\u7EE7\u7EED":"Continue",L.onclick=()=>{let U=j(),Y=D.type==="open_url"&&!n.onOpenUrl&&D.openIn==="new_window"?Se(D.url):null;B(async()=>{let Q="success";if(D.type==="open_url")if(n.onOpenUrl)try{Q=await n.onOpenUrl({receiptId:D.receiptId,url:D.url,openIn:D.openIn})===!1?"failed":"opened"}catch(ae){K(n.onError,ae),Q="failed"}else Q=D.openIn==="new_window"&&!Y?"failed":"opened";if(D.type==="event"){if(!n.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(D.event)}if(i||n.client.view?.nodeId!==U.nodeId||n.client.view.visit!==U.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let se=await n.client.submit({operation:"submit",...U,input:{type:"client_action",receiptId:D.receiptId,outcome:Q}});return M.add(D.receiptId),D.type==="open_url"&&!n.onOpenUrl&&D.openIn==="same_window"&&f.defaultView?.location.assign(D.url),se})},o.replaceChildren(L)}!t.pendingRequest&&t.status==="completed"&&!M.has(`complete:${t.id}`)&&(M.add(`complete:${t.id}`),K(n.onComplete,structuredClone(t))),ne()}function Se(t){let P=f.defaultView?.open(t,"_blank")??null;return P&&(P.opener=null),P}function W(t){return X(),I=I.catch(()=>{}).then(()=>De(t)),I}let Fe=n.client.subscribe(t=>{n.client.configurationReady===!1&&(u.hidden=!0,N?.destroy(),N=null,$?.destroy(),$=null,o.replaceChildren(),R="",_="",J="",A="",c.open&&c.close()),W(t).catch(x)}),Ne=n.client.subscribeError?.(x);function te(){return d||(i?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ie(),Promise.resolve()):(d=B(()=>n.client.submit({operation:"close",...j()}),!0).then(()=>{n.client.view?.status==="closed"&&ie()}).finally(()=>{d=null}),d))}function ie(){h?.destroy(),!i&&(i=!0,a&&clearTimeout(a),Fe(),Ne?.(),N?.destroy(),q.stop(),$?.destroy(),c.close(),c.remove(),u.remove(),l instanceof HTMLElement&&l.isConnected&&l.focus(),K(n.onDismiss,O?structuredClone(O):null))}y.onclick=()=>{if(!y.disabled){if(q.active){q.exit();return}B(()=>n.client.submit({operation:"back",...j()}))}},T.onclick=()=>{q.open()},S.onclick=()=>{te()},F.onclick=()=>{B(()=>n.client.retry())},c.addEventListener("cancel",t=>{t.preventDefault(),te()});try{let t=await n.client.get();await W(n.client.view??t.run)}catch(t){throw ie(),t}return{destroy:ie,refresh:ue,review:q.open,exitReview:q.exit,get unappliedDrafts(){return q.drafts}}}export{Re as a,nn as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as cn,b as dn,c as mn,d as fn}from"./chunk-CPLLMISZ.js";import{a as he}from"./chunk-5O667MKA.js";import{A as H,B as je,C as q,D as He,E as Ee,F as L,G as ze,H as Ke,I as Qe,J as Ye,K as $e,L as We,R as ne,S as Ze,U as we,V as Xe,W as en,ca as nn,da as tn,ha as rn,ia as on,j as oe,ja as an,la as sn,o as qe,q as Ge,qa as un,r as Je,ra as ln,s as Be,sa as Q}from"./chunk-PK5HYUHD.js";import{fa as m}from"./chunk-G23YNWWI.js";import{a as ke,e as ye}from"./chunk-G56XGVMS.js";import{b as ie}from"./chunk-WSVH6IQA.js";import{b as ge}from"./chunk-7DXL3LHT.js";import{e as Me,h as Ue}from"./chunk-3PZ4Y6UD.js";function Vn(e){let n=null,r=null,p=0,u=0,g=!1,c=new Set,t=null,o=null,a=new Set,w=()=>{for(let d of a)try{d()}catch{}},l={attributes:ge.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(d,v)=>{!c.has(d)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(d,structuredClone(v),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(d,v)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(d),structuredClone(v),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?d=>e.saveStickyBucketAssignmentDoc(structuredClone(d)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function x(d,v=new Set){return c.has(d)?!t||!t.features[d]||["unknownFeature","cyclicPrerequisite"].includes(t.features[d].source):v.has(d)?!1:(v.add(d),(n?.features[d]?.rules??[]).some(P=>[...P.parentConditions??[],...(P.tracks??[]).flatMap(R=>R.experiment.parentConditions??[])].some(R=>x(R.id,v))))}let E=d=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return t?.expiresAt&&Date.parse(t.expiresAt)<=Date.now()&&(t=null,l.features=n.features),c.has(d)?!t||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now()?S():structuredClone(t.features[d]??S()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!g||x(d)?S():structuredClone(Ue(d,l))};async function A(){if(!n||!c.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(c.size)throw new Error("Remote Feature evaluation requires a server loader");return}let d=u;if(o?.revision===d)return o.loading;let v=p,P=n,R=[...c],C=(async()=>{let O=Be.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:R}));if(!(v!==p||d!==u||P!==n)){if(e.assertUsable?.(P.generation),O.generation!==P.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(R.some(T=>!Object.hasOwn(O.features,T))||Object.keys(O.features).some(T=>!c.has(T)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!O.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=ge.parse({...l.attributes,...O.merchandiseContext}),g=!0}t=structuredClone(O),l.features={...P.features,...Object.fromEntries(Object.entries(t.features).map(([T,k])=>[T,{defaultValue:k.value}]))},w()}})();o={revision:d,loading:C};try{await C}finally{o?.loading===C&&(o=null)}}function i(){A().catch(d=>{try{e.onError?.(d)}catch{}})}async function s(){if(r)return r;let d=p,v=(async()=>{let P=await e.load(),R="remoteFeatures"in P?Ge.parse(P):null,C=R??ye.parse(P);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(d!==p)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===C.generation){let{evaluatedAt:T,expiresAt:k,...G}=n,{evaluatedAt:W,expiresAt:J,...Z}=C;if(L(G)!==L(Z))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=C.evaluatedAt,n.expiresAt=C.expiresAt,w(),(!t||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())&&i(),structuredClone(n)}let O=new Set(R?.remoteFeatures??[]);if([...O].some(T=>Object.hasOwn(C.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in C&&!n.analyticsConfig.experimentViewsEnabled&&R?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),n=structuredClone(C),c=O,t=null,o=null,u++,l.features=n.features,l.savedGroups=Me(n.savedGroups),l.trackedFeatureUsage={},w(),i(),structuredClone(n)})();r=v;try{return await v}finally{r===v&&(r=null)}}return{init:s,refresh:s,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(d){return a.add(d),()=>{a.delete(d)}},setAttributes(d){let v=ge.parse(d);(l.attributes?.merchandise||l.attributes?.merchandiseId||d.merchandise||d.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=v,u++,g=!1,t=null,o=null,l.features=n?.features??{},l.trackedFeatureUsage={},w(),i()},evalFeature:E,isOn(d){return E(d).on},isOff(d){return E(d).off},getFeatureValue(d,v){let P=E(d).value;return structuredClone(P===null?v:P)},reset(){p++,u++,r=null,o=null,n=null,t=null,c.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),w()}}}function pn(e){let n,r,p=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),u=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,r=e.locks??globalThis.navigator?.locks,!n||!r||!globalThis.crypto?.subtle)throw p();let t=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ie).href,e.runToken])),o=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return"indiana.funnel.commands.v1."+Array.from(o,a=>a.toString(16).padStart(2,"0")).join("")});u.catch(()=>{});async function g(t){try{let o=await u;return await r.request(o,{mode:"exclusive"},()=>t(o))}catch(o){throw o instanceof m?o:p()}}function c(t){let o=n.getItem(t);if(o===null)return{revision:0,entry:null};if(o.length>1048576)throw p();let a=JSON.parse(o);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw p();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>g(c),write:(t,o)=>g(a=>{if(c(a).revision!==t)return null;if(!Number.isSafeInteger(t+1))throw p();return n.setItem(a,JSON.stringify({revision:t+1,entry:o})),t+1})}}async function Ie(e,n){let r=Xe.safeParse(n);if(!r.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let p=r.data;if(e.scope&&(p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return p}async function Fe(e,n,r){if(Number(e.headers.get("content-length"))>n)throw r.error("limit");let p=e.body?.getReader();if(!p)throw r.error("missing");let u=[],g=0;try{for(;;){r.signal?.throwIfAborted();let o=await p.read();if(o.done)break;if(g+=o.value.length,g>n)throw r.error("limit");u.push(o.value)}}finally{await p.cancel().catch(()=>{})}r.signal?.throwIfAborted();let c=new Uint8Array(g),t=0;for(let o of u)c.set(o,t),t+=o.length;return c}async function gn(e,n,r){return new TextDecoder("utf-8",{fatal:!0}).decode(await Fe(e,n,r))}function ve(e,n){let r=typeof e=="string"?new TextEncoder().encode(e):e;return r.byteLength===n.byteLength&&ze(r)===n.sha256}async function Re(e,n){let r=$e.parse(n),{artifact:p,environmentId:u}=r.content,g=new URL(e.baseUrl??ie).origin,c=new URL(p.url,g);if(c.origin!==g||c.username||c.password||c.search||c.hash||c.pathname!==`/api/v1/configuration/${u}/artifacts/${p.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let t=new AbortController,o=setTimeout(()=>t.abort(),q.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(c,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:t.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>p.byteLength)throw new m("INVALID_RESPONSE","Public Paywall is unavailable");let w=await Fe(a,p.byteLength,{signal:t.signal,error:l=>new m("INVALID_RESPONSE",l==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!ve(w,p))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return We(r,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(w)))}finally{clearTimeout(o)}}var le=(e,n)=>new m(e,n);function Xn(e){return on(e,le)}async function Ae(e,n,{predict:r=!0}={}){let p=n.instruction;if(p?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==p.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let u=null,g;if(r)try{let c=await e.funnel(n.source.id,n.source.versionId);g=c.manifest.generation,u=An(e,n,c)}catch{u=null}return g??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:p.policyRevision,generation:g},prediction:u}}function An(e,n,r){let p=n.instruction;if(p?.type!=="evaluate_segment"||!r.growth||r.control.evaluationMode!=="local"||r.control.evaluationRevision!==p.policyRevision)return null;let{analyticsConfig:u,remoteFeatures:g,...c}=r.growth,t=nn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:p.policyRevision,document:r.document,payload:ye.parse(c)}),o=Nn(t,r.document,{...n,...p}),a=o.steps.at(-1),w=o.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+o.steps.length-1}:null);return w?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:w.nodeId,visit:w.visit,terminal:!o.boundary}:null}function Nn(e,n,r){return sn(e,n,r,le)}import{z as B}from"zod";var yn=H.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=B.strictObject({schemaVersion:B.literal(1),scope:ke,runId:B.uuid(),funnelId:B.uuid(),versionId:B.uuid(),command:yn.optional(),closeCommand:yn.refine(e=>e.operation==="close").optional(),purchase:B.strictObject({receiptId:B.uuid(),operationId:B.uuid(),generation:B.number().int().nonnegative()}).optional(),closed:B.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),M=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Ce=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function hn(e){let n=0,r=null,p=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),u=Promise.resolve();async function g(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:wn.parse(o.entry)}}function c(o){let a=u.then(o);return u=a.catch(()=>{}),a}async function t(o){for(let a=0;a<4;a++){let w=await g();if(w.entry&&r!==null&&p(w.entry)!==r)throw M();let l=o(w.entry,w.revision);if(Ce(w.entry,l)){n=w.revision;return}let S=await e.write(w.revision,l);if(S!==null){if(!Number.isSafeInteger(S)||S<=w.revision)throw M();n=S;return}}throw M()}return{bind(o){let a=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(r!==null&&r!==a)throw M();r=a},async load(){let o=await g();return n=o.revision,r=o.entry?p(o.entry):null,o.entry},retain(o){let a=wn.parse(o),w=a.command;return!w||r!==null&&p(a)!==r?Promise.reject(M()):(r??=p(a),c(()=>t((l,S)=>{if(l&&!Ce(p(l),p(a)))throw M();if(!l){if(S!==n&&w.operation!=="close")throw M();return a}if(!l.command)return{...l,command:w,...w.operation==="close"?{closed:!0}:{}};if(w.operation==="close"&&l.command.operation!=="close"){if(l.command.requestId===w.requestId||l.closeCommand&&!Ce(l.closeCommand,w))throw M();return{...l,closeCommand:w,closed:!0}}if(!Ce(l.command,w))throw M();return l})))},observePurchase(o,a,w){return c(()=>t((l,S)=>{if(!l&&S!==n||l&&p(l)!==p({...o,schemaVersion:1}))throw M();if(l?.purchase&&l.purchase.generation>a.generation)return l;if(l?.purchase&&l.purchase.generation===a.generation&&l.purchase.operationId!==a.operationId)throw M();return w?!l?.purchase||l.purchase.operationId!==a.operationId?l:l.command?{...l,purchase:void 0}:null:{schemaVersion:1,...o,...l,purchase:a}}))},settle(o){return c(()=>t(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===o?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===o?{...a,closeCommand:void 0}:a:null))}}}function lt(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ae(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((u,g)=>ae(u,n[g]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let r=Object.entries(e),p=Object.entries(n);return r.length===p.length&&r.every(([u,g])=>Object.hasOwn(n,u)&&ae(g,Reflect.get(n,u)))}function In(e){let n=null,r=0,p=!1,u,g=0,c=new Set;return{get view(){return n},get generation(){return r},get disposed(){return p},get customerToken(){return u},get readSequence(){return g},nextRead(){return++g},assertCurrent(t,o="Run identity changed during the request"){if(t!==r||p)throw new m("IDENTITY_CHANGED",o)},assertRun(t){if(n&&(t.id!==n.id||t.source.type!==n.source.type||t.source.id!==n.source.id||t.source.versionId!==n.source.versionId||t.locale!==n.locale||!ae(t.parameters,n.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&t.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(t,o,a,w,l){if(!(t.operation==="review"&&n&&n!==a&&o.run.revision<=n.revision)&&!(n&&o.run.revision===n.revision&&w!==void 0&&w<g)&&(t.operation==="review"&&!o.run.stopped&&["running","waiting"].includes(o.run.status)&&n&&o.run.nodeId===n.nodeId&&o.run.visit===n.visit&&o.run.revision===n.revision&&(o.run.screen=n.screen,(n.paywall?.quote?.operationId===o.review?.activeOperationId||!n.paywall?.quote&&o.review?.activeOperationId===null)&&(o.run.paywall=n.paywall)),!(n?.paywall&&o.run.paywall&&n.paywall.receiptId===o.run.paywall.receiptId&&(o.run.paywall.selectionGeneration??0)<(n.paywall.selectionGeneration??0)))){if(!n||o.run.revision>=n.revision)n=o.run;else if(!l)return;if(n)for(let S of c)try{S(structuredClone(n))}catch{}}},identify(t){if(!oe.test(t))throw new m("INVALID_TOKEN","Customer credential required");r++,u=t},subscribe(t){return c.add(t),()=>c.delete(t)},reset(){p=!0,r++,u=void 0,n=null,c.clear()}}}var te=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function yt(e,n,r="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!te.test(e))throw new m("INVALID_TOKEN",r)}function wt(e){let n=Q(e);return n.identify(e.apiKey),n}function Y(e){let{customerToken:n,...r}=e;return r}var On=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function vn({options:e,journal:n,state:r,call:p}){let u=null,g=null,c=!1,t={command:null,close:null},o=!1,a,w=null,l=n?n.load().then(i=>{if(r.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(w=i,!i)return;if(e.scope&&(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=i.purchase,c=i.closed===!0,!i.command)return;let s=H.parse(i.command);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");u=s,i.closeCommand&&(g=i.closeCommand,c=!0),s.operation==="close"&&(c=!0),o=!0}):Promise.resolve();l.catch(()=>{});async function S(i=u){if(n&&await l,!i)throw new m("INVALID_REQUEST","No command is pending");let s=i,d=r.generation;if(n){if(!r.view||!e.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await n.retain({schemaVersion:1,scope:e.scope,runId:r.view.id,funnelId:r.view.source.id,versionId:r.view.source.versionId,command:Y(s)})}if(d!==r.generation||u!==s&&g!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let v={...s,...r.customerToken?{customerToken:r.customerToken}:{}},P=o;o=!0;try{return await p(v,R=>{if(!R.settlement)throw new m("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==s.requestId)throw new m("INVALID_RESPONSE","Command settlement identity changed");if(d===r.generation&&(u===s||g===s)&&R.run.pendingRequest?.requestId!==s.requestId&&R.settlement.state==="settled"&&(!c||s.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let C=()=>d!==r.generation||u!==s&&g!==s?!1:(u===s&&(u=null),g===s&&(g=null),o=u!==null,w=null,!0);return n?n.settle(s.requestId).then(C):C()}return!1})}catch(R){throw d===r.generation&&u===s&&!P&&!On(R)&&(n&&await n.settle(s.requestId),d===r.generation&&u===s&&(u=null,o=!1,w=null)),R}}function x(i){let s=H.parse(i);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(c&&s.operation!=="close"){if(u?.requestId===s.requestId)return A(s.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(s.operation==="close"&&u?.operation!=="close"){if(c=!0,g&&JSON.stringify(Y(g))!==JSON.stringify(Y(s)))throw new m("COMMAND_PENDING","Retry the original Close");return g??=s,t.close?t.close:E(g,"close")}if(u){if(JSON.stringify(Y(u))!==JSON.stringify(Y(s)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(t.command)return t.command}else u=s,o=!1;return E(u,"command")}function E(i,s){let d=S(i);t[s]=d;let v=()=>{t[s]===d&&(t[s]=null)};return d.then(v,v),d}async function A(i){let s=await p({operation:"get",settlementRequestId:i,...r.customerToken?{customerToken:r.customerToken}:{}});if(s.settlement?.requestId!==i)throw new m("INVALID_RESPONSE","Exact command settlement is missing");return s.settlement.state==="settled"&&(n&&await n.settle(i),u?.requestId===i&&(u=null,o=!1),g?.requestId===i&&(g=null)),s}return{ready:l,get pending(){return u},get closing(){return g},get closeRequested(){return c},get inFlight(){return t.command},get closeFlight(){return t.close},get purchase(){return a},assertBinding(i){if(w&&(i.run.id!==w.runId||i.run.source.id!==w.funnelId||i.run.source.versionId!==w.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(i,s,d,v){n?.bind({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId}),n&&!e.scope&&(e.scope=s.scope);let P=s.run.paywall,R=P??s.purchase,C=R?.operation,O=s.settlement&&(!P||P.purchaseRequestId===s.settlement.requestId)&&(!a||a.operationId===s.settlement.operationId)?s.settlement:void 0,T=C?.operationId??R?.quote?.operationId??O?.operationId,k=R?.receiptId??O?.receiptId,G=P?.selectionGeneration??a?.generation??0;if(n&&T&&k&&i.operation!=="review"&&(!r.view||s.run.revision>=r.view.revision)&&(v===void 0||v>=r.readSequence)&&(!a||G>=a.generation)){let W={receiptId:k,operationId:T,generation:G},J=C?.status==="complete"||R?.canReselect===!0;return n.observePurchase({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId},W,J).then(()=>{r.assertCurrent(d),J?a?.operationId===W.operationId&&(a=void 0):a=W})}},stop(){c=!0},submit:x,executePending:S,settle:A,reset(){u=null,g=null,t.close=null,o=!1,t.command=null}}}function Rn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!te.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Q({...e,session:void 0,...e.serverKey?{fetch:(i,s)=>{let d=new Headers(s?.headers),v=typeof s?.body=="string"?JSON.parse(s.body):null;return v!==null&&typeof v=="object"&&"customerToken"in v&&typeof v.customerToken=="string"&&v.customerToken.length>0||d.set(en,e.serverKey),(e.fetch??globalThis.fetch)(i,{...s,headers:d})}}:{},...e.session?{fetch:async(i,s)=>{let d=await e.session.access(),v=typeof s?.body=="string"?JSON.parse(s.body):{};return(e.fetch??globalThis.fetch)(i,{...s,body:JSON.stringify({...v,customerToken:d})})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let r=In(e.funnelId),p=e.session?.subscribeIdentity(()=>{r.reset(),n.reset()}),u=null,g=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?pn(e):void 0),c=g&&hn(g),t=vn({options:e,journal:c,state:r,call:o});async function o(i,s,d){let v=r.generation,P=()=>r.assertCurrent(v);c&&await t.ready,P();let R=r.view,C=we.parse(await Ie(e,await n.request("funnels",H.parse(i))));if(i.operation==="review"&&!C.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(P(),C.runToken&&C.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let O=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0;if(O&&C.settlement?.requestId!==O)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");t.assertBinding(C),r.assertRun(C.run);let T=t.observePurchase(i,C,v,d);if(T&&await T,!C.run.stopped&&["running","waiting"].includes(C.run.status)&&i.operation==="get"&&i.settlementRequestId)return C;let k=s?.(C),G=typeof k=="boolean"?k:k?await k:!1;return P(),["running","waiting"].includes(C.run.status)||t.stop(),r.publish(i,C,R,d,G),C}let a=t.submit,w=null,l=new WeakMap;function S(i){let s=l.get(i);if(s)return s;let d=E(i);return l.set(i,d),d}let x=!1;async function E(i){let s=await i;if(s.run.instruction?.type!=="evaluate_segment")return s;if(w)return w;x=!0;let d=r.generation,v=(async()=>{for(let P=0;P<32&&s.run.instruction?.type==="evaluate_segment";P++){if(t.pending||t.closeRequested)return s;let R=s.run;if(s.run.instruction?.type==="evaluate_segment"){let{advance:O}=await Ae(e.configuration,R,{predict:!1});if(d!==r.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(t.pending||t.closeRequested)return s;if(r.view&&(r.view.revision!==R.revision||r.view.visit!==R.visit||r.view.nodeId!==R.nodeId))return o({operation:"get",...r.customerToken?{customerToken:r.customerToken}:{}});let T=!0;Ae(e.configuration,R).then(({prediction:k})=>{T&&d===r.generation&&!t.closeRequested&&r.view?.id===R.id&&!r.view.stopped&&r.view.nodeId===R.nodeId&&r.view.visit===R.visit&&r.view.revision===R.revision&&(u=k)}).catch(()=>{});try{s=await a({operation:"commit_segment",requestId:Ze(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...O})}finally{T=!1,u=null}}}return s})();w=v;try{return await v}finally{w===v&&(w=null)}}let A={get configuration(){return x?e.configuration:void 0},get configurationReady(){return!0},get view(){return r.view?structuredClone(r.view):null},get pendingCommand(){let i=t.closing??t.pending;return i?structuredClone(Y(i)):null},get pendingCommands(){return[t.pending,t.closing].filter(i=>i!==null).map(i=>structuredClone(Y(i)))},get pendingPurchase(){return t.purchase?structuredClone(t.purchase):null},get prediction(){let i=r.view;return u&&i&&!i.stopped&&["running","waiting"].includes(i.status)&&i.id===u.runId&&i.nodeId===u.from.nodeId&&i.visit===u.from.visit&&i.revision===u.from.revision&&!t.closeRequested?structuredClone(u):null},settle:t.settle,get webViewUrl(){return"bundled"},resolvePaywall(i){return Re(e,i)},async pageExperiments(i,s=[]){let d=r.view?.id,v=ln.parse(await n.request("funnels",un.parse({operation:"page_experiments",release:i,usedReceiptIds:s,...r.customerToken?{customerToken:r.customerToken}:{}})));if(!d||v.runId!==d||v.scope.projectId!==e.scope?.projectId||v.scope.environment!==e.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return v},review(i){return o({operation:"review",...i?{receiptId:i}:{},...r.customerToken?{customerToken:r.customerToken}:{}},void 0,r.nextRead())},async get(i,s){c&&await t.ready,s??=t.purchase&&{receiptId:t.purchase.receiptId,operationId:t.purchase.operationId};let d=r.nextRead();return S(o({operation:"get",...i?{data:i}:{},...s?{purchase:s}:{},...r.customerToken?{customerToken:r.customerToken}:{}},void 0,d))},resume(i=r.view?.pendingRequest?.requestId){return i?t.closeRequested?A.settle(i):t.pending?.requestId===i?S(a(t.pending)):S(a({operation:"resume",requestId:i})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(i){return S(a(i))},retry(){return t.closeFlight?t.closeFlight:t.closing?t.executePending(t.closing):t.closeRequested&&t.pending?A.settle(t.pending.requestId):t.inFlight?S(t.inFlight):t.pending?S(a(t.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(i){r.identify(i),u=null,n.identify(e.runToken)},subscribe:r.subscribe,reset(){p?.(),r.reset(),t.reset(),u=null,n.reset()}};return A}async function qt(e,n){if(!oe.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");let r=Q(e);if(!e.session)r.identify(n.customerToken);else if(e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let p=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),u=null,g=!1,c=null,t=null,o=null,a=null,w=e.session?.subscribeIdentity(()=>{g=!0,r.dispose(),u=null,c=null,t=null,o=null});async function l(){if(g)throw new m("IDENTITY_CHANGED","Paywall is closed");let E=ne.resolvePaywall,A=await he(r.request,E,{...p,selector:u?{type:"version",versionId:u.id}:p.selector}),i={paywall:await Re(e,A.paywall)};if(g)throw new m("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?i.paywall.id!==n.paywallVersionId:i.paywall.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(u&&(!cn(i.paywall,u)||i.paywall.paywallId!==u.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return u=i.paywall,structuredClone(u)}async function S(E){if(!c)throw new m("INVALID_REQUEST","A quoted purchase is required");let A=E==="read"?ne.readSubscriptionOperation:ne.attach,i=await he(r.request,A,{operationId:c.operationId,...E==="read"?{}:{intent:E}});return dn(i.operation,{operationId:c.operationId,currency:p.commerce.currency},"The purchase operation changed"),t=fn(t,i.operation),structuredClone(t)}let x={get view(){return u?structuredClone(u):null},get quote(){return c?structuredClone(c):null},get operation(){return t?structuredClone(t):null},get webViewUrl(){return"bundled"},refresh:l,async preview(E){if(!u)throw new m("INVALID_REQUEST","Load the Paywall first");let A=u.document.buttons[E.actionId];if(A?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let i=qe(A.product,E.selection,u.capabilities);if(!i)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let s=ne.previewAttach.request.parse({funnelId:p.funnelId,funnelVersionId:p.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:i}],provider:p.commerce.provider,currency:p.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),d=JSON.stringify(s);if(o&&o!==d&&(!t||t.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===d){if(a)return a;if(c)return structuredClone(c)}o=d;let v=(async()=>{let P=ne.previewAttach,R=await he(r.request,P,s);return mn(R.quote,{productVersionId:i,currency:p.commerce.currency,provider:p.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=R.quote,t=null,structuredClone(c)})();a=v;try{return await v}finally{a===v&&(a=null)}},confirm:()=>S("confirm"),cancel:()=>S("cancel"),read:()=>S("read"),destroy(){w?.(),g=!0,r.dispose(),u=null,c=null,t=null,o=null}};return await l(),x}import{z as Dn}from"zod";import{z as ce}from"zod";var Tn=ce.record(ce.string().regex(/^[a-f0-9]{64}$/),ce.strictObject({at:ce.number(),text:ce.string()})),Cn=2*1048576,xn=100;function _n(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function bn(e,n){let r=n===void 0?_n():n,p=Promise.resolve();async function u(c){if(!r)return null;let t;try{return await Promise.race([Promise.resolve().then(()=>r.getItem(c)),new Promise(o=>{t=setTimeout(()=>o(null),xn)})])}catch{return null}finally{clearTimeout(t)}}async function g(){try{let c=await u(`${e}:artifacts`);if(c&&c.length<=Cn)return Tn.parse(JSON.parse(c))}catch{}return{}}return{async readManifest(){return u(e)},writeManifest(c){Promise.resolve().then(()=>r?.setItem(e,c)).catch(()=>{})},async readArtifact(c){let t=(await g())[c];return t&&Date.now()>=t.at&&Date.now()-t.at<=q.retentionMs?t.text:void 0},writeArtifact(c,t){r&&(p=p.catch(()=>{}).then(async()=>{let o=await g(),a=Date.now();o[c]={at:a,text:t};let w={},l=2,S=0;for(let[x,E]of Object.entries(o).sort(([,A],[,i])=>i.at-A.at)){if(E.at>a||a-E.at>q.retentionMs)continue;let A=new TextEncoder().encode(JSON.stringify({[x]:E})).byteLength;l+A>Cn||S>=128||(w[x]=E,l+=A,S++)}await r.setItem(`${e}:artifacts`,JSON.stringify(w))}).catch(()=>{}))}}}var b=(e,n)=>new m(e,n),$=()=>performance.now(),Sn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Wt(e){let n=He.parse(e.scope),r=new URL(e.origin??ie);if(r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.protocol!=="https:"&&!(r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname)))throw b("INVALID_URL","Configuration requires a trusted HTTPS origin");let p=new Set([r.origin,...(e.assetOrigins??[]).map(y=>{let f=new URL(y);if(f.protocol!=="https:"||f.username||f.password||f.search||f.hash||f.pathname!=="/")throw b("INVALID_URL","Invalid configuration asset origin");return f.origin})]),u=e.fetch??globalThis.fetch.bind(globalThis),g=`/api/v1/configuration/${n.environmentId}`,c=`indiana:configuration:1:${r.origin}:${L(n)}`,t=bn(c,e.storage),o,a=0,w=0,l=!1,S=!1,x=0,E=0,A,i,s,d,v=0,P=new Set,R=new Set,C=new Map,O=new Map,T=0,k=!1;function G(){for(let y of P)try{y()}catch{}}function W(y){try{e.onError?.(y)}catch{}}let J=()=>!S&&!l&&!!o&&$()<a&&Date.now()<w;function Z(){if(!J())throw b("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ne(y,f){let h=new TextEncoder().encode(f).byteLength;if(!C.has(y)){for(;C.size&&(C.size>=128||T+h>q.maxCacheBytes);){let I=C.entries().next().value;T-=new TextEncoder().encode(I[1]).byteLength,C.delete(I[0])}C.set(y,f),T+=h}}function Oe(y,f,h){return gn(y,f,{signal:h,error:I=>b("INVALID_RESPONSE",I==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Te(y){let f=new URL(y,r);if(!p.has(f.origin)||f.username||f.password||f.hash||f.search)throw b("INVALID_URL","Configuration artifact origin is not trusted");return f.href}async function be(y,f,h=!1){let I=await u(Te(y),{method:"GET",credentials:"omit",redirect:"error",cache:h?"default":"no-cache",signal:f,headers:{}});if(I.status===429){let F=I.headers.get("retry-after")??"";v=/^\d+$/.test(F)?Number(F)*1e3:Math.max(0,Date.parse(F)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw b(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function En(y,f,h){let I=Date.parse(y.headers.get("x-indiana-config-validated-at")??""),F=Date.parse(y.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(y.headers.get("date")??""),N=y.headers.get("age"),U=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![I,F,_,U].every(Number.isFinite)||F<=I||F-I>q.maxControlAgeMs||I>_+1e3)throw b("INVALID_RESPONSE","Configuration freshness evidence is invalid");let D=Math.min(F-I,h.maxControlAgeSeconds*1e3,q.maxControlAgeMs)-Math.max(U,_-I,0)-($()-f);if(D<=0)throw b("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return $()+D}function Se(){if(clearTimeout(s),clearTimeout(d),S||!P.size)return;J()&&(d=setTimeout(()=>{J()?Se():G()},Math.max(1,a-$())),Sn(d));let y=E?Math.min(15e3,1e3*2**Math.min(E-1,4)):Math.min(15e3,(o?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{re().catch(W)},Math.max(v,y*(.8+Math.random()*.2))),Sn(s)}async function re(){if(S)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(A)return A;let y=x,f=new AbortController;i=f;let h=(async()=>{if(!k){k=!0;try{let pe=await t.readManifest();if(pe&&!o){let j=Ee.parse(JSON.parse(pe));L(j.scope)===L(n)&&(o=j)}}catch{}}f.signal.throwIfAborted();let N=o,U=$(),V=await be(g,f.signal);V.status===304&&(!N||!V.headers.has("x-indiana-config-validated-at")||!V.headers.has("x-indiana-config-valid-until")||!V.headers.has("age"))&&(V=await be(g,f.signal));let D=V.status===304?N:Ee.parse(JSON.parse(await Oe(V,q.maxManifestBytes,f.signal))),{generation:z,...K}=D,X=V.headers.get("etag");if(L(D.scope)!==L(n)||Ke(K)!==z||X!==`"${z}"`&&X!==`W/"${z}"`)throw b("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(D.revision<N.revision||D.revision===N.revision&&D.generation!==N.generation))throw b("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[pe,j]of Object.entries(N?.funnels??{})){let ee=D.funnels[pe];if(ee&&(ee.controlRevision<j.controlRevision||ee.evaluationRevision<j.evaluationRevision||ee.controlRevision===j.controlRevision&&ee.state!==j.state||ee.evaluationRevision===j.evaluationRevision&&ee.evaluationMode!==j.evaluationMode))throw b("INVALID_RESPONSE","Funnel control revision changed identity")}let Ve=En(V,U,D.policy);if(f.signal.throwIfAborted(),y!==x)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return o=D,a=Ve,w=Date.now()+Math.max(0,Ve-$()),l=!1,E=0,v=0,t.writeManifest(L(D)),G(),structuredClone(D)})(),I=setTimeout(()=>f.abort(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs),F=new Promise((N,U)=>f.signal.addEventListener("abort",()=>U(f.signal.reason),{once:!0})),_=Promise.race([h,F]).catch(N=>{throw E++,(N instanceof Dn.ZodError||N instanceof SyntaxError||N instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,l=!0,G()),N}).finally(()=>{clearTimeout(I),A===_&&(A=void 0),Se()});return A=_,_}async function de(y){let f=y.sha256,h=z=>ve(z,y);Te(y.url);let I=C.get(f);if(I&&h(I))return C.delete(f),C.set(f,I),I;if(O.has(f))return O.get(f);let F=new AbortController;R.add(F);let _=x,N=(async()=>{try{let X=await t.readArtifact(f);if(X&&h(X))return Ne(f,X),X}catch{}F.signal.throwIfAborted();let z=await be(y.url,F.signal,!0),K=await Oe(z,y.byteLength,F.signal);if(!h(K))throw b("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(S||_!==x)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return Ne(f,K),t.writeArtifact(f,K),K})(),U=setTimeout(()=>F.abort(b("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),q.initializationMs),V=new Promise((z,K)=>F.signal.addEventListener("abort",()=>K(F.signal.reason),{once:!0})),D=Promise.race([N,V]).finally(()=>{clearTimeout(U),R.delete(F),O.delete(f)});return O.set(f,D),D}async function me(){return J()||await re(),Z(),o}async function se(y){let f,h=new Promise((I,F)=>{f=setTimeout(()=>F(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs)});try{return await Promise.race([y(),h])}finally{clearTimeout(f)}}function ue(y,f){if(Z(),o?.generation!==y.generation)throw b("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(f&&o.funnels[f]?.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function xe(y){let f=y.gb.features;if(!f)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let h=y.artifacts[f];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=Je.parse(JSON.parse(await de(h)));if(L(I.scope)!==L({projectId:n.projectId,environment:n.environment})||I.generation!==h.generation||I.remoteFeatures.some(F=>Object.hasOwn(I.features,F)))throw b("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return ue(y),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-$())).toISOString()}}async function _e(y,f){let h=await me(),I=h.funnels[y];f&&(!I||I.evaluationMode==="local"&&!I.versions[f])&&(A&&await A,h=await re()),ue(h,y);let F=h.funnels[y];if(F.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let _=f??F.currentVersionId,N=F.versions[_];if(!N)throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(h.artifacts[N.artifact].formatVersion!==3)throw b("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[U,V]=await Promise.all([de(h.artifacts[N.artifact]).then(D=>Ye(JSON.parse(D))),F.evaluationMode==="local"?xe(h):void 0]);if(V&&L(Qe(U,V))!==L(N.dependencies))throw b("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return ue(h,y),{document:U,growth:V,versionId:_,control:structuredClone(F),manifest:structuredClone(h)}}async function De(y,f){try{return await _e(y,f)}catch(h){if(!(h instanceof m)||!(h.code==="CONFIGURATION_CHANGED"||h.code==="CONFIGURATION_HTTP_404"&&J()))throw h;let I=o?.generation;if(A&&await A,await re(),h.code!=="CONFIGURATION_CHANGED"&&o?.generation===I)throw h;return _e(y,f)}}function Pe(){l=!0,G(),re().catch(W)}let fe=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Pe()};function Fn(y){if(S)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(y),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",Pe),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),Se()),()=>{P.delete(y),P.size||(clearTimeout(s),clearTimeout(d),Le())}}function Le(){typeof window<"u"&&(window.removeEventListener("online",Pe),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:re,subscribe:Fn,assertFresh:Z,assertFeatures(y){Z();let f=o.gb.features;if(!f)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(y!==void 0&&o.artifacts[f].generation!==y)throw b("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return J()},get snapshot(){return o?structuredClone(o):null},get remainingMs(){return J()?Math.max(0,a-$()):0},async features(){return se(async()=>xe(await me()))},pageExperiments:()=>se(async()=>{let y=await me(),f=y.gb.pageExperiments;if(!f)throw b("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let h=y.artifacts[f];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=rn.parse(JSON.parse(await de(h)));if(I.environmentId!==n.environmentId||I.generation!==h.generation)throw b("INVALID_RESPONSE","Page experiment scope or generation changed");return ue(y),I}),funnel:(y,f)=>se(()=>De(y,f)),paywall:(y,f)=>se(async()=>{let h=await me(),I=h.paywalls?.[y];if(!I||!f&&I.state!=="published")throw b("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let F=f??I.currentVersionId,_=I.versions[F],N=_&&h.artifacts[_.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let U=je.parse(JSON.parse(await de(N)));return ue(h),{document:U,versionId:F,version:_.version,control:structuredClone(I),manifest:structuredClone(h)}}),async localFunnel(y,f){let h=await se(()=>De(y,f));if(!h.growth)throw b("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:F,..._}=h.growth;return tn({scope:{projectId:n.projectId,environment:n.environment},funnelId:y,versionId:h.versionId,evaluationMode:"local",evaluationRevision:h.control.evaluationRevision,document:h.document,payload:_})},assertFunnel(y,f,h){Z();let I=o.funnels[y];if(!I||I.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel now executes at Indiana");if(f!==void 0&&I.controlRevision!==f)throw b("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(h!==void 0&&!I.versions[h])throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!S){S=!0,x++,a=0,i?.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(d),Le(),G(),P.clear();for(let y of R)y.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));C.clear(),T=0}}}}function nr(e,n,r){return an(e,n,r,le)}function Pn(e){let n=oe.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!te.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");let r=Q({...e,timeoutMs:e.timeoutMs??35e3});return e.session||r.identify(e.apiKey),{async start(p){let u=H.safeParse({...p,operation:"start"});if(!u.success||u.data.operation!=="start"||(n?u.data.customer!==void 0:u.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let g=u.data,c=we.safeParse(await Ie(e,await r.request("funnels",g)));if(!c.success||!c.data.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");let t=c.data;if(t.run.source.id!==g.funnelId||t.run.locale!==(g.locale??"en")||!ae(t.run.parameters,g.parameters??{})||(g.customer?!t.customerId||g.customer.type==="id"&&t.customerId!==g.customer.value:t.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...t,runToken:t.runToken}}}}async function pr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let r={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(r)!==L(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let u=te.test(e.credential);if(u?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let g=Pn({...e,scope:r,apiKey:e.credential}),c=t=>{let o=Rn({...e,scope:r,runToken:t,...u?{serverKey:e.credential}:{}});return u||o.identify(e.credential),o};return{async start(t){let o=await g.start({...t,funnelId:e.funnelId,...u?{customer:{type:"id",value:e.customerId}}:{}}),a=c(o.runToken),w=await a.get();return{...o,...w,controller:a}},async restore(t){let o=c(t),a=await o.get();if(a.run.source.id!==e.funnelId)throw o.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:t,controller:o}}}}export{Vn as a,Ie as b,le as c,Xn as d,Nn as e,pn as f,lt as g,ae as h,yt as i,wt as j,Rn as k,qt as l,Wt as m,nr as n,Pn as o,pr as p};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var s={name:"@tinkerlandai/indiana-sdk",version:"0.
|
|
1
|
+
var s={name:"@tinkerlandai/indiana-sdk",version:"0.9.2",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"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var i="https://api.tinker.cash";export{s as a,i as b};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as D,b as j,c as N,d as $}from"./chunk-65TBYVCS.js";import{a as O}from"./chunk-DSPLGTQI.js";import{a as C}from"./chunk-WSVH6IQA.js";import{b as I,e as _,g as U}from"./chunk-3PZ4Y6UD.js";var W=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function Z(e,t){let n=e,r=o=>Number.isInteger(o)&&o>=0;return!!n&&typeof n=="object"&&r(n.inserted)&&r(n.duplicates)&&r(n.skipped)&&Array.isArray(n.rejected)&&n.inserted+n.duplicates+n.skipped+n.rejected.length===t}function Y(e){let t=[],n,r=(a,i)=>e.log?.(`${e.label} ${a}`,i);function o(a){n===void 0&&t.length&&(n=setTimeout(()=>{u()},a))}async function s(a){let i;try{i=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:a}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(p){return r("not sent",{error:p}),!1}if(i.status===408||i.status===429||i.status>=500)return r("not sent",{status:i.status}),!1;if(!i.ok)return r("rejected",{status:i.status,events:a.length}),!0;let f;try{f=await i.json()}catch{f=void 0}return Z(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:i.status}),!1)}function u(){clearTimeout(n),n=void 0;let a=[];for(;t.length&&a.length<20&&(!a.length||W([...a,t[0]].map(i=>i.event))<=65536);)a.push(t.shift());return a.length?s(a.map(i=>i.event)).then(i=>{if(i)return o(1e3);let f=a.filter(p=>++p.attempts<5);f.length<a.length&&r("dropped after retries",{events:a.length-f.length}),t.unshift(...f),o(5e3)}):Promise.resolve()}return{push(a){t.push({event:a,attempts:0}),t.length>=20?u():o(1e3)},flush:u}}async function V(e,t,n,r={}){let o=r.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(o);let u=e.body.getReader(),a=[],i=0,f=!1,p=()=>{},g=new Promise((v,h)=>{p=()=>h(Error(o)),n.addEventListener("abort",p,{once:!0}),n.aborted&&p()});try{for(;;){let m=await Promise.race([u.read(),g]);if(m.done){f=!0;break}if(i+=m.value.byteLength,i>t)throw Error(o);a.push(m.value)}let v=new Uint8Array(i),h=0;for(let m of a)v.set(m,h),h+=m.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(v))}finally{n.removeEventListener("abort",p),f||u.cancel().catch(()=>{}),u.releaseLock()}}async function q(e,t){let n=e?.body;if(!n)return;let r=n.getReader(),o=0,s=!1,u,a=new Promise((p,g)=>{u=setTimeout(()=>g(Error("Exposure response timeout")),2e3)}),i=()=>{},f=new Promise((p,g)=>{i=()=>g(t?.reason),t?.addEventListener("abort",i,{once:!0}),t?.aborted&&i()});try{for(;;){let p=await Promise.race([r.read(),a,f]);if(p.done){s=!0;return}if(o+=p.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(u),t?.removeEventListener("abort",i),s||r.cancel().catch(()=>{}),r.releaseLock()}}var ue=2*1024*1024,B=256*1024;async function J(e,t,n,r){let o=()=>{},s=new Promise((u,a)=>{o=()=>a(r.reason),r.addEventListener("abort",o,{once:!0}),r.aborted&&o()});try{let u=e(t,{...n,signal:r});return u.then(a=>{r.aborted&&a.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{r.removeEventListener("abort",o)}}async function de(e,t,n,r=!1){if(new TextEncoder().encode(n).byteLength>65536)throw Error("Exposure request budget");let o=new URL(t);o.searchParams.set("sdkVersion",C.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let a=await J(e,o.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:n,credentials:"omit",keepalive:r,redirect:"error"},s.signal);await q(a,s.signal)}finally{clearTimeout(u)}}function G(e){let t,n=!1;return{async read(r,o){if(n)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,a=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let i=await J(e,r,{cache:"no-cache",credentials:"omit",redirect:"error"},u),f=await V(i,o,u);return u.throwIfAborted(),f}finally{clearTimeout(a),t===s&&(t=void 0)}},destroy(){n=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}/*!
|
|
2
|
+
Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
|
|
3
|
+
plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
|
|
4
|
+
*/function ee(e,t){let n,r;try{n=new URL(e),r=new URL(t)}catch{return t}return n.searchParams.forEach((o,s)=>{r.searchParams.has(s)||r.searchParams.set(s,o)}),r.toString()}function te(e,t){let n=navigator.userAgent,r=new URLSearchParams(t.search),o={};for(let s of["source","medium","campaign","term","content"]){let u=r.get(`utm_${s}`);u!==null&&(o[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(n)?"edge":/Chrome/.test(n)?"chrome":/Firefox/.test(n)?"firefox":/Safari/.test(n)?"safari":"unknown",deviceType:/Mobi/.test(n)?"mobile":"desktop",...o}}function re(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(r=>!!r&&!["namespace","status","url","groups"].some(o=>Object.hasOwn(r,o))&&(r.hashVersion===void 0||r.hashVersion===2)&&typeof r.key=="string"&&Array.isArray(r.variations)&&r.variations.length>=2&&r.variations.every(o=>!!o&&typeof o.urlRedirect=="string")&&(r.urlPatterns===void 0||Array.isArray(r.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function ve(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=N(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),r=G(async(c,d)=>{let l=await n(c,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),o=e.log?(c,d)=>O(e.log,c,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=D(e.deviceIdCookie??"indiana_did"),a=j(),i=null,f={...e.attributes??{}},p="",g=!1,v=!1,h=0,m=new Map,R=Y({endpoint:`${s}/events`,fetch:n,log:o,label:"Exposure"}),w=R.flush,E={trackedExperiments:new Set,log:o,onExperimentViewed:(c,d)=>{e.trackExposures===!1||i?.trackExposures===!1||R.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...a?{sessionId:a}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:c.key,variationKey:d.key})}},M=()=>{E.url=location.href,E.attributes={...te(u,location),...f}};function H(c){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return c.variations.some(l=>{if(!l.urlRedirect)return!1;let y=new URL(l.urlRedirect);return y.protocol!==d.protocol||y.host!==d.host})}catch{return!0}}function Q(c,d){let l=e.configuration?.snapshot?.generation;p=c;let y=e.navigate??(x=>location.replace(x)),X=e.navigateDelay??(e.navigate?0:100),z=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(x=>setTimeout(x,z))]),new Promise(x=>setTimeout(x,X))]).then(()=>{!g&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&y(c)})}function b(){if(!(!i||g||e.configuration&&!e.configuration.fresh)){M();for(let c of i.experiments){if(H(c)){o?.("Auto experiment blocked",{id:c.key});continue}let d;try{d=U(c,E)}catch(l){o?.("Skipping page experiment",{id:c.key,error:String(l)});continue}if(m.set(c.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=c.persistQueryString?ee(location.href,d.value.urlRedirect):d.value.urlRedirect;I(l,c.urlPatterns??[])?o?.("Skipping redirect because original URL matches redirect URL",{id:c.key}):l!==p&&Q(l,w())}break}}}}let P="",K=()=>{location.href!==P&&(P=location.href,p="",b())},T,A;function F(){T??=$(K),addEventListener("pagehide",S)}let S=()=>{w()};async function k(){if(g)return!1;let c=++h,d;try{d=e.configuration?await e.configuration.pageExperiments():await r.read(s,B)}catch(y){if(g||c!==h)return!1;throw y}if(g||c!==h)return!1;let l=re(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return i?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),i=l,E.savedGroups=_(l.savedGroups),!0}function L(){g||(A??=e.configuration?.subscribe(()=>{!g&&e.configuration?.fresh&&k().then(c=>{c&&b()}).catch(c=>o?.("Page configuration unavailable",{error:String(c)}))}),F(),P=location.href)}return{async start(){v||g||(v=!0,await k()&&(L(),b()))},async refresh(){await k()&&(v&&L(),p="",b())},setAttributes(c){f={...c},b()},getResults(){return new Map(m)},get generation(){return i?.generation??null},destroy(){g||(g=!0,h++,r.destroy(),A?.(),T?.(),removeEventListener("pagehide",S),i=null,m.clear(),w())}}}export{ue as a,de as b,G as c,ee as d,te as e,re as f,ve as g};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { S as StackNode } from './screen-
|
|
2
|
+
import { S as StackNode } from './screen-BITZ11jn.js';
|
|
3
3
|
|
|
4
4
|
declare const configurationScopeSchema: z.ZodObject<{
|
|
5
5
|
projectId: z.ZodString;
|
|
@@ -348,18 +348,18 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
|
|
|
348
348
|
ranges: [number, number][];
|
|
349
349
|
attribute?: string | undefined;
|
|
350
350
|
}[] | undefined;
|
|
351
|
+
condition?: Record<string, z.core.util.JSONType> | undefined;
|
|
352
|
+
force?: number | undefined;
|
|
353
|
+
hashAttribute?: string | undefined;
|
|
351
354
|
seed?: string | undefined;
|
|
352
355
|
hashVersion?: 2 | undefined;
|
|
353
356
|
ranges?: [number, number][] | undefined;
|
|
354
|
-
condition?: Record<string, z.core.util.JSONType> | undefined;
|
|
355
357
|
urlPatterns?: {
|
|
356
358
|
include: boolean;
|
|
357
359
|
type: "regex" | "simple";
|
|
358
360
|
pattern: string;
|
|
359
361
|
}[] | undefined;
|
|
360
|
-
force?: number | undefined;
|
|
361
362
|
persistQueryString?: boolean | undefined;
|
|
362
|
-
hashAttribute?: string | undefined;
|
|
363
363
|
parentConditions?: {
|
|
364
364
|
id: string;
|
|
365
365
|
condition: Record<string, z.core.util.JSONType>;
|
|
@@ -568,6 +568,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
|
|
|
568
568
|
notParticipating: string;
|
|
569
569
|
id: string;
|
|
570
570
|
name: string;
|
|
571
|
+
applyPageExperiment?: true | undefined;
|
|
571
572
|
position?: {
|
|
572
573
|
x: number;
|
|
573
574
|
y: number;
|
|
@@ -608,7 +609,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
|
|
|
608
609
|
event: string;
|
|
609
610
|
} | {
|
|
610
611
|
type: "api";
|
|
611
|
-
operation: "update" | "
|
|
612
|
+
operation: "update" | "refund" | "sendMessage" | "readBalanceSource" | "adjustBalance" | "readUsage" | "setUsage" | "manageBalanceGrant" | "listBalanceGrants" | "restoreNativePurchase" | "setupPayment" | "readPaymentSetup" | "verifySubscriptions" | "previewAttach" | "attach" | "readSubscriptionOperation" | "previewUpdate" | "readSubscriptionUpdate" | "previewRefund" | "readRefund" | "readBillingControls" | "prepareBillingAuthorization" | "confirmBillingAuthorization" | "setBillingCoupons" | "revokeBillingAuthorization" | "listBillingInvoices" | "confirmBillingAdjustment" | "manageBillingLimits" | "manageUsageEntity" | "readUsageAnalytics" | "readCreditAnalytics" | "submitUsageBatch" | "readUsageBatch" | "checkEntitlement" | "resolveOffering" | "readHoldings" | "readLedger" | "readBillingInvoice" | "readCreditStatement" | "quoteBalance" | "trackUsage" | "mutateBalance" | "redeemReward" | "createReferralCode" | "claimRewardProduct" | "readSeats" | "manageSeat" | "redeemCoupon" | "listOffers" | "grantOffer";
|
|
612
613
|
inputs: Record<string, {
|
|
613
614
|
source: "literal";
|
|
614
615
|
value: z.core.util.JSONType;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as _,j as F}from"./chunk-L7LKE3MG.js";import{b as q}from"./chunk-SSLZKIIU.js";import{n as U}from"./chunk-PK5HYUHD.js";import{R as P,X as M,ca as z,da as N,fa as d}from"./chunk-G23YNWWI.js";import{a as v}from"./chunk-DSPLGTQI.js";import"./chunk-G56XGVMS.js";import"./chunk-WSVH6IQA.js";import{a as O}from"./chunk-7DXL3LHT.js";import"./chunk-3PZ4Y6UD.js";import{z as p}from"zod";var V=new WeakMap;function Q(r){let t={string:p.string(),number:p.number().finite(),boolean:p.boolean(),strings:p.array(p.string()),json:O}[r.type];return r.nullable?t.nullable():t}async function ne(r,t){return W(r,t,!1)}async function re(r,t){return W(r,t,!0)}async function W(r,t,w){t.signal?.throwIfAborted();let T=U.parse(t.content),o=T.document;if(V.has(r))throw new d("CONFLICT","Content is already mounted in this container");let f=p.record(p.string(),O).parse(t.inputs??{});if(Object.keys(f).length>40)throw new d("INVALID_REQUEST","Too many content inputs");for(let[e,s]of Object.entries(f))z.parse({[e]:s});if(Object.keys(f).some(e=>!Object.hasOwn(o.contract.inputs,e)))throw new d("INVALID_REQUEST","Undeclared content input");for(let[e,s]of Object.entries(o.contract.inputs))if(Object.hasOwn(f,e))Q(s).parse(f[e]);else if(s.required)throw new d("INVALID_REQUEST",`Missing content input ${e}`);for(let e of Object.keys(o.contract.outputs))if(typeof t.actions[e]!="function")throw new d("INVALID_REQUEST",`Missing host handler for ${e}`);let $=N.parse(t.bindings??[]),a=r.ownerDocument,L,k=o.kind==="popup",n=k?a.createElement("dialog"):null,i=a.createElement("div");if(i.dataset.indianaContent=o.kind,i.setAttribute("aria-label",o.name),i.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",o.name);let e=o.screen.presentation;n.style.cssText="box-sizing:border-box;padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto",e.type==="modal"||e.type==="sheet"?(n.style.width=`${P[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",n.append(i),r.append(n)}else r.append(i);let c=!1,C=!1,g=!1;w&&!n&&(i.style.width=`${r.getBoundingClientRect().width||a.defaultView?.innerWidth||800}px`);let B=w?_(n??i):()=>{},H,x,A=new Promise((e,s)=>{H=e,x=s});A.catch(()=>{});let l=null,E=structuredClone(o.screen);E.actions=E.actions.map(e=>e.type==="event"?{...e,close:!1}:e);let y;function m(){c||(c=!0,t.signal?.removeEventListener("abort",m),x(new Error("Content preparation cancelled")),y?.destroy(),n?.close(),n?.remove(),i.remove(),V.delete(r),n&&L?.())}let S=()=>{g&&(m(),v(t.onDismiss))};if(n){let e=a.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),e.style.cssText="position:absolute;right:8px;top:8px;width:30px;height:30px;z-index:1",e.addEventListener("click",S),n.prepend(e)}n?.addEventListener("cancel",e=>{e.preventDefault(),S()});async function D(){if(c||!g||C||!l)return;let e=l;C=!0,i.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),l=null}catch(s){v(t.onError,s)}finally{C=!1,c||i.removeAttribute("aria-busy")}}function R(){if(c)throw new d("CONFLICT","Content host has been destroyed");g||(L=q(a),B(),w&&!n&&(i.style.width="100%"),n?.showModal(),g=!0)}try{w||R(),y=F(i,{mode:"live",title:o.name,viewportHeight:o.kind==="page"?r.clientHeight||a.defaultView?.innerHeight||800:void 0,onRendered:H,onError:u=>{let I=new Error(u);x(I),v(t.onError,I)},onEscape:k?S:void 0,onAction:(u,I,J)=>{if(c||!g||C||l)return;let h=o.screen.actions.find(b=>b.id===u),j=o.contract.outputs[u];if(!(h?.type!=="event"||!j))try{let b=Q(j).parse(Object.hasOwn(h.properties,"value")?h.properties.value:h.properties);l={requestId:crypto.randomUUID(),contentVersionId:T.id,actionId:u,event:h.event,value:b,selection:I??{},answers:J??{},requestedClose:h.close},D()}catch(b){v(t.onError,b)}}});let e={destroy:m,show:R,get pendingAction(){return l?structuredClone(l):null},retryAction:D,updateCapabilities:u=>y?.updateCapabilities(u)};V.set(r,e),t.signal?.addEventListener("abort",m,{once:!0}),t.signal?.aborted&&(m(),t.signal.throwIfAborted());let s=M(E,[t.locale,...a.defaultView?.navigator.languages??[]]);if(y.update(E,s,{capabilities:t.capabilities,serverInput:{bindings:$,answers:{},values:f}}),await Promise.race([y.ready,A]),w&&await A,c)throw new Error("Content preparation cancelled");return e}catch(e){throw m(),e}}export{ne as mountContent,re as prepareContent};
|
|
@@ -65,6 +65,17 @@ declare const errorReasonSchema: z.ZodEnum<{
|
|
|
65
65
|
}>;
|
|
66
66
|
type ErrorReason = z.infer<typeof errorReasonSchema>;
|
|
67
67
|
|
|
68
|
+
/** A session survives access-token rotation; neither token selects another Customer. */
|
|
69
|
+
declare const customerSessionSchema: z.ZodObject<{
|
|
70
|
+
customerId: z.ZodUUID;
|
|
71
|
+
sessionId: z.ZodUUID;
|
|
72
|
+
accessToken: z.ZodString;
|
|
73
|
+
refreshToken: z.ZodString;
|
|
74
|
+
expiresAt: z.ZodISODateTime;
|
|
75
|
+
refreshExpiresAt: z.ZodISODateTime;
|
|
76
|
+
}, z.core.$strip>;
|
|
77
|
+
type CustomerSession = z.infer<typeof customerSessionSchema>;
|
|
78
|
+
|
|
68
79
|
type PushJournal = {
|
|
69
80
|
identitySeq: number;
|
|
70
81
|
addressSeq: number;
|
|
@@ -101,4 +112,4 @@ declare class IndianaError extends Error {
|
|
|
101
112
|
});
|
|
102
113
|
}
|
|
103
114
|
|
|
104
|
-
export { IndianaError as I, type PushAddressObservation as P, type Scope as S, type PushHost as a, type PushJournal as b };
|
|
115
|
+
export { type CustomerSession as C, IndianaError as I, type PushAddressObservation as P, type Scope as S, type PushHost as a, type PushJournal as b };
|