@vite-hub/auth 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +58 -5
  2. package/dist/{abilities-CfvuGrBv.d.ts → abilities-IOwpkcz4.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-OKoyOwPM.js → ability-error-DgR91Jwc.js} +1 -1
  5. package/dist/{access-pages-Bej95blM.js → access-pages-C69nwa99.js} +1 -1
  6. package/dist/agent.js +11 -11
  7. package/dist/{auth-instance-5RSiFTDC.js → auth-instance-WeEK1zDd.js} +39 -17
  8. package/dist/cli.js +1 -1
  9. package/dist/client-extension-BgUlm6hy.d.ts +33 -0
  10. package/dist/client-request-B1DCz3a9.js +29 -0
  11. package/dist/{console-runtime-XcplYv4R.d.ts → console-runtime-C71weVrt.d.ts} +1 -1
  12. package/dist/{console-runtime-Bg_PAl7e.js → console-runtime-Dk3j4Jmz.js} +2 -2
  13. package/dist/console-runtime.d.ts +2 -2
  14. package/dist/console-runtime.js +1 -1
  15. package/dist/console.d.ts +1 -1
  16. package/dist/{database-options-DE9lMwu1.js → database-options-Cms7BI3c.js} +12 -4
  17. package/dist/{database-schema-options-CCQsNhjc.js → database-schema-options-IlHEeUBK.js} +1 -1
  18. package/dist/database.d.ts +1 -1
  19. package/dist/database.js +12 -7
  20. package/dist/{definition-DeEeqTLC.js → definition-EpeI5LUG.js} +3 -3
  21. package/dist/{error-diagnostics-DkzL9ltR.js → error-diagnostics-DZHuHXPP.js} +33 -1
  22. package/dist/{events-BUaoHFoC.js → events-Cm7Iwq47.js} +1 -1
  23. package/dist/extension-BWmjJhoN.d.ts +59 -0
  24. package/dist/extension-mCx4TrsO.js +133 -0
  25. package/dist/forward.js +1 -1
  26. package/dist/index.d.ts +4 -3
  27. package/dist/index.js +4 -3
  28. package/dist/internal/server.d.ts +3 -3
  29. package/dist/internal/server.js +5 -5
  30. package/dist/{mcp-config-C7srUMIZ.js → mcp-config-Bbr8kQxm.js} +9 -1
  31. package/dist/{mcp-token-DgveSGEl.js → mcp-token-BleQZK6H.js} +28 -5
  32. package/dist/{mcp-token-DG1jmw4o.d.ts → mcp-token-CxpopXmK.d.ts} +4 -2
  33. package/dist/mcp.d.ts +2 -2
  34. package/dist/mcp.js +26 -5
  35. package/dist/{members-CRlYyxVk.js → members-7OMdqha_.js} +2 -2
  36. package/dist/nuxt.d.ts +4 -14
  37. package/dist/nuxt.js +29 -9
  38. package/dist/{own-access-BvVUjaeL.d.ts → own-access-CGiai2L3.d.ts} +1 -1
  39. package/dist/presets.js +1 -1
  40. package/dist/runtime/client-request-plugin.d.ts +2 -1
  41. package/dist/runtime/client-request-plugin.js +8 -5
  42. package/dist/runtime/console.d.ts +1 -1
  43. package/dist/runtime/console.js +2 -2
  44. package/dist/runtime/empty-abilities.d.ts +1 -1
  45. package/dist/runtime/empty-client.d.ts +3 -0
  46. package/dist/runtime/empty-client.js +3 -1
  47. package/dist/runtime/empty-definition.d.ts +1 -1
  48. package/dist/runtime/server.d.ts +4 -3
  49. package/dist/runtime/server.js +3 -2
  50. package/dist/runtime/vue-nuxt.js +1 -1
  51. package/dist/schema.d.ts +32 -14
  52. package/dist/schema.js +21 -14
  53. package/dist/{server-iQNOXyfS.js → server-5t-HA7I1.js} +41 -316
  54. package/dist/{server-1G_BbfBD.d.ts → server-DyP1v-sZ.d.ts} +25 -6
  55. package/dist/{server-B8kTFrHP.d.ts → server-mmp8EfcE.d.ts} +3 -2
  56. package/dist/server.d.ts +3 -3
  57. package/dist/server.js +4 -4
  58. package/dist/{session-cookies-DN0svCKj.js → session-cookies-BNtY3hMp.js} +4 -16
  59. package/dist/{set-cookie-CMB3t4NF.js → set-cookie-Bva-P-_C.js} +1 -1
  60. package/dist/{table-specs-C3-bLOSF.js → table-specs-Bm7QJCbu.js} +1 -1
  61. package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-BxKeFD_y.d.ts} +5 -0
  62. package/dist/test.d.ts +1 -1
  63. package/dist/test.js +2 -2
  64. package/dist/{types-BmRGse4l.d.ts → types-CnO5bHEF.d.ts} +20 -2
  65. package/dist/{vite-GRzej8Cs.js → vite-7I1bJvqA.js} +641 -240
  66. package/dist/vite-CZ_Z6IR3.d.ts +28 -0
  67. package/dist/vite.d.ts +33 -13
  68. package/dist/vite.js +1 -1
  69. package/dist/vue.d.ts +4 -3
  70. package/dist/vue.js +39 -4
  71. package/package.json +8 -8
  72. package/dist/client-request-BzMKtfCY.js +0 -52
@@ -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$1 } from "./object-CAK6UYR5.js";
3
+ import { t as isRecord } from "./object-CAK6UYR5.js";
4
4
  import { r as resolveAccessRoutePath, t as accessRouteSyntaxError } from "./application-path-zKi7NrvK.js";
