@mitway/sdk 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var postgrestJs=require('@mitway/postgrest-js'),socket_ioClient=require('socket.io-client');var c=class s extends Error{statusCode;error;nextActions;constructor(e,t,r,n){super(e),this.name="MitwayBaasError",this.statusCode=t,this.error=r,this.nextActions=n;}static fromApiError(e){return new s(e.message,e.statusCode,e.error,e.nextActions)}};var ee=["authorization","x-api-key","cookie","set-cookie"],te=["password","token","accesstoken","refreshtoken","authorization","secret","apikey","api_key","email","ssn","creditcard","credit_card"];function re(s){let e={};for(let[t,r]of Object.entries(s))ee.includes(t.toLowerCase())?e[t]="***REDACTED***":e[t]=r;return e}function C(s){if(s==null)return s;if(typeof s=="string")try{let e=JSON.parse(s);return C(e)}catch{return s}if(Array.isArray(s))return s.map(C);if(typeof s=="object"){let e={};for(let[t,r]of Object.entries(s))te.includes(t.toLowerCase().replace(/[-_]/g,""))?e[t]="***REDACTED***":e[t]=C(r);return e}return s}function V(s){if(s==null)return "";if(typeof s=="string")try{return JSON.stringify(JSON.parse(s),null,2)}catch{return s}if(typeof FormData<"u"&&s instanceof FormData)return "[FormData]";try{return JSON.stringify(s,null,2)}catch{return "[Unserializable body]"}}var R=class{enabled;customLog;constructor(e){typeof e=="function"?(this.enabled=true,this.customLog=e):(this.enabled=!!e,this.customLog=null);}log(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.log(r,...t);}warn(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.warn(r,...t);}error(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.error(r,...t);}logRequest(e,t,r,n){if(!this.enabled)return;let i=[`\u2192 ${e} ${t}`];r&&Object.keys(r).length>0&&i.push(` Headers: ${JSON.stringify(re(r))}`);let o=V(C(n));if(o){let a=o.length>1e3?o.slice(0,1e3)+"... [truncated]":o;i.push(` Body: ${a}`);}this.log(i.join(`
2
- `));}logResponse(e,t,r,n,i){if(!this.enabled)return;let o=[`\u2190 ${e} ${t} ${r} (${n}ms)`],a=V(C(i));if(a){let g=a.length>1e3?a.slice(0,1e3)+"... [truncated]":a;o.push(` Body: ${g}`);}r>=400?this.error(o.join(`
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var postgrestJs=require('@mitway/postgrest-js'),socket_ioClient=require('socket.io-client');var c=class r extends Error{statusCode;error;nextActions;constructor(e,t,s,n){super(e),this.name="MitwayBaasError",this.statusCode=t,this.error=s,this.nextActions=n;}static fromApiError(e){return new r(e.message,e.statusCode,e.error,e.nextActions)}};var re=["authorization","x-api-key","cookie","set-cookie"],ie=["password","token","accesstoken","refreshtoken","authorization","secret","apikey","api_key","email","ssn","creditcard","credit_card"];function oe(r){let e={};for(let[t,s]of Object.entries(r))re.includes(t.toLowerCase())?e[t]="***REDACTED***":e[t]=s;return e}function P(r){if(r==null)return r;if(typeof r=="string")try{let e=JSON.parse(r);return P(e)}catch{return r}if(Array.isArray(r))return r.map(P);if(typeof r=="object"){let e={};for(let[t,s]of Object.entries(r))ie.includes(t.toLowerCase().replace(/[-_]/g,""))?e[t]="***REDACTED***":e[t]=P(s);return e}return r}function X(r){if(r==null)return "";if(typeof r=="string")try{return JSON.stringify(JSON.parse(r),null,2)}catch{return r}if(typeof FormData<"u"&&r instanceof FormData)return "[FormData]";try{return JSON.stringify(r,null,2)}catch{return "[Unserializable body]"}}var R=class{enabled;customLog;constructor(e){typeof e=="function"?(this.enabled=true,this.customLog=e):(this.enabled=!!e,this.customLog=null);}log(e,...t){if(!this.enabled)return;let s=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(s,...t):console.log(s,...t);}warn(e,...t){if(!this.enabled)return;let s=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(s,...t):console.warn(s,...t);}error(e,...t){if(!this.enabled)return;let s=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(s,...t):console.error(s,...t);}logRequest(e,t,s,n){if(!this.enabled)return;let i=[`\u2192 ${e} ${t}`];s&&Object.keys(s).length>0&&i.push(` Headers: ${JSON.stringify(oe(s))}`);let o=X(P(n));if(o){let a=o.length>1e3?o.slice(0,1e3)+"... [truncated]":o;i.push(` Body: ${a}`);}this.log(i.join(`
2
+ `));}logResponse(e,t,s,n,i){if(!this.enabled)return;let o=[`\u2190 ${e} ${t} ${s} (${n}ms)`],a=X(P(i));if(a){let d=a.length>1e3?a.slice(0,1e3)+"... [truncated]":a;o.push(` Body: ${d}`);}s>=400?this.error(o.join(`
3
3
  `)):this.log(o.join(`
4
- `));}};var z="mitway_baas_csrf_token",ne="mitway_baas_session";function Y(){return typeof localStorage<"u"?{getItem:e=>{try{return localStorage.getItem(e)}catch{return null}},setItem:(e,t)=>{try{localStorage.setItem(e,t);}catch{}},removeItem:e=>{try{localStorage.removeItem(e);}catch{}}}:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}}var se={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function Q(){if(typeof document>"u")return null;let s=document.cookie.split(";").find(e=>e.trim().startsWith(`${z}=`));return s&&s.split("=")[1]||null}function D(s){if(typeof document>"u")return;let e=10080*60,t=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${z}=${encodeURIComponent(s)}; path=/; max-age=${e}; SameSite=Lax${t}`;}function N(){if(typeof document>"u")return;let s=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${z}=; path=/; max-age=0; SameSite=Lax${s}`;}var S=class{accessToken=null;refreshToken=null;user=null;persistSession;storageKey;storage;onTokenChange=null;constructor(e){this.persistSession=e?.persistSession??true,this.storageKey=e?.storageKey??ne,this.storage=this.persistSession?e?.storage??Y():se,(e?.multiTab??true)&&this.persistSession&&typeof window<"u"&&typeof localStorage<"u"&&window.addEventListener("storage",this.handleStorageEvent),this.restoreSession();}handleStorageEvent=e=>{e.key===this.storageKey&&(typeof localStorage<"u"&&e.storageArea!==localStorage||this.syncFromStorage(e.newValue));};syncFromStorage(e){let t=this.accessToken;if(e===null)this.accessToken=null,this.refreshToken=null,this.user=null;else try{let r=JSON.parse(e);if(!r.accessToken||!r.user)return;this.accessToken=r.accessToken,this.refreshToken=r.refreshToken??null,this.user=r.user;}catch{return}t!==this.accessToken&&this.onTokenChange&&this.onTokenChange();}saveSession(e){let t=e.accessToken!==this.accessToken;this.accessToken=e.accessToken,this.user=e.user,e.refreshToken!==void 0&&(this.refreshToken=e.refreshToken??null),this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getSession(){return !this.accessToken||!this.user?null:{accessToken:this.accessToken,refreshToken:this.refreshToken??void 0,user:this.user}}getAccessToken(){return this.accessToken}setAccessToken(e){let t=e!==this.accessToken;this.accessToken=e,this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getRefreshToken(){return this.refreshToken}setRefreshToken(e){this.refreshToken=e,this.persist();}getUser(){return this.user}setUser(e){this.user=e,this.persist();}clearSession(){let e=this.accessToken!==null;this.accessToken=null,this.refreshToken=null,this.user=null,this.removePersisted(),e&&this.onTokenChange&&this.onTokenChange();}restoreSession(){if(!this.persistSession)return false;try{let e=this.storage.getItem(this.storageKey);if(!e)return !1;let t=JSON.parse(e);return !t.accessToken||!t.user?!1:(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken??null,this.user=t.user,!0)}catch{return false}}persist(){if(!this.persistSession||!this.accessToken||!this.user)return;let e={accessToken:this.accessToken,user:this.user};this.refreshToken&&(e.refreshToken=this.refreshToken),this.storage.setItem(this.storageKey,JSON.stringify(e));}removePersisted(){this.persistSession&&this.storage.removeItem(this.storageKey);}};function P(s){if(!s||typeof s!="object")return s;let e=s,t={...e},r=false;return "access_token"in e&&!("accessToken"in e)&&(t.accessToken=e.access_token,delete t.access_token,r=true),"csrf_token"in e&&!("csrfToken"in e)&&(t.csrfToken=e.csrf_token,delete t.csrf_token,r=true),"refresh_token"in e&&!("refreshToken"in e)&&(t.refreshToken=e.refresh_token,delete t.refresh_token,r=true),r?t:s}var ie=new Set([500,502,503,504]),oe=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),_=class{baseUrl;fetch;defaultHeaders;anonKey;userToken=null;logger;autoRefreshToken=true;isRefreshing=false;refreshPromise=null;tokenManager;refreshToken=null;timeout;retryCount;retryDelay;constructor(e,t,r){if(this.baseUrl=e.baseUrl||"http://localhost:7130",this.autoRefreshToken=e.autoRefreshToken??true,this.fetch=e.fetch||(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),this.anonKey=e.anonKey,this.defaultHeaders={...e.headers},this.tokenManager=t??new S,this.logger=r||new R(false),this.timeout=e.timeout??3e4,this.retryCount=e.retryCount??3,this.retryDelay=e.retryDelay??500,!this.fetch)throw new Error("Fetch is not available. Provide a fetch implementation in the SDK config.")}buildUrl(e,t){let r=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([n,i])=>{if(n==="select"){let o=i.replace(/\s+/g," ").trim();o=o.replace(/\s*\(\s*/g,"(").replace(/\s*\)\s*/g,")").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/,\s+(?=[^()]*\))/g,","),r.searchParams.append(n,o);}else r.searchParams.append(n,i);}),r.toString()}isRetryableStatus(e){return ie.has(e)}computeRetryDelay(e){let r=this.retryDelay*Math.pow(2,e-1)*(.85+Math.random()*.3);return Math.round(r)}async handleRequest(e,t,r={}){let{params:n,headers:i={},body:o,signal:a,...g}=r,p=this.buildUrl(t,n),v=Date.now(),T=oe.has(e.toUpperCase())||r.idempotent===true?this.retryCount:0,b={...this.defaultHeaders},G=this.userToken||this.anonKey;G&&(b.Authorization=`Bearer ${G}`);let F;o!==void 0&&(typeof FormData<"u"&&o instanceof FormData?F=o:(e!=="GET"&&(b["Content-Type"]="application/json;charset=UTF-8"),F=JSON.stringify(o))),i instanceof Headers?i.forEach((f,h)=>{b[h]=f;}):Array.isArray(i)?i.forEach(([f,h])=>{b[f]=h;}):Object.assign(b,i),this.logger.logRequest(e,p,b,F);let q;for(let f=0;f<=T;f++){if(f>0){let l=this.computeRetryDelay(f);if(this.logger.warn(`Retry ${f}/${T} for ${e} ${p} in ${l}ms`),a?.aborted)throw a.reason;await new Promise((u,K)=>{let k=()=>{clearTimeout(Z),K(a.reason);},Z=setTimeout(()=>{a&&a.removeEventListener("abort",k),u();},l);a&&a.addEventListener("abort",k,{once:true});});}let h,m;if((this.timeout>0||a)&&(h=new AbortController,this.timeout>0&&(m=setTimeout(()=>h.abort(),this.timeout)),a))if(a.aborted)h.abort(a.reason);else {let l=()=>h.abort(a.reason);a.addEventListener("abort",l,{once:true}),h.signal.addEventListener("abort",()=>{a.removeEventListener("abort",l);},{once:true});}try{let l=await this.fetch(p,{method:e,headers:b,body:F,...g,...h?{signal:h.signal}:{}});if(this.isRetryableStatus(l.status)&&f<T){m!==void 0&&clearTimeout(m),await l.body?.cancel(),q=new c(`Server error: ${l.status} ${l.statusText}`,l.status,"SERVER_ERROR");continue}if(l.status===204){m!==void 0&&clearTimeout(m);return}let u,K=l.headers.get("content-type");try{K?.includes("json")?u=await l.json():u=await l.text();}catch(k){throw m!==void 0&&clearTimeout(m),new c(`Failed to parse response body: ${k?.message||"Unknown error"}`,l.status,l.ok?"PARSE_ERROR":"REQUEST_FAILED")}if(m!==void 0&&clearTimeout(m),!l.ok){if(this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"error"in u&&u.error!==null&&typeof u.error=="object"){let k=u.error;throw new c(k.message||l.statusText||"Request failed",k.statusCode||l.status,k.code||k.error||"REQUEST_FAILED",k.nextActions)}throw new c(`Request failed: ${l.statusText}`,l.status,"REQUEST_FAILED")}return this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"data"in u&&"error"in u&&u.error===null?u.data:u}catch(l){if(m!==void 0&&clearTimeout(m),l?.name==="AbortError")throw h&&h.signal.aborted&&this.timeout>0&&!a?.aborted?new c(`Request timed out after ${this.timeout}ms`,408,"REQUEST_TIMEOUT"):l;if(l instanceof c)throw l;if(f<T){q=l;continue}throw new c(`Network request failed: ${l?.message||"Unknown error"}`,0,"NETWORK_ERROR")}}throw q||new c("Request failed after all retry attempts",0,"NETWORK_ERROR")}async request(e,t,r={}){try{return await this.handleRequest(e,t,{...r})}catch(n){if(n instanceof c&&n.statusCode===401&&this.autoRefreshToken&&this.refreshToken&&!t.includes("/api/auth/refresh"))try{let i=await this.handleTokenRefresh();this.setAuthToken(i.accessToken),i.refreshToken&&this.setRefreshToken(i.refreshToken),i.csrfToken&&D(i.csrfToken);let o=i.user??this.tokenManager.getUser();return o&&this.tokenManager.saveSession({accessToken:i.accessToken,refreshToken:i.refreshToken,user:o}),await this.handleRequest(e,t,{...r})}catch(i){throw this.tokenManager.clearSession(),this.userToken=null,this.refreshToken=null,N(),i}throw n}}async rawFetch(e,t={}){let r=this.buildUrl(e),n=new Headers(t.headers??{});for(let[i,o]of Object.entries(this.defaultHeaders))n.has(i)||n.set(i,o);if(!n.has("Authorization")){let i=this.userToken??this.anonKey;i&&n.set("Authorization",`Bearer ${i}`);}return this.fetch(r,{...t,headers:n})}get(e,t){return this.request("GET",e,t)}post(e,t,r){return this.request("POST",e,{...r,body:t})}put(e,t,r){return this.request("PUT",e,{...r,body:t})}patch(e,t,r){return this.request("PATCH",e,{...r,body:t})}delete(e,t){return this.request("DELETE",e,t)}setAuthToken(e){this.userToken=e;}setRefreshToken(e){this.refreshToken=e;}getHeaders(){let e={...this.defaultHeaders},t=this.userToken||this.anonKey;return t&&(e.Authorization=`Bearer ${t}`),e}async handleTokenRefresh(){return this.isRefreshing?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let e=Q(),t=this.refreshToken?{refreshToken:this.refreshToken}:void 0,r=await this.handleRequest("POST","/api/auth/refresh",{body:t,headers:e?{"X-CSRF-Token":e}:{},credentials:"include"});return P(r)}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}};function w(s,e){return s instanceof c?{data:null,error:s}:{data:null,error:new c(s instanceof Error?s.message:e,500,"AUTH_ERROR")}}var A=class{constructor(e,t){this.http=e;this.tokenManager=t;this.tokenManager.onTokenChange=()=>this._emitFromTokenChange();let r=this.tokenManager.getSession();if(r){this.http.setAuthToken(r.accessToken);let n=this.tokenManager.getRefreshToken();n&&this.http.setRefreshToken(n),this.lastEmittedUserId=r.user.id,this.lastEmittedAccessToken=r.accessToken;}}http;tokenManager;stateChangeListeners=new Set;lastEmittedUserId=null;lastEmittedAccessToken=null;onAuthStateChange(e){return this.stateChangeListeners.add(e),{unsubscribe:()=>{this.stateChangeListeners.delete(e);}}}emit(e,t){for(let r of this.stateChangeListeners)try{r(e,t);}catch{}}_emitFromTokenChange(){let e=this.tokenManager.getSession();e?(this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null)):(this.http.setAuthToken(null),this.http.setRefreshToken(null));let t=this.lastEmittedUserId,r=this.lastEmittedAccessToken;if(!e){t!==null&&(this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null));return}let n=e.user.id;if(t===null){this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}if(t!==n){this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null),this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}r!==e.accessToken&&(this.lastEmittedAccessToken=e.accessToken,this.emit("TOKEN_REFRESHED",e));}saveSessionFromResponse(e){let t={accessToken:e.accessToken,refreshToken:e.refreshToken,user:e.user};e.csrfToken&&D(e.csrfToken),this.tokenManager.saveSession(t),this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null);}async signUp(e){try{let t=await this.http.post("/api/auth/register",e,{credentials:"include"}),r=P(t);return r?.accessToken&&r.user&&this.saveSessionFromResponse(r),{data:r,error:null}}catch(t){return w(t,"Sign up failed")}}async signInWithPassword(e){try{let t=await this.http.post("/api/auth/login",e,{credentials:"include"}),r=P(t);return r?.accessToken&&r.user&&this.saveSessionFromResponse(r),{data:r,error:null}}catch(t){return w(t,"Sign in failed")}}async signOut(){try{try{await this.http.post("/api/auth/logout",void 0,{credentials:"include"});}catch{}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),N(),{error:null}}catch{return {error:new c("Failed to sign out",500,"SIGNOUT_ERROR")}}}async refreshSession(){try{let e=await this.http.handleTokenRefresh();if(e?.accessToken){let t=e.user??this.tokenManager.getUser();if(t){let r={...e,user:t};return this.saveSessionFromResponse(r),{data:r,error:null}}}return {data:e,error:null}}catch(e){return w(e,"Session refresh failed")}}async initialize(){let e=this.tokenManager.getSession();if(!e)return this.emit("INITIAL_SESSION",null),{data:null,error:new c("No persisted session",0,"NO_SESSION")};try{let t=await this.http.get("/api/auth/sessions/current");if(t?.user){this.tokenManager.setUser(t.user);let r=this.tokenManager.getSession();return this.emit("INITIAL_SESSION",r),{data:{user:t.user,accessToken:e.accessToken},error:null}}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),{data:null,error:new c("Invalid session",401,"INVALID_SESSION")}}catch(t){return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),w(t,"Session restore failed")}}getSession(){return this.tokenManager.getSession()}getUser(){return this.tokenManager.getUser()}async getCurrentUser(){try{let e=await this.http.get("/api/auth/sessions/current");if(e?.user){let t={accessToken:this.tokenManager.getSession()?.accessToken??"",user:e.user};this.tokenManager.saveSession(t);}return {data:e,error:null}}catch(e){return w(e,"Failed to get current user")}}async getProfile(e){try{return {data:await this.http.get(`/api/auth/profiles/${encodeURIComponent(e)}`),error:null}}catch(t){return w(t,"Failed to get profile")}}async setProfile(e){try{let t=await this.http.patch("/api/auth/profiles/current",{profile:e}),r=this.tokenManager.getUser();if(t?.profile&&r){let n={...r,profile:t.profile};this.tokenManager.setUser(n),this.emit("USER_UPDATED",this.tokenManager.getSession());}return {data:t,error:null}}catch(t){return w(t,"Failed to update profile")}}};function ce(s,e,t){return async(r,n)=>{let i=typeof r=="string"?r:r.toString(),o=new URL(i),a=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,g=a.match(/^rpc\/(.+)$/),p=g?`/api/database/rpc/${g[1]}`:`/api/database/records/${a}`,v=`${s.baseUrl}${p}${o.search}`,M=new Headers(n?.headers);if(!M.has("Authorization")){let T=e.getAccessToken()??t;T&&M.set("Authorization",`Bearer ${T}`);}return fetch(v,{...n,headers:M})}}var O=class{postgrest;httpClient;constructor(e,t,r){this.httpClient=e,this.postgrest=new postgrestJs.PostgrestClient("http://dummy",{fetch:ce(e,t,r),headers:{}});}from(e){if(!e||typeof e!="string")throw new c("Database.from(table) requires a non-empty string",400,"INVALID_TABLE_NAME");return this.postgrest.from(e)}rpc(e,t,r){return this.postgrest.rpc(e,t,r)}getUrl(){return this.httpClient.baseUrl}};var ue=2e4;function W(s,e){let t=new Error(e);return t.code=s,t}var de=1e4,L=class{constructor(e,t,r={}){this.topic=e;this.realtime=t;this.options=r;}topic;realtime;bindings=[];state="closed";statusCallback=null;presence={};trackedState=null;presenceHeartbeat=null;lastBroadcastTimestamp=null;options;get isPrivate(){return this.options.config?.private===true}get presenceKey(){return this.options.config?.presence?.key}_state(){return this.state}async _rejoinAfterReconnect(){if(this.state!=="closed"){for(let e of this.bindings)e.type==="postgres_changes"&&(e.subscriptionId=void 0);this.state="joining";try{if(await this.registerAllBindings(),this.trackedState){let e=this.realtime._getSocket(),t=this.presenceKey;e?.emit("realtime:presence:track",t!==void 0?{channel:this.topic,state:this.trackedState,key:t}:{channel:this.topic,state:this.trackedState});}this.lastBroadcastTimestamp&&this.bindings.some(e=>e.type==="broadcast")&&this.replay({since:this.lastBroadcastTimestamp}).catch(()=>{}),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(e){this.state="errored",this.statusCallback?.("CHANNEL_ERROR",W("REJOIN_FAILED",e instanceof Error?e.message:String(e)));}}}on(e,t,r){return e==="postgres_changes"?this.bindings.push({type:"postgres_changes",filter:t,callback:r}):e==="broadcast"?this.bindings.push({type:"broadcast",filter:t,callback:r}):this.bindings.push({type:"presence",filter:t,callback:r}),this}async track(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");this.trackedState=e;let r=this.presenceKey;t.emit("realtime:presence:track",r!==void 0?{channel:this.topic,state:e,key:r}:{channel:this.topic,state:e}),this.presenceHeartbeat||(this.presenceHeartbeat=setInterval(()=>{let i=this.realtime._getSocket();i&&this.trackedState&&i.emit("realtime:presence:track",r!==void 0?{channel:this.topic,state:this.trackedState,key:r}:{channel:this.topic,state:this.trackedState});},ue),this.presenceHeartbeat.unref?.());}untrack(){this.trackedState=null,this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),this.realtime._getSocket()?.emit("realtime:presence:untrack",{channel:this.topic});}presenceState(){return this.presence}subscribe(e){return this.statusCallback=e??null,this.state==="joining"||this.state==="joined"?this:(this.state="joining",this.realtime.connect().then(async()=>{try{await this.registerAllBindings(),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(t){this.state="errored";let r=t instanceof Error?t.message:String(t);this.statusCallback?.("CHANNEL_ERROR",W("SUBSCRIBE_FAILED",r));}},t=>{this.state="errored",this.statusCallback?.("CHANNEL_ERROR",W("CONNECT_FAILED",t.message));}),this)}async unsubscribe(){if(this.state==="closed")return;let e=this.realtime._getSocket();if(this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),!e){this.trackedState=null,this.state="closed";return}this.trackedState&&(e.emit("realtime:presence:untrack",{channel:this.topic}),this.trackedState=null);let t=this.bindings.filter(r=>r.type==="postgres_changes");for(let r of t)r.subscriptionId&&(e.emit("realtime:postgres_changes:unsubscribe",{subscription_id:r.subscriptionId}),r.subscriptionId=void 0);this.bindings.some(r=>r.type==="broadcast"||r.type==="presence")&&e.emit("realtime:unsubscribe",{channel:this.topic}),this.realtime._detachChannel(this),this.state="closed",this.statusCallback?.("CLOSED");}async send(e){if(e.type!=="broadcast")throw new c('Only "broadcast" sends are supported \u2014 DB changes flow via your DB writes, not channel.send()',400,"UNSUPPORTED_SEND_TYPE");if(new Set(["postgres_changes","presence_state","presence_join","presence_leave"]).has(e.event))throw new c(`"${e.event}" is a reserved event name \u2014 pick a different name for broadcast events`,400,"RESERVED_EVENT_NAME");let r=this.realtime._getSocket();if(!r)throw new c("Socket not connected",503,"NOT_CONNECTED");let n=this.options.config?.broadcast?.self,i={channel:this.topic,event:e.event,payload:e.payload};return n===false&&(i.self=false),await new Promise(o=>{r.emit("realtime:publish",i,a=>{o(a);});})}async replay(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");t.emit("realtime:broadcast:replay",{channel:this.topic,since:e.since,limit:e.limit,private:this.isPrivate});}_dispatch(e,t){if(e==="postgres_changes"){let n=t;for(let i of this.bindings)if(!(i.type!=="postgres_changes"||!i.subscriptionId||!n.ids.includes(i.subscriptionId)||!(i.filter.event==="*"||i.filter.event===n.data.eventType)))try{i.callback(n.data);}catch{}return}if(e==="presence_state"||e==="presence_join"||e==="presence_leave"){let n=t;if(n.channel!==this.topic)return;if(e==="presence_state"&&n.state)this.presence={...n.state},this.firePresence({event:"sync",state:this.presence});else if(e==="presence_join"&&n.joins)Object.assign(this.presence,n.joins),this.firePresence({event:"join",joins:n.joins});else if(e==="presence_leave"&&n.leaves){for(let i of Object.keys(n.leaves))delete this.presence[i];this.firePresence({event:"leave",leaves:n.leaves});}return}let r=t.meta;r?.timestamp&&(!this.lastBroadcastTimestamp||r.timestamp>this.lastBroadcastTimestamp)&&(this.lastBroadcastTimestamp=r.timestamp);for(let n of this.bindings){if(n.type!=="broadcast"||n.filter.event!==e)continue;let{meta:i,...o}=t;try{n.callback({type:"broadcast",event:e,payload:o});}catch{}}}firePresence(e){for(let t of this.bindings)if(t.type==="presence"&&t.filter.event===e.event)try{e.event==="sync"?t.callback():(e.event,t.callback(e));}catch{}}async registerAllBindings(){let e=this.realtime._getSocket();if(!e)throw new Error("Socket not available");this.bindings.some(n=>n.type==="broadcast"||n.type==="presence")&&await new Promise((n,i)=>{e.emit("realtime:subscribe",{channel:this.topic,private:this.isPrivate},o=>{o.status==="ok"?n():i(new Error(o.error?.message??"subscribe failed"));});});let r=this.bindings.filter(n=>n.type==="postgres_changes");await Promise.all(r.map(n=>new Promise((i,o)=>{e.emit("realtime:postgres_changes:subscribe",{event:n.filter.event,schema:n.filter.schema??"public",table:n.filter.table,filter:n.filter.filter},a=>{a.status==="ok"&&a.subscription_id?(n.subscriptionId=a.subscription_id,i()):o(new Error(a.error?.message??"postgres_changes subscribe failed"));});})));}},I=class{socket=null;baseUrl;options;anonKey;tokenManager;channels=new Map;connecting=null;firstConnected=false;constructor(e,t,r,n={}){this.baseUrl=e,this.tokenManager=t,this.anonKey=r,this.options=n;}get isConnected(){return this.socket?.connected===true}get socketId(){return this.socket?.id}channel(e,t){let r=this.channels.get(e);if(r)return r;let n=new L(e,this,t);return this.channels.set(e,n),n}connect(){return this.isConnected?Promise.resolve():this.connecting?this.connecting:(this.connecting=this.openSocket(),this.connecting)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.firstConnected=false);}_getSocket(){return this.socket}_detachChannel(e){this.channels.delete(e.topic);}openSocket(){let e=this.tokenManager.getAccessToken()??this.anonKey;if(!e){let n=new c("Realtime requires an access token or anonKey",401,"AUTH_INVALID_API_KEY");return this.connecting=null,Promise.reject(n)}let t=this.options.timeoutMs??de,r=socket_ioClient.io(this.baseUrl,{path:this.options.path,transports:this.options.transports??["websocket"],auth:{token:e,...this.options.extraAuth??{}},reconnection:true,timeout:t});return this.socket=r,r.onAny((n,...i)=>this.dispatch(n,i)),r.on("connect",()=>{if(this.firstConnected)for(let n of this.channels.values()){let i=n._state();(i==="joined"||i==="errored")&&n._rejoinAfterReconnect();}}),new Promise((n,i)=>{let o=setTimeout(()=>{r.off("connect",g),r.off("connect_error",p),this.connecting=null,i(new c(`Realtime connection timeout after ${t}ms`,408,"CONNECTION_TIMEOUT"));},t),a=()=>{clearTimeout(o),r.off("connect",g),r.off("connect_error",p);},g=()=>{a(),this.connecting=null,this.firstConnected=true,n();},p=v=>{a(),this.connecting=null,i(new c(v.message,0,"CONNECTION_FAILED"));};r.once("connect",g),r.once("connect_error",p);})}dispatch(e,t){if(e==="postgres_changes"){let n=t[0]??{};this.channels.forEach(i=>i._dispatch("postgres_changes",n));return}if(e==="connect"||e==="disconnect"||e==="connect_error"||e==="error"||e==="realtime:error"||e==="realtime:shutdown")return;let r=t[0]??{};this.channels.forEach(n=>n._dispatch(e,r));}};function j(s){return {id:s.id,name:s.name,public:s.public,fileSizeLimitBytes:s.file_size_limit_bytes,allowedMimeTypes:s.allowed_mime_types,createdAt:s.created_at,updatedAt:s.updated_at}}function $(s,e){return {id:s.id,bucket:e,key:s.key,size:s.size,mimeType:s.mime_type,etag:s.etag,cacheControl:s.cache_control,contentDisposition:s.content_disposition,uploadedBy:s.uploaded_by,uploadedAt:s.uploaded_at,updatedAt:s.updated_at}}function he(s){return {defaultFileSizeLimitBytes:s.default_file_size_limit_bytes,maxFileSizeLimitBytes:s.max_file_size_limit_bytes,tenantStorageQuotaBytes:s.tenant_storage_quota_bytes,reservedSpaceBytes:s.reserved_space_bytes,signedUrlDefaultTtlSec:s.signed_url_default_ttl_sec,signedUrlMaxTtlSec:s.signed_url_max_ttl_sec}}function ge(s){return s.split("/").map(encodeURIComponent).join("/")}function d(s,e){return s instanceof c?{data:null,error:s}:{data:null,error:new c(s instanceof Error?s.message:e,0,"STORAGE_ERROR")}}async function J(s){let e="STORAGE_ERROR",t=`HTTP ${s.status}`;try{let r=await s.json();r&&r.error&&(e=r.error.code??e,t=r.error.message??t);}catch{}return new c(t,s.status,e)}var H=class{constructor(e,t){this.http=e;this.bucketName=t;}http;bucketName;bucketBase(){return `/api/storage/buckets/${encodeURIComponent(this.bucketName)}`}objectPath(e){return `${this.bucketBase()}/objects/${ge(e)}`}async upload(e,t,r={}){try{let n=r.upsert?"PUT":"POST",i={"Content-Type":r.contentType??"application/octet-stream"};r.cacheControl&&(i["Cache-Control"]=r.cacheControl),r.contentDisposition&&(i["Content-Disposition"]=r.contentDisposition);let o=await this.http.rawFetch(this.objectPath(e),{method:n,headers:i,body:t,signal:r.abortSignal});if(!o.ok)return {data:null,error:await J(o)};let a=await o.json();return a.error||!a.data?{data:null,error:new c(a.error?.message??"Upload failed",o.status,a.error?.code??"STORAGE_ERROR")}:{data:$(a.data,this.bucketName),error:null}}catch(n){return d(n,"Upload failed")}}async download(e,t={}){try{let r={};t.range&&(r.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:r,signal:t.abortSignal});return n.ok?{data:await n.blob(),error:null}:{data:null,error:await J(n)}}catch(r){return d(r,"Download failed")}}async getStream(e,t={}){try{let r={};t.range&&(r.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:r,signal:t.abortSignal});return n.ok?n.body?{data:n.body,error:null}:{data:null,error:new c("Response body is not a stream",n.status,"STORAGE_ERROR")}:{data:null,error:await J(n)}}catch(r){return d(r,"Download failed")}}async remove(e){try{let t=await Promise.allSettled(e.map(i=>this.http.rawFetch(this.objectPath(i),{method:"DELETE"}))),r=[],n=[];for(let i=0;i<e.length;i++){let o=e[i],a=t[i];if(a.status==="fulfilled"&&a.value.ok)r.push(o);else if(a.status==="fulfilled")n.push(`${o}: HTTP ${a.value.status}`);else {let g=a.reason instanceof Error?a.reason.message:String(a.reason);n.push(`${o}: ${g}`);}}return n.length>0?{data:null,error:new c(`Failed to delete some objects: ${n.join("; ")}`,0,"STORAGE_ERROR")}:{data:{removed:r},error:null}}catch(t){return d(t,"Delete failed")}}async list(e={}){try{let t={};return e.prefix!==void 0&&(t.prefix=e.prefix),e.limit!==void 0&&(t.limit=String(e.limit)),e.startAfter!==void 0&&(t.start_after=e.startAfter),{data:(await this.http.get(`${this.bucketBase()}/objects`,{params:t})).map(n=>$(n,this.bucketName)),error:null}}catch(t){return d(t,"List failed")}}async copy(e,t,r){try{let n=await this.http.post(`${this.objectPath(e)}/copy`,{dest_bucket:r??this.bucketName,dest_key:t});return {data:$(n,r??this.bucketName),error:null}}catch(n){return d(n,"Copy failed")}}async move(e,t,r){try{let n=await this.http.post(`${this.objectPath(e)}/move`,{dest_bucket:r??this.bucketName,dest_key:t});return {data:$(n,r??this.bucketName),error:null}}catch(n){return d(n,"Move failed")}}async createSignedUrl(e,t={}){try{let r={};t.expiresIn!==void 0&&(r.expires_in=t.expiresIn);let n=await this.http.post(`${this.objectPath(e)}/sign`,r);return {data:{url:n.url,token:n.token,expiresAt:n.expiresAt},error:null}}catch(r){return d(r,"Sign failed")}}getPublicUrl(e){return {data:{url:`${this.http.baseUrl.replace(/\/$/,"")}${this.objectPath(e)}`}}}},B=class{constructor(e){this.http=e;}http;from(e){return new H(this.http,e)}async listBuckets(){try{return {data:(await this.http.get("/api/storage/buckets")).map(j),error:null}}catch(e){return d(e,"listBuckets failed")}}async getBucket(e){try{let t=await this.http.get(`/api/storage/buckets/${encodeURIComponent(e)}`);return {data:j(t),error:null}}catch(t){return d(t,"getBucket failed")}}async createBucket(e,t={}){try{let r={name:e};t.public!==void 0&&(r.public=t.public),t.fileSizeLimitBytes!==void 0&&(r.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(r.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.post("/api/storage/buckets",r);return {data:j(n),error:null}}catch(r){return d(r,"createBucket failed")}}async updateBucket(e,t){try{let r={};t.public!==void 0&&(r.public=t.public),t.fileSizeLimitBytes!==void 0&&(r.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(r.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.patch(`/api/storage/buckets/${encodeURIComponent(e)}`,r);return {data:j(n),error:null}}catch(r){return d(r,"updateBucket failed")}}async deleteBucket(e){try{return await this.http.delete(`/api/storage/buckets/${encodeURIComponent(e)}`),{data:null,error:null}}catch(t){return d(t,"deleteBucket failed")}}async emptyBucket(e){try{return {data:await this.http.post(`/api/storage/buckets/${encodeURIComponent(e)}/empty`,{}),error:null}}catch(t){return d(t,"emptyBucket failed")}}async getConfig(){try{let e=await this.http.get("/api/storage/config");return {data:he(e),error:null}}catch(e){return d(e,"getConfig failed")}}};function pe(s){return {key:s.key,digest:s.digest,updatedAt:s.updated_at}}function y(s,e){return s instanceof c?{data:null,error:s}:{data:null,error:new c(s instanceof Error?s.message:e,0,"FUNCTIONS_ERROR")}}function fe(s){return typeof s=="object"&&s!==null&&!ArrayBuffer.isView(s)&&!(s instanceof Blob)&&!(s instanceof FormData)&&!(s instanceof URLSearchParams)&&!(s instanceof ReadableStream)}var U=class{constructor(e){this.http=e;}http;async list(){try{return {data:await this.http.get("/api/functions"),error:null}}catch(e){return y(e,"list failed")}}async get(e){try{return {data:await this.http.get(`/api/functions/${encodeURIComponent(e)}`),error:null}}catch(t){return y(t,"get failed")}}async create(e){try{return {data:await this.http.post("/api/functions",e),error:null}}catch(t){return y(t,"create failed")}}async update(e,t){try{return {data:await this.http.put(`/api/functions/${encodeURIComponent(e)}`,t),error:null}}catch(r){return y(r,"update failed")}}async remove(e){try{return await this.http.delete(`/api/functions/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return y(t,"remove failed")}}async invoke(e,t={}){try{let r=t.method??"POST",n={...t.headers},i;return t.body!==void 0&&t.body!==null&&(fe(t.body)?(i=JSON.stringify(t.body),n["Content-Type"]||(n["Content-Type"]="application/json")):i=t.body),{data:await this.http.rawFetch(`/api/invoke/${encodeURIComponent(e)}`,{method:r,headers:n,body:i}),error:null}}catch(r){return y(r,"invoke failed")}}async listSecrets(){try{return {data:(await this.http.get("/api/functions/secrets")).secrets.map(pe),error:null}}catch(e){return y(e,"listSecrets failed")}}async setSecrets(e){try{return await this.http.put("/api/functions/secrets",{secrets:e}),{data:{saved:!0},error:null}}catch(t){return y(t,"setSecrets failed")}}async deleteSecret(e){try{return await this.http.delete(`/api/functions/secrets/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return y(t,"deleteSecret failed")}}};var me=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ke(s){let e=typeof s=="number"&&Number.isFinite(s)?s:50;return Math.max(1,Math.min(200,Math.trunc(e)))}function X(s,e){return s instanceof c?{data:null,error:s}:{data:null,error:new c(s instanceof Error?s.message:e,0,"AGENTS_ERROR")}}var x=class{constructor(e){this.http=e;}http;async list(e){try{let t=ke(e?.limit);return {data:await this.http.get(`/api/agents?limit=${t}`),error:null}}catch(t){return X(t,"list failed")}}async invoke(e,t){if(typeof e!="string"||!me.test(e))return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")};try{let r=t!==void 0?{input:t}:void 0;return {data:await this.http.post(`/api/agents/${encodeURIComponent(e)}/invoke`,r),error:null}}catch(r){return X(r,"invoke failed")}}};var E=class{http;tokenManager;auth;database;realtime;storage;functions;agents;constructor(e={}){let t=new R(e.debug);this.tokenManager=new S({persistSession:e.persistSession,storageKey:e.storageKey,storage:e.storage,multiTab:e.multiTab}),this.http=new _(e,this.tokenManager,t),this.auth=new A(this.http,this.tokenManager),this.database=new O(this.http,this.tokenManager,e.anonKey),this.realtime=new I(this.http.baseUrl,this.tokenManager,e.anonKey,e.realtime),this.storage=new B(this.http),this.functions=new U(this.http),this.agents=new x(this.http);}getHttpClient(){return this.http}};function st(s){return new E(s)}var it=E;
5
- exports.AgentsModule=x;exports.Auth=A;exports.Database=O;exports.Functions=U;exports.HttpClient=_;exports.Logger=R;exports.MitwayBaasClient=E;exports.MitwayBaasError=c;exports.Realtime=I;exports.RealtimeChannel=L;exports.Storage=B;exports.StorageBucketClient=H;exports.TokenManager=S;exports.createClient=st;exports.createLocalStorageAdapter=Y;exports.default=it;
4
+ `));}};var G="mitway_baas_csrf_token",ae="mitway_baas_session";function Z(){return typeof localStorage<"u"?{getItem:e=>{try{return localStorage.getItem(e)}catch{return null}},setItem:(e,t)=>{try{localStorage.setItem(e,t);}catch{}},removeItem:e=>{try{localStorage.removeItem(e);}catch{}}}:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}}var ce={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function ee(){if(typeof document>"u")return null;let r=document.cookie.split(";").find(e=>e.trim().startsWith(`${G}=`));return r&&r.split("=")[1]||null}function L(r){if(typeof document>"u")return;let e=10080*60,t=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=${encodeURIComponent(r)}; path=/; max-age=${e}; SameSite=Lax${t}`;}function j(){if(typeof document>"u")return;let r=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=; path=/; max-age=0; SameSite=Lax${r}`;}var S=class{accessToken=null;refreshToken=null;user=null;persistSession;storageKey;storage;onTokenChange=null;constructor(e){this.persistSession=e?.persistSession??true,this.storageKey=e?.storageKey??ae,this.storage=this.persistSession?e?.storage??Z():ce,(e?.multiTab??true)&&this.persistSession&&typeof window<"u"&&typeof localStorage<"u"&&window.addEventListener("storage",this.handleStorageEvent),this.restoreSession();}handleStorageEvent=e=>{e.key===this.storageKey&&(typeof localStorage<"u"&&e.storageArea!==localStorage||this.syncFromStorage(e.newValue));};syncFromStorage(e){let t=this.accessToken;if(e===null)this.accessToken=null,this.refreshToken=null,this.user=null;else try{let s=JSON.parse(e);if(!s.accessToken||!s.user)return;this.accessToken=s.accessToken,this.refreshToken=s.refreshToken??null,this.user=s.user;}catch{return}t!==this.accessToken&&this.onTokenChange&&this.onTokenChange();}saveSession(e){let t=e.accessToken!==this.accessToken;this.accessToken=e.accessToken,this.user=e.user,e.refreshToken!==void 0&&(this.refreshToken=e.refreshToken??null),this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getSession(){return !this.accessToken||!this.user?null:{accessToken:this.accessToken,refreshToken:this.refreshToken??void 0,user:this.user}}getAccessToken(){return this.accessToken}setAccessToken(e){let t=e!==this.accessToken;this.accessToken=e,this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getRefreshToken(){return this.refreshToken}setRefreshToken(e){this.refreshToken=e,this.persist();}getUser(){return this.user}setUser(e){this.user=e,this.persist();}clearSession(){let e=this.accessToken!==null;this.accessToken=null,this.refreshToken=null,this.user=null,this.removePersisted(),e&&this.onTokenChange&&this.onTokenChange();}restoreSession(){if(!this.persistSession)return false;try{let e=this.storage.getItem(this.storageKey);if(!e)return !1;let t=JSON.parse(e);return !t.accessToken||!t.user?!1:(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken??null,this.user=t.user,!0)}catch{return false}}persist(){if(!this.persistSession||!this.accessToken||!this.user)return;let e={accessToken:this.accessToken,user:this.user};this.refreshToken&&(e.refreshToken=this.refreshToken),this.storage.setItem(this.storageKey,JSON.stringify(e));}removePersisted(){this.persistSession&&this.storage.removeItem(this.storageKey);}};function A(r){if(!r||typeof r!="object")return r;let e=r,t={...e},s=false;return "access_token"in e&&!("accessToken"in e)&&(t.accessToken=e.access_token,delete t.access_token,s=true),"csrf_token"in e&&!("csrfToken"in e)&&(t.csrfToken=e.csrf_token,delete t.csrf_token,s=true),"refresh_token"in e&&!("refreshToken"in e)&&(t.refreshToken=e.refresh_token,delete t.refresh_token,s=true),s?t:r}var le=new Set([500,502,503,504]),ue=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),I=class{baseUrl;fetch;defaultHeaders;anonKey;userToken=null;logger;autoRefreshToken=true;isRefreshing=false;refreshPromise=null;tokenManager;refreshToken=null;timeout;retryCount;retryDelay;constructor(e,t,s){if(this.baseUrl=e.baseUrl||"http://localhost:7130",this.autoRefreshToken=e.autoRefreshToken??true,this.fetch=e.fetch||(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),this.anonKey=e.anonKey,this.defaultHeaders={...e.headers},this.tokenManager=t??new S,this.logger=s||new R(false),this.timeout=e.timeout??3e4,this.retryCount=e.retryCount??3,this.retryDelay=e.retryDelay??500,!this.fetch)throw new Error("Fetch is not available. Provide a fetch implementation in the SDK config.")}buildUrl(e,t){let s=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([n,i])=>{if(n==="select"){let o=i.replace(/\s+/g," ").trim();o=o.replace(/\s*\(\s*/g,"(").replace(/\s*\)\s*/g,")").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/,\s+(?=[^()]*\))/g,","),s.searchParams.append(n,o);}else s.searchParams.append(n,i);}),s.toString()}isRetryableStatus(e){return le.has(e)}computeRetryDelay(e){let s=this.retryDelay*Math.pow(2,e-1)*(.85+Math.random()*.3);return Math.round(s)}async handleRequest(e,t,s={}){let{params:n,headers:i={},body:o,signal:a,...d}=s,p=this.buildUrl(t,n),v=Date.now(),T=ue.has(e.toUpperCase())||s.idempotent===true?this.retryCount:0,b={...this.defaultHeaders},Q=this.userToken||this.anonKey;Q&&(b.Authorization=`Bearer ${Q}`);let N;o!==void 0&&(typeof FormData<"u"&&o instanceof FormData?N=o:(e!=="GET"&&(b["Content-Type"]="application/json;charset=UTF-8"),N=JSON.stringify(o))),i instanceof Headers?i.forEach((f,g)=>{b[g]=f;}):Array.isArray(i)?i.forEach(([f,g])=>{b[f]=g;}):Object.assign(b,i),this.logger.logRequest(e,p,b,N);let W;for(let f=0;f<=T;f++){if(f>0){let l=this.computeRetryDelay(f);if(this.logger.warn(`Retry ${f}/${T} for ${e} ${p} in ${l}ms`),a?.aborted)throw a.reason;await new Promise((u,J)=>{let y=()=>{clearTimeout(ne),J(a.reason);},ne=setTimeout(()=>{a&&a.removeEventListener("abort",y),u();},l);a&&a.addEventListener("abort",y,{once:true});});}let g,m;if((this.timeout>0||a)&&(g=new AbortController,this.timeout>0&&(m=setTimeout(()=>g.abort(),this.timeout)),a))if(a.aborted)g.abort(a.reason);else {let l=()=>g.abort(a.reason);a.addEventListener("abort",l,{once:true}),g.signal.addEventListener("abort",()=>{a.removeEventListener("abort",l);},{once:true});}try{let l=await this.fetch(p,{method:e,headers:b,body:N,...d,...g?{signal:g.signal}:{}});if(this.isRetryableStatus(l.status)&&f<T){m!==void 0&&clearTimeout(m),await l.body?.cancel(),W=new c(`Server error: ${l.status} ${l.statusText}`,l.status,"SERVER_ERROR");continue}if(l.status===204){m!==void 0&&clearTimeout(m);return}let u,J=l.headers.get("content-type");try{J?.includes("json")?u=await l.json():u=await l.text();}catch(y){throw m!==void 0&&clearTimeout(m),new c(`Failed to parse response body: ${y?.message||"Unknown error"}`,l.status,l.ok?"PARSE_ERROR":"REQUEST_FAILED")}if(m!==void 0&&clearTimeout(m),!l.ok){if(this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"error"in u&&u.error!==null&&typeof u.error=="object"){let y=u.error;throw new c(y.message||l.statusText||"Request failed",y.statusCode||l.status,y.code||y.error||"REQUEST_FAILED",y.nextActions)}throw new c(`Request failed: ${l.statusText}`,l.status,"REQUEST_FAILED")}return this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"data"in u&&"error"in u&&u.error===null?u.data:u}catch(l){if(m!==void 0&&clearTimeout(m),l?.name==="AbortError")throw g&&g.signal.aborted&&this.timeout>0&&!a?.aborted?new c(`Request timed out after ${this.timeout}ms`,408,"REQUEST_TIMEOUT"):l;if(l instanceof c)throw l;if(f<T){W=l;continue}throw new c(`Network request failed: ${l?.message||"Unknown error"}`,0,"NETWORK_ERROR")}}throw W||new c("Request failed after all retry attempts",0,"NETWORK_ERROR")}async request(e,t,s={}){try{return await this.handleRequest(e,t,{...s})}catch(n){if(n instanceof c&&n.statusCode===401&&this.autoRefreshToken&&this.refreshToken&&!t.includes("/api/auth/refresh"))try{let i=await this.handleTokenRefresh();this.setAuthToken(i.accessToken),i.refreshToken&&this.setRefreshToken(i.refreshToken),i.csrfToken&&L(i.csrfToken);let o=i.user??this.tokenManager.getUser();return o&&this.tokenManager.saveSession({accessToken:i.accessToken,refreshToken:i.refreshToken,user:o}),await this.handleRequest(e,t,{...s})}catch(i){throw this.tokenManager.clearSession(),this.userToken=null,this.refreshToken=null,j(),i}throw n}}async rawFetch(e,t={}){let s=this.buildUrl(e),n=new Headers(t.headers??{});for(let[i,o]of Object.entries(this.defaultHeaders))n.has(i)||n.set(i,o);if(!n.has("Authorization")){let i=this.userToken??this.anonKey;i&&n.set("Authorization",`Bearer ${i}`);}return this.fetch(s,{...t,headers:n})}get(e,t){return this.request("GET",e,t)}post(e,t,s){return this.request("POST",e,{...s,body:t})}put(e,t,s){return this.request("PUT",e,{...s,body:t})}patch(e,t,s){return this.request("PATCH",e,{...s,body:t})}delete(e,t){return this.request("DELETE",e,t)}setAuthToken(e){this.userToken=e;}setRefreshToken(e){this.refreshToken=e;}getHeaders(){let e={...this.defaultHeaders},t=this.userToken||this.anonKey;return t&&(e.Authorization=`Bearer ${t}`),e}async handleTokenRefresh(){return this.isRefreshing?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let e=ee(),t=this.refreshToken?{refreshToken:this.refreshToken}:void 0,s=await this.handleRequest("POST","/api/auth/refresh",{body:t,headers:e?{"X-CSRF-Token":e}:{},credentials:"include"});return A(s)}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}};function w(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,500,"AUTH_ERROR")}}var U=class{constructor(e,t){this.http=e;this.tokenManager=t;this.tokenManager.onTokenChange=()=>this._emitFromTokenChange();let s=this.tokenManager.getSession();if(s){this.http.setAuthToken(s.accessToken);let n=this.tokenManager.getRefreshToken();n&&this.http.setRefreshToken(n),this.lastEmittedUserId=s.user.id,this.lastEmittedAccessToken=s.accessToken;}}http;tokenManager;stateChangeListeners=new Set;lastEmittedUserId=null;lastEmittedAccessToken=null;onAuthStateChange(e){return this.stateChangeListeners.add(e),{unsubscribe:()=>{this.stateChangeListeners.delete(e);}}}emit(e,t){for(let s of this.stateChangeListeners)try{s(e,t);}catch{}}_emitFromTokenChange(){let e=this.tokenManager.getSession();e?(this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null)):(this.http.setAuthToken(null),this.http.setRefreshToken(null));let t=this.lastEmittedUserId,s=this.lastEmittedAccessToken;if(!e){t!==null&&(this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null));return}let n=e.user.id;if(t===null){this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}if(t!==n){this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null),this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}s!==e.accessToken&&(this.lastEmittedAccessToken=e.accessToken,this.emit("TOKEN_REFRESHED",e));}saveSessionFromResponse(e){let t={accessToken:e.accessToken,refreshToken:e.refreshToken,user:e.user};e.csrfToken&&L(e.csrfToken),this.tokenManager.saveSession(t),this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null);}async signUp(e){try{let t=await this.http.post("/api/auth/register",e,{credentials:"include"}),s=A(t);return s?.accessToken&&s.user&&this.saveSessionFromResponse(s),{data:s,error:null}}catch(t){return w(t,"Sign up failed")}}async signInWithPassword(e){try{let t=await this.http.post("/api/auth/login",e,{credentials:"include"}),s=A(t);return s?.accessToken&&s.user&&this.saveSessionFromResponse(s),{data:s,error:null}}catch(t){return w(t,"Sign in failed")}}async signOut(){try{try{await this.http.post("/api/auth/logout",void 0,{credentials:"include"});}catch{}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),j(),{error:null}}catch{return {error:new c("Failed to sign out",500,"SIGNOUT_ERROR")}}}async refreshSession(){try{let e=await this.http.handleTokenRefresh();if(e?.accessToken){let t=e.user??this.tokenManager.getUser();if(t){let s={...e,user:t};return this.saveSessionFromResponse(s),{data:s,error:null}}}return {data:e,error:null}}catch(e){return w(e,"Session refresh failed")}}async initialize(){let e=this.tokenManager.getSession();if(!e)return this.emit("INITIAL_SESSION",null),{data:null,error:new c("No persisted session",0,"NO_SESSION")};try{let t=await this.http.get("/api/auth/sessions/current");if(t?.user){this.tokenManager.setUser(t.user);let s=this.tokenManager.getSession();return this.emit("INITIAL_SESSION",s),{data:{user:t.user,accessToken:e.accessToken},error:null}}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),{data:null,error:new c("Invalid session",401,"INVALID_SESSION")}}catch(t){return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),w(t,"Session restore failed")}}getSession(){return this.tokenManager.getSession()}getUser(){return this.tokenManager.getUser()}async getCurrentUser(){try{let e=await this.http.get("/api/auth/sessions/current");if(e?.user){let t={accessToken:this.tokenManager.getSession()?.accessToken??"",user:e.user};this.tokenManager.saveSession(t);}return {data:e,error:null}}catch(e){return w(e,"Failed to get current user")}}async getProfile(e){try{return {data:await this.http.get(`/api/auth/profiles/${encodeURIComponent(e)}`),error:null}}catch(t){return w(t,"Failed to get profile")}}async setProfile(e){try{let t=await this.http.patch("/api/auth/profiles/current",{profile:e}),s=this.tokenManager.getUser();if(t?.profile&&s){let n={...s,profile:t.profile};this.tokenManager.setUser(n),this.emit("USER_UPDATED",this.tokenManager.getSession());}return {data:t,error:null}}catch(t){return w(t,"Failed to update profile")}}};function he(r,e,t){return async(s,n)=>{let i=typeof s=="string"?s:s.toString(),o=new URL(i),a=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,d=a.match(/^rpc\/(.+)$/),p=d?`/api/database/rpc/${d[1]}`:`/api/database/records/${a}`,v=`${r.baseUrl}${p}${o.search}`,F=new Headers(n?.headers);if(!F.has("Authorization")){let T=e.getAccessToken()??t;T&&F.set("Authorization",`Bearer ${T}`);}return fetch(v,{...n,headers:F})}}var O=class{postgrest;httpClient;constructor(e,t,s){this.httpClient=e,this.postgrest=new postgrestJs.PostgrestClient("http://dummy",{fetch:he(e,t,s),headers:{}});}from(e){if(!e||typeof e!="string")throw new c("Database.from(table) requires a non-empty string",400,"INVALID_TABLE_NAME");return this.postgrest.from(e)}rpc(e,t,s){return this.postgrest.rpc(e,t,s)}getUrl(){return this.httpClient.baseUrl}};var pe=2e4;function V(r,e){let t=new Error(e);return t.code=r,t}var fe=1e4,$=class{constructor(e,t,s={}){this.topic=e;this.realtime=t;this.options=s;}topic;realtime;bindings=[];state="closed";statusCallback=null;presence={};trackedState=null;presenceHeartbeat=null;lastBroadcastTimestamp=null;options;get isPrivate(){return this.options.config?.private===true}get presenceKey(){return this.options.config?.presence?.key}_state(){return this.state}async _rejoinAfterReconnect(){if(this.state!=="closed"){for(let e of this.bindings)e.type==="postgres_changes"&&(e.subscriptionId=void 0);this.state="joining";try{if(await this.registerAllBindings(),this.trackedState){let e=this.realtime._getSocket(),t=this.presenceKey;e?.emit("realtime:presence:track",t!==void 0?{channel:this.topic,state:this.trackedState,key:t}:{channel:this.topic,state:this.trackedState});}this.lastBroadcastTimestamp&&this.bindings.some(e=>e.type==="broadcast")&&this.replay({since:this.lastBroadcastTimestamp}).catch(()=>{}),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(e){this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("REJOIN_FAILED",e instanceof Error?e.message:String(e)));}}}on(e,t,s){return e==="postgres_changes"?this.bindings.push({type:"postgres_changes",filter:t,callback:s}):e==="broadcast"?this.bindings.push({type:"broadcast",filter:t,callback:s}):this.bindings.push({type:"presence",filter:t,callback:s}),this}async track(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");this.trackedState=e;let s=this.presenceKey;t.emit("realtime:presence:track",s!==void 0?{channel:this.topic,state:e,key:s}:{channel:this.topic,state:e}),this.presenceHeartbeat||(this.presenceHeartbeat=setInterval(()=>{let i=this.realtime._getSocket();i&&this.trackedState&&i.emit("realtime:presence:track",s!==void 0?{channel:this.topic,state:this.trackedState,key:s}:{channel:this.topic,state:this.trackedState});},pe),this.presenceHeartbeat.unref?.());}untrack(){this.trackedState=null,this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),this.realtime._getSocket()?.emit("realtime:presence:untrack",{channel:this.topic});}presenceState(){return this.presence}subscribe(e){return this.statusCallback=e??null,this.state==="joining"||this.state==="joined"?this:(this.state="joining",this.realtime.connect().then(async()=>{try{await this.registerAllBindings(),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(t){this.state="errored";let s=t instanceof Error?t.message:String(t);this.statusCallback?.("CHANNEL_ERROR",V("SUBSCRIBE_FAILED",s));}},t=>{this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("CONNECT_FAILED",t.message));}),this)}async unsubscribe(){if(this.state==="closed")return;let e=this.realtime._getSocket();if(this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),!e){this.trackedState=null,this.state="closed";return}this.trackedState&&(e.emit("realtime:presence:untrack",{channel:this.topic}),this.trackedState=null);let t=this.bindings.filter(s=>s.type==="postgres_changes");for(let s of t)s.subscriptionId&&(e.emit("realtime:postgres_changes:unsubscribe",{subscription_id:s.subscriptionId}),s.subscriptionId=void 0);this.bindings.some(s=>s.type==="broadcast"||s.type==="presence")&&e.emit("realtime:unsubscribe",{channel:this.topic}),this.realtime._detachChannel(this),this.state="closed",this.statusCallback?.("CLOSED");}async send(e){if(e.type!=="broadcast")throw new c('Only "broadcast" sends are supported \u2014 DB changes flow via your DB writes, not channel.send()',400,"UNSUPPORTED_SEND_TYPE");if(new Set(["postgres_changes","presence_state","presence_join","presence_leave"]).has(e.event))throw new c(`"${e.event}" is a reserved event name \u2014 pick a different name for broadcast events`,400,"RESERVED_EVENT_NAME");let s=this.realtime._getSocket();if(!s)throw new c("Socket not connected",503,"NOT_CONNECTED");let n=this.options.config?.broadcast?.self,i={channel:this.topic,event:e.event,payload:e.payload};return n===false&&(i.self=false),await new Promise(o=>{s.emit("realtime:publish",i,a=>{o(a);});})}async replay(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");t.emit("realtime:broadcast:replay",{channel:this.topic,since:e.since,limit:e.limit,private:this.isPrivate});}_dispatch(e,t){if(e==="postgres_changes"){let n=t;for(let i of this.bindings)if(!(i.type!=="postgres_changes"||!i.subscriptionId||!n.ids.includes(i.subscriptionId)||!(i.filter.event==="*"||i.filter.event===n.data.eventType)))try{i.callback(n.data);}catch{}return}if(e==="presence_state"||e==="presence_join"||e==="presence_leave"){let n=t;if(n.channel!==this.topic)return;if(e==="presence_state"&&n.state)this.presence={...n.state},this.firePresence({event:"sync",state:this.presence});else if(e==="presence_join"&&n.joins)Object.assign(this.presence,n.joins),this.firePresence({event:"join",joins:n.joins});else if(e==="presence_leave"&&n.leaves){for(let i of Object.keys(n.leaves))delete this.presence[i];this.firePresence({event:"leave",leaves:n.leaves});}return}let s=t.meta;s?.timestamp&&(!this.lastBroadcastTimestamp||s.timestamp>this.lastBroadcastTimestamp)&&(this.lastBroadcastTimestamp=s.timestamp);for(let n of this.bindings){if(n.type!=="broadcast"||n.filter.event!==e)continue;let{meta:i,...o}=t;try{n.callback({type:"broadcast",event:e,payload:o});}catch{}}}firePresence(e){for(let t of this.bindings)if(t.type==="presence"&&t.filter.event===e.event)try{e.event==="sync"?t.callback():(e.event,t.callback(e));}catch{}}async registerAllBindings(){let e=this.realtime._getSocket();if(!e)throw new Error("Socket not available");this.bindings.some(n=>n.type==="broadcast"||n.type==="presence")&&await new Promise((n,i)=>{e.emit("realtime:subscribe",{channel:this.topic,private:this.isPrivate},o=>{o.status==="ok"?n():i(new Error(o.error?.message??"subscribe failed"));});});let s=this.bindings.filter(n=>n.type==="postgres_changes");await Promise.all(s.map(n=>new Promise((i,o)=>{e.emit("realtime:postgres_changes:subscribe",{event:n.filter.event,schema:n.filter.schema??"public",table:n.filter.table,filter:n.filter.filter},a=>{a.status==="ok"&&a.subscription_id?(n.subscriptionId=a.subscription_id,i()):o(new Error(a.error?.message??"postgres_changes subscribe failed"));});})));}},B=class{socket=null;baseUrl;options;anonKey;tokenManager;channels=new Map;connecting=null;firstConnected=false;constructor(e,t,s,n={}){this.baseUrl=e,this.tokenManager=t,this.anonKey=s,this.options=n;}get isConnected(){return this.socket?.connected===true}get socketId(){return this.socket?.id}channel(e,t){let s=this.channels.get(e);if(s)return s;let n=new $(e,this,t);return this.channels.set(e,n),n}connect(){return this.isConnected?Promise.resolve():this.connecting?this.connecting:(this.connecting=this.openSocket(),this.connecting)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.firstConnected=false);}_getSocket(){return this.socket}_detachChannel(e){this.channels.delete(e.topic);}openSocket(){let e=this.tokenManager.getAccessToken()??this.anonKey;if(!e){let n=new c("Realtime requires an access token or anonKey",401,"AUTH_INVALID_API_KEY");return this.connecting=null,Promise.reject(n)}let t=this.options.timeoutMs??fe,s=socket_ioClient.io(this.baseUrl,{path:this.options.path,transports:this.options.transports??["websocket"],auth:{token:e,...this.options.extraAuth??{}},reconnection:true,timeout:t});return this.socket=s,s.onAny((n,...i)=>this.dispatch(n,i)),s.on("connect",()=>{if(this.firstConnected)for(let n of this.channels.values()){let i=n._state();(i==="joined"||i==="errored")&&n._rejoinAfterReconnect();}}),new Promise((n,i)=>{let o=setTimeout(()=>{s.off("connect",d),s.off("connect_error",p),this.connecting=null,i(new c(`Realtime connection timeout after ${t}ms`,408,"CONNECTION_TIMEOUT"));},t),a=()=>{clearTimeout(o),s.off("connect",d),s.off("connect_error",p);},d=()=>{a(),this.connecting=null,this.firstConnected=true,n();},p=v=>{a(),this.connecting=null,i(new c(v.message,0,"CONNECTION_FAILED"));};s.once("connect",d),s.once("connect_error",p);})}dispatch(e,t){if(e==="postgres_changes"){let n=t[0]??{};this.channels.forEach(i=>i._dispatch("postgres_changes",n));return}if(e==="connect"||e==="disconnect"||e==="connect_error"||e==="error"||e==="realtime:error"||e==="realtime:shutdown")return;let s=t[0]??{};this.channels.forEach(n=>n._dispatch(e,s));}};function H(r){return {id:r.id,name:r.name,public:r.public,fileSizeLimitBytes:r.file_size_limit_bytes,allowedMimeTypes:r.allowed_mime_types,createdAt:r.created_at,updatedAt:r.updated_at}}function q(r,e){return {id:r.id,bucket:e,key:r.key,size:r.size,mimeType:r.mime_type,etag:r.etag,cacheControl:r.cache_control,contentDisposition:r.content_disposition,uploadedBy:r.uploaded_by,uploadedAt:r.uploaded_at,updatedAt:r.updated_at}}function me(r){return {defaultFileSizeLimitBytes:r.default_file_size_limit_bytes,maxFileSizeLimitBytes:r.max_file_size_limit_bytes,tenantStorageQuotaBytes:r.tenant_storage_quota_bytes,reservedSpaceBytes:r.reserved_space_bytes,signedUrlDefaultTtlSec:r.signed_url_default_ttl_sec,signedUrlMaxTtlSec:r.signed_url_max_ttl_sec}}function ye(r){return r.split("/").map(encodeURIComponent).join("/")}function h(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"STORAGE_ERROR")}}async function Y(r){let e="STORAGE_ERROR",t=`HTTP ${r.status}`;try{let s=await r.json();s&&s.error&&(e=s.error.code??e,t=s.error.message??t);}catch{}return new c(t,r.status,e)}var K=class{constructor(e,t){this.http=e;this.bucketName=t;}http;bucketName;bucketBase(){return `/api/storage/buckets/${encodeURIComponent(this.bucketName)}`}objectPath(e){return `${this.bucketBase()}/objects/${ye(e)}`}async upload(e,t,s={}){try{let n=s.upsert?"PUT":"POST",i={"Content-Type":s.contentType??"application/octet-stream"};s.cacheControl&&(i["Cache-Control"]=s.cacheControl),s.contentDisposition&&(i["Content-Disposition"]=s.contentDisposition);let o=await this.http.rawFetch(this.objectPath(e),{method:n,headers:i,body:t,signal:s.abortSignal});if(!o.ok)return {data:null,error:await Y(o)};let a=await o.json();return a.error||!a.data?{data:null,error:new c(a.error?.message??"Upload failed",o.status,a.error?.code??"STORAGE_ERROR")}:{data:q(a.data,this.bucketName),error:null}}catch(n){return h(n,"Upload failed")}}async download(e,t={}){try{let s={};t.range&&(s.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:s,signal:t.abortSignal});return n.ok?{data:await n.blob(),error:null}:{data:null,error:await Y(n)}}catch(s){return h(s,"Download failed")}}async getStream(e,t={}){try{let s={};t.range&&(s.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:s,signal:t.abortSignal});return n.ok?n.body?{data:n.body,error:null}:{data:null,error:new c("Response body is not a stream",n.status,"STORAGE_ERROR")}:{data:null,error:await Y(n)}}catch(s){return h(s,"Download failed")}}async remove(e){try{let t=await Promise.allSettled(e.map(i=>this.http.rawFetch(this.objectPath(i),{method:"DELETE"}))),s=[],n=[];for(let i=0;i<e.length;i++){let o=e[i],a=t[i];if(a.status==="fulfilled"&&a.value.ok)s.push(o);else if(a.status==="fulfilled")n.push(`${o}: HTTP ${a.value.status}`);else {let d=a.reason instanceof Error?a.reason.message:String(a.reason);n.push(`${o}: ${d}`);}}return n.length>0?{data:null,error:new c(`Failed to delete some objects: ${n.join("; ")}`,0,"STORAGE_ERROR")}:{data:{removed:s},error:null}}catch(t){return h(t,"Delete failed")}}async list(e={}){try{let t={};return e.prefix!==void 0&&(t.prefix=e.prefix),e.limit!==void 0&&(t.limit=String(e.limit)),e.startAfter!==void 0&&(t.start_after=e.startAfter),{data:(await this.http.get(`${this.bucketBase()}/objects`,{params:t})).map(n=>q(n,this.bucketName)),error:null}}catch(t){return h(t,"List failed")}}async copy(e,t,s){try{let n=await this.http.post(`${this.objectPath(e)}/copy`,{dest_bucket:s??this.bucketName,dest_key:t});return {data:q(n,s??this.bucketName),error:null}}catch(n){return h(n,"Copy failed")}}async move(e,t,s){try{let n=await this.http.post(`${this.objectPath(e)}/move`,{dest_bucket:s??this.bucketName,dest_key:t});return {data:q(n,s??this.bucketName),error:null}}catch(n){return h(n,"Move failed")}}async createSignedUrl(e,t={}){try{let s={};t.expiresIn!==void 0&&(s.expires_in=t.expiresIn);let n=await this.http.post(`${this.objectPath(e)}/sign`,s);return {data:{url:n.url,token:n.token,expiresAt:n.expiresAt},error:null}}catch(s){return h(s,"Sign failed")}}getPublicUrl(e){return {data:{url:`${this.http.baseUrl.replace(/\/$/,"")}${this.objectPath(e)}`}}}},x=class{constructor(e){this.http=e;}http;from(e){return new K(this.http,e)}async listBuckets(){try{return {data:(await this.http.get("/api/storage/buckets")).map(H),error:null}}catch(e){return h(e,"listBuckets failed")}}async getBucket(e){try{let t=await this.http.get(`/api/storage/buckets/${encodeURIComponent(e)}`);return {data:H(t),error:null}}catch(t){return h(t,"getBucket failed")}}async createBucket(e,t={}){try{let s={name:e};t.public!==void 0&&(s.public=t.public),t.fileSizeLimitBytes!==void 0&&(s.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(s.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.post("/api/storage/buckets",s);return {data:H(n),error:null}}catch(s){return h(s,"createBucket failed")}}async updateBucket(e,t){try{let s={};t.public!==void 0&&(s.public=t.public),t.fileSizeLimitBytes!==void 0&&(s.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(s.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.patch(`/api/storage/buckets/${encodeURIComponent(e)}`,s);return {data:H(n),error:null}}catch(s){return h(s,"updateBucket failed")}}async deleteBucket(e){try{return await this.http.delete(`/api/storage/buckets/${encodeURIComponent(e)}`),{data:null,error:null}}catch(t){return h(t,"deleteBucket failed")}}async emptyBucket(e){try{return {data:await this.http.post(`/api/storage/buckets/${encodeURIComponent(e)}/empty`,{}),error:null}}catch(t){return h(t,"emptyBucket failed")}}async getConfig(){try{let e=await this.http.get("/api/storage/config");return {data:me(e),error:null}}catch(e){return h(e,"getConfig failed")}}};function ke(r){return {key:r.key,digest:r.digest,updatedAt:r.updated_at}}function k(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"FUNCTIONS_ERROR")}}function Te(r){return typeof r=="object"&&r!==null&&!ArrayBuffer.isView(r)&&!(r instanceof Blob)&&!(r instanceof FormData)&&!(r instanceof URLSearchParams)&&!(r instanceof ReadableStream)}var M=class{constructor(e){this.http=e;}http;async list(){try{return {data:await this.http.get("/api/functions"),error:null}}catch(e){return k(e,"list failed")}}async get(e){try{return {data:await this.http.get(`/api/functions/${encodeURIComponent(e)}`),error:null}}catch(t){return k(t,"get failed")}}async create(e){try{return {data:await this.http.post("/api/functions",e),error:null}}catch(t){return k(t,"create failed")}}async update(e,t){try{return {data:await this.http.put(`/api/functions/${encodeURIComponent(e)}`,t),error:null}}catch(s){return k(s,"update failed")}}async remove(e){try{return await this.http.delete(`/api/functions/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return k(t,"remove failed")}}async invoke(e,t={}){try{let s=t.method??"POST",n={...t.headers},i;return t.body!==void 0&&t.body!==null&&(Te(t.body)?(i=JSON.stringify(t.body),n["Content-Type"]||(n["Content-Type"]="application/json")):i=t.body),{data:await this.http.rawFetch(`/api/invoke/${encodeURIComponent(e)}`,{method:s,headers:n,body:i}),error:null}}catch(s){return k(s,"invoke failed")}}async listSecrets(){try{return {data:(await this.http.get("/api/functions/secrets")).secrets.map(ke),error:null}}catch(e){return k(e,"listSecrets failed")}}async setSecrets(e){try{return await this.http.put("/api/functions/secrets",{secrets:e}),{data:{saved:!0},error:null}}catch(t){return k(t,"setSecrets failed")}}async deleteSecret(e){try{return await this.http.delete(`/api/functions/secrets/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return k(t,"deleteSecret failed")}}};var C=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function te(r){let e=typeof r=="number"&&Number.isFinite(r)?r:50;return Math.max(1,Math.min(200,Math.trunc(e)))}function be(r){let e=typeof r=="number"&&Number.isFinite(r)?r:100;return Math.max(1,Math.min(500,Math.trunc(e)))}function z(){return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")}}function se(){return {data:null,error:new c("sessionId must be a valid UUID",400,"INVALID_INPUT")}}function E(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"AGENTS_ERROR")}}var D=class{constructor(e){this.http=e;}http;async list(e){try{let t=te(e?.limit);return {data:await this.http.get(`/api/agents?limit=${t}`),error:null}}catch(t){return E(t,"list failed")}}async invoke(e,t){if(typeof e!="string"||!C.test(e))return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")};try{let s=t!==void 0?{input:t}:void 0;return {data:await this.http.post(`/api/agents/${encodeURIComponent(e)}/invoke`,s),error:null}}catch(s){return E(s,"invoke failed")}}async chat(e,t,s){if(typeof e!="string"||!C.test(e))return z();try{let n={message:t};s?.sessionId!==void 0&&(n.session_id=s.sessionId),s?.extraContext!==void 0&&(n.extra_context=s.extraContext);let i=await this.http.post(`/api/agents/${encodeURIComponent(e)}/chat`,n);return {data:{sessionId:i.session_id,runId:i.runId,status:i.status,output:i.output,text:i.text,totalTokens:i.totalTokens,totalCost:i.totalCost,error:i.error},error:null}}catch(n){return E(n,"chat failed")}}async listSessions(e,t){if(typeof e!="string"||!C.test(e))return z();try{let s=te(t?.limit);return {data:{sessions:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions?limit=${s}`)).sessions??[]).map(o=>({id:o.id,createdAt:o.created_at,lastActivityAt:o.last_activity_at,messageCount:o.message_count,lastMessagePreview:o.last_message_preview??null}))},error:null}}catch(s){return E(s,"listSessions failed")}}async getMessages(e,t,s){if(typeof e!="string"||!C.test(e))return z();if(typeof t!="string"||!C.test(t))return se();try{let n=be(s?.limit),i=new URLSearchParams;return i.set("limit",String(n)),s?.before!==void 0&&i.set("before",s.before),{data:{messages:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/messages?${i.toString()}`)).messages??[]).map(d=>({id:d.id,role:d.role,content:d.content,createdAt:d.created_at}))},error:null}}catch(n){return E(n,"getMessages failed")}}async deleteSession(e,t){if(typeof e!="string"||!C.test(e))return z();if(typeof t!="string"||!C.test(t))return se();try{return await this.http.delete(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}`),{data:{ok:!0},error:null}}catch(s){return E(s,"deleteSession failed")}}};var _=class{http;tokenManager;auth;database;realtime;storage;functions;agents;constructor(e={}){let t=new R(e.debug);this.tokenManager=new S({persistSession:e.persistSession,storageKey:e.storageKey,storage:e.storage,multiTab:e.multiTab}),this.http=new I(e,this.tokenManager,t),this.auth=new U(this.http,this.tokenManager),this.database=new O(this.http,this.tokenManager,e.anonKey),this.realtime=new B(this.http.baseUrl,this.tokenManager,e.anonKey,e.realtime),this.storage=new x(this.http),this.functions=new M(this.http),this.agents=new D(this.http);}getHttpClient(){return this.http}};function at(r){return new _(r)}var ct=_;
5
+ exports.AgentsModule=D;exports.Auth=U;exports.Database=O;exports.Functions=M;exports.HttpClient=I;exports.Logger=R;exports.MitwayBaasClient=_;exports.MitwayBaasError=c;exports.Realtime=B;exports.RealtimeChannel=$;exports.Storage=x;exports.StorageBucketClient=K;exports.TokenManager=S;exports.createClient=at;exports.createLocalStorageAdapter=Z;exports.default=ct;
package/dist/index.d.cts CHANGED
@@ -1116,8 +1116,10 @@ declare class Functions {
1116
1116
 
1117
1117
  /**
1118
1118
  * Agents module — thin wrapper over the `/api/agents/*` REST endpoints
1119
- * exposed by MITWAY-BaaS. Lists agents registered in the tenant and
1120
- * invokes them through the BaaS-native gateway.
1119
+ * exposed by MITWAY-BaaS. Lists agents registered in the tenant, invokes
1120
+ * them through the BaaS-native gateway, and drives multi-turn chat
1121
+ * sessions with server-side memory (`chat`, `listSessions`,
1122
+ * `getMessages`, `deleteSession`).
1121
1123
  */
1122
1124
 
1123
1125
  interface Agent {
@@ -1137,6 +1139,31 @@ interface AgentInvokeResult {
1137
1139
  message: string;
1138
1140
  } | null;
1139
1141
  }
1142
+ interface ChatTurn {
1143
+ sessionId: string;
1144
+ runId: string;
1145
+ status: 'succeeded' | 'failed';
1146
+ output: unknown;
1147
+ text: string | null;
1148
+ totalTokens: number;
1149
+ totalCost: number;
1150
+ error: {
1151
+ message: string;
1152
+ } | null;
1153
+ }
1154
+ interface ChatSession {
1155
+ id: string;
1156
+ createdAt: string;
1157
+ lastActivityAt: string;
1158
+ messageCount: number;
1159
+ lastMessagePreview: string | null;
1160
+ }
1161
+ interface ChatMessage {
1162
+ id: string;
1163
+ role: 'user' | 'assistant';
1164
+ content: string;
1165
+ createdAt: string;
1166
+ }
1140
1167
  type AgentsResult<T> = {
1141
1168
  data: T | null;
1142
1169
  error: MitwayBaasError | null;
@@ -1150,6 +1177,24 @@ declare class AgentsModule {
1150
1177
  agents: Agent[];
1151
1178
  }>>;
1152
1179
  invoke<TInput = unknown>(agentId: string, input?: TInput): Promise<AgentsResult<AgentInvokeResult>>;
1180
+ chat(agentId: string, message: string, opts?: {
1181
+ sessionId?: string;
1182
+ extraContext?: string;
1183
+ }): Promise<AgentsResult<ChatTurn>>;
1184
+ listSessions(agentId: string, opts?: {
1185
+ limit?: number;
1186
+ }): Promise<AgentsResult<{
1187
+ sessions: ChatSession[];
1188
+ }>>;
1189
+ getMessages(agentId: string, sessionId: string, opts?: {
1190
+ limit?: number;
1191
+ before?: string;
1192
+ }): Promise<AgentsResult<{
1193
+ messages: ChatMessage[];
1194
+ }>>;
1195
+ deleteSession(agentId: string, sessionId: string): Promise<AgentsResult<{
1196
+ ok: true;
1197
+ }>>;
1153
1198
  }
1154
1199
 
1155
1200
  /**
@@ -1228,4 +1273,4 @@ declare class MitwayBaasClient {
1228
1273
  */
1229
1274
  declare function createClient(config: MitwayBaasConfig): MitwayBaasClient;
1230
1275
 
1231
- export { type Agent, type AgentInvokeResult, AgentsModule, type AgentsResult, type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };
1276
+ export { type Agent, type AgentInvokeResult, AgentsModule, type AgentsResult, type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type ChatMessage, type ChatSession, type ChatTurn, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };
package/dist/index.d.ts CHANGED
@@ -1116,8 +1116,10 @@ declare class Functions {
1116
1116
 
1117
1117
  /**
1118
1118
  * Agents module — thin wrapper over the `/api/agents/*` REST endpoints
1119
- * exposed by MITWAY-BaaS. Lists agents registered in the tenant and
1120
- * invokes them through the BaaS-native gateway.
1119
+ * exposed by MITWAY-BaaS. Lists agents registered in the tenant, invokes
1120
+ * them through the BaaS-native gateway, and drives multi-turn chat
1121
+ * sessions with server-side memory (`chat`, `listSessions`,
1122
+ * `getMessages`, `deleteSession`).
1121
1123
  */
1122
1124
 
1123
1125
  interface Agent {
@@ -1137,6 +1139,31 @@ interface AgentInvokeResult {
1137
1139
  message: string;
1138
1140
  } | null;
1139
1141
  }
1142
+ interface ChatTurn {
1143
+ sessionId: string;
1144
+ runId: string;
1145
+ status: 'succeeded' | 'failed';
1146
+ output: unknown;
1147
+ text: string | null;
1148
+ totalTokens: number;
1149
+ totalCost: number;
1150
+ error: {
1151
+ message: string;
1152
+ } | null;
1153
+ }
1154
+ interface ChatSession {
1155
+ id: string;
1156
+ createdAt: string;
1157
+ lastActivityAt: string;
1158
+ messageCount: number;
1159
+ lastMessagePreview: string | null;
1160
+ }
1161
+ interface ChatMessage {
1162
+ id: string;
1163
+ role: 'user' | 'assistant';
1164
+ content: string;
1165
+ createdAt: string;
1166
+ }
1140
1167
  type AgentsResult<T> = {
1141
1168
  data: T | null;
1142
1169
  error: MitwayBaasError | null;
@@ -1150,6 +1177,24 @@ declare class AgentsModule {
1150
1177
  agents: Agent[];
1151
1178
  }>>;
1152
1179
  invoke<TInput = unknown>(agentId: string, input?: TInput): Promise<AgentsResult<AgentInvokeResult>>;
1180
+ chat(agentId: string, message: string, opts?: {
1181
+ sessionId?: string;
1182
+ extraContext?: string;
1183
+ }): Promise<AgentsResult<ChatTurn>>;
1184
+ listSessions(agentId: string, opts?: {
1185
+ limit?: number;
1186
+ }): Promise<AgentsResult<{
1187
+ sessions: ChatSession[];
1188
+ }>>;
1189
+ getMessages(agentId: string, sessionId: string, opts?: {
1190
+ limit?: number;
1191
+ before?: string;
1192
+ }): Promise<AgentsResult<{
1193
+ messages: ChatMessage[];
1194
+ }>>;
1195
+ deleteSession(agentId: string, sessionId: string): Promise<AgentsResult<{
1196
+ ok: true;
1197
+ }>>;
1153
1198
  }
1154
1199
 
1155
1200
  /**
@@ -1228,4 +1273,4 @@ declare class MitwayBaasClient {
1228
1273
  */
1229
1274
  declare function createClient(config: MitwayBaasConfig): MitwayBaasClient;
1230
1275
 
1231
- export { type Agent, type AgentInvokeResult, AgentsModule, type AgentsResult, type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };
1276
+ export { type Agent, type AgentInvokeResult, AgentsModule, type AgentsResult, type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type ChatMessage, type ChatSession, type ChatTurn, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import {PostgrestClient}from'@mitway/postgrest-js';import {io}from'socket.io-client';var c=class s extends Error{statusCode;error;nextActions;constructor(e,t,r,n){super(e),this.name="MitwayBaasError",this.statusCode=t,this.error=r,this.nextActions=n;}static fromApiError(e){return new s(e.message,e.statusCode,e.error,e.nextActions)}};var ee=["authorization","x-api-key","cookie","set-cookie"],te=["password","token","accesstoken","refreshtoken","authorization","secret","apikey","api_key","email","ssn","creditcard","credit_card"];function re(s){let e={};for(let[t,r]of Object.entries(s))ee.includes(t.toLowerCase())?e[t]="***REDACTED***":e[t]=r;return e}function C(s){if(s==null)return s;if(typeof s=="string")try{let e=JSON.parse(s);return C(e)}catch{return s}if(Array.isArray(s))return s.map(C);if(typeof s=="object"){let e={};for(let[t,r]of Object.entries(s))te.includes(t.toLowerCase().replace(/[-_]/g,""))?e[t]="***REDACTED***":e[t]=C(r);return e}return s}function V(s){if(s==null)return "";if(typeof s=="string")try{return JSON.stringify(JSON.parse(s),null,2)}catch{return s}if(typeof FormData<"u"&&s instanceof FormData)return "[FormData]";try{return JSON.stringify(s,null,2)}catch{return "[Unserializable body]"}}var R=class{enabled;customLog;constructor(e){typeof e=="function"?(this.enabled=true,this.customLog=e):(this.enabled=!!e,this.customLog=null);}log(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.log(r,...t);}warn(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.warn(r,...t);}error(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.error(r,...t);}logRequest(e,t,r,n){if(!this.enabled)return;let i=[`\u2192 ${e} ${t}`];r&&Object.keys(r).length>0&&i.push(` Headers: ${JSON.stringify(re(r))}`);let o=V(C(n));if(o){let a=o.length>1e3?o.slice(0,1e3)+"... [truncated]":o;i.push(` Body: ${a}`);}this.log(i.join(`
2
- `));}logResponse(e,t,r,n,i){if(!this.enabled)return;let o=[`\u2190 ${e} ${t} ${r} (${n}ms)`],a=V(C(i));if(a){let g=a.length>1e3?a.slice(0,1e3)+"... [truncated]":a;o.push(` Body: ${g}`);}r>=400?this.error(o.join(`
1
+ import {PostgrestClient}from'@mitway/postgrest-js';import {io}from'socket.io-client';var c=class r extends Error{statusCode;error;nextActions;constructor(e,t,s,n){super(e),this.name="MitwayBaasError",this.statusCode=t,this.error=s,this.nextActions=n;}static fromApiError(e){return new r(e.message,e.statusCode,e.error,e.nextActions)}};var re=["authorization","x-api-key","cookie","set-cookie"],ie=["password","token","accesstoken","refreshtoken","authorization","secret","apikey","api_key","email","ssn","creditcard","credit_card"];function oe(r){let e={};for(let[t,s]of Object.entries(r))re.includes(t.toLowerCase())?e[t]="***REDACTED***":e[t]=s;return e}function P(r){if(r==null)return r;if(typeof r=="string")try{let e=JSON.parse(r);return P(e)}catch{return r}if(Array.isArray(r))return r.map(P);if(typeof r=="object"){let e={};for(let[t,s]of Object.entries(r))ie.includes(t.toLowerCase().replace(/[-_]/g,""))?e[t]="***REDACTED***":e[t]=P(s);return e}return r}function X(r){if(r==null)return "";if(typeof r=="string")try{return JSON.stringify(JSON.parse(r),null,2)}catch{return r}if(typeof FormData<"u"&&r instanceof FormData)return "[FormData]";try{return JSON.stringify(r,null,2)}catch{return "[Unserializable body]"}}var R=class{enabled;customLog;constructor(e){typeof e=="function"?(this.enabled=true,this.customLog=e):(this.enabled=!!e,this.customLog=null);}log(e,...t){if(!this.enabled)return;let s=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(s,...t):console.log(s,...t);}warn(e,...t){if(!this.enabled)return;let s=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(s,...t):console.warn(s,...t);}error(e,...t){if(!this.enabled)return;let s=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(s,...t):console.error(s,...t);}logRequest(e,t,s,n){if(!this.enabled)return;let i=[`\u2192 ${e} ${t}`];s&&Object.keys(s).length>0&&i.push(` Headers: ${JSON.stringify(oe(s))}`);let o=X(P(n));if(o){let a=o.length>1e3?o.slice(0,1e3)+"... [truncated]":o;i.push(` Body: ${a}`);}this.log(i.join(`
2
+ `));}logResponse(e,t,s,n,i){if(!this.enabled)return;let o=[`\u2190 ${e} ${t} ${s} (${n}ms)`],a=X(P(i));if(a){let d=a.length>1e3?a.slice(0,1e3)+"... [truncated]":a;o.push(` Body: ${d}`);}s>=400?this.error(o.join(`
3
3
  `)):this.log(o.join(`
4
- `));}};var z="mitway_baas_csrf_token",ne="mitway_baas_session";function Y(){return typeof localStorage<"u"?{getItem:e=>{try{return localStorage.getItem(e)}catch{return null}},setItem:(e,t)=>{try{localStorage.setItem(e,t);}catch{}},removeItem:e=>{try{localStorage.removeItem(e);}catch{}}}:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}}var se={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function Q(){if(typeof document>"u")return null;let s=document.cookie.split(";").find(e=>e.trim().startsWith(`${z}=`));return s&&s.split("=")[1]||null}function D(s){if(typeof document>"u")return;let e=10080*60,t=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${z}=${encodeURIComponent(s)}; path=/; max-age=${e}; SameSite=Lax${t}`;}function N(){if(typeof document>"u")return;let s=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${z}=; path=/; max-age=0; SameSite=Lax${s}`;}var S=class{accessToken=null;refreshToken=null;user=null;persistSession;storageKey;storage;onTokenChange=null;constructor(e){this.persistSession=e?.persistSession??true,this.storageKey=e?.storageKey??ne,this.storage=this.persistSession?e?.storage??Y():se,(e?.multiTab??true)&&this.persistSession&&typeof window<"u"&&typeof localStorage<"u"&&window.addEventListener("storage",this.handleStorageEvent),this.restoreSession();}handleStorageEvent=e=>{e.key===this.storageKey&&(typeof localStorage<"u"&&e.storageArea!==localStorage||this.syncFromStorage(e.newValue));};syncFromStorage(e){let t=this.accessToken;if(e===null)this.accessToken=null,this.refreshToken=null,this.user=null;else try{let r=JSON.parse(e);if(!r.accessToken||!r.user)return;this.accessToken=r.accessToken,this.refreshToken=r.refreshToken??null,this.user=r.user;}catch{return}t!==this.accessToken&&this.onTokenChange&&this.onTokenChange();}saveSession(e){let t=e.accessToken!==this.accessToken;this.accessToken=e.accessToken,this.user=e.user,e.refreshToken!==void 0&&(this.refreshToken=e.refreshToken??null),this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getSession(){return !this.accessToken||!this.user?null:{accessToken:this.accessToken,refreshToken:this.refreshToken??void 0,user:this.user}}getAccessToken(){return this.accessToken}setAccessToken(e){let t=e!==this.accessToken;this.accessToken=e,this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getRefreshToken(){return this.refreshToken}setRefreshToken(e){this.refreshToken=e,this.persist();}getUser(){return this.user}setUser(e){this.user=e,this.persist();}clearSession(){let e=this.accessToken!==null;this.accessToken=null,this.refreshToken=null,this.user=null,this.removePersisted(),e&&this.onTokenChange&&this.onTokenChange();}restoreSession(){if(!this.persistSession)return false;try{let e=this.storage.getItem(this.storageKey);if(!e)return !1;let t=JSON.parse(e);return !t.accessToken||!t.user?!1:(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken??null,this.user=t.user,!0)}catch{return false}}persist(){if(!this.persistSession||!this.accessToken||!this.user)return;let e={accessToken:this.accessToken,user:this.user};this.refreshToken&&(e.refreshToken=this.refreshToken),this.storage.setItem(this.storageKey,JSON.stringify(e));}removePersisted(){this.persistSession&&this.storage.removeItem(this.storageKey);}};function P(s){if(!s||typeof s!="object")return s;let e=s,t={...e},r=false;return "access_token"in e&&!("accessToken"in e)&&(t.accessToken=e.access_token,delete t.access_token,r=true),"csrf_token"in e&&!("csrfToken"in e)&&(t.csrfToken=e.csrf_token,delete t.csrf_token,r=true),"refresh_token"in e&&!("refreshToken"in e)&&(t.refreshToken=e.refresh_token,delete t.refresh_token,r=true),r?t:s}var ie=new Set([500,502,503,504]),oe=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),_=class{baseUrl;fetch;defaultHeaders;anonKey;userToken=null;logger;autoRefreshToken=true;isRefreshing=false;refreshPromise=null;tokenManager;refreshToken=null;timeout;retryCount;retryDelay;constructor(e,t,r){if(this.baseUrl=e.baseUrl||"http://localhost:7130",this.autoRefreshToken=e.autoRefreshToken??true,this.fetch=e.fetch||(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),this.anonKey=e.anonKey,this.defaultHeaders={...e.headers},this.tokenManager=t??new S,this.logger=r||new R(false),this.timeout=e.timeout??3e4,this.retryCount=e.retryCount??3,this.retryDelay=e.retryDelay??500,!this.fetch)throw new Error("Fetch is not available. Provide a fetch implementation in the SDK config.")}buildUrl(e,t){let r=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([n,i])=>{if(n==="select"){let o=i.replace(/\s+/g," ").trim();o=o.replace(/\s*\(\s*/g,"(").replace(/\s*\)\s*/g,")").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/,\s+(?=[^()]*\))/g,","),r.searchParams.append(n,o);}else r.searchParams.append(n,i);}),r.toString()}isRetryableStatus(e){return ie.has(e)}computeRetryDelay(e){let r=this.retryDelay*Math.pow(2,e-1)*(.85+Math.random()*.3);return Math.round(r)}async handleRequest(e,t,r={}){let{params:n,headers:i={},body:o,signal:a,...g}=r,p=this.buildUrl(t,n),v=Date.now(),T=oe.has(e.toUpperCase())||r.idempotent===true?this.retryCount:0,b={...this.defaultHeaders},G=this.userToken||this.anonKey;G&&(b.Authorization=`Bearer ${G}`);let F;o!==void 0&&(typeof FormData<"u"&&o instanceof FormData?F=o:(e!=="GET"&&(b["Content-Type"]="application/json;charset=UTF-8"),F=JSON.stringify(o))),i instanceof Headers?i.forEach((f,h)=>{b[h]=f;}):Array.isArray(i)?i.forEach(([f,h])=>{b[f]=h;}):Object.assign(b,i),this.logger.logRequest(e,p,b,F);let q;for(let f=0;f<=T;f++){if(f>0){let l=this.computeRetryDelay(f);if(this.logger.warn(`Retry ${f}/${T} for ${e} ${p} in ${l}ms`),a?.aborted)throw a.reason;await new Promise((u,K)=>{let k=()=>{clearTimeout(Z),K(a.reason);},Z=setTimeout(()=>{a&&a.removeEventListener("abort",k),u();},l);a&&a.addEventListener("abort",k,{once:true});});}let h,m;if((this.timeout>0||a)&&(h=new AbortController,this.timeout>0&&(m=setTimeout(()=>h.abort(),this.timeout)),a))if(a.aborted)h.abort(a.reason);else {let l=()=>h.abort(a.reason);a.addEventListener("abort",l,{once:true}),h.signal.addEventListener("abort",()=>{a.removeEventListener("abort",l);},{once:true});}try{let l=await this.fetch(p,{method:e,headers:b,body:F,...g,...h?{signal:h.signal}:{}});if(this.isRetryableStatus(l.status)&&f<T){m!==void 0&&clearTimeout(m),await l.body?.cancel(),q=new c(`Server error: ${l.status} ${l.statusText}`,l.status,"SERVER_ERROR");continue}if(l.status===204){m!==void 0&&clearTimeout(m);return}let u,K=l.headers.get("content-type");try{K?.includes("json")?u=await l.json():u=await l.text();}catch(k){throw m!==void 0&&clearTimeout(m),new c(`Failed to parse response body: ${k?.message||"Unknown error"}`,l.status,l.ok?"PARSE_ERROR":"REQUEST_FAILED")}if(m!==void 0&&clearTimeout(m),!l.ok){if(this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"error"in u&&u.error!==null&&typeof u.error=="object"){let k=u.error;throw new c(k.message||l.statusText||"Request failed",k.statusCode||l.status,k.code||k.error||"REQUEST_FAILED",k.nextActions)}throw new c(`Request failed: ${l.statusText}`,l.status,"REQUEST_FAILED")}return this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"data"in u&&"error"in u&&u.error===null?u.data:u}catch(l){if(m!==void 0&&clearTimeout(m),l?.name==="AbortError")throw h&&h.signal.aborted&&this.timeout>0&&!a?.aborted?new c(`Request timed out after ${this.timeout}ms`,408,"REQUEST_TIMEOUT"):l;if(l instanceof c)throw l;if(f<T){q=l;continue}throw new c(`Network request failed: ${l?.message||"Unknown error"}`,0,"NETWORK_ERROR")}}throw q||new c("Request failed after all retry attempts",0,"NETWORK_ERROR")}async request(e,t,r={}){try{return await this.handleRequest(e,t,{...r})}catch(n){if(n instanceof c&&n.statusCode===401&&this.autoRefreshToken&&this.refreshToken&&!t.includes("/api/auth/refresh"))try{let i=await this.handleTokenRefresh();this.setAuthToken(i.accessToken),i.refreshToken&&this.setRefreshToken(i.refreshToken),i.csrfToken&&D(i.csrfToken);let o=i.user??this.tokenManager.getUser();return o&&this.tokenManager.saveSession({accessToken:i.accessToken,refreshToken:i.refreshToken,user:o}),await this.handleRequest(e,t,{...r})}catch(i){throw this.tokenManager.clearSession(),this.userToken=null,this.refreshToken=null,N(),i}throw n}}async rawFetch(e,t={}){let r=this.buildUrl(e),n=new Headers(t.headers??{});for(let[i,o]of Object.entries(this.defaultHeaders))n.has(i)||n.set(i,o);if(!n.has("Authorization")){let i=this.userToken??this.anonKey;i&&n.set("Authorization",`Bearer ${i}`);}return this.fetch(r,{...t,headers:n})}get(e,t){return this.request("GET",e,t)}post(e,t,r){return this.request("POST",e,{...r,body:t})}put(e,t,r){return this.request("PUT",e,{...r,body:t})}patch(e,t,r){return this.request("PATCH",e,{...r,body:t})}delete(e,t){return this.request("DELETE",e,t)}setAuthToken(e){this.userToken=e;}setRefreshToken(e){this.refreshToken=e;}getHeaders(){let e={...this.defaultHeaders},t=this.userToken||this.anonKey;return t&&(e.Authorization=`Bearer ${t}`),e}async handleTokenRefresh(){return this.isRefreshing?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let e=Q(),t=this.refreshToken?{refreshToken:this.refreshToken}:void 0,r=await this.handleRequest("POST","/api/auth/refresh",{body:t,headers:e?{"X-CSRF-Token":e}:{},credentials:"include"});return P(r)}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}};function w(s,e){return s instanceof c?{data:null,error:s}:{data:null,error:new c(s instanceof Error?s.message:e,500,"AUTH_ERROR")}}var A=class{constructor(e,t){this.http=e;this.tokenManager=t;this.tokenManager.onTokenChange=()=>this._emitFromTokenChange();let r=this.tokenManager.getSession();if(r){this.http.setAuthToken(r.accessToken);let n=this.tokenManager.getRefreshToken();n&&this.http.setRefreshToken(n),this.lastEmittedUserId=r.user.id,this.lastEmittedAccessToken=r.accessToken;}}http;tokenManager;stateChangeListeners=new Set;lastEmittedUserId=null;lastEmittedAccessToken=null;onAuthStateChange(e){return this.stateChangeListeners.add(e),{unsubscribe:()=>{this.stateChangeListeners.delete(e);}}}emit(e,t){for(let r of this.stateChangeListeners)try{r(e,t);}catch{}}_emitFromTokenChange(){let e=this.tokenManager.getSession();e?(this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null)):(this.http.setAuthToken(null),this.http.setRefreshToken(null));let t=this.lastEmittedUserId,r=this.lastEmittedAccessToken;if(!e){t!==null&&(this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null));return}let n=e.user.id;if(t===null){this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}if(t!==n){this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null),this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}r!==e.accessToken&&(this.lastEmittedAccessToken=e.accessToken,this.emit("TOKEN_REFRESHED",e));}saveSessionFromResponse(e){let t={accessToken:e.accessToken,refreshToken:e.refreshToken,user:e.user};e.csrfToken&&D(e.csrfToken),this.tokenManager.saveSession(t),this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null);}async signUp(e){try{let t=await this.http.post("/api/auth/register",e,{credentials:"include"}),r=P(t);return r?.accessToken&&r.user&&this.saveSessionFromResponse(r),{data:r,error:null}}catch(t){return w(t,"Sign up failed")}}async signInWithPassword(e){try{let t=await this.http.post("/api/auth/login",e,{credentials:"include"}),r=P(t);return r?.accessToken&&r.user&&this.saveSessionFromResponse(r),{data:r,error:null}}catch(t){return w(t,"Sign in failed")}}async signOut(){try{try{await this.http.post("/api/auth/logout",void 0,{credentials:"include"});}catch{}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),N(),{error:null}}catch{return {error:new c("Failed to sign out",500,"SIGNOUT_ERROR")}}}async refreshSession(){try{let e=await this.http.handleTokenRefresh();if(e?.accessToken){let t=e.user??this.tokenManager.getUser();if(t){let r={...e,user:t};return this.saveSessionFromResponse(r),{data:r,error:null}}}return {data:e,error:null}}catch(e){return w(e,"Session refresh failed")}}async initialize(){let e=this.tokenManager.getSession();if(!e)return this.emit("INITIAL_SESSION",null),{data:null,error:new c("No persisted session",0,"NO_SESSION")};try{let t=await this.http.get("/api/auth/sessions/current");if(t?.user){this.tokenManager.setUser(t.user);let r=this.tokenManager.getSession();return this.emit("INITIAL_SESSION",r),{data:{user:t.user,accessToken:e.accessToken},error:null}}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),{data:null,error:new c("Invalid session",401,"INVALID_SESSION")}}catch(t){return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),w(t,"Session restore failed")}}getSession(){return this.tokenManager.getSession()}getUser(){return this.tokenManager.getUser()}async getCurrentUser(){try{let e=await this.http.get("/api/auth/sessions/current");if(e?.user){let t={accessToken:this.tokenManager.getSession()?.accessToken??"",user:e.user};this.tokenManager.saveSession(t);}return {data:e,error:null}}catch(e){return w(e,"Failed to get current user")}}async getProfile(e){try{return {data:await this.http.get(`/api/auth/profiles/${encodeURIComponent(e)}`),error:null}}catch(t){return w(t,"Failed to get profile")}}async setProfile(e){try{let t=await this.http.patch("/api/auth/profiles/current",{profile:e}),r=this.tokenManager.getUser();if(t?.profile&&r){let n={...r,profile:t.profile};this.tokenManager.setUser(n),this.emit("USER_UPDATED",this.tokenManager.getSession());}return {data:t,error:null}}catch(t){return w(t,"Failed to update profile")}}};function ce(s,e,t){return async(r,n)=>{let i=typeof r=="string"?r:r.toString(),o=new URL(i),a=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,g=a.match(/^rpc\/(.+)$/),p=g?`/api/database/rpc/${g[1]}`:`/api/database/records/${a}`,v=`${s.baseUrl}${p}${o.search}`,M=new Headers(n?.headers);if(!M.has("Authorization")){let T=e.getAccessToken()??t;T&&M.set("Authorization",`Bearer ${T}`);}return fetch(v,{...n,headers:M})}}var O=class{postgrest;httpClient;constructor(e,t,r){this.httpClient=e,this.postgrest=new PostgrestClient("http://dummy",{fetch:ce(e,t,r),headers:{}});}from(e){if(!e||typeof e!="string")throw new c("Database.from(table) requires a non-empty string",400,"INVALID_TABLE_NAME");return this.postgrest.from(e)}rpc(e,t,r){return this.postgrest.rpc(e,t,r)}getUrl(){return this.httpClient.baseUrl}};var ue=2e4;function W(s,e){let t=new Error(e);return t.code=s,t}var de=1e4,L=class{constructor(e,t,r={}){this.topic=e;this.realtime=t;this.options=r;}topic;realtime;bindings=[];state="closed";statusCallback=null;presence={};trackedState=null;presenceHeartbeat=null;lastBroadcastTimestamp=null;options;get isPrivate(){return this.options.config?.private===true}get presenceKey(){return this.options.config?.presence?.key}_state(){return this.state}async _rejoinAfterReconnect(){if(this.state!=="closed"){for(let e of this.bindings)e.type==="postgres_changes"&&(e.subscriptionId=void 0);this.state="joining";try{if(await this.registerAllBindings(),this.trackedState){let e=this.realtime._getSocket(),t=this.presenceKey;e?.emit("realtime:presence:track",t!==void 0?{channel:this.topic,state:this.trackedState,key:t}:{channel:this.topic,state:this.trackedState});}this.lastBroadcastTimestamp&&this.bindings.some(e=>e.type==="broadcast")&&this.replay({since:this.lastBroadcastTimestamp}).catch(()=>{}),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(e){this.state="errored",this.statusCallback?.("CHANNEL_ERROR",W("REJOIN_FAILED",e instanceof Error?e.message:String(e)));}}}on(e,t,r){return e==="postgres_changes"?this.bindings.push({type:"postgres_changes",filter:t,callback:r}):e==="broadcast"?this.bindings.push({type:"broadcast",filter:t,callback:r}):this.bindings.push({type:"presence",filter:t,callback:r}),this}async track(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");this.trackedState=e;let r=this.presenceKey;t.emit("realtime:presence:track",r!==void 0?{channel:this.topic,state:e,key:r}:{channel:this.topic,state:e}),this.presenceHeartbeat||(this.presenceHeartbeat=setInterval(()=>{let i=this.realtime._getSocket();i&&this.trackedState&&i.emit("realtime:presence:track",r!==void 0?{channel:this.topic,state:this.trackedState,key:r}:{channel:this.topic,state:this.trackedState});},ue),this.presenceHeartbeat.unref?.());}untrack(){this.trackedState=null,this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),this.realtime._getSocket()?.emit("realtime:presence:untrack",{channel:this.topic});}presenceState(){return this.presence}subscribe(e){return this.statusCallback=e??null,this.state==="joining"||this.state==="joined"?this:(this.state="joining",this.realtime.connect().then(async()=>{try{await this.registerAllBindings(),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(t){this.state="errored";let r=t instanceof Error?t.message:String(t);this.statusCallback?.("CHANNEL_ERROR",W("SUBSCRIBE_FAILED",r));}},t=>{this.state="errored",this.statusCallback?.("CHANNEL_ERROR",W("CONNECT_FAILED",t.message));}),this)}async unsubscribe(){if(this.state==="closed")return;let e=this.realtime._getSocket();if(this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),!e){this.trackedState=null,this.state="closed";return}this.trackedState&&(e.emit("realtime:presence:untrack",{channel:this.topic}),this.trackedState=null);let t=this.bindings.filter(r=>r.type==="postgres_changes");for(let r of t)r.subscriptionId&&(e.emit("realtime:postgres_changes:unsubscribe",{subscription_id:r.subscriptionId}),r.subscriptionId=void 0);this.bindings.some(r=>r.type==="broadcast"||r.type==="presence")&&e.emit("realtime:unsubscribe",{channel:this.topic}),this.realtime._detachChannel(this),this.state="closed",this.statusCallback?.("CLOSED");}async send(e){if(e.type!=="broadcast")throw new c('Only "broadcast" sends are supported \u2014 DB changes flow via your DB writes, not channel.send()',400,"UNSUPPORTED_SEND_TYPE");if(new Set(["postgres_changes","presence_state","presence_join","presence_leave"]).has(e.event))throw new c(`"${e.event}" is a reserved event name \u2014 pick a different name for broadcast events`,400,"RESERVED_EVENT_NAME");let r=this.realtime._getSocket();if(!r)throw new c("Socket not connected",503,"NOT_CONNECTED");let n=this.options.config?.broadcast?.self,i={channel:this.topic,event:e.event,payload:e.payload};return n===false&&(i.self=false),await new Promise(o=>{r.emit("realtime:publish",i,a=>{o(a);});})}async replay(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");t.emit("realtime:broadcast:replay",{channel:this.topic,since:e.since,limit:e.limit,private:this.isPrivate});}_dispatch(e,t){if(e==="postgres_changes"){let n=t;for(let i of this.bindings)if(!(i.type!=="postgres_changes"||!i.subscriptionId||!n.ids.includes(i.subscriptionId)||!(i.filter.event==="*"||i.filter.event===n.data.eventType)))try{i.callback(n.data);}catch{}return}if(e==="presence_state"||e==="presence_join"||e==="presence_leave"){let n=t;if(n.channel!==this.topic)return;if(e==="presence_state"&&n.state)this.presence={...n.state},this.firePresence({event:"sync",state:this.presence});else if(e==="presence_join"&&n.joins)Object.assign(this.presence,n.joins),this.firePresence({event:"join",joins:n.joins});else if(e==="presence_leave"&&n.leaves){for(let i of Object.keys(n.leaves))delete this.presence[i];this.firePresence({event:"leave",leaves:n.leaves});}return}let r=t.meta;r?.timestamp&&(!this.lastBroadcastTimestamp||r.timestamp>this.lastBroadcastTimestamp)&&(this.lastBroadcastTimestamp=r.timestamp);for(let n of this.bindings){if(n.type!=="broadcast"||n.filter.event!==e)continue;let{meta:i,...o}=t;try{n.callback({type:"broadcast",event:e,payload:o});}catch{}}}firePresence(e){for(let t of this.bindings)if(t.type==="presence"&&t.filter.event===e.event)try{e.event==="sync"?t.callback():(e.event,t.callback(e));}catch{}}async registerAllBindings(){let e=this.realtime._getSocket();if(!e)throw new Error("Socket not available");this.bindings.some(n=>n.type==="broadcast"||n.type==="presence")&&await new Promise((n,i)=>{e.emit("realtime:subscribe",{channel:this.topic,private:this.isPrivate},o=>{o.status==="ok"?n():i(new Error(o.error?.message??"subscribe failed"));});});let r=this.bindings.filter(n=>n.type==="postgres_changes");await Promise.all(r.map(n=>new Promise((i,o)=>{e.emit("realtime:postgres_changes:subscribe",{event:n.filter.event,schema:n.filter.schema??"public",table:n.filter.table,filter:n.filter.filter},a=>{a.status==="ok"&&a.subscription_id?(n.subscriptionId=a.subscription_id,i()):o(new Error(a.error?.message??"postgres_changes subscribe failed"));});})));}},I=class{socket=null;baseUrl;options;anonKey;tokenManager;channels=new Map;connecting=null;firstConnected=false;constructor(e,t,r,n={}){this.baseUrl=e,this.tokenManager=t,this.anonKey=r,this.options=n;}get isConnected(){return this.socket?.connected===true}get socketId(){return this.socket?.id}channel(e,t){let r=this.channels.get(e);if(r)return r;let n=new L(e,this,t);return this.channels.set(e,n),n}connect(){return this.isConnected?Promise.resolve():this.connecting?this.connecting:(this.connecting=this.openSocket(),this.connecting)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.firstConnected=false);}_getSocket(){return this.socket}_detachChannel(e){this.channels.delete(e.topic);}openSocket(){let e=this.tokenManager.getAccessToken()??this.anonKey;if(!e){let n=new c("Realtime requires an access token or anonKey",401,"AUTH_INVALID_API_KEY");return this.connecting=null,Promise.reject(n)}let t=this.options.timeoutMs??de,r=io(this.baseUrl,{path:this.options.path,transports:this.options.transports??["websocket"],auth:{token:e,...this.options.extraAuth??{}},reconnection:true,timeout:t});return this.socket=r,r.onAny((n,...i)=>this.dispatch(n,i)),r.on("connect",()=>{if(this.firstConnected)for(let n of this.channels.values()){let i=n._state();(i==="joined"||i==="errored")&&n._rejoinAfterReconnect();}}),new Promise((n,i)=>{let o=setTimeout(()=>{r.off("connect",g),r.off("connect_error",p),this.connecting=null,i(new c(`Realtime connection timeout after ${t}ms`,408,"CONNECTION_TIMEOUT"));},t),a=()=>{clearTimeout(o),r.off("connect",g),r.off("connect_error",p);},g=()=>{a(),this.connecting=null,this.firstConnected=true,n();},p=v=>{a(),this.connecting=null,i(new c(v.message,0,"CONNECTION_FAILED"));};r.once("connect",g),r.once("connect_error",p);})}dispatch(e,t){if(e==="postgres_changes"){let n=t[0]??{};this.channels.forEach(i=>i._dispatch("postgres_changes",n));return}if(e==="connect"||e==="disconnect"||e==="connect_error"||e==="error"||e==="realtime:error"||e==="realtime:shutdown")return;let r=t[0]??{};this.channels.forEach(n=>n._dispatch(e,r));}};function j(s){return {id:s.id,name:s.name,public:s.public,fileSizeLimitBytes:s.file_size_limit_bytes,allowedMimeTypes:s.allowed_mime_types,createdAt:s.created_at,updatedAt:s.updated_at}}function $(s,e){return {id:s.id,bucket:e,key:s.key,size:s.size,mimeType:s.mime_type,etag:s.etag,cacheControl:s.cache_control,contentDisposition:s.content_disposition,uploadedBy:s.uploaded_by,uploadedAt:s.uploaded_at,updatedAt:s.updated_at}}function he(s){return {defaultFileSizeLimitBytes:s.default_file_size_limit_bytes,maxFileSizeLimitBytes:s.max_file_size_limit_bytes,tenantStorageQuotaBytes:s.tenant_storage_quota_bytes,reservedSpaceBytes:s.reserved_space_bytes,signedUrlDefaultTtlSec:s.signed_url_default_ttl_sec,signedUrlMaxTtlSec:s.signed_url_max_ttl_sec}}function ge(s){return s.split("/").map(encodeURIComponent).join("/")}function d(s,e){return s instanceof c?{data:null,error:s}:{data:null,error:new c(s instanceof Error?s.message:e,0,"STORAGE_ERROR")}}async function J(s){let e="STORAGE_ERROR",t=`HTTP ${s.status}`;try{let r=await s.json();r&&r.error&&(e=r.error.code??e,t=r.error.message??t);}catch{}return new c(t,s.status,e)}var H=class{constructor(e,t){this.http=e;this.bucketName=t;}http;bucketName;bucketBase(){return `/api/storage/buckets/${encodeURIComponent(this.bucketName)}`}objectPath(e){return `${this.bucketBase()}/objects/${ge(e)}`}async upload(e,t,r={}){try{let n=r.upsert?"PUT":"POST",i={"Content-Type":r.contentType??"application/octet-stream"};r.cacheControl&&(i["Cache-Control"]=r.cacheControl),r.contentDisposition&&(i["Content-Disposition"]=r.contentDisposition);let o=await this.http.rawFetch(this.objectPath(e),{method:n,headers:i,body:t,signal:r.abortSignal});if(!o.ok)return {data:null,error:await J(o)};let a=await o.json();return a.error||!a.data?{data:null,error:new c(a.error?.message??"Upload failed",o.status,a.error?.code??"STORAGE_ERROR")}:{data:$(a.data,this.bucketName),error:null}}catch(n){return d(n,"Upload failed")}}async download(e,t={}){try{let r={};t.range&&(r.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:r,signal:t.abortSignal});return n.ok?{data:await n.blob(),error:null}:{data:null,error:await J(n)}}catch(r){return d(r,"Download failed")}}async getStream(e,t={}){try{let r={};t.range&&(r.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:r,signal:t.abortSignal});return n.ok?n.body?{data:n.body,error:null}:{data:null,error:new c("Response body is not a stream",n.status,"STORAGE_ERROR")}:{data:null,error:await J(n)}}catch(r){return d(r,"Download failed")}}async remove(e){try{let t=await Promise.allSettled(e.map(i=>this.http.rawFetch(this.objectPath(i),{method:"DELETE"}))),r=[],n=[];for(let i=0;i<e.length;i++){let o=e[i],a=t[i];if(a.status==="fulfilled"&&a.value.ok)r.push(o);else if(a.status==="fulfilled")n.push(`${o}: HTTP ${a.value.status}`);else {let g=a.reason instanceof Error?a.reason.message:String(a.reason);n.push(`${o}: ${g}`);}}return n.length>0?{data:null,error:new c(`Failed to delete some objects: ${n.join("; ")}`,0,"STORAGE_ERROR")}:{data:{removed:r},error:null}}catch(t){return d(t,"Delete failed")}}async list(e={}){try{let t={};return e.prefix!==void 0&&(t.prefix=e.prefix),e.limit!==void 0&&(t.limit=String(e.limit)),e.startAfter!==void 0&&(t.start_after=e.startAfter),{data:(await this.http.get(`${this.bucketBase()}/objects`,{params:t})).map(n=>$(n,this.bucketName)),error:null}}catch(t){return d(t,"List failed")}}async copy(e,t,r){try{let n=await this.http.post(`${this.objectPath(e)}/copy`,{dest_bucket:r??this.bucketName,dest_key:t});return {data:$(n,r??this.bucketName),error:null}}catch(n){return d(n,"Copy failed")}}async move(e,t,r){try{let n=await this.http.post(`${this.objectPath(e)}/move`,{dest_bucket:r??this.bucketName,dest_key:t});return {data:$(n,r??this.bucketName),error:null}}catch(n){return d(n,"Move failed")}}async createSignedUrl(e,t={}){try{let r={};t.expiresIn!==void 0&&(r.expires_in=t.expiresIn);let n=await this.http.post(`${this.objectPath(e)}/sign`,r);return {data:{url:n.url,token:n.token,expiresAt:n.expiresAt},error:null}}catch(r){return d(r,"Sign failed")}}getPublicUrl(e){return {data:{url:`${this.http.baseUrl.replace(/\/$/,"")}${this.objectPath(e)}`}}}},B=class{constructor(e){this.http=e;}http;from(e){return new H(this.http,e)}async listBuckets(){try{return {data:(await this.http.get("/api/storage/buckets")).map(j),error:null}}catch(e){return d(e,"listBuckets failed")}}async getBucket(e){try{let t=await this.http.get(`/api/storage/buckets/${encodeURIComponent(e)}`);return {data:j(t),error:null}}catch(t){return d(t,"getBucket failed")}}async createBucket(e,t={}){try{let r={name:e};t.public!==void 0&&(r.public=t.public),t.fileSizeLimitBytes!==void 0&&(r.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(r.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.post("/api/storage/buckets",r);return {data:j(n),error:null}}catch(r){return d(r,"createBucket failed")}}async updateBucket(e,t){try{let r={};t.public!==void 0&&(r.public=t.public),t.fileSizeLimitBytes!==void 0&&(r.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(r.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.patch(`/api/storage/buckets/${encodeURIComponent(e)}`,r);return {data:j(n),error:null}}catch(r){return d(r,"updateBucket failed")}}async deleteBucket(e){try{return await this.http.delete(`/api/storage/buckets/${encodeURIComponent(e)}`),{data:null,error:null}}catch(t){return d(t,"deleteBucket failed")}}async emptyBucket(e){try{return {data:await this.http.post(`/api/storage/buckets/${encodeURIComponent(e)}/empty`,{}),error:null}}catch(t){return d(t,"emptyBucket failed")}}async getConfig(){try{let e=await this.http.get("/api/storage/config");return {data:he(e),error:null}}catch(e){return d(e,"getConfig failed")}}};function pe(s){return {key:s.key,digest:s.digest,updatedAt:s.updated_at}}function y(s,e){return s instanceof c?{data:null,error:s}:{data:null,error:new c(s instanceof Error?s.message:e,0,"FUNCTIONS_ERROR")}}function fe(s){return typeof s=="object"&&s!==null&&!ArrayBuffer.isView(s)&&!(s instanceof Blob)&&!(s instanceof FormData)&&!(s instanceof URLSearchParams)&&!(s instanceof ReadableStream)}var U=class{constructor(e){this.http=e;}http;async list(){try{return {data:await this.http.get("/api/functions"),error:null}}catch(e){return y(e,"list failed")}}async get(e){try{return {data:await this.http.get(`/api/functions/${encodeURIComponent(e)}`),error:null}}catch(t){return y(t,"get failed")}}async create(e){try{return {data:await this.http.post("/api/functions",e),error:null}}catch(t){return y(t,"create failed")}}async update(e,t){try{return {data:await this.http.put(`/api/functions/${encodeURIComponent(e)}`,t),error:null}}catch(r){return y(r,"update failed")}}async remove(e){try{return await this.http.delete(`/api/functions/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return y(t,"remove failed")}}async invoke(e,t={}){try{let r=t.method??"POST",n={...t.headers},i;return t.body!==void 0&&t.body!==null&&(fe(t.body)?(i=JSON.stringify(t.body),n["Content-Type"]||(n["Content-Type"]="application/json")):i=t.body),{data:await this.http.rawFetch(`/api/invoke/${encodeURIComponent(e)}`,{method:r,headers:n,body:i}),error:null}}catch(r){return y(r,"invoke failed")}}async listSecrets(){try{return {data:(await this.http.get("/api/functions/secrets")).secrets.map(pe),error:null}}catch(e){return y(e,"listSecrets failed")}}async setSecrets(e){try{return await this.http.put("/api/functions/secrets",{secrets:e}),{data:{saved:!0},error:null}}catch(t){return y(t,"setSecrets failed")}}async deleteSecret(e){try{return await this.http.delete(`/api/functions/secrets/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return y(t,"deleteSecret failed")}}};var me=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ke(s){let e=typeof s=="number"&&Number.isFinite(s)?s:50;return Math.max(1,Math.min(200,Math.trunc(e)))}function X(s,e){return s instanceof c?{data:null,error:s}:{data:null,error:new c(s instanceof Error?s.message:e,0,"AGENTS_ERROR")}}var x=class{constructor(e){this.http=e;}http;async list(e){try{let t=ke(e?.limit);return {data:await this.http.get(`/api/agents?limit=${t}`),error:null}}catch(t){return X(t,"list failed")}}async invoke(e,t){if(typeof e!="string"||!me.test(e))return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")};try{let r=t!==void 0?{input:t}:void 0;return {data:await this.http.post(`/api/agents/${encodeURIComponent(e)}/invoke`,r),error:null}}catch(r){return X(r,"invoke failed")}}};var E=class{http;tokenManager;auth;database;realtime;storage;functions;agents;constructor(e={}){let t=new R(e.debug);this.tokenManager=new S({persistSession:e.persistSession,storageKey:e.storageKey,storage:e.storage,multiTab:e.multiTab}),this.http=new _(e,this.tokenManager,t),this.auth=new A(this.http,this.tokenManager),this.database=new O(this.http,this.tokenManager,e.anonKey),this.realtime=new I(this.http.baseUrl,this.tokenManager,e.anonKey,e.realtime),this.storage=new B(this.http),this.functions=new U(this.http),this.agents=new x(this.http);}getHttpClient(){return this.http}};function st(s){return new E(s)}var it=E;
5
- export{x as AgentsModule,A as Auth,O as Database,U as Functions,_ as HttpClient,R as Logger,E as MitwayBaasClient,c as MitwayBaasError,I as Realtime,L as RealtimeChannel,B as Storage,H as StorageBucketClient,S as TokenManager,st as createClient,Y as createLocalStorageAdapter,it as default};
4
+ `));}};var G="mitway_baas_csrf_token",ae="mitway_baas_session";function Z(){return typeof localStorage<"u"?{getItem:e=>{try{return localStorage.getItem(e)}catch{return null}},setItem:(e,t)=>{try{localStorage.setItem(e,t);}catch{}},removeItem:e=>{try{localStorage.removeItem(e);}catch{}}}:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}}var ce={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function ee(){if(typeof document>"u")return null;let r=document.cookie.split(";").find(e=>e.trim().startsWith(`${G}=`));return r&&r.split("=")[1]||null}function L(r){if(typeof document>"u")return;let e=10080*60,t=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=${encodeURIComponent(r)}; path=/; max-age=${e}; SameSite=Lax${t}`;}function j(){if(typeof document>"u")return;let r=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=; path=/; max-age=0; SameSite=Lax${r}`;}var S=class{accessToken=null;refreshToken=null;user=null;persistSession;storageKey;storage;onTokenChange=null;constructor(e){this.persistSession=e?.persistSession??true,this.storageKey=e?.storageKey??ae,this.storage=this.persistSession?e?.storage??Z():ce,(e?.multiTab??true)&&this.persistSession&&typeof window<"u"&&typeof localStorage<"u"&&window.addEventListener("storage",this.handleStorageEvent),this.restoreSession();}handleStorageEvent=e=>{e.key===this.storageKey&&(typeof localStorage<"u"&&e.storageArea!==localStorage||this.syncFromStorage(e.newValue));};syncFromStorage(e){let t=this.accessToken;if(e===null)this.accessToken=null,this.refreshToken=null,this.user=null;else try{let s=JSON.parse(e);if(!s.accessToken||!s.user)return;this.accessToken=s.accessToken,this.refreshToken=s.refreshToken??null,this.user=s.user;}catch{return}t!==this.accessToken&&this.onTokenChange&&this.onTokenChange();}saveSession(e){let t=e.accessToken!==this.accessToken;this.accessToken=e.accessToken,this.user=e.user,e.refreshToken!==void 0&&(this.refreshToken=e.refreshToken??null),this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getSession(){return !this.accessToken||!this.user?null:{accessToken:this.accessToken,refreshToken:this.refreshToken??void 0,user:this.user}}getAccessToken(){return this.accessToken}setAccessToken(e){let t=e!==this.accessToken;this.accessToken=e,this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getRefreshToken(){return this.refreshToken}setRefreshToken(e){this.refreshToken=e,this.persist();}getUser(){return this.user}setUser(e){this.user=e,this.persist();}clearSession(){let e=this.accessToken!==null;this.accessToken=null,this.refreshToken=null,this.user=null,this.removePersisted(),e&&this.onTokenChange&&this.onTokenChange();}restoreSession(){if(!this.persistSession)return false;try{let e=this.storage.getItem(this.storageKey);if(!e)return !1;let t=JSON.parse(e);return !t.accessToken||!t.user?!1:(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken??null,this.user=t.user,!0)}catch{return false}}persist(){if(!this.persistSession||!this.accessToken||!this.user)return;let e={accessToken:this.accessToken,user:this.user};this.refreshToken&&(e.refreshToken=this.refreshToken),this.storage.setItem(this.storageKey,JSON.stringify(e));}removePersisted(){this.persistSession&&this.storage.removeItem(this.storageKey);}};function A(r){if(!r||typeof r!="object")return r;let e=r,t={...e},s=false;return "access_token"in e&&!("accessToken"in e)&&(t.accessToken=e.access_token,delete t.access_token,s=true),"csrf_token"in e&&!("csrfToken"in e)&&(t.csrfToken=e.csrf_token,delete t.csrf_token,s=true),"refresh_token"in e&&!("refreshToken"in e)&&(t.refreshToken=e.refresh_token,delete t.refresh_token,s=true),s?t:r}var le=new Set([500,502,503,504]),ue=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),I=class{baseUrl;fetch;defaultHeaders;anonKey;userToken=null;logger;autoRefreshToken=true;isRefreshing=false;refreshPromise=null;tokenManager;refreshToken=null;timeout;retryCount;retryDelay;constructor(e,t,s){if(this.baseUrl=e.baseUrl||"http://localhost:7130",this.autoRefreshToken=e.autoRefreshToken??true,this.fetch=e.fetch||(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),this.anonKey=e.anonKey,this.defaultHeaders={...e.headers},this.tokenManager=t??new S,this.logger=s||new R(false),this.timeout=e.timeout??3e4,this.retryCount=e.retryCount??3,this.retryDelay=e.retryDelay??500,!this.fetch)throw new Error("Fetch is not available. Provide a fetch implementation in the SDK config.")}buildUrl(e,t){let s=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([n,i])=>{if(n==="select"){let o=i.replace(/\s+/g," ").trim();o=o.replace(/\s*\(\s*/g,"(").replace(/\s*\)\s*/g,")").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/,\s+(?=[^()]*\))/g,","),s.searchParams.append(n,o);}else s.searchParams.append(n,i);}),s.toString()}isRetryableStatus(e){return le.has(e)}computeRetryDelay(e){let s=this.retryDelay*Math.pow(2,e-1)*(.85+Math.random()*.3);return Math.round(s)}async handleRequest(e,t,s={}){let{params:n,headers:i={},body:o,signal:a,...d}=s,p=this.buildUrl(t,n),v=Date.now(),T=ue.has(e.toUpperCase())||s.idempotent===true?this.retryCount:0,b={...this.defaultHeaders},Q=this.userToken||this.anonKey;Q&&(b.Authorization=`Bearer ${Q}`);let N;o!==void 0&&(typeof FormData<"u"&&o instanceof FormData?N=o:(e!=="GET"&&(b["Content-Type"]="application/json;charset=UTF-8"),N=JSON.stringify(o))),i instanceof Headers?i.forEach((f,g)=>{b[g]=f;}):Array.isArray(i)?i.forEach(([f,g])=>{b[f]=g;}):Object.assign(b,i),this.logger.logRequest(e,p,b,N);let W;for(let f=0;f<=T;f++){if(f>0){let l=this.computeRetryDelay(f);if(this.logger.warn(`Retry ${f}/${T} for ${e} ${p} in ${l}ms`),a?.aborted)throw a.reason;await new Promise((u,J)=>{let y=()=>{clearTimeout(ne),J(a.reason);},ne=setTimeout(()=>{a&&a.removeEventListener("abort",y),u();},l);a&&a.addEventListener("abort",y,{once:true});});}let g,m;if((this.timeout>0||a)&&(g=new AbortController,this.timeout>0&&(m=setTimeout(()=>g.abort(),this.timeout)),a))if(a.aborted)g.abort(a.reason);else {let l=()=>g.abort(a.reason);a.addEventListener("abort",l,{once:true}),g.signal.addEventListener("abort",()=>{a.removeEventListener("abort",l);},{once:true});}try{let l=await this.fetch(p,{method:e,headers:b,body:N,...d,...g?{signal:g.signal}:{}});if(this.isRetryableStatus(l.status)&&f<T){m!==void 0&&clearTimeout(m),await l.body?.cancel(),W=new c(`Server error: ${l.status} ${l.statusText}`,l.status,"SERVER_ERROR");continue}if(l.status===204){m!==void 0&&clearTimeout(m);return}let u,J=l.headers.get("content-type");try{J?.includes("json")?u=await l.json():u=await l.text();}catch(y){throw m!==void 0&&clearTimeout(m),new c(`Failed to parse response body: ${y?.message||"Unknown error"}`,l.status,l.ok?"PARSE_ERROR":"REQUEST_FAILED")}if(m!==void 0&&clearTimeout(m),!l.ok){if(this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"error"in u&&u.error!==null&&typeof u.error=="object"){let y=u.error;throw new c(y.message||l.statusText||"Request failed",y.statusCode||l.status,y.code||y.error||"REQUEST_FAILED",y.nextActions)}throw new c(`Request failed: ${l.statusText}`,l.status,"REQUEST_FAILED")}return this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"data"in u&&"error"in u&&u.error===null?u.data:u}catch(l){if(m!==void 0&&clearTimeout(m),l?.name==="AbortError")throw g&&g.signal.aborted&&this.timeout>0&&!a?.aborted?new c(`Request timed out after ${this.timeout}ms`,408,"REQUEST_TIMEOUT"):l;if(l instanceof c)throw l;if(f<T){W=l;continue}throw new c(`Network request failed: ${l?.message||"Unknown error"}`,0,"NETWORK_ERROR")}}throw W||new c("Request failed after all retry attempts",0,"NETWORK_ERROR")}async request(e,t,s={}){try{return await this.handleRequest(e,t,{...s})}catch(n){if(n instanceof c&&n.statusCode===401&&this.autoRefreshToken&&this.refreshToken&&!t.includes("/api/auth/refresh"))try{let i=await this.handleTokenRefresh();this.setAuthToken(i.accessToken),i.refreshToken&&this.setRefreshToken(i.refreshToken),i.csrfToken&&L(i.csrfToken);let o=i.user??this.tokenManager.getUser();return o&&this.tokenManager.saveSession({accessToken:i.accessToken,refreshToken:i.refreshToken,user:o}),await this.handleRequest(e,t,{...s})}catch(i){throw this.tokenManager.clearSession(),this.userToken=null,this.refreshToken=null,j(),i}throw n}}async rawFetch(e,t={}){let s=this.buildUrl(e),n=new Headers(t.headers??{});for(let[i,o]of Object.entries(this.defaultHeaders))n.has(i)||n.set(i,o);if(!n.has("Authorization")){let i=this.userToken??this.anonKey;i&&n.set("Authorization",`Bearer ${i}`);}return this.fetch(s,{...t,headers:n})}get(e,t){return this.request("GET",e,t)}post(e,t,s){return this.request("POST",e,{...s,body:t})}put(e,t,s){return this.request("PUT",e,{...s,body:t})}patch(e,t,s){return this.request("PATCH",e,{...s,body:t})}delete(e,t){return this.request("DELETE",e,t)}setAuthToken(e){this.userToken=e;}setRefreshToken(e){this.refreshToken=e;}getHeaders(){let e={...this.defaultHeaders},t=this.userToken||this.anonKey;return t&&(e.Authorization=`Bearer ${t}`),e}async handleTokenRefresh(){return this.isRefreshing?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let e=ee(),t=this.refreshToken?{refreshToken:this.refreshToken}:void 0,s=await this.handleRequest("POST","/api/auth/refresh",{body:t,headers:e?{"X-CSRF-Token":e}:{},credentials:"include"});return A(s)}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}};function w(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,500,"AUTH_ERROR")}}var U=class{constructor(e,t){this.http=e;this.tokenManager=t;this.tokenManager.onTokenChange=()=>this._emitFromTokenChange();let s=this.tokenManager.getSession();if(s){this.http.setAuthToken(s.accessToken);let n=this.tokenManager.getRefreshToken();n&&this.http.setRefreshToken(n),this.lastEmittedUserId=s.user.id,this.lastEmittedAccessToken=s.accessToken;}}http;tokenManager;stateChangeListeners=new Set;lastEmittedUserId=null;lastEmittedAccessToken=null;onAuthStateChange(e){return this.stateChangeListeners.add(e),{unsubscribe:()=>{this.stateChangeListeners.delete(e);}}}emit(e,t){for(let s of this.stateChangeListeners)try{s(e,t);}catch{}}_emitFromTokenChange(){let e=this.tokenManager.getSession();e?(this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null)):(this.http.setAuthToken(null),this.http.setRefreshToken(null));let t=this.lastEmittedUserId,s=this.lastEmittedAccessToken;if(!e){t!==null&&(this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null));return}let n=e.user.id;if(t===null){this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}if(t!==n){this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null),this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}s!==e.accessToken&&(this.lastEmittedAccessToken=e.accessToken,this.emit("TOKEN_REFRESHED",e));}saveSessionFromResponse(e){let t={accessToken:e.accessToken,refreshToken:e.refreshToken,user:e.user};e.csrfToken&&L(e.csrfToken),this.tokenManager.saveSession(t),this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null);}async signUp(e){try{let t=await this.http.post("/api/auth/register",e,{credentials:"include"}),s=A(t);return s?.accessToken&&s.user&&this.saveSessionFromResponse(s),{data:s,error:null}}catch(t){return w(t,"Sign up failed")}}async signInWithPassword(e){try{let t=await this.http.post("/api/auth/login",e,{credentials:"include"}),s=A(t);return s?.accessToken&&s.user&&this.saveSessionFromResponse(s),{data:s,error:null}}catch(t){return w(t,"Sign in failed")}}async signOut(){try{try{await this.http.post("/api/auth/logout",void 0,{credentials:"include"});}catch{}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),j(),{error:null}}catch{return {error:new c("Failed to sign out",500,"SIGNOUT_ERROR")}}}async refreshSession(){try{let e=await this.http.handleTokenRefresh();if(e?.accessToken){let t=e.user??this.tokenManager.getUser();if(t){let s={...e,user:t};return this.saveSessionFromResponse(s),{data:s,error:null}}}return {data:e,error:null}}catch(e){return w(e,"Session refresh failed")}}async initialize(){let e=this.tokenManager.getSession();if(!e)return this.emit("INITIAL_SESSION",null),{data:null,error:new c("No persisted session",0,"NO_SESSION")};try{let t=await this.http.get("/api/auth/sessions/current");if(t?.user){this.tokenManager.setUser(t.user);let s=this.tokenManager.getSession();return this.emit("INITIAL_SESSION",s),{data:{user:t.user,accessToken:e.accessToken},error:null}}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),{data:null,error:new c("Invalid session",401,"INVALID_SESSION")}}catch(t){return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),w(t,"Session restore failed")}}getSession(){return this.tokenManager.getSession()}getUser(){return this.tokenManager.getUser()}async getCurrentUser(){try{let e=await this.http.get("/api/auth/sessions/current");if(e?.user){let t={accessToken:this.tokenManager.getSession()?.accessToken??"",user:e.user};this.tokenManager.saveSession(t);}return {data:e,error:null}}catch(e){return w(e,"Failed to get current user")}}async getProfile(e){try{return {data:await this.http.get(`/api/auth/profiles/${encodeURIComponent(e)}`),error:null}}catch(t){return w(t,"Failed to get profile")}}async setProfile(e){try{let t=await this.http.patch("/api/auth/profiles/current",{profile:e}),s=this.tokenManager.getUser();if(t?.profile&&s){let n={...s,profile:t.profile};this.tokenManager.setUser(n),this.emit("USER_UPDATED",this.tokenManager.getSession());}return {data:t,error:null}}catch(t){return w(t,"Failed to update profile")}}};function he(r,e,t){return async(s,n)=>{let i=typeof s=="string"?s:s.toString(),o=new URL(i),a=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,d=a.match(/^rpc\/(.+)$/),p=d?`/api/database/rpc/${d[1]}`:`/api/database/records/${a}`,v=`${r.baseUrl}${p}${o.search}`,F=new Headers(n?.headers);if(!F.has("Authorization")){let T=e.getAccessToken()??t;T&&F.set("Authorization",`Bearer ${T}`);}return fetch(v,{...n,headers:F})}}var O=class{postgrest;httpClient;constructor(e,t,s){this.httpClient=e,this.postgrest=new PostgrestClient("http://dummy",{fetch:he(e,t,s),headers:{}});}from(e){if(!e||typeof e!="string")throw new c("Database.from(table) requires a non-empty string",400,"INVALID_TABLE_NAME");return this.postgrest.from(e)}rpc(e,t,s){return this.postgrest.rpc(e,t,s)}getUrl(){return this.httpClient.baseUrl}};var pe=2e4;function V(r,e){let t=new Error(e);return t.code=r,t}var fe=1e4,$=class{constructor(e,t,s={}){this.topic=e;this.realtime=t;this.options=s;}topic;realtime;bindings=[];state="closed";statusCallback=null;presence={};trackedState=null;presenceHeartbeat=null;lastBroadcastTimestamp=null;options;get isPrivate(){return this.options.config?.private===true}get presenceKey(){return this.options.config?.presence?.key}_state(){return this.state}async _rejoinAfterReconnect(){if(this.state!=="closed"){for(let e of this.bindings)e.type==="postgres_changes"&&(e.subscriptionId=void 0);this.state="joining";try{if(await this.registerAllBindings(),this.trackedState){let e=this.realtime._getSocket(),t=this.presenceKey;e?.emit("realtime:presence:track",t!==void 0?{channel:this.topic,state:this.trackedState,key:t}:{channel:this.topic,state:this.trackedState});}this.lastBroadcastTimestamp&&this.bindings.some(e=>e.type==="broadcast")&&this.replay({since:this.lastBroadcastTimestamp}).catch(()=>{}),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(e){this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("REJOIN_FAILED",e instanceof Error?e.message:String(e)));}}}on(e,t,s){return e==="postgres_changes"?this.bindings.push({type:"postgres_changes",filter:t,callback:s}):e==="broadcast"?this.bindings.push({type:"broadcast",filter:t,callback:s}):this.bindings.push({type:"presence",filter:t,callback:s}),this}async track(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");this.trackedState=e;let s=this.presenceKey;t.emit("realtime:presence:track",s!==void 0?{channel:this.topic,state:e,key:s}:{channel:this.topic,state:e}),this.presenceHeartbeat||(this.presenceHeartbeat=setInterval(()=>{let i=this.realtime._getSocket();i&&this.trackedState&&i.emit("realtime:presence:track",s!==void 0?{channel:this.topic,state:this.trackedState,key:s}:{channel:this.topic,state:this.trackedState});},pe),this.presenceHeartbeat.unref?.());}untrack(){this.trackedState=null,this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),this.realtime._getSocket()?.emit("realtime:presence:untrack",{channel:this.topic});}presenceState(){return this.presence}subscribe(e){return this.statusCallback=e??null,this.state==="joining"||this.state==="joined"?this:(this.state="joining",this.realtime.connect().then(async()=>{try{await this.registerAllBindings(),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(t){this.state="errored";let s=t instanceof Error?t.message:String(t);this.statusCallback?.("CHANNEL_ERROR",V("SUBSCRIBE_FAILED",s));}},t=>{this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("CONNECT_FAILED",t.message));}),this)}async unsubscribe(){if(this.state==="closed")return;let e=this.realtime._getSocket();if(this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),!e){this.trackedState=null,this.state="closed";return}this.trackedState&&(e.emit("realtime:presence:untrack",{channel:this.topic}),this.trackedState=null);let t=this.bindings.filter(s=>s.type==="postgres_changes");for(let s of t)s.subscriptionId&&(e.emit("realtime:postgres_changes:unsubscribe",{subscription_id:s.subscriptionId}),s.subscriptionId=void 0);this.bindings.some(s=>s.type==="broadcast"||s.type==="presence")&&e.emit("realtime:unsubscribe",{channel:this.topic}),this.realtime._detachChannel(this),this.state="closed",this.statusCallback?.("CLOSED");}async send(e){if(e.type!=="broadcast")throw new c('Only "broadcast" sends are supported \u2014 DB changes flow via your DB writes, not channel.send()',400,"UNSUPPORTED_SEND_TYPE");if(new Set(["postgres_changes","presence_state","presence_join","presence_leave"]).has(e.event))throw new c(`"${e.event}" is a reserved event name \u2014 pick a different name for broadcast events`,400,"RESERVED_EVENT_NAME");let s=this.realtime._getSocket();if(!s)throw new c("Socket not connected",503,"NOT_CONNECTED");let n=this.options.config?.broadcast?.self,i={channel:this.topic,event:e.event,payload:e.payload};return n===false&&(i.self=false),await new Promise(o=>{s.emit("realtime:publish",i,a=>{o(a);});})}async replay(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");t.emit("realtime:broadcast:replay",{channel:this.topic,since:e.since,limit:e.limit,private:this.isPrivate});}_dispatch(e,t){if(e==="postgres_changes"){let n=t;for(let i of this.bindings)if(!(i.type!=="postgres_changes"||!i.subscriptionId||!n.ids.includes(i.subscriptionId)||!(i.filter.event==="*"||i.filter.event===n.data.eventType)))try{i.callback(n.data);}catch{}return}if(e==="presence_state"||e==="presence_join"||e==="presence_leave"){let n=t;if(n.channel!==this.topic)return;if(e==="presence_state"&&n.state)this.presence={...n.state},this.firePresence({event:"sync",state:this.presence});else if(e==="presence_join"&&n.joins)Object.assign(this.presence,n.joins),this.firePresence({event:"join",joins:n.joins});else if(e==="presence_leave"&&n.leaves){for(let i of Object.keys(n.leaves))delete this.presence[i];this.firePresence({event:"leave",leaves:n.leaves});}return}let s=t.meta;s?.timestamp&&(!this.lastBroadcastTimestamp||s.timestamp>this.lastBroadcastTimestamp)&&(this.lastBroadcastTimestamp=s.timestamp);for(let n of this.bindings){if(n.type!=="broadcast"||n.filter.event!==e)continue;let{meta:i,...o}=t;try{n.callback({type:"broadcast",event:e,payload:o});}catch{}}}firePresence(e){for(let t of this.bindings)if(t.type==="presence"&&t.filter.event===e.event)try{e.event==="sync"?t.callback():(e.event,t.callback(e));}catch{}}async registerAllBindings(){let e=this.realtime._getSocket();if(!e)throw new Error("Socket not available");this.bindings.some(n=>n.type==="broadcast"||n.type==="presence")&&await new Promise((n,i)=>{e.emit("realtime:subscribe",{channel:this.topic,private:this.isPrivate},o=>{o.status==="ok"?n():i(new Error(o.error?.message??"subscribe failed"));});});let s=this.bindings.filter(n=>n.type==="postgres_changes");await Promise.all(s.map(n=>new Promise((i,o)=>{e.emit("realtime:postgres_changes:subscribe",{event:n.filter.event,schema:n.filter.schema??"public",table:n.filter.table,filter:n.filter.filter},a=>{a.status==="ok"&&a.subscription_id?(n.subscriptionId=a.subscription_id,i()):o(new Error(a.error?.message??"postgres_changes subscribe failed"));});})));}},B=class{socket=null;baseUrl;options;anonKey;tokenManager;channels=new Map;connecting=null;firstConnected=false;constructor(e,t,s,n={}){this.baseUrl=e,this.tokenManager=t,this.anonKey=s,this.options=n;}get isConnected(){return this.socket?.connected===true}get socketId(){return this.socket?.id}channel(e,t){let s=this.channels.get(e);if(s)return s;let n=new $(e,this,t);return this.channels.set(e,n),n}connect(){return this.isConnected?Promise.resolve():this.connecting?this.connecting:(this.connecting=this.openSocket(),this.connecting)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.firstConnected=false);}_getSocket(){return this.socket}_detachChannel(e){this.channels.delete(e.topic);}openSocket(){let e=this.tokenManager.getAccessToken()??this.anonKey;if(!e){let n=new c("Realtime requires an access token or anonKey",401,"AUTH_INVALID_API_KEY");return this.connecting=null,Promise.reject(n)}let t=this.options.timeoutMs??fe,s=io(this.baseUrl,{path:this.options.path,transports:this.options.transports??["websocket"],auth:{token:e,...this.options.extraAuth??{}},reconnection:true,timeout:t});return this.socket=s,s.onAny((n,...i)=>this.dispatch(n,i)),s.on("connect",()=>{if(this.firstConnected)for(let n of this.channels.values()){let i=n._state();(i==="joined"||i==="errored")&&n._rejoinAfterReconnect();}}),new Promise((n,i)=>{let o=setTimeout(()=>{s.off("connect",d),s.off("connect_error",p),this.connecting=null,i(new c(`Realtime connection timeout after ${t}ms`,408,"CONNECTION_TIMEOUT"));},t),a=()=>{clearTimeout(o),s.off("connect",d),s.off("connect_error",p);},d=()=>{a(),this.connecting=null,this.firstConnected=true,n();},p=v=>{a(),this.connecting=null,i(new c(v.message,0,"CONNECTION_FAILED"));};s.once("connect",d),s.once("connect_error",p);})}dispatch(e,t){if(e==="postgres_changes"){let n=t[0]??{};this.channels.forEach(i=>i._dispatch("postgres_changes",n));return}if(e==="connect"||e==="disconnect"||e==="connect_error"||e==="error"||e==="realtime:error"||e==="realtime:shutdown")return;let s=t[0]??{};this.channels.forEach(n=>n._dispatch(e,s));}};function H(r){return {id:r.id,name:r.name,public:r.public,fileSizeLimitBytes:r.file_size_limit_bytes,allowedMimeTypes:r.allowed_mime_types,createdAt:r.created_at,updatedAt:r.updated_at}}function q(r,e){return {id:r.id,bucket:e,key:r.key,size:r.size,mimeType:r.mime_type,etag:r.etag,cacheControl:r.cache_control,contentDisposition:r.content_disposition,uploadedBy:r.uploaded_by,uploadedAt:r.uploaded_at,updatedAt:r.updated_at}}function me(r){return {defaultFileSizeLimitBytes:r.default_file_size_limit_bytes,maxFileSizeLimitBytes:r.max_file_size_limit_bytes,tenantStorageQuotaBytes:r.tenant_storage_quota_bytes,reservedSpaceBytes:r.reserved_space_bytes,signedUrlDefaultTtlSec:r.signed_url_default_ttl_sec,signedUrlMaxTtlSec:r.signed_url_max_ttl_sec}}function ye(r){return r.split("/").map(encodeURIComponent).join("/")}function h(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"STORAGE_ERROR")}}async function Y(r){let e="STORAGE_ERROR",t=`HTTP ${r.status}`;try{let s=await r.json();s&&s.error&&(e=s.error.code??e,t=s.error.message??t);}catch{}return new c(t,r.status,e)}var K=class{constructor(e,t){this.http=e;this.bucketName=t;}http;bucketName;bucketBase(){return `/api/storage/buckets/${encodeURIComponent(this.bucketName)}`}objectPath(e){return `${this.bucketBase()}/objects/${ye(e)}`}async upload(e,t,s={}){try{let n=s.upsert?"PUT":"POST",i={"Content-Type":s.contentType??"application/octet-stream"};s.cacheControl&&(i["Cache-Control"]=s.cacheControl),s.contentDisposition&&(i["Content-Disposition"]=s.contentDisposition);let o=await this.http.rawFetch(this.objectPath(e),{method:n,headers:i,body:t,signal:s.abortSignal});if(!o.ok)return {data:null,error:await Y(o)};let a=await o.json();return a.error||!a.data?{data:null,error:new c(a.error?.message??"Upload failed",o.status,a.error?.code??"STORAGE_ERROR")}:{data:q(a.data,this.bucketName),error:null}}catch(n){return h(n,"Upload failed")}}async download(e,t={}){try{let s={};t.range&&(s.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:s,signal:t.abortSignal});return n.ok?{data:await n.blob(),error:null}:{data:null,error:await Y(n)}}catch(s){return h(s,"Download failed")}}async getStream(e,t={}){try{let s={};t.range&&(s.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:s,signal:t.abortSignal});return n.ok?n.body?{data:n.body,error:null}:{data:null,error:new c("Response body is not a stream",n.status,"STORAGE_ERROR")}:{data:null,error:await Y(n)}}catch(s){return h(s,"Download failed")}}async remove(e){try{let t=await Promise.allSettled(e.map(i=>this.http.rawFetch(this.objectPath(i),{method:"DELETE"}))),s=[],n=[];for(let i=0;i<e.length;i++){let o=e[i],a=t[i];if(a.status==="fulfilled"&&a.value.ok)s.push(o);else if(a.status==="fulfilled")n.push(`${o}: HTTP ${a.value.status}`);else {let d=a.reason instanceof Error?a.reason.message:String(a.reason);n.push(`${o}: ${d}`);}}return n.length>0?{data:null,error:new c(`Failed to delete some objects: ${n.join("; ")}`,0,"STORAGE_ERROR")}:{data:{removed:s},error:null}}catch(t){return h(t,"Delete failed")}}async list(e={}){try{let t={};return e.prefix!==void 0&&(t.prefix=e.prefix),e.limit!==void 0&&(t.limit=String(e.limit)),e.startAfter!==void 0&&(t.start_after=e.startAfter),{data:(await this.http.get(`${this.bucketBase()}/objects`,{params:t})).map(n=>q(n,this.bucketName)),error:null}}catch(t){return h(t,"List failed")}}async copy(e,t,s){try{let n=await this.http.post(`${this.objectPath(e)}/copy`,{dest_bucket:s??this.bucketName,dest_key:t});return {data:q(n,s??this.bucketName),error:null}}catch(n){return h(n,"Copy failed")}}async move(e,t,s){try{let n=await this.http.post(`${this.objectPath(e)}/move`,{dest_bucket:s??this.bucketName,dest_key:t});return {data:q(n,s??this.bucketName),error:null}}catch(n){return h(n,"Move failed")}}async createSignedUrl(e,t={}){try{let s={};t.expiresIn!==void 0&&(s.expires_in=t.expiresIn);let n=await this.http.post(`${this.objectPath(e)}/sign`,s);return {data:{url:n.url,token:n.token,expiresAt:n.expiresAt},error:null}}catch(s){return h(s,"Sign failed")}}getPublicUrl(e){return {data:{url:`${this.http.baseUrl.replace(/\/$/,"")}${this.objectPath(e)}`}}}},x=class{constructor(e){this.http=e;}http;from(e){return new K(this.http,e)}async listBuckets(){try{return {data:(await this.http.get("/api/storage/buckets")).map(H),error:null}}catch(e){return h(e,"listBuckets failed")}}async getBucket(e){try{let t=await this.http.get(`/api/storage/buckets/${encodeURIComponent(e)}`);return {data:H(t),error:null}}catch(t){return h(t,"getBucket failed")}}async createBucket(e,t={}){try{let s={name:e};t.public!==void 0&&(s.public=t.public),t.fileSizeLimitBytes!==void 0&&(s.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(s.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.post("/api/storage/buckets",s);return {data:H(n),error:null}}catch(s){return h(s,"createBucket failed")}}async updateBucket(e,t){try{let s={};t.public!==void 0&&(s.public=t.public),t.fileSizeLimitBytes!==void 0&&(s.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(s.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.patch(`/api/storage/buckets/${encodeURIComponent(e)}`,s);return {data:H(n),error:null}}catch(s){return h(s,"updateBucket failed")}}async deleteBucket(e){try{return await this.http.delete(`/api/storage/buckets/${encodeURIComponent(e)}`),{data:null,error:null}}catch(t){return h(t,"deleteBucket failed")}}async emptyBucket(e){try{return {data:await this.http.post(`/api/storage/buckets/${encodeURIComponent(e)}/empty`,{}),error:null}}catch(t){return h(t,"emptyBucket failed")}}async getConfig(){try{let e=await this.http.get("/api/storage/config");return {data:me(e),error:null}}catch(e){return h(e,"getConfig failed")}}};function ke(r){return {key:r.key,digest:r.digest,updatedAt:r.updated_at}}function k(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"FUNCTIONS_ERROR")}}function Te(r){return typeof r=="object"&&r!==null&&!ArrayBuffer.isView(r)&&!(r instanceof Blob)&&!(r instanceof FormData)&&!(r instanceof URLSearchParams)&&!(r instanceof ReadableStream)}var M=class{constructor(e){this.http=e;}http;async list(){try{return {data:await this.http.get("/api/functions"),error:null}}catch(e){return k(e,"list failed")}}async get(e){try{return {data:await this.http.get(`/api/functions/${encodeURIComponent(e)}`),error:null}}catch(t){return k(t,"get failed")}}async create(e){try{return {data:await this.http.post("/api/functions",e),error:null}}catch(t){return k(t,"create failed")}}async update(e,t){try{return {data:await this.http.put(`/api/functions/${encodeURIComponent(e)}`,t),error:null}}catch(s){return k(s,"update failed")}}async remove(e){try{return await this.http.delete(`/api/functions/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return k(t,"remove failed")}}async invoke(e,t={}){try{let s=t.method??"POST",n={...t.headers},i;return t.body!==void 0&&t.body!==null&&(Te(t.body)?(i=JSON.stringify(t.body),n["Content-Type"]||(n["Content-Type"]="application/json")):i=t.body),{data:await this.http.rawFetch(`/api/invoke/${encodeURIComponent(e)}`,{method:s,headers:n,body:i}),error:null}}catch(s){return k(s,"invoke failed")}}async listSecrets(){try{return {data:(await this.http.get("/api/functions/secrets")).secrets.map(ke),error:null}}catch(e){return k(e,"listSecrets failed")}}async setSecrets(e){try{return await this.http.put("/api/functions/secrets",{secrets:e}),{data:{saved:!0},error:null}}catch(t){return k(t,"setSecrets failed")}}async deleteSecret(e){try{return await this.http.delete(`/api/functions/secrets/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return k(t,"deleteSecret failed")}}};var C=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function te(r){let e=typeof r=="number"&&Number.isFinite(r)?r:50;return Math.max(1,Math.min(200,Math.trunc(e)))}function be(r){let e=typeof r=="number"&&Number.isFinite(r)?r:100;return Math.max(1,Math.min(500,Math.trunc(e)))}function z(){return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")}}function se(){return {data:null,error:new c("sessionId must be a valid UUID",400,"INVALID_INPUT")}}function E(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"AGENTS_ERROR")}}var D=class{constructor(e){this.http=e;}http;async list(e){try{let t=te(e?.limit);return {data:await this.http.get(`/api/agents?limit=${t}`),error:null}}catch(t){return E(t,"list failed")}}async invoke(e,t){if(typeof e!="string"||!C.test(e))return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")};try{let s=t!==void 0?{input:t}:void 0;return {data:await this.http.post(`/api/agents/${encodeURIComponent(e)}/invoke`,s),error:null}}catch(s){return E(s,"invoke failed")}}async chat(e,t,s){if(typeof e!="string"||!C.test(e))return z();try{let n={message:t};s?.sessionId!==void 0&&(n.session_id=s.sessionId),s?.extraContext!==void 0&&(n.extra_context=s.extraContext);let i=await this.http.post(`/api/agents/${encodeURIComponent(e)}/chat`,n);return {data:{sessionId:i.session_id,runId:i.runId,status:i.status,output:i.output,text:i.text,totalTokens:i.totalTokens,totalCost:i.totalCost,error:i.error},error:null}}catch(n){return E(n,"chat failed")}}async listSessions(e,t){if(typeof e!="string"||!C.test(e))return z();try{let s=te(t?.limit);return {data:{sessions:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions?limit=${s}`)).sessions??[]).map(o=>({id:o.id,createdAt:o.created_at,lastActivityAt:o.last_activity_at,messageCount:o.message_count,lastMessagePreview:o.last_message_preview??null}))},error:null}}catch(s){return E(s,"listSessions failed")}}async getMessages(e,t,s){if(typeof e!="string"||!C.test(e))return z();if(typeof t!="string"||!C.test(t))return se();try{let n=be(s?.limit),i=new URLSearchParams;return i.set("limit",String(n)),s?.before!==void 0&&i.set("before",s.before),{data:{messages:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/messages?${i.toString()}`)).messages??[]).map(d=>({id:d.id,role:d.role,content:d.content,createdAt:d.created_at}))},error:null}}catch(n){return E(n,"getMessages failed")}}async deleteSession(e,t){if(typeof e!="string"||!C.test(e))return z();if(typeof t!="string"||!C.test(t))return se();try{return await this.http.delete(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}`),{data:{ok:!0},error:null}}catch(s){return E(s,"deleteSession failed")}}};var _=class{http;tokenManager;auth;database;realtime;storage;functions;agents;constructor(e={}){let t=new R(e.debug);this.tokenManager=new S({persistSession:e.persistSession,storageKey:e.storageKey,storage:e.storage,multiTab:e.multiTab}),this.http=new I(e,this.tokenManager,t),this.auth=new U(this.http,this.tokenManager),this.database=new O(this.http,this.tokenManager,e.anonKey),this.realtime=new B(this.http.baseUrl,this.tokenManager,e.anonKey,e.realtime),this.storage=new x(this.http),this.functions=new M(this.http),this.agents=new D(this.http);}getHttpClient(){return this.http}};function at(r){return new _(r)}var ct=_;
5
+ export{D as AgentsModule,U as Auth,O as Database,M as Functions,I as HttpClient,R as Logger,_ as MitwayBaasClient,c as MitwayBaasError,B as Realtime,$ as RealtimeChannel,x as Storage,K as StorageBucketClient,S as TokenManager,at as createClient,Z as createLocalStorageAdapter,ct as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitway/sdk",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "TypeScript/JavaScript client for MITWAY-BaaS — auth + database for end-user apps",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -18,6 +18,14 @@
18
18
  "LICENSE"
19
19
  ],
20
20
  "type": "module",
21
+ "scripts": {
22
+ "build": "tsup",
23
+ "dev": "tsup --watch",
24
+ "test": "vitest run --passWithNoTests",
25
+ "test:watch": "vitest",
26
+ "typecheck": "tsc --noEmit",
27
+ "prepublishOnly": "pnpm build"
28
+ },
21
29
  "keywords": [
22
30
  "mitway",
23
31
  "mitway-baas",
@@ -53,12 +61,5 @@
53
61
  },
54
62
  "publishConfig": {
55
63
  "access": "public"
56
- },
57
- "scripts": {
58
- "build": "tsup",
59
- "dev": "tsup --watch",
60
- "test": "vitest run --passWithNoTests",
61
- "test:watch": "vitest",
62
- "typecheck": "tsc --noEmit"
63
64
  }
64
- }
65
+ }