learn-auth-sdk 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  if(typeof process==="undefined"){globalThis.process={env:{NODE_ENV:"production"}}};
2
- "use strict";var AuthSDK=(()=>{var Z=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Je=Object.prototype.hasOwnProperty;var Qe=(e,t)=>{for(var r in t)Z(e,r,{get:t[r],enumerable:!0})},Ke=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ze(t))!Je.call(e,o)&&o!==r&&Z(e,o,{get:()=>t[o],enumerable:!(n=$e(t,o))||n.enumerable});return e};var Xe=e=>Ke(Z({},"__esModule",{value:!0}),e);var Kt={};Qe(Kt,{AuthSDK:()=>Q});var he="1.6.9";var me=he;var ee=Symbol.for("better-auth:broadcast-channel"),Ze=()=>Math.floor(Date.now()/1e3),et=class{listeners=new Set;name;constructor(e="better-auth.message"){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(!(typeof window>"u"))try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:Ze()}))}catch{}}setup(){if(typeof window>"u"||typeof window.addEventListener>"u")return()=>{};let e=t=>{if(t.key!==this.name)return;let r=JSON.parse(t.newValue??"{}");r?.event!=="session"||!r?.data||this.listeners.forEach(n=>n(r))};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};function q(e="better-auth.message"){return globalThis[ee]||(globalThis[ee]=new et(e)),globalThis[ee]}var te=Symbol.for("better-auth:focus-manager"),tt=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>"u"||typeof document>"u"||typeof window.addEventListener>"u")return()=>{};let e=()=>{document.visibilityState==="visible"&&this.setFocused(!0)};return document.addEventListener("visibilitychange",e,!1),()=>{document.removeEventListener("visibilitychange",e,!1)}}};function re(){return globalThis[te]||(globalThis[te]=new tt),globalThis[te]}var ne=Symbol.for("better-auth:online-manager"),rt=class{listeners=new Set;isOnline=typeof navigator<"u"?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>"u"||typeof window.addEventListener>"u")return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener("online",e,!1),window.addEventListener("offline",t,!1),()=>{window.removeEventListener("online",e,!1),window.removeEventListener("offline",t,!1)}}};function W(){return globalThis[ne]||(globalThis[ne]=new rt),globalThis[ne]}var nt={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},ot=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Ee={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},st=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function it(e){return e instanceof Date&&!isNaN(e.getTime())}function at(e){let t=st.exec(e);if(!t)return null;let[,r,n,o,s,i,c,a,u,l,d]=t,p=new Date(Date.UTC(parseInt(r,10),parseInt(n,10)-1,parseInt(o,10),parseInt(s,10),parseInt(i,10),parseInt(c,10),a?parseInt(a.padEnd(3,"0"),10):0));if(u){let E=(parseInt(l,10)*60+parseInt(d,10))*(u==="+"?-1:1);p.setUTCMinutes(p.getUTCMinutes()+E)}return it(p)?p:null}function lt(e,t={}){let{strict:r=!1,warnings:n=!1,reviver:o,parseDates:s=!0}=t;if(typeof e!="string")return e;let i=e.trim();if(i.length>0&&i[0]==='"'&&i.endsWith('"')&&!i.slice(1,-1).includes('"'))return i.slice(1,-1);let c=i.toLowerCase();if(c.length<=9&&c in Ee)return Ee[c];if(!ot.test(i)){if(r)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(nt).some(([a,u])=>{let l=u.test(i);return l&&n&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${a} pattern`),l})&&r)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(i,(u,l)=>{if(u==="__proto__"||u==="constructor"&&l&&typeof l=="object"&&"prototype"in l){n&&console.warn(`[better-json] Dropping "${u}" key to prevent prototype pollution`);return}if(s&&typeof l=="string"){let d=at(l);if(d)return d}return o?o(u,l):l})}catch(a){if(r)throw a;return e}}function _e(e,t={strict:!0}){return lt(e,t)}var F=Symbol("clean");var v=[],I=0,V=4,ut=globalThis.nanostoresGlobal||={epoch:0},B=e=>{let t=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},init:e,lc:0,listen(n){return r.lc=t.push(n),()=>{for(let s=I+V;s<v.length;)v[s]===n?v.splice(s,V):s+=V;let o=t.indexOf(n);~o&&(t.splice(o,1),--r.lc||r.off())}},notify(n,o){ut.epoch++;let s=!v.length;for(let i of t)v.push(i,r.value,n,o);if(s){for(I=0;I<v.length;I+=V)v[I](v[I+1],v[I+2],v[I+3]);v.length=0}},off(){},set(n){let o=r.value;o!==n&&(r.value=n,r.notify(o))},subscribe(n){let o=r.listen(n);return n(r.value),o},value:e};return process.env.NODE_ENV!=="production"&&(r[F]=()=>{t=[],r.lc=0,r.off()}),r};var ct=5,k=6,G=10,ft=(e,t,r,n)=>(e.events=e.events||{},e.events[r+G]||(e.events[r+G]=n(o=>{e.events[r].reduceRight((s,i)=>(i(s),s),{shared:{},...o})})),e.events[r]=e.events[r]||[],e.events[r].push(t),()=>{let o=e.events[r],s=o.indexOf(t);o.splice(s,1),o.length||(delete e.events[r],e.events[r+G](),delete e.events[r+G])});var Re=1e3,Y=(e,t)=>ft(e,n=>{let o=t(n);o&&e.events[k].push(o)},ct,n=>{let o=e.listen;e.listen=(...i)=>(!e.lc&&!e.active&&(e.active=!0,n()),o(...i));let s=e.off;if(e.events[k]=[],e.off=()=>{s(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let i of e.events[k])i();e.events[k]=[]}},Re)},process.env.NODE_ENV!=="production"){let i=e[F];e[F]=()=>{for(let c of e.events[k])c();e.events[k]=[],e.active=!1,i()}}return()=>{e.listen=o,e.off=s}});var dt=()=>typeof window>"u",ye=(e,t,r,n)=>{let o=B({data:null,error:null,isPending:!0,isRefetching:!1,refetch:c=>s(c)}),s=async c=>new Promise(a=>{let u=typeof n=="function"?n({data:o.get().data,error:o.get().error,isPending:o.get().isPending}):n;r(t,{...u,query:{...u?.query,...c?.query},async onSuccess(l){o.set({data:l.data,error:null,isPending:!1,isRefetching:!1,refetch:o.value.refetch}),await u?.onSuccess?.(l)},async onError(l){let{request:d}=l,p=typeof d.retry=="number"?d.retry:d.retry?.attempts,E=d.retryAttempt||0;if(p&&E<p)return;let y=l.error.status===401;o.set({error:l.error,data:y?null:o.get().data,isPending:!1,isRefetching:!1,refetch:o.value.refetch}),await u?.onError?.(l)},async onRequest(l){let d=o.get();o.set({isPending:d.data===null,data:d.data,error:null,isRefetching:!0,refetch:o.value.refetch}),await u?.onRequest?.(l)}}).catch(l=>{o.set({error:l,data:o.get().data,isPending:!1,isRefetching:!1,refetch:o.value.refetch})}).finally(()=>{a(void 0)})});e=Array.isArray(e)?e:[e];let i=!1;for(let c of e)c.subscribe(async()=>{dt()||(i?await s():Y(o,()=>{let a=setTimeout(async()=>{i||(i=!0,await s())},0);return()=>{o.off(),c.off(),clearTimeout(a)}}))});return o};var M=()=>Math.floor(Date.now()/1e3);function ge(e){return typeof e=="object"&&e!==null&&"data"in e&&"error"in e?e:{data:e,error:null}}var pt=5;function Oe(e){let{sessionAtom:t,sessionSignal:r,$fetch:n,options:o={}}=e,s=o.sessionOptions?.refetchInterval??0,i=o.sessionOptions?.refetchOnWindowFocus??!0,c=o.sessionOptions?.refetchWhenOffline??!1,a={lastSync:0,lastSessionRequest:0,cachedSession:void 0},u=()=>c||W().isOnline,l=_=>{if(!u())return;if(_?.event==="storage"){a.lastSync=M(),r.set(!r.get());return}let g=t.get(),m=()=>{a.lastSessionRequest=M(),n("/get-session").then(async f=>{let{data:h,error:D}=ge(f);if(h?.needsRefresh)try{let x=await n("/get-session",{method:"POST"});({data:h,error:D}=ge(x))}catch{}let K=h?.session&&h?.user?h:null;t.set({...g,data:K,error:D}),a.lastSync=M(),r.set(!r.get())}).catch(()=>{})};if(_?.event==="poll"){m();return}if(_?.event==="visibilitychange"){if(M()-a.lastSessionRequest<pt)return;a.lastSessionRequest=M()}if(_?.event==="visibilitychange"){m();return}(g?.data===null||g?.data===void 0)&&(a.lastSync=M(),r.set(!r.get()))},d=_=>{q().post({event:"session",data:{trigger:_},clientId:Math.random().toString(36).substring(7)})},p=()=>{s&&s>0&&(a.pollInterval=setInterval(()=>{t.get()?.data&&l({event:"poll"})},s*1e3))},E=()=>{a.unsubscribeBroadcast=q().subscribe(()=>{l({event:"storage"})})},y=()=>{i&&(a.unsubscribeFocus=re().subscribe(()=>{l({event:"visibilitychange"})}))},N=()=>{a.unsubscribeOnline=W().subscribe(_=>{_&&l({event:"visibilitychange"})})};return{init:()=>{p(),E(),y(),N(),q().setup(),re().setup(),W().setup()},cleanup:()=>{a.pollInterval&&(clearInterval(a.pollInterval),a.pollInterval=void 0),a.unsubscribeBroadcast&&(a.unsubscribeBroadcast(),a.unsubscribeBroadcast=void 0),a.unsubscribeFocus&&(a.unsubscribeFocus(),a.unsubscribeFocus=void 0),a.unsubscribeOnline&&(a.unsubscribeOnline(),a.unsubscribeOnline=void 0),a.lastSync=0,a.lastSessionRequest=0,a.cachedSession=void 0},triggerRefetch:l,broadcastSessionUpdate:d}}var $=Object.create(null),j=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?$:globalThis),L=new Proxy($,{get(e,t){return j()[t]??$[t]},has(e,t){return t in j()||t in $},set(e,t,r){let n=j(!0);return n[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=j(!0);return delete r[t],!0},ownKeys(){let e=j(!0);return Object.keys(e)}});var ht=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";function P(e,t){return typeof process<"u"&&process.env?process.env[e]??t:typeof Deno<"u"?Deno.env.get(e)??t:typeof Bun<"u"?Bun.env[e]??t:t}var mt=Object.freeze({get BETTER_AUTH_SECRET(){return P("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return P("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return P("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return P("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return P("NODE_ENV","development")},get PACKAGE_VERSION(){return P("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return P("BETTER_AUTH_TELEMETRY_ENDPOINT","")}});function Te(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,{code:t,message:r,toString:()=>t}]))}function Et(){let e=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,"writable")?e.writable:e.set!==void 0}function _t(e){let t=e.split(`
2
+ "use strict";var AuthSDK=(()=>{var Z=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Je=Object.prototype.hasOwnProperty;var Qe=(e,t)=>{for(var r in t)Z(e,r,{get:t[r],enumerable:!0})},Ke=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ze(t))!Je.call(e,o)&&o!==r&&Z(e,o,{get:()=>t[o],enumerable:!(n=$e(t,o))||n.enumerable});return e};var Xe=e=>Ke(Z({},"__esModule",{value:!0}),e);var Kt={};Qe(Kt,{AuthSDK:()=>Q});var he="1.6.9";var me=he;var ee=Symbol.for("better-auth:broadcast-channel"),Ze=()=>Math.floor(Date.now()/1e3),et=class{listeners=new Set;name;constructor(e="better-auth.message"){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(!(typeof window>"u"))try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:Ze()}))}catch{}}setup(){if(typeof window>"u"||typeof window.addEventListener>"u")return()=>{};let e=t=>{if(t.key!==this.name)return;let r=JSON.parse(t.newValue??"{}");r?.event!=="session"||!r?.data||this.listeners.forEach(n=>n(r))};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};function q(e="better-auth.message"){return globalThis[ee]||(globalThis[ee]=new et(e)),globalThis[ee]}var te=Symbol.for("better-auth:focus-manager"),tt=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>"u"||typeof document>"u"||typeof window.addEventListener>"u")return()=>{};let e=()=>{document.visibilityState==="visible"&&this.setFocused(!0)};return document.addEventListener("visibilitychange",e,!1),()=>{document.removeEventListener("visibilitychange",e,!1)}}};function re(){return globalThis[te]||(globalThis[te]=new tt),globalThis[te]}var ne=Symbol.for("better-auth:online-manager"),rt=class{listeners=new Set;isOnline=typeof navigator<"u"?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>"u"||typeof window.addEventListener>"u")return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener("online",e,!1),window.addEventListener("offline",t,!1),()=>{window.removeEventListener("online",e,!1),window.removeEventListener("offline",t,!1)}}};function W(){return globalThis[ne]||(globalThis[ne]=new rt),globalThis[ne]}var nt={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},ot=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Ee={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},st=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function it(e){return e instanceof Date&&!isNaN(e.getTime())}function at(e){let t=st.exec(e);if(!t)return null;let[,r,n,o,s,i,u,a,c,l,d]=t,p=new Date(Date.UTC(parseInt(r,10),parseInt(n,10)-1,parseInt(o,10),parseInt(s,10),parseInt(i,10),parseInt(u,10),a?parseInt(a.padEnd(3,"0"),10):0));if(c){let E=(parseInt(l,10)*60+parseInt(d,10))*(c==="+"?-1:1);p.setUTCMinutes(p.getUTCMinutes()+E)}return it(p)?p:null}function lt(e,t={}){let{strict:r=!1,warnings:n=!1,reviver:o,parseDates:s=!0}=t;if(typeof e!="string")return e;let i=e.trim();if(i.length>0&&i[0]==='"'&&i.endsWith('"')&&!i.slice(1,-1).includes('"'))return i.slice(1,-1);let u=i.toLowerCase();if(u.length<=9&&u in Ee)return Ee[u];if(!ot.test(i)){if(r)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(nt).some(([a,c])=>{let l=c.test(i);return l&&n&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${a} pattern`),l})&&r)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(i,(c,l)=>{if(c==="__proto__"||c==="constructor"&&l&&typeof l=="object"&&"prototype"in l){n&&console.warn(`[better-json] Dropping "${c}" key to prevent prototype pollution`);return}if(s&&typeof l=="string"){let d=at(l);if(d)return d}return o?o(c,l):l})}catch(a){if(r)throw a;return e}}function _e(e,t={strict:!0}){return lt(e,t)}var F=Symbol("clean");var v=[],I=0,V=4,ct=globalThis.nanostoresGlobal||={epoch:0},B=e=>{let t=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},init:e,lc:0,listen(n){return r.lc=t.push(n),()=>{for(let s=I+V;s<v.length;)v[s]===n?v.splice(s,V):s+=V;let o=t.indexOf(n);~o&&(t.splice(o,1),--r.lc||r.off())}},notify(n,o){ct.epoch++;let s=!v.length;for(let i of t)v.push(i,r.value,n,o);if(s){for(I=0;I<v.length;I+=V)v[I](v[I+1],v[I+2],v[I+3]);v.length=0}},off(){},set(n){let o=r.value;o!==n&&(r.value=n,r.notify(o))},subscribe(n){let o=r.listen(n);return n(r.value),o},value:e};return process.env.NODE_ENV!=="production"&&(r[F]=()=>{t=[],r.lc=0,r.off()}),r};var ut=5,k=6,G=10,ft=(e,t,r,n)=>(e.events=e.events||{},e.events[r+G]||(e.events[r+G]=n(o=>{e.events[r].reduceRight((s,i)=>(i(s),s),{shared:{},...o})})),e.events[r]=e.events[r]||[],e.events[r].push(t),()=>{let o=e.events[r],s=o.indexOf(t);o.splice(s,1),o.length||(delete e.events[r],e.events[r+G](),delete e.events[r+G])});var ge=1e3,Y=(e,t)=>ft(e,n=>{let o=t(n);o&&e.events[k].push(o)},ut,n=>{let o=e.listen;e.listen=(...i)=>(!e.lc&&!e.active&&(e.active=!0,n()),o(...i));let s=e.off;if(e.events[k]=[],e.off=()=>{s(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let i of e.events[k])i();e.events[k]=[]}},ge)},process.env.NODE_ENV!=="production"){let i=e[F];e[F]=()=>{for(let u of e.events[k])u();e.events[k]=[],e.active=!1,i()}}return()=>{e.listen=o,e.off=s}});var dt=()=>typeof window>"u",Re=(e,t,r,n)=>{let o=B({data:null,error:null,isPending:!0,isRefetching:!1,refetch:u=>s(u)}),s=async u=>new Promise(a=>{let c=typeof n=="function"?n({data:o.get().data,error:o.get().error,isPending:o.get().isPending}):n;r(t,{...c,query:{...c?.query,...u?.query},async onSuccess(l){o.set({data:l.data,error:null,isPending:!1,isRefetching:!1,refetch:o.value.refetch}),await c?.onSuccess?.(l)},async onError(l){let{request:d}=l,p=typeof d.retry=="number"?d.retry:d.retry?.attempts,E=d.retryAttempt||0;if(p&&E<p)return;let R=l.error.status===401;o.set({error:l.error,data:R?null:o.get().data,isPending:!1,isRefetching:!1,refetch:o.value.refetch}),await c?.onError?.(l)},async onRequest(l){let d=o.get();o.set({isPending:d.data===null,data:d.data,error:null,isRefetching:!0,refetch:o.value.refetch}),await c?.onRequest?.(l)}}).catch(l=>{o.set({error:l,data:o.get().data,isPending:!1,isRefetching:!1,refetch:o.value.refetch})}).finally(()=>{a(void 0)})});e=Array.isArray(e)?e:[e];let i=!1;for(let u of e)u.subscribe(async()=>{dt()||(i?await s():Y(o,()=>{let a=setTimeout(async()=>{i||(i=!0,await s())},0);return()=>{o.off(),u.off(),clearTimeout(a)}}))});return o};var M=()=>Math.floor(Date.now()/1e3);function ye(e){return typeof e=="object"&&e!==null&&"data"in e&&"error"in e?e:{data:e,error:null}}var pt=5;function Oe(e){let{sessionAtom:t,sessionSignal:r,$fetch:n,options:o={}}=e,s=o.sessionOptions?.refetchInterval??0,i=o.sessionOptions?.refetchOnWindowFocus??!0,u=o.sessionOptions?.refetchWhenOffline??!1,a={lastSync:0,lastSessionRequest:0,cachedSession:void 0},c=()=>u||W().isOnline,l=_=>{if(!c())return;if(_?.event==="storage"){a.lastSync=M(),r.set(!r.get());return}let y=t.get(),m=()=>{a.lastSessionRequest=M(),n("/get-session").then(async f=>{let{data:h,error:D}=ye(f);if(h?.needsRefresh)try{let x=await n("/get-session",{method:"POST"});({data:h,error:D}=ye(x))}catch{}let K=h?.session&&h?.user?h:null;t.set({...y,data:K,error:D}),a.lastSync=M(),r.set(!r.get())}).catch(()=>{})};if(_?.event==="poll"){m();return}if(_?.event==="visibilitychange"){if(M()-a.lastSessionRequest<pt)return;a.lastSessionRequest=M()}if(_?.event==="visibilitychange"){m();return}(y?.data===null||y?.data===void 0)&&(a.lastSync=M(),r.set(!r.get()))},d=_=>{q().post({event:"session",data:{trigger:_},clientId:Math.random().toString(36).substring(7)})},p=()=>{s&&s>0&&(a.pollInterval=setInterval(()=>{t.get()?.data&&l({event:"poll"})},s*1e3))},E=()=>{a.unsubscribeBroadcast=q().subscribe(()=>{l({event:"storage"})})},R=()=>{i&&(a.unsubscribeFocus=re().subscribe(()=>{l({event:"visibilitychange"})}))},N=()=>{a.unsubscribeOnline=W().subscribe(_=>{_&&l({event:"visibilitychange"})})};return{init:()=>{p(),E(),R(),N(),q().setup(),re().setup(),W().setup()},cleanup:()=>{a.pollInterval&&(clearInterval(a.pollInterval),a.pollInterval=void 0),a.unsubscribeBroadcast&&(a.unsubscribeBroadcast(),a.unsubscribeBroadcast=void 0),a.unsubscribeFocus&&(a.unsubscribeFocus(),a.unsubscribeFocus=void 0),a.unsubscribeOnline&&(a.unsubscribeOnline(),a.unsubscribeOnline=void 0),a.lastSync=0,a.lastSessionRequest=0,a.cachedSession=void 0},triggerRefetch:l,broadcastSessionUpdate:d}}var $=Object.create(null),j=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?$:globalThis),L=new Proxy($,{get(e,t){return j()[t]??$[t]},has(e,t){return t in j()||t in $},set(e,t,r){let n=j(!0);return n[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=j(!0);return delete r[t],!0},ownKeys(){let e=j(!0);return Object.keys(e)}});var ht=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";function P(e,t){return typeof process<"u"&&process.env?process.env[e]??t:typeof Deno<"u"?Deno.env.get(e)??t:typeof Bun<"u"?Bun.env[e]??t:t}var mt=Object.freeze({get BETTER_AUTH_SECRET(){return P("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return P("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return P("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return P("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return P("NODE_ENV","development")},get PACKAGE_VERSION(){return P("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return P("BETTER_AUTH_TELEMETRY_ENDPOINT","")}});function Te(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,{code:t,message:r,toString:()=>t}]))}function Et(){let e=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,"writable")?e.writable:e.set!==void 0}function _t(e){let t=e.split(`
3
3
  at `);return t.length<=1?e:(t.splice(1,1),t.join(`
4
- at `))}function Rt(e,t){class r extends e{#e;constructor(...o){if(Et()){let i=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...o),Error.stackTraceLimit=i}else super(...o);let s=new Error().stack;s&&(this.#e=_t(s.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),r}var yt={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},gt=class extends Error{constructor(e="INTERNAL_SERVER_ERROR",t=void 0,r={},n=typeof e=="number"?e:yt[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=r,this.statusCode=n,this.name="APIError",this.status=e,this.headers=r,this.statusCode=n,this.body=t}};var Ot=Rt(gt,Error);var C=class extends Error{constructor(e,t){super(e,t),this.name="BetterAuthError",this.message=e,this.stack=""}};function Tt(e){try{return(new URL(e).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new C(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function St(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new C(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof C?t:new C(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function H(e,t="/api/auth"){if(St(e),Tt(e))return e;let r=e.replace(/\/+$/,"");return!t||t==="/"?r:(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`)}function Se(e,t){return!e||e.trim()===""?!1:t==="proto"?e==="http"||e==="https":t==="host"?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(r=>r.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function ve(e,t,r,n,o){if(e)return H(e,t);if(n!==!1){let c=L.BETTER_AUTH_URL||L.NEXT_PUBLIC_BETTER_AUTH_URL||L.PUBLIC_BETTER_AUTH_URL||L.NUXT_PUBLIC_BETTER_AUTH_URL||L.NUXT_PUBLIC_AUTH_URL||(L.BASE_URL!=="/"?L.BASE_URL:void 0);if(c)return H(c,t)}let s=r?.headers.get("x-forwarded-host"),i=r?.headers.get("x-forwarded-proto");if(s&&i&&o&&Se(i,"proto")&&Se(s,"host"))try{return H(`${i}://${s}`,t)}catch{}if(r){let c=vt(r.url);if(!c)throw new C("Could not get origin from request. Please provide a valid base URL.");return H(c,t)}if(typeof window<"u"&&window.location)return H(window.location.origin,t)}function vt(e){try{let t=new URL(e);return t.origin==="null"?null:t.origin}catch{return null}}var Ae={id:"redirect",name:"Redirect",hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};function be(e,t){let r=B(!1),n=ye(r,"/get-session",e,{method:"GET"}),o=()=>{};return Y(n,()=>{let s=Oe({sessionAtom:n,sessionSignal:r,$fetch:e,options:t});return s.init(),o=s.broadcastSessionUpdate,()=>{s.cleanup()}}),{session:n,$sessionSignal:r,broadcastSessionUpdate:s=>o(s)}}function oe(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)==="[object Module]":!0}function se(e,t,r=".",n){if(!oe(t))return se(e,{},r,n);let o={...t};for(let s of Object.keys(e)){if(s==="__proto__"||s==="constructor")continue;let i=e[s];i!=null&&(n&&n(o,s,i,r)||(Array.isArray(i)&&Array.isArray(o[s])?o[s]=[...i,...o[s]]:oe(i)&&oe(o[s])?o[s]=se(i,o[s],(r?`${r}.`:"")+s.toString(),n):o[s]=i))}return o}function ie(e){return(...t)=>t.reduce((r,n)=>se(r,n,"",e),{})}var we=ie(),Jr=ie((e,t,r)=>{if(e[t]!==void 0&&typeof r=="function")return e[t]=r(e[t]),!0}),Qr=ie((e,t,r)=>{if(Array.isArray(e[t])&&typeof r=="function")return e[t]=r(e[t]),!0});var At=Object.defineProperty,bt=Object.defineProperties,wt=Object.getOwnPropertyDescriptors,Ue=Object.getOwnPropertySymbols,Ut=Object.prototype.hasOwnProperty,Lt=Object.prototype.propertyIsEnumerable,Le=(e,t,r)=>t in e?At(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t)=>{for(var r in t||(t={}))Ut.call(t,r)&&Le(e,r,t[r]);if(Ue)for(var r of Ue(t))Lt.call(t,r)&&Le(e,r,t[r]);return e},b=(e,t)=>bt(e,wt(t)),Nt=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r,Error.captureStackTrace(this,this.constructor)}},It=async(e,t)=>{var r,n,o,s,i,c;let a=t||{},u={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:a,hooks:u};for(let l of t?.plugins||[]){if(l.init){let d=await((r=l.init)==null?void 0:r.call(l,e.toString(),t));a=d.options||a,e=d.url}u.onRequest.push((n=l.hooks)==null?void 0:n.onRequest),u.onResponse.push((o=l.hooks)==null?void 0:o.onResponse),u.onSuccess.push((s=l.hooks)==null?void 0:s.onSuccess),u.onError.push((i=l.hooks)==null?void 0:i.onError),u.onRetry.push((c=l.hooks)==null?void 0:c.onRetry)}return{url:e,options:a,hooks:u}},Ne=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Pt=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function Ct(e){if(typeof e=="number")return new Ne({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new Ne(e);case"exponential":return new Pt(e);default:throw new Error("Invalid retry strategy")}}var Dt=async e=>{let t={},r=async n=>typeof n=="function"?await n():n;if(e?.auth){if(e.auth.type==="Bearer"){let n=await r(e.auth.token);if(!n)return t;t.authorization=`Bearer ${n}`}else if(e.auth.type==="Basic"){let[n,o]=await Promise.all([r(e.auth.username),r(e.auth.password)]);if(!n||!o)return t;t.authorization=`Basic ${btoa(`${n}:${o}`)}`}else if(e.auth.type==="Custom"){let[n,o]=await Promise.all([r(e.auth.prefix),r(e.auth.value)]);if(!o)return t;t.authorization=`${n??""} ${o}`}}return t},xt=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function kt(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let n=t.split(";").shift()||"";return xt.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function Mt(e){try{return JSON.parse(e),!0}catch{return!1}}function ae(e){if(e===void 0)return!1;let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function Ie(e){try{return JSON.parse(e)}catch{return e}}function Pe(e){return typeof e=="function"}function Ft(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&Pe(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Pe(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Bt(e){let t=new Headers(e?.headers),r=await Dt(e);for(let[n,o]of Object.entries(r||{}))t.set(n,o);if(!t.has("content-type")){let n=Yt(e?.body);n&&t.set("content-type",n)}return t}function Yt(e){return ae(e)?"application/json":null}function jt(e){if(!e?.body)return null;let t=new Headers(e?.headers);if(ae(e.body)&&!t.has("content-type")){for(let[r,n]of Object.entries(e?.body))n instanceof Date&&(e.body[r]=n.toISOString());return JSON.stringify(e.body)}return t.has("content-type")&&t.get("content-type")==="application/x-www-form-urlencoded"&&ae(e.body)?new URLSearchParams(e.body).toString():e.body}function Ht(e,t){var r;if(t?.method)return t.method.toUpperCase();if(e.startsWith("@")){let n=(r=e.split("@")[1])==null?void 0:r.split("/")[0];return De.includes(n)?n.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function qt(e,t){let r;return!e?.signal&&e?.timeout&&(r=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var Wt=class Ce extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,Ce.prototype)}};async function z(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new Wt(r.issues);return r.value}var De=["get","post","put","patch","delete"];var Vt=e=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(t,r){var n,o,s,i;let c=((o=(n=e.plugins)==null?void 0:n.find(a=>{var u;return(u=a.schema)!=null&&u.config?t.startsWith(a.schema.config.baseURL||"")||t.startsWith(a.schema.config.prefix||""):!1}))==null?void 0:o.schema)||e.schema;if(c){let a=t;(s=c.config)!=null&&s.prefix&&a.startsWith(c.config.prefix)&&(a=a.replace(c.config.prefix,""),c.config.baseURL&&(t=t.replace(c.config.prefix,c.config.baseURL))),(i=c.config)!=null&&i.baseURL&&a.startsWith(c.config.baseURL)&&(a=a.replace(c.config.baseURL,""));let u=c.schema[a];if(u){let l=b(A({},r),{method:u.method,output:u.output});return r?.disableValidation||(l=b(A({},l),{body:u.input?await z(u.input,r?.body):r?.body,params:u.params?await z(u.params,r?.params):r?.params,query:u.query?await z(u.query,r?.query):r?.query})),{url:t,options:l}}}return{url:t,options:r}}}),xe=e=>{async function t(r,n){let o=b(A(A({},e),n),{plugins:[...e?.plugins||[],Vt(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await le(r,o)}catch(s){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:s}}}return await le(r,o)}return t};function Gt(e,t){let{baseURL:r,params:n,query:o}=t||{query:{},params:{},baseURL:""},s=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let d=e.toString().split("@")[1].split("/")[0];De.includes(d)&&(e=e.replace(`@${d}/`,"/"))}s.endsWith("/")||(s+="/");let[i,c]=e.replace(s,"").split("?"),a=new URLSearchParams(c);for(let[d,p]of Object.entries(o||{})){if(p==null)continue;let E;if(typeof p=="string")E=p;else if(Array.isArray(p)){for(let y of p)a.append(d,y);continue}else E=JSON.stringify(p);a.set(d,E)}if(n)if(Array.isArray(n)){let d=i.split("/").filter(p=>p.startsWith(":"));for(let[p,E]of d.entries()){let y=n[p];i=i.replace(E,y)}}else for(let[d,p]of Object.entries(n))i=i.replace(`:${d}`,String(p));i=i.split("/").map(encodeURIComponent).join("/"),i.startsWith("/")&&(i=i.slice(1));let u=a.toString();return u=u.length>0?`?${u}`.replace(/\+/g,"%20"):"",s.startsWith("http")?new URL(`${i}${u}`,s):`${s}${i}${u}`}var le=async(e,t)=>{var r,n,o,s,i,c,a,u;let{hooks:l,url:d,options:p}=await It(e,t),E=Ft(p),y=new AbortController,N=(r=p.signal)!=null?r:y.signal,O=Gt(d,p),T=jt(p),_=await Bt(p),g=Ht(d,p),m=b(A({},p),{url:O,headers:_,body:T,method:g,signal:N});for(let S of l.onRequest)if(S){let R=await S(m);typeof R=="object"&&R!==null&&(m=R)}("pipeTo"in m&&typeof m.pipeTo=="function"||typeof((n=t?.body)==null?void 0:n.pipe)=="function")&&("duplex"in m||(m.duplex="half"));let{clearTimeout:f}=qt(p,y),h=await E(m.url,m);f();let D={response:h,request:m};for(let S of l.onResponse)if(S){let R=await S(b(A({},D),{response:(o=t?.hookOptions)!=null&&o.cloneResponse?h.clone():h}));R instanceof Response?h=R:typeof R=="object"&&R!==null&&(h=R.response)}if(h.ok){if(!(m.method!=="HEAD"))return{data:"",error:null};let R=kt(h),w={data:null,response:h,request:m};if(R==="json"||R==="text"){let U=await h.text(),Ge=(s=m.jsonParser)!=null?s:Ie;w.data=await Ge(U)}else w.data=await h[R]();m?.output&&m.output&&!m.disableValidation&&(w.data=await z(m.output,w.data));for(let U of l.onSuccess)U&&await U(b(A({},w),{response:(i=t?.hookOptions)!=null&&i.cloneResponse?h.clone():h}));return t?.throw?w.data:{data:w.data,error:null}}let K=(c=t?.jsonParser)!=null?c:Ie,x=await h.text(),pe=Mt(x),X=pe?await K(x):null,Ve={response:h,responseText:x,request:m,error:b(A({},X),{status:h.status,statusText:h.statusText})};for(let S of l.onError)S&&await S(b(A({},Ve),{response:(a=t?.hookOptions)!=null&&a.cloneResponse?h.clone():h}));if(t?.retry){let S=Ct(t.retry),R=(u=t.retryAttempt)!=null?u:0;if(await S.shouldAttemptRetry(R,h)){for(let U of l.onRetry)U&&await U(D);let w=S.getDelay(R);return await new Promise(U=>setTimeout(U,w)),await le(e,b(A({},t),{retryAttempt:R+1}))}}if(t?.throw)throw new Nt(h.status,h.statusText,pe?X:x);return{data:null,error:b(A({},X),{status:h.status,statusText:h.statusText})}};var $t=e=>{if(typeof process>"u")return;let t=e??"/api/auth";if(process.env.NEXT_PUBLIC_AUTH_URL)return process.env.NEXT_PUBLIC_AUTH_URL;if(typeof window>"u"){if(process.env.NEXTAUTH_URL)try{return process.env.NEXTAUTH_URL}catch{}if(process.env.VERCEL_URL)try{let r=process.env.VERCEL_URL.startsWith("http")?"":"https://";return`${new URL(`${r}${process.env.VERCEL_URL}`).origin}${t}`}catch{}}},ke=(e,t)=>{let r="credentials"in Request.prototype,n=ve(e?.baseURL,e?.basePath,void 0,t)??$t(e?.basePath)??"/api/auth",o=e?.plugins?.flatMap(f=>f.fetchPlugins).filter(f=>f!==void 0)||[],s={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:i,onError:c,onRequest:a,onResponse:u,...l}=e?.fetchOptions||{},d=xe({baseURL:n,...r?{credentials:"include"}:{},method:"GET",jsonParser(f){return f?_e(f,{strict:!1}):null},customFetchImpl:fetch,...l,plugins:[s,...l.plugins||[],...e?.disableDefaultFetchPlugins?[]:[Ae],...o]}),{$sessionSignal:p,session:E,broadcastSessionUpdate:y}=be(d,e),N=e?.plugins||[],O={},T={$sessionSignal:p,session:E},_={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},g=[{signal:"$sessionSignal",matcher(f){return f==="/sign-out"||f==="/update-user"||f==="/update-session"||f==="/sign-up/email"||f==="/sign-in/email"||f==="/delete-user"||f==="/verify-email"||f==="/revoke-sessions"||f==="/revoke-session"||f==="/revoke-other-sessions"||f==="/change-email"||f==="/change-password"},callback(f){f==="/sign-out"?y("signout"):(f==="/update-user"||f==="/update-session")&&y("updateUser")}}];for(let f of N)f.getAtoms&&Object.assign(T,f.getAtoms?.(d)),f.pathMethods&&Object.assign(_,f.pathMethods),f.atomListeners&&g.push(...f.atomListeners);let m={notify:f=>{T[f].set(!T[f].get())},listen:(f,h)=>{T[f].subscribe(h)},atoms:T};for(let f of N)f.getActions&&(O=we(f.getActions?.(d,m,e)??{},O));return{get baseURL(){return n},pluginsActions:O,pluginsAtoms:T,pluginPathMethods:_,atomListeners:g,$fetch:d,$store:m}};function Me(e){return typeof e=="object"&&e!==null&&"get"in e&&typeof e.get=="function"&&"lc"in e&&typeof e.lc=="number"}function zt(e,t,r){let n=t[e],{fetchOptions:o,query:s,...i}=r||{};return n||(o?.method?o.method:i&&Object.keys(i).length>0?"POST":"GET")}function Fe(e,t,r,n,o){function s(i=[]){return new Proxy(function(){},{get(c,a){if(typeof a!="string"||a==="then"||a==="catch"||a==="finally")return;let u=[...i,a],l=e;for(let d of u)if(l&&typeof l=="object"&&d in l)l=l[d];else{l=void 0;break}return typeof l=="function"||Me(l)?l:s(u)},apply:async(c,a,u)=>{let l="/"+i.map(_=>_.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)).join("/"),d=u[0]||{},p=u[1]||{},{query:E,fetchOptions:y,...N}=d,O={...p,...y},T=zt(l,r,d);return await t(l,{...O,body:T==="GET"?void 0:{...N,...O?.body||{}},query:E||O?.query,method:T,async onSuccess(_){if(await O?.onSuccess?.(_),!o||O.disableSignal)return;let g=o.filter(f=>f.matcher(l));if(!g.length)return;let m=new Set;for(let f of g){let h=n[f.signal];if(!h)return;if(m.has(f.signal))continue;m.add(f.signal);let D=h.get();setTimeout(()=>{h.set(!D)},10),f.callback?.(l)}}})}})}return s()}function Be(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ue(e){let{pluginPathMethods:t,pluginsActions:r,pluginsAtoms:n,$fetch:o,atomListeners:s,$store:i}=ke(e),c={};for(let[a,u]of Object.entries(n))c[`use${Be(a)}`]=u;return Fe({...r,...c,$fetch:o,$store:i},o,t,n,s)}var Ye=Te({FAILED_TO_CREATE_USER:"Failed to create user",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",YOU_CANNOT_BAN_YOURSELF:"You cannot ban yourself",YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE:"You are not allowed to change users role",YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS:"You are not allowed to create users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS:"You are not allowed to list users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS:"You are not allowed to list users sessions",YOU_ARE_NOT_ALLOWED_TO_BAN_USERS:"You are not allowed to ban users",YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS:"You are not allowed to impersonate users",YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS:"You are not allowed to revoke users sessions",YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS:"You are not allowed to delete users",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD:"You are not allowed to set users password",BANNED_USER:"You have been banned from this application",YOU_ARE_NOT_ALLOWED_TO_GET_USER:"You are not allowed to get user",NO_DATA_TO_UPDATE:"No data to update",YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS:"You are not allowed to update users",YOU_CANNOT_REMOVE_YOURSELF:"You cannot remove yourself",YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE:"You are not allowed to set a non-existent role value",YOU_CANNOT_IMPERSONATE_ADMINS:"You cannot impersonate admins",INVALID_ROLE_TYPE:"Invalid role type"});function Jt(e){return{authorize(t,r="AND"){let n=!1;for(let[o,s]of Object.entries(t)){let i=e[o];if(!i)return{success:!1,error:`You are not allowed to access resource: ${o}`};if(Array.isArray(s))n=s.every(c=>i.includes(c));else if(typeof s=="object"){let c=s;c.connector==="OR"?n=c.actions.some(a=>i.includes(a)):n=c.actions.every(a=>i.includes(a))}else throw new C("Invalid access control request");if(n&&r==="OR")return{success:n};if(!n&&r==="AND")return{success:!1,error:`unauthorized to access resource "${o}"`}}return n?{success:n}:{success:!1,error:"Not authorized"}},statements:e}}function je(e){return{newRole(t){return Jt(t)},statements:e}}var Qt={user:["create","list","set-role","ban","impersonate","impersonate-admins","delete","set-password","get","update"],session:["list","revoke","delete"]},He=je(Qt),ce=He.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),fe=He.newRole({user:[],session:[]}),qe={admin:ce,user:fe};var We=e=>{if(e.userId&&e.options?.adminUserIds?.includes(e.userId))return!0;if(!e.permissions)return!1;let t=(e.role||e.options?.defaultRole||"user").split(","),r=e.options?.roles||qe;for(let n of t)if(r[n]?.authorize(e.permissions)?.success)return!0;return!1};var de=e=>{let t={admin:ce,user:fe,...e?.roles};return{id:"admin-client",version:me,$InferServerPlugin:{},getActions:()=>({admin:{checkRolePermission:r=>We({role:r.role,options:{ac:e?.ac,roles:t},permissions:r.permissions})}}),pathMethods:{"/admin/list-users":"GET","/admin/stop-impersonating":"POST"},$ERROR_CODES:Ye}};var J="learn_auth_token",Q=class{client;token=null;constructor(t){typeof localStorage<"u"&&(this.token=localStorage.getItem(J));let r=this;this.client=ue({baseURL:t.tenantUrl,plugins:[de()],fetchOptions:{onRequest(n){return r.token&&n.headers.set("Authorization",`Bearer ${r.token}`),n}}})}async signIn(t,r){let n=await this.client.signIn.email({email:t,password:r});return n.data?.token&&(this.token=n.data.token,typeof localStorage<"u"&&localStorage.setItem(J,this.token)),n}async signUp(t,r,n){let o=await this.client.signUp.email({email:t,password:r,name:n});return o.data?.token&&(this.token=o.data.token,typeof localStorage<"u"&&localStorage.setItem(J,this.token)),o}async signOut(){let t=await this.client.signOut();return this.token=null,typeof localStorage<"u"&&localStorage.removeItem(J),t}async getSession(){return await this.client.getSession()}getToken(){return this.token}async hasRole(t){let r=await this.getSession();if(!r?.data?.user)return!1;let n=r.data.user;return!!(n.role===t||n.roles?.includes(t))}async getRoles(){let t=await this.getSession();if(!t?.data?.user)return[];let r=t.data.user,n=[];return r.role&&n.push(r.role),r.roles&&n.push(...r.roles),[...new Set(n)]}};return Xe(Kt);})();
4
+ at `))}function gt(e,t){class r extends e{#e;constructor(...o){if(Et()){let i=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...o),Error.stackTraceLimit=i}else super(...o);let s=new Error().stack;s&&(this.#e=_t(s.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),r}var Rt={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},yt=class extends Error{constructor(e="INTERNAL_SERVER_ERROR",t=void 0,r={},n=typeof e=="number"?e:Rt[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=r,this.statusCode=n,this.name="APIError",this.status=e,this.headers=r,this.statusCode=n,this.body=t}};var Ot=gt(yt,Error);var C=class extends Error{constructor(e,t){super(e,t),this.name="BetterAuthError",this.message=e,this.stack=""}};function Tt(e){try{return(new URL(e).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new C(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function St(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new C(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof C?t:new C(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function H(e,t="/api/auth"){if(St(e),Tt(e))return e;let r=e.replace(/\/+$/,"");return!t||t==="/"?r:(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`)}function Se(e,t){return!e||e.trim()===""?!1:t==="proto"?e==="http"||e==="https":t==="host"?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(r=>r.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function ve(e,t,r,n,o){if(e)return H(e,t);if(n!==!1){let u=L.BETTER_AUTH_URL||L.NEXT_PUBLIC_BETTER_AUTH_URL||L.PUBLIC_BETTER_AUTH_URL||L.NUXT_PUBLIC_BETTER_AUTH_URL||L.NUXT_PUBLIC_AUTH_URL||(L.BASE_URL!=="/"?L.BASE_URL:void 0);if(u)return H(u,t)}let s=r?.headers.get("x-forwarded-host"),i=r?.headers.get("x-forwarded-proto");if(s&&i&&o&&Se(i,"proto")&&Se(s,"host"))try{return H(`${i}://${s}`,t)}catch{}if(r){let u=vt(r.url);if(!u)throw new C("Could not get origin from request. Please provide a valid base URL.");return H(u,t)}if(typeof window<"u"&&window.location)return H(window.location.origin,t)}function vt(e){try{let t=new URL(e);return t.origin==="null"?null:t.origin}catch{return null}}var Ae={id:"redirect",name:"Redirect",hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};function we(e,t){let r=B(!1),n=Re(r,"/get-session",e,{method:"GET"}),o=()=>{};return Y(n,()=>{let s=Oe({sessionAtom:n,sessionSignal:r,$fetch:e,options:t});return s.init(),o=s.broadcastSessionUpdate,()=>{s.cleanup()}}),{session:n,$sessionSignal:r,broadcastSessionUpdate:s=>o(s)}}function oe(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)==="[object Module]":!0}function se(e,t,r=".",n){if(!oe(t))return se(e,{},r,n);let o={...t};for(let s of Object.keys(e)){if(s==="__proto__"||s==="constructor")continue;let i=e[s];i!=null&&(n&&n(o,s,i,r)||(Array.isArray(i)&&Array.isArray(o[s])?o[s]=[...i,...o[s]]:oe(i)&&oe(o[s])?o[s]=se(i,o[s],(r?`${r}.`:"")+s.toString(),n):o[s]=i))}return o}function ie(e){return(...t)=>t.reduce((r,n)=>se(r,n,"",e),{})}var be=ie(),Jr=ie((e,t,r)=>{if(e[t]!==void 0&&typeof r=="function")return e[t]=r(e[t]),!0}),Qr=ie((e,t,r)=>{if(Array.isArray(e[t])&&typeof r=="function")return e[t]=r(e[t]),!0});var At=Object.defineProperty,wt=Object.defineProperties,bt=Object.getOwnPropertyDescriptors,Ue=Object.getOwnPropertySymbols,Ut=Object.prototype.hasOwnProperty,Lt=Object.prototype.propertyIsEnumerable,Le=(e,t,r)=>t in e?At(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t)=>{for(var r in t||(t={}))Ut.call(t,r)&&Le(e,r,t[r]);if(Ue)for(var r of Ue(t))Lt.call(t,r)&&Le(e,r,t[r]);return e},w=(e,t)=>wt(e,bt(t)),Nt=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r,Error.captureStackTrace(this,this.constructor)}},It=async(e,t)=>{var r,n,o,s,i,u;let a=t||{},c={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:a,hooks:c};for(let l of t?.plugins||[]){if(l.init){let d=await((r=l.init)==null?void 0:r.call(l,e.toString(),t));a=d.options||a,e=d.url}c.onRequest.push((n=l.hooks)==null?void 0:n.onRequest),c.onResponse.push((o=l.hooks)==null?void 0:o.onResponse),c.onSuccess.push((s=l.hooks)==null?void 0:s.onSuccess),c.onError.push((i=l.hooks)==null?void 0:i.onError),c.onRetry.push((u=l.hooks)==null?void 0:u.onRetry)}return{url:e,options:a,hooks:c}},Ne=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Pt=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function Ct(e){if(typeof e=="number")return new Ne({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new Ne(e);case"exponential":return new Pt(e);default:throw new Error("Invalid retry strategy")}}var Dt=async e=>{let t={},r=async n=>typeof n=="function"?await n():n;if(e?.auth){if(e.auth.type==="Bearer"){let n=await r(e.auth.token);if(!n)return t;t.authorization=`Bearer ${n}`}else if(e.auth.type==="Basic"){let[n,o]=await Promise.all([r(e.auth.username),r(e.auth.password)]);if(!n||!o)return t;t.authorization=`Basic ${btoa(`${n}:${o}`)}`}else if(e.auth.type==="Custom"){let[n,o]=await Promise.all([r(e.auth.prefix),r(e.auth.value)]);if(!o)return t;t.authorization=`${n??""} ${o}`}}return t},xt=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function kt(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let n=t.split(";").shift()||"";return xt.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function Mt(e){try{return JSON.parse(e),!0}catch{return!1}}function ae(e){if(e===void 0)return!1;let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function Ie(e){try{return JSON.parse(e)}catch{return e}}function Pe(e){return typeof e=="function"}function Ft(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&Pe(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Pe(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Bt(e){let t=new Headers(e?.headers),r=await Dt(e);for(let[n,o]of Object.entries(r||{}))t.set(n,o);if(!t.has("content-type")){let n=Yt(e?.body);n&&t.set("content-type",n)}return t}function Yt(e){return ae(e)?"application/json":null}function jt(e){if(!e?.body)return null;let t=new Headers(e?.headers);if(ae(e.body)&&!t.has("content-type")){for(let[r,n]of Object.entries(e?.body))n instanceof Date&&(e.body[r]=n.toISOString());return JSON.stringify(e.body)}return t.has("content-type")&&t.get("content-type")==="application/x-www-form-urlencoded"&&ae(e.body)?new URLSearchParams(e.body).toString():e.body}function Ht(e,t){var r;if(t?.method)return t.method.toUpperCase();if(e.startsWith("@")){let n=(r=e.split("@")[1])==null?void 0:r.split("/")[0];return De.includes(n)?n.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function qt(e,t){let r;return!e?.signal&&e?.timeout&&(r=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var Wt=class Ce extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,Ce.prototype)}};async function z(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new Wt(r.issues);return r.value}var De=["get","post","put","patch","delete"];var Vt=e=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(t,r){var n,o,s,i;let u=((o=(n=e.plugins)==null?void 0:n.find(a=>{var c;return(c=a.schema)!=null&&c.config?t.startsWith(a.schema.config.baseURL||"")||t.startsWith(a.schema.config.prefix||""):!1}))==null?void 0:o.schema)||e.schema;if(u){let a=t;(s=u.config)!=null&&s.prefix&&a.startsWith(u.config.prefix)&&(a=a.replace(u.config.prefix,""),u.config.baseURL&&(t=t.replace(u.config.prefix,u.config.baseURL))),(i=u.config)!=null&&i.baseURL&&a.startsWith(u.config.baseURL)&&(a=a.replace(u.config.baseURL,""));let c=u.schema[a];if(c){let l=w(A({},r),{method:c.method,output:c.output});return r?.disableValidation||(l=w(A({},l),{body:c.input?await z(c.input,r?.body):r?.body,params:c.params?await z(c.params,r?.params):r?.params,query:c.query?await z(c.query,r?.query):r?.query})),{url:t,options:l}}}return{url:t,options:r}}}),xe=e=>{async function t(r,n){let o=w(A(A({},e),n),{plugins:[...e?.plugins||[],Vt(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await le(r,o)}catch(s){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:s}}}return await le(r,o)}return t};function Gt(e,t){let{baseURL:r,params:n,query:o}=t||{query:{},params:{},baseURL:""},s=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let d=e.toString().split("@")[1].split("/")[0];De.includes(d)&&(e=e.replace(`@${d}/`,"/"))}s.endsWith("/")||(s+="/");let[i,u]=e.replace(s,"").split("?"),a=new URLSearchParams(u);for(let[d,p]of Object.entries(o||{})){if(p==null)continue;let E;if(typeof p=="string")E=p;else if(Array.isArray(p)){for(let R of p)a.append(d,R);continue}else E=JSON.stringify(p);a.set(d,E)}if(n)if(Array.isArray(n)){let d=i.split("/").filter(p=>p.startsWith(":"));for(let[p,E]of d.entries()){let R=n[p];i=i.replace(E,R)}}else for(let[d,p]of Object.entries(n))i=i.replace(`:${d}`,String(p));i=i.split("/").map(encodeURIComponent).join("/"),i.startsWith("/")&&(i=i.slice(1));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",s.startsWith("http")?new URL(`${i}${c}`,s):`${s}${i}${c}`}var le=async(e,t)=>{var r,n,o,s,i,u,a,c;let{hooks:l,url:d,options:p}=await It(e,t),E=Ft(p),R=new AbortController,N=(r=p.signal)!=null?r:R.signal,O=Gt(d,p),T=jt(p),_=await Bt(p),y=Ht(d,p),m=w(A({},p),{url:O,headers:_,body:T,method:y,signal:N});for(let S of l.onRequest)if(S){let g=await S(m);typeof g=="object"&&g!==null&&(m=g)}("pipeTo"in m&&typeof m.pipeTo=="function"||typeof((n=t?.body)==null?void 0:n.pipe)=="function")&&("duplex"in m||(m.duplex="half"));let{clearTimeout:f}=qt(p,R),h=await E(m.url,m);f();let D={response:h,request:m};for(let S of l.onResponse)if(S){let g=await S(w(A({},D),{response:(o=t?.hookOptions)!=null&&o.cloneResponse?h.clone():h}));g instanceof Response?h=g:typeof g=="object"&&g!==null&&(h=g.response)}if(h.ok){if(!(m.method!=="HEAD"))return{data:"",error:null};let g=kt(h),b={data:null,response:h,request:m};if(g==="json"||g==="text"){let U=await h.text(),Ge=(s=m.jsonParser)!=null?s:Ie;b.data=await Ge(U)}else b.data=await h[g]();m?.output&&m.output&&!m.disableValidation&&(b.data=await z(m.output,b.data));for(let U of l.onSuccess)U&&await U(w(A({},b),{response:(i=t?.hookOptions)!=null&&i.cloneResponse?h.clone():h}));return t?.throw?b.data:{data:b.data,error:null}}let K=(u=t?.jsonParser)!=null?u:Ie,x=await h.text(),pe=Mt(x),X=pe?await K(x):null,Ve={response:h,responseText:x,request:m,error:w(A({},X),{status:h.status,statusText:h.statusText})};for(let S of l.onError)S&&await S(w(A({},Ve),{response:(a=t?.hookOptions)!=null&&a.cloneResponse?h.clone():h}));if(t?.retry){let S=Ct(t.retry),g=(c=t.retryAttempt)!=null?c:0;if(await S.shouldAttemptRetry(g,h)){for(let U of l.onRetry)U&&await U(D);let b=S.getDelay(g);return await new Promise(U=>setTimeout(U,b)),await le(e,w(A({},t),{retryAttempt:g+1}))}}if(t?.throw)throw new Nt(h.status,h.statusText,pe?X:x);return{data:null,error:w(A({},X),{status:h.status,statusText:h.statusText})}};var $t=e=>{if(typeof process>"u")return;let t=e??"/api/auth";if(process.env.NEXT_PUBLIC_AUTH_URL)return process.env.NEXT_PUBLIC_AUTH_URL;if(typeof window>"u"){if(process.env.NEXTAUTH_URL)try{return process.env.NEXTAUTH_URL}catch{}if(process.env.VERCEL_URL)try{let r=process.env.VERCEL_URL.startsWith("http")?"":"https://";return`${new URL(`${r}${process.env.VERCEL_URL}`).origin}${t}`}catch{}}},ke=(e,t)=>{let r="credentials"in Request.prototype,n=ve(e?.baseURL,e?.basePath,void 0,t)??$t(e?.basePath)??"/api/auth",o=e?.plugins?.flatMap(f=>f.fetchPlugins).filter(f=>f!==void 0)||[],s={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:i,onError:u,onRequest:a,onResponse:c,...l}=e?.fetchOptions||{},d=xe({baseURL:n,...r?{credentials:"include"}:{},method:"GET",jsonParser(f){return f?_e(f,{strict:!1}):null},customFetchImpl:fetch,...l,plugins:[s,...l.plugins||[],...e?.disableDefaultFetchPlugins?[]:[Ae],...o]}),{$sessionSignal:p,session:E,broadcastSessionUpdate:R}=we(d,e),N=e?.plugins||[],O={},T={$sessionSignal:p,session:E},_={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},y=[{signal:"$sessionSignal",matcher(f){return f==="/sign-out"||f==="/update-user"||f==="/update-session"||f==="/sign-up/email"||f==="/sign-in/email"||f==="/delete-user"||f==="/verify-email"||f==="/revoke-sessions"||f==="/revoke-session"||f==="/revoke-other-sessions"||f==="/change-email"||f==="/change-password"},callback(f){f==="/sign-out"?R("signout"):(f==="/update-user"||f==="/update-session")&&R("updateUser")}}];for(let f of N)f.getAtoms&&Object.assign(T,f.getAtoms?.(d)),f.pathMethods&&Object.assign(_,f.pathMethods),f.atomListeners&&y.push(...f.atomListeners);let m={notify:f=>{T[f].set(!T[f].get())},listen:(f,h)=>{T[f].subscribe(h)},atoms:T};for(let f of N)f.getActions&&(O=be(f.getActions?.(d,m,e)??{},O));return{get baseURL(){return n},pluginsActions:O,pluginsAtoms:T,pluginPathMethods:_,atomListeners:y,$fetch:d,$store:m}};function Me(e){return typeof e=="object"&&e!==null&&"get"in e&&typeof e.get=="function"&&"lc"in e&&typeof e.lc=="number"}function zt(e,t,r){let n=t[e],{fetchOptions:o,query:s,...i}=r||{};return n||(o?.method?o.method:i&&Object.keys(i).length>0?"POST":"GET")}function Fe(e,t,r,n,o){function s(i=[]){return new Proxy(function(){},{get(u,a){if(typeof a!="string"||a==="then"||a==="catch"||a==="finally")return;let c=[...i,a],l=e;for(let d of c)if(l&&typeof l=="object"&&d in l)l=l[d];else{l=void 0;break}return typeof l=="function"||Me(l)?l:s(c)},apply:async(u,a,c)=>{let l="/"+i.map(_=>_.replace(/[A-Z]/g,y=>`-${y.toLowerCase()}`)).join("/"),d=c[0]||{},p=c[1]||{},{query:E,fetchOptions:R,...N}=d,O={...p,...R},T=zt(l,r,d);return await t(l,{...O,body:T==="GET"?void 0:{...N,...O?.body||{}},query:E||O?.query,method:T,async onSuccess(_){if(await O?.onSuccess?.(_),!o||O.disableSignal)return;let y=o.filter(f=>f.matcher(l));if(!y.length)return;let m=new Set;for(let f of y){let h=n[f.signal];if(!h)return;if(m.has(f.signal))continue;m.add(f.signal);let D=h.get();setTimeout(()=>{h.set(!D)},10),f.callback?.(l)}}})}})}return s()}function Be(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ce(e){let{pluginPathMethods:t,pluginsActions:r,pluginsAtoms:n,$fetch:o,atomListeners:s,$store:i}=ke(e),u={};for(let[a,c]of Object.entries(n))u[`use${Be(a)}`]=c;return Fe({...r,...u,$fetch:o,$store:i},o,t,n,s)}var Ye=Te({FAILED_TO_CREATE_USER:"Failed to create user",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",YOU_CANNOT_BAN_YOURSELF:"You cannot ban yourself",YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE:"You are not allowed to change users role",YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS:"You are not allowed to create users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS:"You are not allowed to list users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS:"You are not allowed to list users sessions",YOU_ARE_NOT_ALLOWED_TO_BAN_USERS:"You are not allowed to ban users",YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS:"You are not allowed to impersonate users",YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS:"You are not allowed to revoke users sessions",YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS:"You are not allowed to delete users",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD:"You are not allowed to set users password",BANNED_USER:"You have been banned from this application",YOU_ARE_NOT_ALLOWED_TO_GET_USER:"You are not allowed to get user",NO_DATA_TO_UPDATE:"No data to update",YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS:"You are not allowed to update users",YOU_CANNOT_REMOVE_YOURSELF:"You cannot remove yourself",YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE:"You are not allowed to set a non-existent role value",YOU_CANNOT_IMPERSONATE_ADMINS:"You cannot impersonate admins",INVALID_ROLE_TYPE:"Invalid role type"});function Jt(e){return{authorize(t,r="AND"){let n=!1;for(let[o,s]of Object.entries(t)){let i=e[o];if(!i)return{success:!1,error:`You are not allowed to access resource: ${o}`};if(Array.isArray(s))n=s.every(u=>i.includes(u));else if(typeof s=="object"){let u=s;u.connector==="OR"?n=u.actions.some(a=>i.includes(a)):n=u.actions.every(a=>i.includes(a))}else throw new C("Invalid access control request");if(n&&r==="OR")return{success:n};if(!n&&r==="AND")return{success:!1,error:`unauthorized to access resource "${o}"`}}return n?{success:n}:{success:!1,error:"Not authorized"}},statements:e}}function je(e){return{newRole(t){return Jt(t)},statements:e}}var Qt={user:["create","list","set-role","ban","impersonate","impersonate-admins","delete","set-password","get","update"],session:["list","revoke","delete"]},He=je(Qt),ue=He.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),fe=He.newRole({user:[],session:[]}),qe={admin:ue,user:fe};var We=e=>{if(e.userId&&e.options?.adminUserIds?.includes(e.userId))return!0;if(!e.permissions)return!1;let t=(e.role||e.options?.defaultRole||"user").split(","),r=e.options?.roles||qe;for(let n of t)if(r[n]?.authorize(e.permissions)?.success)return!0;return!1};var de=e=>{let t={admin:ue,user:fe,...e?.roles};return{id:"admin-client",version:me,$InferServerPlugin:{},getActions:()=>({admin:{checkRolePermission:r=>We({role:r.role,options:{ac:e?.ac,roles:t},permissions:r.permissions})}}),pathMethods:{"/admin/list-users":"GET","/admin/stop-impersonating":"POST"},$ERROR_CODES:Ye}};var J="learn_auth_token",Q=class{client;token=null;config;constructor(t){this.config=t,typeof localStorage<"u"&&(this.token=localStorage.getItem(J));let r=this;this.client=ce({baseURL:t.tenantUrl,plugins:[de()],fetchOptions:{onRequest(n){return r.token&&n.headers.set("Authorization",`Bearer ${r.token}`),n}}})}async signIn(t,r){let n=await this.client.signIn.email({email:t,password:r});return n.data?.token&&(this.token=n.data.token,typeof localStorage<"u"&&localStorage.setItem(J,this.token)),n}async signUp(t,r,n){let o=await this.client.signUp.email({email:t,password:r,name:n});return o.data?.token&&(this.token=o.data.token,typeof localStorage<"u"&&localStorage.setItem(J,this.token)),o}async signOut(){let t=await this.client.signOut();return this.token=null,typeof localStorage<"u"&&localStorage.removeItem(J),t}async getSession(){return await this.client.getSession()}getToken(){return this.token}async hasRole(t){let r=await this.getSession();if(!r?.data?.user)return!1;let n=r.data.user;return!!(n.role===t||n.roles?.includes(t))}async getRoles(){let t=await this.getSession();if(!t?.data?.user)return[];let r=t.data.user,n=[];return r.role&&n.push(r.role),r.roles&&n.push(...r.roles),[...new Set(n)]}async loginWithGoogle(t){let r=t??(typeof window<"u"?window.location.href:"/"),n=this.config.tenantUrl.replace(/\/api\/auth\/?$/,""),o=new URLSearchParams({callbackURL:r});window.location.href=`${n}/auth/google?${o}`}};return Xe(Kt);})();
5
5
 
6
6
  ;AuthSDK=AuthSDK.AuthSDK;
package/dist/index.d.ts CHANGED
@@ -36,6 +36,7 @@ type SDKName = 'learn-secrets-sdk' | 'learn-auth-sdk';
36
36
  declare class AuthSDK {
37
37
  private client;
38
38
  private token;
39
+ private config;
39
40
  constructor(config: AuthSDKConfig);
40
41
  signIn(email: string, password: string): Promise<{
41
42
  data: Omit<{
@@ -175,6 +176,7 @@ declare class AuthSDK {
175
176
  getToken(): string | null;
176
177
  hasRole(role: string): Promise<boolean>;
177
178
  getRoles(): Promise<string[]>;
179
+ loginWithGoogle(callbackURL?: string): Promise<void>;
178
180
  }
179
181
 
180
182
  /**
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{createAuthClient as S}from"better-auth/client";import{adminClient as w}from"better-auth/client/plugins";var l="learn_auth_token",h=class{client;token=null;constructor(e){typeof localStorage<"u"&&(this.token=localStorage.getItem(l));let r=this;this.client=S({baseURL:e.tenantUrl,plugins:[w()],fetchOptions:{onRequest(n){return r.token&&n.headers.set("Authorization",`Bearer ${r.token}`),n}}})}async signIn(e,r){let n=await this.client.signIn.email({email:e,password:r});return n.data?.token&&(this.token=n.data.token,typeof localStorage<"u"&&localStorage.setItem(l,this.token)),n}async signUp(e,r,n){let o=await this.client.signUp.email({email:e,password:r,name:n});return o.data?.token&&(this.token=o.data.token,typeof localStorage<"u"&&localStorage.setItem(l,this.token)),o}async signOut(){let e=await this.client.signOut();return this.token=null,typeof localStorage<"u"&&localStorage.removeItem(l),e}async getSession(){return await this.client.getSession()}getToken(){return this.token}async hasRole(e){let r=await this.getSession();if(!r?.data?.user)return!1;let n=r.data.user;return!!(n.role===e||n.roles?.includes(e))}async getRoles(){let e=await this.getSession();if(!e?.data?.user)return[];let r=e.data.user,n=[];return r.role&&n.push(r.role),r.roles&&n.push(...r.roles),[...new Set(n)]}};import{exec as y}from"child_process";import{promisify as C}from"util";import{createHash as p}from"crypto";import*as i from"os";var a=C(y);async function I(){let t=process.platform;try{let e;if(t==="darwin")e=await D();else if(t==="linux")e=await x();else if(t==="win32")e=await k();else throw new Error(`Unsupported platform: ${t}`);let r=p("sha256").update(e).digest("hex").substring(0,32),n=JSON.stringify({machineId:r,cpus:i.cpus().length,arch:i.arch(),platform:i.platform(),homedir:i.homedir()}),o=p("sha256").update(n).digest("hex");return{machineId:r,fingerprint:o}}catch(e){throw new Error(`Failed to get machine ID: ${e.message}`)}}async function D(){try{let{stdout:t}=await a(`ioreg -l | grep IOPlatformSerialNumber | awk '{print $4}' | sed 's/"//g'`),{stdout:e}=await a("hostname"),r=t.trim(),n=e.trim();if(r&&n)return`${r}-${n}`;let{stdout:o}=await a(`ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk '{print $3}' | sed 's/"//g'`);return o.trim()}catch{throw new Error("Failed to get macOS machine ID")}}async function x(){try{let{stdout:t}=await a("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null"),e=t.trim();if(e)return e;throw new Error("Machine ID file not found")}catch{throw new Error("Failed to get Linux machine ID")}}async function k(){try{let{stdout:t}=await a("wmic csproduct get uuid"),r=t.split(`
2
- `).map(n=>n.trim()).find(n=>n&&n!=="UUID");if(r)return r;throw new Error("Failed to parse machine UUID from WMIC")}catch{throw new Error("Failed to get Windows machine ID")}}import*as s from"fs";import*as c from"path";import*as u from"os";function f(){let t=u.homedir(),e=c.join(t,".learn");return c.join(e,"credentials.json")}function K(){let t=u.homedir(),e=c.join(t,".learn");s.existsSync(e)||s.mkdirSync(e,{recursive:!0,mode:448})}function d(){try{let t=f();if(!s.existsSync(t))return null;let e=s.readFileSync(t,"utf-8"),r=JSON.parse(e);return r.access_token&&!r["learn-secrets-sdk"]&&!r["learn-auth-sdk"]?{"learn-secrets-sdk":r}:r}catch{return null}}function m(t){K();let e=f(),r=JSON.stringify(t,null,2);s.writeFileSync(e,r,{mode:384})}function g(t){let e=d();return e&&e[t]||null}function v(t,e){let r=d()||{};r[t]=e,m(r)}function U(t){let e=d();e&&(delete e[t],Object.keys(e).length===0?O():m(e))}function O(){try{let t=f();s.existsSync(t)&&s.unlinkSync(t)}catch{}}function P(t){let e=g(t);return e!==null&&!!e.access_token}export{h as AuthSDK,U as deleteSDKCredentials,I as getMachineId,P as hasSDKCredentials,d as readAllCredentials,g as readSDKCredentials,m as writeAllCredentials,v as writeSDKCredentials};
1
+ import{createAuthClient as w}from"better-auth/client";import{adminClient as S}from"better-auth/client/plugins";var c="learn_auth_token",h=class{client;token=null;config;constructor(e){this.config=e,typeof localStorage<"u"&&(this.token=localStorage.getItem(c));let r=this;this.client=w({baseURL:e.tenantUrl,plugins:[S()],fetchOptions:{onRequest(n){return r.token&&n.headers.set("Authorization",`Bearer ${r.token}`),n}}})}async signIn(e,r){let n=await this.client.signIn.email({email:e,password:r});return n.data?.token&&(this.token=n.data.token,typeof localStorage<"u"&&localStorage.setItem(c,this.token)),n}async signUp(e,r,n){let s=await this.client.signUp.email({email:e,password:r,name:n});return s.data?.token&&(this.token=s.data.token,typeof localStorage<"u"&&localStorage.setItem(c,this.token)),s}async signOut(){let e=await this.client.signOut();return this.token=null,typeof localStorage<"u"&&localStorage.removeItem(c),e}async getSession(){return await this.client.getSession()}getToken(){return this.token}async hasRole(e){let r=await this.getSession();if(!r?.data?.user)return!1;let n=r.data.user;return!!(n.role===e||n.roles?.includes(e))}async getRoles(){let e=await this.getSession();if(!e?.data?.user)return[];let r=e.data.user,n=[];return r.role&&n.push(r.role),r.roles&&n.push(...r.roles),[...new Set(n)]}async loginWithGoogle(e){let r=e??(typeof window<"u"?window.location.href:"/"),n=this.config.tenantUrl.replace(/\/api\/auth\/?$/,""),s=new URLSearchParams({callbackURL:r});window.location.href=`${n}/auth/google?${s}`}};import{exec as y}from"child_process";import{promisify as C}from"util";import{createHash as p}from"crypto";import*as o from"os";var a=C(y);async function D(){let t=process.platform;try{let e;if(t==="darwin")e=await I();else if(t==="linux")e=await x();else if(t==="win32")e=await k();else throw new Error(`Unsupported platform: ${t}`);let r=p("sha256").update(e).digest("hex").substring(0,32),n=JSON.stringify({machineId:r,cpus:o.cpus().length,arch:o.arch(),platform:o.platform(),homedir:o.homedir()}),s=p("sha256").update(n).digest("hex");return{machineId:r,fingerprint:s}}catch(e){throw new Error(`Failed to get machine ID: ${e.message}`)}}async function I(){try{let{stdout:t}=await a(`ioreg -l | grep IOPlatformSerialNumber | awk '{print $4}' | sed 's/"//g'`),{stdout:e}=await a("hostname"),r=t.trim(),n=e.trim();if(r&&n)return`${r}-${n}`;let{stdout:s}=await a(`ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk '{print $3}' | sed 's/"//g'`);return s.trim()}catch{throw new Error("Failed to get macOS machine ID")}}async function x(){try{let{stdout:t}=await a("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null"),e=t.trim();if(e)return e;throw new Error("Machine ID file not found")}catch{throw new Error("Failed to get Linux machine ID")}}async function k(){try{let{stdout:t}=await a("wmic csproduct get uuid"),r=t.split(`
2
+ `).map(n=>n.trim()).find(n=>n&&n!=="UUID");if(r)return r;throw new Error("Failed to parse machine UUID from WMIC")}catch{throw new Error("Failed to get Windows machine ID")}}import*as i from"fs";import*as l from"path";import*as u from"os";function f(){let t=u.homedir(),e=l.join(t,".learn");return l.join(e,"credentials.json")}function K(){let t=u.homedir(),e=l.join(t,".learn");i.existsSync(e)||i.mkdirSync(e,{recursive:!0,mode:448})}function d(){try{let t=f();if(!i.existsSync(t))return null;let e=i.readFileSync(t,"utf-8"),r=JSON.parse(e);return r.access_token&&!r["learn-secrets-sdk"]&&!r["learn-auth-sdk"]?{"learn-secrets-sdk":r}:r}catch{return null}}function m(t){K();let e=f(),r=JSON.stringify(t,null,2);i.writeFileSync(e,r,{mode:384})}function g(t){let e=d();return e&&e[t]||null}function U(t,e){let r=d()||{};r[t]=e,m(r)}function v(t){let e=d();e&&(delete e[t],Object.keys(e).length===0?P():m(e))}function P(){try{let t=f();i.existsSync(t)&&i.unlinkSync(t)}catch{}}function O(t){let e=g(t);return e!==null&&!!e.access_token}export{h as AuthSDK,v as deleteSDKCredentials,D as getMachineId,O as hasSDKCredentials,d as readAllCredentials,g as readSDKCredentials,m as writeAllCredentials,U as writeSDKCredentials};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "learn-auth-sdk",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "description": "Open-source Auth SDK for decentralized tenant backends",
5
5
  "license": "MIT",
6
6
  "main": "./dist/index.js",