@vite-hub/auth 0.6.1 → 0.8.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/README.md +86 -12
- package/dist/{abilities-BYOcyQ9B.d.ts → abilities-IOwpkcz4.d.ts} +1 -1
- package/dist/abilities.d.ts +1 -1
- package/dist/{ability-error-D3-u8k1A.js → ability-error-DgR91Jwc.js} +1 -1
- package/dist/{access-pages-9aKr6z-k.js → access-pages-C69nwa99.js} +10 -3
- package/dist/agent.d.ts +2 -3
- package/dist/agent.js +31 -12
- package/dist/{auth-instance-BWiRS9QZ.js → auth-instance-WeEK1zDd.js} +174 -64
- package/dist/{cli-C5pAfY4x.d.ts → cli-DL7uCAvz.d.ts} +15 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +1 -1
- package/dist/client-extension-BgUlm6hy.d.ts +33 -0
- package/dist/client-request-B1DCz3a9.js +29 -0
- package/dist/{console-runtime-DMH1I2fl.d.ts → console-runtime-C71weVrt.d.ts} +1 -1
- package/dist/{console-runtime-CaIXVtB_.js → console-runtime-Dk3j4Jmz.js} +5 -3
- package/dist/console-runtime.d.ts +2 -2
- package/dist/console-runtime.js +1 -1
- package/dist/console.d.ts +1 -1
- package/dist/database-options-Cms7BI3c.js +36 -0
- package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-IlHEeUBK.js} +1 -1
- package/dist/database.d.ts +1 -1
- package/dist/database.js +13 -8
- package/dist/{definition-BypPLIbI.js → definition-EpeI5LUG.js} +18 -4
- package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DZHuHXPP.js} +46 -5
- package/dist/{events-BXU1_9mc.js → events-Cm7Iwq47.js} +1 -1
- package/dist/extension-BWmjJhoN.d.ts +59 -0
- package/dist/extension-mCx4TrsO.js +133 -0
- package/dist/forward.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +5 -3
- package/dist/internal/server.d.ts +3 -3
- package/dist/internal/server.js +5 -4
- package/dist/{mcp-config-C7srUMIZ.js → mcp-config-Bbr8kQxm.js} +9 -1
- package/dist/{mcp-token-CuqdbBy8.js → mcp-token-BleQZK6H.js} +52 -11
- package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-CxpopXmK.d.ts} +5 -2
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +27 -6
- package/dist/{members-CwPIx10t.js → members-7OMdqha_.js} +188 -152
- package/dist/nuxt.d.ts +4 -14
- package/dist/nuxt.js +53 -20
- package/dist/{own-access-BNcxKrDl.d.ts → own-access-CGiai2L3.d.ts} +1 -1
- package/dist/{page-tools-shared-CtoKaNQZ.js → page-tools-shared-dVJBPPTk.js} +8 -0
- package/dist/presets.js +1 -1
- package/dist/roles-BGi8CyBG.js +17 -0
- package/dist/runtime/client-request-plugin.d.ts +2 -1
- package/dist/runtime/client-request-plugin.js +8 -5
- package/dist/runtime/console.d.ts +1 -1
- package/dist/runtime/console.js +2 -2
- package/dist/runtime/empty-abilities.d.ts +1 -1
- package/dist/runtime/empty-client.d.ts +3 -0
- package/dist/runtime/empty-client.js +3 -1
- package/dist/runtime/empty-definition.d.ts +1 -1
- package/dist/runtime/server.d.ts +4 -3
- package/dist/runtime/server.js +7 -4
- package/dist/runtime/vue-nuxt.js +27 -11
- package/dist/schema.d.ts +32 -14
- package/dist/schema.js +21 -14
- package/dist/{server-Iru6jcnW.js → server-5t-HA7I1.js} +80 -328
- package/dist/{server-C4Kni3Vj.d.ts → server-DyP1v-sZ.d.ts} +39 -7
- package/dist/{server-BHniJi2m.d.ts → server-mmp8EfcE.d.ts} +4 -2
- package/dist/server.d.ts +6 -3
- package/dist/server.js +9 -3
- package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-BNtY3hMp.js} +4 -16
- package/dist/{set-cookie-DVfi-nJX.js → set-cookie-Bva-P-_C.js} +1 -1
- package/dist/{table-specs-CCSY4tiS.js → table-specs-Bm7QJCbu.js} +1 -1
- package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-BxKeFD_y.d.ts} +5 -0
- package/dist/test.d.ts +1 -1
- package/dist/test.js +2 -2
- package/dist/{types-DmH31d2t.d.ts → types-CnO5bHEF.d.ts} +40 -6
- package/dist/{vite-CpWhT1Wi.js → vite-7I1bJvqA.js} +686 -244
- package/dist/vite-CZ_Z6IR3.d.ts +28 -0
- package/dist/vite.d.ts +41 -6
- package/dist/vite.js +1 -1
- package/dist/vue.d.ts +4 -3
- package/dist/vue.js +39 -4
- package/package.json +9 -8
- package/dist/client-request-BzMKtfCY.js +0 -52
- package/dist/database-options-B87hDU4j.js +0 -28
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
// ../internal/src/runtime/page-tools-shared.ts
|
|
2
|
+
/** The query that turns the page tools on for a page. `?vitehub=<tool id>` also opens that tool. */
|
|
3
|
+
const viteHubPageToolsQuery = "vitehub";
|
|
4
|
+
/**
|
|
5
|
+
* Query parameters of links into a tool, such as `?comment=3` of Comments. Like `?vitehub`, they load the page tools,
|
|
6
|
+
* so a person who follows a link sees what it points at. The tool with that `param` opens.
|
|
7
|
+
*/
|
|
8
|
+
const viteHubPageToolsLinkParams = ["comment"];
|
|
2
9
|
/**
|
|
3
10
|
* The cookie that remembers the session route's answer for this browser: `1` when a tool allows the person, `0` when
|
|
4
11
|
* none does or the person turned the tools off. It is a hint, never a credential, and it is not HttpOnly, because the
|
|
@@ -15,4 +22,5 @@ const viteHubSessionMarkerCookie = "vitehub_session";
|
|
|
15
22
|
* next page asks the session route again for the new person.
|
|
16
23
|
*/
|
|
17
24
|
const viteHubPageToolsResetCookie = `${viteHubPageToolsCookie}=; Path=/; Max-Age=0; SameSite=Lax`;
|
|
25
|
+
`${JSON.stringify([viteHubPageToolsQuery, ...viteHubPageToolsLinkParams])}`;
|
|
18
26
|
export { viteHubPageToolsResetCookie as n, viteHubSessionMarkerCookie as r, viteHubPageToolsCookie as t };
|
package/dist/presets.js
CHANGED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/roles.ts
|
|
2
|
+
/**
|
|
3
|
+
* Whether `user.role` has one of `roles`. Better Auth's `admin()` plugin stores the roles of a user as one string,
|
|
4
|
+
* separated by commas, such as `"team,admin"`.
|
|
5
|
+
*/
|
|
6
|
+
function hasRole(user, roles) {
|
|
7
|
+
const role = typeof user === "object" && user !== null ? Reflect.get(user, "role") : void 0;
|
|
8
|
+
if (typeof role !== "string") return false;
|
|
9
|
+
const wanted = typeof roles === "string" ? [roles] : roles;
|
|
10
|
+
return role.split(",").some((name) => wanted.includes(name.trim()));
|
|
11
|
+
}
|
|
12
|
+
/** Whether `value` is a role or a non-empty list of roles, each a non-empty string without a comma. */
|
|
13
|
+
function isAuthRole(value) {
|
|
14
|
+
const isName = (name) => typeof name === "string" && name.trim() === name && name !== "" && !name.includes(",");
|
|
15
|
+
return isName(value) || Array.isArray(value) && value.length > 0 && value.every(isName);
|
|
16
|
+
}
|
|
17
|
+
export { isAuthRole as n, hasRole as t };
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
/** Keeps each request that the Nitro app serves for `clientRequest()`. Auth and Comments each ship it, so it wraps `fetch` once. */
|
|
2
|
+
export default function clientRequestPlugin(nitroApp: unknown): void;
|
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
import { t as isRecord } from "../object-CAK6UYR5.js";
|
|
2
|
-
import {
|
|
3
|
-
// src/runtime/client-request-plugin.ts
|
|
2
|
+
import { n as runWithClientRequest } from "../client-request-B1DCz3a9.js";
|
|
3
|
+
// ../internal/src/runtime/client-request-plugin.ts
|
|
4
|
+
const installed = Symbol.for("vitehub.client-request.installed");
|
|
4
5
|
function isRequest(value) {
|
|
5
6
|
return isRecord(value) && typeof value.url === "string" && value.headers instanceof Headers;
|
|
6
7
|
}
|
|
7
|
-
|
|
8
|
+
/** Keeps each request that the Nitro app serves for `clientRequest()`. Auth and Comments each ship it, so it wraps `fetch` once. */
|
|
9
|
+
function clientRequestPlugin(nitroApp) {
|
|
8
10
|
if (!isRecord(nitroApp)) return;
|
|
9
11
|
const h3 = nitroApp.h3;
|
|
10
12
|
const owner = isRecord(h3) && h3.fetch instanceof Function ? h3 : nitroApp;
|
|
11
13
|
const fetch = owner.fetch;
|
|
12
|
-
if (!(fetch instanceof Function)) return;
|
|
14
|
+
if (!(fetch instanceof Function) || owner[installed]) return;
|
|
15
|
+
owner[installed] = true;
|
|
13
16
|
owner.fetch = (request, ...rest) => {
|
|
14
17
|
const call = () => Reflect.apply(fetch, owner, [request, ...rest]);
|
|
15
18
|
return isRequest(request) ? runWithClientRequest(request, call) : call();
|
|
16
19
|
};
|
|
17
20
|
}
|
|
18
|
-
export {
|
|
21
|
+
export { clientRequestPlugin as default };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import "../server.js";
|
|
2
|
-
import {
|
|
2
|
+
import { M as authForRequest, r as aggregateAuthEvents, y as listAuthEvents } from "../server-DyP1v-sZ.js";
|
|
3
3
|
export { aggregateAuthEvents, authForRequest, listAuthEvents };
|
package/dist/runtime/console.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as authForRequest } from "../auth-instance-
|
|
1
|
+
import { _ as listAuthEvents, t as aggregateAuthEvents } from "../server-5t-HA7I1.js";
|
|
2
|
+
import { t as authForRequest } from "../auth-instance-WeEK1zDd.js";
|
|
3
3
|
import "../server.js";
|
|
4
4
|
export { aggregateAuthEvents, authForRequest, listAuthEvents };
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { r as AuthClientExtensionSource } from "../client-extension-BgUlm6hy.js";
|
|
1
2
|
import { BetterAuthClientOptions } from "better-auth";
|
|
2
3
|
/** The options of the default Auth client when the app has no `auth.client.ts`. */
|
|
3
4
|
declare const options: BetterAuthClientOptions | undefined;
|
|
5
|
+
/** The parts of the client options, from the `auth.client.extend.ts` files. An app without parts exports none. */
|
|
6
|
+
export declare const extensions: readonly AuthClientExtensionSource[] | undefined;
|
|
4
7
|
export { options as default };
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
// src/runtime/empty-client.ts
|
|
2
2
|
/** The options of the default Auth client when the app has no `auth.client.ts`. */
|
|
3
3
|
const options = void 0;
|
|
4
|
-
|
|
4
|
+
/** The parts of the client options, from the `auth.client.extend.ts` files. An app without parts exports none. */
|
|
5
|
+
const extensions = void 0;
|
|
6
|
+
export { options as default, extensions };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as AuthDefinition } from "../types-
|
|
1
|
+
import { _ as AuthDefinition } from "../types-CnO5bHEF.js";
|
|
2
2
|
declare const definition: AuthDefinition | undefined;
|
|
3
3
|
export declare function getAuthApp(): object | undefined;
|
|
4
4
|
export { definition as default };
|
package/dist/runtime/server.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { a as applyAuthExtensions } from "../extension-BWmjJhoN.js";
|
|
2
|
+
import { t as authAccessHandlerMeta } from "../own-access-CGiai2L3.js";
|
|
3
|
+
import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as checkBuiltAuthPages, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-mmp8EfcE.js";
|
|
4
|
+
export { AuthAccessRouteMatch, applyAuthExtensions, authAccessHandlerMeta, checkBuiltAuthPages, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
|
package/dist/runtime/server.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { n as canonicalAccessPath, r as resolveAccessRoutePath } from "../application-path-zKi7NrvK.js";
|
|
2
|
-
import { t as authErrorDiagnostics } from "../error-diagnostics-
|
|
2
|
+
import { t as authErrorDiagnostics } from "../error-diagnostics-DZHuHXPP.js";
|
|
3
3
|
import { r as routedToAccessHandler, t as authAccessHandlerMeta } from "../own-access-CYsakJiH.js";
|
|
4
4
|
import { r as unwrapAuthRequest } from "../request-Dpq7GO8B.js";
|
|
5
5
|
import { t as getAuthRuntimeState } from "../runtime-state-C0Rd1W4m.js";
|
|
6
|
+
import { t as applyAuthExtensions } from "../extension-mCx4TrsO.js";
|
|
6
7
|
// src/runtime/server.ts
|
|
7
8
|
function setAuthRuntimeEnvResolver(resolver, definition) {
|
|
8
9
|
const state = getAuthRuntimeState();
|
|
@@ -11,7 +12,7 @@ function setAuthRuntimeEnvResolver(resolver, definition) {
|
|
|
11
12
|
}
|
|
12
13
|
function assertSamePages(pages = {}, built) {
|
|
13
14
|
const keys = Object.keys(pages);
|
|
14
|
-
if (keys.length === Object.keys(built).length && keys.every((key) => Object.hasOwn(built, key) && built[key] === pages[key])) return;
|
|
15
|
+
if (keys.length === Object.keys(built).length && keys.every((key) => Object.hasOwn(built, key) && JSON.stringify(built[key]) === JSON.stringify(pages[key]))) return;
|
|
15
16
|
throw authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: "`defineAuth()` access.pages is not the map that the build read from server/auth.ts, so the build guards other pages. Write `access` and `access.pages` inline in `defineAuth()`, and restart the dev server after you change them." });
|
|
16
17
|
}
|
|
17
18
|
/**
|
|
@@ -50,6 +51,7 @@ function createAuthAccessRouteMatcher(routes, publicRoutes = []) {
|
|
|
50
51
|
const rules = routes.map((route, index) => ({
|
|
51
52
|
index,
|
|
52
53
|
authorize: route.authorize === true,
|
|
54
|
+
role: route.role === true,
|
|
53
55
|
method: route.method?.toUpperCase(),
|
|
54
56
|
...resolveAccessRoutePath(route.route)
|
|
55
57
|
}));
|
|
@@ -62,7 +64,8 @@ function createAuthAccessRouteMatcher(routes, publicRoutes = []) {
|
|
|
62
64
|
const method = request.method.toUpperCase();
|
|
63
65
|
return rules.filter((rule) => (!rule.method || rule.method === method || rule.method === "GET" && method === "HEAD") && matchesPath(rule, pathname)).map((rule) => ({
|
|
64
66
|
index: rule.index,
|
|
65
|
-
authorize: rule.authorize
|
|
67
|
+
authorize: rule.authorize,
|
|
68
|
+
role: rule.role
|
|
66
69
|
}));
|
|
67
70
|
};
|
|
68
71
|
}
|
|
@@ -82,4 +85,4 @@ function createLazyAuthAccessHandler(routes, load, publicRoutes = []) {
|
|
|
82
85
|
return await (await handler)(input);
|
|
83
86
|
};
|
|
84
87
|
}
|
|
85
|
-
export { authAccessHandlerMeta, checkBuiltAuthPages, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
|
|
88
|
+
export { applyAuthExtensions, authAccessHandlerMeta, checkBuiltAuthPages, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
|
package/dist/runtime/vue-nuxt.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { n as invariantError } from "../invariant-Dj2R1eMr.js";
|
|
2
|
-
import "../page-tools-shared-
|
|
2
|
+
import "../page-tools-shared-dVJBPPTk.js";
|
|
3
3
|
import { i as resolveAuthMountPath } from "../application-path-zKi7NrvK.js";
|
|
4
|
+
import { t as authErrorDiagnostics } from "../error-diagnostics-DZHuHXPP.js";
|
|
5
|
+
import { n as isAuthRole, t as hasRole } from "../roles-BGi8CyBG.js";
|
|
4
6
|
import { a as setRequestFetchResolver, i as setNuxtErrorFactory, n as setDefaultAuthBasePath, o as setSessionSeedResolver, r as setNuxtAppResolver, s as setSignOutHandler } from "../nuxt-bridge-pRyfYD5c.js";
|
|
5
7
|
import { addRouteMiddleware, createError, defineNuxtPlugin, navigateTo, showError, tryUseNuxtApp, useRequestEvent, useRouter, useRuntimeConfig, useState } from "#app";
|
|
6
8
|
// src/runtime/vue-nuxt.ts
|
|
@@ -96,6 +98,9 @@ async function fetchServerSession(event, basePath) {
|
|
|
96
98
|
return;
|
|
97
99
|
}
|
|
98
100
|
}
|
|
101
|
+
function userOf(session) {
|
|
102
|
+
return typeof session === "object" && session !== null ? Reflect.get(session, "user") ?? null : null;
|
|
103
|
+
}
|
|
99
104
|
/** The session read of each server request, so the page guard and all components share one read. */
|
|
100
105
|
const serverReads = /* @__PURE__ */ new WeakMap();
|
|
101
106
|
const viteHubAuthPlugin = defineNuxtPlugin({
|
|
@@ -115,13 +120,18 @@ const viteHubAuthPlugin = defineNuxtPlugin({
|
|
|
115
120
|
if (config === false || meta === void 0 || meta === false) return;
|
|
116
121
|
const mode = typeof meta === "string" ? meta : meta === true ? "user" : meta.only ?? "user";
|
|
117
122
|
const redirectTo = typeof meta === "object" ? meta.redirectTo : void 0;
|
|
123
|
+
const role = typeof meta === "object" ? meta.role : void 0;
|
|
124
|
+
if (role !== void 0 && !isAuthRole(role)) throw authErrorDiagnostics.AUTH_ACCESS_ROLE_INVALID({ message: "`definePageMeta()` auth.role must be a role name or a non-empty list of role names." });
|
|
118
125
|
const isThisPage = (target) => {
|
|
119
126
|
const page = useRouter().resolve(target);
|
|
120
127
|
return page.matched.length > 0 && page.matched.at(-1) === to.matched.at(-1) && sameParams(page.params, to.params);
|
|
121
128
|
};
|
|
122
|
-
return (loggedIn, signedOut = false) => {
|
|
129
|
+
return (loggedIn, signedOut = false, user) => {
|
|
123
130
|
if (mode === "guest") return loggedIn && !isThisPage(redirectTo ?? afterSignIn) ? navigateTo(redirectTo ?? afterSignIn) : void 0;
|
|
124
|
-
if (loggedIn) return
|
|
131
|
+
if (loggedIn) return role && user !== void 0 && !hasRole(user, role) ? showError({
|
|
132
|
+
statusCode: 403,
|
|
133
|
+
statusMessage: "Forbidden"
|
|
134
|
+
}) : void 0;
|
|
125
135
|
const signInTarget = redirectTo ?? signInPage;
|
|
126
136
|
if (signInTarget && isThisPage(signInTarget)) return showError({
|
|
127
137
|
statusCode: 401,
|
|
@@ -181,28 +191,34 @@ const viteHubAuthPlugin = defineNuxtPlugin({
|
|
|
181
191
|
if (!decide) return;
|
|
182
192
|
const page = to.fullPath.split("#", 1)[0];
|
|
183
193
|
if (navigation === 1 && !serverSession && !stale && !nuxtApp.payload.error && nuxtApp.isHydrating && useState(guardRouteKey).value === page) return decide(true);
|
|
184
|
-
const decideAndSeed = (
|
|
194
|
+
const decideAndSeed = (user) => {
|
|
195
|
+
const loggedIn = user !== null;
|
|
185
196
|
if (serverSession && loggedIn) {
|
|
186
197
|
useState(guardRouteKey).value = page;
|
|
187
198
|
useRequestEvent()?.res.headers.set("cache-control", "private, no-store");
|
|
188
199
|
}
|
|
189
|
-
return decide(loggedIn);
|
|
200
|
+
return decide(loggedIn, false, user);
|
|
190
201
|
};
|
|
191
202
|
const session = serverSession?.();
|
|
192
203
|
const app = tryUseNuxtApp();
|
|
193
204
|
const inApp = (run) => app ? app.runWithContext(run) : run();
|
|
194
|
-
const
|
|
195
|
-
if (
|
|
196
|
-
return
|
|
205
|
+
const user = !serverSession ? import("../vue.js").then(({ useUserSession }) => inApp(() => useUserSession().refresh({}))).then((current) => current?.session && current?.user ? current.user : null) : session instanceof Promise ? session.then(userOf) : userOf(session);
|
|
206
|
+
if (!(user instanceof Promise)) return decideAndSeed(user);
|
|
207
|
+
return user.then((value) => {
|
|
197
208
|
if (navigation !== navigations) return;
|
|
198
209
|
return inApp(() => decideAndSeed(value));
|
|
199
210
|
});
|
|
200
211
|
};
|
|
201
212
|
addRouteMiddleware("vitehub-auth", (to) => guard(to, to.meta.auth, ++navigations), { global: true });
|
|
202
|
-
|
|
213
|
+
const pageGuards = [
|
|
214
|
+
["vitehub-auth-user", "user"],
|
|
215
|
+
["vitehub-auth-guest", "guest"],
|
|
216
|
+
...(config?.pageRoles ?? []).map((role, index) => [`vitehub-auth-role-${index}`, { role }])
|
|
217
|
+
];
|
|
218
|
+
for (const [name, meta] of pageGuards) addRouteMiddleware(name, (to) => {
|
|
203
219
|
if (to.meta.auth !== void 0) return;
|
|
204
|
-
routeModes.set(to,
|
|
205
|
-
return guard(to,
|
|
220
|
+
routeModes.set(to, meta);
|
|
221
|
+
return guard(to, meta, navigations);
|
|
206
222
|
});
|
|
207
223
|
}
|
|
208
224
|
});
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as AuthSchemaPlugin, c as AuthTableSpec, d as resolveAuthTableSpecs, i as AuthSchemaOptions, l as authPluginSchemas, n as AuthCoreTableSpecs, o as AuthTableField, r as AuthPluginSchemas, s as AuthTableName, t as AuthCoreModel, u as authTableSpecs } from "./table-specs-
|
|
1
|
+
import { a as AuthSchemaPlugin, c as AuthTableSpec, d as resolveAuthTableSpecs, i as AuthSchemaOptions, l as authPluginSchemas, n as AuthCoreTableSpecs, o as AuthTableField, r as AuthPluginSchemas, s as AuthTableName, t as AuthCoreModel, u as authTableSpecs } from "./table-specs-BxKeFD_y.js";
|
|
2
2
|
import { $Type, BuildColumns, HasDefault, IsPrimaryKey, NotNull } from "drizzle-orm";
|
|
3
|
-
import { PgBigInt53Builder, PgBooleanBuilder, PgBuildColumns, PgColumn, PgIntegerBuilder, PgJsonbBuilder, PgTableWithColumns, PgTextBuilder, PgTimestampBuilder } from "drizzle-orm/pg-core";
|
|
3
|
+
import { PgBigInt53Builder, PgBooleanBuilder, PgBuildColumns, PgColumn, PgIntegerBuilder, PgJsonbBuilder, PgTableWithColumns, PgTextBuilder, PgTimestampBuilder, PgUUIDBuilder } from "drizzle-orm/pg-core";
|
|
4
4
|
import { SQLiteBooleanBuilder, SQLiteColumn, SQLiteIntegerBuilder, SQLiteTableWithColumns, SQLiteTextBuilder, SQLiteTextJsonBuilder, SQLiteTimestampBuilder } from "drizzle-orm/sqlite-core";
|
|
5
5
|
interface AuthExistingColumn {
|
|
6
6
|
notNull: boolean;
|
|
@@ -86,7 +86,7 @@ type SqliteBuilder<F> = F extends {
|
|
|
86
86
|
} ? SQLiteIntegerBuilder : F extends {
|
|
87
87
|
type: "string";
|
|
88
88
|
} ? SQLiteTextBuilder<[string, ...string[]]> : $Type<SQLiteTextJsonBuilder, FieldData<F>>;
|
|
89
|
-
type PostgresBuilder<F> = F extends {
|
|
89
|
+
type PostgresBuilder<F, TUuidIds extends boolean> = F extends {
|
|
90
90
|
type: "boolean";
|
|
91
91
|
} ? PgBooleanBuilder : F extends {
|
|
92
92
|
type: "date";
|
|
@@ -96,7 +96,11 @@ type PostgresBuilder<F> = F extends {
|
|
|
96
96
|
bigint: true;
|
|
97
97
|
} ? PgBigInt53Builder : PgIntegerBuilder : F extends {
|
|
98
98
|
type: "string";
|
|
99
|
-
} ?
|
|
99
|
+
} ? [TUuidIds, F] extends [true, {
|
|
100
|
+
references: {
|
|
101
|
+
field: "id";
|
|
102
|
+
};
|
|
103
|
+
}] ? PgUUIDBuilder : PgTextBuilder : F extends {
|
|
100
104
|
type: "json";
|
|
101
105
|
} ? PgJsonbBuilder : $Type<PgTextBuilder, FieldData<F>>;
|
|
102
106
|
type WithSqliteConstraints<TBuilder, TField, TColumns, TName extends string> = [TColumns] extends [never] ? WithConstraints<TBuilder, TField> : [TColumns] extends [Record<TName, infer TColumn extends AuthExistingColumn>] ? WithColumnConstraints<TBuilder, [TColumn] extends [{
|
|
@@ -107,9 +111,9 @@ type WithSqliteConstraints<TBuilder, TField, TColumns, TName extends string> = [
|
|
|
107
111
|
type SqliteColumns<TFields, TExistingColumns> = {
|
|
108
112
|
id: IsPrimaryKey<SQLiteTextBuilder<[string, ...string[]]>>;
|
|
109
113
|
} & { -readonly [K in keyof TFields]: WithSqliteConstraints<SqliteBuilder<TFields[K]>, TFields[K], TExistingColumns, SqlName<K & string>>; };
|
|
110
|
-
type PostgresColumns<TFields> = {
|
|
111
|
-
id: IsPrimaryKey<PgTextBuilder>;
|
|
112
|
-
} & { -readonly [K in keyof TFields]: WithConstraints<PostgresBuilder<TFields[K]>, TFields[K]>; };
|
|
114
|
+
type PostgresColumns<TFields, TUuidIds extends boolean> = {
|
|
115
|
+
id: TUuidIds extends true ? HasDefault<IsPrimaryKey<PgUUIDBuilder>> : IsPrimaryKey<PgTextBuilder>;
|
|
116
|
+
} & { -readonly [K in keyof TFields]: WithConstraints<PostgresBuilder<TFields[K], TUuidIds>, TFields[K]>; };
|
|
113
117
|
/** A SQLite table with a typed column for each field of `TFields`. */
|
|
114
118
|
export type AuthSqliteTableOf<TFields, TExistingColumns = never> = SQLiteTableWithColumns<{
|
|
115
119
|
name: string;
|
|
@@ -118,11 +122,11 @@ export type AuthSqliteTableOf<TFields, TExistingColumns = never> = SQLiteTableWi
|
|
|
118
122
|
dialect: "sqlite";
|
|
119
123
|
isAlias: false;
|
|
120
124
|
}>;
|
|
121
|
-
/** A Postgres table with a typed column for each field of `TFields`. */
|
|
122
|
-
export type AuthPostgresTableOf<TFields> = PgTableWithColumns<{
|
|
125
|
+
/** A Postgres table with a typed column for each field of `TFields`. `TUuidIds` types the `uuid` IDs and references. */
|
|
126
|
+
export type AuthPostgresTableOf<TFields, TUuidIds extends boolean = false> = PgTableWithColumns<{
|
|
123
127
|
name: string;
|
|
124
128
|
schema: undefined;
|
|
125
|
-
columns: PgBuildColumns<string, PostgresColumns<TFields>>;
|
|
129
|
+
columns: PgBuildColumns<string, PostgresColumns<TFields, TUuidIds>>;
|
|
126
130
|
dialect: "pg";
|
|
127
131
|
isAlias: false;
|
|
128
132
|
}>;
|
|
@@ -156,6 +160,9 @@ type TableFields<TOptions, TModel extends AuthTableName> = Prefer<Prefer<AuthCor
|
|
|
156
160
|
type PluginTableFields<TOptions, TTable extends keyof PluginTables<SchemaPlugins<TOptions>>> = PluginTables<SchemaPlugins<TOptions>>[TTable] extends {
|
|
157
161
|
fields: infer TFields;
|
|
158
162
|
} ? TFields : never;
|
|
163
|
+
type UuidIds<TOptions> = [TOptions] extends [{
|
|
164
|
+
generateId: "uuid";
|
|
165
|
+
}] ? true : false;
|
|
159
166
|
type Lower = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z";
|
|
160
167
|
type Upper = Uppercase<Lower>;
|
|
161
168
|
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
|
|
@@ -167,9 +174,17 @@ type ExistingColumns<TExisting, TModel extends string> = [TExisting] extends [Re
|
|
|
167
174
|
/** The Better Auth tables for SQLite, with fields from `TOptions` and constraints from a literal migration snapshot. */
|
|
168
175
|
export type AuthSqliteSchemaFor<TOptions extends AuthSchemaOptions, TExisting extends AuthExistingTables | undefined = undefined> = { readonly [TModel in AuthTableName]: AuthSqliteTableOf<TableFields<TOptions, TModel>, ExistingColumns<TExisting, TModel>>; } & { readonly [TTable in keyof PluginTables<SchemaPlugins<TOptions>>]: AuthSqliteTableOf<PluginTableFields<TOptions, TTable>, ExistingColumns<TExisting, TTable & string>>; };
|
|
169
176
|
/** The Better Auth tables for Postgres, with the plugin tables and the plugin and additional columns of `TOptions`. */
|
|
170
|
-
export type AuthPostgresSchemaFor<TOptions extends AuthSchemaOptions> = { readonly [TModel in AuthTableName]: AuthPostgresTableOf<TableFields<TOptions, TModel>>; } & { readonly [TTable in keyof PluginTables<SchemaPlugins<TOptions>>]: AuthPostgresTableOf<PluginTableFields<TOptions, TTable>>; };
|
|
171
|
-
|
|
172
|
-
|
|
177
|
+
export type AuthPostgresSchemaFor<TOptions extends AuthSchemaOptions> = { readonly [TModel in AuthTableName]: AuthPostgresTableOf<TableFields<TOptions, TModel>, UuidIds<TOptions>>; } & { readonly [TTable in keyof PluginTables<SchemaPlugins<TOptions>>]: AuthPostgresTableOf<PluginTableFields<TOptions, TTable>, UuidIds<TOptions>>; };
|
|
178
|
+
declare global {
|
|
179
|
+
namespace ViteHub {
|
|
180
|
+
interface AuthRegistry {}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
type RegisteredAuthSchema<TExport extends string, TCore> = ViteHub.AuthRegistry extends {
|
|
184
|
+
schema: { readonly [K in TExport]: infer TSchema; };
|
|
185
|
+
} ? TSchema : TCore;
|
|
186
|
+
export declare const authSqliteSchema: RegisteredAuthSchema<"authSqliteSchema", AuthSqliteSchema>;
|
|
187
|
+
export declare const authPostgresSchema: RegisteredAuthSchema<"authPostgresSchema", AuthPostgresSchema>;
|
|
173
188
|
/**
|
|
174
189
|
* The Better Auth tables for SQLite, libSQL, and Cloudflare D1, with the plugins and additional fields of `options`. The
|
|
175
190
|
* Auth Vite plugin writes a module that calls it when the Auth Definition adds fields or imports a plugin of
|
|
@@ -180,6 +195,9 @@ export declare const authPostgresSchema: AuthPostgresSchema;
|
|
|
180
195
|
* snapshot literal when present.
|
|
181
196
|
*/
|
|
182
197
|
export declare function createAuthSqliteSchema<const TOptions extends AuthSchemaOptions, const TExisting extends AuthExistingTables | undefined = AuthExistingTables | undefined>(options: TOptions, existing?: TExisting): AuthSqliteSchemaFor<TOptions, TExisting>;
|
|
183
|
-
/**
|
|
198
|
+
/**
|
|
199
|
+
* The Better Auth tables for Postgres, with the plugins and additional fields of `options`, typed from its literal. With
|
|
200
|
+
* `generateId: "uuid"`, each `id` is `uuid` with a `gen_random_uuid()` default, and each column that references one is `uuid`.
|
|
201
|
+
*/
|
|
184
202
|
export declare function createAuthPostgresSchema<const TOptions extends AuthSchemaOptions>(options: TOptions): AuthPostgresSchemaFor<TOptions>;
|
|
185
203
|
export { type AuthCoreModel, type AuthCoreTableSpecs, type AuthPluginSchemas, type AuthSchemaOptions, type AuthSchemaPlugin, type AuthTableField, type AuthTableName, type AuthTableSpec, authPluginSchemas, authTableSpecs, resolveAuthTableSpecs };
|
package/dist/schema.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as resolveAuthTableSpecs, n as authSqlName, r as authTableSpecs, t as authPluginSchemas } from "./table-specs-
|
|
1
|
+
import { i as resolveAuthTableSpecs, n as authSqlName, r as authTableSpecs, t as authPluginSchemas } from "./table-specs-Bm7QJCbu.js";
|
|
2
2
|
import { sql } from "drizzle-orm";
|
|
3
|
-
import { bigint, boolean, foreignKey, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
|
3
|
+
import { bigint, boolean, foreignKey, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
|
|
4
4
|
import { foreignKey as foreignKey$1, index as index$1, integer as integer$1, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from "drizzle-orm/sqlite-core";
|
|
5
5
|
// src/schema.ts
|
|
6
6
|
const sameColumns = (left, right) => left.length === right.length && left.every((column, index) => column === right[index]);
|
|
@@ -13,7 +13,7 @@ function buildTables(dialect, specs, existing) {
|
|
|
13
13
|
const modelBySqlName = new Map(Object.keys(specs).map((model) => [authSqlName(model), model]));
|
|
14
14
|
for (const [model, spec] of Object.entries(specs)) {
|
|
15
15
|
const current = existing && Object.hasOwn(existing, authSqlName(model)) ? existing[authSqlName(model)] : void 0;
|
|
16
|
-
const columns = {
|
|
16
|
+
const columns = {};
|
|
17
17
|
const indexed = [];
|
|
18
18
|
const foreignKeys = [];
|
|
19
19
|
const indexName = (fields, unique, name) => current?.indexes.find((entry) => entry.unique === unique && sameColumns(entry.columns, fields.map(authSqlName)))?.name ?? name;
|
|
@@ -23,7 +23,7 @@ function buildTables(dialect, specs, existing) {
|
|
|
23
23
|
let builder = dialect.column(name, field);
|
|
24
24
|
if (column) {
|
|
25
25
|
if (column.default !== void 0) builder = builder.default(dialect.raw(column.default));
|
|
26
|
-
} else if (field.defaultValue !== void 0) builder = builder.default(field.defaultValue === "now" && field.type !== "string" ? field.type === "number" ? dialect.nowMs : dialect.now : field.defaultValue);
|
|
26
|
+
} else if (field.defaultValue !== void 0 && !(current && field.unique && !field.required)) builder = builder.default(field.defaultValue === "now" && field.type !== "string" ? field.type === "number" ? dialect.nowMs : dialect.now : field.defaultValue);
|
|
27
27
|
if (field.onUpdate) builder = builder.$onUpdate(() => /* @__PURE__ */ new Date());
|
|
28
28
|
if (column ? column.notNull : field.required && (!current || field.defaultValue !== void 0)) builder = builder.notNull();
|
|
29
29
|
if (field.unique) {
|
|
@@ -99,7 +99,6 @@ const sqliteDialect = {
|
|
|
99
99
|
column(name, field) {
|
|
100
100
|
return field.type === "boolean" ? integer$1(name, { mode: "boolean" }) : field.type === "date" ? integer$1(name, { mode: "timestamp_ms" }) : field.type === "number" ? integer$1(name) : field.type === "string" ? text$1(name) : text$1(name, { mode: "json" });
|
|
101
101
|
},
|
|
102
|
-
id: () => text$1("id").primaryKey(),
|
|
103
102
|
index: (name, unique, columns) => (unique ? uniqueIndex$1(name) : index$1(name)).on(...columns),
|
|
104
103
|
foreignKey: (name, columns, foreignColumns, actions) => foreignKey$1({
|
|
105
104
|
name,
|
|
@@ -109,13 +108,15 @@ const sqliteDialect = {
|
|
|
109
108
|
now: sql`(cast(unixepoch('subsecond') * 1000 as integer))`,
|
|
110
109
|
nowMs: sql`(cast(unixepoch('subsecond') * 1000 as integer))`,
|
|
111
110
|
raw: (sqlText) => sql.raw(sqlText),
|
|
112
|
-
table: (name, columns, extras) => sqliteTable(name,
|
|
111
|
+
table: (name, columns, extras) => sqliteTable(name, {
|
|
112
|
+
id: text$1("id").primaryKey(),
|
|
113
|
+
...columns
|
|
114
|
+
}, (table) => extras(table))
|
|
113
115
|
};
|
|
114
|
-
const postgresDialect = {
|
|
116
|
+
const postgresDialect = (uuidIds) => ({
|
|
115
117
|
column(name, field) {
|
|
116
|
-
return field.type === "boolean" ? boolean(name) : field.type === "date" ? timestamp(name) : field.type === "number" ? field.bigint ? bigint(name, { mode: "number" }) : integer(name) : field.type === "string" ? text(name) : field.type === "string[]" ? text(name).array() : field.type === "number[]" ? integer(name).array() : jsonb(name);
|
|
118
|
+
return field.type === "boolean" ? boolean(name) : field.type === "date" ? timestamp(name) : field.type === "number" ? field.bigint ? bigint(name, { mode: "number" }) : integer(name) : field.type === "string" ? uuidIds && field.references?.field === "id" ? uuid(name) : text(name) : field.type === "string[]" ? text(name).array() : field.type === "number[]" ? (field.bigint ? bigint(name, { mode: "number" }) : integer(name)).array() : jsonb(name);
|
|
117
119
|
},
|
|
118
|
-
id: () => text("id").primaryKey(),
|
|
119
120
|
index: (name, unique, columns) => (unique ? uniqueIndex(name) : index(name)).on(...columns),
|
|
120
121
|
foreignKey: (name, columns, foreignColumns, actions) => foreignKey({
|
|
121
122
|
name,
|
|
@@ -125,10 +126,13 @@ const postgresDialect = {
|
|
|
125
126
|
now: sql`now()`,
|
|
126
127
|
nowMs: sql`(extract(epoch from now()) * 1000)::bigint`,
|
|
127
128
|
raw: (sqlText) => sql.raw(sqlText),
|
|
128
|
-
table: (name, columns, extras) => pgTable(name,
|
|
129
|
-
|
|
129
|
+
table: (name, columns, extras) => pgTable(name, {
|
|
130
|
+
id: uuidIds ? uuid("id").defaultRandom().primaryKey() : text("id").primaryKey(),
|
|
131
|
+
...columns
|
|
132
|
+
}, (table) => extras(table))
|
|
133
|
+
});
|
|
130
134
|
const authSqliteSchema = buildTables(sqliteDialect, authTableSpecs);
|
|
131
|
-
const authPostgresSchema = buildTables(postgresDialect, authTableSpecs);
|
|
135
|
+
const authPostgresSchema = buildTables(postgresDialect(false), authTableSpecs);
|
|
132
136
|
/**
|
|
133
137
|
* The Better Auth tables for SQLite, libSQL, and Cloudflare D1, with the plugins and additional fields of `options`. The
|
|
134
138
|
* Auth Vite plugin writes a module that calls it when the Auth Definition adds fields or imports a plugin of
|
|
@@ -141,8 +145,11 @@ const authPostgresSchema = buildTables(postgresDialect, authTableSpecs);
|
|
|
141
145
|
function createAuthSqliteSchema(options, existing) {
|
|
142
146
|
return buildTables(sqliteDialect, resolveAuthTableSpecs(options), existing);
|
|
143
147
|
}
|
|
144
|
-
/**
|
|
148
|
+
/**
|
|
149
|
+
* The Better Auth tables for Postgres, with the plugins and additional fields of `options`, typed from its literal. With
|
|
150
|
+
* `generateId: "uuid"`, each `id` is `uuid` with a `gen_random_uuid()` default, and each column that references one is `uuid`.
|
|
151
|
+
*/
|
|
145
152
|
function createAuthPostgresSchema(options) {
|
|
146
|
-
return buildTables(postgresDialect, resolveAuthTableSpecs(options));
|
|
153
|
+
return buildTables(postgresDialect(options.generateId === "uuid"), resolveAuthTableSpecs(options));
|
|
147
154
|
}
|
|
148
155
|
export { authPluginSchemas, authPostgresSchema, authSqliteSchema, authTableSpecs, createAuthPostgresSchema, createAuthSqliteSchema, resolveAuthTableSpecs };
|