5
- import { t as authErrorDiagnostics } from "./error-diagnostics-DkzL9ltR.js";
6
- import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-Bej95blM.js";
7
- import { a as authDatabaseSchemaError, i as authDatabasePlacementError, n as authDatabaseAdditionalFieldsError, o as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-DE9lMwu1.js";
8
- import { i as resolveAuthTableSpecs, n as authSqlName } from "./table-specs-C3-bLOSF.js";
5
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
6
+ import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-C69nwa99.js";
7
+ import { a as differentFieldAttributes, c as mergeFieldDeclarations, i as authExtensionKeys, n as assertUniquePluginIds, o as effectiveFieldAttributes, r as authCoreModels } from "./extension-mCx4TrsO.js";
8
+ import { a as authDatabasePlacementError, n as authDatabaseAdditionalFieldsError, o as authDatabaseSchemaError, s as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-Cms7BI3c.js";
9
+ import { i as resolveAuthTableSpecs, n as authSqlName } from "./table-specs-Bm7QJCbu.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, rm, writeFile } from "node:fs/promises";
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.
@@ -330,6 +345,19 @@ function findPackageDir(file) {
330
345
  function ownModule(importMetaUrl, modulePath) {
331
346
  return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
332
347
  }
348
+ function createImportPath(fromFile, targetFile) {
349
+ const fromDir = realpathIfExists(dirname$1(fromFile));
350
+ const target = realpathIfExists(targetFile);
351
+ const importPath = relative$1(fromDir, target);
352
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
353
+ }
354
+ function realpathIfExists(path) {
355
+ try {
356
+ return realpathSync.native(path);
357
+ } catch {
358
+ return resolve$1(path);
359
+ }
360
+ }
333
361
  // ../internal/src/definition-catalog.ts
334
362
  /** `writeFileIfChangedSync` for async callers. */
335
363
  async function writeFileIfChanged(file, contents) {
@@ -346,7 +374,7 @@ async function flattenPlugins(value, plugins, seen) {
346
374
  for (const item of value) await flattenPlugins(item, plugins, seen);
347
375
  return;
348
376
  }
349
- if (!isRecord$1(value) || seen.has(value)) return;
377
+ if (!isRecord(value) || seen.has(value)) return;
350
378
  seen.add(value);
351
379
  if (isThenable(value)) {
352
380
  await flattenPlugins(await value, plugins, seen);
@@ -443,6 +471,10 @@ function scanModule(source, file = "module.ts") {
443
471
  source
444
472
  };
445
473
  }
474
+ /** The source text of a node. */
475
+ function nodeText(module, node) {
476
+ return module.source.slice(node.start, node.end);
477
+ }
446
478
  /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
447
479
  function unwrapExpression(node) {
448
480
  while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
@@ -594,9 +626,38 @@ function discoverAuthDefinitions(rootDir, options = {}) {
594
626
  ].join("\n") });
595
627
  return layerDefinitions;
596
628
  }
597
- /** Finds the app's Auth client options, `auth.client.ts`, in the Vite root, which is `app/` in a Nuxt app. */
598
- function discoverAuthClient(appDir) {
599
- return authDefinitionExtensions.map((extension) => resolve(appDir, `auth.client${extension}`)).find((file) => existsSync(file));
629
+ /** The Auth Definitions of Nuxt layers. The first server directory is the application. */
630
+ function discoverLayerAuthDefinitions(serverDirs = []) {
631
+ return existingDefinitions(serverDirs.slice(1).flatMap(serverAuthCandidates));
632
+ }
633
+ /**
634
+ * Finds the Auth client options, `auth.client.ts`, in the Vite root, which is `app/` in a Nuxt app. Without an
635
+ * application file, one Nuxt layer can supply its `app/auth.client.ts`. A layer file that Auth would not load fails
636
+ * discovery.
637
+ */
638
+ function discoverAuthClient(appDir, options = {}) {
639
+ const clientIn = (directory) => authDefinitionExtensions.map((extension) => resolve(directory, `auth.client${extension}`)).find((file) => existsSync(file));
640
+ const app = clientIn(appDir);
641
+ const layers = [...new Set((options.layerAppDirs ?? []).flatMap((directory) => clientIn(directory) ?? []))].filter((file) => file !== app);
642
+ if (layers.length > (app ? 0 : 1)) throw authErrorDiagnostics.AUTH_LAYER_CLIENT_IGNORED({
643
+ files: layers,
644
+ ...app ? { app } : {}
645
+ });
646
+ return app ?? layers[0];
647
+ }
648
+ /**
649
+ * The parts of the Auth Definition, `server/auth.extend.ts`: the file of the application first, then the files of
650
+ * Nuxt layers in priority order.
651
+ */
652
+ function discoverAuthExtensions(rootDir, options = {}) {
653
+ return (options.serverDirs ?? [resolve(rootDir, "server")]).flatMap((serverDir) => authDefinitionExtensions.map((extension) => resolve(serverDir, `auth.extend${extension}`)).find((file) => existsSync(file)) ?? []);
654
+ }
655
+ /**
656
+ * The parts of the Auth client options, `auth.client.extend.ts`: the file in the Vite root first, which is `app/` in a
657
+ * Nuxt app, then the `app/auth.client.extend.ts` of Nuxt layers in priority order.
658
+ */
659
+ function discoverAuthClientExtensions(appDir, options = {}) {
660
+ return [.../* @__PURE__ */ new Set([appDir, ...options.layerAppDirs ?? []])].flatMap((directory) => authDefinitionExtensions.map((extension) => resolve(directory, `auth.client.extend${extension}`)).find((file) => existsSync(file)) ?? []);
600
661
  }
601
662
  function discoverAuthDefinition(rootDir, options = {}) {
602
663
  return discoverAuthDefinitions(rootDir, options)[0];
@@ -639,6 +700,90 @@ function discoverAuthAbilities(rootDir, options = {}) {
639
700
  if (found.length > 1) throw authErrorDiagnostics.AUTH_C0060({ message: ["[vitehub] Only one abilities file is allowed. Found:", ...found.map((file) => ` - ${file}`)].join("\n") });
640
701
  return found[0];
641
702
  }
703
+ // src/config-fields.ts
704
+ const authFieldTypes = /* @__PURE__ */ new Set([
705
+ "boolean",
706
+ "date",
707
+ "json",
708
+ "number",
709
+ "number[]",
710
+ "string",
711
+ "string[]"
712
+ ]);
713
+ function readStaticBooleanOption(field, key, label, fail) {
714
+ if (!hasObjectProperty(field, key)) return;
715
+ const value = readStaticBooleanLiteral(readObjectPropertyValue(field, key));
716
+ if (value === void 0) throw fail(`${label}.${key} must be \`true\` or \`false\``);
717
+ return value;
718
+ }
719
+ /** One additional field, read from its object literal: the parts that shape the column. */
720
+ function readAdditionalField(value, key, label, fail = authDatabaseAdditionalFieldsError) {
721
+ const field = objectLiteral(value && unwrapExpression(value));
722
+ if (!field) throw fail(`${label} must be an inline object, such as \`{ type: "string", required: false }\``);
723
+ const typeValue = readObjectPropertyValue(field, "type");
724
+ const unwrappedType = typeValue && unwrapExpression(typeValue);
725
+ const type = unwrappedType?.type === "ArrayExpression" ? "string" : staticString(unwrappedType);
726
+ if (!type || !authFieldTypes.has(type)) throw fail(`${label}.type must be one of ${[...authFieldTypes].map((name) => `"${name}"`).join(", ")}, or a list of strings`);
727
+ const fieldName = readObjectPropertyValue(field, "fieldName");
728
+ if (fieldName && staticString(fieldName) !== key) throw authDatabaseSchemaError(`${label}.fieldName cannot rename the column`);
729
+ const spec = { type };
730
+ if (readStaticBooleanOption(field, "required", label, fail)) spec.required = true;
731
+ if (readStaticBooleanOption(field, "unique", label, fail)) spec.unique = true;
732
+ if (readStaticBooleanOption(field, "index", label, fail)) spec.index = true;
733
+ if (readStaticBooleanOption(field, "bigint", label, fail)) spec.bigint = true;
734
+ const defaultValue = readObjectPropertyValue(field, "defaultValue");
735
+ const staticDefault = defaultValue && staticValue(defaultValue);
736
+ if (typeof staticDefault === "string" || typeof staticDefault === "number" || typeof staticDefault === "boolean") spec.defaultValue = staticDefault;
737
+ const references = readObjectPropertyValue(field, "references");
738
+ if (references) {
739
+ const reference = staticValue(references);
740
+ const model = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.model : void 0;
741
+ const target = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.field : void 0;
742
+ const onDelete = typeof reference === "object" && reference !== null && !Array.isArray(reference) ? reference.onDelete ?? "cascade" : void 0;
743
+ 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" }\``);
744
+ spec.references = {
745
+ model,
746
+ field: target,
747
+ onDelete
748
+ };
749
+ }
750
+ return spec;
751
+ }
752
+ /** The `additionalFields` of each core model, which `authDatabase()` adds as columns. */
753
+ function readAuthAdditionalFields(body) {
754
+ const result = {};
755
+ for (const model of authCoreModels) {
756
+ const value = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, model)), "additionalFields");
757
+ if (!value) continue;
758
+ const fields = objectLiteral(unwrapExpression(value));
759
+ if (!fields) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must be an inline object literal, so the Auth Vite plugin can add its columns`);
760
+ const entries = readObjectEntries(fields);
761
+ if (entries.some((entry) => !entry.key)) throw authDatabaseAdditionalFieldsError(`${model}.additionalFields must use static keys`);
762
+ if (entries.length) result[model] = Object.fromEntries(entries.map((entry) => [entry.key, readAdditionalField(entry.value, entry.key, `${model}.additionalFields.${entry.key}`)]));
763
+ }
764
+ return Object.keys(result).length ? result : void 0;
765
+ }
766
+ /** Object entries. `key` is empty for spread and computed keys. `value` is undefined for methods and accessors. */
767
+ function readObjectEntries(body) {
768
+ if (!body) return [];
769
+ return objectProperties(body).map((property) => ({
770
+ key: property.computed ? "" : property.key ?? "",
771
+ value: property.node.type === "Property" && property.node.kind === "init" && !property.node.method ? property.value : void 0
772
+ }));
773
+ }
774
+ function readObjectPropertyValue(body, property) {
775
+ return readObjectEntries(body).findLast((entry) => entry.key === property)?.value;
776
+ }
777
+ function hasObjectProperty(body, property) {
778
+ return readObjectEntries(body).some((entry) => entry.key === property);
779
+ }
780
+ function objectLiteral(value) {
781
+ return value?.type === "ObjectExpression" ? value : void 0;
782
+ }
783
+ function readStaticBooleanLiteral(expression) {
784
+ const value = expression && staticValue(expression);
785
+ return typeof value === "boolean" ? value : void 0;
786
+ }
642
787
  // src/config.ts
643
788
  const authDatabaseModules = /* @__PURE__ */ new Set(["@vite-hub/auth/database", "vite-hub/auth/database"]);
644
789
  function readAuthDatabaseImports(module) {
@@ -711,7 +856,7 @@ function addBoundNames(pattern, names) {
711
856
  }
712
857
  });
713
858
  }
714
- function readModuleBindings(module) {
859
+ function readModuleBindings(module, layers) {
715
860
  const bindings = {
716
861
  declarations: /* @__PURE__ */ new Map(),
717
862
  imports: /* @__PURE__ */ new Map(),
@@ -721,7 +866,11 @@ function readModuleBindings(module) {
721
866
  pluginFactories: /* @__PURE__ */ new Map(),
722
867
  pluginNamespaces: /* @__PURE__ */ new Map()
723
868
  };
724
- const localFile = (specifier) => specifier.startsWith("./") || specifier.startsWith("../") ? resolveLocalModule(module.file, specifier) : void 0;
869
+ const localFile = (specifier) => {
870
+ if (specifier.startsWith("./") || specifier.startsWith("../")) return resolveLocalModule(module.file, specifier);
871
+ const alias = Object.keys(layers).find((name) => specifier === name || specifier.startsWith(`${name}/`));
872
+ return alias ? resolveLocalModule(module.file, resolve(layers[alias], specifier.slice(alias.length + 1))) : void 0;
873
+ };
725
874
  const declare = (name, node) => bindings.declarations.set(name, [...bindings.declarations.get(name) ?? [], node]);
726
875
  const readDeclaration = (declaration, exported) => {
727
876
  const names = [];
@@ -784,86 +933,178 @@ function readModuleBindings(module) {
784
933
  } else readDeclaration(statement, false);
785
934
  return bindings;
786
935
  }
787
- /**
788
- * Reads what `needs` reaches in `module`: the plugin factories that its reached code calls, and what it needs from the
789
- * local modules it imports. The whole module counts for the Definition. In an imported module, only the exports that
790
- * the importer uses count, with the declarations and imports that they use.
791
- */
792
- function readModuleNeeds(module, needs, exportedFactory) {
793
- const bindings = readModuleBindings(module);
794
- const plugins = /* @__PURE__ */ new Set();
795
- const imports = [];
796
- const need = (file, imported) => imports.push([file, /* @__PURE__ */ new Set([imported])]);
797
- const needImport = ({ file, imported }) => imported === "*" ? imports.push([file, "all"]) : need(file, imported);
798
- const calledFactory = (callee) => {
799
- if (callee.type === "Identifier") {
800
- const imported = bindings.imports.get(callee.name);
801
- return bindings.pluginFactories.get(callee.name) ?? (imported && imported.imported !== "*" ? exportedFactory(imported.file, imported.imported) : void 0);
936
+ function pluginFunctionScope(scope, factory) {
937
+ const locals = new Map(scope.locals);
938
+ for (const param of factory.params) {
939
+ const names = [];
940
+ addBoundNames(param, names);
941
+ for (const name of names) locals.set(name, void 0);
942
+ }
943
+ if (factory.body?.type === "BlockStatement") for (const statement of factory.body.body) {
944
+ if (statement.type !== "VariableDeclaration") continue;
945
+ for (const declaration of statement.declarations) {
946
+ const names = [];
947
+ addBoundNames(declaration.id, names);
948
+ const value = statement.kind === "const" && declaration.id.type === "Identifier" && declaration.init ? unwrapExpression(declaration.init) : void 0;
949
+ for (const name of names) locals.set(name, value);
802
950
  }
803
- if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier") return void 0;
804
- const property = staticMemberName(callee);
805
- if (property === void 0) return void 0;
806
- const factories = bindings.pluginNamespaces.get(callee.object.name);
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;
951
+ }
952
+ return {
953
+ module: scope.module,
954
+ locals
810
955
  };
811
- const collectCalls = (node, references) => walk(node, (child, parent) => {
812
- if (child.type === "ImportDeclaration") return false;
813
- const plugin = child.type === "CallExpression" ? calledFactory(child.callee) : void 0;
814
- if (plugin) plugins.add(plugin);
815
- if (child.type !== "Identifier") return;
816
- if (parent?.type === "MemberExpression") {
817
- if (parent.property === child && !parent.computed) return;
818
- if (parent.object === child) {
819
- const imported = bindings.imports.get(child.name);
820
- const member = staticMemberName(parent);
821
- if (imported?.imported === "*" && member !== void 0) {
822
- need(imported.file, member);
956
+ }
957
+ function readConfiguredPluginFields(definition, options, body, moduleOf, bindingsOf, scan, knownFactory, plugins) {
958
+ const start = readObjectPropertyValue(body, "plugins");
959
+ if (!start) return [];
960
+ const active = /* @__PURE__ */ new Set();
961
+ const resolvingExports = /* @__PURE__ */ new Set();
962
+ function fromExport(file, name, read) {
963
+ const key = `${file}\0${name}`;
964
+ if (resolvingExports.has(key)) return;
965
+ resolvingExports.add(key);
966
+ try {
967
+ const bindings = bindingsOf(file);
968
+ const target = bindings.exports.get(name);
969
+ if (target && "file" in target) return fromExport(target.file, target.imported, read);
970
+ if (target && "local" in target) return fromLocal(target.local, { module: moduleOf(file) }, read);
971
+ if (!target && name !== "default") for (const source of bindings.exportAll) {
972
+ const value = fromExport(source, name, read);
973
+ if (value !== void 0) return value;
974
+ }
975
+ } finally {
976
+ resolvingExports.delete(key);
977
+ }
978
+ }
979
+ function fromLocal(name, scope, read) {
980
+ if (scope.locals?.has(name)) return visit(scope.locals.get(name), scope, read);
981
+ const bindings = bindingsOf(scope.module.file);
982
+ const imported = bindings.imports.get(name);
983
+ if (imported && imported.imported !== "*") return fromExport(imported.file, imported.imported, read);
984
+ const declaration = bindings.declarations.get(name)?.[0];
985
+ return visit(name === "default" ? defaultExportExpression(scope.module) ?? declaration : declaration?.type === "VariableDeclarator" ? topLevelConstValue(scope.module, name) : declaration, { module: scope.module }, read);
986
+ }
987
+ function visit(node, scope, read) {
988
+ if (!node || active.has(node)) return;
989
+ active.add(node);
990
+ try {
991
+ if (node.type === "Identifier") return fromLocal(node.name, scope, read);
992
+ if (node.type === "MemberExpression" && node.object.type === "Identifier" && !scope.locals?.has(node.object.name)) {
993
+ const imported = bindingsOf(scope.module.file).imports.get(node.object.name);
994
+ const name = staticMemberName(node);
995
+ if (imported?.imported === "*" && name !== void 0) return fromExport(imported.file, name, read);
996
+ }
997
+ if (node.type === "CallExpression" && (node.callee.type === "Identifier" || node.callee.type === "MemberExpression")) {
998
+ const registered = read === readPlugin;
999
+ const known = registered ? knownFactory(node.callee, scope) : void 0;
1000
+ if (known) {
1001
+ plugins.push(known);
823
1002
  return;
824
1003
  }
1004
+ return visit(node.callee, scope, (factory, factoryScope) => {
1005
+ if (factory.type !== "ArrowFunctionExpression" && factory.type !== "FunctionExpression" && factory.type !== "FunctionDeclaration") return;
1006
+ const body = factory.body;
1007
+ if (!body) return;
1008
+ const end = body.type === "BlockStatement" ? body.body.at(-1) : void 0;
1009
+ const value = body.type !== "BlockStatement" ? body : end?.type === "ReturnStatement" ? end.argument ?? void 0 : void 0;
1010
+ 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")) {
1011
+ if (registered && scan.ownsTables) throw authErrorDiagnostics.AUTH_PLUGIN_SCHEMA_UNREADABLE({
1012
+ plugin: nodeText(scope.module, node.callee),
1013
+ file: relative(scan.rootDir, factoryScope.module.file),
1014
+ detail: "the local factory must return a statically readable plugin object or plugin list"
1015
+ });
1016
+ return;
1017
+ }
1018
+ return visit(unwrapExpression(value), pluginFunctionScope(factoryScope, factory), read);
1019
+ });
825
1020
  }
1021
+ return read(node, scope);
1022
+ } finally {
1023
+ active.delete(node);
826
1024
  }
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
1025
  }
839
- const locals = [];
840
- for (const name of needs) {
841
- const target = bindings.exports.get(name);
842
- if (!target) for (const file of bindings.exportAll) need(file, name);
843
- else if ("file" in target) needImport(target);
844
- else if ("local" in target) locals.push(target.local);
1026
+ function entries(value, scope, keysOnly = false, unreadable) {
1027
+ const result = visit(value && unwrapExpression(value), scope, (object, objectScope) => object.type === "ObjectExpression" ? objectEntries(object, objectScope, keysOnly, unreadable) : void 0);
1028
+ if (!result && unreadable) throw unreadable();
1029
+ return result;
845
1030
  }
846
- const reached = /* @__PURE__ */ new Set();
847
- for (let local = locals.pop(); local !== void 0; local = locals.pop()) {
848
- if (reached.has(local)) continue;
849
- reached.add(local);
850
- const imported = bindings.imports.get(local);
851
- if (imported) needImport(imported);
852
- const references = /* @__PURE__ */ new Set();
853
- for (const declaration of bindings.declarations.get(local) ?? []) collectCalls(declaration, references);
854
- for (const reference of references) if (bindings.declarations.has(reference) || bindings.imports.has(reference)) locals.push(reference);
1031
+ function objectEntries(object, scope, keysOnly = false, unreadable) {
1032
+ const result = /* @__PURE__ */ new Map();
1033
+ for (const property of objectProperties(object)) if (property.node.type === "SpreadElement") {
1034
+ const spread = entries(property.node.argument, scope, keysOnly, unreadable);
1035
+ if (spread) for (const [key, entry] of spread) result.set(key, entry);
1036
+ else if (!keysOnly) result.clear();
1037
+ } else if (property.key) {
1038
+ const value = property.node.kind === "init" && !property.node.method ? property.value : void 0;
1039
+ result.set(property.key, {
1040
+ value,
1041
+ scope
1042
+ });
1043
+ } else if (unreadable) throw unreadable();
1044
+ else if (!keysOnly) result.clear();
1045
+ return result;
855
1046
  }
856
- return {
857
- plugins: [...plugins],
858
- imports
1047
+ const objectAt = (entry, keysOnly = false, unreadable) => entry && entries(entry.value, entry.scope, keysOnly, unreadable);
1048
+ const fields = [];
1049
+ const readPlugin = (node, scope) => {
1050
+ if (node.type === "ArrayExpression") for (const element of node.elements) {
1051
+ const value = element?.type === "SpreadElement" ? element.argument : element;
1052
+ if (value) visit(unwrapExpression(value), scope, readPlugin);
1053
+ }
1054
+ if (node.type !== "ObjectExpression") return;
1055
+ const pluginObject = objectEntries(node, scope);
1056
+ const id = pluginObject.get("id");
1057
+ const plugin = id && visit(id.value && unwrapExpression(id.value), id.scope, (value) => value.type === "Literal" && typeof value.value === "string" ? value.value : void 0);
1058
+ if (!plugin) return;
1059
+ const file = scope.module.file;
1060
+ const unreadable = (detail) => authErrorDiagnostics.AUTH_PLUGIN_SCHEMA_UNREADABLE({
1061
+ plugin,
1062
+ file: relative(scan.rootDir, file),
1063
+ detail
1064
+ });
1065
+ 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);
1066
+ const columns = [];
1067
+ for (const [model, entry] of schema ?? []) {
1068
+ const core = scan.ownsTables && authCoreModels.some((core) => core === model);
1069
+ const label = `schema.${model}.fields`;
1070
+ const invalidFields = () => unreadable(`\`${label}\` must be an inline object literal or resolve to an object with static keys`);
1071
+ const modelFields = objectAt(objectAt(entry, false, core ? invalidFields : void 0)?.get("fields"), !core, core ? invalidFields : void 0);
1072
+ if (core && !modelFields) throw invalidFields();
1073
+ for (const [field, { value, scope: fieldScope }] of modelFields ?? []) {
1074
+ const declaration = authCoreModels.some((coreModel) => coreModel === model) ? visit(value && unwrapExpression(value), fieldScope, (node) => {
1075
+ if (node.type !== "ObjectExpression") return;
1076
+ if (readObjectEntries(node).some((entry) => !entry.key)) {
1077
+ if (core) throw unreadable(`${label}.${field} must have static attributes`);
1078
+ return;
1079
+ }
1080
+ return {
1081
+ attributes: staticFieldAttributes(node),
1082
+ spec: core ? readAdditionalField(node, field, `${label}.${field}`, unreadable) : void 0
1083
+ };
1084
+ }) : void 0;
1085
+ if (core && !declaration) throw unreadable(`${label}.${field} must be an inline object or resolve to one`);
1086
+ columns.push({
1087
+ model,
1088
+ field,
1089
+ ...declaration
1090
+ });
1091
+ }
1092
+ }
1093
+ fields.push({
1094
+ plugin,
1095
+ file,
1096
+ fields: columns
1097
+ });
859
1098
  };
