@tinkerlandai/longplay-sdk 0.10.21-rc.2 → 0.10.21

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.
@@ -1 +1 @@
1
- import{lb as d}from"./chunk-ZC6PDVLR.js";import{a as u}from"./chunk-DSPLGTQI.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
1
+ import{lb as d}from"./chunk-JXNNWCEB.js";import{a as u}from"./chunk-DSPLGTQI.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
@@ -1,4 +1,4 @@
1
- import{a as $,b as N,c as J,d as q}from"./chunk-2QSCQD6Q.js";import{a as P}from"./chunk-KOFZECHE.js";import{kb as D}from"./chunk-ZC6PDVLR.js";import{a as _}from"./chunk-DSPLGTQI.js";import{I as C,J as O,L as j}from"./chunk-HDVLCRC6.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}}/*!
1
+ import{a as $,b as N,c as J,d as q}from"./chunk-53C6LI3D.js";import{a as P}from"./chunk-Z5CW2N7E.js";import{kb as D}from"./chunk-JXNNWCEB.js";import{a as _}from"./chunk-DSPLGTQI.js";import{I as C,J as O,L as j}from"./chunk-HDVLCRC6.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{a as P}from"./chunk-QVGTHPWT.js";import{g as pA,h as xA,i as gA,kb as zA,lb as FA,r as $A}from"./chunk-ZC6PDVLR.js";import{a as sA,b as MA,e as jA,f as UA,g as _A}from"./chunk-HDVLCRC6.js";function S(A){return typeof A=="string"?A:String(A)}var ye=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Pe(A){return A.replace(ye,"$1\uFFFD")}function PA(A,e){if(typeof A!="object"||A==null){let t="";throw t+="The provided value is not an object",new TypeError(t)}return A}function ZA(A){if(A!=null&&(typeof A=="object"||typeof A=="function")){let e=A[Symbol.iterator];if(e==null)return;if(typeof e!="function")throw new TypeError("The provided value is not iterable");let t=e.call(A);if(!t||typeof t!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return t}}function QA(A){let e;if(Array.isArray(A)){let t=A.map(S);if(t.length===2)return t}else if((e=ZA(A))!=null){let t=PA(e.next()),n=PA(e.next());if(!t.done&&!n.done)return[S(t.value),S(n.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var GA="0123456789ABCDEF",De=/(?:%[0-9A-Fa-f]{2})+/g;function U(A){return`%${GA[A>>4&15]}${GA[15&A]}`}function Ae(A,e,t=!1){return A>=55296&&A<=57343&&(A=65533),A<=127?t&&A===32?"+":e(A)?U(A):String.fromCharCode(A):A<=2047?U(192|A>>6)+U(128|63&A):A<=65535?U(224|A>>12)+U(128|A>>6&63)+U(128|63&A):U(240|A>>18)+U(128|A>>12&63)+U(128|A>>6&63)+U(128|63&A)}function DA(A){return A>=48&&A<=57?A-48:A>=65&&A<=70?A-65+10:A>=97&&A<=102?A-97+10:-1}function bA(A,e=!1){let t=0;for(;t<A.length;t++){let n=A.charCodeAt(t);if(n===37||e&&n===43)break}return t===A.length?A:(e?A.replace(/\+/g," "):A).replace(De,n=>{try{return decodeURIComponent(n)}catch{return"\uFFFD".repeat(n.length/3)}})}function AA(A){return A<=31||A>126}function be(A){switch(A){case 32:case 34:case 60:case 62:case 96:return!0;default:return AA(A)}}function qA(A){switch(A){case 32:case 34:case 35:case 60:case 62:return!0;default:return AA(A)}}function Se(A){return qA(A)||A===39}function SA(A){switch(A){case 63:case 94:case 96:case 123:case 125:return!0;default:return qA(A)}}function cA(A){switch(A){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return SA(A)}}function YA(A){switch(A){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(t){switch(t){case 36:case 37:case 38:case 43:case 44:return!0;default:return cA(t)}})(A)}}function ee(A,e){return Ae(A=A||0,e)}function _(A,e,t=!1){let n=0;for(;n<A.length;n++){let u=A.charCodeAt(n);if(u>=128||t&&u===32||e(u))break}if(n===A.length)return A;let r=A.slice(0,n);for(;n<A.length;n++){let u=A.charCodeAt(n),l=u;if(u>=55296&&u<=56319&&n+1<A.length){let a=A.charCodeAt(n+1);a>=56320&&a<=57343&&(l=(u-55296<<10)+a-56320+65536,n++)}r+=Ae(l,e,t)}return r}function NA(A){let e=[],t=0,n=0;for(;n<=A.length;){if(n=A.indexOf("&",t),n<0&&(n=A.length),n!==t){let r=A.slice(t,n),u=r.indexOf("=");u<0&&(u=r.length),e.push([bA(r.slice(0,u),!0),bA(r.slice(u+1),!0)])}if(t=n+1,n===A.length)break}return e}function CA(A){let e="";for(let t=0;t<A.length;t++){let n=_(A[t][0],YA,!0),r=_(A[t][1],YA,!0);e+=t!==0?`&${n}=${r}`:`${n}=${r}`}return e}var Ce=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],Ie=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Ee=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],ve=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function Te(A){for(let e=0;e<A.length;e++){let t=A.codePointAt(e);if(t>65535&&e++,t<=32||t===37||t===127||t>=55296&&t<=57343||t>=128&&t<=159||t>=64976&&t<=65007||!(65534&~t)||t===65533)return!0}return!1}var[qe,Ne,Oe,VA]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([e,t,n]){return[e,t.split(",").map(r=>parseInt(r,36)),Uint8Array.from(atob(n),r=>r.charCodeAt(0))]});function Re(A,e){return e===931||e===1010||e===120531||e===120589||e===120647||e===120705||e===120763?"\u03C3":e>=5112&&e<=5117?String.fromCodePoint(e-8):e>=43888&&e<=43967?String.fromCodePoint(e-38864):e>=93856&&e<=93880?String.fromCodePoint(e+27):e===837||e===890||e>=8064&&e<=8111||e>=8114&&e<=8188?A.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function te(A,e){for(let t=0;t<A.length;t+=2)if(e>=A[t]&&e<=A[t+1])return!0;return!1}function X(A,e){let[t,n,r]=A,u=e>>8;for(let f=0;f<t.length;f+=2)if(u>=t[f]&&u<=t[f+1])return!0;let l=n.indexOf(u);if(l<0)return!1;let a=255&e;return!!(r[32*l+(a>>3)]&1<<(7&a))}function ke(A){let e=Array.from(A,t=>t.codePointAt(0));for(let t=0;t<e.length;t++){let n=e[t];if(n!==8204&&n!==8205||t>0&&te(ve,e[t-1]))continue;if(n===8205)return!1;let r=t-1;for(;r>=0&&X(VA,e[r]);)r--;let u=t+1;for(;u<e.length&&X(VA,e[u]);)u++;if(!(r>=0&&u<e.length&&X(Ne,e[r])&&X(Oe,e[u])))return!1}return!0}var Le=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,Be=/\p{Script=Latin}/u;function He(A){return!Le.test(A)||!Be.test(A)}var F=36,iA=1,IA=26,Me=38,je=700,Ue=72,_e=128,xe=2147483647;function KA(A){return String.fromCharCode(A+22+75*+(A<26))}function $e(A,e,t){let n=0;for(A=t?Math.floor(A/je):A>>1,A+=Math.floor(A/e);A>(F-iA)*IA>>1;n+=F)A=Math.floor(A/(F-iA));return Math.floor(n+(F-iA+1)*A/(A+Me))}function ze(A){let e=Array.from(A,f=>f.codePointAt(0)),t="",n=0;for(let f=0;f<e.length;f++){let h=e[f];h<128&&(t+=String.fromCharCode(h),n++)}let r=n;r&&(t+="-");let u=_e,l=0,a=Ue;for(;n<e.length;){let f=xe;for(let h=0;h<e.length;h++){let w=e[h];w>=u&&w<f&&(f=w)}l+=(f-u)*(n+1),u=f;for(let h=0;h<e.length;h++){let w=e[h];if(w<u&&l++,w===u){let p=l;for(let m=F;;m+=F){let y=m<=a?iA:m>=a+IA?IA:m-a;if(p<y)break;t+=KA(y+(p-y)%(F-y)),p=Math.floor((p-y)/(F-y))}t+=KA(p),a=$e(l,n+1,n===r),l=0,n++}}l++,u++}return t}function wA(A){let e=10;if(A.length>=2&&A[0]==="0"&&(A[1]==="x"||A[1]==="X"))A=A.slice(2),e=16;else if(A.length>=2&&A[0]==="0")A=A.slice(1),e=8;else if(A==="")return-1;let t=0;for(let n=0;n<A.length;n++){let r=DA(A.charCodeAt(n));if(r>=e||r<0)return-1;t=t*e+r}return t}function JA(A){switch(A){case".":case"%2e":case"%2E":return!0;default:return!1}}function ne(A,e){return(A>=65&&A<=90||A>=97&&A<=122)&&(e===58||e===124)}function re(A){return A.length===2&&ne(A.codePointAt(0),A.codePointAt(1))}function WA(A){return A.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function I(A){switch(A){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function se(A){switch(A){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function EA(A,e){if(A[0]==="[")return A[A.length-1]==="]"?(function(n){let r=[0,0,0,0,0,0,0,0],u=null,l=0,a=0,f=Array.from(n,h=>h.codePointAt(0));if(f[a]===58){if(f[a+1]!==58)return null;a+=2,l++,u=l}for(;a<f.length;){if(l===8)return null;if(f[a]===58){if(u!==null)return null;a++,l++,u=l;continue}let h=0,w=0,p=0;for(;p<4&&(h=DA(f[a]))>=0;)w=(w<<4)+h,a++,p++;if(f[a]===46){if(p===0||l>6)return null;a-=p;let m=0;for(;f[a]!==void 0;){let y=0;if(m>0)if(f[a]===46&&m<4)a++;else return null;if(f[a]==null||f[a]<48||f[a]>57)return null;for(;f[a]>=48&&f[a]<=57;){if(y=10*y+DA(f[a]),y>255)return null;a++}r[l]=256*r[l]+y,m++,m%2==0&&l++}if(m!==4)return null;break}else if(f[a]===58){if(f[++a]===void 0)return null}else if(f[a]!==void 0)return null;r[l]=w,l++}if(u!==null){let h=l-u;for(l=7;l!==0&&h>0;){let w=r[u+h-1];r[u+h-1]=r[l],r[l]=w,l--,h--}}else if(u===null&&l!==8)return null;return r})(A.substring(1,A.length-1)):null;if(e)return(function(n){return WA(n)?null:_(n,AA)})(A);{let t=(function(r){let u=!1,l=!1;for(let f=0;f<r.length;f++){let h=r.charCodeAt(f);if(h<=32||h===37||h===127)return null;if(h>=128){u=!0;break}h>=65&&h<=90&&(l=!0)}if(!u)return r!==""?l?r.toLowerCase():r:null;if((function(h){for(let w of h){let p=w.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(w)&&!te(Ce,p)||X(qe,p))return!0}return!1})(r))return null;let a=(r=(function(h){let w="";for(let p of h){let m=p.codePointAt(0);if(m!==8204&&m!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(p))continue;let y=Re(p,m);if(y){w+=y;continue}let N=Ie.indexOf(m);w+=N<0?p:Ee[N]}return w})(r).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let f=0;f<a.length;f++){let h=a[f];if(h==="")continue;let w=/[^\0-\x7f]/.test(h);if(Te(h)||w&&(/^\p{Mark}/u.test(h)||!ke(h)||!He(h)||h.startsWith("xn--")))return null;w&&(a[f]=`xn--${ze(h)}`)}return(r=a.join("."))!==""?r:null})(A.indexOf("%")===-1?A:bA(A));return t===null||WA(t)?null:(function(r){let u=r.length,l=r.lastIndexOf(".",u-2)+1;if(r.charCodeAt(u-1)===46&&u--,u<=l)return!1;if(wA(r.slice(l,u))>=0)return!0;for(;l<u;l++){let a=r.charCodeAt(l);if(a<48||a>57)return!1}return!0})(t)?(function(r){let u=r.split("."),l=u.length;if(u[l-1]||l--,l>4)return null;let a=0;for(let h=0;h<l-1;h++){let w=wA(u[h]);if(w<0||w>255)return null;a+=w*(1<<8*(3-h))}let f=wA(u[l-1]);return f<0||f>=256**(5-l)?null:(a+=f,a)})(t):t}}function vA(A){return typeof A=="number"?(function(t){let r="";return r+=`${(t>>>24&255).toString(10)}.`,r+=`${(t>>>16&255).toString(10)}.`,r+=`${(t>>>8&255).toString(10)}.`,r+=(t&255).toString(10),r})(A):Array.isArray(A)?`[${(function(t){let n=(function(a){let f=-1,h=-1,w=1,p=0;for(let m=0;m<a.length;++m)a[m]!==0?(p>w&&(f=h,w=p),h=-1,p=0):(h===-1&&(h=m),++p);return p>w?h:f})(t),r="",u=!1;for(let l=0;l<=7;++l)if(!(u&&t[l]===0)){if(u&&(u=!1),n===l){r+=l===0?"::":":",u=!0;continue}r+=t[l].toString(16),l!==7&&(r+=":")}return r})(A)}]`:A}function oe(A){A.path.length>0&&(A.path.length!==1||A.scheme!=="file"||!(function(t){return/^[A-Za-z]:$/u.test(t)})(A.path[0]))&&A.path.pop()}function ie(A){return A.username!==""||A.password!==""}function mA(A){return A.host===null||A.host===""||A.scheme==="file"}var s=0,o="",g="",D=null,i,lA=!1,uA=!1,G=!1,E;function B(A,e,t,n){e||(A=(function(l){let a=0,f=l.length;for(;a<f&&!(l.charCodeAt(a)>32);++a);for(;f>a&&!(l.charCodeAt(f-1)>32);--f);return l.substring(a,f)})(A)),A=(function(l){let a=0;for(;a<l.length;a++){let h=l.charCodeAt(a);if(h===9||h===10||h===13)break}if(a===l.length)return l;let f=l.slice(0,a);for(;a<l.length;a++){let h=l.charCodeAt(a);h!==9&&h!==10&&h!==13&&(f+=l[a])}return f})(A),s=0,o=A,g="",D=t||null,i=e||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},lA=!1,uA=!1,G=!1,E=n||0;let r=Fe;switch(n){case 3:case 4:r=aA;break;case 5:r=RA;break;case 6:r=Y;break;case 7:r=Q;break;case 8:r=x}return r(c(A,s))!==1?i:null}function d(A,e){return s+=s===A?M(e):1,s<=o.length}function c(A,e){return e<A.length?A.codePointAt(e):void 0}function M(A){return A!=null&&A>65535?2:1}function le(A){return A==null?"":A<=65535?String.fromCharCode(A):String.fromCodePoint(A)}var Fe=A=>{let e=s;if(A!=null&&(A>=65&&A<=90||A>=97&&A<=122)){let t=s+1;for(A=o.charCodeAt(t);A===43||A===45||A===46||A>=65&&A<=90||A>=97&&A<=122||A>=48&&A<=57;)t++,A=o.charCodeAt(t);return g=o.slice(s,t).toLowerCase(),s=t,Qe(t<o.length?A:void 0)}else return E?1:(--s,d(e,A)?ue(c(o,s)):0)},Qe=A=>{let e=s;if(A===58){if(E){if(I(i.scheme)!==I(g))return 0;if((ie(i)||i.port!==null)&&g==="file")return 0;if(i.scheme==="file"&&i.host==="")return 0}return i.scheme=g,E?(i.port===se(i.scheme)&&(i.port=null),0):(g="",i.scheme==="file"?d(e,A)?kA(c(o,s)):0:I(i.scheme)&&D!==null&&D.scheme===i.scheme?d(e,A)?Ge(c(o,s)):0:I(i.scheme)?d(e,A)?Ve(c(o,s)):0:c(o,s+1)===47?(s++,d(e,A)?Ye(c(o,s)):0):(i.path=[""],i.opaquePath=!0,d(e,A)?ae(c(o,s)):0))}else return E?1:(g="",s=-1,d(e,A)?ue(c(o,s)):0)},ue=A=>{let e=s;return D===null||D.opaquePath&&A!==35?1:D.opaquePath&&A===35?(i.scheme=D.scheme,i.path=D.path.slice(),i.opaquePath=D.opaquePath,i.query=D.query,i.fragment="",d(e,A)?x(c(o,s)):0):D.scheme==="file"?(s--,d(e,A)?kA(c(o,s)):0):(s--,d(e,A)?OA(c(o,s)):0)},Ge=A=>{let e=s;return A===47&&c(o,s+1)===47?(++s,d(e,A)?hA(c(o,s)):0):(s--,d(e,A)?OA(c(o,s)):0)},Ye=A=>{let e=s;return A===47?d(e,A)?W(c(o,s)):0:(s--,d(e,A)?j(c(o,s)):0)},OA=A=>{let e=s;return i.scheme=D.scheme,A===47||I(i.scheme)&&A===92?d(e,A)?XA(c(o,s)):0:(i.username=D.username,i.password=D.password,i.host=D.host,i.port=D.port,i.path=D.path.slice(),i.query=D.query,A===63?(i.query="",d(e,A)?Q(c(o,s)):0):A===35?(i.fragment="",d(e,A)?x(c(o,s)):0):A!=null?(i.query=null,i.path.pop(),s--,d(e,A)?j(c(o,s)):0):d(e,A)?OA(c(o,s)):0)},XA=A=>{let e=s;return I(i.scheme)&&(A===47||A===92)?d(e,A)?hA(c(o,s)):0:A===47?d(e,A)?W(c(o,s)):0:(i.username=D.username,i.password=D.password,i.host=D.host,i.port=D.port,s--,d(e,A)?j(c(o,s)):0)},Ve=A=>{let e=s;return A===47&&c(o,s+1)===47?s++:s--,d(e,A)?hA(c(o,s)):0},hA=A=>{let e=s;return A!==47&&A!==92?(s--,d(e,A)?W(c(o,s)):0):d(e,A)?hA(c(o,s)):0},W=A=>{let e=s;if(A!=null&&A!==64&&A!==35&&A!==47&&A!==63&&(A!==92||!I(i.scheme))){let t=s+M(A);for(;t<o.length;){let n=c(o,t);if(n==null||n===64||n===35||n===47||n===63||n===92&&I(i.scheme))break;t+=M(n)}return g+=o.slice(s,t),s=t-1,d(e,A)?W(c(o,s)):0}if(A===64){lA&&(g=`%40${g}`),lA=!0;for(let t=0;t<g.length;t++){let n=g.codePointAt(t);if(n===58&&!uA){uA=!0;continue}let r=ee(n,cA);uA?i.password+=r:i.username+=r,n!=null&&n>65535&&t++}return g="",d(e,A)?W(c(o,s)):0}else return A==null||A===35||A===47||A===63||A===92&&I(i.scheme)?lA&&g===""?1:(s-=g.length+1,g="",d(e,A)?aA(c(o,s)):0):(g+=le(A),d(e,A)?W(c(o,s)):0)},aA=A=>{let e=s;if(E&&i.scheme==="file")return s--,d(e,A)?LA(c(o,s)):0;if(A!=null&&A!==58&&A!==35&&A!==47&&A!==63&&(A!==92||!I(i.scheme))){let t=s+M(A);for(A===91?G=!0:A===93&&(G=!1);t<o.length;){let n=c(o,t);if(n==null||!G&&n===58||n===35||n===47||n===63||n===92&&I(i.scheme))break;n===91?G=!0:n===93&&(G=!1),t+=M(n)}return g+=o.slice(s,t),s=t-1,d(e,A)?aA(c(o,s)):0}else if(A===58&&!G){if(g===""||E===4)return 1;let t=EA(g,!I(i.scheme));return t===null?1:(i.host=vA(t),g="",d(e,A)?RA(c(o,s)):0)}else if(A==null||A===35||A===47||A===63||A===92&&I(i.scheme)){if(s--,I(i.scheme)&&g==="")return 1;if(E&&g===""&&(ie(i)||i.port!==null))return 1;let t=EA(g,!I(i.scheme));return t===null?1:(i.host=vA(t),g="",E?0:d(e,A)?Y(c(o,s)):0)}else return g+=le(A),d(e,A)?aA(c(o,s)):0},RA=A=>{let e=s;if(A!=null&&A>=48&&A<=57){let t=s+1;for(;t<o.length;){let n=o.charCodeAt(t);if(n<48||n>57)break;t++}return g+=o.slice(s,t),s=t-1,d(e,A)?RA(c(o,s)):0}else if(E||A==null||A===35||A===47||A===63||A===92&&I(i.scheme)){if(g!==""){let t=parseInt(g,10);if(t>65535)return 1;if(i.port=t===se(i.scheme)?null:t,g="",E)return 0}return E?1:(s--,d(e,A)?Y(c(o,s)):0)}else return 1};function ce(A,e){let t=A.length-e;if(t<2)return!1;if(ne(c(A,e),c(A,e+1))){if(t===2)return!0;{let n=c(A,e+2);return n===47||n===92||n===63||n===35}}else return!1}var kA=A=>{let e=s;return i.scheme="file",i.host="",A===47||A===92?d(e,A)?Ke(c(o,s)):0:D?.scheme==="file"?(i.host=D.host,i.path=D.path.slice(),i.opaquePath=D.opaquePath,i.query=D.query,A===63?(i.query="",d(e,A)?Q(c(o,s)):0):A===35?(i.fragment="",d(e,A)?x(c(o,s)):0):A!=null?(i.query=null,ce(o,s)?i.path=[]:oe(i),s--,d(e,A)?j(c(o,s)):0):d(e,A)?kA(c(o,s)):0):(s--,d(e,A)?j(c(o,s)):0)},Ke=A=>{let e=s;return A===47||A===92?d(e,A)?LA(c(o,s)):0:(D!==null&&D.scheme==="file"&&(!ce(o,s)&&(function(n){if(n.length===2){let r=n.codePointAt(0),u=n.codePointAt(1);return(r>=65&&r<=90||r>=97&&r<=122)&&u===58}else return!1})(D.path[0])&&i.path.push(D.path[0]),i.host=D.host),s--,d(e,A)?j(c(o,s)):0)},LA=A=>{let e=s;if(A!=null&&A!==47&&A!==92&&A!==63&&A!==35){let t=s+M(A);for(;t<o.length;){let n=c(o,t);if(n==null||n===47||n===92||n===63||n===35)break;t+=M(n)}return g+=o.slice(s,t),s=t-1,d(e,A)?LA(c(o,s)):0}else if(A==null||A===47||A===92||A===63||A===35){if(s--,!E&&re(g))return d(e,A)?j(c(o,s)):0;if(g==="")return i.host="",E?0:d(e,A)?Y(c(o,s)):0;{let t=EA(g,!I(i.scheme));return t===null?1:(t==="localhost"&&(t=""),i.host=vA(t),g="",E?0:d(e,A)?Y(c(o,s)):0)}}return 1},Y=A=>{let e=s;return I(i.scheme)?(A!==92&&A!==47&&s--,d(e,A)?j(c(o,s)):0):!E&&A===63?(i.query="",d(e,A)?Q(c(o,s)):0):!E&&A===35?(i.fragment="",d(e,A)?x(c(o,s)):0):A!=null?(A!==47&&s--,d(e,A)?j(c(o,s)):0):(E&&i.host===null&&i.path.push(""),d(e,A)?Y(c(o,s)):0)},j=A=>{let e=s;if(A!=null&&A!==47&&(!I(i.scheme)||A!==92)&&(E||A!==63&&A!==35)){let t=s+M(A);for(;t<o.length;){let n=c(o,t);if(n==null||n===47||I(i.scheme)&&n===92||!E&&(n===63||n===35))break;t+=M(n)}g+=_(o.slice(s,t),SA),s=t,A=c(o,t)}if(A==null||A===47||I(i.scheme)&&A===92||!E&&(A===63||A===35)){let t=I(i.scheme)&&A===92;return(function(r){switch(r){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(g)?(oe(i),A!==47&&!t&&i.path.push("")):JA(g)&&A!==47&&!t?i.path.push(""):JA(g)||(i.scheme==="file"&&i.path.length===0&&re(g)&&(g=`${g[0]}:`),i.path.push(g)),g="",A===63?(i.query="",d(e,A)?Q(c(o,s)):0):A===35?(i.fragment="",d(e,A)?x(c(o,s)):0):d(e,A)?j(c(o,s)):0}else return g+=ee(A,SA),d(e,A)?j(c(o,s)):0},ae=A=>{let e=s;if(A===63)return i.query="",d(e,A)?Q(c(o,s)):0;if(A===35)return i.fragment="",d(e,A)?x(c(o,s)):0;if(A!=null){let t=s+M(A);for(;t<o.length;){let r=c(o,t);if(r===63||r===35)break;t+=M(r)}let n=o.slice(s,t);if(t<o.length&&n.charCodeAt(n.length-1)===32?i.path[0]+=_(n.slice(0,-1),AA)+"%20":i.path[0]+=_(n,AA),s=t,(A=c(o,t))===63)return i.query="",d(e,A)?Q(c(o,s)):0;if(A===35)return i.fragment="",d(e,A)?x(c(o,s)):0}return d(e,A)?ae(c(o,s)):0},Q=A=>{let e=s,t=s;if(A!=null){if(E)t=o.length;else{let r=o.indexOf("#",s);t=r===-1?o.length:r}let n=I(i.scheme)?Se:qA;i.query+=_(o.slice(s,t),n)}return s=t,c(o,t)===35&&!E?(i.fragment="",d(e,A)?x(c(o,s)):0):d(e,A)?Q(c(o,s)):0},x=A=>{let e=s;return A!=null&&(i.fragment+=_(o.slice(s),be),s=o.length),d(e,A)?x(c(o,s)):0};function TA(A){if(A.opaquePath)return A.path[0];{let e="";for(let t of A.path)e+=`/${t}`;return e}}function fe(A){switch(A.scheme){case"blob":{let e=B(TA(A),null,null,0);return e===null||e.scheme!=="http"&&e.scheme!=="https"?"null":fe(e)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(t){let n=`${t.scheme}://`;return n+=t.host,t.port!==null&&(n+=`:${t.port}`),n})(A);default:return"null"}}var b=Symbol("URLImpl"),eA=class A{constructor(e,t){if(e===void 0&&t===void 0)throw new TypeError('The "url" argument must be specified.');e=S(e),t!=null&&(t=S(t));let n=null;if(t!=null&&(n=B(t,null,null,0),n==null))throw new TypeError(`Invalid base URL: ${t}`);let r=B(e,null,n,0);if(r==null)throw new TypeError(`Invalid URL: ${e}`);this[b]={url:r,query:null}}static createObjectURL(e){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(e){}static parse(e,t){e=S(e),t!==void 0&&(t=S(t));try{return new A(e,t)}catch{return null}}static canParse(e,t){e=S(e),t!==void 0&&(t=S(t));let n=null;return t!=null&&(n=B(t,null,null,0),n==null)?!1:B(e,null,n,0)!=null}get href(){return(function(t){let n=`${t.scheme}:`;return t.host!==null&&(n+="//",(t.username!==""||t.password!=="")&&(n+=t.username,t.password!==""&&(n+=`:${t.password}`),n+="@"),n+=t.host,t.port!==null&&(n+=`:${t.port}`)),t.host===null&&!t.opaquePath&&t.path.length>1&&t.path[0]===""&&(n+="/."),n+=TA(t),t.query!==null&&(n+=`?${t.query}`),t.fragment!==null&&(n+=`#${t.fragment}`),n})(this[b].url)}set href(e){let t=B(e=S(e),null,null,0);if(t==null)throw new TypeError(`Invalid URL: ${e}`);this[b].url=t,this[b].query&&yA(this[b].query,t.query)}get origin(){return fe(this[b].url)}get protocol(){return`${this[b].url.scheme}:`}set protocol(e){B(`${e=S(e)}:`,this[b].url,null,2)}get username(){return this[b].url.username}set username(e){e=S(e),mA(this[b].url)||(function(n,r){n.username=_(r,cA)})(this[b].url,e)}get password(){return this[b].url.password}set password(e){e=S(e),mA(this[b].url)||(function(n,r){n.password=_(r,cA)})(this[b].url,e)}get host(){let{url:e}=this[b];return e.host==null?"":e.port==null?e.host:`${e.host}:${e.port}`}set host(e){e=S(e),this[b].url.opaquePath||B(e,this[b].url,null,3)}get hostname(){let{url:e}=this[b];return e.host!=null?e.host:""}set hostname(e){e=S(e),this[b].url.opaquePath||B(e,this[b].url,null,4)}get port(){let{url:e}=this[b];return e.port!=null?`${e.port}`:""}set port(e){e=S(e);let{url:t}=this[b];mA(t)||(e?B(e,t,null,5):t.port=null)}get pathname(){return TA(this[b].url)}set pathname(e){e=S(e);let{url:t}=this[b];t.opaquePath||(t.path=[],B(e,t,null,6))}get search(){let{url:e}=this[b];return e.query?`?${e.query}`:""}set search(e){e=S(e);let{url:t,query:n}=this[b];if(!e)t.query=null,n&&yA(n,null);else{let r=e[0]==="?"?e.substring(1):e;t.query="",B(r,t,null,7),n&&yA(n,t.query)}}get searchParams(){let e=this[b],t=e.query;return t==null&&(t=e.query=(function(r,u){let l=new fA;return l[C].url=r,l[C].serialized=u==null,u&&(l[C].list=NA(u)),l})(this,e.url.query)),t}get hash(){let{url:e}=this[b];return e.fragment?`#${e.fragment}`:""}set hash(e){e=S(e);let{url:t}=this[b];if(!e)t.fragment=null;else{let n=e[0]==="#"?e.substring(1):e;t.fragment="",B(n,t,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(eA.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var C=Symbol("URLSearchParamsImpl"),Je=Symbol.dispose||Symbol.for("dispose");function yA(A,e){e?A[C].list=NA(e):A[C].list.length=0,A[C].serialized=e==null}function oA(A){if(A.url){let e=CA(A.list);(function(n,r){n[b].url.query=r})(A.url,e||null),A.serialized=!0}}var We=typeof Iterator<"u"?Iterator:Object,Z=class extends We{constructor(e,t){super(),this[C]={ptr:e,map:t,index:0}}next(){let e=this[C];return e.index<e.ptr.list.length?{value:e.map(e.ptr.list[e.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[Je](){}},fA=class{constructor(e){let t=this[C]={list:[],url:null,serialized:!0},n;if(Array.isArray(e))for(let r=0;r<e.length;r++)t.list.push(QA(e[r]));else if((n=ZA(e))!=null){let r;for(;!(r=PA(n.next())).done;)t.list.push(QA(r.value))}else if((typeof e=="object"||typeof e=="function")&&e!=null){let r=Object.keys(e);for(let u=0;u<r.length;u++){let l=r[u],a=Pe(l),f=S(e[l]),h=t.list.find(w=>w[0]===a);h?h[1]=f:t.list.push([a,f])}}else if(e!==void 0){let r=S(e);r=r[0]==="?"?r.substring(1):r,t.list=NA(r)}}get size(){return this[C].list.length}append(e,t){e=S(e),t=S(t),this[C].list.push([e,t]);let n=this[C];n.url&&n.serialized?(function(u,l){let a=u[b].url;a.query=a.query?`${a.query}&${l}`:l})(n.url,CA([[e,t]])):oA(n)}delete(e,t){e=S(e),t=t!=null?S(t):void 0;let{list:n}=this[C],r=0;for(;r<n.length;)n[r][0]===e&&(t==null||n[r][1]===t)?n.splice(r,1):r++;oA(this[C])}get(e){e=S(e);let{list:t}=this[C];for(let n=0;n<t.length;n++)if(t[n][0]===e)return t[n][1];return null}getAll(e){e=S(e);let t=[],{list:n}=this[C];for(let r=0;r<n.length;r++)n[r][0]===e&&t.push(n[r][1]);return t}has(e,t){e=S(e),t=t!=null?S(t):void 0;let{list:n}=this[C];for(let r=0;r<n.length;r++)if(n[r][0]===e&&(t==null||n[r][1]===t))return!0;return!1}set(e,t){e=S(e),t=S(t);let{list:n}=this[C],r=!1,u=!1,l=0;for(;l<n.length;)n[l][0]===e?r?(n.splice(l,1),u=!0):(r=!0,n[l][1]!==t&&(n[l][1]=t,u=!0),l++):l++;r||(n.push([e,t]),u=!0),u&&oA(this[C])}sort(){this[C].list.sort((e,t)=>e[0]<t[0]?-1:e[0]>t[0]?1:0),oA(this[C])}forEach(e,t){if(typeof e!="function")throw new TypeError('The "callback" argument must be of type function');let{list:n}=this[C];for(let r=0;r<n.length;r++)e.call(t,n[r][1],n[r][0],this)}entries(){return new Z(this[C],e=>e)}keys(){return new Z(this[C],e=>e[0])}values(){return new Z(this[C],e=>e[1])}toString(){return CA(this[C].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(fA.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});function he(A){let e,t=()=>typeof e=="string"?e:e?.accessToken,n=0,r,u=new Map,l=()=>{for(let p of[...u.keys()])try{p()}catch{}};function a(p){let m=++n;r=void 0,e=void 0;for(let y of[...u.values()])try{y?.()}catch{}m===n&&(e=p,l())}let f=()=>a();function h(p,m=!1){let y=$A.safeParse(p);if(!y.success||m&&Date.parse(y.data.expiresAt)<=Date.now()||Date.parse(y.data.refreshExpiresAt)<=Date.now()||Date.parse(y.data.refreshExpiresAt)<Date.parse(y.data.expiresAt))throw new P("INVALID_RESPONSE","Invalid customer session credentials");return y.data}async function w(){if(r)return r;let p=typeof e=="object"?e:void 0,m=n;if(!p||Date.parse(p.refreshExpiresAt)<=Date.now())throw p&&f(),new P("UNAUTHENTICATED","Customer authentication is required",401);let y=(async()=>{try{let N=await A(p.refreshToken);if(m!==n)throw new P("IDENTITY_CHANGED","Customer identity changed during refresh");let V=h(N,!0);if(V.customerId!==p.customerId||V.sessionId!==p.sessionId)throw new P("SCOPE_MISMATCH","Refresh changed the customer session");return e=V,{...V}}catch(N){throw m!==n?new P("IDENTITY_CHANGED","Customer identity changed during refresh"):(N instanceof P&&N.status===401&&f(),N)}})();r=y;try{return await y}finally{r===y&&(r=void 0)}}return{identify(p){let m=typeof p=="string"?p:h(p),y=typeof m=="string"?m:m.accessToken;if(!y.trim()||/\s/.test(y)||y.length>4096)throw new P("INVALID_TOKEN","A server-issued token is required");a(m)},reset:f,subscribeIdentity(p,m){return u.set(p,m),()=>{u.delete(p)}},access(){let p=typeof e=="object"?e:void 0;if(p&&Date.parse(p.expiresAt)<=Date.now()+3e4){let y=n;return w().then(()=>{let N=t();if(y!==n||!N)throw new P("IDENTITY_CHANGED","Customer identity changed during refresh");return N})}let m=t();if(!m)throw new P("NOT_IDENTIFIED","Identify a customer session before making a request");return m},peek:t,snapshot:()=>typeof e=="object"?{...e}:void 0,refresh:w}}var de=Symbol("IndianaNoContent");function ut(A,e,t=eA){let n=A.configuration?.scope,r=A.scope??(n&&{projectId:n.projectId,environment:n.environment}),u=r?sA.parse(r):void 0;if(u&&n&&(u.projectId!==n.projectId||u.environment!==n.environment))throw new P("SCOPE_MISMATCH","Configuration belongs to another App/environment");let l=new t(A.baseUrl??FA);if(l.username||l.password||l.search||l.hash)throw new P("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(l.protocol!=="https:"&&!(l.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(l.hostname)))throw new P("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let a=A.fetch??globalThis.fetch.bind(globalThis),f=A.timeoutMs??1e4;if(!Number.isFinite(f)||f<1||f>12e4)throw new P("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let h=!1,w=0,p=null,m=new Set,y=A.session??he(async q=>{let O=await tA("customer-sessions/refresh",{},"POST",{},q);if(!O||typeof O!="object")throw new P("INVALID_RESPONSE","Invalid refresh response");let{requestId:$,scope:H,...K}=O;return K});function N(){w+=1,p=null;for(let q of m)q.abort();m.clear()}let V=y.subscribeIdentity(N);function pe(){h||y.reset()}async function tA(q,O={},$="POST",H={},K){let k=H.installationDetach===!0;if(k&&(q!=="push/installations/detach"||$!=="POST"))throw new P("INVALID_REQUEST","Installation authority only detaches this installation");if(!K&&!k)throw new P("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let J=w,L=new AbortController;k||m.add(L);let nA=()=>!k&&J!==w?new P("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new P("TIMEOUT","Longplay request timed out"),dA,ge=new Promise((T,R)=>{dA=()=>R(nA()),L.signal.addEventListener("abort",dA,{once:!0})}),we=setTimeout(()=>L.abort(),H.timeoutMs??f),me=async()=>{let T=await a(`${l.href.replace(/\/$/,"")}/api/v1/${q}`,{method:$,headers:{...H.headers,"Content-Type":"application/json",...k?{}:{Authorization:`Bearer ${K}`},[pA]:gA.current,[xA]:zA.version,...u?{"X-Indiana-Project":u.projectId,"X-Indiana-Environment":u.environment}:{}},body:$==="POST"?JSON.stringify(O):void 0,signal:L.signal,credentials:"omit",cache:"no-store",redirect:"error",...H.keepalive?{keepalive:!0}:{}});if(L.signal.aborted)throw nA();let R;try{R=T.status===204?de:await T.json()}catch{throw L.signal.aborted?nA():new P(T.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",T.status,T.headers.get("X-Request-Id")??void 0)}if(L.signal.aborted)throw nA();if(!k&&J!==w)throw new P("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!T.ok){let v=UA.safeParse(R),z=v.success&&(!MA.safeParse(v.data.error.code).success||jA(v.data.error.code,T.status)),BA=z?v.data.error.code:"HTTP_ERROR",HA=_A(BA,T.status,{retryAfter:T.headers.get("Retry-After"),recovery:z?v.data.error.recovery:void 0,reason:z?v.data.error.reason:void 0});throw new P(BA,z?v.data.error.message:"Longplay request failed",T.status,T.headers.get("X-Request-Id")??(v.success?v.data.requestId:void 0),{...HA,...v.success&&v.data.error.retryable===!1?{retryable:!1}:{},...HA.retryAfterSeconds===void 0&&v.success&&v.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:v.data.error.retryAfterSeconds}:{}})}if(T.headers.get(pA)!==gA.current)throw new P("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(u&&R!==de){let v=R&&typeof R=="object"&&"scope"in R?R:R&&typeof R=="object"&&"configuration"in R?R.configuration:null;if(!v||typeof v!="object"||!("scope"in v))throw new P("INVALID_RESPONSE","Response is missing its App/environment scope");let z=sA.safeParse(v.scope);if(!z.success||z.data.projectId!==u.projectId||z.data.environment!==u.environment)throw new P("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let rA=T.headers.get("X-Indiana-Telemetry-Subject");if(rA){if(!/^[a-f0-9]{64}$/.test(rA))throw new P("INVALID_RESPONSE","Invalid telemetry identity");p!==rA&&(p=rA,e?.(p))}return R};try{return await Promise.race([me(),ge])}catch(T){throw!k&&J!==w?new P("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):T instanceof P?T:new P(L.signal.aborted?"TIMEOUT":"NETWORK_ERROR",L.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(we),L.signal.removeEventListener("abort",dA),m.delete(L)}}return{session:y,requestWithCredential(q,O,$,H={}){return h?Promise.reject(new P("CLOSED","SDK client was destroyed")):tA(q,O,"POST",H,$)},subjectKey:()=>p,identify(q){if(h)throw new P("CLOSED","SDK client was destroyed");if(u&&typeof q=="object"&&"scope"in q){let O=sA.safeParse(q.scope);if(!O.success||O.data.projectId!==u.projectId||O.data.environment!==u.environment)throw new P("SCOPE_MISMATCH","Customer session belongs to another App/environment")}y.identify(q)},reset:pe,dispose(){h||(h=!0,V(),N())},request(q,O={},$="POST",H={}){if(h)return Promise.reject(new P("CLOSED","SDK client was destroyed"));if(H.installationDetach)return tA(q,O,$,H);let K=w;try{let k=y.access(),J=L=>{if(K!==w)throw new P("IDENTITY_CHANGED","Customer identity changed before dispatch");return tA(q,O,$,H,L)};return typeof k=="string"?J(k):k.then(J)}catch(k){return Promise.reject(k)}}}}export{eA as a,ut as b};
1
+ import{a as P}from"./chunk-QVGTHPWT.js";import{g as pA,h as xA,i as gA,kb as zA,lb as FA,r as $A}from"./chunk-JXNNWCEB.js";import{a as sA,b as MA,e as jA,f as UA,g as _A}from"./chunk-HDVLCRC6.js";function S(A){return typeof A=="string"?A:String(A)}var ye=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Pe(A){return A.replace(ye,"$1\uFFFD")}function PA(A,e){if(typeof A!="object"||A==null){let t="";throw t+="The provided value is not an object",new TypeError(t)}return A}function ZA(A){if(A!=null&&(typeof A=="object"||typeof A=="function")){let e=A[Symbol.iterator];if(e==null)return;if(typeof e!="function")throw new TypeError("The provided value is not iterable");let t=e.call(A);if(!t||typeof t!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return t}}function QA(A){let e;if(Array.isArray(A)){let t=A.map(S);if(t.length===2)return t}else if((e=ZA(A))!=null){let t=PA(e.next()),n=PA(e.next());if(!t.done&&!n.done)return[S(t.value),S(n.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var GA="0123456789ABCDEF",De=/(?:%[0-9A-Fa-f]{2})+/g;function U(A){return`%${GA[A>>4&15]}${GA[15&A]}`}function Ae(A,e,t=!1){return A>=55296&&A<=57343&&(A=65533),A<=127?t&&A===32?"+":e(A)?U(A):String.fromCharCode(A):A<=2047?U(192|A>>6)+U(128|63&A):A<=65535?U(224|A>>12)+U(128|A>>6&63)+U(128|63&A):U(240|A>>18)+U(128|A>>12&63)+U(128|A>>6&63)+U(128|63&A)}function DA(A){return A>=48&&A<=57?A-48:A>=65&&A<=70?A-65+10:A>=97&&A<=102?A-97+10:-1}function bA(A,e=!1){let t=0;for(;t<A.length;t++){let n=A.charCodeAt(t);if(n===37||e&&n===43)break}return t===A.length?A:(e?A.replace(/\+/g," "):A).replace(De,n=>{try{return decodeURIComponent(n)}catch{return"\uFFFD".repeat(n.length/3)}})}function AA(A){return A<=31||A>126}function be(A){switch(A){case 32:case 34:case 60:case 62:case 96:return!0;default:return AA(A)}}function qA(A){switch(A){case 32:case 34:case 35:case 60:case 62:return!0;default:return AA(A)}}function Se(A){return qA(A)||A===39}function SA(A){switch(A){case 63:case 94:case 96:case 123:case 125:return!0;default:return qA(A)}}function cA(A){switch(A){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return SA(A)}}function YA(A){switch(A){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(t){switch(t){case 36:case 37:case 38:case 43:case 44:return!0;default:return cA(t)}})(A)}}function ee(A,e){return Ae(A=A||0,e)}function _(A,e,t=!1){let n=0;for(;n<A.length;n++){let u=A.charCodeAt(n);if(u>=128||t&&u===32||e(u))break}if(n===A.length)return A;let r=A.slice(0,n);for(;n<A.length;n++){let u=A.charCodeAt(n),l=u;if(u>=55296&&u<=56319&&n+1<A.length){let a=A.charCodeAt(n+1);a>=56320&&a<=57343&&(l=(u-55296<<10)+a-56320+65536,n++)}r+=Ae(l,e,t)}return r}function NA(A){let e=[],t=0,n=0;for(;n<=A.length;){if(n=A.indexOf("&",t),n<0&&(n=A.length),n!==t){let r=A.slice(t,n),u=r.indexOf("=");u<0&&(u=r.length),e.push([bA(r.slice(0,u),!0),bA(r.slice(u+1),!0)])}if(t=n+1,n===A.length)break}return e}function CA(A){let e="";for(let t=0;t<A.length;t++){let n=_(A[t][0],YA,!0),r=_(A[t][1],YA,!0);e+=t!==0?`&${n}=${r}`:`${n}=${r}`}return e}var Ce=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],Ie=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Ee=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],ve=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function Te(A){for(let e=0;e<A.length;e++){let t=A.codePointAt(e);if(t>65535&&e++,t<=32||t===37||t===127||t>=55296&&t<=57343||t>=128&&t<=159||t>=64976&&t<=65007||!(65534&~t)||t===65533)return!0}return!1}var[qe,Ne,Oe,VA]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([e,t,n]){return[e,t.split(",").map(r=>parseInt(r,36)),Uint8Array.from(atob(n),r=>r.charCodeAt(0))]});function Re(A,e){return e===931||e===1010||e===120531||e===120589||e===120647||e===120705||e===120763?"\u03C3":e>=5112&&e<=5117?String.fromCodePoint(e-8):e>=43888&&e<=43967?String.fromCodePoint(e-38864):e>=93856&&e<=93880?String.fromCodePoint(e+27):e===837||e===890||e>=8064&&e<=8111||e>=8114&&e<=8188?A.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function te(A,e){for(let t=0;t<A.length;t+=2)if(e>=A[t]&&e<=A[t+1])return!0;return!1}function X(A,e){let[t,n,r]=A,u=e>>8;for(let f=0;f<t.length;f+=2)if(u>=t[f]&&u<=t[f+1])return!0;let l=n.indexOf(u);if(l<0)return!1;let a=255&e;return!!(r[32*l+(a>>3)]&1<<(7&a))}function ke(A){let e=Array.from(A,t=>t.codePointAt(0));for(let t=0;t<e.length;t++){let n=e[t];if(n!==8204&&n!==8205||t>0&&te(ve,e[t-1]))continue;if(n===8205)return!1;let r=t-1;for(;r>=0&&X(VA,e[r]);)r--;let u=t+1;for(;u<e.length&&X(VA,e[u]);)u++;if(!(r>=0&&u<e.length&&X(Ne,e[r])&&X(Oe,e[u])))return!1}return!0}var Le=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,Be=/\p{Script=Latin}/u;function He(A){return!Le.test(A)||!Be.test(A)}var F=36,iA=1,IA=26,Me=38,je=700,Ue=72,_e=128,xe=2147483647;function KA(A){return String.fromCharCode(A+22+75*+(A<26))}function $e(A,e,t){let n=0;for(A=t?Math.floor(A/je):A>>1,A+=Math.floor(A/e);A>(F-iA)*IA>>1;n+=F)A=Math.floor(A/(F-iA));return Math.floor(n+(F-iA+1)*A/(A+Me))}function ze(A){let e=Array.from(A,f=>f.codePointAt(0)),t="",n=0;for(let f=0;f<e.length;f++){let h=e[f];h<128&&(t+=String.fromCharCode(h),n++)}let r=n;r&&(t+="-");let u=_e,l=0,a=Ue;for(;n<e.length;){let f=xe;for(let h=0;h<e.length;h++){let w=e[h];w>=u&&w<f&&(f=w)}l+=(f-u)*(n+1),u=f;for(let h=0;h<e.length;h++){let w=e[h];if(w<u&&l++,w===u){let p=l;for(let m=F;;m+=F){let y=m<=a?iA:m>=a+IA?IA:m-a;if(p<y)break;t+=KA(y+(p-y)%(F-y)),p=Math.floor((p-y)/(F-y))}t+=KA(p),a=$e(l,n+1,n===r),l=0,n++}}l++,u++}return t}function wA(A){let e=10;if(A.length>=2&&A[0]==="0"&&(A[1]==="x"||A[1]==="X"))A=A.slice(2),e=16;else if(A.length>=2&&A[0]==="0")A=A.slice(1),e=8;else if(A==="")return-1;let t=0;for(let n=0;n<A.length;n++){let r=DA(A.charCodeAt(n));if(r>=e||r<0)return-1;t=t*e+r}return t}function JA(A){switch(A){case".":case"%2e":case"%2E":return!0;default:return!1}}function ne(A,e){return(A>=65&&A<=90||A>=97&&A<=122)&&(e===58||e===124)}function re(A){return A.length===2&&ne(A.codePointAt(0),A.codePointAt(1))}function WA(A){return A.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function I(A){switch(A){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function se(A){switch(A){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function EA(A,e){if(A[0]==="[")return A[A.length-1]==="]"?(function(n){let r=[0,0,0,0,0,0,0,0],u=null,l=0,a=0,f=Array.from(n,h=>h.codePointAt(0));if(f[a]===58){if(f[a+1]!==58)return null;a+=2,l++,u=l}for(;a<f.length;){if(l===8)return null;if(f[a]===58){if(u!==null)return null;a++,l++,u=l;continue}let h=0,w=0,p=0;for(;p<4&&(h=DA(f[a]))>=0;)w=(w<<4)+h,a++,p++;if(f[a]===46){if(p===0||l>6)return null;a-=p;let m=0;for(;f[a]!==void 0;){let y=0;if(m>0)if(f[a]===46&&m<4)a++;else return null;if(f[a]==null||f[a]<48||f[a]>57)return null;for(;f[a]>=48&&f[a]<=57;){if(y=10*y+DA(f[a]),y>255)return null;a++}r[l]=256*r[l]+y,m++,m%2==0&&l++}if(m!==4)return null;break}else if(f[a]===58){if(f[++a]===void 0)return null}else if(f[a]!==void 0)return null;r[l]=w,l++}if(u!==null){let h=l-u;for(l=7;l!==0&&h>0;){let w=r[u+h-1];r[u+h-1]=r[l],r[l]=w,l--,h--}}else if(u===null&&l!==8)return null;return r})(A.substring(1,A.length-1)):null;if(e)return(function(n){return WA(n)?null:_(n,AA)})(A);{let t=(function(r){let u=!1,l=!1;for(let f=0;f<r.length;f++){let h=r.charCodeAt(f);if(h<=32||h===37||h===127)return null;if(h>=128){u=!0;break}h>=65&&h<=90&&(l=!0)}if(!u)return r!==""?l?r.toLowerCase():r:null;if((function(h){for(let w of h){let p=w.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(w)&&!te(Ce,p)||X(qe,p))return!0}return!1})(r))return null;let a=(r=(function(h){let w="";for(let p of h){let m=p.codePointAt(0);if(m!==8204&&m!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(p))continue;let y=Re(p,m);if(y){w+=y;continue}let N=Ie.indexOf(m);w+=N<0?p:Ee[N]}return w})(r).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let f=0;f<a.length;f++){let h=a[f];if(h==="")continue;let w=/[^\0-\x7f]/.test(h);if(Te(h)||w&&(/^\p{Mark}/u.test(h)||!ke(h)||!He(h)||h.startsWith("xn--")))return null;w&&(a[f]=`xn--${ze(h)}`)}return(r=a.join("."))!==""?r:null})(A.indexOf("%")===-1?A:bA(A));return t===null||WA(t)?null:(function(r){let u=r.length,l=r.lastIndexOf(".",u-2)+1;if(r.charCodeAt(u-1)===46&&u--,u<=l)return!1;if(wA(r.slice(l,u))>=0)return!0;for(;l<u;l++){let a=r.charCodeAt(l);if(a<48||a>57)return!1}return!0})(t)?(function(r){let u=r.split("."),l=u.length;if(u[l-1]||l--,l>4)return null;let a=0;for(let h=0;h<l-1;h++){let w=wA(u[h]);if(w<0||w>255)return null;a+=w*(1<<8*(3-h))}let f=wA(u[l-1]);return f<0||f>=256**(5-l)?null:(a+=f,a)})(t):t}}function vA(A){return typeof A=="number"?(function(t){let r="";return r+=`${(t>>>24&255).toString(10)}.`,r+=`${(t>>>16&255).toString(10)}.`,r+=`${(t>>>8&255).toString(10)}.`,r+=(t&255).toString(10),r})(A):Array.isArray(A)?`[${(function(t){let n=(function(a){let f=-1,h=-1,w=1,p=0;for(let m=0;m<a.length;++m)a[m]!==0?(p>w&&(f=h,w=p),h=-1,p=0):(h===-1&&(h=m),++p);return p>w?h:f})(t),r="",u=!1;for(let l=0;l<=7;++l)if(!(u&&t[l]===0)){if(u&&(u=!1),n===l){r+=l===0?"::":":",u=!0;continue}r+=t[l].toString(16),l!==7&&(r+=":")}return r})(A)}]`:A}function oe(A){A.path.length>0&&(A.path.length!==1||A.scheme!=="file"||!(function(t){return/^[A-Za-z]:$/u.test(t)})(A.path[0]))&&A.path.pop()}function ie(A){return A.username!==""||A.password!==""}function mA(A){return A.host===null||A.host===""||A.scheme==="file"}var s=0,o="",g="",D=null,i,lA=!1,uA=!1,G=!1,E;function B(A,e,t,n){e||(A=(function(l){let a=0,f=l.length;for(;a<f&&!(l.charCodeAt(a)>32);++a);for(;f>a&&!(l.charCodeAt(f-1)>32);--f);return l.substring(a,f)})(A)),A=(function(l){let a=0;for(;a<l.length;a++){let h=l.charCodeAt(a);if(h===9||h===10||h===13)break}if(a===l.length)return l;let f=l.slice(0,a);for(;a<l.length;a++){let h=l.charCodeAt(a);h!==9&&h!==10&&h!==13&&(f+=l[a])}return f})(A),s=0,o=A,g="",D=t||null,i=e||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},lA=!1,uA=!1,G=!1,E=n||0;let r=Fe;switch(n){case 3:case 4:r=aA;break;case 5:r=RA;break;case 6:r=Y;break;case 7:r=Q;break;case 8:r=x}return r(c(A,s))!==1?i:null}function d(A,e){return s+=s===A?M(e):1,s<=o.length}function c(A,e){return e<A.length?A.codePointAt(e):void 0}function M(A){return A!=null&&A>65535?2:1}function le(A){return A==null?"":A<=65535?String.fromCharCode(A):String.fromCodePoint(A)}var Fe=A=>{let e=s;if(A!=null&&(A>=65&&A<=90||A>=97&&A<=122)){let t=s+1;for(A=o.charCodeAt(t);A===43||A===45||A===46||A>=65&&A<=90||A>=97&&A<=122||A>=48&&A<=57;)t++,A=o.charCodeAt(t);return g=o.slice(s,t).toLowerCase(),s=t,Qe(t<o.length?A:void 0)}else return E?1:(--s,d(e,A)?ue(c(o,s)):0)},Qe=A=>{let e=s;if(A===58){if(E){if(I(i.scheme)!==I(g))return 0;if((ie(i)||i.port!==null)&&g==="file")return 0;if(i.scheme==="file"&&i.host==="")return 0}return i.scheme=g,E?(i.port===se(i.scheme)&&(i.port=null),0):(g="",i.scheme==="file"?d(e,A)?kA(c(o,s)):0:I(i.scheme)&&D!==null&&D.scheme===i.scheme?d(e,A)?Ge(c(o,s)):0:I(i.scheme)?d(e,A)?Ve(c(o,s)):0:c(o,s+1)===47?(s++,d(e,A)?Ye(c(o,s)):0):(i.path=[""],i.opaquePath=!0,d(e,A)?ae(c(o,s)):0))}else return E?1:(g="",s=-1,d(e,A)?ue(c(o,s)):0)},ue=A=>{let e=s;return D===null||D.opaquePath&&A!==35?1:D.opaquePath&&A===35?(i.scheme=D.scheme,i.path=D.path.slice(),i.opaquePath=D.opaquePath,i.query=D.query,i.fragment="",d(e,A)?x(c(o,s)):0):D.scheme==="file"?(s--,d(e,A)?kA(c(o,s)):0):(s--,d(e,A)?OA(c(o,s)):0)},Ge=A=>{let e=s;return A===47&&c(o,s+1)===47?(++s,d(e,A)?hA(c(o,s)):0):(s--,d(e,A)?OA(c(o,s)):0)},Ye=A=>{let e=s;return A===47?d(e,A)?W(c(o,s)):0:(s--,d(e,A)?j(c(o,s)):0)},OA=A=>{let e=s;return i.scheme=D.scheme,A===47||I(i.scheme)&&A===92?d(e,A)?XA(c(o,s)):0:(i.username=D.username,i.password=D.password,i.host=D.host,i.port=D.port,i.path=D.path.slice(),i.query=D.query,A===63?(i.query="",d(e,A)?Q(c(o,s)):0):A===35?(i.fragment="",d(e,A)?x(c(o,s)):0):A!=null?(i.query=null,i.path.pop(),s--,d(e,A)?j(c(o,s)):0):d(e,A)?OA(c(o,s)):0)},XA=A=>{let e=s;return I(i.scheme)&&(A===47||A===92)?d(e,A)?hA(c(o,s)):0:A===47?d(e,A)?W(c(o,s)):0:(i.username=D.username,i.password=D.password,i.host=D.host,i.port=D.port,s--,d(e,A)?j(c(o,s)):0)},Ve=A=>{let e=s;return A===47&&c(o,s+1)===47?s++:s--,d(e,A)?hA(c(o,s)):0},hA=A=>{let e=s;return A!==47&&A!==92?(s--,d(e,A)?W(c(o,s)):0):d(e,A)?hA(c(o,s)):0},W=A=>{let e=s;if(A!=null&&A!==64&&A!==35&&A!==47&&A!==63&&(A!==92||!I(i.scheme))){let t=s+M(A);for(;t<o.length;){let n=c(o,t);if(n==null||n===64||n===35||n===47||n===63||n===92&&I(i.scheme))break;t+=M(n)}return g+=o.slice(s,t),s=t-1,d(e,A)?W(c(o,s)):0}if(A===64){lA&&(g=`%40${g}`),lA=!0;for(let t=0;t<g.length;t++){let n=g.codePointAt(t);if(n===58&&!uA){uA=!0;continue}let r=ee(n,cA);uA?i.password+=r:i.username+=r,n!=null&&n>65535&&t++}return g="",d(e,A)?W(c(o,s)):0}else return A==null||A===35||A===47||A===63||A===92&&I(i.scheme)?lA&&g===""?1:(s-=g.length+1,g="",d(e,A)?aA(c(o,s)):0):(g+=le(A),d(e,A)?W(c(o,s)):0)},aA=A=>{let e=s;if(E&&i.scheme==="file")return s--,d(e,A)?LA(c(o,s)):0;if(A!=null&&A!==58&&A!==35&&A!==47&&A!==63&&(A!==92||!I(i.scheme))){let t=s+M(A);for(A===91?G=!0:A===93&&(G=!1);t<o.length;){let n=c(o,t);if(n==null||!G&&n===58||n===35||n===47||n===63||n===92&&I(i.scheme))break;n===91?G=!0:n===93&&(G=!1),t+=M(n)}return g+=o.slice(s,t),s=t-1,d(e,A)?aA(c(o,s)):0}else if(A===58&&!G){if(g===""||E===4)return 1;let t=EA(g,!I(i.scheme));return t===null?1:(i.host=vA(t),g="",d(e,A)?RA(c(o,s)):0)}else if(A==null||A===35||A===47||A===63||A===92&&I(i.scheme)){if(s--,I(i.scheme)&&g==="")return 1;if(E&&g===""&&(ie(i)||i.port!==null))return 1;let t=EA(g,!I(i.scheme));return t===null?1:(i.host=vA(t),g="",E?0:d(e,A)?Y(c(o,s)):0)}else return g+=le(A),d(e,A)?aA(c(o,s)):0},RA=A=>{let e=s;if(A!=null&&A>=48&&A<=57){let t=s+1;for(;t<o.length;){let n=o.charCodeAt(t);if(n<48||n>57)break;t++}return g+=o.slice(s,t),s=t-1,d(e,A)?RA(c(o,s)):0}else if(E||A==null||A===35||A===47||A===63||A===92&&I(i.scheme)){if(g!==""){let t=parseInt(g,10);if(t>65535)return 1;if(i.port=t===se(i.scheme)?null:t,g="",E)return 0}return E?1:(s--,d(e,A)?Y(c(o,s)):0)}else return 1};function ce(A,e){let t=A.length-e;if(t<2)return!1;if(ne(c(A,e),c(A,e+1))){if(t===2)return!0;{let n=c(A,e+2);return n===47||n===92||n===63||n===35}}else return!1}var kA=A=>{let e=s;return i.scheme="file",i.host="",A===47||A===92?d(e,A)?Ke(c(o,s)):0:D?.scheme==="file"?(i.host=D.host,i.path=D.path.slice(),i.opaquePath=D.opaquePath,i.query=D.query,A===63?(i.query="",d(e,A)?Q(c(o,s)):0):A===35?(i.fragment="",d(e,A)?x(c(o,s)):0):A!=null?(i.query=null,ce(o,s)?i.path=[]:oe(i),s--,d(e,A)?j(c(o,s)):0):d(e,A)?kA(c(o,s)):0):(s--,d(e,A)?j(c(o,s)):0)},Ke=A=>{let e=s;return A===47||A===92?d(e,A)?LA(c(o,s)):0:(D!==null&&D.scheme==="file"&&(!ce(o,s)&&(function(n){if(n.length===2){let r=n.codePointAt(0),u=n.codePointAt(1);return(r>=65&&r<=90||r>=97&&r<=122)&&u===58}else return!1})(D.path[0])&&i.path.push(D.path[0]),i.host=D.host),s--,d(e,A)?j(c(o,s)):0)},LA=A=>{let e=s;if(A!=null&&A!==47&&A!==92&&A!==63&&A!==35){let t=s+M(A);for(;t<o.length;){let n=c(o,t);if(n==null||n===47||n===92||n===63||n===35)break;t+=M(n)}return g+=o.slice(s,t),s=t-1,d(e,A)?LA(c(o,s)):0}else if(A==null||A===47||A===92||A===63||A===35){if(s--,!E&&re(g))return d(e,A)?j(c(o,s)):0;if(g==="")return i.host="",E?0:d(e,A)?Y(c(o,s)):0;{let t=EA(g,!I(i.scheme));return t===null?1:(t==="localhost"&&(t=""),i.host=vA(t),g="",E?0:d(e,A)?Y(c(o,s)):0)}}return 1},Y=A=>{let e=s;return I(i.scheme)?(A!==92&&A!==47&&s--,d(e,A)?j(c(o,s)):0):!E&&A===63?(i.query="",d(e,A)?Q(c(o,s)):0):!E&&A===35?(i.fragment="",d(e,A)?x(c(o,s)):0):A!=null?(A!==47&&s--,d(e,A)?j(c(o,s)):0):(E&&i.host===null&&i.path.push(""),d(e,A)?Y(c(o,s)):0)},j=A=>{let e=s;if(A!=null&&A!==47&&(!I(i.scheme)||A!==92)&&(E||A!==63&&A!==35)){let t=s+M(A);for(;t<o.length;){let n=c(o,t);if(n==null||n===47||I(i.scheme)&&n===92||!E&&(n===63||n===35))break;t+=M(n)}g+=_(o.slice(s,t),SA),s=t,A=c(o,t)}if(A==null||A===47||I(i.scheme)&&A===92||!E&&(A===63||A===35)){let t=I(i.scheme)&&A===92;return(function(r){switch(r){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(g)?(oe(i),A!==47&&!t&&i.path.push("")):JA(g)&&A!==47&&!t?i.path.push(""):JA(g)||(i.scheme==="file"&&i.path.length===0&&re(g)&&(g=`${g[0]}:`),i.path.push(g)),g="",A===63?(i.query="",d(e,A)?Q(c(o,s)):0):A===35?(i.fragment="",d(e,A)?x(c(o,s)):0):d(e,A)?j(c(o,s)):0}else return g+=ee(A,SA),d(e,A)?j(c(o,s)):0},ae=A=>{let e=s;if(A===63)return i.query="",d(e,A)?Q(c(o,s)):0;if(A===35)return i.fragment="",d(e,A)?x(c(o,s)):0;if(A!=null){let t=s+M(A);for(;t<o.length;){let r=c(o,t);if(r===63||r===35)break;t+=M(r)}let n=o.slice(s,t);if(t<o.length&&n.charCodeAt(n.length-1)===32?i.path[0]+=_(n.slice(0,-1),AA)+"%20":i.path[0]+=_(n,AA),s=t,(A=c(o,t))===63)return i.query="",d(e,A)?Q(c(o,s)):0;if(A===35)return i.fragment="",d(e,A)?x(c(o,s)):0}return d(e,A)?ae(c(o,s)):0},Q=A=>{let e=s,t=s;if(A!=null){if(E)t=o.length;else{let r=o.indexOf("#",s);t=r===-1?o.length:r}let n=I(i.scheme)?Se:qA;i.query+=_(o.slice(s,t),n)}return s=t,c(o,t)===35&&!E?(i.fragment="",d(e,A)?x(c(o,s)):0):d(e,A)?Q(c(o,s)):0},x=A=>{let e=s;return A!=null&&(i.fragment+=_(o.slice(s),be),s=o.length),d(e,A)?x(c(o,s)):0};function TA(A){if(A.opaquePath)return A.path[0];{let e="";for(let t of A.path)e+=`/${t}`;return e}}function fe(A){switch(A.scheme){case"blob":{let e=B(TA(A),null,null,0);return e===null||e.scheme!=="http"&&e.scheme!=="https"?"null":fe(e)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(t){let n=`${t.scheme}://`;return n+=t.host,t.port!==null&&(n+=`:${t.port}`),n})(A);default:return"null"}}var b=Symbol("URLImpl"),eA=class A{constructor(e,t){if(e===void 0&&t===void 0)throw new TypeError('The "url" argument must be specified.');e=S(e),t!=null&&(t=S(t));let n=null;if(t!=null&&(n=B(t,null,null,0),n==null))throw new TypeError(`Invalid base URL: ${t}`);let r=B(e,null,n,0);if(r==null)throw new TypeError(`Invalid URL: ${e}`);this[b]={url:r,query:null}}static createObjectURL(e){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(e){}static parse(e,t){e=S(e),t!==void 0&&(t=S(t));try{return new A(e,t)}catch{return null}}static canParse(e,t){e=S(e),t!==void 0&&(t=S(t));let n=null;return t!=null&&(n=B(t,null,null,0),n==null)?!1:B(e,null,n,0)!=null}get href(){return(function(t){let n=`${t.scheme}:`;return t.host!==null&&(n+="//",(t.username!==""||t.password!=="")&&(n+=t.username,t.password!==""&&(n+=`:${t.password}`),n+="@"),n+=t.host,t.port!==null&&(n+=`:${t.port}`)),t.host===null&&!t.opaquePath&&t.path.length>1&&t.path[0]===""&&(n+="/."),n+=TA(t),t.query!==null&&(n+=`?${t.query}`),t.fragment!==null&&(n+=`#${t.fragment}`),n})(this[b].url)}set href(e){let t=B(e=S(e),null,null,0);if(t==null)throw new TypeError(`Invalid URL: ${e}`);this[b].url=t,this[b].query&&yA(this[b].query,t.query)}get origin(){return fe(this[b].url)}get protocol(){return`${this[b].url.scheme}:`}set protocol(e){B(`${e=S(e)}:`,this[b].url,null,2)}get username(){return this[b].url.username}set username(e){e=S(e),mA(this[b].url)||(function(n,r){n.username=_(r,cA)})(this[b].url,e)}get password(){return this[b].url.password}set password(e){e=S(e),mA(this[b].url)||(function(n,r){n.password=_(r,cA)})(this[b].url,e)}get host(){let{url:e}=this[b];return e.host==null?"":e.port==null?e.host:`${e.host}:${e.port}`}set host(e){e=S(e),this[b].url.opaquePath||B(e,this[b].url,null,3)}get hostname(){let{url:e}=this[b];return e.host!=null?e.host:""}set hostname(e){e=S(e),this[b].url.opaquePath||B(e,this[b].url,null,4)}get port(){let{url:e}=this[b];return e.port!=null?`${e.port}`:""}set port(e){e=S(e);let{url:t}=this[b];mA(t)||(e?B(e,t,null,5):t.port=null)}get pathname(){return TA(this[b].url)}set pathname(e){e=S(e);let{url:t}=this[b];t.opaquePath||(t.path=[],B(e,t,null,6))}get search(){let{url:e}=this[b];return e.query?`?${e.query}`:""}set search(e){e=S(e);let{url:t,query:n}=this[b];if(!e)t.query=null,n&&yA(n,null);else{let r=e[0]==="?"?e.substring(1):e;t.query="",B(r,t,null,7),n&&yA(n,t.query)}}get searchParams(){let e=this[b],t=e.query;return t==null&&(t=e.query=(function(r,u){let l=new fA;return l[C].url=r,l[C].serialized=u==null,u&&(l[C].list=NA(u)),l})(this,e.url.query)),t}get hash(){let{url:e}=this[b];return e.fragment?`#${e.fragment}`:""}set hash(e){e=S(e);let{url:t}=this[b];if(!e)t.fragment=null;else{let n=e[0]==="#"?e.substring(1):e;t.fragment="",B(n,t,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(eA.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var C=Symbol("URLSearchParamsImpl"),Je=Symbol.dispose||Symbol.for("dispose");function yA(A,e){e?A[C].list=NA(e):A[C].list.length=0,A[C].serialized=e==null}function oA(A){if(A.url){let e=CA(A.list);(function(n,r){n[b].url.query=r})(A.url,e||null),A.serialized=!0}}var We=typeof Iterator<"u"?Iterator:Object,Z=class extends We{constructor(e,t){super(),this[C]={ptr:e,map:t,index:0}}next(){let e=this[C];return e.index<e.ptr.list.length?{value:e.map(e.ptr.list[e.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[Je](){}},fA=class{constructor(e){let t=this[C]={list:[],url:null,serialized:!0},n;if(Array.isArray(e))for(let r=0;r<e.length;r++)t.list.push(QA(e[r]));else if((n=ZA(e))!=null){let r;for(;!(r=PA(n.next())).done;)t.list.push(QA(r.value))}else if((typeof e=="object"||typeof e=="function")&&e!=null){let r=Object.keys(e);for(let u=0;u<r.length;u++){let l=r[u],a=Pe(l),f=S(e[l]),h=t.list.find(w=>w[0]===a);h?h[1]=f:t.list.push([a,f])}}else if(e!==void 0){let r=S(e);r=r[0]==="?"?r.substring(1):r,t.list=NA(r)}}get size(){return this[C].list.length}append(e,t){e=S(e),t=S(t),this[C].list.push([e,t]);let n=this[C];n.url&&n.serialized?(function(u,l){let a=u[b].url;a.query=a.query?`${a.query}&${l}`:l})(n.url,CA([[e,t]])):oA(n)}delete(e,t){e=S(e),t=t!=null?S(t):void 0;let{list:n}=this[C],r=0;for(;r<n.length;)n[r][0]===e&&(t==null||n[r][1]===t)?n.splice(r,1):r++;oA(this[C])}get(e){e=S(e);let{list:t}=this[C];for(let n=0;n<t.length;n++)if(t[n][0]===e)return t[n][1];return null}getAll(e){e=S(e);let t=[],{list:n}=this[C];for(let r=0;r<n.length;r++)n[r][0]===e&&t.push(n[r][1]);return t}has(e,t){e=S(e),t=t!=null?S(t):void 0;let{list:n}=this[C];for(let r=0;r<n.length;r++)if(n[r][0]===e&&(t==null||n[r][1]===t))return!0;return!1}set(e,t){e=S(e),t=S(t);let{list:n}=this[C],r=!1,u=!1,l=0;for(;l<n.length;)n[l][0]===e?r?(n.splice(l,1),u=!0):(r=!0,n[l][1]!==t&&(n[l][1]=t,u=!0),l++):l++;r||(n.push([e,t]),u=!0),u&&oA(this[C])}sort(){this[C].list.sort((e,t)=>e[0]<t[0]?-1:e[0]>t[0]?1:0),oA(this[C])}forEach(e,t){if(typeof e!="function")throw new TypeError('The "callback" argument must be of type function');let{list:n}=this[C];for(let r=0;r<n.length;r++)e.call(t,n[r][1],n[r][0],this)}entries(){return new Z(this[C],e=>e)}keys(){return new Z(this[C],e=>e[0])}values(){return new Z(this[C],e=>e[1])}toString(){return CA(this[C].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(fA.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});function he(A){let e,t=()=>typeof e=="string"?e:e?.accessToken,n=0,r,u=new Map,l=()=>{for(let p of[...u.keys()])try{p()}catch{}};function a(p){let m=++n;r=void 0,e=void 0;for(let y of[...u.values()])try{y?.()}catch{}m===n&&(e=p,l())}let f=()=>a();function h(p,m=!1){let y=$A.safeParse(p);if(!y.success||m&&Date.parse(y.data.expiresAt)<=Date.now()||Date.parse(y.data.refreshExpiresAt)<=Date.now()||Date.parse(y.data.refreshExpiresAt)<Date.parse(y.data.expiresAt))throw new P("INVALID_RESPONSE","Invalid customer session credentials");return y.data}async function w(){if(r)return r;let p=typeof e=="object"?e:void 0,m=n;if(!p||Date.parse(p.refreshExpiresAt)<=Date.now())throw p&&f(),new P("UNAUTHENTICATED","Customer authentication is required",401);let y=(async()=>{try{let N=await A(p.refreshToken);if(m!==n)throw new P("IDENTITY_CHANGED","Customer identity changed during refresh");let V=h(N,!0);if(V.customerId!==p.customerId||V.sessionId!==p.sessionId)throw new P("SCOPE_MISMATCH","Refresh changed the customer session");return e=V,{...V}}catch(N){throw m!==n?new P("IDENTITY_CHANGED","Customer identity changed during refresh"):(N instanceof P&&N.status===401&&f(),N)}})();r=y;try{return await y}finally{r===y&&(r=void 0)}}return{identify(p){let m=typeof p=="string"?p:h(p),y=typeof m=="string"?m:m.accessToken;if(!y.trim()||/\s/.test(y)||y.length>4096)throw new P("INVALID_TOKEN","A server-issued token is required");a(m)},reset:f,subscribeIdentity(p,m){return u.set(p,m),()=>{u.delete(p)}},access(){let p=typeof e=="object"?e:void 0;if(p&&Date.parse(p.expiresAt)<=Date.now()+3e4){let y=n;return w().then(()=>{let N=t();if(y!==n||!N)throw new P("IDENTITY_CHANGED","Customer identity changed during refresh");return N})}let m=t();if(!m)throw new P("NOT_IDENTIFIED","Identify a customer session before making a request");return m},peek:t,snapshot:()=>typeof e=="object"?{...e}:void 0,refresh:w}}var de=Symbol("IndianaNoContent");function ut(A,e,t=eA){let n=A.configuration?.scope,r=A.scope??(n&&{projectId:n.projectId,environment:n.environment}),u=r?sA.parse(r):void 0;if(u&&n&&(u.projectId!==n.projectId||u.environment!==n.environment))throw new P("SCOPE_MISMATCH","Configuration belongs to another App/environment");let l=new t(A.baseUrl??FA);if(l.username||l.password||l.search||l.hash)throw new P("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(l.protocol!=="https:"&&!(l.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(l.hostname)))throw new P("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let a=A.fetch??globalThis.fetch.bind(globalThis),f=A.timeoutMs??1e4;if(!Number.isFinite(f)||f<1||f>12e4)throw new P("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let h=!1,w=0,p=null,m=new Set,y=A.session??he(async q=>{let O=await tA("customer-sessions/refresh",{},"POST",{},q);if(!O||typeof O!="object")throw new P("INVALID_RESPONSE","Invalid refresh response");let{requestId:$,scope:H,...K}=O;return K});function N(){w+=1,p=null;for(let q of m)q.abort();m.clear()}let V=y.subscribeIdentity(N);function pe(){h||y.reset()}async function tA(q,O={},$="POST",H={},K){let k=H.installationDetach===!0;if(k&&(q!=="push/installations/detach"||$!=="POST"))throw new P("INVALID_REQUEST","Installation authority only detaches this installation");if(!K&&!k)throw new P("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let J=w,L=new AbortController;k||m.add(L);let nA=()=>!k&&J!==w?new P("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new P("TIMEOUT","Longplay request timed out"),dA,ge=new Promise((T,R)=>{dA=()=>R(nA()),L.signal.addEventListener("abort",dA,{once:!0})}),we=setTimeout(()=>L.abort(),H.timeoutMs??f),me=async()=>{let T=await a(`${l.href.replace(/\/$/,"")}/api/v1/${q}`,{method:$,headers:{...H.headers,"Content-Type":"application/json",...k?{}:{Authorization:`Bearer ${K}`},[pA]:gA.current,[xA]:zA.version,...u?{"X-Indiana-Project":u.projectId,"X-Indiana-Environment":u.environment}:{}},body:$==="POST"?JSON.stringify(O):void 0,signal:L.signal,credentials:"omit",cache:"no-store",redirect:"error",...H.keepalive?{keepalive:!0}:{}});if(L.signal.aborted)throw nA();let R;try{R=T.status===204?de:await T.json()}catch{throw L.signal.aborted?nA():new P(T.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",T.status,T.headers.get("X-Request-Id")??void 0)}if(L.signal.aborted)throw nA();if(!k&&J!==w)throw new P("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!T.ok){let v=UA.safeParse(R),z=v.success&&(!MA.safeParse(v.data.error.code).success||jA(v.data.error.code,T.status)),BA=z?v.data.error.code:"HTTP_ERROR",HA=_A(BA,T.status,{retryAfter:T.headers.get("Retry-After"),recovery:z?v.data.error.recovery:void 0,reason:z?v.data.error.reason:void 0});throw new P(BA,z?v.data.error.message:"Longplay request failed",T.status,T.headers.get("X-Request-Id")??(v.success?v.data.requestId:void 0),{...HA,...v.success&&v.data.error.retryable===!1?{retryable:!1}:{},...HA.retryAfterSeconds===void 0&&v.success&&v.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:v.data.error.retryAfterSeconds}:{}})}if(T.headers.get(pA)!==gA.current)throw new P("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(u&&R!==de){let v=R&&typeof R=="object"&&"scope"in R?R:R&&typeof R=="object"&&"configuration"in R?R.configuration:null;if(!v||typeof v!="object"||!("scope"in v))throw new P("INVALID_RESPONSE","Response is missing its App/environment scope");let z=sA.safeParse(v.scope);if(!z.success||z.data.projectId!==u.projectId||z.data.environment!==u.environment)throw new P("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let rA=T.headers.get("X-Indiana-Telemetry-Subject");if(rA){if(!/^[a-f0-9]{64}$/.test(rA))throw new P("INVALID_RESPONSE","Invalid telemetry identity");p!==rA&&(p=rA,e?.(p))}return R};try{return await Promise.race([me(),ge])}catch(T){throw!k&&J!==w?new P("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):T instanceof P?T:new P(L.signal.aborted?"TIMEOUT":"NETWORK_ERROR",L.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(we),L.signal.removeEventListener("abort",dA),m.delete(L)}}return{session:y,requestWithCredential(q,O,$,H={}){return h?Promise.reject(new P("CLOSED","SDK client was destroyed")):tA(q,O,"POST",H,$)},subjectKey:()=>p,identify(q){if(h)throw new P("CLOSED","SDK client was destroyed");if(u&&typeof q=="object"&&"scope"in q){let O=sA.safeParse(q.scope);if(!O.success||O.data.projectId!==u.projectId||O.data.environment!==u.environment)throw new P("SCOPE_MISMATCH","Customer session belongs to another App/environment")}y.identify(q)},reset:pe,dispose(){h||(h=!0,V(),N())},request(q,O={},$="POST",H={}){if(h)return Promise.reject(new P("CLOSED","SDK client was destroyed"));if(H.installationDetach)return tA(q,O,$,H);let K=w;try{let k=y.access(),J=L=>{if(K!==w)throw new P("IDENTITY_CHANGED","Customer identity changed before dispatch");return tA(q,O,$,H,L)};return typeof k=="string"?J(k):k.then(J)}catch(k){return Promise.reject(k)}}}}export{eA as a,ut as b};
@@ -1 +1 @@
1
- import{a as u}from"./chunk-QVGTHPWT.js";import{Aa as j,Ba as O,Ca as T,ya as E,za as M}from"./chunk-ZC6PDVLR.js";import{q as w}from"./chunk-HDVLCRC6.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
1
+ import{a as u}from"./chunk-QVGTHPWT.js";import{Aa as j,Ba as O,Ca as T,ya as E,za as M}from"./chunk-JXNNWCEB.js";import{q as w}from"./chunk-HDVLCRC6.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
@@ -1 +1 @@
1
- import{b as mn,c as pn,d as gn,e as yn,f as wn}from"./chunk-YAVWELIV.js";import{a as ae,b as ee}from"./chunk-H6PIJ4WG.js";import{a as l}from"./chunk-QVGTHPWT.js";import{a as dn,b as fn,c as Pe}from"./chunk-KOFZECHE.js";import{$ as Se,Da as ie,Ea as nn,Ha as tn,Ia as rn,Na as Te,Oa as on,Z as je,aa as Je,ab as an,ba as He,bb as sn,ca as ze,eb as un,fb as ln,ib as cn,lb as ye,ma as X,na as Qe,o as ke,oa as Y,pa as Ye,q as ge,qa as Oe,ra as j,ta as $e,ua as We,va as Ze,wa as Xe,xa as en}from"./chunk-ZC6PDVLR.js";import{a as hn}from"./chunk-DSPLGTQI.js";import{C as Ue,J as Ge,M as Be,Na as Ke,P as be,a as qe}from"./chunk-HDVLCRC6.js";function zn(e){let n=null,a=null,t=0,f=0,p=new Set,m=null,c=null,r=new Set,o=()=>{for(let i of r)try{i()}catch{}},s={attributes:be.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(i,y)=>{!p.has(i)&&n&&(!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(i,structuredClone(y),structuredClone(s.attributes),n.generation)}:void 0,onExperimentViewed:e.onExperimentViewed?(i,y)=>n&&(!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(i),structuredClone(y),structuredClone(s.attributes),n.generation):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?i=>e.saveStickyBucketAssignmentDoc(structuredClone(i)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},I=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function g(i,y=new Set){return p.has(i)?!m||!m.features[i]||["unknownFeature","cyclicPrerequisite"].includes(m.features[i].source):y.has(i)?!1:(y.add(i),(n?.features[i]?.rules??[]).some(P=>[...P.parentConditions??[],...(P.tracks??[]).flatMap(N=>N.experiment.parentConditions??[])].some(N=>g(N.id,y))))}let d=i=>{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 m?.expiresAt&&Date.parse(m.expiresAt)<=Date.now()&&(m=null,s.features=n.features),p.has(i)?!m||m.expiresAt&&Date.parse(m.expiresAt)<=Date.now()?I():structuredClone(m.features[i]??I()):e.evaluateRemote&&(s.attributes?.merchandise||s.attributes?.merchandiseId)&&!m||g(i)?I():structuredClone(Be(i,s))};async function S(){if(!n||!p.size&&!s.attributes?.merchandise&&!s.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(p.size)throw new Error("Remote Feature evaluation requires a server loader");return}let i=f;if(c?.revision===i)return c.loading;let y=t,P=n,N=[...p],D=(async()=>{let T=ze.parse(await e.evaluateRemote({attributes:structuredClone(s.attributes),features:N}));if(!(y!==t||i!==f||P!==n)){if(e.assertUsable?.(P.generation),T.generation!==P.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(N.some(u=>!Object.hasOwn(T.features,u))||Object.keys(T.features).some(u=>!p.has(u)))throw new Error("Invalid remote Feature results");if(s.attributes?.merchandise||s.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");s.attributes=be.parse({...s.attributes,...T.merchandiseContext})}m=structuredClone(T),s.features={...P.features,...Object.fromEntries(Object.entries(m.features).map(([u,b])=>[u,{defaultValue:b.value}]))},o()}})();c={revision:i,loading:D};try{await D}finally{c?.loading===D&&(c=null)}}function _(){S().catch(i=>{try{e.onError?.(i)}catch{}})}async function q(){if(a)return a;let i=t,y=(async()=>{let P=await e.load(),N="remoteFeatures"in P?Je.parse(P):null,D=N??Se.parse(P);if(D.scope.projectId!==e.scope.projectId||D.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(i!==t)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===D.generation){let{evaluatedAt:u,expiresAt:b,...L}=n,{evaluatedAt:v,expiresAt:O,...E}=D;if(j(L)!==j(E))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=D.evaluatedAt,n.expiresAt=D.expiresAt,o(),(!m||m.expiresAt&&Date.parse(m.expiresAt)<=Date.now())&&_(),structuredClone(n)}let T=new Set(N?.remoteFeatures??[]);if([...T].some(u=>Object.hasOwn(D.features,u)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in D&&!n.analyticsConfig.experimentViewsEnabled&&N?.analyticsConfig.experimentViewsEnabled&&s.trackedExperiments?.clear(),n=structuredClone(D),p=T,m=null,c=null,f++,s.features=n.features,s.savedGroups=Ge(n.savedGroups),s.trackedFeatureUsage={},o(),_(),structuredClone(n)})();a=y;try{return await y}finally{a===y&&(a=null)}}return{init:q,refresh:q,refreshRemote:S,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(i){return r.add(i),()=>{r.delete(i)}},setAttributes(i){let y=be.parse(i);(s.attributes?.merchandise||s.attributes?.merchandiseId||i.merchandise||i.merchandiseId)&&s.trackedExperiments?.clear(),s.attributes=y,f++,m=null,c=null,s.features=n?.features??{},s.trackedFeatureUsage={},o(),_()},evalFeature:d,isOn(i){return d(i).on},isOff(i){return d(i).off},getFeatureValue(i,y){let P=d(i).value;return structuredClone(P===null?y:P)},reset(){t++,f++,a=null,c=null,n=null,m=null,p.clear(),s.features={},s.savedGroups={},s.stickyBucketAssignmentDocs={},s.attributes={},s.trackedFeatureUsage={},s.trackedExperiments?.clear(),o()}}}function In(e){let n,a,t=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),f=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,a=e.locks??globalThis.navigator?.locks,!n||!a||!globalThis.crypto?.subtle)throw t();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ye).href,e.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return"indiana.funnel.commands.v1."+Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")});f.catch(()=>{});async function p(c){try{let r=await f;return await a.request(r,{mode:"exclusive"},()=>c(r))}catch(r){throw r instanceof l?r:t()}}function m(c){let r=n.getItem(c);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw t();let o=JSON.parse(r);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw t();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(m),write:(c,r)=>p(o=>{if(m(o).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw t();return n.setItem(o,JSON.stringify({revision:c+1,entry:r})),c+1})}}function Ee(e,n){let a=tn.safeParse(n);if(!a.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let t=a.data;if(e.scope&&(t.scope.projectId!==e.scope.projectId||t.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return t}async function Ae(e,n){let a=Xe.parse(n),{artifact:t,environmentId:f}=a.content,p=new ae(e.baseUrl??ye).origin,m=new ae(t.url,p);if(m.origin!==p||m.username||m.password||m.search||m.hash||m.pathname!==`/api/v1/configuration/${f}/artifacts/${t.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let c=new AbortController,r,o=new Promise((I,g)=>{r=setTimeout(()=>{let d=new l("TIMEOUT","Public Paywall read timed out");c.abort(d),g(d)},Y.initializationMs)}),s=(async()=>{let I=await(e.fetch??globalThis.fetch)(m,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:c.signal});if(c.signal.aborted&&(I.body?.cancel().catch(()=>{}),c.signal.throwIfAborted()),!I.ok||!I.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(I.headers.get("content-length"))>t.byteLength)throw I.body?.cancel().catch(()=>{}),new l("INVALID_RESPONSE","Public Paywall is unavailable");let g=await dn(I,t.byteLength,{signal:c.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Pe(g,t))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return en(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(g)))})();try{return await Promise.race([s,o])}finally{clearTimeout(r)}}var _e=(e,n)=>new l(e,n);function ut(e){return ln(e,_e)}var _n=3,Dn=2e3;function Ln(e){return e instanceof TypeError||e instanceof l&&/^(?: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(a){if(n===_n||!Ln(a))throw a;await new Promise(t=>setTimeout(t,n*Dn))}}async function De(e,n,{predict:a=!0}={}){let t=n.instruction;if(t?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==t.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let f=null,p;if(a)try{let m=await e.funnel(n.source.id,n.source.versionId);p=m.manifest.generation,f=Mn(e,n,m)}catch{f=null}return p??=e.snapshot?.generation??(await xn(e)).generation,{advance:{policyRevision:t.policyRevision,generation:p},prediction:f}}function Mn(e,n,a){let t=n.instruction;if(t?.type!=="evaluate_segment"||!a.growth||a.control.evaluationMode!=="local"||a.control.evaluationRevision!==t.policyRevision)return null;let{analyticsConfig:f,remoteFeatures:p,...m}=a.growth,c=an({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:t.policyRevision,document:a.document,payload:Se.parse(m)}),r=Vn(c,a.document,{...n,...t}),o=r.steps.at(-1),s=r.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:n.visit+r.steps.length-1}:null);return s?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:s.nodeId,visit:s.visit,terminal:!r.boundary}:null}function Vn(e,n,a){return cn(e,n,a,_e)}import{z as $}from"zod";var vn=X.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 l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Rn=$.strictObject({schemaVersion:$.literal(1),scope:qe,runId:$.uuid(),funnelId:$.uuid(),versionId:$.uuid(),processBindingIds:$.record($.uuid(),$.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.refine(e=>e.operation==="close").optional(),purchase:$.strictObject({receiptId:$.uuid(),operationId:$.uuid(),generation:$.number().int().nonnegative()}).optional(),closed:$.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"),z=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Fe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function Cn(e){let n=0,a=null,t=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),f=Promise.resolve();async function p(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:Rn.parse(o.entry)}}function m(o){let s=f.then(o);return f=s.catch(()=>{}),s}async function c(o){for(let s=0;s<4;s++){let I=await p();if(I.entry&&a!==null&&t(I.entry)!==a)throw z();let g=o(I.entry,I.revision);if(Fe(I.entry,g)){n=I.revision;return}let d=await e.write(I.revision,g);if(d!==null){if(!Number.isSafeInteger(d)||d<=I.revision)throw z();n=d;return}}throw z()}function r(o,s){if(!o||!s)return o;if(o.processBindingIds&&Object.hasOwn(o.processBindingIds,s)){let I={...o.processBindingIds};delete I[s],o={...o,processBindingIds:I}}return o.command?.requestId===s?o.closeCommand?{...o,command:o.closeCommand,closeCommand:void 0}:o.purchase?{...o,command:void 0}:null:o.closeCommand?.requestId===s?{...o,closeCommand:void 0}:o}return{bind(o){let s=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(a!==null&&a!==s)throw z();a=s},async load(){let o=await p();return n=o.revision,a=o.entry?t(o.entry):null,o.entry},retain(o){let s=Rn.parse(o),I=s.command;return!I||a!==null&&t(s)!==a?Promise.reject(z()):(a??=t(s),m(()=>c((g,d)=>{if(g&&!Fe(t(g),t(s)))throw z();if(g&&s.processBindingIds){for(let[S,_]of Object.entries(s.processBindingIds))if(g.processBindingIds&&Object.hasOwn(g.processBindingIds,S)&&g.processBindingIds[S]!==_)throw z();g={...g,processBindingIds:{...g.processBindingIds,...s.processBindingIds}}}if(!g){if(d!==n&&I.operation!=="close")throw z();return s}if(!g.command)return{...g,command:I,...I.operation==="close"?{closed:!0}:{}};if(I.operation==="close"&&g.command.operation!=="close"){if(g.command.requestId===I.requestId||g.closeCommand&&!Fe(g.closeCommand,I))throw z();return{...g,closeCommand:I,closed:!0}}if(!Fe(g.command,I))throw z();return g})))},observePurchase(o,s,I,g){return m(()=>c((d,S)=>{if(!d&&S!==n||d&&t(d)!==t({...o,schemaVersion:1}))throw z();if(d?.purchase&&d.purchase.generation>s.generation)return r(d,g);if(d?.purchase&&d.purchase.generation===s.generation&&d.purchase.operationId!==s.operationId)throw z();return I?!d?.purchase||d.purchase.operationId!==s.operationId?r(d,g):r(d.command?{...d,purchase:void 0}:null,g):r({schemaVersion:1,...o,...d,purchase:s},g)}))},settle(o){return m(()=>c(s=>r(s,o)))}}}function ht(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function we(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((f,p)=>we(f,n[p]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let a=Object.entries(e),t=Object.entries(n);return a.length===t.length&&a.every(([f,p])=>Object.hasOwn(n,f)&&we(p,Reflect.get(n,f)))}function bn(e,n){let a=n&&{...n},t=null,f=0,p=-1,m=0,c=new AbortController;function r(){m++,c.abort(new l("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let o=!1,s,I=0,g=new Set;return{get scope(){return a},bindScope(d){if(a&&(a.projectId!==d.projectId||a.environment!==d.environment))throw new l("SCOPE_MISMATCH","Run scope changed");a??={...d}},get view(){return t},get currentView(){return p===m?t:null},get viewAgeMs(){return t&&p===m?performance.now()-f:void 0},get generation(){return m},get signal(){return c.signal},get disposed(){return o},get customerToken(){return s},get readSequence(){return I},nextRead(){return++I},assertCurrent(d,S="Run identity changed during the request"){if(d!==m||o)throw new l("IDENTITY_CHANGED",S)},assertRun(d){if(t&&(d.id!==t.id||d.source.type!==t.source.type||d.source.id!==t.source.id||d.source.versionId!==t.source.versionId||d.locale!==t.locale||!we(d.parameters,t.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&d.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(d,S,_,q,i){if(!(d.operation==="review"&&t&&t!==_&&S.run.revision<=t.revision)&&!(t&&S.run.revision===t.revision&&q!==void 0&&q<I)&&(d.operation==="review"&&!S.run.stopped&&["running","waiting"].includes(S.run.status)&&t&&p===m&&S.run.nodeId===t.nodeId&&S.run.visit===t.visit&&S.run.revision===t.revision&&(S.run.screen=t.screen,(t.paywall?.quote?.operationId===S.review?.activeOperationId||!t.paywall?.quote&&S.review?.activeOperationId===null)&&(S.run.paywall=t.paywall)),!(t?.paywall&&S.run.paywall&&t.paywall.receiptId===S.run.paywall.receiptId&&(S.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||S.run.revision>=t.revision)t=S.run,f=performance.now(),p=m;else if(!i)return;if(t&&p===m)for(let y of g)try{y(structuredClone(t))}catch{}}},identify(d){if(o)throw new l("IDENTITY_CHANGED","Controller was reset");if(!ge.test(d))throw new l("INVALID_TOKEN","Customer credential required");r(),s=d},subscribe(d){return g.add(d),()=>g.delete(d)},reset(){o||(o=!0,r(),s=void 0,t=null,g.clear())}}}var se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Pt(e,n,a="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!se.test(e))throw new l("INVALID_TOKEN",a)}function Et(e){let n=ee(e);return n.identify(e.apiKey),n}function ne(e){let{customerToken:n,...a}=e;return a}var qn=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Sn({journal:e,state:n,call:a,processIdentity:t}){let f=null,p=null,m=!1,c={command:null,close:null},r=new Set,o,s=null,I=e?e.load().then(i=>{if(n.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(s=i,!i)return;if(t){if([i.command,i.closeCommand].some(P=>P&&!Object.hasOwn(i.processBindingIds??{},P.requestId)))throw new l("COMMAND_STORAGE_INVALID","The original process identity is missing");t.restore(i.processBindingIds??{})}if(n.scope&&(i.scope.projectId!==n.scope.projectId||i.scope.environment!==n.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=i.purchase,m=i.closed===!0,!i.command)return;let y=i.command;f=y.operation==="close"?null:y,p=y.operation==="close"?y:i.closeCommand?.operation==="close"?i.closeCommand:null,p&&(m=!0);for(let P of[f,p])P&&r.add(P.requestId)}):Promise.resolve();I.catch(()=>{});async function g(i){e&&await I;let y=n.generation;if(e){if(!n.view||!n.scope)throw new l("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:ne(i),...t?{processBindingIds:{[i.requestId]:t.binding(i.requestId)}}:{}})}if(y!==n.generation||f!==i&&p!==i)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let P=r.has(i.requestId);r.add(i.requestId);try{return await a(i)}catch(N){throw y===n.generation&&(f===i||p===i)&&!P&&!qn(N)&&(e&&await e.settle(i.requestId),y===n.generation&&q(i)),N}}function d(i){let y=X.parse(i);if(y.operation==="start"||y.operation==="get"||y.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(m&&y.operation!=="close"){if(f?.requestId===y.requestId)return _(y.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(y.operation==="close"){if(f?.requestId===y.requestId)throw new l("INVALID_REQUEST","Close requires its own request identity");if(m=!0,p&&JSON.stringify(ne(p))!==JSON.stringify(ne(y)))throw new l("COMMAND_PENDING","Retry the original Close");return p??=y,c.close?c.close:S(p,"close")}if(f){if(JSON.stringify(ne(f))!==JSON.stringify(ne(y)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else f=y;return S(f,"command")}function S(i,y){let P=g(i);c[y]=P;let N=()=>{c[y]===P&&(c[y]=null)};return P.then(N,N),P}function _(i){return a({operation:"get",settlementRequestId:i})}function q(i){return!i||f!==i&&p!==i?!1:(f===i&&(f=null),p===i&&(p=null),r.delete(i.requestId),!f&&!p&&(s=null),!0)}return{ready:I,get pending(){return f},get closing(){return p},get closeRequested(){return m},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return o},assertBinding(i){if(s&&(i.run.id!==s.runId||i.run.source.id!==s.funnelId||i.run.source.versionId!==s.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(i,y,P,N){let D=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0,T=D&&y.settlement?.state==="settled"&&y.run.pendingRequest?.requestId!==D&&(i.operation==="get"||!m||i.operation==="close"||!["running","waiting"].includes(y.run.status))?D:void 0,u=f?.requestId===T?f:p?.requestId===T?p:void 0;e?.bind({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId});let b=y.run.paywall,L=b??y.purchase,v=L?.operation,O=y.settlement&&(!b||b.purchaseRequestId===y.settlement.requestId)&&(!o||o.operationId===y.settlement.operationId)?y.settlement:void 0,E=v?.operationId??L?.quote?.operationId??O?.operationId,A=L?.receiptId??O?.receiptId,U=b?.selectionGeneration??o?.generation??0;if(e&&E&&A&&i.operation!=="review"&&(!n.view||y.run.revision>=n.view.revision)&&(N===void 0||N>=n.readSequence)&&(!o||U>=o.generation)){let x={receiptId:A,operationId:E,generation:U},H=v?.status==="complete"||L?.canReselect===!0;await e.observePurchase({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId},x,H,T),n.assertCurrent(P),(!o||x.generation>=o.generation)&&(N===void 0||N>=n.readSequence)&&(H?o?.operationId===x.operationId&&(o=void 0):o=x)}else e&&T&&await e.settle(T);return n.assertCurrent(P),T?q(u):!1},stop(){m=!0},submit:d,settle:_,reset(){m=!0,f=null,p=null,o=void 0,s=null,c.close=null,r.clear(),c.command=null}}}function Pn(e){e={...e};let n=e.initialResponse;if(delete e.initialResponse,typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!se.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let a=ee({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=bn(e.funnelId,e.scope??e.configuration?.scope),f=e.session?.subscribeIdentity(d),p=null,m=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?In(e):void 0),c=m&&Cn(m),r=Sn({journal:c,state:t,call:S,processIdentity:e.process}),o=0,s=new Map;function I(){o++,s.clear(),n=void 0}async function g(u){if(e.process)return e.process.request(u);let b=t.generation;t.assertCurrent(b);let L=performance.now()+(e.timeoutMs??35e3),v=t.customerToken??("customerToken"in u?u.customerToken:void 0);if(e.session){let A=t.signal,U,x=()=>{},H=new Promise((K,G)=>{x=()=>G(A.reason),A.addEventListener("abort",x,{once:!0}),U=setTimeout(()=>G(new l("TIMEOUT","Longplay request timed out")),Math.max(1,L-performance.now()))});try{v=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(b),e.session.access())),H])}finally{clearTimeout(U),A.removeEventListener("abort",x)}}t.assertCurrent(b);let O={...u,...v?{customerToken:v}:{}},E=u.operation==="page_experiments"?Te.parse(O):X.parse(O);return a.requestWithCredential("funnels",E,e.runToken,{headers:e.serverKey&&!v?{[rn]:e.serverKey}:void 0,timeoutMs:Math.max(1,L-performance.now())})}function d(){I(),f?.(),t.reset(),r.reset(),p=null,a.dispose()}async function S(u,b){let L=n;n=void 0;let v=t.generation,O=()=>t.assertCurrent(v);c&&await r.ready,O();let E=t.view,A=Ee(e,L!==void 0&&u.operation==="get"&&!u.data&&!u.purchase&&!u.settlementRequestId?L:await g(u));if(u.operation==="review"&&!A.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(O(),A.runToken&&A.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let U=u.operation==="get"?u.settlementRequestId:"requestId"in u&&u.operation!=="start"?u.requestId:void 0;if(U&&A.settlement?.requestId!==U)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(A),t.assertRun(A.run),t.bindScope(A.scope);let x=await r.observe(u,A,v,b);return!A.run.stopped&&["running","waiting"].includes(A.run.status)&&u.operation==="get"&&u.settlementRequestId||(O(),["running","waiting"].includes(A.run.status)||r.stop(),t.publish(u,A,E,b,x)),A}function _(u){let b=t.generation;I();let L=u(),v=()=>{t.generation===b&&I()};return L.then(v,v),L}let q=u=>_(()=>r.submit(u)),i=null,y=new WeakMap;function P(u){let b=y.get(u);if(b)return b;let L=D(u);return y.set(u,L),L}let N=!1;async function D(u){let b=await u;if(b.run.instruction?.type!=="evaluate_segment")return b;if(i)return i;N=!0;let L=t.generation,v=(async()=>{for(let O=0;O<32&&b.run.instruction?.type==="evaluate_segment";O++){if(r.pending||r.closeRequested)return b;let E=b.run;if(b.run.instruction?.type==="evaluate_segment"){let{advance:U}=await De(e.configuration,E,{predict:!1});if(L!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return b;if(t.view&&(t.view.revision!==E.revision||t.view.visit!==E.visit||t.view.nodeId!==E.nodeId))return S({operation:"get"});let x=!0;De(e.configuration,E).then(({prediction:H})=>{x&&L===t.generation&&!r.closeRequested&&t.view?.id===E.id&&!t.view.stopped&&t.view.nodeId===E.nodeId&&t.view.visit===E.visit&&t.view.revision===E.revision&&(p=H)}).catch(()=>{});try{b=await q({operation:"commit_segment",requestId:nn(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...U})}finally{x=!1,p=null}}}return b})();i=v;try{return await v}finally{i===v&&(i=null)}}let T={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){let u=t.currentView;return u?structuredClone(u):null},get viewAgeMs(){return t.viewAgeMs},get pendingCommand(){let u=r.closing??r.pending;return u?structuredClone(ne(u)):null},get pendingCommands(){return[r.pending,r.closing].filter(u=>u!==null).map(u=>structuredClone(ne(u)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get hasDurableJournal(){return c!==void 0},get prediction(){let u=t.view;return p&&u&&!u.stopped&&["running","waiting"].includes(u.status)&&u.id===p.runId&&u.nodeId===p.from.nodeId&&u.visit===p.from.visit&&u.revision===p.from.revision&&!r.closeRequested?structuredClone(p):null},settle:(...u)=>_(()=>r.settle(...u)),get webViewUrl(){return"bundled"},resolvePaywall(u){return Ae(e,u)},async pageExperiments(u,b=[]){let L=t.generation;t.assertCurrent(L);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let O=on.parse(await g(Te.parse({operation:"page_experiments",release:u,usedReceiptIds:b})));if(t.assertCurrent(L),O.runId!==v||O.scope.projectId!==t.scope?.projectId||O.scope.environment!==t.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return O},review(u){return S({operation:"review",...u?{receiptId:u}:{}},t.nextRead())},async get(u,b){let L=t.generation;u=u&&structuredClone(u),b=b&&{...b},c&&await r.ready,t.assertCurrent(L),b??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let v=JSON.stringify([t.generation,o,u??null,b??null]),O=s.get(v);if(O)return O.then(x=>structuredClone(x));let E=t.nextRead(),A=P(S({operation:"get",...u?{data:u}:{},...b?{purchase:b}:{}},E));s.set(v,A);let U=()=>{s.get(v)===A&&s.delete(v)};return A.then(U,U),A.then(x=>structuredClone(x))},resume(u=t.view?.pendingRequest?.requestId){return u?r.closeRequested?T.settle(u):r.pending?.requestId===u?P(q(r.pending)):P(q({operation:"resume",requestId:u})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(u){return P(q(u))},retry(){return r.closeFlight?r.closeFlight:r.closing?q(r.closing):r.closeRequested&&r.pending?T.settle(r.pending.requestId):r.inFlight?P(r.inFlight):r.pending?P(q(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(u){let b=t.customerToken?void 0:n;I(),t.identify(u),n=b,p=null,a.reset()},get identitySignal(){return t.signal},subscribe:t.subscribe,reset:d};return T}function kn(e,n,a,t){if(!Ue(e,n)||a!==void 0&&n.observation&&n.observation.subject.customerId!==a||t!==void 0&&n.observation!==void 0&&(n.observation.subject.scope.projectId!==t.projectId||n.observation.subject.scope.environment!==t.environment))throw new l("INVALID_RESPONSE","The access requirement or Customer changed");return n}function En(e,n,a){if(e.requirement){if(!n)throw new l("INVALID_RESPONSE","The requested access check is missing");kn(e.requirement,n,e.customerId,a)}}import{ZodError as Un}from"zod";function An(e,n,a,t){try{return e.parse(n)}catch(f){throw t&&f instanceof Un?new l(a,t):f}}async function Ne(e,n,a,t={},f){let p=typeof t=="function"?{}:t,m=An(n.request,a,"INVALID_REQUEST",p.request);try{let c=await e(n.path,m,n.method,f),r=typeof t=="function"?t:t.parseResponse;return r?r(n.response,c):An(n.response,c,"INVALID_RESPONSE",p.response)}catch(c){throw c instanceof l&&m!==null&&typeof m=="object"&&"requestId"in m&&typeof m.requestId=="string"&&(c.commandRequestId??=m.requestId),c}}async function or(e,n){if(!ge.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let a=ie.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}:{}}),t=ee(e);e.session||t.identify(n.customerToken);let f=null,p=!1,m=new AbortController,c=null,r=null,o=null,s=null,I=null,g=null,d=null,S=0,_=null,q="",i=0,y=new Map,P=new Set;function N(){if(p)throw new l("IDENTITY_CHANGED","Paywall is closed")}function D(){let v=JSON.stringify([S,d!==null]);if(!_||v!==q){q=v;let O=T(++i);_=O;let E=()=>{_===O&&(_=null)};O.then(E,E)}return _.then(O=>structuredClone(O))}async function T(v){N();let O=ie.resolvePaywall,E=await Ne(t.request,O,{...a,selector:f?{type:"version",versionId:f.id}:a.selector});En(a,E.paywall.check,E.scope);let A=await Ae(e,E.paywall);if(N(),n.paywallVersionId?A.id!==n.paywallVersionId:A.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(f&&(!mn(A,f)||A.paywallId!==f.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(v!==i)return structuredClone(f??A);f=A;for(let U of P)hn(U,structuredClone(f));return structuredClone(f)}async function u(v){if(N(),s&&v!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let O=c;if(v!=="read"){if(d){if(g===v)return d;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(g&&g!==v)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");g=v,S++,i++}let E=g,A=S,U=v==="read"&&d===null,x=JSON.stringify([O.operationId,A,d!==null]);if(v==="read"&&y.has(x))return y.get(x).then(G=>structuredClone(G));let H=v==="read"?ie.readSubscriptionOperation:ie.attach,K=(async()=>{let G=await Ne(t.request,H,{operationId:O.operationId,...v==="read"?{}:{intent:v},...v==="confirm"&&O.merchantTerms?{merchantConfirmation:ke(O.merchantTerms)}:{}});return pn(G.operation,{operationId:O.operationId,currency:a.commerce.currency},"The purchase operation changed"),N(),c?.operationId!==O.operationId?structuredClone(G.operation):(r=yn(r,G.operation),(v!=="read"||U&&d===null)&&S===A&&g===E&&(g=null),structuredClone(r))})();if(v!=="read"){d=K;let G=()=>{d===K&&(d=null)};K.then(G,G)}else{y.set(x,K);let G=()=>{y.get(x)===K&&y.delete(x)};K.then(G,G)}return K.then(G=>structuredClone(G))}let b={signal:m.signal,get view(){return f?structuredClone(f):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},get recovery(){return wn({quote:c,operation:r,requestId:I,pending:s!==null||g!==null,destroyed:p})},get pendingCancellation(){return!p&&g==="cancel"},refresh:D,subscribe(v){return p?()=>{}:(P.add(v),()=>P.delete(v))},async preview(v){if(N(),!f)throw new l("INVALID_REQUEST","Load the Paywall first");let O=f.document.buttons[v.actionId];if(O?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let E=je(O.product,v.selection,f.capabilities);if(!E)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let A=Ke(f.document.screen,E,v.selection,f.capabilities),U=ie.previewAttach.request.parse({funnelId:a.funnelId,funnelVersionId:a.funnelVersionId,requestId:v.requestId,plans:[{productVersionId:E,...Object.keys(A).length?{featureQuantities:A}:{}}],provider:a.commerce.provider,currency:a.commerce.currency,...v.offerId?{offerId:v.offerId}:{},...v.nativeOffer?{nativeOffer:v.nativeOffer}:{}}),x=JSON.stringify(U);if(o&&o!==x&&(s||g||!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===x){if(s)return s;if(c)return structuredClone(c)}o!==x&&(c=null,r=null),o=x,I=U.requestId;let H=(async()=>{let K=ie.previewAttach,G=await Ne(t.request,K,U);return N(),gn(G.quote,{productVersionId:E,featureQuantities:A,currency:a.commerce.currency,provider:a.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=G.quote,r=null,structuredClone(c)})();s=H;try{return await H}finally{s===H&&(s=null)}},confirm:()=>u("confirm"),cancel:()=>u("cancel"),read:()=>u("read"),destroy(){p||(p=!0,m.abort(),P.clear(),y.clear(),L?.(),t.dispose(),f=null,c=null,r=null,o=null,I=null)}},L=e.session?.subscribeIdentity(b.destroy);try{return await D(),b}catch(v){throw b.destroy(),v}}import{z as Jn}from"zod";import{z as Ie}from"zod";var Gn=Ie.record(Ie.string().regex(/^[a-f0-9]{64}$/),Ie.strictObject({at:Ie.number(),text:Ie.string()})),ue=2*1048576,Bn=100;function jn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Fn(e,n){let a=n===void 0?jn():n,t=new Map,f=0,p=!1,m=!1,c,r;async function o(I){if(!a)return null;let g;try{let d=await Promise.race([Promise.resolve().then(()=>a.getItem(I)),new Promise(S=>{g=setTimeout(()=>S(null),Bn)})]);return typeof d=="string"&&d.length<=ue&&new TextEncoder().encode(d).byteLength<=ue?d:null}catch{return null}finally{clearTimeout(g)}}function s(){if(r)return r;let I=(async()=>{try{let g=await o(`${e}:artifacts`);if(g)return Gn.parse(JSON.parse(g))}catch{}return{}})();return r=I,I.finally(()=>{r===I&&(r=void 0)}),I}return{async readManifest(){return o(e)},writeManifest(I){!a||I.length>ue||new TextEncoder().encode(I).byteLength>ue||(c=I,!m&&(m=!0,Promise.resolve().then(async()=>{try{for(;c!==void 0;){let g=c;try{await a.setItem(e,g)}catch{}c===g&&(c=void 0)}}finally{m=!1}})))},async readArtifact(I){let g=(await s())[I],d=Date.now();return g&&d>=g.at&&d-g.at<=Y.retentionMs?g.text:void 0},writeArtifact(I,g){if(!a||g.length>ue)return;let d=t.get(I);if(d?.text===g||!d&&t.size>=128)return;let S=new TextEncoder().encode(g).byteLength;f-(d?.byteLength??0)+S>ue||(t.set(I,{text:g,byteLength:S}),f+=S-(d?.byteLength??0),!p&&(p=!0,Promise.resolve().then(async()=>{try{for(;t.size;){let _=new Map(t);try{let q={...await s()},i=Date.now();for(let[D,T]of _)q[D]={at:i,text:T.text};let y={},P=2,N=0;for(let[D,T]of Object.entries(q).sort(([,u],[,b])=>b.at-u.at)){if(T.at>i||i-T.at>Y.retentionMs)continue;let u=new TextEncoder().encode(JSON.stringify({[D]:T})).byteLength;P+u>ue||N>=128||(y[D]=T,P+=u,N++)}await a.setItem(`${e}:artifacts`,JSON.stringify(y))}catch{}finally{for(let[q,i]of _)t.get(q)===i&&(t.delete(q),f-=i.byteLength)}}}finally{p=!1}})))}}}var F=(e,n)=>new l(e,n),te=()=>performance.now(),Nn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function yr(e){let n=Ye.parse(e.scope),a=new ae(e.origin??ye);if(a.username||a.password||a.search||a.hash||a.pathname!=="/"||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))throw F("INVALID_URL","Configuration requires a trusted HTTPS origin");let t=new Set([a.origin,...(e.assetOrigins??[]).map(h=>{let w=new ae(h);if(w.protocol!=="https:"||w.username||w.password||w.search||w.hash||w.pathname!=="/")throw F("INVALID_URL","Invalid configuration asset origin");return w.origin})]),f=e.fetch??globalThis.fetch.bind(globalThis),p=`/api/v1/configuration/${n.environmentId}`,m=`indiana:configuration:1:${a.origin}:${j(n)}`,c=Fn(m,e.storage),r,o=0,s=0,I=!1,g=!1,d=0,S=0,_,q,i,y,P=0,N=new Set,D=new Set,T=new Map,u=new Map,b=0,L=!1;function v(){for(let h of N)try{h()}catch{}}function O(h){try{e.onError?.(h)}catch{}}let E=()=>!g&&!I&&!!r&&te()<o&&Date.now()<s;function A(){if(!E())throw F("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function U(h,w,R){if(!T.has(h)){for(;T.size&&(T.size>=128||b+R>Y.maxCacheBytes);){let C=T.entries().next().value;b-=C[1].byteLength,T.delete(C[0])}T.set(h,{text:w,byteLength:R}),b+=R}}function x(h,w,R){return fn(h,w,{signal:R,error:C=>F("INVALID_RESPONSE",C==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function H(h){let w=new ae(h,a);if(!t.has(w.origin)||w.username||w.password||w.hash||w.search)throw F("INVALID_URL","Configuration artifact origin is not trusted");return w.href}async function K(h,w,R=!1){let C=await f(H(h),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:w,headers:{}});if(C.status===429){let V=C.headers.get("retry-after")??"";P=/^\d+$/.test(V)?Number(V)*1e3:Math.max(0,Date.parse(V)-Date.now())||15e3}if(!C.ok&&C.status!==304)throw F(`CONFIGURATION_HTTP_${C.status}`,"Configuration synchronization failed");return C}function G(h,w,R){let C=Date.parse(h.headers.get("x-indiana-config-validated-at")??""),V=Date.parse(h.headers.get("x-indiana-config-valid-until")??""),k=Date.parse(h.headers.get("date")??""),M=h.headers.get("age"),Q=M!==null&&/^\d+(\.\d+)?$/.test(M)?Number(M)*1e3:NaN;if(![C,V,k,Q].every(Number.isFinite)||V<=C||V-C>Y.maxControlAgeMs||C>k+1e3)throw F("INVALID_RESPONSE","Configuration freshness evidence is invalid");let B=Math.min(V-C,R.maxControlAgeSeconds*1e3,Y.maxControlAgeMs)-Math.max(Q,k-C,0)-(te()-w);if(B<=0)throw F("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return te()+B}function ve(){if(clearTimeout(i),clearTimeout(y),g||!N.size||(E()&&(y=setTimeout(()=>{E()?ve():v()},Math.max(1,o-te())),Nn(y)),typeof document<"u"&&document.visibilityState==="hidden"))return;let h=S?Math.min(15e3,1e3*2**Math.min(S-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);i=setTimeout(()=>{le().catch(O)},Math.max(P,h*(.8+Math.random()*.2))),Nn(i)}async function le(){if(g)throw F("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(_)return _;let h=d,w=new AbortController;q=w;let R=(async()=>{if(!L){L=!0;try{let Ce=await c.readManifest();if(Ce&&!r){let Z=Oe.parse(JSON.parse(Ce));j(Z.scope)===j(n)&&(r=Z)}}catch{}}w.signal.throwIfAborted();let M=r,Q=te(),J=await K(p,w.signal);J.status===304&&(!M||!J.headers.has("x-indiana-config-validated-at")||!J.headers.has("x-indiana-config-valid-until")||!J.headers.has("age"))&&(J=await K(p,w.signal));let B=J.status===304?M:Oe.parse(JSON.parse(await x(J,Y.maxManifestBytes,w.signal))),{generation:me,...pe}=B,W=J.headers.get("etag");if(j(B.scope)!==j(n)||$e(pe)!==me||W!==`"${me}"`&&W!==`W/"${me}"`)throw F("INVALID_RESPONSE","Configuration scope or content identity changed");if(M&&(B.revision<M.revision||B.revision===M.revision&&B.generation!==M.generation))throw F("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Ce,Z]of Object.entries(M?.funnels??{})){let oe=B.funnels[Ce];if(oe&&(oe.controlRevision<Z.controlRevision||oe.evaluationRevision<Z.evaluationRevision||oe.controlRevision===Z.controlRevision&&oe.state!==Z.state||oe.evaluationRevision===Z.evaluationRevision&&oe.evaluationMode!==Z.evaluationMode))throw F("INVALID_RESPONSE","Funnel control revision changed identity")}let re=G(J,Q,B.policy);if(w.signal.throwIfAborted(),h!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return r=B,o=re,s=Date.now()+Math.max(0,re-te()),I=!1,S=0,P=0,c.writeManifest(j(B)),v(),structuredClone(B)})(),C=setTimeout(()=>w.abort(F("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Y.initializationMs),V=new Promise((M,Q)=>w.signal.addEventListener("abort",()=>Q(w.signal.reason),{once:!0})),k=Promise.race([R,V]).catch(M=>{throw S++,(M instanceof Jn.ZodError||M instanceof SyntaxError||M instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(M.code))&&(o=0,I=!0,v()),M}).finally(()=>{clearTimeout(C),_===k&&(_=void 0),ve()});return _=k,k}async function Re(h){let w=h.sha256,R=pe=>Pe(pe,h);H(h.url);let C=T.get(w);if(C){if(C.byteLength!==h.byteLength)throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.delete(w),T.set(w,C),C.text}let V=u.get(w);if(V){if(V.byteLength!==h.byteLength)throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return V.promise}let k=new AbortController;D.add(k);let M=d,Q=(async()=>{try{let re=await c.readArtifact(w);if(re&&R(re)){if(k.signal.throwIfAborted(),g||M!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return U(w,re,h.byteLength),re}}catch{}k.signal.throwIfAborted();let pe=await K(h.url,k.signal,!0),W=await x(pe,h.byteLength,k.signal);if(!R(W))throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(g||M!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return U(w,W,h.byteLength),c.writeArtifact(w,W),W})(),J=setTimeout(()=>k.abort(F("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Y.initializationMs),B=new Promise((pe,W)=>k.signal.addEventListener("abort",()=>W(k.signal.reason),{once:!0})),me=Promise.race([Q,B]).finally(()=>{clearTimeout(J),D.delete(k),u.delete(w)});return u.set(w,{promise:me,byteLength:h.byteLength}),me}async function he(){return E()||await le(),A(),r}async function ce(h){let w,R=new Promise((C,V)=>{w=setTimeout(()=>V(F("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Y.initializationMs)});try{return await Promise.race([h(),R])}finally{clearTimeout(w)}}function de(h,w){if(A(),r?.generation!==h.generation)throw F("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(w&&r.funnels[w]?.state!=="active")throw F("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Le(h){let w=h.gb.features;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=h.artifacts[w];if(R.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let C=He.parse(JSON.parse(await Re(R)));if(j(C.scope)!==j({projectId:n.projectId,environment:n.environment})||C.generation!==R.generation||C.remoteFeatures.some(V=>Object.hasOwn(C.features,V)))throw F("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return de(h),{...C,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,o-te())).toISOString()}}async function xe(h,w){let R=await he(),C=R.funnels[h];w&&(!C||C.evaluationMode==="local"&&!C.versions[w])&&(_&&await _,R=await le()),de(R,h);let V=R.funnels[h];if(V.evaluationMode!=="local")throw F("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let k=w??V.currentVersionId,M=V.versions[k];if(!M)throw F("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[M.artifact].formatVersion!==3)throw F("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Q,J]=await Promise.all([Re(R.artifacts[M.artifact]).then(B=>Ze(JSON.parse(B))),V.evaluationMode==="local"?Le(R):void 0]);if(J&&j(We(Q,J))!==j(M.dependencies))throw F("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return de(R,h),{document:Q,growth:J,versionId:k,control:structuredClone(V),manifest:structuredClone(R)}}async function Me(h,w){try{return await xe(h,w)}catch(R){if(!(R instanceof l)||!(R.code==="CONFIGURATION_CHANGED"||R.code==="CONFIGURATION_HTTP_404"&&E()))throw R;let C=r?.generation;if(_&&await _,await le(),R.code!=="CONFIGURATION_CHANGED"&&r?.generation===C)throw R;return xe(h,w)}}function fe(){if(E()||v(),typeof document<"u"&&document.visibilityState==="hidden"){ve();return}le().catch(O)}function Tn(h){if(g)throw F("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return N.add(h),N.size===1&&(typeof window<"u"&&(window.addEventListener("online",fe),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),ve()),()=>{N.delete(h),N.size||(clearTimeout(i),clearTimeout(y),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",fe),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:le,subscribe:Tn,assertFresh:A,assertFeatures(h){A();let w=r.gb.features;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(h!==void 0&&r.artifacts[w].generation!==h)throw F("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return E()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return E()?Math.max(0,o-te()):0},async features(){return ce(async()=>Le(await he()))},pageExperiments:()=>ce(async()=>{let h=await he(),w=h.gb.pageExperiments;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=h.artifacts[w];if(R.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let C=un.parse(JSON.parse(await Re(R)));if(C.environmentId!==n.environmentId||C.generation!==R.generation)throw F("INVALID_RESPONSE","Page experiment scope or generation changed");return de(h),C}),funnel:(h,w)=>ce(()=>Me(h,w)),funnelControl:h=>ce(async()=>{let w=await he();return de(w,h),structuredClone(w.funnels[h])}),paywall:(h,w)=>ce(async()=>{let R=await he(),C=R.paywalls?.[h];if(!C||!w&&C.state!=="published")throw F("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let V=w??C.currentVersionId,k=C.versions[V],M=k&&R.artifacts[k.artifact];if(!M||M.kind!=="paywall"||M.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Q=Qe.parse(JSON.parse(await Re(M)));return de(R),{document:Q,versionId:V,version:k.version,control:structuredClone(C),manifest:structuredClone(R)}}),async localFunnel(h,w){let R=await ce(()=>Me(h,w));if(!R.growth)throw F("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:C,remoteFeatures:V,...k}=R.growth;return sn({scope:{projectId:n.projectId,environment:n.environment},funnelId:h,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:k})},assertFunnel(h,w,R){A();let C=r.funnels[h];if(!C||C.state!=="active")throw F("FUNNEL_STOPPED","Funnel is paused or unavailable");if(C.evaluationMode!=="local")throw F("EVALUATION_MODE","This Funnel now executes at Longplay");if(w!==void 0&&C.controlRevision!==w)throw F("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!C.versions[R])throw F("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!g){g=!0,d++,o=0,q?.abort(F("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(i),clearTimeout(y),Ve(),v(),N.clear();for(let h of D)h.abort(F("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));T.clear(),b=0}}}}function On(e){let n=ge.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!se.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");return{async start(a){let t=X.safeParse({...a,operation:"start"});if(!t.success||t.data.operation!=="start"||(n?t.data.customer!==void 0:t.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let f=t.data,p=ee({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||p.identify(e.apiKey);let m=Ee(e,await p.request("funnels",f));if(!m.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");if(m.run.source.id!==f.funnelId||m.run.locale!==(f.locale??"en")||!we(m.run.parameters,f.parameters??{})||(f.customer?!m.customerId||f.customer.type==="id"&&m.customerId!==f.customer.value:m.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...m,runToken:m.runToken}}finally{p.dispose()}}}}async function Nr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let a={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&j(a)!==j(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnelControl(e.funnelId)).evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let f=se.test(e.credential);if(f?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let p=On({...e,scope:a,apiKey:e.credential}),m=(c,r)=>{let o=Pn({...e,scope:a,runToken:c,initialResponse:r,...f?{serverKey:e.credential}:{}});return f||o.identify(e.credential),o};return{async start(c){let r=await p.start({...c,funnelId:e.funnelId,...f?{customer:{type:"id",value:e.customerId}}:{}}),o=m(r.runToken,r),s=await o.get();return{...r,...s,controller:o}},async restore(c){let r=m(c),o=await r.get();if(o.run.source.id!==e.funnelId)throw r.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...o,runToken:c,controller:r}}}}export{Ne as a,kn as b,En as c,zn as d,Ee as e,_e as f,ut as g,Vn as h,In as i,ht as j,we as k,Pt as l,Et as m,Pn as n,or as o,yr as p,On as q,Nr as r};
1
+ import{b as mn,c as pn,d as gn,e as yn,f as wn}from"./chunk-YAVWELIV.js";import{a as ae,b as ee}from"./chunk-BP6G3YGP.js";import{a as l}from"./chunk-QVGTHPWT.js";import{a as dn,b as fn,c as Pe}from"./chunk-Z5CW2N7E.js";import{$ as Se,Da as ie,Ea as nn,Ha as tn,Ia as rn,Na as Te,Oa as on,Z as je,aa as Je,ab as an,ba as He,bb as sn,ca as ze,eb as un,fb as ln,ib as cn,lb as ye,ma as X,na as Qe,o as ke,oa as Y,pa as Ye,q as ge,qa as Oe,ra as j,ta as $e,ua as We,va as Ze,wa as Xe,xa as en}from"./chunk-JXNNWCEB.js";import{a as hn}from"./chunk-DSPLGTQI.js";import{C as Ue,J as Ge,M as Be,Na as Ke,P as be,a as qe}from"./chunk-HDVLCRC6.js";function zn(e){let n=null,a=null,t=0,f=0,p=new Set,m=null,c=null,r=new Set,o=()=>{for(let i of r)try{i()}catch{}},s={attributes:be.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(i,y)=>{!p.has(i)&&n&&(!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(i,structuredClone(y),structuredClone(s.attributes),n.generation)}:void 0,onExperimentViewed:e.onExperimentViewed?(i,y)=>n&&(!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(i),structuredClone(y),structuredClone(s.attributes),n.generation):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?i=>e.saveStickyBucketAssignmentDoc(structuredClone(i)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},I=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function g(i,y=new Set){return p.has(i)?!m||!m.features[i]||["unknownFeature","cyclicPrerequisite"].includes(m.features[i].source):y.has(i)?!1:(y.add(i),(n?.features[i]?.rules??[]).some(P=>[...P.parentConditions??[],...(P.tracks??[]).flatMap(N=>N.experiment.parentConditions??[])].some(N=>g(N.id,y))))}let d=i=>{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 m?.expiresAt&&Date.parse(m.expiresAt)<=Date.now()&&(m=null,s.features=n.features),p.has(i)?!m||m.expiresAt&&Date.parse(m.expiresAt)<=Date.now()?I():structuredClone(m.features[i]??I()):e.evaluateRemote&&(s.attributes?.merchandise||s.attributes?.merchandiseId)&&!m||g(i)?I():structuredClone(Be(i,s))};async function S(){if(!n||!p.size&&!s.attributes?.merchandise&&!s.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(p.size)throw new Error("Remote Feature evaluation requires a server loader");return}let i=f;if(c?.revision===i)return c.loading;let y=t,P=n,N=[...p],D=(async()=>{let T=ze.parse(await e.evaluateRemote({attributes:structuredClone(s.attributes),features:N}));if(!(y!==t||i!==f||P!==n)){if(e.assertUsable?.(P.generation),T.generation!==P.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(N.some(u=>!Object.hasOwn(T.features,u))||Object.keys(T.features).some(u=>!p.has(u)))throw new Error("Invalid remote Feature results");if(s.attributes?.merchandise||s.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");s.attributes=be.parse({...s.attributes,...T.merchandiseContext})}m=structuredClone(T),s.features={...P.features,...Object.fromEntries(Object.entries(m.features).map(([u,b])=>[u,{defaultValue:b.value}]))},o()}})();c={revision:i,loading:D};try{await D}finally{c?.loading===D&&(c=null)}}function _(){S().catch(i=>{try{e.onError?.(i)}catch{}})}async function q(){if(a)return a;let i=t,y=(async()=>{let P=await e.load(),N="remoteFeatures"in P?Je.parse(P):null,D=N??Se.parse(P);if(D.scope.projectId!==e.scope.projectId||D.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(i!==t)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===D.generation){let{evaluatedAt:u,expiresAt:b,...L}=n,{evaluatedAt:v,expiresAt:O,...E}=D;if(j(L)!==j(E))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=D.evaluatedAt,n.expiresAt=D.expiresAt,o(),(!m||m.expiresAt&&Date.parse(m.expiresAt)<=Date.now())&&_(),structuredClone(n)}let T=new Set(N?.remoteFeatures??[]);if([...T].some(u=>Object.hasOwn(D.features,u)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in D&&!n.analyticsConfig.experimentViewsEnabled&&N?.analyticsConfig.experimentViewsEnabled&&s.trackedExperiments?.clear(),n=structuredClone(D),p=T,m=null,c=null,f++,s.features=n.features,s.savedGroups=Ge(n.savedGroups),s.trackedFeatureUsage={},o(),_(),structuredClone(n)})();a=y;try{return await y}finally{a===y&&(a=null)}}return{init:q,refresh:q,refreshRemote:S,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(i){return r.add(i),()=>{r.delete(i)}},setAttributes(i){let y=be.parse(i);(s.attributes?.merchandise||s.attributes?.merchandiseId||i.merchandise||i.merchandiseId)&&s.trackedExperiments?.clear(),s.attributes=y,f++,m=null,c=null,s.features=n?.features??{},s.trackedFeatureUsage={},o(),_()},evalFeature:d,isOn(i){return d(i).on},isOff(i){return d(i).off},getFeatureValue(i,y){let P=d(i).value;return structuredClone(P===null?y:P)},reset(){t++,f++,a=null,c=null,n=null,m=null,p.clear(),s.features={},s.savedGroups={},s.stickyBucketAssignmentDocs={},s.attributes={},s.trackedFeatureUsage={},s.trackedExperiments?.clear(),o()}}}function In(e){let n,a,t=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),f=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,a=e.locks??globalThis.navigator?.locks,!n||!a||!globalThis.crypto?.subtle)throw t();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ye).href,e.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return"indiana.funnel.commands.v1."+Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")});f.catch(()=>{});async function p(c){try{let r=await f;return await a.request(r,{mode:"exclusive"},()=>c(r))}catch(r){throw r instanceof l?r:t()}}function m(c){let r=n.getItem(c);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw t();let o=JSON.parse(r);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw t();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(m),write:(c,r)=>p(o=>{if(m(o).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw t();return n.setItem(o,JSON.stringify({revision:c+1,entry:r})),c+1})}}function Ee(e,n){let a=tn.safeParse(n);if(!a.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let t=a.data;if(e.scope&&(t.scope.projectId!==e.scope.projectId||t.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return t}async function Ae(e,n){let a=Xe.parse(n),{artifact:t,environmentId:f}=a.content,p=new ae(e.baseUrl??ye).origin,m=new ae(t.url,p);if(m.origin!==p||m.username||m.password||m.search||m.hash||m.pathname!==`/api/v1/configuration/${f}/artifacts/${t.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let c=new AbortController,r,o=new Promise((I,g)=>{r=setTimeout(()=>{let d=new l("TIMEOUT","Public Paywall read timed out");c.abort(d),g(d)},Y.initializationMs)}),s=(async()=>{let I=await(e.fetch??globalThis.fetch)(m,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:c.signal});if(c.signal.aborted&&(I.body?.cancel().catch(()=>{}),c.signal.throwIfAborted()),!I.ok||!I.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(I.headers.get("content-length"))>t.byteLength)throw I.body?.cancel().catch(()=>{}),new l("INVALID_RESPONSE","Public Paywall is unavailable");let g=await dn(I,t.byteLength,{signal:c.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Pe(g,t))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return en(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(g)))})();try{return await Promise.race([s,o])}finally{clearTimeout(r)}}var _e=(e,n)=>new l(e,n);function ut(e){return ln(e,_e)}var _n=3,Dn=2e3;function Ln(e){return e instanceof TypeError||e instanceof l&&/^(?: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(a){if(n===_n||!Ln(a))throw a;await new Promise(t=>setTimeout(t,n*Dn))}}async function De(e,n,{predict:a=!0}={}){let t=n.instruction;if(t?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==t.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let f=null,p;if(a)try{let m=await e.funnel(n.source.id,n.source.versionId);p=m.manifest.generation,f=Mn(e,n,m)}catch{f=null}return p??=e.snapshot?.generation??(await xn(e)).generation,{advance:{policyRevision:t.policyRevision,generation:p},prediction:f}}function Mn(e,n,a){let t=n.instruction;if(t?.type!=="evaluate_segment"||!a.growth||a.control.evaluationMode!=="local"||a.control.evaluationRevision!==t.policyRevision)return null;let{analyticsConfig:f,remoteFeatures:p,...m}=a.growth,c=an({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:t.policyRevision,document:a.document,payload:Se.parse(m)}),r=Vn(c,a.document,{...n,...t}),o=r.steps.at(-1),s=r.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:n.visit+r.steps.length-1}:null);return s?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:s.nodeId,visit:s.visit,terminal:!r.boundary}:null}function Vn(e,n,a){return cn(e,n,a,_e)}import{z as $}from"zod";var vn=X.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 l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Rn=$.strictObject({schemaVersion:$.literal(1),scope:qe,runId:$.uuid(),funnelId:$.uuid(),versionId:$.uuid(),processBindingIds:$.record($.uuid(),$.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.refine(e=>e.operation==="close").optional(),purchase:$.strictObject({receiptId:$.uuid(),operationId:$.uuid(),generation:$.number().int().nonnegative()}).optional(),closed:$.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"),z=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Fe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function Cn(e){let n=0,a=null,t=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),f=Promise.resolve();async function p(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:Rn.parse(o.entry)}}function m(o){let s=f.then(o);return f=s.catch(()=>{}),s}async function c(o){for(let s=0;s<4;s++){let I=await p();if(I.entry&&a!==null&&t(I.entry)!==a)throw z();let g=o(I.entry,I.revision);if(Fe(I.entry,g)){n=I.revision;return}let d=await e.write(I.revision,g);if(d!==null){if(!Number.isSafeInteger(d)||d<=I.revision)throw z();n=d;return}}throw z()}function r(o,s){if(!o||!s)return o;if(o.processBindingIds&&Object.hasOwn(o.processBindingIds,s)){let I={...o.processBindingIds};delete I[s],o={...o,processBindingIds:I}}return o.command?.requestId===s?o.closeCommand?{...o,command:o.closeCommand,closeCommand:void 0}:o.purchase?{...o,command:void 0}:null:o.closeCommand?.requestId===s?{...o,closeCommand:void 0}:o}return{bind(o){let s=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(a!==null&&a!==s)throw z();a=s},async load(){let o=await p();return n=o.revision,a=o.entry?t(o.entry):null,o.entry},retain(o){let s=Rn.parse(o),I=s.command;return!I||a!==null&&t(s)!==a?Promise.reject(z()):(a??=t(s),m(()=>c((g,d)=>{if(g&&!Fe(t(g),t(s)))throw z();if(g&&s.processBindingIds){for(let[S,_]of Object.entries(s.processBindingIds))if(g.processBindingIds&&Object.hasOwn(g.processBindingIds,S)&&g.processBindingIds[S]!==_)throw z();g={...g,processBindingIds:{...g.processBindingIds,...s.processBindingIds}}}if(!g){if(d!==n&&I.operation!=="close")throw z();return s}if(!g.command)return{...g,command:I,...I.operation==="close"?{closed:!0}:{}};if(I.operation==="close"&&g.command.operation!=="close"){if(g.command.requestId===I.requestId||g.closeCommand&&!Fe(g.closeCommand,I))throw z();return{...g,closeCommand:I,closed:!0}}if(!Fe(g.command,I))throw z();return g})))},observePurchase(o,s,I,g){return m(()=>c((d,S)=>{if(!d&&S!==n||d&&t(d)!==t({...o,schemaVersion:1}))throw z();if(d?.purchase&&d.purchase.generation>s.generation)return r(d,g);if(d?.purchase&&d.purchase.generation===s.generation&&d.purchase.operationId!==s.operationId)throw z();return I?!d?.purchase||d.purchase.operationId!==s.operationId?r(d,g):r(d.command?{...d,purchase:void 0}:null,g):r({schemaVersion:1,...o,...d,purchase:s},g)}))},settle(o){return m(()=>c(s=>r(s,o)))}}}function ht(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function we(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((f,p)=>we(f,n[p]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let a=Object.entries(e),t=Object.entries(n);return a.length===t.length&&a.every(([f,p])=>Object.hasOwn(n,f)&&we(p,Reflect.get(n,f)))}function bn(e,n){let a=n&&{...n},t=null,f=0,p=-1,m=0,c=new AbortController;function r(){m++,c.abort(new l("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let o=!1,s,I=0,g=new Set;return{get scope(){return a},bindScope(d){if(a&&(a.projectId!==d.projectId||a.environment!==d.environment))throw new l("SCOPE_MISMATCH","Run scope changed");a??={...d}},get view(){return t},get currentView(){return p===m?t:null},get viewAgeMs(){return t&&p===m?performance.now()-f:void 0},get generation(){return m},get signal(){return c.signal},get disposed(){return o},get customerToken(){return s},get readSequence(){return I},nextRead(){return++I},assertCurrent(d,S="Run identity changed during the request"){if(d!==m||o)throw new l("IDENTITY_CHANGED",S)},assertRun(d){if(t&&(d.id!==t.id||d.source.type!==t.source.type||d.source.id!==t.source.id||d.source.versionId!==t.source.versionId||d.locale!==t.locale||!we(d.parameters,t.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&d.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(d,S,_,q,i){if(!(d.operation==="review"&&t&&t!==_&&S.run.revision<=t.revision)&&!(t&&S.run.revision===t.revision&&q!==void 0&&q<I)&&(d.operation==="review"&&!S.run.stopped&&["running","waiting"].includes(S.run.status)&&t&&p===m&&S.run.nodeId===t.nodeId&&S.run.visit===t.visit&&S.run.revision===t.revision&&(S.run.screen=t.screen,(t.paywall?.quote?.operationId===S.review?.activeOperationId||!t.paywall?.quote&&S.review?.activeOperationId===null)&&(S.run.paywall=t.paywall)),!(t?.paywall&&S.run.paywall&&t.paywall.receiptId===S.run.paywall.receiptId&&(S.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||S.run.revision>=t.revision)t=S.run,f=performance.now(),p=m;else if(!i)return;if(t&&p===m)for(let y of g)try{y(structuredClone(t))}catch{}}},identify(d){if(o)throw new l("IDENTITY_CHANGED","Controller was reset");if(!ge.test(d))throw new l("INVALID_TOKEN","Customer credential required");r(),s=d},subscribe(d){return g.add(d),()=>g.delete(d)},reset(){o||(o=!0,r(),s=void 0,t=null,g.clear())}}}var se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Pt(e,n,a="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!se.test(e))throw new l("INVALID_TOKEN",a)}function Et(e){let n=ee(e);return n.identify(e.apiKey),n}function ne(e){let{customerToken:n,...a}=e;return a}var qn=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Sn({journal:e,state:n,call:a,processIdentity:t}){let f=null,p=null,m=!1,c={command:null,close:null},r=new Set,o,s=null,I=e?e.load().then(i=>{if(n.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(s=i,!i)return;if(t){if([i.command,i.closeCommand].some(P=>P&&!Object.hasOwn(i.processBindingIds??{},P.requestId)))throw new l("COMMAND_STORAGE_INVALID","The original process identity is missing");t.restore(i.processBindingIds??{})}if(n.scope&&(i.scope.projectId!==n.scope.projectId||i.scope.environment!==n.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=i.purchase,m=i.closed===!0,!i.command)return;let y=i.command;f=y.operation==="close"?null:y,p=y.operation==="close"?y:i.closeCommand?.operation==="close"?i.closeCommand:null,p&&(m=!0);for(let P of[f,p])P&&r.add(P.requestId)}):Promise.resolve();I.catch(()=>{});async function g(i){e&&await I;let y=n.generation;if(e){if(!n.view||!n.scope)throw new l("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:ne(i),...t?{processBindingIds:{[i.requestId]:t.binding(i.requestId)}}:{}})}if(y!==n.generation||f!==i&&p!==i)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let P=r.has(i.requestId);r.add(i.requestId);try{return await a(i)}catch(N){throw y===n.generation&&(f===i||p===i)&&!P&&!qn(N)&&(e&&await e.settle(i.requestId),y===n.generation&&q(i)),N}}function d(i){let y=X.parse(i);if(y.operation==="start"||y.operation==="get"||y.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(m&&y.operation!=="close"){if(f?.requestId===y.requestId)return _(y.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(y.operation==="close"){if(f?.requestId===y.requestId)throw new l("INVALID_REQUEST","Close requires its own request identity");if(m=!0,p&&JSON.stringify(ne(p))!==JSON.stringify(ne(y)))throw new l("COMMAND_PENDING","Retry the original Close");return p??=y,c.close?c.close:S(p,"close")}if(f){if(JSON.stringify(ne(f))!==JSON.stringify(ne(y)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else f=y;return S(f,"command")}function S(i,y){let P=g(i);c[y]=P;let N=()=>{c[y]===P&&(c[y]=null)};return P.then(N,N),P}function _(i){return a({operation:"get",settlementRequestId:i})}function q(i){return!i||f!==i&&p!==i?!1:(f===i&&(f=null),p===i&&(p=null),r.delete(i.requestId),!f&&!p&&(s=null),!0)}return{ready:I,get pending(){return f},get closing(){return p},get closeRequested(){return m},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return o},assertBinding(i){if(s&&(i.run.id!==s.runId||i.run.source.id!==s.funnelId||i.run.source.versionId!==s.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(i,y,P,N){let D=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0,T=D&&y.settlement?.state==="settled"&&y.run.pendingRequest?.requestId!==D&&(i.operation==="get"||!m||i.operation==="close"||!["running","waiting"].includes(y.run.status))?D:void 0,u=f?.requestId===T?f:p?.requestId===T?p:void 0;e?.bind({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId});let b=y.run.paywall,L=b??y.purchase,v=L?.operation,O=y.settlement&&(!b||b.purchaseRequestId===y.settlement.requestId)&&(!o||o.operationId===y.settlement.operationId)?y.settlement:void 0,E=v?.operationId??L?.quote?.operationId??O?.operationId,A=L?.receiptId??O?.receiptId,U=b?.selectionGeneration??o?.generation??0;if(e&&E&&A&&i.operation!=="review"&&(!n.view||y.run.revision>=n.view.revision)&&(N===void 0||N>=n.readSequence)&&(!o||U>=o.generation)){let x={receiptId:A,operationId:E,generation:U},H=v?.status==="complete"||L?.canReselect===!0;await e.observePurchase({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId},x,H,T),n.assertCurrent(P),(!o||x.generation>=o.generation)&&(N===void 0||N>=n.readSequence)&&(H?o?.operationId===x.operationId&&(o=void 0):o=x)}else e&&T&&await e.settle(T);return n.assertCurrent(P),T?q(u):!1},stop(){m=!0},submit:d,settle:_,reset(){m=!0,f=null,p=null,o=void 0,s=null,c.close=null,r.clear(),c.command=null}}}function Pn(e){e={...e};let n=e.initialResponse;if(delete e.initialResponse,typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!se.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let a=ee({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=bn(e.funnelId,e.scope??e.configuration?.scope),f=e.session?.subscribeIdentity(d),p=null,m=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?In(e):void 0),c=m&&Cn(m),r=Sn({journal:c,state:t,call:S,processIdentity:e.process}),o=0,s=new Map;function I(){o++,s.clear(),n=void 0}async function g(u){if(e.process)return e.process.request(u);let b=t.generation;t.assertCurrent(b);let L=performance.now()+(e.timeoutMs??35e3),v=t.customerToken??("customerToken"in u?u.customerToken:void 0);if(e.session){let A=t.signal,U,x=()=>{},H=new Promise((K,G)=>{x=()=>G(A.reason),A.addEventListener("abort",x,{once:!0}),U=setTimeout(()=>G(new l("TIMEOUT","Longplay request timed out")),Math.max(1,L-performance.now()))});try{v=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(b),e.session.access())),H])}finally{clearTimeout(U),A.removeEventListener("abort",x)}}t.assertCurrent(b);let O={...u,...v?{customerToken:v}:{}},E=u.operation==="page_experiments"?Te.parse(O):X.parse(O);return a.requestWithCredential("funnels",E,e.runToken,{headers:e.serverKey&&!v?{[rn]:e.serverKey}:void 0,timeoutMs:Math.max(1,L-performance.now())})}function d(){I(),f?.(),t.reset(),r.reset(),p=null,a.dispose()}async function S(u,b){let L=n;n=void 0;let v=t.generation,O=()=>t.assertCurrent(v);c&&await r.ready,O();let E=t.view,A=Ee(e,L!==void 0&&u.operation==="get"&&!u.data&&!u.purchase&&!u.settlementRequestId?L:await g(u));if(u.operation==="review"&&!A.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(O(),A.runToken&&A.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let U=u.operation==="get"?u.settlementRequestId:"requestId"in u&&u.operation!=="start"?u.requestId:void 0;if(U&&A.settlement?.requestId!==U)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(A),t.assertRun(A.run),t.bindScope(A.scope);let x=await r.observe(u,A,v,b);return!A.run.stopped&&["running","waiting"].includes(A.run.status)&&u.operation==="get"&&u.settlementRequestId||(O(),["running","waiting"].includes(A.run.status)||r.stop(),t.publish(u,A,E,b,x)),A}function _(u){let b=t.generation;I();let L=u(),v=()=>{t.generation===b&&I()};return L.then(v,v),L}let q=u=>_(()=>r.submit(u)),i=null,y=new WeakMap;function P(u){let b=y.get(u);if(b)return b;let L=D(u);return y.set(u,L),L}let N=!1;async function D(u){let b=await u;if(b.run.instruction?.type!=="evaluate_segment")return b;if(i)return i;N=!0;let L=t.generation,v=(async()=>{for(let O=0;O<32&&b.run.instruction?.type==="evaluate_segment";O++){if(r.pending||r.closeRequested)return b;let E=b.run;if(b.run.instruction?.type==="evaluate_segment"){let{advance:U}=await De(e.configuration,E,{predict:!1});if(L!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return b;if(t.view&&(t.view.revision!==E.revision||t.view.visit!==E.visit||t.view.nodeId!==E.nodeId))return S({operation:"get"});let x=!0;De(e.configuration,E).then(({prediction:H})=>{x&&L===t.generation&&!r.closeRequested&&t.view?.id===E.id&&!t.view.stopped&&t.view.nodeId===E.nodeId&&t.view.visit===E.visit&&t.view.revision===E.revision&&(p=H)}).catch(()=>{});try{b=await q({operation:"commit_segment",requestId:nn(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...U})}finally{x=!1,p=null}}}return b})();i=v;try{return await v}finally{i===v&&(i=null)}}let T={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){let u=t.currentView;return u?structuredClone(u):null},get viewAgeMs(){return t.viewAgeMs},get pendingCommand(){let u=r.closing??r.pending;return u?structuredClone(ne(u)):null},get pendingCommands(){return[r.pending,r.closing].filter(u=>u!==null).map(u=>structuredClone(ne(u)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get hasDurableJournal(){return c!==void 0},get prediction(){let u=t.view;return p&&u&&!u.stopped&&["running","waiting"].includes(u.status)&&u.id===p.runId&&u.nodeId===p.from.nodeId&&u.visit===p.from.visit&&u.revision===p.from.revision&&!r.closeRequested?structuredClone(p):null},settle:(...u)=>_(()=>r.settle(...u)),get webViewUrl(){return"bundled"},resolvePaywall(u){return Ae(e,u)},async pageExperiments(u,b=[]){let L=t.generation;t.assertCurrent(L);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let O=on.parse(await g(Te.parse({operation:"page_experiments",release:u,usedReceiptIds:b})));if(t.assertCurrent(L),O.runId!==v||O.scope.projectId!==t.scope?.projectId||O.scope.environment!==t.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return O},review(u){return S({operation:"review",...u?{receiptId:u}:{}},t.nextRead())},async get(u,b){let L=t.generation;u=u&&structuredClone(u),b=b&&{...b},c&&await r.ready,t.assertCurrent(L),b??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let v=JSON.stringify([t.generation,o,u??null,b??null]),O=s.get(v);if(O)return O.then(x=>structuredClone(x));let E=t.nextRead(),A=P(S({operation:"get",...u?{data:u}:{},...b?{purchase:b}:{}},E));s.set(v,A);let U=()=>{s.get(v)===A&&s.delete(v)};return A.then(U,U),A.then(x=>structuredClone(x))},resume(u=t.view?.pendingRequest?.requestId){return u?r.closeRequested?T.settle(u):r.pending?.requestId===u?P(q(r.pending)):P(q({operation:"resume",requestId:u})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(u){return P(q(u))},retry(){return r.closeFlight?r.closeFlight:r.closing?q(r.closing):r.closeRequested&&r.pending?T.settle(r.pending.requestId):r.inFlight?P(r.inFlight):r.pending?P(q(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(u){let b=t.customerToken?void 0:n;I(),t.identify(u),n=b,p=null,a.reset()},get identitySignal(){return t.signal},subscribe:t.subscribe,reset:d};return T}function kn(e,n,a,t){if(!Ue(e,n)||a!==void 0&&n.observation&&n.observation.subject.customerId!==a||t!==void 0&&n.observation!==void 0&&(n.observation.subject.scope.projectId!==t.projectId||n.observation.subject.scope.environment!==t.environment))throw new l("INVALID_RESPONSE","The access requirement or Customer changed");return n}function En(e,n,a){if(e.requirement){if(!n)throw new l("INVALID_RESPONSE","The requested access check is missing");kn(e.requirement,n,e.customerId,a)}}import{ZodError as Un}from"zod";function An(e,n,a,t){try{return e.parse(n)}catch(f){throw t&&f instanceof Un?new l(a,t):f}}async function Ne(e,n,a,t={},f){let p=typeof t=="function"?{}:t,m=An(n.request,a,"INVALID_REQUEST",p.request);try{let c=await e(n.path,m,n.method,f),r=typeof t=="function"?t:t.parseResponse;return r?r(n.response,c):An(n.response,c,"INVALID_RESPONSE",p.response)}catch(c){throw c instanceof l&&m!==null&&typeof m=="object"&&"requestId"in m&&typeof m.requestId=="string"&&(c.commandRequestId??=m.requestId),c}}async function or(e,n){if(!ge.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let a=ie.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}:{}}),t=ee(e);e.session||t.identify(n.customerToken);let f=null,p=!1,m=new AbortController,c=null,r=null,o=null,s=null,I=null,g=null,d=null,S=0,_=null,q="",i=0,y=new Map,P=new Set;function N(){if(p)throw new l("IDENTITY_CHANGED","Paywall is closed")}function D(){let v=JSON.stringify([S,d!==null]);if(!_||v!==q){q=v;let O=T(++i);_=O;let E=()=>{_===O&&(_=null)};O.then(E,E)}return _.then(O=>structuredClone(O))}async function T(v){N();let O=ie.resolvePaywall,E=await Ne(t.request,O,{...a,selector:f?{type:"version",versionId:f.id}:a.selector});En(a,E.paywall.check,E.scope);let A=await Ae(e,E.paywall);if(N(),n.paywallVersionId?A.id!==n.paywallVersionId:A.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(f&&(!mn(A,f)||A.paywallId!==f.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(v!==i)return structuredClone(f??A);f=A;for(let U of P)hn(U,structuredClone(f));return structuredClone(f)}async function u(v){if(N(),s&&v!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let O=c;if(v!=="read"){if(d){if(g===v)return d;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(g&&g!==v)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");g=v,S++,i++}let E=g,A=S,U=v==="read"&&d===null,x=JSON.stringify([O.operationId,A,d!==null]);if(v==="read"&&y.has(x))return y.get(x).then(G=>structuredClone(G));let H=v==="read"?ie.readSubscriptionOperation:ie.attach,K=(async()=>{let G=await Ne(t.request,H,{operationId:O.operationId,...v==="read"?{}:{intent:v},...v==="confirm"&&O.merchantTerms?{merchantConfirmation:ke(O.merchantTerms)}:{}});return pn(G.operation,{operationId:O.operationId,currency:a.commerce.currency},"The purchase operation changed"),N(),c?.operationId!==O.operationId?structuredClone(G.operation):(r=yn(r,G.operation),(v!=="read"||U&&d===null)&&S===A&&g===E&&(g=null),structuredClone(r))})();if(v!=="read"){d=K;let G=()=>{d===K&&(d=null)};K.then(G,G)}else{y.set(x,K);let G=()=>{y.get(x)===K&&y.delete(x)};K.then(G,G)}return K.then(G=>structuredClone(G))}let b={signal:m.signal,get view(){return f?structuredClone(f):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},get recovery(){return wn({quote:c,operation:r,requestId:I,pending:s!==null||g!==null,destroyed:p})},get pendingCancellation(){return!p&&g==="cancel"},refresh:D,subscribe(v){return p?()=>{}:(P.add(v),()=>P.delete(v))},async preview(v){if(N(),!f)throw new l("INVALID_REQUEST","Load the Paywall first");let O=f.document.buttons[v.actionId];if(O?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let E=je(O.product,v.selection,f.capabilities);if(!E)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let A=Ke(f.document.screen,E,v.selection,f.capabilities),U=ie.previewAttach.request.parse({funnelId:a.funnelId,funnelVersionId:a.funnelVersionId,requestId:v.requestId,plans:[{productVersionId:E,...Object.keys(A).length?{featureQuantities:A}:{}}],provider:a.commerce.provider,currency:a.commerce.currency,...v.offerId?{offerId:v.offerId}:{},...v.nativeOffer?{nativeOffer:v.nativeOffer}:{}}),x=JSON.stringify(U);if(o&&o!==x&&(s||g||!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===x){if(s)return s;if(c)return structuredClone(c)}o!==x&&(c=null,r=null),o=x,I=U.requestId;let H=(async()=>{let K=ie.previewAttach,G=await Ne(t.request,K,U);return N(),gn(G.quote,{productVersionId:E,featureQuantities:A,currency:a.commerce.currency,provider:a.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=G.quote,r=null,structuredClone(c)})();s=H;try{return await H}finally{s===H&&(s=null)}},confirm:()=>u("confirm"),cancel:()=>u("cancel"),read:()=>u("read"),destroy(){p||(p=!0,m.abort(),P.clear(),y.clear(),L?.(),t.dispose(),f=null,c=null,r=null,o=null,I=null)}},L=e.session?.subscribeIdentity(b.destroy);try{return await D(),b}catch(v){throw b.destroy(),v}}import{z as Jn}from"zod";import{z as Ie}from"zod";var Gn=Ie.record(Ie.string().regex(/^[a-f0-9]{64}$/),Ie.strictObject({at:Ie.number(),text:Ie.string()})),ue=2*1048576,Bn=100;function jn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Fn(e,n){let a=n===void 0?jn():n,t=new Map,f=0,p=!1,m=!1,c,r;async function o(I){if(!a)return null;let g;try{let d=await Promise.race([Promise.resolve().then(()=>a.getItem(I)),new Promise(S=>{g=setTimeout(()=>S(null),Bn)})]);return typeof d=="string"&&d.length<=ue&&new TextEncoder().encode(d).byteLength<=ue?d:null}catch{return null}finally{clearTimeout(g)}}function s(){if(r)return r;let I=(async()=>{try{let g=await o(`${e}:artifacts`);if(g)return Gn.parse(JSON.parse(g))}catch{}return{}})();return r=I,I.finally(()=>{r===I&&(r=void 0)}),I}return{async readManifest(){return o(e)},writeManifest(I){!a||I.length>ue||new TextEncoder().encode(I).byteLength>ue||(c=I,!m&&(m=!0,Promise.resolve().then(async()=>{try{for(;c!==void 0;){let g=c;try{await a.setItem(e,g)}catch{}c===g&&(c=void 0)}}finally{m=!1}})))},async readArtifact(I){let g=(await s())[I],d=Date.now();return g&&d>=g.at&&d-g.at<=Y.retentionMs?g.text:void 0},writeArtifact(I,g){if(!a||g.length>ue)return;let d=t.get(I);if(d?.text===g||!d&&t.size>=128)return;let S=new TextEncoder().encode(g).byteLength;f-(d?.byteLength??0)+S>ue||(t.set(I,{text:g,byteLength:S}),f+=S-(d?.byteLength??0),!p&&(p=!0,Promise.resolve().then(async()=>{try{for(;t.size;){let _=new Map(t);try{let q={...await s()},i=Date.now();for(let[D,T]of _)q[D]={at:i,text:T.text};let y={},P=2,N=0;for(let[D,T]of Object.entries(q).sort(([,u],[,b])=>b.at-u.at)){if(T.at>i||i-T.at>Y.retentionMs)continue;let u=new TextEncoder().encode(JSON.stringify({[D]:T})).byteLength;P+u>ue||N>=128||(y[D]=T,P+=u,N++)}await a.setItem(`${e}:artifacts`,JSON.stringify(y))}catch{}finally{for(let[q,i]of _)t.get(q)===i&&(t.delete(q),f-=i.byteLength)}}}finally{p=!1}})))}}}var F=(e,n)=>new l(e,n),te=()=>performance.now(),Nn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function yr(e){let n=Ye.parse(e.scope),a=new ae(e.origin??ye);if(a.username||a.password||a.search||a.hash||a.pathname!=="/"||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))throw F("INVALID_URL","Configuration requires a trusted HTTPS origin");let t=new Set([a.origin,...(e.assetOrigins??[]).map(h=>{let w=new ae(h);if(w.protocol!=="https:"||w.username||w.password||w.search||w.hash||w.pathname!=="/")throw F("INVALID_URL","Invalid configuration asset origin");return w.origin})]),f=e.fetch??globalThis.fetch.bind(globalThis),p=`/api/v1/configuration/${n.environmentId}`,m=`indiana:configuration:1:${a.origin}:${j(n)}`,c=Fn(m,e.storage),r,o=0,s=0,I=!1,g=!1,d=0,S=0,_,q,i,y,P=0,N=new Set,D=new Set,T=new Map,u=new Map,b=0,L=!1;function v(){for(let h of N)try{h()}catch{}}function O(h){try{e.onError?.(h)}catch{}}let E=()=>!g&&!I&&!!r&&te()<o&&Date.now()<s;function A(){if(!E())throw F("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function U(h,w,R){if(!T.has(h)){for(;T.size&&(T.size>=128||b+R>Y.maxCacheBytes);){let C=T.entries().next().value;b-=C[1].byteLength,T.delete(C[0])}T.set(h,{text:w,byteLength:R}),b+=R}}function x(h,w,R){return fn(h,w,{signal:R,error:C=>F("INVALID_RESPONSE",C==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function H(h){let w=new ae(h,a);if(!t.has(w.origin)||w.username||w.password||w.hash||w.search)throw F("INVALID_URL","Configuration artifact origin is not trusted");return w.href}async function K(h,w,R=!1){let C=await f(H(h),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:w,headers:{}});if(C.status===429){let V=C.headers.get("retry-after")??"";P=/^\d+$/.test(V)?Number(V)*1e3:Math.max(0,Date.parse(V)-Date.now())||15e3}if(!C.ok&&C.status!==304)throw F(`CONFIGURATION_HTTP_${C.status}`,"Configuration synchronization failed");return C}function G(h,w,R){let C=Date.parse(h.headers.get("x-indiana-config-validated-at")??""),V=Date.parse(h.headers.get("x-indiana-config-valid-until")??""),k=Date.parse(h.headers.get("date")??""),M=h.headers.get("age"),Q=M!==null&&/^\d+(\.\d+)?$/.test(M)?Number(M)*1e3:NaN;if(![C,V,k,Q].every(Number.isFinite)||V<=C||V-C>Y.maxControlAgeMs||C>k+1e3)throw F("INVALID_RESPONSE","Configuration freshness evidence is invalid");let B=Math.min(V-C,R.maxControlAgeSeconds*1e3,Y.maxControlAgeMs)-Math.max(Q,k-C,0)-(te()-w);if(B<=0)throw F("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return te()+B}function ve(){if(clearTimeout(i),clearTimeout(y),g||!N.size||(E()&&(y=setTimeout(()=>{E()?ve():v()},Math.max(1,o-te())),Nn(y)),typeof document<"u"&&document.visibilityState==="hidden"))return;let h=S?Math.min(15e3,1e3*2**Math.min(S-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);i=setTimeout(()=>{le().catch(O)},Math.max(P,h*(.8+Math.random()*.2))),Nn(i)}async function le(){if(g)throw F("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(_)return _;let h=d,w=new AbortController;q=w;let R=(async()=>{if(!L){L=!0;try{let Ce=await c.readManifest();if(Ce&&!r){let Z=Oe.parse(JSON.parse(Ce));j(Z.scope)===j(n)&&(r=Z)}}catch{}}w.signal.throwIfAborted();let M=r,Q=te(),J=await K(p,w.signal);J.status===304&&(!M||!J.headers.has("x-indiana-config-validated-at")||!J.headers.has("x-indiana-config-valid-until")||!J.headers.has("age"))&&(J=await K(p,w.signal));let B=J.status===304?M:Oe.parse(JSON.parse(await x(J,Y.maxManifestBytes,w.signal))),{generation:me,...pe}=B,W=J.headers.get("etag");if(j(B.scope)!==j(n)||$e(pe)!==me||W!==`"${me}"`&&W!==`W/"${me}"`)throw F("INVALID_RESPONSE","Configuration scope or content identity changed");if(M&&(B.revision<M.revision||B.revision===M.revision&&B.generation!==M.generation))throw F("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Ce,Z]of Object.entries(M?.funnels??{})){let oe=B.funnels[Ce];if(oe&&(oe.controlRevision<Z.controlRevision||oe.evaluationRevision<Z.evaluationRevision||oe.controlRevision===Z.controlRevision&&oe.state!==Z.state||oe.evaluationRevision===Z.evaluationRevision&&oe.evaluationMode!==Z.evaluationMode))throw F("INVALID_RESPONSE","Funnel control revision changed identity")}let re=G(J,Q,B.policy);if(w.signal.throwIfAborted(),h!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return r=B,o=re,s=Date.now()+Math.max(0,re-te()),I=!1,S=0,P=0,c.writeManifest(j(B)),v(),structuredClone(B)})(),C=setTimeout(()=>w.abort(F("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Y.initializationMs),V=new Promise((M,Q)=>w.signal.addEventListener("abort",()=>Q(w.signal.reason),{once:!0})),k=Promise.race([R,V]).catch(M=>{throw S++,(M instanceof Jn.ZodError||M instanceof SyntaxError||M instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(M.code))&&(o=0,I=!0,v()),M}).finally(()=>{clearTimeout(C),_===k&&(_=void 0),ve()});return _=k,k}async function Re(h){let w=h.sha256,R=pe=>Pe(pe,h);H(h.url);let C=T.get(w);if(C){if(C.byteLength!==h.byteLength)throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.delete(w),T.set(w,C),C.text}let V=u.get(w);if(V){if(V.byteLength!==h.byteLength)throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return V.promise}let k=new AbortController;D.add(k);let M=d,Q=(async()=>{try{let re=await c.readArtifact(w);if(re&&R(re)){if(k.signal.throwIfAborted(),g||M!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return U(w,re,h.byteLength),re}}catch{}k.signal.throwIfAborted();let pe=await K(h.url,k.signal,!0),W=await x(pe,h.byteLength,k.signal);if(!R(W))throw F("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(g||M!==d)throw F("CONFIGURATION_DISPOSED","Configuration scope changed");return U(w,W,h.byteLength),c.writeArtifact(w,W),W})(),J=setTimeout(()=>k.abort(F("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Y.initializationMs),B=new Promise((pe,W)=>k.signal.addEventListener("abort",()=>W(k.signal.reason),{once:!0})),me=Promise.race([Q,B]).finally(()=>{clearTimeout(J),D.delete(k),u.delete(w)});return u.set(w,{promise:me,byteLength:h.byteLength}),me}async function he(){return E()||await le(),A(),r}async function ce(h){let w,R=new Promise((C,V)=>{w=setTimeout(()=>V(F("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Y.initializationMs)});try{return await Promise.race([h(),R])}finally{clearTimeout(w)}}function de(h,w){if(A(),r?.generation!==h.generation)throw F("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(w&&r.funnels[w]?.state!=="active")throw F("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Le(h){let w=h.gb.features;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=h.artifacts[w];if(R.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let C=He.parse(JSON.parse(await Re(R)));if(j(C.scope)!==j({projectId:n.projectId,environment:n.environment})||C.generation!==R.generation||C.remoteFeatures.some(V=>Object.hasOwn(C.features,V)))throw F("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return de(h),{...C,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,o-te())).toISOString()}}async function xe(h,w){let R=await he(),C=R.funnels[h];w&&(!C||C.evaluationMode==="local"&&!C.versions[w])&&(_&&await _,R=await le()),de(R,h);let V=R.funnels[h];if(V.evaluationMode!=="local")throw F("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let k=w??V.currentVersionId,M=V.versions[k];if(!M)throw F("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[M.artifact].formatVersion!==3)throw F("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Q,J]=await Promise.all([Re(R.artifacts[M.artifact]).then(B=>Ze(JSON.parse(B))),V.evaluationMode==="local"?Le(R):void 0]);if(J&&j(We(Q,J))!==j(M.dependencies))throw F("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return de(R,h),{document:Q,growth:J,versionId:k,control:structuredClone(V),manifest:structuredClone(R)}}async function Me(h,w){try{return await xe(h,w)}catch(R){if(!(R instanceof l)||!(R.code==="CONFIGURATION_CHANGED"||R.code==="CONFIGURATION_HTTP_404"&&E()))throw R;let C=r?.generation;if(_&&await _,await le(),R.code!=="CONFIGURATION_CHANGED"&&r?.generation===C)throw R;return xe(h,w)}}function fe(){if(E()||v(),typeof document<"u"&&document.visibilityState==="hidden"){ve();return}le().catch(O)}function Tn(h){if(g)throw F("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return N.add(h),N.size===1&&(typeof window<"u"&&(window.addEventListener("online",fe),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),ve()),()=>{N.delete(h),N.size||(clearTimeout(i),clearTimeout(y),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",fe),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:le,subscribe:Tn,assertFresh:A,assertFeatures(h){A();let w=r.gb.features;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(h!==void 0&&r.artifacts[w].generation!==h)throw F("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return E()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return E()?Math.max(0,o-te()):0},async features(){return ce(async()=>Le(await he()))},pageExperiments:()=>ce(async()=>{let h=await he(),w=h.gb.pageExperiments;if(!w)throw F("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=h.artifacts[w];if(R.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let C=un.parse(JSON.parse(await Re(R)));if(C.environmentId!==n.environmentId||C.generation!==R.generation)throw F("INVALID_RESPONSE","Page experiment scope or generation changed");return de(h),C}),funnel:(h,w)=>ce(()=>Me(h,w)),funnelControl:h=>ce(async()=>{let w=await he();return de(w,h),structuredClone(w.funnels[h])}),paywall:(h,w)=>ce(async()=>{let R=await he(),C=R.paywalls?.[h];if(!C||!w&&C.state!=="published")throw F("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let V=w??C.currentVersionId,k=C.versions[V],M=k&&R.artifacts[k.artifact];if(!M||M.kind!=="paywall"||M.formatVersion!==1)throw F("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Q=Qe.parse(JSON.parse(await Re(M)));return de(R),{document:Q,versionId:V,version:k.version,control:structuredClone(C),manifest:structuredClone(R)}}),async localFunnel(h,w){let R=await ce(()=>Me(h,w));if(!R.growth)throw F("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:C,remoteFeatures:V,...k}=R.growth;return sn({scope:{projectId:n.projectId,environment:n.environment},funnelId:h,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:k})},assertFunnel(h,w,R){A();let C=r.funnels[h];if(!C||C.state!=="active")throw F("FUNNEL_STOPPED","Funnel is paused or unavailable");if(C.evaluationMode!=="local")throw F("EVALUATION_MODE","This Funnel now executes at Longplay");if(w!==void 0&&C.controlRevision!==w)throw F("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!C.versions[R])throw F("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!g){g=!0,d++,o=0,q?.abort(F("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(i),clearTimeout(y),Ve(),v(),N.clear();for(let h of D)h.abort(F("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));T.clear(),b=0}}}}function On(e){let n=ge.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!se.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");return{async start(a){let t=X.safeParse({...a,operation:"start"});if(!t.success||t.data.operation!=="start"||(n?t.data.customer!==void 0:t.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let f=t.data,p=ee({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||p.identify(e.apiKey);let m=Ee(e,await p.request("funnels",f));if(!m.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");if(m.run.source.id!==f.funnelId||m.run.locale!==(f.locale??"en")||!we(m.run.parameters,f.parameters??{})||(f.customer?!m.customerId||f.customer.type==="id"&&m.customerId!==f.customer.value:m.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...m,runToken:m.runToken}}finally{p.dispose()}}}}async function Nr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let a={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&j(a)!==j(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnelControl(e.funnelId)).evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let f=se.test(e.credential);if(f?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let p=On({...e,scope:a,apiKey:e.credential}),m=(c,r)=>{let o=Pn({...e,scope:a,runToken:c,initialResponse:r,...f?{serverKey:e.credential}:{}});return f||o.identify(e.credential),o};return{async start(c){let r=await p.start({...c,funnelId:e.funnelId,...f?{customer:{type:"id",value:e.customerId}}:{}}),o=m(r.runToken,r),s=await o.get();return{...r,...s,controller:o}},async restore(c){let r=m(c),o=await r.get();if(o.run.source.id!==e.funnelId)throw r.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...o,runToken:c,controller:r}}}}export{Ne as a,kn as b,En as c,zn as d,Ee as e,_e as f,ut as g,Vn as h,In as i,ht as j,we as k,Pt as l,Et as m,Pn as n,or as o,yr as p,On as q,Nr as r};