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