@vite-hub/auth 0.1.0 → 0.3.1

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 (89) hide show
  1. package/README.md +333 -49
  2. package/dist/abilities-DfAnFYwG.d.ts +93 -0
  3. package/dist/abilities.d.ts +2 -0
  4. package/dist/abilities.js +43 -0
  5. package/dist/ability-error-CqgBrBfR.js +91 -0
  6. package/dist/ability-error-DcgChwCN.d.ts +34 -0
  7. package/dist/admin-claim-code-CDipqeAU.js +22 -0
  8. package/dist/agent.d.ts +5 -5
  9. package/dist/agent.js +17 -9
  10. package/dist/application-path-DuTpfGFj.js +62 -0
  11. package/dist/auth-instance-CR6b1W80.js +1168 -0
  12. package/dist/bun-sqlite.d.ts +8 -0
  13. package/dist/cli-ubYJpAL_.d.ts +163 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +47 -7
  16. package/dist/console-runtime-DTopBP-x.d.ts +71 -0
  17. package/dist/console-runtime-J9_Vx9pT.js +1166 -0
  18. package/dist/console-runtime.d.ts +3 -3
  19. package/dist/console-runtime.js +2 -819
  20. package/dist/console.d.ts +215 -3
  21. package/dist/console.js +1 -1
  22. package/dist/database-options-BRNef9oy.js +29 -0
  23. package/dist/database-schema-options-ENuRMduM.js +12 -0
  24. package/dist/database.d.ts +12 -0
  25. package/dist/database.js +45 -0
  26. package/dist/definition-CqQMcDEK.js +280 -0
  27. package/dist/error-diagnostics-C8XtVz0i.js +138 -0
  28. package/dist/{events-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
  29. package/dist/forward.d.ts +50 -0
  30. package/dist/forward.js +120 -0
  31. package/dist/host-declarations.d.ts +2 -1
  32. package/dist/index.d.ts +24 -3
  33. package/dist/index.js +3 -102
  34. package/dist/internal/server.d.ts +5 -0
  35. package/dist/internal/server.js +858 -0
  36. package/dist/invariant-D8_xBqmZ.js +22 -0
  37. package/dist/mcp.d.ts +187 -0
  38. package/dist/mcp.js +353 -0
  39. package/dist/members-D9lfaEO_.js +533 -0
  40. package/dist/nuxt-bridge-Cl988STZ.js +44 -0
  41. package/dist/nuxt.d.ts +13 -5
  42. package/dist/nuxt.js +90 -13
  43. package/dist/object-Da1zyPCR.js +11 -0
  44. package/dist/page-tools-shared-l4eyj53D.js +19 -0
  45. package/dist/presets.js +1 -1
  46. package/dist/request-z6DHHmrb.js +47 -0
  47. package/dist/runtime/console.d.ts +3 -7
  48. package/dist/runtime/console.js +4 -42
  49. package/dist/runtime/empty-abilities.d.ts +5 -0
  50. package/dist/runtime/empty-abilities.js +4 -0
  51. package/dist/runtime/empty-client.d.ts +6 -0
  52. package/dist/runtime/empty-client.js +5 -0
  53. package/dist/runtime/empty-definition.d.ts +1 -1
  54. package/dist/runtime/nuxt.js +1 -1
  55. package/dist/runtime/server.d.ts +2 -0
  56. package/dist/runtime/server.js +77 -0
  57. package/dist/runtime/vue-nuxt.d.ts +3 -2
  58. package/dist/runtime/vue-nuxt.js +157 -5
  59. package/dist/runtime-state-ojQCzKOc.js +25 -0
  60. package/dist/schema.d.ts +137 -0
  61. package/dist/schema.js +147 -0
  62. package/dist/server-C0qnKN2W.d.ts +143 -0
  63. package/dist/server-bQGzVQ--.d.ts +41 -0
  64. package/dist/server.d.ts +3 -2
  65. package/dist/server.js +3 -3
  66. package/dist/session-cookies-BbH3UR2m.js +227 -0
  67. package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
  68. package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
  69. package/dist/table-specs-8gq_FCaq.js +771 -0
  70. package/dist/table-specs-DbXyaXWs.d.ts +842 -0
  71. package/dist/test.d.ts +26 -0
  72. package/dist/test.js +25 -0
  73. package/dist/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
  74. package/dist/vite-CV400XXY.js +1556 -0
  75. package/dist/vite.d.ts +138 -20
  76. package/dist/vite.js +2 -2
  77. package/dist/vue.d.ts +330 -21
  78. package/dist/vue.js +583 -36
  79. package/package.json +84 -15
  80. package/dist/application-path-C290OAIs.js +0 -18
  81. package/dist/cli-mgXvsBtA.d.ts +0 -85
  82. package/dist/console-B7eERmGv.d.ts +0 -180
  83. package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
  84. package/dist/error-diagnostics-CL0yjHiM.js +0 -79
  85. package/dist/events-config-CjcFOhTE.js +0 -177
  86. package/dist/inspect-DPtsW8dB.d.ts +0 -36
  87. package/dist/server-B7LU19dS.js +0 -1730
  88. package/dist/server-CTD_JAww.d.ts +0 -77
  89. package/dist/vite-COWkwxsj.js +0 -990
@@ -1,990 +0,0 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-CL0yjHiM.js";
2
- import { n as normalizeAuthBasePath, t as isAuthRequestPath } from "./shared-DnpgYiLF.js";
3
- import { r as resetAuth, t as readSetCookies } from "./set-cookie-2as_DbHe.js";
4
- import { basename, dirname, parse, relative, resolve } from "node:path";
5
- import { existsSync, readFileSync, statSync } from "node:fs";
6
- import { tmpdir } from "node:os";
7
- import { Readable } from "node:stream";
8
- import { mkdir, readFile, writeFile } from "node:fs/promises";
9
- import { parseSync } from "vite";
10
- //#region ../internal/src/build/vite.ts
11
- const generatedViteHubFilesPattern = "**/.vitehub/**";
12
- const projectRootDirectoryMarkers = [
13
- ["server", "agents"],
14
- ["server", "channels"],
15
- ["server", "connections"],
16
- ["server", "browsers"],
17
- ["server", "emails"],
18
- ["server", "schedules"],
19
- ["server", "workspaces"]
20
- ];
21
- const projectRootFileMarkers = [
22
- ["package.json"],
23
- ["nuxt.config.ts"],
24
- ["nuxt.config.mts"],
25
- ["nuxt.config.js"],
26
- ["nuxt.config.mjs"]
27
- ];
28
- function createNoExternalAddition(...packageNames) {
29
- return (current) => {
30
- if (current === true) return;
31
- const values = Array.isArray(current) ? current : [current];
32
- const missing = packageNames.filter((packageName) => !values.includes(packageName));
33
- return missing.length ? missing : void 0;
34
- };
35
- }
36
- function isServerEnvironment(name, config) {
37
- return name === "ssr" || config.consumer === "server";
38
- }
39
- /**
40
- * Server directories that ViteHub scans for Definitions. The first entry is the application.
41
- * Later entries are Nuxt layers in Nuxt priority order.
42
- */
43
- const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
44
- /**
45
- * Lists the server directory of the application and of each Nuxt layer it extends.
46
- * The application comes first. Layers follow in Nuxt priority order, like Nuxt's own Nitro scan directories.
47
- */
48
- function resolveNuxtServerDirs(options) {
49
- const appRoot = options.rootDir ? resolve(options.rootDir) : void 0;
50
- let appDirectory = options.serverDir ? resolve(options.serverDir) : void 0;
51
- const layerDirectories = [];
52
- for (const layer of options._layers ?? []) {
53
- const root = layer.config?.rootDir ?? layer.cwd;
54
- const isApp = Boolean(root && appRoot && resolve(root) === appRoot);
55
- if (isApp && appDirectory) continue;
56
- const config = isApp ? options : layer.config ?? {};
57
- const sourceDir = config.srcDir ?? layer.cwd ?? root;
58
- if (!sourceDir) continue;
59
- const directory = resolve(sourceDir, config.serverDir ?? "server");
60
- if (isApp) appDirectory = directory;
61
- else layerDirectories.push(directory);
62
- }
63
- if (!appDirectory && layerDirectories.length && appRoot) appDirectory = resolve(appRoot, "server");
64
- const directories = [.../* @__PURE__ */ new Set([...appDirectory ? [appDirectory] : [], ...layerDirectories])];
65
- return directories.length ? directories : void 0;
66
- }
67
- function generatedViteHubWatchIgnoredAddition(ignored) {
68
- return (Array.isArray(ignored) ? ignored : [ignored]).includes(generatedViteHubFilesPattern) ? void 0 : [generatedViteHubFilesPattern];
69
- }
70
- function resolveViteHubProjectRoot(root, options = {}) {
71
- const resolvedRoot = resolve(root);
72
- const temporaryRoot = resolve(tmpdir());
73
- const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
74
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
75
- if (basename(resolvedRoot) === "app") {
76
- const parent = dirname(resolvedRoot);
77
- if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
78
- "nuxt.config.ts",
79
- "nuxt.config.mts",
80
- "nuxt.config.js",
81
- "nuxt.config.mjs"
82
- ]))) return parent;
83
- }
84
- let current = resolvedRoot;
85
- while (true) {
86
- if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
87
- if (hasProjectRootMarker(current)) return current;
88
- const parent = dirname(current);
89
- if (parent === current) return resolvedRoot;
90
- current = parent;
91
- }
92
- }
93
- function hasProjectRootDirectoryMarker(root) {
94
- for (const marker of projectRootDirectoryMarkers) try {
95
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
96
- } catch (error) {
97
- if (error.code !== "ENOENT") throw error;
98
- }
99
- return false;
100
- }
101
- function hasProjectRootMarker(root) {
102
- if (hasProjectRootDirectoryMarker(root)) return true;
103
- return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
104
- }
105
- function hasProjectRootFileMarker(root, markers) {
106
- for (const marker of markers) {
107
- const path = Array.isArray(marker) ? marker : [marker];
108
- try {
109
- if (statSync(resolve(root, ...path)).isFile()) return true;
110
- } catch (error) {
111
- if (error.code !== "ENOENT") throw error;
112
- }
113
- }
114
- return false;
115
- }
116
- //#endregion
117
- //#region ../internal/src/nitro-kit.ts
118
- function cloneArray(value) {
119
- return Array.isArray(value) ? [...value] : [];
120
- }
121
- function isRecord(value) {
122
- return Object(value) === value && !Array.isArray(value);
123
- }
124
- function sameHandler(left, right) {
125
- return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
126
- }
127
- /** Create a Nitro 3 configuration builder for generated ViteHub output. */
128
- function createNitroServerKit(value = {}) {
129
- const config = isRecord(value) ? { ...value } : {};
130
- const handlers = cloneArray(config.handlers);
131
- const plugins = cloneArray(config.plugins);
132
- config.handlers = handlers;
133
- config.plugins = plugins;
134
- return {
135
- config,
136
- addHandler(handler, position = "end") {
137
- if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
138
- if (position === "start") handlers.unshift({ ...handler });
139
- else handlers.push({ ...handler });
140
- },
141
- addPlugin(plugin, position = "end") {
142
- if (plugins.includes(plugin)) return;
143
- if (position === "start") plugins.unshift(plugin);
144
- else plugins.push(plugin);
145
- }
146
- };
147
- }
148
- //#endregion
149
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
150
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
151
- function normalizeWindowsPath(input = "") {
152
- if (!input) return input;
153
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
154
- }
155
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
156
- const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
157
- function cwd() {
158
- if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
159
- return "/";
160
- }
161
- const resolve$1 = function(...arguments_) {
162
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
163
- let resolvedPath = "";
164
- let resolvedAbsolute = false;
165
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
166
- const path = index >= 0 ? arguments_[index] : cwd();
167
- if (!path || path.length === 0) continue;
168
- resolvedPath = `${path}/${resolvedPath}`;
169
- resolvedAbsolute = isAbsolute(path);
170
- }
171
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
172
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
173
- return resolvedPath.length > 0 ? resolvedPath : ".";
174
- };
175
- function normalizeString(path, allowAboveRoot) {
176
- let res = "";
177
- let lastSegmentLength = 0;
178
- let lastSlash = -1;
179
- let dots = 0;
180
- let char = null;
181
- for (let index = 0; index <= path.length; ++index) {
182
- if (index < path.length) char = path[index];
183
- else if (char === "/") break;
184
- else char = "/";
185
- if (char === "/") {
186
- if (lastSlash === index - 1 || dots === 1);
187
- else if (dots === 2) {
188
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
189
- if (res.length > 2) {
190
- const lastSlashIndex = res.lastIndexOf("/");
191
- if (lastSlashIndex === -1) {
192
- res = "";
193
- lastSegmentLength = 0;
194
- } else {
195
- res = res.slice(0, lastSlashIndex);
196
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
197
- }
198
- lastSlash = index;
199
- dots = 0;
200
- continue;
201
- } else if (res.length > 0) {
202
- res = "";
203
- lastSegmentLength = 0;
204
- lastSlash = index;
205
- dots = 0;
206
- continue;
207
- }
208
- }
209
- if (allowAboveRoot) {
210
- res += res.length > 0 ? "/.." : "..";
211
- lastSegmentLength = 2;
212
- }
213
- } else {
214
- if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
215
- else res = path.slice(lastSlash + 1, index);
216
- lastSegmentLength = index - lastSlash - 1;
217
- }
218
- lastSlash = index;
219
- dots = 0;
220
- } else if (char === "." && dots !== -1) ++dots;
221
- else dots = -1;
222
- }
223
- return res;
224
- }
225
- const isAbsolute = function(p) {
226
- return _IS_ABSOLUTE_RE.test(p);
227
- };
228
- const relative$1 = function(from, to) {
229
- const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
230
- const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
231
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
232
- const _fromCopy = [..._from];
233
- for (const segment of _fromCopy) {
234
- if (_to[0] !== segment) break;
235
- _from.shift();
236
- _to.shift();
237
- }
238
- return [..._from.map(() => ".."), ..._to].join("/");
239
- };
240
- //#endregion
241
- //#region ../internal/src/definition-catalog.ts
242
- async function writeFileIfChanged(file, contents) {
243
- if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
244
- await mkdir(resolve$1(file, ".."), { recursive: true });
245
- await writeFile(file, contents, "utf8");
246
- }
247
- //#endregion
248
- //#region ../internal/src/inspect.ts
249
- function relativeDefinitionFile(projectRoot, file) {
250
- return relative$1(projectRoot, file).replaceAll("\\", "/");
251
- }
252
- /** Summarizes Definitions that have no owner-specific fields. */
253
- function summarizeDefinitions(projectRoot, definitions, fallbackSource) {
254
- return definitions.map((definition) => ({
255
- fields: [],
256
- file: relativeDefinitionFile(projectRoot, definition.handler),
257
- name: definition.name,
258
- source: definition.source || fallbackSource
259
- }));
260
- }
261
- const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
262
- new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
263
- new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
264
- //#endregion
265
- //#region ../internal/src/build/scan-module.ts
266
- /**
267
- * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
268
- * the oxc parser that Vite ships through Rolldown, and never runs it. Values that are not static literals read as
269
- * `dynamic`, so callers can report their own diagnostics.
270
- */
271
- /** The value of an expression that the scanner cannot read without running the module. */
272
- const dynamic = Symbol("dynamic");
273
- function languageOf(file) {
274
- if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
275
- if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
276
- if (/\.(?:c|m)?js$/i.test(file)) return "js";
277
- return "ts";
278
- }
279
- /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
280
- function scanModule(source, file = "module.ts") {
281
- const result = parseSync(file, source, {
282
- lang: languageOf(file),
283
- preserveParens: false,
284
- sourceType: "module"
285
- });
286
- return {
287
- comments: result.comments,
288
- errors: result.errors,
289
- file,
290
- program: result.program,
291
- source
292
- };
293
- }
294
- function isNode(value) {
295
- return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
296
- }
297
- /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
298
- function walk(node, visit, parent) {
299
- if (visit(node, parent) === false) return;
300
- const fields = node;
301
- for (const key in fields) {
302
- const child = fields[key];
303
- if (typeof child !== "object" || child === null || key === "parent") continue;
304
- if (Array.isArray(child)) {
305
- for (const item of child) if (isNode(item)) walk(item, visit, node);
306
- } else if (isNode(child)) walk(child, visit, node);
307
- }
308
- }
309
- /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
310
- function unwrapExpression(node) {
311
- while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
312
- return node;
313
- }
314
- /** The expression of `export default <expression>`, without assertions. Declarations return undefined. */
315
- function defaultExportExpression(module) {
316
- for (const statement of module.program.body) {
317
- if (statement.type !== "ExportDefaultDeclaration") continue;
318
- const declaration = statement.declaration;
319
- if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration" || declaration.type === "TSInterfaceDeclaration") return;
320
- return unwrapExpression(declaration);
321
- }
322
- }
323
- function staticKey(property) {
324
- const key = property.key;
325
- if (key.type === "Identifier" && !property.computed) return key.name;
326
- if (key.type === "PrivateIdentifier") return;
327
- const value = staticValue(key);
328
- return typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? String(value) : void 0;
329
- }
330
- /** The members of an object literal in source order. */
331
- function objectProperties(object) {
332
- return object.properties.map((node) => node.type === "SpreadElement" ? {
333
- computed: false,
334
- key: void 0,
335
- node,
336
- value: void 0
337
- } : {
338
- computed: node.computed,
339
- key: staticKey(node),
340
- node,
341
- value: unwrapExpression(node.value)
342
- });
343
- }
344
- /** The value of a template literal without substitutions. */
345
- function staticTemplate(node) {
346
- if (node.expressions.length) return dynamic;
347
- return node.quasis[0]?.value.cooked ?? dynamic;
348
- }
349
- const escapePattern = /\\(u\{[^}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|0\d|[\s\S])/g;
350
- /**
351
- * True when a string literal has an escape that strict mode code rejects. The parser recovers from some bad escapes
352
- * and accepts legacy octal escapes, so the scanner checks them again.
353
- */
354
- function hasInvalidEscape(raw) {
355
- for (const [, escape = ""] of raw.matchAll(escapePattern)) if (escape.startsWith("u{")) {
356
- const code = escape.slice(2, -1);
357
- if (!escape.endsWith("}") || !/^[\da-fA-F]+$/.test(code) || Number.parseInt(code, 16) > 1114111) return true;
358
- } else if (escape.startsWith("u")) {
359
- if (!/^u[\da-fA-F]{4}$/.test(escape)) return true;
360
- } else if (escape.startsWith("x")) {
361
- if (!/^x[\da-fA-F]{2}$/.test(escape)) return true;
362
- } else if (/^(?:[1-9]|0\d)$/.test(escape)) return true;
363
- return false;
364
- }
365
- /**
366
- * Reads a literal value: strings, numbers, booleans, `null`, `undefined`, template literals without substitutions,
367
- * and arrays and objects of these. Any other expression gives `dynamic`.
368
- */
369
- function staticValue(node) {
370
- node = unwrapExpression(node);
371
- switch (node.type) {
372
- case "Literal":
373
- if ("regex" in node) return dynamic;
374
- return typeof node.value === "string" && hasInvalidEscape(node.raw ?? "") ? dynamic : node.value;
375
- case "TemplateLiteral": return staticTemplate(node);
376
- case "Identifier": return node.name === "undefined" ? void 0 : dynamic;
377
- case "UnaryExpression": {
378
- if (node.operator === "void") return staticValue(node.argument) === dynamic ? dynamic : void 0;
379
- const value = staticValue(node.argument);
380
- if (node.operator === "-" && (typeof value === "number" || typeof value === "bigint")) return -value;
381
- return dynamic;
382
- }
383
- case "ArrayExpression": {
384
- const values = [];
385
- for (const element of node.elements) {
386
- if (element === null || element.type === "SpreadElement") return dynamic;
387
- const value = staticValue(element);
388
- if (value === dynamic) return dynamic;
389
- values.push(value);
390
- }
391
- return values;
392
- }
393
- case "ObjectExpression": {
394
- const values = {};
395
- for (const property of objectProperties(node)) {
396
- if (property.key === void 0 || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value === void 0) return dynamic;
397
- const value = staticValue(property.value);
398
- if (value === dynamic) return dynamic;
399
- Object.defineProperty(values, property.key, {
400
- configurable: true,
401
- enumerable: true,
402
- value,
403
- writable: true
404
- });
405
- }
406
- return values;
407
- }
408
- default: return dynamic;
409
- }
410
- }
411
- /** The static string value of an expression, or undefined when it is not a string literal. */
412
- function staticString(node) {
413
- if (node === void 0) return;
414
- const value = staticValue(node);
415
- return typeof value === "string" ? value : void 0;
416
- }
417
- //#endregion
418
- //#region src/discovery.ts
419
- const authDefinitionExtensions = [
420
- ".ts",
421
- ".mts",
422
- ".cts",
423
- ".js",
424
- ".mjs",
425
- ".cjs"
426
- ];
427
- function serverAuthCandidates(serverDir) {
428
- return authDefinitionExtensions.map((extension) => ({
429
- handler: resolve(serverDir, `auth${extension}`),
430
- name: "default",
431
- source: "server-auth"
432
- }));
433
- }
434
- function rootAuthCandidates(rootDir) {
435
- return authDefinitionExtensions.map((extension) => ({
436
- handler: resolve(rootDir, `server.auth${extension}`),
437
- name: "default",
438
- source: "server-auth-suffix"
439
- }));
440
- }
441
- function existingDefinitions(candidates) {
442
- return candidates.filter((definition) => existsSync(definition.handler));
443
- }
444
- /**
445
- * Finds the Auth Definition. The first server directory is the application and later ones are Nuxt layers.
446
- * An application Definition replaces layer Definitions. Two Definitions at the same level fail discovery.
447
- */
448
- function discoverAuthDefinitions(rootDir, options = {}) {
449
- const [appServerDir, ...layerServerDirs] = options.serverDirs ?? [resolve(rootDir, "server")];
450
- const appDefinitions = existingDefinitions([...appServerDir ? serverAuthCandidates(appServerDir) : [], ...rootAuthCandidates(rootDir)]);
451
- if (appDefinitions.length > 1) throw authErrorDiagnostics.AUTH_R0003({ message: ["[vitehub] Only one Auth Definition is allowed. Found:", ...appDefinitions.map((definition) => ` - ${definition.handler}`)].join("\n") });
452
- if (appDefinitions.length) return appDefinitions;
453
- const layerDefinitions = existingDefinitions(layerServerDirs.flatMap(serverAuthCandidates));
454
- if (layerDefinitions.length > 1) throw authErrorDiagnostics.AUTH_R0003({ message: [
455
- "[vitehub] Only one Auth Definition is allowed. More than one Nuxt layer defines one:",
456
- ...layerDefinitions.map((definition) => ` - ${definition.handler}`),
457
- "Add `server/auth.ts` to the application to select the Auth Definition."
458
- ].join("\n") });
459
- return layerDefinitions;
460
- }
461
- function discoverAuthDefinition(rootDir, options = {}) {
462
- return discoverAuthDefinitions(rootDir, options)[0];
463
- }
464
- //#endregion
465
- //#region src/config.ts
466
- /** The object that a callback returns, from `() => ({ ... })` or the first `return { ... }` in its body. */
467
- function readReturnedObject(callback) {
468
- if (callback.type !== "ArrowFunctionExpression") return;
469
- if (callback.body.type !== "BlockStatement") {
470
- const body = unwrapExpression(callback.body);
471
- return body.type === "ObjectExpression" ? body : void 0;
472
- }
473
- let returned;
474
- walk(callback.body, (node) => {
475
- if (returned !== void 0) return false;
476
- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return false;
477
- if (node.type === "ReturnStatement") {
478
- returned = node.argument;
479
- return false;
480
- }
481
- });
482
- const value = returned ? unwrapExpression(returned) : void 0;
483
- return value?.type === "ObjectExpression" ? value : void 0;
484
- }
485
- function readDefinitionObjectBody(file) {
486
- const call = defaultExportExpression(scanModule(readFileSync(file, "utf8"), file));
487
- if (call?.type !== "CallExpression" || call.callee.type !== "Identifier" || call.callee.name !== "defineAuth") return;
488
- const argument = call.arguments[0];
489
- if (argument === void 0 || argument.type === "SpreadElement") return;
490
- const options = unwrapExpression(argument);
491
- if (options.type === "ObjectExpression") return {
492
- body: options,
493
- callback: false
494
- };
495
- const returned = readReturnedObject(options);
496
- return returned === void 0 ? void 0 : {
497
- body: returned,
498
- callback: true
499
- };
500
- }
501
- /** Object entries. `key` is empty for spread and computed keys. `value` is undefined for methods and accessors. */
502
- function readObjectEntries(body) {
503
- if (!body) return [];
504
- return objectProperties(body).map((property) => ({
505
- key: property.computed ? "" : property.key ?? "",
506
- value: property.node.type === "Property" && property.node.kind === "init" && !property.node.method ? property.value : void 0
507
- }));
508
- }
509
- function readObjectPropertyValue(body, property) {
510
- return readObjectEntries(body).find((entry) => entry.key === property)?.value;
511
- }
512
- function hasObjectProperty(body, property) {
513
- return readObjectEntries(body).some((entry) => entry.key === property);
514
- }
515
- function objectLiteral(value) {
516
- return value?.type === "ObjectExpression" ? value : void 0;
517
- }
518
- function readStaticBooleanLiteral(expression) {
519
- const value = expression && staticValue(expression);
520
- return typeof value === "boolean" ? value : void 0;
521
- }
522
- function readStaticStringProperty(body, property, label) {
523
- if (!hasObjectProperty(body, property)) return;
524
- const value = staticString(readObjectPropertyValue(body, property));
525
- if (typeof value === "undefined") throw authErrorDiagnostics.AUTH_C0001({ message: `\`defineAuth()\` ${label} must be an inline string literal.` });
526
- if (value.trim().length === 0 || value !== value.trim()) throw authErrorDiagnostics.AUTH_C0002({ message: `\`defineAuth()\` ${label} must be a non-empty trimmed string.` });
527
- return value;
528
- }
529
- function readStaticRouteProperty(body, property, label) {
530
- const value = readStaticStringProperty(body, property, label);
531
- if (typeof value !== "undefined" && !value.startsWith("/")) throw authErrorDiagnostics.AUTH_C0003({ message: `\`defineAuth()\` ${label} must start with \`/\`.` });
532
- return value;
533
- }
534
- function readStaticBooleanProperty(body, property, label) {
535
- if (!hasObjectProperty(body, property)) return;
536
- const value = readStaticBooleanLiteral(readObjectPropertyValue(body, property));
537
- if (typeof value === "undefined") throw authErrorDiagnostics.AUTH_C0004({ message: `\`defineAuth()\` ${label} must be an inline boolean literal.` });
538
- return value;
539
- }
540
- function assertOnlyObjectKeys(body, allowed, label) {
541
- const unknownEntry = readObjectEntries(body).find((entry) => !entry.key || !allowed.has(entry.key));
542
- if (!unknownEntry) return;
543
- if (!unknownEntry.key) throw authErrorDiagnostics.AUTH_C0005({ message: `\`defineAuth()\` ${label} must use static object keys.` });
544
- throw authErrorDiagnostics.AUTH_C0006({ message: `\`defineAuth()\` ${label} does not support the "${unknownEntry.key}" option.` });
545
- }
546
- function assertStaticObjectKeys(body, label) {
547
- if (readObjectEntries(body).some((entry) => !entry.key)) throw authErrorDiagnostics.AUTH_C0007({ message: `\`defineAuth()\` ${label} must use static object keys.` });
548
- }
549
- function readAuthRouteConfig(body) {
550
- const basePath = normalizeAuthBasePath(readStaticStringProperty(body, "basePath", "basePath"));
551
- if (!hasObjectProperty(body, "route")) return basePath;
552
- if (readStaticBooleanLiteral(readObjectPropertyValue(body, "route")) === false) return false;
553
- throw authErrorDiagnostics.AUTH_C0008({ message: "`defineAuth()` route can only be `false` when provided." });
554
- }
555
- function readAuthAccessRoute(entry, index) {
556
- const route = staticString(entry);
557
- if (typeof route !== "undefined") {
558
- if (!route.startsWith("/")) throw authErrorDiagnostics.AUTH_C0009({ message: `\`defineAuth()\` access.routes[${index}] must start with \`/\`.` });
559
- return { route };
560
- }
561
- const routeObject = objectLiteral(entry && unwrapExpression(entry));
562
- if (typeof routeObject === "undefined") throw authErrorDiagnostics.AUTH_C0010({ message: `\`defineAuth()\` access.routes[${index}] must be an inline route string or route object.` });
563
- assertOnlyObjectKeys(routeObject, /* @__PURE__ */ new Set([
564
- "authorize",
565
- "method",
566
- "route"
567
- ]), `access.routes[${index}]`);
568
- const resolvedRoute = readStaticRouteProperty(routeObject, "route", `access.routes[${index}].route`);
569
- if (!resolvedRoute) throw authErrorDiagnostics.AUTH_C0011({ message: `\`defineAuth()\` access.routes[${index}].route is required.` });
570
- const method = readStaticStringProperty(routeObject, "method", `access.routes[${index}].method`);
571
- const authorize = readObjectEntries(routeObject).find((entry) => entry.key === "authorize");
572
- const resolved = { route: resolvedRoute };
573
- if (authorize) resolved.authorize = true;
574
- if (method) resolved.method = method;
575
- return resolved;
576
- }
577
- function readAuthAccessRoutesConfig(body) {
578
- const access = objectLiteral(readObjectPropertyValue(body, "access"));
579
- if (!access || !hasObjectProperty(access, "routes")) return [];
580
- const routes = readObjectPropertyValue(access, "routes");
581
- if (routes?.type !== "ArrayExpression") throw authErrorDiagnostics.AUTH_C0012({ message: "`defineAuth()` access.routes must be an inline array." });
582
- return routes.elements.map((entry, index) => readAuthAccessRoute(entry === null || entry.type === "SpreadElement" ? void 0 : entry, index));
583
- }
584
- function readAuthDatabaseConfig(body, allowRuntimeValue = false) {
585
- if (!hasObjectProperty(body, "database")) return { mode: "default" };
586
- const expression = readObjectPropertyValue(body, "database");
587
- const flag = readStaticBooleanLiteral(expression);
588
- if (flag === true) return { mode: "default" };
589
- if (flag === false) throw authErrorDiagnostics.AUTH_C0013({ message: "`defineAuth()` database cannot be `false`." });
590
- const database = objectLiteral(expression);
591
- if (typeof database === "undefined") {
592
- if (allowRuntimeValue) return { mode: "default" };
593
- throw authErrorDiagnostics.AUTH_C0014({ message: "`defineAuth()` database must be `true` or an inline object with `name`." });
594
- }
595
- assertOnlyObjectKeys(database, /* @__PURE__ */ new Set(["dedicated", "name"]), "database");
596
- return {
597
- dedicated: readStaticBooleanProperty(database, "dedicated", "database.dedicated") ?? false,
598
- mode: "named",
599
- name: readStaticStringProperty(database, "name", "database.name") ?? (() => {
600
- throw authErrorDiagnostics.AUTH_C0015({ message: "`defineAuth()` database.name is required when database is an object." });
601
- })()
602
- };
603
- }
604
- function readAuthSecondaryStorageConfig(body, allowRuntimeValue = false) {
605
- if (!hasObjectProperty(body, "secondaryStorage")) return false;
606
- const expression = readObjectPropertyValue(body, "secondaryStorage");
607
- const flag = readStaticBooleanLiteral(expression);
608
- if (flag === true) return { mode: "default" };
609
- if (flag === false) throw authErrorDiagnostics.AUTH_C0016({ message: "`defineAuth()` secondaryStorage cannot be `false`." });
610
- const secondaryStorage = objectLiteral(expression);
611
- if (typeof secondaryStorage === "undefined") {
612
- if (allowRuntimeValue) return false;
613
- throw authErrorDiagnostics.AUTH_C0017({ message: "`defineAuth()` secondaryStorage must be `true` or an inline object with `store`." });
614
- }
615
- assertOnlyObjectKeys(secondaryStorage, /* @__PURE__ */ new Set(["store"]), "secondaryStorage");
616
- return {
617
- mode: "named",
618
- store: readStaticStringProperty(secondaryStorage, "store", "secondaryStorage.store") ?? (() => {
619
- throw authErrorDiagnostics.AUTH_C0018({ message: "`defineAuth()` secondaryStorage.store is required when secondaryStorage is an object." });
620
- })()
621
- };
622
- }
623
- function resolveAuthViteConfig(options, rootDir = process.cwd(), discovery = {}) {
624
- if (options === false) return;
625
- const definition = discoverAuthDefinition(rootDir, discovery);
626
- if (!definition) return;
627
- const definitionObject = readDefinitionObjectBody(definition.handler);
628
- if (typeof definitionObject === "undefined") throw authErrorDiagnostics.AUTH_C0019({ message: "`defineAuth()` options must be an inline object literal." });
629
- const body = definitionObject.body;
630
- assertStaticObjectKeys(body, "options");
631
- const basePath = normalizeAuthBasePath(readStaticStringProperty(body, "basePath", "basePath"));
632
- return {
633
- access: { routes: readAuthAccessRoutesConfig(body) },
634
- basePath,
635
- database: readAuthDatabaseConfig(body, definitionObject.callback),
636
- definition,
637
- rootDir,
638
- route: readAuthRouteConfig(body),
639
- secondaryStorage: readAuthSecondaryStorageConfig(body, definitionObject.callback)
640
- };
641
- }
642
- //#endregion
643
- //#region src/node-response.ts
644
- async function sendWebResponse(response, target) {
645
- target.statusCode = response.status;
646
- target.statusMessage = response.statusText;
647
- const setCookieHeaders = readSetCookies(response.headers);
648
- response.headers.forEach((value, key) => {
649
- if (key.toLowerCase() === "set-cookie" && setCookieHeaders.length > 0) return;
650
- target.appendHeader(key, value);
651
- });
652
- for (const value of setCookieHeaders) target.appendHeader("set-cookie", value);
653
- if (!response.body) {
654
- target.end();
655
- return;
656
- }
657
- const reader = response.body.getReader();
658
- try {
659
- for (;;) {
660
- const chunk = await reader.read();
661
- if (chunk.done) break;
662
- target.write(Buffer.from(chunk.value));
663
- }
664
- } finally {
665
- target.end();
666
- reader.releaseLock();
667
- }
668
- }
669
- //#endregion
670
- //#region src/vite.ts
671
- function shouldPassThroughAuthResponse(basePath, status) {
672
- return basePath === "/" && status === 404;
673
- }
674
- const AUTH_DEFINITION_ID = "#vitehub/auth/definition";
675
- const AUTH_SERVER_ID = "#vitehub/auth/server";
676
- const AUTH_VITE_PLUGIN_NAME = "@vite-hub/auth/vite";
677
- const RESOLVED_AUTH_DEFINITION_ID = `\0${AUTH_DEFINITION_ID}`;
678
- const RESOLVED_AUTH_SERVER_ID = `\0${AUTH_SERVER_ID}`;
679
- const authPackageName = "@vite-hub/auth";
680
- const envServerModuleId = "#vitehub/env/server";
681
- const envVitePluginName = "@vite-hub/env/vite";
682
- const generatedAuthAccessMiddlewareHandler = ".vitehub/auth/access-middleware.ts";
683
- const generatedAuthRouteHandler = ".vitehub/auth/route.ts";
684
- const mergeNoExternal = createNoExternalAddition(authPackageName);
685
- /** Lists the Auth Definition as a serializable inspection summary. */
686
- function inspectAuthDefinitions(options) {
687
- return summarizeDefinitions(options.projectRoot, discoverAuthDefinitions(options.rootDir, { serverDirs: options.serverDirs }), "server-auth");
688
- }
689
- function createAuthNitroConfig(plugin, options) {
690
- const viteConfig = {
691
- root: options.projectRoot,
692
- nitro: options.nitro,
693
- auth: options.viteAuth,
694
- ...options.serverDirs ? { [VITEHUB_SERVER_DIRS]: options.serverDirs } : {}
695
- };
696
- if (plugin.config && typeof plugin.config === "function") plugin.config.call({}, viteConfig, {
697
- command: "build",
698
- isPreview: false,
699
- isSsrBuild: true,
700
- mode: "production"
701
- });
702
- return viteConfig.nitro;
703
- }
704
- function renderAuthDefinitionModule(config) {
705
- if (!config) return "export const definition = undefined\nexport default definition\n";
706
- return [
707
- `import definition from ${JSON.stringify(config.definition.handler)}`,
708
- "export { definition }",
709
- "export default definition",
710
- ""
711
- ].join("\n");
712
- }
713
- function renderAuthServerModule(options = { serverEnv: false }) {
714
- const serverImport = `${options.importBase ?? authPackageName}/server`;
715
- return [
716
- ...options.serverEnv ? [
717
- `import definition from ${JSON.stringify(AUTH_DEFINITION_ID)}`,
718
- `import { setAuthRuntimeEnvResolver } from ${JSON.stringify(serverImport)}`,
719
- `import { useServerEnv } from ${JSON.stringify(envServerModuleId)}`,
720
- "setAuthRuntimeEnvResolver(useServerEnv, definition)",
721
- ""
722
- ] : [],
723
- `export * from ${JSON.stringify(serverImport)}`,
724
- `export { handleAuth as default } from ${JSON.stringify(serverImport)}`,
725
- ""
726
- ].join("\n");
727
- }
728
- function renderAuthRouteHandler() {
729
- return [`export { default } from ${JSON.stringify(AUTH_SERVER_ID)}`, ""].join("\n");
730
- }
731
- function renderAuthAccessMiddlewareHandler(config) {
732
- const routes = JSON.stringify(config?.access.routes ?? []);
733
- return [
734
- `import { createAuthAccessHandler } from ${JSON.stringify(AUTH_SERVER_ID)}`,
735
- "",
736
- `export default createAuthAccessHandler(${routes})`,
737
- ""
738
- ].join("\n");
739
- }
740
- /** A relative `import()` type specifier that resolves under NodeNext and bundler resolution: `auth.ts` becomes `auth.js`. */
741
- function typeImportSpecifier(from, file) {
742
- const path = relative(from, file).replaceAll("\\", "/").replace(/\.([cm]?)ts$/, ".$1js");
743
- return path.startsWith(".") ? path : `./${path}`;
744
- }
745
- function authAmbientTypesPath(root) {
746
- return resolve(root, ".vitehub", "types", "auth.d.ts");
747
- }
748
- function authServerTypesPath(root) {
749
- return resolve(root, ".vitehub", "types", "auth-server.d.ts");
750
- }
751
- function renderAuthAmbientTypes(options = { serverEnv: false }) {
752
- const registry = options.definition ? [`interface AuthRegistry { definition: typeof import(${JSON.stringify(options.definition)}).default }`] : [];
753
- if (options.serverEnv) return [
754
- `import type { ServerEnv } from ${JSON.stringify(envServerModuleId)}`,
755
- "",
756
- "declare global {",
757
- " namespace ViteHub {",
758
- " interface AuthRuntimeEnv extends ServerEnv {}",
759
- ...registry.map((line) => ` ${line}`),
760
- " }",
761
- "}",
762
- ""
763
- ].join("\n");
764
- return registry.length ? [
765
- "declare namespace ViteHub {",
766
- ...registry.map((line) => ` ${line}`),
767
- "}",
768
- ""
769
- ].join("\n") : "export {}\n";
770
- }
771
- /**
772
- * The declaration of the virtual module. It stays out of a file with imports, which would make it an augmentation of
773
- * a module that must already resolve. A Nuxt 4 app resolves `#vitehub/auth/server` only in the bundler, so its
774
- * tsconfig would not find it and the types of everything that imports the Auth handlers would be `any`.
775
- */
776
- function renderAuthServerTypes(importBase = authPackageName) {
777
- const serverImport = `${importBase}/server`;
778
- return [
779
- `declare module ${JSON.stringify(AUTH_SERVER_ID)} {`,
780
- ` export * from ${JSON.stringify(serverImport)}`,
781
- ` export { handleAuth as default } from ${JSON.stringify(serverImport)}`,
782
- "}",
783
- ""
784
- ].join("\n");
785
- }
786
- async function refreshAuthGeneratedFiles(root, config, options = {}) {
787
- await Promise.all([
788
- writeFileIfChanged(resolve(root, generatedAuthAccessMiddlewareHandler), renderAuthAccessMiddlewareHandler(config)),
789
- writeFileIfChanged(authAmbientTypesPath(root), renderAuthAmbientTypes({
790
- definition: config && typeImportSpecifier(dirname(authAmbientTypesPath(root)), config.definition.handler),
791
- serverEnv: Boolean(options.serverEnv)
792
- })),
793
- writeFileIfChanged(authServerTypesPath(root), renderAuthServerTypes(options.importBase)),
794
- writeFileIfChanged(resolve(root, generatedAuthRouteHandler), renderAuthRouteHandler())
795
- ]);
796
- }
797
- function hasServerEnvIntegration(config) {
798
- return Array.isArray(config?.plugins) && config.plugins.some((plugin) => plugin.name === envVitePluginName);
799
- }
800
- function cloneNitroConfig(value) {
801
- return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
802
- }
803
- function authRoutePattern(route) {
804
- return `${route}/**`;
805
- }
806
- const authApplicationBaseURLName = "__VITEHUB_AUTH_APP_BASE_URL__";
807
- /** Return Nitro `baseURL` when the host serves the app below a path, such as Nuxt `app.baseURL`. */
808
- function nitroApplicationBaseURL(value) {
809
- const nitro = cloneNitroConfig(value);
810
- const baseURL = typeof nitro.baseURL === "string" ? nitro.baseURL : "/";
811
- return baseURL.split("/").some(Boolean) ? baseURL : void 0;
812
- }
813
- function mergeNitroAuthHandler(value, config) {
814
- const nitro = cloneNitroConfig(value);
815
- if (!config) return nitro;
816
- const applicationBaseURL = nitroApplicationBaseURL(nitro);
817
- if (applicationBaseURL) nitro.replace = {
818
- ...cloneNitroConfig(nitro.replace),
819
- [authApplicationBaseURLName]: JSON.stringify(applicationBaseURL)
820
- };
821
- const kit = createNitroServerKit(nitro);
822
- const authHandlers = [...config.route === false ? [] : [{
823
- handler: resolve(resolveViteHubProjectRoot(config.rootDir), generatedAuthRouteHandler),
824
- route: authRoutePattern(config.route)
825
- }], ...config.access.routes.length > 0 ? [{
826
- handler: resolve(resolveViteHubProjectRoot(config.rootDir), generatedAuthAccessMiddlewareHandler),
827
- middleware: true,
828
- route: "/**"
829
- }] : []];
830
- if (!authHandlers.length) return nitro;
831
- for (const handler of authHandlers) kit.addHandler(handler);
832
- return kit.config;
833
- }
834
- function readForwardedProtocol(request) {
835
- const value = request.headers["x-forwarded-proto"];
836
- return (Array.isArray(value) ? value[0] : value)?.split(",", 1)[0]?.trim() || "http";
837
- }
838
- function createWebRequest(request) {
839
- const host = request.headers.host ?? "localhost";
840
- const url = new URL(request.url ?? "/", `${readForwardedProtocol(request)}://${host}`);
841
- const headers = new Headers();
842
- for (const [key, value] of Object.entries(request.headers)) {
843
- if (typeof value === "undefined") continue;
844
- if (Array.isArray(value)) {
845
- for (const item of value) headers.append(key, item);
846
- continue;
847
- }
848
- headers.set(key, value);
849
- }
850
- const init = {
851
- headers,
852
- method: request.method
853
- };
854
- if (request.method !== "GET" && request.method !== "HEAD") {
855
- init.body = Readable.toWeb(request);
856
- init.duplex = "half";
857
- }
858
- return new Request(url, init);
859
- }
860
- function loadAuthDefinitionModule(module) {
861
- const value = module;
862
- return value.default ?? value.definition;
863
- }
864
- function hubAuth(options, internalOptions = {}) {
865
- const importBase = internalOptions.importBase ?? authPackageName;
866
- let resolved;
867
- let runtimeConfig;
868
- let serverDirs;
869
- let serverEnv = false;
870
- function resolvedOptions() {
871
- return resolved?.auth ?? options;
872
- }
873
- function refreshRuntimeConfig() {
874
- if (!resolved) return;
875
- runtimeConfig = resolveAuthViteConfig(resolvedOptions(), resolved.root, { serverDirs });
876
- runtimeConfig ??= resolveAuthViteConfig(resolvedOptions(), resolveViteHubProjectRoot(resolved.root), { serverDirs });
877
- resetAuth();
878
- return runtimeConfig;
879
- }
880
- return {
881
- name: AUTH_VITE_PLUGIN_NAME,
882
- enforce: "pre",
883
- api: {
884
- getConfig: () => runtimeConfig,
885
- refresh: refreshRuntimeConfig
886
- },
887
- vitehub: {
888
- cli: async () => resolvedOptions() === false ? void 0 : (await import("./cli.js")).createAuthCliContributor(),
889
- inspect: () => {
890
- if (resolvedOptions() === false) return;
891
- return { definitions: [{
892
- kind: "auth",
893
- label: "Auth",
894
- list: () => {
895
- const rootDir = resolve(resolved?.root ?? process.cwd());
896
- return inspectAuthDefinitions({
897
- projectRoot: resolveViteHubProjectRoot(rootDir),
898
- rootDir,
899
- serverDirs
900
- });
901
- }
902
- }] };
903
- }
904
- },
905
- config(config) {
906
- const configRoot = config.root || process.cwd();
907
- serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
908
- const authOptions = config.auth ?? options;
909
- const authConfig = resolveAuthViteConfig(authOptions, configRoot, { serverDirs }) ?? resolveAuthViteConfig(authOptions, resolveViteHubProjectRoot(configRoot), { serverDirs });
910
- const nitro = mergeNitroAuthHandler(config.nitro, authConfig);
911
- const hasNitroHandlers = Boolean(authConfig && (authConfig.route !== false || authConfig.access.routes.length > 0));
912
- const applicationBaseURL = authConfig ? nitroApplicationBaseURL(nitro) : void 0;
913
- if (hasNitroHandlers || applicationBaseURL) Object.assign(config, { nitro });
914
- const contribution = {
915
- ssr: { noExternal: mergeNoExternal(config.ssr?.noExternal) },
916
- server: { watch: { ignored: generatedViteHubWatchIgnoredAddition(config.server?.watch?.ignored) } }
917
- };
918
- if (applicationBaseURL) contribution.define = { [authApplicationBaseURLName]: JSON.stringify(applicationBaseURL) };
919
- return contribution;
920
- },
921
- async configResolved(config) {
922
- resolved = config;
923
- serverEnv = hasServerEnvIntegration(config);
924
- const runtimeConfig = refreshRuntimeConfig();
925
- await refreshAuthGeneratedFiles(resolveViteHubProjectRoot(config.root), runtimeConfig, {
926
- importBase,
927
- serverEnv
928
- });
929
- },
930
- configEnvironment(name, config) {
931
- if (!isServerEnvironment(name, config)) return;
932
- return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
933
- },
934
- configureServer(server) {
935
- if (!("runner" in server.environments.ssr)) return;
936
- server.middlewares.use(async (request, response, next) => {
937
- try {
938
- const config = runtimeConfig ?? refreshRuntimeConfig();
939
- if (!config || config.route === false || !request.url) {
940
- next();
941
- return;
942
- }
943
- const url = new URL(request.url, "http://vitehub.local");
944
- if (!isAuthRequestPath(url.pathname, config.basePath)) {
945
- next();
946
- return;
947
- }
948
- const definition = loadAuthDefinitionModule(await server.ssrLoadModule(AUTH_DEFINITION_ID));
949
- if (!definition) {
950
- next();
951
- return;
952
- }
953
- const webRequest = createWebRequest(request);
954
- const hasRequestRuntime = typeof definition.options === "function" || typeof definition.options.runtime === "function";
955
- const { getAuthForDefinition, handleAuthRequest } = await import("./server.js");
956
- const authResponse = hasRequestRuntime ? await handleAuthRequest(definition, webRequest) : await getAuthForDefinition(definition).handler(webRequest);
957
- if (shouldPassThroughAuthResponse(config.basePath, authResponse.status)) {
958
- next();
959
- return;
960
- }
961
- await sendWebResponse(authResponse, response);
962
- } catch (error) {
963
- next(error);
964
- }
965
- });
966
- },
967
- handleHotUpdate(context) {
968
- const changed = context.file.replace(/\\/g, "/");
969
- 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;
970
- refreshRuntimeConfig();
971
- const definitionModule = context.server.moduleGraph.getModuleById(RESOLVED_AUTH_DEFINITION_ID);
972
- if (definitionModule) context.server.moduleGraph.invalidateModule(definitionModule);
973
- const serverModule = context.server.moduleGraph.getModuleById(RESOLVED_AUTH_SERVER_ID);
974
- if (serverModule) context.server.moduleGraph.invalidateModule(serverModule);
975
- },
976
- resolveId(id) {
977
- if (id === "#vitehub/auth/definition") return RESOLVED_AUTH_DEFINITION_ID;
978
- if (id === "#vitehub/auth/server") return RESOLVED_AUTH_SERVER_ID;
979
- },
980
- load(id) {
981
- if (id === RESOLVED_AUTH_DEFINITION_ID) return renderAuthDefinitionModule(runtimeConfig);
982
- if (id === RESOLVED_AUTH_SERVER_ID) return renderAuthServerModule({
983
- importBase,
984
- serverEnv
985
- });
986
- }
987
- };
988
- }
989
- //#endregion
990
- export { hubAuth as a, resolveAuthViteConfig as c, createAuthNitroConfig as i, resolveNuxtServerDirs as l, AUTH_SERVER_ID as n, inspectAuthDefinitions as o, AUTH_VITE_PLUGIN_NAME as r, shouldPassThroughAuthResponse as s, AUTH_DEFINITION_ID as t, resolveViteHubProjectRoot as u };