1099
+ const scope = { module: definition };
1100
+ visit(unwrapExpression(start), options.type === "ArrowFunctionExpression" || options.type === "FunctionExpression" ? pluginFunctionScope(scope, options) : scope, readPlugin);
1101
+ return fields;
860
1102
  }
861
1103
  /**
862
- * The plugins of `AuthSchemaPlugin` that the Definition module calls, and that the local modules it imports call in
863
- * the exports it uses, such as `stripe()` in `src/server/auth-plugins.ts` that returns the plugins of `server/auth.ts`.
1104
+ * The schema contributions reached from the registered plugins, including plugins returned by local helpers.
864
1105
  */
865
- function readDefinitionSchemaPlugins(definition) {
866
- const plugins = /* @__PURE__ */ new Set();
1106
+ function readDefinitionSchemaPlugins(definition, scan, options, body) {
1107
+ const plugins = [];
867
1108
  const modules = /* @__PURE__ */ new Map([[definition.file, definition]]);
868
1109
  const moduleOf = (file) => {
869
1110
  let module = modules.get(file);
@@ -871,12 +1112,16 @@ function readDefinitionSchemaPlugins(definition) {
871
1112
  return module;
872
1113
  };
873
1114
  const bindingsByFile = /* @__PURE__ */ new Map();
1115
+ const bindingsOf = (file) => {
1116
+ let bindings = bindingsByFile.get(file);
1117
+ if (!bindings) bindingsByFile.set(file, bindings = readModuleBindings(moduleOf(file), scan.layers));
1118
+ return bindings;
1119
+ };
874
1120
  const exportedFactory = (file, name, seen = /* @__PURE__ */ new Set()) => {
875
1121
  const key = `${file}\0${name}`;
876
1122
  if (seen.has(key)) return void 0;
877
1123
  seen.add(key);
878
- let bindings = bindingsByFile.get(file);
879
- if (!bindings) bindingsByFile.set(file, bindings = readModuleBindings(moduleOf(file)));
1124
+ const bindings = bindingsOf(file);
880
1125
  const target = bindings.exports.get(name);
881
1126
  if (target && "plugin" in target) return target.plugin;
882
1127
  if (target && "file" in target) return exportedFactory(target.file, target.imported, seen);
@@ -891,89 +1136,25 @@ function readDefinitionSchemaPlugins(definition) {
891
1136
  if (plugin) return plugin;
892
1137
  }
893
1138
  };
894
- const done = /* @__PURE__ */ new Map();
895
- const queue = [[definition.file, "all"]];
896
- for (let item = queue.shift(); item; item = queue.shift()) {
897
- const [file, needs] = item;
898
- const previous = done.get(file);
899
- if (previous === "all") continue;
900
- const fresh = needs === "all" ? "all" : new Set([...needs].filter((name) => !previous?.has(name)));
901
- if (fresh !== "all" && !fresh.size) continue;
902
- done.set(file, fresh === "all" ? "all" : /* @__PURE__ */ new Set([...previous ?? [], ...fresh]));
903
- const result = readModuleNeeds(moduleOf(file), fresh, exportedFactory);
904
- for (const plugin of result.plugins) plugins.add(plugin);
905
- queue.push(...result.imports);
906
- }
907
- return [...plugins].sort();
908
- }
909
- const authFieldTypes = /* @__PURE__ */ new Set([
910
- "boolean",
911
- "date",
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;
1139
+ const knownFactory = (callee, scope) => {
1140
+ const bindings = bindingsOf(scope.module.file);
1141
+ if (callee.type === "Identifier" && !scope.locals?.has(callee.name)) {
1142
+ const imported = bindings.imports.get(callee.name);
1143
+ return bindings.pluginFactories.get(callee.name) ?? (imported && imported.imported !== "*" ? exportedFactory(imported.file, imported.imported) : void 0);
1144
+ }
1145
+ if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || scope.locals?.has(callee.object.name)) return;
1146
+ const name = staticMemberName(callee);
1147
+ if (name === void 0) return;
1148
+ const factories = bindings.pluginNamespaces.get(callee.object.name);
1149
+ if (factories) return Object.hasOwn(factories, name) ? factories[name] : void 0;
1150
+ const imported = bindings.imports.get(callee.object.name);
1151
+ if (imported?.imported === "*") return exportedFactory(imported.file, name);
1152
+ };
1153
+ return {
1154
+ plugins,
1155
+ pluginFields: readConfiguredPluginFields(definition, options, body, moduleOf, bindingsOf, scan, knownFactory, plugins)
1156
+ };
975
1157
  }
976
- /** The object that a callback returns, from `() => ({ ... })` or the first `return { ... }` in its body. */
977
1158
  function readReturnedObject(callback) {
978
1159
  if (callback.type !== "ArrowFunctionExpression") return;
979
1160
  if (callback.body.type !== "BlockStatement") {
@@ -1010,7 +1191,12 @@ function exportedDefineAuthCall(module) {
1010
1191
  const call = exported?.type === "Identifier" ? topLevelConstValue(module, exported.name) : exported;
1011
1192
  return call?.type === "CallExpression" && call.callee.type === "Identifier" && call.callee.name === "defineAuth" ? call : void 0;
1012
1193
  }
1013
- function readDefinitionObjectBody(file) {
1194
+ function readPluginCalls(module, body) {
1195
+ 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)";
1196
+ const plugins = readObjectPropertyValue(body, "plugins");
1197
+ return plugins?.type === "ArrayExpression" ? plugins.elements.flatMap((element) => element ? [label(element)] : []) : plugins ? [label(plugins)] : [];
1198
+ }
1199
+ function readDefinitionObjectBody(file, scan) {
1014
1200
  const module = scanModule(readFileSync(file, "utf8"), file);
1015
1201
  const authDatabase = readAuthDatabaseImports(module);
1016
1202
  const call = exportedDefineAuthCall(module);
@@ -1018,7 +1204,6 @@ function readDefinitionObjectBody(file) {
1018
1204
  const argument = call.arguments[0];
1019
1205
  if (argument === void 0 || argument.type === "SpreadElement") return;
1020
1206
  const options = unwrapExpression(argument);
1021
- const plugins = readDefinitionSchemaPlugins(module);
1022
1207
  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
1208
  if (options.type === "ObjectExpression") {
1024
1209
  assertAuthDatabasePlacement(options, options, authDatabase);
@@ -1026,7 +1211,12 @@ function readDefinitionObjectBody(file) {
1026
1211
  authDatabase,
1027
1212
  body: options,
1028
1213
  callback: false,
1029
- plugins
1214
+ file,
1215
+ pluginCalls: readPluginCalls(module, options),
1216
+ ...readDefinitionSchemaPlugins(module, {
1217
+ ...scan,
1218
+ ownsTables: Boolean(readAuthDatabaseCall(options, authDatabase))
1219
+ }, options, options)
1030
1220
  };
1031
1221
  }
1032
1222
  const returned = readReturnedObject(options);
@@ -1036,7 +1226,12 @@ function readDefinitionObjectBody(file) {
1036
1226
  authDatabase,
1037
1227
  body: returned,
1038
1228
  callback: true,
1039
- plugins
1229
+ file,
1230
+ pluginCalls: readPluginCalls(module, returned),
1231
+ ...readDefinitionSchemaPlugins(module, {
1232
+ ...scan,
1233
+ ownsTables: Boolean(readAuthDatabaseCall(returned, authDatabase))
1234
+ }, options, returned)
1040
1235
  };
1041
1236
  }
1042
1237
  /** Owned tables must have the same target in every request and in the build-time contribution. */
@@ -1056,29 +1251,11 @@ function assertAuthDatabasePlacement(options, body, names) {
1056
1251
  const unconditional = options.body.body.some((statement) => statement.type === "ReturnStatement" && statement.argument && unwrapExpression(statement.argument) === body);
1057
1252
  if (returns !== 1 || !unconditional) throw authDatabasePlacementError();
1058
1253
  }
1059
- const generateId = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, "advanced")), "database")), "generateId");
1060
- if (generateId) assertAuthDatabaseIdStrategy(staticValue(generateId));
1254
+ assertAuthDatabaseIdStrategy(readAuthGenerateId(body));
1061
1255
  }
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
- }));
1069
- }
1070
- function readObjectPropertyValue(body, property) {
1071
- return readObjectEntries(body).findLast((entry) => entry.key === property)?.value;
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;
1256
+ function readAuthGenerateId(body) {
1257
+ const generateId = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(objectLiteral(readObjectPropertyValue(body, "advanced")), "database")), "generateId");
1258
+ return generateId && staticValue(generateId);
1082
1259
  }
