@vite-hub/comments 0.0.0-stage → 0.1.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 (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +242 -2
  3. package/dist/anchor.d.ts +40 -0
  4. package/dist/anchor.js +128 -0
  5. package/dist/client.d.ts +101 -0
  6. package/dist/client.js +553 -0
  7. package/dist/console-BIz9t2cO.d.ts +243 -0
  8. package/dist/database/postgres.d.ts +1011 -0
  9. package/dist/database/postgres.js +60 -0
  10. package/dist/database-BSnVrwHn.js +60 -0
  11. package/dist/database-C-ktS9Do.js +95 -0
  12. package/dist/database-Cb2xjC1V.d.ts +1096 -0
  13. package/dist/database.d.ts +104 -0
  14. package/dist/database.js +3 -0
  15. package/dist/define-BzW2Ychn.d.ts +46 -0
  16. package/dist/define-Cbhl6QVJ.js +32 -0
  17. package/dist/errors-BAQYcy3_.d.ts +89 -0
  18. package/dist/errors-DeD6wTCl.js +77 -0
  19. package/dist/h3-v1-request-DDGXJ9E7.js +166 -0
  20. package/dist/identity-3qtVC4rF.js +34 -0
  21. package/dist/index-DklG2Etf.d.ts +111 -0
  22. package/dist/index.d.ts +7 -0
  23. package/dist/index.js +5 -0
  24. package/dist/operations-0B0QTVWX.d.ts +138 -0
  25. package/dist/operations-NZG5dB8y.js +732 -0
  26. package/dist/operations.d.ts +7 -0
  27. package/dist/operations.js +2 -0
  28. package/dist/overlay/overlay.js +195 -0
  29. package/dist/page/loader.js +22 -0
  30. package/dist/page-BtXADR6d.d.ts +21 -0
  31. package/dist/page-BuroSMXO.js +38 -0
  32. package/dist/page-tools-shared-D-amu6sx.js +53 -0
  33. package/dist/plugin-QElKQYkA.js +725 -0
  34. package/dist/realtime.d.ts +18 -0
  35. package/dist/realtime.js +48 -0
  36. package/dist/request-DVc3M_AG.js +14 -0
  37. package/dist/rpc.d.ts +29 -0
  38. package/dist/rpc.js +75 -0
  39. package/dist/runtime/auth.d.ts +6 -0
  40. package/dist/runtime/auth.js +15 -0
  41. package/dist/runtime/connect/node.d.ts +1 -0
  42. package/dist/runtime/connect/node.js +2 -0
  43. package/dist/runtime/connect.d.ts +1 -0
  44. package/dist/runtime/connect.js +2 -0
  45. package/dist/runtime/console.d.ts +5 -0
  46. package/dist/runtime/console.js +59 -0
  47. package/dist/runtime/index.d.ts +222 -0
  48. package/dist/runtime/index.js +665 -0
  49. package/dist/server-BomGg3Gb.js +63 -0
  50. package/dist/server.d.ts +94 -0
  51. package/dist/server.js +326 -0
  52. package/dist/src-CRTwnaEG.js +1362 -0
  53. package/dist/testing.d.ts +30 -0
  54. package/dist/testing.js +175 -0
  55. package/dist/types-Cj8K7Vx7.d.ts +176 -0
  56. package/dist/types-Un2dcJWD.d.ts +288 -0
  57. package/dist/vite.d.ts +304 -0
  58. package/dist/vite.js +1921 -0
  59. package/package.json +156 -3
package/dist/vite.js ADDED
@@ -0,0 +1,1921 @@
1
+ import { t as commentsErrorDiagnostics } from "./errors-DeD6wTCl.js";
2
+ import { i as validateCommentsDefinition } from "./define-Cbhl6QVJ.js";
3
+ import { a as mountedCommentsRoute, i as commentsRoute, r as commentsRealtimeDefinition } from "./page-BuroSMXO.js";
4
+ import { a as viteHubPageToolsInlineScript, i as viteHubPageToolsCookie, l as viteHubPageToolsQuery, n as viteHubPageSessionPath, r as viteHubPageToolsAssets, t as viteHubBasePath } from "./page-tools-shared-D-amu6sx.js";
5
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { basename, dirname, join, parse, relative, resolve, sep } from "node:path";
8
+ import { parseSync } from "vite";
9
+ import { execFile } from "node:child_process";
10
+ import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
11
+ import { fileURLToPath, pathToFileURL } from "node:url";
12
+ import { promisify } from "node:util";
13
+ import { nitro } from "nitro/vite";
14
+ import { parseDatabaseLocation } from "@vite-hub/database/config";
15
+ import { parseJSONC, parseTOML } from "confbox";
16
+ //#region ../internal/src/build/vite.ts
17
+ const projectRootDirectoryMarkers = [
18
+ ["server", "agents"],
19
+ ["server", "channels"],
20
+ ["server", "connections"],
21
+ ["server", "browsers"],
22
+ ["server", "emails"],
23
+ ["server", "schedules"],
24
+ ["server", "workspaces"]
25
+ ];
26
+ const projectRootFileMarkers = [
27
+ ["package.json"],
28
+ ["nuxt.config.ts"],
29
+ ["nuxt.config.mts"],
30
+ ["nuxt.config.js"],
31
+ ["nuxt.config.mjs"]
32
+ ];
33
+ function isServerEnvironment(name, config) {
34
+ return name === "ssr" || config.consumer === "server";
35
+ }
36
+ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
37
+ /** The application's mount path, which can differ from Nuxt's Vite asset base. */
38
+ const VITEHUB_APP_BASE_URL = "__vitehubAppBaseURL";
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
+ function resolveViteHubProjectRoot(root, options = {}) {
45
+ const resolvedRoot = resolve(root);
46
+ const temporaryRoot = resolve(tmpdir());
47
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
48
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
49
+ if (basename(resolvedRoot) === "app") {
50
+ const parent = dirname(resolvedRoot);
51
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
52
+ "nuxt.config.ts",
53
+ "nuxt.config.mts",
54
+ "nuxt.config.js",
55
+ "nuxt.config.mjs"
56
+ ]))) return parent;
57
+ }
58
+ let current = resolvedRoot;
59
+ while (true) {
60
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
61
+ if (hasProjectRootMarker(current)) return current;
62
+ const parent = dirname(current);
63
+ if (parent === current) return resolvedRoot;
64
+ current = parent;
65
+ }
66
+ }
67
+ function hasProjectRootDirectoryMarker(root) {
68
+ for (const marker of projectRootDirectoryMarkers) try {
69
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
70
+ } catch (error) {
71
+ if (error.code !== "ENOENT") throw error;
72
+ }
73
+ return false;
74
+ }
75
+ function hasProjectRootMarker(root) {
76
+ if (hasProjectRootDirectoryMarker(root)) return true;
77
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
78
+ }
79
+ function hasProjectRootFileMarker(root, markers) {
80
+ for (const marker of markers) {
81
+ const path = Array.isArray(marker) ? marker : [marker];
82
+ try {
83
+ if (statSync(resolve(root, ...path)).isFile()) return true;
84
+ } catch (error) {
85
+ if (error.code !== "ENOENT") throw error;
86
+ }
87
+ }
88
+ return false;
89
+ }
90
+ //#endregion
91
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
92
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
93
+ function normalizeWindowsPath(input = "") {
94
+ if (!input) return input;
95
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
96
+ }
97
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
98
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
99
+ function cwd() {
100
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
101
+ return "/";
102
+ }
103
+ const resolve$1 = function(...arguments_) {
104
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
105
+ let resolvedPath = "";
106
+ let resolvedAbsolute = false;
107
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
108
+ const path = index >= 0 ? arguments_[index] : cwd();
109
+ if (!path || path.length === 0) continue;
110
+ resolvedPath = `${path}/${resolvedPath}`;
111
+ resolvedAbsolute = isAbsolute(path);
112
+ }
113
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
114
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
115
+ return resolvedPath.length > 0 ? resolvedPath : ".";
116
+ };
117
+ function normalizeString(path, allowAboveRoot) {
118
+ let res = "";
119
+ let lastSegmentLength = 0;
120
+ let lastSlash = -1;
121
+ let dots = 0;
122
+ let char = null;
123
+ for (let index = 0; index <= path.length; ++index) {
124
+ if (index < path.length) char = path[index];
125
+ else if (char === "/") break;
126
+ else char = "/";
127
+ if (char === "/") {
128
+ if (lastSlash === index - 1 || dots === 1);
129
+ else if (dots === 2) {
130
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
131
+ if (res.length > 2) {
132
+ const lastSlashIndex = res.lastIndexOf("/");
133
+ if (lastSlashIndex === -1) {
134
+ res = "";
135
+ lastSegmentLength = 0;
136
+ } else {
137
+ res = res.slice(0, lastSlashIndex);
138
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
139
+ }
140
+ lastSlash = index;
141
+ dots = 0;
142
+ continue;
143
+ } else if (res.length > 0) {
144
+ res = "";
145
+ lastSegmentLength = 0;
146
+ lastSlash = index;
147
+ dots = 0;
148
+ continue;
149
+ }
150
+ }
151
+ if (allowAboveRoot) {
152
+ res += res.length > 0 ? "/.." : "..";
153
+ lastSegmentLength = 2;
154
+ }
155
+ } else {
156
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
157
+ else res = path.slice(lastSlash + 1, index);
158
+ lastSegmentLength = index - lastSlash - 1;
159
+ }
160
+ lastSlash = index;
161
+ dots = 0;
162
+ } else if (char === "." && dots !== -1) ++dots;
163
+ else dots = -1;
164
+ }
165
+ return res;
166
+ }
167
+ const isAbsolute = function(p) {
168
+ return _IS_ABSOLUTE_RE.test(p);
169
+ };
170
+ const relative$1 = function(from, to) {
171
+ const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
172
+ const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
173
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
174
+ const _fromCopy = [..._from];
175
+ for (const segment of _fromCopy) {
176
+ if (_to[0] !== segment) break;
177
+ _from.shift();
178
+ _to.shift();
179
+ }
180
+ return [..._from.map(() => ".."), ..._to].join("/");
181
+ };
182
+ //#endregion
183
+ //#region ../internal/src/inspect.ts
184
+ function relativeDefinitionFile(projectRoot, file) {
185
+ return relative$1(projectRoot, file).replaceAll("\\", "/");
186
+ }
187
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
188
+ 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");
189
+ new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
190
+ //#endregion
191
+ //#region ../internal/src/object.ts
192
+ function isPlainObject(value) {
193
+ if (value === null || Object(value) !== value || Array.isArray(value)) return false;
194
+ return typeof value === "object";
195
+ }
196
+ //#endregion
197
+ //#region ../internal/src/build/scan-module.ts
198
+ /**
199
+ * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
200
+ * the oxc parser that Vite ships through Rolldown, and never runs it. Values that are not static literals read as
201
+ * `dynamic`, so callers can report their own diagnostics.
202
+ */
203
+ /** The value of an expression that the scanner cannot read without running the module. */
204
+ const dynamic = Symbol("dynamic");
205
+ function languageOf(file) {
206
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
207
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
208
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
209
+ return "ts";
210
+ }
211
+ /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
212
+ function scanModule(source, file = "module.ts") {
213
+ const result = parseSync(file, source, {
214
+ lang: languageOf(file),
215
+ preserveParens: false,
216
+ sourceType: "module"
217
+ });
218
+ return {
219
+ comments: result.comments,
220
+ errors: result.errors,
221
+ file,
222
+ program: result.program,
223
+ source
224
+ };
225
+ }
226
+ /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
227
+ function unwrapExpression(node) {
228
+ while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
229
+ return node;
230
+ }
231
+ /** A call argument without assertions, or undefined for a spread or missing argument. */
232
+ function argumentExpression(argument) {
233
+ return argument === void 0 || argument.type === "SpreadElement" ? void 0 : unwrapExpression(argument);
234
+ }
235
+ function staticKey(property) {
236
+ const key = property.key;
237
+ if (key.type === "Identifier" && !property.computed) return key.name;
238
+ if (key.type === "PrivateIdentifier") return;
239
+ const value = staticValue(key);
240
+ return typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? String(value) : void 0;
241
+ }
242
+ /** The members of an object literal in source order. */
243
+ function objectProperties(object) {
244
+ return object.properties.map((node) => node.type === "SpreadElement" ? {
245
+ computed: false,
246
+ key: void 0,
247
+ node,
248
+ value: void 0
249
+ } : {
250
+ computed: node.computed,
251
+ key: staticKey(node),
252
+ node,
253
+ value: unwrapExpression(node.value)
254
+ });
255
+ }
256
+ /** The value of a template literal without substitutions. */
257
+ function staticTemplate(node) {
258
+ if (node.expressions.length) return dynamic;
259
+ return node.quasis[0]?.value.cooked ?? dynamic;
260
+ }
261
+ const escapePattern = /\\(u\{[^}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|0\d|[\s\S])/g;
262
+ /**
263
+ * True when a string literal has an escape that strict mode code rejects. The parser recovers from some bad escapes
264
+ * and accepts legacy octal escapes, so the scanner checks them again.
265
+ */
266
+ function hasInvalidEscape(raw) {
267
+ for (const [, escape = ""] of raw.matchAll(escapePattern)) if (escape.startsWith("u{")) {
268
+ const code = escape.slice(2, -1);
269
+ if (!escape.endsWith("}") || !/^[\da-fA-F]+$/.test(code) || Number.parseInt(code, 16) > 1114111) return true;
270
+ } else if (escape.startsWith("u")) {
271
+ if (!/^u[\da-fA-F]{4}$/.test(escape)) return true;
272
+ } else if (escape.startsWith("x")) {
273
+ if (!/^x[\da-fA-F]{2}$/.test(escape)) return true;
274
+ } else if (/^(?:[1-9]|0\d)$/.test(escape)) return true;
275
+ return false;
276
+ }
277
+ /**
278
+ * Reads a literal value: strings, numbers, booleans, `null`, `undefined`, template literals without substitutions,
279
+ * and arrays and objects of these. Any other expression gives `dynamic`.
280
+ */
281
+ function staticValue(node) {
282
+ node = unwrapExpression(node);
283
+ switch (node.type) {
284
+ case "Literal":
285
+ if ("regex" in node) return dynamic;
286
+ return typeof node.value === "string" && hasInvalidEscape(node.raw ?? "") ? dynamic : node.value;
287
+ case "TemplateLiteral": return staticTemplate(node);
288
+ case "Identifier": return node.name === "undefined" ? void 0 : dynamic;
289
+ case "UnaryExpression": {
290
+ if (node.operator === "void") return staticValue(node.argument) === dynamic ? dynamic : void 0;
291
+ const value = staticValue(node.argument);
292
+ if (node.operator === "-" && (typeof value === "number" || typeof value === "bigint")) return -value;
293
+ return dynamic;
294
+ }
295
+ case "ArrayExpression": {
296
+ const values = [];
297
+ for (const element of node.elements) {
298
+ if (element === null || element.type === "SpreadElement") return dynamic;
299
+ const value = staticValue(element);
300
+ if (value === dynamic) return dynamic;
301
+ values.push(value);
302
+ }
303
+ return values;
304
+ }
305
+ case "ObjectExpression": {
306
+ const values = {};
307
+ for (const property of objectProperties(node)) {
308
+ if (property.key === void 0 || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value === void 0) return dynamic;
309
+ const value = staticValue(property.value);
310
+ if (value === dynamic) return dynamic;
311
+ Object.defineProperty(values, property.key, {
312
+ configurable: true,
313
+ enumerable: true,
314
+ value,
315
+ writable: true
316
+ });
317
+ }
318
+ return values;
319
+ }
320
+ default: return dynamic;
321
+ }
322
+ }
323
+ /** The static string value of an expression, or undefined when it is not a string literal. */
324
+ function staticString(node) {
325
+ if (node === void 0) return;
326
+ const value = staticValue(node);
327
+ return typeof value === "string" ? value : void 0;
328
+ }
329
+ //#endregion
330
+ //#region src/entry.ts
331
+ const extensions = [
332
+ ".ts",
333
+ ".mts",
334
+ ".js",
335
+ ".mjs"
336
+ ];
337
+ /** `server/comments.ts`, or undefined when the app does not define Comments. */
338
+ function findCommentsEntry$2(projectRoot, serverDirs) {
339
+ for (const directory of serverDirs?.length ? serverDirs : ["server"]) for (const extension of extensions) {
340
+ const file = resolve(projectRoot, directory, `comments${extension}`);
341
+ if (existsSync(file)) return file;
342
+ }
343
+ }
344
+ /** `server/content.ts`, or undefined. Inline edits need it. */
345
+ function findContentEntry(projectRoot, serverDirs) {
346
+ for (const directory of serverDirs?.length ? serverDirs : ["server"]) for (const extension of extensions) {
347
+ const file = resolve(projectRoot, directory, `content${extension}`);
348
+ if (existsSync(file)) return file;
349
+ }
350
+ }
351
+ //#endregion
352
+ //#region ../internal/src/build/page-tools.ts
353
+ /**
354
+ * Adds the session route `GET <mount>/_vitehub/page/session` and the loader script at
355
+ * `<mount>/_vitehub/page/assets/loader.js` to a Nitro configuration. Each owner package of a page tool calls it from its
356
+ * Vite plugin, so the routes exist without the Console. The first owner wins: a later call keeps the route and the asset
357
+ * that are already there, because the page tools registry is shared by every copy of this package.
358
+ */
359
+ function addViteHubPageToolRoutes(kit, options) {
360
+ const mount = options.mount ?? "";
361
+ const route = `${mount}${viteHubPageSessionPath}`;
362
+ const assetsBase = `${mount}${viteHubPageToolsAssets}`;
363
+ if (!(Array.isArray(kit.config.handlers) ? kit.config.handlers : []).some((handler) => Object(handler) === handler && Reflect.get(Object(handler), "route") === route)) kit.addHandler({
364
+ handler: options.handler,
365
+ route
366
+ });
367
+ const assets = Array.isArray(kit.config.publicAssets) ? [...kit.config.publicAssets] : [];
368
+ if (!assets.some((asset) => Object(asset) === asset && Reflect.get(Object(asset), "baseURL") === assetsBase)) assets.push({
369
+ baseURL: assetsBase,
370
+ dir: options.loader,
371
+ maxAge: 300
372
+ });
373
+ kit.config.publicAssets = assets;
374
+ }
375
+ function readString(value, key) {
376
+ const field = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
377
+ return typeof field === "string" ? field : void 0;
378
+ }
379
+ /**
380
+ * The app base of a Vite configuration. ViteHub's application-base config field or `__VITEHUB_APP_BASE_URL__` constant
381
+ * takes precedence over the Vite `base`; the Nuxt module sets both from `app.baseURL`. Only a root-relative Vite `base`
382
+ * supplies an application path; absolute and protocol-relative URLs are asset CDN bases. The Nitro base is
383
+ * `nitro.baseURL`, else `NITRO_APP_BASE_URL`.
384
+ */
385
+ function viteHubPageToolsBase(config, env = process.env) {
386
+ const defined = readString(config !== null && typeof config === "object" ? Reflect.get(config, "define") : void 0, "__VITEHUB_APP_BASE_URL__");
387
+ const viteBase = readString(config, "base");
388
+ let appBase = viteBase?.startsWith("/") && !viteBase.startsWith("//") ? viteBase : void 0;
389
+ if (defined) try {
390
+ const value = JSON.parse(defined);
391
+ if (typeof value === "string") appBase = value;
392
+ } catch {}
393
+ const base = viteHubBasePath(readString(config, "__vitehubAppBaseURL") ?? appBase);
394
+ const nitro = config !== null && typeof config === "object" ? Reflect.get(config, "nitro") : void 0;
395
+ const nitroBase = viteHubBasePath(readString(nitro, "baseURL") ?? env.NITRO_APP_BASE_URL);
396
+ return {
397
+ base,
398
+ mount: nitroBase && (base === nitroBase || base.startsWith(`${nitroBase}/`)) ? base.slice(nitroBase.length) : base
399
+ };
400
+ }
401
+ /**
402
+ * Adds the page tools loader to the `index.html` of a single page app, for an owner's Vite `transformIndexHtml` hook.
403
+ * The added module script loads `<base>/_vitehub/page/assets/loader.js` in the browser when the page has the hint: the
404
+ * `?vitehub` query or the `vitehub-tools=1` cookie. It works where no server changes the HTML: in the Vite dev server,
405
+ * and for a built `index.html` that a host serves as a static file. It returns `undefined` when the page already has
406
+ * the loader, so several owner packages add one script. `base` is the Vite `base`, such as `/portal/`.
407
+ */
408
+ function viteHubPageToolsIndexHtml(html, base) {
409
+ if (html.includes("data-vitehub-page-tools")) return void 0;
410
+ const script = viteHubPageToolsInlineScript(base);
411
+ const index = html.search(/<\/body\s*>/i);
412
+ return index === -1 ? `${html}${script}` : `${html.slice(0, index)}${script}${html.slice(index)}`;
413
+ }
414
+ //#endregion
415
+ //#region ../internal/src/build/included-nitro.ts
416
+ const includedKey = Symbol.for("vitehub.included-nitro");
417
+ const scope = globalThis;
418
+ const includedNitroPlugins = scope[includedKey] ??= /* @__PURE__ */ new WeakSet();
419
+ function flattenPlugins$1(option) {
420
+ if (Array.isArray(option)) return option.flatMap(flattenPlugins$1);
421
+ return option && typeof option === "object" && "name" in option ? [option] : [];
422
+ }
423
+ /** Whether the app added `nitro()` itself. Nitro plugins that a ViteHub package included do not count. */
424
+ function findAppNitro(value) {
425
+ if (Array.isArray(value)) return value.some(findAppNitro);
426
+ return value !== null && typeof value === "object" && !includedNitroPlugins.has(value) && Reflect.get(value, "name") === "nitro:main";
427
+ }
428
+ function applies(apply, config, env) {
429
+ if (typeof apply === "function") return apply(config, env);
430
+ return apply === void 0 || apply === env.command;
431
+ }
432
+ /**
433
+ * Returns the Vite plugins of Nitro, the server of a ViteHub app. They apply only when the app does not add `nitro()`
434
+ * itself, so an app that still adds it gets one Nitro. `unless` steps aside for another package that includes Nitro.
435
+ */
436
+ function includedNitro(options = {}) {
437
+ const plugins = flattenPlugins$1(nitro());
438
+ for (const plugin of plugins) {
439
+ const apply = plugin.apply;
440
+ plugin.apply = (config, env) => !findAppNitro(config.plugins) && !options.unless?.(config) && applies(apply, config, env);
441
+ includedNitroPlugins.add(plugin);
442
+ }
443
+ return plugins;
444
+ }
445
+ //#endregion
446
+ //#region ../internal/src/build/nitro-workerd-dependencies.ts
447
+ /**
448
+ * Nitro's workerd dev runner, the default of its Cloudflare presets, sets `resolve.noExternal: true` and runs every
449
+ * dependency through Vite's module runner as source. Vite pre-bundles dependencies only for the client by default, so
450
+ * a CommonJS dependency, such as `promise-limit` under `@libsql/client` or the OpenTelemetry constants under Better
451
+ * Auth, reaches workerd unconverted and fails with "module is not defined" or "exports is not defined".
452
+ *
453
+ * This plugin lets Vite find and pre-bundle the dependencies of those environments, as `@cloudflare/vite-plugin` does
454
+ * for its Workers. Nitro stays out of the pre-bundle, because its app module must keep the routes of the app. An app
455
+ * that sets `optimizeDeps.noDiscovery` for the environment keeps its own setting.
456
+ */
457
+ function nitroWorkerdDependencies() {
458
+ return {
459
+ name: "vite-hub/nitro-workerd-dependencies",
460
+ apply: "serve",
461
+ enforce: "post",
462
+ configEnvironment(name, config) {
463
+ if (!isServerEnvironment(name, config) || config.resolve?.noExternal !== true) return;
464
+ if (!config.resolve.conditions?.some((condition) => condition === "workerd" || condition === "worker")) return;
465
+ return { optimizeDeps: {
466
+ noDiscovery: config.optimizeDeps?.noDiscovery ?? false,
467
+ exclude: ["nitro"]
468
+ } };
469
+ }
470
+ };
471
+ }
472
+ //#endregion
473
+ //#region ../internal/src/nitro-kit.ts
474
+ function cloneArray(value) {
475
+ return Array.isArray(value) ? [...value] : [];
476
+ }
477
+ function isRecord(value) {
478
+ return Object(value) === value && !Array.isArray(value);
479
+ }
480
+ function sameHandler(left, right) {
481
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
482
+ }
483
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
484
+ function createNitroServerKit(value = {}) {
485
+ const config = isRecord(value) ? { ...value } : {};
486
+ const handlers = cloneArray(config.handlers);
487
+ const plugins = cloneArray(config.plugins);
488
+ config.handlers = handlers;
489
+ config.plugins = plugins;
490
+ return {
491
+ config,
492
+ addHandler(handler, position = "end") {
493
+ if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
494
+ if (position === "start") handlers.unshift({ ...handler });
495
+ else handlers.push({ ...handler });
496
+ },
497
+ addPlugin(plugin, position = "end") {
498
+ if (plugins.includes(plugin)) return;
499
+ if (position === "start") plugins.unshift(plugin);
500
+ else plugins.push(plugin);
501
+ }
502
+ };
503
+ }
504
+ //#endregion
505
+ //#region src/console.ts
506
+ /**
507
+ * Console section for Comments: every thread with its first comment, page, author, replies, and status, open threads
508
+ * first. People reply and resolve on the page itself, where the context is; each record links there with the page tools on. The
509
+ * Console shows it when the app has `server/comments.ts`.
510
+ */
511
+ const commentsConsoleSection = {
512
+ entry: ({ projectRoot, serverDirs }) => findCommentsEntry$2(projectRoot, serverDirs),
513
+ description: "Triage comments that the team left on the site's pages.",
514
+ icon: "i-lucide-message-square-text",
515
+ id: "comments",
516
+ label: "Comments",
517
+ runtime: {
518
+ export: "readCommentsConsoleRecords",
519
+ module: "@vite-hub/comments/runtime/console"
520
+ },
521
+ view: {
522
+ columns: [
523
+ {
524
+ key: "comment",
525
+ label: "Comment"
526
+ },
527
+ {
528
+ key: "page",
529
+ label: "Page"
530
+ },
531
+ {
532
+ key: "author",
533
+ label: "Author"
534
+ },
535
+ {
536
+ key: "replies",
537
+ label: "Replies"
538
+ },
539
+ {
540
+ key: "status",
541
+ label: "Status"
542
+ },
543
+ {
544
+ key: "updated",
545
+ label: "Last activity"
546
+ }
547
+ ],
548
+ kind: "record-table",
549
+ notice: "People comment, reply, and resolve on the site's pages, which show the Comments toolbar after you open the Console. Open threads come first. Server code reads the same threads with `comments.list()`."
550
+ }
551
+ };
552
+ //#endregion
553
+ //#region src/live-vite.ts
554
+ const defaultImports$1 = {
555
+ runtime: "@vite-hub/comments/runtime",
556
+ realtime: "@vite-hub/comments/realtime",
557
+ auth: "@vite-hub/comments/runtime/auth",
558
+ database: "@vite-hub/comments/database",
559
+ databases: "@vite-hub/database/drizzle",
560
+ contentClient: "@vite-hub/content/client",
561
+ connect: "@vite-hub/comments/runtime/connect"
562
+ };
563
+ /**
564
+ * The Database name in `defineComments({ database: "name" })`, read without running the file. Undefined means the
565
+ * default or only Database.
566
+ */
567
+ async function readCommentsDatabase(file) {
568
+ const module = scanModule(await readFile(file, "utf8").catch(() => ""), file);
569
+ if (module.errors.length) return;
570
+ const bindings = /* @__PURE__ */ new Set();
571
+ const factories = /* @__PURE__ */ new Set(["defineComments"]);
572
+ for (const statement of module.program.body) {
573
+ if (statement.type === "ImportDeclaration" && statement.importKind !== "type" && ["vite-hub/comments", "@vite-hub/comments"].includes(statement.source.value)) for (const specifier of statement.specifiers) {
574
+ if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") continue;
575
+ if ((specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value) === "defineComments") factories.add(specifier.local.name);
576
+ }
577
+ if (statement.type !== "ExportNamedDeclaration" || statement.source) continue;
578
+ if (statement.declaration?.type === "VariableDeclaration") {
579
+ for (const declaration of statement.declaration.declarations) if (declaration.id.type === "Identifier" && declaration.id.name === "comments") bindings.add(declaration.id.name);
580
+ }
581
+ for (const specifier of statement.specifiers) if ((specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === "comments" && specifier.local.type === "Identifier") bindings.add(specifier.local.name);
582
+ }
583
+ for (const statement of module.program.body) {
584
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
585
+ if (declaration?.type !== "VariableDeclaration") continue;
586
+ for (const binding of declaration.declarations) {
587
+ if (binding.id.type !== "Identifier" || !bindings.has(binding.id.name) || !binding.init) continue;
588
+ const call = unwrapExpression(binding.init);
589
+ if (call.type !== "CallExpression" || call.callee.type !== "Identifier" || !factories.has(call.callee.name)) continue;
590
+ const options = argumentExpression(call.arguments[0]);
591
+ if (options?.type !== "ObjectExpression") return;
592
+ for (const property of objectProperties(options).reverse()) {
593
+ if (property.key === void 0) return;
594
+ if (property.key !== "database") continue;
595
+ if (property.node.type !== "Property" || property.node.kind !== "init" || property.node.method) return;
596
+ return staticString(property.value);
597
+ }
598
+ return;
599
+ }
600
+ }
601
+ }
602
+ /** A directory of prebuilt browser scripts in this package. */
603
+ function builtDirectory(name) {
604
+ const here = dirname(fileURLToPath(import.meta.url));
605
+ return here.endsWith("src") ? resolve(here, `../dist/${name}`) : resolve(here, name);
606
+ }
607
+ /** The directory of the prebuilt overlay script in this package. */
608
+ function commentsOverlayDirectory() {
609
+ return builtDirectory("overlay");
610
+ }
611
+ /** CI and host variables that name the commit and branch of a build, in the order they are read. */
612
+ const buildVariables = [
613
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
614
+ ["WORKERS_CI_COMMIT_SHA", "WORKERS_CI_BRANCH"],
615
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
616
+ ["COMMIT_REF", "BRANCH"],
617
+ ["GITHUB_SHA", "GITHUB_HEAD_REF"]
618
+ ];
619
+ async function git(root, args) {
620
+ try {
621
+ const { stdout } = await promisify(execFile)("git", args, {
622
+ cwd: root,
623
+ encoding: "utf8",
624
+ timeout: 3e3
625
+ });
626
+ return stdout.trim() || void 0;
627
+ } catch {
628
+ return;
629
+ }
630
+ }
631
+ /** `owner/name` of a GitHub or Enterprise remote. The forge's API URL selects the server at runtime. */
632
+ function githubRepository(remote) {
633
+ return remote ? /^(?:(?:https?|ssh|git):\/\/[^/]+\/|(?:[^@/:]+@)?[\w.-]+:)([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(remote.trim())?.[1] : void 0;
634
+ }
635
+ /** The pull request that the CI or host builds, when it names one. */
636
+ function pullRequestOf(env) {
637
+ const value = env.VERCEL_GIT_PULL_REQUEST_ID || (env.PULL_REQUEST === "true" ? env.REVIEW_ID : void 0) || /^refs\/pull\/(\d+)\//.exec(env.GITHUB_REF ?? "")?.[1];
638
+ const number = Number(value);
639
+ return Number.isSafeInteger(number) && number > 0 ? number : void 0;
640
+ }
641
+ /**
642
+ * The build of the app, from the CI or host, else from Git: the commit and branch, the GitHub repository, and the pull
643
+ * request when the host names it. Empty outside a Git checkout.
644
+ */
645
+ async function readCommentsBuild(root, env = process.env) {
646
+ const repository = env.GITHUB_REPOSITORY || (env.VERCEL_GIT_PROVIDER === "github" && env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}` : void 0) || githubRepository(env.REPOSITORY_URL) || githubRepository(await git(root, [
647
+ "remote",
648
+ "get-url",
649
+ "origin"
650
+ ]));
651
+ const pullRequest = pullRequestOf(env);
652
+ const extra = {
653
+ ...repository ? { repository } : {},
654
+ ...pullRequest ? { pullRequest } : {}
655
+ };
656
+ for (const [commitName, branchName] of buildVariables) {
657
+ const commit = env[commitName];
658
+ if (!commit) continue;
659
+ const branch = env[branchName] || (commitName === "GITHUB_SHA" ? env.GITHUB_REF_NAME : void 0);
660
+ return {
661
+ commit,
662
+ ...branch ? { branch } : {},
663
+ ...extra
664
+ };
665
+ }
666
+ const [commit, branch] = await Promise.all([git(root, ["rev-parse", "HEAD"]), git(root, [
667
+ "rev-parse",
668
+ "--abbrev-ref",
669
+ "HEAD"
670
+ ])]);
671
+ return {
672
+ ...commit ? { commit } : {},
673
+ ...branch && branch !== "HEAD" ? { branch } : {},
674
+ ...extra
675
+ };
676
+ }
677
+ const skippedDirectories = /* @__PURE__ */ new Set([
678
+ "node_modules",
679
+ "dist",
680
+ "coverage",
681
+ "public"
682
+ ]);
683
+ /**
684
+ * The names that a production build may give the component of a `.vue` file: its file name, which `<script setup>`
685
+ * uses; under `pages/`, the Nuxt route name, such as `blog-id` for `pages/blog/[id].vue`.
686
+ * Nuxt component names come from its resolved registry rather than a path heuristic.
687
+ */
688
+ function componentNames(file) {
689
+ const names = /* @__PURE__ */ new Set([basename(file, ".vue")]);
690
+ const parts = file.replace(/\.vue$/, "").split("/");
691
+ const pages = parts.lastIndexOf("pages");
692
+ if (pages !== -1) {
693
+ const route = parts.slice(pages + 1).filter((part) => part !== "index" && !/^\(.*\)$/.test(part)).map((part) => part.replace(/[[\].]/g, "")).join("-");
694
+ names.add(route || "index");
695
+ }
696
+ return [...names];
697
+ }
698
+ /**
699
+ * The Vue files of a project by component name, relative to the project root. `<script setup>` components carry the
700
+ * name of their file in production builds, so the name finds the file. It skips dot directories and build output.
701
+ */
702
+ async function readCommentsComponents(root, limit = 5e3, resolvedComponents = []) {
703
+ const components = Object.create(null);
704
+ let count = 0;
705
+ async function walk(directory, depth) {
706
+ if (depth > 12 || count >= limit) return;
707
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
708
+ for (const entry of entries) {
709
+ if (entry.name.startsWith(".") || skippedDirectories.has(entry.name)) continue;
710
+ const path = join(directory, entry.name);
711
+ if (entry.isDirectory()) await walk(path, depth + 1);
712
+ else if (entry.isFile() && entry.name.endsWith(".vue") && count < limit) {
713
+ count++;
714
+ const file = relative(root, path).split(sep).join("/");
715
+ for (const name of componentNames(file)) {
716
+ const files = components[name] ??= [];
717
+ if (!files.includes(file)) files.push(file);
718
+ }
719
+ }
720
+ }
721
+ }
722
+ await walk(root, 0);
723
+ const resolvedNames = Object.create(null);
724
+ for (const component of resolvedComponents) {
725
+ const file = relative(root, component.filePath).split(sep).join("/");
726
+ if (!file.endsWith(".vue") || file.split("/").some((part) => part !== ".." && (part.startsWith(".") || skippedDirectories.has(part)))) continue;
727
+ const files = resolvedNames[component.pascalName] ??= [];
728
+ if (!files.includes(file)) files.push(file);
729
+ }
730
+ Object.assign(components, resolvedNames);
731
+ return components;
732
+ }
733
+ const version = "3";
734
+ /** Generated session reader: the Console user of a request, else the ViteHub Auth user. */
735
+ function sessionLines(options, imports) {
736
+ if (options.console) return {
737
+ imports: [`import { consoleRealtimeAccess } from ${JSON.stringify(options.console.module)}`, `import { commentsConsoleSession } from ${JSON.stringify(imports.runtime)}`],
738
+ option: "consoleSession",
739
+ value: `commentsConsoleSession(consoleRealtimeAccess(${JSON.stringify(commentsConsoleSection.id)}))`
740
+ };
741
+ return options.auth ? {
742
+ imports: [`import { commentsAuthSession } from ${JSON.stringify(imports.auth)}`],
743
+ option: "session",
744
+ value: "commentsAuthSession"
745
+ } : {
746
+ imports: [],
747
+ option: "session",
748
+ value: "undefined"
749
+ };
750
+ }
751
+ /** The session reader of presence and MCP: the Console or Auth user, else the person signed in with GitHub. */
752
+ function sessionWithGitHubLines(options, imports, repository, base) {
753
+ if (options.auth || options.console) return sessionLines(options, imports);
754
+ const route = mountedCommentsRoute(base);
755
+ return {
756
+ imports: [`import { createCommentsGitHubLogin } from ${JSON.stringify(imports.runtime)}`, `const githubLogin = createCommentsGitHubLogin(${JSON.stringify({
757
+ ...repository ? { repository } : {},
758
+ ...route !== "/api/_vitehub/comments" ? { basePath: `${route}/auth` } : {}
759
+ })})`],
760
+ option: "session",
761
+ value: "githubLogin.user",
762
+ githubLogin: true
763
+ };
764
+ }
765
+ function renderCommentsHandler(input) {
766
+ const session = sessionLines(input.session, input.imports);
767
+ const route = mountedCommentsRoute(input.base);
768
+ const githubLogin = !input.session.auth && !input.session.console;
769
+ return [
770
+ `import { createCommentsHandler${githubLogin ? ", createCommentsGitHubLogin" : ""} } from ${JSON.stringify(input.imports.runtime)}`,
771
+ `import components from "./components.mjs"`,
772
+ `import { comments } from ${JSON.stringify(pathToFileURL(input.definition).href)}`,
773
+ ...session.imports,
774
+ ...input.content ? [`import * as contentModule from ${JSON.stringify(pathToFileURL(input.content).href)}`, `import { parseContentField } from ${JSON.stringify(input.imports.contentClient)}`] : [],
775
+ "",
776
+ "export default createCommentsHandler({",
777
+ " comments,",
778
+ ` ${session.option}: ${session.value},`,
779
+ ...githubLogin ? [` githubLogin: createCommentsGitHubLogin(${JSON.stringify({
780
+ ...input.build?.repository ? { repository: input.build.repository } : {},
781
+ ...route !== "/api/_vitehub/comments" ? { basePath: `${route}/auth` } : {}
782
+ })}),`] : [],
783
+ ...input.content ? [" content: contentModule.content ? { runtime: contentModule.content, parseField: parseContentField } : undefined,"] : [],
784
+ ` realtime: ${input.realtime},`,
785
+ ` build: ${JSON.stringify(input.build ?? {})},`,
786
+ " components,",
787
+ "})",
788
+ ""
789
+ ].join("\n");
790
+ }
791
+ function renderCommentsPlugin(input) {
792
+ const session = sessionWithGitHubLines(input.session ?? {}, input.imports, input.build?.repository, input.base);
793
+ if (input.standalone) {
794
+ const { where, fallback, node } = input.standalone;
795
+ const options = [
796
+ `name: "comments"`,
797
+ "setup: commentsTables",
798
+ ...fallback ? [`fallback: ${JSON.stringify(fallback)}`] : []
799
+ ];
800
+ return [
801
+ `import { defineCommentsPlugin } from ${JSON.stringify(input.imports.runtime)}`,
802
+ `import { connectDatabase } from ${JSON.stringify(node ? `${input.imports.connect}/node` : input.imports.connect)}`,
803
+ `import { commentsTables } from ${JSON.stringify(input.imports.database)}`,
804
+ `import { comments } from ${JSON.stringify(pathToFileURL(input.definition).href)}`,
805
+ ...session.imports,
806
+ "",
807
+ `const database = () => connectDatabase(${where === void 0 ? "undefined" : JSON.stringify(where)}, { ${options.join(", ")} })`,
808
+ "",
809
+ `export default defineCommentsPlugin({ comments, database, ${session.option}: ${session.value}, ${session.githubLogin ? "githubLogin, " : ""}development: ${input.development === true}, overlay: ${JSON.stringify(`${commentsRoute}/assets/overlay.js?v=${version}`)}, base: ${JSON.stringify(input.base ?? "")} })`,
810
+ ""
811
+ ].join("\n");
812
+ }
813
+ return [
814
+ `import { defineCommentsPlugin } from ${JSON.stringify(input.imports.runtime)}`,
815
+ `import { databases } from ${JSON.stringify(input.imports.databases)}`,
816
+ `import { comments } from ${JSON.stringify(pathToFileURL(input.definition).href)}`,
817
+ ...session.imports,
818
+ "",
819
+ "// The Database that `defineComments({ database })` names, else `default`, else the only one.",
820
+ "function database() {",
821
+ ` const name = ${JSON.stringify(input.database ?? null)}`,
822
+ " if (name) return databases[name]?.db",
823
+ " // Without a default Database, `databases.default` is a placeholder that throws when read.",
824
+ " try {",
825
+ " if (databases.default.db.select) return databases.default.db",
826
+ " }",
827
+ " catch {}",
828
+ " const names = Object.keys(databases).filter(key => key !== \"default\")",
829
+ " return names.length === 1 ? databases[names[0]].db : undefined",
830
+ "}",
831
+ "",
832
+ `export default defineCommentsPlugin({ comments, database, ${session.option}: ${session.value}, ${session.githubLogin ? "githubLogin, " : ""}development: ${input.development === true}, overlay: ${JSON.stringify(`${commentsRoute}/assets/overlay.js?v=${version}`)}, base: ${JSON.stringify(input.base ?? "")} })`,
833
+ ""
834
+ ].join("\n");
835
+ }
836
+ /** `server/comments.ts` for an app without one: Comments with its defaults. */
837
+ async function writeDefaultDefinition(directory, imports) {
838
+ const file = join(directory, "definition.mjs");
839
+ const index = imports.runtime.replace(/\/runtime$/, "");
840
+ await writeFile(file, [
841
+ `import { defineComments } from ${JSON.stringify(index)}`,
842
+ "",
843
+ "// Add `server/comments.ts` to choose who may comment, notify people, or post to pull requests.",
844
+ "export const comments = defineComments()",
845
+ ""
846
+ ].join("\n"));
847
+ return file;
848
+ }
849
+ /**
850
+ * The storage of `comments()`. A build connects to the `database` option, else to what it finds at runtime. The
851
+ * development server uses `.vitehub/data/comments.sqlite`, unless the option is a file, or a variable that is set. In
852
+ * workerd, which cannot open files, it uses the option, else a D1 binding that Miniflare keeps in `.wrangler/state`.
853
+ */
854
+ async function standaloneDatabase(projectRoot, options, command, workerd) {
855
+ const where = options.database || void 0;
856
+ const location = parseDatabaseLocation(where, "comments", { node: command !== "serve" || !workerd });
857
+ if (where && /[?&]authToken=/.test(where)) console.warn("[vitehub] The token in `comments({ database })` ends up in the build. Use `env:` with a variable instead.");
858
+ if (command !== "serve") return {
859
+ ...where ? { where } : {},
860
+ node: location.kind === "file"
861
+ };
862
+ if (location.kind === "file") return {
863
+ where,
864
+ node: true
865
+ };
866
+ if (workerd) return {
867
+ where: where ?? "d1:COMMENTS",
868
+ ...location.kind === "env" ? { fallback: "d1:COMMENTS" } : {},
869
+ node: false
870
+ };
871
+ const data = resolve(projectRoot, ".vitehub/data");
872
+ await mkdir(data, { recursive: true });
873
+ await writeFile(join(data, ".gitignore"), "*\n", { flag: "wx" }).catch(() => {});
874
+ const file = `file:${join(data, "comments.sqlite")}`;
875
+ return where?.startsWith("env:") ? {
876
+ where,
877
+ fallback: file,
878
+ node: true
879
+ } : {
880
+ where: file,
881
+ node: true
882
+ };
883
+ }
884
+ /**
885
+ * Adds the D1 binding of `database: "d1:NAME"` to the Wrangler config of the build, unless the app's Wrangler file has
886
+ * it. Without an id, `wrangler deploy` creates the database.
887
+ */
888
+ async function addD1Binding(projectRoot, nitro, where) {
889
+ if (!where?.startsWith("d1:")) return;
890
+ const binding = where.slice(3);
891
+ for (const file of [
892
+ "wrangler.jsonc",
893
+ "wrangler.json",
894
+ "wrangler.toml"
895
+ ]) {
896
+ const source = await readFile(join(projectRoot, file), "utf8").catch(() => "");
897
+ if (!source) continue;
898
+ const config = file.endsWith(".toml") ? parseTOML(source) : parseJSONC(source, { allowTrailingComma: true });
899
+ if (config === null || typeof config !== "object") continue;
900
+ const entries = Reflect.get(config, "d1_databases");
901
+ if (Array.isArray(entries) && entries.some((entry) => entry !== null && typeof entry === "object" && Reflect.get(entry, "binding") === binding)) return;
902
+ }
903
+ const cloudflare = nitro.cloudflare ?? {};
904
+ const wrangler = cloudflare.wrangler ?? {};
905
+ const bindings = wrangler.d1_databases ?? [];
906
+ if (bindings.some((entry) => entry.binding === binding)) return;
907
+ nitro.cloudflare = {
908
+ ...cloudflare,
909
+ wrangler: {
910
+ ...wrangler,
911
+ d1_databases: [...bindings, {
912
+ binding,
913
+ database_name: "comments"
914
+ }]
915
+ }
916
+ };
917
+ }
918
+ /** Whether `vite-hub` is in the app, so it runs Comments and `comments()` steps aside. */
919
+ function hasViteHubComments(config) {
920
+ const find = (value) => Array.isArray(value) ? value.some(find) : value !== null && typeof value === "object" && Reflect.get(value, "name") === "@vite-hub/comments/vite";
921
+ return find(config.plugins);
922
+ }
923
+ /**
924
+ * Comments for any Vite app, without `vite-hub`: the comment overlay on every page with `?vitehub`, threads in a
925
+ * SQLite file, and Sign in with GitHub. It adds Nitro, the server, unless the app has it. With `vite-hub`, it does
926
+ * nothing, because `vitehub()` runs Comments.
927
+ */
928
+ function comments(options = {}) {
929
+ const plugin = hubComments$2({ standalone: options });
930
+ plugin.apply = (config) => !hasViteHubComments(config);
931
+ return [
932
+ plugin,
933
+ {
934
+ ...nitroWorkerdDependencies(),
935
+ apply: (config) => !hasViteHubComments(config)
936
+ },
937
+ ...includedNitro({ unless: hasViteHubComments })
938
+ ];
939
+ }
940
+ /**
941
+ * Comments build integration. When the app has `server/comments.ts`, it serves the Comments API at
942
+ * `/api/_vitehub/comments/**`, installs the runtime with its Database, adds the tables to that Database, serves the
943
+ * overlay script, and adds it to pages in comment mode. Apps without the file are unaffected.
944
+ */
945
+ function hubComments$2(options = {}) {
946
+ const imports = {
947
+ ...defaultImports$1,
948
+ ...options.imports
949
+ };
950
+ let projectRoot;
951
+ let serverDirs;
952
+ let realtime = false;
953
+ let resolvedComponents = [];
954
+ let componentsFile;
955
+ let route = commentsRoute;
956
+ let appBase = "";
957
+ let development = false;
958
+ const discover = () => findCommentsEntry$2(projectRoot ?? process.cwd(), serverDirs);
959
+ const enabled = () => Boolean(options.standalone) || Boolean(discover());
960
+ async function writeComponents() {
961
+ if (!projectRoot || !componentsFile) return;
962
+ const components = await readCommentsComponents(projectRoot, 5e3, resolvedComponents);
963
+ await writeFile(componentsFile, `export default JSON.parse(${JSON.stringify(JSON.stringify(components))})\n`);
964
+ }
965
+ const integration = {
966
+ name: options.standalone ? "@vite-hub/comments" : "@vite-hub/comments/vite",
967
+ nitro: options.standalone ? { async setup(nitro) {
968
+ if (!projectRoot || !options.standalone) return;
969
+ const runner = nitro.options.devServer.runner || process.env.NITRO_DEV_RUNNER || "node-worker";
970
+ const standalone = await standaloneDatabase(projectRoot, options.standalone, nitro.options.dev ? "serve" : "build", runner === "miniflare");
971
+ if (!nitro.options.dev) {
972
+ parseDatabaseLocation(standalone.where, "comments", { node: nitro.options.node });
973
+ standalone.node = nitro.options.node;
974
+ }
975
+ const directory = resolve(projectRoot, ".vitehub/nitro/comments");
976
+ const definition = discover() ?? join(directory, "definition.mjs");
977
+ const build = await readCommentsBuild(projectRoot);
978
+ await writeFile(join(directory, "plugin.mjs"), renderCommentsPlugin({
979
+ definition,
980
+ session: options,
981
+ imports,
982
+ build,
983
+ base: appBase,
984
+ standalone,
985
+ development
986
+ }));
987
+ await addD1Binding(projectRoot, nitro.options, standalone.where);
988
+ await addD1Binding(projectRoot, nitro.options, standalone.fallback);
989
+ } } : void 0,
990
+ api: {
991
+ async setComponents(components) {
992
+ resolvedComponents = components;
993
+ await writeComponents();
994
+ },
995
+ async contributeRealtime(context) {
996
+ const definition = findCommentsEntry$2(context.projectRoot, context.serverDirs);
997
+ if (!definition) return;
998
+ realtime = true;
999
+ const file = join(context.directory, "comments.mjs");
1000
+ const { repository } = await readCommentsBuild(context.projectRoot);
1001
+ const session = sessionWithGitHubLines(options, imports, repository, appBase);
1002
+ await mkdir(context.directory, { recursive: true });
1003
+ await writeFile(file, [
1004
+ `import { commentsRealtime } from ${JSON.stringify(imports.realtime)}`,
1005
+ `import { comments } from ${JSON.stringify(pathToFileURL(definition).href)}`,
1006
+ ...session.imports,
1007
+ "",
1008
+ `export default commentsRealtime(comments, { ${session.option}: ${session.value} })`,
1009
+ ""
1010
+ ].join("\n"));
1011
+ return { definitions: [{
1012
+ handler: file,
1013
+ name: commentsRealtimeDefinition
1014
+ }] };
1015
+ }
1016
+ },
1017
+ vitehub: {
1018
+ inspect: () => ({ definitions: [{
1019
+ kind: "comments",
1020
+ label: "Comments",
1021
+ list: () => {
1022
+ const definition = discover();
1023
+ if (!definition) return [];
1024
+ return [{
1025
+ fields: [
1026
+ {
1027
+ label: "Route",
1028
+ value: `${route}/**`
1029
+ },
1030
+ {
1031
+ label: "Presence",
1032
+ value: realtime ? `Realtime Definition "${commentsRealtimeDefinition}"` : "off: the host has no Realtime authority"
1033
+ },
1034
+ {
1035
+ label: "Page tool",
1036
+ value: `?${viteHubPageToolsQuery} or the ${viteHubPageToolsCookie} cookie, for people that authorize allows to read`
1037
+ }
1038
+ ],
1039
+ file: relativeDefinitionFile(projectRoot ?? process.cwd(), definition),
1040
+ name: "comments",
1041
+ source: "server-comments"
1042
+ }];
1043
+ }
1044
+ }] }),
1045
+ async databases(context) {
1046
+ if (options.standalone) return [];
1047
+ const definition = findCommentsEntry$2(projectRoot ?? context.projectRoot ?? context.rootDir ?? context.root ?? process.cwd(), serverDirs ?? context.serverDirs?.slice());
1048
+ if (!definition) return [];
1049
+ const database = await readCommentsDatabase(definition);
1050
+ return [{
1051
+ ...database ? { database } : {},
1052
+ definition: {
1053
+ export: "commentsSchema",
1054
+ module: imports.database
1055
+ },
1056
+ dialect: "sqlite",
1057
+ name: "comments",
1058
+ reason: "Stores the comment threads of `server/comments.ts`."
1059
+ }];
1060
+ }
1061
+ },
1062
+ enforce: "pre",
1063
+ config: { async handler(config, env) {
1064
+ development = env.command === "serve" && !env.isPreview;
1065
+ const viteConfig = config;
1066
+ const { base, mount } = viteHubPageToolsBase(config);
1067
+ appBase = base;
1068
+ route = mountedCommentsRoute(base);
1069
+ projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(resolve(config.root || process.cwd()));
1070
+ serverDirs = viteConfig[VITEHUB_SERVER_DIRS]?.slice();
1071
+ const directory = resolve(projectRoot, ".vitehub/nitro/comments");
1072
+ if (!enabled()) {
1073
+ componentsFile = void 0;
1074
+ await rm(directory, {
1075
+ force: true,
1076
+ recursive: true
1077
+ });
1078
+ return;
1079
+ }
1080
+ await mkdir(directory, { recursive: true });
1081
+ const definition = discover() ?? await writeDefaultDefinition(directory, imports);
1082
+ const handler = join(directory, "handler.mjs");
1083
+ const plugin = join(directory, "plugin.mjs");
1084
+ const pageSession = join(directory, "page-session.mjs");
1085
+ componentsFile = join(directory, "components.mjs");
1086
+ const build = await readCommentsBuild(projectRoot);
1087
+ const pluginInput = {
1088
+ definition,
1089
+ database: await readCommentsDatabase(definition),
1090
+ session: options,
1091
+ imports,
1092
+ build,
1093
+ base,
1094
+ development
1095
+ };
1096
+ await Promise.all([
1097
+ writeFile(handler, renderCommentsHandler({
1098
+ definition,
1099
+ content: findContentEntry(projectRoot, serverDirs),
1100
+ session: options,
1101
+ realtime,
1102
+ imports,
1103
+ build,
1104
+ base
1105
+ })),
1106
+ writeComponents(),
1107
+ options.standalone ? void 0 : writeFile(plugin, renderCommentsPlugin(pluginInput)),
1108
+ writeFile(pageSession, `export { viteHubPageSessionHandler as default } from ${JSON.stringify(imports.runtime)}\n`)
1109
+ ]);
1110
+ const kit = createNitroServerKit(Reflect.get(config, "nitro"));
1111
+ kit.addHandler({
1112
+ handler,
1113
+ route: `${mount}${commentsRoute}/**`
1114
+ });
1115
+ kit.addPlugin(plugin);
1116
+ addViteHubPageToolRoutes(kit, {
1117
+ handler: pageSession,
1118
+ loader: builtDirectory("page"),
1119
+ mount
1120
+ });
1121
+ const nitro = kit.config;
1122
+ if (integration.nitro) {
1123
+ const modules = Array.isArray(nitro.modules) ? [...nitro.modules] : [];
1124
+ if (!modules.includes(configNitroModule)) modules.push(configNitroModule);
1125
+ nitro.modules = modules;
1126
+ }
1127
+ const assets = Array.isArray(nitro.publicAssets) ? [...nitro.publicAssets] : [];
1128
+ const overlay = commentsOverlayDirectory();
1129
+ if (!assets.some((asset) => Object(asset) === asset && Reflect.get(Object(asset), "dir") === overlay)) assets.push({
1130
+ baseURL: `${mount}${commentsRoute}/assets`,
1131
+ dir: overlay,
1132
+ maxAge: 300
1133
+ });
1134
+ nitro.publicAssets = assets;
1135
+ Reflect.set(config, "nitro", nitro);
1136
+ } },
1137
+ transformIndexHtml(html) {
1138
+ return enabled() ? viteHubPageToolsIndexHtml(html, appBase) : void 0;
1139
+ }
1140
+ };
1141
+ const configNitroModule = { setup(nitro) {
1142
+ const setup = integration.nitro?.setup;
1143
+ if (!setup) return;
1144
+ if (!nitro.options.modules?.some((module) => typeof module === "object" && "setup" in module && module.setup === setup)) return setup(nitro);
1145
+ } };
1146
+ return integration;
1147
+ }
1148
+ //#endregion
1149
+ //#region ../internal/src/contributions.ts
1150
+ function isThenable(value) {
1151
+ return typeof value.then === "function";
1152
+ }
1153
+ async function flattenPlugins(value, plugins, seen) {
1154
+ if (Array.isArray(value)) {
1155
+ for (const item of value) await flattenPlugins(item, plugins, seen);
1156
+ return;
1157
+ }
1158
+ if (!isPlainObject(value) || seen.has(value)) return;
1159
+ seen.add(value);
1160
+ if (isThenable(value)) {
1161
+ await flattenPlugins(await value, plugins, seen);
1162
+ return;
1163
+ }
1164
+ plugins.push(value);
1165
+ }
1166
+ /**
1167
+ * Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
1168
+ * list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
1169
+ * filter this list, because `vitehub()` nests its plugins in an array.
1170
+ */
1171
+ async function flattenPluginOptions(plugins) {
1172
+ const flattened = [];
1173
+ await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
1174
+ return flattened;
1175
+ }
1176
+ //#endregion
1177
+ //#region src/overlay.ts
1178
+ /** Where the loader and overlay are served, below the app mount. */
1179
+ const overlayRoute = "/_vitehub/comments";
1180
+ /** The path the app is mounted at: `""` for the root, `"/portal"` below it. A relative or empty Vite base is the root. */
1181
+ function mountPath(base) {
1182
+ if (!base || base === "./") return "";
1183
+ let pathname = base;
1184
+ if (/^https?:\/\//.test(pathname)) try {
1185
+ pathname = new URL(pathname).pathname;
1186
+ } catch {
1187
+ return "";
1188
+ }
1189
+ if (!pathname.startsWith("/") || pathname.startsWith("//")) return "";
1190
+ return pathname.replace(/\/+$/, "");
1191
+ }
1192
+ /** The URL of the loader. Its query names the overlay file, says whether the app can edit pages, and carries the page filter and when to ask. */
1193
+ function loaderUrl(mount, assets, options = {}) {
1194
+ const filter = options.paths?.length || options.exclude?.length ? `&o=${encodeURIComponent(JSON.stringify({
1195
+ exclude: options.exclude ?? [],
1196
+ paths: options.paths ?? []
1197
+ }))}` : "";
1198
+ return `${mount}${overlayRoute}/${assets.loader}?f=${encodeURIComponent(assets.overlay)}${options.edit ? "&e=1" : ""}${options.session ? `&s=${options.session}` : ""}${filter}`;
1199
+ }
1200
+ /** A nonce is base64 or base64url. Anything else is not put in a tag. */
1201
+ const safeNonce = /^[\w+/=-]+$/;
1202
+ function loaderTag(url, nonce) {
1203
+ return `<script type="module"${nonce && safeNonce.test(nonce) ? ` nonce="${nonce}"` : ""} src="${url.replaceAll("&", "&amp;").replaceAll("\"", "&quot;")}"><\/script>`;
1204
+ }
1205
+ /** The nonce that a `Content-Security-Policy` allows for scripts, when it has one. */
1206
+ function scriptNonce(policy) {
1207
+ if (!policy) return void 0;
1208
+ const directives = policy.split(";").map((directive) => directive.trim().split(/\s+/));
1209
+ const nonce = (directives.find(([name]) => name?.toLowerCase() === "script-src-elem") ?? directives.find(([name]) => name?.toLowerCase() === "script-src") ?? directives.find(([name]) => name?.toLowerCase() === "default-src"))?.map((source) => /^'nonce-([^']+)'$/.exec(source)?.[1]).find(Boolean);
1210
+ return nonce && safeNonce.test(nonce) ? nonce : void 0;
1211
+ }
1212
+ /** Attribute values and their offsets in a complete tag, including unquoted values. Also serialized below. */
1213
+ function htmlAttributes(tag) {
1214
+ const start = /^<\/?[a-z][\w:-]*/i.exec(tag)?.[0].length ?? tag.length;
1215
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
1216
+ const attributes = [];
1217
+ const source = tag.slice(start, -1);
1218
+ let match;
1219
+ while (match = pattern.exec(source)) attributes.push({
1220
+ name: match[1].toLowerCase(),
1221
+ value: match[2] ?? match[3] ?? match[4] ?? "",
1222
+ start: start + match.index,
1223
+ end: start + pattern.lastIndex
1224
+ });
1225
+ return attributes;
1226
+ }
1227
+ /** Self-contained apart from htmlAttributes, so both can be serialized into the generated middleware. */
1228
+ function createHtmlScanner() {
1229
+ let raw = "";
1230
+ let comment = false;
1231
+ let cdata = false;
1232
+ let templates = 0;
1233
+ return (html, start = 0) => {
1234
+ let position = start;
1235
+ while (position < html.length) {
1236
+ if (comment) {
1237
+ const end = html.indexOf("-->", position);
1238
+ if (end === -1) return { scanned: Math.max(position, html.length - 2) };
1239
+ comment = false;
1240
+ position = end + 3;
1241
+ continue;
1242
+ }
1243
+ if (cdata) {
1244
+ const end = html.indexOf("]]>", position);
1245
+ if (end === -1) return { scanned: Math.max(position, html.length - 2) };
1246
+ cdata = false;
1247
+ position = end + 3;
1248
+ continue;
1249
+ }
1250
+ if (raw === "plaintext") return { scanned: html.length };
1251
+ if (raw) {
1252
+ const end = new RegExp(`</${raw}(?=[\\s/>])`, "i").exec(html.slice(position));
1253
+ if (!end) return { scanned: Math.max(position, html.length - raw.length - 4) };
1254
+ position += end.index;
1255
+ } else {
1256
+ const next = html.indexOf("<", position);
1257
+ if (next === -1) return { scanned: html.length };
1258
+ position = next;
1259
+ if (html.startsWith("<!--", position)) {
1260
+ comment = true;
1261
+ position += 4;
1262
+ continue;
1263
+ }
1264
+ if (html.startsWith("<![CDATA[", position)) {
1265
+ cdata = true;
1266
+ position += 9;
1267
+ continue;
1268
+ }
1269
+ }
1270
+ const rest = html.slice(position);
1271
+ const tag = /^<(?:[^"'<>]|"[^"]*"|'[^']*')*>/.exec(rest)?.[0];
1272
+ if (!tag) {
1273
+ if (/^<(?:\/?[a-z!/?]|\/?$)/i.test(rest)) return { scanned: position };
1274
+ position++;
1275
+ continue;
1276
+ }
1277
+ const element = /^<(\/?)([a-z][\w:-]*)(?=[\s/>])/i.exec(tag);
1278
+ const name = element?.[2]?.toLowerCase();
1279
+ if (raw) raw = "";
1280
+ else if (name === "template") templates = element?.[1] === "/" ? Math.max(0, templates - 1) : templates + 1;
1281
+ else if (!templates && element?.[1] === "/" && (name === "body" || name === "html")) return {
1282
+ close: position,
1283
+ scanned: position
1284
+ };
1285
+ else if (element?.[1] === "") {
1286
+ if (!templates && name === "script") {
1287
+ const src = htmlAttributes(tag).find((attribute) => attribute.name === "src")?.value;
1288
+ if (src && /\/_vitehub\/comments\/loader\.[\w-]+\.js(?:[?#]|$)/i.test(src)) return {
1289
+ loaded: {
1290
+ start: position,
1291
+ end: position + tag.length
1292
+ },
1293
+ scanned: position
1294
+ };
1295
+ }
1296
+ if (name && /^(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript|plaintext)$/.test(name)) raw = name;
1297
+ }
1298
+ position += tag.length;
1299
+ }
1300
+ return { scanned: position };
1301
+ };
1302
+ }
1303
+ /** Puts the tag before the first `</body>` or `</html>`. A fragment, or a page that has the loader, stays as it is. */
1304
+ function injectLoader(html, tag, found = createHtmlScanner()(html)) {
1305
+ const { close, loaded } = found;
1306
+ if (loaded) {
1307
+ const nonce = htmlAttributes(tag).find((attribute) => attribute.name === "nonce")?.value;
1308
+ if (!nonce || !safeNonce.test(nonce)) return html;
1309
+ const attributes = htmlAttributes(html.slice(loaded.start, loaded.end));
1310
+ const existing = attributes.find((attribute) => attribute.name === "nonce");
1311
+ const at = loaded.start + (existing ?? attributes.find((attribute) => attribute.name === "src")).start;
1312
+ const end = existing ? loaded.start + existing.end : at;
1313
+ return html.slice(0, at) + `nonce="${nonce}"${existing ? "" : " "}` + html.slice(end);
1314
+ }
1315
+ return close === void 0 ? html : `${html.slice(0, close)}${tag}${html.slice(close)}`;
1316
+ }
1317
+ /**
1318
+ * Source of the Nitro middleware that adds the loader to HTML responses: server-rendered pages and, when Nitro
1319
+ * prerenders them, the saved files. It is Nitro 3 middleware `(event, next)`. Where the host calls it without `next`,
1320
+ * such as Nitro 2 under Nuxt, it does nothing, and the `render:html` hook of the runtime plugin does the work.
1321
+ *
1322
+ * It rewrites only what is safe to rewrite: UTF-8 `text/html` that is not compressed, with a `</body>` or `</html>`.
1323
+ * A stream is piped through a transform that holds back a short tail, so a tag split across chunks is still found.
1324
+ */
1325
+ function renderOverlayMiddleware(url) {
1326
+ const loaderPath = new URL(url, "http://localhost").pathname;
1327
+ const consolePath = loaderPath.slice(0, loaderPath.lastIndexOf("/comments/"));
1328
+ return [
1329
+ "// Generated by @vite-hub/comments. Do not edit.",
1330
+ `const url = ${JSON.stringify(url)}`,
1331
+ `const consolePath = ${JSON.stringify(consolePath)}`,
1332
+ "const safeNonce = /^[\\w+/=-]+$/",
1333
+ `const htmlAttributes = ${htmlAttributes.toString()}`,
1334
+ `const createHtmlScanner = ${createHtmlScanner.toString()}`,
1335
+ `const inject = ${injectLoader.toString()}`,
1336
+ "// Keep a short tail plus any unfinished tag; the scanner carries raw-text and comment state across cuts.",
1337
+ "const tail = 4096",
1338
+ "",
1339
+ "function tagFor(nonce) {",
1340
+ " const attribute = nonce && safeNonce.test(nonce) ? ` nonce=\"${nonce}\"` : \"\"",
1341
+ " return `<script type=\"module\"${attribute} src=\"${url.replaceAll(\"&\", \"&amp;\").replaceAll('\"', \"&quot;\")}\"><\/script>`",
1342
+ "}",
1343
+ "",
1344
+ "function scriptNonce(policy) {",
1345
+ " if (!policy) return undefined",
1346
+ " const directives = policy.split(\";\").map(directive => directive.trim().split(/\\s+/))",
1347
+ " const scripts = directives.find(([name]) => name?.toLowerCase() === \"script-src-elem\")",
1348
+ " ?? directives.find(([name]) => name?.toLowerCase() === \"script-src\")",
1349
+ " ?? directives.find(([name]) => name?.toLowerCase() === \"default-src\")",
1350
+ " const nonce = scripts?.map(source => /^'nonce-([^']+)'$/.exec(source)?.[1]).find(Boolean)",
1351
+ " return nonce && safeNonce.test(nonce) ? nonce : undefined",
1352
+ "}",
1353
+ "",
1354
+ "// Only UTF-8 HTML that nothing has compressed or tagged with another charset.",
1355
+ "function rewritable(headers) {",
1356
+ " if (headers.has(\"content-range\")) return false",
1357
+ " const type = headers.get(\"content-type\") ?? \"\"",
1358
+ " if (!/^text\\/html\\s*(;|$)/i.test(type)) return false",
1359
+ " const charset = /;\\s*charset\\s*=\\s*\"?([^\";\\s]+)/i.exec(type)?.[1]",
1360
+ " if (charset && !/^utf-?8$/i.test(charset)) return false",
1361
+ " const encoding = headers.get(\"content-encoding\")",
1362
+ " return !encoding || encoding.toLowerCase() === \"identity\"",
1363
+ "}",
1364
+ "",
1365
+ "function injector(tag) {",
1366
+ " const decoder = new TextDecoder()",
1367
+ " const encoder = new TextEncoder()",
1368
+ " let pending = \"\"",
1369
+ " let done = false",
1370
+ " let scanned = 0",
1371
+ " const scan = createHtmlScanner()",
1372
+ " return new TransformStream({",
1373
+ " transform(chunk, controller) {",
1374
+ " pending += decoder.decode(chunk, { stream: true })",
1375
+ " const found = done ? { scanned: pending.length } : scan(pending, scanned)",
1376
+ " scanned = found.scanned",
1377
+ " if (done || found.loaded || found.close !== undefined) {",
1378
+ " done = true",
1379
+ " controller.enqueue(encoder.encode(inject(pending, tag, found)))",
1380
+ " pending = \"\"",
1381
+ " return",
1382
+ " }",
1383
+ " if (pending.length > tail) {",
1384
+ " let cut = Math.min(scanned, pending.length - tail)",
1385
+ " if (cut > 0 && /[\\uD800-\\uDBFF]/.test(pending[cut - 1])) cut--",
1386
+ " controller.enqueue(encoder.encode(pending.slice(0, cut)))",
1387
+ " pending = pending.slice(cut)",
1388
+ " scanned -= cut",
1389
+ " }",
1390
+ " },",
1391
+ " flush(controller) {",
1392
+ " pending += decoder.decode()",
1393
+ " if (pending) controller.enqueue(encoder.encode(pending))",
1394
+ " },",
1395
+ " })",
1396
+ "}",
1397
+ "",
1398
+ "export default async function injectCommentsLoader(event, next) {",
1399
+ " if (typeof next !== \"function\") return",
1400
+ " const result = await next()",
1401
+ " try {",
1402
+ " const path = new URL(event.req.url).pathname",
1403
+ " if (event.req.method !== \"GET\" || path === consolePath || path.startsWith(`${consolePath}/`)) return result",
1404
+ " if (result instanceof Response) {",
1405
+ " if (!result.body || result.status < 200 || result.status === 204 || result.status === 205 || result.status === 206 || result.status === 304 || !rewritable(result.headers)) return result",
1406
+ " const tag = tagFor(scriptNonce(result.headers.get(\"content-security-policy\")))",
1407
+ " const headers = new Headers(result.headers)",
1408
+ " // The body changes, so its length does too, and so does any validator of the old bytes.",
1409
+ " headers.delete(\"content-length\")",
1410
+ " headers.delete(\"etag\")",
1411
+ " return new Response(result.body.pipeThrough(injector(tag)), { headers, status: result.status, statusText: result.statusText })",
1412
+ " }",
1413
+ " if (typeof result === \"string\") {",
1414
+ " const headers = event.res.headers",
1415
+ " const type = headers.get(\"content-type\")",
1416
+ " // A string with no type is HTML only when it looks like a page. One with another type is never touched.",
1417
+ " if (headers.has(\"content-range\") || event.res.status === 206 || (type && !rewritable(headers))) return result",
1418
+ " const injected = inject(result, tagFor(scriptNonce(headers.get(\"content-security-policy\"))))",
1419
+ " if (injected !== result) {",
1420
+ " headers.delete(\"content-length\")",
1421
+ " headers.delete(\"etag\")",
1422
+ " }",
1423
+ " return injected",
1424
+ " }",
1425
+ " }",
1426
+ " catch {",
1427
+ " // A page without the overlay is better than a failed page.",
1428
+ " }",
1429
+ " return result",
1430
+ "}",
1431
+ ""
1432
+ ].join("\n");
1433
+ }
1434
+ //#endregion
1435
+ //#region src/operations-core/console.ts
1436
+ /**
1437
+ * Console section for the comment inbox. It lists the result of `comments.list`, called with the Console user, so
1438
+ * `authorize` applies to each thread. A page thread links to `<page>?comment=<n>`.
1439
+ */
1440
+ const commentsConsoleSection$1 = {
1441
+ description: "Read the comment threads of the site and jump to the page.",
1442
+ icon: "i-lucide-message-square",
1443
+ id: "comments",
1444
+ label: "Comments",
1445
+ view: {
1446
+ columns: [
1447
+ {
1448
+ key: "n",
1449
+ label: "#"
1450
+ },
1451
+ {
1452
+ key: "subject.id",
1453
+ label: "Subject"
1454
+ },
1455
+ {
1456
+ key: "status",
1457
+ label: "Status"
1458
+ },
1459
+ {
1460
+ key: "author.name|author.id",
1461
+ label: "Author"
1462
+ },
1463
+ {
1464
+ key: "messages.0.body",
1465
+ label: "Comment",
1466
+ format: "excerpt"
1467
+ },
1468
+ {
1469
+ key: "updatedAt",
1470
+ label: "Updated",
1471
+ format: "datetime"
1472
+ }
1473
+ ],
1474
+ filters: [
1475
+ {
1476
+ id: "all",
1477
+ input: {},
1478
+ label: "All"
1479
+ },
1480
+ {
1481
+ id: "open",
1482
+ input: { status: "open" },
1483
+ label: "Open"
1484
+ },
1485
+ {
1486
+ id: "resolved",
1487
+ input: { status: "resolved" },
1488
+ label: "Resolved"
1489
+ },
1490
+ {
1491
+ id: "mine",
1492
+ input: { mine: true },
1493
+ label: "Mine"
1494
+ },
1495
+ {
1496
+ id: "mentions",
1497
+ input: { mentions: true },
1498
+ label: "Mentions"
1499
+ }
1500
+ ],
1501
+ kind: "operation-view",
1502
+ link: {
1503
+ label: "Open page",
1504
+ template: "{subject.id:path}?comment={n}",
1505
+ when: {
1506
+ equals: "page",
1507
+ path: "subject.kind"
1508
+ }
1509
+ },
1510
+ notice: "The list comes from the comments.list operation with your sign-in, so it shows only the threads that authorize lets you read. Without an authorize policy nobody can read comments: add one to defineComments(). `vitehub comments list` lists the same threads.",
1511
+ operation: "comments.list",
1512
+ pagination: {
1513
+ limit: 200,
1514
+ cursor: {
1515
+ id: "id",
1516
+ updatedAt: "updatedAt"
1517
+ }
1518
+ }
1519
+ }
1520
+ };
1521
+ //#endregion
1522
+ //#region src/operations-core/vite.ts
1523
+ const COMMENTS_VITE_PLUGIN_NAME = "@vite-hub/comments/vite";
1524
+ /** Generated Nitro plugin that installs the comments runtime, relative to the project root. */
1525
+ const commentsNitroPluginPath = ".vitehub/nitro/comments/plugin.mjs";
1526
+ /** Generated Nitro middleware that adds the overlay loader to HTML responses, relative to the project root. */
1527
+ const commentsOverlayMiddlewarePath = ".vitehub/comments/inject-overlay.mjs";
1528
+ /** Generated Database Definition that comments add when the app has none, relative to the project root. */
1529
+ const commentsDatabaseModulePath = ".vitehub/comments/database.ts";
1530
+ const commentsAndContent = /* @__PURE__ */ new Set(["@vite-hub/comments/vite", "@vite-hub/content/vite"]);
1531
+ function displayPath(file, root) {
1532
+ return file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file;
1533
+ }
1534
+ /** The `default` Database that comments add when the app has no Database Definition. */
1535
+ function renderCommentsDatabaseModule(imports, dialect = "sqlite") {
1536
+ return [
1537
+ "// Generated by @vite-hub/comments for server/comments.ts. Do not edit.",
1538
+ "// The app has no Database Definition, so comments add the `default` Database. Its migrations live in",
1539
+ "// server/databases/migrations. Add server/databases/config.ts to define the Database yourself.",
1540
+ `import { defineDatabase } from ${JSON.stringify(imports.databaseDefinition)}`,
1541
+ "",
1542
+ `export default defineDatabase({ dialect: ${JSON.stringify(dialect)}, schema: {} })`,
1543
+ ""
1544
+ ].join("\n");
1545
+ }
1546
+ const defaultImports = {
1547
+ auth: "@vite-hub/auth/server",
1548
+ database: "@vite-hub/database/drizzle",
1549
+ databaseDefinition: "@vite-hub/database",
1550
+ databaseSchema: "@vite-hub/comments/database",
1551
+ operations: "@vite-hub/comments/operations",
1552
+ runtime: "@vite-hub/comments/server"
1553
+ };
1554
+ function candidates(projectRoot, serverDirs) {
1555
+ return (serverDirs === void 0 ? [resolve(projectRoot, "server")] : serverDirs.map((directory) => resolve(projectRoot, directory))).flatMap((directory) => [
1556
+ "comments.ts",
1557
+ "comments.mts",
1558
+ "comments.js",
1559
+ "comments.mjs"
1560
+ ].map((name) => join(directory, name)));
1561
+ }
1562
+ /** The `server/comments.{ts,js}` file of the project, or undefined. */
1563
+ function findCommentsEntry$1(options) {
1564
+ return candidates(options.projectRoot, options.serverDirs).find((file) => existsSync(file));
1565
+ }
1566
+ /** Whether the project has a `server/comments.ts`. `vitehub()` reads it while Vite filters plugins. */
1567
+ function usesComments(options) {
1568
+ return findCommentsEntry$1(options) !== void 0;
1569
+ }
1570
+ function writeIfChangedSync(file, contents) {
1571
+ try {
1572
+ if (readFileSync(file, "utf8") === contents) return;
1573
+ } catch {}
1574
+ mkdirSync(dirname(file), { recursive: true });
1575
+ writeFileSync(file, contents, "utf8");
1576
+ }
1577
+ async function writeIfChanged(file, contents) {
1578
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
1579
+ await mkdir(dirname(file), { recursive: true });
1580
+ await writeFile(file, contents, "utf8");
1581
+ }
1582
+ /** The Nitro plugin that installs the comments runtime in each server process. */
1583
+ function renderCommentsNitroPlugin(options) {
1584
+ const name = options.database === void 0 ? "undefined" : JSON.stringify(options.database);
1585
+ return [
1586
+ `import { databases } from ${JSON.stringify(options.imports.database)}`,
1587
+ `import { createAuthUsers, createCommentsStore, installComments, validateCommentsDefinition } from ${JSON.stringify(options.imports.runtime)}`,
1588
+ ...options.auth ? [`import { getAuth } from ${JSON.stringify(options.imports.auth)}`] : [],
1589
+ `import * as app from ${JSON.stringify(pathToFileURL(options.entry).href)}`,
1590
+ "",
1591
+ `const definition = validateCommentsDefinition(app.default, ${JSON.stringify(options.entry)})`,
1592
+ `const databaseName = ${name}`,
1593
+ "",
1594
+ "function entry() {",
1595
+ " const list = Object.values(databases)",
1596
+ " const found = databaseName === undefined ? databases.default ?? (list.length === 1 ? list[0] : undefined) : databases[databaseName]",
1597
+ " if (!found?.db) throw new Error(\"[vitehub] Comments found no Database. Define one, or set hubComments({ database }).\")",
1598
+ " return found",
1599
+ "}",
1600
+ "",
1601
+ ...options.overlayUrl === void 0 ? [] : [
1602
+ `const overlayUrl = ${JSON.stringify(options.overlayUrl)}`,
1603
+ "const safeNonce = /^[\\w+/=-]+$/",
1604
+ "const loaderScript = /<script\\b[^>]*?\\ssrc\\s*=\\s*[\"'][^\"']*\\/_vitehub\\/comments\\/loader\\.[\\w-]+\\.js[^\"']*[\"']/i",
1605
+ "",
1606
+ "function overlayTag(nonce) {",
1607
+ " const attribute = nonce && safeNonce.test(nonce) ? ` nonce=\"${nonce}\"` : \"\"",
1608
+ " return `<script type=\"module\"${attribute} src=\"${overlayUrl.replaceAll(\"&\", \"&amp;\").replaceAll('\"', \"&quot;\")}\"><\/script>`",
1609
+ "}",
1610
+ "",
1611
+ "function scriptNonce(policy) {",
1612
+ " const directives = String(policy ?? \"\").split(\";\").map(directive => directive.trim().split(/\\s+/))",
1613
+ " const scripts = directives.find(([name]) => name?.toLowerCase() === \"script-src-elem\")",
1614
+ " ?? directives.find(([name]) => name?.toLowerCase() === \"script-src\")",
1615
+ " ?? directives.find(([name]) => name?.toLowerCase() === \"default-src\")",
1616
+ " return scripts?.map(source => /^'nonce-([^']+)'$/.exec(source)?.[1]).find(Boolean)",
1617
+ "}",
1618
+ "",
1619
+ "// Nitro 2, under Nuxt, renders pages through a hook. Nitro 3 has the generated middleware instead.",
1620
+ "function addOverlay(nitroApp) {",
1621
+ " nitroApp?.hooks?.hook?.(\"render:html\", (html, context) => {",
1622
+ " if (!html?.bodyAppend || html.bodyAppend.some(part => loaderScript.test(String(part)))) return",
1623
+ " const policy = context?.event?.node?.res?.getHeader?.(\"content-security-policy\")",
1624
+ " html.bodyAppend.push(overlayTag(scriptNonce(policy)))",
1625
+ " })",
1626
+ "}",
1627
+ ""
1628
+ ],
1629
+ `export default function viteHubComments(${options.overlayUrl === void 0 ? "" : "nitroApp"}) {`,
1630
+ ...options.overlayUrl === void 0 ? [] : [" addOverlay(nitroApp)"],
1631
+ " installComments(() => {",
1632
+ " const { db, schema } = entry()",
1633
+ " return {",
1634
+ " definition,",
1635
+ " store: createCommentsStore(db, { commentCounters: schema.commentCounters, commentMessages: schema.commentMessages, commentThreads: schema.commentThreads }),",
1636
+ ...options.auth ? [" users: createAuthUsers(() => getAuth()),"] : [],
1637
+ " }",
1638
+ " })",
1639
+ "}",
1640
+ ""
1641
+ ].join("\n");
1642
+ }
1643
+ /**
1644
+ * The path that the app is mounted at, under Nuxt. There Vite's `base` is the folder of its built files (`/_nuxt/` in
1645
+ * development). Prefer the host's app base, which stays available when later plugins replace the client define
1646
+ * with Vite's assets base. The define is a fallback for hosts without the shared app-base key.
1647
+ */
1648
+ function nuxtAppMount(config) {
1649
+ if (!config["__vitehubNitroConfigContext"]) return void 0;
1650
+ if (typeof config["__vitehubAppBaseURL"] === "string") return mountPath(config[VITEHUB_APP_BASE_URL]);
1651
+ const base = config.define?.__VITEHUB_APP_BASE_URL__;
1652
+ try {
1653
+ const value = typeof base === "string" ? JSON.parse(base) : base;
1654
+ return typeof value === "string" ? mountPath(value) : void 0;
1655
+ } catch {
1656
+ return;
1657
+ }
1658
+ }
1659
+ /**
1660
+ * Comments build integration. When the project has `server/comments.ts`, it contributes the comment tables to the
1661
+ * Database, the `comments.*` operations, and a Nitro plugin that installs the runtime. Apps without the file are
1662
+ * unaffected.
1663
+ */
1664
+ function hubComments$1(options = {}) {
1665
+ const imports = {
1666
+ ...defaultImports,
1667
+ ...options.imports
1668
+ };
1669
+ const postgres = options.dialect === "postgresql";
1670
+ let projectRoot;
1671
+ let serverDirs;
1672
+ const discover = () => findCommentsEntry$1({
1673
+ projectRoot: projectRoot ?? process.cwd(),
1674
+ serverDirs
1675
+ });
1676
+ let assets = options.overlay === false ? void 0 : options.overlayAssets;
1677
+ const overlayOptions = options.overlay || {};
1678
+ let mount = "";
1679
+ let edit = false;
1680
+ const overlayUrl = () => assets ? loaderUrl(mount, assets, {
1681
+ ...overlayOptions,
1682
+ edit
1683
+ }) : void 0;
1684
+ /** The runtime plugin and the middleware carry the loader URL, which depends on the mount. */
1685
+ const writeGenerated = (root, entry) => {
1686
+ const url = overlayUrl();
1687
+ const plugin = resolve(root, commentsNitroPluginPath);
1688
+ writeIfChangedSync(plugin, renderCommentsNitroPlugin({
1689
+ auth: options.auth === true,
1690
+ imports,
1691
+ entry,
1692
+ ...options.database === void 0 ? {} : { database: options.database },
1693
+ ...url === void 0 ? {} : { overlayUrl: url }
1694
+ }));
1695
+ if (!url) return { plugin };
1696
+ const middleware = resolve(root, commentsOverlayMiddlewarePath);
1697
+ writeIfChangedSync(middleware, renderOverlayMiddleware(url));
1698
+ return {
1699
+ middleware,
1700
+ plugin
1701
+ };
1702
+ };
1703
+ return {
1704
+ name: COMMENTS_VITE_PLUGIN_NAME,
1705
+ enforce: "post",
1706
+ config: {
1707
+ order: "pre",
1708
+ async handler(config, env) {
1709
+ assets = options.overlay === false || options.overlayDevOnly && env?.command !== "serve" ? void 0 : options.overlayAssets;
1710
+ const viteConfig = config;
1711
+ projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(viteConfig.root || process.cwd());
1712
+ serverDirs = viteConfig[VITEHUB_SERVER_DIRS]?.slice();
1713
+ const entry = discover();
1714
+ if (!entry) return;
1715
+ edit = options.overlayEdit?.({
1716
+ projectRoot,
1717
+ ...serverDirs ? { serverDirs } : {}
1718
+ }) ?? false;
1719
+ const nitroConfig = Reflect.get(config, "nitro");
1720
+ mount = nuxtAppMount(viteConfig) ?? (mountPath(viteConfig.base) || mountPath(typeof Reflect.get(Object(nitroConfig), "baseURL") === "string" ? String(Reflect.get(Object(nitroConfig), "baseURL")) : void 0));
1721
+ const { middleware, plugin } = writeGenerated(projectRoot, entry);
1722
+ const url = overlayUrl();
1723
+ const kit = createNitroServerKit(nitroConfig);
1724
+ kit.addPlugin(plugin);
1725
+ if (assets && url && middleware) {
1726
+ kit.addHandler({
1727
+ handler: middleware,
1728
+ middleware: true,
1729
+ route: "/**"
1730
+ });
1731
+ const served = {
1732
+ baseURL: `${mount}${overlayRoute}`,
1733
+ dir: assets.dir,
1734
+ fallthrough: false,
1735
+ maxAge: 31536e3
1736
+ };
1737
+ const existing = Reflect.get(kit.config, "publicAssets");
1738
+ Reflect.set(kit.config, "publicAssets", [...Array.isArray(existing) ? existing.filter((asset) => asset?.dir !== served.dir) : [], served]);
1739
+ }
1740
+ Reflect.set(config, "nitro", kit.config);
1741
+ }
1742
+ },
1743
+ transformIndexHtml: {
1744
+ order: "post",
1745
+ handler(html) {
1746
+ const url = discover() ? overlayUrl() : void 0;
1747
+ return url ? injectLoader(html, loaderTag(url)) : html;
1748
+ }
1749
+ },
1750
+ async configResolved(config) {
1751
+ const entry = discover();
1752
+ if (!entry) return;
1753
+ const resolvedMount = config["__vitehubNitroConfigContext"] ? mount : mountPath(config.base);
1754
+ if (resolvedMount !== mount) {
1755
+ mount = resolvedMount;
1756
+ writeGenerated(projectRoot ?? process.cwd(), entry);
1757
+ const served = Reflect.get(Object(Reflect.get(config, "nitro")), "publicAssets");
1758
+ if (assets && Array.isArray(served)) {
1759
+ for (const asset of served) if (asset?.dir === assets.dir) asset.baseURL = `${mount}${overlayRoute}`;
1760
+ }
1761
+ }
1762
+ if (!(config["__vitehubNitroConfigContext"] || config.plugins.some((plugin) => plugin.name === "@vite-hub/database/vite"))) throw commentsErrorDiagnostics.COMMENTS_B0001({ file: entry.slice((projectRoot ?? "").length + 1) || entry });
1763
+ const { runnerImport } = await import("vite");
1764
+ const { module: app } = await runnerImport(entry, {
1765
+ configFile: false,
1766
+ root: projectRoot,
1767
+ resolve: { alias: config.resolve?.alias },
1768
+ logLevel: "silent"
1769
+ });
1770
+ validateCommentsDefinition(app.default, displayPath(entry, projectRoot ?? ""));
1771
+ },
1772
+ vitehub: {
1773
+ async databases(context) {
1774
+ const entry = discover();
1775
+ if (!entry) return [];
1776
+ const root = projectRoot ?? context.projectRoot;
1777
+ const tables = {
1778
+ definition: {
1779
+ export: postgres ? "commentsPostgresSchema" : "commentsOperationsSchema",
1780
+ module: postgres ? `${imports.databaseSchema}/postgres` : imports.databaseSchema
1781
+ },
1782
+ name: "comments",
1783
+ reason: "Stores the comment threads and messages of server/comments.ts.",
1784
+ ...options.database === void 0 ? {} : { database: options.database },
1785
+ ...postgres ? { dialect: "postgresql" } : {}
1786
+ };
1787
+ if (options.database !== void 0) return [tables];
1788
+ const others = (await flattenPluginOptions(context.plugins)).filter((plugin) => !commentsAndContent.has(String(Reflect.get(plugin, "name"))));
1789
+ const { collectDatabaseContributions } = await import("@vite-hub/database/vite");
1790
+ const { discoverDatabaseDefinitions } = await import("@vite-hub/database/config");
1791
+ const contributed = await collectDatabaseContributions(others, {
1792
+ ...context,
1793
+ plugins: others
1794
+ });
1795
+ const names = [...discoverDatabaseDefinitions(context.rootDir, { serverDirs: context.serverDirs?.map((directory) => resolve(root ?? context.rootDir, directory)) }).map((definition) => definition.name), ...contributed.definitions.map((definition) => definition.name)];
1796
+ const module = resolve(root ?? context.rootDir, commentsDatabaseModulePath);
1797
+ if (names.length) {
1798
+ await rm(module, { force: true });
1799
+ return [tables];
1800
+ }
1801
+ await writeIfChanged(module, renderCommentsDatabaseModule(imports, options.dialect));
1802
+ return [{
1803
+ definition: module,
1804
+ name: "default",
1805
+ reason: `${displayPath(entry, root ?? context.rootDir)} uses comments and the app has no Database Definition. Add server/databases/config.ts to define this Database yourself.`
1806
+ }, {
1807
+ ...tables,
1808
+ database: "default"
1809
+ }];
1810
+ },
1811
+ inspect: () => {
1812
+ const entry = discover();
1813
+ if (!entry) return void 0;
1814
+ return { definitions: [{
1815
+ kind: "comments",
1816
+ label: "Comments",
1817
+ list: () => [{
1818
+ fields: [{
1819
+ label: "Operations",
1820
+ value: "vitehub comments list"
1821
+ }],
1822
+ file: relativeDefinitionFile(projectRoot ?? process.cwd(), entry),
1823
+ name: "comments",
1824
+ source: "server-comments"
1825
+ }]
1826
+ }] };
1827
+ },
1828
+ operations: async () => discover() ? [{
1829
+ export: "commentsOperations",
1830
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations-NZG5dB8y.js").then((n) => n.r) : import("./operations-NZG5dB8y.js").then((n) => n.r))).commentsOperations,
1831
+ module: imports.operations
1832
+ }] : []
1833
+ }
1834
+ };
1835
+ }
1836
+ //#endregion
1837
+ //#region src/vite.ts
1838
+ function findCommentsEntry(options, serverDirs) {
1839
+ return typeof options === "string" ? findCommentsEntry$2(options, serverDirs) : findCommentsEntry$1(options);
1840
+ }
1841
+ /** A default export opts into Operations; the named `comments` export retains the live-site API. */
1842
+ function commentsEntryMode(file) {
1843
+ const module = scanModule(readFileSync(file, "utf8"), file);
1844
+ let named = false;
1845
+ for (const statement of module.program.body) {
1846
+ if (statement.type === "ExportDefaultDeclaration") {
1847
+ if (statement.declaration.type !== "TSInterfaceDeclaration") return "operations";
1848
+ continue;
1849
+ }
1850
+ if (statement.type !== "ExportNamedDeclaration" || statement.exportKind === "type") continue;
1851
+ const exports = statement.specifiers.filter((specifier) => specifier.exportKind !== "type");
1852
+ if (exports.some((specifier) => (specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === "default")) return "operations";
1853
+ if (statement.declaration?.type === "VariableDeclaration" && statement.declaration.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.name === "comments")) named = true;
1854
+ if (exports.some((specifier) => (specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === "comments")) named = true;
1855
+ }
1856
+ return named ? "live" : "operations";
1857
+ }
1858
+ /** Select one runtime and schema so the two entry forms never install competing thread tables. */
1859
+ function hubComments(options = {}) {
1860
+ const operations = hubComments$1({
1861
+ ...options,
1862
+ imports: options.operationsImports
1863
+ });
1864
+ const live = hubComments$2(options);
1865
+ let projectRoot;
1866
+ let serverDirs;
1867
+ function select(context) {
1868
+ const entry = findCommentsEntry({
1869
+ projectRoot: projectRoot ?? context?.projectRoot ?? context?.rootDir ?? process.cwd(),
1870
+ serverDirs: serverDirs ?? context?.serverDirs
1871
+ });
1872
+ return entry && commentsEntryMode(entry) === "live" ? live : operations;
1873
+ }
1874
+ return {
1875
+ name: operations.name,
1876
+ enforce: "pre",
1877
+ api: {
1878
+ setComponents: live.api.setComponents,
1879
+ async contributeRealtime(context) {
1880
+ const entry = findCommentsEntry({
1881
+ projectRoot: context.projectRoot,
1882
+ serverDirs: context.serverDirs
1883
+ });
1884
+ if (entry && commentsEntryMode(entry) === "live") return live.api.contributeRealtime(context);
1885
+ }
1886
+ },
1887
+ config: { async handler(config, environment) {
1888
+ const configuredRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
1889
+ projectRoot = typeof configuredRoot === "string" ? resolve(configuredRoot) : resolveViteHubProjectRoot(resolve(config.root ?? process.cwd()));
1890
+ serverDirs = Reflect.get(config, VITEHUB_SERVER_DIRS);
1891
+ const hook = select().config;
1892
+ return typeof hook === "function" ? hook.call(this, config, environment) : hook?.handler.call(this, config, environment);
1893
+ } },
1894
+ async configResolved(config) {
1895
+ const hook = select().configResolved;
1896
+ if (typeof hook === "function") await hook.call(this, config);
1897
+ else await hook?.handler.call(this, config);
1898
+ },
1899
+ transformIndexHtml: {
1900
+ order: "post",
1901
+ handler(html, context) {
1902
+ const hook = select().transformIndexHtml;
1903
+ return typeof hook === "function" ? hook.call(this, html, context) : hook?.handler.call(this, html, context);
1904
+ }
1905
+ },
1906
+ vitehub: {
1907
+ databases: (context) => select(context).vitehub.databases(context),
1908
+ inspect: () => {
1909
+ const inspect = select().vitehub.inspect;
1910
+ return typeof inspect === "function" ? inspect() : inspect;
1911
+ },
1912
+ operations: async () => {
1913
+ if (select() !== operations) return [];
1914
+ const contributions = operations.vitehub.operations;
1915
+ return typeof contributions === "function" ? contributions() : contributions;
1916
+ }
1917
+ }
1918
+ };
1919
+ }
1920
+ //#endregion
1921
+ export { COMMENTS_VITE_PLUGIN_NAME, comments, comments as default, commentsConsoleSection, commentsDatabaseModulePath, commentsEntryMode, commentsNitroPluginPath, commentsConsoleSection$1 as commentsOperationsConsoleSection, commentsOverlayDirectory, commentsOverlayMiddlewarePath, componentNames, findCommentsEntry, githubRepository, hubComments, injectLoader, loaderTag, loaderUrl, mountPath, mountedCommentsRoute, overlayRoute, readCommentsBuild, readCommentsComponents, readCommentsDatabase, renderCommentsDatabaseModule, renderCommentsHandler, renderCommentsNitroPlugin, renderCommentsPlugin, renderOverlayMiddleware, scriptNonce, usesComments };