next-pocketbase-auth
Version:
Wrapper for Next.js applications using PocketBase, with support for both client and server components
118 lines (117 loc) • 2.54 kB
JavaScript
var y = Object.defineProperty;
var _ = (t, e, n) => e in t ? y(t, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[e] = n;
var u = (t, e, n) => _(t, typeof e != "symbol" ? e + "" : e, n);
import l from "js-cookie";
import f, { BaseAuthStore as w, getTokenPayload as O } from "pocketbase";
const h = "http://127.0.0.1:8090/api/", o = "pb_auth__", v = {
httpOnly: !1,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
path: "/",
expires: new Date(Date.now() + 86400)
// will be set to the token expiration date, this is safe default of 24 hours
};
class d extends w {
constructor(n) {
super();
u(this, "saveFunc");
u(this, "clearFunc");
if (this.saveFunc = n.save, this.clearFunc = n.clear, n.initial)
try {
const r = S(n.initial);
this.save(r.token, r.record ?? r.model ?? null);
} catch {
}
}
/**
* @inheritdoc
*/
save(n, r) {
super.save(n, r);
let s = "";
const i = {}, c = O(n);
"exp" in c && typeof c.exp == "number" && (i.expires = new Date(c.exp * 1e3));
try {
s = m({ token: n, record: r ?? null });
} catch {
console.warn("SyncAuthStore: failed to stringify the new state");
}
this.saveFunc(s, i);
}
/**
* @inheritdoc
*/
clear() {
this.clearFunc(), super.clear();
}
}
function S(t) {
const e = JSON.parse(atob(t));
if (typeof e == "object" && e !== null && "token" in e && typeof e.token == "string" && ("record" in e || "model" in e))
return e;
throw new Error("Invalid DTO");
}
function m(t) {
return btoa(JSON.stringify(t));
}
function E(t) {
const e = {
...v,
...t
};
return new d({
save: (n, r) => {
l.set(o, n, {
...e,
...r
});
},
clear: () => {
l.remove(o);
},
initial: l.get(o)
});
}
let a;
function A(t = process.env.NEXT_PUBLIC_PB_URL ?? h, e, n) {
return a || (a = new f(t, E(n), e), a);
}
function b(t, e) {
var r;
const n = {
...v,
...e
};
return new d({
save: (s, i) => {
p(
() => t.set(o, s, {
...n,
...i
})
);
},
clear: () => {
p(() => t.delete(o));
},
initial: (r = t.get(o)) == null ? void 0 : r.value
});
}
function p(t) {
try {
t();
} catch {
}
}
function B(t, e = process.env.NEXT_PUBLIC_PB_URL ?? h, n, r) {
return new f(
e,
b(t, r),
n
);
}
export {
E as clientAuthStore,
A as createBrowserClient,
B as createServerClient
};