learn-auth-sdk 0.3.4 → 0.4.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/browser.global.js +2 -2
- package/dist/cli/index.js +24 -8
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/browser.global.js
CHANGED
|
@@ -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 ge=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]=[]}},ge)},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 Re(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 R=t.get(),m=()=>{a.lastSessionRequest=M(),n("/get-session").then(async f=>{let{data:h,error:D}=Re(f);if(h?.needsRefresh)try{let x=await n("/get-session",{method:"POST"});({data:h,error:D}=Re(x))}catch{}let K=h?.session&&h?.user?h:null;t.set({...R,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}(R?.data===null||R?.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,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 ge=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]=[]}},ge)},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",Re=(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 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 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 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,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 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 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 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},Rt=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=gt(Rt,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 we(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 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,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=w(A({},r),{method:u.method,output:u.output});return r?.disableValidation||(l=w(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=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,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),R=Ht(d,p),m=w(A({},p),{url:O,headers:_,body:T,method:R,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,y),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=(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: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=(u=t.retryAttempt)!=null?u: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: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}=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"},R=[{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&&R.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:R,$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,R=>`-${R.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 R=o.filter(f=>f.matcher(l));if(!R.length)return;let m=new Set;for(let f of R){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)]}async loginWithGoogle(t){let r=await this.client.signIn.social({provider:"google",callbackURL:t??(typeof window<"u"?window.location.href:"/")});if(r?.data?.url)window.location.href=r.data.url;else if(r?.error)throw new Error(r.error.message||"Failed to initiate Google sign-in")}};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 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 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,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=w(A({},r),{method:u.method,output:u.output});return r?.disableValidation||(l=w(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=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,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 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 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),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=(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: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=(u=t.retryAttempt)!=null?u: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: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: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(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,y=>`-${y.toLowerCase()}`)).join("/"),d=u[0]||{},p=u[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 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;config;constructor(t){this.config=t,typeof sessionStorage<"u"&&(this.token=sessionStorage.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 sessionStorage<"u"&&sessionStorage.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 sessionStorage<"u"&&sessionStorage.setItem(J,this.token)),o}async signOut(){let t=await this.client.signOut();return this.token=null,typeof sessionStorage<"u"&&sessionStorage.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/cli/index.js
CHANGED
|
@@ -200,8 +200,8 @@ Log in on ${baseUrl}`);
|
|
|
200
200
|
console.log("Login at:");
|
|
201
201
|
console.log(deviceData.verification_uri_complete);
|
|
202
202
|
console.log("\nPress ENTER to open in the browser...");
|
|
203
|
-
const
|
|
204
|
-
const rl =
|
|
203
|
+
const readline2 = await import("readline");
|
|
204
|
+
const rl = readline2.createInterface({
|
|
205
205
|
input: process.stdin,
|
|
206
206
|
output: process.stdout
|
|
207
207
|
});
|
|
@@ -244,8 +244,8 @@ Log in on ${baseUrl}`);
|
|
|
244
244
|
console.log("\n\nDevice authorized! Retrieving access token...");
|
|
245
245
|
writeSDKCredentials(SDK_NAME, {
|
|
246
246
|
access_token: tokenData.access_token,
|
|
247
|
-
refresh_token: null,
|
|
248
|
-
expires_at:
|
|
247
|
+
refresh_token: tokenData.refresh_token ?? null,
|
|
248
|
+
expires_at: tokenData.expires_in ? new Date(Date.now() + tokenData.expires_in * 1e3).toISOString() : new Date(Date.now() + 90 * 864e5).toISOString(),
|
|
249
249
|
user_id: tokenData.user_id,
|
|
250
250
|
machine_id: machineInfo.machineId,
|
|
251
251
|
sdk_name: SDK_NAME,
|
|
@@ -262,10 +262,26 @@ Log in on ${baseUrl}`);
|
|
|
262
262
|
|
|
263
263
|
// src/cli/commands/init.ts
|
|
264
264
|
import fs2 from "fs";
|
|
265
|
-
|
|
266
|
-
|
|
265
|
+
import readline from "readline";
|
|
266
|
+
async function initCommand(options = {}) {
|
|
267
|
+
const roles = options.roles ? options.roles.split(",").map((r) => r.trim()) : [];
|
|
268
|
+
const defaultConfig = { roles, protectedPages: [] };
|
|
269
|
+
if (!options.yes) {
|
|
270
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
271
|
+
await new Promise((resolve) => {
|
|
272
|
+
rl.question(`Initialize auth-config.json with roles [${roles.join(", ") || "none"}]? (y/N) `, (answer) => {
|
|
273
|
+
rl.close();
|
|
274
|
+
if (answer.toLowerCase() !== "y") {
|
|
275
|
+
console.log("Aborted.");
|
|
276
|
+
process.exit(0);
|
|
277
|
+
}
|
|
278
|
+
resolve();
|
|
279
|
+
});
|
|
280
|
+
});
|
|
281
|
+
}
|
|
267
282
|
fs2.writeFileSync("auth-config.json", JSON.stringify(defaultConfig, null, 2));
|
|
268
283
|
console.log("Initialized auth-config.json");
|
|
284
|
+
if (roles.length) console.log(`Roles: ${roles.join(", ")}`);
|
|
269
285
|
}
|
|
270
286
|
|
|
271
287
|
// src/cli/commands/config.ts
|
|
@@ -311,8 +327,8 @@ program.name("learn-auth").description("CLI tool for managing Auth settings").ve
|
|
|
311
327
|
program.command("login").description("Authenticate with Learn Auth via browser").option("--base-url <url>", "Custom base URL for API").action(async (options) => {
|
|
312
328
|
await loginCommand(options);
|
|
313
329
|
});
|
|
314
|
-
program.command("init").description("Initialize auth configuration").action(async () => {
|
|
315
|
-
await initCommand();
|
|
330
|
+
program.command("init").description("Initialize auth configuration").option("--roles <roles>", "Comma-separated list of roles to create (e.g. admin,user)").option("-y, --yes", "Skip confirmation prompt").action(async (options) => {
|
|
331
|
+
await initCommand(options);
|
|
316
332
|
});
|
|
317
333
|
program.command("config").description("Configure roles and protected pages").option("--roles <roles>", "Comma separated roles").option("--protect <page>", "Page URL to protect").option("--allowed-roles <roles>", "Roles allowed to view protected page").action(async (options) => {
|
|
318
334
|
await configCommand(options);
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createAuthClient as w}from"better-auth/client";import{adminClient as S}from"better-auth/client/plugins";var
|
|
2
|
-
`).map(n=>n.trim()).find(n=>n&&n!=="UUID");if(
|
|
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 sessionStorage<"u"&&(this.token=sessionStorage.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 sessionStorage<"u"&&sessionStorage.setItem(c,this.token)),n}async signUp(e,r,n){let i=await this.client.signUp.email({email:e,password:r,name:n});return i.data?.token&&(this.token=i.data.token,typeof sessionStorage<"u"&&sessionStorage.setItem(c,this.token)),i}async signOut(){let e=await this.client.signOut();return this.token=null,typeof sessionStorage<"u"&&sessionStorage.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\/?$/,""),i=new URLSearchParams({callbackURL:r});window.location.href=`${n}/auth/google?${i}`}};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()}),i=p("sha256").update(n).digest("hex");return{machineId:r,fingerprint:i}}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:i}=await a(`ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID | awk '{print $3}' | sed 's/"//g'`);return i.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 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");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 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();s.existsSync(t)&&s.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};
|