1083
1260
  function readStaticStringProperty(body, property, label) {
1084
1261
  if (!hasObjectProperty(body, property)) return;
@@ -1226,27 +1403,146 @@ function readAuthDatabaseCall(body, authDatabase) {
1226
1403
  const expression = value && unwrapExpression(value);
1227
1404
  return expression?.type === "CallExpression" && expression.callee.type === "Identifier" && authDatabase.has(expression.callee.name) ? expression : void 0;
1228
1405
  }
1406
+ function readAuthExtension(file, scan) {
1407
+ const module = scanModule(readFileSync(file, "utf8"), file);
1408
+ const invalid = (option) => authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({
1409
+ file: relative(scan.rootDir, file),
1410
+ option
1411
+ });
1412
+ const call = defaultExportExpression(module);
1413
+ const argument = call?.type === "CallExpression" && call.callee.type === "Identifier" && call.callee.name === "extendAuth" ? call.arguments[0] : void 0;
1414
+ const body = argument && argument.type !== "SpreadElement" ? objectLiteral(unwrapExpression(argument)) : void 0;
1415
+ if (!body) throw invalid();
1416
+ const outside = (object, allowed) => readObjectEntries(object).find((entry) => !allowed(entry.key));
1417
+ const option = outside(body, (key) => authExtensionKeys.has(key));
1418
+ if (option) throw invalid(option.key || "...");
1419
+ if (hasObjectProperty(body, "user")) {
1420
+ const user = objectLiteral(readObjectPropertyValue(body, "user"));
1421
+ const userOption = user ? outside(user, (key) => key === "additionalFields") : void 0;
1422
+ if (!user || userOption) throw invalid(`user.${userOption?.key || "..."}`);
1423
+ }
1424
+ return {
1425
+ file,
1426
+ body,
1427
+ pluginCalls: readPluginCalls(module, body),
1428
+ ...readDefinitionSchemaPlugins(module, scan, body, body),
1429
+ additionalFields: readAuthAdditionalFields(body)
1430
+ };
1431
+ }
1432
+ const pluginIdOf = (plugin) => plugin.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
1433
+ function staticFieldAttributes(field) {
1434
+ return effectiveFieldAttributes(Object.fromEntries(readObjectEntries(field).map((entry) => [entry.key, entry.value ? staticValue(entry.value) : dynamic])));
1435
+ }
1436
+ function staticOptionFieldDeclarations(source, rootDir) {
1437
+ return authCoreModels.flatMap((model) => {
1438
+ return readObjectEntries(objectLiteral(readObjectPropertyValue(objectLiteral(readObjectPropertyValue(source.body, model)), "additionalFields"))).flatMap(({ key, value }) => {
1439
+ const attributes = objectLiteral(value);
1440
+ return key && attributes && readObjectEntries(attributes).every((entry) => entry.key) ? [{
1441
+ model,
1442
+ field: key,
1443
+ file: relative(rootDir, source.file),
1444
+ attributes: staticFieldAttributes(attributes)
1445
+ }] : [];
1446
+ });
1447
+ });
1448
+ }
1229
1449
  /**
1230
1450
  * The Database that gets the Better Auth tables (the name that `authDatabase()` receives, `"default"` without one), and
1231
- * the plugins and additional fields that add tables and columns.
1451
+ * the plugins and additional fields that add tables and columns: those of the Definition, then those of each part.
1232
1452
  */
1233
- function readAuthTablesConfig(definition) {
1234
- const { authDatabase, body, plugins } = definition;
1453
+ function readAuthTablesConfig(definition, extensions, rootDir) {
1454
+ const { authDatabase, body } = definition;
1235
1455
  const call = readAuthDatabaseCall(body, authDatabase);
1236
- if (!call) return false;
1237
- const [argument, ...rest] = call.arguments;
1456
+ const [argument, ...rest] = call?.arguments ?? [];
1238
1457
  const name = argument === void 0 ? "default" : argument.type === "SpreadElement" || rest.length ? void 0 : staticString(argument);
1239
1458
  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 additionalFields = readAuthAdditionalFields(body);
1459
+ const sources = [{
1460
+ ...definition,
1461
+ additionalFields: call ? readAuthAdditionalFields(body) : void 0
1462
+ }, ...extensions];
1463
+ const file = (source) => relative(rootDir, source.file);
1464
+ assertUniquePluginIds(sources.map((source) => ({
1465
+ file: file(source),
1466
+ ids: [...source.plugins.map(pluginIdOf), ...source.pluginFields.map((written) => written.plugin)]
1467
+ })));
1468
+ mergeFieldDeclarations(sources.flatMap((source) => [...staticOptionFieldDeclarations(source, rootDir), ...source.pluginFields.flatMap((written) => written.fields.flatMap(({ model, field, attributes }) => attributes ? [{
1469
+ model,
1470
+ field,
1471
+ file: file(written),
1472
+ attributes
1473
+ }] : []))]), (left, right) => differentFieldAttributes(left, right).filter((key) => left[key] !== dynamic && right[key] !== dynamic));
1474
+ const mergedFields = mergeFieldDeclarations(sources.flatMap((source) => [...Object.entries(source.additionalFields ?? {}).flatMap(([model, fields]) => Object.entries(fields).map(([field, attributes]) => ({
1475
+ model,
1476
+ field,
1477
+ file: file(source),
1478
+ attributes
1479
+ }))), ...source.pluginFields.flatMap((written) => written.fields.flatMap(({ model, field, spec }) => spec ? [{
1480
+ model,
1481
+ field,
1482
+ file: file(written),
1483
+ attributes: spec
1484
+ }] : []))]));
1485
+ if (!call) return false;
1486
+ const plugins = [...new Set(sources.flatMap((source) => source.plugins))].sort();
1487
+ const existing = resolveAuthTableSpecs({ plugins });
1488
+ for (const written of sources.flatMap((source) => source.pluginFields)) for (const { model, field, spec } of written.fields) {
1489
+ const column = existing[model]?.fields[field];
1490
+ if (!spec || !column) continue;
1491
+ const attributes = differentFieldAttributes(spec, column).filter((key) => Object.hasOwn(spec, key));
1492
+ if (attributes.length) throw authErrorDiagnostics.AUTH_PLUGIN_SCHEMA_UNREADABLE({
1493
+ plugin: written.plugin,
1494
+ file: file(written),
1495
+ detail: `${model}.${field} cannot change existing column attributes: ${attributes.join(", ")}`
1496
+ });
1497
+ }
1498
+ const additionalFields = Object.keys(mergedFields).length ? mergedFields : void 0;
1499
+ const uuidIds = readAuthGenerateId(body) === "uuid";
1241
1500
  const schema = {
1242
1501
  ...plugins.length ? { plugins } : {},
1243
- ...additionalFields ? { additionalFields } : {}
1502
+ ...additionalFields ? { additionalFields } : {},
1503
+ ...uuidIds ? { generateId: "uuid" } : {}
1244
1504
  };
1245
- if (!plugins.length && !additionalFields) return { database: name };
1246
- resolveAuthTableSpecs(schema);
1247
- return {
1505
+ const specs = resolveAuthTableSpecs(schema);
1506
+ for (const written of sources.flatMap((source) => source.pluginFields)) {
1507
+ const missing = written.fields.filter(({ model, field }) => Object.hasOwn(specs, model) && !Object.hasOwn(specs[model].fields, field)).map(({ model, field }) => `${model}.${field}`);
1508
+ if (missing.length) throw authErrorDiagnostics.AUTH_PLUGIN_FIELD_NOT_IN_SCHEMA({
1509
+ plugin: written.plugin,
1510
+ file: file(written),
1511
+ fields: missing
1512
+ });
1513
+ }
1514
+ return plugins.length || additionalFields || uuidIds ? {
1248
1515
  database: name,
1249
1516
  schema
1517
+ } : { database: name };
1518
+ }
1519
+ function assertAppKeepsLayerTables(app, serverDirs, scan) {
1520
+ const appSpecs = (database) => app.tables && app.tables.database === database ? resolveAuthTableSpecs(app.tables.schema) : {};
1521
+ for (const layer of discoverLayerAuthDefinitions(serverDirs)) {
1522
+ if (layer.handler === app.handler) continue;
1523
+ const definition = readDefinitionObjectBody(layer.handler, scan);
1524
+ const tables = definition && readAuthTablesConfig(definition, [], scan.rootDir);
1525
+ if (!tables) continue;
1526
+ const kept = appSpecs(tables.database);
1527
+ 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]);
1528
+ if (dropped.length) throw authErrorDiagnostics.AUTH_LAYER_DEFINITION_REPLACED({
1529
+ app: relative(scan.rootDir, app.handler),
1530
+ layer: relative(scan.rootDir, layer.handler),
1531
+ dropped
1532
+ });
1533
+ }
1534
+ }
1535
+ function summarizeAuthSource(source, rootDir) {
1536
+ const additional = authCoreModels.flatMap((model) => {
1537
+ const value = readObjectPropertyValue(objectLiteral(readObjectPropertyValue(source.body, model)), "additionalFields");
1538
+ return readObjectEntries(objectLiteral(value && unwrapExpression(value))).map((entry) => `${model}.${entry.key}`);
1539
+ });
1540
+ const written = source.pluginFields.flatMap((plugin) => plugin.fields.flatMap(({ model, field }) => authCoreModels.some((core) => core === model) ? [`${model}.${field}`] : []));
1541
+ return {
1542
+ file: source.file,
1543
+ name: relativeDefinitionFile(rootDir, source.file),
1544
+ plugins: source.pluginCalls,
1545
+ fields: [.../* @__PURE__ */ new Set([...additional, ...written])]
1250
1546
  };
1251
1547
  }
1252
1548
  /** Reports `true`, `false`, or an object literal with only `keys`: the removed placement forms, which create no storage. */
@@ -1269,24 +1565,57 @@ function assertAuthStorageConfig(body, callback, authDatabase) {
1269
1565
  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
1566
  }
1271
1567
  }
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
1568
  function usesAuthDatabase(project) {
1277
1569
  return Boolean(resolveAuthViteConfig(void 0, project.viteRoot ?? project.projectRoot, project)?.tables);
1278
1570
  }
