@tinkerlandai/longplay-sdk 0.10.18 → 0.10.19
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/README.md +9 -3
- package/README.zh-CN.md +1 -1
- package/dist/{ai-usage-D7BUuP1H.d.ts → ai-usage-DPGx5otD.d.ts} +3 -3
- package/dist/{api-CIbhe8RY.d.ts → api-G8EA_ueL.d.ts} +3596 -200
- package/dist/chunk-2JBNOE2D.js +1 -0
- package/dist/chunk-4SWGHICJ.js +17 -0
- package/dist/chunk-5OD42XQS.js +1 -0
- package/dist/{chunk-OMHZBCS3.js → chunk-A7U4Z6EH.js} +1 -1
- package/dist/{chunk-LHBBSD77.js → chunk-CCRBXW4M.js} +1 -1
- package/dist/chunk-DVKZLOS7.js +1 -0
- package/dist/{chunk-ML6EHT43.js → chunk-EDVR7FPD.js} +1 -1
- package/dist/chunk-FISFN5IY.js +1 -0
- package/dist/chunk-GSFNAB3W.js +6 -0
- package/dist/{chunk-26HU2HXU.js → chunk-KHIQQNTR.js} +1 -1
- package/dist/{chunk-6HWNW6FJ.js → chunk-LNSFRQ6G.js} +1 -1
- package/dist/chunk-W2Z3UVW3.js +1 -0
- package/dist/{chunk-T5COWMDA.js → chunk-XIYNQHN7.js} +1 -1
- package/dist/{chunk-P6HCD5OQ.js → chunk-XXBN76NP.js} +1 -1
- package/dist/{chunk-E4LUW6KP.js → chunk-YNMSSQQY.js} +1 -1
- package/dist/{content-DLYNJIEB.js → content-E2OWWKDG.js} +1 -1
- package/dist/{customer-page-km5f1PJZ.d.ts → customer-page-BV5EvCUY.d.ts} +20 -0
- package/dist/{funnel-local-client-CAuNpJ-e.d.ts → funnel-local-client-DjvVzCfH.d.ts} +14039 -312
- package/dist/{funnel-node-evaluation-BLnJp8vj.d.ts → funnel-node-evaluation-D9FwkMa3.d.ts} +425 -1
- package/dist/funnel-process-client-bO9Wfumi.d.ts +62372 -0
- package/dist/funnel-runtime-host-FOM4Z7ZK.js +1 -0
- package/dist/index.d.ts +322 -23334
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +2 -2
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/paywall-OUIB7SVI.js +1 -0
- package/dist/popup.d.ts +2 -2
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +41 -38098
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-ZNELQB64.js +1 -0
- package/dist/server.d.ts +6860 -298
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-4ZUMMPHV.js +0 -1
- package/dist/chunk-EEZLS2YP.js +0 -1
- package/dist/chunk-JVQVQHV2.js +0 -6
- package/dist/chunk-KYXX676W.js +0 -1
- package/dist/chunk-LC2VUKYM.js +0 -1
- package/dist/chunk-N4HZ55YU.js +0 -1
- package/dist/chunk-PFHS7HK3.js +0 -17
- package/dist/chunk-VVW2J2GL.js +0 -1
- package/dist/funnel-process-client-C9EIwNTr.d.ts +0 -20575
- package/dist/funnel-runtime-host-FVOUCR35.js +0 -1
- package/dist/paywall-6Q3VLXXL.js +0 -1
- package/dist/screen-renderer-IZ3VJGU6.js +0 -1
- package/dist/{coupon-fA1QujHt.d.ts → coupon-Btz_KFKp.d.ts} +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as mn,c as pn,d as gn,e as yn,f as wn}from"./chunk-FISFN5IY.js";import{a as te,b as Y}from"./chunk-YNMSSQQY.js";import{a as m}from"./chunk-KHIQQNTR.js";import{a as dn,b as fn,c as Ce}from"./chunk-CCRBXW4M.js";import{$ as Re,$a as an,Ca as ne,Da as nn,Ga as tn,Ha as rn,Ma as Te,Na as on,Z as je,aa as Je,ab as sn,ba as He,ca as ze,db as un,eb as ln,hb as cn,kb as le,la as Q,ma as Qe,na as j,o as Ue,oa as Ye,pa as Oe,q as ue,qa as M,sa as $e,ta as We,ua as Ze,va as Xe,wa as en}from"./chunk-GSFNAB3W.js";import{C as ke,J as Ge,M as Be,Na as Ke,P as ve,a as qe}from"./chunk-4SWGHICJ.js";function zn(e){let n=null,t=null,a=0,d=0,w=new Set,f=null,o=null,g=new Set,i=()=>{for(let s of g)try{s()}catch{}},l={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(s,r)=>{!w.has(s)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(s,structuredClone(r),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(s,r)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(s),structuredClone(r),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?s=>e.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},u=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function c(s,r=new Set){return w.has(s)?!f||!f.features[s]||["unknownFeature","cyclicPrerequisite"].includes(f.features[s].source):r.has(s)?!1:(r.add(s),(n?.features[s]?.rules??[]).some(p=>[...p.parentConditions??[],...(p.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>c(v.id,r))))}let h=s=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,l.features=n.features),w.has(s)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?u():structuredClone(f.features[s]??u()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!f||c(s)?u():structuredClone(Be(s,l))};async function A(){if(!n||!w.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(w.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=d;if(o?.revision===s)return o.loading;let r=a,p=n,v=[...w],C=(async()=>{let S=ze.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(r!==a||s!==d||p!==n)){if(e.assertUsable?.(p.generation),S.generation!==p.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(R=>!Object.hasOwn(S.features,R))||Object.keys(S.features).some(R=>!w.has(R)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!S.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=ve.parse({...l.attributes,...S.merchandiseContext})}f=structuredClone(S),l.features={...p.features,...Object.fromEntries(Object.entries(f.features).map(([R,O])=>[R,{defaultValue:O.value}]))},i()}})();o={revision:s,loading:C};try{await C}finally{o?.loading===C&&(o=null)}}function N(){A().catch(s=>{try{e.onError?.(s)}catch{}})}async function x(){if(t)return t;let s=a,r=(async()=>{let p=await e.load(),v="remoteFeatures"in p?Je.parse(p):null,C=v??Re.parse(p);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(s!==a)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===C.generation){let{evaluatedAt:R,expiresAt:O,...D}=n,{evaluatedAt:L,expiresAt:k,...G}=C;if(M(D)!==M(G))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=C.evaluatedAt,n.expiresAt=C.expiresAt,i(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&N(),structuredClone(n)}let S=new Set(v?.remoteFeatures??[]);if([...S].some(R=>Object.hasOwn(C.features,R)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in C&&!n.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),n=structuredClone(C),w=S,f=null,o=null,d++,l.features=n.features,l.savedGroups=Ge(n.savedGroups),l.trackedFeatureUsage={},i(),N(),structuredClone(n)})();t=r;try{return await r}finally{t===r&&(t=null)}}return{init:x,refresh:x,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(s){return g.add(s),()=>{g.delete(s)}},setAttributes(s){let r=ve.parse(s);(l.attributes?.merchandise||l.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=r,d++,f=null,o=null,l.features=n?.features??{},l.trackedFeatureUsage={},i(),N()},evalFeature:h,isOn(s){return h(s).on},isOff(s){return h(s).off},getFeatureValue(s,r){let p=h(s).value;return structuredClone(p===null?r:p)},reset(){a++,d++,t=null,o=null,n=null,f=null,w.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),i()}}}function In(e){let n,t,a=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),d=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw a();let o=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),g=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return"indiana.funnel.commands.v1."+Array.from(g,i=>i.toString(16).padStart(2,"0")).join("")});d.catch(()=>{});async function w(o){try{let g=await d;return await t.request(g,{mode:"exclusive"},()=>o(g))}catch(g){throw g instanceof m?g:a()}}function f(o){let g=n.getItem(o);if(g===null)return{revision:0,entry:null};if(g.length>1048576)throw a();let i=JSON.parse(g);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw a();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>w(f),write:(o,g)=>w(i=>{if(f(i).revision!==o)return null;if(!Number.isSafeInteger(o+1))throw a();return n.setItem(i,JSON.stringify({revision:o+1,entry:g})),o+1})}}function be(e,n){let t=tn.safeParse(n);if(!t.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let a=t.data;if(e.scope&&(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return a}async function Pe(e,n){let t=Xe.parse(n),{artifact:a,environmentId:d}=t.content,w=new te(e.baseUrl??le).origin,f=new te(a.url,w);if(f.origin!==w||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${d}/artifacts/${a.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,g,i=new Promise((u,c)=>{g=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");o.abort(h),c(h)},j.initializationMs)}),l=(async()=>{let u=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(u.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>a.byteLength)throw u.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let c=await dn(u,a.byteLength,{signal:o.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(c,a))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return en(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c)))})();try{return await Promise.race([l,i])}finally{clearTimeout(g)}}var _e=(e,n)=>new m(e,n);function ut(e){return ln(e,_e)}var _n=3,Dn=2e3;function Ln(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function xn(e){for(let n=1;;n++)try{return await e.refresh()}catch(t){if(n===_n||!Ln(t))throw t;await new Promise(a=>setTimeout(a,n*Dn))}}async function De(e,n,{predict:t=!0}={}){let a=n.instruction;if(a?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==a.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let d=null,w;if(t)try{let f=await e.funnel(n.source.id,n.source.versionId);w=f.manifest.generation,d=Vn(e,n,f)}catch{d=null}return w??=e.snapshot?.generation??(await xn(e)).generation,{advance:{policyRevision:a.policyRevision,generation:w},prediction:d}}function Vn(e,n,t){let a=n.instruction;if(a?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==a.policyRevision)return null;let{analyticsConfig:d,remoteFeatures:w,...f}=t.growth,o=an({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:a.policyRevision,document:t.document,payload:Re.parse(f)}),g=Mn(o,t.document,{...n,...a}),i=g.steps.at(-1),l=g.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:n.visit+g.steps.length-1}:null);return l?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:l.nodeId,visit:l.visit,terminal:!g.boundary}:null}function Mn(e,n,t){return cn(e,n,t,_e)}import{z as J}from"zod";var hn=Q.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),vn=J.strictObject({schemaVersion:J.literal(1),scope:qe,runId:J.uuid(),funnelId:J.uuid(),versionId:J.uuid(),processBindingIds:J.record(J.uuid(),J.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:J.strictObject({receiptId:J.uuid(),operationId:J.uuid(),generation:J.number().int().nonnegative()}).optional(),closed:J.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),U=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function Rn(e){let n=0,t=null,a=i=>JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]),d=Promise.resolve();async function w(){let i=await e.read();if(!Number.isSafeInteger(i.revision)||i.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:i.revision,entry:i.entry===null?null:vn.parse(i.entry)}}function f(i){let l=d.then(i);return d=l.catch(()=>{}),l}async function o(i){for(let l=0;l<4;l++){let u=await w();if(u.entry&&t!==null&&a(u.entry)!==t)throw U();let c=i(u.entry,u.revision);if(Se(u.entry,c)){n=u.revision;return}let h=await e.write(u.revision,c);if(h!==null){if(!Number.isSafeInteger(h)||h<=u.revision)throw U();n=h;return}}throw U()}function g(i,l){if(!i||!l)return i;if(i.processBindingIds&&Object.hasOwn(i.processBindingIds,l)){let u={...i.processBindingIds};delete u[l],i={...i,processBindingIds:u}}return i.command?.requestId===l?i.closeCommand?{...i,command:i.closeCommand,closeCommand:void 0}:i.purchase?{...i,command:void 0}:null:i.closeCommand?.requestId===l?{...i,closeCommand:void 0}:i}return{bind(i){let l=JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]);if(t!==null&&t!==l)throw U();t=l},async load(){let i=await w();return n=i.revision,t=i.entry?a(i.entry):null,i.entry},retain(i){let l=vn.parse(i),u=l.command;return!u||t!==null&&a(l)!==t?Promise.reject(U()):(t??=a(l),f(()=>o((c,h)=>{if(c&&!Se(a(c),a(l)))throw U();if(c&&l.processBindingIds){for(let[A,N]of Object.entries(l.processBindingIds))if(c.processBindingIds&&Object.hasOwn(c.processBindingIds,A)&&c.processBindingIds[A]!==N)throw U();c={...c,processBindingIds:{...c.processBindingIds,...l.processBindingIds}}}if(!c){if(h!==n&&u.operation!=="close")throw U();return l}if(!c.command)return{...c,command:u,...u.operation==="close"?{closed:!0}:{}};if(u.operation==="close"&&c.command.operation!=="close"){if(c.command.requestId===u.requestId||c.closeCommand&&!Se(c.closeCommand,u))throw U();return{...c,closeCommand:u,closed:!0}}if(!Se(c.command,u))throw U();return c})))},observePurchase(i,l,u,c){return f(()=>o((h,A)=>{if(!h&&A!==n||h&&a(h)!==a({...i,schemaVersion:1}))throw U();if(h?.purchase&&h.purchase.generation>l.generation)return g(h,c);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw U();return u?!h?.purchase||h.purchase.operationId!==l.operationId?g(h,c):g(h.command?{...h,purchase:void 0}:null,c):g({schemaVersion:1,...i,...h,purchase:l},c)}))},settle(i){return f(()=>o(l=>g(l,i)))}}}function It(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((d,w)=>ce(d,n[w]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),a=Object.entries(n);return t.length===a.length&&t.every(([d,w])=>Object.hasOwn(n,d)&&ce(w,Reflect.get(n,d)))}function Cn(e,n){let t=n&&{...n},a=null,d=0,w=new AbortController;function f(){d++,w.abort(new m("IDENTITY_CHANGED","Run identity changed")),w=new AbortController}let o=!1,g,i=0,l=new Set;return{get scope(){return t},bindScope(u){if(t&&(t.projectId!==u.projectId||t.environment!==u.environment))throw new m("SCOPE_MISMATCH","Run scope changed");t??={...u}},get view(){return a},get generation(){return d},get signal(){return w.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return i},nextRead(){return++i},assertCurrent(u,c="Run identity changed during the request"){if(u!==d||o)throw new m("IDENTITY_CHANGED",c)},assertRun(u){if(a&&(u.id!==a.id||u.source.type!==a.source.type||u.source.id!==a.source.id||u.source.versionId!==a.source.versionId||u.locale!==a.locale||!ce(u.parameters,a.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&u.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(u,c,h,A,N){if(!(u.operation==="review"&&a&&a!==h&&c.run.revision<=a.revision)&&!(a&&c.run.revision===a.revision&&A!==void 0&&A<i)&&(u.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&a&&c.run.nodeId===a.nodeId&&c.run.visit===a.visit&&c.run.revision===a.revision&&(c.run.screen=a.screen,(a.paywall?.quote?.operationId===c.review?.activeOperationId||!a.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=a.paywall)),!(a?.paywall&&c.run.paywall&&a.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(a.paywall.selectionGeneration??0)))){if(!a||c.run.revision>=a.revision)a=c.run;else if(!N)return;if(a)for(let x of l)try{x(structuredClone(a))}catch{}}},identify(u){if(o)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(u))throw new m("INVALID_TOKEN","Customer credential required");f(),g=u},subscribe(u){return l.add(u),()=>l.delete(u)},reset(){o||(o=!0,f(),g=void 0,a=null,l.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function St(e,n,t="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",t)}function Et(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...t}=e;return t}var qn=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function bn({journal:e,state:n,call:t,processIdentity:a}){let d=null,w=null,f=!1,o={command:null,close:null},g=new Set,i,l=null,u=e?e.load().then(s=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=s,!s)return;if(a){if([s.command,s.closeCommand].some(p=>p&&!Object.hasOwn(s.processBindingIds??{},p.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");a.restore(s.processBindingIds??{})}if(n.scope&&(s.scope.projectId!==n.scope.projectId||s.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,f=s.closed===!0,!s.command)return;let r=s.command;d=r.operation==="close"?null:r,w=r.operation==="close"?r:s.closeCommand?.operation==="close"?s.closeCommand:null,w&&(f=!0);for(let p of[d,w])p&&g.add(p.requestId)}):Promise.resolve();u.catch(()=>{});async function c(s){e&&await u;let r=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(s),...a?{processBindingIds:{[s.requestId]:a.binding(s.requestId)}}:{}})}if(r!==n.generation||d!==s&&w!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let p=g.has(s.requestId);g.add(s.requestId);try{return await t(s)}catch(v){throw r===n.generation&&(d===s||w===s)&&!p&&!qn(v)&&(e&&await e.settle(s.requestId),r===n.generation&&x(s)),v}}function h(s){let r=Q.parse(s);if(r.operation==="start"||r.operation==="get"||r.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&r.operation!=="close"){if(d?.requestId===r.requestId)return N(r.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(r.operation==="close"){if(d?.requestId===r.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,w&&JSON.stringify($(w))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original Close");return w??=r,o.close?o.close:A(w,"close")}if(d){if(JSON.stringify($(d))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(o.command)return o.command}else d=r;return A(d,"command")}function A(s,r){let p=c(s);o[r]=p;let v=()=>{o[r]===p&&(o[r]=null)};return p.then(v,v),p}function N(s){return t({operation:"get",settlementRequestId:s})}function x(s){return!s||d!==s&&w!==s?!1:(d===s&&(d=null),w===s&&(w=null),g.delete(s.requestId),!d&&!w&&(l=null),!0)}return{ready:u,get pending(){return d},get closing(){return w},get closeRequested(){return f},get inFlight(){return o.command},get closeFlight(){return o.close},get purchase(){return i},assertBinding(s){if(l&&(s.run.id!==l.runId||s.run.source.id!==l.funnelId||s.run.source.versionId!==l.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,r,p,v){let C=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,S=C&&r.settlement?.state==="settled"&&r.run.pendingRequest?.requestId!==C&&(s.operation==="get"||!f||s.operation==="close"||!["running","waiting"].includes(r.run.status))?C:void 0,R=d?.requestId===S?d:w?.requestId===S?w:void 0;e?.bind({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId});let O=r.run.paywall,D=O??r.purchase,L=D?.operation,k=r.settlement&&(!O||O.purchaseRequestId===r.settlement.requestId)&&(!i||i.operationId===r.settlement.operationId)?r.settlement:void 0,G=L?.operationId??D?.quote?.operationId??k?.operationId,H=D?.receiptId??k?.receiptId,de=O?.selectionGeneration??i?.generation??0;if(e&&G&&H&&s.operation!=="review"&&(!n.view||r.run.revision>=n.view.revision)&&(v===void 0||v>=n.readSequence)&&(!i||de>=i.generation)){let Z={receiptId:H,operationId:G,generation:de},fe=L?.status==="complete"||D?.canReselect===!0;await e.observePurchase({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId},Z,fe,S),n.assertCurrent(p),(!i||Z.generation>=i.generation)&&(v===void 0||v>=n.readSequence)&&(fe?i?.operationId===Z.operationId&&(i=void 0):i=Z)}else e&&S&&await e.settle(S);return n.assertCurrent(p),S?x(R):!1},stop(){f=!0},submit:h,settle:N,reset(){f=!0,d=null,w=null,i=void 0,l=null,o.close=null,g.clear(),o.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=Cn(e.funnelId,e.scope??e.configuration?.scope),a=e.session?.subscribeIdentity(i),d=null,w=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?In(e):void 0),f=w&&Rn(w),o=bn({journal:f,state:t,call:l,processIdentity:e.process});async function g(r){if(e.process)return e.process.request(r);let p=t.generation;t.assertCurrent(p);let v=performance.now()+(e.timeoutMs??35e3),C=t.customerToken??("customerToken"in r?r.customerToken:void 0);if(e.session){let O=t.signal,D,L=()=>{},k=new Promise((G,H)=>{L=()=>H(O.reason),O.addEventListener("abort",L,{once:!0}),D=setTimeout(()=>H(new m("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(p),e.session.access())),k])}finally{clearTimeout(D),O.removeEventListener("abort",L)}}t.assertCurrent(p);let S={...r,...C?{customerToken:C}:{}},R=r.operation==="page_experiments"?Te.parse(S):Q.parse(S);return n.requestWithCredential("funnels",R,e.runToken,{headers:e.serverKey&&!C?{[rn]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function i(){a?.(),t.reset(),o.reset(),d=null,n.dispose()}async function l(r,p){let v=t.generation,C=()=>t.assertCurrent(v);f&&await o.ready,C();let S=t.view,R=be(e,await g(r));if(r.operation==="review"&&!R.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(C(),R.runToken&&R.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let O=r.operation==="get"?r.settlementRequestId:"requestId"in r&&r.operation!=="start"?r.requestId:void 0;if(O&&R.settlement?.requestId!==O)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(R),t.assertRun(R.run),t.bindScope(R.scope);let D=await o.observe(r,R,v,p);return!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r.operation==="get"&&r.settlementRequestId||(C(),["running","waiting"].includes(R.run.status)||o.stop(),t.publish(r,R,S,p,D)),R}let u=o.submit,c=null,h=new WeakMap;function A(r){let p=h.get(r);if(p)return p;let v=x(r);return h.set(r,v),v}let N=!1;async function x(r){let p=await r;if(p.run.instruction?.type!=="evaluate_segment")return p;if(c)return c;N=!0;let v=t.generation,C=(async()=>{for(let S=0;S<32&&p.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return p;let R=p.run;if(p.run.instruction?.type==="evaluate_segment"){let{advance:D}=await De(e.configuration,R,{predict:!1});if(v!==t.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return p;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return l({operation:"get"});let L=!0;De(e.configuration,R).then(({prediction:k})=>{L&&v===t.generation&&!o.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(d=k)}).catch(()=>{});try{p=await u({operation:"commit_segment",requestId:nn(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...D})}finally{L=!1,d=null}}}return p})();c=C;try{return await C}finally{c===C&&(c=null)}}let s={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let r=o.closing??o.pending;return r?structuredClone($(r)):null},get pendingCommands(){return[o.pending,o.closing].filter(r=>r!==null).map(r=>structuredClone($(r)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return f!==void 0},get prediction(){let r=t.view;return d&&r&&!r.stopped&&["running","waiting"].includes(r.status)&&r.id===d.runId&&r.nodeId===d.from.nodeId&&r.visit===d.from.visit&&r.revision===d.from.revision&&!o.closeRequested?structuredClone(d):null},settle:o.settle,get webViewUrl(){return"bundled"},resolvePaywall(r){return Pe(e,r)},async pageExperiments(r,p=[]){let v=t.generation;t.assertCurrent(v);let C=t.view?.id;if(!C)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=on.parse(await g(Te.parse({operation:"page_experiments",release:r,usedReceiptIds:p})));if(t.assertCurrent(v),S.runId!==C||S.scope.projectId!==t.scope?.projectId||S.scope.environment!==t.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(r){return l({operation:"review",...r?{receiptId:r}:{}},t.nextRead())},async get(r,p){f&&await o.ready,p??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let v=t.nextRead();return A(l({operation:"get",...r?{data:r}:{},...p?{purchase:p}:{}},v))},resume(r=t.view?.pendingRequest?.requestId){return r?o.closeRequested?s.settle(r):o.pending?.requestId===r?A(u(o.pending)):A(u({operation:"resume",requestId:r})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(r){return A(u(r))},retry(){return o.closeFlight?o.closeFlight:o.closing?u(o.closing):o.closeRequested&&o.pending?s.settle(o.pending.requestId):o.inFlight?A(o.inFlight):o.pending?A(u(o.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(r){t.identify(r),d=null,n.reset()},subscribe:t.subscribe,reset:i};return s}function Un(e,n,t,a){if(!ke(e,n)||t!==void 0&&n.observation&&n.observation.subject.customerId!==t||a!==void 0&&n.observation!==void 0&&(n.observation.subject.scope.projectId!==a.projectId||n.observation.subject.scope.environment!==a.environment))throw new m("INVALID_RESPONSE","The access requirement or Customer changed");return n}function Sn(e,n,t){if(e.requirement){if(!n)throw new m("INVALID_RESPONSE","The requested access check is missing");Un(e.requirement,n,e.customerId,t)}}import{ZodError as kn}from"zod";function En(e,n,t,a){try{return e.parse(n)}catch(d){throw a&&d instanceof kn?new m(t,a):d}}async function Ee(e,n,t,a={},d){let w=typeof a=="function"?{}:a,f=En(n.request,t,"INVALID_REQUEST",w.request);try{let o=await e(n.path,f,n.method,d),g=typeof a=="function"?a:a.parseResponse;return g?g(n.response,o):En(n.response,o,"INVALID_RESPONSE",w.response)}catch(o){throw o instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(o.commandRequestId??=f.requestId),o}}async function rr(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let t=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),a=Y(e);e.session||a.identify(n.customerToken);let d=null,w=!1,f=null,o=null,g=null,i=null,l=null,u=null,c=null,h=0;function A(){if(w)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function N(){A();let p=ne.resolvePaywall,v=await Ee(a.request,p,{...t,selector:d?{type:"version",versionId:d.id}:t.selector});Sn(t,v.paywall.check,v.scope);let C=await Pe(e,v.paywall);if(A(),n.paywallVersionId?C.id!==n.paywallVersionId:C.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(d&&(!mn(C,d)||C.paywallId!==d.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return d=C,structuredClone(d)}async function x(p){if(A(),i&&p!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let v=f;if(p!=="read"){if(c){if(u===p)return c;throw new m("COMMAND_PENDING","Wait for the original purchase command")}if(u&&u!==p)throw new m("COMMAND_PENDING","Read the original purchase before changing an uncertain command");u=p,h++}let C=u,S=h,R=p==="read"&&c===null,O=p==="read"?ne.readSubscriptionOperation:ne.attach,D=(async()=>{let L=await Ee(a.request,O,{operationId:v.operationId,...p==="read"?{}:{intent:p},...p==="confirm"&&v.merchantTerms?{merchantConfirmation:Ue(v.merchantTerms)}:{}});return pn(L.operation,{operationId:v.operationId,currency:t.commerce.currency},"The purchase operation changed"),A(),f?.operationId!==v.operationId?structuredClone(L.operation):(o=yn(o,L.operation),(p!=="read"||R&&c===null)&&h===S&&u===C&&(u=null),structuredClone(o))})();if(p!=="read"){c=D;let L=()=>{c===D&&(c=null)};D.then(L,L)}return D}let s={get view(){return d?structuredClone(d):null},get quote(){return f?structuredClone(f):null},get operation(){return o?structuredClone(o):null},get webViewUrl(){return"bundled"},get recovery(){return wn({quote:f,operation:o,requestId:l,pending:i!==null||u!==null,destroyed:w})},get pendingCancellation(){return!w&&u==="cancel"},refresh:N,async preview(p){if(A(),!d)throw new m("INVALID_REQUEST","Load the Paywall first");let v=d.document.buttons[p.actionId];if(v?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let C=je(v.product,p.selection,d.capabilities);if(!C)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let S=Ke(d.document.screen,C,p.selection,d.capabilities),R=ne.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:C,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:t.commerce.provider,currency:t.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),O=JSON.stringify(R);if(g&&g!==O&&(i||u||!o||o.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(g===O){if(i)return i;if(f)return structuredClone(f)}g!==O&&(f=null,o=null),g=O,l=R.requestId;let D=(async()=>{let L=ne.previewAttach,k=await Ee(a.request,L,R);return A(),gn(k.quote,{productVersionId:C,featureQuantities:S,currency:t.commerce.currency,provider:t.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=k.quote,o=null,structuredClone(f)})();i=D;try{return await D}finally{i===D&&(i=null)}},confirm:()=>x("confirm"),cancel:()=>x("cancel"),read:()=>x("read"),destroy(){w||(w=!0,r?.(),a.dispose(),d=null,f=null,o=null,g=null,l=null)}},r=e.session?.subscribeIdentity(s.destroy);try{return await N(),s}catch(p){throw s.destroy(),p}}import{z as Jn}from"zod";import{z as ge}from"zod";var Gn=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,Bn=100;function jn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function An(e,n){let t=n===void 0?jn():n,a=new Map,d=0,w=!1,f=!1,o,g;async function i(u){if(!t)return null;let c;try{let h=await Promise.race([Promise.resolve().then(()=>t.getItem(u)),new Promise(A=>{c=setTimeout(()=>A(null),Bn)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(c)}}function l(){if(g)return g;let u=(async()=>{try{let c=await i(`${e}:artifacts`);if(c)return Gn.parse(JSON.parse(c))}catch{}return{}})();return g=u,u.finally(()=>{g===u&&(g=void 0)}),u}return{async readManifest(){return i(e)},writeManifest(u){!t||u.length>oe||new TextEncoder().encode(u).byteLength>oe||(o=u,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;o!==void 0;){let c=o;try{await t.setItem(e,c)}catch{}o===c&&(o=void 0)}}finally{f=!1}})))},async readArtifact(u){let c=(await l())[u],h=Date.now();return c&&h>=c.at&&h-c.at<=j.retentionMs?c.text:void 0},writeArtifact(u,c){if(!t||c.length>oe)return;let h=a.get(u);if(h?.text===c||!h&&a.size>=128)return;let A=new TextEncoder().encode(c).byteLength;d-(h?.byteLength??0)+A>oe||(a.set(u,{text:c,byteLength:A}),d+=A-(h?.byteLength??0),!w&&(w=!0,Promise.resolve().then(async()=>{try{for(;a.size;){let N=new Map(a);try{let x={...await l()},s=Date.now();for(let[C,S]of N)x[C]={at:s,text:S.text};let r={},p=2,v=0;for(let[C,S]of Object.entries(x).sort(([,R],[,O])=>O.at-R.at)){if(S.at>s||s-S.at>j.retentionMs)continue;let R=new TextEncoder().encode(JSON.stringify({[C]:S})).byteLength;p+R>oe||v>=128||(r[C]=S,p+=R,v++)}await t.setItem(`${e}:artifacts`,JSON.stringify(r))}catch{}finally{for(let[x,s]of N)a.get(x)===s&&(a.delete(x),d-=s.byteLength)}}}finally{w=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Fn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function gr(e){let n=Ye.parse(e.scope),t=new te(e.origin??le);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let a=new Set([t.origin,...(e.assetOrigins??[]).map(I=>{let y=new te(I);if(y.protocol!=="https:"||y.username||y.password||y.search||y.hash||y.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return y.origin})]),d=e.fetch??globalThis.fetch.bind(globalThis),w=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${t.origin}:${M(n)}`,o=An(f,e.storage),g,i=0,l=0,u=!1,c=!1,h=0,A=0,N,x,s,r,p=0,v=new Set,C=new Set,S=new Map,R=new Map,O=0,D=!1;function L(){for(let I of v)try{I()}catch{}}function k(I){try{e.onError?.(I)}catch{}}let G=()=>!c&&!u&&!!g&&W()<i&&Date.now()<l;function H(){if(!G())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(I,y,b){if(!S.has(I)){for(;S.size&&(S.size>=128||O+b>j.maxCacheBytes);){let P=S.entries().next().value;O-=P[1].byteLength,S.delete(P[0])}S.set(I,{text:y,byteLength:b}),O+=b}}function Z(I,y,b){return fn(I,y,{signal:b,error:P=>E("INVALID_RESPONSE",P==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(I){let y=new te(I,t);if(!a.has(y.origin)||y.username||y.password||y.hash||y.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return y.href}async function Ae(I,y,b=!1){let P=await d(fe(I),{method:"GET",credentials:"omit",redirect:"error",cache:b?"default":"no-cache",signal:y,headers:{}});if(P.status===429){let T=P.headers.get("retry-after")??"";p=/^\d+$/.test(T)?Number(T)*1e3:Math.max(0,Date.parse(T)-Date.now())||15e3}if(!P.ok&&P.status!==304)throw E(`CONFIGURATION_HTTP_${P.status}`,"Configuration synchronization failed");return P}function On(I,y,b){let P=Date.parse(I.headers.get("x-indiana-config-validated-at")??""),T=Date.parse(I.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(I.headers.get("date")??""),F=I.headers.get("age"),B=F!==null&&/^\d+(\.\d+)?$/.test(F)?Number(F)*1e3:NaN;if(![P,T,_,B].every(Number.isFinite)||T<=P||T-P>j.maxControlAgeMs||P>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let V=Math.min(T-P,b.maxControlAgeSeconds*1e3,j.maxControlAgeMs)-Math.max(B,_-P,0)-(W()-y);if(V<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+V}function Fe(){if(clearTimeout(s),clearTimeout(r),c||!v.size)return;G()&&(r=setTimeout(()=>{G()?Fe():L()},Math.max(1,i-W())),Fn(r));let I=A?Math.min(15e3,1e3*2**Math.min(A-1,4)):Math.min(15e3,(g?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{ie().catch(k)},Math.max(p,I*(.8+Math.random()*.2))),Fn(s)}async function ie(){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(N)return N;let I=h,y=new AbortController;x=y;let b=(async()=>{if(!D){D=!0;try{let he=await o.readManifest();if(he&&!g){let K=Oe.parse(JSON.parse(he));M(K.scope)===M(n)&&(g=K)}}catch{}}y.signal.throwIfAborted();let F=g,B=W(),q=await Ae(w,y.signal);q.status===304&&(!F||!q.headers.has("x-indiana-config-validated-at")||!q.headers.has("x-indiana-config-valid-until")||!q.headers.has("age"))&&(q=await Ae(w,y.signal));let V=q.status===304?F:Oe.parse(JSON.parse(await Z(q,j.maxManifestBytes,y.signal))),{generation:ae,...se}=V,z=q.headers.get("etag");if(M(V.scope)!==M(n)||$e(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(F&&(V.revision<F.revision||V.revision===F.revision&&V.generation!==F.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(F?.funnels??{})){let ee=V.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=On(q,B,V.policy);if(y.signal.throwIfAborted(),I!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return g=V,i=X,l=Date.now()+Math.max(0,X-W()),u=!1,A=0,p=0,o.writeManifest(M(V)),L(),structuredClone(V)})(),P=setTimeout(()=>y.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),j.initializationMs),T=new Promise((F,B)=>y.signal.addEventListener("abort",()=>B(y.signal.reason),{once:!0})),_=Promise.race([b,T]).catch(F=>{throw A++,(F instanceof Jn.ZodError||F instanceof SyntaxError||F instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(F.code))&&(i=0,u=!0,L()),F}).finally(()=>{clearTimeout(P),N===_&&(N=void 0),Fe()});return N=_,_}async function ye(I){let y=I.sha256,b=se=>Ce(se,I);fe(I.url);let P=S.get(y);if(P){if(P.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return S.delete(y),S.set(y,P),P.text}let T=R.get(y);if(T){if(T.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.promise}let _=new AbortController;C.add(_);let F=h,B=(async()=>{try{let X=await o.readArtifact(y);if(X&&b(X)){if(_.signal.throwIfAborted(),c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,X,I.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Ae(I.url,_.signal,!0),z=await Z(se,I.byteLength,_.signal);if(!b(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,z,I.byteLength),o.writeArtifact(y,z),z})(),q=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),j.initializationMs),V=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([B,V]).finally(()=>{clearTimeout(q),C.delete(_),R.delete(y)});return R.set(y,{promise:ae,byteLength:I.byteLength}),ae}async function we(){return G()||await ie(),H(),g}async function me(I){let y,b=new Promise((P,T)=>{y=setTimeout(()=>T(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),j.initializationMs)});try{return await Promise.race([I(),b])}finally{clearTimeout(y)}}function pe(I,y){if(H(),g?.generation!==I.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(y&&g.funnels[y]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Le(I){let y=I.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let P=He.parse(JSON.parse(await ye(b)));if(M(P.scope)!==M({projectId:n.projectId,environment:n.environment})||P.generation!==b.generation||P.remoteFeatures.some(T=>Object.hasOwn(P.features,T)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(I),{...P,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,i-W())).toISOString()}}async function xe(I,y){let b=await we(),P=b.funnels[I];y&&(!P||P.evaluationMode==="local"&&!P.versions[y])&&(N&&await N,b=await ie()),pe(b,I);let T=b.funnels[I];if(T.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=y??T.currentVersionId,F=T.versions[_];if(!F)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(b.artifacts[F.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[B,q]=await Promise.all([ye(b.artifacts[F.artifact]).then(V=>Ze(JSON.parse(V))),T.evaluationMode==="local"?Le(b):void 0]);if(q&&M(We(B,q))!==M(F.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(b,I),{document:B,growth:q,versionId:_,control:structuredClone(T),manifest:structuredClone(b)}}async function Ve(I,y){try{return await xe(I,y)}catch(b){if(!(b instanceof m)||!(b.code==="CONFIGURATION_CHANGED"||b.code==="CONFIGURATION_HTTP_404"&&G()))throw b;let P=g?.generation;if(N&&await N,await ie(),b.code!=="CONFIGURATION_CHANGED"&&g?.generation===P)throw b;return xe(I,y)}}function Ne(){u=!0,L(),ie().catch(k)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function Tn(I){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(I),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Fe()),()=>{v.delete(I),v.size||(clearTimeout(s),clearTimeout(r),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:Tn,assertFresh:H,assertFeatures(I){H();let y=g.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(I!==void 0&&g.artifacts[y].generation!==I)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return g?structuredClone(g):null},get remainingMs(){return G()?Math.max(0,i-W()):0},async features(){return me(async()=>Le(await we()))},pageExperiments:()=>me(async()=>{let I=await we(),y=I.gb.pageExperiments;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let P=un.parse(JSON.parse(await ye(b)));if(P.environmentId!==n.environmentId||P.generation!==b.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(I),P}),funnel:(I,y)=>me(()=>Ve(I,y)),paywall:(I,y)=>me(async()=>{let b=await we(),P=b.paywalls?.[I];if(!P||!y&&P.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let T=y??P.currentVersionId,_=P.versions[T],F=_&&b.artifacts[_.artifact];if(!F||F.kind!=="paywall"||F.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let B=Qe.parse(JSON.parse(await ye(F)));return pe(b),{document:B,versionId:T,version:_.version,control:structuredClone(P),manifest:structuredClone(b)}}),async localFunnel(I,y){let b=await me(()=>Ve(I,y));if(!b.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:P,remoteFeatures:T,..._}=b.growth;return sn({scope:{projectId:n.projectId,environment:n.environment},funnelId:I,versionId:b.versionId,evaluationMode:"local",evaluationRevision:b.control.evaluationRevision,document:b.document,payload:_})},assertFunnel(I,y,b){H();let P=g.funnels[I];if(!P||P.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(P.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(y!==void 0&&P.controlRevision!==y)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(b!==void 0&&!P.versions[b])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!c){c=!0,h++,i=0,x?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(r),Me(),L(),v.clear();for(let I of C)I.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));S.clear(),O=0}}}}function Nn(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(t){let a=Q.safeParse({...t,operation:"start"});if(!a.success||a.data.operation!=="start"||(n?a.data.customer!==void 0:a.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let d=a.data,w=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||w.identify(e.apiKey);let f=be(e,await w.request("funnels",d));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==d.funnelId||f.run.locale!==(d.locale??"en")||!ce(f.run.parameters,d.parameters??{})||(d.customer?!f.customerId||d.customer.type==="id"&&f.customerId!==d.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{w.dispose()}}}}async function Fr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&M(t)!==M(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let d=re.test(e.credential);if(d?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let w=Nn({...e,scope:t,apiKey:e.credential}),f=o=>{let g=Pn({...e,scope:t,runToken:o,...d?{serverKey:e.credential}:{}});return d||g.identify(e.credential),g};return{async start(o){let g=await w.start({...o,funnelId:e.funnelId,...d?{customer:{type:"id",value:e.customerId}}:{}}),i=f(g.runToken),l=await i.get();return{...g,...l,controller:i}},async restore(o){let g=f(o),i=await g.get();if(i.run.source.id!==e.funnelId)throw g.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...i,runToken:o,controller:g}}}}export{Ee as a,Un as b,Sn as c,zn as d,be as e,_e as f,ut as g,Mn as h,In as i,It as j,ce as k,St as l,Et as m,Pn as n,rr as o,gr as p,Nn as q,Fr as r};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{z as lr}from"zod";var pr=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],z=lr.enum(pr);function dr(e){let t=z.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function We(e,t,n="en",r={}){let i=z.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:i,...r}).format(e/10**dr(i))}import{z as E}from"zod";import{z as R}from"zod";var Ce=R.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),N=R.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),fr=R.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Je=N.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Pt=R.string().min(1).max(64),ie=R.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Lt=R.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),B=R.record(Pt,R.union([R.string().max(120),R.number().finite(),R.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),Ut=R.record(Pt,R.union([R.string().max(120),R.number().finite(),R.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),le=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},zt=R.array(R.object({upTo:Je.nullable(),cost:N}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&le(t.upTo)>le(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),mr=R.object({key:Lt,match:Ut,priority:R.number().int().default(0),cost:N.optional(),tiers:zt.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),gr=R.object({key:Lt,match:Ut,factor:Je.optional(),add:fr.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"})),br=R.object({units:Je.default("1"),cost:N,tiers:zt.optional(),dimensions:R.array(mr).max(12).optional(),multipliers:R.array(gr).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(a=>a.key)).size!==n.length||new Set(r.map(a=>a.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[a,s]of n.entries())for(let u of n.slice(a+1))Object.keys(s.match).length===Object.keys(u.match).length&&s.priority===u.priority&&!Object.keys(s.match).some(f=>u.match[f]!==void 0&&u.match[f]!==s.match[f])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(a=>a.cost),...n.flatMap(a=>[...a.cost===void 0?[]:[a.cost],...(a.tiers??[]).map(s=>s.cost)])],o=le(e.units);for(let a of i)for(let s=0;s<1<<r.length;s++){let u=r.filter((b,k)=>s&1<<k);if(u.some((b,k)=>u.slice(k+1).some(O=>Object.keys(b.match).some(U=>O.match[U]!==void 0&&O.match[U]!==b.match[U]))))continue;let f=le(a),d=BigInt("1"),g=BigInt("0");for(let[b,k]of r.entries())s&1<<b&&(f*=le(k.factor??"1"),d*=BigInt("1000000"),g+=le(k.add??"0"));let A=(f+g*d)*BigInt("1000000"),y=d*o;(A<BigInt("0")||A%y!==BigInt("0")||A/y>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),ko=br.safeExtend({featureKey:ie});import{z as hr}from"zod";import{z as pe}from"zod";var $t=pe.enum(["stripe","apple","google","merchant"]),Eo=pe.enum(["membership","credit_pack","lifetime"]),_o=pe.enum(["active","grace","suspended","inactive","revoked"]),wo=pe.strictObject({currency:pe.string().regex(/^[A-Z]{3}$/),micros:pe.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var Ft=hr.object({provider:$t,currency:z}).strict();import{z as de}from"zod";var yr=e=>e/2**32|0,xr=e=>e>>>0;function Vt(e,t,n,r){let i=yr(n),o=xr(n);e.setUint32(t,r?o:i,r),e.setUint32(t+4,r?i:o,r)}function Bt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ye=e=>e?`"${e}" `:"";function Sr(e,t=""){if(typeof e!="number")throw new TypeError(Ye(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Ye(t)+"expected integer >= 0, got "+e);return e}function je(e,t,n=""){if(Bt(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Sr(t,"length");let r=Bt(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=Ye(n)+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)}var kr=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Mt=(e,t)=>{kr(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Xe(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function qt(e,t){je(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function et(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Te(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function M(e,t){return e<<32-t|e>>>t}var Ar=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ir=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function De(e){if(je(e),Ar)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ir[e[n]];return t}function Er(e,t,n="opts"){return Mt(e,"defaults"),t!==void 0&&Mt(t,n),Object.assign(Object.create(null),e,t)}function Ht(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Er({},t,"info");let n=(i,o)=>e(o).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var Gt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Qt(e,t,n){return e&t^~e&n}function Kt(e,t,n){return e&t^e&n^t&n}var Pe=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,i){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Te(this.buffer)}update(t){Xe(this),je(t);let{view:n,buffer:r,blockLen:i}=this,o=t.length,a=!1;for(let s=0;s<o;){let u=Math.min(i-this.pos,o-s);if(u===i){let f=Te(t);for(;i<=o-s;s+=i)this.process(f,s);a=!0;continue}r.set(s===0&&u===o?t:t.subarray(s,s+u),this.pos),this.pos+=u,s+=u,this.pos===i&&(this.process(n,0),this.pos=0,a=!0)}return this.length+=t.length,a&&this.roundClean(),this}digestInto(t){Xe(this),qt(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:o}=this,{pos:a}=this;n[a++]=128,n.fill(0,a),this.padOffset>i-a&&(this.process(r,0),n.fill(0)),Vt(r,i-8,this.length*8,o),this.process(r,0),this.roundClean();let s=t===n?r:Te(t),u=this.outputLen,f=u/4,d=this.get();if(u%4||f>d.length)throw new Error("invalid outputLen");for(let g=0;g<f;g++)s.setUint32(4*g,d[g],o)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=i,t.length=r,t.pos=a,a&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Zt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var _r=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),X=new Uint32Array(64),tt=class extends Pe{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:i,E:o,F:a,G:s,H:u}=this;return[t,n,r,i,o,a,s,u]}set(t,n,r,i,o,a,s,u){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=a|0,this.G=s|0,this.H=u|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let g=0;g<16;g++,n+=4)X[g]=t.getUint32(n,!1);for(let g=16;g<64;g++){let A=X[g-15],y=X[g-2],b=M(A,7)^M(A,18)^A>>>3,k=M(y,17)^M(y,19)^y>>>10;X[g]=k+X[g-7]+b+X[g-16]|0}let{A:r,B:i,C:o,D:a,E:s,F:u,G:f,H:d}=this;for(let g=0;g<64;g++){let A=M(s,6)^M(s,11)^M(s,25),y=d+A+Qt(s,u,f)+_r[g]+X[g]|0,k=(M(r,2)^M(r,13)^M(r,22))+Kt(r,i,o)|0;d=f,f=u,u=s,s=a+y|0,a=o,o=i,i=r,r=y+k|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,a=a+this.D|0,s=s+this.E|0,u=u+this.F|0,f=f+this.G|0,d=d+this.H|0,this.set(r,i,o,a,s,u,f,d)}roundClean(){et(X)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),et(this.buffer)}},nt=class extends tt{constructor(){super(32,Zt)}};var Le=Ht(()=>new nt,Gt(1));import{z as rt}from"zod";var it=rt.enum(["sandbox","live"]),qo=rt.object({projectId:rt.string().min(1),environment:it}).strict();var Wt=de.string().regex(/^[a-f0-9]{64}$/),Ue=de.strictObject({scope:de.strictObject({projectId:de.uuid(),environmentId:de.uuid(),environment:it}),customerId:de.uuid()});function Jt(e){let t=n=>{if(Array.isArray(n))return`[${n.map(t).join(",")}]`;if(n!==null&&typeof n=="object"){let r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(n).filter(([,i])=>i!==void 0).sort(([i],[o])=>i<o?-1:i>o?1:0).map(([i,o])=>`${JSON.stringify(i)}:${t(o)}`).join(",")}}`}if(n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return JSON.stringify(n);throw new TypeError("Commerce protocol digests require JSON values")};return De(Le(new TextEncoder().encode(t(e))))}var Se=E.strictObject({internal_feature_id:E.uuid(),quantity:N.refine(e=>/[1-9]/.test(e)),properties:B,entityId:E.uuid().optional()}),na=E.strictObject({requirement:Se,commerce:Ft.optional(),paywallId:E.uuid().optional()}),wr=E.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Or=E.strictObject({productId:E.string().min(1),productVersionId:E.string().min(1),name:E.string().min(1).max(120),action:E.enum(["purchase","upgrade","addon","topup"]),membershipId:E.string().min(1).nullable(),currency:z,amountMinor:E.string().regex(/^(0|[1-9]\d{0,8})$/),interval:E.enum(["free","week","month","year","one_time"]),intervalCount:E.number().int().min(1).max(156)}),Yt=E.strictObject({subject:Ue,authority:E.enum(["longplay","merchant"]),observedAt:E.iso.datetime({offset:!0}),sourceRevision:E.string().min(1).max(128),requirementDigest:Wt});function vr(e,t){return Jt({subject:Ue.parse(e),requirement:Se.parse(t)})}var ot=E.strictObject({internal_feature_id:E.string().min(1),name:E.string().min(1).max(120),kind:E.enum(["access","metered","credit"]),quantity:N,allowed:E.boolean(),observation:Yt.optional(),reason:wr.nullable(),preview:E.strictObject({scenario:E.enum(["feature_flag","usage_limit"]),candidates:E.array(Or).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),ra=E.strictObject({paywallId:E.uuid(),requirement:Se}),ia=E.strictObject({subject:Ue,requirement:Se}),oa=ot.safeExtend({observation:Yt.extend({authority:E.literal("merchant")})});function aa(e,t){let n=Se.parse(e);return t.internal_feature_id===n.internal_feature_id&&t.quantity===n.quantity&&(!t.observation||t.observation.requirementDigest===vr(t.observation.subject,n))}import{z as l}from"zod";function at(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function ke(e,t,n){return n===2?at(at(e+t)+"")%1e4/1e4:null}function Xt(e){return e<=0?[]:new Array(e).fill(1/e)}function Ae(e,t){return e>=t[0]&&e<t[1]}function st(e,t){for(let[n,r]of t.entries())if(Ae(e,r))return n;return-1}function ct(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=Xt(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,u)=>u+s,0);(i<.99||i>1.01)&&(n=r);let o=0,a=t;return n.map(s=>{let u=o;return o+=s,[u,u+a*s]})}function ut(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let o=r.replace(/#.*/,"").split("&").map(a=>a.split("=",2)).filter(([a])=>a===e).map(([,a])=>a===void 0?NaN:parseInt(a))[0];return o!==void 0&&o>=0&&o<n?o:null}function lt(e){try{return e()}catch{return!1}}function fe(e){return typeof e=="string"?e:JSON.stringify(e)}function $(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function en(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function pt(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let o=Cr(e,i.type,i.pattern);if(i.include===!1){if(o)return!1}else n=!0,o&&(r=!0)}return r||!n}function Rr(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function Nr(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,o)=>{r.push([e.searchParams.get(o)||"",i,!1])}),!r.some(i=>!Rr(i[0],i[1],i[2]))}catch{return!1}}function Cr(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=en(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return Nr(r,n);return!1}catch{return!1}}function dt(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function ze(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function tn(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);ze(e.savedGroups??{})}var nn=new Map,ft=32,rn=new WeakMap,on=new WeakMap;function jr(e){return De(Le(new TextEncoder().encode(String(e))))}var Fe=e=>Array.isArray(e)?e.map(Fe):typeof e=="string"||typeof e=="number"?jr(e):null,$e=e=>typeof e=="string"?e.toLowerCase():e;function ln(e){let t=rn.get(e);return t||(t=new Set(e),rn.set(e,t)),t}function Tr(e){let t=on.get(e);return t||(t=new Set(e.map($e)),on.set(e,t)),t}function pn(e){ze(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=ft&&ln(n)}return e}function q(e,t,n,r){n=n||{},r||ze(n),r=r||new Set;for(let[i,o]of Object.entries(t))switch(i){case"$or":if(!un(e,o,n,r))return!1;break;case"$nor":if(un(e,o,n,r))return!1;break;case"$and":if(!zr(e,o,n,r))return!1;break;case"$not":if(q(e,o,n,r))return!1;break;case"$savedGroup":if(!Dr(e,o,n,r))return!1;break;default:if(!Ie(o,dn(e,i),n,!1,r))return!1}return!0}function Dr(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:o}=t;if(typeof i!="string"||r.has(i)||o!==void 0&&typeof o!="string")return!1;let a=n[i];if(!a||Array.isArray(a)||typeof a!="object")return!1;let s=new Set(r).add(i);if(a.type==="list"||a.type==="hashed"){let u=o??a.attributeKey;if(typeof u!="string"||!Array.isArray(a.values))return!1;let f=dn(e,u);return oe(a.type==="hashed"?Fe(f):f,a.values)}return a.type==="condition"?!a.condition||typeof a.condition!="object"?!1:q(e,a.condition,n,s):!1}function dn(e,t){let n=t.split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return null;return r}function an(e,t=!1){let n=`${e}${t?"/i":""}`,r=nn.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),nn.set(n,r)),r}function Ie(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!fn(e))return JSON.stringify(t)===JSON.stringify(e);let o=e;for(let a in o)if(!Ur(a,t,o[a],n,i))return!1;return!0}function fn(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function Pr(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function Lr(e,t,n,r){if(!Array.isArray(e))return!1;let i=fn(t)?o=>Ie(t,o,n,!1,r):o=>q(o,t,n,r);for(let o=0;o<e.length;o++)if((e[o]??null)!==null&&i(e[o]))return!0;return!1}function oe(e,t,n=!1){if(n){let i;if(t.length>=ft){let o=Tr(t);i=a=>{let s=$e(a);return!(typeof s=="number"&&Number.isNaN(s))&&o.has(s)}}else i=o=>t.some(a=>$e(o)===$e(a));return Array.isArray(e)?e.some(o=>i(o)):i(e)}let r=t.length>=ft?(i=>o=>i.has(o))(ln(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function sn(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function cn(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let o=0;o<t.length;o++){let a=!1;for(let s=0;s<e.length;s++)if(Ie(t[o],e[s],n,r,i)){a=!0;break}if(!a)return!1}return!0}function Ur(e,t,n,r,i=new Set){let o=t,a=n;switch(e){case"$veq":return $(t)===$(n);case"$vne":return $(t)!==$(n);case"$vgt":return $(t)>$(n);case"$vgte":return $(t)>=$(n);case"$vlt":return $(t)<$(n);case"$vlte":return $(t)<=$(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return o<a;case"$lte":return o<=a;case"$gt":return o>a;case"$gte":return o>=a;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?oe(t,n):!1;case"$ini":return Array.isArray(n)?oe(t,n,!0):!1;case"$inGroup":{let s=r[n],u=sn(s);return u===null?!1:oe(s?.type==="hashed"?Fe(t):t,u)}case"$notInGroup":{let s=r[n],u=sn(s);return u===null?!1:!oe(s?.type==="hashed"?Fe(t):t,u)}case"$nin":return Array.isArray(n)?!oe(t,n):!1;case"$nini":return Array.isArray(n)?!oe(t,n,!0):!1;case"$not":return!Ie(n,t,r,!1,i);case"$size":return Array.isArray(t)?Ie(n,t.length,r,!1,i):!1;case"$elemMatch":return Lr(t,n,r,i);case"$all":return Array.isArray(n)?cn(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?cn(t,n,r,!0,i):!1;case"$regex":try{return an(n).test(t)}catch{return!1}case"$regexi":try{return an(n,!0).test(t)}catch{return!1}case"$type":return Pr(t)===n;default:return!1}}function un(e,t,n,r){if(!t.length)return!0;for(let i of t)if(q(e,i,n,r))return!0;return!1}function zr(e,t,n,r){for(let i of t)if(!q(e,i,n,r))return!1;return!0}function mt(e){return tn(e),{context:e,stack:{evaluatedFeatures:new Set}}}function gt(e){return{...e.attributes,...e.attributeOverrides}}function ee(e,t,n){let r=t||"id",i="",o=gt(e);return o[r]&&(i=o[r]),!i&&n&&(o[n]&&(i=o[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function _(e,t,n){e.context.log?.(t,n)}function Ve(e,t){return t=t||0,`${e}__${t}`}function bt(e,t){return`${e}||${t}`}function $r(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:o}=ee(e,t),a=bt(i,fe(o)),{hashAttribute:s,hashValue:u}=ee(e,n),f=u?bt(s,fe(u)):null,d={};return f&&r[f]&&Object.assign(d,r[f].assignments||{}),r[a]&&Object.assign(d,r[a].assignments||{}),d}function mn({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:o,expMeta:a}){n=n||0,o=o||0,r=r||"id",a=a||[];let s=Ve(t,n),u=$r(e,r,i);if(o>0)for(let g=0;g<o;g++){let A=Ve(t,g);if(u[A]!==void 0)return{variation:-1,versionIsBlocked:!0}}let f=u[s];if(f===void 0)return{variation:-1};let d=a.findIndex(g=>g.key===f);return d<0?{variation:-1}:{variation:d}}function gn(e,t,n,r){let i=bt(t,n),o=e.stickyBucketAssignmentDocs,a=o&&o[i]?o[i].assignments||{}:{},s={...a,...r},u=JSON.stringify(a)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:u}}function bn(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function hn(e,t){let n=mt(t),r=Sn(e,null,n);return t.onExperimentEval?.(e,r),r}function yn(e,t){return yt(e,mt(t))}function Fr(e){return e.forcedVariations||{}}function xn(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=In(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}ht(()=>r.onExperimentViewed?.(t,n))}function Vr(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}ht(()=>r.onFeatureUsage?.(t,n))}function ht(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function yt(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return _(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),te(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let o of r?.rules??[])dt(o);let i=n.forcedFeatureValues;if(i&&i.has(e))return _(t,"Global override",{id:e,value:i.get(e)}),te(t,e,i.get(e),"override");if(!r)return _(t,"Unknown feature",{id:e}),te(t,e,null,"unknownFeature");if(r.rules){let o=new Set(t.stack.evaluatedFeatures);e:for(let a of r.rules){if(a.parentConditions)for(let f of a.parentConditions){t.stack.evaluatedFeatures=new Set(o);let d=yt(f.id,t);if(d.source==="cyclicPrerequisite")return te(t,e,null,"cyclicPrerequisite");let g={value:d.value};if(!q(g,f.condition||{},n.savedGroups||{})){if(f.gate)return _(t,"Feature blocked by prerequisite",{id:e,rule:a}),te(t,e,null,"prerequisite");_(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:a});continue e}}if(a.filters&&An(a.filters,t)){_(t,"Skip rule because of filters",{id:e,rule:a});continue}if("force"in a){if(a.condition&&!kn(a.condition,t)){_(t,"Skip rule because of condition ff",{id:e,rule:a});continue}if(!Br(t,a.seed||e,a.hashAttribute,n.saveStickyBucketAssignmentDoc&&!a.disableStickyBucketing?a.fallbackAttribute:void 0,a.range,a.coverage,a.hashVersion)){_(t,"Skip rule because user not included in rollout",{id:e,rule:a});continue}return _(t,"Force value from rule",{id:e,rule:a}),a.tracks&&a.tracks.forEach(f=>{xn(t,f.experiment,f.result)}),te(t,e,a.force,"force",a.id)}if(!a.variations){_(t,"Skip invalid rule",{id:e,rule:a});continue}let s={variations:a.variations,key:a.key||e};"coverage"in a&&(s.coverage=a.coverage),a.weights&&(s.weights=a.weights),a.hashAttribute&&(s.hashAttribute=a.hashAttribute),a.fallbackAttribute&&(s.fallbackAttribute=a.fallbackAttribute),a.disableStickyBucketing&&(s.disableStickyBucketing=a.disableStickyBucketing),a.bucketVersion!==void 0&&(s.bucketVersion=a.bucketVersion),a.minBucketVersion!==void 0&&(s.minBucketVersion=a.minBucketVersion),a.meta&&(s.meta=a.meta),a.ranges&&(s.ranges=a.ranges),a.name&&(s.name=a.name),a.phase&&(s.phase=a.phase),a.seed&&(s.seed=a.seed),a.hashVersion&&(s.hashVersion=a.hashVersion),a.filters&&(s.filters=a.filters),a.condition&&(s.condition=a.condition);let u=Sn(s,e,t);if(n.onExperimentEval?.(s,u),u.inExperiment&&!u.passthrough)return te(t,e,u.value,"experiment",a.id,s,u)}}return _(t,"Use default value",{id:e,value:r.defaultValue}),te(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Sn(e,t,n){let{context:r}=n;dt(e);let i=e.key,o=e.variations.length;if(o<2)return _(n,"Invalid experiment",{id:i}),P(n,e,-1,!1,t);if(r.enabled===!1)return _(n,"Context disabled",{id:i}),P(n,e,-1,!1,t);if(e.urlPatterns&&!pt(r.url||"",e.urlPatterns))return _(n,"Skip because of url targeting",{id:i}),P(n,e,-1,!1,t);let a=ut(i,r.url||"",o);if(a!==null)return _(n,"Force via querystring",{id:i,variation:a}),P(n,e,a,!1,t);let u=Fr(r)[i];if(u!==void 0)return _(n,"Force via dev tools",{id:i,variation:u}),P(n,e,u,!1,t);if(e.active===!1)return _(n,"Skip because inactive",{id:i}),P(n,e,-1,!1,t);let{hashAttribute:f,hashValue:d}=ee(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return _(n,"Skip because missing hashAttribute",{id:i}),P(n,e,-1,!1,t);let g=-1,A=!1,y=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:O,versionIsBlocked:U}=mn(bn({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));A=O>=0,g=O,y=!!U}if(!A){if(e.filters&&An(e.filters,n))return _(n,"Skip because of filters",{id:i}),P(n,e,-1,!1,t);if(e.include&&!lt(e.include))return _(n,"Skip because of include function",{id:i}),P(n,e,-1,!1,t);if(e.condition&&!kn(e.condition,n))return _(n,"Skip because of condition exp",{id:i}),P(n,e,-1,!1,t);if(e.parentConditions){let O=new Set(n.stack.evaluatedFeatures);for(let U of e.parentConditions){n.stack.evaluatedFeatures=new Set(O);let re=yt(U.id,n);if(re.source==="cyclicPrerequisite")return P(n,e,-1,!1,t);let Ze={value:re.value};if(!q(Ze,U.condition||{},r.savedGroups||{}))return _(n,"Skip because prerequisite evaluation fails",{id:i}),P(n,e,-1,!1,t)}}}let b=ke(e.seed||i,d,e.hashVersion??2);if(b===null)return _(n,"Skip because of invalid hash version",{id:i}),P(n,e,-1,!1,t);if(!A){let O=e.ranges||ct(o,e.coverage===void 0?1:e.coverage,e.weights);g=st(b,O)}if(y)return _(n,"Skip because sticky bucket version is blocked",{id:i}),P(n,e,-1,!1,t,void 0,!0);if(g<0)return _(n,"Skip because of coverage",{id:i}),P(n,e,-1,!1,t);if("force"in e)return _(n,"Force variation",{id:i,variation:e.force}),P(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return _(n,"Skip because QA mode",{id:i}),P(n,e,-1,!1,t);let k=P(n,e,g,!0,t,b,A);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:O,key:U,doc:re}=gn(r,f,fe(d),{[Ve(e.key,e.bucketVersion)]:k.key});if(O){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[U]=re;let Ze=r.saveStickyBucketAssignmentDoc;ht(()=>Ze(re))}}return xn(n,e,k),_(n,"In experiment",{id:i,variation:k.variationId}),k}function te(e,t,n,r,i,o,a){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return o&&(s.experiment=o),a&&(s.experimentResult=a),r!=="override"&&Vr(e,t,s),s}function kn(e,t){return q(gt(t.context),e,t.context.savedGroups||{})}function An(e,t){return e.some(n=>{let{hashValue:r}=ee(t.context,n.attribute);if(!r)return!0;let i=ke(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(o=>Ae(i,o))})}function Br(e,t,n,r,i,o,a){if(!i&&o===void 0)return!0;if(!i&&o===0)return!1;let{hashValue:s}=ee(e.context,n,r);if(!s)return!1;let u=ke(t,s,a??2);return u===null?!1:i?Ae(u,i):o!==void 0?u<=o:!0}function P(e,t,n,r,i,o,a){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:u,hashValue:f}=ee(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},g=t.variations[0];for(let[y,b]of t.variations.entries())if(y===n){g=b;break}let A={key:d.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:g,hashAttribute:u,hashValue:f,stickyBucketUsed:!!a};return d.name&&(A.name=d.name),o!==void 0&&(A.bucket=o),d.passthrough&&(A.passthrough=d.passthrough),A}function In(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
2
|
+
Copyright (c) 2025 GrowthBook, Inc.
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
|
5
|
+
furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all
|
|
8
|
+
copies or substantial portions of the Software.
|
|
9
|
+
|
|
10
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
11
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
12
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
13
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
14
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
15
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
16
|
+
SOFTWARE.
|
|
17
|
+
*/var ne=l.json().superRefine((e,t)=>{let n=0;function r(i,o){if(++n>1e4||o>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(a=>r(a,o+1));else if(i&&typeof i=="object")for(let[a,s]of Object.entries(i))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,o+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),St=l.record(l.string().min(1).max(128),ne).superRefine((e,t)=>{(!ne.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),Mr=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Be=St.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r)){if(i==="$savedGroup"&&!l.strictObject({id:l.uuid(),attributeKey:l.string().min(1).max(128).optional()}).safeParse(o).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!Mr.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof o=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(o)||[...o.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(o.replace(/\\u([0-9a-f]{4})/gi,(a,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(o)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(o)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),qr=l.discriminatedUnion("type",[l.strictObject({type:l.literal("condition"),condition:Be}),l.strictObject({type:l.literal("list"),attributeKey:l.string().min(1).max(128),values:l.array(l.union([l.string(),l.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Hr(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r))i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.id=="string"?t.add(o.id):["$inGroup","$notInGroup"].includes(i)&&typeof o=="string"?t.add(o):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(o)}return n(e),[...t]}var Gr=l.record(l.uuid(),qr).superRefine((e,t)=>{let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(o),a.type==="condition"&&Hr(a.condition).forEach(i),n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),kt=l.tuple([l.number().min(0).max(1),l.number().min(0).max(1)]).refine(([e,t])=>e<=t),En=l.strictObject({attribute:l.string().optional(),seed:l.string().min(1),hashVersion:l.literal(2),ranges:l.array(kt).min(1).max(100)}),Qr=l.strictObject({id:l.string().min(1).max(128),condition:Be,gate:l.boolean().optional()}),xt={id:l.string().max(128).optional(),condition:Be.optional(),parentConditions:l.array(Qr).max(50).optional(),filters:l.array(En).max(20).optional()},Kr=l.union([l.strictObject({...xt}),l.strictObject({...xt,force:ne,coverage:l.number().min(0).max(1).optional(),range:kt.optional(),seed:l.string().min(1).optional(),hashAttribute:l.string().optional(),hashVersion:l.literal(2).optional()}),l.strictObject({...xt,type:l.literal("experiment-ref"),experimentId:l.uuid(),values:l.record(l.string().min(1),ne),meta:l.record(l.string().min(1),l.strictObject({passthrough:l.boolean()})).optional()})]),Zr=l.strictObject({defaultValue:ne,rules:l.array(Kr).max(100)}),za=l.record(l.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Zr).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${o}`});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${o}`});return}n.add(o);for(let s of a.rules)for(let u of s.parentConditions??[])i(u.id);n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),Wr=l.strictObject({name:l.string().max(80),reason:l.string().max(500),dateStarted:l.iso.datetime({offset:!0}),dateEnded:l.iso.datetime({offset:!0}).nullable(),coverage:l.number().min(0).max(1),variationWeights:l.array(l.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Be,savedGroups:l.array(l.strictObject({match:l.enum(["any","all","none"]),ids:l.array(l.uuid()).min(1)})).max(50),namespace:l.strictObject({id:l.uuid(),ranges:l.array(kt).min(1)}).nullable(),seed:l.string().min(1).max(128)}),Jr=l.strictObject({key:l.string().min(1).max(128),name:l.string().min(1).max(80),hypothesis:l.string().max(2e3),status:l.enum(["draft","running","stopped"]),hashAttribute:l.string().min(1).max(128),fallbackAttribute:l.string().max(128).nullable(),hashVersion:l.literal(2),disableStickyBucketing:l.boolean(),bucketVersion:l.number().int().min(0).max(1e3),minBucketVersion:l.number().int().min(0).max(1e3),variations:l.array(l.strictObject({id:l.string().min(1),key:l.string().min(1),name:l.string().max(80),description:l.string().max(500)})).min(2).max(20),phases:l.array(Wr).min(1).max(100),releasedVariationId:l.string().nullable(),excludeFromPayload:l.boolean(),statusSchedule:l.strictObject({startAt:l.iso.datetime({offset:!0}).nullable(),stopAt:l.iso.datetime({offset:!0}).nullable(),stopAfter:l.strictObject({value:l.number().int().positive().max(36500),unit:l.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],o,a)=>r>=i||a.some(([s,u],f)=>f!==o&&r<u&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var Yr=Jr.safeExtend({filters:l.array(En).optional()}),Xr=l.strictObject({experiments:l.record(l.uuid(),Yr),savedGroups:Gr}),ei=l.strictObject({attributeName:l.string(),attributeValue:l.string(),assignments:l.record(l.string(),l.string())}),$a=l.strictObject({snapshot:Xr,attributes:St,results:St,stickyBucketAssignmentDocs:l.record(l.string(),ei)}),Fa=l.strictObject({variantKey:l.string().nullable(),bucketVersion:l.number().int().min(0),source:l.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:l.number().min(0).max(1).optional(),stickyBucketUsed:l.boolean().optional(),hashUsed:l.boolean().optional()});import{z as x}from"zod";import{z as be}from"zod";import{z as ge}from"zod";import{z as me}from"zod";var _n=me.number().int().min(0).max(1e8),At=me.strictObject({kind:me.enum(["graduated","volume"]),tiers:me.array(me.strictObject({upTo:me.number().int().min(1).max(1e4).nullable(),unitAmountMinor:_n,flatAmountMinor:_n.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function It(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?At.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let o of n.tiers){let a=o.upTo??1e4;if(n.kind==="volume"){if(t<=a){r=BigInt(t)*BigInt(o.unitAmountMinor)+BigInt(o.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,a)-i)*BigInt(o.unitAmountMinor));i=a}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function wn(e){return It({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var ti=N.refine(e=>/[1-9]/.test(e)),vn=ge.strictObject({units:ti,prices:ge.array(ge.strictObject({currency:z,amountMinor:ge.number().int().min(0).max(1e8),pricing:At.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:ge.number().int().min(0).max(1e4),maximumQuantity:ge.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&It({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function On(e){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(e))throw new Error("Invalid quantity");let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))}function Rn(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=On(e)+On(t)*BigInt(n);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let i=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(i?"."+i:"")}var Et=be.strictObject({internalFeatureId:be.uuid(),name:be.string().min(1).max(120),includedAmount:be.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:be.enum(["hour","day","week","month","year","lifetime"]),resetCount:be.number().int().min(1).max(100),terms:vn});var ni=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],Me=x.object({plan:x.string().min(1).max(200).optional(),coupon:x.uuid().optional(),promotionCode:x.uuid().optional(),picker:x.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Nn=x.object({text:x.string().optional(),label:x.string().optional(),alt:x.string().optional(),html:x.string().max(32768).optional(),price:x.object({current:x.string(),original:x.string().nullable(),period:x.string()}).optional(),code:x.string().optional(),countdownAt:x.iso.datetime().optional(),planId:x.string().min(1).max(200).optional(),planVersionId:x.string().min(1).max(200).optional(),currency:z.optional(),couponId:x.uuid().optional(),offerId:x.uuid().optional(),unavailable:x.boolean().optional(),unavailableReason:x.string().optional(),missing:x.array(x.string()).optional()}).strict(),ns=x.object({paywall:ot.optional(),nodes:x.record(x.string(),x.object({base:Nn,picker:x.string().optional(),byPlan:x.record(x.string(),Nn).optional()}).strict()),plans:x.record(x.string(),x.object({id:x.string().min(1).max(200),versionId:x.string().min(1).max(200),available:x.boolean(),name:x.string(),price:x.string(),period:x.string(),currency:z.optional(),amountMinor:x.number().int().nonnegative().optional(),interval:x.enum(["free","week","month","year","one_time"]).optional(),intervalCount:x.number().int().positive().optional(),prepaid:x.array(Et).max(100).optional()}).strict()),pickers:x.record(x.string(),x.object({options:x.array(x.string().min(1).max(200)).max(20),selected:x.string().min(1).max(200).nullable()}).strict()),quantities:x.record(x.string(),x.strictObject({minimum:x.number().int().nonnegative(),maximum:x.number().int().nonnegative(),step:x.number().int().positive(),value:x.number().int().nonnegative(),label:x.string(),available:x.boolean()})).optional(),diagnostics:x.array(x.object({nodeId:x.string(),message:x.string()}).strict())}).strict();function Cn(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function _t(e){let t=Cn(e).filter(r=>!ni.includes(r)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(r)),n=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(n.includes("{{")||n.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function rs(e,t,n={}){let r=e?.nodes[t];if(!r)return;let i=r.picker?n[r.picker]??e?.pickers[r.picker]?.selected:void 0;return typeof i=="string"?r.byPlan?.[i]??r.base:r.base}import{z as S}from"zod";var ri=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],jn=S.enum(ri),Tn=S.object({source:jn,layout:S.enum(["full","compact"]),resourceKey:ie.optional(),pageSize:S.number().int().min(1).max(50),showSources:S.boolean(),allowPurchase:S.boolean(),outputs:S.object({billing_adjustment:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),T=S.string().max(2e3),Dn=S.object({id:S.string().max(100),label:T,detail:S.array(T).max(12),value:T.optional(),status:T.optional(),facts:S.array(S.object({label:T,value:T}).strict()).max(1e3),purchaseId:S.uuid().optional(),invoiceUrl:S.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:S.array(S.strictObject({action:S.literal("invoice_open"),label:T})).max(1).optional(),membershipActions:S.array(S.object({value:S.string().max(100),label:T}).strict()).max(3).optional()}).strict(),ii=S.object({key:ie,name:T,spendable:T,reserved:T,available:T,expiry:T.nullable(),sources:S.array(Dn).max(50),sourceCount:S.number().int().nonnegative(),sourcePage:S.number().int().positive(),hasNextSources:S.boolean(),hasPreviousSources:S.boolean()}).strict(),oi=S.object({source:jn,status:S.enum(["idle","loading","ready","error"]),stale:S.boolean(),preview:S.boolean(),errorCode:S.string().max(80).optional(),errorMessage:T.optional(),resources:S.array(ii).max(500),rows:S.array(Dn).max(50),hasNext:S.boolean(),hasPrevious:S.boolean(),page:S.number().int().positive(),filter:S.string().max(40),updatedAt:S.iso.datetime().optional(),buyingId:S.uuid().optional(),membershipBusy:S.boolean().optional(),billingBusy:S.boolean().optional(),membershipReview:S.object({title:T,note:T,facts:S.array(S.object({label:T,value:T}).strict()).max(100)}).strict().optional(),membershipResult:T.optional()}).strict(),ss=S.object({nodes:S.record(S.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),oi)}).strict(),cs=S.object({nodeId:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:S.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:S.string().max(100).optional()}).strict();import{z as v}from"zod";var ai=v.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ps=v.discriminatedUnion("type",[v.object({type:v.literal("fixed"),productVersionId:v.string().min(1).max(200)}).strict(),v.object({type:v.literal("picker"),pickerId:ai,allowedProductVersionIds:v.array(v.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),si=v.strictObject({min:v.number().finite().min(1).max(1800),max:v.number().finite().min(1).max(1800),viewport:v.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Pn={desktopWidth:si.optional(),mobile:v.enum(["sheet","fullscreen"]).optional(),backdrop:v.enum(["none","scrim","dim","strong-dim","blur"]).optional()},Ln=v.discriminatedUnion("type",[v.strictObject({type:v.literal("modal"),size:v.enum(["sm","md","lg"]),...Pn}),v.strictObject({type:v.literal("sheet"),size:v.enum(["sm","md","lg"]),...Pn}),v.strictObject({type:v.literal("fullscreen")}),v.strictObject({type:v.literal("inline")})]),ci={sm:360,md:420,lg:560};import{z as c}from"zod";function Un(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function zn(e){let t={};function n(r){if(Un(r)){let i=t[r.interaction.pickerId]??={ids:[],defaultId:null};for(let a of r.children){let s=a.type==="stack"?a.bind?.plan:void 0;s&&!i.ids.includes(s)&&i.ids.push(s)}let o=r.children[r.interaction.defaultIndex];!i.defaultId&&o?.type==="stack"&&(i.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}function $n(e,t,n){let r={};function i(u){if(u.hidden)return;if(u.type==="plan_picker"){let g=n.pickers[u.id];r[u.id]={ids:g?.options??[],defaults:g?.selected?[g.selected]:[],remembered:[]};return}if(u.type!=="stack")return;let f=u.children.filter(g=>!g.hidden),d=u.interaction;if(Un(u)){let g=r[u.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},A=n.pickers[u.interaction.pickerId]?.options??[];for(let b of f){let k=b.type==="stack"?b.bind?.plan:void 0;k&&A.includes(k)&&!g.ids.includes(k)&&g.ids.push(k),k&&b.id===t[u.id]&&g.remembered.push(k)}let y=u.children[u.interaction.defaultIndex];y?.type==="stack"&&!y.hidden&&y.bind?.plan&&g.defaults.push(y.bind.plan)}if(d?.type==="tabs"){let g=f.find(A=>A.id===t[u.id])??u.children[d.defaultIndex];g&&i(g)}else if(d?.type==="toggle"){let g=typeof t[u.id]=="boolean"?t[u.id]:d.defaultEnabled,A=u.children[g?0:1];A&&i(A)}else f.forEach(i)}let o=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,a=e.pages.find(u=>u.id===o);a&&i(a.root);let s={};for(let[u,f]of Object.entries(r)){let d=t[u],g=f.remembered[0]??(f.ids.includes(n.pickers[u]?.selected??"")?n.pickers[u]?.selected:f.defaults[0]);s[u]=typeof d=="string"?f.ids.includes(d)?d:"":g&&f.ids.includes(g)?g:""}for(let u of Object.keys(zn(e)))s[u]??="";return s}import{z as Y}from"zod";var Fn=Y.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Vn=Y.strictObject({tiers:Y.array(Y.strictObject({id:Fn,name:Y.string().trim().min(1).max(80)})).min(1).max(8),assignments:Y.array(Y.strictObject({productVersionId:Y.string().min(1).max(200),tierId:Fn,period:Y.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Bn(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}function hs(e){let t=_t(e).map(n=>`\u672A\u77E5\u53D8\u91CF\uFF1A${n}`);for(let n=0;n<e.length;n++){if(e[n]!=="<"||!/[A-Za-z!/?{]/.test(e[n+1]??""))continue;let r=n;if(e.startsWith("<!--",n)){let i=e.indexOf("-->",n+4);n=i<0?e.length:i+2}else{let i="";for(n++;n<e.length;n++){let o=e[n];if(i)o===i&&(i="");else if(o==='"'||o==="'")i=o;else if(o===">")break}}/\{\{|\}\}/.test(e.slice(r,n+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}import{z as m}from"zod";var j={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},qn=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),L=m.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!qn.has(e),"Reserved UI identifier"),wt=m.union([m.string().max(2e3),m.number().finite(),m.boolean(),m.null()]),ui=m.discriminatedUnion("type",[m.strictObject({type:m.literal("enum"),values:m.array(wt).min(1).max(j.enumValues),default:wt}),m.strictObject({type:m.literal("number"),min:m.number().finite(),max:m.number().finite(),step:m.number().finite().positive(),default:m.number().finite()}),m.strictObject({type:m.literal("text"),maxLength:m.number().int().min(0).max(2e3),default:m.string().max(2e3).nullable()}),m.strictObject({type:m.literal("boolean"),default:m.boolean()})]);function qe(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var li=ui.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),qe(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),pi=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function di(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var se=m.lazy(()=>m.union([wt,m.strictObject({ref:L}),m.strictObject({op:m.enum(pi),args:m.array(se).max(j.expressionNodes)}).superRefine((e,t)=>{di(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function H(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ae(e,t,n){if(!e||typeof e!="object")return!0;if(!H(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(qn.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function he(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let o=i.pop();if(++r.nodes>j.expressionNodes||o.depth>j.depth){t.addIssue({code:"custom",path:o.path,message:"UI expression budget exceeded"});return}if(!ae(o.value,t,o.path))return;if(H(o.value)&&Array.isArray(o.value.args)){if(o.value.args.length>j.expressionNodes){t.addIssue({code:"custom",path:[...o.path,"args"],message:"UI expression budget exceeded"});return}for(let a=o.value.args.length-1;a>=0;a--)i.push({value:o.value.args[a],depth:o.depth+1,path:[...o.path,"args",a]})}}}var Ss=m.unknown().superRefine((e,t)=>{he(e,t,[],{nodes:0})}).pipe(se),Ot=m.record(L,se).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=j.state,"UI assignments need 1\u201332 state keys"),fi=m.strictObject({target:L,property:m.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:se,className:L.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),mi=m.discriminatedUnion("type",[m.strictObject({type:m.literal("scroll_latch"),target:L,state:L}),m.strictObject({type:m.literal("input"),target:L,state:L,set:Ot.optional()}),m.strictObject({type:m.literal("action"),target:L,set:Ot}),m.strictObject({type:m.literal("carousel"),target:L,state:L,initialIndex:m.number().int().nonnegative().optional(),maxWidth:m.number().int().min(1).max(1e4).optional(),previousTarget:L.optional(),nextTarget:L.optional(),inactiveTargets:m.array(L).max(20).optional(),inactiveMaxWidth:m.number().int().min(1).max(1e4).optional()})]),gi=m.strictObject({afterMs:m.number().int().min(0).max(6e4),set:Ot}),bi=m.strictObject({type:m.literal("mosaic_waves"),target:L,color:m.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:m.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:se.optional(),speed:m.number().min(0).max(4).optional(),pitch:m.number().min(.05).max(4).optional(),fill:m.number().min(.05).max(1).optional(),feather:m.number().min(0).max(1).optional(),warp:m.number().min(0).max(4).optional(),warpScale:m.number().min(0).max(32).optional(),detailScale:m.number().min(0).max(32).optional(),waveScale:m.number().min(0).max(32).optional(),falloff:m.number().min(.1).max(32).optional(),brightness:m.number().min(0).max(32).optional(),ambient:m.number().min(0).max(1).optional(),gamma:m.number().min(.05).max(8).optional(),vignette:m.number().min(0).max(1).optional(),opacity:m.number().min(0).max(1).optional()}),hi=m.strictObject({type:m.literal("number_counter"),target:L,value:se,prefix:m.string().max(20).optional(),format:m.enum(["number","short"]).optional()}),yi=m.strictObject({state:m.record(L,li).refine(e=>Object.keys(e).length<=j.state,"Too many UI state keys").optional(),derived:m.record(L,se).refine(e=>Object.keys(e).length<=j.derived,"Too many UI derived keys").optional(),bindings:m.array(fi).max(j.bindings).optional(),controls:m.array(mi).max(j.controls).optional(),timers:m.array(gi).max(j.timers).optional(),effects:m.array(m.discriminatedUnion("type",[bi,hi])).max(j.effects).optional(),clock:m.boolean().optional()});function xi(e,t){if(!ae(e,t,[])||!H(e))return;for(let[r,i]of[["state",j.state],["derived",j.derived]]){let o=e[r];if(!ae(o,t,[r]))return;if(H(o)&&Object.keys(o).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",j.bindings],["controls",j.controls],["timers",j.timers],["effects",j.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!ae(i,t,["effects",r]))return}if(H(e.state))for(let[r,i]of Object.entries(e.state)){if(!ae(i,t,["state",r]))return;if(H(i)&&Array.isArray(i.values)&&i.values.length>j.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(H(e.derived))for(let[r,i]of Object.entries(e.derived))he(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[o,a]of i.entries())if(!(!ae(a,t,[r,o])||!H(a))){if(r==="bindings")he(a.expression,t,[r,o,"expression"],n);else if(ae(a.set,t,[r,o,"set"])&&H(a.set)){if(Object.keys(a.set).length>j.state){t.addIssue({code:"custom",path:[r,o,"set"],message:"Too many UI assignments"});return}for(let[s,u]of Object.entries(a.set))he(u,t,[r,o,"set",s],n)}if(n.nodes>j.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())H(i)&&i.type==="number_counter"?he(i.value,t,["effects",r,"value"],n):H(i)&&i.enabled!==void 0&&he(i.enabled,t,["effects",r,"enabled"],n)}function Mn(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var Hn=m.unknown().superRefine(xi).pipe(yi).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),o=(y,b)=>{for(let k of Mn(y))i.has(k)||t.addIssue({code:"custom",path:b,message:`Unknown UI reference: ${k}`})};for(let[y,b]of Object.entries(e.derived??{}))Object.hasOwn(n,y)&&t.addIssue({code:"custom",path:["derived",y],message:"UI state and derived identifiers must be distinct"}),o(b,["derived",y]);let a=new Set,s=new Set,u=y=>{if(a.has(y))return!1;if(s.has(y))return!0;a.add(y);for(let b of Mn(r[y]))if(Object.hasOwn(r,b)&&!u(b))return!1;return a.delete(y),s.add(y),!0};for(let y of Object.keys(r))if(!u(y)){t.addIssue({code:"custom",path:["derived",y],message:"Cyclic UI derived references"});break}for(let[y,b]of(e.bindings??[]).entries())o(b.expression,["bindings",y,"expression"]);let f=new Set;for(let[y,b]of(e.effects??[]).entries())f.has(b.target)&&t.addIssue({code:"custom",path:["effects",y,"target"],message:"Effect targets must be unique"}),f.add(b.target),b.type==="number_counter"?(o(b.value,["effects",y,"value"]),typeof b.value=="number"&&Math.abs(b.value)>1e12&&t.addIssue({code:"custom",path:["effects",y,"value"],message:"Counter values must be within the display bound"})):b.enabled!==void 0&&o(b.enabled,["effects",y,"enabled"]);let d=(y,b)=>{for(let[k,O]of Object.entries(y))Object.hasOwn(n,k)||t.addIssue({code:"custom",path:[...b,k],message:"UI assignments can only update declared state"}),o(O,[...b,k])},g=new Set,A=new Set;for(let[y,b]of(e.controls??[]).entries()){if(b.type==="carousel"&&b.inactiveMaxWidth!==void 0&&b.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",y,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),b.type==="carousel")for(let k of b.inactiveTargets??[])(k===b.target||A.has(k))&&t.addIssue({code:"custom",path:["controls",y,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),A.add(k);if(b.type==="carousel")for(let k of["previousTarget","nextTarget"]){let O=b[k];O!==void 0&&((O===b.target||g.has(O)||(e.controls??[]).some(U=>U.target===O))&&t.addIssue({code:"custom",path:["controls",y,k],message:"Carousel navigation needs a distinct, exclusive button target"}),g.add(O))}if(b.type!=="action"){let k=Object.hasOwn(n,b.state)?n[b.state]:void 0;(!k||b.type==="input"&&k.type==="enum"&&k.values.some(O=>typeof O!="string"))&&t.addIssue({code:"custom",path:["controls",y,"state"],message:"Control needs a supported declared UI state"}),b.type==="carousel"&&(k?.type!=="number"||!Number.isInteger(k.min)||k.min<0||!Number.isInteger(k.max)||k.step!==1||b.initialIndex!==void 0&&!qe(k,b.initialIndex))&&t.addIssue({code:"custom",path:["controls",y],message:"Carousel needs bounded nonnegative integer index state"}),b.type==="scroll_latch"&&k?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",y,"state"],message:"Scroll latches require boolean UI state"})}(b.type==="input"||b.type==="action")&&b.set&&d(b.set,["controls",y,"set"])}for(let[y,b]of(e.timers??[]).entries())d(b.set,["timers",y,"set"])});import{z as Si}from"zod";var Qn=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,ye=Si.string().max(16).regex(Qn,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");function vt(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:n,script:r,region:i}=new Intl.Locale(t),o=[n,r,i].filter(Boolean).join("-");return Qn.test(o)?o:null}catch{return null}}var ki=new Set(["TW","HK","MO"]);function Gn(e){let[t,n,r]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let i=n?.length===4?n:void 0,o=n?.length===4?r:n;return i?`zh-${i}`:o&&ki.has(o)?"zh-Hant":"zh-Hans"}function Kn(e,t,n){let r=t.map(i=>({code:ye.parse(i),normalized:i}));for(let i of e){let o=vt(i);if(!o)continue;let a=r.find(d=>d.normalized===o);if(a)return a.code;let s=Gn(o),u=r.filter(d=>Gn(d.normalized)===s),f=u.find(d=>!d.normalized.includes("-")||d.normalized===s)??u[0];if(f)return f.code}return n}var Ai=4,Q={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},_e=c.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),w=c.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ii=c.enum(["none","xs","sm","md","lg","xl"]),Ei=c.enum(["none","sm","md","lg","full"]),Rt=c.string().regex(/^#[0-9a-fA-F]{6}$/),Ct=c.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Nt=c.union([Ct,c.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),c.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),c.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Zn=c.object({primary:Rt,background:Rt,text:Rt,radius:Ei,font:c.enum(["system","serif","rounded","mono"]),fontAssets:c.object({family:c.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:c.array(c.object({url:Ct,weight:c.number().int().min(100).max(900).multipleOf(100),family:c.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),we=c.union([c.enum(["primary","text","muted","background","surface"]),c.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),I=(e,t)=>c.number().int().min(e).max(t),Wn=c.union([c.enum(["fit","fill"]),I(1,1200)]),_i=c.object({top:I(0,200),right:I(0,200),bottom:I(0,200),left:I(0,200)}).strict(),wi=c.object({top:I(-100,200),right:I(-100,200),bottom:I(-100,200),left:I(-100,200)}).strict(),Jn=c.object({x:I(0,100),y:I(0,100)}).strict(),Oi=c.discriminatedUnion("type",[c.object({type:c.literal("color"),color:we}).strict(),c.object({type:c.literal("linear"),angle:I(0,360),stops:c.array(c.object({color:we,at:I(0,100)}).strict()).min(2).max(4)}).strict(),c.object({type:c.literal("image"),src:Nt,fit:c.enum(["cover","contain"]),position:Jn.optional()}).strict()]),vi=c.discriminatedUnion("type",[c.object({type:c.literal("rect"),radius:c.union([I(0,200),c.object({topLeft:I(0,200),topRight:I(0,200),bottomRight:I(0,200),bottomLeft:I(0,200)}).strict()])}).strict(),c.object({type:c.literal("pill")}).strict()]),Ri=c.object({width:I(0,12),color:we,style:c.enum(["solid","dashed"])}).strict(),Ni=c.object({x:I(-40,40),y:I(-40,40),blur:I(0,80),spread:I(-20,40),color:we}).strict(),Ci=c.object({font:c.enum(["system","serif","rounded","mono"]),size:I(8,96),weight:c.number().int().min(100).max(900).multipleOf(100),lineHeight:c.number().min(.8).max(3),letterSpacing:c.number().min(-5).max(20),color:we,align:c.enum(["start","center","end"]),italic:c.boolean(),decoration:c.enum(["none","underline","line-through"]),transform:c.enum(["none","uppercase"])}).strict().partial(),ce=c.object({width:Wn,height:Wn,padding:_i,margin:wi,gap:I(0,120),grow:c.union([c.boolean(),c.number().min(0).max(12)]),background:Oi,opacity:c.number().min(0).max(1),clipContent:c.boolean(),shape:vi,border:Ri,shadow:Ni,text:Ci}).strict().partial(),F={id:_e,name:c.string().trim().min(1).max(60).optional(),hidden:c.boolean().optional(),style:ce.optional(),fallback:w.optional()},ji=c.object({...F,type:c.literal("text"),productField:c.enum(["name","price","trial","period"]).optional(),feature:c.object({id:c.uuid(),field:c.enum(["name","allowance"])}).strict().optional(),text:w,variant:c.enum(["title","heading","body","caption"])}).strict(),Ti=c.object({...F,type:c.literal("image"),src:Nt,localizedSrc:c.record(ye,Nt).optional(),alt:w,aspect:c.enum(["auto","1:1","4:3","16:9","3:1"]),fit:c.enum(["cover","contain"]),position:Jn.optional()}).strict(),Di=c.object({...F,type:c.literal("button"),label:w,variant:c.enum(["primary","secondary","link"]),action:w,purpose:c.enum(["purchase","navigation","close"]).optional(),bind:Me.optional()}).strict(),Pi=c.object({...F,type:c.literal("divider")}).strict(),Li=c.object({...F,type:c.literal("customer_data"),title:w,data:Tn}).strict(),Ui=c.object({...F,type:c.literal("spacer"),size:Ii}).strict(),zi=c.object({...F,type:c.literal("custom_html"),html:c.record(ye,c.string().max(Q.customHtml)),css:c.string().max(Q.customCss),ui:Hn.optional()}).strict(),$i=c.object({...F,type:c.literal("price"),fallback:w,parts:c.object({current:ce.optional(),original:ce.optional(),period:ce.optional()}).strict().optional()}).strict(),Fi=c.object({...F,type:c.literal("coupon_code"),label:w,fallback:w}).strict(),Vi=c.object({...F,type:c.literal("countdown"),source:c.enum(["offer.ends_at","offer.expires_at","fixed"]),at:c.iso.datetime().optional(),granularity:c.enum(["day","hour","minute","second"]),expired:w,fallback:w}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Bi=c.object({...F,type:c.literal("plan_picker"),label:w,fallback:w,planIds:c.array(c.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:c.string().min(1).max(200).optional(),grouping:Vn.safeExtend({monthLabel:w,yearLabel:w,unavailableLabel:w}).optional(),states:c.object({selected:ce.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Bn(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Mi=c.object({...F,type:c.literal("quantity_picker"),bind:Me.optional(),label:w,fallback:w,internalFeatureId:c.uuid(),minimumQuantity:I(0,1e4),maximumQuantity:I(0,1e4),defaultQuantity:I(0,1e4),step:I(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),qi=c.discriminatedUnion("type",[c.object({type:c.literal("input"),label:w,keyboard:c.enum(["text","email","tel","url"]),maxLength:I(1,500)}).strict(),c.object({type:c.literal("multiselect"),label:w,min:I(0,50),max:I(1,50)}).strict(),c.object({type:c.literal("select"),label:w,defaultIndex:I(0,49),purpose:c.enum(["option","product","tier"]).optional(),pickerId:_e.optional(),selectedStyle:ce.optional()}).strict(),c.object({type:c.literal("tabs"),label:w,defaultIndex:I(0,49),purpose:c.literal("tier").optional()}).strict(),c.object({type:c.literal("toggle"),label:w,defaultEnabled:c.boolean()}).strict(),c.object({type:c.literal("carousel"),label:w}).strict()]),G={...F,type:c.literal("stack"),direction:c.enum(["vertical","horizontal","overlay"]),align:c.enum(["start","center","end","stretch"]),justify:c.enum(["start","center","end","between"]),productSlot:c.object({index:I(0,19),period:c.enum(["month","year"]).optional(),requireBinding:c.boolean().optional()}).strict().optional(),interaction:qi.optional(),states:c.object({selected:ce.optional()}).strict().optional(),purpose:c.literal("benefits").optional(),purchaseAction:w.optional(),buttonVariant:c.enum(["primary","secondary","link"]).optional(),bind:Me.optional()},Yn=c.lazy(()=>c.object({...F,type:G.type,direction:G.direction,align:G.align,justify:G.justify,children:c.array(Hi).max(Q.children),productSlot:G.productSlot,interaction:G.interaction,states:G.states,purpose:G.purpose,purchaseAction:G.purchaseAction,buttonVariant:G.buttonVariant,bind:G.bind}).strict()),Hi=c.lazy(()=>c.union([Yn,ji,Ti,Di,Pi,Ui,zi,$i,Fi,Vi,Bi,Mi,Li])),Gi=c.union([c.string().max(500),c.number().finite(),c.boolean(),c.null()]),Ee={id:w,event:w,properties:c.record(w,Gi).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Qi=c.discriminatedUnion("type",[c.object({...Ee,type:c.literal("navigate"),close:c.literal(!1),pageId:_e}).strict(),c.object({...Ee,type:c.literal("event"),close:c.boolean()}).strict(),c.object({...Ee,type:c.literal("close"),close:c.literal(!0)}).strict(),c.object({...Ee,type:c.literal("open_url"),close:c.boolean(),url:Ct}).strict(),c.object({...Ee,type:c.literal("claim_offer"),close:c.boolean(),couponId:c.uuid()}).strict()]),Ki=c.object({defaultLocale:ye,locales:c.record(ye,c.record(w,c.string().max(Q.stringLength)))}).strict(),Zi=c.enum(["popup","paywall","onboarding","page","banner"]);var Wi=c.object({kind:c.literal("screen"),schemaVersion:c.literal(Ai),name:c.string().trim().min(1).max(80),surface:Zi,initialPageId:_e.optional(),presentation:Ln,theme:Zn,pages:c.array(c.object({id:_e,name:c.string().trim().min(1).max(60),root:Yn,theme:Zn.optional(),editorPosition:c.object({x:c.number().finite().min(-1e5).max(1e5),y:c.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Q.pages),strings:Ki,actions:c.array(Qi).max(Q.actions)}).strict();function W(e,t){for(let n of e.pages)jt(n.root,t)}var js=Wi.superRefine((e,t)=>{let n=Q;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(d=>d.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let d of e.actions)d.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(g=>g.id===d.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=d=>t.addIssue({code:"custom",message:d}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>Q.locales&&r(`\u6700\u591A ${Q.locales} \u79CD\u8BED\u8A00`);let o=new Set;for(let d of e.actions)o.has(d.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${d.id}`),o.add(d.id);let a=new Set;for(let d of e.pages)["next","back"].includes(d.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${d.id}`),a.has(d.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${d.id}`),a.add(d.id);let s=new Set,u=0,f=!1;W(e,(d,g)=>{if(u++,g>Q.depth&&(f=!0),s.has(d.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${d.id}`),s.add(d.id),d.type==="button"&&!o.has(d.action)&&r(`\u6309\u94AE ${d.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${d.action}`),d.type==="custom_html")for(let A of Object.keys(d.html))i.includes(A)||r(`\u81EA\u5B9A\u4E49 HTML ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${A}`);if(d.type==="image")for(let A of Object.keys(d.localizedSrc??{}))i.includes(A)||r(`\u56FE\u7247 ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${A}`)}),u>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),f&&r(`\u5C42\u7EA7\u6700\u591A ${Q.depth} \u5C42`)});function jt(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)jt(i,t,n+1,e)}function Xn(e){let t=[],n=new Set;return W(e,r=>{let i=(o,a,s)=>{n.has(o)||(n.add(o),t.push({key:o,nodeId:r.id,nodeType:r.type,field:a,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function Ji(e,t,n){if(t.field==="html"){let r;return W(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Tt(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function Yi(e){let t=Xn(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(o=>!Ji(e,o,r)?.trim()).map(o=>o.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function Xi(e){return Yi(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Ts(e,t){return Kn(t,Xi(e),e.strings.defaultLocale)}function Ds(e,t){let n=e.strings.locales[t]??{},r=e.strings.locales[e.strings.defaultLocale]??{},i={};for(let a of Xn(e)){if(a.field==="html"||a.field==="src")continue;let s=n[a.key]?.trim()?n[a.key]:r[a.key];s!==void 0&&(i[a.key]=s)}let o=a=>{if(a.type==="stack")return{...a,children:a.children.map(o)};if(a.type==="custom_html"){let s=a.html[t]?.trim()?a.html[t]:a.html[e.strings.defaultLocale];return{...a,html:s===void 0?{}:{[t]:s}}}if(a.type==="image"){let{localizedSrc:s,...u}=a;return{...u,src:s?.[t]??s?.[e.strings.defaultLocale]??a.src}}return a};return{...e,pages:e.pages.map(a=>({...a,root:o(a.root)})),strings:{defaultLocale:t,locales:{[t]:i}}}}function eo(e,t){let n=null;return jt(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Tt(e,t){for(let n of e.pages){let r=eo(n.root,t);if(r)return r}return null}function Ps(e){let t=vt(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function Ls(e,t,n){let r={};if(!t||typeof t!="object"||Array.isArray(t))return r;let i=t;if(W(e,o=>{if(o.type==="quantity_picker"){let s=i[o.id];typeof s=="number"&&Number.isSafeInteger(s)&&s>=o.minimumQuantity&&s<=o.maximumQuantity&&(s-o.minimumQuantity)%o.step===0&&(r[o.id]=s);return}if(o.type==="plan_picker"){let s=i[o.id];typeof s=="string"&&(r[o.id]=n?.pickers[o.id]?.options.includes(s)?s:"");return}if(o.type==="custom_html"&&o.ui)for(let[s,u]of Object.entries(o.ui.state??{})){let f=`${o.id}.${s}`,d=i[f];d!==null&&qe(u,d)&&(r[f]=d)}if(o.type!=="stack"||!o.interaction)return;let a=Object.hasOwn(i,o.id)?i[o.id]:void 0;["select","tabs"].includes(o.interaction.type)&&typeof a=="string"&&o.children.some(s=>s.id===a)&&(r[o.id]=a),o.interaction.type==="toggle"&&typeof a=="boolean"&&(r[o.id]=a)}),e.surface==="paywall"&&typeof i.__page=="string"&&e.pages.some(o=>o.id===i.__page)&&(r.__page=i.__page),n){let o={...r};for(let[a,s]of Object.entries(i))(typeof s=="string"||typeof s=="boolean")&&(o[a]=s);Object.assign(r,$n(e,o,n))}return r}import{z as C}from"zod";import{z as p}from"zod";import{z as h}from"zod";var ue=N.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Oe=h.string().min(1).max(120),He=h.enum(["cap","overflow"]),V=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},ve=e=>{try{return e()}catch{return!1}},Vs=h.discriminatedUnion("operation",[h.object({operation:h.literal("quote"),overageBehavior:He.optional(),internal_feature_id:h.uuid(),entityId:h.uuid().optional(),quantity:ue,properties:B}).strict(),h.object({operation:h.literal("consume"),overageBehavior:He.optional(),occurredAt:h.iso.datetime({offset:!0}).optional(),internal_feature_id:h.uuid(),entityId:h.uuid().optional(),quantity:N,properties:B,idempotencyKey:Oe}).strict(),h.object({operation:h.literal("reserve"),occurredAt:h.iso.datetime({offset:!0}).optional(),internal_feature_id:h.uuid(),entityId:h.uuid().optional(),quantity:ue,properties:B,idempotencyKey:Oe,expiresInSeconds:h.number().int().min(1).max(86400)}).strict(),h.object({operation:h.literal("confirm"),operationId:h.uuid(),quantity:ue,properties:B.optional(),idempotencyKey:Oe}).strict(),h.object({operation:h.literal("refund"),operationId:h.uuid(),quantity:ue,idempotencyKey:Oe}).strict(),h.object({operation:h.literal("release"),operationId:h.uuid(),idempotencyKey:Oe}).strict()]),to=h.object({internal_credit_feature_id:h.uuid().nullable(),internal_metered_feature_id:h.uuid(),dimension:h.string().min(1).max(64),counterKey:h.string().min(1).max(240),cycleStart:h.iso.datetime({offset:!0}),unitCost:N,units:ue,amount:Ce,tier:h.number().int().min(1).max(12).nullable()}).strict(),Re=h.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function er(e,t){let n=e.reduce((r,i)=>r+V(i.units,12),0n)-V(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var tr=h.discriminatedUnion("funding",[h.strictObject({funding:h.literal("balance"),sourceId:h.uuid(),rolloverId:h.uuid().nullable(),units:Re.refine(e=>/[1-9]/.test(e)),amount:Ce}),h.strictObject({funding:h.literal("unbilled"),units:Re.refine(e=>/[1-9]/.test(e))}),h.object({funding:h.literal("prepaid"),sourceId:h.uuid(),units:ue,amount:Ce,pricing:h.array(to).min(1).max(12)}).strict().refine(e=>ve(()=>e.pricing.reduce((t,n)=>t+V(n.units,6),0n)===V(e.units,6)&&e.pricing.reduce((t,n)=>t+V(n.amount,12),0n)===V(e.amount,12)&&e.pricing.every(t=>V(t.unitCost,6)*V(t.units,6)===V(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),h.object({funding:h.literal("postpaid"),invoiceLineId:h.uuid().nullable(),units:ue,authorizationId:h.uuid()}).strict()]),Ge=h.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Bs=h.object({allowed:h.boolean(),internal_feature_id:h.uuid(),quantity:N,requestedQuantity:N.optional(),overageBehavior:He.optional(),reason:Ge.nullable(),allocations:h.array(tr).max(500)}).strict().refine(e=>ve(()=>e.allowed?e.reason===null&&er(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>ve(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&V(e.requestedQuantity,6)>=V(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Ms=h.object({id:h.uuid(),internal_feature_id:h.uuid(),kind:h.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:h.uuid().nullable(),quantity:N,requestedQuantity:N.optional(),overageBehavior:He.optional(),accepted:h.boolean(),reason:h.enum([...Ge.options,"expired"]).nullable(),createdAt:h.iso.datetime({offset:!0}),reservationStatus:h.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:h.iso.datetime({offset:!0}).nullable(),allocations:h.array(tr).max(500)}).strict().refine(e=>ve(()=>e.accepted?e.reason===null&&er(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>ve(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&V(e.requestedQuantity,6)>=V(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as K}from"zod";var no=K.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),ro=K.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),nr=K.strictObject({internal_feature_id:K.uuid(),entityId:K.uuid().nullable()}),Qs=nr.extend({quantity:N,expectedRevision:K.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:K.string().min(1).max(120),properties:B.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),rr=nr.extend({operationId:K.uuid().nullable(),usage:N,capacity:no.nullable(),remaining:ro.nullable(),withinLimit:K.boolean(),revision:K.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:K.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[o,a=""]=(i?r.slice(1):r).split(".");if(o===void 0||o==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(o)*10n**12n+BigInt(a.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var J=p.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),Z=p.iso.datetime({offset:!0}),io=p.enum(["access","metered","credit"]),Ne={internal_feature_id:p.uuid(),key:ie,name:p.string().min(1).max(120),kind:io},ec=p.object({customerId:p.uuid(),snapshotAt:Z,memberships:p.array(p.object({id:p.uuid(),productId:p.string().min(1).max(255),productVersionId:p.uuid(),billingProductVersionId:p.uuid(),version:p.number().int().positive(),key:p.string().min(1).max(64),name:p.string().min(1).max(120),groupId:p.string().max(255).nullable(),membershipType:p.enum(["main","addon"]),status:p.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:p.boolean(),accessEnabled:p.boolean(),renewalChange:p.object({productVersionId:p.uuid(),name:p.string().min(1).max(120),version:p.number().int().positive(),effectiveAt:Z,benefitsAppliedAt:Z.nullable(),timing:p.enum(["immediate","renewal"]),changeKind:p.enum(["plan","seats","quantity"]),feature:p.strictObject({internal_feature_id:p.uuid(),name:p.string().min(1).max(80),fromQuantity:p.number().int().min(0).max(1e4),toQuantity:p.number().int().min(0).max(1e4)}).optional(),seat:p.object({key:p.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:p.number().int().min(0).max(1e4),toQuantity:p.number().int().min(0).max(1e4)}).strict().nullable(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:p.object({phase:p.enum(["paid","trial"]),startsAt:Z,endsAt:Z.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:p.boolean(),balances:p.array(p.object({...Ne,usageType:p.enum(["consumable","non_consumable"]).nullable(),accessible:p.boolean(),unlimited:p.boolean(),available:J,held:J,debt:J,nextExpiresAt:Z.nullable(),usage:rr.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:p.boolean()}).strict(),ir=p.enum(["source","usage","transaction","invoice","debt","settlement"]),Qe=p.object({at:Z,id:p.uuid(),type:ir}).strict(),tc=p.object({type:ir.nullable(),resourceKey:ie.optional(),kind:p.enum(["purchase","refund"]).optional(),topup:p.boolean().optional(),from:p.iso.date().nullable(),to:p.iso.date().nullable(),after:Qe.nullable(),limit:p.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),xe={id:p.uuid(),occurredAt:Z},oo=p.discriminatedUnion("type",[p.strictObject({...xe,type:p.literal("invoice"),status:p.string().min(1).max(80),paid:J,refunded:J,currency:z,externalId:p.string().nullable()}),p.object({...xe,...Ne,type:p.literal("source"),reason:p.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:J,unlimited:p.boolean(),status:p.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:Z,expiresAt:Z.nullable(),orderId:p.uuid().nullable(),parentSourceId:p.uuid().nullable()}).strict(),p.object({...xe,type:p.literal("usage"),internal_feature_id:p.uuid(),name:p.string().min(1).max(120),kind:p.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:p.uuid().nullable(),quantity:N,accepted:p.boolean(),reason:p.enum([...Ge.options,"expired"]).nullable(),properties:B,reservationStatus:p.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Z.nullable(),charges:p.array(p.discriminatedUnion("funding",[p.strictObject({funding:p.literal("balance"),sourceId:p.uuid(),rolloverId:p.uuid().nullable(),units:Re,amount:J}),p.strictObject({funding:p.literal("unbilled"),units:Re}),p.object({...Ne,funding:p.literal("prepaid"),amount:J}).strict(),p.object({funding:p.literal("postpaid"),invoiceId:p.uuid(),invoiceLineId:p.uuid(),authorizationId:p.uuid(),units:N,currency:z}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),p.object({...xe,type:p.literal("transaction"),purpose:p.enum(["product","invoice"]),productVersionId:p.uuid().nullable(),productName:p.string().min(1).max(120).nullable(),productVersion:p.number().int().positive().nullable(),invoiceId:p.uuid().nullable(),orderId:p.uuid(),originalId:p.uuid().nullable(),kind:p.enum(["purchase","refund"]),amountMinor:p.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),p.object({...xe,...Ne,type:p.literal("debt"),sourceId:p.uuid(),transactionId:p.uuid(),amount:J}).strict(),p.object({...xe,...Ne,type:p.literal("settlement"),sourceId:p.uuid(),debtId:p.uuid(),kind:p.enum(["payment","usage_refund","payment_return"]),amount:J}).strict()]),nc=p.object({customerId:p.uuid(),rows:p.array(oo).max(50),nextCursor:Qe.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var sc=C.discriminatedUnion("kind",[C.object({kind:C.literal("ledger"),cursor:Qe}).strict(),C.object({kind:C.literal("billing"),cursor:C.uuid()}).strict()]),ao=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),so=C.record(C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),C.union([C.string().max(500),C.boolean(),C.array(C.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),co=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Dt(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Dt(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||co.test(n)||Dt(r,t+1)))}var uo=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,cc=C.record(ao,ne).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Dt(e)&&!uo.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var or=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),lo=C.array(C.object({variable:or,componentId:or,required:C.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),uc=C.object({bindings:lo,answers:so,values:C.record(C.string(),ne).optional()}).strict();function ar(e,t,n=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0]??"en",i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},o={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},a=e==="week"?`/${o[r]??o.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?a:`/${n} ${a.slice(1)}${r==="en"?"s":""}`}function hc(e,t){let n=[],r={};W(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let o=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&W(e,a=>{if(a.type==="plan_picker"&&a.id===i.bind?.picker&&o.push(...a.planIds??[]),a.type==="stack"&&a.interaction?.type==="select"&&a.interaction.pickerId===i.bind?.picker)for(let s of a.children)s.type==="stack"&&s.bind?.plan&&o.push(s.bind.plan)}),o.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let a of new Set(o)){let s=t[a]?.prepaid?.find(f=>f.internalFeatureId===i.internalFeatureId)?.terms,u=r[a]??=new Set;(!s||u.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),u.add(i.internalFeatureId)}});for(let[i,o]of Object.entries(t))for(let a of o.prepaid??[])r[i]?.has(a.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${a.internalFeatureId}`);return n}function yc(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let o={};if(W(e,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker"||a.hidden||(a.bind?.plan??(a.bind?.picker?n[a.bind.picker]:void 0))!==t)return;let u=i.prepaid?.find(d=>d.internalFeatureId===a.internalFeatureId)?.terms,f=n[a.id];if(!u||typeof f!="number"||!Number.isSafeInteger(f)||f<Math.max(u.minimumQuantity,a.minimumQuantity)||f>Math.min(u.maximumQuantity,a.maximumQuantity)||(f-a.minimumQuantity)%a.step!==0||o[a.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");o[a.internalFeatureId]=f}),(i.prepaid??[]).some(a=>o[a.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return o}function po(e,t,n){let r=e.terms.prices.find(i=>i.currency===t);if(!r||n<e.terms.minimumQuantity||n>e.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:wn({quantity:n,unitAmountMinor:r.amountMinor,...r.pricing?{pricing:r.pricing}:{}}),allowance:Rn(e.includedAmount,e.terms.units,n)}}function xc(e,t,n,r){let i=!1;if(W(e,s=>{s.type==="quantity_picker"&&(i=!0)}),!i)return t;let o=structuredClone(t);o.quantities={};let a=new Map;W(e,s=>{if(s.hidden)return!1;if(s.type!=="quantity_picker")return;let u=s.bind?.plan??(s.bind?.picker?n[s.bind.picker]??o.pickers[s.bind.picker]?.selected:void 0),f=typeof u=="string"?o.plans[u]:void 0,d=f?.prepaid?.find(re=>re.internalFeatureId===s.internalFeatureId),g=Math.max(s.minimumQuantity,d?.terms.minimumQuantity??0),A=Math.min(s.maximumQuantity,d?.terms.maximumQuantity??0),y=n[s.id]??s.defaultQuantity,b=typeof y=="number"&&Number.isSafeInteger(y)?y:s.defaultQuantity,k=!!d&&!!f?.available&&b>=g&&b<=A&&(b-s.minimumQuantity)%s.step===0,O=o.quantities[s.id]={minimum:g,maximum:Math.max(g,A),step:s.step,value:b,label:"",available:k};if(!k||!d||!f?.currency||f.amountMinor===void 0)return;let U=po(d,f.currency,b);O.label=`${new Intl.NumberFormat(r).format(Number(U.allowance))} ${d.name}${["week","month","year"].includes(d.reset)?ar(d.reset,r,d.resetCount):d.reset==="lifetime"?"":` / ${d.resetCount} ${d.reset}`}`,a.set(String(u),(a.get(String(u))??f.amountMinor)+U.amountMinor)});for(let[s,u]of a){let f=o.plans[s];if(!f?.currency)continue;let d=We(u,f.currency,r);f.price=d;for(let[g,A]of Object.entries(o.nodes)){let y=Tt(e,g),b=k=>{if(k.price&&(k.price={...k.price,current:d,original:null}),y?.type==="text"){let O=e.strings.locales[r]?.[y.text]??e.strings.locales[e.strings.defaultLocale]?.[y.text];O?.includes("{{plan.price")&&(k.text=O.replace(/\{\{\s*plan.price\s*\}\}/g,d).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,We(Math.round(u/((f.interval==="year"?12:1)*(f.intervalCount??1))),f.currency,r)))}};A.byPlan?.[s]&&b(A.byPlan[s]),(A.base.planVersionId===s||y&&"bind"in y&&y.bind?.plan===s)&&b(A.base)}}return o}import{z as D}from"zod";var Ke=D.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"]),Ic=D.enum([...Ke.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),Ec=D.enum([...Ke.options,"stale_revision"]),fo=D.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"]),mo=D.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"]),cr={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 sr={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"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",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",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",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",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 go(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(sr,e)){let r=sr[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Ke.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:cr[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function _c(e,t){let n=Ke.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):cr[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function bo(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var ur=D.object({retryable:D.boolean(),recovery:fo,reason:mo.optional(),retryAfterSeconds:D.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),ho=D.object({requestId:D.uuid().optional(),error:D.object({code:D.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:D.string(),...ur.partial().shape})}),wc=D.object({error:ho.shape.error.extend({requestId:D.uuid().optional()})}),Oc=D.object({error:D.string(),code:D.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:D.uuid(),...ur.shape});function vc(e,t,n={}){let r=go(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,o=r.retryable&&n.retryable!==!1&&i!=="recover_operation",a=o?bo(n.retryAfter??null):void 0;return{...r,retryable:o,recovery:i,...a===void 0?{}:{retryAfterSeconds:a},...n.reason?{reason:n.reason}:{}}}export{qo as a,Ke as b,fo as c,mo as d,_c as e,ho as f,vc as g,z as h,dr as i,We as j,De as k,Le as l,Wt as m,Ue as n,Jt as o,Ce as p,N as q,fr as r,B as s,Eo as t,Ft as u,Se as v,na as w,Or as x,vr as y,ot as z,ia as A,oa as B,aa as C,At as D,wn as E,vn as F,Rn as G,fe as H,pt as I,pn as J,q as K,hn as L,yn as M,In as N,ne as O,St as P,Be as Q,Hr as R,ei as S,ye as T,vt as U,Vs as V,to as W,Re as X,Bs as Y,Ms as Z,nr as _,Qs as $,rr as aa,J as ba,ec as ca,tc as da,nc as ea,Et as fa,Nn as ga,ns as ha,Cn as ia,rs as ja,zn as ka,Vn as la,Bn as ma,ss as na,cs as oa,hs as pa,ps as qa,Ln as ra,ci as sa,Q as ta,w as ua,Nt as va,W as wa,js as xa,jt as ya,Xn as za,Yi as Aa,Ts as Ba,Ds as Ca,Tt as Da,Ps as Ea,Ls as Fa,sc as Ga,so as Ha,cc as Ia,lo as Ja,uc as Ka,ar as La,hc as Ma,yc as Na,xc as Oa};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as d,b as te,c as U,d as ne,n as j,q as re}from"./chunk-2JBNOE2D.js";import{b as ee}from"./chunk-YNMSSQQY.js";import{a as o}from"./chunk-KHIQQNTR.js";import{a as J}from"./chunk-DSPLGTQI.js";import{Ca as c,Ea as G,Pa as Z,_ as $,a as K,b as Q,c as W,d as M,e as H,f as X,q as B}from"./chunk-GSFNAB3W.js";import{a as Y}from"./chunk-4SWGHICJ.js";var L=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new o("INVALID_STATE","Installation sequence exhausted");return t+1},we=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new o("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ie(t,e,n){let r=null,s=0,a=0,l=0,I=Promise.resolve(),v=!1;if(t&&(!n||Y.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new o("SCOPE_MISMATCH","Push installation belongs to another scope");let y=()=>{if(v)throw new o("CLOSED","SDK client was destroyed");if(!t)throw new o("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==s)throw new o("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(i){let u=y();if(!u.sha256&&!globalThis.crypto?.subtle)throw new o("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let p=u.sha256?await u.sha256(Uint8Array.from(i,h=>h.charCodeAt(0))):await we(i);if(!/^[a-f0-9]{64}$/.test(p))throw new o("INVALID_STATE","Push credential digest is invalid");return p}function f(i){let u=H.parse(i);if(u.installationId.toLowerCase()!==y().installationId.toLowerCase())throw new o("INVALID_RESPONSE","Push response belongs to another installation");return u}async function C(i,u){let p=y(),h={installationId:p.installationId,publicKey:p.publicKey,issuedAt:new Date().toISOString(),...u},P=await p.sign(X(i,p.scope,h));return{...h,signature:P}}let m=(i,u,p)=>e.requestWithCredential?e.requestWithCredential(i,u,p):e.request(i,u);async function w(){let i=y(),u=s,p=r?await(e.session?.access()??r):null,h=_(i,A=>A),P;if(h.detachSeq!==null){let A=h.detachSeq,V=K.parse(await C("detach",{sequence:A,platform:i.platform}));try{let N=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new o("INVALID_RESPONSE","Push detach acknowledgement is invalid");let F=f(N.installation);if(F.bound||F.identitySeq!==A)throw new o("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof o&&N.status===404)P=N;else if(!(N instanceof o)||N.status!==412)throw N}P||_(i,N=>({...N,detachSeq:N.detachSeq===A?null:N.detachSeq}))}if(O(u),!p){if(P)throw P;return null}let R=c.bindPushInstallation,k=R.request.parse(await C("bind",{sequence:l,platform:i.platform,credentialDigest:await D(p)}));O(u);let q=R.response.parse(await m(R.path,k,p));O(u);let T=f(q.installation);if(!T.bound||T.identitySeq!==l)throw new o("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return P&&h.detachSeq!==null&&l>h.detachSeq&&_(i,A=>({...A,detachSeq:A.detachSeq===h.detachSeq?null:A.detachSeq})),T}async function E(){y();let i=s,u=r?await(e.session?.access()??r):null;if(!u)throw new o("NOT_IDENTIFIED","Identify before reading this installation");let p=c.readPushInstallation,h=p.request.parse(await C("read",{credentialDigest:await D(u)}));O(i);let P=p.response.parse(await m(p.path,h,u));return O(i),f(P.installation)}function g(i=w){let u=I.catch(()=>{}).then(i);return I=u,u.catch(p=>{try{t?.onError?.(p instanceof Error?p:new Error("Push synchronization failed"))}catch{}}),u}async function S(i,u,p){let h=y(),P=u.identity,R=u.observation,k=r?await(e.session?.access()??r):null;if(O(P),R!==a)throw new o("INVALID_STATE","Push observation changed during recovery");if(!k)throw new o("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new o("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await g(async()=>{if(O(P),await w(),O(P),R!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let q=_(h,F=>p?F:{...F,addressSeq:L(F.addressSeq)}),A=await C(p?"recovery_confirm":"recovery_request",{...i,sequence:q.addressSeq,credentialDigest:await D(k),...p?{challenge:p}:{}}),V=p?W.parse(A):Q.parse(A);if(O(P),R!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let N=await m(`push/installations/recovery/${p?"confirm":"request"}`,V,k);if(O(P),R!==a||_(h,F=>F).addressSeq!==q.addressSeq)throw new o("INVALID_STATE","Push observation changed during recovery");if(p){let F=c.updatePushAddress.response.parse(N),x=f(F.installation);if(!x.bound||x.identitySeq!==l||x.addressSeq!==q.addressSeq||x.connectionId!==i.connectionId||x.addressStatus!=="active")throw new o("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return x}if(!N||typeof N!="object"||!("recovery"in N))throw new o("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return M.parse(N.recovery)})}return{recoveryObserver(){y();let i={identity:s,observation:++a};return{async request(u){return M.parse(await S(u,i))},async confirm(u,p){return H.parse(await S(p,i,u))}}},identify(i){if(!t)return;l=_(t,p=>({...p,identitySeq:L(p.identitySeq)})).identitySeq,r=i,s++,a++},reset(){if(t)try{_(t,i=>{let u=L(i.identitySeq);return{...i,identitySeq:u,detachSeq:u}})}finally{r=null,s++,a++}},start(){t&&!v&&g()},destroy(){v=!0,r=null,s++,a++},async sync(){return await g()},read:E,async recover(){let i=y(),u=s,p=l;return a++,await g(async()=>{O(u);let h=await E();return O(u),l=_(i,R=>{if(R.identitySeq!==p)throw new o("IDENTITY_CHANGED","A newer installation intent exists");return{...R,identitySeq:L(Math.max(R.identitySeq,h.identitySeq)),addressSeq:Math.max(R.addressSeq,h.addressSeq)}}).identitySeq,await w()})},tokenObserver(){y();let i=++a,u=s;return async p=>{if(i!==a||u!==s)return null;let h=y(),P=r?await(e.session?.access()??r):null;if(!P)throw new o("NOT_IDENTIFIED","Identify before registering a Push token");if(await g(),O(u),i!==a)return null;let R=_(h,A=>({...A,addressSeq:L(A.addressSeq)})),k=c.updatePushAddress,q=k.request.parse(await C("address",{...p,sequence:R.addressSeq,credentialDigest:await D(P)}));if(O(u),i!==a)return null;let T=await m(k.path,q,P);return O(u),i!==a||_(h,A=>A).addressSeq!==R.addressSeq?null:f(k.response.parse(T).installation)}}}}function se(t,e){let n={async preference(r){let s=c.readMessagingPreference;return(await d(t,s,{channel:r})).preference},async setPreference(r){let s=c.setMessagingPreference;return(await d(t,s,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}function oe(t,e,n={}){let r=!1;function s(){if(r)throw new o("CLOSED","SDK client was destroyed")}let a=new Set,l=v=>{for(let y of a)try{y(v)}catch{}},I=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:s,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(v){return s(),a.add(v),()=>{a.delete(v)}},identify(v){s();let y=typeof v=="string"?v:v.accessToken;if(!B.test(y))throw new o("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(y),t.identify(v)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,I(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function b(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new o("INVALID_REQUEST","Customer requests use the verified session identity")}var ve={...c.readHoldings,request:c.readHoldings.request.omit({customerId:!0})};function ae(t){return{async checkEntitlement(e){b(e);let n=c.checkEntitlement,r=n.request.parse(e),s=await d(t,n,r);return te(r.requirement,s.check,void 0,s.scope),s},async readHoldings(e={}){return d(t,ve,e)}}}function ce(t){return{async readLedger(e){let n=c.readLedger;return d(t,n,{query:e})},async readCreditStatement(e){b(e);let n=c.readCreditStatement;return d(t,n,e)},async quoteBalance(e){b(e);let n=c.quoteBalance;return d(t,n,{command:e})}}}function ue(t){return{async setupPayment(e){b(e);let n=c.setupPayment;return d(t,n,e)},async readPaymentSetup(e){b(e);let n=c.readPaymentSetup;return d(t,n,e)},async readBillingInvoice(e){b(e);let n=c.readBillingInvoice;return d(t,n,e)},async readBillingControls(e={}){b(e);let n=c.readBillingControls;return d(t,n,e)},async prepareBillingAuthorization(e){b(e);let n=c.prepareBillingAuthorization;return d(t,n,e)},async confirmBillingAuthorization(e){b(e);let n=c.confirmBillingAuthorization;return d(t,n,e)},async setBillingCoupons(e){b(e);let n=c.setBillingCoupons;return d(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){b(e);let n=c.revokeBillingAuthorization;return d(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){b(e);let n=c.listBillingInvoices;return d(t,n,e)},async confirmBillingAdjustment(e){b(e);let n=c.confirmBillingAdjustment;return d(t,n,e)}}}function de(t){return{async previewUpdate(e){b(e);let n=c.previewUpdate;return d(t,n,e)},async update(e){b(e);let n=c.update;return d(t,n,e)},async readSubscriptionUpdate(e){b(e);let n=c.readSubscriptionUpdate;return d(t,n,e)},async restoreNativePurchase(e){b(e);let n=c.restoreNativePurchase;return d(t,n,e)},async previewAttach(e){b(e);let n=c.previewAttach;return d(t,n,e)},async attach(e){b(e);let n=c.attach;return d(t,n,e)},async readSubscriptionOperation(e){b(e);let n=c.readSubscriptionOperation;return d(t,n,e)}}}function pe(t){return{async redeemReward(e){return b(e),(await d(t,c.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return b(e),(await d(t,c.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return b(e),(await d(t,c.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await d(t,c.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await d(t,c.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await d(t,c.listOffers,{},{response:"Invalid offers response"})).offers}}}function le(t){return{...ae(t),...ce(t),...ue(t),...de(t),...pe(t)}}function me(t){return{async resolveContent(e){b(e);let n=c.resolveContent;return d(t,n,e)},async resolvePaywall(e){b(e);let n=c.resolvePaywall,r=n.request.parse(e),s=await d(t,n,r);return U(r,s.paywall.check,s.scope),s},async resolveOffering(e){b(e);let n=c.resolveOffering,r=n.request.parse(e),s=await d(t,n,r);return U(r,s.check,s.scope),s}}}var z=t=>new TextEncoder().encode(JSON.stringify(t)).length,fe=16384;function ye(t,e){let n=0,r,s=m=>{r={config:structuredClone(m),until:Date.now()+3e4}},a=[],l=null,I;function v(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}function y(){I||!a.length||(I=setTimeout(()=>{I=void 0,D().catch(()=>{}).finally(y)},5e3),typeof I=="object"&&"unref"in I&&I.unref())}function O(m,w={},E={}){if(v(),r&&Date.now()<r.until&&!$(r.config,m))return;C();let g=c.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:m,properties:w,...E}]}).events[0];if(z({events:[g]})>fe)throw new o("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new o("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(g)),y()}async function D(m=!1){if(v(),l)return l;let w=n,E=(async()=>{let g={inserted:0,duplicates:0,rejected:0,skipped:0},S=a.length;for(;S&&w===n;){let i=[],u=z({events:[]});for(let P of a.slice(0,Math.min(S,100))){let R=z(P)+(i.length?1:0);if(i.length&&u+R>fe)break;i.push(P),u+=R}let p=c.trackEvents,h=await d(t,p,{events:i},void 0,{keepalive:m});if(w!==n)throw new o("IDENTITY_CHANGED","Event identity changed during delivery");if(h.inserted+h.duplicates+h.rejected+h.skipped!==i.length)throw new o("INVALID_RESPONSE","Incomplete event acknowledgement");s(h.analyticsConfig),a.splice(0,i.length),S-=i.length,g.inserted+=h.inserted,g.duplicates+=h.duplicates,g.rejected+=h.rejected,g.skipped+=h.skipped}return g})();l=E;try{return await E}finally{l===E&&(l=null)}}let f;function C(){if(f||typeof document>"u")return;let m=()=>{document.visibilityState==="hidden"&&e()&&a.length&&D(!0).catch(()=>{})};document.addEventListener("visibilitychange",m),f=()=>document.removeEventListener("visibilitychange",m)}return{rememberConfiguration:s,track:O,flush:D,reset(){n++,r=void 0,clearTimeout(I),I=void 0,a=[],l=null},detachVisibility(){f?.(),f=void 0}}}function Ie(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function Ae(t){let e=Ie(t),{merchandiseId:n,merchandise:r,...s}=t;return{...s,...e?{merchandise:e}:{}}}function he(t,e,n,r,s){if(s&&r&&(s.scope.projectId!==r.projectId||s.scope.environment!==r.environment))throw new o("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,l=new Set;function I(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}async function v(y={}){s||I();let O=a,D=!1,f=async()=>{if(D||O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let q=c.getFeatures,T=s?{scope:{projectId:s.scope.projectId,environment:s.scope.environment},payload:await s.features()}:await d(t,q,{});if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");if(r&&(T.scope.projectId!==r.projectId||T.scope.environment!==r.environment))throw new o("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(T.payload.analyticsConfig),T},C=await f(),m=!0,w,E=q=>{try{y.onError?.(q)}catch{}},g=(q,T,A)=>{try{let V=Ie(A);n.track(q,T,V?{merchandise:V}:{})}catch(V){E(V)}},S=ne({assertUsable:s?.assertFeatures,scope:C.scope,attributes:y.attributes,onError:y.onError,load:async()=>m?(m=!1,C.payload):(await f()).payload,evaluateRemote:async q=>{if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let T=c.evaluateFeatures,A=await d(t,T,{...q,attributes:Ae(q.attributes)});if(A.scope.projectId!==C.scope.projectId||A.scope.environment!==C.scope.environment)throw new o("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:A.generation,evaluatedAt:A.evaluatedAt,expiresAt:A.expiresAt,features:A.features,...A.merchandiseContext?{merchandiseContext:A.merchandiseContext}:{}}},onExperimentViewed:(q,T,A)=>g("Experiment Viewed",{experimentId:q.key,variationId:T.key},A),onFeatureUsage:(q,T,A)=>g("Feature Evaluated",{feature:q,value:T.value,source:T.source,ruleId:T.ruleId,...T.experimentResult?{variationId:T.experimentResult.key}:{}},A)}),i=S.refresh;function u(){clearTimeout(w),!s&&(D||O!==a||!S.expiresAt||(w=setTimeout(()=>{p().catch(E)},Math.min(2147483647,Math.max(1e3,Date.parse(S.expiresAt)-Date.now()))),typeof w=="object"&&"unref"in w&&w.unref()))}async function p(){try{return await i()}finally{u()}}let h=()=>{D||p().catch(E)},P=S.subscribe(u),R=s?.subscribe(()=>{!D&&s.fresh&&p().catch(E)});function k(){D||(D=!0,clearTimeout(w),typeof window<"u"&&window.removeEventListener("focus",h),P(),R?.(),S.reset(),l.delete(k))}l.add(k);try{await S.init(),(y.attributes?.merchandise||y.attributes?.merchandiseId)&&await S.refreshRemote()}catch(q){throw k(),q}return u(),!s&&typeof window<"u"&&window.addEventListener("focus",h),Object.assign(S,{refresh:p,destroy:k})}return{features:v,reset(y){a++,y();for(let O of l)O()}}}import{z as be}from"zod";function ge(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=be.object({funnelId:G.shape.id,funnelVersionId:G.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new o("INVALID_REQUEST","A valid Funnel source is required");let s=Object.freeze(r.data);function a(l){if("customerId"in l)throw new o("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==s.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==s.funnelVersionId)throw new o("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...s}}return{async claimCoupon(l,I=crypto.randomUUID()){let v=c.grantOffer,y=await d(t,v,a({couponId:l,requestId:I}));return{offer:y.offer,reason:y.reason}},async resolveOffering(l){let I=c.resolveOffering,v=I.request.parse(a(l)),y=await d(t,I,v);return U(v,y.check,y.scope),y},async resolvePaywall(l){let I=c.resolvePaywall,v=I.request.parse(a(l)),y=await d(t,I,v);return U(v,y.paywall.check,y.scope),y},async previewAttach(l){let I=c.previewAttach;return d(t,I,a(l))}}}function xt(t){return Oe(t)}function Oe(t){let e=ee(t),n=e.request,r;try{r=ie(t.push,e,t.scope??t.configuration?.scope)}catch(I){throw e.dispose(),I}let s=oe(e,()=>{l.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ye(n,s.isIdentified),l=he(n,s.isIdentified,a,t.scope,t.configuration);return{session:e.session,...se(n,r),...le(n),...me(n),forFunnel(I){return s.assertActive(),ge(n,I)},async features(I={}){return s.assertActive(),l.features(I)},track(I,v,y={}){return a.track(I,v,y)},flush(){return a.flush()},...s.methods}}function Ht(t){if(!B.test(t.customerToken))throw new o("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new o("INVALID_REQUEST","An explicit App and environment scope is required");let e=re({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),s=j({...t,runToken:r.runToken});s.identify(t.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await s.get():r;return{...r,...a,controller:s}}}}function Qt(t){if(!t.scope)throw new o("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new o("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,s=new Set,a=new Map,l=new Map;async function I(f){let C,m=new Promise((w,E)=>{C=setTimeout(()=>E(new o("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(f),m])}finally{clearTimeout(C)}}function v(f){throw f instanceof o&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear()),f}function y(f,C){if(C!==r)throw new o("IDENTITY_CHANGED","Process was detached during a request");let m=Z.parse(f);if(m.scope.projectId!==t.scope.projectId||m.scope.environment!==t.scope.environment)throw new o("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==m.run.id||e.run.source.versionId!==m.run.source.versionId||e.run.source.id!==m.run.source.id||e.run.runExpiresAt!==m.run.runExpiresAt||e.run.identity.startedAs!==m.run.identity.startedAs||e.run.identity.participantId!==m.run.identity.participantId||e.run.identity.binding&&m.run.identity.binding&&e.run.identity.binding.id!==m.run.identity.binding.id))throw new o("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||m.run.revision>=e.run.revision){if(e?.run.identity.binding&&!m.run.identity.binding)throw new o("INVALID_RESPONSE","The process lost its Customer binding");e=m;for(let h of s)J(h,m.run);m.run.instruction?.type==="authentication_required"&&J(t.onAuthenticationRequired,m.run)}m.settlement?.accepted!==void 0&&l.set(m.settlement.requestId,m.settlement.accepted);let{identity:w,instruction:E,...g}=m.run,{contract:S,settlement:i,...u}=m,p=i&&(({accepted:h,...P})=>P)(i);return{...u,run:{...g,authenticated:w.binding!==null,instruction:E?.type==="authentication_required"?null:E},...p?{settlement:p}:{}}}let O=f=>(a.has(f)||a.set(f,e?.run.identity.binding?.id??null),a.get(f));async function D(f){let C=r,m=e?.run.identity.binding?.id??null,w=g=>{if(m!==(e?.run.identity.binding?.id??null))throw g;return v(g)};if(f.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new o("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return I(()=>t.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(w)}let E;if(f.operation==="get"){let{operation:g,customerToken:S,...i}=f;E=await I(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(w)}else if(f.operation==="review")E=await I(()=>t.adapter.review(f.receiptId)).catch(w);else{if(f.operation==="start")throw new o("INVALID_REQUEST","Use process.open for entry");{let{customerToken:g,...S}=f;E=await I(()=>t.adapter.command(S,O(S.requestId))).catch(w)}}return y(E,C)}return{get view(){return e?.run??null},get controller(){return n},async open(f){let C=r,m=await I(()=>t.adapter.open(f)).catch(v);if(y(m,C),!n){n=j({...t,runToken:m.runToken,process:{request:D,binding:O,restore(g){for(let[S,i]of Object.entries(g))a.set(S,i)}}});let w=n,E=w.submit;w.submit=async g=>{try{return await E(g)}catch(S){if(!(S instanceof o)||S.reason!=="IDENTITY_CONTEXT_CHANGED"||g.operation!=="submit"||g.input.type!=="screen"||a.get(g.requestId)!==null)throw S;await w.settle?.(g.requestId),await w.get();let i=w.view;if(l.get(g.requestId)!==!1||!i||i.id!==e?.run.id||i.nodeId!==g.nodeId||i.visit!==g.visit||!e?.run.identity.binding)throw S;return E({...g,requestId:crypto.randomUUID(),revision:i.revision})}}}await n.get();for(let w of n.pendingCommands??[])a.has(w.requestId)&&a.get(w.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(w.requestId);return{run:e.run,controller:n}},async syncIdentity(){let f=r;y(await I(()=>t.adapter.syncIdentity()).catch(v),f),await n?.get();for(let C of n?.pendingCommands??[])a.has(C.requestId)&&a.get(C.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(C.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),await I(()=>t.adapter.detach())},forProcess(f){if(!e?.run.identity.binding)throw new o("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:f}},subscribe(f){return s.add(f),()=>{s.delete(f)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),s.clear()}}}export{xt as a,Oe as b,Ht as c,Qt as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as $,b as N,c as J,d as q}from"./chunk-
|
|
1
|
+
import{a as $,b as N,c as J,d as q}from"./chunk-LNSFRQ6G.js";import{a as _}from"./chunk-DSPLGTQI.js";import{a as P}from"./chunk-CCRBXW4M.js";import{jb as D}from"./chunk-GSFNAB3W.js";import{I as C,J as O,L as j}from"./chunk-4SWGHICJ.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
|
|
2
2
|
Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
|
|
3
3
|
plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
|
|
4
4
|
*/function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ra as g}from"./chunk-GSFNAB3W.js";async function u(t,r,e){if(Number(t.headers.get("content-length"))>r)throw t.body?.cancel().catch(()=>{}),e.error("limit");let o=t.body?.getReader();if(!o)throw e.error("missing");let i=[],s=0,c=!1,a=()=>{},b=new Promise((n,f)=>{a=()=>f(e.signal?.reason),e.signal?.addEventListener("abort",a,{once:!0}),e.signal?.aborted&&a()});try{for(;;){let n=await Promise.race([o.read(),b]);if(n.done){c=!0;break}if(s+=n.value.length,s>r)throw e.error("limit");i.push(n.value)}}finally{e.signal?.removeEventListener("abort",a),c||o.cancel().catch(()=>{}),o.releaseLock()}e.signal?.throwIfAborted();let l=new Uint8Array(s),d=0;for(let n of i)l.set(n,d),d+=n.length;return l}async function m(t,r,e){return new TextDecoder("utf-8",{fatal:!0}).decode(await u(t,r,e))}function y(t,r){let e=typeof t=="string"?new TextEncoder().encode(t):t;return e.byteLength===r.byteLength&&g(e)===r.sha256}export{u as a,m as b,y as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as t}from"./chunk-2JBNOE2D.js";import{fb as n}from"./chunk-GSFNAB3W.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
|