PageSourceSearch

https://www.transcript365.com/blog/assets/util-Bon_jvgQ.js

js transcript365.com collected 2026-10-02 00:57:15 UTC 334,815 bytes, 61 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/stegaEncodeSourceMap-_pIIFwxD.js","assets/chunk-EVOBXE3Y-CnOf8VlI.js","assets/browser-D9sIT06I.js"])))=>i.map(i=>d[i]);
2import{a as D,t as Jr,p as m}from"./chunk-EVOBXE3Y-CnOf8VlI.js";const Ao="modulepreload",To=function(t){return"/blog/"+t},us={},En=function(e,r,s){let n=Promise.resolve();if(r&&r.length>0){let c=function(l){return Promise.all(l.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");n=c(r.map(l=>{if(l=To(l),l in us)return;us[l]=!0;const u=l.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Ao,u||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((d,p)=>{f.addEventListener("load",d),f.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${l}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return n.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return e().catch(i)})},kn=!(typeof navigator>"u")&&navigator.product==="ReactNative",xn={timeout:kn?6e4:12e4},Co=function(t){const e={...xn,...typeof t=="string"?{url:t}:t};if(e.timeout=An(e.timeout),e.query){const{url:r,searchParams:s}=(function(n){const i=n.indexOf("?");if(i===-1)return{url:n,searchParams:new URLSearchParams};const o=n.slice(0,i),a=n.slice(i+1);if(!kn)return{url:o,searchParams:new URLSearchParams(a)};if(typeof decodeURIComponent!="function")throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const c=new URLSearchParams;for(const l of a.split("&")){const[u,h]=l.split("=");u&&c.append(hs(u),hs(h||""))}return{url:o,searchParams:c}})(e.url);for(const[n,i]of Object.entries(e.query)){if(i!==void 0)if(Array.isArray(i))for(const a of i)s.append(n,a);else s.append(n,i);const o=s.toString();o&&(e.url=`${r}?${o}`)}}return e.method=e.body&&!e.method?"POST":(e.method||"GET").toUpperCase(),e};function hs(t){return decodeURIComponent(t.replace(/\+/g," "))}function An(t){if(t===!1||t===0)return!1;if(t.connect||t.socket)return t;const e=Number(t);return isNaN(e)?An(xn.timeout):{connect:e,socket:e}}const Oo=/^https?:\/\//i,Ro=function(t){if(!Oo.test(t.url))throw new Error(`"${t.url}" is not a valid URL`)};function Tn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}const jo=["request","response","progress","error","abort"],ds=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function Cn(t,e){const r=[],s=ds.reduce((i,o)=>(i[o]=i[o]||[],i),{processOptions:[Co],validateOptions:[Ro]});function n(i){const o=jo.reduce((d,p)=>(d[p]=(function(){const g=Object.create(null);let y=0;return{publish:function(w){for(const b in g)g[b](w)},subscribe:function(w){const b=y++;return g[b]=w,function(){delete g[b]}}}})(),d),{}),a=(d=>function(p,g,...y){const w=p==="onError";let b=g;for(let v=0;v<d[p].length&&(b=(0,d[p][v])(b,...y),!w||b);v++);return b})(s),c=a("processOptions",i);a("validateOptions",c);const l={options:c,channels:o,applyMiddleware:a};let u;const h=o.request.subscribe(d=>{u=e(d,(p,g)=>((y,w,b)=>{let v=y,S=w;if(!v)try{S=a("onResponse",w,b)}catch(O){S=null,v=O}v=v&&a("onError",v,b),v?o.error.publish(v):S&&o.response.publish(S)})(p,g,d))});o.abort.subscribe(()=>{h(),u&&u.abort()});const f=a("onReturn",o,l);return f===o&&o.request.publish(l),f}return n.use=function(i){if(!i)throw new Error("Tried to add middleware that resolved to falsey value");if(typeof i=="function")throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(i.onReturn&&s.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return ds.forEach(o=>{i[o]&&s[o].push(i[o])}),r.push(i),n},n.clone=()=>Cn(r,e),t.forEach(n.use),n}var fs,ps,Io=Tn((function(){if(ps)return fs;ps=1;var t=function(r){return r.replace(/^\s+|\s+$/g,"")},e=function(r){return Object.prototype.toString.call(r)==="[object Array]"};return fs=function(r){if(!r)return{};for(var s=Object.create(null),n=t(r).split(`
3`),i=0;i<n.length;i++){var o=n[i],a=o.indexOf(":"),c=t(o.slice(0,a)).toLowerCase(),l=t(o.slice(a+1));typeof s[c]>"u"?s[c]=l:e(s[c])?s[c].push(l):s[c]=[s[c],l]}return s}})());let $r=class{onabort;onerror;onreadystatechange;ontimeout;readyState=0;response;responseText="";responseType="";status;statusText;withCredentials;#e;#t;#r;#n={};#s;#i={};#o;open(e,r,s){this.#e=e,this.#t=r,this.#r="",this.readyState=1,this.onreadystatechange?.(),this.#s=void 0}abort(){this.#s&&this.#s.abort()}getAllResponseHeaders(){return this.#r}setRequestHeader(e,r){this.#n[e]=r}setInit(e,r=!0){this.#i=e,this.#o=r}send(e){const r=this.responseType!=="arraybuffer",s={...this.#i,method:this.#e,headers:this.#n,body:e};typeof AbortController=="function"&&this.#o&&(this.#s=new AbortController,typeof EventTarget<"u"&&this.#s.signal instanceof EventTarget&&(s.signal=this.#s.signal)),typeof document<"u"&&(s.credentials=this.withCredentials?"include":"omit"),fetch(this.#t,s).then(n=>
3(n.headers.forEach((i,o)=>{this.#r+=`${o}: ${i}\r
4`}),this.status=n.status,this.statusText=n.statusText,this.readyState=3,this.onreadystatechange?.(),r?n.text():n.arrayBuffer())).then(n=>{typeof n=="string"?this.responseText=n:this.response=n,this.readyState=4,this.onreadystatechange?.()}).catch(n=>{n.name!=="AbortError"?this.onerror?.(n):this.onabort?.()})}};const Pr=typeof XMLHttpRequest=="function"?"xhr":"fetch",$o=Pr==="xhr"?XMLHttpRequest:$r,Po=(t,e)=>{const r=t.options,s=t.applyMiddleware("finalizeOptions",r),n={},i=t.applyMiddleware("interceptRequest",void 0,{adapter:Pr,context:t});if(i){const g=setTimeout(e,0,null,i);return{abort:()=>clearTimeout(g)}}let o=new $o;o instanceof $r&&typeof s.fetch=="object"&&o.setInit(s.fetch,s.useAbortSignal??!0);const a=s.headers,c=s.timeout;let l=!1,u=!1,h=!1;if(o.onerror=g=>{p(o instanceof $r?g instanceof Error?g:new Error(`Request error while attempting to reach is ${s.url}`,{cause:g}):new Error(`Request error while attempting to reach is ${s.url}${g.lengthComputable?`(${g.loaded} of ${g.total} bytes transferred)`:""}`))},o.ontimeout=g=>{p(new Error(`Request timeout while attempting to reach ${s.url}${g.lengthComputable?`(${g.loaded} of ${g.total} bytes transferred)`:""}`))},o.onabort=()=>{d(!0),l=!0},o.onreadystatechange=function(){c&&(d(),n.socket=setTimeout(()=>f("ESOCKETTIMEDOUT"),c.socket)),!l&&o&&o.readyState===4&&o.status!==0&&(function(){if(!(l||u||h)){if(o.status===0)return void p(new Error("Unknown XHR error"));d(),u=!0,e(null,{body:o.response||(o.responseType===""||o.responseType==="text"?o.responseText:""),url:s.url,method:s.method,headers:Io(o.getAllResponseHeaders()),statusCode:o.status,statusMessage:o.statusText})}})()},o.open(s.method,s.url,!0),o.withCredentials=!!s.withCredentials,a&&o.setRequestHeader)for(const g in a)a.hasOwnProperty(g)&&o.setRequestHeader(g,a[g]);return s.rawBody&&(o.responseType="arraybuffer"),t.applyMiddleware("onRequest",{options:s,adapter:Pr,request:o,context:t}),o.send(s.body||null),c&&(n.connect=setTimeout(()=>f("ETIMEDOUT"),c.connect)),{abort:function(){l=!0,o&&o.abort()}};function f(g){h=!0,o.abort();const y=new Error(g==="ESOCKETTIMEDOUT"?`Socket timed out on request to ${s.url}`:`Connection timed out on request to ${s.url}`);y.code=g,t.channels.error.publish(y)}function d(g){(g||l||o&&o.readyState>=2&&n.connect)&&clearTimeout(n.connect),n.socket&&clearTimeout(n.socket)}function p(g){if(u)return;d(!0),u=!0,o=null;const y=g||new Error(`Network error while attempting to reach ${s.url}`);y.isNetworkError=!0,y.request=s,e(y)}},No=(t=[],e=Po)=>Cn(t,e);var Lo={},gs,ms,ys,vs,ws,gr={exports:{}};ws||(ws=1,(function(t,e){e.formatArgs=function(s){if(s[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+s[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;s.splice(1,0,n,"color: inherit");let i=0,o=0;s[0].replace(/%[a-zA-Z%]/g,a=>{a!=="%%"&&(i++,a==="%c"&&(o=i))}),s.splice(o,0,n)},e.save=function(s){try{s?e.storage.setItem("debug",s):e.storage.removeItem("debug")}catch{}},e.load=function(){let s;try{s=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!s&&typeof process<"u"&&"env"in process&&(s=Lo.DEBUG),s},e.useColors=function(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let s;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(s=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(s[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=(function(){try{return localStorage}catch{}})(),e.destroy=(()=>{let s=!1;return()=>{s||(s=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33
4CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),t.exports=(vs?ys:(vs=1,ys=function(s){function n(a){let c,l,u,h=null;function f(...d){if(!f.enabled)return;const p=f,g=Number(new Date),y=g-(c||g);p.diff=y,p.prev=c,p.curr=g,c=g,d[0]=n.coerce(d[0]),typeof d[0]!="string"&&d.unshift("%O");let w=0;d[0]=d[0].replace(/%([a-zA-Z%])/g,(b,v)=>{if(b==="%%")return"%";w++;const S=n.formatters[v];if(typeof S=="function"){const O=d[w];b=S.call(p,O),d.splice(w,1),w--}return b}),n.formatArgs.call(p,d),(p.log||n.log).apply(p,d)}return f.namespace=a,f.useColors=n.useColors(),f.color=n.selectColor(a),f.extend=i,f.destroy=n.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(l!==n.namespaces&&(l=n.namespaces,u=n.enabled(a)),u),set:d=>{h=d}}),typeof n.init=="function"&&n.init(f),f}function i(a,c){const l=n(this.namespace+(typeof c>"u"?":":c)+a);return l.log=this.log,l}function o(a,c){let l=0,u=0,h=-1,f=0;for(;l<a.length;)if(u<c.length&&(c[u]===a[l]||c[u]==="*"))c[u]==="*"?(h=u,f=l,u++):(l++,u++);else{if(h===-1)return!1;u=h+1,f++,l=f}for(;u<c.length&&c[u]==="*";)u++;return u===c.length}return n.debug=n,n.default=n,n.coerce=function(a){return a instanceof Error?a.stack||a.message:a},n.disable=function(){const a=[...n.names,...n.skips.map(c=>"-"+c)].join(",");return n.enable(""),a},n.enable=function(a){n.save(a),n.namespaces=a,n.names=[],n.skips=[];const c=(typeof a=="string"?a:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const l of c)l[0]==="-"?n.skips.push(l.slice(1)):n.names.push(l)},n.enabled=function(a){for(const c of n.skips)if(o(a,c))return!1;for(const c of n.names)if(o(a,c))return!0;return!1},n.humanize=(function(){if(ms)return gs;ms=1;var a=1e3,c=60*a,l=60*c,u=24*l,h=7*u;function f(d,p,g,y){var w=p>=1.5*g;return Math.round(d/g)+" "+y+(w?"s":"")}return gs=function(d,p){p=p||{};var g,y,w=typeof d;if(w==="string"&&d.length>0)return(function(b){if(!((b=String(b)).length>100)){var v=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(b);if(v){var S=parseFloat(v[1]);switch((v[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*S;case"weeks":case"week":case"w":return S*h;case"days":case"day":case"d":return S*u;case"hours":case"hour":case"hrs":case"hr":case"h":return S*l;case"minutes":case"minute":case"mins":case"min":case"m":return S*c;case"seconds":case"second":case"secs":case"sec":case"s":return S*a;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return S;default:return}}}})(d);if(w==="number"&&isFinite(d))return p.long?(g=d,(y=Math.abs(g))>=u?f(g,y,u,"day"):y>=l?f(g,y,l,"hour"):y>=c?f(g,y,c,"minute"):y>=a?f(g,y,a,"second"):g+" ms"):(function(b){var v=Math.abs(b);return v>=u?Math.round(b/u)+"d":v>=l?Math.round(b/l)+"h":v>=c?Math.round(b/c)+"m":v>=a?Math.round(b/a)+"s":b+"ms"})(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))}})(),n.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(s).forEach(a=>{n[a]=s[a]}),n.names=[],n.skips=[],n.formatters={},n.selectColor=function(a){let c=0;for(let l=0;l<a.length;l++)c=(c<<5)-c+a.charCodeAt(l),c|=0;return n.colors[Math.abs(c)%n.colors.length]},n.enable(n.load()),n}))(e);const{formatters:r}=t.exports;r.j=function(s){try{return JSON.stringify(s)}catch(n){return"[UnexpectedJSONParseError]: "+n.message}}})(gr,gr.exports)),gr.exports;const Uo=typeof Buffer>"u"?()=>!1:t=>Buffer.isBuffer(t);function bs(t){return Object.prototype.toString.call(t)==="[object Object]"}function Do(t){if(bs(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(bs(r)===!1||r.hasOwnProperty("isPrototypeOf")===!1)}const Mo=["boolean","string","number"];function Fo(){return{processOptions:t=>{const e=t.body;return!e||typeof e.pipe=="function"||Uo(e)||Mo.indexOf(typeof e)===-1&&!Array.isArray(e)&&!Do(e)?t:Object.assign({},t,{body:JSON.stringify(t.body),headers:Object.assign({},t.headers,{"Content-Type":"application/json"})})}}}function qo(t){return{onResponse:r=>{const s=r.headers["content-type"]||"",n=t&&t.force||s.indexOf("application/json")!==-1;return r.body&&s&&n?Object.assign({},r,{body:e(r.body)}):r},processOptions:r=>Object.assign({},r,{headers:Object.assign({Accept:"application/json"},r.headers)})};function e(r){try{return JSON.parse(r)}catch(s){throw s.message=`Failed to parsed response body as JSON: ${s.message}`,s}}}let rt={};typeof globalThis<"u"?rt=globalThis:typeof window<"u"?rt=window:typeof global<"u"?rt=global:typeof self<"u"&&(rt=self);var Bo=rt;function Ho(t={}){const e=t.implementation||Bo.Observable;if(!e)throw new Error("`Observable` is not available in global scope, and n
4o implementation was passed");return{onReturn:(r,s)=>new e(n=>(r.error.subscribe(i=>n.error(i)),r.progress.subscribe(i=>n.next(Object.assign({type:"progress"},i))),r.response.subscribe(i=>{n.next(Object.assign({type:"response"},i)),n.complete()}),r.request.publish(s),()=>r.abort.publish()))}}function Vo(){return{onRequest:t=>{if(t.adapter!=="xhr")return;const e=t.request,r=t.context;function s(n){return i=>{const o=i.lengthComputable?i.loaded/i.total*100:-1;r.channels.progress.publish({stage:n,percent:o,total:i.total,loaded:i.loaded,lengthComputable:i.lengthComputable})}}"upload"in e&&"onprogress"in e.upload&&(e.upload.onprogress=s("upload")),"onprogress"in e&&(e.onprogress=s("download"))}}}var On=(t,e,r)=>(r.method==="GET"||r.method==="HEAD")&&(t.isNetworkError||!1);function Wo(t){return 100*Math.pow(2,t)+100*Math.random()}const Yr=(t={})=>(e=>{const r=e.maxRetries||5,s=e.retryDelay||Wo,n=e.shouldRetry;return{onError:(i,o)=>{const a=o.options,c=a.maxRetries||r,l=a.retryDelay||s,u=a.shouldRetry||n,h=a.attemptNumber||0;if((f=a.body)!==null&&typeof f=="object"&&typeof f.pipe=="function"||!u(i,h,a)||h>=c)return i;var f;const d=Object.assign({},o,{options:Object.assign({},a,{attemptNumber:h+1})});return setTimeout(()=>o.channels.request.publish(d),l(h)),null}}})({shouldRetry:On,...t});Yr.shouldRetry=On;var Nr=function(t,e){return Nr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(r[n]=s[n])},Nr(t,e)};function le(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Nr(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function rr(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function Rn(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(h){o(h)}}function c(u){try{l(s.throw(u))}catch(h){o(h)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(t,e||[])).next())})}function jn(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,n,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(s)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(r=0)),r;)try{if(s=1,n&&(i=l[0]&2?n.return:l[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,l[1])).done)return i;switch(n=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,n=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],n=0}finally{s=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Ve(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],s=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&s>=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ae(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var s=r.call(t),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return i}function ce(t,e,r){if(r||arguments.length===2)for(var s=0,n=e.length,i;s<n;s++)(i||!(s in e))&&(i||(i=Array.prototype.slice.call(e,0,s)),i[s]=e[s]);return t.concat(i||Array.prototype.slice.call(e))}function Me(t){return this instanceof Me?(this.v=t,this):new Me(t)}function zo(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=r.apply(t,e||[]),n,i=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),n[Symbol.asyncIterator]=function(){return this},n;function o(d){return function(p){return Promise.resolve(p).then(d,h)}}function a(d,p){s[d]&&(n[d]=function(g){return new Promise(function(y,w){i.push([d,g,y,w])>1||c(d,g)})},p&&(n[d]=p(n[d])))}function c(d,p){try{l(s[d](p))}catch(g){f(i[0][3],g)}}function l(d){d.value instanceof Me?Promise.resolve(d.value.v).then(u,h):f(i[0][2],d)}function u(d){c("next",d)}function h(d){c("throw",d)}function f(d,p){d(p),i.shift(),i.length&&c(i[0][0],i[0][1])}}function Ko(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Ve=="function"?Ve(t):t[Symbol.iterator](),r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r);function s(i){r[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),n(a,c,o.done,o.value)})}}function n(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function j(t){return typeof t=="function"}function Xr(t){var e=function(s){Error.call(s),s.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var mr=Xr(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
5`+r.map(function(s,n){return n+1+") "+s.toString()}).join(`
6  `):"",this.name="UnsubscriptionError",this.errors=r}});function Ft(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var bt=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,r,s,n,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=Ve(o
vendor: 7,082 bytes, line 6
6),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(g){e={error:g}}finally{try{c&&!c.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}else o.remove(this);var u=this.initialTeardown;if(j(u))try{u()}catch(g){i=g instanceof mr?g.errors:[g]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var f=Ve(h),d=f.next();!d.done;d=f.next()){var p=d.value;try{_s(p)}catch(g){i=i??[],g instanceof mr?i=ce(ce([],ae(i)),ae(g.errors)):i.push(g)}}}catch(g){s={error:g}}finally{try{d&&!d.done&&(n=f.return)&&n.call(f)}finally{if(s)throw s.error}}}if(i)throw new mr(i)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)_s(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(e)}},t.prototype._hasParent=function(e){var r=this._parentage;return r===e||Array.isArray(r)&&r.includes(e)},t.prototype._addParent=function(e){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(e),r):r?[r,e]:e},t.prototype._removeParent=function(e){var r=this._parentage;r===e?this._parentage=null:Array.isArray(r)&&Ft(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&Ft(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})(),In=bt.EMPTY;function $n(t){return t instanceof bt||t&&"closed"in t&&j(t.remove)&&j(t.add)&&j(t.unsubscribe)}function _s(t){j(t)?t():t.unsubscribe()}var Go={Promise:void 0},Jo={setTimeout:function(t,e){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];return setTimeout.apply(void 0,ce([t,e],ae(r)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function Pn(t){Jo.setTimeout(function(){throw t})}function Ss(){}function Ut(t){t()}var Qr=(function(t){le(e,t);function e(r){var s=t.call(this)||this;return s.isStopped=!1,r?(s.destination=r,$n(r)&&r.add(s)):s.destination=Qo,s}return e.create=function(r,s,n){return new We(r,s,n)},e.prototype.next=function(r){this.isStopped||this._next(r)},e.prototype.error=function(r){this.isStopped||(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(r){this.destination.next(r)},e.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(bt),Yo=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var r=this.partialObserver;if(r.next)try{r.next(e)}catch(s){Ct(s)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(s){Ct(s)}else Ct(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){Ct(r)}},t})(),We=(function(t){le(e,t);function e(r,s,n){var i=t.call(this)||this,o;return j(r)||!r?o={next:r??void 0,error:s??void 0,complete:n??void 0}:o=r,i.destination=new Yo(o),i}return e})(Qr);function Ct(t){Pn(t)}function Xo(t){throw t}var Qo={closed:!0,next:Ss,error:Xo,complete:Ss},Zr=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function sr(t){return t}function Zo(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Nn(t)}function Nn(t){return t.length===0?sr:t.length===1?t[0]:function(r){return t.reduce(function(s,n){return n(s)},r)}}var N=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(e,r,s){var n=this,i=ta(e)?e:new We(e,r,s);return Ut(function(){var o=n,a=o.operator,c=o.source;i.add(a?a.call(i,c):c?n._subscribe(i):n._trySubscribe(i))}),i},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(r){e.error(r)}},t.prototype.forEach=function(e,r){var s=this;return r=Es(r),new r(function(n,i){var o=new We({next:function(a){try{e(a)}catch(c){i(c),o.unsubscribe()}},error:i,complete:n});s.subscribe(o)})},t.prototype._subscribe=function(e){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(e)},t.prototype[Zr]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Nn(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=Es(e),new e(function(s,n){var i;r.subscribe(function(o){return i=o},function(o){return n(o)},function(){return s(i)})})},t.create=function(e){return new t(e)},t})();function Es(t){var e;return(e=t??Go.Promise)!==null&&e!==void 0?e:Promise}function ea(t){return t&&j(t.next)&&j(t.error)&&j(t.complete)}function ta(t){return t&&t instanceof Qr||ea(t)&&$n(t)}function ra(t){return j(t?.lift)}function re(t){return function(e){if(ra(e))return e.lift(function(r){try{return t(r,this)}catch(s){this.error(s)}});throw new TypeError("Unable to lift unknown Observable type")}}function ve(t,e,r,s,n){return new sa(t,e,r,s,n)}var sa=(function(t){le(e,t);function e(r,s,n,i,o,a){var c=t.call(this,r)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=s?function(l){try{s(l)}catch(u){r.error(u)}}:t.prototype._next,c._error=i?function(l){try{i(l)}catch(u){r.error(u)}finally{this.unsubscribe()}}:t.prototype._error,c._complete=n?function(){try{n()}catch(l){r.error(l)}finally{this.unsubscribe()}}:t.prototype._complete,c}return e.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var s=this.closed;t.prototype.unsubscribe.call(this),!s&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},e})(Qr),na=Xr(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),es=(function(t){le(e,t);function e(){var r=t.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return e.prototype.lift=function(r){var s=new ks(this,this);return s.operator=r,s},e.prototype._throwIfClosed=function(){if(this.closed)throw new na},e.prototype.next=function(r){var s=this;Ut(function(){var n,i;if(s._throwIfClosed(),!s.isStopped){s.currentObservers||(s.currentObservers=Array.from(s.observers));try{for(var o=Ve(s.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(r)}}catch(l){n={error:l}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}}})},e.prototype.error=function(r){var s=this;Ut(function(){if(s._throwIfClosed(),!s.isStopped){s.hasError=s.isStopped=!0,s.thrownError=r;for(var n=s.observers;n.length;)n.shift().error(r)}})},e.prototype.complete=function(){var r=this;Ut(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var s=r.observers;s.length;)s.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0}
6,enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(r){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,r)},e.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},e.prototype._innerSubscribe=function(r){var s=this,n=this,i=n.hasError,o=n.isStopped,a=n.observers;return i||o?In:(this.currentObservers=null,a.push(r),new bt(function(){s.currentObservers=null,Ft(a,r)}))},e.prototype._checkFinalizedStatuses=function(r){var s=this,n=s.hasError,i=s.thrownError,o=s.isStopped;n?r.error(i):o&&r.complete()},e.prototype.asObservable=function(){var r=new N;return r.source=this,r},e.create=function(r,s){return new ks(r,s)},e})(N),ks=(function(t){le(e,t);function e(r,s){var n=t.call(this)||this;return n.destination=r,n.source=s,n}return e.prototype.next=function(r){var s,n;(n=(s=this.destination)===null||s===void 0?void 0:s.next)===null||n===void 0||n.call(s,r)},e.prototype.error=function(r){var s,n;(n=(s=this.destination)===null||s===void 0?void 0:s.error)===null||n===void 0||n.call(s,r)},e.prototype.complete=function(){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||s===void 0||s.call(r)},e.prototype._subscribe=function(r){var s,n;return(n=(s=this.source)===null||s===void 0?void 0:s.subscribe(r))!==null&&n!==void 0?n:In},e})(es),ts={now:function(){return(ts.delegate||Date).now()},delegate:void 0},ia=(function(t){le(e,t);function e(r,s,n){r===void 0&&(r=1/0),s===void 0&&(s=1/0),n===void 0&&(n=ts);var i=t.call(this)||this;return i._bufferSize=r,i._windowTime=s,i._timestampProvider=n,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=s===1/0,i._bufferSize=Math.max(1,r),i._windowTime=Math.max(1,s),i}return e.prototype.next=function(r){var s=this,n=s.isStopped,i=s._buffer,o=s._infiniteTimeWindow,a=s._timestampProvider,c=s._windowTime;n||(i.push(r),!o&&i.push(a.now()+c)),this._trimBuffer(),t.prototype.next.call(this,r)},e.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var s=this._innerSubscribe(r),n=this,i=n._infiniteTimeWindow,o=n._buffer,a=o.slice(),c=0;c<a.length&&!r.closed;c+=i?1:2)r.next(a[c]);return this._checkFinalizedStatuses(r),s},e.prototype._trimBuffer=function(){var r=this,s=r._bufferSize,n=r._timestampProvider,i=r._buffer,o=r._infiniteTimeWindow,a=(o?1:2)*s;if(s<1/0&&a<i.length&&i.splice(0,i.length-a),!o){for(var c=n.now(),l=0,u=1;u<i.length&&i[u]<=c;u+=2)l=u;l&&i.splice(0,l+1)}},e})(es),oa=(function(t){le(e,t);function e(r,s){return t.call(this)||this}return e.prototype.schedule=function(r,s){return this},e})(bt),xs={setInterval:function(t,e){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];return setInterval.apply(void 0,ce([t,e],ae(r)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},aa=(function(t){le(e,t);function e(r,s){var n=t.call(this,r,s)||this;
vendor: 4,803 bytes, line 6
6return n.scheduler=r,n.work=s,n.pending=!1,n}return e.prototype.schedule=function(r,s){var n;if(s===void 0&&(s=0),this.closed)return this;this.state=r;var i=this.id,o=this.scheduler;return i!=null&&(this.id=this.recycleAsyncId(o,i,s)),this.pending=!0,this.delay=s,this.id=(n=this.id)!==null&&n!==void 0?n:this.requestAsyncId(o,this.id,s),this},e.prototype.requestAsyncId=function(r,s,n){return n===void 0&&(n=0),xs.setInterval(r.flush.bind(r,this),n)},e.prototype.recycleAsyncId=function(r,s,n){if(n===void 0&&(n=0),n!=null&&this.delay===n&&this.pending===!1)return s;s!=null&&xs.clearInterval(s)},e.prototype.execute=function(r,s){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(r,s);if(n)return n;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(r,s){var n=!1,i;try{this.work(r)}catch(o){n=!0,i=o||new Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),i},e.prototype.unsubscribe=function(){if(!this.closed){var r=this,s=r.id,n=r.scheduler,i=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Ft(i,this),s!=null&&(this.id=this.recycleAsyncId(n,s,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e})(oa),As=(function(){function t(e,r){r===void 0&&(r=t.now),this.schedulerActionCtor=e,this.now=r}return t.prototype.schedule=function(e,r,s){return r===void 0&&(r=0),new this.schedulerActionCtor(this,e).schedule(s,r)},t.now=ts.now,t})(),ca=(function(t){le(e,t);function e(r,s){s===void 0&&(s=As.now);var n=t.call(this,r,s)||this;return n.actions=[],n._active=!1,n}return e.prototype.flush=function(r){var s=this.actions;if(this._active){s.push(r);return}var n;this._active=!0;do if(n=r.execute(r.state,r.delay))break;while(r=s.shift());if(this._active=!1,n){for(;r=s.shift();)r.unsubscribe();throw n}},e})(As),la=new ca(aa),ua=la,ha=new N(function(t){return t.complete()});function da(t){return t&&j(t.schedule)}function rs(t){return t[t.length-1]}function fa(t){return j(rs(t))?t.pop():void 0}function ss(t){return da(rs(t))?t.pop():void 0}function pa(t,e){return typeof rs(t)=="number"?t.pop():e}var Ln=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function Un(t){return j(t?.then)}function Dn(t){return j(t[Zr])}function Mn(t){return Symbol.asyncIterator&&j(t?.[Symbol.asyncIterator])}function Fn(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function ga(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var qn=ga();function Bn(t){return j(t?.[qn])}function Hn(t){return zo(this,arguments,function(){var r,s,n,i;return jn(this,function(o){switch(o.label){case 0:r=t.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,Me(r.read())];case 3:return s=o.sent(),n=s.value,i=s.done,i?[4,Me(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,Me(n)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function Vn(t){return j(t?.getReader)}function se(t){if(t instanceof N)return t;if(t!=null){if(Dn(t))return ma(t);if(Ln(t))return ya(t);if(Un(t))return va(t);if(Mn(t))return Wn(t);if(Bn(t))return wa(t);if(Vn(t))return ba(t)}throw Fn(t)}function ma(t){return new N(function(e){var r=t[Zr]();if(j(r.subscribe))return r.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function ya(t){return new N(function(e){for(var r=0;r<t.length&&!e.closed;r++)e.next(t[r]);e.complete()})}function va(t){return new N(function(e){t.then(function(r){e.closed||(e.next(r),e.complete())},function(r){return e.error(r)}).then(null,Pn)})}function wa(t){return new N(function(e){var r,s;try{for(var n=Ve(t),i=n.next();!i.done;i=n.next()){var o=i.value;if(e.next(o),e.closed)return}}catch(a){r={error:a}}finally{try{i&&!i.done&&(s=n.return)&&s.call(n)}finally{if(r)throw r.error}}e.complete()})}function Wn(t){return new N(function(e){_a(t,e).catch(function(r){return e.error(r)})})}function ba(t){return Wn(Hn(t))}function _a(t,e){var r,s,n,i;return Rn(this,void 0,void 0,function(){var o,a;return jn(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=Ko(t),c.label=1;case 1:return[4,r.next()];case 2:if(s=c.sent(),!!s.done)return[3,4];if(o=s.value,e.next(o),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),n={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),s&&!s.done&&(i=r.return)?[4,i.call(r)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(n)throw n.error;return[7];
6case 10:return[7];case 11:return e.complete(),[2]}})})}function Ee(t,e,r,s,n){s===void 0&&(s=0),n===void 0&&(n=!1);var i=e.schedule(function(){r(),n?t.add(this.schedule(null,s)):this.unsubscribe()},s);if(t.add(i),!n)return i}function zn(t,e){return e===void 0&&(e=0),re(function(r,s){r.subscribe(ve(s,function(n){return Ee(s,t,function(){return s.next(n)},e)},function(){return Ee(s,t,function(){return s.complete()},e)},function(n){return Ee(s,t,function(){return s.error(n)},e)}))})}function Kn(t,e){return e===void 0&&(e=0),re(function(r,s){s.add(t.schedule(function(){return r.subscribe(s)},e))})}function Sa(t,e){return se(t).pipe(Kn(e),zn(e))}function Ea(t,e){return se(t).pipe(Kn(e),zn(e))}function ka(t,e){return new N(function(r){var s=0;return e.schedule(function(){s===t.length?r.complete():(r.next(t[s++]),r.closed||this.schedule())})})}function xa(t,e){return new N(function(r){var s;return Ee(r,e,function(){s=t[qn](),Ee(r,e,function(){var n,i,o;try{n=s.next(),i=n.value,o=n.done}catch(a){r.error(a);return}o?r.complete():r.next(i)},0,!0)}),function(){return j(s?.return)&&s.return()}})}function Gn(t,e){if(!t)throw new Error("Iterable cannot be null");return new N(function(r){Ee(r,e,function(){var s=t[Symbol.asyncIterator]();Ee(r,e,function(){s.next().then(function(n){n.done?r.complete():r.next(n.value)})},0,!0)})})}function Aa(t,e){return Gn(Hn(t),e)}function Ta(t,e){if(t!=null){if(Dn(t))return Sa(t,e);if(Ln(t))return ka(t,e);if(Un(t))return Ea(t,e);if(Mn(t))return Gn(t,e);if(Bn(t))return xa(t,e);if(Vn(t))return Aa(t,e)}throw Fn(t)}function _t(t,e){return e?Ta(t,e):se(t)}function Fe(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=ss(t);return _t(t,r)}function Jn(t,e){var r=j(t)?t:function(){return t},s=function(n){return n.error(r())};return new N(s)}function Ca(t){return!!t&&(t instanceof N||j(t.lift)&&j(t.subscribe))}var Yn=Xr(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function T(t,e){return new Promise(function(r,s){var n=!1,i;t.subscribe({next:function(o){i=o,n=!0},error:s,complete:function(){n?r(i):s(new Yn)}})})}function yr(t,e){return new Promise(function(r,s){var n=new We({next:function(i){r(i),n.unsubscribe()},error:s,complete:function(){s(new Yn)}});t.subscribe(n)})}function Oa(t){return t instanceof Date&&!isNaN(t)}function B(t,e){return re(function(r,s){var n=0;r.subscribe(ve(s,function(i){s.next(t.call(e,i,n++))}))})}var Ra=Array.isArray;function ja(t,e){return Ra(e)?t.apply(void 0,ce([],ae(e))):t(e)}function Ia(t){return B(function(e){return ja(t,e)})}function $a(t,e,r){return r===void 0&&(r=sr),function(s){Ts(e,function(){for(var n=t.length,i=new Array(n),o=n,a=n,c=function(u){Ts(e,function(){var h=_t(t[u],e),f=!1;h.subscribe(ve(s,function(d){i[u]=d,f||(f=!0,a--),a||s.next(r(i.slice()))},function(){--o||s.complete()}))},s)},l=0;l<n;l++)c(l)})}}function Ts(t,e,r){e()}function Pa(t,e,r,s,n,i,o,a){var c=[],l=0,u=0,h=!1,f=function(){h&&!c.length&&!l&&e.complete()},d=function(g){return l<s?p(g):c.push(g)},p=function(g){l++;var y=!1;se(r(g,u++)).subscribe(ve(e,function(w){e.next(w)},function(){y=!0},void 0,function(){if(y)try{l--;for(var w=function(){var b=c.shift();o||p(b)};c.length&&l<s;)w();f()}catch(b){e.error(b)}}))};return t.subscribe(ve(e,d,function(){h=!0,f()})),function(){}}function ke(t,e,r){return r===void 0&&(r=1/0),j(e)?ke(function(s,n){return B(function(i,o){return e(s,i,n,o)})(se(t(s,n)))},r):(typeof e=="number"&&(r=e),re(function(s,n){return Pa(s,n,t,r)}))}function Xn(t){return t===void 0&&(t=1/0),ke(sr,t)}function Na(){return Xn(1)}function La(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Na()(_t(t,ss(t)))}function Qn(t){return new N(function(e){se(t()).subscribe(e)})}function Ua(t,e,r){return r===void 0&&(r=ua),new N(function(s){var n=Oa(t)?+t-r.now():t;n<0&&(n=0);var i=0;return r.schedule(function(){s.closed||(s.next(i++),s.complete())},n)})}function Da(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=ss(t),s=pa(t,1/0),n=t;return n.length?n.length===1?se(n[0]):Xn(s)(_t(n,r)):ha}var Ma=Array.isArray;function Fa(t){return t.length===1&&Ma(t[0])?t[0]:t}function Xe(t,e){return re(function(r,s){var n=0;r.subscribe(ve(s,function(i){return t.call(e,i,n++)&&s.next(i)}))})}function qt(t){return re(function(e,r){var s=null,n=!1,i;
6s=e.subscribe(ve(r,void 0,void 0,function(o){i=se(t(o,qt(t)(e))),s?(s.unsubscribe(),s=null,i.subscribe(r)):n=!0})),n&&(s.unsubscribe(),s=null,i.subscribe(r))})}function Zn(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=fa(t);return r?Zo(Zn.apply(void 0,ce([],ae(t))),Ia(r)):re(function(s,n){$a(ce([s],ae(Fa(t))))(n)})}function qa(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Zn.apply(void 0,ce([],ae(t)))}function ei(t){return re(function(e,r){try{e.subscribe(r)}finally{r.add(t)}})}function ti(t){t===void 0&&(t={});var e=t.connector,r=e===void 0?function(){return new es}:e,s=t.resetOnError,n=s===void 0?!0:s,i=t.resetOnComplete,o=i===void 0?!0:i,a=t.resetOnRefCountZero,c=a===void 0?!0:a;return function(l){var u,h,f,d=0,p=!1,g=!1,y=function(){h?.unsubscribe(),h=void 0},w=function(){y(),u=f=void 0,p=g=!1},b=function(){var v=u;w(),v?.unsubscribe()};return re(function(v,S){d++,!g&&!p&&y();var O=f=f??r();S.add(function(){d--,d===0&&!g&&!p&&(h=vr(b,c))}),O.subscribe(S),!u&&d>0&&(u=new We({next:function(A){return O.next(A)},error:function(A){g=!0,y(),h=vr(w,n,A),O.error(A)},complete:function(){p=!0,y(),h=vr(w,o),O.complete()}}),se(v).subscribe(u))})(l)}}function vr(t,e){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];if(e===!0){t();return}if(e!==!1){var n=new We({next:function(){n.unsubscribe(),t()}});return se(e.apply(void 0,ce([],ae(r)))).subscribe(n)}}function Ba(t,e,r){var s,n=!1;return s=t,ti({connector:function(){return new ia(s,e,r)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:n})}function Ha(t,e,r){var s=j(t)||e||r?{next:t,error:e,complete:r}:t;return s?re(function(n,i){var o;(o=s.subscribe)===null||o===void 0||o.call(s);var a=!0;n.subscribe(ve(i,function(c){var l;(l=s.next)===null||l===void 0||l.call(s,c),i.next(c)},function(){var c;a=!1,(c=s.complete)===null||c===void 0||c.call(s),i.complete()},function(c){var l;a=!1,(l=s.error)===null||l===void 0||l.call(s,c),i.error(c)},function(){var c,l;a&&((c=s.unsubscribe)===null||c===void 0||c.call(s)),(l=s.finalize)===null||l===void 0||l.call(s)}))}):sr}function ri(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var si={0:8203,1:8204,2:8205,3:8290,4:8291,5:8288,6:65279,7:8289,8:119155,9:119156,a:119157,b:119158,c:119159,d:119160,e:119161,f:119162},st={0:8203,1:8204,2:8205,3:65279},nt={0:String.fromCodePoint(st[0]),1:String.fromCodePoint(st[1]),2:String.fromCodePoint(st[2]),3:String.fromCodePoint(st[3])},Va=new Array(4).fill(String.fromCodePoint(st[0])).join("");function Wa(t){let e=JSON.stringify(t),r=new TextEncoder().encode(e),s="";for(let n=0;n<r.length;n++){let i=r[n];s+=nt[i>>6&3]+nt[i>>4&3]+nt[i>>2&3]+nt[i&3]}return Va+s}function za(t){return!Number.isNaN(Number(t))||/[a-z]/i.test(t)&&!/\d+(?:[-:\/]\d+){2}(?:T\d+(?:[-:\/]\d+){1,2}(\.\d+)?Z?)?/.test(t)?!1:!!Date.parse(t)}function Ka(t){try{new URL(t,t.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}function Tf(t,e,r="auto"){return r===!0||r==="auto"&&(za(t)||Ka(t))?t:`${t}${Wa(e)}`}Object.fromEntries(Object.entries(nt).map(t=>[t[1],+t[0]]));Object.fromEntries(Object.entries(si).map(t=>t.reverse()));var Ga=`${Object.values(si).map(t=>`\\u{${t.toString(16)}}`).join("")}`,Cs=new RegExp(`[${Ga}]{4,}`,"gu");function Ja(t){var e;return{cleaned:t.replace(Cs,""),encoded:((e=t.match(Cs))==null?void 0:e[0])||""}}function Ya(t){return t&&JSON.parse(Ja(JSON.stringify(t)).cleaned)}function Xa(t){return Ya(t)}const Qa="drafts",Za="versions",ze=".",Bt=`${Qa}${ze}`,ni=`${Za}${ze}`;function nr(t){return t.startsWith(Bt)}function ir(t){return t.startsWith(ni)}function ii(t){if(ir(t)){const e=or(t);return Bt+e}return nr(t)?t:Bt+t}function St(t,e){if(e==="drafts"||e==="published")throw new Error('Version can not be "published" or "drafts"');return`${ni}${e}${ze}${or(t)}`}function oi(t){if(!ir(t))return;const[e,r]=t.split(ze);return r}function or(t){return ir(t)?t.split(ze).slice(2).join(ze):nr(t)?t.slice(Bt.length):t}let ec=t=>crypto.getRandomValues(new Uint8Array(t)),tc=(t,e,r)=>{let s=(2<<Math.log(t.length-1)/Math.LN2)-1,n=-~(1.6*s*e/t.length);return(i=e)=>{let o="";for(;;){let a=r(n),c=n|0;for(;c--;)if(o+=t[a[c]&s]||"",o.length===i)return o}}},rc=(t,e=21)=>tc(t,e,ec);const Os=/\r\n|[\n\r\u2028\u2029]/;function sc(t,e,r){const s=t.split(Os),n={start:Rs(e.start,s),end:e.end?Rs(e.end,s):void 0},{start:i,end:o,markerLines:a}=nc(n,s),c=`${o}`.length;return t.split(Os,o).slice(i,o).map((l,u)=>{const h=i+1+u,f=` ${` ${h}`.slice(-c)} |`,d=a[h],p=!a[h+1];if(!d)return` ${f}${l.length>0?` ${l}`:""}`;let g="";if(Array.isArray(d)){const y=l.slice(0,Math.max(d[0]-1,0)).replace(/[^\t]/g," "),w=d[1]||1;g=[`
7 `,f.replace(/\d/g," ")," ",y,"^".repeat(w)].join(""),p&&r&&(g+=" "+r)}return[">",f,l.length>0?` ${l}`:"",g].join("")}).join(`
8`)}function nc(t,e){const r={...t.start},s={...r,...t.end},n=2,i=3,o=r.line??-1,a=r.column??0,c=s.line,l=s.column;let u=Math.max(o-(n+1),0),h=Math.min(e.length,c+i);o===-1&&(u=0),c===-1&&(h=e.length);const f=c-o,d={};if(f)for(let p=0;p<=f;p++){const g=p+o;if(!a)d[g]=!0;else if(p===0){const y=e[g-1].length;d[g]=[a,y-a+1]}else if(p===f)d[g]=[0,l];else{const y=e[g-p].length;d[g]=[0,y]}}else a===l?a?d[o]=[a,0]:d[o]=!0:d[o]=[a,l-a];return{start:u,end:h,markerLines:d}}function Rs(t,e){let r=0;for(let s=0;s<e.length;s++){const n=e[s].length+1;if(r+n>t)return{line:s+1,column:t-r};r+=n}return{line:e.length,column:e[e.length-1]?.length??0}}const wr=5;
8class ic extends Error{response;statusCode=400;responseBody;traceId;details;constructor(e,r){const s=ai(e,r);super(s.message),Object.assign(this,s)}}class oc extends Error{response;statusCode=500;responseBody;traceId;details;constructor(e){const r=ai(e);super(r.message),Object.assign(this,r)}}function ai(t,e){const r=t.body,s={response:t,statusCode:t.statusCode,responseBody:uc(r,t),traceId:lc(t),message:"",details:void 0};if(!ri(r))return s.message=`${br(t,r)}${pe(s.traceId)}`,s;const n=r.error;if(typeof n=="string"&&typeof r.message=="string")return s.message=`${n} - ${r.message}${pe(s.traceId)}`,s;if(typeof n!="object"||n===null)return typeof n=="string"?s.message=`${n}${pe(s.traceId)}`:typeof r.message=="string"?s.message=`${r.message}${pe(s.traceId)}`:s.message=`${br(t,r)}${pe(s.traceId)}`,s;if(ac(n)||cc(n)){const i=n.items||[],o=i.slice(0,wr).map(c=>c.error?.description).filter(Boolean);let a=o.length?`:
9- ${o.join(`
10- `)}`:"";return i.length>wr&&(a+=`
11...and ${i.length-wr} more`),s.message=`${n.description}${pe(s.traceId)}${a}`,s.details=r.error,s}if(ci(n)){const i=e?.options?.query?.tag;return s.message=li(n,i,s.traceId),s.details=r.error,s}return"description"in n&&typeof n.description=="string"?(s.message=`${n.description}${pe(s.traceId)}`,s.details=n,s):(s.message=`${br(t,r)}${pe(s.traceId)}`,s)}function ac(t){return"type"in t&&t.type==="mutationError"&&"description"in t&&typeof t.description=="string"}function cc(t){return"type"in t&&t.type==="actionError"&&"description"in t&&typeof t.description=="string"}function ci(t){return ri(t)&&t.type==="queryParseError"&&typeof t.query=="string"&&typeof t.start=="number"&&typeof t.end=="number"}function li(t,e,r){const{query:s,start:n,end:i,description:o}=t,a=r?`
12(traceId: ${r})`:"";if(!s||typeof n>"u")return`GROQ query parse error: ${o}${a}`;const c=e?`
13
14Tag: ${e}`:"";return`GROQ query parse error:
15${sc(s,{start:n,end:i},o)}${c}${a}`}function br(t,e){const r=typeof e=="string"?` (${hc(e,100)})`:"",s=t.statusMessage?` ${t.statusMessage}`:"";return`${t.method}-request to ${t.url} resulted in HTTP ${t.statusCode}${s}${r}`}function lc(t){const e=t?.headers?.traceparent;if(e)return e.split("-")[1]}function uc(t,e){return(e.headers["content-type"]||"").toLowerCase().indexOf("application/json")!==-1?JSON.stringify(t,null,2):t}function pe(t){return t?` (traceId: ${t})`:""}function hc(t,e){return t.length>e?`${t.slice(0,e)}…`:t}class dc extends Error{projectId;addOriginUrl;constructor({projectId:e}){super("CorsOriginError"),this.name="CorsOriginError",this.projectId=e;const r=new URL(`https://sanity.io/manage/project/${e}/api`);if(typeof location<"u"){const{origin:s}=location;r.searchParams.set("cors","add"),r.searchParams.set("origin",s),this.addOriginUrl=r,this.message=`The current origin is not allowed to connect to the Live Content API. Add it here: ${r}`}else this.message=`The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${r}`}}const fc={onResponse:(t,e)=>{if(t.statusCode>=500)throw new oc(t);if(t.statusCode>=400)throw new ic(t,e);return t}};function pc(t={}){const e={},r=s=>t.ignoreWarnings===void 0?!1:(Array.isArray(t.ignoreWarnings)?t.ignoreWarnings:[t.ignoreWarnings]).some(n=>typeof n=="string"?s.includes(n):n instanceof RegExp?n.test(s):!1);return{onResponse:s=>{const n=s.headers["x-sanity-warning"],i=Array.isArray(n)?n:[n];for(const o of i)!o||e[o]||r(o)||(e[o]=!0,console.warn(o));return s}}}function js(t,e={}){return No([Yr({shouldRetry:gc}),...t,pc(e),Fo(),qo(),Vo(),fc,Ho({implementation:N})])}function gc(t,e,r){if(r.maxRetries===0)return!1;const s=r.method==="GET"||r.method==="HEAD",n=(r.uri||r.url).startsWith("/data/query"),i=t.response&&(t.response.statusCode===429||t.response.statusCode===502||t.response.statusCode===503);return(s||n)&&i?!0:Yr.shouldRetry(t,e,r)}const mc="https://www.sanity.io/help/";function ns(t){return mc+t}const Is=["image","file"],$s=["before","after","replace"],Ke=t=>{if(!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(t))throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters")},yc=t=>{if(!/^[-a-z0-9]+$/i.test(t))throw new Error("`projectId` can only contain only a-z, 0-9 and dashes")},vc=t=>{if(Is.indexOf(t)===-1)throw new Error(`Invalid asset type: ${t}. Must be one of ${Is.join(", ")}`)},at=(t,e)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t}() takes an object of properties`)},Ht=(t,e)=>{if(typeof e!="string"||!/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(e)||e.includes(".."))throw new Error(`${t}(): "${e}" is not a valid document ID`)},Ge=(t,e)=>{if(!e._id)throw new Error(`${t}() requires that the document contains an ID ("_id" property)`);Ht(t,e._id)},wc=(t,e)=>{if(typeof e!="string")throw new Error(`\`${t}()\`: \`${e}\` is not a valid document type`)},ui=(t,e)=>{if(!e._type)throw new Error(`\`${t}()\` requires that the document contains a type (\`_type\` property)`);wc(t,e._type)},bc=(t,e)=>{if(e._id&&e._id!==t)throw new Error(`The provided document ID (\`${e._id}
15\`) does not match the generated version ID (\`${t}\`)`)},_c=(t,e,r)=>{const s="insert(at, selector, items)";if($s.indexOf(t)===-1){const n=$s.map(i=>`"${i}"`).join(", ");throw new Error(`${s} takes an "at"-argument which is one of: ${n}`)}if(typeof e!="string")throw new Error(`${s} takes a "selector"-argument which must be a string`);if(!Array.isArray(r))throw new Error(`${s} takes an "items"-argument which must be an array`)},Ae=t=>{if(t.dataset)return t.dataset;const e=t.resource;if(e&&e.type==="dataset"){const r=e.id.split(".");if(r.length!==2)throw new Error('Dataset resource ID must be in the format "project.dataset"');return r[1]}throw new Error("`dataset` must be provided to perform queries")},hi=t=>{if(typeof t!="string"||!/^[a-z0-9._-]{1,75}$/i.test(t))throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");return t},di=t=>{const e=t.resource;if(!e)throw new Error("`resource` must be provided to perform resource queries");const{type:r,id:s}=e;switch(r){case"dataset":{if(s.split(".").length!==2)throw new Error('Dataset resource ID must be in the format "project.dataset"');return}case"dashboard":case"media-library":case"canvas":return;default:throw new Error(`Unsupported resource type: ${r.toString()}`)}},ee=(t,e)=>{if(e.resource)throw new Error(`\`${t}\` does not support resource-based operations`)};function Sc(t){let e=!1,r;return(...s)=>(e||(r=t(...s),e=!0),r)}const ue=t=>Sc((...e)=>console.warn(t.join(" "),...e)),Ec=ue(["Because you set `withCredentials` to true, we will override your `useCdn`","setting to be false since (cookie-based) credentials are never set on the CDN"]),kc=ue(["Since you haven't set a value for `useCdn`, we will deliver content using our","global, edge-cached API-CDN. If you wish to have content delivered faster, set","`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."]),xc=ue(["The Sanity client is configured with the `perspective` set to `drafts` or `previewDrafts`, which doesn't support the API-CDN.","The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."]),Ac=ue(["The `previewDrafts` perspective has been renamed to  `drafts` and will be removed in a future API version"]),Tc=ue(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",`See ${ns("js-client-browser-token")} for more information and how to hide this warning.`]),Cc=ue(["You have configured Sanity client to use a token, but also provided `withCredentials: true`.","This is no longer supported - only token will be used - remove `withCredentials: true`."]),Oc=ue(["Using the Sanity client without specifying an API version is deprecated.",`See ${ns("js-client-api-version")}`]),Rc=ue(["You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead."]),jc=ue(["The `~experimental_resource` configuration property has been renamed to `resource`.","Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version."]),Ic="apicdn.sanity.io",ct={apiHost:"https://api.sanity.io",apiVersion:"1",useProjectHostname:!0,stega:{enabled:!1}},$c=["localhost","127.0.0.1","0.0.0.0"],Pc=t=>$c.indexOf(t)!==-1;function Nc(t){if(t==="1"||t==="X")return;const e=new Date(t);if(!(/^\d{4}-\d{2}-\d{2}$/.test(t)&&e instanceof Date&&e.getTime()>0))throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`")}function fi(t){if(Array.isArray(t)&&t.length>1&&t.includes("raw"))throw new TypeError('Invalid API perspective value: "raw". The raw-perspective can not be combined with other perspectives')}const pi=(t,e)=>{const r={...e,...t,stega:{...typeof e.stega=="boolean"?{enabled:e.stega}:e.stega||ct.stega,...typeof t.stega=="boolean"?{enabled:t.stega}:t.stega||{}}};r.apiVersion||Oc();const s={...ct,...r};s["~experimental_resource"]&&!s.resource&&(jc(),s.resource=s["~experimental_resource"]);const n=s.resource,i=s.useProjectHostname&&!n;if(typeof Promise>
15"u"){const d=ns("js-client-promise-polyfill");throw new Error(`No native Promise-implementation found, polyfill needed - see ${d}`)}if(i&&!s.projectId)throw new Error("Configuration must contain `projectId`");if(n&&di(s),typeof s.perspective<"u"&&fi(s.perspective),"encodeSourceMap"in s)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?");if("encodeSourceMapAtPath"in s)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?");if(typeof s.stega.enabled!="boolean")throw new Error(`stega.enabled must be a boolean, received ${s.stega.enabled}`);if(s.stega.enabled&&s.stega.studioUrl===void 0)throw new Error("stega.studioUrl must be defined when stega.enabled is true");if(s.stega.enabled&&typeof s.stega.studioUrl!="string"&&typeof s.stega.studioUrl!="function")throw new Error(`stega.studioUrl must be a string or a function, received ${s.stega.studioUrl}`);const o=typeof window<"u"&&window.location&&window.location.hostname,a=o&&Pc(window.location.hostname),c=!!s.token;s.withCredentials&&c&&(Cc(),s.withCredentials=!1),o&&a&&c&&s.ignoreBrowserTokenWarning!==!0?Tc():typeof s.useCdn>"u"&&kc(),i&&yc(s.projectId),s.dataset&&Ke(s.dataset),"requestTagPrefix"in s&&(s.requestTagPrefix=s.requestTagPrefix?hi(s.requestTagPrefix).replace(/\.+$/,""):void 0),s.apiVersion=`${s.apiVersion}`.replace(/^v/,""),s.isDefaultApi=s.apiHost===ct.apiHost,s.useCdn===!0&&s.withCredentials&&Ec(),s.useCdn=s.useCdn!==!1&&!s.withCredentials,Nc(s.apiVersion);const l=s.apiHost.split("://",2),u=l[0],h=l[1],f=s.isDefaultApi?Ic:h;return i?(s.url=`${u}://${s.projectId}.${h}/v${s.apiVersion}`,s.cdnUrl=`${u}://${s.projectId}.${f}/v${s.apiVersion}`):(s.url=`${s.apiHost}/v${s.apiVersion}`,s.cdnUrl=s.url),s};class gi extends Error{name="ConnectionFailedError"}class Lc extends Error{name="DisconnectError";reason;constructor(e,r,s={}){super(e,s),this.reason=r}}class Uc extends Error{name="ChannelError";data;constructor(e,r){super(e),this.data=r}}class Dc extends Error{name="MessageError";data;constructor(e,r,s={}){super(e,s),this.data=r}}class Ps extends Error{name="MessageParseError"}const Mc=["channelError","disconnect"];function mi(t,e){return Qn(()=>{const r=t();return Ca(r)?r:Fe(r)}).pipe(ke(r=>Fc(r,e)))}function Fc(t,e){return new N(r=>{const s=e.includes("open"),n=e.includes("reconnect");function i(l){if("data"in l){const[u,h]=Ns(l);r.error(u?new Ps("Unable to parse EventSource error message",{cause:h}):new Dc((h?.data).message,h));return}t.readyState===t.CLOSED?r.error(new gi("EventSource connection failed")):n&&r.next({type:"reconnect"})}function o(){r.next({type:"open"})}function a(l){const[u,h]=Ns(l);if(u){r.error(new Ps("Unable to parse EventSource message",{cause:u}));return}if(l.type==="channelError"){const f=new URL(t.url).searchParams.get("tag");r.error(new Uc(qc(h?.data,f),h.data));return}if(l.type==="disconnect"){r.error(new Lc(`Server disconnected client: ${h.data?.reason||"unknown error"}`));return}r.next({type:l.type,id:l.lastEventId,...h.data?{data:h.data}:{}})}t.addEventListener("error",i),s&&t.addEventListener("open",o);const c=[...new Set([...Mc,...e])].filter(l=>l!=="error"&&l!=="open"&&l!=="reconnect");return c.forEach(l=>t.addEventListener(l,a)),()=>{t.removeEventListener("error",i),s&&t.removeEventListener("open",o),c.forEach(l=>t.removeEventListener(l,a)),t.close()}})}function Ns(t){try{const e=typeof t.data=="string"&&JSON.parse(t.data);return[null,{type:t.type,id:t.lastEventId,...Bc(e)?{}:{data:e}}]}catch(e){return[e,null]}}function qc(t,e){const r=t.error;return r?ci(r)?li(r,e):r.description?r.description:typeof r=="string"?r:JSON.stringify(r,null,2):t.message||"Unknown listener error"}function Bc(t){for(const e in t)return!1;return!0}function yi(t){if(typeof t=="string")return{id:t};if(Array.isArray(t))return{query:"*[_id in $ids]",params:{ids:t}};if(typeof t=="object"&&t!==null&&"query"in t&&typeof t.query=="string")return"params"in t&&typeof t.params=="object"&&t.params!==null?{query:t.query,params:t.params}:{query:t.query};const e=["* Document ID (<docId>)","* Array of document IDs","* Object containing `query`"].join(`
16`);throw new Error(`Unknown selection - must be one of:
17
18${e}`)}class vi{selection;operations;constructor(e,r={}){this.selection=e,this.operations=r}set(e){return this._assign("set",e)}setIfMissing(e){return this._assign("setIfMissing",e)}diffMatchPatch(e){return at("diffMatchPatch",e),this._assign("diffMatchPatch",e)}unset(e){if(!Array.isArray(e))throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");return this.operations=Object.assign({},this.operations,{unset:e}),this}inc(e){return this._assign("inc",e)}dec(e){return this._assign("dec",e)}insert(e,r,s){return _c(e,r,s),this._assign("insert",{[e]:r,items:s})}append(e,r){return this.insert("after",`${e}[-1]`,r)}prepend(e,r){return this.insert("before",`${e}[0]`,r)}splice(e,r,s,n){const i=typeof s>"u"||s===-1,o=r<0?r-1:r,a=i?-1:Math.max(0,r+s),c=o<0&&a>=0?"":a,l=`${e}[${o}:${c}]`;return this.insert("replace",l,n||[])}ifRevisionId(e){return this.operations.ifRevisionID=e,this}serialize(){return{...yi(this.selection),...this.operations}}toJSON(){return this.serialize()}reset(){return this.operations={},this}_assign(e,r,s=!0){return at(e,r),this.operations=Object.assign({},this.operations,{[e]:Object.assign({},s&&this.operations[e]||{},r)}),this}_set(e,r){return this._assign(e,r,!1)}}class xe extends vi{#e;constructor(e,r,s){super(e,r),this.#e=s}clone(){return new xe(this.selection,{...this.operations},this.#e)}commit(e){if(!this.#e)throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
18const r=typeof this.selection=="string",s=Object.assign({returnFirst:r,returnDocuments:!0},e);return this.#e.mutate({patch:this.serialize()},s)}}class ye extends vi{#e;constructor(e,r,s){super(e,r),this.#e=s}clone(){return new ye(this.selection,{...this.operations},this.#e)}commit(e){if(!this.#e)throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");const r=typeof this.selection=="string",s=Object.assign({returnFirst:r,returnDocuments:!0},e);return this.#e.mutate({patch:this.serialize()},s)}}const wi={returnDocuments:!1};class bi{operations;trxId;constructor(e=[],r){this.operations=e,this.trxId=r}create(e){return at("create",e),this._add({create:e})}createIfNotExists(e){const r="createIfNotExists";return at(r,e),Ge(r,e),this._add({[r]:e})}createOrReplace(e){const r="createOrReplace";return at(r,e),Ge(r,e),this._add({[r]:e})}delete(e){return Ht("delete",e),this._add({delete:{id:e}})}transactionId(e){return e?(this.trxId=e,this):this.trxId}serialize(){return[...this.operations]}toJSON(){return this.serialize()}reset(){return this.operations=[],this}_add(e){return this.operations.push(e),this}}class ar extends bi{#e;constructor(e,r,s){super(e,s),this.#e=r}clone(){return new ar([...this.operations],this.#e,this.trxId)}commit(e){if(!this.#e)throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return this.#e.mutate(this.serialize(),Object.assign({transactionId:this.trxId},wi,e||{}))}patch(e,r){const s=typeof r=="function",n=typeof e!="string"&&e instanceof ye,i=typeof e=="object"&&("query"in e||"id"in e);if(n)return this._add({patch:e.serialize()});if(s){const o=r(new ye(e,{},this.#e));if(!(o instanceof ye))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:o.serialize()})}if(i){const o=new ye(e,r||{},this.#e);return this._add({patch:o.serialize()})}return this._add({patch:{id:e,...r}})}}class cr extends bi{#e;constructor(e,r,s){super(e,s),this.#e=r}clone(){return new cr([...this.operations],this.#e,this.trxId)}commit(e){if(!this.#e)throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return this.#e.mutate(this.serialize(),Object.assign({transactionId:this.trxId},wi,e||{}))}patch(e,r){const s=typeof r=="function";if(typeof e!="string"&&e instanceof xe)return this._add({patch:e.serialize()});if(s){const n=r(new xe(e,{},this.#e));if(!(n instanceof xe))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:n.serialize()})}return this._add({patch:{id:e,...r}})}}const Hc="X-Sanity-Project-ID";function Vc(t,e={}){const r={};t.headers&&Object.assign(r,t.headers);const s=e.token||t.token;s&&(r.Authorization=`Bearer ${s}`),!e.useGlobalApi&&!t.useProjectHostname&&t.projectId&&(r[Hc]=t.projectId);const n=!!(typeof e.withCredentials>"u"?t.withCredentials:e.withCredentials),i=typeof e.timeout>"u"?t.timeout:e.timeout;return Object.assign({},e,{headers:Object.assign({},r,e.headers||{}),timeout:typeof i>"u"?300*1e3:i,proxy:e.proxy||t.proxy,json:!0,withCredentials:n,fetch:typeof e.fetch=="object"&&typeof t.fetch=="object"?{...t.fetch,...e.fetch}:e.fetch||t.fetch})}const _i=({query:t,params:e={},options:r={}})=>{const s=new URLSearchParams,{tag:n,includeMutations:i,returnQuery:o,...a}=r;n&&s.append("tag",n),s.append("query",t);for(const[c,l]of Object.entries(e))l!==void 0&&s.append(`$${c}`,JSON.stringify(l));for(const[c,l]of Object.entries(a))l&&s.append(c,`${l}`);return o===!1&&s.append("returnQuery","false"),i===!1&&s.append("includeMutations","false"),`?${s}`},Wc=(t,e)=>t===!1?void 0:typeof t>"u"?e:t,zc=(t={})=>({dryRun:t.dryRun,returnIds:!0,returnDocuments:Wc(t.returnDocuments,!0),visibility:t.visibility||"sync",autoGenerateArrayKeys:t.autoGenerateArrayKeys,skipCrossDatasetReferenceValidation:t.skipCrossDatasetReferenceValidation}),is=t=>t.type==="response",Kc=t=>t.body,Gc=(t,e)=>t.reduce((r,s)=>(r[e(s)]=s,r),Object.create(null)),Jc=11264;function Si(t,e,r,s,n={},i={}){const o="stega"in i?{...r||{},...typeof i.stega=="boolean"?{enabled:i.stega}:i.stega||{}}:r,a=o.enabled?Xa(n):n,c=i.filterResponse===!1?p=>p:p=>p.result,{cache:l,next:u,...h}={useAbortSignal:typeof i.signal<"u",resultSourceMap:o.enabled?"withKeyArraySelector":i.resultSourceMap,...i,returnQuery:i.filterResponse===!1&&i.returnQuery!==!1}
18,f=typeof l<"u"||typeof u<"u"?{...h,fetch:{cache:l,next:u}}:h,d=Te(t,e,"query",{query:s,params:a},f);return o.enabled?d.pipe(qa(_t(En(()=>import("./stegaEncodeSourceMap-_pIIFwxD.js"),__vite__mapDeps([0,1])).then(function(p){return p.stegaEncodeSourceMap$1}).then(({stegaEncodeSourceMap:p})=>p))),B(([p,g])=>{const y=g(p.result,p.resultSourceMap,o);return c({...p,result:y})})):d.pipe(B(c))}function Je(t,e,r,s={}){const n=(()=>{if(!s.releaseId)return r;const o=oi(r);if(!o){if(nr(r))throw new Error(`The document ID (\`${r}\`) is a draft, but \`options.releaseId\` is set as \`${s.releaseId}\``);return St(r,s.releaseId)}if(o!==s.releaseId)throw new Error(`The document ID (\`${r}\`) is already a version of \`${o}\` release, but this does not match the provided \`options.releaseId\` (\`${s.releaseId}\`)`);return r})(),i={uri:G(t,"doc",n),json:!0,tag:s.tag,signal:s.signal,query:s.includeAllVersions!==void 0?{includeAllVersions:s.includeAllVersions}:void 0};return kt(t,e,i).pipe(Xe(is),B(o=>{const a=o.body.documents;return a?s.includeAllVersions?a:a[0]:s.includeAllVersions?[]:void 0}))}function Ei(t,e,r,s={}){const n={uri:G(t,"doc",r.join(",")),json:!0,tag:s.tag,signal:s.signal};return kt(t,e,n).pipe(Xe(is),B(i=>{const o=Gc(i.body.documents||[],a=>a._id);return r.map(a=>o[a]||null)}))}function ki(t,e,r,s={}){return Te(t,e,"query",{query:"*[sanity::partOfRelease($releaseId)]",params:{releaseId:r}},s)}function xi(t,e,r,s){return Ge("createIfNotExists",r),lr(t,e,r,"createIfNotExists",s)}function Ai(t,e,r,s){return Ge("createOrReplace",r),lr(t,e,r,"createOrReplace",s)}function Ti(t,e,r,s,n){return Ge("createVersion",r),ui("createVersion",r),Rc(),I(t,e,{actionType:"sanity.action.document.version.create",publishedId:s,document:r},n)}function Ci(t,e,r,s,n,i,o){if(!s)throw new Error("`createVersion()` requires `baseId` when no `document` is provided");if(!r)throw new Error("`createVersion()` requires `publishedId` when `baseId` is provided");Ht("createVersion",s),Ht("createVersion",r);const a={actionType:"sanity.action.document.version.create",publishedId:r,baseId:s,versionId:n?St(r,n):ii(r),ifBaseRevisionId:i};return I(t,e,a,o)}function Oi(t,e,r,s){return Te(t,e,"mutate",{mutations:[{delete:yi(r)}]},s)}function Ri(t,e,r,s=!1,n){return I(t,e,{actionType:"sanity.action.document.version.discard",versionId:r,purge:s},n)}function ji(t,e,r,s){return Ge("replaceVersion",r),ui("replaceVersion",r),I(t,e,{actionType:"sanity.action.document.version.replace",document:r},s)}function Ii(t,e,r,s,n){return I(t,e,{actionType:"sanity.action.document.version.unpublish",versionId:r,publishedId:s},n)}function $i(t,e,r,s){let n;r instanceof ye||r instanceof xe?n={patch:r.serialize()}:r instanceof ar||r instanceof cr?n=r.serialize():n=r;const i=Array.isArray(n)?n:[n],o=s&&s.transactionId||void 0;return Te(t,e,"mutate",{mutations:i,transactionId:o},s)}function I(t,e,r,s){const n=Array.isArray(r)?r:[r],i=s&&s.transactionId||void 0,o=s&&s.skipCrossDatasetReferenceValidation||void 0,a=s&&s.dryRun||void 0;return Te(t,e,"actions",{actions:n,transactionId:i,skipCrossDatasetReferenceValidation:o,dryRun:a},s)}function Te(t,e,r,s,n={}){const i=r==="mutate",o=r==="actions",a=r==="query",c=i||o?"":_i(s),l=!i&&!o&&c.length<Jc,u=l?c:"",h=n.returnFirst,{timeout:f,token:d,tag:p,headers:g,returnQuery:y,lastLiveEventId:w,cacheMode:b}=n,v=G(t,r,u),S={method:l?"GET":"POST",uri:v,json:!0,body:l?void 0:s,query:i&&zc(n),timeout:f,headers:g,token:d,tag:p,returnQuery:y,perspective:n.perspective,resultSourceMap:n.resultSourceMap,lastLiveEventId:Array.isArray(w)?w[0]:w,cacheMode:b,canUseCdn:a,signal:n.signal,fetch:n.fetch,useAbortSignal:n.useAbortSignal,useCdn:n.useCdn};return kt(t,e,S).pipe(Xe(is),B(Kc),B(O=>{if(!i)return O;const A=O.results||[];if(n.returnDocuments)return h?A[0]&&A[0].document:A.map(H=>H.document);const $=h?"documentId":"documentIds",Ce=h?A[0]&&A[0].id:A.map(H=>H.id);return{transactionId:O.transactionId,results:A,[$]:Ce}}))}function lr(t,e,r,s,n={}){const i={[s]:r},o=Object.assign({returnFirst:!0,returnDocuments:!0},n);return Te(t,e,"mutate",{mutations:[i]},o)}const Et=t=>{const e=t.config();return e.dataset!==void 0&&e.projectId!==void 0||e.resource!==void 0},Pi=(t,e)=>Et(t)&&e.startsWith(G(t,"query")),Yc=(t,e)=>Et(t)&&e.startsWith(G(t,"mutate")),Xc=(t,e)=>Et(t)&&e.startsWith(G(t,"doc","")),Qc=(t,e)=>Et(t)&&e.startsWith(G(t,"listen")),Zc=(t,e)=>Et(t)&&e.startsWith(G(t,"history","")),el=(t,e)=>e.startsWith("/data/")||Pi(t,e)||Yc(t,e)||Xc(t,e)||Qc(t,e)||Zc(t,e);function kt(t,e,r){const s=r.url||r.uri,n=t.config(),i=typeof r.canUseCdn>"u"?["GET","HEAD"].indexOf(r.method||"GET")>=0&&el(t,s):r.canUseCdn;let o=(r.useCdn??n.useCdn)&&i;const a=r.tag&&n.requestTagPrefix?[n.requestTagPrefix,r.tag].join("."):r.tag||n.requestTagPrefix;if(a&&r.tag!==null&&(r.query={tag:hi(a),...r.query}),["GET","HEAD","POST"].indexOf(r.method||"GET")>=0&&Pi(t,s)){const u=r.resultSourceMap??n.resultSourceMap;u!==void 0&&u!==!1&&(r.query={resultSourceMap:u,...r.query});const h=r.perspective||n.perspective;typeof h<"u"&&(h==="previewDrafts"&&Ac(),fi(h),r.query={perspective:Array.isArray(h)?h.join(","):h,...r.query},(Array.isArray(h)&&h.length>0||h==="previewDrafts"||h==="drafts")&&o&&(o=!1,xc())),r.lastLiveEventId&&(r.query={...r.query,lastLiveEventId:r.lastLiveEventId}),r.returnQuery===!1&&(r.query={returnQuery:"false",...r.query}),o&&r.cacheMode=="noStale"&&(r.query={cacheMode:"noStale",...r.query})}const c=Vc(n,Object.assign({},r,{url:os(t,s,o)})),l=new N(u=>e(c,n.requester).subscribe(u));return r.signal?l.pipe(tl(r.signal)):l}function L(t,e,r){return kt(t,e,r).pipe(Xe(s=>s.type==="response"),B(s=>s.body))}function G(t,e,r){const s=t.config();if(s.resource){di(s);const o=nl(s),a=r!==void 0?`${e}/${r}`:e;return`${o}/${a}`.replace(/\/($|\?)/,"$1")}const n=Ae(s),i=`/${e}/${n}`;return`/data${r!==void 0?`${i}/${r}`:i}`.replace(/\/($|\?)/,"$1")}function os(t,e,r=!1){const{url:s,cdnUrl:n}=t.config();return`${r?n:s}/${e.replace(/^\//,"")}`}function tl(t){return e=>new N(r=>{const s=()=>r.error(sl(t));if(t&&t.aborted){s();return}const n=e.subscribe(r);return t.addEventListener("abort",s),()=>{t.removeEventListener("abort",s),n.unsubscribe()}})}const rl=!!globalThis.DOMException;function sl(t){if(rl)return new DOMException(t?.reason??"The operation was aborted.","AbortError");const e=new Error(t?.reason??"The operation was aborted.");return e.name="AbortError",e}const nl=t=>{const e=t.resource;if(!e)throw new Error("`resource` must be provided to perform resource queries");const{type:r,id:s}=e;switch(r){case"dataset":{const n=s.split(".");if(n.length!==2)throw new Error('Dataset ID must be in the format "project.dataset"');return`/projects/${n[0]}/datasets/${n[1]}`}case"canvas":return`/canvases/${s}`;case"media-library":return`/media-libraries/${s}`;case"dashboard":return`/dashboards/${s}`;default:throw new Error(`Unsupported resource type: ${r.toString()}`)}};function Ni(t,e,r){const s=Ae(t.config());return L(t,e,{method:"POST",uri:`/agent/action/generate/${s}`,body:r})}function il(t,e,r){const s=Ae(t.config());return L(t,e,{method:"POST",uri:`/agent/action/patch/${s}`,body:r})}function ol(t,e,r){const s=Ae(t.config());return L(t,e,{method:"POST",uri:`/agent/action/prompt/${s}`,body:r})}function Li(t,e,r){const s=Ae(t.config());return L(t,e,{method:"POST",uri:`/agent/action/transform/${s}`,body:r})}function Ui(t,e,r){const s=Ae(t.config());return L(t,e,{method:"POST",uri:`/agent/action/translate/${s}`,body:r})}class al{#e;#t;constructor(e,r){this.#e=e,this.#t=r}generate(e){return Ni(this.#e,this.#t,e)}transform(e){return Li(this.#e,this.#t,e)}translate(e){return Ui(this.#e,this.#t,e)}}class cl{#e;#t;constructor(e,r){this.#e=e,this.#t=r}generate(e){return T(Ni(this.#e,this.#t,e))}transform(e){return T(Li(this.#e,this.#t,e))}translate(e){return T(Ui(this.#e,this.#t,e))}prompt(e){return T(ol(this.#e,this.#t,e))}patch(e){return T(il(this.#e,this.#t,e))}}class ll{#e;#t;constructor(e,r){this.#e=e,this.#t=r}upload(e,r,s){return Di(this.#e,this.#t,e,r,s)}}class ul{#e;#t;constructor(e,r){this.#e=e,this.#t=r}upload(e,r,s){const n=Di(this.#e,this.#t,e,r,s);return T(n.pipe(Xe(i=>i.type==="response"),B(i=>i.body.document)))}}function Di(t,e,r,s,n={}){vc(r);let i=n.extract||void 0;i&&!i.length&&(i=["none"]);const o=t.config(),a=dl(n,s),{tag:c,label:l,title:u,description:h,creditLine:f,filename:d,source:p}=a,g=o.resource?.type==="media-library",y=g?{title:u,filename:d}:{label:l,title:u,description:h,filename:d,meta:i,creditLine:f};return p&&!g&&(y.sourceId=p.id,y.sourceName=p.name,y.sourceUrl=p.url),kt(t,e,{tag:c,method:"POST",timeout:a.timeout||0,uri:hl(o,r),headers:a.contentType?{"Content-Type":a.contentType}:{},query:y,body:s})}function hl(t,e){const r=e==="image"?"images":"files",s=t.resource;if(s){const{type:i,id:o}=s;switch(i){case"dataset":throw new Error("Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead.");case"canvas":return`/canvases/${o}/assets/${r}`;case"media-library":return`/media-libraries/${o}/upload`;case"dashboard":return`/dashboards/${o}/assets/${r}`;default:throw new Error(`Unsupported resource type: ${i.toString()}`)}}const n=Ae(t);return`assets/${r}/${n}`}function dl(t,e){return typeof File>"u"||!(e instanceof File)?t:Object.assign({filename:t.preserveFilename===!1?void 0:e.name,contentType:e.type},t)}var fl=(t,e)=>Object.keys(e).concat(Object.keys(t)).reduce((r,s)=>(r[s]=typeof t[s]>"u"?e[s]:t[s],r),{});const pl=(t,e)=>e.reduce((r,s)=>(typeof t[s]>"u"||(r[s]=t[s]),r),{}),Mi=Qn(()=>En(()=>import("./browser-D9sIT06I.js").then(t=>
18t.b),__vite__mapDeps([2,1]))).pipe(B(({default:t})=>t),Ba(1));function Fi(){return function(t){return t.pipe(qt((e,r)=>e instanceof gi?La(Fe({type:"reconnect"}),Ua(1e3).pipe(ke(()=>r))):Jn(()=>e)))}}const gl=14800,ml=["includePreviousRevision","includeResult","includeMutations","includeAllVersions","visibility","effectFormat","enableResume","tag"],yl={includeResult:!0};function qi(t,e,r={}){const{url:s,token:n,withCredentials:i,requestTagPrefix:o,headers:a}=this.config(),c=r.tag&&o?[o,r.tag].join("."):r.tag,l={...fl(r,yl),tag:c},u=pl(l,ml),h=_i({query:t,params:e,options:{tag:c,...u}}),f=`${s}${G(this,"listen",h)}`;if(f.length>gl)return Jn(()=>new Error("Query too large for listener"));const d=l.events?l.events:["mutation"],p={};return i&&(p.withCredentials=!0),(n||a)&&(p.headers={},n&&(p.headers.Authorization=`Bearer ${n}`),a&&Object.assign(p.headers,a)),mi(()=>(typeof EventSource>"u"||p.headers?Mi:Fe(EventSource)).pipe(B(g=>new g(f,p))),d).pipe(Fi(),Xe(g=>d.includes(g.type)),B(g=>({type:g.type,..."data"in g?g.data:{}})))}function vl(t,e){return wl(typeof t=="function"?{predicate:t,...e}:t)}function wl(t){return e=>{let r,s=!1;const{predicate:n,...i}=t,o=e.pipe(Ha(c=>{t.predicate(c)&&(s=!0,r=c)}),ei(()=>{s=!1,r=void 0}),ti(i)),a=new N(c=>{s&&c.next(r),c.complete()});return Da(o,a)}}const Ls="2021-03-25";class Bi{#e;constructor(e){this.#e=e}events({includeDrafts:e=!1,tag:r,waitFor:s}={}){const{projectId:n,apiVersion:i,token:o,withCredentials:a,requestTagPrefix:c,headers:l}=this.#e.config(),u=i.replace(/^v/,"");if(u!=="X"&&u<Ls)throw new Error(`The live events API requires API version ${Ls} or later. The current API version is ${u}. Please update your API version to use this feature.`);if(e&&!o&&!a)throw new Error("The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.");const h=G(this.#e,"live/events"),f=new URL(this.#e.getUrl(h,!1)),d=r&&c?[c,r].join("."):r;d&&f.searchParams.set("tag",d),e&&f.searchParams.set("includeDrafts","true"),s&&f.searchParams.set("waitFor",s);const p={};e&&a&&(p.withCredentials=!0),(e&&o||l)&&(p.headers={},e&&o&&(p.headers.Authorization=`Bearer ${o}`),l&&Object.assign(p.headers,l));const g=`${f.href}::${JSON.stringify(p)}`,y=_r.get(g);if(y)return y;const w=mi(()=>(typeof EventSource>"u"||p.headers?Mi:Fe(EventSource)).pipe(B(S=>new S(f.href,p))),["message","restart","welcome","reconnect","goaway"]),b=bl(f,{method:"OPTIONS",mode:"cors",credentials:p.withCredentials?"include":"omit",headers:p.headers}).pipe(qt(()=>{throw new dc({projectId:n})})),v=w.pipe(Fi(),ke(S=>S.type==="reconnect"?b.pipe(ke(()=>Fe(S))):Fe(S)),qt(S=>b.pipe(ke(()=>{throw S}))),B(S=>{if(S.type==="message"){const{data:O,...A}=S;return{...A,tags:O.tags}}return S})).pipe(ei(()=>_r.delete(g)),vl({predicate:S=>S.type==="welcome"}));return _r.set(g,v),v}}function bl(t,e){return new N(r=>{const s=new AbortController,n=s.signal;return fetch(t,{...e,signal:s.signal}).then(i=>{r.next(i),r.complete()},i=>{n.aborted||r.error(i)}),()=>s.abort()})}const _r=new Map;class _l{#e;#t;constructor(e,r){this.#e=e,this.#t=r}create(e,r){return qe(this.#e,this.#t,"PUT",e,r)}edit(e,r){return qe(this.#e,this.#t,"PATCH",e,r)}delete(e){return qe(this.#e,this.#t,"DELETE",e)}list(){ee("dataset",this.#e.config());const e=this.#e.config(),r=e.projectId;let s="/datasets";return e.useProjectHostname===!1&&(s=`/projects/${r}/datasets`),L(this.#e,this.#t,{uri:s,tag:null})}getEmbeddingsSettings(e){return ee("dataset",this.#e.config()),Ke(e),L(this.#e,this.#t,{uri:Vt(this.#e,e),tag:null})}editEmbeddingsSettings(e,r){return ee("dataset",this.#e.config()),Ke(e),L(this.#e,this.#t,{method:"PUT",uri:Vt(this.#e,e),body:r,tag:null})}}class Sl{#e;#t;constructor(e,r){this.#e=e,this.#t=r}create(e,r){return ee("dataset",this.#e.config()),T(qe(this.#e,this.#t,"PUT",e,r))}edit(e,r){return ee("dataset",this.#e.config()),T(qe(this.#e,this.#t,"PATCH",e,r))}delete(e){return ee("dataset",this.#e.config()),T(qe(this.#e,this.#t,"DELETE",e))}list(){ee("dataset",this.#e.config());const e=this.#e.config(),r=e.projectId;let s="/datasets";return e.useProjectHostname===!1&&(s=`/projects/${r}/datasets`),T(L(this.#e,this.#t,{uri:s,tag:null}))}getEmbeddingsSettings(e){return ee("dataset",this.#e.config()),Ke(e),T(L(this.#e,this.#t,{uri:Vt(this.#e,e),tag:null}))}editEmbeddingsSettings(e,r){return ee("dataset",this.#e.config()),Ke(e),T(L(this.#e,this.#t,{method:"PUT",uri:Vt(this.#e,e),body:r,tag:null}))}}function Vt(t,e){const r=t.config();return r.useProjectHostname===!1?`/projects/${r.projectId}/datasets/${e}/settings/embeddings`:`/datasets/${e}/settings/embeddings`}function qe(t,e,r,s,n){return ee("dataset",t.config()),Ke(s),L(t,e,{method:r,uri:`/datasets/${s}`,body:n,tag:null})}class Hi{#e;#t;constructor(e,r){this.#e=e,this.#t=r}getPlaybackInfo(e,r={}){const s=this.#e.config(),n=(s.resource||s["~experimental_resource"])?.id,{instanceId:i,library
18Id:o}=Al(e),a=o||n;if(!a)throw new Error("Could not determine Media Library ID - you need to provide a valid Media Library ID in the client config or a Media Library GDR");const c=Tl(i,a),l=Cl(r);return L(this.#e,this.#t,{method:"GET",uri:c,query:l})}}class El{#e;#t;constructor(e,r){this.#e=e,this.#t=r}getPlaybackInfo(e,r={}){return T(new Hi(this.#e.observable,this.#t).getPlaybackInfo(e,r))}}const kl=/^media-library:(ml[^:]+):([^:]+)$/;function xl(t){return typeof t=="object"&&"_ref"in t}function Al(t){const e=xl(t)?t._ref:t,r=kl.exec(e);if(r){const[,s,n]=r;return{libraryId:s,instanceId:n}}if(typeof t=="string"&&t.startsWith("video-"))return{instanceId:t};throw new Error(`Invalid video asset instance identifier "${e}": must be a valid video instance id or a Global Dataset Reference (GDR) to the video asset in the Media Library`)}function Tl(t,e){return`/media-libraries/${e}/video/${t}/playback-info`}function Cl(t){const e={};if(t.transformations){const{thumbnail:r,animated:s,storyboard:n}=t.transformations;r&&(r.width&&(e.thumbnailWidth=r.width),r.height&&(e.thumbnailHeight=r.height),r.time!==void 0&&(e.thumbnailTime=r.time),r.fit&&(e.thumbnailFit=r.fit),r.format&&(e.thumbnailFormat=r.format)),s&&(s.width&&(e.animatedWidth=s.width),s.height&&(e.animatedHeight=s.height),s.start!==void 0&&(e.animatedStart=s.start),s.end!==void 0&&(e.animatedEnd=s.end),s.fps&&(e.animatedFps=s.fps),s.format&&(e.animatedFormat=s.format)),n&&n.format&&(e.storyboardFormat=n.format)}return t.expiration&&(e.expiration=t.expiration),e}class Ol{#e;#t;constructor(e,r){this.#e=e,this.#t=r}list(e){const r={},s="/projects";return e?.includeMembers===!1&&(r.includeMembers="false"),e?.includeFeatures===!1&&(r.includeFeatures="false"),e?.organizationId&&(r.organizationId=e.organizationId),e?.onlyExplicitMembership&&(r.onlyExplicitMembership="true"),L(this.#e,this.#t,{uri:s,query:r})}getById(e){return L(this.#e,this.#t,{uri:`/projects/${e}`})}}class Rl{#e;#t;constructor(e,r){this.#e=e,this.#t=r}list(e){const r={},s="/projects";return e?.includeMembers===!1&&(r.includeMembers="false"),e?.includeFeatures===!1&&(r.includeFeatures="false"),e?.organizationId&&(r.organizationId=e.organizationId),e?.onlyExplicitMembership&&(r.onlyExplicitMembership="true"),T(L(this.#e,this.#t,{uri:s,query:r}))}getById(e){return T(L(this.#e,this.#t,{uri:`/projects/${e}`}))}}const Us=rc("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",8),Wt=(t,e)=>e?St(t,e):ii(t);function zt(t,{releaseId:e,publishedId:r,document:s}){if(r&&s._id){const n=Wt(r,e);return bc(n,s),n}if(s._id){const n=nr(s._id),i=ir(s._id);if(!n&&!i)throw new Error(`\`${t}()\` requires a document with an \`_id\` that is a version or draft ID`);if(e){if(n)throw new Error(`\`${t}()\` was called with a document ID (\`${s._id}\`) that is a draft ID, but a release ID (\`${e}\`) was also provided.`);const o=oi(s._id);if(o!==e)throw new Error(`\`${t}()\` was called with a document ID (\`${s._id}\`) that is a version ID, but the release ID (\`${e}\`) does not match the document's version ID (\`${o}\`).`)}return s._id}if(r)return Wt(r,e);throw new Error(`\`${t}()\` requires either a publishedId or a document with an \`_id\``)}const jl=(t,e)=>{if(typeof t=="object"&&t!==null&&("releaseId"in t||"metadata"in t)){const{releaseId:r=Us(),metadata:s={}}=t;return[r,s,e]}return[Us(),{},t]},Vi=(t,e)=>{const[r,s,n]=jl(t,e),i={...s,releaseType:s.releaseType||"undecided"};return{action:{actionType:"sanity.action.release.create",releaseId:r,metadata:i},options:n}};class Il{#e;#t;constructor(e,r){this.#e=e,this.#t=r}get({releaseId:e},r){return Je(this.#e,this.#t,`_.releases.${e}`,r)}create(e,r){const{action:s,options:n}=Vi(e,r),{releaseId:i,metadata:o}=s;return I(this.#e,this.#t,s,n).pipe(B(a=>({...a,releaseId:i,metadata:o})))}edit({releaseId:e,patch:r},s){const n={actionType:"sanity.action.release.edit",releaseId:e,patch:r};return I(this.#e,this.#t,n,s)}publish({releaseId:e},r){const s={actionType:"sanity.action.release.publish",releaseId:e};return I(this.#e,this.#t,s,r)}archive({releaseId:e},r){const s={actionType:"sanity.action.release.archive",releaseId:e};return I(this.#e,this.#t,s,r)}unarchive({releaseId:e},r){const s={actionType:"sanity.action.release.unarchive",releaseId:e};return I(this.#e,this.#t,s,r)}schedule({releaseId:e,publishAt:r},s){const n={actionType:"sanity.action.release.schedule",releaseId:e,publishAt:r};return I(this.#e,this.#t,n,s)}unschedule({releaseId:e},r){const s={actionType:"sanity.action.release.unschedule",releaseId:e};return I(this.#e,this.#t,s,r)}delete({releaseId:e},r){const s={actionType:"sanity.action.release.delete",releaseId:e};return I(this.#e,this.#t,s,r)}fetchDocuments({releaseId:e},r){return ki(this.#e,this.#t,e,r)}}class $l{#e;#t;constructor(e,r){this.#e=e,this.#t=r}get({releaseId:e},r){return T(Je(this.#e,this.#t,`_.releases.${e}`,r))}async create(e,r){const{action:s,options:n}=Vi(e,r),{releaseId:i,metadata:o}=s;return{...await T(I(this.#e,this.#t,s,n)),releaseId:i,metadata:o}}edit({releaseId:e,patch:r},s){const n={actionType:"sanity.action.release.edit",releaseId:e,patch:r};return T(I(this.#e,this.#t,n,s))}publish({releaseId:e},r){const s={actionType:"sanity.action.release.publish",releaseId:e};return T(I(this.#e,this.#t,s,r))}archive({releaseId:e},r){const s={actionType:"sanity.action.release.archive",releaseId:e};return T(I(this.#e,this.#t,s,r))}unarchive({releaseId:e},r){const s={actionType:"sanity.action.release.unarchive",releaseId:e};return T(I(this.#e,this.#t,s,r))}schedule({releaseId:e,publishAt:r},s){const n={actionType:"sanity.action.release.schedule",releaseId:e,publishAt:r};return T(I(this.#e,this.#t,n,s))}unschedule({releaseId:e},r){const s={actionType:"sanity.action.release.unschedule",releaseId:e};return T(I(this.#e,this.#t,s,r))}delete({releaseId:e},r){const s={actionType:"sanity.action.release.delete",releaseId:e};return T(I(this.#e,this.#t,s,r))}fetchDocuments({releaseId:e},r){return T(ki(this.#e,this.#t,e,r))}}class Pl{#e;#t;constructor(e,r){this.#e=e,this.#t=r}getById(e){return L(this.#e,this.#t,{uri:`/users/${e}`})}}class Nl{#e;#t;constructor(e,r){this.#e=e,this.#t=r}getById(e){return T(L(this.#e,this.#t,{uri:`/users/${e}`}))}}class Kt{assets;datasets;live;mediaLibrary;projects;users;agent;releases;#e;#t;#r;listen=qi;constructor(e,r=ct){this.config(r),this.#t=e;const s=r._requestHandler;this.#r=s?(()=>{let n;return(i,o)=>{const a=i;return n||(n=new Be(e,{...r,_requestHandler:void 0})),s(a,c=>e(c,o),n)}})():e,this.assets=new ll(this,this.#r),this.datasets=new _l(this,this.#r),this.live=new Bi(this),this.mediaLibrary={video:new Hi(this,this.#r)},this.projects=new Ol(this,this.#r),this.users=new Pl(this,this.#r),this.agent={action:new al(this,this.#r)},this.releases=new Il(this,this.#r)}clone(){return new Kt(this.#t,this.config())}config(e){if(e===void 0)return{...this.#e};if(this.#e&&this.#e.allowReconfigure===!1)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return this.#e=pi(e,this.#e||{}),this}withConfig(e){const r=this.config();return new Kt(this.#t,{...r,...e,stega:{...r.stega||{},...typeof e?.stega=="boolean"?{enabled:e.stega}:e?.stega||{}}})}fetch(e,r,s){return Si(this,this.#r,this.#e.stega,e,r,s)}getDocument(e,r){if(r?.includeAllVersions===!0)return Je(this,this.#r,e,{...r,includeAllVersions:!0});const s={signal:r?.signal,tag:r?.tag,releaseId:r?.releaseId,...r&&"includeAllVersions"in r?{includeAllVersions:!1}:{}};return Je(this,this.#r,e,s)}getDocuments(e,r){return Ei(this,this.#r,e,r)}create(e,r){return lr(this,this.#r,e,"create",r)}createIfNotExists(e,r){return xi(this,this.#r,e,r)}createOrReplace(e,r){return Ai(this,this.#r,e,r)}createVersion({document:e,publishedId:r,releaseId:s,baseId:n,ifBaseRevisionId:i},o){if(!e)return Ci(this,this.#r,r,n,s,i,o);const a=zt("createVersion",{document:e,publishedId:r,releaseId:s}),c={...e,_id:a},l=r||or(e._id);return Ti(this,this.#r,c,l,o)}delete(e,r){return Oi(this,this.#r,e,r)}discardVersion({releaseId:e,publishedId:r},s,n){const i=Wt(r,e);return Ri(this,this.#r,i,s,n)}replaceVersion({document:e,publishedId:r,releaseId:s},n){const i=zt("replaceVersion",{document:e,publishedId:r,releaseId:s}),o={...e,_id:i};return ji(this,this.#r,o,n)}unpublishVersion({releaseId:e,publishedId:r},s){const n=St(r,e);return Ii(this,this.#r,n,r,s)}mutate(e,r){return $i(this,this.#r,e,r)}patch(e,r){return new xe(e,r,this)}transaction(e){return new cr(e,this)}action(e,r){return I(this,this.#r,e,r)}request(e){return L(this,this.#r,e)}getUrl(e,r){return os(this,e,r)}getDataUrl(e,r){return G(this,e,r)}}class Be{assets;datasets;live;mediaLibrary;projects;users;agent;releases;observable;#e;#t;#r;listen=qi;constructor(e,r=ct){this.config(r),this.#t=e;const s=r._requestHandler;this.#r=s?(()=>{let n;return(i,o)=>{const a=i;return n||(n=new Be(e,{...r,_requestHandler:void 0})),s(a,c=>e(c,o),n)}})():e,this.assets=new ul(this,this.#r),this.datasets=new Sl(this,this.#r),this.live=new Bi(this),this.mediaLibrary={video:new El(this,this.#r)},this.projects=new Rl(this,this.#r),this.users=new Nl(this,this.#r),this.agent={action:new cl(this,this.#r)}
18,this.releases=new $l(this,this.#r),this.observable=new Kt(e,r)}clone(){return new Be(this.#t,this.config())}config(e){if(e===void 0)return{...this.#e};if(this.#e&&this.#e.allowReconfigure===!1)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return this.observable&&this.observable.config(e),this.#e=pi(e,this.#e||{}),this}withConfig(e){const r=this.config();return new Be(this.#t,{...r,...e,stega:{...r.stega||{},...typeof e?.stega=="boolean"?{enabled:e.stega}:e?.stega||{}}})}fetch(e,r,s){return T(Si(this,this.#r,this.#e.stega,e,r,s))}getDocument(e,r){if(r?.includeAllVersions===!0)return T(Je(this,this.#r,e,{...r,includeAllVersions:!0}));const s={signal:r?.signal,tag:r?.tag,releaseId:r?.releaseId,...r&&"includeAllVersions"in r?{includeAllVersions:!1}:{}};return T(Je(this,this.#r,e,s))}getDocuments(e,r){return T(Ei(this,this.#r,e,r))}create(e,r){return T(lr(this,this.#r,e,"create",r))}createIfNotExists(e,r){return T(xi(this,this.#r,e,r))}createOrReplace(e,r){return T(Ai(this,this.#r,e,r))}createVersion({document:e,publishedId:r,releaseId:s,baseId:n,ifBaseRevisionId:i},o){if(!e)return yr(Ci(this,this.#r,r,n,s,i,o));const a=zt("createVersion",{document:e,publishedId:r,releaseId:s}),c={...e,_id:a},l=r||or(e._id);return yr(Ti(this,this.#r,c,l,o))}delete(e,r){return T(Oi(this,this.#r,e,r))}discardVersion({releaseId:e,publishedId:r},s,n){const i=Wt(r,e);return T(Ri(this,this.#r,i,s,n))}replaceVersion({document:e,publishedId:r,releaseId:s},n){const i=zt("replaceVersion",{document:e,publishedId:r,releaseId:s}),o={...e,_id:i};return yr(ji(this,this.#r,o,n))}unpublishVersion({releaseId:e,publishedId:r},s){const n=St(r,e);return T(Ii(this,this.#r,n,r,s))}mutate(e,r){return T($i(this,this.#r,e,r))}patch(e,r){return new ye(e,r,this)}transaction(e){return new ar(e,this)}action(e,r){return T(I(this,this.#r,e,r))}request(e){return T(L(this,this.#r,e))}dataRequest(e,r,s){return T(Te(this,this.#r,e,r,s))}getUrl(e,r){return os(this,e,r)}getDataUrl(e,r){return G(this,e,r)}}function Ll(t,e){return{requester:js(t),createClient:r=>{const s=js(t,{ignoreWarnings:r.ignoreWarnings});return new e((n,i)=>(i||s)({maxRedirects:0,maxRetries:r.maxRetries,retryDelay:r.retryDelay,lineage:r.lineage,...n}),r)}}}var Ul=[];const Dl=Ll(Ul,Be),Ml=Dl.createClient,Cf=Ml({projectId:"en6fw1xz",dataset:"production",apiVersion:"2024-01-01",useCdn:!1}),Ds="image-Tb9Ew8CXIwaY6R1kjMvI0uRR-2000x3000-jpg";function Fl(t){const[,e,r,s]=t.split("-");if(!e||!r||!s)throw new Error(`Malformed asset _ref '${t}'. Expected an id like "${Ds}".`);const[n,i]=r.split("x"),o=+n,a=+i;if(!(isFinite(o)&&isFinite(a)))throw new Error(`Malformed asset _ref '${t}'. Expected an id like "${Ds}".`);return{id:e,width:o,height:a,format:s}}const ql=t=>{const e=t;return e?typeof e._ref=="string":!1},Bl=t=>{const e=t;return e?typeof e._id=="string":!1},Hl=t=>{const e=t;return e&&e.asset?typeof e.asset.url=="string":!1},Vl=t=>{if(typeof t=="object"&&t!==null){const e=t;return e._upload&&(!e.asset||!e.asset._ref)}return!1};function Wl(t){if(!t)return null;let e;if(typeof t=="string"&&zl(t))e={asset:{_ref:Ms(t)}};else if(typeof t=="string")e={asset:{_ref:t}};else if(ql(t))e={asset:t};else if(Bl(t))e={asset:{_ref:t._id||""}};else if(Hl(t))e={asset:{_ref:Ms(t.asset.url)}};else if(typeof t.asset=="object")e={...t};else return null;const r=t;return r.crop&&(e.crop=r.crop),r.hotspot&&(e.hotspot=r.hotspot),Kl(e)}function zl(t){return/^https?:\/\//.test(`${t}`)}function Ms(t){return`image-${t.split("/").slice(-1)[0]}`.replace(/\.([a-z]+)$/,"-$1")}function Kl(t){if(t.crop&&t.hotspot)return t;const e={...t};return e.crop||(e.crop={left:0,top:0,bottom:0,right:0}),e.hotspot||(e.hotspot={x:.5,y:.5,height:1,width:1}),e}const Wi=[["width","w"],["height","h"],["format","fm"],["download","dl"],["blur","blur"],["sharpen","sharp"],["invert","invert"],["orientation","or"],["minHeight","min-h"],["maxHeight","max-h"],["minWidth","min-w"],["maxWidth","max-w"],["quality","q"],["fit","fit"],["crop","crop"],["saturation","sat"],["auto","auto"],["dpr","dpr"],["pad","pad"],["frame","frame"]];function Gl(t){let e={...t||{}};const r=e.source;delete e.source;const s=Wl(r);if(!s){if(r&&Vl(r))return"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8HwQACfsD/QNViZkAAAAASUVORK5CYII=";throw new Error(`Unable to resolve image URL from source (${JSON.stringify(r)})`)}const n=s.asset._ref||s.asset._id||"",i=Fl(n),o=Math.round(s.crop.left*i.width),a=Math.round(s.crop.top*i.height),c={left:o,top:a,width:Math.round(i.width-s.crop.right*i.width-o),height:Math.round(i.height-s.crop.bottom*i.height-a)},l=s.hotspot.height*i.height/2,u=s.hotspot.width*i.width/2,h=s.hotspot.x*i.width,f=s.hotspot.y*i.height,d={left:h-u,top:f-l,right:h+u,bottom:f+l};return e.rect||e.focalPoint||e.ignoreImageParams||e.crop||(e={...e,...Yl({crop:c,hotspot:d},e)}),Jl({...e,asset:i})}function Jl(t){const e=(t.baseUrl||"https://cdn.sanity.io").replace(/\/+$/,""),r=t.vanityName?`/${t.vanityName}`:"",s=`${t.asset.id}-${t.asset.width}x${t.asset.height}.${t.asset.format}${r}`;let n;t.mediaLibraryId?n=`${e}/media-libraries/${t.mediaLibraryId}/images/${s}`:t.canvasId?n=`${e}/images/canvases/${t.canvasId}/${s}`:n=`${e}/images/${t.projectId}/${t.dataset}/${s}`;const i=[];if(t.rect){const{left:a,top:c,width:l,height:u}=t.rect;(a!==0||c!==0||u!==t.asset.height||l!==t.asset.width)&&i.push(`rect=${a},${c},${l},${u}`)}
18t.bg&&i.push(`bg=${t.bg}`),t.focalPoint&&(i.push(`fp-x=${t.focalPoint.x}`),i.push(`fp-y=${t.focalPoint.y}`));const o=[t.flipHorizontal&&"h",t.flipVertical&&"v"].filter(Boolean).join("");return o&&i.push(`flip=${o}`),Wi.forEach(a=>{const[c,l]=a;typeof t[c]<"u"?i.push(`${l}=${encodeURIComponent(t[c])}`):typeof t[l]<"u"&&i.push(`${l}=${encodeURIComponent(t[l])}`)}),i.length===0?n:`${n}?${i.join("&")}`}function Yl(t,e){let r;const s=e.width,n=e.height;if(!(s&&n))return{width:s,height:n,rect:t.crop};const i=t.crop,o=t.hotspot,a=s/n;if(i.width/i.height>a){const c=Math.round(i.height),l=Math.round(c*a),u=Math.max(0,Math.round(i.top)),h=Math.round((o.right-o.left)/2+o.left);let f=Math.max(0,Math.round(h-l/2));f<i.left?f=i.left:f+l>i.left+i.width&&(f=i.left+i.width-l),r={left:f,top:u,width:l,height:c}}else{const c=i.width,l=Math.round(c/a),u=Math.max(0,Math.round(i.left)),h=Math.round((o.bottom-o.top)/2+o.top);let f=Math.max(0,Math.round(h-l/2));f<i.top?f=i.top:f+l>i.top+i.height&&(f=i.top+i.height-l),r={left:u,top:f,width:c,height:l}}return{width:s,height:n,rect:r}}const Xl=["clip","crop","fill","fillmax","max","scale","min"],Ql=["top","bottom","left","right","center","focalpoint","entropy"],Zl=["format"];function eu(t){return t&&"config"in t?typeof t.config=="function":!1}function tu(t){return t&&"clientConfig"in t?typeof t.clientConfig=="object":!1}function Fs(t){const{apiHost:e,projectId:r,dataset:s}=t,n={baseUrl:(e||"https://api.sanity.io").replace(/^https:\/\/api\./,"https://cdn.")},i=t.resource??t["~experimental_resource"];if(i?.type==="media-library"){if(typeof i.id!="string"||i.id.length===0)throw new Error('Media library clients must include an id in "resource"');return{...n,mediaLibraryId:i.id}}if(i?.type==="canvas"){if(typeof i.id!="string"||i.id.length===0)throw new Error('Canvas clients must include an id in "resource"');return{...n,canvasId:i.id}}if(i?.type==="dataset"){if(typeof i.id!="string"||i.id.length===0)throw new Error('Dataset clients must include an id in "resource"');const[o,a]=i.id.split(".");if(!o||!a)throw new Error('Dataset resource id must be in the format "projectId.dataset", got: '+i.id);return{...n,projectId:o,dataset:a}}return{...n,projectId:r,dataset:s}}function ru(t){const e=Wi;for(const r of e){const[s,n]=r;if(t===s||t===n)return s}return t}function zi(t){let e={};return eu(t)?e=Fs(t.config()):tu(t)?e=Fs(t.clientConfig):e=t||{},e}function su(t,e){const r=zi(e);return new t(null,r)}function Of(t){return su(Gt,t)}function nu(t,e){const r=e.baseUrl||t.baseUrl,s={baseUrl:r};for(const n in e)if(e.hasOwnProperty(n)){const i=ru(n);s[i]=e[n]}return{baseUrl:r,...s}}class Gt{options;constructor(e,r){this.options=e?{...e.options||{},...r||{}}:{...r||{}}}withOptions(e){const r=nu(this.options,e);return new Gt(this,r)}image(e){return this.withOptions({source:e})}dataset(e){return this.withOptions({dataset:e})}projectId(e){return this.withOptions({projectId:e})}withClient(e){const r=zi(e),s={...this.options};return delete s.baseUrl,delete s.projectId,delete s.dataset,delete s.mediaLibraryId,delete s.canvasId,new Gt(null,{...r,...s})}bg(e){return this.withOptions({bg:e})}dpr(e){return this.withOptions(e&&e!==1?{dpr:e}:{})}width(e){return this.withOptions({width:e})}height(e){return this.withOptions({height:e})}focalPoint(e,r){return this.withOptions({focalPoint:{x:e,y:r}})}maxWidth(e){return this.withOptions({maxWidth:e})}minWidth(e){return this.withOptions({minWidth:e})}maxHeight(e){return this.withOptions({maxHeight:e})}minHeight(e){return this.withOptions({minHeight:e})}size(e,r){return this.withOptions({width:e,height:r})}blur(e){return this.withOptions({blur:e})}sharpen(e){return this.withOptions({sharpen:e})}rect(e,r,s,n){return this.withOptions({rect:{left:e,top:r,width:s,height:n}})}format(e){return this.withOptions({format:e})}invert(e){return this.withOptions({invert:e})}orientation(e){return this.withOptions({orientation:e})}quality(e){return this.withOptions({quality:e})}forceDownload(e){return this.withOptions({download:e})}flipHorizontal(){return this.withOptions({flipHorizontal:!0})}flipVertical(){return this.withOptions({flipVertical:!0})}ignoreImageParams(){return this.withOptions({ignoreImageParams:!0})}fit(e){if(Xl.indexOf(e)===-1)throw new Error(`Invalid fit mode "${e}"`);return this.withOptions({fit:e})}crop(e){if(Ql.indexOf(e)===-1)throw new Error(`Invalid crop mode "${e}"`);return this.withOptions({crop:e})}saturation(e){return this.withOptions({saturation:e})}auto(e){if(Zl.indexOf(e)===-1)throw new Error(`Invalid auto mode "${e}"`);return this.withOptions({auto:e})}pad(e){return this.withOptions({pad:e})}vanityName(e){return this.withOptions({vanityName:e})}frame(e){if(e!==1)throw new Error(`Invalid frame value "${e}"`);return this.withOptions({frame:e})}
18url(){return Gl(this.options)}toString(){return this.url()}}const iu=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ou=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,r,s)=>s?s.toUpperCase():r.toLowerCase()),qs=t=>{const e=ou(t);return e.charAt(0).toUpperCase()+e.slice(1)},Ki=(...t)=>t.filter((e,r,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===r).join(" ").trim();var au={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const cu=D.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:n="",children:i,iconNode:o,...a},c)=>D.createElement("svg",{ref:c,...au,width:e,height:e,stroke:t,strokeWidth:s?Number(r)*24/Number(e):r,className:Ki("lucide",n),...a},[...o.map(([l,u])=>D.createElement(l,u)),...Array.isArray(i)?i:[i]]));const he=(t,e)=>{const r=D.forwardRef(({className:s,...n},i)=>D.createElement(cu,{ref:i,iconNode:e,className:Ki(`lucide-${iu(qs(t))}`,`lucide-${t}`,s),...n}));return r.displayName=qs(t),r};const lu=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Sr=he("chevron-down",lu);const uu=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["line",{x1:"21.17",x2:"12",y1:"8",y2:"8",key:"a0cw5f"}],["line",{x1:"3.95",x2:"8.54",y1:"6.06",y2:"14",key:"1kftof"}],["line",{x1:"10.88",x2:"15.46",y1:"21.94",y2:"14",key:"1ymyh8"}]],hu=he("chrome",uu);const du=[["path",{d:"M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z",key:"1jg4f8"}]],Er=he("facebook",du);const fu=[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]],pu=he("github",fu);const gu=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],mu=he("globe",gu);const yu=[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"5",ry:"5",key:"2e1cvw"}],["path",{d:"M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z",key:"9exkf1"}],["line",{x1:"17.5",x2:"17.51",y1:"6.5",y2:"6.5",key:"r4j83e"}]],kr=he("instagram",yu);const vu=[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]],wu=he("mail",vu);const bu=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],_u=he("x",bu);const Su=[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]],xr=he("youtube",Su),Eu=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class as extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class ku extends as{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Bs extends as{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Hs extends as{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Lr;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Lr||(Lr={}));class xu{constructor(e,{headers:r={},customFetch:s,region:n=Lr.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=Eu(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Rn(this,arguments,void 0,function*(r,s={}){var n;let i,o;try{const{headers:a,method:c,body:l,signal:u,timeout:h}=s;let f={},{region:d}=s;d||(d=this.region);const p=new URL(`${this.url}/${r}`);d&&d!=="any"&&(f["x-region"]=d,p.searchParams.set("forceFunctionRegion",d));let g;
18l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=l):typeof l=="string"?(f["Content-Type"]="text/plain",g=l):typeof FormData<"u"&&l instanceof FormData?g=l:(f["Content-Type"]="application/json",g=JSON.stringify(l)):l&&typeof l!="string"&&!(typeof Blob<"u"&&l instanceof Blob)&&!(l instanceof ArrayBuffer)&&!(typeof FormData<"u"&&l instanceof FormData)?g=JSON.stringify(l):g=l;let y=u;h&&(o=new AbortController,i=setTimeout(()=>o.abort(),h),u?(y=o.signal,u.addEventListener("abort",()=>o.abort())):y=o.signal);const w=yield this.fetch(p.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:y}).catch(O=>{throw new ku(O)}),b=w.headers.get("x-relay-error");if(b&&b==="true")throw new Bs(w);if(!w.ok)throw new Hs(w);let v=((n=w.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),S;return v==="application/json"?S=yield w.json():v==="application/octet-stream"||v==="application/pdf"?S=yield w.blob():v==="text/event-stream"?S=w:v==="multipart/form-data"?S=yield w.formData():S=yield w.text(),{data:S,error:null,response:w}}catch(a){return{data:null,error:a,response:a instanceof Hs||a instanceof Bs?a.context:void 0}}finally{i&&clearTimeout(i)}})}}const Gi=3,Vs=t=>Math.min(1e3*2**t,3e4),Au=[520,503],Ji=["GET","HEAD","OPTIONS"];var Tu=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.co
18de=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Ws(t,e){return new Promise(r=>{if(e?.aborted){r();return}const s=setTimeout(()=>{e?.removeEventListener("abort",n),r()},t);function n(){clearTimeout(s),r()}e?.addEventListener("abort",n)})}function Cu(t,e,r,s){return!(!s||r>=Gi||!Ji.includes(t)||!Au.includes(e))}var Ou=class{constructor(t){var e,r,s,n,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(s=t.shouldStripNulls)!==null&&s!==void 0?s:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,this.retryEnabled=(i=t.retry)!==null&&i!==void 0?i:!0,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const s=this.fetch;let i=(async()=>{let o=0;for(;;){const l=new Headers(r.headers);o>0&&l.set("X-Retry-Count",String(o));let u;try{u=await s(r.url.toString(),{method:r.method,headers:l,body:JSON.stringify(r.body,(h,f)=>typeof f=="bigint"?f.toString():f),signal:r.signal})}catch(h){if(h?.name==="AbortError"||h?.code==="ABORT_ERR"||!Ji.includes(r.method))throw h;if(r.retryEnabled&&o<Gi){const f=Vs(o);o++,await Ws(f,r.signal);continue}throw h}if(Cu(r.method,u.status,o,r.retryEnabled)){var a,c;const h=(a=(c=u.headers)===null||c===void 0?void 0:c.get("Retry-After"))!==null&&a!==void 0?a:null,f=h!==null?Math.max(0,parseInt(h,10)||0)*1e3:Vs(o);await u.text(),o++,await Ws(f,r.signal);continue}return await r.processResponse(u)}})();return this.shouldThrowOnError||(i=i.catch(o=>{var a;let c="",l="",u="";const h=o?.cause;if(h){var f,d,p,g;const b=(f=h?.message)!==null&&f!==void 0?f:"",v=(d=h?.code)!==null&&d!==void 0?d:"";c=`${(p=o?.name)!==null&&p!==void 0?p:"FetchError"}: ${o?.message}`,c+=`
19
20Caused by: ${(g=h?.name)!==null&&g!==void 0?g:"Error"}: ${b}`,v&&(c+=` (${v})`),h?.stack&&(c+=`
21${h.stack}`)}else{var y;c=(y=o?.stack)!==null&&y!==void 0?y:""}const w=this.url.toString().length;return o?.name==="AbortError"||o?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(l+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(a=o?.name)!==null&&a!==void 0?a:"FetchError"}: ${o?.message}`,details:c,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}async processResponse(t){var e=this;let r=null,s=null,n=null,i=t.status,o=t.statusText;if(t.ok){var a,c;if(e.method!=="HEAD"){var l;const f=await t.text();f===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((l=e.headers.get("Accept"))===null||l===void 0)&&l.includes("application/vnd.pgrst.plan+text"))?s=f:s=JSON.parse(f))}const u=(a=e.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),h=(c=t.headers.get("content-range"))===null||c===void 0?void 0:c.split("/");u&&h&&h.length>1&&(n=parseInt(h[1])),e.isMaybeSingle&&Array.isArray(s)&&(s.length>1?(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,i=406,o="Not Acceptable"):s.length===1?s=s[0]:s=null)}else{const u=await t.text();try{r=JSON.parse(u),Array.isArray(r)&&t.status===404&&(s=[],r=null,i=200,o="OK")}catch{t.status===404&&u===""?(i=204,o="No Content"):r={message:u}}if(r&&e.shouldThrowOnError)throw new Tu(r)}return{success:r===null,error:r,data:s,count:n,status:i,statusText:o}}returns(){return this}overrideTypes(){return this}},Ru=class extends Ou{select(t){let e=!1;const r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
21explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var o;const a=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const zs=new RegExp("[,()]");var Pe=class extends Ru{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&zs.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&zs.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");const i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},ju=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3,retry:i}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET";let i=!1;const o=(t??"*").split("").map(l=>/\s/.test(l)&&!i?"":(l==='"'&&(i=!i),l)).join(""),{url:a,headers:c}=this.cloneRequestState();return a.searchParams.set("select",o),s&&c.append("Prefer",`count=${s}`),new Pe({method:n,url:a,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){const a=t.reduce((c,l)=>c.concat(Object.keys(l)),[]);if(a.length>
210){const c=[...new Set(a)].map(l=>`"${l}"`);i.searchParams.set("columns",c.join(","))}}return new Pe({method:n,url:i,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const o="POST",{url:a,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),n||c.append("Prefer","missing=default"),Array.isArray(t)){const l=t.reduce((u,h)=>u.concat(Object.keys(h)),[]);if(l.length>0){const u=[...new Set(l)].map(h=>`"${h}"`);a.searchParams.set("columns",u.join(","))}}return new Pe({method:o,url:a,headers:c,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Pe({method:s,url:n,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Pe({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function ft(t){"@babel/helpers - typeof";return ft=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ft(t)}function Iu(t,e){if(ft(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ft(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function $u(t){var e=Iu(t,"string");return ft(e)=="symbol"?e:e+""}function Pu(t,e,r){return(e=$u(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ks(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function Ot(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ks(Object(r),!0).forEach(function(s){Pu(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ks(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Nu=class Yi{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:o=8e3,retry:a}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=o;const c=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(l,u)=>{const h=new AbortController,f=setTimeout(()=>h.abort(),i),d=u?.signal;if(d){if(d.aborted)return clearTimeout(f),c(l,u);const p=()=>{clearTimeout(f),h.abort()};return d.addEventListener("abort",p,{once:!0}),c(l,Ot(Ot({},u),{},{signal:h.signal})).finally(()=>{clearTimeout(f),d.removeEventListener("abort",p)})}return c(l,Ot(Ot({},u),{},{signal:h.signal})).finally(()=>clearTimeout(f))}:this.fetch=c,this.retry=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ju(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new Yi(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var o;let a;const c=new URL(`${this.url}/rpc/${e}`);let l;const u=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(u)),h=s&&Object.values(r).some(u);h?(a="POST",l=r):s||n?(a=s?"HEAD":"GET",Object.entries(r).filter(([d,p])=>p!==void 0).map(([d,p])=>[d,Array.isArray(p)?`{${p.join(",")}}`:`${p}
21`]).forEach(([d,p])=>{c.searchParams.append(d,p)})):(a="POST",l=r);const f=new Headers(this.headers);return h?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new Pe({method:a,url:c,headers:f,schema:this.schemaName,body:l,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class Lu{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};const s=typeof global<"u"?global:void 0;if(s&&typeof s.WebSocket<"u")return{type:"native",wsConstructor:s.WebSocket};if(typeof globalThis<"u"&&typeof r.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&r.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const n=globalThis.process;if(n){const i=n.versions;if(i&&i.node){const o=i.node,a=parseInt(o.replace(/^v/,"").split(".")[0]);return a>=22?typeof globalThis.WebSocket<"u"?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${a} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${a} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
22import ws from "ws"
23new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
24
25Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const Uu="2.105.4",Du=`realtime-js/${Uu}`,Mu="1.0.0",Xi="2.0.0",Fu=Xi,qu=1e4,Bu=100,ge={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Qi={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Ur={connecting:"connecting",closing:"closing",closed:"closed"};class Hu{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},o=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,s){var n,i;const o=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",c=(i=e.join_ref)!==null&&i!==void 0?i:"",l=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=Object.keys(u).length===0?"":JSON.stringify(u);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const f=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+a.length+o.length+l.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+f);let p=new DataView(d),g=0;p.setUint8(g++,this.KINDS.userBroadcastPush),p.setUint8(g++,c.length),p.setUint8(g++,a.length),p.setUint8(g++,o.length),p.setUint8(g++,l.length),p.setUint8(g++,h.length),p.setUint8(g++,r),Array.from(c,w=>
25p.setUint8(g++,w.charCodeAt(0))),Array.from(a,w=>p.setUint8(g++,w.charCodeAt(0))),Array.from(o,w=>p.setUint8(g++,w.charCodeAt(0))),Array.from(l,w=>p.setUint8(g++,w.charCodeAt(0))),Array.from(h,w=>p.setUint8(g++,w.charCodeAt(0)));var y=new Uint8Array(d.byteLength+s.byteLength);return y.set(new Uint8Array(d),0),y.set(new Uint8Array(s),d.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){const s=JSON.parse(e),[n,i,o,a,c]=s;return r({join_ref:n,ref:i,topic:o,event:a,payload:c})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;if(s===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,s){const n=r.getUint8(1),i=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4);let c=this.HEADER_LENGTH+4;const l=s.decode(e.slice(c,c+n));c=c+n;const u=s.decode(e.slice(c,c+i));c=c+i;const h=s.decode(e.slice(c,c+o));c=c+o;const f=e.slice(c,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(s.decode(f)):f,p={type:this.BROADCAST_EVENT,event:u,payload:d};return o>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}var R;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(R||(R={}));const Gs=(t,e,r={})=>{var s;const n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=Vu(o,t,e,n),i),{}):{}},Vu=(t,e,r,s)=>{const n=e.find(a=>a.name===t),i=n?.type,o=r[t];return i&&!s.includes(i)?Zi(i,o):Dr(o)},Zi=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return Gu(e,r)}switch(t){case R.bool:return Wu(e);case R.float4:case R.float8:case R.int2:case R.int4:case R.int8:case R.numeric:case R.oid:return zu(e);case R.json:case R.jsonb:return Ku(e);case R.timestamp:return Ju(e);case R.abstime:case R.date:case R.daterange:case R.int4range:case R.int8range:case R.money:case R.reltime:case R.text:case R.time:case R.timestamptz:case R.timetz:case R.tsrange:case R.tstzrange:return Dr(e);default:return Dr(e)}},Dr=t=>t,Wu=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},zu=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Ku=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Gu=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i;const o=t.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>Zi(e,a))}return t},Ju=t=>typeof t=="string"?t.replace(" ","T"):t,eo=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var lt=t=>typeof t=="function"?t:function(){return t},Yu=typeof self<"u"?self:null,Ne=typeof window<"u"?window:null,Z=Yu||Ne||globalThis,Xu="2.0.0",Qu=1e4,Zu=1e3,te={connecting:0,open:1,closing:2,closed:3},V={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ie={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Mr={longpoll:"longpoll",websocket:"websocket"},eh={complete:4},Fr="base64url.bearer.phx.",Rt=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHo
vendor: 8,368 bytes, line 25
25oks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},to=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},th=class{constructor(t,e,r){this.state=V.closed,this.topic=t,this.params=lt(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Rt(this,ie.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new to(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=V.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=V.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=V.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=V.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Rt(this,ie.leave,lt({}),this.timeout).send(),this.state=V.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(ie.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=V.closed,this.bindings=[]}onClose(t){this.on(ie.close,t)}onError(t){return this.on(ie.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new Rt(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=V.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(ie.close,"leave")},r=new Rt(this,ie.leave,lt({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=V.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;o<i.length;o++)i[o].callback(n,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===V.closed}isErrored(){return this.state===V.errored}isJoined(){return this.state===V.joined}isJoining(){return this.state===V.joining}isLeaving(){return this.state===V.leaving}},Jt=class{static request(t,e,r,s,n,i,o){if(Z.XDomainRequest){let a=new Z.XDomainRequest;return this.xdomainRequest(a,t,e,s,n,i,o)}else if(Z.XMLHttpRequest){let a=new Z.XMLHttpRequest;return this.xhrRequest(a,t,e,r,s,n,i,o)}else{if(Z.fetch&&Z.AbortController)return this.fetchRequest(t,e,r,s,n,i,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,n,i,o){let a={method:t,headers:r,body:s},c=null;return n&&(c=new AbortController,setTimeout(()=>c.abort(),n),a.signal=c.signal),Z.fetch(e,a).then(l=>l.text()).then(l=>this.parseJSON(l)).then(l=>o&&o(l)).catch(l=>{l.name==="AbortError"&&i?i():o&&o(null)}),c}static xdomainRequest(t,e,r,s,n,i,o){return t.timeout=n,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,i,o,a){t.open(e,r,!0),t.timeout=i;for(let[c,l]of Object.entries(s))t.setRequestHeader(c,l);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===eh.complete&&a){let c=this.parseJSON(t.responseText);a(c)}},o&&(t.ontimeout=o),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,i=t[s];typeof i=="object"?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},rh=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(r[n]);return btoa(e)},Oe=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Fr)&&(this.authToken=atob(e[1].slice(Fr.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=te.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Mr.websocket),"$1/"+Mr.longpoll)}endpointURL(){return Jt.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=te.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===te.open||this.readyState===te.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;
25if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=te.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=rh(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
26`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=te.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let i,o=()=>{this.reqs.delete(i),s()};i=Jt.request(t,this.endpointURL(),e,r,this.timeout,o,a=>{this.reqs.delete(i),this.isActive()&&n(a)}),this.reqs.add(i)}},sh=class it{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=it.syncState(this.state,n,i,o),this.pendingDiffs.forEach(c=>{this.state=it.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],a()}),this.channel.on(s.diff,n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=it.syncDiff(this.state,n,i,o),a())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return it.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let i=this.clone(e),o={},a={};return this.map(i,(c,l)=>{r[c]||(a[c]=l)}),this.map(r,(c,l)=>{let u=i[c];if(u){let h=l.metas.map(g=>g.phx_ref),f=u.metas.map(g=>g.phx_ref),d=l.metas.filter(g=>f.indexOf(g.phx_ref)<0),p=u.metas.filter(g=>h.indexOf(g.phx_ref)<0);d.length>0&&(o[c]=l,o[c].metas=d),p.length>0&&(a[c]=this.clone(u),a[c].metas=p)}else o[c]=l}),this.syncDiff(i,{joins:o,leaves:a},s,n)}static syncDiff(e,r,s,n){let{joins:i,leaves:o}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(i,(a,c)=>{let l=e[a];if(e[a]=this.clone(c),l){let u=e[a].metas.map(f=>f.phx_ref),h=l.metas.filter(f=>u.indexOf(f.phx_ref)<0);e[a].metas.unshift(...h)}s(a,l,c)}),this.map(o,(a,c)=>{let l=e[a];if(!l)return;let u=c.metas.map(h=>h.phx_ref);l.metas=l.metas.filter(h=>u.indexOf(h.phx_ref)<0),n(a,l,c),l.metas.length===0&&delete e[a]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static clone(e){return JSON.parse(JSON.stringify(e))}},jt={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,i,o]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:i,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:i}=t,o=this.META_LENGTH+e.length+r.length+n.length+s.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),c=new DataView(a),l=0;c.setUint8(l++,this.KINDS.push),c.setUint8(l++,e.length),c.setUint8(l++,r.length),c.setUint8(l++,n.length),c.setUint8(l++,s.length),Array.from(e,h=>c.setUint8(l++,h.charCodeAt(0))),Array.from(r,h=>c.setUint8(l++,h.charCodeAt(0))),Array.from(n,h=>c.setUint8(l++,h.charCodeAt(0))),Array.from(s,h=>c.setUint8(l++,h.charCodeAt(0)));var u=new Uint8Array(a.byteLength+i.byteLength);return u.set(new Uint8Array(a),0),u.set(new Uint8Array(i),a.byteLength),u.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(o,o+s));o=o+s;let c=r.decode(t.slice(o,o+n));o=o+n;let l=r.decode(t.slice(o,o+i));o=o+i;let u=t.slice(o,t.byteLength);return{join_ref:a,ref:null,topic:c,event:l,payload:u}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,c=r.decode(t.slice(a,a+s));a=a+s;let l=r.decode(t.slice(a,a+n));a=a+n;let u=r.decode(t.slice(a,a+i));a=a+i;let h=r.decode(t.slice(a,a+o));a=a+o;let f=t.slice(a,t.byteLength),d={status:h,response:f};return{join_ref:c,ref:l,topic:u,event:ie.reply,payload:d}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=this.HEADER_LENGTH+2,o=r.decode(t.slice(i,i+s));i=i+s;let a=r.decode(t.slice(i,i+n));i=i+n;let c=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:c}}},nh=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Qu,this.transport=e.transport||Z.WebSocket||Oe,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=Z&&Z.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=jt.encode.bind(jt),this.defaultDecoder=jt.decode.bind(jt),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Oe?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;Ne&&Ne.addEventListener&&(Ne.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),s=this.connectClock)}),Ne.addEventListener("pageshow",n=>{s===this.connectClock&&(s=null,this.connect())}),Ne.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,o)=>{console.log(`${n}: ${i}`,o)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=lt(e.params||{}),this.endPoint=`${t}/${Mr.websocket}`,this.vsn=e.vsn||Xu,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new to(()=>
26{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return Oe}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Jt.appendParams(Jt.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=lt(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Oe?this.connectWithF
vendor: 4,353 bytes, line 26
26allback(Oe,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(n=>{n.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){return t===Oe?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Fr}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,i,o=this.transportName(t),a=c=>{this.log("transport",`falling back to ${o}...`,c),this.off([n,i]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),i=this.onError(c=>{this.log("transport","error",c),s&&!r&&(clearTimeout(this.fallbackTimer),a(c))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let c=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${c}`,"true"),this.log("transport",`established ${c} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(c=>{this.log("transport","connected to primary after",c),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Zu,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===te.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}
26triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(ie.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case te.connecting:return"connecting";case te.open:return"open";case te.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new th(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:n,join_ref:i}=t;this.log("push",`${e} ${r} (${i}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:i,join_ref:o}=e;if(i&&i===this.pendingHeartbeatRef){const a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",a)}catch(c){this.log("error","error in heartbeat callback",c)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${i&&"("+i+")"||""}`.trim(),n);for(let a=0;a<this.channels.length;a++){const c=this.channels[a];c.isMember(r,s,n,o)&&c.trigger(s,n,i,o)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class ut{constructor(e,r){const s=oh(r);this.presence=new sh(e.getChannel(),s),this.presence.onJoin((n,i,o)=>{const a=ut.onJoinPayload(n,i,o);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,i,o)=>{const a=ut.onLeavePayload(n,i,o);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return ut.transformState(this.presence.state)}static transformState(e){return e=ih(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=Dt(n),r},{})}static onJoinPayload(e,r,s){const n=Js(r),i=Dt(s);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,r,s){const n=Js(r),i=Dt(s);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function Dt(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function ih(t){return JSON.parse(JSON.stringify(t))}function oh(t){return t?.events&&{events:t.events}}function Js(t){return t?.metas?Dt(t):[]}var Ys;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Ys||(Ys={}));class ah{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new ut(this.channel.channelAdapter,r)}}function ch(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t;
26if(typeof e.code=="number"){const r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}class lh{constructor(e,r,s){const n=uh(s);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,s){let n;try{n=this.channel.push(e,r,s)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>Bu){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===ge.joined}isJoined(){return this.state===ge.joined}isJoining(){return this.state===ge.joining}isClosed(){return this.state===ge.closed}isLeaving(){return this.state===ge.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function uh(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Xs;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Xs||(Xs={}));var De;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(De||(De={}));var oe;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(oe||(oe={}));class ht{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new lh(this.socket.socketAdapter,e,this.params),this.presence=new ah(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=eo(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var s,n,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:o,presence:a,private:c}}=this.params,l=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(d=>d.filter))!==null&&n!==void 0?n:[],u=!!this.bindings[De.PRESENCE]&&this.bindings[De.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},f={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:l,private:c};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(d=>{e?.(oe.CHANNEL_ERROR,ch(d))}),this._onClose(()=>e?.(oe.CLOSED)),this.updateJoinPayload(Object.assign({config:f},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:d})=>{if(this.socket._isManualToken()||this.socket.setAuth(),d===void 0){e?.(oe.SUBSCRIBED);return}this._updatePostgresBindings(d,e)}).receive("error",d=>{this.state=ge.errored;const p=Object.values(d).join(", ")||"error";e?.(oe.CHANNEL_ERROR,new Error(p,{cause:d}))}).receive("timeout",()=>{e?.(oe.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const n=this.bindings.postgres_changes,i=(s=n?.length)!==null&&s!==void 0?s:0,o=[];for(let a=0;a<i;
26a++){const c=n[a],{filter:{event:l,schema:u,table:h,filter:f}}=c,d=e&&e[a];if(d&&d.event===l&&ht.isFilterValueEqual(d.schema,u)&&ht.isFilterValueEqual(d.table,h)&&ht.isFilterValueEqual(d.filter,f))o.push(Object.assign(Object.assign({},c),{id:d.id}));else{this.unsubscribe(),this.state=ge.errored,r?.(oe.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=ge.errored&&r&&r(oe.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){const n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===De.PRESENCE||e===De.POSTGRES_CHANGES;if(n&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject(new Error("Payload is required for httpSend()"));const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let c=a.statusText;try{const l=await a.json();c=l.error||l.message||c}catch{}return Promise.reject(new Error(c))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated 
26in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const l=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=l.body)===null||n===void 0?void 0:n.cancel()),l.ok?"ok":"error"}catch(l){return l instanceof Error&&l.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,c;const l=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),l.receive("ok",()=>i("ok")),l.receive("error",()=>i("error")),l.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){const n=new AbortController,i=setTimeout(()=>n.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),o}_on(e,r,s){const n=e.toLocaleLowerCase(),i=this.channelAdapter.on(e,s),o={type:n,filter:r,callback:s,ref:i};return this.bindings[n]?this.bindings[n].push(o):this.bindings[n]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,i,o,a,c,l,u;const h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;const f=(n=this.bindings[h])===null||n===void 0?void 0:n.find(d=>d.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in f){const d=f.id,p=(i=f.filter)===null||i===void 0?void 0:i.event;return d&&((o=r.ids)===null||o===void 0?void 0:o.includes(d))&&(p==="*"||p?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{const d=(l=(c=f?.filter)===null||c===void 0?void 0:c.event)===null||l===void 0?void 0:l.toLocaleLowerCase();return d==="*"||d===((u=r?.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){const{close:s,error:n,leave:i,join:o}=Qi;return r&&[s,n,i,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){const n=r.data,{schema:i,table:o,commit_timestamp:a,type:c,errors:l}=n;return Object.assign(Object.assign({},{schema:i,table:o,commit_timestamp:a,eventType:c,new:{},old:{},errors:l}),this._getPayloadRecords(n))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Gs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Gs(e.columns,e.old_record)),r}}class hh{constructor(e,r){this.socket=new nh(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Ur.connecting}isDisconnecting(){return this.socket.connectionState()==Ur.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const Qs={HEARTBEAT_INTERVAL:25e3},dh=[1e3,2e3,5e3,1e4],fh=1e4;function ph(){const t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function gh(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return ph()}const mh=`
27  addEventListener("message", (e) => {
28    if (e.data.event === "start") {
29      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
30    }
31  });`;class yh{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var s;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={}
31,this.ref=0,this.serializer=new Hu,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...o)=>i(...o):(...o)=>fetch(...o),!(!((s=r?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;const n=this._initializeOptions(r);this.socketAdapter=new hh(e,n),this.httpEndpoint=eo(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const r=e.message;throw r.includes("Node.js")?new Error(`${r}
32
33To use Realtime in Node.js, you need to provide a WebSocket implementation:
34
35Option 1: Use Node.js 22+ which has native WebSocket support
36Option 2: Install and provide the "ws" package:
37
38  npm install ws
39
40  import ws from "ws"
41  const client = new RealtimeClient(url, {
42    ...options,
43    transport: ws
44  })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){const e=this.channels.map(async s=>{const n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}connectionState(){return this.socketAdapter.connectionState()||Ur.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{const i=new ht(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}
44this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const i={access_token:r,version:Du};r&&n.updateJoinPayload(i),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Qi.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,s)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([mh],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,i,o,a,c,l,u,h,f,d;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e?.accessToken)!==null&&s!==void 0?s:null;const p={};p.timeout=(n=e?.timeout)!==null&&n!==void 0?n:qu,p.heartbeatIntervalMs=(i=e?.heartbeatIntervalMs)!==null&&i!==void 0?i:Qs.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(o=e?.disconnectOnEmptyChannelsAfterMs)!==null&&o!==void 0?o:2*((a=e?.heartbeatIntervalMs)!==null&&a!==void 0?a:Qs.HEARTBEAT_INTERVAL),p.transport=(c=e?.transport)!==null&&c!==void 0?c:Lu.getWebSocketConstructor(),p.params=e?.params,p.logger=e?.logger,p.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),p.sessionStorage=(l=e?.sessionStorage)!==null&&l!==void 0?l:gh(),p.reconnectAfterMs=(u=e?.reconnectAfterMs)!==null&&u!==void 0?u:(b=>dh[b-1]||fh);let g,y;const w=(h=e?.vsn)!==null&&h!==void 0?h:Fu;switch(w){case Mu:g=(b,v)=>v(JSON.stringify(b)),y=(b,v)=>v(JSON.parse(b));break;case Xi:g=this.serializer.encode.bind(this.serializer),y=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${p.vsn}`)}if(p.vsn=w,p.encode=(f=e?.encode)!==null&&f!==void 0?f:g,p.decode=(d=e?.decode)!==null&&d!==void 0?d:y,p.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,p.params=Object.assign(Object.assign({},p.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,p.autoSendHeartbeat=!this.worker}return p}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}
44var pt=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function vh(t,e,r){const s=new URL(e,t);if(r)for(const[n,i]of Object.entries(r))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function wh(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function bh(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:o}){const a=vh(t.baseUrl,s,n),c=await wh(t.auth),l=await e(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...c,...o},body:i?JSON.stringify(i):void 0}),u=await l.text(),h=(l.headers.get("content-type")||"").includes("application/json"),f=h&&u?JSON.parse(u):u;if(!l.ok){const d=h?f:void 0,p=d?.error;throw new pt(p?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:p?.type,icebergCode:p?.code,details:d})}return{status:l.status,headers:l.headers,data:f}}}}function It(t){return t.join("�")}var _h=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:It(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${It(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${It(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${It(t.namespace)}`}),!0}catch(e){if(e instanceof pt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof pt&&r.status===409)return;throw r}}};function Re(t){return t.join("�")}var Sh=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Re(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Re(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Re(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Re(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Re(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Re(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof pt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof pt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Eh=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=bh({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new _h(this.client,e),this.tableOps=new Sh(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}
44async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function gt(t){"@babel/helpers - typeof";return gt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gt(t)}function kh(t,e){if(gt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(gt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function xh(t){var e=kh(t,"string");return gt(e)=="symbol"?e:e+""}function Ah(t,e,r){return(e=xh(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Zs(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function x(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Zs(Object(r),!0).forEach(function(s){Ah(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Zs(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var ur=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function hr(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var qr=class extends ur{constructor(t,e,r,s="storage"){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return x({},super.toJSON())}},ro=class extends ur{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function Yt(t,e,r){const s=x({},t),n=e.toLowerCase();for(const i of Object.keys(s))i.toLowerCase()===n&&delete s[i];return s[n]=r,s}function Th(t){const e={};for(const[r,s]of Object.entries(t))e[r.toLowerCase()]=s;return e}const Ch=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Oh=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Br=t=>{if(Array.isArray(t))return t.map(r=>Br(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,s])=>{const n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=Br(s)}),e},Rh=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),en=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},jh=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){const n=t;let i=parseInt(String(n.status),10);Number.isFinite(i)||(i=500),n.json().then(o=>{const a=o?.statusCode||o?.code||i+"";e(new qr(en(o),i,a,s))}).catch(()=>{const o=i+"";e(new qr(n.statusText||`HTTP ${i} error`,i,o,s))})}else e(new ro(en(t),t,s))},Ih=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!s)return x(x({},n),r);if(Oh(s)){var i;const o=e?.headers||{};let a;for(const[c,l]of Object.entries(o))c.toLowerCase()==="content-type"&&(a=l);n.headers=Yt(o,"Content-Type",(i=a)!==null&&i!==void 0?i:"application/json"),n.body=JSON.stringify(s)}else n.body=s;return e?.duplex&&(n.duplex=e.duplex),x(x({},n),r)};async function et(t,e,r,s,n,i,o){return new Promise((a,c)=>{t(r,Ih(e,s,n,i)).then(l=>{if(!l.ok)throw l;if(s?.noResolveJson)return l;if(o==="vectors"){const u=l.headers.get("content-type");if(l.headers.get("content-length")==="0"||l.status===204)return{};if(!u||!u.includes("application/json"))return{}}return l.json()}).then(l=>a(l)).catch(l=>jh(l,c,s,o))})}function so(t="storage"){return{get:async(e,r,s,n)=>et(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>et(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>et(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>et(e,"HEAD",r,x(x({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>et(e,"DELETE",r,n,i,s,t)}}const $h=so("storage"),{get:mt,post:Y,put:Hr,head:Ph,remove:cs}=$h,z=so("vectors");var Qe=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=Th(e),this.fetch=Ch(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=Yt(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(hr(r))return{data:null,error:r};throw r}}},Nh=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(hr(e))return{data:null,error:e};throw e}}};let no;no=Symbol.toStringTag;var Lh=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[no]="BlobDownloadBuilder",this.promise=null}asStream(){return new Nh(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(hr(e))return{data:null,error:e};throw e}}};const Uh={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},tn={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Dh=class extends Qe{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let i;const o=x(x({},tn),s);let a=x(x({},n.headers),t==="POST"&&{"x-upsert":String(o.upsert)});const c=o.metadata;if(typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),c&&i.append("metadata",n.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),c&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(c))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,c&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(c))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),s?.headers)for(const[f,d]of Object.entries(s.headers))a=Yt(a,f,d);const l=n._removeEmptyFolders(e),u=n._getFinalPath(l),h=await(t=="PUT"?Hr:Y)(n.fetch,`${n.url}/object/${u}`,i,x({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:l,id:h.Id,fullPath:h.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}
44async uploadToSignedUrl(t,e,r,s){var n=this;const i=n._removeEmptyFolders(t),o=n._getFinalPath(i),a=new URL(n.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let c;const l=x(x({},tn),s);let u=x(x({},n.headers),{"x-upsert":String(l.upsert)});const h=l.metadata;if(typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),h&&c.append("metadata",n.encodeMetadata(h)),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.has("cacheControl")||c.append("cacheControl",l.cacheControl),h&&!c.has("metadata")&&c.append("metadata",n.encodeMetadata(h))):(c=r,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType,h&&(u["x-metadata"]=n.toBase64(n.encodeMetadata(h))),(typeof ReadableStream<"u"&&c instanceof ReadableStream||c&&typeof c=="object"&&"pipe"in c&&typeof c.pipe=="function")&&!l.duplex&&(l.duplex="half")),s?.headers)for(const[f,d]of Object.entries(s.headers))u=Yt(u,f,d);return{path:i,fullPath:(await Hr(n.fetch,a.toString(),c,x({headers:u},l?.duplex?{duplex:l.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=x({},r.headers);e?.upsert&&(n["x-upsert"]="true");const i=await Y(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new ur("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await Y(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await Y(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t);const i=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let o=await Y(s.fetch,`${s.url}/object/sign/${n}`,x({expiresIn:e},i?{transform:r.transform}:{}),{headers:s.headers});const a=new URLSearchParams;r?.download&&a.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&a.set("cacheNonce",String(r.cacheNonce));const c=a.toString();return{signedUrl:encodeURI(`${s.url}${o.signedURL}${c?`&${c}`:""}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await Y(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=new URLSearchParams;r?.download&&i.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&i.set("cacheNonce",String(r.cacheNonce));const o=i.toString();return n.map(a=>x(x({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){const s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",n=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));const i=n.toString(),o=this._getFinalPath(t),a=()=>mt(this.fetch,`${this.url}/${s}/${o}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new Lh(a,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>Br(await mt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await Ph(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(hr(n)){var s;const i=n instanceof qr?n.status:n instanceof ro?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=new URLSearchParams;e?.download&&s.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(s,e.transform),e?.cacheNonce!=null&&s.set("cacheNonce",String(e.cacheNonce));const n=s.toString(),i=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}`)+(n?`?${n}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await cs(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=x(x(x({},Uh),e),{},{prefix:t||""});return await Y(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=x({},t);return await Y(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("qual
44ity",e.quality.toString()),t}};const Mh="2.105.4",xt={"X-Client-Info":`storage-js/${Mh}`};var Fh=class extends Qe{constructor(t,e={},r,s){const n=new URL(t);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));const i=n.href.replace(/\/$/,""),o=x(x({},xt),e);super(i,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await mt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await mt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await Y(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await Hr(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Y(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await cs(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},qh=class extends Qe{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=x(x({},xt),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Y(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await mt(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await cs(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Rh(t))throw new ur("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new Eh({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){const o=n[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(n,a),error:null}}catch(c){if(s)throw c;return{data:null,error:c}}}}})}},Bh=class extends Qe{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=x(x({},xt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await z.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await z.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Hh=class extends Qe{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=x(x({},xt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");
44if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Vh=class extends Qe{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=x(x({},xt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await z.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Wh=class extends Vh{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new zh(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},zh=class extends Bh{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,x(x({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,x(x({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Kh(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Kh=class extends Hh{constructor(t,e,r,s,n){super(t,e,n),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,x(x({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,x(x({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,x(x({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,x(x({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,x(x({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Gh=class extends Fh{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new Dh(this.url,this.headers,t,this.fetch)}get vectors(){return new Wh(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new qh(this.url+"/iceberg",this.headers,this.fetch)}};const io="2.105.4",Le=30*1e3,Vr=3,Ar=Vr*Le,Jh="http://localhost:9999",Yh="supabase.auth.token",Xh={"X-Client-Info":`gotrue-js/${io}`},Wr="X-Supabase-Api-Version",oo={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Qh=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Zh=600*1e3;class yt extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function _(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class ed extends yt{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.co
44de=s}}function td(t){return _(t)&&t.name==="AuthApiError"}class X extends yt{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class de extends yt{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class M extends de{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function $t(t){return _(t)&&t.name==="AuthSessionMissingError"}class je extends de{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Pt extends de{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Nt extends de{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function rd(t){return _(t)&&t.name==="AuthImplicitGrantRedirectError"}class rn extends de{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class sd extends de{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class zr extends de{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Tr(t){return _(t)&&t.name==="AuthRetryableFetchError"}class sn extends de{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class Kr extends de{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Xt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),nn=` 	
45\r=`.split(""),nd=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<nn.length;e+=1)t[nn[e].charCodeAt(0)]=-2;for(let e=0;e<Xt.length;e+=1)t[Xt[e].charCodeAt(0)]=e;return t})();function on(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(Xt[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(Xt[s]),e.queuedBits-=6}}function ao(t,e,r){const s=nd[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function an(t){const e=[],r=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=o=>{ad(o,s,r)};for(let o=0;o<t.length;o+=1)ao(t.charCodeAt(o),n,i);return e.join("")}function id(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function od(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){const n=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}id(s,e)}}function ad(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function He(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)ao(t.charCodeAt(n),r,s);return new Uint8Array(e)}function cd(t){const e=[];return od(t,r=>e.push(r)),new Uint8Array(e)}function Se(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>on(n,r,s)),on(null,r,s),e.join("")}function ld(t){return Math.round(Date.now()/1e3)+t}function ud(){return Symbol("auth-callback")}const q=()=>typeof window<"u"&&typeof document<"u",we={tested:!1,writable:!1},co=()=>
45{if(!q())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(we.tested)return we.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),we.tested=!0,we.writable=!0}catch{we.tested=!0,we.writable=!1}return we.writable};function hd(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}const lo=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),dd=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Ue=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},be=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},F=async(t,e)=>{await t.removeItem(e)};class dr{constructor(){this.promise=new dr.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}dr.promiseConstructor=Promise;function Lt(t){const e=t.split(".");if(e.length!==3)throw new Kr("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Qh.test(e[s]))throw new Kr("JWT not in base64url format");return{header:JSON.parse(an(e[0])),payload:JSON.parse(an(e[1])),signature:He(e[2]),raw:{header:e[0],payload:e[1]}}}async function fd(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function pd(t,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await t(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){n(o);return}}})()})}function gd(t){return("0"+t.toString(16)).substr(-2)}function md(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length;let n="";for(let i=0;i<56;i++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,gd).join("")}async function yd(t){const r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function vd(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await yd(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ie(t,e,r=!1){const s=md();let n=s;r&&(n+="/recovery"),await Ue(t,`${e}-code-verifier`,n);const i=await vd(s);return[i,s===i?"plain":"s256"]}const wd=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function bd(t){const e=t.headers.get(Wr);if(!e||!e.match(wd))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function _d(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Sd(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Ed=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ne(t){if(!Ed.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function J(t){if(!t.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function Cr(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function kd(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;
45if(typeof s=="symbol"){const i=s.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,n)}return!e.value&&typeof s=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,s,n)}})}function cn(t){return JSON.parse(JSON.stringify(t))}const _e=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},xd=[502,503,504,520,521,522,523,524,530];async function ln(t){var e;if(!dd(t))throw new zr(_e(t),0);if(xd.includes(t.status))throw new zr(_e(t),t.status);let r;try{r=await t.json()}catch(i){throw new X(_e(i),i)}let s;const n=bd(t);if(n&&n.getTime()>=oo["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new sn(_e(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new M}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new sn(_e(r),t.status,r.weak_password.reasons);throw new ed(_e(r),t.status||500,s)}const Ad=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function k(t,e,r,s){var n;const i=Object.assign({},s?.headers);i[Wr]||(i[Wr]=oo["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const o=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Td(t,e,r+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Td(t,e,r,s,n,i){const o=Ad(e,s,n,i);let a;try{a=await t(r,Object.assign({},o))}catch(c){throw console.error(c),new zr(_e(c),0)}if(a.ok||await ln(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await ln(c)}}function K(t){var e;let r=null;Rd(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=ld(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function un(t){const e=K(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function me(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Cd(t){return{data:t,error:null}}function Od(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,o=rr(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function hn(t){return t}function Rd(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}const Or=["global","local","others"];class jd{constructor({url:e="",headers:r={},fetch:s,experimental:n}){this.url=e,this.headers=r,this.fetch=lo(s),this.experimental=n??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,r=Or[0]){if(Or.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Or.join(", ")}`);try{return await k(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(_(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await k(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:me})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=rr(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await k(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Od,redirectTo:r?.redirectTo})}catch(r){if(_(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await k(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:me})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,o,a,c;try{const l={nextPage:null,lastPage:0,total:0},u=await k(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:hn});if(u.error)throw u.error;const h=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,d=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return d.length>
450&&(d.forEach(p=>{const g=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(p.split(";")[1].split("=")[1]);l[`${y}Page`]=g}),l.total=parseInt(f)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(_(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){ne(e);try{return await k(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:me})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){ne(e);try{return await k(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:me})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){ne(e);try{return await k(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:me})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){ne(e.userId);try{const{data:r,error:s}=await k(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(_(r))return{data:null,error:r};throw r}}async _deleteFactor(e){ne(e.userId),ne(e.id);try{return{data:await k(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(_(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,o,a,c;try{const l={nextPage:null,lastPage:0,total:0},u=await k(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:hn});if(u.error)throw u.error;const h=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,d=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return d.length>0&&(d.forEach(p=>{const g=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(p.split(";")[1].split("=")[1]);l[`${y}Page`]=g}),l.total=parseInt(f)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(_(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await k(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(_(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await k(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(_(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await k(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(_(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await k(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(_(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await k(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(_(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e?.type&&(r.type=e.type),await k(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(_(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await k(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(_(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await k(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(_(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await k(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(_(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await k(this.fetch,"DELET
45E",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(_(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){J(this.experimental),ne(e.userId);try{return await k(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(_(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){J(this.experimental),ne(e.userId),ne(e.passkeyId);try{return await k(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(_(r))return{data:null,error:r};throw r}}}function dn(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const Q={debug:!!(globalThis&&co()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class uo extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class fn extends uo{}async function Id(t,e,r){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;let n;e>0&&(n=setTimeout(()=>{s.abort(),Q.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){clearTimeout(n),Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new fn(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Q.debug)try{const o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null,"  "))}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(n),await r()}})}catch(i){if(e>0&&clearTimeout(n),i!==null&&typeof i=="object"&&"name"in i&&i.name==="AbortError"&&e>0){if(s.signal.aborted)return Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async o=>{if(o){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,o.name);try{return await r()}finally{Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,o.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new fn(`Lock "${t}" was released because another request stole it`)}throw i}}function $d(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function ho(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Pd(t){return parseInt(t,16)}function Nd(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Ld(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:c,resources:l,scheme:u,uri:h,version:f}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
46`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const d=ho(t.address),p=u?`${u}://${s}`:s,g=t.statement?`${t.statement}
47`:"",y=`${p} wants you to sign in with your Ethereum account:
48${d}
49
50${g}`;let w=`URI: ${h}
51Version: ${f}
52Chain ID: ${r}${o?`
53Nonce: ${o}`:""}
54Issued At: ${i.toISOString()}`;if(n&&(w+=`
55Expiration Time: ${n.toISOString()}`),a&&(w+=`
56Not Before: ${a.toISOString()}
56`),c&&(w+=`
57Request ID: ${c}`),l){let b=`
58Resources:`;for(const v of l){if(!v||typeof v!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${v}`);b+=`
59- ${v}`}w+=b}return`${y}
60${w}`}class U extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Qt extends U{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function Ud({error:t,options:e}){var r,s,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new U({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new U({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new U({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new U({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new U({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new U({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new U({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const o=window.location.hostname;if(fo(o)){if(i.rp.id!==o)return new U({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new U({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Dd({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new U({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(fo(s)){if(r.rpId!==s)return new U({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ER
60ROR",cause:t})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class Md{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Gr=new Md;function pn(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:s}=t,n=rr(t,["challenge","user","excludeCredentials"]),i=He(e).buffer,o=Object.assign(Object.assign({},r),{id:He(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:i,user:o});if(s&&s.length>0){a.excludeCredentials=new Array(s.length);for(let c=0;c<s.length;c++){const l=s[c];a.excludeCredentials[c]=Object.assign(Object.assign({},l),{id:He(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return a}function gn(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,s=rr(t,["challenge","allowCredentials"]),n=He(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){const a=r[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:He(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function mn(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:Se(new Uint8Array(t.response.attestationObject)),clientDataJSON:Se(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function yn(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Se(new Uint8Array(n.authenticatorData)),clientDataJSON:Se(new Uint8Array(n.clientDataJSON)),signature:Se(new Uint8Array(n.signature)),userHandle:n.userHandle?Se(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function fo(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Zt(){var t,e;return!!(q()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function po(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Qt("Browser returned unexpected credential type",e)}:{data:null,error:new Qt("Empty credential response",e)}}catch(e){return{data:null,error:Ud({error:e,options:t})}}}async function go(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Qt("Browser returned unexpected credential type",e)}:{data:null,error:new Qt("Empty credential response",e)}}catch(e){return{data:null,error:Dd({error:e,options:t})}}}const Fd={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},qd={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function er(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const i in n){const o=n[i];if(o!==void 0)if(Array.isArray(o))s[i]=o;else if(r(o))s[i]=o;else if(e(o)){const a=s[i];e(a)?s[i]=er(a,o):s[i]=er(o)}else s[i]=o}return s}function Bd(t,e){return er(Fd,t,e||{})}function Hd(t,e){return er(qd,t,e||{})}class Vd{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},i){var o;try{const{data:a,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:c};const l=n??Gr.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){const h=s;if(h)u.name=`${u.id}:${h}`;else{const d=(await this.client.getUser()).data.user,p=((o=d?.user_metadata)===null||o===void 0?void 0:o.name)||d?.email||d?.id||"User";u.name=`${u.id}:${p}`}}u.displayName||(u.displayName=u.name)}
60switch(a.webauthn.type){case"create":{const u=Bd(a.webauthn.credential_options.publicKey,i?.create),{data:h,error:f}=await po({publicKey:u,signal:l});return h?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:f}}case"request":{const u=Hd(a.webauthn.credential_options.publicKey,i?.request),{data:h,error:f}=await go(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:l}));return h?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:f}}}}catch(a){return _(a)?{data:null,error:a}:{data:null,error:new X("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new yt("rpId is required for WebAuthn authentication")};try{if(!Zt())return{data:null,error:new X("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!o)return{data:null,error:a};const{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:s,credential_response:c.credential_response}})}catch(o){return _(o)?{data:null,error:o}:{data:null,error:new X("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new yt("rpId is required for WebAuthn registration")};try{if(!Zt())return{data:null,error:new X("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var h;return(h=u.data)===null||h===void 0?void 0:h.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};const{data:c,error:l}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:l}}catch(o){return _(o)?{data:null,error:o}:{data:null,error:new X("Unexpected error in register",o)}}}}$d();const Wd={url:Jh,storageKey:Yh,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Xh,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function vn(t,e,r){return await r()}const $e={};class vt{get jwks(){var e,r;return(r=(e=$e[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){$e[this.storageKey]=Object.assign(Object.assign({},$e[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=$e[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){$e[this.storageKey]=Object.assign(Object.assign({},$e[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n,i;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const o=Object.assign(Object.assign({},Wd),e);if(this.storageKey=o.storageKey,this.instanceID=(r=vt.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,vt.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!o.debug,typeof o.debug=="function"&&(this.logger=o.debug),this.instanceID>0&&q()){const a=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=o.persistSession,this.autoRefreshToken=o.autoRefreshToken,this.experimental=(s=o.experimental)!==null&&s!==void 0?s:{},this.admin=new jd({url:o.url,headers:o.headers,fetch:o.fetch,experimental:this.experimental}),this.url=o.url,this.headers=o.headers,this.fetch=lo(o.fetch),this.lock=o.lock||vn,this.detectSessionInUrl=o.detectSessionInUrl,this.flowType=o.flowType,this.hasCustomAuthorizationHeader=o.hasCustomAuthorizationHeader,this.throwOnError=o.throwOnError,this.lockAcquireTimeout=o.lockAcquireTimeout,o.lock?this.lock=o.lock:this.persistSession&&q()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=Id:this.lock=vn,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new Vd(this)}
60,this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(o.storage?this.storage=o.storage:co()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=dn(this.memoryStorage)),o.userStorage&&(this.userStorage=o.userStorage)):(this.memoryStorage={},this.storage=dn(this.memoryStorage)),q()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(c){this._debug("#broadcastChannel","error",c)}})}o.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${io}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},s="none";if(q()&&(r=hd(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),q()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),rd(i)){const c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:o,redirectType:a}=n;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return _(r)?this._returnResult({error:r}):this._returnResult({error:new X("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:K}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(_(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){const{email:u,password:h,options:f}=e;let d=null,p=null;this.flowType==="pkce"&&([d,p]=await Ie(this.storage,this.storageKey)),i=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:h,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:d,code_challenge_method:p},xform:K})}else if("phone"in e){const{phone:u,password:h,options:f}=e;i=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:K})}else throw new Pt("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return await F(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});const c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(await F(this.storage,`${this.storageKey}-code-verifier`),_(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:o,options:a}=e;r=await k(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:un})}else if("phone"in e){const{phone:i,password:o,options:a}=e;r=await k(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:un})}else throw new Pt("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const i=new je;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(_(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,o,a,c,l,u,h,f;let d,p;
60if("message"in e)d=e.message,p=e.signature;else{const{chain:g,wallet:y,statement:w,options:b}=e;let v;if(q())if(typeof y=="object")v=y;else{const H=window;if("ethereum"in H&&typeof H.ethereum=="object"&&"request"in H.ethereum&&typeof H.ethereum.request=="function")v=H.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=y}const S=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),O=await v.request({method:"eth_requestAccounts"}).then(H=>H).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!O||O.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const A=ho(O[0]);let $=(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!$){const H=await v.request({method:"eth_chainId"});$=Pd(H)}const Ce={domain:S.host,address:A,statement:w,uri:S.href,version:"1",chainId:$,nonce:(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(o=(i=b?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.resources};d=Ld(Ce),p=await v.request({method:"personal_sign",params:[Nd(d),A]})}try{const{data:g,error:y}=await k(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:K});if(y)throw y;if(!g||!g.session||!g.user){const w=new je;return this._returnResult({data:{user:null,session:null},error:w})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(_(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,s,n,i,o,a,c,l,u,h,f,d;let p,g;if("message"in e)p=e.message,g=e.signature;else{const{chain:y,wallet:w,statement:b,options:v}=e;let S;if(q())if(typeof w=="object")S=w;else{const A=window;if("solana"in A&&typeof A.solana=="object"&&("signIn"in A.solana&&typeof A.solana.signIn=="function"||"signMessage"in A.solana&&typeof A.solana.signMessage=="function"))S=A.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof w!="object"||!v?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=w}const O=new URL((r=v?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in S&&S.signIn){const A=await S.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v?.signInWithSolana),{version:"1",domain:O.host,uri:O.href}),b?{statement:b}:null));let $;if(Array.isArray(A)&&A[0]&&typeof A[0]=="object")$=A[0];else if(A&&typeof A=="object"&&"signedMessage"in A&&"signature"in A)$=A;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in $&&"signature"in $&&(typeof $.signedMessage=="string"||$.signedMessage instanceof Uint8Array)&&$.signature instanceof Uint8Array)p=typeof $.signedMessage=="string"?$.signedMessage:new TextDecoder().decode($.signedMessage),g=$.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in S)||typeof S.signMessage!="function"||!("publicKey"in S)||typeof S!="object"||!S.publicKey||!("toBase58"in S.publicKey)||typeof S.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${O.host} wants you to sign in with your Solana account:`,S.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${O.href}`,`Issued At: ${(n=(s=v?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=v?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}
60`]:[],...!((o=v?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((a=v?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((c=v?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((l=v?.signInWithSolana)===null||l===void 0)&&l.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((h=(u=v?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...v.signInWithSolana.resources.map($=>`- ${$}`)]:[]].join(`
61`);const A=await S.signMessage(new TextEncoder().encode(p),"utf8");if(!A||!(A instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=A}}try{const{data:y,error:w}=await k(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:Se(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(d=e.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:K});if(w)throw w;if(!y||!y.session||!y.user){const b=new je;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:w})}catch(y){if(_(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){const r=await be(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new sd;const{data:i,error:o}=await k(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:K});if(await F(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const a=new je;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers(n==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}catch(i){if(await F(this.storage,`${this.storageKey}-code-verifier`),_(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await k(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:K}),{data:c,error:l}=a;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){const u=new je;return this._returnResult({data:{user:null,session:null},error:u})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(r){if(_(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;try{if("email"in e){const{email:a,options:c}=e;let l=null,u=null;this.flowType==="pkce"&&([l,u]=await Ie(this.storage,this.storageKey));const{error:h}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=c?.data)!==null&&r!==void 0?r:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:a,options:c}=e,{data:l,error:u}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=c?.data)!==null&&n!==void 0?n:{},create_user:(i=c?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:u})}throw new Pt("You must provide either an email or phone number.")}catch(a){if(await F(this.storage,`${this.storageKey}-code-verifier`),_(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:a}=await k(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:K});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(n){if(_(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,o;try{let a=null,c=null;this.flowType==="pkce"&&([a,c]=await Ie(this.storage,this.storageKey));const l=await k(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:c}),headers:this.headers,xform:Cd});return!((i=l.data)===null||i===void 0)&&i.url&&q()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(a){if(await F(this.storage,`${this.storageKey}-code-verifier`),_(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new M;const{error:n}=await k(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(_(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e,{error:o}=await k(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:o,error:a}=await k(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new Pt("You must provide either an email or phone number and a type")}catch(r){if(_(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await be(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not val
61id"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Ar:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const o=await be(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=Cr()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=kd(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:me}):await this._useSession(async r=>{var s,n,i;const{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new M}:await k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:me})})}catch(r){if(_(r))return $t(r)&&(await this._removeSession(),await F(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new M;const o=n.session;let a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await Ie(this.storage,this.storageKey));const{data:l,error:u}=await k(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:me});if(u)throw u;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(s){if(await F(this.storage,`${this.storageKey}-code-verifier`),_(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new M;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:o}=Lt(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){const{data:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(_(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new M;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(_(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!q())throw new Nt("No browser detected.");
61if(e.error||e.error_description||e.error_code)throw new Nt(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new rn("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Nt("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new rn("No code detected.");const{data:v,error:S}=await this._exchangeCodeForSession(e.code);if(S)throw S;const O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:v.session,redirectType:(s=v.redirectType)!==null&&s!==void 0?s:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:a,expires_in:c,expires_at:l,token_type:u}=e;if(!o||!c||!a||!u)throw new Nt("No session defined in URL");const h=Math.round(Date.now()/1e3),f=parseInt(c);let d=h+f;l&&(d=parseInt(l));const p=d-h;p*1e3<=Le&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${f}s`);const g=d-f;h-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,h):h-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,d,h);const{data:y,error:w}=await this._getUser(o);if(w)throw w;const b={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:f,expires_at:d,refresh_token:a,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(n){if(_(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await be(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i&&!$t(i))return this._returnResult({error:i});const o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(td(a)&&(a.status===404||a.status===401||a.status===403)||$t(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await F(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=ud(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session:i},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),$t(i)?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Ie(this.storage,this.storageKey,!0));try{return await k(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await F(this.storage,`${this.storageKey}-code-verifier`),_(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async i=>{var o,a,c,l,u;const{data:h,error:f}=i;if(f)throw f;const d=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await k(this.fetch,"GET",d,{headers:this.headers,jwt:(u=(l=h.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return q()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url},error:null})}catch(s){if(_(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:o,provider:a,token:c,access_token:l,nonce:u}=e,h=await k(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:a,id_token:c,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:K}),{data:f,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new je}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:d}))}catch(n){if(await F(this.storage,`${this.storageKey}-code-verifier`),_(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:o}=r;if(o)throw o;
61return await k(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await pd(async n=>(n>0&&await fd(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await k(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:K})),(n,i)=>{const o=200*Math.pow(2,n);return i&&Tr(i)&&Date.now()+o-s<Le})}catch(s){if(this._debug(r,"error",s),_(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),q()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await be(this.storage,this.storageKey);if(n&&this.userStorage){let o=await be(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await Ue(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o?.user)!==null&&e!==void 0?e:Cr()}else if(n&&!n.user&&!n.user){const o=await be(this.storage,this.storageKey+"-user");o&&o?.user?(n.user=o.user,await F(this.storage,this.storageKey+"-user"),await Ue(this.storage,this.storageKey,n)):n.user=Cr()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Ar;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Ar}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),Tr(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:a}=await this._getUser(n.access_token);!a&&o?.user?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new M;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new dr;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new M;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const a={data:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(n,"error",i),_(i)){const o={data:null,error:i};return Tr(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await F(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Ue(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=cn(n);await Ue(this.storage,this.storageKey,i)}else{const n=cn(r);await Ue(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await F(this.storage,this.storageKey),await F(this.storage,this.storageKey+"-code-verifier"),await F(this.storage,this.storageKey+"-user"),this.userStorage&&await F(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&q()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}
61catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Le);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/Le);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Le}ms, refresh threshold is ${Vr} ticks`),n<=Vr&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof uo)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!q()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const n=[`provider=${encodeURIComponent(r)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,o]=await Ie(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(s?.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await k(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:l}=await k(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c?.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?mn(e.webauthn.credential_response):yn(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:c}=await k(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:c}))})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const o=await k(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:pn(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:gn(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:d}=Lt(e);let p=null;d.aal&&(p=d.aal);let g=p;const{data:{user:y},error:w}=await this.getUser(e);if(w)return this._returnResult({data:null,error:w});((s=(r=y?.factors)===null||r===void 0?void 0:r.filter(S=>S.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(g="aal2");const v=d.amr||[];return{data:{currentLevel:p,nextLevel:g,currentAuthenticationMethods:v},error:null}}catch(d){if(_(d))return this._returnResult({data:null,error:d});throw d}const{data:{session:o},error:a}
61=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=Lt(o.access_token);let l=null;c.aal&&(l=c.aal);let u=l;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(d=>d.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");const f=c.amr||[];return{data:{currentLevel:l,nextLevel:u,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await k(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new M})})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new M});const o=await k(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(_(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new M});const o=await k(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(_(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await k(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new M})})}catch(e){if(_(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await k(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new M})})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+Zh>n)return s;const{data:i,error:o}=await k(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:d,error:p}
61=await this.getSession();if(p||!d.session)return this._returnResult({data:null,error:p});s=d.session.access_token}const{header:n,payload:i,signature:o,raw:{header:a,payload:c}}=Lt(s);r?.allowExpired||_d(i.exp);const l=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!l){const{error:d}=await this.getUser(s);if(d)throw d;return{data:{claims:i,header:n,signature:o},error:null}}const u=Sd(n.alg),h=await crypto.subtle.importKey("jwk",l,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,o,cd(`${a}.${c}`)))throw new Kr("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if(_(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;J(this.experimental);try{if(!Zt())return this._returnResult({data:null,error:new X("Browser does not support WebAuthn",null)});const{data:i,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(o||!i)return this._returnResult({data:null,error:o});const a=gn(i.options),c=(n=(s=e?.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:Gr.createNewAbortSignal(),{data:l,error:u}=await go({publicKey:a,signal:c});if(u||!l)return this._returnResult({data:null,error:u??new X("WebAuthn ceremony failed",null)});const h=yn(l);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(_(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,s;J(this.experimental);try{if(!Zt())return this._returnResult({data:null,error:new X("Browser does not support WebAuthn",null)});const{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});const o=pn(n.options),a=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:Gr.createNewAbortSignal(),{data:c,error:l}=await po({publicKey:o,signal:a});if(l||!c)return this._returnResult({data:null,error:l??new X("WebAuthn ceremony failed",null)});const u=mn(c);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:u})}catch(n){if(_(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){J(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new M});const{data:n,error:i}=await k(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(_(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){J(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new M});const{data:i,error:o}=await k(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;J(this.experimental);try{const{data:s,error:n}=await k(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(_(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){J(this.experimental);try{const{data:r,error:s}=await k(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:K});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){J(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new M});const{data:n,error:i}=await k(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(_(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){J(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new M});const{data:i,error:o}=await k(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){J(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new M});const{error:i}
61=await k(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(_(r))return this._returnResult({data:null,error:r});throw r}}}vt.nextInstanceID={};const zd=vt,Kd="2.105.4";let ot="";typeof Deno<"u"?ot="deno":typeof document<"u"?ot="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ot="react-native":ot="node";const Gd={"X-Client-Info":`supabase-js-${ot}/${Kd}`},Jd={headers:Gd},Yd={schema:"public"},Xd={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Qd={};function wt(t){"@babel/helpers - typeof";return wt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},wt(t)}function Zd(t,e){if(wt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(wt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ef(t){var e=Zd(t,"string");return wt(e)=="symbol"?e:e+""}function tf(t,e,r){return(e=ef(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function wn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function P(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?wn(Object(r),!0).forEach(function(s){tf(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):wn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const rf=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),sf=()=>Headers,nf=(t,e,r)=>{const s=rf(r),n=sf();return async(i,o)=>{var a;const c=(a=await e())!==null&&a!==void 0?a:t;let l=new n(o?.headers);return l.has("apikey")||l.set("apikey",t),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),s(i,P(P({},o),{},{headers:l}))}};function of(t){return t.endsWith("/")?t:t+"/"}function af(t,e){var r,s;const{db:n,auth:i,realtime:o,global:a}=t,{db:c,auth:l,realtime:u,global:h}=e,f={db:P(P({},c),n),auth:P(P({},l),i),realtime:P(P({},u),o),storage:{},global:P(P(P({},h),a),{},{headers:P(P({},(r=h?.headers)!==null&&r!==void 0?r:{}),(s=a?.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function cf(t){const e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(of(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var lf=class extends zd{constructor(t){super(t)}},uf=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=cf(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:Yd,realtime:Qd,auth:P(P({},Xd),{},{storageKey:o}),global:Jd},c=af(r??{},a);if(this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(u,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var l;this.auth=this._initSupabaseAuthClient((l=c.auth)!==null&&l!==void 0?l:{},this.headers,c.global.fetch)}this.fetch=nf(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(P({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new Nu(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new Gh(this.storageUrl.href,this.headers,this.fetch,r?.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new xu(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:c,throwOnError:l,experimental:u,lockAcquireTimeout:h,skipAutoInitialize:f},d,p){const g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new lf({url:this.authUrl.href,headers:P(P({},g),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:c,throwOnError:l,experimental:u,fetch:p,lockAcquireTimeout:h,skipAutoInitialize:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new yh(this.realtimeUrl.href,P(P({},t),{},{params:P(P({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const hf=(t,e,r)=>new uf(t,e,r);function df(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}df()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to N
61ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Mt=[{code:"en",name:"English"},{code:"ja",name:"日本語"},{code:"ko",name:"한국어"},{code:"zh-Hant",name:"繁體中文"},{code:"zh",name:"简体中文"}],ff=[{platform:"tiktok",link:"/free/tiktok-transcript"},{platform:"instagram",link:"/free/instagram-transcript"},{platform:"youtube",link:"/free/youtube-transcript"},{platform:"twitter",link:"/free/x-transcript"},{platform:"facebook",link:"/free/facebook-transcript"},{platform:"xiaohongshu",link:"/free/xiaohongshu-transcript"}];function tr(t){return ff.find(e=>e.platform===t)?.link||""}function dt(t,e){if(t&&t.startsWith("mailto:"))return t;const r=mo(e).code;let s;return r&&r!="en"?s="/"+r+"/":t.indexOf("/free/")!=-1||t.indexOf("/pricing")!=-1||t.indexOf("/about")!=-1?s="/":s="",!t||t=="/"?s||"/":`${t}${s}`}function pf(){return Mt}function mo(t){const e=t?.split("/").filter(n=>n&&n!="").pop();let r=Mt.find(n=>n.code===e);if(r)return r;const s="en";return r=Mt.find(n=>n.code===s),r||Mt[0]}const gf="https://qdqslaistdojvittjlay.supabase.co",mf="sb_publishable_RyJiohxqLZO8wcG_g8_QiA_EK_c0ZMd";function At(){return hf(gf,mf)}function Ye(){setTimeout(async()=>{location.replace("/account")},500)}function bn(){setTimeout(async()=>{localStorage.removeItem("sb-qdqslaistdojvittjlay-auth-token"),window.location.replace("/")},100)}async function yf(t=!1){const e=At();return fr({onSyncSuccess:t?Ye:()=>null,onSyncError:t?Ye:()=>null}),e.auth.getSession()}async function vf(t){const e=location.href.substring(0,location.href.indexOf("/",10)),r=At(),s=await r.auth.getSession();if(s&&s.data&&s.data.session)fr({onSyncSuccess:Ye,onSyncError:Ye});else{const{data:n,error:i}=await r.auth.signInWithOtp({email:t,options:{shouldCreateUser:!0,emailRedirectTo:`${e}/auth/callback`}});location.href="/verify-request.html"}}async function wf(){let t=document.getElementById("url-input")?.value;!t||t==""||sessionStorage.setItem("url",t),sessionStorage.setItem("logined_redirect",window.location.href.toString()),bf()}async function bf(){const t=location.href.substring(0,location.href.indexOf("/",10)),e=At(),r=await e.auth.getSession();if(r&&r.data&&r.data.session)fr({onSyncSuccess:Ye,onSyncError:Ye});else{const{data:s,error:n}=await e.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${t}/auth/callback`}});console.log(s,n)}}async function _f(){try{localStorage.removeItem("sb-qdqslaistdojvittjlay-auth-token");const t=At();fr({onSyncSuccess:bn,onSyncError:bn});let e=await t.auth.signOut()}catch(t){console.error("signOut err",t)}}const Sf="dcjapbnpoegpcbhbekgfoipfdkdimgjf";class Ef{supabase;extensionId;onSyncSuccess;onSyncError;syncSubscription=null;messageListener=null;constructor(e){this.supabase=At(),this.extensionId=Sf,this.onSyncSuccess=e.onSyncSuccess,this.onSyncError=e.onSyncError}async startSync(){this.syncSubscription=this.supabase.auth.onAuthStateChange(async(r,s)=>{(r==="SIGNED_IN"||r==="TOKEN_REFRESHED")&&s?await this.syncSessionToExtension(s):r==="SIGNED_OUT"&&await this.clearExtensionSession()}).data.subscription,this.setupExtensionMessageListener();const{data:{session:e}}=await this.supabase.auth.getSession();e&&await this.syncSessionToExtension(e)}stopSync(){this.syncSubscription&&(this.syncSubscription.unsubscribe(),this.syncSubscription=null),this.messageListener&&typeof chrome<"u"&&chrome.runtime?.onMessage&&(chrome.runtime.onMessage.removeListener(this.messageListener),this.messageListener=null)}setupExtensionMessageListener(){typeof chrome>"u"||!chrome.runtime?.onMessage||(this.messageListener=async e=>{if(e.type==="EXTENSION_SESSION_SYNC"&&e.session){console.log("[SessionSync] Received session sync from extension");try{const{error:r}=await this.supabase.auth.setSession({access_token:e.session.access_token,refresh_token:e.session.refresh_token});r?console.error("[SessionSync] Failed to set session from extension:",r):console.log("[SessionSync] Session updated from extension successfully")}catch(r){console.error("[SessionSync] Error handling extension session sync:",r)}}
61else if(e.type==="EXTENSION_LOGOUT"){console.log("[SessionSync] Received logout from extension");try{await this.supabase.auth.signOut()}catch(r){console.error("[SessionSync] Error handling extension logout:",r)}}},chrome.runtime.onMessage.addListener(this.messageListener))}async syncSessionToExtension(e){if(typeof chrome>"u"||!chrome.runtime?.sendMessage){console.warn("[SessionSync] Chrome extension API not available");return}try{const r=await chrome.runtime.sendMessage(this.extensionId,{type:"SUPABASE_SESSION_SYNC",session:{access_token:e.access_token,refresh_token:e.refresh_token,expires_at:e.expires_at,expires_in:e.expires_in,token_type:e.token_type,user:e.user}});r?.success?(console.log("[SessionSync] Session synced to extension successfully"),this.onSyncSuccess?.(r)):(console.error("[SessionSync] Failed to sync session:",r?.error),this.onSyncError?.(r?.error||"Unknown error"))}catch(r){console.error("[SessionSync] Error sending message to extension:",r),this.onSyncError?.(r instanceof Error?r.message:"Failed to sync session")}}async clearExtensionSession(){if(!(typeof chrome>"u"||!chrome.runtime?.sendMessage))try{const e=await chrome.runtime.sendMessage(this.extensionId,{type:"SUPABASE_SESSION_CLEAR"});e?.success?(console.log("[SessionSync] Extension session cleared successfully"),this.onSyncSuccess?.(e)):(console.error("[SessionSync] Failed to sync session:",e?.error),this.onSyncError?.(e?.error||"Unknown error"))}catch(e){console.error("[SessionSync] Error clearing extension session:",e),this.onSyncError?.(e instanceof Error?e.message:"Failed to clearing session")}}async checkExtensionAvailable(){return typeof chrome>"u"||!chrome.runtime?.sendMessage?!1:new Promise(e=>{try{chrome.runtime.sendMessage(this.extensionId,{type:"PING"},r=>{e(r?.success===!0)}),setTimeout(()=>e(!1),3e3)}catch{e(!1)}})}}let tt=null;function fr(t){return tt&&tt.stopSync(),tt=new Ef(t),tt.startSync(),tt}function kf({onClose:t,mode:e="signin"}){const[r,s]=D.useState(e),{locale_languages:[n,i]}=Jr(),a=i.common.pages.loginmodal;return m.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[m.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-black/60 via-black/50 to-black/60 backdrop-blur-md",onClick:t}
61),m.jsxs("div",{className:"relative bg-white w-full max-w-md shadow-[0_20px_60px_rgba(0,0,0,0.3)] overflow-hidden",children:[m.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#41C97F] via-[#36B56D] to-[#2EAA5F]"}),m.jsx("button",{onClick:t,className:"absolute top-6 right-6 w-8 h-8 flex items-center justify-center rounded-full bg-[#F5F7FA] text-[#636E72] hover:bg-[#41C97F] hover:text-white transition-all cursor-pointer z-10",children:m.jsx(_u,{className:"w-5 h-5"})}),m.jsxs("div",{className:"p-10",children:[m.jsxs("div",{className:"mb-8",children:[m.jsx("div",{className:"flex items-center gap-2 mb-2",children:m.jsx("img",{src:"https://www.transcript365.com/images/transcript365-logo-full.png",style:{width:"162px",maxHeight:"36px"},width:"162",height:"36",alt:"Transcript365",decoding:"async",className:"w-12 h-12"})}),m.jsx("p",{className:"text-sm text-[#95A5A6]",children:a[r].text})]}),m.jsx("h3",{className:"text-3xl font-bold text-[#2D3436] mb-8 leading-tight",children:a[r].title}),m.jsxs("button",{onClick:wf,className:"group w-full h-13 bg-white border-2 border-[#E8E8E8] rounded-xl flex items-center justify-center gap-3 hover:border-[#41C97F] hover:shadow-[0_8px_16px_rgba(65,201,127,0.15)] transition-all cursor-pointer mb-5",children:[m.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",children:[m.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),m.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),m.jsx("path",{fill:"#FBBC05",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),m.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),m.jsx("span",{className:"font-semibold text-[#2D3436] group-hover:text-[#41C97F] transition-colors",children:a[r].oauth2_google})]}),m.jsxs("div",{className:"relative my-7",children:[m.jsx("div",{className:"absolute inset-0 flex items-center",children:m.jsx("div",{className:"w-full border-t border-[#E8E8E8]"})}),m.jsx("div",{className:"relative flex justify-center",children:m.jsx("span",{className:"px-4 bg-white text-xs text-[#B2BEC3] uppercase tracking-wider font-medium",children:a[r].linetext})})]}),m.jsx("div",{className:"mb-5",children:m.jsx("input",{id:"email",type:"email",placeholder:"[email protected]",className:"w-full h-13 px-5 bg-[#F8F9FA] border-2 border-transparent rounded-xl focus:outline-none focus:bg-white focus:border-[#41C97F] focus:shadow-[0_0_0_4px_rgba(65,201,127,0.1)] transition-all placeholder:text-[#B2BEC3]"})}),m.jsxs("button",{onClick:async c=>{const u=document.getElementById("email").value;if(!u){alert("Please enter your email address");return}c.target.disabled=!0,vf(u)},className:"w-full h-13 bg-gradient-to-r from-[#41C97F] to-[#36B56D] text-white rounded-xl font-bold text-base hover:shadow-[0_8px_24px_rgba(65,201,127,0.4)] hover:-translate-y-0.5 active:translate-y-0 transition-all mb-6 cursor-pointer",children:[a[r].continuebut," →"]}),m.jsxs("p",{className:"text-center text-sm text-[#95A5A6]",children:[a[r].desc,"  ",m.jsx("button",{onClick:()=>s(r==="signin"?"signup":"signin"),className:"text-[#41C97F] font-bold hover:text-[#36B56D] transition-colors",children:a[r].linktext})]})]})]})]})}function Rr({className:t}){return m.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:m.jsx("path",{d:"M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-5.2 1.74 2.89 2.89 0 0 1 2.31-4.64 2.93 2.93 0 0 1 .88.13V9.4a6.84 6.84 0 0 0-1-.05A6.33 6.33 0 0 0 5 20.1a6.34 6.34 0 0 0 10.86-4.43v-7a8.16 8.16 0 0 0 4.77 1.52v-3.4a4.85 4.85 0 0 1-1-.1z"})})}function jr({className:t}){return m.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:m.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})})}function Ir({className:t}){return m.jsx("img",{src:"/images/xhsicon.png",alt:"Xiaohongshu",className:`${t} rounded-lg object-cover`})}const _n=pf();
61function Rf(){const[t,e]=D.useState(!1),[r,s]=D.useState(!1),[n,i]=D.useState("signin"),[o,a]=D.useState({}),[c,l]=D.useState(!1),[u,h]=D.useState(!1),[f,d]=D.useState(!1),p=D.useRef(null),g=D.useRef(null),[y,w]=D.useState(!1),b=D.useRef(null),{locale_languages:[v,S]}=Jr(),[O,A]=D.useState(v),$=mo(O),Ce=$.code,H=async E=>{let C=window.location.pathname;if(C&&C.indexOf(".html")!=-1){window.location.replace(E);return}let W;if(C&&C==="/")E=="en"?W="/":W=`/${E}/`;else{if(C.substring(C.length-1)=="/"&&(C=C.substring(0,C.length-1)),C.indexOf("/"+Ce)!=-1)W=C.substring(0,C.indexOf("/"+Ce));else{let fe=C.split("/").filter(xo=>xo!="").pop();fe=="zh-Hant"||fe.length==2?W=C.substring(0,C.indexOf("/"+fe)):W=C}_n.find(fe=>fe.code===E)?.code,E=="en"?W=W+"/":W=W+"/"+E+"/"}window.location.replace(W)},Ze=S.common,Tt=Ze.pages.navbar.sections,yo=Ze.pages.navbar.resources,vo=Ze.platforms,wo=Ze.chromeBrowserExtension,bo=Ze.edgeBrowserExtension,_o=(yo||[]).filter(E=>E.link!="").map(E=>({...E,link:dt(E.link,v)})),So=vo.filter(E=>tr(E.platform)!="").map(E=>({...E,link:dt(tr(E.platform),v)})),ls=wo.filter(E=>E.link!=""),pr=bo.filter(E=>E.link!=""),Eo=()=>{i("signin"),e(!0)},ko=()=>{i("signup"),e(!0)};return D.useEffect(()=>{const E=C=>{p.current&&!p.current.contains(C.target)&&h(!1),b.current&&!b.current.contains(C.target)&&w(!1),g.current&&!g.current.contains(C.target)&&d(!1)};return document.addEventListener("mousedown",E),location.href&&location.href.indexOf("/login")!=-1&&setTimeout(()=>{let C=document.getElementById("signin-btn");C&&(C.style.visibility="visible")},0),yf(!1).then(C=>{if(C&&C.data&&C.data.session){const W=C.data.session;let fe={...W.user,...W.user.user_metadata||{}};delete fe.user_metadata,a(fe)}}),()=>document.removeEventListener("mousedown",E)},[]),m.jsxs(m.Fragment,{children:[m.jsx("nav",{className:"bg-white border-b border-[#DFE6E9] h-14 sm:h-16 relative",children:m.jsx("div",{className:"max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 h-full",children:m.jsxs("div",{className:"flex items-center justify-between h-full gap-2",children:[m.jsxs("div",{className:"flex items-center gap-4 sm:gap-8 flex-shrink min-w-0",children:[m.jsx("a",{href:dt("/",v),className:"flex items-center gap-2 h-7 sm:h-10 flex-shrink-0",children:m.jsx("img",{src:"https://www.transcript365.com/images/transcript365-logo-full.png",style:{width:"162px",maxHeight:"36px"},alt:"Transcript365",className:"w-12 h-12"})}),m.jsxs("div",{className:"hidden lg:flex items-center gap-6",children:[m.jsxs("div",{className:"relative",ref:p,children:[m.jsxs("button",{onClick:()=>h(!u),className:"flex items-center gap-1 text-sm font-medium text-[#636E72] hover:text-[#41C97F] transition-colors",children:[Tt.tools.name,m.jsx(Sr,{className:"w-4 h-4"})]}),u&&m.jsx("div",{className:"absolute top-full left-0 mt-2 w-64 bg-white border border-[#DFE6E9] rounded-lg shadow-lg py-2 z-50",children:So.map((E,C)=>m.jsxs("a",{href:E.link,className:"flex items-center gap-3 px-4 py-2.5 hover:bg-[#F5F7FA] transition-colors group",onClick:()=>h(!1),children:[E.platform=="tiktok"&&m.jsx(Rr,{className:"w-5 h-5 text-[#000000] group-hover:scale-110 transition-transform"}),E.platform=="instagram"&&m.jsx(kr,{className:"w-5 h-5 text-pink-600 group-hover:scale-110 transition-transform"}),E.platform=="youtube"&&m.jsx(xr,{className:"w-5 h-5 text-red-600 group-hover:scale-110 transition-transform"}),E.platform=="facebook"&&m.jsx(Er,{className:"w-5 h-5 text-[#1877F2] group-hover:scale-110 transition-transform"}),E.platform=="twitter"&&m.jsx(jr,{className:"w-5 h-5 text-[#000000] group-hover:scale-110 transition-transform"}),E.platform=="xiaohongshu"&&m.jsx(Ir,{className:"w-5 h-5 group-hover:scale-110 transition-transform"}),m.jsx("span",{className:"text-sm text-[#2D3436] flex-1",children:E.title}),E.tip&&m.jsx("span",{className:"text-xs font-bold text-white bg-[#41C97F] px-2 py-0.5 rounded-full",children:E.tip})]},C))})]}),m.jsxs("div",{className:"relative",ref:b,children:[m.jsxs("button",{onClick:()=>w(!y),className:"flex items-center gap-1 text-sm font-medium text-[#636E72] hover:text-[#41C97F] transition-colors",children:[Tt.integrations.name,m.jsx(Sr,{className:"w-4 h-4"})]}),y&&m.jsxs("div",{className:(ls.length>0&&pr.length>0?"w-[500px] grid-cols-2 ":"w-[260px] grid-cols-1 ")+" absolute top-full left-0 mt-2 bg-white border border-[#DFE6E9] rounded-lg shadow-lg p-4 z-50 grid gap-6",children:[m.jsxs("div",{children:[m.jsxs("div",{className:"flex items-center gap-2 mb-3 px-2",children:[m.jsx(hu,{className:"w-4 h-4 text-[#636E72]"}),m.jsx("h4",{className:"text-xs font-bold text-[#636E72] uppercase tracking-wide",children:"Chrome Extensions"})]}),m.jsx("div",{className:"space-y-1",children:ls.map((E,C)=>m.jsxs("a",{href:E.link,className:"flex items-center gap-3 px-2 py-2 hover:bg-[#F5F7FA] rounded transition-colors group",onClick:()=>w(!1),children:[E.platform=="tiktok"&&m.jsx(Rr,{className:"w-4 h-4 text-[#000000] group-hover:scale-110 transition-transform"}),E.platform=="instagram"&&m.jsx(kr,{className:"w-4 h-4 text-pink-600 group-hover:scale-110 transition-transform"}),E.platform=="youtube"&&m.jsx(xr,{className:"w-4 h-4 text-red-600 group-hover:scale-110 transition-transform"}),E.platform=="facebook"&&m.jsx(Er,{className:"w-4 h-4 text-[#1877F2] group-hover:scale-110 transition-transform"}),E.platform=="twitter"&&m.jsx(jr,{className:"w-4 h-4 text-[#000000] group-hover:scale-110 transition-transform"}),E.platform=="xiaohongshu"&&m.jsx(Ir,{className:"w-4 h-4 group-hover:scale-110 transition-transform"}),m.jsx("span",{className:"text-sm text-[#2D3436]",children:E.title}),E.tip&&m.jsx("span",{className:"text-[9px] font-bold text-white bg-[#41C97F] px-1.5 py-0.5 rounded-full",children:E.tip})]},C))})]}),pr.length>0&&m.jsxs("div",{children:[m.jsxs("div",{className:"flex items-center gap-2 mb-3 px-2",children:[m.jsx("svg",{className:"w-4 h-4 text-[#636E72]",viewBox:"0 0 24 24",fill:"
61currentColor",children:m.jsx("path",{d:"M20.408 2.872c-.437-.315-.937-.538-1.473-.653-1.304-.277-2.62-.214-3.85.21-1.647.567-3.105 1.598-4.197 2.967a8.87 8.87 0 00-1.472 3.32c-.224.99-.27 2.013-.133 3.017.035.26.083.517.142.77.028.118.059.236.093.353.03.107.064.212.1.316.03.087.062.172.095.257.067.168.139.333.217.495.011.023.021.047.033.07a7.33 7.33 0 001.67 2.305c.722.68 1.587 1.18 2.532 1.466.946.286 1.947.348 2.927.183 1.962-.331 3.73-1.363 5.008-2.92.078-.095.153-.193.227-.291a7.77 7.77 0 00.93-1.582c.214-.498.359-1.022.432-1.56.133-.988.016-2-.342-2.93-.716-1.857-2.165-3.392-4.051-4.288C18.87 3.91 17.35 3.415 15.813 3.23c-1.536-.184-3.095-.067-4.588.33-2.987.797-5.59 2.68-7.332 5.3-.87 1.313-1.488 2.804-1.79 4.38-.152.79-.23 1.595-.23 2.403 0 .808.078 1.613.23 2.403.304 1.577.92 3.068 1.79 4.38 1.742 2.62 4.345 4.503 7.332 5.3 1.493.398 3.052.515 4.588.33 1.537-.184 3.057-.68 4.421-1.437 1.364-.758 2.552-1.768 3.49-2.967.938-1.2 1.61-2.568 1.967-4.022.179-.728.27-1.475.27-2.227 0-4.65-3.108-8.58-7.333-9.82z"})}),m.jsx("h4",{className:"text-xs font-bold text-[#636E72] uppercase tracking-wide",children:"Edge Extensions"})]}),m.jsx("div",{className:"space-y-1",children:pr.map((E,C)=>m.jsxs("a",{href:E.link,className:"flex items-center gap-3 px-2 py-2 hover:bg-[#F5F7FA] rounded transition-colors group",onClick:()=>w(!1),children:[E.platform=="tiktok"&&m.jsx(Rr,{className:"w-4 h-4 text-[#000000] group-hover:scale-110 transition-transform"}),E.platform=="instagram"&&m.jsx(kr,{className:"w-4 h-4 text-pink-600 group-hover:scale-110 transition-transform"}),E.platform=="youtube"&&m.jsx(xr,{className:"w-4 h-4 text-red-600 group-hover:scale-110 transition-transform"}),E.platform=="facebook"&&m.jsx(Er,{className:"w-4 h-4 text-[#1877F2] group-hover:scale-110 transition-transform"}),E.platform=="twitter"&&m.jsx(jr,{className:"w-4 h-4 text-[#000000] group-hover:scale-110 transition-transform"}),E.platform=="xiaohongshu"&&m.jsx(Ir,{className:"w-4 h-4 group-hover:scale-110 transition-transform"}),m.jsx("span",{className:"text-sm text-[#2D3436]",children:E.title}),E.tip&&m.jsx("span",{className:"text-[9px] font-bold text-white bg-[#41C97F] px-1.5 py-0.5 rounded-full",children:E.tip})]},C))})]})]})]}),_o.map((E,C)=>m.jsx("a",{href:E.link,className:"text-sm font-medium text-[#636E72] hover:text-[#41C97F] transition-colors",children:E.title},C))]})]}),m.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-shrink-0",children:[m.jsxs("div",{className:"relative",ref:g,children:[m.jsxs("button",{onClick:()=>d(!f),className:"flex items-center gap-1.5 text-sm font-medium text-[#636E72] hover:text-[#41C97F] transition-colors",children:[m.jsx(mu,{className:"w-4 h-4"}),m.jsx("span",{children:$?.name}),m.jsx(Sr,{className:"w-4 h-4"})]}),f&&m.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-white border border-[#DFE6E9] rounded-lg shadow-lg py-2 z-50 max-h-96 overflow-y-auto",children:_n.map(E=>m.jsxs("button",{onClick:()=>{A(E.code),d(!1),H(E.code)},className:`w-full flex items-center justify-between px-4 py-2.5 hover:bg-[#F5F7FA] transition-colors text-left ${O===E.code?"bg-[#F0FDF4]":""}`,children:[m.jsx("span",{className:"text-sm text-[#2D3436]",children:E.name}),O===E.code&&m.jsx("span",{className:"text-[#41C97F]",children:"✓"})]},E.code))})]}),!(o&&o.id)&&m.jsxs("div",{className:"hidden lg:flex items-center gap-3",children:[m.jsx("button",{onClick:Eo,className:"px-5 py-2.5 text-base text-[#636E72] font-semibold hover:text-[#41C97F] transition-colors cursor-pointer whitespace-nowrap",children:Tt.signin.name}),m.jsx("button",{onClick:ko,className:"px-5 py-2.5 text-base bg-[#41C97F] text-white rounded-lg font-semibold hover:bg-[#36B56D] transition-all hover:shadow-lg hover:-translate-y-0.5 cursor-pointer whitespace-nowrap",children:Tt.signup.name})]}),o&&o.id&&m.jsx("div",{className:"border-t border-[#DFE6E9] p-4",children:m.jsxs("div",{className:"relative",children:[m.jsxs("button",{className:"w-full flex items-center gap-3 p-2 rounded-lg hover:bg-[#F5F7FA] transition-colors",onClick:()=>l(!c),children:[!o.avatar_url&&m.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-[#41C97F] to-[#2EAA5F] flex items-center justify-center text-white font-semibold flex-shrink-0",children:(o.full_name||o.name||o.email).substring(0,1)}),o.avatar_url&&m.jsx("img",{style:{width:"32px",height:"32px",borderRadius:"50%"},src:o.avatar_url,alt:"user avatar"}),m.jsx("div",{className:"flex-1 text-left overflow-hidden",children:m.jsx("div",{className:"text-sm font-semibold text-[#2D3436] truncate",children:o.full_name||o.name})})]}),c&&m.jsxs("div",{style:{zIndex:1e3},className:"absolute left-0 right-0 mb-2 bg-white border border-[#DFE6E9] rounded-lg shadow-lg overflow-hidden",children:[m.jsx("button",{onClick:()=>{location.href="/account"},className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-[#F5F7FA] transition-colors text-left",children:m.jsx("span",{className:"text-sm text-[#2D3436]",children:"Account"})}),m.jsx("button",{onClick:()=>{location.href="/my-transcripts"},className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-[#F5F7FA] transition-colors text-left",children:m.jsx("span",{className:"text-sm text-[#2D3436]",children:"My transcript"})}),m.jsx("button",{onClick:_f,className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-[#F5F7FA] transition-colors text-left",children:m.jsx("span",{className:"text-sm text-[#2D3436]",children:"Sign Out"})})]})]})})]})]})})}),t&&m.jsx(kf,{onClose:()=>e(!1)})]})}function jf({platform:t}){const{locale_languages:[e,r]}=Jr(),n=r.common.pages.footer,i=n.onlinetools.items.filter(u=>tr(u.platform)!="").map(u=>({...u,link:dt(tr(u.platform),e)})),o=n.integrations.chrome.filter(u=>u.link!=""),a=n.integrations.edge.filter(u=>u.link!=""),c=n.resources.items.filter(u=>u.link!="").map(u=>({...u,link:dt(u.link,e)})),l=n.compare.items.filter(u=>u.link!="");return m.jsx("footer",{className:"bg-gradient-to-br from-[#2D3436] to-[#1E272E] text-white",children:m.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12",children:[m.jsxs("div",{className:"flex flex-col lg:flex-row gap-8 mb-8",children:[m.jsxs("div",{className:"lg:w-1/4 flex-shrink-0",children:[m.jsxs("h3",{className:"text-lg sm:text-xl font-bold mb-2",children:["Transcript",m.jsx("span",{className:"text-[#41C97F]",children:"365"})]}),m.jsx("p",{className:"text-white/60 text-xs leading-relaxed max-w-xs mb-4",children:n.desc}),m.jsxs("div",{children:[m.jsx("h5",{className:"text-[10px] font-semibold text-white/40 uppercase tracking-wide mb-2",children:n.followus}),m.jsxs("div",{className:"flex gap-2",children:[m.jsx("a",{href:"https://github.com",target:"_blank",rel:"noopener noreferrer",className:"w-8 h-8 rounded-lg bg-white/5 hover:bg-[#41C97F] transition-all flex items-center justify-center group",title:"GitHub",children:m.jsx(pu,{className:"w-4 h-4 text-white/70 group-hover:text-white transition-colors"})}),m.jsx("a",{href:"mailto:[email protected]",className:"w-8 h-8 rounded-lg bg-white/5 hover:bg-[#41C97F] transition-all flex items-center justify-center group",title:"Email Us",children:m.jsx(wu,{className:"w-4 h-4 text-white/70 group-hover:text-white transition-colors"})})]})]})]}),m.jsxs("div",{className:"lg:flex-1 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 ga
61p-6 sm:gap-8",children:[m.jsxs("div",{children:[m.jsx("h4",{className:"text-xs sm:text-sm font-bold mb-2 sm:mb-3 text-white",children:n.onlinetools.title}),m.jsx("ul",{className:"space-y-1.5 sm:space-y-2 text-xs",children:i.map((u,h)=>m.jsx("li",{children:m.jsxs("a",{href:u.link,className:"text-white/70 hover:text-[#41C97F] transition-colors flex items-center gap-2",children:[m.jsx("span",{className:"flex-1 whitespace-nowrap",children:u.title}),u.tip&&m.jsx("span",{className:"text-[9px] font-bold text-white bg-[#41C97F] px-1.5 py-0.5 rounded-full",children:u.tip})]})},h))})]}),m.jsxs("div",{children:[m.jsx("h4",{className:"text-xs sm:text-sm font-bold mb-2 sm:mb-3 text-white",children:n.integrations.title}),n.integrations.chrome&&m.jsxs("div",{className:"mb-2 sm:mb-3",children:[m.jsx("h5",{className:"text-[10px] font-semibold text-white/40 uppercase tracking-wide mb-2",children:"Chrome"}),m.jsx("ul",{className:"space-y-1.5 text-xs",children:o.map((u,h)=>m.jsx("li",{children:m.jsxs("a",{href:u.link,className:"text-white/70 hover:text-[#41C97F] transition-colors flex items-center gap-2",children:[m.jsx("span",{className:"flex-1 whitespace-nowrap",children:u.title}),u.tip&&m.jsx("span",{className:"text-[9px] font-bold text-white bg-[#41C97F] px-1.5 py-0.5 rounded-full",children:u.tip})]})},h))})]}),a.length>0&&m.jsxs("div",{children:[m.jsx("h5",{className:"text-[10px] font-semibold text-white/40 uppercase tracking-wide mb-2",children:"Edge"}),m.jsx("ul",{className:"space-y-1.5 text-xs",children:a.map((u,h)=>m.jsx("li",{children:m.jsxs("a",{href:u.link,className:"text-white/70 hover:text-[#41C97F] transition-colors flex items-center gap-2",children:[m.jsx("span",{className:"flex-1 whitespace-nowrap",children:u.title}),u.tip&&m.jsx("span",{className:"text-[9px] font-bold text-white bg-[#41C97F] px-1.5 py-0.5 rounded-full",children:u.tip})]})},h))})]})]}),m.jsxs("div",{children:[m.jsx("h4",{className:"text-xs sm:text-sm font-bold mb-2 sm:mb-3 text-white",children:n.resources.title}),m.jsx("ul",{className:"space-y-1.5 sm:space-y-2 text-xs",children:c.map((u,h)=>m.jsx("li",{children:m.jsxs("a",{href:u.link,className:"text-white/70 hover:text-[#41C97F] transition-colors flex items-center gap-2",children:[m.jsx("span",{className:"flex-1 whitespace-nowrap",children:u.title}),u.tip&&m.jsx("span",{className:"text-[9px] font-bold text-white bg-[#41C97F] px-1.5 py-0.5 rounded-full",children:u.tip})]})},h))})]}),l.length>0&&m.jsxs("div",{children:[m.jsx("h4",{className:"text-xs sm:text-sm font-bold mb-2 sm:mb-3 text-white",children:n.compare.title}),m.jsx("ul",{className:"space-y-1.5 sm:space-y-2 text-xs",children:l.map((u,h)=>m.jsx("li",{children:m.jsxs("a",{href:u.link,className:"text-white/70 hover:text-[#41C97F] transition-colors flex items-center gap-2",children:[m.jsx("span",{className:"flex-1 whitespace-nowrap",children:u.title}),u.tip&&m.jsx("span",{className:"text-[9px] font-bold text-white bg-[#41C97F] px-1.5 py-0.5 rounded-full",children:u.tip})]})},h))})]}),m.jsxs("div",{children:[m.jsx("h4",{className:"text-xs sm:text-sm font-bold mb-2 sm:mb-3 text-white",children:n.legal.title}),m.jsx("ul",{className:"space-y-1.5 sm:space-y-2 text-xs",children:n.legal.items.map((u,h)=>m.jsx("li",{children:m.jsxs("a",{href:u.link,className:"text-white/70 hover:text-[#41C97F] transition-colors flex items-center gap-2",children:[m.jsx("span",{className:"flex-1 whitespace-nowrap",children:u.title}),u.tip&&m.jsx("span",{className:"text-[9px] font-bold text-white bg-[#41C97F] px-1.5 py-0.5 rounded-full",children:u.tip})]})},h))})]})]})]}),m.jsx("div",{className:"border-t border-white/10 pt-4 sm:pt-6 mt-4",children:m.jsx("p",{className:"text-white/40 text-[10px] sm:text-[11px] text-center md:text-left",children:n.copyright})})]})})}function If(t){const e=new Date(t);if(isNaN(e.getTime()))return"-";const s=new Date().getTime()-e.getTime();if(s<0)return Sn(e);const n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}minutes ago`;const i=Math.floor(n/60);return i<24?`${i}hours ago`:Sn(e)}function Sn(t){const e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0");return`${e}年${r}月${s}日`}export{jf as F,Rf as N,Cf as a,Of as b,he as c,dt as f,ri as i,If as t,Tf as y};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.