@vite-hub/auth 0.4.1 → 0.5.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 (66) hide show
  1. package/README.md +31 -7
  2. package/dist/{abilities-CbmTAoS_.d.ts → abilities-9jC7iuN0.d.ts} +2 -2
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-DcgChwCN.d.ts → ability-error-DUWJ6Q1W.d.ts} +1 -1
  5. package/dist/{ability-error-IeZQBr_-.js → ability-error-DmnUGicq.js} +1 -1
  6. package/dist/access-pages-FNQTyGRD.js +96 -0
  7. package/dist/agent.js +3 -3
  8. package/dist/{auth-instance-CmDogt4D.js → auth-instance-zYMjldPG.js} +227 -25
  9. package/dist/{cli-ubYJpAL_.d.ts → cli-NCtitmny.d.ts} +1 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/{console-runtime-_LrpyCYY.js → console-runtime-CuXRDhGy.js} +67 -33
  13. package/dist/{console-runtime-D2ai-Et5.d.ts → console-runtime-Dqidb3zF.d.ts} +13 -11
  14. package/dist/console-runtime.d.ts +2 -2
  15. package/dist/console-runtime.js +1 -1
  16. package/dist/console.d.ts +1 -1
  17. package/dist/{database-options-DpOVjUti.js → database-options-CcjUG-us.js} +1 -1
  18. package/dist/{database-schema-options-Sk-1Bvyu.js → database-schema-options-CTKCAfqW.js} +1 -1
  19. package/dist/database.d.ts +1 -1
  20. package/dist/database.js +4 -4
  21. package/dist/{definition-BCaLA9kW.js → definition-BFT9T6In.js} +12 -4
  22. package/dist/{error-diagnostics-Dymr-S_n.js → error-diagnostics-uEbxSY2G.js} +8 -2
  23. package/dist/{events-DCfuicoo.js → events-DJmO9a9I.js} +1 -1
  24. package/dist/forward.js +1 -1
  25. package/dist/index.d.ts +3 -2
  26. package/dist/index.js +4 -3
  27. package/dist/internal/server.d.ts +4 -4
  28. package/dist/internal/server.js +4 -4
  29. package/dist/{invariant-D8_xBqmZ.js → invariant-DolT9EEx.js} +1 -1
  30. package/dist/{mcp-token-CpxLyl_p.js → mcp-token-BhonlK9C.js} +2 -2
  31. package/dist/mcp.js +1 -1
  32. package/dist/{members-DdlsS8kJ.js → members-Cl3hFRjk.js} +3 -3
  33. package/dist/nitro-kit-32CVgbWS.js +44 -0
  34. package/dist/nuxt.d.ts +32 -19
  35. package/dist/nuxt.js +337 -16
  36. package/dist/own-access-C8pwo_Kn.js +31 -0
  37. package/dist/own-access-CdgEICjO.d.ts +20 -0
  38. package/dist/presets.js +1 -1
  39. package/dist/runtime/console.d.ts +1 -1
  40. package/dist/runtime/console.js +2 -2
  41. package/dist/runtime/empty-abilities.d.ts +1 -1
  42. package/dist/runtime/empty-definition.d.ts +1 -1
  43. package/dist/runtime/server.d.ts +3 -2
  44. package/dist/runtime/server.js +23 -14
  45. package/dist/runtime/vue-nuxt.js +70 -28
  46. package/dist/schema.d.ts +71 -19
  47. package/dist/schema.js +5 -3
  48. package/dist/{server-C8TlOrSy.d.ts → server-B-zNtSvm.d.ts} +9 -10
  49. package/dist/{server-BM-RSf1T.d.ts → server-Ci2i6p1S.d.ts} +7 -6
  50. package/dist/{server-BG_MFd4q.js → server-CyqLFm3L.js} +45 -25
  51. package/dist/server.d.ts +2 -2
  52. package/dist/server.js +2 -2
  53. package/dist/{session-cookies-DVzjOKc7.js → session-cookies-CZmZS5QF.js} +2 -2
  54. package/dist/{set-cookie-DmqWq6kj.js → set-cookie-DWIyCCJO.js} +1 -1
  55. package/dist/{table-specs-DbXyaXWs.d.ts → table-specs-BhWz_U0M.d.ts} +255 -1
  56. package/dist/{table-specs-CURphR3n.js → table-specs-D0VLp1U4.js} +43 -43
  57. package/dist/test.d.ts +1 -1
  58. package/dist/test.js +2 -2
  59. package/dist/{types-CruflEFI.d.ts → types-gl-myjZc.d.ts} +51 -4
  60. package/dist/{vite-Dy0Xhq4H.js → vite-QKjsPLwP.js} +349 -120
  61. package/dist/vite.d.ts +6 -2
  62. package/dist/vite.js +1 -1
  63. package/dist/vue.d.ts +17 -68
  64. package/dist/vue.js +22 -69
  65. package/package.json +13 -9
  66. package/dist/shared-DRtfuFsV.js +0 -12
@@ -1,11 +1,12 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
2
- import { n as isRecordOrFunction, t as isRecord$1 } from "./object-Da1zyPCR.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-uEbxSY2G.js";
2
+ import { t as isRecord$1 } from "./object-Da1zyPCR.js";
3
3
  import { i as resetAuth } from "./runtime-state-ojQCzKOc.js";
