@vite-hub/auth 0.7.0 → 0.9.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 +59 -6
- package/dist/{abilities-CfvuGrBv.d.ts → abilities-6LE7VSdN.d.ts} +1 -1
- package/dist/abilities.d.ts +1 -1
- package/dist/{ability-error-OKoyOwPM.js → ability-error-Ccm5Iy4F.js} +1 -1
- package/dist/{access-pages-Bej95blM.js → access-pages-lQGfRvfL.js} +1 -4
- package/dist/{admin-claim-code-C3X_U43x.js → admin-claim-code-CMa0eRRm.js} +0 -1
- package/dist/agent.js +11 -11
- package/dist/{application-path-zKi7NrvK.js → application-path-LMc_ptL9.js} +0 -2
- package/dist/{auth-instance-5RSiFTDC.js → auth-instance-0PTsOttV.js} +41 -57
- package/dist/bun-sqlite.d.ts +0 -2
- package/dist/cli.js +2 -2
- package/dist/client-extension-BVBVUqa1.d.ts +33 -0
- package/dist/client-request-B1DCz3a9.js +29 -0
- package/dist/{console-runtime-Bg_PAl7e.js → console-runtime-BlOx9hWC.js} +3 -19
- package/dist/{console-runtime-XcplYv4R.d.ts → console-runtime-D2FUATXQ.d.ts} +1 -1
- 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-CPhnGap9.js +36 -0
- package/dist/{database-schema-options-CCQsNhjc.js → database-schema-options-BQyynyhw.js} +1 -1
- package/dist/database.d.ts +1 -1
- package/dist/database.js +22 -11
- package/dist/{definition-DeEeqTLC.js → definition-CvmvHaQT.js} +4 -12
- package/dist/{error-diagnostics-DkzL9ltR.js → error-diagnostics-BpQy1iIO.js} +35 -4
- package/dist/{events-BUaoHFoC.js → events-aP_Rz_gx.js} +1 -1
- package/dist/extension-B35v_o1u.js +133 -0
- package/dist/extension-C2giF7w2.d.ts +59 -0
- package/dist/forward.d.ts +0 -5
- package/dist/forward.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/internal/server.d.ts +3 -3
- package/dist/internal/server.js +5 -5
- package/dist/{mcp-config-C7srUMIZ.js → mcp-config-DYlTXmr6.js} +9 -1
- package/dist/{mcp-token-DG1jmw4o.d.ts → mcp-token-CxpopXmK.d.ts} +4 -2
- package/dist/{mcp-token-DgveSGEl.js → mcp-token-i-8NMulH.js} +28 -6
- package/dist/mcp.d.ts +2 -7
- package/dist/mcp.js +26 -7
- package/dist/{members-CRlYyxVk.js → members-USm08YwK.js} +4 -6
- package/dist/nuxt.d.ts +4 -14
- package/dist/nuxt.js +29 -61
- package/dist/{own-access-BvVUjaeL.d.ts → own-access-B7VRd92K.d.ts} +1 -1
- package/dist/presets.js +1 -1
- package/dist/{request-Dpq7GO8B.js → request-CdlcvqVc.js} +0 -1
- 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 +5 -4
- package/dist/runtime/vue-nuxt.js +2 -18
- package/dist/schema.d.ts +32 -17
- package/dist/schema.js +39 -16
- package/dist/{server-1G_BbfBD.d.ts → server-4_EXgXFn.d.ts} +25 -8
- package/dist/{server-iQNOXyfS.js → server-CZR2dVVp.js} +43 -352
- package/dist/{server-B8kTFrHP.d.ts → server-DAIBBKbR.d.ts} +3 -2
- package/dist/server.d.ts +3 -3
- package/dist/server.js +4 -4
- package/dist/{session-cookies-DN0svCKj.js → session-cookies-CfXdF1yd.js} +5 -33
- package/dist/{set-cookie-CMB3t4NF.js → set-cookie-BYZslovs.js} +1 -1
- package/dist/{table-specs-C3-bLOSF.js → table-specs-Cvjc_Ccs.js} +28 -2
- package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-VYAy_jJ7.d.ts} +5 -2
- package/dist/test.d.ts +1 -1
- package/dist/test.js +2 -2
- package/dist/{types-BmRGse4l.d.ts → types-DakualFJ.d.ts} +20 -4
- package/dist/vite-CZ_Z6IR3.d.ts +28 -0
- package/dist/{vite-GRzej8Cs.js → vite-DVvWaN3D.js} +652 -301
- package/dist/vite.d.ts +35 -17
- package/dist/vite.js +1 -1
- package/dist/vue.d.ts +4 -34
- package/dist/vue.js +40 -66
- package/package.json +9 -8
- package/dist/client-request-BzMKtfCY.js +0 -52
- package/dist/database-options-DE9lMwu1.js +0 -28
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import { t as invariant } from "./invariant-Dj2R1eMr.js";
|
|
2
2
|
import { t as createNitroServerKit } from "./nitro-kit-BumWIKa5.js";
|
|
3
|
-
import { t as isRecord
|
|
4
|
-
import { r as resolveAccessRoutePath, t as accessRouteSyntaxError } from "./application-path-
|
|
5
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
6
|
-
import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-
|
|
7
|
-
import { a as
|
|
8
|
-
import {
|
|
3
|
+
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
4
|
+
import { r as resolveAccessRoutePath, t as accessRouteSyntaxError } from "./application-path-LMc_ptL9.js";
|
|
5
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
|
|
6
|
+
import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-lQGfRvfL.js";
|
|
7
|
+
import { a as differentFieldAttributes, c as mergeFieldDeclarations, i as authExtensionKeys, n as assertUniquePluginIds, o as effectiveFieldAttributes, r as authCoreModels } from "./extension-B35v_o1u.js";
|
|
8
|
+
import { a as authDatabasePlacementError, n as authDatabaseAdditionalFieldsError, o as authDatabaseSchemaError, s as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-CPhnGap9.js";
|
|
9
|
+
import { a as resolveAuthTableSpecs, r as authSqlName, t as authJoinRelations } from "./table-specs-Cvjc_Ccs.js";
|
|
9
10
|
import { n as resetAuth } from "./runtime-state-C0Rd1W4m.js";
|
|
10
|
-
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
11
|
+
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
11
12
|
import { basename, dirname, join, parse, relative, resolve } from "node:path";
|
|
12
13
|
import { fileURLToPath } from "node:url";
|
|
13
14
|
import { tmpdir } from "node:os";
|
|
14
|
-
import { mkdir, readFile,
|
|
15
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
15
16
|
import { parseSync } from "vite";
|
|
16
17
|
// ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
|
|
17
18
|
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
|
@@ -161,6 +162,20 @@ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
|
|
|
161
162
|
* Later entries are Nuxt layers in Nuxt priority order.
|
|
162
163
|
*/
|
|
163
164
|
const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
|
|
165
|
+
const VITEHUB_NUXT_AUTH_DISCOVERY = "__vitehubNuxtAuthDiscovery";
|
|
166
|
+
function resolveNuxtAuthDiscovery(options) {
|
|
167
|
+
const appDir = options.srcDir;
|
|
168
|
+
const appRoot = options.rootDir && resolve(options.rootDir);
|
|
169
|
+
return {
|
|
170
|
+
appDir,
|
|
171
|
+
layerAppDirs: (options._layers ?? []).flatMap((layer) => {
|
|
172
|
+
const root = layer.config?.rootDir ?? layer.cwd;
|
|
173
|
+
const source = layer.config?.srcDir ?? layer.cwd ?? root;
|
|
174
|
+
return source && (!root || resolve(root) !== appRoot) ? [resolve(source)] : [];
|
|
175
|
+
}),
|
|
176
|
+
layerAliases: Object.fromEntries(Object.entries(options.alias ?? {}).filter(([name]) => name.startsWith("#layers/")))
|
|
177
|
+
};
|
|
178
|
+
}
|
|
164
179
|
/**
|
|
165
180
|
* Lists the server directory of the application and of each Nuxt layer it extends.
|
|
166
181
|
* The application comes first. Layers follow in Nuxt priority order, like Nuxt's own Nitro scan directories.
|
|
@@ -253,7 +268,6 @@ const methodOrder = [
|
|
|
253
268
|
"GET",
|
|
254
269
|
"HEAD"
|
|
255
270
|
];
|
|
256
|
-
/** h3 applies the GET rules of a pattern to HEAD requests too. */
|
|
257
271
|
function appliesTo(entry, method) {
|
|
258
272
|
return !entry.method || entry.method === method || method === "HEAD" && entry.method === "GET";
|
|
259
273
|
}
|
|
@@ -330,6 +344,19 @@ function findPackageDir(file) {
|
|
|
330
344
|
function ownModule(importMetaUrl, modulePath) {
|
|
331
345
|
return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
|
|
332
346
|
}
|
|
347
|
+
function createImportPath(fromFile, targetFile) {
|
|
348
|
+
const fromDir = realpathIfExists(dirname$1(fromFile));
|
|
349
|
+
const target = realpathIfExists(targetFile);
|
|
350
|
+
const importPath = relative$1(fromDir, target);
|
|
351
|
+
return importPath.startsWith(".") ? importPath : `./${importPath}`;
|
|
352
|
+
}
|
|
353
|
+
function realpathIfExists(path) {
|
|
354
|
+
try {
|
|
355
|
+
return realpathSync.native(path);
|
|
356
|
+
} catch {
|
|
357
|
+
return resolve$1(path);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
333
360
|
// ../internal/src/definition-catalog.ts
|
|
334
361
|
/** `writeFileIfChangedSync` for async callers. */
|
|
335
362
|
async function writeFileIfChanged(file, contents) {
|
|
@@ -346,7 +373,7 @@ async function flattenPlugins(value, plugins, seen) {
|
|
|
346
373
|
for (const item of value) await flattenPlugins(item, plugins, seen);
|
|
347
374
|
return;
|
|
348
375
|
}
|
|
349
|
-
if (!isRecord
|
|
376
|
+
if (!isRecord(value) || seen.has(value)) return;
|
|
350
377
|
seen.add(value);
|
|
351
378
|
if (isThenable(value)) {
|
|
352
379
|
await flattenPlugins(await value, plugins, seen);
|
|
@@ -365,11 +392,6 @@ async function flattenPluginOptions(plugins) {
|
|
|
365
392
|
return flattened;
|
|
366
393
|
}
|
|
367
394
|
// src/access-route-cache.ts
|
|
368
|
-
/**
|
|
369
|
-
* The rou3 pattern of the paths that the access middleware guards for a route. The middleware matches the path
|
|
370
|
-
* literally, so the pattern escapes every character that rou3 reads as syntax. In rou3, `/**` also matches the path
|
|
371
|
-
* itself.
|
|
372
|
-
*/
|
|
373
395
|
function accessRoutePattern(route, baseURL) {
|
|
374
396
|
const { path, recursive } = resolveAccessRoutePath(route, baseURL);
|
|
375
397
|
const literal = path.replace(/[\\:(){}*?+]/g, "\\$&");
|
|
@@ -443,6 +465,10 @@ function scanModule(source, file = "module.ts") {
|
|
|
443
465
|
source
|
|
444
466
|
};
|
|
445
467
|
}
|
|
468
|
+
/** The source text of a node. */
|
|
469
|
+
function nodeText(module, node) {
|
|
470
|
+
return module.source.slice(node.start, node.end);
|
|
471
|
+
}
|
|
446
472
|
/** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
|
|
447
473
|
function unwrapExpression(node) {
|
|
448
474
|
while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
|
|
@@ -478,16 +504,11 @@ function objectProperties(object) {
|
|
|
478
504
|
value: unwrapExpression(node.value)
|
|
479
505
|
});
|
|
480
506
|
}
|
|
481
|
-
/** The value of a template literal without substitutions. */
|
|
482
507
|
function staticTemplate(node) {
|
|
483
508
|
if (node.expressions.length) return dynamic;
|
|
484
509
|
return node.quasis[0]?.value.cooked ?? dynamic;
|
|
485
510
|
}
|
|
486
511
|
const escapePattern = /\\(u\{[^}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|0\d|[\s\S])/g;
|
|
487
|
-
/**
|
|
488
|
-
* True when a string literal has an escape that strict mode code rejects. The parser recovers from some bad escapes
|
|
489
|
-
* and accepts legacy octal escapes, so the scanner checks them again.
|
|
490
|
-
*/
|
|
491
512
|
function hasInvalidEscape(raw) {
|
|
492
513
|
for (const [, escape = ""] of raw.matchAll(escapePattern)) if (escape.startsWith("u{")) {
|
|
493
514
|
const code = escape.slice(2, -1);
|
|
@@ -594,9 +615,38 @@ function discoverAuthDefinitions(rootDir, options = {}) {
|
|
|
594
615
|
].join("\n") });
|
|
595
616
|
return layerDefinitions;
|
|
596
617
|
}
|
|
597
|
-
/**
|
|
598
|
-
function
|
|
599
|
-
return
|
|
618
|
+
/** The Auth Definitions of Nuxt layers. The first server directory is the application. */
|
|
619
|
+
function discoverLayerAuthDefinitions(serverDirs = []) {
|
|
620
|
+
return existingDefinitions(serverDirs.slice(1).flatMap(serverAuthCandidates));
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Finds the Auth client options, `auth.client.ts`, in the Vite root, which is `app/` in a Nuxt app. Without an
|
|
624
|
+
* application file, one Nuxt layer can supply its `app/auth.client.ts`. A layer file that Auth would not load fails
|
|
625
|
+
* discovery.
|
|
626
|
+
*/
|
|
627
|
+
function discoverAuthClient(appDir, options = {}) {
|
|
628
|
+
const clientIn = (directory) => authDefinitionExtensions.map((extension) => resolve(directory, `auth.client${extension}`)).find((file) => existsSync(file));
|
|
629
|
+
const app = clientIn(appDir);
|
|
630
|
+
const layers = [...new Set((options.layerAppDirs ?? []).flatMap((directory) => clientIn(directory) ?? []))].filter((file) => file !== app);
|
|
631
|
+
if (layers.length > (app ? 0 : 1)) throw authErrorDiagnostics.AUTH_LAYER_CLIENT_IGNORED({
|
|
632
|
+
files: layers,
|
|
633
|
+
...app ? { app } : {}
|
|
634
|
+
});
|
|
635
|
+
return app ?? layers[0];
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* The parts of the Auth Definition, `server/auth.extend.ts`: the file of the application first, then the files of
|
|
639
|
+
* Nuxt layers in priority order.
|
|
640
|
+
*/
|
|
641
|
+
function discoverAuthExtensions(rootDir, options = {}) {
|
|
642
|
+
return (options.serverDirs ?? [resolve(rootDir, "server")]).flatMap((serverDir) => authDefinitionExtensions.map((extension) => resolve(serverDir, `auth.extend${extension}`)).find((file) => existsSync(file)) ?? []);
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* The parts of the Auth client options, `auth.client.extend.ts`: the file in the Vite root first, which is `app/` in a
|
|
646
|
+
* Nuxt app, then the `app/auth.client.extend.ts` of Nuxt layers in priority order.
|
|
647
|
+
*/
|
|
648
|
+
function discoverAuthClientExtensions(appDir, options = {}) {
|
|
649
|
+
return [.../* @__PURE__ */ new Set([appDir, ...options.layerAppDirs ?? []])].flatMap((directory) => authDefinitionExtensions.map((extension) => resolve(directory, `auth.client.extend${extension}`)).find((file) => existsSync(file)) ?? []);
|
|
600
650
|
}
|
|
601
651
|
function discoverAuthDefinition(rootDir, options = {}) {
|
|
602
652
|
return discoverAuthDefinitions(rootDir, options)[0];
|
|
@@ -639,6 +689,90 @@ function discoverAuthAbilities(rootDir, options = {}) {
|
|
|
639
689
|
if (found.length > 1) throw authErrorDiagnostics.AUTH_C0060({ message: ["[vitehub] Only one abilities file is allowed. Found:", ...found.map((file) => ` - ${file}`)].join("\n") });
|
|
640
690
|
return found[0];
|
|
641
691
|
}
|
|
692
|
+
// src/config-fields.ts
|
|
693
|
+
const authFieldTypes = /* @__PURE__ */ new Set([
|
|
694
|
+
"boolean",
|
|
695
|
+
"date",
|
|
696
|
+
"json",
|
|
697
|
+
"number",
|
|
698
|
+
"number[]",
|
|
699
|
+
"string",
|
|
700
|
+
"string[]"
|
|
701
|
+
]);
|
|
702
|
+
function readStaticBooleanOption(field, key, label, fail) {
|
|
703
|
+
if (!hasObjectProperty(field, key)) return;
|
|
704
|
+
const value = readStaticBooleanLiteral(readObjectPropertyValue(field, key));
|
|
705
|
+
if (value === void 0) throw fail(`${label}.${key} must be \`true\` or \`false\``);
|
|
706
|
+
return value;
|
|
707
|
+
}
|
|
708
|
+
/** One additional field, read from its object literal: the parts that shape the column. */
|
|
709
|
+
function readAdditionalField(value, key, label, fail = authDatabaseAdditionalFieldsError) {
|
|
710
|
+
const field = objectLiteral(value && unwrapExpression(value));
|
|
711
|
+
if (!field) throw fail(`${label} must be an inline object, such as \`{ type: "string", required: false }\``);
|
|
712
|
+
const typeValue = readObjectPropertyValue(field, "type");
|
|
713
|
+
const unwrappedType = typeValue && unwrapExpression(typeValue);
|
|
714
|
+
const type = unwrappedType?.type === "ArrayExpression" ? "string" : staticString(unwrappedType);
|
|
715
|
+
if (!type || !authFieldTypes.has(type)) throw fail(`${label}.type must be one of ${[...authFieldTypes].map((name) => `"${name}"`).join(", ")}, or a list of strings`);
|
|
716
|
+
const fieldName = readObjectPropertyValue(field, "fieldName");
|
|
717
|
+
if (fieldName && staticString(fieldName) !== key) throw authDatabaseSchemaError(`${label}.fieldName cannot rename the column`);
|
|
718
|
+
const spec = { type };
|
|
719
|
+
if (readStaticBooleanOption(field, "required", label, fail)) spec.required = true;
|
|
720
|
+
if (readStaticBooleanOption(field, "unique", label, fail)) spec.unique = true;
|
|
721
|
+
if (readStaticBooleanOption(field, "index", label, fail)) spec.index = true;
|
|
722
|
+
if (readStaticBooleanOption(field, "bigint", label, fail)) spec.bigint = true;
|
|
723
|
+
const defaultValue = readObjectPropertyValue(field, "defaultValue");
|
|
724
|
+
const staticDefault = defaultValue && staticValue(defaultValue);
|
|
725
|
+
if (typeof staticDefault === "string" || typeof staticDefault === "number" || typeof staticDefault === "boolean") spec.defaultValue = staticDefault;
|
|
726
|
+
const references = readObjectPropertyValue(field, "references");
|
|
727
|
+
if (references) {
|
|
728
|
+
const reference = staticValue(references);
|
|
729
|
+
const model = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.model : void 0;
|
|
730
|
+
const target = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.field : void 0;
|
|
731
|
+
const onDelete = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.onDelete ?? "cascade" : void 0;
|
|
732
|
+
if (typeof model !== "string" || typeof target !== "string" || onDelete !== "cascade" && onDelete !== "set null") throw fail(`${label}.references must be an inline object, such as \`{ model: "user", field: "id", onDelete: "cascade" }\``);
|
|
733
|
+
spec.references = {
|
|
734
|
+
model,
|
|
735
|
+
field: target,
|
|
736
|
+
onDelete
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
return spec;
|
|
740
|
+
}
|
|
741
|
+
/** The `additionalFields` of each core model, which `authDatabase()` adds as columns. */
|
|
742
|
+
function readAuthAdditionalFields(body) {
|
|
743
|
+
const result = {};
|
|
744
|
+
for (const model of authCoreModels) {
|
|
745
|
+
const value = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, model)), "additionalFields");
|
|
746
|
+
if (!value) continue;
|
|
747
|
+
const fields = objectLiteral(unwrapExpression(value));
|
|
748
|
+
if (!fields) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must be an inline object literal, so the Auth Vite plugin can add its columns`);
|
|
749
|
+
const entries = readObjectEntries(fields);
|
|
750
|
+
if (entries.some((entry) => !entry.key)) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must use static keys`);
|
|
751
|
+
if (entries.length) result[model] = Object.fromEntries(entries.map((entry) => [entry.key, readAdditionalField(entry.value, entry.key, `${model}.additionalFields.${entry.key}`)]));
|
|
752
|
+
}
|
|
753
|
+
return Object.keys(result).length ? result : void 0;
|
|
754
|
+
}
|
|
755
|
+
/** Object entries. `key` is empty for spread and computed keys. `value` is undefined for methods and accessors. */
|
|
756
|
+
function readObjectEntries(body) {
|
|
757
|
+
if (!body) return [];
|
|
758
|
+
return objectProperties(body).map((property) => ({
|
|
759
|
+
key: property.computed ? "" : property.key ?? "",
|
|
760
|
+
value: property.node.type === "Property" && property.node.kind === "init" && !property.node.method ? property.value : void 0
|
|
761
|
+
}));
|
|
762
|
+
}
|
|
763
|
+
function readObjectPropertyValue(body, property) {
|
|
764
|
+
return readObjectEntries(body).findLast((entry) => entry.key === property)?.value;
|
|
765
|
+
}
|
|
766
|
+
function hasObjectProperty(body, property) {
|
|
767
|
+
return readObjectEntries(body).some((entry) => entry.key === property);
|
|
768
|
+
}
|
|
769
|
+
function objectLiteral(value) {
|
|
770
|
+
return value?.type === "ObjectExpression" ? value : void 0;
|
|
771
|
+
}
|
|
772
|
+
function readStaticBooleanLiteral(expression) {
|
|
773
|
+
const value = expression && staticValue(expression);
|
|
774
|
+
return typeof value === "boolean" ? value : void 0;
|
|
775
|
+
}
|
|
642
776
|
// src/config.ts
|
|
643
777
|
const authDatabaseModules = /* @__PURE__ */ new Set(["@vite-hub/auth/database", "vite-hub/auth/database"]);
|
|
644
778
|
function readAuthDatabaseImports(module) {
|
|
@@ -652,7 +786,6 @@ function readAuthDatabaseImports(module) {
|
|
|
652
786
|
}
|
|
653
787
|
return names;
|
|
654
788
|
}
|
|
655
|
-
/** The plugin factories whose tables `authDatabase()` adds, by the module that exports them. */
|
|
656
789
|
const authSchemaPluginImports = {
|
|
657
790
|
"better-auth/plugins": {
|
|
658
791
|
admin: "admin",
|
|
@@ -684,10 +817,6 @@ const typeScriptSources = {
|
|
|
684
817
|
".cjs": [".cts"]
|
|
685
818
|
};
|
|
686
819
|
const isFile = (file) => existsSync(file) && statSync(file).isFile();
|
|
687
|
-
/**
|
|
688
|
-
* The file of a relative import, resolved in the order Vite uses: the file itself, the TypeScript source of a `.js`
|
|
689
|
-
* path, the path with each extension, then the `index` file of the folder.
|
|
690
|
-
*/
|
|
691
820
|
function resolveLocalModule(importer, specifier) {
|
|
692
821
|
const path = resolve(dirname(importer), specifier);
|
|
693
822
|
if (isFile(path)) return path;
|
|
@@ -711,7 +840,7 @@ function addBoundNames(pattern, names) {
|
|
|
711
840
|
}
|
|
712
841
|
});
|
|
713
842
|
}
|
|
714
|
-
function readModuleBindings(module) {
|
|
843
|
+
function readModuleBindings(module, layers) {
|
|
715
844
|
const bindings = {
|
|
716
845
|
declarations: /* @__PURE__ */ new Map(),
|
|
717
846
|
imports: /* @__PURE__ */ new Map(),
|
|
@@ -721,7 +850,11 @@ function readModuleBindings(module) {
|
|
|
721
850
|
pluginFactories: /* @__PURE__ */ new Map(),
|
|
722
851
|
pluginNamespaces: /* @__PURE__ */ new Map()
|
|
723
852
|
};
|
|
724
|
-
const localFile = (specifier) =>
|
|
853
|
+
const localFile = (specifier) => {
|
|
854
|
+
if (specifier.startsWith("./") || specifier.startsWith("../")) return resolveLocalModule(module.file, specifier);
|
|
855
|
+
const alias = Object.keys(layers).find((name) => specifier === name || specifier.startsWith(`${name}/`));
|
|
856
|
+
return alias ? resolveLocalModule(module.file, resolve(layers[alias], specifier.slice(alias.length + 1))) : void 0;
|
|
857
|
+
};
|
|
725
858
|
const declare = (name, node) => bindings.declarations.set(name, [...bindings.declarations.get(name) ?? [], node]);
|
|
726
859
|
const readDeclaration = (declaration, exported) => {
|
|
727
860
|
const names = [];
|
|
@@ -784,86 +917,175 @@ function readModuleBindings(module) {
|
|
|
784
917
|
} else readDeclaration(statement, false);
|
|
785
918
|
return bindings;
|
|
786
919
|
}
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
const
|
|
801
|
-
return bindings.pluginFactories.get(callee.name) ?? (imported && imported.imported !== "*" ? exportedFactory(imported.file, imported.imported) : void 0);
|
|
920
|
+
function pluginFunctionScope(scope, factory) {
|
|
921
|
+
const locals = new Map(scope.locals);
|
|
922
|
+
for (const param of factory.params) {
|
|
923
|
+
const names = [];
|
|
924
|
+
addBoundNames(param, names);
|
|
925
|
+
for (const name of names) locals.set(name, void 0);
|
|
926
|
+
}
|
|
927
|
+
if (factory.body?.type === "BlockStatement") for (const statement of factory.body.body) {
|
|
928
|
+
if (statement.type !== "VariableDeclaration") continue;
|
|
929
|
+
for (const declaration of statement.declarations) {
|
|
930
|
+
const names = [];
|
|
931
|
+
addBoundNames(declaration.id, names);
|
|
932
|
+
const value = statement.kind === "const" && declaration.id.type === "Identifier" && declaration.init ? unwrapExpression(declaration.init) : void 0;
|
|
933
|
+
for (const name of names) locals.set(name, value);
|
|
802
934
|
}
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
if (factories) return Object.hasOwn(factories, property) ? factories[property] : void 0;
|
|
808
|
-
const imported = bindings.imports.get(callee.object.name);
|
|
809
|
-
return imported?.imported === "*" ? exportedFactory(imported.file, property) : void 0;
|
|
935
|
+
}
|
|
936
|
+
return {
|
|
937
|
+
module: scope.module,
|
|
938
|
+
locals
|
|
810
939
|
};
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
940
|
+
}
|
|
941
|
+
function readConfiguredPluginFields(definition, options, body, moduleOf, bindingsOf, scan, knownFactory, plugins) {
|
|
942
|
+
const start = readObjectPropertyValue(body, "plugins");
|
|
943
|
+
if (!start) return [];
|
|
944
|
+
const active = /* @__PURE__ */ new Set();
|
|
945
|
+
const resolvingExports = /* @__PURE__ */ new Set();
|
|
946
|
+
function fromExport(file, name, read) {
|
|
947
|
+
const key = `${file}\0${name}`;
|
|
948
|
+
if (resolvingExports.has(key)) return;
|
|
949
|
+
resolvingExports.add(key);
|
|
950
|
+
try {
|
|
951
|
+
const bindings = bindingsOf(file);
|
|
952
|
+
const target = bindings.exports.get(name);
|
|
953
|
+
if (target && "file" in target) return fromExport(target.file, target.imported, read);
|
|
954
|
+
if (target && "local" in target) return fromLocal(target.local, { module: moduleOf(file) }, read);
|
|
955
|
+
if (!target && name !== "default") for (const source of bindings.exportAll) {
|
|
956
|
+
const value = fromExport(source, name, read);
|
|
957
|
+
if (value !== void 0) return value;
|
|
958
|
+
}
|
|
959
|
+
} finally {
|
|
960
|
+
resolvingExports.delete(key);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
function fromLocal(name, scope, read) {
|
|
964
|
+
if (scope.locals?.has(name)) return visit(scope.locals.get(name), scope, read);
|
|
965
|
+
const bindings = bindingsOf(scope.module.file);
|
|
966
|
+
const imported = bindings.imports.get(name);
|
|
967
|
+
if (imported && imported.imported !== "*") return fromExport(imported.file, imported.imported, read);
|
|
968
|
+
const declaration = bindings.declarations.get(name)?.[0];
|
|
969
|
+
return visit(name === "default" ? defaultExportExpression(scope.module) ?? declaration : declaration?.type === "VariableDeclarator" ? topLevelConstValue(scope.module, name) : declaration, { module: scope.module }, read);
|
|
970
|
+
}
|
|
971
|
+
function visit(node, scope, read) {
|
|
972
|
+
if (!node || active.has(node)) return;
|
|
973
|
+
active.add(node);
|
|
974
|
+
try {
|
|
975
|
+
if (node.type === "Identifier") return fromLocal(node.name, scope, read);
|
|
976
|
+
if (node.type === "MemberExpression" && node.object.type === "Identifier" && !scope.locals?.has(node.object.name)) {
|
|
977
|
+
const imported = bindingsOf(scope.module.file).imports.get(node.object.name);
|
|
978
|
+
const name = staticMemberName(node);
|
|
979
|
+
if (imported?.imported === "*" && name !== void 0) return fromExport(imported.file, name, read);
|
|
980
|
+
}
|
|
981
|
+
if (node.type === "CallExpression" && (node.callee.type === "Identifier" || node.callee.type === "MemberExpression")) {
|
|
982
|
+
const registered = read === readPlugin;
|
|
983
|
+
const known = registered ? knownFactory(node.callee, scope) : void 0;
|
|
984
|
+
if (known) {
|
|
985
|
+
plugins.push(known);
|
|
823
986
|
return;
|
|
824
987
|
}
|
|
988
|
+
return visit(node.callee, scope, (factory, factoryScope) => {
|
|
989
|
+
if (factory.type !== "ArrowFunctionExpression" && factory.type !== "FunctionExpression" && factory.type !== "FunctionDeclaration") return;
|
|
990
|
+
const body = factory.body;
|
|
991
|
+
if (!body) return;
|
|
992
|
+
const end = body.type === "BlockStatement" ? body.body.at(-1) : void 0;
|
|
993
|
+
const value = body.type !== "BlockStatement" ? body : end?.type === "ReturnStatement" ? end.argument ?? void 0 : void 0;
|
|
994
|
+
if (!value || factory.async || "generator" in factory && factory.generator || body.type === "BlockStatement" && !body.body.slice(0, -1).every((statement) => statement.type === "VariableDeclaration" || statement.type === "ExpressionStatement")) {
|
|
995
|
+
if (registered && scan.ownsTables) throw authErrorDiagnostics.AUTH_PLUGIN_SCHEMA_UNREADABLE({
|
|
996
|
+
plugin: nodeText(scope.module, node.callee),
|
|
997
|
+
file: relative(scan.rootDir, factoryScope.module.file),
|
|
998
|
+
detail: "the local factory must return a statically readable plugin object or plugin list"
|
|
999
|
+
});
|
|
1000
|
+
return;
|
|
1001
|
+
}
|
|
1002
|
+
return visit(unwrapExpression(value), pluginFunctionScope(factoryScope, factory), read);
|
|
1003
|
+
});
|
|
825
1004
|
}
|
|
1005
|
+
return read(node, scope);
|
|
1006
|
+
} finally {
|
|
1007
|
+
active.delete(node);
|
|
826
1008
|
}
|
|
827
|
-
references.add(child.name);
|
|
828
|
-
});
|
|
829
|
-
if (needs === "all") {
|
|
830
|
-
const references = /* @__PURE__ */ new Set();
|
|
831
|
-
collectCalls(module.program, references);
|
|
832
|
-
for (const [name, imported] of bindings.imports) if (references.has(name)) needImport(imported);
|
|
833
|
-
for (const target of bindings.exports.values()) if ("file" in target) needImport(target);
|
|
834
|
-
return {
|
|
835
|
-
plugins: [...plugins],
|
|
836
|
-
imports
|
|
837
|
-
};
|
|
838
1009
|
}
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
else if ("file" in target) needImport(target);
|
|
844
|
-
else if ("local" in target) locals.push(target.local);
|
|
1010
|
+
function entries(value, scope, keysOnly = false, unreadable) {
|
|
1011
|
+
const result = visit(value && unwrapExpression(value), scope, (object, objectScope) => object.type === "ObjectExpression" ? objectEntries(object, objectScope, keysOnly, unreadable) : void 0);
|
|
1012
|
+
if (!result && unreadable) throw unreadable();
|
|
1013
|
+
return result;
|
|
845
1014
|
}
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
1015
|
+
function objectEntries(object, scope, keysOnly = false, unreadable) {
|
|
1016
|
+
const result = /* @__PURE__ */ new Map();
|
|
1017
|
+
for (const property of objectProperties(object)) if (property.node.type === "SpreadElement") {
|
|
1018
|
+
const spread = entries(property.node.argument, scope, keysOnly, unreadable);
|
|
1019
|
+
if (spread) for (const [key, entry] of spread) result.set(key, entry);
|
|
1020
|
+
else if (!keysOnly) result.clear();
|
|
1021
|
+
} else if (property.key) {
|
|
1022
|
+
const value = property.node.kind === "init" && !property.node.method ? property.value : void 0;
|
|
1023
|
+
result.set(property.key, {
|
|
1024
|
+
value,
|
|
1025
|
+
scope
|
|
1026
|
+
});
|
|
1027
|
+
} else if (unreadable) throw unreadable();
|
|
1028
|
+
else if (!keysOnly) result.clear();
|
|
1029
|
+
return result;
|
|
855
1030
|
}
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
1031
|
+
const objectAt = (entry, keysOnly = false, unreadable) => entry && entries(entry.value, entry.scope, keysOnly, unreadable);
|
|
1032
|
+
const fields = [];
|
|
1033
|
+
const readPlugin = (node, scope) => {
|
|
1034
|
+
if (node.type === "ArrayExpression") for (const element of node.elements) {
|
|
1035
|
+
const value = element?.type === "SpreadElement" ? element.argument : element;
|
|
1036
|
+
if (value) visit(unwrapExpression(value), scope, readPlugin);
|
|
1037
|
+
}
|
|
1038
|
+
if (node.type !== "ObjectExpression") return;
|
|
1039
|
+
const pluginObject = objectEntries(node, scope);
|
|
1040
|
+
const id = pluginObject.get("id");
|
|
1041
|
+
const plugin = id && visit(id.value && unwrapExpression(id.value), id.scope, (value) => value.type === "Literal" && typeof value.value === "string" ? value.value : void 0);
|
|
1042
|
+
if (!plugin) return;
|
|
1043
|
+
const file = scope.module.file;
|
|
1044
|
+
const unreadable = (detail) => authErrorDiagnostics.AUTH_PLUGIN_SCHEMA_UNREADABLE({
|
|
1045
|
+
plugin,
|
|
1046
|
+
file: relative(scan.rootDir, file),
|
|
1047
|
+
detail
|
|
1048
|
+
});
|
|
1049
|
+
const schema = objectAt(pluginObject.get("schema"), false, scan.ownsTables ? () => unreadable("`schema` must be an inline object literal or resolve to an object with static keys") : void 0);
|
|
1050
|
+
const columns = [];
|
|
1051
|
+
for (const [model, entry] of schema ?? []) {
|
|
1052
|
+
const core = scan.ownsTables && authCoreModels.some((core) => core === model);
|
|
1053
|
+
const label = `schema.${model}.fields`;
|
|
1054
|
+
const invalidFields = () => unreadable(`\`${label}\` must be an inline object literal or resolve to an object with static keys`);
|
|
1055
|
+
const modelFields = objectAt(objectAt(entry, false, core ? invalidFields : void 0)?.get("fields"), !core, core ? invalidFields : void 0);
|
|
1056
|
+
if (core && !modelFields) throw invalidFields();
|
|
1057
|
+
for (const [field, { value, scope: fieldScope }] of modelFields ?? []) {
|
|
1058
|
+
const declaration = authCoreModels.some((coreModel) => coreModel === model) ? visit(value && unwrapExpression(value), fieldScope, (node) => {
|
|
1059
|
+
if (node.type !== "ObjectExpression") return;
|
|
1060
|
+
if (readObjectEntries(node).some((entry) => !entry.key)) {
|
|
1061
|
+
if (core) throw unreadable(`${label}.${field} must have static attributes`);
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
return {
|
|
1065
|
+
attributes: staticFieldAttributes(node),
|
|
1066
|
+
spec: core ? readAdditionalField(node, field, `${label}.${field}`, unreadable) : void 0
|
|
1067
|
+
};
|
|
1068
|
+
}) : void 0;
|
|
1069
|
+
if (core && !declaration) throw unreadable(`${label}.${field} must be an inline object or resolve to one`);
|
|
1070
|
+
columns.push({
|
|
1071
|
+
model,
|
|
1072
|
+
field,
|
|
1073
|
+
...declaration
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
fields.push({
|
|
1078
|
+
plugin,
|
|
1079
|
+
file,
|
|
1080
|
+
fields: columns
|
|
1081
|
+
});
|
|
859
1082
|
};
|
|
1083
|
+
const scope = { module: definition };
|
|
1084
|
+
visit(unwrapExpression(start), options.type === "ArrowFunctionExpression" || options.type === "FunctionExpression" ? pluginFunctionScope(scope, options) : scope, readPlugin);
|
|
1085
|
+
return fields;
|
|
860
1086
|
}
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
* the exports it uses, such as `stripe()` in `src/server/auth-plugins.ts` that returns the plugins of `server/auth.ts`.
|
|
864
|
-
*/
|
|
865
|
-
function readDefinitionSchemaPlugins(definition) {
|
|
866
|
-
const plugins = /* @__PURE__ */ new Set();
|
|
1087
|
+
function readDefinitionSchemaPlugins(definition, scan, options, body) {
|
|
1088
|
+
const plugins = [];
|
|
867
1089
|
const modules = /* @__PURE__ */ new Map([[definition.file, definition]]);
|
|
868
1090
|
const moduleOf = (file) => {
|
|
869
1091
|
let module = modules.get(file);
|
|
@@ -871,12 +1093,16 @@ function readDefinitionSchemaPlugins(definition) {
|
|
|
871
1093
|
return module;
|
|
872
1094
|
};
|
|
873
1095
|
const bindingsByFile = /* @__PURE__ */ new Map();
|
|
1096
|
+
const bindingsOf = (file) => {
|
|
1097
|
+
let bindings = bindingsByFile.get(file);
|
|
1098
|
+
if (!bindings) bindingsByFile.set(file, bindings = readModuleBindings(moduleOf(file), scan.layers));
|
|
1099
|
+
return bindings;
|
|
1100
|
+
};
|
|
874
1101
|
const exportedFactory = (file, name, seen = /* @__PURE__ */ new Set()) => {
|
|
875
1102
|
const key = `${file}\0${name}`;
|
|
876
1103
|
if (seen.has(key)) return void 0;
|
|
877
1104
|
seen.add(key);
|
|
878
|
-
|
|
879
|
-
if (!bindings) bindingsByFile.set(file, bindings = readModuleBindings(moduleOf(file)));
|
|
1105
|
+
const bindings = bindingsOf(file);
|
|
880
1106
|
const target = bindings.exports.get(name);
|
|
881
1107
|
if (target && "plugin" in target) return target.plugin;
|
|
882
1108
|
if (target && "file" in target) return exportedFactory(target.file, target.imported, seen);
|
|
@@ -891,89 +1117,25 @@ function readDefinitionSchemaPlugins(definition) {
|
|
|
891
1117
|
if (plugin) return plugin;
|
|
892
1118
|
}
|
|
893
1119
|
};
|
|
894
|
-
const
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
const
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
"json",
|
|
913
|
-
"number",
|
|
914
|
-
"number[]",
|
|
915
|
-
"string",
|
|
916
|
-
"string[]"
|
|
917
|
-
]);
|
|
918
|
-
function readStaticBooleanOption(field, key, label) {
|
|
919
|
-
if (!hasObjectProperty(field, key)) return;
|
|
920
|
-
const value = readStaticBooleanLiteral(readObjectPropertyValue(field, key));
|
|
921
|
-
if (value === void 0) throw authDatabaseAdditionalFieldsError(`${label}.${key} must be \`true\` or \`false\``);
|
|
922
|
-
return value;
|
|
923
|
-
}
|
|
924
|
-
/** One additional field, read from its object literal: the parts that shape the column. */
|
|
925
|
-
function readAdditionalField(value, key, label) {
|
|
926
|
-
const field = objectLiteral(value && unwrapExpression(value));
|
|
927
|
-
if (!field) throw authDatabaseAdditionalFieldsError(`${label} must be an inline object, such as \`{ type: "string", required: false }\``);
|
|
928
|
-
const typeValue = readObjectPropertyValue(field, "type");
|
|
929
|
-
const unwrappedType = typeValue && unwrapExpression(typeValue);
|
|
930
|
-
const type = unwrappedType?.type === "ArrayExpression" ? "string" : staticString(unwrappedType);
|
|
931
|
-
if (!type || !authFieldTypes.has(type)) throw authDatabaseAdditionalFieldsError(`${label}.type must be one of ${[...authFieldTypes].map((name) => `"${name}"`).join(", ")}, or a list of strings`);
|
|
932
|
-
const fieldName = readObjectPropertyValue(field, "fieldName");
|
|
933
|
-
if (fieldName && staticString(fieldName) !== key) throw authDatabaseSchemaError(`${label}.fieldName cannot rename the column`);
|
|
934
|
-
const spec = { type };
|
|
935
|
-
if (readStaticBooleanOption(field, "required", label)) spec.required = true;
|
|
936
|
-
if (readStaticBooleanOption(field, "unique", label)) spec.unique = true;
|
|
937
|
-
if (readStaticBooleanOption(field, "index", label)) spec.index = true;
|
|
938
|
-
if (readStaticBooleanOption(field, "bigint", label)) spec.bigint = true;
|
|
939
|
-
const defaultValue = readObjectPropertyValue(field, "defaultValue");
|
|
940
|
-
const staticDefault = defaultValue && staticValue(defaultValue);
|
|
941
|
-
if (typeof staticDefault === "string" || typeof staticDefault === "number" || typeof staticDefault === "boolean") spec.defaultValue = staticDefault;
|
|
942
|
-
const references = readObjectPropertyValue(field, "references");
|
|
943
|
-
if (references) {
|
|
944
|
-
const reference = staticValue(references);
|
|
945
|
-
const model = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.model : void 0;
|
|
946
|
-
const target = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.field : void 0;
|
|
947
|
-
const onDelete = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.onDelete ?? "cascade" : void 0;
|
|
948
|
-
if (typeof model !== "string" || typeof target !== "string" || onDelete !== "cascade" && onDelete !== "set null") throw authDatabaseAdditionalFieldsError(`${label}.references must be an inline object, such as \`{ model: "user", field: "id", onDelete: "cascade" }\``);
|
|
949
|
-
spec.references = {
|
|
950
|
-
model,
|
|
951
|
-
field: target,
|
|
952
|
-
onDelete
|
|
953
|
-
};
|
|
954
|
-
}
|
|
955
|
-
return spec;
|
|
956
|
-
}
|
|
957
|
-
/** The `additionalFields` of each core model, which `authDatabase()` adds as columns. */
|
|
958
|
-
function readAuthAdditionalFields(body) {
|
|
959
|
-
const result = {};
|
|
960
|
-
for (const model of [
|
|
961
|
-
"user",
|
|
962
|
-
"session",
|
|
963
|
-
"account",
|
|
964
|
-
"verification"
|
|
965
|
-
]) {
|
|
966
|
-
const value = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, model)), "additionalFields");
|
|
967
|
-
if (!value) continue;
|
|
968
|
-
const fields = objectLiteral(unwrapExpression(value));
|
|
969
|
-
if (!fields) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must be an inline object literal, so the Auth Vite plugin can add its columns`);
|
|
970
|
-
const entries = readObjectEntries(fields);
|
|
971
|
-
if (entries.some((entry) => !entry.key)) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must use static keys`);
|
|
972
|
-
if (entries.length) result[model] = Object.fromEntries(entries.map((entry) => [entry.key, readAdditionalField(entry.value, entry.key, `${model}.additionalFields.${entry.key}`)]));
|
|
973
|
-
}
|
|
974
|
-
return Object.keys(result).length ? result : void 0;
|
|
1120
|
+
const knownFactory = (callee, scope) => {
|
|
1121
|
+
const bindings = bindingsOf(scope.module.file);
|
|
1122
|
+
if (callee.type === "Identifier" && !scope.locals?.has(callee.name)) {
|
|
1123
|
+
const imported = bindings.imports.get(callee.name);
|
|
1124
|
+
return bindings.pluginFactories.get(callee.name) ?? (imported && imported.imported !== "*" ? exportedFactory(imported.file, imported.imported) : void 0);
|
|
1125
|
+
}
|
|
1126
|
+
if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || scope.locals?.has(callee.object.name)) return;
|
|
1127
|
+
const name = staticMemberName(callee);
|
|
1128
|
+
if (name === void 0) return;
|
|
1129
|
+
const factories = bindings.pluginNamespaces.get(callee.object.name);
|
|
1130
|
+
if (factories) return Object.hasOwn(factories, name) ? factories[name] : void 0;
|
|
1131
|
+
const imported = bindings.imports.get(callee.object.name);
|
|
1132
|
+
if (imported?.imported === "*") return exportedFactory(imported.file, name);
|
|
1133
|
+
};
|
|
1134
|
+
return {
|
|
1135
|
+
plugins,
|
|
1136
|
+
pluginFields: readConfiguredPluginFields(definition, options, body, moduleOf, bindingsOf, scan, knownFactory, plugins)
|
|
1137
|
+
};
|
|
975
1138
|
}
|
|
976
|
-
/** The object that a callback returns, from `() => ({ ... })` or the first `return { ... }` in its body. */
|
|
977
1139
|
function readReturnedObject(callback) {
|
|
978
1140
|
if (callback.type !== "ArrowFunctionExpression") return;
|
|
979
1141
|
if (callback.body.type !== "BlockStatement") {
|
|
@@ -992,7 +1154,6 @@ function readReturnedObject(callback) {
|
|
|
992
1154
|
const value = returned ? unwrapExpression(returned) : void 0;
|
|
993
1155
|
return value?.type === "ObjectExpression" ? value : void 0;
|
|
994
1156
|
}
|
|
995
|
-
/** The value of a top-level `const name = value`, exported or not. */
|
|
996
1157
|
function topLevelConstValue(module, name) {
|
|
997
1158
|
for (const statement of module.program.body) {
|
|
998
1159
|
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
@@ -1000,17 +1161,17 @@ function topLevelConstValue(module, name) {
|
|
|
1000
1161
|
for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier" && declarator.id.name === name) return declarator.init ? unwrapExpression(declarator.init) : void 0;
|
|
1001
1162
|
}
|
|
1002
1163
|
}
|
|
1003
|
-
/**
|
|
1004
|
-
* The exported `defineAuth()` call: `export default defineAuth(...)`, or `export default auth` after a top-level
|
|
1005
|
-
* `const auth: AuthDefinition<...> = defineAuth(...)`. A composite TypeScript project needs that annotation when it
|
|
1006
|
-
* cannot write the inferred type of the Definition (TS7056), as with the Better Auth `apiKey()` plugin.
|
|
1007
|
-
*/
|
|
1008
1164
|
function exportedDefineAuthCall(module) {
|
|
1009
1165
|
const exported = defaultExportExpression(module);
|
|
1010
1166
|
const call = exported?.type === "Identifier" ? topLevelConstValue(module, exported.name) : exported;
|
|
1011
1167
|
return call?.type === "CallExpression" && call.callee.type === "Identifier" && call.callee.name === "defineAuth" ? call : void 0;
|
|
1012
1168
|
}
|
|
1013
|
-
function
|
|
1169
|
+
function readPluginCalls(module, body) {
|
|
1170
|
+
const label = (node) => node.type === "SpreadElement" ? `...${label(node.argument)}` : node.type === "CallExpression" ? `${nodeText(module, node.callee)}()` : node.type === "Identifier" ? node.name : node.type === "ObjectExpression" ? staticString(readObjectPropertyValue(node, "id")) ?? "(object)" : "(expression)";
|
|
1171
|
+
const plugins = readObjectPropertyValue(body, "plugins");
|
|
1172
|
+
return plugins?.type === "ArrayExpression" ? plugins.elements.flatMap((element) => element ? [label(element)] : []) : plugins ? [label(plugins)] : [];
|
|
1173
|
+
}
|
|
1174
|
+
function readDefinitionObjectBody(file, scan) {
|
|
1014
1175
|
const module = scanModule(readFileSync(file, "utf8"), file);
|
|
1015
1176
|
const authDatabase = readAuthDatabaseImports(module);
|
|
1016
1177
|
const call = exportedDefineAuthCall(module);
|
|
@@ -1018,7 +1179,6 @@ function readDefinitionObjectBody(file) {
|
|
|
1018
1179
|
const argument = call.arguments[0];
|
|
1019
1180
|
if (argument === void 0 || argument.type === "SpreadElement") return;
|
|
1020
1181
|
const options = unwrapExpression(argument);
|
|
1021
|
-
const plugins = readDefinitionSchemaPlugins(module);
|
|
1022
1182
|
if (hasObjectProperty(objectLiteral(options) ?? readReturnedObject(options), "runtime")) throw authErrorDiagnostics.AUTH_C0039({ message: "`defineAuth()` no longer takes `runtime`. Pass one callback that returns all options, so no option replaces another." });
|
|
1023
1183
|
if (options.type === "ObjectExpression") {
|
|
1024
1184
|
assertAuthDatabasePlacement(options, options, authDatabase);
|
|
@@ -1026,7 +1186,12 @@ function readDefinitionObjectBody(file) {
|
|
|
1026
1186
|
authDatabase,
|
|
1027
1187
|
body: options,
|
|
1028
1188
|
callback: false,
|
|
1029
|
-
|
|
1189
|
+
file,
|
|
1190
|
+
pluginCalls: readPluginCalls(module, options),
|
|
1191
|
+
...readDefinitionSchemaPlugins(module, {
|
|
1192
|
+
...scan,
|
|
1193
|
+
ownsTables: Boolean(readAuthDatabaseCall(options, authDatabase))
|
|
1194
|
+
}, options, options)
|
|
1030
1195
|
};
|
|
1031
1196
|
}
|
|
1032
1197
|
const returned = readReturnedObject(options);
|
|
@@ -1036,10 +1201,14 @@ function readDefinitionObjectBody(file) {
|
|
|
1036
1201
|
authDatabase,
|
|
1037
1202
|
body: returned,
|
|
1038
1203
|
callback: true,
|
|
1039
|
-
|
|
1204
|
+
file,
|
|
1205
|
+
pluginCalls: readPluginCalls(module, returned),
|
|
1206
|
+
...readDefinitionSchemaPlugins(module, {
|
|
1207
|
+
...scan,
|
|
1208
|
+
ownsTables: Boolean(readAuthDatabaseCall(returned, authDatabase))
|
|
1209
|
+
}, options, returned)
|
|
1040
1210
|
};
|
|
1041
1211
|
}
|
|
1042
|
-
/** Owned tables must have the same target in every request and in the build-time contribution. */
|
|
1043
1212
|
function assertAuthDatabasePlacement(options, body, names) {
|
|
1044
1213
|
const calls = [];
|
|
1045
1214
|
walk(options, (node) => {
|
|
@@ -1056,29 +1225,11 @@ function assertAuthDatabasePlacement(options, body, names) {
|
|
|
1056
1225
|
const unconditional = options.body.body.some((statement) => statement.type === "ReturnStatement" && statement.argument && unwrapExpression(statement.argument) === body);
|
|
1057
1226
|
if (returns !== 1 || !unconditional) throw authDatabasePlacementError();
|
|
1058
1227
|
}
|
|
1059
|
-
|
|
1060
|
-
if (generateId) assertAuthDatabaseIdStrategy(staticValue(generateId));
|
|
1061
|
-
}
|
|
1062
|
-
/** Object entries. `key` is empty for spread and computed keys. `value` is undefined for methods and accessors. */
|
|
1063
|
-
function readObjectEntries(body) {
|
|
1064
|
-
if (!body) return [];
|
|
1065
|
-
return objectProperties(body).map((property) => ({
|
|
1066
|
-
key: property.computed ? "" : property.key ?? "",
|
|
1067
|
-
value: property.node.type === "Property" && property.node.kind === "init" && !property.node.method ? property.value : void 0
|
|
1068
|
-
}));
|
|
1228
|
+
assertAuthDatabaseIdStrategy(readAuthGenerateId(body));
|
|
1069
1229
|
}
|
|
1070
|
-
function
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
function hasObjectProperty(body, property) {
|
|
1074
|
-
return readObjectEntries(body).some((entry) => entry.key === property);
|
|
1075
|
-
}
|
|
1076
|
-
function objectLiteral(value) {
|
|
1077
|
-
return value?.type === "ObjectExpression" ? value : void 0;
|
|
1078
|
-
}
|
|
1079
|
-
function readStaticBooleanLiteral(expression) {
|
|
1080
|
-
const value = expression && staticValue(expression);
|
|
1081
|
-
return typeof value === "boolean" ? value : void 0;
|
|
1230
|
+
function readAuthGenerateId(body) {
|
|
1231
|
+
const generateId = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, "advanced")), "database")), "generateId");
|
|
1232
|
+
return generateId && staticValue(generateId);
|
|
1082
1233
|
}
|
|
1083
1234
|
function readStaticStringProperty(body, property, label) {
|
|
1084
1235
|
if (!hasObjectProperty(body, property)) return;
|
|
@@ -1155,7 +1306,6 @@ function readAuthAccessPublicConfig(body) {
|
|
|
1155
1306
|
return route;
|
|
1156
1307
|
});
|
|
1157
1308
|
}
|
|
1158
|
-
/** `access.signIn` and `access.afterSignIn`, which the Nuxt page guard reads at build time, like `basePath`. */
|
|
1159
1309
|
function readAuthAccessSignInConfig(body) {
|
|
1160
1310
|
const access = objectLiteral(readObjectPropertyValue(body, "access"));
|
|
1161
1311
|
if (!access) return {};
|
|
@@ -1176,7 +1326,6 @@ function readAuthAccessSignInConfig(body) {
|
|
|
1176
1326
|
}
|
|
1177
1327
|
return resolved;
|
|
1178
1328
|
}
|
|
1179
|
-
/** The build reads only the first return of a callback, so access.pages in any other branch would go unguarded. */
|
|
1180
1329
|
function assertOneReturnWithPages(options) {
|
|
1181
1330
|
if (options.type !== "ArrowFunctionExpression" || options.body.type !== "BlockStatement") return;
|
|
1182
1331
|
const returned = [];
|
|
@@ -1193,7 +1342,6 @@ function assertOneReturnWithPages(options) {
|
|
|
1193
1342
|
};
|
|
1194
1343
|
if (returned.length > 1 && returned.some(declaresPages)) throw authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: "A `defineAuth()` callback that sets access.pages must have one `return`, so that the build reads the same pages as every request." });
|
|
1195
1344
|
}
|
|
1196
|
-
/** `access.pages`, which the Nuxt module turns into route rules at build time, like `access.signIn`. */
|
|
1197
1345
|
function readAuthAccessPagesConfig(body) {
|
|
1198
1346
|
if (!hasObjectProperty(body, "access")) return {};
|
|
1199
1347
|
const expression = readObjectPropertyValue(body, "access");
|
|
@@ -1210,7 +1358,6 @@ function readAuthAccessPagesConfig(body) {
|
|
|
1210
1358
|
assertAuthPages(pages);
|
|
1211
1359
|
return { pages };
|
|
1212
1360
|
}
|
|
1213
|
-
/** `components.prefix`, which the Nuxt module reads at build time to name `<AuthPermission>`, like `basePath`. */
|
|
1214
1361
|
function readAuthComponentsConfig(body) {
|
|
1215
1362
|
if (!hasObjectProperty(body, "components")) return;
|
|
1216
1363
|
const components = objectLiteral(readObjectPropertyValue(body, "components"));
|
|
@@ -1220,45 +1367,154 @@ function readAuthComponentsConfig(body) {
|
|
|
1220
1367
|
if (!prefix?.trim() || prefix !== prefix.trim()) throw authErrorDiagnostics.AUTH_COMPONENTS_INVALID();
|
|
1221
1368
|
return { prefix };
|
|
1222
1369
|
}
|
|
1223
|
-
/** The `authDatabase()` call of the `database` option, or undefined for any other value. */
|
|
1224
1370
|
function readAuthDatabaseCall(body, authDatabase) {
|
|
1225
1371
|
const value = readObjectPropertyValue(body, "database");
|
|
1226
1372
|
const expression = value && unwrapExpression(value);
|
|
1227
1373
|
return expression?.type === "CallExpression" && expression.callee.type === "Identifier" && authDatabase.has(expression.callee.name) ? expression : void 0;
|
|
1228
1374
|
}
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1375
|
+
function readAuthExtension(file, scan) {
|
|
1376
|
+
const module = scanModule(readFileSync(file, "utf8"), file);
|
|
1377
|
+
const invalid = (option) => authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({
|
|
1378
|
+
file: relative(scan.rootDir, file),
|
|
1379
|
+
option
|
|
1380
|
+
});
|
|
1381
|
+
const call = defaultExportExpression(module);
|
|
1382
|
+
const argument = call?.type === "CallExpression" && call.callee.type === "Identifier" && call.callee.name === "extendAuth" ? call.arguments[0] : void 0;
|
|
1383
|
+
const body = argument && argument.type !== "SpreadElement" ? objectLiteral(unwrapExpression(argument)) : void 0;
|
|
1384
|
+
if (!body) throw invalid();
|
|
1385
|
+
const outside = (object, allowed) => readObjectEntries(object).find((entry) => !allowed(entry.key));
|
|
1386
|
+
const option = outside(body, (key) => authExtensionKeys.has(key));
|
|
1387
|
+
if (option) throw invalid(option.key || "...");
|
|
1388
|
+
if (hasObjectProperty(body, "user")) {
|
|
1389
|
+
const user = objectLiteral(readObjectPropertyValue(body, "user"));
|
|
1390
|
+
const userOption = user ? outside(user, (key) => key === "additionalFields") : void 0;
|
|
1391
|
+
if (!user || userOption) throw invalid(`user.${userOption?.key || "..."}`);
|
|
1392
|
+
}
|
|
1393
|
+
return {
|
|
1394
|
+
file,
|
|
1395
|
+
body,
|
|
1396
|
+
pluginCalls: readPluginCalls(module, body),
|
|
1397
|
+
...readDefinitionSchemaPlugins(module, scan, body, body),
|
|
1398
|
+
additionalFields: readAuthAdditionalFields(body)
|
|
1399
|
+
};
|
|
1400
|
+
}
|
|
1401
|
+
const pluginIdOf = (plugin) => plugin.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
1402
|
+
function staticFieldAttributes(field) {
|
|
1403
|
+
return effectiveFieldAttributes(Object.fromEntries(readObjectEntries(field).map((entry) => [entry.key, entry.value ? staticValue(entry.value) : dynamic])));
|
|
1404
|
+
}
|
|
1405
|
+
function staticOptionFieldDeclarations(source, rootDir) {
|
|
1406
|
+
return authCoreModels.flatMap((model) => {
|
|
1407
|
+
return readObjectEntries(objectLiteral(readObjectPropertyValue(objectLiteral(readObjectPropertyValue(source.body, model)), "additionalFields"))).flatMap(({ key, value }) => {
|
|
1408
|
+
const attributes = objectLiteral(value);
|
|
1409
|
+
return key && attributes && readObjectEntries(attributes).every((entry) => entry.key) ? [{
|
|
1410
|
+
model,
|
|
1411
|
+
field: key,
|
|
1412
|
+
file: relative(rootDir, source.file),
|
|
1413
|
+
attributes: staticFieldAttributes(attributes)
|
|
1414
|
+
}] : [];
|
|
1415
|
+
});
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
function readAuthTablesConfig(definition, extensions, rootDir) {
|
|
1419
|
+
const { authDatabase, body } = definition;
|
|
1235
1420
|
const call = readAuthDatabaseCall(body, authDatabase);
|
|
1236
|
-
|
|
1237
|
-
const [argument, ...rest] = call.arguments;
|
|
1421
|
+
const [argument, ...rest] = call?.arguments ?? [];
|
|
1238
1422
|
const name = argument === void 0 ? "default" : argument.type === "SpreadElement" || rest.length ? void 0 : staticString(argument);
|
|
1239
1423
|
if (name === void 0 || !name || name !== name.trim()) throw authErrorDiagnostics.AUTH_C0052({ message: "`authDatabase()` takes the Database name as one inline string literal, such as `authDatabase(\"content\")`, or no argument for the `default` Database." });
|
|
1240
|
-
const
|
|
1424
|
+
const sources = [{
|
|
1425
|
+
...definition,
|
|
1426
|
+
additionalFields: call ? readAuthAdditionalFields(body) : void 0
|
|
1427
|
+
}, ...extensions];
|
|
1428
|
+
const file = (source) => relative(rootDir, source.file);
|
|
1429
|
+
assertUniquePluginIds(sources.map((source) => ({
|
|
1430
|
+
file: file(source),
|
|
1431
|
+
ids: [...source.plugins.map(pluginIdOf), ...source.pluginFields.map((written) => written.plugin)]
|
|
1432
|
+
})));
|
|
1433
|
+
mergeFieldDeclarations(sources.flatMap((source) => [...staticOptionFieldDeclarations(source, rootDir), ...source.pluginFields.flatMap((written) => written.fields.flatMap(({ model, field, attributes }) => attributes ? [{
|
|
1434
|
+
model,
|
|
1435
|
+
field,
|
|
1436
|
+
file: file(written),
|
|
1437
|
+
attributes
|
|
1438
|
+
}] : []))]), (left, right) => differentFieldAttributes(left, right).filter((key) => left[key] !== dynamic && right[key] !== dynamic));
|
|
1439
|
+
const mergedFields = mergeFieldDeclarations(sources.flatMap((source) => [...Object.entries(source.additionalFields ?? {}).flatMap(([model, fields]) => Object.entries(fields).map(([field, attributes]) => ({
|
|
1440
|
+
model,
|
|
1441
|
+
field,
|
|
1442
|
+
file: file(source),
|
|
1443
|
+
attributes
|
|
1444
|
+
}))), ...source.pluginFields.flatMap((written) => written.fields.flatMap(({ model, field, spec }) => spec ? [{
|
|
1445
|
+
model,
|
|
1446
|
+
field,
|
|
1447
|
+
file: file(written),
|
|
1448
|
+
attributes: spec
|
|
1449
|
+
}] : []))]));
|
|
1450
|
+
if (!call) return false;
|
|
1451
|
+
const plugins = [...new Set(sources.flatMap((source) => source.plugins))].sort();
|
|
1452
|
+
const existing = resolveAuthTableSpecs({ plugins });
|
|
1453
|
+
for (const written of sources.flatMap((source) => source.pluginFields)) for (const { model, field, spec } of written.fields) {
|
|
1454
|
+
const column = existing[model]?.fields[field];
|
|
1455
|
+
if (!spec || !column) continue;
|
|
1456
|
+
const attributes = differentFieldAttributes(spec, column).filter((key) => Object.hasOwn(spec, key));
|
|
1457
|
+
if (attributes.length) throw authErrorDiagnostics.AUTH_PLUGIN_SCHEMA_UNREADABLE({
|
|
1458
|
+
plugin: written.plugin,
|
|
1459
|
+
file: file(written),
|
|
1460
|
+
detail: `${model}.${field} cannot change existing column attributes: ${attributes.join(", ")}`
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
const additionalFields = Object.keys(mergedFields).length ? mergedFields : void 0;
|
|
1464
|
+
const uuidIds = readAuthGenerateId(body) === "uuid";
|
|
1241
1465
|
const schema = {
|
|
1242
1466
|
...plugins.length ? { plugins } : {},
|
|
1243
|
-
...additionalFields ? { additionalFields } : {}
|
|
1467
|
+
...additionalFields ? { additionalFields } : {},
|
|
1468
|
+
...uuidIds ? { generateId: "uuid" } : {}
|
|
1244
1469
|
};
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1470
|
+
const specs = resolveAuthTableSpecs(schema);
|
|
1471
|
+
for (const written of sources.flatMap((source) => source.pluginFields)) {
|
|
1472
|
+
const missing = written.fields.filter(({ model, field }) => Object.hasOwn(specs, model) && !Object.hasOwn(specs[model].fields, field)).map(({ model, field }) => `${model}.${field}`);
|
|
1473
|
+
if (missing.length) throw authErrorDiagnostics.AUTH_PLUGIN_FIELD_NOT_IN_SCHEMA({
|
|
1474
|
+
plugin: written.plugin,
|
|
1475
|
+
file: file(written),
|
|
1476
|
+
fields: missing
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
1479
|
+
return plugins.length || additionalFields || uuidIds ? {
|
|
1248
1480
|
database: name,
|
|
1249
1481
|
schema
|
|
1482
|
+
} : { database: name };
|
|
1483
|
+
}
|
|
1484
|
+
function assertAppKeepsLayerTables(app, serverDirs, scan) {
|
|
1485
|
+
const appSpecs = (database) => app.tables && app.tables.database === database ? resolveAuthTableSpecs(app.tables.schema) : {};
|
|
1486
|
+
for (const layer of discoverLayerAuthDefinitions(serverDirs)) {
|
|
1487
|
+
if (layer.handler === app.handler) continue;
|
|
1488
|
+
const definition = readDefinitionObjectBody(layer.handler, scan);
|
|
1489
|
+
const tables = definition && readAuthTablesConfig(definition, [], scan.rootDir);
|
|
1490
|
+
if (!tables) continue;
|
|
1491
|
+
const kept = appSpecs(tables.database);
|
|
1492
|
+
const dropped = Object.entries(resolveAuthTableSpecs(tables.schema)).flatMap(([model, spec]) => Object.hasOwn(kept, model) ? Object.keys(spec.fields).filter((field) => !Object.hasOwn(kept[model].fields, field)).map((field) => `${model}.${field}`) : [model]);
|
|
1493
|
+
if (dropped.length) throw authErrorDiagnostics.AUTH_LAYER_DEFINITION_REPLACED({
|
|
1494
|
+
app: relative(scan.rootDir, app.handler),
|
|
1495
|
+
layer: relative(scan.rootDir, layer.handler),
|
|
1496
|
+
dropped
|
|
1497
|
+
});
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
function summarizeAuthSource(source, rootDir) {
|
|
1501
|
+
const additional = authCoreModels.flatMap((model) => {
|
|
1502
|
+
const value = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(source.body, model)), "additionalFields");
|
|
1503
|
+
return readObjectEntries(objectLiteral(value && unwrapExpression(value))).map((entry) => `${model}.${entry.key}`);
|
|
1504
|
+
});
|
|
1505
|
+
const written = source.pluginFields.flatMap((plugin) => plugin.fields.flatMap(({ model, field }) => authCoreModels.some((core) => core === model) ? [`${model}.${field}`] : []));
|
|
1506
|
+
return {
|
|
1507
|
+
file: source.file,
|
|
1508
|
+
name: relativeDefinitionFile(rootDir, source.file),
|
|
1509
|
+
plugins: source.pluginCalls,
|
|
1510
|
+
fields: [.../* @__PURE__ */ new Set([...additional, ...written])]
|
|
1250
1511
|
};
|
|
1251
1512
|
}
|
|
1252
|
-
/** Reports `true`, `false`, or an object literal with only `keys`: the removed placement forms, which create no storage. */
|
|
1253
1513
|
function isPlacementLiteral(expression, keys) {
|
|
1254
1514
|
if (readStaticBooleanLiteral(expression) !== void 0) return true;
|
|
1255
1515
|
const object = objectLiteral(expression);
|
|
1256
1516
|
return object !== void 0 && readObjectEntries(object).every((entry) => keys.has(entry.key));
|
|
1257
1517
|
}
|
|
1258
|
-
/**
|
|
1259
|
-
* `database` and `secondaryStorage` take Better Auth adapters only. A static Definition can hold only `authDatabase()` or
|
|
1260
|
-
* `"memory"`.
|
|
1261
|
-
*/
|
|
1262
1518
|
function assertAuthStorageConfig(body, callback, authDatabase) {
|
|
1263
1519
|
const database = readObjectPropertyValue(body, "database");
|
|
1264
1520
|
if (hasObjectProperty(body, "database") && !readAuthDatabaseCall(body, authDatabase) && staticString(database) !== "memory") {
|
|
@@ -1269,24 +1525,57 @@ function assertAuthStorageConfig(body, callback, authDatabase) {
|
|
|
1269
1525
|
if (!callback || isPlacementLiteral(secondaryStorage, /* @__PURE__ */ new Set(["store"]))) throw authErrorDiagnostics.AUTH_C0017({ message: "`defineAuth()` secondaryStorage takes only a Better Auth adapter, from the Definition callback. `true` and `{ store }` do not create storage." });
|
|
1270
1526
|
}
|
|
1271
1527
|
}
|
|
1272
|
-
/**
|
|
1273
|
-
* Whether the Auth Definition of the project keeps users in the app Database with `authDatabase()`. ViteHub turns the
|
|
1274
|
-
* Database on for it, as it does for Connections.
|
|
1275
|
-
*/
|
|
1276
1528
|
function usesAuthDatabase(project) {
|
|
1277
1529
|
return Boolean(resolveAuthViteConfig(void 0, project.viteRoot ?? project.projectRoot, project)?.tables);
|
|
1278
1530
|
}
|
|
1531
|
+
/**
|
|
1532
|
+
* The client sources: `auth.client.ts` when the app has one, then each `auth.client.extend.ts` in merge order. A part
|
|
1533
|
+
* must be `export default extendAuthClient({ plugins })`.
|
|
1534
|
+
*/
|
|
1535
|
+
function readAuthClientSources(client, extensions, rootDir) {
|
|
1536
|
+
const read = (file, part) => {
|
|
1537
|
+
const module = scanModule(readFileSync(file, "utf8"), file);
|
|
1538
|
+
const name = relativeDefinitionFile(rootDir, file);
|
|
1539
|
+
const call = defaultExportExpression(module);
|
|
1540
|
+
const argument = call?.type === "CallExpression" ? call.arguments[0] : void 0;
|
|
1541
|
+
const body = argument && argument.type !== "SpreadElement" ? objectLiteral(unwrapExpression(argument)) : void 0;
|
|
1542
|
+
if (part) {
|
|
1543
|
+
if (!body || call?.type !== "CallExpression" || call.callee.type !== "Identifier" || call.callee.name !== "extendAuthClient") throw authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({ file: name });
|
|
1544
|
+
const option = readObjectEntries(body).find((entry) => entry.key !== "plugins");
|
|
1545
|
+
if (option) throw authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({
|
|
1546
|
+
file: name,
|
|
1547
|
+
option: option.key || "..."
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
return {
|
|
1551
|
+
file,
|
|
1552
|
+
name,
|
|
1553
|
+
plugins: readPluginCalls(module, body),
|
|
1554
|
+
fields: []
|
|
1555
|
+
};
|
|
1556
|
+
};
|
|
1557
|
+
return [...client ? [read(client, false)] : [], ...extensions.map((file) => read(file, true))];
|
|
1558
|
+
}
|
|
1279
1559
|
function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {}) {
|
|
1280
1560
|
if (options === false) return;
|
|
1561
|
+
const projectRoot = discovery.projectRoot ?? rootDir;
|
|
1281
1562
|
const found = discoverProjectAuthDefinition({
|
|
1282
|
-
projectRoot
|
|
1563
|
+
projectRoot,
|
|
1283
1564
|
viteRoot: rootDir,
|
|
1284
1565
|
serverDirs: discovery.serverDirs
|
|
1285
1566
|
});
|
|
1286
|
-
|
|
1567
|
+
const extensionFiles = discoverAuthExtensions(found?.rootDir ?? projectRoot, discovery);
|
|
1568
|
+
if (!found) {
|
|
1569
|
+
if (extensionFiles[0]) throw authErrorDiagnostics.AUTH_EXTENSION_WITHOUT_DEFINITION({ file: relative(projectRoot, extensionFiles[0]) });
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1287
1572
|
const { definition } = found;
|
|
1288
1573
|
rootDir = found.rootDir;
|
|
1289
|
-
const
|
|
1574
|
+
const scan = {
|
|
1575
|
+
layers: discovery.layerAliases ?? {},
|
|
1576
|
+
rootDir: projectRoot
|
|
1577
|
+
};
|
|
1578
|
+
const definitionObject = readDefinitionObjectBody(definition.handler, scan);
|
|
1290
1579
|
if (typeof definitionObject === "undefined") throw authErrorDiagnostics.AUTH_C0019({ message: "`defineAuth()` options must be an inline object literal." });
|
|
1291
1580
|
const body = definitionObject.body;
|
|
1292
1581
|
assertStaticObjectKeys(body, "options");
|
|
@@ -1295,6 +1584,15 @@ function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {})
|
|
|
1295
1584
|
const abilities = discoverAuthAbilities(rootDir, { serverDirs: discovery.serverDirs?.slice() });
|
|
1296
1585
|
const publicRoutes = readAuthAccessPublicConfig(body);
|
|
1297
1586
|
const components = readAuthComponentsConfig(body);
|
|
1587
|
+
const extensions = extensionFiles.map((file) => readAuthExtension(file, {
|
|
1588
|
+
...scan,
|
|
1589
|
+
ownsTables: Boolean(readAuthDatabaseCall(body, definitionObject.authDatabase))
|
|
1590
|
+
}));
|
|
1591
|
+
const tables = readAuthTablesConfig(definitionObject, extensions, projectRoot);
|
|
1592
|
+
assertAppKeepsLayerTables({
|
|
1593
|
+
handler: definition.handler,
|
|
1594
|
+
tables
|
|
1595
|
+
}, discovery.serverDirs, scan);
|
|
1298
1596
|
return {
|
|
1299
1597
|
...abilities ? { abilities } : {},
|
|
1300
1598
|
access: {
|
|
@@ -1306,9 +1604,11 @@ function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {})
|
|
|
1306
1604
|
basePath,
|
|
1307
1605
|
...components ? { components } : {},
|
|
1308
1606
|
definition,
|
|
1607
|
+
projectRoot,
|
|
1309
1608
|
rootDir,
|
|
1310
1609
|
route: readAuthRouteConfig(body),
|
|
1311
|
-
|
|
1610
|
+
sources: [definitionObject, ...extensions].map((source) => summarizeAuthSource(source, projectRoot)),
|
|
1611
|
+
tables,
|
|
1312
1612
|
...!definitionObject.callback && !["database", "preset"].some((key) => hasObjectProperty(body, key)) ? { implicitMemory: true } : {}
|
|
1313
1613
|
};
|
|
1314
1614
|
}
|
|
@@ -1381,13 +1681,9 @@ const authTableNames = {
|
|
|
1381
1681
|
passkey: "passkey"
|
|
1382
1682
|
};
|
|
1383
1683
|
// src/existing-tables.ts
|
|
1384
|
-
function isRecord(value) {
|
|
1385
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1386
|
-
}
|
|
1387
1684
|
function strings(value) {
|
|
1388
1685
|
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
1389
1686
|
}
|
|
1390
|
-
/** The snapshot of the newest migration folder, which Drizzle Kit compares the schema with. */
|
|
1391
1687
|
function latestSnapshot(migrationsDir) {
|
|
1392
1688
|
if (!existsSync(migrationsDir)) return;
|
|
1393
1689
|
const latest = readdirSync(migrationsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(join(migrationsDir, entry.name, "snapshot.json"))).map((entry) => entry.name).sort().at(-1);
|
|
@@ -1461,27 +1757,40 @@ const generatedAuthSchema = ".vitehub/auth/schema.ts";
|
|
|
1461
1757
|
const cachedAccessRouteGuardName = "vite-hub/auth-cached-access-route-guard";
|
|
1462
1758
|
const memoryDatabaseGuardName = "vite-hub/auth-memory-database-guard";
|
|
1463
1759
|
const mergeNoExternal = createNoExternalAddition(authPackageName);
|
|
1464
|
-
/**
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1760
|
+
/** The specifiers of the Auth tables. Each host resolves them to the generated module, so an app imports the tables that Auth adds. */
|
|
1761
|
+
const authSchemaSpecifiers = ["@vite-hub/auth/schema", "vite-hub/auth/schema"];
|
|
1762
|
+
/** The generated module of the Auth tables, which `authSchemaSpecifiers` resolve to when the Definition uses `authDatabase()`. */
|
|
1763
|
+
function authSchemaModule(config) {
|
|
1764
|
+
return resolve(config.projectRoot, generatedAuthSchema);
|
|
1765
|
+
}
|
|
1766
|
+
const columnAccess = (name) => /^[A-Za-z_$][\w$]*$/.test(name) ? `.${name}` : `[${JSON.stringify(name)}]`;
|
|
1767
|
+
function renderAuthRelations(schema) {
|
|
1768
|
+
const specs = resolveAuthTableSpecs(schema);
|
|
1769
|
+
const relations = {};
|
|
1770
|
+
for (const { model, key, target, many, from, to } of authJoinRelations(specs)) {
|
|
1771
|
+
if (Object.hasOwn(specs[model]?.fields ?? {}, key)) continue;
|
|
1772
|
+
(relations[model] ??= []).push(` ${key}: r.${many ? "many" : "one"}.${target}({ from: r.${model}${columnAccess(from)}, to: r.${target}${columnAccess(to)} }),`);
|
|
1773
|
+
}
|
|
1774
|
+
return `r => ({\n${Object.entries(relations).map(([model, entries]) => ` ${model}: {\n${entries.join("\n")}\n },`).join("\n")}\n})`;
|
|
1775
|
+
}
|
|
1776
|
+
function renderAuthSchemaModule(file, schema, existing) {
|
|
1469
1777
|
const options = JSON.stringify(schema);
|
|
1778
|
+
const relations = renderAuthRelations(schema);
|
|
1779
|
+
const packageModule = JSON.stringify(createImportPath(file, ownModule(import.meta.url, "schema")).replaceAll("\\", "/"));
|
|
1470
1780
|
return [
|
|
1471
1781
|
"// Generated by the Auth Vite plugin from the plugins and additional fields of the Auth Definition, and from the Auth",
|
|
1472
1782
|
"// tables of the latest migration of the Database.",
|
|
1473
|
-
|
|
1783
|
+
"import { defineRelationsPart } from \"drizzle-orm\"",
|
|
1784
|
+
`import { createAuthPostgresSchema, createAuthSqliteSchema } from ${packageModule}`,
|
|
1474
1785
|
"",
|
|
1786
|
+
`export * from ${packageModule}`,
|
|
1475
1787
|
`export const authSqliteSchema = createAuthSqliteSchema(${options}${existing ? `, ${JSON.stringify(existing)}` : ""})`,
|
|
1476
1788
|
`export const authPostgresSchema = createAuthPostgresSchema(${options})`,
|
|
1789
|
+
`export const authSqliteRelations = defineRelationsPart(authSqliteSchema, ${relations})`,
|
|
1790
|
+
`export const authPostgresRelations = defineRelationsPart(authPostgresSchema, ${relations})`,
|
|
1477
1791
|
""
|
|
1478
1792
|
].join("\n");
|
|
1479
1793
|
}
|
|
1480
|
-
/**
|
|
1481
|
-
* The dialect and the migrations folder of the Database that gets the Auth tables, read from its Definition without
|
|
1482
|
-
* running it. Without a Database Definition, the Database integration adds the implicit `default` Database, which uses
|
|
1483
|
-
* SQLite unless another contribution needs Postgres.
|
|
1484
|
-
*/
|
|
1485
1794
|
async function readTargetDatabase(context, database) {
|
|
1486
1795
|
const { discoverDatabaseDefinitions, getDefaultMigrationsDir, readDatabaseDefinitionDialect } = await import("@vite-hub/database/config");
|
|
1487
1796
|
const { collectDatabaseContributions } = await import("@vite-hub/database/vite");
|
|
@@ -1504,15 +1813,29 @@ async function readTargetDatabase(context, database) {
|
|
|
1504
1813
|
migrationsDir: resolve(context.rootDir, getDefaultMigrationsDir(context.rootDir, target, serverDirs))
|
|
1505
1814
|
};
|
|
1506
1815
|
}
|
|
1507
|
-
/** Lists the Auth Definition as a serializable inspection summary. */
|
|
1508
1816
|
function inspectAuthDefinitions(options) {
|
|
1509
|
-
return summarizeDefinitions(options.projectRoot, discoverAuthDefinitions(options.rootDir, { serverDirs: options.serverDirs }), "server-auth");
|
|
1817
|
+
if (!options.config) return summarizeDefinitions(options.projectRoot, discoverAuthDefinitions(options.rootDir, { serverDirs: options.serverDirs }), "server-auth");
|
|
1818
|
+
const summary = (source, kind) => ({
|
|
1819
|
+
fields: [...source.plugins.length ? [{
|
|
1820
|
+
label: "Plugins",
|
|
1821
|
+
value: source.plugins.join(", ")
|
|
1822
|
+
}] : [], ...source.fields.length ? [{
|
|
1823
|
+
label: "Fields",
|
|
1824
|
+
value: source.fields.join(", ")
|
|
1825
|
+
}] : []],
|
|
1826
|
+
file: source.name,
|
|
1827
|
+
name: "default",
|
|
1828
|
+
source: kind
|
|
1829
|
+
});
|
|
1830
|
+
const { definition, sources } = options.config;
|
|
1831
|
+
return [...sources.map((source, index) => summary(source, index ? "server-auth-extend" : definition.source)), ...(options.client ?? []).map((source) => summary(source, /\.extend\.[cm]?[jt]s$/.test(source.file) ? "auth-client-extend" : "auth-client"))];
|
|
1510
1832
|
}
|
|
1511
1833
|
function createAuthNitroConfig(plugin, options) {
|
|
1512
1834
|
const viteConfig = {
|
|
1513
1835
|
root: options.projectRoot,
|
|
1514
1836
|
nitro: options.nitro,
|
|
1515
|
-
...options.serverDirs ? { [VITEHUB_SERVER_DIRS]: options.serverDirs } : {}
|
|
1837
|
+
...options.serverDirs ? { [VITEHUB_SERVER_DIRS]: options.serverDirs } : {},
|
|
1838
|
+
...options.nuxtDiscovery ? { [VITEHUB_NUXT_AUTH_DISCOVERY]: options.nuxtDiscovery } : {}
|
|
1516
1839
|
};
|
|
1517
1840
|
if (plugin.config && typeof plugin.config === "function") {
|
|
1518
1841
|
const dev = options.nitro.dev === true;
|
|
@@ -1528,8 +1851,14 @@ function createAuthNitroConfig(plugin, options) {
|
|
|
1528
1851
|
function renderAuthDefinitionModule(config, options = { serverEnv: false }) {
|
|
1529
1852
|
if (!config) return "export const definition = undefined\nexport const getAuthApp = () => undefined\nexport default definition\n";
|
|
1530
1853
|
const runtimeServer = JSON.stringify(options.runtimeServer ?? privateAuthImport(options.importBase ?? authPackageName, "runtime/server"));
|
|
1854
|
+
const [source, ...extensions] = config.sources;
|
|
1531
1855
|
return [
|
|
1532
|
-
|
|
1856
|
+
...extensions.length ? [
|
|
1857
|
+
`import authDefinition from ${JSON.stringify(config.definition.handler)}`,
|
|
1858
|
+
...extensions.map((extension, index) => `import extension${index} from ${JSON.stringify(extension.file)}`),
|
|
1859
|
+
`import { applyAuthExtensions } from ${runtimeServer}`,
|
|
1860
|
+
`const definition = applyAuthExtensions(authDefinition, ${JSON.stringify(source?.name)}, [${extensions.map((extension, index) => `{ file: ${JSON.stringify(extension.name)}, extension: extension${index} }`).join(", ")}])`
|
|
1861
|
+
] : [`import definition from ${JSON.stringify(config.definition.handler)}`],
|
|
1533
1862
|
options.testMode ? "export const getAuthApp = () => undefined" : "export { useNitroApp as getAuthApp } from \"nitro/app\"",
|
|
1534
1863
|
...options.serverEnv ? [
|
|
1535
1864
|
`import { setAuthRuntimeEnvResolver } from ${runtimeServer}`,
|
|
@@ -1551,11 +1880,9 @@ async function writeNuxtAuthDefinition(root, config) {
|
|
|
1551
1880
|
}));
|
|
1552
1881
|
return file;
|
|
1553
1882
|
}
|
|
1554
|
-
/** Private Auth entries of the distribution. */
|
|
1555
1883
|
function privateAuthImport(importBase, entry) {
|
|
1556
1884
|
return importBase === "vite-hub/auth" ? ownModule(import.meta.url, entry) : `${importBase}/${entry}`;
|
|
1557
1885
|
}
|
|
1558
|
-
/** The rules of `shared/abilities.ts` for the server and the app, or no rules. */
|
|
1559
1886
|
function renderAuthAbilitiesModule(config) {
|
|
1560
1887
|
return config?.abilities ? `export { default } from ${JSON.stringify(config.abilities)}\n` : "export default {}\n";
|
|
1561
1888
|
}
|
|
@@ -1572,7 +1899,6 @@ function renderAuthServerModule(options = {}) {
|
|
|
1572
1899
|
function renderAuthRouteHandler() {
|
|
1573
1900
|
return [`export { default } from ${JSON.stringify(AUTH_SERVER_ID)}`, ""].join("\n");
|
|
1574
1901
|
}
|
|
1575
|
-
/** `access.public`, and the Auth route: sign-in and the OAuth callback must work without a session. */
|
|
1576
1902
|
function accessPublicRoutes(config) {
|
|
1577
1903
|
return [authRoutePattern(config.basePath), ...config.access.public ?? []];
|
|
1578
1904
|
}
|
|
@@ -1586,7 +1912,6 @@ function renderAuthAccessMiddlewareHandler(config, importBase = authPackageName)
|
|
|
1586
1912
|
""
|
|
1587
1913
|
].join("\n");
|
|
1588
1914
|
}
|
|
1589
|
-
/** A relative `import()` type specifier that resolves under NodeNext and bundler resolution: `auth.ts` becomes `auth.js`. */
|
|
1590
1915
|
function typeImportSpecifier(from, file) {
|
|
1591
1916
|
const path = relative(from, file).replaceAll("\\", "/").replace(/\.([cm]?)ts$/, ".$1js");
|
|
1592
1917
|
return path.startsWith(".") ? path : `./${path}`;
|
|
@@ -1597,15 +1922,29 @@ function authAmbientTypesPath(root) {
|
|
|
1597
1922
|
function authServerTypesPath(root) {
|
|
1598
1923
|
return resolve(root, ".vitehub", "types", "auth-server.d.ts");
|
|
1599
1924
|
}
|
|
1925
|
+
function renderAuthClientModule(client, extensions) {
|
|
1926
|
+
return [
|
|
1927
|
+
client ? `import options from ${JSON.stringify(client)}` : "const options = undefined",
|
|
1928
|
+
...extensions.map((extension, index) => `import extension${index} from ${JSON.stringify(extension.file)}`),
|
|
1929
|
+
"export default options",
|
|
1930
|
+
`export const extensions = [${extensions.map((extension, index) => `{ file: ${JSON.stringify(extension.name)}, extension: extension${index} }`).join(", ")}]`,
|
|
1931
|
+
""
|
|
1932
|
+
].join("\n");
|
|
1933
|
+
}
|
|
1600
1934
|
function renderAuthAmbientTypes(options = { serverEnv: false }) {
|
|
1935
|
+
const importBase = options.importBase ?? authPackageName;
|
|
1936
|
+
const defaultOf = (file) => `typeof import(${JSON.stringify(file)}).default`;
|
|
1937
|
+
const definition = options.definition && (options.extensions?.length ? `import(${JSON.stringify(importBase)}).ExtendedAuthDefinition<${defaultOf(options.definition)}, [${options.extensions.map(defaultOf).join(", ")}]>` : defaultOf(options.definition));
|
|
1938
|
+
const client = options.clientExtensions?.length ? `import(${JSON.stringify(`${importBase}/vue`)}).ExtendedAuthClientOptions<${options.client ? defaultOf(options.client) : "{}"}, [${options.clientExtensions.map(defaultOf).join(", ")}]>` : options.client && defaultOf(options.client);
|
|
1601
1939
|
const entries = [
|
|
1602
|
-
...
|
|
1940
|
+
...definition ? [`definition: ${definition}`] : [],
|
|
1603
1941
|
...options.abilities ? [`abilities: typeof import(${JSON.stringify(options.abilities)}).default`] : [],
|
|
1604
|
-
...
|
|
1942
|
+
...client ? [`client: ${client}`] : [],
|
|
1943
|
+
...options.schema ? [`schema: typeof import(${JSON.stringify(options.schema)})`] : []
|
|
1605
1944
|
];
|
|
1606
1945
|
const registry = entries.length ? [`interface AuthRegistry { ${entries.join("; ")} }`] : [];
|
|
1607
|
-
if (
|
|
1608
|
-
const session = `Pick<import(${JSON.stringify(
|
|
1946
|
+
if (definition) {
|
|
1947
|
+
const session = `Pick<import(${JSON.stringify(importBase)}).AuthAuthorization<{ definition: ${definition} }>, "user" | "session">`;
|
|
1609
1948
|
registry.push(`interface AuthRegistry { sessionResult: ${session} }`);
|
|
1610
1949
|
}
|
|
1611
1950
|
if (options.serverEnv) return [
|
|
@@ -1626,13 +1965,6 @@ function renderAuthAmbientTypes(options = { serverEnv: false }) {
|
|
|
1626
1965
|
""
|
|
1627
1966
|
].join("\n") : "export {}\n";
|
|
1628
1967
|
}
|
|
1629
|
-
/**
|
|
1630
|
-
* The declaration of the virtual module. It stays out of a file with imports, which would make it an augmentation of
|
|
1631
|
-
* a module that must already resolve. When only the bundler resolves `#vitehub/auth/server`, the tsconfig would not
|
|
1632
|
-
* find it and the types of everything that imports the Auth handlers would be `any`. An `export ... from` in this
|
|
1633
|
-
* block must name a package: TypeScript drops one with a file path (TS2439), and the private entry of `vite-hub` is a
|
|
1634
|
-
* file path. A `typeof import()` type takes any path.
|
|
1635
|
-
*/
|
|
1636
1968
|
function renderAuthServerTypes(importBase = authPackageName) {
|
|
1637
1969
|
const serverImport = `${importBase}/server`;
|
|
1638
1970
|
return [
|
|
@@ -1647,13 +1979,17 @@ function renderAuthServerTypes(importBase = authPackageName) {
|
|
|
1647
1979
|
].join("\n");
|
|
1648
1980
|
}
|
|
1649
1981
|
async function refreshAuthGeneratedFiles(root, config, options = {}) {
|
|
1982
|
+
const typeImport = (file) => typeImportSpecifier(dirname(authAmbientTypesPath(root)), file);
|
|
1650
1983
|
await Promise.all([
|
|
1651
1984
|
writeFileIfChanged(resolve(root, generatedAuthAccessMiddlewareHandler), renderAuthAccessMiddlewareHandler(config, options.importBase)),
|
|
1652
1985
|
writeFileIfChanged(authAmbientTypesPath(root), renderAuthAmbientTypes({
|
|
1653
|
-
abilities: config?.abilities &&
|
|
1654
|
-
client: options.client &&
|
|
1655
|
-
|
|
1986
|
+
abilities: config?.abilities && typeImport(config.abilities),
|
|
1987
|
+
client: options.client && typeImport(options.client),
|
|
1988
|
+
clientExtensions: options.clientExtensions?.map((extension) => typeImport(extension.file)),
|
|
1989
|
+
definition: config && typeImport(config.definition.handler),
|
|
1990
|
+
extensions: config?.sources.slice(1).map((extension) => typeImport(extension.file)),
|
|
1656
1991
|
importBase: options.importBase,
|
|
1992
|
+
schema: config?.tables ? typeImportSpecifier(dirname(authAmbientTypesPath(root)), authSchemaModule(config)) : void 0,
|
|
1657
1993
|
serverEnv: Boolean(options.serverEnv)
|
|
1658
1994
|
})),
|
|
1659
1995
|
writeFileIfChanged(authServerTypesPath(root), renderAuthServerTypes(options.importBase)),
|
|
@@ -1671,13 +2007,11 @@ function authRoutePattern(route) {
|
|
|
1671
2007
|
}
|
|
1672
2008
|
const authApplicationBaseURLName = "__VITEHUB_AUTH_APP_BASE_URL__";
|
|
1673
2009
|
const authDevName = "__VITEHUB_AUTH_DEV__";
|
|
1674
|
-
/** Return Nitro `baseURL` when the host serves the app below a path, such as Nuxt `app.baseURL`. */
|
|
1675
2010
|
function nitroApplicationBaseURL(value) {
|
|
1676
2011
|
const nitro = cloneNitroConfig(value);
|
|
1677
2012
|
const baseURL = typeof nitro.baseURL === "string" ? nitro.baseURL : "/";
|
|
1678
2013
|
return baseURL.split("/").some(Boolean) ? baseURL : void 0;
|
|
1679
2014
|
}
|
|
1680
|
-
/** Fails a production build, not the first sign-in. `nuxt prepare` also creates Nitro, but it does not build. */
|
|
1681
2015
|
const memoryDatabaseGuard = {
|
|
1682
2016
|
name: memoryDatabaseGuardName,
|
|
1683
2017
|
setup(nitro) {
|
|
@@ -1734,14 +2068,18 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1734
2068
|
let resolved;
|
|
1735
2069
|
let runtimeConfig;
|
|
1736
2070
|
let clientFile;
|
|
2071
|
+
let clientSources = [];
|
|
2072
|
+
const clientExtensions = () => clientSources.filter((source) => source.file !== clientFile);
|
|
1737
2073
|
let serverDirs;
|
|
2074
|
+
let nuxtDiscovery;
|
|
1738
2075
|
let serverEnv = false;
|
|
1739
2076
|
function readViteAuthConfig(config) {
|
|
1740
2077
|
const root = resolve(config.root ?? process.cwd());
|
|
1741
2078
|
const projectRoot = config[VITEHUB_PROJECT_ROOT];
|
|
1742
2079
|
return resolveAuthViteConfig(options, root, {
|
|
1743
2080
|
projectRoot: projectRoot ? resolve(projectRoot) : resolveViteHubProjectRoot(root),
|
|
1744
|
-
serverDirs
|
|
2081
|
+
serverDirs,
|
|
2082
|
+
layerAliases: nuxtDiscovery?.layerAliases ?? internalOptions.layerAliases
|
|
1745
2083
|
});
|
|
1746
2084
|
}
|
|
1747
2085
|
function refreshRuntimeConfig() {
|
|
@@ -1765,26 +2103,25 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1765
2103
|
if (authOptions === false) return [];
|
|
1766
2104
|
const config = resolveAuthViteConfig(authOptions, context.root, {
|
|
1767
2105
|
projectRoot: context.projectRoot ?? resolveViteHubProjectRoot(context.root),
|
|
1768
|
-
serverDirs: context.serverDirs ?? serverDirs
|
|
2106
|
+
serverDirs: context.serverDirs ?? serverDirs,
|
|
2107
|
+
layerAliases: nuxtDiscovery?.layerAliases ?? internalOptions.layerAliases
|
|
1769
2108
|
});
|
|
1770
2109
|
if (!config?.tables) return [];
|
|
1771
2110
|
const { database, schema } = config.tables;
|
|
1772
|
-
const schemaModule =
|
|
2111
|
+
const schemaModule = authSchemaModule(config);
|
|
1773
2112
|
const { dialect, migrationsDir } = await readTargetDatabase(context, database);
|
|
1774
2113
|
const tables = schema ? Object.fromEntries(Object.keys(resolveAuthTableSpecs(schema)).map((model) => [model, authSqlName(model)])) : authTableNames;
|
|
1775
2114
|
const existing = dialect === "sqlite" ? readAuthExistingTables(migrationsDir, Object.values(tables)) : void 0;
|
|
1776
|
-
|
|
1777
|
-
const generated = Boolean(schema || adopted);
|
|
1778
|
-
if (generated) await writeFileIfChanged(schemaModule, renderAuthSchemaModule(schema ?? {}, adopted, importBase));
|
|
1779
|
-
else await rm(schemaModule, { force: true });
|
|
2115
|
+
await writeFileIfChanged(schemaModule, renderAuthSchemaModule(schemaModule, schema ?? {}, existing && Object.keys(existing).length ? existing : void 0));
|
|
1780
2116
|
return [{
|
|
1781
2117
|
name: "auth",
|
|
1782
2118
|
database,
|
|
1783
2119
|
dialect,
|
|
1784
2120
|
definition: {
|
|
1785
|
-
module:
|
|
2121
|
+
module: schemaModule,
|
|
1786
2122
|
export: dialect === "postgresql" ? "authPostgresSchema" : "authSqliteSchema"
|
|
1787
2123
|
},
|
|
2124
|
+
relations: dialect === "postgresql" ? "authPostgresRelations" : "authSqliteRelations",
|
|
1788
2125
|
tables,
|
|
1789
2126
|
reason: "Stores the Better Auth users, sessions, accounts, and verifications, the tables and columns of the plugins and additional fields that the Auth Definition adds, and the Console MCP OAuth clients and tokens of authDatabase()."
|
|
1790
2127
|
}];
|
|
@@ -1797,6 +2134,8 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1797
2134
|
list: () => {
|
|
1798
2135
|
const rootDir = resolve(resolved?.root ?? process.cwd());
|
|
1799
2136
|
return inspectAuthDefinitions({
|
|
2137
|
+
client: clientSources,
|
|
2138
|
+
config: runtimeConfig,
|
|
1800
2139
|
projectRoot: resolveViteHubProjectRoot(rootDir),
|
|
1801
2140
|
rootDir,
|
|
1802
2141
|
serverDirs
|
|
@@ -1807,7 +2146,9 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1807
2146
|
},
|
|
1808
2147
|
config(config, env) {
|
|
1809
2148
|
const configRoot = config.root || process.cwd();
|
|
1810
|
-
|
|
2149
|
+
const discovery = config;
|
|
2150
|
+
serverDirs = discovery["__vitehubServerDirs"] ?? serverDirs;
|
|
2151
|
+
nuxtDiscovery = discovery["__vitehubNuxtAuthDiscovery"] ?? nuxtDiscovery;
|
|
1811
2152
|
const authConfig = readViteAuthConfig(config);
|
|
1812
2153
|
if (authConfig?.tables && internalOptions.databaseDisabled) throw authErrorDiagnostics.AUTH_DATABASE_DISABLED({ definition: relative(configRoot, authConfig.definition.handler) });
|
|
1813
2154
|
const dev = env?.command === "serve";
|
|
@@ -1817,6 +2158,10 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1817
2158
|
const hasMemoryDatabaseGuard = Boolean(authConfig?.implicitMemory && !dev);
|
|
1818
2159
|
if (hasNitroHandlers || applicationBaseURL || hasMemoryDatabaseGuard) Object.assign(config, { nitro });
|
|
1819
2160
|
const contribution = {
|
|
2161
|
+
...authConfig?.tables ? { resolve: { alias: authSchemaSpecifiers.map((find) => ({
|
|
2162
|
+
find,
|
|
2163
|
+
replacement: authSchemaModule(authConfig)
|
|
2164
|
+
})) } } : {},
|
|
1820
2165
|
optimizeDeps: {
|
|
1821
2166
|
exclude: [authPackageName, "vite-hub/auth"],
|
|
1822
2167
|
include: [`${authPackageName} > better-auth/vue`]
|
|
@@ -1834,9 +2179,13 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1834
2179
|
resolved = config;
|
|
1835
2180
|
serverEnv = hasServerEnvIntegration(config);
|
|
1836
2181
|
const runtimeConfig = refreshRuntimeConfig();
|
|
1837
|
-
|
|
1838
|
-
|
|
2182
|
+
const projectRoot = resolveViteHubProjectRoot(config.root);
|
|
2183
|
+
const appDir = nuxtDiscovery?.appDir ?? config.root;
|
|
2184
|
+
clientFile = options === false ? void 0 : discoverAuthClient(appDir, nuxtDiscovery);
|
|
2185
|
+
clientSources = options === false ? [] : readAuthClientSources(clientFile, discoverAuthClientExtensions(appDir, nuxtDiscovery), projectRoot);
|
|
2186
|
+
await refreshAuthGeneratedFiles(projectRoot, runtimeConfig, {
|
|
1839
2187
|
client: clientFile,
|
|
2188
|
+
clientExtensions: clientExtensions(),
|
|
1840
2189
|
importBase,
|
|
1841
2190
|
serverEnv
|
|
1842
2191
|
});
|
|
@@ -1856,6 +2205,7 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1856
2205
|
const config = refreshRuntimeConfig();
|
|
1857
2206
|
await refreshAuthGeneratedFiles(projectRoot, config, {
|
|
1858
2207
|
client: clientFile,
|
|
2208
|
+
clientExtensions: clientExtensions(),
|
|
1859
2209
|
importBase,
|
|
1860
2210
|
serverEnv
|
|
1861
2211
|
});
|
|
@@ -1879,10 +2229,11 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1879
2229
|
},
|
|
1880
2230
|
async handleHotUpdate(context) {
|
|
1881
2231
|
const changed = context.file.replace(/\\/g, "/");
|
|
1882
|
-
if (changed !== runtimeConfig?.definition.handler.replace(/\\/g, "/") && !/\/?server\.auth\.(?:c|m)?[jt]s$/i.test(changed) && !/\/server\/auth
|
|
2232
|
+
if (changed !== runtimeConfig?.definition.handler.replace(/\\/g, "/") && !/\/?server\.auth\.(?:c|m)?[jt]s$/i.test(changed) && !/\/server\/auth(?:\.extend)?\.(?:c|m)?[jt]s$/i.test(changed)) return;
|
|
1883
2233
|
const config = refreshRuntimeConfig();
|
|
1884
2234
|
await refreshAuthGeneratedFiles(resolveViteHubProjectRoot(context.server.config.root), config, {
|
|
1885
2235
|
client: clientFile,
|
|
2236
|
+
clientExtensions: clientExtensions(),
|
|
1886
2237
|
importBase,
|
|
1887
2238
|
serverEnv
|
|
1888
2239
|
});
|
|
@@ -1899,7 +2250,7 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1899
2250
|
filter: { id: /^#vitehub\/auth\/(?:abilities|client|definition|server)$/ },
|
|
1900
2251
|
handler(id) {
|
|
1901
2252
|
if (id === "#vitehub/auth/abilities") return RESOLVED_AUTH_ABILITIES_ID;
|
|
1902
|
-
if (id === "#vitehub/auth/client") return clientFile ?? RESOLVED_AUTH_CLIENT_ID;
|
|
2253
|
+
if (id === "#vitehub/auth/client") return clientExtensions().length ? RESOLVED_AUTH_CLIENT_ID : clientFile ?? RESOLVED_AUTH_CLIENT_ID;
|
|
1903
2254
|
if (id === "#vitehub/auth/definition") return RESOLVED_AUTH_DEFINITION_ID;
|
|
1904
2255
|
if (id === "#vitehub/auth/server") return RESOLVED_AUTH_SERVER_ID;
|
|
1905
2256
|
}
|
|
@@ -1908,7 +2259,7 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1908
2259
|
filter: { id: /^\0(?:virtual:vitehub\/auth\/(?:abilities|client)|#vitehub\/auth\/(?:definition|server))$/ },
|
|
1909
2260
|
handler(id) {
|
|
1910
2261
|
if (id === RESOLVED_AUTH_ABILITIES_ID) return renderAuthAbilitiesModule(runtimeConfig);
|
|
1911
|
-
if (id === RESOLVED_AUTH_CLIENT_ID) return "export default undefined\n";
|
|
2262
|
+
if (id === RESOLVED_AUTH_CLIENT_ID) return clientExtensions().length ? renderAuthClientModule(clientFile, clientExtensions()) : "export default undefined\n";
|
|
1912
2263
|
if (id === RESOLVED_AUTH_DEFINITION_ID) return renderAuthDefinitionModule(runtimeConfig, {
|
|
1913
2264
|
importBase,
|
|
1914
2265
|
serverEnv,
|
|
@@ -1919,4 +2270,4 @@ function hubAuth(options, internalOptions = {}) {
|
|
|
1919
2270
|
}
|
|
1920
2271
|
};
|
|
1921
2272
|
}
|
|
1922
|
-
export { resolveViteHubProjectRoot as _, AUTH_VITE_PLUGIN_NAME as a,
|
|
2273
|
+
export { resolveViteHubProjectRoot as C, resolveNuxtServerDirs as S, createCachingRouteRuleFinder as _, AUTH_VITE_PLUGIN_NAME as a, VITEHUB_SERVER_DIRS as b, createAuthNitroConfig as c, resolveAuthViteConfig as d, usesAuthDatabase as f, cachingRuleNames as g, discoverProjectAuthDefinition as h, AUTH_SERVER_ID as i, hubAuth as l, discoverAuthExtensions as m, AUTH_CLIENT_ID as n, authSchemaModule as o, authAbilitiesCandidates as p, AUTH_DEFINITION_ID as r, authSchemaSpecifiers as s, AUTH_ABILITIES_ID as t, writeNuxtAuthDefinition as u, methodOrder as v, resolveNuxtAuthDiscovery as x, VITEHUB_NUXT_AUTH_DISCOVERY as y };
|