1571
+ /**
1572
+ * The client sources: `auth.client.ts` when the app has one, then each `auth.client.extend.ts` in merge order. A part
1573
+ * must be `export default extendAuthClient({ plugins })`.
1574
+ */
1575
+ function readAuthClientSources(client, extensions, rootDir) {
1576
+ const read = (file, part) => {
1577
+ const module = scanModule(readFileSync(file, "utf8"), file);
1578
+ const name = relativeDefinitionFile(rootDir, file);
1579
+ const call = defaultExportExpression(module);
1580
+ const argument = call?.type === "CallExpression" ? call.arguments[0] : void 0;
1581
+ const body = argument && argument.type !== "SpreadElement" ? objectLiteral(unwrapExpression(argument)) : void 0;
1582
+ if (part) {
1583
+ if (!body || call?.type !== "CallExpression" || call.callee.type !== "Identifier" || call.callee.name !== "extendAuthClient") throw authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({ file: name });
1584
+ const option = readObjectEntries(body).find((entry) => entry.key !== "plugins");
1585
+ if (option) throw authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({
1586
+ file: name,
1587
+ option: option.key || "..."
1588
+ });
1589
+ }
1590
+ return {
1591
+ file,
1592
+ name,
1593
+ plugins: readPluginCalls(module, body),
1594
+ fields: []
1595
+ };
1596
+ };
1597
+ return [...client ? [read(client, false)] : [], ...extensions.map((file) => read(file, true))];
1598
+ }
1279
1599
  function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {}) {
1280
1600
  if (options === false) return;
1601
+ const projectRoot = discovery.projectRoot ?? rootDir;
1281
1602
  const found = discoverProjectAuthDefinition({
1282
- projectRoot: discovery.projectRoot ?? rootDir,
1603
+ projectRoot,
1283
1604
  viteRoot: rootDir,
1284
1605
  serverDirs: discovery.serverDirs
1285
1606
  });
1286
- if (!found) return;
1607
+ const extensionFiles = discoverAuthExtensions(found?.rootDir ?? projectRoot, discovery);
1608
+ if (!found) {
1609
+ if (extensionFiles[0]) throw authErrorDiagnostics.AUTH_EXTENSION_WITHOUT_DEFINITION({ file: relative(projectRoot, extensionFiles[0]) });
1610
+ return;
1611
+ }
1287
1612
  const { definition } = found;
1288
1613
  rootDir = found.rootDir;
1289
- const definitionObject = readDefinitionObjectBody(definition.handler);
1614
+ const scan = {
1615
+ layers: discovery.layerAliases ?? {},
1616
+ rootDir: projectRoot
1617
+ };
1618
+ const definitionObject = readDefinitionObjectBody(definition.handler, scan);
1290
1619
  if (typeof definitionObject === "undefined") throw authErrorDiagnostics.AUTH_C0019({ message: "`defineAuth()` options must be an inline object literal." });
1291
1620
  const body = definitionObject.body;
1292
1621
  assertStaticObjectKeys(body, "options");
@@ -1295,6 +1624,15 @@ function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {})
1295
1624
  const abilities = discoverAuthAbilities(rootDir, { serverDirs: discovery.serverDirs?.slice() });