4
- import { t as invariant } from "./invariant-D8_xBqmZ.js";
4
+ import { t as invariant } from "./invariant-DolT9EEx.js";
5
5
  import { r as resolveAccessRoutePath, t as accessRouteSyntaxError } from "./application-path-DuTpfGFj.js";
6
- import { t as normalizeAuthBasePath } from "./shared-DRtfuFsV.js";
7
- import { a as authDatabaseSchemaError, i as authDatabasePlacementError, n as authDatabaseAdditionalFieldsError, o as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-DpOVjUti.js";
8
- import { i as resolveAuthTableSpecs, n as authSqlName } from "./table-specs-CURphR3n.js";
6
+ import { a as normalizeAuthBasePath, n as assertAuthPages } from "./access-pages-FNQTyGRD.js";
7
+ import { a as authDatabaseSchemaError, i as authDatabasePlacementError, n as authDatabaseAdditionalFieldsError, o as authMemoryDatabaseError, t as assertAuthDatabaseIdStrategy } from "./database-options-CcjUG-us.js";
8
+ import { t as createNitroServerKit } from "./nitro-kit-32CVgbWS.js";
9
+ import { i as resolveAuthTableSpecs, n as authSqlName } from "./table-specs-D0VLp1U4.js";
9
10
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
10
11
  import { basename, dirname, join, parse, relative, resolve } from "node:path";
11
12
  import { fileURLToPath } from "node:url";
@@ -33,10 +34,10 @@ const resolve$1 = function(...arguments_) {
33
34
  const path = index >= 0 ? arguments_[index] : cwd();
34
35
  if (!path || path.length === 0) continue;
35
36
  resolvedPath = `${path}/${resolvedPath}`;
36
- resolvedAbsolute = isAbsolute(path);
37
+ resolvedAbsolute = isAbsolute$1(path);
37
38
  }
38
39
  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
39
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
40
+ if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
40
41
  return resolvedPath.length > 0 ? resolvedPath : ".";
41
42
  };
42
43
  function normalizeString(path, allowAboveRoot) {
@@ -89,7 +90,7 @@ function normalizeString(path, allowAboveRoot) {
89
90
  }
90
91
  return res;
91
92
  }
