@tinkerlandai/longplay-sdk 0.10.56 → 0.10.58
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 +8 -0
- package/dist/check-response-EYOK5EU5.js +1 -0
- package/dist/{chunk-MJ3YZT3G.js → chunk-227Z7LU4.js} +1 -1
- package/dist/{chunk-TPFGWBVS.js → chunk-2PY7INHO.js} +1 -1
- package/dist/{chunk-TKBXL3WV.js → chunk-46MFVWRW.js} +1 -1
- package/dist/{chunk-C6THF4EZ.js → chunk-4BHGHPI5.js} +1 -1
- package/dist/{chunk-V7KYGDFS.js → chunk-4UOJT46E.js} +1 -1
- package/dist/{chunk-YNBMNXUI.js → chunk-4VZCPOVE.js} +1 -1
- package/dist/{chunk-ZOVQW5BP.js → chunk-6HNCADWS.js} +1 -1
- package/dist/chunk-6PVQF4FJ.js +1 -0
- package/dist/{chunk-HBMFTVDT.js → chunk-6UQ7BKSR.js} +1 -1
- package/dist/{chunk-O6URZTR3.js → chunk-6VWVBQFR.js} +1 -1
- package/dist/{chunk-R4CEK37U.js → chunk-AIRW6CZ7.js} +1 -1
- package/dist/{chunk-RUAV3HOQ.js → chunk-D26ZQC46.js} +1 -1
- package/dist/{chunk-QVPSTUJ4.js → chunk-EHYW66EH.js} +1 -1
- package/dist/{chunk-5NDKI3NX.js → chunk-EP2L4VTS.js} +1 -1
- package/dist/chunk-F4E42S54.js +1 -0
- package/dist/{chunk-UFOIGB3V.js → chunk-G2JC7G3R.js} +1 -1
- package/dist/{chunk-W66QWQ2D.js → chunk-GCTD4RXV.js} +1 -1
- package/dist/{chunk-OPUEQMJ2.js → chunk-GIX2F53I.js} +1 -1
- package/dist/{chunk-3B6TBSJL.js → chunk-GLVCBJL5.js} +1 -1
- package/dist/{chunk-GH5OMAX4.js → chunk-HIH6IEV7.js} +1 -1
- package/dist/{chunk-XZTHQPBE.js → chunk-IJQFSZQG.js} +1 -1
- package/dist/{chunk-VROUIFSG.js → chunk-KXA4JHFW.js} +1 -1
- package/dist/{chunk-XRCW5N3J.js → chunk-LB2ZRTRA.js} +1 -1
- package/dist/{chunk-3DH36REB.js → chunk-LDNDI6G3.js} +1 -1
- package/dist/{chunk-BSYGUZTD.js → chunk-LTWU7HH5.js} +1 -1
- package/dist/{chunk-DJP3QRW3.js → chunk-NFZUVZJP.js} +1 -1
- package/dist/{chunk-FA4TDZ5J.js → chunk-NPKNI2UD.js} +1 -1
- package/dist/{chunk-EJ5YUUWB.js → chunk-NQZ23AGQ.js} +1 -1
- package/dist/{chunk-64KBBZD7.js → chunk-NTYIQ5YC.js} +1 -1
- package/dist/{chunk-5OPOCHOK.js → chunk-P2JQEGYV.js} +1 -1
- package/dist/{chunk-ZPGXI7SS.js → chunk-PYTI77BV.js} +1 -1
- package/dist/{chunk-LI5S3AAP.js → chunk-PZTFSADV.js} +1 -1
- package/dist/{chunk-SIEWM7RJ.js → chunk-QA3LXFSK.js} +1 -1
- package/dist/{chunk-YTT3OR7C.js → chunk-QY5TS3OY.js} +1 -1
- package/dist/chunk-RB2SBQMM.js +1 -0
- package/dist/{chunk-QV6FPIP5.js → chunk-RSKDG2VD.js} +1 -1
- package/dist/{chunk-5GFDXNBE.js → chunk-RXEYS3X5.js} +1 -1
- package/dist/{chunk-LEDJ6HS3.js → chunk-T7AK4QLG.js} +1 -1
- package/dist/{chunk-XQQZZYX6.js → chunk-UB5SVEM6.js} +1 -1
- package/dist/{chunk-JHHSO553.js → chunk-WILVPHE6.js} +2 -2
- package/dist/{chunk-F2PTNSHT.js → chunk-XBF44N3Z.js} +1 -1
- package/dist/{chunk-YQW3LPLJ.js → chunk-XFOU4DZG.js} +1 -1
- package/dist/{chunk-KRTURVO3.js → chunk-XH2JMWC6.js} +1 -1
- package/dist/{chunk-MG4LSTTR.js → chunk-XQAGF6SQ.js} +1 -1
- package/dist/{chunk-7MS4ZLIM.js → chunk-XQJW2RXY.js} +1 -1
- package/dist/{chunk-YKGPZJTV.js → chunk-Y2DUFDPV.js} +1 -1
- package/dist/{chunk-MR475LAL.js → chunk-YIHMOK6T.js} +1 -1
- package/dist/{chunk-3IMU6FJB.js → chunk-YJ2IOBHW.js} +1 -1
- package/dist/{chunk-4VKXDWOF.js → chunk-ZG3EYP5L.js} +1 -1
- package/dist/{content-JV2I65BF.js → content-2SRJS3E3.js} +1 -1
- package/dist/funnel-host-purchase-PBCM5VL5.js +1 -0
- package/dist/{funnel-host-recovery-paywall-PSGZT6MQ.js → funnel-host-recovery-paywall-7Z4VOQCV.js} +1 -1
- package/dist/funnel-paywall-prerender-4J5EFPFQ.js +1 -0
- package/dist/funnel-route-prediction-4CW6WOJY.js +1 -0
- package/dist/funnel-route-source-UM5O7FJS.js +1 -0
- package/dist/funnel-runtime-host-F6B7XCVB.js +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-YVMAYBE2.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-WX2HYHD5.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-PWWDHKVH.js +1 -0
- package/dist/paywall-content-DSZJWOTF.js +1 -0
- package/dist/paywall-session-OOXP3SRE.js +1 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-WZFPWLB5.js +1 -0
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +9 -10
- package/dist/check-response-3OBQIMGN.js +0 -1
- package/dist/chunk-7XX5ZESI.js +0 -1
- package/dist/chunk-LWGET37W.js +0 -1
- package/dist/chunk-OG2WLSCL.js +0 -1
- package/dist/funnel-host-purchase-6Y6SU3B6.js +0 -1
- package/dist/funnel-paywall-prerender-BZ3OBCHW.js +0 -1
- package/dist/funnel-route-prediction-4UCZCVH5.js +0 -1
- package/dist/funnel-route-source-FQEIEUDC.js +0 -1
- package/dist/funnel-runtime-host-DBIJVDWC.js +0 -1
- package/dist/merchant-bridge-contracts-GBBL3HTW.js +0 -1
- package/dist/operation-contracts-RDRBT3QK.js +0 -1
- package/dist/paywall-EL57YBHZ.js +0 -1
- package/dist/paywall-content-YLX2XXIT.js +0 -1
- package/dist/paywall-session-6NKVDVYG.js +0 -1
- package/dist/screen-renderer-XIKOUOI5.js +0 -1
- /package/dist/{chunk-JX6MARAN.js → chunk-COMZFFUA.js} +0 -0
- /package/dist/{chunk-JHHSO553.js.LEGAL.txt → chunk-WILVPHE6.js.LEGAL.txt} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as Bn}from"./chunk-YTT3OR7C.js";import{a as wn}from"./chunk-ZPGXI7SS.js";import{a as _n,b as Un,c as fn,d as mn,e as $e,f as Vn,h as $n,i as Mn,j as xn,k as zn}from"./chunk-HBMFTVDT.js";import{a as Jn}from"./chunk-MG4LSTTR.js";import{a as Sn}from"./chunk-W32FI2A2.js";import{c as On,e as qn,f as Ln,i as Hn,j as He,k as nn,l as Nn,m as tn}from"./chunk-5NDKI3NX.js";import{b as An}from"./chunk-KRTURVO3.js";import{a as pn,d as Dn}from"./chunk-FA4TDZ5J.js";import{C as Tn}from"./chunk-64KBBZD7.js";import{a as ne}from"./chunk-YKGPZJTV.js";import{a as Ie}from"./chunk-DSPLGTQI.js";function Gn(i){let E=new Set,U=new Set,n=null;async function p(a,f){let L=!1;for(;!i.stopped&&i.key===a&&i.client.pendingCommand?.requestId===f;){if(!i.client.settle)throw new ne("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),L=!0,i.client.pendingCommand?.requestId===f&&await new Promise(H=>setTimeout(H,1500))}i.stopped||i.key!==a||(L&&await i.client.get(),!(i.stopped||i.key!==a)&&E.add(a))}function k(a,f){n=f;let L=()=>{n===f&&(n=null),U.delete(a)};return f.then(L,H=>{L(),i.busy||i.fail(H)}),f}function V(a){if(i.reviewing||E.has(a)||U.has(a)||i.stopped)return;U.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||E.has(a)){U.delete(a);return}if(i.busy||i.client.pendingCommand){setTimeout(()=>{f()},250);return}let L=(async()=>{if(i.staleRead){if(await i.staleRead,i.stopped||i.key!==a)return;if(i.client.pendingCommand){setTimeout(()=>{f()},250);return}}let H=i.client.view,oe=i.expected(),u=oe.requestId;try{await i.client.submit({operation:"shown",...oe})}catch(P){if(!(P instanceof ne)||P.code!=="CONFLICT"||P.status!==409||i.client.pendingCommand)throw P;await i.client.get();let s=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!s||!H||s.id!==H.id||s.source.versionId!==H.source.versionId||s.nodeId!==oe.nodeId||s.visit!==oe.visit||s.revision<=oe.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==H.paywall?.receiptId)||!["running","waiting"].includes(s.status)||i.client.pendingCommand)throw P;let r=i.expected();u=r.requestId,await i.client.submit({operation:"shown",...r})}await p(a,u)})();k(a,L)};f()}function D(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return U.add(f),k(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:V,settled:D,get inFlight(){return n}}}function Qn(i){let E={},U=new Map;async function n(p){let k=i.client.view,V=k?.screen,D=V?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!k||!V||!D)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let P=i.document,s=P?Tn(P,p.nodeId):null,r=s?.type==="customer_data"?s.data.outputs?.[p.action]:void 0;r&&V.outputs.includes(r)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:r,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,k);return}let f=p.action.startsWith("sources_")?D.resources.find(P=>P.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new ne("INVALID_REQUEST","Choose a current resource");let L=`${k.visit}:${p.nodeId}:${f?.key??""}`,H=U.get(L)??[null],u=E[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let P=p.value;if(!P||!(D.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(P))throw new ne("INVALID_REQUEST","Unknown data filter");u={page:1,after:null,filter:P},H.splice(0,H.length,null)}else if(p.action==="next"||p.action==="sources_next"){let P=f?.sources.at(-1),s=f?P?{kind:"ledger",cursor:{at:P.detail[0],id:P.id,type:"source"}}:null:V.dataCursors[p.nodeId];if(!s||!f&&!D.hasNext)return;H[u.page]=s,u={...u,page:u.page+1,after:s}}else if(p.action==="previous"||p.action==="sources_previous"){if(u.page<=1)return;u={...u,page:u.page-1,after:H[u.page-2]??null}}U.set(L,H),E={...E,[p.nodeId]:u},await i.perform(()=>i.client.get({nodeId:k.nodeId,visit:k.visit,revision:k.revision,components:E}))}return{get queries(){return E},intent:n,reset(){E={},U.clear()}}}function Wn(i){let{doc:E,holder:U,reviewHolder:n,mountScreenPreview:p}=i,k=!1,V,D=0,a=null,f="",L,H=new Map,oe=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function u(s){if(i.stopped||!i.client.review||k&&s===V&&L?.active)return;let r=!k||s!==V;k||(f=oe(i.client.view),H.set(f,structuredClone(i.answers))),k=!0,V=s,U.hidden=!0,i.suspend(!0),n.hidden=!1;let S=++D;r&&(L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),L=nn(n,i.loadingOptions,"funnel",()=>{P()}));let A=r?L:void 0;try{if(A?.start(!1,i.client.view?.locale),S!==D||i.stopped)return;let de=i.client.review(s),N=await(A?.wait(de,He)??de);if(i.stopped||S!==D||!k)return;if(!N.review)throw new ne("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,A||n.replaceChildren();let Q=E.createElement("div"),W=A?tn(Q,n):()=>{};n.append(Q);let O=N.run.locale.startsWith("zh"),g=i.chrome;Q.style.cssText=g.history;let j=E.createElement("p");j.textContent=O?"只读回看":"Read-only history",j.style.cssText=g.historyTitle,Q.append(j);let F=E.createElement("p");F.style.cssText=g.historyNote,F.textContent=N.review.pages.length?O?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":O?"还没有可回看的页面。":"There are no earlier pages yet.",Q.append(F);let Te=N.review.page?.receiptId,ve=E.createElement("div");ve.style.cssText=g.historyPages;for(let[K,R]of N.review.pages.entries()){let v=E.createElement("button");v.type="button",v.textContent=O?`第 ${K+1} 页`:`Page ${K+1}`;let he=Te!==void 0&&R.receiptId===Te;v.style.cssText=he?g.primary:g.secondary,he&&v.setAttribute("aria-current","page"),$e(v,()=>i.chrome.focus),v.onclick=()=>{u(R.receiptId)},ve.append(v)}if(ve.childElementCount&&Q.append(ve),N.review.page){let K=N.review.page,R=E.createElement("div");R.inert=!0,R.style.cssText=g.historyPage,Q.append(R),a=p(R,{mode:"live",rendererUrl:i.client.webViewUrl,title:K.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{S===D&&!i.stopped&&A?.present(W)},onError:he=>{if(S!==D||i.stopped)return;let Ce=new Error(he);A?.finish("error",Ce),a?.destroy(),a=null,Q.remove(),i.fail(Ce)},onEscape:()=>{P()}});let v=a;if(v.update(K.document,N.run.locale,{serverInput:{bindings:K.inputs,answers:K.answers,values:K.values}}),await v.ready,i.stopped||S!==D||!k)return}let me=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},z=E.createElement("div");z.style.cssText=g.historyRecords;for(let K of[...N.review.coupons.map((R,v)=>`${O?"优惠券":"Coupon"} ${v+1}: ${me[R.status]}`),...N.review.purchases.map((R,v)=>`${O?"购买":"Purchase"} ${v+1}: ${zn(R.status,O)}`)]){let R=E.createElement("p");R.textContent=K,R.style.margin="0",z.append(R)}z.childElementCount&&Q.append(z),N.review.page||A?.present(W),i.client.view&&await i.enqueue(i.client.view)}catch(de){if(S!==D||i.stopped)return;A?.finish("error",de),a?.destroy(),a=null,n.replaceChildren(),i.fail(de)}}async function P(){if(!k||i.stopped||!i.client.review)return;let s=++D;L?.finish("dismissed");try{if(await i.client.review(),i.stopped||s!==D)return;k=!1,D++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,U.hidden=!1;let r=i.client.view;oe(r)!==f?(H.set(f,structuredClone(i.answers)),i.resetScreen()):(H.delete(f),i.suspend(!1)),r&&await i.enqueue(r)}catch(r){if(s!==D||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(r)}}return{get active(){return k},get receipt(){return V},open:u,exit:P,get drafts(){return new Map([...H].map(([s,r])=>[s,structuredClone(r)]))},stop(){k=!1,D++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,U.hidden=!1}}}var yn=5e3;async function et(i,E,U){let n=E,p=n.prepared&&Bn(n.prepared),k=()=>{};function V(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let D=()=>n.prepared?.state==="shown"&&!!p?.modal,a=n.client.identitySignal,f;try{f=await Promise.all([import("./screen-renderer-XIKOUOI5.js"),import("./paywall-EL57YBHZ.js")]),n.signal?.throwIfAborted(),a?.throwIfAborted()}catch(e){throw V(),e}let[{mountScreenPreview:L},{showPaywall:H}]=f,oe=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Jn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;oe?.start();let u=i.ownerDocument,P=Hn(u),s=!1,r=u.createElement("section"),S=u.createElement("div"),A=u.createElement("div"),de=u.createElement("div"),N=u.createElement("button");de.hidden=!0,N.type="button";let Q=u.createElement("p"),W=u.createElement("p"),O=u.createElement("button"),g=u.createElement("button"),j=u.createElement("button"),F=u.createElement("dialog"),Te,ve=!1;r.dataset.indianaFunnel="",r.dataset.longplayCloseOwner="sdk",r.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),W.setAttribute("role","alert"),W.hidden=!0,O.type=g.type=j.type="button",A.append(O,N,Q,W,j,g),r.append(S,de,A),i.append(r);let me=Un,z=fn(me),K="",R=(u.documentElement.lang||"").startsWith("zh"),v,he="",Ce;for(let e of[O,N,j,g])$e(e,()=>z.focus);function gn(){let e=R?"关闭":"Close";g.parentElement===F?(g.textContent="×",g.setAttribute("aria-label",e),Ln(g,me)):(g.textContent=e,g.removeAttribute("aria-label"),g.style.cssText=z.link+";margin-inline-start:auto")}function Me(e){let t=e?.screen?.content.document.theme??me,o=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,g.parentElement===F]);if(o===K)return;K=o,me=t;let h=g.parentElement===F;z=fn(me,h),r.style.cssText=z.root+";min-width:0"+(h?";display:flex;flex-direction:column;min-height:100%":""),A.style.cssText=z.bar+(h?";margin-top:auto":""),A.hidden&&(A.style.display="none"),O.style.cssText=N.style.cssText=z.secondary,j.style.cssText=z.primary,Q.style.cssText=z.status,W.style.cssText=z.alert,gn(),mn(O)}function be(){A.hidden=O.hidden&&N.hidden&&j.hidden&&W.hidden&&!Q.textContent&&(g.hidden||g.parentElement!==A),A.style.display=A.hidden?"none":"flex",v?.responsive&&Ce!==void 0&&v.setContentHeight(Ce+A.getBoundingClientRect().height)}Me();let ae=null,I=null,le=null,we="",ee="",Pe=!1,xe="",rn="",ze="",l=!1,X=0,Be=!1,vn="",on=null,sn=Promise.resolve(),hn=!n.client.view,Ne,T=U,Je=n.hostPaywallTarget,Ae,_e,Ge="",Qe,te=!1,Re=null,ue=!1,We=()=>n.client.pendingCommand?.operation==="close",ie=null,$=null,an=Sn({document:u,run:async()=>{(!I?.observing||n.client.pendingCommand)&&await dn()},delay:()=>{if(!re.pending&&!(l||!le||!["running","waiting"].includes(le.status)&&!n.client.pendingCommand)&&!(I?.observing&&!n.client.pendingCommand))return le.pendingRequest||n.client.pendingCommand?1500:yn},hiddenDelay:()=>!l&&!re.pending&&n.client.pendingCommand?15e3:void 0}),M=null;function ln(){return $&&n.client.hasDurableJournal===!0&&M?.acknowledged===!0&&M.operationId===$.operationId&&n.client.view?.id===M.runId&&n.client.view?.status==="closed"&&n.client.view.revision===M.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?$:null}function In(e){let t=e.run.paywall;if(M&&e.settlement?.requestId===M.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===M.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===M.revision+1&&e.run.nodeId===M.nodeId&&e.run.visit===M.visit&&t?.receiptId===M.receiptId&&t.selectionGeneration===M.selectionGeneration&&(t.quote?.operationId??null)===M.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===M.operationId){let o=M.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,h=pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(o||t.canReselect===!0&&h.type==="native")&&(M.acknowledged=!0)}}let Ee=null,Ue=new Set,ce={},De=!1,Y=(e,t=null)=>{l||(e instanceof ne&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&an.destroy(),Ee=t,De=!1,W.textContent=Vn(e,R),W.hidden=!1,j.hidden=n.client.pendingCommand===null,be(),Ie(n.onError,e))},re=An({client:n.client,document:u,conceal(){l||(pe(),T?.finish("dismissed"),r.hidden=!0,s||(s=!0,P()))},async receive(e){l||await se(n.client.view??e.run)},failed(e){if(!l){if(!re.pending){ue=!1;let t=n.client.view;t&&se(t).then(()=>Y(e),Y);return}Ze(),r.parentElement!==i&&i.append(r),r.hidden=!1,O.hidden=N.hidden=g.hidden=!0,Q.textContent="",Me(),Y(e,n.client.pendingCommand?.requestId??null)}}}),Cn=()=>{l||(Ee=null,W.textContent=Mn(R),W.hidden=!1,j.hidden=!0,be())};function ke(){let e=n.client.view;if(!e)throw new ne("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=Wn({client:n.client,doc:u,holder:S,reviewHolder:de,mountScreenPreview:L,loadingOptions:n,get chrome(){return z},get stopped(){return l},get answers(){return ce},suspend(e){I?.setSuspended(e)},resetScreen(){we="",ee="",xe=""},enqueue:se,fail:Y}),Ve=Gn({client:n.client,expected:ke,fail:Y,get stopped(){return l},get reviewing(){return w.active},get key(){return we},get busy(){return X},get staleRead(){return on}}),je=Qn({client:n.client,expected:ke,perform:Oe,onIntent:n.onCustomerDataIntent,get stopped(){return l},get busy(){return X},get document(){return ae?.document},get answers(){return ce}}),Xe=e=>`${e.id}:${e.nodeId}:${e.visit}`,Se=e=>e&&(e.screen||e.paywall)?Xe(e):"";function ye(){let e=n.client.view;O.disabled=!w.active&&(X>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Se(e)||ee!==Se(e)),O.hidden=!w.active&&!e?.canBack,mn(O);let t=!!I&&!w.active;g.hidden=t&&!T?.active||ve&&!w.active,N.hidden=!n.client.review||!w.active&&!e?.canBack;let o=e?.locale.startsWith("zh");Q.textContent=t?"":X>0||e?.pendingRequest?o?"正在处理":"Processing":e?.instruction?.type==="wait"?o?"等待中":"Waiting":"",be()}async function bn(e){if(!e)return;let t=n.client.view;await e;let o=n.client.view;if(!t||!o||o.id!==t.id||o.nodeId!==t.nodeId||o.visit!==t.visit||o.stopped||!["running","waiting"].includes(o.status))throw new ne("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Oe(e,t=!1,o){if(!((X||ue||ie||$)&&!t||l||w.active&&!t)){X++,r.setAttribute("aria-busy","true"),W.hidden=!0,Ee=null,De=!1,ye();try{if(t||await bn(Ve.inFlight),l)return;let h=await e();l||await se(n.client.view??h.run)}catch(h){o?.(h)&&n.client.pendingCommand===null?Cn():re.pending||Y(h,n.client.pendingCommand?.requestId??null)}finally{X=Math.max(0,X-1),r.setAttribute("aria-busy",String(X>0)),l||(j.hidden=n.client.pendingCommand===null,ye())}}}function qe(){an.schedule()}async function dn(){if(!(l||Be||X)&&!re.pending){if(w.active){await w.open(w.receipt);return}Be=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,o=je.queries,h=await n.client.get(t?.screen&&Object.keys(o).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:o}:void 0);De&&!l&&(De=!1,W.hidden=!0,be()),!l&&o===je.queries&&await se(n.client.view??h.run)}catch(e){Y(e),De=!l}finally{Be=!1}}}function Ye(e,t,o){if(T?.active){let Z=T;return Z.setDismissHandler(()=>Pn(Z)),Z}let h=nn(i,n,"funnel",()=>Pn(h),_n);return T=h,h.start(e,t,o),h}function Pn(e){l||te||(te=!0,e.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):B())}function un(){clearTimeout(Qe?.timeout),Qe=void 0}function pe(e){ve=!1,un(),Ae?.abort(),Ae=void 0,ae?.destroy(),ae=null,I?.destroy(),I=null,Ne=void 0,_e?.(),_e=void 0,F.open&&F.close();for(let t of Array.from(S.children))(!e||!t.contains(e))&&t.remove();S.style.cssText="",Ce=void 0,we="",ee="",Pe=!1,xe="",ze=""}function Rn(){let e=u.defaultView;v?.responsive&&e&&ae?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ze(){v?.destroy(),v=void 0,he=""}function Ke(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){F.open&&F.close(),Ze(),g.parentElement!==A&&A.append(g),r.parentElement!==i&&i.append(r);for(let Z of["flex","display","flex-direction","justify-content"])S.style.removeProperty(Z);Me(e),be();return}r.parentElement!==F&&(F.append(g,r),i.append(F)),S.style.flex="1 0 auto",S.style.display="flex",S.style.flexDirection="column",S.style.justifyContent="center",Me(e);let o=e.screen.content.document,h=JSON.stringify([t,K]);if(h!==he){Ze(),he=h;let Z={sm:420,md:640,lg:900},fe="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";F.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${me.background};color:${me.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${Z[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${fe};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),v=On(F,{presentation:t,theme:o.theme,pages:o.pages},Rn),v.latch()}be(),F.setAttribute("aria-label",(Te?.screen===e.screen?.content.document.name?Te?.label:void 0)??ae?.document?.name??e.screen?.content.document.name??"Funnel")}async function jn(e){if(l||te)return;if(re.observe(),re.pending){le=e;return}if(ue&&(We()||["running","waiting"].includes(e.status))||(le=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(W.hidden=!0,Ee=null),R=e.locale.startsWith("zh"),N.textContent=R?"回看":"History",O.textContent=w.active?R?"返回当前":"Return to current":R?"返回":"Back",gn(),j.textContent=R?"重试":"Retry",j.hidden=n.client.pendingCommand===null,ye(),vn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(vn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ie(n.onState,structuredClone(e))),l||te))return;if((!e.pendingRequest||ue&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){B();return}if(e.stopped&&D()){B();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),V(),pe(),T?.finish("skipped"),r.hidden=!0,qe();return}if(r.hidden=!1,w.active){qe();return}if(e.status==="completed"&&I?.subscriptionUpgradeActive){qe();return}let t=Se(e),o=n.client.view;if(o&&o.revision>e.revision&&Se(o)!==t)return;let h=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==we&&(we&&T?.finish("dismissed"),pe(),we=t,ce={...e.answers},je.reset());let Z=Xe(e);if(Ge===Z){r.hidden=!0;return}if(h&&!t){r.hidden=!0;let C=n.prepared?.state==="shown"?null:Ye(!0,e.locale);!l&&!te&&Qe?.key!==Z&&(un(),Qe={key:Z,timeout:setTimeout(()=>{let d=n.client.view;if(l||!C?.active&&n.prepared?.state!=="shown"||!d||Xe(d)!==Z)return;Ge=Z;let q=new Error("Funnel screen preparation timed out");C?.finish("error",q),V(),pe(),Y(q)},He)}),qe();return}un();let _=C=>{let d=n.client.view;return!l&&!te&&!Re&&!C.aborted&&n.client.configurationReady!==!1&&!!d&&!d.stopped&&!["closed","ineligible","failed"].includes(d.status)&&(Se(d)===t||d.status==="completed"&&I?.subscriptionUpgradeActive===!0)},fe=(C,d)=>{_(d)&&(Ge=t,T?.finish("error",C),pe(),r.hidden=!0,Y(C))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&V(),Ke(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&T?.finish("skipped")),e.screen){Je=void 0,V();let C=e.screen.content;if(!ae){let J=e.screen.presentation.type!=="inline",b=Ye(J,e.locale);if(l||te)return;let x=(Ae=new AbortController).signal;Ke(e),_e=J?Nn(F):tn(r,i),ae=L(S,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...C.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){_(x)&&(ve=y,ye())},rendererUrl:n.client.webViewUrl,title:C.document.name,...J?{hostPresentation:()=>v?.type??e.screen.presentation.type}:{},onResize:y=>{Ce=y,v?.responsive&&v.setContentHeight(y+A.getBoundingClientRect().height)},onAction(y,c={},Fe={}){if(w.active||!_(x)||ee!==t)return;ce={...ce,...Fe};let cn=e.screen?.inputs??[],Fn=Object.fromEntries(cn.filter(({variable:Le})=>Object.hasOwn(ce,Le)).map(({variable:Le})=>[Le,ce[Le]]));if(xn(cn,Fn).length){Cn();return}Oe(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Fn,selection:c}}),!1,Le=>$n(Le,cn))},onAnswers:y=>{w.active||!_(x)||ee!==t||(ce={...ce,...y})},onCustomerDataIntent:y=>{w.active||!_(x)||ee!==t||je.intent(y).catch(Y)},onEscape:()=>{!_(x)||ee!==t||w.active||ie||$||ge()},onError:y=>{let c=new Error(y);ee===t?Y(c):fe(c,x)},onRendered:y=>{if(!(!_(x)||ee===t))try{b.present(c=>{_e?.(),_e=void 0,y&&(Te={screen:C.document.name,label:y},F.setAttribute("aria-label",y)),J&&(F.showModal(),s=!1,v?.responsive&&F.focus({preventScroll:!0}),!c&&n.loading!=="host"&&qn(F,v?.type??e.screen.presentation.type,v?.responsive)),ee=t,Pe=J,ye()}),_(x)&&Ve.report(t)}catch(c){fe(c,x)}}}),Rn()}let d={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:ce,values:e.screen.values}},q=JSON.stringify([C,e.locale,d.parameters,e.screen.inputs,e.screen.values]);if(q!==xe)ae.update(C.document,e.locale,d),xe=q,rn=JSON.stringify(d.capabilities),ze=JSON.stringify(d.customerData);else{let J=JSON.stringify(d.capabilities);J!==rn&&(ae.updateCapabilities(d.capabilities),rn=J),JSON.stringify(d.customerData)!==ze&&(ae.updateCustomerData(d.customerData),ze=JSON.stringify(d.customerData))}let G=ae;if(G)try{await(T?.wait(G.ready)??G.ready)}catch(J){Ae&&fe(J,Ae.signal)}}else if(e.paywall&&!I){let C=e.paywall.resolution,d="document"in C?C.document:null,q=p,G=n.mountPaywallControls,J=null,b=(Ae=new AbortController).signal,x={loading:"host",signal:b,...G&&{mountControls:c=>G(c,e)},canInteract:()=>_(b)&&!w.active&&!ie&&!$,beforeAction:async()=>{X++;try{await bn(Ve.settled()),W.hidden=!0,Ee=null,De=!1,be()}finally{X=Math.max(0,X-1)}},start:()=>wn(n.client),onObservationChange:qe,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,beforeCheckoutReplacement:n.beforeCheckoutReplacement,purchaseConfirmation:n.purchaseConfirmation,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:c=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:c,openIn:"same_window"}):u.defaultView?.location.assign(c),onAction:async c=>{if(w.active)return;let Fe=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:c,answers:{}}});await se(n.client.view??Fe.run)},onError:c=>{ee===t?Y(c):fe(c,b)}},y={quoteError:c=>Ie(n.onError,c),loadingLayout:()=>_(b)?J?.getLoadingLayout?.():void 0,present(c){_(b)&&(J?.present(Fe=>{c(Fe),ee=t,Pe=y.retainedDialog?.dialog.open??!!S.querySelector("dialog[open]"),Pe&&(s=!1),ye()}),_(b)&&Ve.report(t))},async closeAction(c){l||w.active||await re.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:c,answers:{}}})},async dismiss(){if(l||b.aborted||w.active||ie||$||!ue&&!_(b))return;ue=!0;let c=n.client.view;if(c?.status==="completed"&&I?.subscriptionUpgradeActive){Ue.add(`complete:${c.id}`),Ie(n.onComplete,structuredClone(c)),B();return}if((n.resumeCheckout||n.terminateCheckout)&&Kn()){le=n.client.view,B();return}await ge()}};if(q&&G)V();else if(q){let c=await q.adopt(e,{options:x,handoff:y,start:()=>wn(n.client)});c&&_(b)&&!l?(Ke(e),I=c,Ne={runId:e.id,receiptId:e.paywall.receiptId},T?.active&&T.present(()=>{}),ee=t,Pe=q.modal,Pe&&(s=!1),ye(),Ve.report(t),w.active&&I.setSuspended(!0)):(c?.destroy(),V())}if(l||te)return;if(!I){if(J=Ye(!0,e.locale,d),l||te)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Je?.ownerDocument===u&&(y.hostPaywallTarget=Je),Je=void 0,Ke(e);let c=await H(S,x,y).catch(Fe=>(fe(Fe,b),null));!_(b)&&!(ue&&!l&&!b.aborted)?c?.host?.destroy():c&&(I=c.host,I&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),I?.setSuspended(w.active))}}if(l||te)return;ye();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let C=u.createElement("button");C.type="button",C.style.cssText=z.primary,$e(C,()=>z.focus),S.style.cssText=z.stage,C.textContent=m.type==="open_url"?`${R?"前往":"Continue to"} ${new URL(m.url).host}`:R?"继续":"Continue",C.onclick=()=>{let d=ke(),q=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Xn(m.url):null;Oe(async()=>{let G="success";if(m.type==="open_url")if(n.onOpenUrl)try{G=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(b){Ie(n.onError,b),G="failed"}else G=m.openIn==="new_window"&&!q?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new ne("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(l||n.client.view?.nodeId!==d.nodeId||n.client.view.visit!==d.visit)throw new ne("PRECONDITION_FAILED","The client action visit changed");let J=await n.client.submit({operation:"submit",...d,input:{type:"client_action",receiptId:m.receiptId,outcome:G}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&u.defaultView?.location.assign(m.url),J})},T?.active?T.present(()=>S.replaceChildren(C)):S.replaceChildren(C)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),Ie(n.onComplete,structuredClone(e))),qe()}function Xn(e){let t=u.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function se(e){return ye(),sn=sn.catch(()=>{}).then(async()=>{try{await jn(e)}catch(t){throw T?.active&&(Ge=Xe(e),T.finish("error",t),pe(),r.hidden=!0),t}}),sn}let Yn=n.client.subscribe(e=>{if(!hn){if(e.stopped&&(Pe||D())&&!ue){le=e,B();return}!ue&&(e.stopped||n.client.configurationReady===!1||we&&ee!==we&&(Se(e)!==we||["closed","ineligible","failed"].includes(e.status)))&&(pe(),T?.finish("dismissed"),r.hidden=!0),se(e).catch(Y)}}),Zn=n.client.subscribeError?.(e=>{re.pending||Y(e)});function Kn(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&Dn(pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function ge(e){if(Re)return Re;if(l||!e&&(ie||$))return Promise.resolve();let t=!e&&We();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(le=n.client.view,B(),Promise.resolve()):(Re=Oe(async()=>{let o=t?await n.client.retry():await(e?n.client.submit.bind(n.client):re.submit)({operation:"close",...e??ke()});return e&&In(o),o},!0).then(()=>{let o=n.client.view;o?.status==="closed"&&!We()&&(le=o,B())}).finally(()=>{Re=null}),Re)}function B(){En()}function En(e){oe?.destroy(),!l&&(l=!0,re.destroy(),k(),V(),n.signal?.removeEventListener("abort",B),a?.removeEventListener("abort",B),T?.finish("dismissed"),an.destroy(),Yn(),Zn?.(),pe(e),Ze(),w.stop(),F.remove(),!e||!r.contains(e)?r.remove():(A.remove(),de.remove()),!e&&!s&&P(),Ie(n.onDismiss,le?structuredClone(le):null))}O.onclick=()=>{if(!O.disabled){if(w.active){w.exit();return}Oe(()=>n.client.submit({operation:"back",...ke()}))}},N.onclick=()=>{w.open()},g.onclick=()=>{T?.active?T.dismiss():ie||ge()},j.onclick=()=>{re.pending?re.retry().catch(()=>{}):We()?ge():Oe(()=>n.client.retry())},F.addEventListener("cancel",e=>{e.preventDefault(),T?.active?T.dismiss():ie||ge()}),n.signal?.addEventListener("abort",B,{once:!0}),a?.addEventListener("abort",B,{once:!0});let en=!1;p&&(k=p.onClose(()=>{l||te||(te=!0,T?.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):en=!0)}));let kn={destroy:B,refresh:dn,get recoveryPaywall(){if(I&&Ne)return{...Ne,view:I.currentResolution}},setPurchaseRecovery(e,t){return I?.setPurchaseRecovery(e,t),I!==null},retainPurchaseDialog(){let e=I?.retainPurchaseDialog();if(e)return I=null,En(e.dialog),{dialog:e.dialog,release(){e.release(),r.remove(),s||P()}}},get recovery(){let e=ln();if(e)return e;if(!l&&!X&&!ue&&!ie&&I){let t=I.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??$?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(ie)return ie;let e=ln();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??$?.operationId??null,o=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=I?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:o())}let h=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(l&&!(h||$&&n.client.view?.status==="closed")||X||Be||Re||w.active||!I&&!$&&!h)return Promise.resolve(o());let Z=I,_=(async()=>{try{if(!$&&h){let d=await n.client.retry();return await se(n.client.view??d.run),o()}if(!$){let d=await Z.prepareFallback();if(d.type!=="native")return d;if(n.client.hasDurableJournal!==!0)return o();$=d}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let d=m.find(G=>G.operation==="close");if(!d||!M||d.requestId!==M.requestId)return o();let q=await n.client.retry();In(q),await se(n.client.view??q.run)}else{let d=n.client.view,q=d?.paywall;if(!d||!q||q.selectionGeneration===void 0||(q.quote?.operationId??null)!==$.operationId||$.operationId!==null&&q.canReselect!==!0)return o();let G=q.selectionGeneration,J=await n.client.get();await se(n.client.view??J.run);let b=n.client.view,x=b?.paywall;if(!b||!x||!["running","waiting"].includes(b.status)||b.stopped||b.id!==d.id||b.nodeId!==d.nodeId||b.visit!==d.visit||x.receiptId!==q.receiptId||x.selectionGeneration!==G||(x.quote?.operationId??null)!==$.operationId||$.operationId!==null&&x.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return o();let y=ke();M={runId:b.id,operationId:$.operationId,revision:y.revision,requestId:y.requestId,nodeId:b.nodeId,visit:b.visit,receiptId:x.receiptId,selectionGeneration:G,acknowledged:!1},await ge(y)}let C=ln();return C?(B(),C):o()}catch(m){return Y(m),o()}})();ie=_;let fe=()=>{ie===_&&(ie=null)};return _.then(fe,fe),_},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??yn)>=yn||e.instruction?.type==="evaluate_segment")&&(on=dn().finally(()=>{on=null})),await se(e);else{if(r.hidden=!0,l)throw new DOMException("Presentation cancelled","AbortError");let t=en||n.prepared?.state==="shown"?null:Ye(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(l||te&&!en)throw new DOMException("Presentation cancelled","AbortError");let o=n.client.get(),h=await(t?t.wait(o,He):nt(o,He));if(hn=!1,en)return l||await ge().finally(B),kn;await se(n.client.view??h.run)}}catch(e){throw T?.finish("error",e),B(),e}return kn}function nt(i,E){let U;return Promise.race([i,new Promise((n,p)=>{U=setTimeout(()=>p(new Error("Presentation data timed out")),E)})]).finally(()=>clearTimeout(U))}function St(i,E,U){return et(i,E,U)}export{et as a,St as b};
|
|
1
|
+
import{b as Bn}from"./chunk-QY5TS3OY.js";import{a as wn}from"./chunk-PYTI77BV.js";import{a as _n,b as Un,c as fn,d as mn,e as $e,f as Vn,h as $n,i as Mn,j as xn,k as zn}from"./chunk-6UQ7BKSR.js";import{a as Jn}from"./chunk-XQAGF6SQ.js";import{a as Sn}from"./chunk-W32FI2A2.js";import{c as On,e as qn,f as Ln,i as Hn,j as He,k as nn,l as Nn,m as tn}from"./chunk-EP2L4VTS.js";import{b as An}from"./chunk-XH2JMWC6.js";import{a as pn,d as Dn}from"./chunk-NPKNI2UD.js";import{C as Tn}from"./chunk-NTYIQ5YC.js";import{a as ne}from"./chunk-Y2DUFDPV.js";import{a as Ie}from"./chunk-DSPLGTQI.js";function Gn(i){let E=new Set,U=new Set,n=null;async function p(a,f){let L=!1;for(;!i.stopped&&i.key===a&&i.client.pendingCommand?.requestId===f;){if(!i.client.settle)throw new ne("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),L=!0,i.client.pendingCommand?.requestId===f&&await new Promise(H=>setTimeout(H,1500))}i.stopped||i.key!==a||(L&&await i.client.get(),!(i.stopped||i.key!==a)&&E.add(a))}function k(a,f){n=f;let L=()=>{n===f&&(n=null),U.delete(a)};return f.then(L,H=>{L(),i.busy||i.fail(H)}),f}function V(a){if(i.reviewing||E.has(a)||U.has(a)||i.stopped)return;U.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||E.has(a)){U.delete(a);return}if(i.busy||i.client.pendingCommand){setTimeout(()=>{f()},250);return}let L=(async()=>{if(i.staleRead){if(await i.staleRead,i.stopped||i.key!==a)return;if(i.client.pendingCommand){setTimeout(()=>{f()},250);return}}let H=i.client.view,oe=i.expected(),u=oe.requestId;try{await i.client.submit({operation:"shown",...oe})}catch(P){if(!(P instanceof ne)||P.code!=="CONFLICT"||P.status!==409||i.client.pendingCommand)throw P;await i.client.get();let s=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!s||!H||s.id!==H.id||s.source.versionId!==H.source.versionId||s.nodeId!==oe.nodeId||s.visit!==oe.visit||s.revision<=oe.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==H.paywall?.receiptId)||!["running","waiting"].includes(s.status)||i.client.pendingCommand)throw P;let r=i.expected();u=r.requestId,await i.client.submit({operation:"shown",...r})}await p(a,u)})();k(a,L)};f()}function D(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return U.add(f),k(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:V,settled:D,get inFlight(){return n}}}function Qn(i){let E={},U=new Map;async function n(p){let k=i.client.view,V=k?.screen,D=V?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!k||!V||!D)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let P=i.document,s=P?Tn(P,p.nodeId):null,r=s?.type==="customer_data"?s.data.outputs?.[p.action]:void 0;r&&V.outputs.includes(r)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:r,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,k);return}let f=p.action.startsWith("sources_")?D.resources.find(P=>P.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new ne("INVALID_REQUEST","Choose a current resource");let L=`${k.visit}:${p.nodeId}:${f?.key??""}`,H=U.get(L)??[null],u=E[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let P=p.value;if(!P||!(D.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(P))throw new ne("INVALID_REQUEST","Unknown data filter");u={page:1,after:null,filter:P},H.splice(0,H.length,null)}else if(p.action==="next"||p.action==="sources_next"){let P=f?.sources.at(-1),s=f?P?{kind:"ledger",cursor:{at:P.detail[0],id:P.id,type:"source"}}:null:V.dataCursors[p.nodeId];if(!s||!f&&!D.hasNext)return;H[u.page]=s,u={...u,page:u.page+1,after:s}}else if(p.action==="previous"||p.action==="sources_previous"){if(u.page<=1)return;u={...u,page:u.page-1,after:H[u.page-2]??null}}U.set(L,H),E={...E,[p.nodeId]:u},await i.perform(()=>i.client.get({nodeId:k.nodeId,visit:k.visit,revision:k.revision,components:E}))}return{get queries(){return E},intent:n,reset(){E={},U.clear()}}}function Wn(i){let{doc:E,holder:U,reviewHolder:n,mountScreenPreview:p}=i,k=!1,V,D=0,a=null,f="",L,H=new Map,oe=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function u(s){if(i.stopped||!i.client.review||k&&s===V&&L?.active)return;let r=!k||s!==V;k||(f=oe(i.client.view),H.set(f,structuredClone(i.answers))),k=!0,V=s,U.hidden=!0,i.suspend(!0),n.hidden=!1;let S=++D;r&&(L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),L=nn(n,i.loadingOptions,"funnel",()=>{P()}));let A=r?L:void 0;try{if(A?.start(!1,i.client.view?.locale),S!==D||i.stopped)return;let de=i.client.review(s),N=await(A?.wait(de,He)??de);if(i.stopped||S!==D||!k)return;if(!N.review)throw new ne("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,A||n.replaceChildren();let Q=E.createElement("div"),W=A?tn(Q,n):()=>{};n.append(Q);let O=N.run.locale.startsWith("zh"),g=i.chrome;Q.style.cssText=g.history;let j=E.createElement("p");j.textContent=O?"只读回看":"Read-only history",j.style.cssText=g.historyTitle,Q.append(j);let F=E.createElement("p");F.style.cssText=g.historyNote,F.textContent=N.review.pages.length?O?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":O?"还没有可回看的页面。":"There are no earlier pages yet.",Q.append(F);let Te=N.review.page?.receiptId,ve=E.createElement("div");ve.style.cssText=g.historyPages;for(let[K,R]of N.review.pages.entries()){let v=E.createElement("button");v.type="button",v.textContent=O?`第 ${K+1} 页`:`Page ${K+1}`;let he=Te!==void 0&&R.receiptId===Te;v.style.cssText=he?g.primary:g.secondary,he&&v.setAttribute("aria-current","page"),$e(v,()=>i.chrome.focus),v.onclick=()=>{u(R.receiptId)},ve.append(v)}if(ve.childElementCount&&Q.append(ve),N.review.page){let K=N.review.page,R=E.createElement("div");R.inert=!0,R.style.cssText=g.historyPage,Q.append(R),a=p(R,{mode:"live",rendererUrl:i.client.webViewUrl,title:K.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{S===D&&!i.stopped&&A?.present(W)},onError:he=>{if(S!==D||i.stopped)return;let Ce=new Error(he);A?.finish("error",Ce),a?.destroy(),a=null,Q.remove(),i.fail(Ce)},onEscape:()=>{P()}});let v=a;if(v.update(K.document,N.run.locale,{serverInput:{bindings:K.inputs,answers:K.answers,values:K.values}}),await v.ready,i.stopped||S!==D||!k)return}let me=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},z=E.createElement("div");z.style.cssText=g.historyRecords;for(let K of[...N.review.coupons.map((R,v)=>`${O?"优惠券":"Coupon"} ${v+1}: ${me[R.status]}`),...N.review.purchases.map((R,v)=>`${O?"购买":"Purchase"} ${v+1}: ${zn(R.status,O)}`)]){let R=E.createElement("p");R.textContent=K,R.style.margin="0",z.append(R)}z.childElementCount&&Q.append(z),N.review.page||A?.present(W),i.client.view&&await i.enqueue(i.client.view)}catch(de){if(S!==D||i.stopped)return;A?.finish("error",de),a?.destroy(),a=null,n.replaceChildren(),i.fail(de)}}async function P(){if(!k||i.stopped||!i.client.review)return;let s=++D;L?.finish("dismissed");try{if(await i.client.review(),i.stopped||s!==D)return;k=!1,D++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,U.hidden=!1;let r=i.client.view;oe(r)!==f?(H.set(f,structuredClone(i.answers)),i.resetScreen()):(H.delete(f),i.suspend(!1)),r&&await i.enqueue(r)}catch(r){if(s!==D||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(r)}}return{get active(){return k},get receipt(){return V},open:u,exit:P,get drafts(){return new Map([...H].map(([s,r])=>[s,structuredClone(r)]))},stop(){k=!1,D++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,U.hidden=!1}}}var yn=5e3;async function et(i,E,U){let n=E,p=n.prepared&&Bn(n.prepared),k=()=>{};function V(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let D=()=>n.prepared?.state==="shown"&&!!p?.modal,a=n.client.identitySignal,f;try{f=await Promise.all([import("./screen-renderer-WZFPWLB5.js"),import("./paywall-PWWDHKVH.js")]),n.signal?.throwIfAborted(),a?.throwIfAborted()}catch(e){throw V(),e}let[{mountScreenPreview:L},{showPaywall:H}]=f,oe=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Jn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;oe?.start();let u=i.ownerDocument,P=Hn(u),s=!1,r=u.createElement("section"),S=u.createElement("div"),A=u.createElement("div"),de=u.createElement("div"),N=u.createElement("button");de.hidden=!0,N.type="button";let Q=u.createElement("p"),W=u.createElement("p"),O=u.createElement("button"),g=u.createElement("button"),j=u.createElement("button"),F=u.createElement("dialog"),Te,ve=!1;r.dataset.indianaFunnel="",r.dataset.longplayCloseOwner="sdk",r.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),W.setAttribute("role","alert"),W.hidden=!0,O.type=g.type=j.type="button",A.append(O,N,Q,W,j,g),r.append(S,de,A),i.append(r);let me=Un,z=fn(me),K="",R=(u.documentElement.lang||"").startsWith("zh"),v,he="",Ce;for(let e of[O,N,j,g])$e(e,()=>z.focus);function gn(){let e=R?"关闭":"Close";g.parentElement===F?(g.textContent="×",g.setAttribute("aria-label",e),Ln(g,me)):(g.textContent=e,g.removeAttribute("aria-label"),g.style.cssText=z.link+";margin-inline-start:auto")}function Me(e){let t=e?.screen?.content.document.theme??me,o=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,g.parentElement===F]);if(o===K)return;K=o,me=t;let h=g.parentElement===F;z=fn(me,h),r.style.cssText=z.root+";min-width:0"+(h?";display:flex;flex-direction:column;min-height:100%":""),A.style.cssText=z.bar+(h?";margin-top:auto":""),A.hidden&&(A.style.display="none"),O.style.cssText=N.style.cssText=z.secondary,j.style.cssText=z.primary,Q.style.cssText=z.status,W.style.cssText=z.alert,gn(),mn(O)}function be(){A.hidden=O.hidden&&N.hidden&&j.hidden&&W.hidden&&!Q.textContent&&(g.hidden||g.parentElement!==A),A.style.display=A.hidden?"none":"flex",v?.responsive&&Ce!==void 0&&v.setContentHeight(Ce+A.getBoundingClientRect().height)}Me();let ae=null,I=null,le=null,we="",ee="",Pe=!1,xe="",rn="",ze="",l=!1,X=0,Be=!1,vn="",on=null,sn=Promise.resolve(),hn=!n.client.view,Ne,T=U,Je=n.hostPaywallTarget,Ae,_e,Ge="",Qe,te=!1,Re=null,ue=!1,We=()=>n.client.pendingCommand?.operation==="close",ie=null,$=null,an=Sn({document:u,run:async()=>{(!I?.observing||n.client.pendingCommand)&&await dn()},delay:()=>{if(!re.pending&&!(l||!le||!["running","waiting"].includes(le.status)&&!n.client.pendingCommand)&&!(I?.observing&&!n.client.pendingCommand))return le.pendingRequest||n.client.pendingCommand?1500:yn},hiddenDelay:()=>!l&&!re.pending&&n.client.pendingCommand?15e3:void 0}),M=null;function ln(){return $&&n.client.hasDurableJournal===!0&&M?.acknowledged===!0&&M.operationId===$.operationId&&n.client.view?.id===M.runId&&n.client.view?.status==="closed"&&n.client.view.revision===M.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?$:null}function In(e){let t=e.run.paywall;if(M&&e.settlement?.requestId===M.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===M.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===M.revision+1&&e.run.nodeId===M.nodeId&&e.run.visit===M.visit&&t?.receiptId===M.receiptId&&t.selectionGeneration===M.selectionGeneration&&(t.quote?.operationId??null)===M.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===M.operationId){let o=M.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,h=pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(o||t.canReselect===!0&&h.type==="native")&&(M.acknowledged=!0)}}let Ee=null,Ue=new Set,ce={},De=!1,Y=(e,t=null)=>{l||(e instanceof ne&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&an.destroy(),Ee=t,De=!1,W.textContent=Vn(e,R),W.hidden=!1,j.hidden=n.client.pendingCommand===null,be(),Ie(n.onError,e))},re=An({client:n.client,document:u,conceal(){l||(pe(),T?.finish("dismissed"),r.hidden=!0,s||(s=!0,P()))},async receive(e){l||await se(n.client.view??e.run)},failed(e){if(!l){if(!re.pending){ue=!1;let t=n.client.view;t&&se(t).then(()=>Y(e),Y);return}Ze(),r.parentElement!==i&&i.append(r),r.hidden=!1,O.hidden=N.hidden=g.hidden=!0,Q.textContent="",Me(),Y(e,n.client.pendingCommand?.requestId??null)}}}),Cn=()=>{l||(Ee=null,W.textContent=Mn(R),W.hidden=!1,j.hidden=!0,be())};function ke(){let e=n.client.view;if(!e)throw new ne("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=Wn({client:n.client,doc:u,holder:S,reviewHolder:de,mountScreenPreview:L,loadingOptions:n,get chrome(){return z},get stopped(){return l},get answers(){return ce},suspend(e){I?.setSuspended(e)},resetScreen(){we="",ee="",xe=""},enqueue:se,fail:Y}),Ve=Gn({client:n.client,expected:ke,fail:Y,get stopped(){return l},get reviewing(){return w.active},get key(){return we},get busy(){return X},get staleRead(){return on}}),je=Qn({client:n.client,expected:ke,perform:Oe,onIntent:n.onCustomerDataIntent,get stopped(){return l},get busy(){return X},get document(){return ae?.document},get answers(){return ce}}),Xe=e=>`${e.id}:${e.nodeId}:${e.visit}`,Se=e=>e&&(e.screen||e.paywall)?Xe(e):"";function ye(){let e=n.client.view;O.disabled=!w.active&&(X>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Se(e)||ee!==Se(e)),O.hidden=!w.active&&!e?.canBack,mn(O);let t=!!I&&!w.active;g.hidden=t&&!T?.active||ve&&!w.active,N.hidden=!n.client.review||!w.active&&!e?.canBack;let o=e?.locale.startsWith("zh");Q.textContent=t?"":X>0||e?.pendingRequest?o?"正在处理":"Processing":e?.instruction?.type==="wait"?o?"等待中":"Waiting":"",be()}async function bn(e){if(!e)return;let t=n.client.view;await e;let o=n.client.view;if(!t||!o||o.id!==t.id||o.nodeId!==t.nodeId||o.visit!==t.visit||o.stopped||!["running","waiting"].includes(o.status))throw new ne("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Oe(e,t=!1,o){if(!((X||ue||ie||$)&&!t||l||w.active&&!t)){X++,r.setAttribute("aria-busy","true"),W.hidden=!0,Ee=null,De=!1,ye();try{if(t||await bn(Ve.inFlight),l)return;let h=await e();l||await se(n.client.view??h.run)}catch(h){o?.(h)&&n.client.pendingCommand===null?Cn():re.pending||Y(h,n.client.pendingCommand?.requestId??null)}finally{X=Math.max(0,X-1),r.setAttribute("aria-busy",String(X>0)),l||(j.hidden=n.client.pendingCommand===null,ye())}}}function qe(){an.schedule()}async function dn(){if(!(l||Be||X)&&!re.pending){if(w.active){await w.open(w.receipt);return}Be=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,o=je.queries,h=await n.client.get(t?.screen&&Object.keys(o).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:o}:void 0);De&&!l&&(De=!1,W.hidden=!0,be()),!l&&o===je.queries&&await se(n.client.view??h.run)}catch(e){Y(e),De=!l}finally{Be=!1}}}function Ye(e,t,o){if(T?.active){let Z=T;return Z.setDismissHandler(()=>Pn(Z)),Z}let h=nn(i,n,"funnel",()=>Pn(h),_n);return T=h,h.start(e,t,o),h}function Pn(e){l||te||(te=!0,e.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):B())}function un(){clearTimeout(Qe?.timeout),Qe=void 0}function pe(e){ve=!1,un(),Ae?.abort(),Ae=void 0,ae?.destroy(),ae=null,I?.destroy(),I=null,Ne=void 0,_e?.(),_e=void 0,F.open&&F.close();for(let t of Array.from(S.children))(!e||!t.contains(e))&&t.remove();S.style.cssText="",Ce=void 0,we="",ee="",Pe=!1,xe="",ze=""}function Rn(){let e=u.defaultView;v?.responsive&&e&&ae?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ze(){v?.destroy(),v=void 0,he=""}function Ke(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){F.open&&F.close(),Ze(),g.parentElement!==A&&A.append(g),r.parentElement!==i&&i.append(r);for(let Z of["flex","display","flex-direction","justify-content"])S.style.removeProperty(Z);Me(e),be();return}r.parentElement!==F&&(F.append(g,r),i.append(F)),S.style.flex="1 0 auto",S.style.display="flex",S.style.flexDirection="column",S.style.justifyContent="center",Me(e);let o=e.screen.content.document,h=JSON.stringify([t,K]);if(h!==he){Ze(),he=h;let Z={sm:420,md:640,lg:900},fe="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";F.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${me.background};color:${me.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${Z[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${fe};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),v=On(F,{presentation:t,theme:o.theme,pages:o.pages},Rn),v.latch()}be(),F.setAttribute("aria-label",(Te?.screen===e.screen?.content.document.name?Te?.label:void 0)??ae?.document?.name??e.screen?.content.document.name??"Funnel")}async function jn(e){if(l||te)return;if(re.observe(),re.pending){le=e;return}if(ue&&(We()||["running","waiting"].includes(e.status))||(le=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(W.hidden=!0,Ee=null),R=e.locale.startsWith("zh"),N.textContent=R?"回看":"History",O.textContent=w.active?R?"返回当前":"Return to current":R?"返回":"Back",gn(),j.textContent=R?"重试":"Retry",j.hidden=n.client.pendingCommand===null,ye(),vn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(vn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ie(n.onState,structuredClone(e))),l||te))return;if((!e.pendingRequest||ue&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){B();return}if(e.stopped&&D()){B();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),V(),pe(),T?.finish("skipped"),r.hidden=!0,qe();return}if(r.hidden=!1,w.active){qe();return}if(e.status==="completed"&&I?.subscriptionUpgradeActive){qe();return}let t=Se(e),o=n.client.view;if(o&&o.revision>e.revision&&Se(o)!==t)return;let h=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==we&&(we&&T?.finish("dismissed"),pe(),we=t,ce={...e.answers},je.reset());let Z=Xe(e);if(Ge===Z){r.hidden=!0;return}if(h&&!t){r.hidden=!0;let C=n.prepared?.state==="shown"?null:Ye(!0,e.locale);!l&&!te&&Qe?.key!==Z&&(un(),Qe={key:Z,timeout:setTimeout(()=>{let d=n.client.view;if(l||!C?.active&&n.prepared?.state!=="shown"||!d||Xe(d)!==Z)return;Ge=Z;let q=new Error("Funnel screen preparation timed out");C?.finish("error",q),V(),pe(),Y(q)},He)}),qe();return}un();let _=C=>{let d=n.client.view;return!l&&!te&&!Re&&!C.aborted&&n.client.configurationReady!==!1&&!!d&&!d.stopped&&!["closed","ineligible","failed"].includes(d.status)&&(Se(d)===t||d.status==="completed"&&I?.subscriptionUpgradeActive===!0)},fe=(C,d)=>{_(d)&&(Ge=t,T?.finish("error",C),pe(),r.hidden=!0,Y(C))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&V(),Ke(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&T?.finish("skipped")),e.screen){Je=void 0,V();let C=e.screen.content;if(!ae){let J=e.screen.presentation.type!=="inline",b=Ye(J,e.locale);if(l||te)return;let x=(Ae=new AbortController).signal;Ke(e),_e=J?Nn(F):tn(r,i),ae=L(S,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...C.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){_(x)&&(ve=y,ye())},rendererUrl:n.client.webViewUrl,title:C.document.name,...J?{hostPresentation:()=>v?.type??e.screen.presentation.type}:{},onResize:y=>{Ce=y,v?.responsive&&v.setContentHeight(y+A.getBoundingClientRect().height)},onAction(y,c={},Fe={}){if(w.active||!_(x)||ee!==t)return;ce={...ce,...Fe};let cn=e.screen?.inputs??[],Fn=Object.fromEntries(cn.filter(({variable:Le})=>Object.hasOwn(ce,Le)).map(({variable:Le})=>[Le,ce[Le]]));if(xn(cn,Fn).length){Cn();return}Oe(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Fn,selection:c}}),!1,Le=>$n(Le,cn))},onAnswers:y=>{w.active||!_(x)||ee!==t||(ce={...ce,...y})},onCustomerDataIntent:y=>{w.active||!_(x)||ee!==t||je.intent(y).catch(Y)},onEscape:()=>{!_(x)||ee!==t||w.active||ie||$||ge()},onError:y=>{let c=new Error(y);ee===t?Y(c):fe(c,x)},onRendered:y=>{if(!(!_(x)||ee===t))try{b.present(c=>{_e?.(),_e=void 0,y&&(Te={screen:C.document.name,label:y},F.setAttribute("aria-label",y)),J&&(F.showModal(),s=!1,v?.responsive&&F.focus({preventScroll:!0}),!c&&n.loading!=="host"&&qn(F,v?.type??e.screen.presentation.type,v?.responsive)),ee=t,Pe=J,ye()}),_(x)&&Ve.report(t)}catch(c){fe(c,x)}}}),Rn()}let d={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:ce,values:e.screen.values}},q=JSON.stringify([C,e.locale,d.parameters,e.screen.inputs,e.screen.values]);if(q!==xe)ae.update(C.document,e.locale,d),xe=q,rn=JSON.stringify(d.capabilities),ze=JSON.stringify(d.customerData);else{let J=JSON.stringify(d.capabilities);J!==rn&&(ae.updateCapabilities(d.capabilities),rn=J),JSON.stringify(d.customerData)!==ze&&(ae.updateCustomerData(d.customerData),ze=JSON.stringify(d.customerData))}let G=ae;if(G)try{await(T?.wait(G.ready)??G.ready)}catch(J){Ae&&fe(J,Ae.signal)}}else if(e.paywall&&!I){let C=e.paywall.resolution,d="document"in C?C.document:null,q=p,G=n.mountPaywallControls,J=null,b=(Ae=new AbortController).signal,x={loading:"host",signal:b,...G&&{mountControls:c=>G(c,e)},canInteract:()=>_(b)&&!w.active&&!ie&&!$,beforeAction:async()=>{X++;try{await bn(Ve.settled()),W.hidden=!0,Ee=null,De=!1,be()}finally{X=Math.max(0,X-1)}},start:()=>wn(n.client),onObservationChange:qe,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,beforeCheckoutReplacement:n.beforeCheckoutReplacement,purchaseConfirmation:n.purchaseConfirmation,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:c=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:c,openIn:"same_window"}):u.defaultView?.location.assign(c),onAction:async c=>{if(w.active)return;let Fe=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:c,answers:{}}});await se(n.client.view??Fe.run)},onError:c=>{ee===t?Y(c):fe(c,b)}},y={quoteError:c=>Ie(n.onError,c),loadingLayout:()=>_(b)?J?.getLoadingLayout?.():void 0,present(c){_(b)&&(J?.present(Fe=>{c(Fe),ee=t,Pe=y.retainedDialog?.dialog.open??!!S.querySelector("dialog[open]"),Pe&&(s=!1),ye()}),_(b)&&Ve.report(t))},async closeAction(c){l||w.active||await re.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:c,answers:{}}})},async dismiss(){if(l||b.aborted||w.active||ie||$||!ue&&!_(b))return;ue=!0;let c=n.client.view;if(c?.status==="completed"&&I?.subscriptionUpgradeActive){Ue.add(`complete:${c.id}`),Ie(n.onComplete,structuredClone(c)),B();return}if((n.resumeCheckout||n.terminateCheckout)&&Kn()){le=n.client.view,B();return}await ge()}};if(q&&G)V();else if(q){let c=await q.adopt(e,{options:x,handoff:y,start:()=>wn(n.client)});c&&_(b)&&!l?(Ke(e),I=c,Ne={runId:e.id,receiptId:e.paywall.receiptId},T?.active&&T.present(()=>{}),ee=t,Pe=q.modal,Pe&&(s=!1),ye(),Ve.report(t),w.active&&I.setSuspended(!0)):(c?.destroy(),V())}if(l||te)return;if(!I){if(J=Ye(!0,e.locale,d),l||te)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Je?.ownerDocument===u&&(y.hostPaywallTarget=Je),Je=void 0,Ke(e);let c=await H(S,x,y).catch(Fe=>(fe(Fe,b),null));!_(b)&&!(ue&&!l&&!b.aborted)?c?.host?.destroy():c&&(I=c.host,I&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),I?.setSuspended(w.active))}}if(l||te)return;ye();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let C=u.createElement("button");C.type="button",C.style.cssText=z.primary,$e(C,()=>z.focus),S.style.cssText=z.stage,C.textContent=m.type==="open_url"?`${R?"前往":"Continue to"} ${new URL(m.url).host}`:R?"继续":"Continue",C.onclick=()=>{let d=ke(),q=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Xn(m.url):null;Oe(async()=>{let G="success";if(m.type==="open_url")if(n.onOpenUrl)try{G=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(b){Ie(n.onError,b),G="failed"}else G=m.openIn==="new_window"&&!q?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new ne("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(l||n.client.view?.nodeId!==d.nodeId||n.client.view.visit!==d.visit)throw new ne("PRECONDITION_FAILED","The client action visit changed");let J=await n.client.submit({operation:"submit",...d,input:{type:"client_action",receiptId:m.receiptId,outcome:G}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&u.defaultView?.location.assign(m.url),J})},T?.active?T.present(()=>S.replaceChildren(C)):S.replaceChildren(C)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),Ie(n.onComplete,structuredClone(e))),qe()}function Xn(e){let t=u.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function se(e){return ye(),sn=sn.catch(()=>{}).then(async()=>{try{await jn(e)}catch(t){throw T?.active&&(Ge=Xe(e),T.finish("error",t),pe(),r.hidden=!0),t}}),sn}let Yn=n.client.subscribe(e=>{if(!hn){if(e.stopped&&(Pe||D())&&!ue){le=e,B();return}!ue&&(e.stopped||n.client.configurationReady===!1||we&&ee!==we&&(Se(e)!==we||["closed","ineligible","failed"].includes(e.status)))&&(pe(),T?.finish("dismissed"),r.hidden=!0),se(e).catch(Y)}}),Zn=n.client.subscribeError?.(e=>{re.pending||Y(e)});function Kn(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&Dn(pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function ge(e){if(Re)return Re;if(l||!e&&(ie||$))return Promise.resolve();let t=!e&&We();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(le=n.client.view,B(),Promise.resolve()):(Re=Oe(async()=>{let o=t?await n.client.retry():await(e?n.client.submit.bind(n.client):re.submit)({operation:"close",...e??ke()});return e&&In(o),o},!0).then(()=>{let o=n.client.view;o?.status==="closed"&&!We()&&(le=o,B())}).finally(()=>{Re=null}),Re)}function B(){En()}function En(e){oe?.destroy(),!l&&(l=!0,re.destroy(),k(),V(),n.signal?.removeEventListener("abort",B),a?.removeEventListener("abort",B),T?.finish("dismissed"),an.destroy(),Yn(),Zn?.(),pe(e),Ze(),w.stop(),F.remove(),!e||!r.contains(e)?r.remove():(A.remove(),de.remove()),!e&&!s&&P(),Ie(n.onDismiss,le?structuredClone(le):null))}O.onclick=()=>{if(!O.disabled){if(w.active){w.exit();return}Oe(()=>n.client.submit({operation:"back",...ke()}))}},N.onclick=()=>{w.open()},g.onclick=()=>{T?.active?T.dismiss():ie||ge()},j.onclick=()=>{re.pending?re.retry().catch(()=>{}):We()?ge():Oe(()=>n.client.retry())},F.addEventListener("cancel",e=>{e.preventDefault(),T?.active?T.dismiss():ie||ge()}),n.signal?.addEventListener("abort",B,{once:!0}),a?.addEventListener("abort",B,{once:!0});let en=!1;p&&(k=p.onClose(()=>{l||te||(te=!0,T?.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):en=!0)}));let kn={destroy:B,refresh:dn,get recoveryPaywall(){if(I&&Ne)return{...Ne,view:I.currentResolution}},setPurchaseRecovery(e,t){return I?.setPurchaseRecovery(e,t),I!==null},retainPurchaseDialog(){let e=I?.retainPurchaseDialog();if(e)return I=null,En(e.dialog),{dialog:e.dialog,release(){e.release(),r.remove(),s||P()}}},get recovery(){let e=ln();if(e)return e;if(!l&&!X&&!ue&&!ie&&I){let t=I.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??$?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(ie)return ie;let e=ln();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??$?.operationId??null,o=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=I?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:o())}let h=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(l&&!(h||$&&n.client.view?.status==="closed")||X||Be||Re||w.active||!I&&!$&&!h)return Promise.resolve(o());let Z=I,_=(async()=>{try{if(!$&&h){let d=await n.client.retry();return await se(n.client.view??d.run),o()}if(!$){let d=await Z.prepareFallback();if(d.type!=="native")return d;if(n.client.hasDurableJournal!==!0)return o();$=d}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let d=m.find(G=>G.operation==="close");if(!d||!M||d.requestId!==M.requestId)return o();let q=await n.client.retry();In(q),await se(n.client.view??q.run)}else{let d=n.client.view,q=d?.paywall;if(!d||!q||q.selectionGeneration===void 0||(q.quote?.operationId??null)!==$.operationId||$.operationId!==null&&q.canReselect!==!0)return o();let G=q.selectionGeneration,J=await n.client.get();await se(n.client.view??J.run);let b=n.client.view,x=b?.paywall;if(!b||!x||!["running","waiting"].includes(b.status)||b.stopped||b.id!==d.id||b.nodeId!==d.nodeId||b.visit!==d.visit||x.receiptId!==q.receiptId||x.selectionGeneration!==G||(x.quote?.operationId??null)!==$.operationId||$.operationId!==null&&x.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return o();let y=ke();M={runId:b.id,operationId:$.operationId,revision:y.revision,requestId:y.requestId,nodeId:b.nodeId,visit:b.visit,receiptId:x.receiptId,selectionGeneration:G,acknowledged:!1},await ge(y)}let C=ln();return C?(B(),C):o()}catch(m){return Y(m),o()}})();ie=_;let fe=()=>{ie===_&&(ie=null)};return _.then(fe,fe),_},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??yn)>=yn||e.instruction?.type==="evaluate_segment")&&(on=dn().finally(()=>{on=null})),await se(e);else{if(r.hidden=!0,l)throw new DOMException("Presentation cancelled","AbortError");let t=en||n.prepared?.state==="shown"?null:Ye(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(l||te&&!en)throw new DOMException("Presentation cancelled","AbortError");let o=n.client.get(),h=await(t?t.wait(o,He):nt(o,He));if(hn=!1,en)return l||await ge().finally(B),kn;await se(n.client.view??h.run)}}catch(e){throw T?.finish("error",e),B(),e}return kn}function nt(i,E){let U;return Promise.race([i,new Promise((n,p)=>{U=setTimeout(()=>p(new Error("Presentation data timed out")),E)})]).finally(()=>clearTimeout(U))}function St(i,E,U){return et(i,E,U)}export{et as a,St as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as w,f as b}from"./chunk-
|
|
1
|
+
import{e as w,f as b}from"./chunk-EHYW66EH.js";import{n as h,s as u}from"./chunk-KXA4JHFW.js";import{a as y}from"./chunk-UB5SVEM6.js";import{a as n}from"./chunk-Y2DUFDPV.js";import{a as g}from"./chunk-3VUPVXAV.js";import{b as f}from"./chunk-XFOU4DZG.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{J as se,d as O,f as ie}from"./chunk-LI5S3AAP.js";import{e as ee,k as ae}from"./chunk-MR475LAL.js";import{a as F}from"./chunk-5OPOCHOK.js";import{b as te,f as ne,g as re,h as oe}from"./chunk-EJ5YUUWB.js";import{s as ce}from"./chunk-BSYGUZTD.js";import{C as Y,e as J,j as Z,l as W,p as R,s as X,t as H,v as w,w as P,x as Q,z as k}from"./chunk-64KBBZD7.js";import{a as T,f as K}from"./chunk-TPFGWBVS.js";import{a as I,b as S,d as h,e as D,f as C,g as A}from"./chunk-LEDJ6HS3.js";import{h as j}from"./chunk-XRCW5N3J.js";import{b as e}from"./chunk-JX6MARAN.js";import{a as L,b as U}from"./chunk-CILM5XMH.js";var V=e.strictObject({eventsEnabled:e.boolean(),experimentViewsEnabled:e.boolean(),featureUsageEnabled:e.boolean()}),Ze=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function We(t,r){return r==="experiment_exposure"?t.experimentViewsEnabled:r==="feature_usage"?t.featureUsageEnabled:t.eventsEnabled}var z=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,r])=>t<=r),Se=e.strictObject({attribute:e.string().optional(),seed:e.string(),hashVersion:e.literal(2),ranges:e.array(z).max(100)}),we=e.strictObject({id:e.string().min(1).max(255),condition:C,gate:e.boolean().optional()}),Oe=e.strictObject({key:e.string().optional(),name:e.string().optional(),passthrough:e.boolean().optional()}),ue={condition:C.optional(),parentConditions:e.array(we).max(100).optional(),weights:e.array(e.number().min(0).max(1)).max(20).optional(),coverage:e.number().min(0).max(1).optional(),hashAttribute:e.string().optional(),fallbackAttribute:e.string().optional(),hashVersion:e.literal(2).optional(),disableStickyBucketing:e.boolean().optional(),bucketVersion:e.number().int().nonnegative().optional(),minBucketVersion:e.number().int().nonnegative().optional(),filters:e.array(Se).max(100).optional(),ranges:e.array(z).max(20).optional(),meta:e.array(Oe).max(20).optional(),seed:e.string().optional(),name:e.string().optional(),phase:e.string().optional()},pe=e.strictObject({...ue,key:e.string().min(1).max(255),variations:e.tuple([h,h]).rest(h).refine(t=>t.length<=20),urlPatterns:e.array(e.strictObject({include:e.boolean(),type:e.enum(["regex","simple"]),pattern:e.string()})).max(100).optional(),force:e.number().int().nonnegative().optional(),active:e.boolean().optional(),persistQueryString:e.boolean().optional()}),G=e.strictObject({value:h,variationId:e.number().int(),key:e.string(),name:e.string().optional(),bucket:e.number().optional(),passthrough:e.boolean().optional(),inExperiment:e.boolean(),hashUsed:e.boolean().optional(),hashAttribute:e.string(),hashValue:e.string(),featureId:e.string().nullable(),stickyBucketUsed:e.boolean().optional()}),je=e.strictObject({...ue,id:e.string().max(255).optional(),force:h.optional(),variations:e.array(h).min(2).max(20).optional(),key:e.string().optional(),range:z.optional(),tracks:e.array(e.strictObject({experiment:pe,result:G})).max(100).optional()}),Ie=e.strictObject({defaultValue:h.optional(),rules:e.array(je).max(500).optional()}),Pe=e.record(e.string(),e.union([e.strictObject({type:e.literal("hashed"),attributeKey:e.string(),values:e.array(e.string().regex(/^[a-f0-9]{64}$/))}),e.strictObject({type:e.literal("list"),attributeKey:e.string(),values:e.array(e.union([e.string(),e.number()]))}),e.strictObject({type:e.literal("condition"),condition:C})])),v=e.strictObject({scope:j,generation:e.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}).nullable(),features:e.record(e.string(),Ie),savedGroups:Pe,experiments:e.record(e.uuid(),pe)});var ke=v.extend({analyticsConfig:V,remoteFeatures:e.array(e.string().min(1).max(255)).max(500)}),it=ke.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((t,r)=>{for(let a of t.remoteFeatures)Object.hasOwn(t.features,a)&&r.addIssue({code:"custom",path:["features",a],message:"Remote Feature definitions cannot be public"});for(let[a,o]of Object.entries(t.savedGroups))o.type==="list"&&r.addIssue({code:"custom",path:["savedGroups",a],message:"Raw Saved Group lists cannot be public"})}),at=e.strictObject({attributes:D,features:e.array(e.string().min(1).max(255)).max(500).optional(),customerId:e.uuid().optional()}),me=e.strictObject({value:h,source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:e.boolean(),off:e.boolean(),ruleId:e.string(),experimentResult:G.optional()}),st=e.strictObject({generation:v.shape.generation,evaluatedAt:v.shape.evaluatedAt,expiresAt:v.shape.expiresAt,features:e.record(e.string(),me),merchandiseContext:e.strictObject({merchandiseId:e.uuid(),merchandise:D}).optional()}),de={eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}),merchandise:te.optional(),deviceId:e.string().min(1).max(255).optional(),sessionId:e.string().min(1).max(255).optional()},le={...de,generation:v.shape.generation},Ce=e.discriminatedUnion("kind",[e.strictObject({...de,kind:e.literal("custom"),name:e.string().min(1).max(255),properties:e.record(e.string(),h).default({})}),e.strictObject({...le,kind:e.literal("experiment_exposure"),experimentId:e.string().min(1).max(255),variationId:e.string().min(1).max(255)}),e.strictObject({...le,kind:e.literal("feature_usage"),feature:e.string().min(1).max(255),value:h,source:me.shape.source,ruleId:e.string().max(255),variationId:e.string().min(1).max(255).optional()})]),ct=e.strictObject({customerId:e.uuid().optional(),events:e.array(Ce).min(1).max(100)}),Ae=e.strictObject({eventUuid:e.uuid(),reason:e.enum(["invalid_event","invalid_merchandise","not_delivered","reserved_name"])}),ut=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),rejected:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejections:e.array(Ae).max(100),analyticsConfig:V});function fe(t,r){let a=new Set,o=new Set,c=new Set,p=[],g=new Map,f=new Map,d=new Map;function m(s){for(let n of A(s))i(n)}function i(s){if(c.has(s)||!Object.hasOwn(r.savedGroups,s))return;let n=r.savedGroups[s];n&&(c.add(s),d.set(s,n),p.push(()=>{!Array.isArray(n)&&n.type==="condition"&&m(n.condition)}))}function u(s){for(let n of["hashAttribute","fallbackAttribute"])if(s[n]!==void 0&&ae(s[n]))throw new Error(`Funnel GB ${n} uses a reserved flow namespace`);m(s.condition);for(let n of s.parentConditions??[])l(n.id),m(n.condition)}function l(s,n=!1){let b=Object.hasOwn(r.features,s)?r.features[s]:void 0;if(!b){if(n)throw new Error("Required GB Feature is unavailable");return}a.has(s)||(a.add(s),g.set(s,b),p.push(()=>{for(let x of b.rules??[]){u(x);for(let ve of x.tracks??[])u(ve.experiment)}}))}function y(s){let n=Object.hasOwn(r.experiments,s)?r.experiments[s]:void 0;if(!n)throw new Error("Required GB Experiment is unavailable");o.has(s)||(o.add(s),f.set(s,n),p.push(()=>u(n)))}for(let s of t.graph.nodes){s.type==="feature"&&l(s.featureKey,!0),s.type==="split"&&y(s.experimentId),s.type==="condition"&&s.cases.forEach(b=>m(b.condition)),s.type==="offering"&&s.configuration.source==="feature"&&l(s.configuration.featureKey,!0);let n=s.type==="output"?s.value:s.type==="end"?s.output:null;n?.type==="feature"&&l(n.featureKey,!0)}for(let s of p)s();return{...r,features:Object.fromEntries(g),experiments:Object.fromEntries(f),savedGroups:Object.fromEntries(d)}}var ge=e.object({defaultLocale:R,locales:e.record(R,e.object({name:e.string().max(80),description:e.string().max(500)}).strict())}).strict().superRefine((t,r)=>{let a=Object.keys(t.locales);(!a.length||a.length>20||!t.locales[t.defaultLocale])&&r.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(t)).length>5e4&&r.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var M=e.discriminatedUnion("type",[e.strictObject({type:e.literal("event"),event:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),e.strictObject({type:e.literal("open_url"),url:e.url().refine(t=>new URL(t).protocol==="https:")})]),Fe=P,Ee=e.discriminatedUnion("type",[e.object({type:e.literal("checkout"),product:I}).strict(),e.object({type:e.literal("close")}).strict(),e.object({type:e.literal("action"),action:M}).strict()]),E=e.object({schemaVersion:e.literal(3),kind:e.literal("paywall"),name:e.string().trim().min(1).max(80),presentation:S,requirement:K.optional(),products:F,offeringVersionId:e.uuid().nullable(),offeringId:e.uuid(),screen:Fe,buttons:e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ee)}).strict(),Pt=E.superRefine((t,r)=>{(t.screen.surface!=="paywall"||t.screen.actions.some(o=>!["event","navigate"].includes(o.type)||o.close))&&r.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let o of Re(t))r.addIssue({code:"custom",message:o});for(let o of _e(t))r.addIssue({code:"custom",message:o});for(let o of t.screen.actions){let c=o.properties.closeControl;c!==void 0&&(c!=="content"||t.buttons[o.id]?.type!=="close")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:'Only a close button can carry closeControl, and its value is "content"'})}for(let o of t.screen.actions){let c=o.properties.couponBinding;c!==void 0&&(typeof c!="string"||!X.safeParse(c).success||t.buttons[o.id]?.type!=="checkout"||Y(t.screen,c)?.type!=="text")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:"Choose a Coupon text binding for this checkout action"})}k(t.screen).some(o=>!o.complete)&&r.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(t.buttons).length!==t.screen.actions.filter(o=>o.type!=="navigate").length||t.screen.actions.some(o=>o.type!=="navigate"&&!Object.hasOwn(t.buttons,o.id)))&&r.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(t.buttons).some(o=>o.type==="checkout")||r.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function _e(t){let r=t.products.items.map(p=>p.productVersionId),a=Z(t.screen),o=new Set,c=[];(!r.length||!t.products.defaultProductVersionId||!r.includes(t.products.defaultProductVersionId))&&c.push("products"),t.offeringVersionId||c.push("offering"),t.products.grouping&&(!W(t.products.grouping,r)||t.products.grouping.tiers.some(p=>!t.products.grouping.assignments.some(g=>g.tierId===p.id)))&&c.push("grouping");for(let p of Object.values(t.buttons))if(p.type==="checkout"){let g=p.product;if(g.type==="fixed")o.add(g.productVersionId);else{g.allowedProductVersionIds.forEach(m=>o.add(m));let f=!1,d=a[g.pickerId];d&&(f=!0,(g.allowedProductVersionIds.some(m=>!d.ids.includes(m))||d.ids.some(m=>!g.allowedProductVersionIds.includes(m)))&&c.push("picker")),w(t.screen,m=>{if(m.id!==g.pickerId||m.type!=="plan_picker")return;f=!0,(JSON.stringify(m.planIds)!==JSON.stringify(r)||JSON.stringify(g.allowedProductVersionIds)!==JSON.stringify(r)||m.defaultPlan!==t.products.defaultProductVersionId)&&c.push("picker");let i=m.grouping?{tiers:m.grouping.tiers,assignments:m.grouping.assignments}:void 0;JSON.stringify(i)!==JSON.stringify(t.products.grouping)&&c.push("grouping")}),f||c.push("picker")}}return(!o.size||[...o].some(p=>!r.includes(p)))&&c.push("purchase"),w(t.screen,p=>{p.type==="stack"&&p.productSlot&&!p.bind?.plan&&c.push(`productBinding:${p.id}`),(p.type==="stack"||p.type==="button")&&p.bind?.plan&&!r.includes(p.bind.plan)&&c.push("binding"),p.type==="plan_picker"&&(!p.planIds?.length||p.planIds.some(g=>!r.includes(g)))&&c.push("binding")}),[...new Set(c)]}function Re(t){let r=[],a=t.screen.pages.at(-1),o=new Map;for(let f of t.screen.pages)o.set(f.id,[]),Q(f.root,d=>{let m=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(m){let i=t.screen.actions.find(l=>l.id===m);i?.type==="navigate"&&o.get(f.id).push(i.pageId);let u=t.buttons[m];f.id!==a.id&&u&&u.type!=="close"&&r.push(`purchaseScreen:${d.id}`)}f.id!==a.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&r.push(`packageScreen:${d.id}`)});let c=new Set;function p(f){if(!c.has(f)){c.add(f);for(let d of o.get(f)??[])p(d)}}let g=t.screen.initialPageId??t.screen.pages[0]?.id;g?p(g):r.push("initialPage");for(let f of t.screen.pages)c.has(f.id)||r.push(`unreachableScreen:${f.id}`);return[...new Set(r)]}var ye=e.object({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),state:e.enum(["active","archived"]),publishedVersionId:e.uuid().nullable(),updatedAt:e.iso.datetime({offset:!0}),draft:E}).strict(),kt=e.object({rows:e.array(ye).max(200),nextCursor:e.uuid().nullable()}).strict(),Ct=ye.omit({draft:!0}).extend({name:e.string(),productCount:e.number().int().nonnegative()}).strict(),At=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),document:E}).strict(),e.object({action:e.enum(["publish","archive"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Ft=e.object({paywalls:e.array(e.object({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),name:e.string().min(1).max(80),presentation:S,buttons:E.shape.buttons}).strict()).max(500),limited:e.boolean()}).strict();var De=["customer_data","coupon_code"],be=e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Ve=e.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),_=(t,r)=>new Set(t.map(r)).size===t.length,ze=e.strictObject({currency:T,amountMinor:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Ge=e.strictObject({featureId:e.uuid(),name:e.string().trim().min(1).max(120),allowance:e.string().max(40).nullable(),access:e.boolean()}),Me=e.strictObject({stripe:e.strictObject({prices:e.array(ze).min(1).max(50)}).optional(),apple:e.strictObject({productIds:e.array(be).min(1).max(10)}).optional(),google:e.strictObject({products:e.array(e.strictObject({productId:be,basePlanId:Ve.nullable()})).min(1).max(10)}).optional()}).superRefine((t,r)=>{(t.stripe&&!_(t.stripe.prices,a=>a.currency)||t.apple&&!_(t.apple.productIds,a=>a)||t.google&&!_(t.google.products,a=>`${a.productId}:${a.basePlanId}`))&&r.addIssue({code:"custom",message:"Duplicate channel entry"})}),qe=e.strictObject({name:e.string().trim().min(1).max(80),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(100),trial:e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}).nullable(),benefits:e.array(Ge).max(50).refine(t=>_(t,r=>r.featureId),"Duplicate benefit"),channels:Me,prepaid:e.array(J).max(100).optional()}),Be=e.strictObject({digest:O,content:e.strictObject({discount:ne,duration:re,appliesTo:oe,displayCopy:ge.nullable(),firstPurchaseOnly:e.boolean(),qualificationRequired:e.boolean(),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),grantWindowHours:e.number().int().positive(),perCustomerLimit:e.number().int().positive()})}),Ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("checkout"),product:I}),e.strictObject({type:e.literal("close")}),e.strictObject({type:e.literal("action"),action:M})]),Lt=e.strictObject({kind:e.literal("paywall"),formatVersion:e.literal(1),name:e.string().trim().min(1).max(80),offeringVersionId:e.uuid(),presentation:S,screen:P,products:F,catalog:e.record(e.uuid(),qe),buttons:e.record(H,Ne),coupons:e.record(e.uuid(),Be)}).superRefine((t,r)=>{let a=n=>r.addIssue({code:"custom",message:n}),{screen:o}=t;ce(o,t.catalog).forEach(a),o.surface!=="paywall"&&a("Screen must be a Paywall"),ie(o,De).forEach(a),k(o).some(n=>!n.complete)&&a("Every published locale must be complete");let c=new Set,p=new Set,g=new Set;w(o,n=>{let b="bind"in n?n.bind:void 0;b?.promotionCode&&a("Promotion codes must not be published"),b?.plan&&c.add(b.plan),b?.coupon&&p.add(b.coupon),n.type==="plan_picker"&&(n.planIds?.forEach(x=>c.add(x)),n.defaultPlan&&c.add(n.defaultPlan)),n.type==="text"&&n.feature&&g.add(n.feature.id)});let f=t.products.items.map(n=>n.productVersionId),d=Object.keys(t.catalog);(f.length!==d.length||f.some(n=>!Object.hasOwn(t.catalog,n)))&&a("Catalog must contain exactly the displayed Products");let m=new Set(f);t.products.defaultProductVersionId!==null&&!m.has(t.products.defaultProductVersionId)&&a("Default Product must be displayed");for(let n of c)m.has(n)||a("Screen references a Product that is not displayed");for(let n of Object.values(t.catalog))!n.channels.stripe&&!n.channels.apple&&!n.channels.google&&a("A displayed Product needs at least one sales channel");let i=new Set(Object.values(t.catalog).flatMap(n=>n.benefits.map(b=>b.featureId)));for(let n of g)i.has(n)||a("Feature text must read a displayed benefit");let u=o.actions.filter(n=>n.type!=="navigate");o.actions.some(n=>n.type!=="event"&&n.type!=="navigate")&&a("Paywall actions are events or navigation"),(Object.keys(t.buttons).length!==u.length||u.some(n=>!Object.hasOwn(t.buttons,n.id)))&&a("Buttons must match the screen's actions");let y=!1;for(let n of Object.values(t.buttons)){if(n.type!=="checkout")continue;y=!0,(n.product.type==="fixed"?[n.product.productVersionId]:n.product.allowedProductVersionIds).some(x=>!m.has(x))&&a("Checkout may only sell displayed Products")}y||a("A Paywall needs a checkout button");let s=Object.keys(t.coupons);(s.length!==p.size||s.some(n=>!p.has(n)))&&a("Coupons must be exactly the bound Coupons")}),he=e.strictObject({state:e.enum(["published","archived"]),controlRevision:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({version:e.number().int().positive(),artifact:e.string().min(1),sourceDigest:e.string().regex(/^[a-f0-9]{64}$/)}))}).refine(t=>Object.keys(t.versions).length>0,"Reviewed Paywall Versions are required");var $e={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},q=e.string().regex(/^[a-f0-9]{64}$/),B=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Le=j.extend({environmentId:e.uuid()}),xe=e.strictObject({features:e.array(e.string()).max(500),experiments:e.record(e.uuid(),e.array(e.string()).max(20)),savedGroups:e.array(e.string()).max(1e3)}),Ue=e.strictObject({kind:e.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:e.number().int().positive(),url:e.string().min(1).max(2048),sha256:q,byteLength:e.number().int().positive().max($e.maxArtifactBytes),generation:q.optional()}),Te=e.strictObject({state:e.enum(["active","paused","archived"]),controlRevision:B,evaluationMode:e.enum(["local","remote"]),evaluationRevision:B,currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({artifact:e.string(),dependencies:xe,definitionDigest:O.optional(),couponDigests:e.record(e.uuid(),O).optional()}))}),en=e.strictObject({kind:e.literal("sdk_configuration"),schemaVersion:e.literal(1),scope:Le,revision:B,generation:q,policy:e.strictObject({refreshIntervalSeconds:e.number().positive().max(15),maxControlAgeSeconds:e.number().positive().max(60)}),gb:e.strictObject({features:e.string().nullable(),pageExperiments:e.string().nullable()}),artifacts:e.record(e.string(),Ue),funnels:e.record(e.uuid(),Te),paywalls:e.record(e.uuid(),he).optional()}).superRefine((t,r)=>{let a=(o,c)=>{o!==null&&t.artifacts[o]?.kind!==c&&r.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};a(t.gb.features,"gb_features"),a(t.gb.pageExperiments,"gb_page_experiments");for(let o of Object.values(t.paywalls??{}))for(let c of Object.values(o.versions))a(c.artifact,"paywall");for(let o of Object.values(t.funnels)){o.evaluationMode==="remote"&&Object.keys(o.versions).length&&r.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),o.evaluationMode==="local"&&!o.versions[o.currentVersionId]&&r.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let c of Object.values(o.versions))a(c.artifact,"funnel")}});function N(t){if(Array.isArray(t))return`[${t.map(N).join(",")}]`;if(t!==null&&typeof t=="object")return`{${Object.entries(t).sort(([a],[o])=>a<o?-1:a>o?1:0).map(([a,o])=>`${JSON.stringify(a)}:${N(o)}`).join(",")}}`;let r=JSON.stringify(t);if(r===void 0)throw new Error("Configuration must contain JSON values");return r}function Je(t){return L(U(typeof t=="string"?new TextEncoder().encode(t):t))}function tn(t){return Je(N(t))}var $=class extends Error{constructor(a,o){super(a);this.dependency=o}dependency};function nn(t,r){let a=i=>i.type==="feature"?i.featureKey:i.type==="end"&&i.output?.type==="feature"?i.output.featureKey:i.type==="output"&&i.value.type==="feature"?i.value.featureKey:void 0,o=(i,u)=>t.graph.nodes.find(l=>i==="experiment"?l.type==="split"&&l.experimentId===u:i==="feature"&&a(l)===u)?.name,c=(i,u,l=o(u.type,u.resource))=>new $(i,{...u,...l?{step:l}:{}});for(let i of Object.values(t.references)){let u=i.type==="flag"?!Object.hasOwn(r.features,i.key)||r.remoteFeatures.includes(i.key)?{type:"feature",resource:i.key}:null:i.type==="experiment"?Object.hasOwn(r.experiments,i.id)?null:{type:"experiment",resource:i.id}:i.type==="saved_group"&&!Object.hasOwn(r.savedGroups,i.id)?{type:"saved_group",resource:i.id}:null;if(u)throw c("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...u})}let p=fe(t,{...r,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),g=new Set(r.remoteFeatures);for(let i of t.graph.nodes){let u=a(i);if(!u)continue;let l=p.features[u],y=i.type==="feature"?t.variables[i.writes.value]:t.outputSchema,s={type:"feature",resource:u};if(!l||!y)throw c("Required public Feature declaration is unavailable",{reason:"unavailable",...s},i.name);if([l.defaultValue,...(l.rules??[]).flatMap(b=>[...Object.hasOwn(b,"force")?[b.force]:[],...b.variations??[],...(b.tracks??[]).flatMap(x=>x.experiment.variations)])].some(b=>b===void 0||!ee(y,b)))throw c("GB Feature values violate the Funnel type contract",{reason:"value_type",...s},i.name)}let f=new Set,d=(i,u)=>{for(let l of A(i)){if(f.has(l))continue;let y=r.savedGroups[l];if(!y)throw c("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:l},u);f.add(l),!Array.isArray(y)&&y.type==="condition"&&d(y.condition,u)}},m=(i,u)=>{if(g.has(i)||!r.features[i])throw c("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:i},u)};for(let i of t.graph.nodes)if(i.type==="condition")for(let u of i.cases)d(u.condition,i.name);for(let[i,u]of Object.entries(p.features)){let l=o("feature",i);for(let y of u.rules??[]){d(y.condition,l);for(let s of[...y.parentConditions??[],...(y.tracks??[]).flatMap(n=>n.experiment.parentConditions??[])])m(s.id,l),d(s.condition,l);for(let s of y.tracks??[])d(s.experiment.condition,l)}}for(let[i,u]of Object.entries(p.experiments)){let l=o("experiment",i);d(u.condition,l);for(let y of u.parentConditions??[])m(y.id,l),d(y.condition,l)}for(let i of t.graph.nodes)if(i.type==="split"){let u=p.experiments[i.experimentId],l={type:"experiment",resource:i.experimentId};if(!u)throw c("Local Funnel requires a public Experiment",{reason:"unavailable",...l},i.name);for(let y of u.variations)if(typeof y!="string"||!Object.hasOwn(i.routes,y))throw c("Experiment variation has no declared Funnel route",{reason:"variation_route",...l},i.name)}return xe.parse({features:Object.keys(p.features).sort(),experiments:Object.fromEntries(Object.entries(p.experiments).map(([i,u])=>[i,u.variations.map(String)])),savedGroups:[...f].sort()})}function rn(t){return se.parse(t)}export{E as a,We as b,pe as c,Pe as d,v as e,ke as f,it as g,at as h,st as i,ct as j,ut as k,fe as l,Lt as m,$e as n,Le as o,Ue as p,en as q,N as r,Je as s,tn as t,nn as u,rn as v};
|
|
1
|
+
import{J as se,d as O,f as ie}from"./chunk-PZTFSADV.js";import{e as ee,k as ae}from"./chunk-YIHMOK6T.js";import{a as F}from"./chunk-P2JQEGYV.js";import{b as te,f as ne,g as re,h as oe}from"./chunk-NQZ23AGQ.js";import{s as ce}from"./chunk-LTWU7HH5.js";import{C as Y,e as J,j as Z,l as W,p as R,s as X,t as H,v as w,w as P,x as Q,z as k}from"./chunk-NTYIQ5YC.js";import{a as T,f as K}from"./chunk-2PY7INHO.js";import{a as I,b as S,d as h,e as D,f as C,g as A}from"./chunk-T7AK4QLG.js";import{h as j}from"./chunk-LB2ZRTRA.js";import{b as e}from"./chunk-COMZFFUA.js";import{a as L,b as U}from"./chunk-CILM5XMH.js";var V=e.strictObject({eventsEnabled:e.boolean(),experimentViewsEnabled:e.boolean(),featureUsageEnabled:e.boolean()}),Ze=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function We(t,r){return r==="experiment_exposure"?t.experimentViewsEnabled:r==="feature_usage"?t.featureUsageEnabled:t.eventsEnabled}var z=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,r])=>t<=r),Se=e.strictObject({attribute:e.string().optional(),seed:e.string(),hashVersion:e.literal(2),ranges:e.array(z).max(100)}),we=e.strictObject({id:e.string().min(1).max(255),condition:C,gate:e.boolean().optional()}),Oe=e.strictObject({key:e.string().optional(),name:e.string().optional(),passthrough:e.boolean().optional()}),ue={condition:C.optional(),parentConditions:e.array(we).max(100).optional(),weights:e.array(e.number().min(0).max(1)).max(20).optional(),coverage:e.number().min(0).max(1).optional(),hashAttribute:e.string().optional(),fallbackAttribute:e.string().optional(),hashVersion:e.literal(2).optional(),disableStickyBucketing:e.boolean().optional(),bucketVersion:e.number().int().nonnegative().optional(),minBucketVersion:e.number().int().nonnegative().optional(),filters:e.array(Se).max(100).optional(),ranges:e.array(z).max(20).optional(),meta:e.array(Oe).max(20).optional(),seed:e.string().optional(),name:e.string().optional(),phase:e.string().optional()},pe=e.strictObject({...ue,key:e.string().min(1).max(255),variations:e.tuple([h,h]).rest(h).refine(t=>t.length<=20),urlPatterns:e.array(e.strictObject({include:e.boolean(),type:e.enum(["regex","simple"]),pattern:e.string()})).max(100).optional(),force:e.number().int().nonnegative().optional(),active:e.boolean().optional(),persistQueryString:e.boolean().optional()}),G=e.strictObject({value:h,variationId:e.number().int(),key:e.string(),name:e.string().optional(),bucket:e.number().optional(),passthrough:e.boolean().optional(),inExperiment:e.boolean(),hashUsed:e.boolean().optional(),hashAttribute:e.string(),hashValue:e.string(),featureId:e.string().nullable(),stickyBucketUsed:e.boolean().optional()}),je=e.strictObject({...ue,id:e.string().max(255).optional(),force:h.optional(),variations:e.array(h).min(2).max(20).optional(),key:e.string().optional(),range:z.optional(),tracks:e.array(e.strictObject({experiment:pe,result:G})).max(100).optional()}),Ie=e.strictObject({defaultValue:h.optional(),rules:e.array(je).max(500).optional()}),Pe=e.record(e.string(),e.union([e.strictObject({type:e.literal("hashed"),attributeKey:e.string(),values:e.array(e.string().regex(/^[a-f0-9]{64}$/))}),e.strictObject({type:e.literal("list"),attributeKey:e.string(),values:e.array(e.union([e.string(),e.number()]))}),e.strictObject({type:e.literal("condition"),condition:C})])),v=e.strictObject({scope:j,generation:e.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}).nullable(),features:e.record(e.string(),Ie),savedGroups:Pe,experiments:e.record(e.uuid(),pe)});var ke=v.extend({analyticsConfig:V,remoteFeatures:e.array(e.string().min(1).max(255)).max(500)}),it=ke.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((t,r)=>{for(let a of t.remoteFeatures)Object.hasOwn(t.features,a)&&r.addIssue({code:"custom",path:["features",a],message:"Remote Feature definitions cannot be public"});for(let[a,o]of Object.entries(t.savedGroups))o.type==="list"&&r.addIssue({code:"custom",path:["savedGroups",a],message:"Raw Saved Group lists cannot be public"})}),at=e.strictObject({attributes:D,features:e.array(e.string().min(1).max(255)).max(500).optional(),customerId:e.uuid().optional()}),me=e.strictObject({value:h,source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:e.boolean(),off:e.boolean(),ruleId:e.string(),experimentResult:G.optional()}),st=e.strictObject({generation:v.shape.generation,evaluatedAt:v.shape.evaluatedAt,expiresAt:v.shape.expiresAt,features:e.record(e.string(),me),merchandiseContext:e.strictObject({merchandiseId:e.uuid(),merchandise:D}).optional()}),de={eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}),merchandise:te.optional(),deviceId:e.string().min(1).max(255).optional(),sessionId:e.string().min(1).max(255).optional()},le={...de,generation:v.shape.generation},Ce=e.discriminatedUnion("kind",[e.strictObject({...de,kind:e.literal("custom"),name:e.string().min(1).max(255),properties:e.record(e.string(),h).default({})}),e.strictObject({...le,kind:e.literal("experiment_exposure"),experimentId:e.string().min(1).max(255),variationId:e.string().min(1).max(255)}),e.strictObject({...le,kind:e.literal("feature_usage"),feature:e.string().min(1).max(255),value:h,source:me.shape.source,ruleId:e.string().max(255),variationId:e.string().min(1).max(255).optional()})]),ct=e.strictObject({customerId:e.uuid().optional(),events:e.array(Ce).min(1).max(100)}),Ae=e.strictObject({eventUuid:e.uuid(),reason:e.enum(["invalid_event","invalid_merchandise","not_delivered","reserved_name"])}),ut=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),rejected:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejections:e.array(Ae).max(100),analyticsConfig:V});function fe(t,r){let a=new Set,o=new Set,c=new Set,p=[],g=new Map,f=new Map,d=new Map;function m(s){for(let n of A(s))i(n)}function i(s){if(c.has(s)||!Object.hasOwn(r.savedGroups,s))return;let n=r.savedGroups[s];n&&(c.add(s),d.set(s,n),p.push(()=>{!Array.isArray(n)&&n.type==="condition"&&m(n.condition)}))}function u(s){for(let n of["hashAttribute","fallbackAttribute"])if(s[n]!==void 0&&ae(s[n]))throw new Error(`Funnel GB ${n} uses a reserved flow namespace`);m(s.condition);for(let n of s.parentConditions??[])l(n.id),m(n.condition)}function l(s,n=!1){let b=Object.hasOwn(r.features,s)?r.features[s]:void 0;if(!b){if(n)throw new Error("Required GB Feature is unavailable");return}a.has(s)||(a.add(s),g.set(s,b),p.push(()=>{for(let x of b.rules??[]){u(x);for(let ve of x.tracks??[])u(ve.experiment)}}))}function y(s){let n=Object.hasOwn(r.experiments,s)?r.experiments[s]:void 0;if(!n)throw new Error("Required GB Experiment is unavailable");o.has(s)||(o.add(s),f.set(s,n),p.push(()=>u(n)))}for(let s of t.graph.nodes){s.type==="feature"&&l(s.featureKey,!0),s.type==="split"&&y(s.experimentId),s.type==="condition"&&s.cases.forEach(b=>m(b.condition)),s.type==="offering"&&s.configuration.source==="feature"&&l(s.configuration.featureKey,!0);let n=s.type==="output"?s.value:s.type==="end"?s.output:null;n?.type==="feature"&&l(n.featureKey,!0)}for(let s of p)s();return{...r,features:Object.fromEntries(g),experiments:Object.fromEntries(f),savedGroups:Object.fromEntries(d)}}var ge=e.object({defaultLocale:R,locales:e.record(R,e.object({name:e.string().max(80),description:e.string().max(500)}).strict())}).strict().superRefine((t,r)=>{let a=Object.keys(t.locales);(!a.length||a.length>20||!t.locales[t.defaultLocale])&&r.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(t)).length>5e4&&r.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var M=e.discriminatedUnion("type",[e.strictObject({type:e.literal("event"),event:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),e.strictObject({type:e.literal("open_url"),url:e.url().refine(t=>new URL(t).protocol==="https:")})]),Fe=P,Ee=e.discriminatedUnion("type",[e.object({type:e.literal("checkout"),product:I}).strict(),e.object({type:e.literal("close")}).strict(),e.object({type:e.literal("action"),action:M}).strict()]),E=e.object({schemaVersion:e.literal(3),kind:e.literal("paywall"),name:e.string().trim().min(1).max(80),presentation:S,requirement:K.optional(),products:F,offeringVersionId:e.uuid().nullable(),offeringId:e.uuid(),screen:Fe,buttons:e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ee)}).strict(),Pt=E.superRefine((t,r)=>{(t.screen.surface!=="paywall"||t.screen.actions.some(o=>!["event","navigate"].includes(o.type)||o.close))&&r.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let o of Re(t))r.addIssue({code:"custom",message:o});for(let o of _e(t))r.addIssue({code:"custom",message:o});for(let o of t.screen.actions){let c=o.properties.closeControl;c!==void 0&&(c!=="content"||t.buttons[o.id]?.type!=="close")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:'Only a close button can carry closeControl, and its value is "content"'})}for(let o of t.screen.actions){let c=o.properties.couponBinding;c!==void 0&&(typeof c!="string"||!X.safeParse(c).success||t.buttons[o.id]?.type!=="checkout"||Y(t.screen,c)?.type!=="text")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:"Choose a Coupon text binding for this checkout action"})}k(t.screen).some(o=>!o.complete)&&r.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(t.buttons).length!==t.screen.actions.filter(o=>o.type!=="navigate").length||t.screen.actions.some(o=>o.type!=="navigate"&&!Object.hasOwn(t.buttons,o.id)))&&r.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(t.buttons).some(o=>o.type==="checkout")||r.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function _e(t){let r=t.products.items.map(p=>p.productVersionId),a=Z(t.screen),o=new Set,c=[];(!r.length||!t.products.defaultProductVersionId||!r.includes(t.products.defaultProductVersionId))&&c.push("products"),t.offeringVersionId||c.push("offering"),t.products.grouping&&(!W(t.products.grouping,r)||t.products.grouping.tiers.some(p=>!t.products.grouping.assignments.some(g=>g.tierId===p.id)))&&c.push("grouping");for(let p of Object.values(t.buttons))if(p.type==="checkout"){let g=p.product;if(g.type==="fixed")o.add(g.productVersionId);else{g.allowedProductVersionIds.forEach(m=>o.add(m));let f=!1,d=a[g.pickerId];d&&(f=!0,(g.allowedProductVersionIds.some(m=>!d.ids.includes(m))||d.ids.some(m=>!g.allowedProductVersionIds.includes(m)))&&c.push("picker")),w(t.screen,m=>{if(m.id!==g.pickerId||m.type!=="plan_picker")return;f=!0,(JSON.stringify(m.planIds)!==JSON.stringify(r)||JSON.stringify(g.allowedProductVersionIds)!==JSON.stringify(r)||m.defaultPlan!==t.products.defaultProductVersionId)&&c.push("picker");let i=m.grouping?{tiers:m.grouping.tiers,assignments:m.grouping.assignments}:void 0;JSON.stringify(i)!==JSON.stringify(t.products.grouping)&&c.push("grouping")}),f||c.push("picker")}}return(!o.size||[...o].some(p=>!r.includes(p)))&&c.push("purchase"),w(t.screen,p=>{p.type==="stack"&&p.productSlot&&!p.bind?.plan&&c.push(`productBinding:${p.id}`),(p.type==="stack"||p.type==="button")&&p.bind?.plan&&!r.includes(p.bind.plan)&&c.push("binding"),p.type==="plan_picker"&&(!p.planIds?.length||p.planIds.some(g=>!r.includes(g)))&&c.push("binding")}),[...new Set(c)]}function Re(t){let r=[],a=t.screen.pages.at(-1),o=new Map;for(let f of t.screen.pages)o.set(f.id,[]),Q(f.root,d=>{let m=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(m){let i=t.screen.actions.find(l=>l.id===m);i?.type==="navigate"&&o.get(f.id).push(i.pageId);let u=t.buttons[m];f.id!==a.id&&u&&u.type!=="close"&&r.push(`purchaseScreen:${d.id}`)}f.id!==a.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&r.push(`packageScreen:${d.id}`)});let c=new Set;function p(f){if(!c.has(f)){c.add(f);for(let d of o.get(f)??[])p(d)}}let g=t.screen.initialPageId??t.screen.pages[0]?.id;g?p(g):r.push("initialPage");for(let f of t.screen.pages)c.has(f.id)||r.push(`unreachableScreen:${f.id}`);return[...new Set(r)]}var ye=e.object({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),state:e.enum(["active","archived"]),publishedVersionId:e.uuid().nullable(),updatedAt:e.iso.datetime({offset:!0}),draft:E}).strict(),kt=e.object({rows:e.array(ye).max(200),nextCursor:e.uuid().nullable()}).strict(),Ct=ye.omit({draft:!0}).extend({name:e.string(),productCount:e.number().int().nonnegative()}).strict(),At=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),document:E}).strict(),e.object({action:e.enum(["publish","archive"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Ft=e.object({paywalls:e.array(e.object({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),name:e.string().min(1).max(80),presentation:S,buttons:E.shape.buttons}).strict()).max(500),limited:e.boolean()}).strict();var De=["customer_data","coupon_code"],be=e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Ve=e.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),_=(t,r)=>new Set(t.map(r)).size===t.length,ze=e.strictObject({currency:T,amountMinor:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Ge=e.strictObject({featureId:e.uuid(),name:e.string().trim().min(1).max(120),allowance:e.string().max(40).nullable(),access:e.boolean()}),Me=e.strictObject({stripe:e.strictObject({prices:e.array(ze).min(1).max(50)}).optional(),apple:e.strictObject({productIds:e.array(be).min(1).max(10)}).optional(),google:e.strictObject({products:e.array(e.strictObject({productId:be,basePlanId:Ve.nullable()})).min(1).max(10)}).optional()}).superRefine((t,r)=>{(t.stripe&&!_(t.stripe.prices,a=>a.currency)||t.apple&&!_(t.apple.productIds,a=>a)||t.google&&!_(t.google.products,a=>`${a.productId}:${a.basePlanId}`))&&r.addIssue({code:"custom",message:"Duplicate channel entry"})}),qe=e.strictObject({name:e.string().trim().min(1).max(80),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(100),trial:e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}).nullable(),benefits:e.array(Ge).max(50).refine(t=>_(t,r=>r.featureId),"Duplicate benefit"),channels:Me,prepaid:e.array(J).max(100).optional()}),Be=e.strictObject({digest:O,content:e.strictObject({discount:ne,duration:re,appliesTo:oe,displayCopy:ge.nullable(),firstPurchaseOnly:e.boolean(),qualificationRequired:e.boolean(),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),grantWindowHours:e.number().int().positive(),perCustomerLimit:e.number().int().positive()})}),Ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("checkout"),product:I}),e.strictObject({type:e.literal("close")}),e.strictObject({type:e.literal("action"),action:M})]),Lt=e.strictObject({kind:e.literal("paywall"),formatVersion:e.literal(1),name:e.string().trim().min(1).max(80),offeringVersionId:e.uuid(),presentation:S,screen:P,products:F,catalog:e.record(e.uuid(),qe),buttons:e.record(H,Ne),coupons:e.record(e.uuid(),Be)}).superRefine((t,r)=>{let a=n=>r.addIssue({code:"custom",message:n}),{screen:o}=t;ce(o,t.catalog).forEach(a),o.surface!=="paywall"&&a("Screen must be a Paywall"),ie(o,De).forEach(a),k(o).some(n=>!n.complete)&&a("Every published locale must be complete");let c=new Set,p=new Set,g=new Set;w(o,n=>{let b="bind"in n?n.bind:void 0;b?.promotionCode&&a("Promotion codes must not be published"),b?.plan&&c.add(b.plan),b?.coupon&&p.add(b.coupon),n.type==="plan_picker"&&(n.planIds?.forEach(x=>c.add(x)),n.defaultPlan&&c.add(n.defaultPlan)),n.type==="text"&&n.feature&&g.add(n.feature.id)});let f=t.products.items.map(n=>n.productVersionId),d=Object.keys(t.catalog);(f.length!==d.length||f.some(n=>!Object.hasOwn(t.catalog,n)))&&a("Catalog must contain exactly the displayed Products");let m=new Set(f);t.products.defaultProductVersionId!==null&&!m.has(t.products.defaultProductVersionId)&&a("Default Product must be displayed");for(let n of c)m.has(n)||a("Screen references a Product that is not displayed");for(let n of Object.values(t.catalog))!n.channels.stripe&&!n.channels.apple&&!n.channels.google&&a("A displayed Product needs at least one sales channel");let i=new Set(Object.values(t.catalog).flatMap(n=>n.benefits.map(b=>b.featureId)));for(let n of g)i.has(n)||a("Feature text must read a displayed benefit");let u=o.actions.filter(n=>n.type!=="navigate");o.actions.some(n=>n.type!=="event"&&n.type!=="navigate")&&a("Paywall actions are events or navigation"),(Object.keys(t.buttons).length!==u.length||u.some(n=>!Object.hasOwn(t.buttons,n.id)))&&a("Buttons must match the screen's actions");let y=!1;for(let n of Object.values(t.buttons)){if(n.type!=="checkout")continue;y=!0,(n.product.type==="fixed"?[n.product.productVersionId]:n.product.allowedProductVersionIds).some(x=>!m.has(x))&&a("Checkout may only sell displayed Products")}y||a("A Paywall needs a checkout button");let s=Object.keys(t.coupons);(s.length!==p.size||s.some(n=>!p.has(n)))&&a("Coupons must be exactly the bound Coupons")}),he=e.strictObject({state:e.enum(["published","archived"]),controlRevision:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({version:e.number().int().positive(),artifact:e.string().min(1),sourceDigest:e.string().regex(/^[a-f0-9]{64}$/)}))}).refine(t=>Object.keys(t.versions).length>0,"Reviewed Paywall Versions are required");var $e={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},q=e.string().regex(/^[a-f0-9]{64}$/),B=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Le=j.extend({environmentId:e.uuid()}),xe=e.strictObject({features:e.array(e.string()).max(500),experiments:e.record(e.uuid(),e.array(e.string()).max(20)),savedGroups:e.array(e.string()).max(1e3)}),Ue=e.strictObject({kind:e.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:e.number().int().positive(),url:e.string().min(1).max(2048),sha256:q,byteLength:e.number().int().positive().max($e.maxArtifactBytes),generation:q.optional()}),Te=e.strictObject({state:e.enum(["active","paused","archived"]),controlRevision:B,evaluationMode:e.enum(["local","remote"]),evaluationRevision:B,currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({artifact:e.string(),dependencies:xe,definitionDigest:O.optional(),couponDigests:e.record(e.uuid(),O).optional()}))}),en=e.strictObject({kind:e.literal("sdk_configuration"),schemaVersion:e.literal(1),scope:Le,revision:B,generation:q,policy:e.strictObject({refreshIntervalSeconds:e.number().positive().max(15),maxControlAgeSeconds:e.number().positive().max(60)}),gb:e.strictObject({features:e.string().nullable(),pageExperiments:e.string().nullable()}),artifacts:e.record(e.string(),Ue),funnels:e.record(e.uuid(),Te),paywalls:e.record(e.uuid(),he).optional()}).superRefine((t,r)=>{let a=(o,c)=>{o!==null&&t.artifacts[o]?.kind!==c&&r.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};a(t.gb.features,"gb_features"),a(t.gb.pageExperiments,"gb_page_experiments");for(let o of Object.values(t.paywalls??{}))for(let c of Object.values(o.versions))a(c.artifact,"paywall");for(let o of Object.values(t.funnels)){o.evaluationMode==="remote"&&Object.keys(o.versions).length&&r.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),o.evaluationMode==="local"&&!o.versions[o.currentVersionId]&&r.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let c of Object.values(o.versions))a(c.artifact,"funnel")}});function N(t){if(Array.isArray(t))return`[${t.map(N).join(",")}]`;if(t!==null&&typeof t=="object")return`{${Object.entries(t).sort(([a],[o])=>a<o?-1:a>o?1:0).map(([a,o])=>`${JSON.stringify(a)}:${N(o)}`).join(",")}}`;let r=JSON.stringify(t);if(r===void 0)throw new Error("Configuration must contain JSON values");return r}function Je(t){return L(U(typeof t=="string"?new TextEncoder().encode(t):t))}function tn(t){return Je(N(t))}var $=class extends Error{constructor(a,o){super(a);this.dependency=o}dependency};function nn(t,r){let a=i=>i.type==="feature"?i.featureKey:i.type==="end"&&i.output?.type==="feature"?i.output.featureKey:i.type==="output"&&i.value.type==="feature"?i.value.featureKey:void 0,o=(i,u)=>t.graph.nodes.find(l=>i==="experiment"?l.type==="split"&&l.experimentId===u:i==="feature"&&a(l)===u)?.name,c=(i,u,l=o(u.type,u.resource))=>new $(i,{...u,...l?{step:l}:{}});for(let i of Object.values(t.references)){let u=i.type==="flag"?!Object.hasOwn(r.features,i.key)||r.remoteFeatures.includes(i.key)?{type:"feature",resource:i.key}:null:i.type==="experiment"?Object.hasOwn(r.experiments,i.id)?null:{type:"experiment",resource:i.id}:i.type==="saved_group"&&!Object.hasOwn(r.savedGroups,i.id)?{type:"saved_group",resource:i.id}:null;if(u)throw c("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...u})}let p=fe(t,{...r,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),g=new Set(r.remoteFeatures);for(let i of t.graph.nodes){let u=a(i);if(!u)continue;let l=p.features[u],y=i.type==="feature"?t.variables[i.writes.value]:t.outputSchema,s={type:"feature",resource:u};if(!l||!y)throw c("Required public Feature declaration is unavailable",{reason:"unavailable",...s},i.name);if([l.defaultValue,...(l.rules??[]).flatMap(b=>[...Object.hasOwn(b,"force")?[b.force]:[],...b.variations??[],...(b.tracks??[]).flatMap(x=>x.experiment.variations)])].some(b=>b===void 0||!ee(y,b)))throw c("GB Feature values violate the Funnel type contract",{reason:"value_type",...s},i.name)}let f=new Set,d=(i,u)=>{for(let l of A(i)){if(f.has(l))continue;let y=r.savedGroups[l];if(!y)throw c("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:l},u);f.add(l),!Array.isArray(y)&&y.type==="condition"&&d(y.condition,u)}},m=(i,u)=>{if(g.has(i)||!r.features[i])throw c("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:i},u)};for(let i of t.graph.nodes)if(i.type==="condition")for(let u of i.cases)d(u.condition,i.name);for(let[i,u]of Object.entries(p.features)){let l=o("feature",i);for(let y of u.rules??[]){d(y.condition,l);for(let s of[...y.parentConditions??[],...(y.tracks??[]).flatMap(n=>n.experiment.parentConditions??[])])m(s.id,l),d(s.condition,l);for(let s of y.tracks??[])d(s.experiment.condition,l)}}for(let[i,u]of Object.entries(p.experiments)){let l=o("experiment",i);d(u.condition,l);for(let y of u.parentConditions??[])m(y.id,l),d(y.condition,l)}for(let i of t.graph.nodes)if(i.type==="split"){let u=p.experiments[i.experimentId],l={type:"experiment",resource:i.experimentId};if(!u)throw c("Local Funnel requires a public Experiment",{reason:"unavailable",...l},i.name);for(let y of u.variations)if(typeof y!="string"||!Object.hasOwn(i.routes,y))throw c("Experiment variation has no declared Funnel route",{reason:"variation_route",...l},i.name)}return xe.parse({features:Object.keys(p.features).sort(),experiments:Object.fromEntries(Object.entries(p.experiments).map(([i,u])=>[i,u.variations.map(String)])),savedGroups:[...f].sort()})}function rn(t){return se.parse(t)}export{E as a,We as b,pe as c,Pe as d,v as e,ke as f,it as g,at as h,st as i,ct as j,ut as k,fe as l,Lt as m,$e as n,Le as o,Ue as p,en as q,N as r,Je as s,tn as t,nn as u,rn as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as r}from"./chunk-
|
|
1
|
+
import{b as r}from"./chunk-COMZFFUA.js";var R=r.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),H=r.enum([...R.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED","SENSITIVE_OUTPUT_REQUIRED"]),j=r.enum([...R.options,"stale_revision"]),v=r.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),x=r.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED","FUNNEL_PAUSED"]),L={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var S={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",CUSTOMER_SESSION_REQUIRED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",PURCHASE_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",PURCHASE_STORAGE_CONFLICT:"resolve_conflict",PURCHASE_STORAGE_INVALID:"recover_operation",EXECUTION_POLICY_REFUSED:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",ROUTE_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",COUPON_UNAVAILABLE:"reload_state",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function g(e,o){if(e==="CONFLICT"&&o===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&o===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION"||e==="SENSITIVE_OUTPUT_REQUIRED")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(S,e)){let n=S[e];return{retryable:n==="retry_same_request",recovery:n}}let t=R.safeParse(e);return t.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:L[t.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Q(e,o){let t=R.safeParse(e);if(t.success)return e==="CONFLICT"?[409,412,425].includes(o):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(o):e==="INVALID_REQUEST"?[400,405,415,422].includes(o):e==="NOT_CONFIGURED"?[501,503].includes(o):L[t.data].status===o;let n={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],SENSITIVE_OUTPUT_REQUIRED:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(n,e)&&(n[e]?.includes(o)??!1)}function P(e,o=Date.now()){if(e===null)return;let t=e.trim();if(/^\d+$/.test(t)){let s=Number(t);return Number.isSafeInteger(s)?s:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(t))return;let n=Date.parse(t);return Number.isFinite(n)?Math.max(0,Math.ceil((n-o)/1e3)):void 0}var y=r.object({retryable:r.boolean(),recovery:v,reason:x.optional(),retryAfterSeconds:r.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),b=r.object({requestId:r.uuid().optional(),error:r.object({code:r.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:r.string(),...y.partial().shape})}),z=r.object({error:b.shape.error.extend({requestId:r.uuid().optional()})}),Y=r.object({error:r.string(),code:r.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:r.uuid(),...y.shape});function $(e,o,t={}){let n=g(e,o),s=t.reason==="RESULT_UNKNOWN"?"recover_operation":t.recovery??n.recovery,A=n.retryable&&t.retryable!==!1&&s!=="recover_operation",i=A?P(t.retryAfter??null):void 0;return{...n,retryable:A,recovery:s,...i===void 0?{}:{retryAfterSeconds:i},...t.reason?{reason:t.reason}:{}}}var V=r.enum(["sandbox","live"]),W=r.object({projectId:r.string().min(1),environment:V}).strict();var J=r.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),u=r.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),M=r.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let o=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return o==="-0"?"0":o}),p=u.refine(e=>/[1-9]/.test(e),"数量必须大于 0"),D=r.string().min(1).max(64),B=r.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),C=r.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),ee=r.record(D,r.union([r.string().max(120),r.number().finite(),r.boolean()])).refine(e=>Object.keys(e).length<=16,"最多 16 个计价属性").transform(e=>Object.fromEntries(Object.entries(e).map(([o,t])=>[o,String(t)]))),U=r.record(D,r.union([r.string().max(120),r.number().finite(),r.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"匹配条件最多 8 个属性"),I=e=>{let o=e.startsWith("-");o&&(e=e.slice(1));let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");let s=BigInt(t)*BigInt("1000000")+BigInt(n.padEnd(6,"0"));return o?-s:s},h=r.array(r.object({upTo:p.nullable(),cost:u}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((o,t)=>{let n=e[t-1]?.upTo;return o.upTo!==null&&(t===0||n!=null&&I(o.upTo)>I(n))}),"阶梯上限必须递增,最后一档为无限"),G=r.object({key:C,match:U,priority:r.number().int().default(0),cost:u.optional(),tiers:h.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"维度需要指定单价或阶梯"),F=r.object({key:C,match:U,factor:p.optional(),add:M.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),k=r.object({units:p.default("1"),cost:u,tiers:h.optional(),dimensions:r.array(G).max(12).optional(),multipliers:r.array(F).max(4).optional()}).strict().superRefine((e,o)=>{let t=e.dimensions??[],n=e.multipliers??[];(new Set(t.map(i=>i.key)).size!==t.length||new Set(n.map(i=>i.key)).size!==n.length)&&o.addIssue({code:"custom",message:"维度和倍率的 ID 不能重复"});for(let[i,a]of t.entries())for(let c of t.slice(i+1))Object.keys(a.match).length===Object.keys(c.match).length&&a.priority===c.priority&&!Object.keys(a.match).some(E=>c.match[E]!==void 0&&c.match[E]!==a.match[E])&&o.addIssue({code:"custom",message:"维度可能同时匹配,请调整优先级"});let s=[e.cost,...(e.tiers??[]).map(i=>i.cost),...t.flatMap(i=>[...i.cost===void 0?[]:[i.cost],...(i.tiers??[]).map(a=>a.cost)])],A=I(e.units);for(let i of s)for(let a=0;a<1<<n.length;a++){let c=n.filter((N,_)=>a&1<<_);if(c.some((N,_)=>c.slice(_+1).some(d=>Object.keys(N.match).some(l=>d.match[l]!==void 0&&d.match[l]!==N.match[l]))))continue;let E=I(i),O=BigInt("1"),f=BigInt("0");for(let[N,_]of n.entries())a&1<<N&&(E*=I(_.factor??"1"),O*=BigInt("1000000"),f+=I(_.add??"0"));let T=(E+f*O)*BigInt("1000000"),m=O*A;(T<BigInt("0")||T%m!==BigInt("0")||T/m>BigInt("999999999999999999"))&&o.addIssue({code:"custom",message:"每个业务单位的最终单价必须非负、在范围内且能精确表示为最多 6 位小数"})}}),re=k.safeExtend({featureKey:B});export{R as a,v as b,x as c,Q as d,b as e,$ as f,V as g,W as h,J as i,u as j,M as k,B as l,ee as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b as o,c as i}from"./chunk-
|
|
1
|
+
import{a,b as o,c as i}from"./chunk-RSKDG2VD.js";import{a as p}from"./chunk-Y2DUFDPV.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as K,b as U,d as D,v as _}from"./chunk-64KBBZD7.js";import{a as z,c as F}from"./chunk-TPFGWBVS.js";import{d as $}from"./chunk-LEDJ6HS3.js";import{i as C,j as m,l as O,m as g}from"./chunk-XRCW5N3J.js";import{b as e}from"./chunk-JX6MARAN.js";var I=m.refine(t=>/[1-9]/.test(t),"Quantity must be positive"),j=e.string().min(1).max(120),R=e.enum(["cap","overflow"]),p=(t,n)=>{let[i,u=""]=t.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(n)+BigInt(u.padEnd(n,"0"))},A=t=>{try{return t()}catch{return!1}},le=e.discriminatedUnion("operation",[e.object({operation:e.literal("quote"),overageBehavior:R.optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g}).strict(),e.object({operation:e.literal("consume"),overageBehavior:R.optional(),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:m,properties:g,idempotencyKey:j}).strict(),e.object({operation:e.literal("reserve"),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g,idempotencyKey:j,expiresInSeconds:e.number().int().min(1).max(86400)}).strict(),e.object({operation:e.literal("confirm"),operationId:e.uuid(),quantity:I,properties:g.optional(),idempotencyKey:j}).strict(),e.object({operation:e.literal("refund"),operationId:e.uuid(),quantity:I,idempotencyKey:j}).strict(),e.object({operation:e.literal("release"),operationId:e.uuid(),idempotencyKey:j}).strict()]),J=e.object({internal_credit_feature_id:e.uuid().nullable(),internal_metered_feature_id:e.uuid(),dimension:e.string().min(1).max(64),counterKey:e.string().min(1).max(240),cycleStart:e.iso.datetime({offset:!0}),unitCost:m,units:I,amount:C,tier:e.number().int().min(1).max(12).nullable()}).strict(),Q=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function N(t,n){let i=t.reduce((u,a)=>u+p(a.units,12),0n)-p(n,12);return t.some(u=>u.funding==="balance")?i>=-100n&&i<=100n:i===0n}var v=e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q.refine(t=>/[1-9]/.test(t)),amount:C}),e.strictObject({funding:e.literal("unbilled"),units:Q.refine(t=>/[1-9]/.test(t))}),e.object({funding:e.literal("prepaid"),sourceId:e.uuid(),units:I,amount:C,pricing:e.array(J).min(1).max(12)}).strict().refine(t=>A(()=>t.pricing.reduce((n,i)=>n+p(i.units,6),0n)===p(t.units,6)&&t.pricing.reduce((n,i)=>n+p(i.amount,12),0n)===p(t.amount,12)&&t.pricing.every(n=>p(n.unitCost,6)*p(n.units,6)===p(n.amount,12))),"Frozen pricing must conserve allocated units and amounts"),e.object({funding:e.literal("postpaid"),invoiceLineId:e.uuid().nullable(),units:I,authorizationId:e.uuid()}).strict()]),B=e.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),de=e.object({allowed:e.boolean(),internal_feature_id:e.uuid(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),reason:B.nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.allowed?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"A quote must conserve its accepted units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0&&/[1-9]/.test(t.quantity):t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Explicit overage behavior must retain the requested quantity"),me=e.object({id:e.uuid(),internal_feature_id:e.uuid(),kind:e.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),createdAt:e.iso.datetime({offset:!0}),reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:e.iso.datetime({offset:!0}).nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.accepted?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"An operation must conserve its requested units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0:t.kind==="consume"&&t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(t=>/[1-9]/.test(t.quantity)||t.kind==="consume","Only consumption can record a zero cost event").refine(t=>t.allocations.every(n=>n.funding!=="postpaid"||n.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(t=>t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null)&&(t.kind!=="reserve"||!t.accepted||t.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var X=e.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Y=e.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),T=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable()}),ye=T.extend({quantity:m,expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:e.string().min(1).max(120),properties:g.refine(t=>Object.keys(t).length<=13&&!Object.keys(t).some(n=>n.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),V=T.extend({operationId:e.uuid().nullable(),usage:m,capacity:X.nullable(),remaining:Y.nullable(),withinLimit:e.boolean(),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}).strict().superRefine((t,n)=>{let i=u=>{let a=u.startsWith("-"),[s,r=""]=(a?u.slice(1):u).split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(s)*10n**12n+BigInt(r.padEnd(12,"0")))};(t.capacity===null!=(t.remaining===null)||(t.capacity===null?!t.withinLimit:t.remaining===null||i(t.remaining)!==i(t.capacity)-i(t.usage)||t.withinLimit!==i(t.remaining)>=0n)||t.revision===0!=(t.operationId===null)||t.operationId===null!=(t.updatedAt===null))&&n.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var y=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),f=e.iso.datetime({offset:!0}),ee=e.enum(["access","metered","credit"]),q={internal_feature_id:e.uuid(),key:O,name:e.string().min(1).max(120),kind:ee},we=e.object({customerId:e.uuid(),snapshotAt:f,memberships:e.array(e.object({id:e.uuid(),productId:e.string().min(1).max(255),productVersionId:e.uuid(),billingProductVersionId:e.uuid(),version:e.number().int().positive(),key:e.string().min(1).max(64),name:e.string().min(1).max(120),groupId:e.string().max(255).nullable(),membershipType:e.enum(["main","addon"]),status:e.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:e.boolean(),accessEnabled:e.boolean(),renewalChange:e.object({productVersionId:e.uuid(),name:e.string().min(1).max(120),version:e.number().int().positive(),effectiveAt:f,benefitsAppliedAt:f.nullable(),timing:e.enum(["immediate","renewal"]),changeKind:e.enum(["plan","seats","quantity"]),feature:e.strictObject({internal_feature_id:e.uuid(),name:e.string().min(1).max(80),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).optional(),seat:e.object({key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).strict().nullable(),status:e.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(t=>t.changeKind==="seats"==(t.seat!==null)&&t.changeKind==="quantity"==(t.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:e.object({phase:e.enum(["paid","trial"]),startsAt:f,endsAt:f.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:e.boolean(),balances:e.array(e.object({...q,usageType:e.enum(["consumable","non_consumable"]).nullable(),accessible:e.boolean(),unlimited:e.boolean(),available:y,held:y,debt:y,nextExpiresAt:f.nullable(),usage:V.nullable()}).strict().refine(t=>t.kind==="metered"==(t.usageType!==null)&&(t.accessible||t.available==="0"&&t.held==="0")&&(t.usageType==="non_consumable"?t.usage!==null&&t.usage.internal_feature_id===t.internal_feature_id&&t.unlimited===(t.usage.capacity===null)&&t.available===(t.usage.remaining===null||t.usage.remaining.startsWith("-")?"0":t.usage.remaining)&&t.held==="0"&&t.debt==="0":t.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:e.boolean()}).strict(),Z=e.enum(["source","usage","transaction","invoice","debt","settlement"]),E=e.object({at:f,id:e.uuid(),type:Z}).strict(),ke=e.object({type:Z.nullable(),resourceKey:O.optional(),kind:e.enum(["purchase","refund"]).optional(),topup:e.boolean().optional(),from:e.iso.date().nullable(),to:e.iso.date().nullable(),after:E.nullable(),limit:e.number().int().min(1).max(50)}).strict().refine(t=>!t.from||!t.to||t.from<=t.to,"Date range is reversed"),w={id:e.uuid(),occurredAt:f},te=e.discriminatedUnion("type",[e.strictObject({...w,type:e.literal("invoice"),status:e.string().min(1).max(80),paid:y,refunded:y,currency:z,externalId:e.string().nullable()}),e.object({...w,...q,type:e.literal("source"),reason:e.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:y,unlimited:e.boolean(),status:e.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:f,expiresAt:f.nullable(),orderId:e.uuid().nullable(),parentSourceId:e.uuid().nullable()}).strict(),e.object({...w,type:e.literal("usage"),internal_feature_id:e.uuid(),name:e.string().min(1).max(120),kind:e.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),properties:g,reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:f.nullable(),charges:e.array(e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q,amount:y}),e.strictObject({funding:e.literal("unbilled"),units:Q}),e.object({...q,funding:e.literal("prepaid"),amount:y}).strict(),e.object({funding:e.literal("postpaid"),invoiceId:e.uuid(),invoiceLineId:e.uuid(),authorizationId:e.uuid(),units:m,currency:z}).strict()])).max(500)}).strict().refine(t=>(t.kind==="set_usage"||t.kind==="consume"&&t.quantity==="0"?t.accepted&&t.reason===null&&t.charges.length===0&&t.reservationStatus===null:t.accepted?t.reason===null&&t.charges.length>0:t.reason!==null&&t.charges.length===0)&&t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),e.object({...w,type:e.literal("transaction"),purpose:e.enum(["product","invoice"]),productVersionId:e.uuid().nullable(),productName:e.string().min(1).max(120).nullable(),productVersion:e.number().int().positive().nullable(),invoiceId:e.uuid().nullable(),orderId:e.uuid(),originalId:e.uuid().nullable(),kind:e.enum(["purchase","refund"]),amountMinor:e.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(t=>t.currency===null==(t.amountMinor===null)&&(t.purpose==="product"?t.productVersionId!==null&&t.productName!==null&&t.productVersion!==null&&t.invoiceId===null:t.productVersionId===null&&t.productName===null&&t.productVersion===null&&t.invoiceId!==null)&&t.kind==="refund"==(t.originalId!==null)&&(t.kind!=="refund"||t.amountMinor===null||t.amountMinor>0),"Payment fact provenance is incomplete"),e.object({...w,...q,type:e.literal("debt"),sourceId:e.uuid(),transactionId:e.uuid(),amount:y}).strict(),e.object({...w,...q,type:e.literal("settlement"),sourceId:e.uuid(),debtId:e.uuid(),kind:e.enum(["payment","usage_refund","payment_return"]),amount:y}).strict()]),je=e.object({customerId:e.uuid(),rows:e.array(te).max(50),nextCursor:E.nullable()}).strict().refine(t=>new Set(t.rows.map(n=>n.type+n.id)).size===t.rows.length,"A page cannot repeat a fact").refine(t=>{let n=t.rows.at(-1);return!t.nextCursor||!!(n&&n.id===t.nextCursor.id&&n.type===t.nextCursor.type&&n.occurredAt===t.nextCursor.at)},"Cursor must name the final displayed fact");var Ce=e.discriminatedUnion("kind",[e.object({kind:e.literal("ledger"),cursor:E}).strict(),e.object({kind:e.literal("billing"),cursor:e.uuid()}).strict()]),ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ie=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),e.union([e.string().max(500),e.boolean(),e.array(e.string().max(500)).max(50)])).refine(t=>Object.keys(t).length<=40,"Too many answers"),re=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function L(t,n=0){return n>20?!0:!!t&&typeof t=="object"&&(Array.isArray(t)?t.some(i=>L(i,n+1)):Object.entries(t).some(([i,u])=>["__proto__","constructor","prototype"].includes(i)||re.test(i)||L(u,n+1)))}var ae=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ze=e.record(ne,$).refine(t=>Object.keys(t).length<=20,"Too many parameters").refine(t=>!L(t)&&!ae.test(JSON.stringify(t)),"Credentials cannot be screen parameters");var W=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oe=e.array(e.object({variable:W,componentId:W,required:e.boolean()}).strict()).max(40).refine(t=>new Set(t.map(n=>n.variable)).size===t.length&&new Set(t.map(n=>n.componentId)).size===t.length,"Input bindings must be unique"),Re=e.object({bindings:oe,answers:ie,values:e.record(e.string(),$).optional()}).strict();function H(t,n,i=1){if(t==="free")return"";if(t==="one_time")return n.startsWith("zh")?" · 一次付款":" · one-time";let u=n.split("-")[0]??"en",a={zh:["/月","/年"],en:["/month","/year"],ja:["/月","/年"],ko:["/월","/년"],es:["/mes","/año"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/mês","/ano"],it:["/mese","/anno"],ar:["/شهر","/سنة"]},s={zh:"周",en:"week",ja:"週",ko:"주",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"أسبوع"},r=t==="week"?`/${s[u]??s.en}`:(a[u]??a.en)[t==="month"?0:1];return i===1?r:`/${i} ${r.slice(1)}${u==="en"?"s":""}`}function De(t,n){let i=[],u={};_(t,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker")return;let s=a.bind?.plan?[a.bind.plan]:[];a.bind?.picker&&_(t,r=>{if(r.type==="plan_picker"&&r.id===a.bind?.picker&&s.push(...r.planIds??[]),r.type==="stack"&&r.interaction?.type==="select"&&r.interaction.pickerId===a.bind?.picker)for(let o of r.children)o.type==="stack"&&o.bind?.plan&&s.push(o.bind.plan)}),s.length||i.push(`Quantity control ${a.id} needs a Product binding`);for(let r of new Set(s)){let o=n[r]?.prepaid?.find(c=>c.internalFeatureId===a.internalFeatureId)?.terms,d=u[r]??=new Set;(!o||d.has(a.internalFeatureId)||a.minimumQuantity<o.minimumQuantity||a.maximumQuantity>o.maximumQuantity)&&i.push(`Quantity control ${a.id} must match its Product's prepaid Feature and bounds`),d.add(a.internalFeatureId)}});for(let[a,s]of Object.entries(n))for(let r of s.prepaid??[])u[a]?.has(r.internalFeatureId)||i.push(`Product ${a} needs a quantity control for ${r.internalFeatureId}`);return i}function Ke(t,n,i,u){let a=u.plans[n];if(!a?.available)throw new Error("Selected Product is unavailable");let s={};if(_(t,r=>{if(r.hidden)return!1;if(r.type!=="quantity_picker"||r.hidden||(r.bind?.plan??(r.bind?.picker?i[r.bind.picker]:void 0))!==n)return;if(u.quantities?.[r.id]?.available===!1)throw new Error("This prepaid Feature is unavailable");let d=a.prepaid?.find(l=>l.internalFeatureId===r.internalFeatureId)?.terms,c=i[r.id];if(!d||typeof c!="number"||!Number.isSafeInteger(c)||c<Math.max(d.minimumQuantity,r.minimumQuantity)||c>Math.min(d.maximumQuantity,r.maximumQuantity)||(c-r.minimumQuantity)%r.step!==0||s[r.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");s[r.internalFeatureId]=c}),(a.prepaid??[]).some(r=>s[r.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return s}function ue(t,n,i){let u=t.terms.prices.find(a=>a.currency===n);if(!u||i<t.terms.minimumQuantity||i>t.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:U({quantity:i,unitAmountMinor:u.amountMinor,...u.pricing?{pricing:u.pricing}:{}}),allowance:D(t.includedAmount,t.terms.units,i)}}function Ne(t,n,i,u){let a=!1;if(_(t,o=>{o.type==="quantity_picker"&&(a=!0)}),!a)return n;let s=structuredClone(n);s.quantities={};let r=new Map;_(t,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let d=o.bind?.plan??(o.bind?.picker?i[o.bind.picker]??s.pickers[o.bind.picker]?.selected:void 0),c=typeof d=="string"?s.plans[d]:void 0,l=c?.prepaid?.find(G=>G.internalFeatureId===o.internalFeatureId),k=Math.max(o.minimumQuantity,l?.terms.minimumQuantity??0),x=Math.min(o.maximumQuantity,l?.terms.maximumQuantity??0),b=i[o.id]??o.defaultQuantity,h=typeof b=="number"&&Number.isSafeInteger(b)?b:o.defaultQuantity,S=!!l&&!!c?.available&&n.quantities?.[o.id]?.available!==!1&&h>=k&&h<=x&&(h-o.minimumQuantity)%o.step===0,P=s.quantities[o.id]={minimum:k,maximum:Math.max(k,x),step:o.step,value:h,label:"",available:S};if(!S||!l||!c?.currency||c.amountMinor===void 0)return;let M=ue(l,c.currency,h);P.label=`${new Intl.NumberFormat(u).format(Number(M.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?H(l.reset,u,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,M.amountMinor!==0&&r.set(String(d),(r.get(String(d))??c.amountMinor)+M.amountMinor)});for(let[o,d]of r){let c=s.plans[o];if(!c?.currency)continue;let l=F(d,c.currency,u);c.price=l;for(let[k,x]of Object.entries(s.nodes)){let b=K(t,k),h=S=>{if(S.price&&(S.price={...S.price,current:l,original:null}),b?.type==="text"){let P=t.strings.locales[u]?.[b.text]??t.strings.locales[t.strings.defaultLocale]?.[b.text];P?.includes("{{plan.price")&&(S.text=P.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,F(Math.round(d/((c.interval==="year"?12:1)*(c.intervalCount??1))),c.currency,u)))}};x.byPlan?.[o]&&h(x.byPlan[o]),(x.base.planVersionId===o||b&&"bind"in b&&b.bind?.plan===o)&&h(x.base)}}return s}export{le as a,J as b,Q as c,de as d,me as e,T as f,ye as g,V as h,y as i,we as j,ke as k,je as l,Ce as m,ie as n,ze as o,oe as p,Re as q,H as r,De as s,Ke as t,Ne as u};
|
|
1
|
+
import{C as K,b as U,d as D,v as _}from"./chunk-NTYIQ5YC.js";import{a as z,c as F}from"./chunk-2PY7INHO.js";import{d as $}from"./chunk-T7AK4QLG.js";import{i as C,j as m,l as O,m as g}from"./chunk-LB2ZRTRA.js";import{b as e}from"./chunk-COMZFFUA.js";var I=m.refine(t=>/[1-9]/.test(t),"Quantity must be positive"),j=e.string().min(1).max(120),R=e.enum(["cap","overflow"]),p=(t,n)=>{let[i,u=""]=t.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(n)+BigInt(u.padEnd(n,"0"))},A=t=>{try{return t()}catch{return!1}},le=e.discriminatedUnion("operation",[e.object({operation:e.literal("quote"),overageBehavior:R.optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g}).strict(),e.object({operation:e.literal("consume"),overageBehavior:R.optional(),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:m,properties:g,idempotencyKey:j}).strict(),e.object({operation:e.literal("reserve"),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g,idempotencyKey:j,expiresInSeconds:e.number().int().min(1).max(86400)}).strict(),e.object({operation:e.literal("confirm"),operationId:e.uuid(),quantity:I,properties:g.optional(),idempotencyKey:j}).strict(),e.object({operation:e.literal("refund"),operationId:e.uuid(),quantity:I,idempotencyKey:j}).strict(),e.object({operation:e.literal("release"),operationId:e.uuid(),idempotencyKey:j}).strict()]),J=e.object({internal_credit_feature_id:e.uuid().nullable(),internal_metered_feature_id:e.uuid(),dimension:e.string().min(1).max(64),counterKey:e.string().min(1).max(240),cycleStart:e.iso.datetime({offset:!0}),unitCost:m,units:I,amount:C,tier:e.number().int().min(1).max(12).nullable()}).strict(),Q=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function N(t,n){let i=t.reduce((u,a)=>u+p(a.units,12),0n)-p(n,12);return t.some(u=>u.funding==="balance")?i>=-100n&&i<=100n:i===0n}var v=e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q.refine(t=>/[1-9]/.test(t)),amount:C}),e.strictObject({funding:e.literal("unbilled"),units:Q.refine(t=>/[1-9]/.test(t))}),e.object({funding:e.literal("prepaid"),sourceId:e.uuid(),units:I,amount:C,pricing:e.array(J).min(1).max(12)}).strict().refine(t=>A(()=>t.pricing.reduce((n,i)=>n+p(i.units,6),0n)===p(t.units,6)&&t.pricing.reduce((n,i)=>n+p(i.amount,12),0n)===p(t.amount,12)&&t.pricing.every(n=>p(n.unitCost,6)*p(n.units,6)===p(n.amount,12))),"Frozen pricing must conserve allocated units and amounts"),e.object({funding:e.literal("postpaid"),invoiceLineId:e.uuid().nullable(),units:I,authorizationId:e.uuid()}).strict()]),B=e.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),de=e.object({allowed:e.boolean(),internal_feature_id:e.uuid(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),reason:B.nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.allowed?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"A quote must conserve its accepted units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0&&/[1-9]/.test(t.quantity):t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Explicit overage behavior must retain the requested quantity"),me=e.object({id:e.uuid(),internal_feature_id:e.uuid(),kind:e.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),createdAt:e.iso.datetime({offset:!0}),reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:e.iso.datetime({offset:!0}).nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.accepted?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"An operation must conserve its requested units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0:t.kind==="consume"&&t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(t=>/[1-9]/.test(t.quantity)||t.kind==="consume","Only consumption can record a zero cost event").refine(t=>t.allocations.every(n=>n.funding!=="postpaid"||n.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(t=>t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null)&&(t.kind!=="reserve"||!t.accepted||t.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var X=e.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Y=e.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),T=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable()}),ye=T.extend({quantity:m,expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:e.string().min(1).max(120),properties:g.refine(t=>Object.keys(t).length<=13&&!Object.keys(t).some(n=>n.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),V=T.extend({operationId:e.uuid().nullable(),usage:m,capacity:X.nullable(),remaining:Y.nullable(),withinLimit:e.boolean(),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}).strict().superRefine((t,n)=>{let i=u=>{let a=u.startsWith("-"),[s,r=""]=(a?u.slice(1):u).split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(s)*10n**12n+BigInt(r.padEnd(12,"0")))};(t.capacity===null!=(t.remaining===null)||(t.capacity===null?!t.withinLimit:t.remaining===null||i(t.remaining)!==i(t.capacity)-i(t.usage)||t.withinLimit!==i(t.remaining)>=0n)||t.revision===0!=(t.operationId===null)||t.operationId===null!=(t.updatedAt===null))&&n.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var y=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),f=e.iso.datetime({offset:!0}),ee=e.enum(["access","metered","credit"]),q={internal_feature_id:e.uuid(),key:O,name:e.string().min(1).max(120),kind:ee},we=e.object({customerId:e.uuid(),snapshotAt:f,memberships:e.array(e.object({id:e.uuid(),productId:e.string().min(1).max(255),productVersionId:e.uuid(),billingProductVersionId:e.uuid(),version:e.number().int().positive(),key:e.string().min(1).max(64),name:e.string().min(1).max(120),groupId:e.string().max(255).nullable(),membershipType:e.enum(["main","addon"]),status:e.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:e.boolean(),accessEnabled:e.boolean(),renewalChange:e.object({productVersionId:e.uuid(),name:e.string().min(1).max(120),version:e.number().int().positive(),effectiveAt:f,benefitsAppliedAt:f.nullable(),timing:e.enum(["immediate","renewal"]),changeKind:e.enum(["plan","seats","quantity"]),feature:e.strictObject({internal_feature_id:e.uuid(),name:e.string().min(1).max(80),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).optional(),seat:e.object({key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).strict().nullable(),status:e.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(t=>t.changeKind==="seats"==(t.seat!==null)&&t.changeKind==="quantity"==(t.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:e.object({phase:e.enum(["paid","trial"]),startsAt:f,endsAt:f.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:e.boolean(),balances:e.array(e.object({...q,usageType:e.enum(["consumable","non_consumable"]).nullable(),accessible:e.boolean(),unlimited:e.boolean(),available:y,held:y,debt:y,nextExpiresAt:f.nullable(),usage:V.nullable()}).strict().refine(t=>t.kind==="metered"==(t.usageType!==null)&&(t.accessible||t.available==="0"&&t.held==="0")&&(t.usageType==="non_consumable"?t.usage!==null&&t.usage.internal_feature_id===t.internal_feature_id&&t.unlimited===(t.usage.capacity===null)&&t.available===(t.usage.remaining===null||t.usage.remaining.startsWith("-")?"0":t.usage.remaining)&&t.held==="0"&&t.debt==="0":t.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:e.boolean()}).strict(),Z=e.enum(["source","usage","transaction","invoice","debt","settlement"]),E=e.object({at:f,id:e.uuid(),type:Z}).strict(),ke=e.object({type:Z.nullable(),resourceKey:O.optional(),kind:e.enum(["purchase","refund"]).optional(),topup:e.boolean().optional(),from:e.iso.date().nullable(),to:e.iso.date().nullable(),after:E.nullable(),limit:e.number().int().min(1).max(50)}).strict().refine(t=>!t.from||!t.to||t.from<=t.to,"Date range is reversed"),w={id:e.uuid(),occurredAt:f},te=e.discriminatedUnion("type",[e.strictObject({...w,type:e.literal("invoice"),status:e.string().min(1).max(80),paid:y,refunded:y,currency:z,externalId:e.string().nullable()}),e.object({...w,...q,type:e.literal("source"),reason:e.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:y,unlimited:e.boolean(),status:e.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:f,expiresAt:f.nullable(),orderId:e.uuid().nullable(),parentSourceId:e.uuid().nullable()}).strict(),e.object({...w,type:e.literal("usage"),internal_feature_id:e.uuid(),name:e.string().min(1).max(120),kind:e.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),properties:g,reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:f.nullable(),charges:e.array(e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q,amount:y}),e.strictObject({funding:e.literal("unbilled"),units:Q}),e.object({...q,funding:e.literal("prepaid"),amount:y}).strict(),e.object({funding:e.literal("postpaid"),invoiceId:e.uuid(),invoiceLineId:e.uuid(),authorizationId:e.uuid(),units:m,currency:z}).strict()])).max(500)}).strict().refine(t=>(t.kind==="set_usage"||t.kind==="consume"&&t.quantity==="0"?t.accepted&&t.reason===null&&t.charges.length===0&&t.reservationStatus===null:t.accepted?t.reason===null&&t.charges.length>0:t.reason!==null&&t.charges.length===0)&&t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),e.object({...w,type:e.literal("transaction"),purpose:e.enum(["product","invoice"]),productVersionId:e.uuid().nullable(),productName:e.string().min(1).max(120).nullable(),productVersion:e.number().int().positive().nullable(),invoiceId:e.uuid().nullable(),orderId:e.uuid(),originalId:e.uuid().nullable(),kind:e.enum(["purchase","refund"]),amountMinor:e.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(t=>t.currency===null==(t.amountMinor===null)&&(t.purpose==="product"?t.productVersionId!==null&&t.productName!==null&&t.productVersion!==null&&t.invoiceId===null:t.productVersionId===null&&t.productName===null&&t.productVersion===null&&t.invoiceId!==null)&&t.kind==="refund"==(t.originalId!==null)&&(t.kind!=="refund"||t.amountMinor===null||t.amountMinor>0),"Payment fact provenance is incomplete"),e.object({...w,...q,type:e.literal("debt"),sourceId:e.uuid(),transactionId:e.uuid(),amount:y}).strict(),e.object({...w,...q,type:e.literal("settlement"),sourceId:e.uuid(),debtId:e.uuid(),kind:e.enum(["payment","usage_refund","payment_return"]),amount:y}).strict()]),je=e.object({customerId:e.uuid(),rows:e.array(te).max(50),nextCursor:E.nullable()}).strict().refine(t=>new Set(t.rows.map(n=>n.type+n.id)).size===t.rows.length,"A page cannot repeat a fact").refine(t=>{let n=t.rows.at(-1);return!t.nextCursor||!!(n&&n.id===t.nextCursor.id&&n.type===t.nextCursor.type&&n.occurredAt===t.nextCursor.at)},"Cursor must name the final displayed fact");var Ce=e.discriminatedUnion("kind",[e.object({kind:e.literal("ledger"),cursor:E}).strict(),e.object({kind:e.literal("billing"),cursor:e.uuid()}).strict()]),ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ie=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),e.union([e.string().max(500),e.boolean(),e.array(e.string().max(500)).max(50)])).refine(t=>Object.keys(t).length<=40,"Too many answers"),re=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function L(t,n=0){return n>20?!0:!!t&&typeof t=="object"&&(Array.isArray(t)?t.some(i=>L(i,n+1)):Object.entries(t).some(([i,u])=>["__proto__","constructor","prototype"].includes(i)||re.test(i)||L(u,n+1)))}var ae=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ze=e.record(ne,$).refine(t=>Object.keys(t).length<=20,"Too many parameters").refine(t=>!L(t)&&!ae.test(JSON.stringify(t)),"Credentials cannot be screen parameters");var W=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oe=e.array(e.object({variable:W,componentId:W,required:e.boolean()}).strict()).max(40).refine(t=>new Set(t.map(n=>n.variable)).size===t.length&&new Set(t.map(n=>n.componentId)).size===t.length,"Input bindings must be unique"),Re=e.object({bindings:oe,answers:ie,values:e.record(e.string(),$).optional()}).strict();function H(t,n,i=1){if(t==="free")return"";if(t==="one_time")return n.startsWith("zh")?" · 一次付款":" · one-time";let u=n.split("-")[0]??"en",a={zh:["/月","/年"],en:["/month","/year"],ja:["/月","/年"],ko:["/월","/년"],es:["/mes","/año"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/mês","/ano"],it:["/mese","/anno"],ar:["/شهر","/سنة"]},s={zh:"周",en:"week",ja:"週",ko:"주",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"أسبوع"},r=t==="week"?`/${s[u]??s.en}`:(a[u]??a.en)[t==="month"?0:1];return i===1?r:`/${i} ${r.slice(1)}${u==="en"?"s":""}`}function De(t,n){let i=[],u={};_(t,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker")return;let s=a.bind?.plan?[a.bind.plan]:[];a.bind?.picker&&_(t,r=>{if(r.type==="plan_picker"&&r.id===a.bind?.picker&&s.push(...r.planIds??[]),r.type==="stack"&&r.interaction?.type==="select"&&r.interaction.pickerId===a.bind?.picker)for(let o of r.children)o.type==="stack"&&o.bind?.plan&&s.push(o.bind.plan)}),s.length||i.push(`Quantity control ${a.id} needs a Product binding`);for(let r of new Set(s)){let o=n[r]?.prepaid?.find(c=>c.internalFeatureId===a.internalFeatureId)?.terms,d=u[r]??=new Set;(!o||d.has(a.internalFeatureId)||a.minimumQuantity<o.minimumQuantity||a.maximumQuantity>o.maximumQuantity)&&i.push(`Quantity control ${a.id} must match its Product's prepaid Feature and bounds`),d.add(a.internalFeatureId)}});for(let[a,s]of Object.entries(n))for(let r of s.prepaid??[])u[a]?.has(r.internalFeatureId)||i.push(`Product ${a} needs a quantity control for ${r.internalFeatureId}`);return i}function Ke(t,n,i,u){let a=u.plans[n];if(!a?.available)throw new Error("Selected Product is unavailable");let s={};if(_(t,r=>{if(r.hidden)return!1;if(r.type!=="quantity_picker"||r.hidden||(r.bind?.plan??(r.bind?.picker?i[r.bind.picker]:void 0))!==n)return;if(u.quantities?.[r.id]?.available===!1)throw new Error("This prepaid Feature is unavailable");let d=a.prepaid?.find(l=>l.internalFeatureId===r.internalFeatureId)?.terms,c=i[r.id];if(!d||typeof c!="number"||!Number.isSafeInteger(c)||c<Math.max(d.minimumQuantity,r.minimumQuantity)||c>Math.min(d.maximumQuantity,r.maximumQuantity)||(c-r.minimumQuantity)%r.step!==0||s[r.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");s[r.internalFeatureId]=c}),(a.prepaid??[]).some(r=>s[r.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return s}function ue(t,n,i){let u=t.terms.prices.find(a=>a.currency===n);if(!u||i<t.terms.minimumQuantity||i>t.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:U({quantity:i,unitAmountMinor:u.amountMinor,...u.pricing?{pricing:u.pricing}:{}}),allowance:D(t.includedAmount,t.terms.units,i)}}function Ne(t,n,i,u){let a=!1;if(_(t,o=>{o.type==="quantity_picker"&&(a=!0)}),!a)return n;let s=structuredClone(n);s.quantities={};let r=new Map;_(t,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let d=o.bind?.plan??(o.bind?.picker?i[o.bind.picker]??s.pickers[o.bind.picker]?.selected:void 0),c=typeof d=="string"?s.plans[d]:void 0,l=c?.prepaid?.find(G=>G.internalFeatureId===o.internalFeatureId),k=Math.max(o.minimumQuantity,l?.terms.minimumQuantity??0),x=Math.min(o.maximumQuantity,l?.terms.maximumQuantity??0),b=i[o.id]??o.defaultQuantity,h=typeof b=="number"&&Number.isSafeInteger(b)?b:o.defaultQuantity,S=!!l&&!!c?.available&&n.quantities?.[o.id]?.available!==!1&&h>=k&&h<=x&&(h-o.minimumQuantity)%o.step===0,P=s.quantities[o.id]={minimum:k,maximum:Math.max(k,x),step:o.step,value:h,label:"",available:S};if(!S||!l||!c?.currency||c.amountMinor===void 0)return;let M=ue(l,c.currency,h);P.label=`${new Intl.NumberFormat(u).format(Number(M.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?H(l.reset,u,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,M.amountMinor!==0&&r.set(String(d),(r.get(String(d))??c.amountMinor)+M.amountMinor)});for(let[o,d]of r){let c=s.plans[o];if(!c?.currency)continue;let l=F(d,c.currency,u);c.price=l;for(let[k,x]of Object.entries(s.nodes)){let b=K(t,k),h=S=>{if(S.price&&(S.price={...S.price,current:l,original:null}),b?.type==="text"){let P=t.strings.locales[u]?.[b.text]??t.strings.locales[t.strings.defaultLocale]?.[b.text];P?.includes("{{plan.price")&&(S.text=P.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,F(Math.round(d/((c.interval==="year"?12:1)*(c.intervalCount??1))),c.currency,u)))}};x.byPlan?.[o]&&h(x.byPlan[o]),(x.base.planVersionId===o||b&&"bind"in b&&b.bind?.plan===o)&&h(x.base)}}return s}export{le as a,J as b,Q as c,de as d,me as e,T as f,ye as g,V as h,y as i,we as j,ke as k,je as l,Ce as m,ie as n,ze as o,oe as p,Re as q,H as r,De as s,Ke as t,Ne as u};
|