1296
1625
  const publicRoutes = readAuthAccessPublicConfig(body);
1297
1626
  const components = readAuthComponentsConfig(body);
1627
+ const extensions = extensionFiles.map((file) => readAuthExtension(file, {
1628
+ ...scan,
1629
+ ownsTables: Boolean(readAuthDatabaseCall(body, definitionObject.authDatabase))
1630
+ }));
1631
+ const tables = readAuthTablesConfig(definitionObject, extensions, projectRoot);
1632
+ assertAppKeepsLayerTables({
1633
+ handler: definition.handler,
1634
+ tables
1635
+ }, discovery.serverDirs, scan);
1298
1636
  return {
1299
1637
  ...abilities ? { abilities } : {},
1300
1638
  access: {
@@ -1306,9 +1644,11 @@ function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {})
1306
1644
  basePath,
1307
1645
  ...components ? { components } : {},
1308
1646
  definition,
1647
+ projectRoot,
1309
1648
  rootDir,
1310
1649
  route: readAuthRouteConfig(body),
1311
- tables: readAuthTablesConfig(definitionObject),
1650
+ sources: [definitionObject, ...extensions].map((source) => summarizeAuthSource(source, projectRoot)),
1651
+ tables,
1312
1652
  ...!definitionObject.callback && !["database", "preset"].some((key) => hasObjectProperty(body, key)) ? { implicitMemory: true } : {}
1313
1653
  };
1314
1654
  }
@@ -1381,9 +1721,6 @@ const authTableNames = {
1381
1721
  passkey: "passkey"
1382
1722
  };
1383
1723
  // src/existing-tables.ts
1384
- function isRecord(value) {
1385
- return typeof value === "object" && value !== null && !Array.isArray(value);
1386
- }
1387
1724
  function strings(value) {
1388
1725
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
1389
1726
  }
@@ -1461,17 +1798,26 @@ const generatedAuthSchema = ".vitehub/auth/schema.ts";
1461
1798
  const cachedAccessRouteGuardName = "vite-hub/auth-cached-access-route-guard";
1462
1799
  const memoryDatabaseGuardName = "vite-hub/auth-memory-database-guard";
1463
1800
  const mergeNoExternal = createNoExternalAddition(authPackageName);
1801
+ /** The specifiers of the Auth tables. Each host resolves them to the generated module, so an app imports the tables that Auth adds. */
1802
+ const authSchemaSpecifiers = ["@vite-hub/auth/schema", "vite-hub/auth/schema"];
1803
+ /** The generated module of the Auth tables, which `authSchemaSpecifiers` resolve to when the Definition uses `authDatabase()`. */
1804
+ function authSchemaModule(config) {
1805
+ return resolve(config.projectRoot, generatedAuthSchema);
1806
+ }
1464
1807
  /**
1465
1808
  * A module that builds the Auth tables with the plugins and additional fields of the Definition, and keeps the SQLite
1466
- * tables that the Database has already as `existing` describes them.
1809
+ * tables that the Database has already as `existing` describes them. It imports the package module by file, because
1810
+ * the package specifier resolves to this module.
1467
1811
  */