92
- const isAbsolute = function(p) {
93
+ const isAbsolute$1 = function(p) {
93
94
  return _IS_ABSOLUTE_RE.test(p);
94
95
  };
95
96
  const relative$1 = function(from, to) {
@@ -107,7 +108,7 @@ const relative$1 = function(from, to) {
107
108
  const dirname$1 = function(p) {
108
109
  const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
109
110
  if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
110
- return segments.join("/") || (isAbsolute(p) ? "/" : ".");
111
+ return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
111
112
  };
112
113
  //#endregion
113
114
  //#region ../internal/src/inspect.ts
@@ -214,7 +215,7 @@ function hasProjectRootDirectoryMarker(root) {
214
215
  for (const marker of projectRootDirectoryMarkers) try {
215
216
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
216
217
  } catch (error) {
217
- if (error.code !== "ENOENT") throw error;
218
+ if (!isMissingProjectMarker(error)) throw error;
218
219
  }
219
220
  return false;
220
221
  }
@@ -228,11 +229,82 @@ function hasProjectRootFileMarker(root, markers) {
228
229
  try {
229
230
  if (statSync(resolve(root, ...path)).isFile()) return true;
230
231
  } catch (error) {
231
- if (error.code !== "ENOENT") throw error;
232
+ if (!isMissingProjectMarker(error)) throw error;
232
233
  }
233
234
  }
234
235
  return false;
235
236
  }
237
+ function isMissingProjectMarker(error) {
238
+ const code = error.code;
239
+ return code === "ENOENT" || code === "ENOTDIR";
240
+ }
241
+ //#endregion
242
+ //#region src/route-rule-cache.ts
243
+ /** Route rules that keep one response and serve it to many visitors. */
244
+ const cachingRuleNames = [
245
+ "cache",
246
+ "isr",
247
+ "prerender",
248
+ "static"
249
+ ];
250
+ /** Nitro caches and prerenders only GET and HEAD requests. */
251
+ const cachedMethods = ["GET", "HEAD"];
252
+ /** On one pattern, h3 merges the rules for every method first, then GET rules, then HEAD rules. */
253
+ const methodOrder = [
254
+ "",
255
+ "GET",
256
+ "HEAD"
257
+ ];
258
+ /** h3 applies the GET rules of a pattern to HEAD requests too. */
259
+ function appliesTo(entry, method) {
260
+ return !entry.method || entry.method === method || method === "HEAD" && entry.method === "GET";
261
+ }
262
+ /**
263
+ * Reads the route rules that Nitro serves and returns a function that finds a route rule that caches or prerenders a
264
+ * guarded rou3 pattern. `toPattern` maps the path of a rule key to the rou3 pattern that the guard pattern is compared
265
+ * with.
266
+ *
267
+ * The finder compares patterns, not sample paths. A rule that caches and matches at least one guarded path counts,
268
+ * unless a `false` value of the same rule turns the cache off on all of these paths: the `false` rule must match every
269
+ * guarded path, or every path of the caching rule, and h3 must merge it after the caching rule. A cache that more than
270
+ * one `false` rule turns off together still counts. `toPattern` can fold the case of the rule paths, as Nuxt does when
271
+ * its router is not case sensitive.
272
+ */
273
+ async function createCachingRouteRuleFinder(routeRules, toPattern = (path) => path) {
274
+ const [{ normalizeRouteRules }, { compareRoutes, routesOverlap }] = await Promise.all([import("h3/rules"), import("rou3")]);
275
+ const entries = Object.entries(normalizeRouteRules(routeRules)).map(([key, rules]) => {
276
+ const [, method = "", path = key] = /^([A-Z]+) (\/.*)$/.exec(key) ?? [];
277
+ return {
278
+ key,
279
+ method,
280
+ pattern: toPattern(path),
281
+ rules
282
+ };
283
+ });
284
+ return (guarded, { methods = cachedMethods, names = cachingRuleNames, exempt } = {}) => {
285
+ for (const method of methods) {
286
+ const applied = entries.filter((entry) => appliesTo(entry, method));
287
+ for (const name of names) {
288
+ const turnsOff = (entry, off) => {
289
+ if (off.rules[name] !== false) return false;
290
+ const relation = compareRoutes(off.pattern, entry.pattern);
291
+ if (relation === "equal") return methodOrder.indexOf(off.method) > methodOrder.indexOf(entry.method);
292
+ return relation === "subset" && ["equal", "superset"].includes(compareRoutes(off.pattern, guarded));
293
+ };
294
+ for (const entry of applied) {
295
+ const value = entry.rules[name];
296
+ if (value === void 0 || value === false || !routesOverlap(guarded, entry.pattern)) continue;
297
+ if (applied.some((off) => turnsOff(entry, off)) || exempt?.(entry, applied, name)) continue;
298
+ return {
299
+ key: entry.key,
300
+ name,
301
+ method
302
+ };
303
+ }
304
+ }
305
+ }
306
+ };
307
+ }
236
308
  //#endregion
237
309
  //#region ../internal/src/build/paths.ts
238
310
  function resolveRuntimeModule(packageDir, modulePath) {
@@ -262,35 +334,6 @@ function ownModule(importMetaUrl, modulePath) {
262
334
  return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
263
335
  }
264
336
  //#endregion
265
- //#region ../internal/src/nitro-kit.ts
266
- function cloneArray(value) {
267
- return Array.isArray(value) ? [...value] : [];
268
- }
269
- function sameHandler(left, right) {
270
- return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
271
- }
272
- /** Create a Nitro 3 configuration builder for generated ViteHub output. */
273
- function createNitroServerKit(value = {}) {
274
- const config = isRecordOrFunction(value) ? { ...value } : {};
275
- const handlers = cloneArray(config.handlers);
276
- const plugins = cloneArray(config.plugins);
277
- config.handlers = handlers;
278
- config.plugins = plugins;
279
- return {
280
- config,
281
- addHandler(handler, position = "end") {
282
- if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
283
- if (position === "start") handlers.unshift({ ...handler });
284
- else handlers.push({ ...handler });
285
- },
286
- addPlugin(plugin, position = "end") {
287
- if (plugins.includes(plugin)) return;
288
- if (position === "start") plugins.unshift(plugin);
289
- else plugins.push(plugin);
290
- }
291
- };
292
- }
293
- //#endregion
294
337
  //#region ../internal/src/definition-catalog.ts
295
338
  /** `writeFileIfChangedSync` for async callers. */
296
339
  async function writeFileIfChanged(file, contents) {
@@ -328,25 +371,6 @@ async function flattenPluginOptions(plugins) {
328
371
  }
329
372
  //#endregion
330
373
  //#region src/access-route-cache.ts
331
- /** Route rules that keep one response and serve it to many visitors. Nitro stores `swr` as `cache`. */
332
- const cachingRuleNames = [
333
- "cache",
334
- "isr",
335
- "prerender",
336
- "static"
337
- ];
338
- /** Nitro caches and prerenders only GET and HEAD requests. */
339
- const cachedMethods = ["GET", "HEAD"];
340
- /** On one pattern, h3 merges the rules for every method first, then GET rules, then HEAD rules. */
341
- const methodOrder = [
342
- "",
343
- "GET",
344
- "HEAD"
345
- ];
346
- /** h3 applies the GET rules of a pattern to HEAD requests too. */
347
- function appliesTo(entry, method) {
348
- return !entry.method || entry.method === method || method === "HEAD" && entry.method === "GET";
349
- }
350
374
  /**
351
375
  * The rou3 pattern of the paths that the access middleware guards for a route. The middleware matches the path
352
376
  * literally, so the pattern escapes every character that rou3 reads as syntax. In rou3, `/**` also matches the path
@@ -359,51 +383,24 @@ function accessRoutePattern(route, baseURL) {
359
383
  }
360
384
  /**
361
385
  * Stops the build when a route rule caches or prerenders a path that `access.routes` guards. The cache would keep the
362
- * response of one visitor and serve it to others.
363
- *
364
- * The check compares patterns, not sample paths. A rule that caches and matches at least one guarded path fails,
365
- * unless a `false` value of the same rule turns the cache off on all of these paths: the `false` rule must match every
366
- * guarded path, or every path of the caching rule, and h3 must merge it after the caching rule. A cache that more than
367
- * one `false` rule turns off together still fails. A rule whose paths are all in one route of `publicRoutes` passes,
368
- * because the middleware guards none of them.
386
+ * response of one visitor and serve it to others. `createCachingRouteRuleFinder` holds the rules of the check. A rule
387
+ * whose paths are all in one route of `publicRoutes` passes, because the middleware guards none of them.
369
388
  */
370
389
  async function assertNoCachedAccessRoutes(routes, routeRules, baseURL = "/", publicRoutes = []) {
371
390
  const guards = routes.filter((route) => !route.method || cachedMethods.includes(route.method.toUpperCase()));
372
391
  if (!guards.length || !Object.keys(routeRules).length) return;
373
- const [{ normalizeRouteRules }, { compareRoutes, routesOverlap }] = await Promise.all([import("h3/rules"), import("rou3")]);
374
392
  const base = baseURL.replace(/\/$/, "");
375
- const entries = Object.entries(normalizeRouteRules(routeRules)).map(([key, rules]) => {
376
- const [, method = "", path = key] = /^([A-Z]+) (\/.*)$/.exec(key) ?? [];
377
- return {
378
- key,
379
- method,
380
- pattern: `${base}${path}`,
381
- rules
382
- };
383
- });
393
+ const [findCachingRule, { compareRoutes }] = await Promise.all([createCachingRouteRuleFinder(routeRules, (path) => `${base}${path}`), import("rou3")]);
384
394
  const exceptions = publicRoutes.map((route) => accessRoutePattern(route, baseURL));
385
395
  const isPublic = (entry) => exceptions.some((pattern) => ["equal", "superset"].includes(compareRoutes(pattern, entry.pattern)));
386
396
  for (const guard of guards) {
387
- const guarded = accessRoutePattern(guard.route, baseURL);
388
397
  const method = guard.method?.toUpperCase();
389
- const methods = !method || method === "GET" ? cachedMethods : [method];
390
- for (const method of methods) {
391
- const applied = entries.filter((entry) => appliesTo(entry, method));
392
- for (const name of cachingRuleNames) {
393
- const turnsOff = (entry, off) => {
394
- if (off.rules[name] !== false) return false;
395
- const relation = compareRoutes(off.pattern, entry.pattern);
396
- if (relation === "equal") return methodOrder.indexOf(off.method) > methodOrder.indexOf(entry.method);
397
- return relation === "subset" && ["equal", "superset"].includes(compareRoutes(off.pattern, guarded));
398
- };
399
- for (const entry of applied) {
400
- const value = entry.rules[name];
401
- if (value === void 0 || value === false || !routesOverlap(guarded, entry.pattern) || isPublic(entry)) continue;
402
- if (applied.some((off) => turnsOff(entry, off))) continue;
403
- throw authErrorDiagnostics.AUTH_B0002({ message: `[vitehub] Route rule ${JSON.stringify(entry.key)} sets \`${name}\` on ${method} requests to paths that the \`access.routes\` entry ${JSON.stringify(guard.route)} guards. A cached or prerendered response is made for one visitor and served to others.` });
404
- }
405
- }
406
- }
398
+ const cached = findCachingRule(accessRoutePattern(guard.route, baseURL), {
399
+ exempt: isPublic,
400
+ ...method && method !== "GET" ? { methods: [method] } : {}
401
+ });
402
+ if (!cached) continue;
403
+ throw authErrorDiagnostics.AUTH_B0002({ message: `[vitehub] Route rule ${JSON.stringify(cached.key)} sets \`${cached.name}\` on ${cached.method} requests to paths that the \`access.routes\` entry ${JSON.stringify(guard.route)} guards. A cached or prerendered response is made for one visitor and served to others.` });
407
404
  }
408
405
  }
409
406
  //#endregion
@@ -662,24 +659,181 @@ const authSchemaPluginImports = {
662
659
  "@better-auth/api-key": { apiKey: "apiKey" },
663
660
  "@better-auth/stripe": { stripe: "stripe" }
664
661
  };
665
- /** The plugins of `AuthSchemaPlugin` that `module` imports and calls, such as `twoFactor()` from `better-auth/plugins`. */
666
- function readAuthSchemaPlugins(module) {
667
- const locals = /* @__PURE__ */ new Map();
668
- for (const statement of module.program.body) {
669
- if (statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
670
- const source = statement.source.value.startsWith("better-auth/plugins/") ? "better-auth/plugins" : statement.source.value;
671
- const exports = authSchemaPluginImports[source];
672
- if (!exports) continue;
662
+ const viteExtensions = [
663
+ ".mjs",
664
+ ".js",
665
+ ".mts",
666
+ ".ts",
667
+ ".jsx",
668
+ ".tsx",
669
+ ".json"
670
+ ];
671
+ const typeScriptSources = {
672
+ ".js": [".ts", ".tsx"],
673
+ ".jsx": [".tsx"],
674
+ ".mjs": [".mts"],
675
+ ".cjs": [".cts"]
676
+ };
677
+ const isFile = (file) => existsSync(file) && statSync(file).isFile();
678
+ /**
679
+ * The file of a relative import, resolved in the order Vite uses: the file itself, the TypeScript source of a `.js`
680
+ * path, the path with each extension, then the `index` file of the folder.
681
+ */
682
+ function resolveLocalModule(importer, specifier) {
683
+ const path = resolve(dirname(importer), specifier);
684
+ if (isFile(path)) return path;
685
+ const extension = Object.keys(typeScriptSources).find((item) => path.endsWith(item));
686
+ return [
687
+ ...extension ? typeScriptSources[extension].map((item) => path.slice(0, -extension.length) + item) : [],
688
+ ...viteExtensions.map((item) => path + item),
689
+ ...viteExtensions.map((item) => resolve(path, `index${item}`))
690
+ ].find(isFile);
691
+ }
692
+ const nameOf = (node) => node.type === "Identifier" ? node.name : String(node.value);
693
+ function addBoundNames(pattern, names) {
694
+ walk(pattern, (node) => {
695
+ if (node.type === "Identifier") names.push(node.name);
696
+ if (node.type === "AssignmentPattern") {
697
+ addBoundNames(node.left, names);
698
+ return false;
699
+ }
700
+ });
701
+ }
702
+ function readModuleBindings(module) {
703
+ const bindings = {
704
+ declarations: /* @__PURE__ */ new Map(),
705
+ imports: /* @__PURE__ */ new Map(),
706
+ exports: /* @__PURE__ */ new Map(),
707
+ exportAll: [],
708
+ pluginFactories: /* @__PURE__ */ new Map()
709
+ };
710
+ const localFile = (specifier) => specifier.startsWith("./") || specifier.startsWith("../") ? resolveLocalModule(module.file, specifier) : void 0;
711
+ const declare = (name, node) => bindings.declarations.set(name, [...bindings.declarations.get(name) ?? [], node]);
712
+ const readDeclaration = (declaration, exported) => {
713
+ const names = [];
714
+ if ((declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") && declaration.id) names.push(declaration.id.name);
715
+ if (declaration.type === "VariableDeclaration") for (const declarator of declaration.declarations) {
716
+ const bound = [];
717
+ addBoundNames(declarator.id, bound);
718
+ for (const name of bound) declare(name, declarator);
719
+ names.push(...bound);
720
+ }
721
+ else for (const name of names) declare(name, declaration);
722
+ if (exported) for (const name of names) bindings.exports.set(name, { local: name });
723
+ };
724
+ for (const statement of module.program.body) if (statement.type === "ImportDeclaration") {
725
+ if (statement.importKind === "type") continue;
726
+ const source = statement.source.value;
727
+ const factories = authSchemaPluginImports[source.startsWith("better-auth/plugins/") ? "better-auth/plugins" : source];
728
+ const file = localFile(source);
673
729
  for (const specifier of statement.specifiers) {
674
- if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") continue;
675
- const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
676
- if (Object.hasOwn(exports, imported)) locals.set(specifier.local.name, exports[imported]);
730
+ if (specifier.type === "ImportSpecifier" && specifier.importKind === "type") continue;
731
+ const imported = specifier.type === "ImportSpecifier" ? nameOf(specifier.imported) : specifier.type === "ImportDefaultSpecifier" ? "default" : "*";
732
+ if (factories && Object.hasOwn(factories, imported)) bindings.pluginFactories.set(specifier.local.name, factories[imported]);
733
+ if (file) bindings.imports.set(specifier.local.name, {
734
+ file,
735
+ imported
736
+ });
677
737
  }
678
- }
738
+ } else if (statement.type === "ExportNamedDeclaration") {
739
+ if (statement.exportKind === "type") continue;
740
+ if (statement.declaration) readDeclaration(statement.declaration, true);
741
+ const file = statement.source ? localFile(statement.source.value) : void 0;
742
+ for (const specifier of statement.specifiers) {
743
+ if (specifier.exportKind === "type") continue;
744
+ const local = nameOf(specifier.local);
745
+ if (statement.source) {
746
+ if (file) bindings.exports.set(nameOf(specifier.exported), {
747
+ file,
748
+ imported: local
749
+ });
750
+ } else bindings.exports.set(nameOf(specifier.exported), { local });
751
+ }
752
+ } else if (statement.type === "ExportAllDeclaration") {
753
+ const file = statement.exportKind === "type" ? void 0 : localFile(statement.source.value);
754
+ if (!file) continue;
755
+ if (statement.exported) bindings.exports.set(nameOf(statement.exported), {
756
+ file,
757
+ imported: "*"
758
+ });
759
+ else bindings.exportAll.push(file);
760
+ } else if (statement.type === "ExportDefaultDeclaration") {
761
+ declare("default", statement.declaration);
762
+ bindings.exports.set("default", { local: "default" });
763
+ const declaration = statement.declaration;
764
+ if ((declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") && declaration.id) declare(declaration.id.name, declaration);
765
+ } else readDeclaration(statement, false);
766
+ return bindings;
767
+ }
768
+ /**
769
+ * Reads what `needs` reaches in `module`: the plugin factories that its reached code calls, and what it needs from the
770
+ * local modules it imports. The whole module counts for the Definition. In an imported module, only the exports that
771
+ * the importer uses count, with the declarations and imports that they use.
772
+ */
773
+ function readModuleNeeds(module, needs) {
774
+ const bindings = readModuleBindings(module);
679
775
  const plugins = /* @__PURE__ */ new Set();
680
- if (locals.size) walk(module.program, (node) => {
681
- if (node.type === "CallExpression" && node.callee.type === "Identifier" && locals.has(node.callee.name)) plugins.add(locals.get(node.callee.name));
776
+ const imports = [];
777
+ const need = (file, imported) => imports.push([file, imported === "*" ? "all" : /* @__PURE__ */ new Set([imported])]);
778
+ const collectCalls = (node, references) => walk(node, (child) => {
779
+ if (child.type === "ImportDeclaration") return false;
780
+ if (child.type === "CallExpression" && child.callee.type === "Identifier" && bindings.pluginFactories.has(child.callee.name)) plugins.add(bindings.pluginFactories.get(child.callee.name));
781
+ if (child.type === "Identifier") references?.add(child.name);
682
782
  });
783
+ if (needs === "all") {
784
+ const references = /* @__PURE__ */ new Set();
785
+ collectCalls(module.program, references);
786
+ for (const [name, { file, imported }] of bindings.imports) if (references.has(name)) need(file, imported);
787
+ for (const [, target] of bindings.exports) if ("file" in target) need(target.file, target.imported);
788
+ return {
789
+ plugins: [...plugins],
790
+ imports
791
+ };
792
+ }
793
+ const locals = [];
794
+ for (const name of needs) {
795
+ const target = bindings.exports.get(name);
796
+ if (!target) for (const file of bindings.exportAll) need(file, name);
797
+ else if ("file" in target) need(target.file, target.imported);
798
+ else locals.push(target.local);
799
+ }
800
+ const reached = /* @__PURE__ */ new Set();
801
+ for (let local = locals.pop(); local !== void 0; local = locals.pop()) {
802
+ if (reached.has(local)) continue;
803
+ reached.add(local);
804
+ const imported = bindings.imports.get(local);
805
+ if (imported) need(imported.file, imported.imported);
806
+ const references = /* @__PURE__ */ new Set();
807
+ for (const declaration of bindings.declarations.get(local) ?? []) collectCalls(declaration, references);
808
+ for (const reference of references) if (bindings.declarations.has(reference) || bindings.imports.has(reference)) locals.push(reference);
809
+ }
810
+ return {
811
+ plugins: [...plugins],
812
+ imports
813
+ };
814
+ }
815
+ /**
816
+ * The plugins of `AuthSchemaPlugin` that the Definition module calls, and that the local modules it imports call in
817
+ * the exports it uses, such as `stripe()` in `src/server/auth-plugins.ts` that returns the plugins of `server/auth.ts`.
818
+ */
819
+ function readDefinitionSchemaPlugins(definition) {
820
+ const plugins = /* @__PURE__ */ new Set();
821
+ const modules = /* @__PURE__ */ new Map([[definition.file, definition]]);
822
+ const done = /* @__PURE__ */ new Map();
823
+ const queue = [[definition.file, "all"]];
824
+ for (let item = queue.shift(); item; item = queue.shift()) {
825
+ const [file, needs] = item;
826
+ const previous = done.get(file);
827
+ if (previous === "all") continue;
828
+ const fresh = needs === "all" ? "all" : new Set([...needs].filter((name) => !previous?.has(name)));
829
+ if (fresh !== "all" && !fresh.size) continue;
830
+ done.set(file, fresh === "all" ? "all" : /* @__PURE__ */ new Set([...previous ?? [], ...fresh]));
831
+ let module = modules.get(file);
832
+ if (!module) modules.set(file, module = scanModule(readFileSync(file, "utf8"), file));
833
+ const result = readModuleNeeds(module, fresh);
834
+ for (const plugin of result.plugins) plugins.add(plugin);
835
+ queue.push(...result.imports);
836
+ }
683
837
  return [...plugins].sort();
684
838
  }
685
839
  const authFieldTypes = /* @__PURE__ */ new Set([
@@ -768,15 +922,33 @@ function readReturnedObject(callback) {
768
922
  const value = returned ? unwrapExpression(returned) : void 0;
769
923
  return value?.type === "ObjectExpression" ? value : void 0;
770
924
  }
925
+ /** The value of a top-level `const name = value`, exported or not. */
926
+ function topLevelConstValue(module, name) {
927
+ for (const statement of module.program.body) {
928
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
929
+ if (declaration?.type !== "VariableDeclaration" || declaration.kind !== "const") continue;
930
+ for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier" && declarator.id.name === name) return declarator.init ? unwrapExpression(declarator.init) : void 0;
931
+ }
932
+ }
933
+ /**
934
+ * The exported `defineAuth()` call: `export default defineAuth(...)`, or `export default auth` after a top-level
935
+ * `const auth: AuthDefinition<...> = defineAuth(...)`. A composite TypeScript project needs that annotation when it
936
+ * cannot write the inferred type of the Definition (TS7056), as with the Better Auth `apiKey()` plugin.
937
+ */
938
+ function exportedDefineAuthCall(module) {
939
+ const exported = defaultExportExpression(module);
940
+ const call = exported?.type === "Identifier" ? topLevelConstValue(module, exported.name) : exported;
941
+ return call?.type === "CallExpression" && call.callee.type === "Identifier" && call.callee.name === "defineAuth" ? call : void 0;
942
+ }
771
943
  function readDefinitionObjectBody(file) {
772
944
  const module = scanModule(readFileSync(file, "utf8"), file);
773
945
  const authDatabase = readAuthDatabaseImports(module);
774
- const call = defaultExportExpression(module);
775
- if (call?.type !== "CallExpression" || call.callee.type !== "Identifier" || call.callee.name !== "defineAuth") return;
946
+ const call = exportedDefineAuthCall(module);
947
+ if (!call) return;
776
948
  const argument = call.arguments[0];
777
949
  if (argument === void 0 || argument.type === "SpreadElement") return;
778
950
  const options = unwrapExpression(argument);
779
- const plugins = readAuthSchemaPlugins(module);
951
+ const plugins = readDefinitionSchemaPlugins(module);
780
952
  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." });
781
953
  if (options.type === "ObjectExpression") {
782
954
  assertAuthDatabasePlacement(options, options, authDatabase);
@@ -789,6 +961,7 @@ function readDefinitionObjectBody(file) {
789
961
  }
790
962
  const returned = readReturnedObject(options);
791
963
  assertAuthDatabasePlacement(options, returned, authDatabase);
964
+ assertOneReturnWithPages(options);
792
965
  return returned === void 0 ? void 0 : {
793
966
  authDatabase,
794
967
  body: returned,
@@ -931,6 +1104,50 @@ function readAuthAccessSignInConfig(body) {
931
1104
  }
932
1105
  return resolved;
933
1106
  }
1107
+ /** The build reads only the first return of a callback, so access.pages in any other branch would go unguarded. */
1108
+ function assertOneReturnWithPages(options) {
1109
+ if (options.type !== "ArrowFunctionExpression" || options.body.type !== "BlockStatement") return;
1110
+ const returned = [];
1111
+ walk(options.body, (node) => {
1112
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return false;
1113
+ if (node.type === "ReturnStatement") returned.push(node.argument);
1114
+ });
1115
+ const declaresPages = (argument) => {
1116
+ const body = objectLiteral(argument ? unwrapExpression(argument) : void 0);
1117
+ if (!hasObjectProperty(body, "access")) return false;
1118
+ const access = readObjectPropertyValue(body, "access");
1119
+ const object = objectLiteral(access && unwrapExpression(access));
1120
+ return !object || hasObjectProperty(object, "pages");
1121
+ };
1122
+ 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." });
1123
+ }
1124
+ /** `access.pages`, which the Nuxt module turns into route rules at build time, like `access.signIn`. */
1125
+ function readAuthAccessPagesConfig(body) {
1126
+ if (!hasObjectProperty(body, "access")) return {};
1127
+ const expression = readObjectPropertyValue(body, "access");
1128
+ const unwrapped = expression && unwrapExpression(expression);
1129
+ if (unwrapped?.type === "Identifier" && unwrapped.name === "undefined") return {};
1130
+ const access = objectLiteral(unwrapped);
1131
+ if (!access || readObjectEntries(access).some((entry) => !entry.key)) throw authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: "`defineAuth()` access must be an inline object with only static keys, without a spread, so that the build can read access.pages." });
1132
+ if (!hasObjectProperty(access, "pages")) return {};
1133
+ const value = readObjectPropertyValue(access, "pages");
1134
+ const object = objectLiteral(value && unwrapExpression(value));
1135
+ const entries = readObjectEntries(object);
1136
+ if (!object || entries.some((entry) => !entry.key)) throw authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: "`defineAuth()` access.pages must be an inline object literal with string keys, such as `{ '/dashboard/**': 'user' }`." });
1137
+ const pages = Object.fromEntries(entries.map(({ key, value }) => [key, value && staticValue(value)]));
1138
+ assertAuthPages(pages);
1139
+ return { pages };
1140
+ }
1141
+ /** `components.prefix`, which the Nuxt module reads at build time to name `<AuthPermission>`, like `basePath`. */
1142
+ function readAuthComponentsConfig(body) {
1143
+ if (!hasObjectProperty(body, "components")) return;
1144
+ const components = objectLiteral(readObjectPropertyValue(body, "components"));
1145
+ if (!components || readObjectEntries(components).some((entry) => entry.key !== "prefix")) throw authErrorDiagnostics.AUTH_COMPONENTS_INVALID();
1146
+ if (!hasObjectProperty(components, "prefix")) return;
1147
+ const prefix = staticString(readObjectPropertyValue(components, "prefix"));
1148
+ if (!prefix?.trim() || prefix !== prefix.trim()) throw authErrorDiagnostics.AUTH_COMPONENTS_INVALID();
1149
+ return { prefix };
1150
+ }
934
1151
  /** The `authDatabase()` call of the `database` option, or undefined for any other value. */
935
1152
  function readAuthDatabaseCall(body, authDatabase) {
936
1153
  const value = readObjectPropertyValue(body, "database");
@@ -992,14 +1209,17 @@ function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {})
992
1209
  const basePath = normalizeAuthBasePath(readStaticStringProperty(body, "basePath", "basePath"));
993
1210
  const abilities = discoverAuthAbilities(rootDir, discovery);
994
1211
  const publicRoutes = readAuthAccessPublicConfig(body);
1212
+ const components = readAuthComponentsConfig(body);
995
1213
  return {
996
1214
  ...abilities ? { abilities } : {},
997
1215
  access: {
998
1216
  routes: readAuthAccessRoutesConfig(body),
999
1217
  ...publicRoutes.length ? { public: publicRoutes } : {},
1000
- ...readAuthAccessSignInConfig(body)
1218
+ ...readAuthAccessSignInConfig(body),
1219
+ ...readAuthAccessPagesConfig(body)
1001
1220
  },
1002
1221
  basePath,
1222
+ ...components ? { components } : {},
1003
1223
  definition,
1004
1224
  rootDir,
1005
1225
  route: readAuthRouteConfig(body),
@@ -1226,14 +1446,17 @@ function createAuthNitroConfig(plugin, options) {
1226
1446
  }
1227
1447
  function renderAuthDefinitionModule(config, options = { serverEnv: false }) {
1228
1448
  if (!config) return "export const definition = undefined\nexport const getAuthApp = () => undefined\nexport default definition\n";
1449
+ const runtimeServer = JSON.stringify(options.runtimeServer ?? privateAuthImport(options.importBase ?? authPackageName, "runtime/server"));
1229
1450
  return [
1230
1451
  `import definition from ${JSON.stringify(config.definition.handler)}`,
1231
1452
  options.testMode ? "export const getAuthApp = () => undefined" : "export { useNitroApp as getAuthApp } from \"nitro/app\"",
1232
1453
  ...options.serverEnv ? [
1233
- `import { setAuthRuntimeEnvResolver } from ${JSON.stringify(privateAuthImport(options.importBase ?? authPackageName, "runtime/server"))}`,
1454
+ `import { setAuthRuntimeEnvResolver } from ${runtimeServer}`,
1234
1455
  `import { useServerEnv } from ${JSON.stringify(envServerModuleId)}`,
1235
1456
  "setAuthRuntimeEnvResolver(useServerEnv, definition)"
1236
1457
  ] : [],
1458
+ `import { checkBuiltAuthPages } from ${runtimeServer}`,
1459
+ `checkBuiltAuthPages(definition, ${JSON.stringify(config.access.pages ?? {})})`,
1237
1460
  "export { definition }",
1238
1461
  "export default definition",
1239
1462
  ""
@@ -1241,7 +1464,10 @@ function renderAuthDefinitionModule(config, options = { serverEnv: false }) {
1241
1464
  }
1242
1465
  async function writeNuxtAuthDefinition(root, config) {
1243
1466
  const file = resolve(resolveViteHubProjectRoot(root), ".vitehub/auth/definition.ts");
1244
- await writeFileIfChanged(file, renderAuthDefinitionModule(config));
1467
+ await writeFileIfChanged(file, renderAuthDefinitionModule(config, {
1468
+ runtimeServer: ownModule(import.meta.url, "runtime/server"),
1469
+ serverEnv: false
1470
+ }));
1245
1471
  return file;
1246
1472
  }
1247
1473
  /** Private Auth entries of the distribution. */
@@ -1258,7 +1484,7 @@ function renderAuthServerModule(options = {}) {
1258
1484
  return [
1259
1485
  `export * from ${JSON.stringify(serverImport)}`,
1260
1486
  `export { default } from ${JSON.stringify(serverImport)}`,
1261
- `export { createAuthAccessHandler } from ${JSON.stringify(privateAuthImport(importBase, "internal/server"))}`,
1487
+ `export { createAuthAccessHandler, findVerifiedAuthUserId } from ${JSON.stringify(privateAuthImport(importBase, "internal/server"))}`,
1262
1488
  ""
1263
1489
  ].join("\n");
1264
1490
  }
@@ -1322,7 +1548,9 @@ function renderAuthAmbientTypes(options = { serverEnv: false }) {
1322
1548
  /**
1323
1549
  * The declaration of the virtual module. It stays out of a file with imports, which would make it an augmentation of
1324
1550
  * a module that must already resolve. When only the bundler resolves `#vitehub/auth/server`, the tsconfig would not
1325
- * find it and the types of everything that imports the Auth handlers would be `any`.
1551
+ * find it and the types of everything that imports the Auth handlers would be `any`. An `export ... from` in this
1552
+ * block must name a package: TypeScript drops one with a file path (TS2439), and the private entry of `vite-hub` is a
1553
+ * file path. A `typeof import()` type takes any path.
1326
1554
  */
1327
1555
  function renderAuthServerTypes(importBase = authPackageName) {
1328
1556
  const serverImport = `${importBase}/server`;
@@ -1330,7 +1558,8 @@ function renderAuthServerTypes(importBase = authPackageName) {
1330
1558
  `declare module ${JSON.stringify(AUTH_SERVER_ID)} {`,
1331
1559
  ` export * from ${JSON.stringify(serverImport)}`,
1332
1560
  ` export { default } from ${JSON.stringify(serverImport)}`,
1333
- ` export { createAuthAccessHandler } from ${JSON.stringify(privateAuthImport(importBase, "internal/server"))}`,
1561
+ ` export const createAuthAccessHandler: typeof import(${JSON.stringify(privateAuthImport(importBase, "internal/server"))}).createAuthAccessHandler`,
1562
+ ` export const findVerifiedAuthUserId: typeof import(${JSON.stringify(privateAuthImport(importBase, "internal/server"))}).findVerifiedAuthUserId`,
1334
1563
  "}",
1335
1564
  ""
1336
1565
  ].join("\n");
@@ -1599,4 +1828,4 @@ function hubAuth(options, internalOptions = {}) {
1599
1828
  };
1600
1829
  }
1601
1830
  //#endregion
1602
- export { AUTH_VITE_PLUGIN_NAME as a, writeNuxtAuthDefinition as c, resolveNuxtServerDirs as d, resolveViteHubProjectRoot as f, AUTH_SERVER_ID as i, resolveAuthViteConfig as l, AUTH_CLIENT_ID as n, createAuthNitroConfig as o, AUTH_DEFINITION_ID as r, hubAuth as s, AUTH_ABILITIES_ID as t, authAbilitiesCandidates as u };
1831
+ export { AUTH_VITE_PLUGIN_NAME as a, writeNuxtAuthDefinition as c, cachingRuleNames as d, createCachingRouteRuleFinder as f, resolveViteHubProjectRoot as h, AUTH_SERVER_ID as i, resolveAuthViteConfig as l, resolveNuxtServerDirs as m, AUTH_CLIENT_ID as n, createAuthNitroConfig as o, methodOrder as p, AUTH_DEFINITION_ID as r, hubAuth as s, AUTH_ABILITIES_ID as t, authAbilitiesCandidates as u };