1468
- function renderAuthSchemaModule(schema, existing, importBase) {
1812
+ function renderAuthSchemaModule(file, schema, existing) {
1469
1813
  const options = JSON.stringify(schema);
1814
+ const packageModule = JSON.stringify(createImportPath(file, ownModule(import.meta.url, "schema")).replaceAll("\\", "/"));
1470
1815
  return [
1471
1816
  "// Generated by the Auth Vite plugin from the plugins and additional fields of the Auth Definition, and from the Auth",
1472
1817
  "// tables of the latest migration of the Database.",
1473
- `import { createAuthPostgresSchema, createAuthSqliteSchema } from ${JSON.stringify(`${importBase}/schema`)}`,
1818
+ `import { createAuthPostgresSchema, createAuthSqliteSchema } from ${packageModule}`,
1474
1819
  "",
1820
+ `export * from ${packageModule}`,
1475
1821
  `export const authSqliteSchema = createAuthSqliteSchema(${options}${existing ? `, ${JSON.stringify(existing)}` : ""})`,
1476
1822
  `export const authPostgresSchema = createAuthPostgresSchema(${options})`,
1477
1823
  ""
@@ -1504,15 +1850,30 @@ async function readTargetDatabase(context, database) {
1504
1850
  migrationsDir: resolve(context.rootDir, getDefaultMigrationsDir(context.rootDir, target, serverDirs))
1505
1851
  };
1506
1852
  }
1507
- /** Lists the Auth Definition as a serializable inspection summary. */
1853
+ /** Lists each file of the resolved source list, with the plugins and fields it adds, as serializable inspection summaries. */
1508
1854
  function inspectAuthDefinitions(options) {
1509
- return summarizeDefinitions(options.projectRoot, discoverAuthDefinitions(options.rootDir, { serverDirs: options.serverDirs }), "server-auth");
1855
+ if (!options.config) return summarizeDefinitions(options.projectRoot, discoverAuthDefinitions(options.rootDir, { serverDirs: options.serverDirs }), "server-auth");
1856
+ const summary = (source, kind) => ({
1857
+ fields: [...source.plugins.length ? [{
1858
+ label: "Plugins",
1859
+ value: source.plugins.join(", ")
1860
+ }] : [], ...source.fields.length ? [{
1861
+ label: "Fields",
1862
+ value: source.fields.join(", ")
1863
+ }] : []],
1864
+ file: source.name,
1865
+ name: "default",
1866
+ source: kind
1867
+ });
1868
+ const { definition, sources } = options.config;
1869
+ 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
1870
  }
1511
1871
  function createAuthNitroConfig(plugin, options) {
1512
1872
  const viteConfig = {
1513
1873
  root: options.projectRoot,
1514
1874
  nitro: options.nitro,
1515
- ...options.serverDirs ? { [VITEHUB_SERVER_DIRS]: options.serverDirs } : {}
1875
+ ...options.serverDirs ? { [VITEHUB_SERVER_DIRS]: options.serverDirs } : {},
1876
+ ...options.nuxtDiscovery ? { [VITEHUB_NUXT_AUTH_DISCOVERY]: options.nuxtDiscovery } : {}
1516
1877
  };
1517
1878
  if (plugin.config && typeof plugin.config === "function") {
1518
1879
  const dev = options.nitro.dev === true;
@@ -1528,8 +1889,14 @@ function createAuthNitroConfig(plugin, options) {
1528
1889
  function renderAuthDefinitionModule(config, options = { serverEnv: false }) {
1529
1890
  if (!config) return "export const definition = undefined\nexport const getAuthApp = () => undefined\nexport default definition\n";
1530
1891
  const runtimeServer = JSON.stringify(options.runtimeServer ?? privateAuthImport(options.importBase ?? authPackageName, "runtime/server"));
1892
+ const [source, ...extensions] = config.sources;
1531
1893
  return [
1532
- `import definition from ${JSON.stringify(config.definition.handler)}`,
1894
+ ...extensions.length ? [
1895
+ `import authDefinition from ${JSON.stringify(config.definition.handler)}`,
1896
+ ...extensions.map((extension, index) => `import extension${index} from ${JSON.stringify(extension.file)}`),
1897
+ `import { applyAuthExtensions } from ${runtimeServer}`,
1898
+ `const definition = applyAuthExtensions(authDefinition, ${JSON.stringify(source?.name)}, [${extensions.map((extension, index) => `{ file: ${JSON.stringify(extension.name)}, extension: extension${index} }`).join(", ")}])`
1899
+ ] : [`import definition from ${JSON.stringify(config.definition.handler)}`],
1533
1900
  options.testMode ? "export const getAuthApp = () => undefined" : "export { useNitroApp as getAuthApp } from \"nitro/app\"",
1534
1901
  ...options.serverEnv ? [
1535
1902
  `import { setAuthRuntimeEnvResolver } from ${runtimeServer}`,
@@ -1597,15 +1964,29 @@ function authAmbientTypesPath(root) {
1597
1964
  function authServerTypesPath(root) {
1598
1965
  return resolve(root, ".vitehub", "types", "auth-server.d.ts");
1599
1966
  }
1967
+ function renderAuthClientModule(client, extensions) {
1968
+ return [
1969
+ client ? `import options from ${JSON.stringify(client)}` : "const options = undefined",
1970
+ ...extensions.map((extension, index) => `import extension${index} from ${JSON.stringify(extension.file)}`),
1971
+ "export default options",
1972
+ `export const extensions = [${extensions.map((extension, index) => `{ file: ${JSON.stringify(extension.name)}, extension: extension${index} }`).join(", ")}]`,
1973
+ ""
1974
+ ].join("\n");
1975
+ }
1600
1976
  function renderAuthAmbientTypes(options = { serverEnv: false }) {
1977
+ const importBase = options.importBase ?? authPackageName;
1978
+ const defaultOf = (file) => `typeof import(${JSON.stringify(file)}).default`;
1979
+ const definition = options.definition && (options.extensions?.length ? `import(${JSON.stringify(importBase)}).ExtendedAuthDefinition<${defaultOf(options.definition)}, [${options.extensions.map(defaultOf).join(", ")}]>` : defaultOf(options.definition));
1980
+ 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
1981
  const entries = [
1602
- ...options.definition ? [`definition: typeof import(${JSON.stringify(options.definition)}).default`] : [],
1982
+ ...definition ? [`definition: ${definition}`] : [],
1603
1983
  ...options.abilities ? [`abilities: typeof import(${JSON.stringify(options.abilities)}).default`] : [],
1604
- ...options.client ? [`client: typeof import(${JSON.stringify(options.client)}).default`] : []
1984
+ ...client ? [`client: ${client}`] : [],
1985
+ ...options.schema ? [`schema: typeof import(${JSON.stringify(options.schema)})`] : []
1605
1986
  ];
1606
1987
  const registry = entries.length ? [`interface AuthRegistry { ${entries.join("; ")} }`] : [];
1607
- if (options.definition) {
1608
- const session = `Pick<import(${JSON.stringify(options.importBase ?? authPackageName)}).AuthAuthorization<{ definition: typeof import(${JSON.stringify(options.definition)}).default }>, "user" | "session">`;
1988
+ if (definition) {
1989
+ const session = `Pick<import(${JSON.stringify(importBase)}).AuthAuthorization<{ definition: ${definition} }>, "user" | "session">`;
1609
1990
  registry.push(`interface AuthRegistry { sessionResult: ${session} }`);
1610
1991
  }
1611
1992
  if (options.serverEnv) return [
@@ -1647,13 +2028,17 @@ function renderAuthServerTypes(importBase = authPackageName) {
1647
2028
  ].join("\n");
1648
2029
  }
1649
2030
  async function refreshAuthGeneratedFiles(root, config, options = {}) {
2031
+ const typeImport = (file) => typeImportSpecifier(dirname(authAmbientTypesPath(root)), file);
1650
2032
  await Promise.all([
1651
2033
  writeFileIfChanged(resolve(root, generatedAuthAccessMiddlewareHandler), renderAuthAccessMiddlewareHandler(config, options.importBase)),
1652
2034
  writeFileIfChanged(authAmbientTypesPath(root), renderAuthAmbientTypes({
1653
- abilities: config?.abilities && typeImportSpecifier(dirname(authAmbientTypesPath(root)), config.abilities),
1654
- client: options.client && typeImportSpecifier(dirname(authAmbientTypesPath(root)), options.client),
1655
- definition: config && typeImportSpecifier(dirname(authAmbientTypesPath(root)), config.definition.handler),
2035
+ abilities: config?.abilities && typeImport(config.abilities),
2036
+ client: options.client && typeImport(options.client),
2037
+ clientExtensions: options.clientExtensions?.map((extension) => typeImport(extension.file)),
2038
+ definition: config && typeImport(config.definition.handler),
2039
+ extensions: config?.sources.slice(1).map((extension) => typeImport(extension.file)),
1656
2040
  importBase: options.importBase,
2041
+ schema: config?.tables ? typeImportSpecifier(dirname(authAmbientTypesPath(root)), authSchemaModule(config)) : void 0,
1657
2042
  serverEnv: Boolean(options.serverEnv)
1658
2043
  })),
1659
2044
  writeFileIfChanged(authServerTypesPath(root), renderAuthServerTypes(options.importBase)),
@@ -1734,14 +2119,18 @@ function hubAuth(options, internalOptions = {}) {
1734
2119
  let resolved;
1735
2120
  let runtimeConfig;
1736
2121
  let clientFile;
2122
+ let clientSources = [];
2123
+ const clientExtensions = () => clientSources.filter((source) => source.file !== clientFile);
1737
2124
  let serverDirs;
2125
+ let nuxtDiscovery;
1738
2126
  let serverEnv = false;
1739
2127
  function readViteAuthConfig(config) {
1740
2128
  const root = resolve(config.root ?? process.cwd());
1741
2129
  const projectRoot = config[VITEHUB_PROJECT_ROOT];
1742
2130
  return resolveAuthViteConfig(options, root, {
1743
2131
  projectRoot: projectRoot ? resolve(projectRoot) : resolveViteHubProjectRoot(root),
1744
- serverDirs
2132
+ serverDirs,
2133
+ layerAliases: nuxtDiscovery?.layerAliases ?? internalOptions.layerAliases
1745
2134
  });
1746
2135
  }
1747
2136
  function refreshRuntimeConfig() {
@@ -1765,24 +2154,22 @@ function hubAuth(options, internalOptions = {}) {
1765
2154
  if (authOptions === false) return [];
1766
2155
  const config = resolveAuthViteConfig(authOptions, context.root, {
1767
2156
  projectRoot: context.projectRoot ?? resolveViteHubProjectRoot(context.root),
1768
- serverDirs: context.serverDirs ?? serverDirs
2157
+ serverDirs: context.serverDirs ?? serverDirs,
2158
+ layerAliases: nuxtDiscovery?.layerAliases ?? internalOptions.layerAliases
1769
2159
  });
1770
2160
  if (!config?.tables) return [];
1771
2161
  const { database, schema } = config.tables;
1772
- const schemaModule = resolve(config.rootDir, generatedAuthSchema);
2162
+ const schemaModule = authSchemaModule(config);
1773
2163
  const { dialect, migrationsDir } = await readTargetDatabase(context, database);
1774
2164
  const tables = schema ? Object.fromEntries(Object.keys(resolveAuthTableSpecs(schema)).map((model) => [model, authSqlName(model)])) : authTableNames;
1775
2165
  const existing = dialect === "sqlite" ? readAuthExistingTables(migrationsDir, Object.values(tables)) : void 0;
1776
- const adopted = existing && Object.keys(existing).length ? existing : void 0;
1777
- const generated = Boolean(schema || adopted);
1778
- if (generated) await writeFileIfChanged(schemaModule, renderAuthSchemaModule(schema ?? {}, adopted, importBase));
1779
- else await rm(schemaModule, { force: true });
2166
+ await writeFileIfChanged(schemaModule, renderAuthSchemaModule(schemaModule, schema ?? {}, existing && Object.keys(existing).length ? existing : void 0));
1780
2167
  return [{
1781
2168
  name: "auth",
1782
2169
  database,
1783
2170
  dialect,
1784
2171
  definition: {
1785
- module: generated ? schemaModule : `${importBase}/schema`,
2172
+ module: schemaModule,
1786
2173
  export: dialect === "postgresql" ? "authPostgresSchema" : "authSqliteSchema"
1787
2174
  },
1788
2175
  tables,
@@ -1797,6 +2184,8 @@ function hubAuth(options, internalOptions = {}) {
1797
2184
  list: () => {
1798
2185
  const rootDir = resolve(resolved?.root ?? process.cwd());
1799
2186
  return inspectAuthDefinitions({
2187
+ client: clientSources,
2188
+ config: runtimeConfig,
1800
2189
  projectRoot: resolveViteHubProjectRoot(rootDir),
1801
2190
  rootDir,
1802
2191
  serverDirs
@@ -1807,7 +2196,9 @@ function hubAuth(options, internalOptions = {}) {
1807
2196
  },
1808
2197
  config(config, env) {
1809
2198
  const configRoot = config.root || process.cwd();
1810
- serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
2199
+ const discovery = config;
2200
+ serverDirs = discovery["__vitehubServerDirs"] ?? serverDirs;
2201
+ nuxtDiscovery = discovery["__vitehubNuxtAuthDiscovery"] ?? nuxtDiscovery;
1811
2202
  const authConfig = readViteAuthConfig(config);
1812
2203
  if (authConfig?.tables && internalOptions.databaseDisabled) throw authErrorDiagnostics.AUTH_DATABASE_DISABLED({ definition: relative(configRoot, authConfig.definition.handler) });
1813
2204
  const dev = env?.command === "serve";
@@ -1817,6 +2208,10 @@ function hubAuth(options, internalOptions = {}) {
1817
2208
  const hasMemoryDatabaseGuard = Boolean(authConfig?.implicitMemory && !dev);
1818
2209
  if (hasNitroHandlers || applicationBaseURL || hasMemoryDatabaseGuard) Object.assign(config, { nitro });
1819
2210
  const contribution = {
2211
+ ...authConfig?.tables ? { resolve: { alias: authSchemaSpecifiers.map((find) => ({
2212
+ find,
2213
+ replacement: authSchemaModule(authConfig)
2214
+ })) } } : {},
1820
2215
  optimizeDeps: {
1821
2216
  exclude: [authPackageName, "vite-hub/auth"],
1822
2217
  include: [`${authPackageName} > better-auth/vue`]
@@ -1834,9 +2229,13 @@ function hubAuth(options, internalOptions = {}) {
1834
2229
  resolved = config;
1835
2230
  serverEnv = hasServerEnvIntegration(config);
1836
2231
  const runtimeConfig = refreshRuntimeConfig();
1837
- clientFile = options === false ? void 0 : discoverAuthClient(config.root);
1838
- await refreshAuthGeneratedFiles(resolveViteHubProjectRoot(config.root), runtimeConfig, {
2232
+ const projectRoot = resolveViteHubProjectRoot(config.root);
2233
+ const appDir = nuxtDiscovery?.appDir ?? config.root;
2234
+ clientFile = options === false ? void 0 : discoverAuthClient(appDir, nuxtDiscovery);
2235
+ clientSources = options === false ? [] : readAuthClientSources(clientFile, discoverAuthClientExtensions(appDir, nuxtDiscovery), projectRoot);
2236
+ await refreshAuthGeneratedFiles(projectRoot, runtimeConfig, {
1839
2237
  client: clientFile,
2238
+ clientExtensions: clientExtensions(),
1840
2239
  importBase,
1841
2240
  serverEnv
1842
2241
  });
@@ -1856,6 +2255,7 @@ function hubAuth(options, internalOptions = {}) {
1856
2255
  const config = refreshRuntimeConfig();
1857
2256
  await refreshAuthGeneratedFiles(projectRoot, config, {
1858
2257
  client: clientFile,
2258
+ clientExtensions: clientExtensions(),
1859
2259
  importBase,
1860
2260
  serverEnv
1861
2261
  });
@@ -1879,10 +2279,11 @@ function hubAuth(options, internalOptions = {}) {
1879
2279
  },
1880
2280
  async handleHotUpdate(context) {
1881
2281
  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\.(?:c|m)?[jt]s$/i.test(changed)) return;
2282
+ 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
2283
  const config = refreshRuntimeConfig();
1884
2284
  await refreshAuthGeneratedFiles(resolveViteHubProjectRoot(context.server.config.root), config, {
1885
2285
  client: clientFile,
2286
+ clientExtensions: clientExtensions(),
1886
2287
  importBase,
1887
2288
  serverEnv
1888
2289
  });
@@ -1899,7 +2300,7 @@ function hubAuth(options, internalOptions = {}) {
1899
2300
  filter: { id: /^#vitehub\/auth\/(?:abilities|client|definition|server)$/ },
1900
2301
  handler(id) {
1901
2302
  if (id === "#vitehub/auth/abilities") return RESOLVED_AUTH_ABILITIES_ID;
1902
- if (id === "#vitehub/auth/client") return clientFile ?? RESOLVED_AUTH_CLIENT_ID;
2303
+ if (id === "#vitehub/auth/client") return clientExtensions().length ? RESOLVED_AUTH_CLIENT_ID : clientFile ?? RESOLVED_AUTH_CLIENT_ID;
1903
2304
  if (id === "#vitehub/auth/definition") return RESOLVED_AUTH_DEFINITION_ID;
1904
2305
  if (id === "#vitehub/auth/server") return RESOLVED_AUTH_SERVER_ID;
1905
2306
  }
@@ -1908,7 +2309,7 @@ function hubAuth(options, internalOptions = {}) {
1908
2309
  filter: { id: /^\0(?:virtual:vitehub\/auth\/(?:abilities|client)|#vitehub\/auth\/(?:definition|server))$/ },
1909
2310
  handler(id) {
1910
2311
  if (id === RESOLVED_AUTH_ABILITIES_ID) return renderAuthAbilitiesModule(runtimeConfig);
1911
- if (id === RESOLVED_AUTH_CLIENT_ID) return "export default undefined\n";
2312
+ if (id === RESOLVED_AUTH_CLIENT_ID) return clientExtensions().length ? renderAuthClientModule(clientFile, clientExtensions()) : "export default undefined\n";
1912
2313
  if (id === RESOLVED_AUTH_DEFINITION_ID) return renderAuthDefinitionModule(runtimeConfig, {
1913
2314
  importBase,
1914
2315
  serverEnv,
@@ -1919,4 +2320,4 @@ function hubAuth(options, internalOptions = {}) {
1919
2320
  }
1920
2321
  };
1921
2322
  }
1922
- export { resolveViteHubProjectRoot as _, AUTH_VITE_PLUGIN_NAME as a, writeNuxtAuthDefinition as c, authAbilitiesCandidates as d, discoverProjectAuthDefinition as f, resolveNuxtServerDirs as g, methodOrder as h, AUTH_SERVER_ID as i, resolveAuthViteConfig as l, createCachingRouteRuleFinder as m, AUTH_CLIENT_ID as n, createAuthNitroConfig as o, cachingRuleNames as p, AUTH_DEFINITION_ID as r, hubAuth as s, AUTH_ABILITIES_ID as t, usesAuthDatabase as u };
2323
+ 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 };