@vite-hub/comments 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +79 -31
  2. package/dist/anchor.d.ts +7 -4
  3. package/dist/anchor.js +10 -5
  4. package/dist/client-diagnostics-CcFpkbAk.js +40 -0
  5. package/dist/client.d.ts +78 -3
  6. package/dist/client.js +198 -13
  7. package/dist/{console-BIz9t2cO.d.ts → console-h4KlhIik.d.ts} +97 -8
  8. package/dist/context-BqIsmYP1.js +61 -0
  9. package/dist/database/postgres.d.ts +738 -347
  10. package/dist/database/postgres.js +28 -7
  11. package/dist/{database-Cb2xjC1V.d.ts → database-CA1aHKN7.d.ts} +675 -276
  12. package/dist/database.d.ts +6 -98
  13. package/dist/database.js +2 -3
  14. package/dist/define-43mMR39K.js +89 -0
  15. package/dist/define-B3TF9zzn.d.ts +204 -0
  16. package/dist/errors-4gelGVmK.js +57 -0
  17. package/dist/errors-C6qptPoG.js +135 -0
  18. package/dist/errors-CyQyKAvy.d.ts +185 -0
  19. package/dist/fold-name-B7Zb3-MF.js +7 -0
  20. package/dist/{identity-3qtVC4rF.js → identity-CBOzgxSf.js} +7 -2
  21. package/dist/index-DNhy69Wt.d.ts +83 -0
  22. package/dist/index.d.ts +7 -7
  23. package/dist/index.js +196 -5
  24. package/dist/install-BcMPgPk_.js +1154 -0
  25. package/dist/install-W9ghhGoh.d.ts +36 -0
  26. package/dist/installed-B-PfERBU.js +30 -0
  27. package/dist/invariant-D8_xBqmZ.js +22 -0
  28. package/dist/migrate-B0k_0swk.d.ts +54 -0
  29. package/dist/migrate-BDQ8xqUs.js +289 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/{operations-0B0QTVWX.d.ts → operations-D4A1Fcgf.d.ts} +37 -15
  32. package/dist/operations-DMMIfYPW.js +1159 -0
  33. package/dist/operations-GLeOqgMt.d.ts +257 -0
  34. package/dist/operations.d.ts +3 -7
  35. package/dist/operations.js +3 -2
  36. package/dist/overlay/client-DmsSMOzi.js +4 -0
  37. package/dist/overlay/dist-BoHMOFax.js +14 -0
  38. package/dist/overlay/dist-yIZmvSaU.js +1 -0
  39. package/dist/overlay/overlay.js +183 -177
  40. package/dist/page/loader.js +138 -18
  41. package/dist/{page-BuroSMXO.js → page-B41ozN63.js} +8 -6
  42. package/dist/{page-BtXADR6d.d.ts → page-DtbMOEMd.d.ts} +6 -5
  43. package/dist/page-tools-shared-NHUjKI8E.js +117 -0
  44. package/dist/path--zk6PEMz.js +18 -0
  45. package/dist/plugin-PS8PMYus.js +74 -0
  46. package/dist/realtime.d.ts +6 -12
  47. package/dist/realtime.js +23 -24
  48. package/dist/rpc-HBcWtg0T.d.ts +17 -0
  49. package/dist/rpc-RKPAusHp.js +153 -0
  50. package/dist/rpc.d.ts +2 -29
  51. package/dist/rpc.js +2 -75
  52. package/dist/runtime/auth.d.ts +5 -3
  53. package/dist/runtime/auth.js +8 -5
  54. package/dist/runtime/console.d.ts +1 -1
  55. package/dist/runtime/console.js +26 -21
  56. package/dist/runtime/index.d.ts +108 -60
  57. package/dist/runtime/index.js +684 -236
  58. package/dist/{server-BomGg3Gb.js → server-D8k-0GXe.js} +16 -7
  59. package/dist/server.d.ts +14 -88
  60. package/dist/server.js +7 -326
  61. package/dist/service-CFVm23k7.d.ts +158 -0
  62. package/dist/service-GHhhyQj4.js +609 -0
  63. package/dist/session-DVx-1Tym.d.ts +14 -0
  64. package/dist/session-EkudzUmm.js +503 -0
  65. package/dist/testing.d.ts +1 -1
  66. package/dist/testing.js +14 -2
  67. package/dist/tokens-DSbwkVSy.js +58 -0
  68. package/dist/types-BIS0hCEl.d.ts +124 -0
  69. package/dist/types-CZujrMFd.d.ts +322 -0
  70. package/dist/vite.d.ts +91 -87
  71. package/dist/vite.js +535 -796
  72. package/package.json +24 -27
  73. package/dist/database-BSnVrwHn.js +0 -60
  74. package/dist/database-C-ktS9Do.js +0 -95
  75. package/dist/define-BzW2Ychn.d.ts +0 -46
  76. package/dist/define-Cbhl6QVJ.js +0 -32
  77. package/dist/errors-BAQYcy3_.d.ts +0 -89
  78. package/dist/errors-DeD6wTCl.js +0 -77
  79. package/dist/h3-v1-request-DDGXJ9E7.js +0 -166
  80. package/dist/index-DklG2Etf.d.ts +0 -111
  81. package/dist/operations-NZG5dB8y.js +0 -732
  82. package/dist/page-tools-shared-D-amu6sx.js +0 -53
  83. package/dist/plugin-QElKQYkA.js +0 -725
  84. package/dist/request-DVc3M_AG.js +0 -14
  85. package/dist/src-CRTwnaEG.js +0 -1362
  86. package/dist/types-Cj8K7Vx7.d.ts +0 -176
  87. package/dist/types-Un2dcJWD.d.ts +0 -288
package/dist/vite.js CHANGED
@@ -1,17 +1,18 @@
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";
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";
6
8
  import { tmpdir } from "node:os";
7
9
  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
10
  import { fileURLToPath, pathToFileURL } from "node:url";
12
- import { promisify } from "node:util";
11
+ import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
12
+ import { parseSync } from "vite";
13
13
  import { nitro } from "nitro/vite";
14
14
  import { parseDatabaseLocation } from "@vite-hub/database/config";
15
+ import { githubRepository, readForgeBuild } from "@vite-hub/forge/build/node";
15
16
  import { parseJSONC, parseTOML } from "confbox";
16
17
  //#region ../internal/src/build/vite.ts
17
18
  const projectRootDirectoryMarkers = [
@@ -33,9 +34,16 @@ const projectRootFileMarkers = [
33
34
  function isServerEnvironment(name, config) {
34
35
  return name === "ssr" || config.consumer === "server";
35
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
+ }
36
46
  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
47
  /**
40
48
  * Server directories that ViteHub scans for Definitions. The first entry is the application.
41
49
  * Later entries are Nuxt layers in Nuxt priority order.
@@ -95,6 +103,7 @@ function normalizeWindowsPath(input = "") {
95
103
  return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
96
104
  }
97
105
  const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
106
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
98
107
  const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
99
108
  function cwd() {
100
109
  if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
@@ -179,6 +188,11 @@ const relative$1 = function(from, to) {
179
188
  }
180
189
  return [..._from.map(() => ".."), ..._to].join("/");
181
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
+ };
182
196
  //#endregion
183
197
  //#region ../internal/src/inspect.ts
184
198
  function relativeDefinitionFile(projectRoot, file) {
@@ -188,10 +202,117 @@ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|pr
188
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");
189
203
  new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
190
204
  //#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";
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)}`;
195
316
  }
196
317
  //#endregion
197
318
  //#region ../internal/src/build/scan-module.ts
@@ -320,110 +441,32 @@ function staticValue(node) {
320
441
  default: return dynamic;
321
442
  }
322
443
  }
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
444
  //#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
- };
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);
400
452
  }
401
453
  /**
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/`.
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.
407
456
  */
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)}`;
457
+ function isIncludedNitroPlugin(plugin) {
458
+ return includedNitroPlugins.has(plugin);
413
459
  }
414
460
  //#endregion
415
461
  //#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);
462
+ function flattenPlugins(option) {
463
+ if (Array.isArray(option)) return option.flatMap(flattenPlugins);
421
464
  return option && typeof option === "object" && "name" in option ? [option] : [];
422
465
  }
423
466
  /** Whether the app added `nitro()` itself. Nitro plugins that a ViteHub package included do not count. */
424
467
  function findAppNitro(value) {
425
468
  if (Array.isArray(value)) return value.some(findAppNitro);
426
- return value !== null && typeof value === "object" && !includedNitroPlugins.has(value) && Reflect.get(value, "name") === "nitro:main";
469
+ return value !== null && typeof value === "object" && !isIncludedNitroPlugin(value) && Reflect.get(value, "name") === "nitro:main";
427
470
  }
428
471
  function applies(apply, config, env) {
429
472
  if (typeof apply === "function") return apply(config, env);
@@ -434,55 +477,25 @@ function applies(apply, config, env) {
434
477
  * itself, so an app that still adds it gets one Nitro. `unless` steps aside for another package that includes Nitro.
435
478
  */
436
479
  function includedNitro(options = {}) {
437
- const plugins = flattenPlugins$1(nitro());
480
+ const plugins = flattenPlugins(nitro());
438
481
  for (const plugin of plugins) {
439
482
  const apply = plugin.apply;
440
483
  plugin.apply = (config, env) => !findAppNitro(config.plugins) && !options.unless?.(config) && applies(apply, config, env);
441
- includedNitroPlugins.add(plugin);
484
+ markIncludedNitroPlugin(plugin);
442
485
  }
443
486
  return plugins;
444
487
  }
445
488
  //#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
489
  //#region ../internal/src/nitro-kit.ts
474
490
  function cloneArray(value) {
475
491
  return Array.isArray(value) ? [...value] : [];
476
492
  }
477
- function isRecord(value) {
478
- return Object(value) === value && !Array.isArray(value);
479
- }
480
493
  function sameHandler(left, right) {
481
494
  return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
482
495
  }
483
496
  /** Create a Nitro 3 configuration builder for generated ViteHub output. */
484
497
  function createNitroServerKit(value = {}) {
485
- const config = isRecord(value) ? { ...value } : {};
498
+ const config = isRecordOrFunction(value) ? { ...value } : {};
486
499
  const handlers = cloneArray(config.handlers);
487
500
  const plugins = cloneArray(config.plugins);
488
501
  config.handlers = handlers;
@@ -490,7 +503,7 @@ function createNitroServerKit(value = {}) {
490
503
  return {
491
504
  config,
492
505
  addHandler(handler, position = "end") {
493
- if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
506
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
494
507
  if (position === "start") handlers.unshift({ ...handler });
495
508
  else handlers.push({ ...handler });
496
509
  },
@@ -502,21 +515,97 @@ function createNitroServerKit(value = {}) {
502
515
  };
503
516
  }
504
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
505
594
  //#region src/console.ts
506
595
  /**
507
596
  * 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
597
+ * first. People reply and resolve on the page itself, where the context is; each record links there. The
509
598
  * Console shows it when the app has `server/comments.ts`.
510
599
  */
511
600
  const commentsConsoleSection = {
512
601
  entry: ({ projectRoot, serverDirs }) => findCommentsEntry$2(projectRoot, serverDirs),
513
602
  description: "Triage comments that the team left on the site's pages.",
514
- icon: "i-lucide-message-square-text",
603
+ icon: "i-vitehub-comments",
515
604
  id: "comments",
516
605
  label: "Comments",
517
606
  runtime: {
518
607
  export: "readCommentsConsoleRecords",
519
- module: "@vite-hub/comments/runtime/console"
608
+ module: ownModule(import.meta.url, "runtime/console")
520
609
  },
521
610
  view: {
522
611
  columns: [
@@ -537,6 +626,7 @@ const commentsConsoleSection = {
537
626
  label: "Replies"
538
627
  },
539
628
  {
629
+ filter: true,
540
630
  key: "status",
541
631
  label: "Status"
542
632
  },
@@ -546,19 +636,34 @@ const commentsConsoleSection = {
546
636
  }
547
637
  ],
548
638
  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()`."
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()`."
550
640
  }
551
641
  };
552
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
553
656
  //#region src/live-vite.ts
554
- const defaultImports$1 = {
657
+ const defaultImports = {
555
658
  runtime: "@vite-hub/comments/runtime",
556
659
  realtime: "@vite-hub/comments/realtime",
557
660
  auth: "@vite-hub/comments/runtime/auth",
558
661
  database: "@vite-hub/comments/database",
559
- databases: "@vite-hub/database/drizzle",
662
+ databases: "@vite-hub/database/runtime/registry",
560
663
  contentClient: "@vite-hub/content/client",
561
- connect: "@vite-hub/comments/runtime/connect"
664
+ connect: "@vite-hub/comments/runtime/connect",
665
+ blob: "@vite-hub/blob",
666
+ rateLimit: "@vite-hub/rate-limit"
562
667
  };
563
668
  /**
564
669
  * The Database name in `defineComments({ database: "name" })`, read without running the file. Undefined means the
@@ -569,33 +674,43 @@ async function readCommentsDatabase(file) {
569
674
  if (module.errors.length) return;
570
675
  const bindings = /* @__PURE__ */ new Set();
571
676
  const factories = /* @__PURE__ */ new Set(["defineComments"]);
677
+ let defaultCall;
572
678
  for (const statement of module.program.body) {
573
679
  if (statement.type === "ImportDeclaration" && statement.importKind !== "type" && ["vite-hub/comments", "@vite-hub/comments"].includes(statement.source.value)) for (const specifier of statement.specifiers) {
574
680
  if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") continue;
575
681
  if ((specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value) === "defineComments") factories.add(specifier.local.name);
576
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
+ }
577
689
  if (statement.type !== "ExportNamedDeclaration" || statement.source) continue;
578
690
  if (statement.declaration?.type === "VariableDeclaration") {
579
691
  for (const declaration of statement.declaration.declarations) if (declaration.id.type === "Identifier" && declaration.id.name === "comments") bindings.add(declaration.id.name);
580
692
  }
581
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);
582
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);
583
708
  for (const statement of module.program.body) {
584
709
  const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
585
710
  if (declaration?.type !== "VariableDeclaration") continue;
586
711
  for (const binding of declaration.declarations) {
587
712
  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;
713
+ return databaseOf(unwrapExpression(binding.init));
599
714
  }
600
715
  }
601
716
  }
@@ -608,71 +723,12 @@ function builtDirectory(name) {
608
723
  function commentsOverlayDirectory() {
609
724
  return builtDirectory("overlay");
610
725
  }
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
726
  /**
642
727
  * 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.
728
+ * request when the host names it. Empty outside a Git checkout. Forge's `readForgeBuild` reads it.
644
729
  */
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
- };
730
+ function readCommentsBuild(root, env = process.env) {
731
+ return readForgeBuild(root, env);
676
732
  }
677
733
  const skippedDirectories = /* @__PURE__ */ new Set([
678
734
  "node_modules",
@@ -730,58 +786,59 @@ async function readCommentsComponents(root, limit = 5e3, resolvedComponents = []
730
786
  Object.assign(components, resolvedNames);
731
787
  return components;
732
788
  }
733
- const version = "3";
734
- /** Generated session reader: the Console user of a request, else the ViteHub Auth user. */
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. */
735
799
  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
800
  return options.auth ? {
742
801
  imports: [`import { commentsAuthSession } from ${JSON.stringify(imports.auth)}`],
743
- option: "session",
744
802
  value: "commentsAuthSession"
745
803
  } : {
746
804
  imports: [],
747
- option: "session",
748
805
  value: "undefined"
749
806
  };
750
807
  }
751
- /** The session reader of presence and MCP: the Console or Auth user, else the person signed in with GitHub. */
808
+ /** The session reader of presence and MCP: the Auth user, else `githubLogin`, the person signed in with GitHub. */
752
809
  function sessionWithGitHubLines(options, imports, repository, base) {
753
- if (options.auth || options.console) return sessionLines(options, imports);
810
+ if (options.auth) return sessionLines(options, imports);
754
811
  const route = mountedCommentsRoute(base);
755
812
  return {
756
813
  imports: [`import { createCommentsGitHubLogin } from ${JSON.stringify(imports.runtime)}`, `const githubLogin = createCommentsGitHubLogin(${JSON.stringify({
757
814
  ...repository ? { repository } : {},
758
815
  ...route !== "/api/_vitehub/comments" ? { basePath: `${route}/auth` } : {}
759
816
  })})`],
760
- option: "session",
761
- value: "githubLogin.user",
817
+ value: "undefined",
762
818
  githubLogin: true
763
819
  };
764
820
  }
765
821
  function renderCommentsHandler(input) {
766
822
  const session = sessionLines(input.session, input.imports);
767
823
  const route = mountedCommentsRoute(input.base);
768
- const githubLogin = !input.session.auth && !input.session.console;
824
+ const githubLogin = !input.session.auth;
769
825
  return [
770
826
  `import { createCommentsHandler${githubLogin ? ", createCommentsGitHubLogin" : ""} } from ${JSON.stringify(input.imports.runtime)}`,
771
827
  `import components from "./components.mjs"`,
772
- `import { comments } from ${JSON.stringify(pathToFileURL(input.definition).href)}`,
828
+ ...definitionLines(input.definition, input.imports.runtime),
773
829
  ...session.imports,
774
830
  ...input.content ? [`import * as contentModule from ${JSON.stringify(pathToFileURL(input.content).href)}`, `import { parseContentField } from ${JSON.stringify(input.imports.contentClient)}`] : [],
775
831
  "",
776
832
  "export default createCommentsHandler({",
777
833
  " comments,",
778
- ` ${session.option}: ${session.value},`,
834
+ ` session: ${session.value},`,
779
835
  ...githubLogin ? [` githubLogin: createCommentsGitHubLogin(${JSON.stringify({
780
836
  ...input.build?.repository ? { repository: input.build.repository } : {},
781
837
  ...route !== "/api/_vitehub/comments" ? { basePath: `${route}/auth` } : {}
782
838
  })}),`] : [],
783
- ...input.content ? [" content: contentModule.content ? { runtime: contentModule.content, parseField: parseContentField } : undefined,"] : [],
839
+ ...input.content ? [" content: contentModule.default ? { runtime: contentModule.default, parseField: parseContentField } : undefined,"] : [],
784
840
  ` realtime: ${input.realtime},`,
841
+ ...input.session.overlay && input.session.overlay.presence === false ? [" presence: false,"] : [],
785
842
  ` build: ${JSON.stringify(input.build ?? {})},`,
786
843
  " components,",
787
844
  "})",
@@ -790,53 +847,59 @@ function renderCommentsHandler(input) {
790
847
  }
791
848
  function renderCommentsPlugin(input) {
792
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}`);
793
852
  if (input.standalone) {
794
853
  const { where, fallback, node } = input.standalone;
795
- const options = [
796
- `name: "comments"`,
797
- "setup: commentsTables",
798
- ...fallback ? [`fallback: ${JSON.stringify(fallback)}`] : []
799
- ];
854
+ const options = [`name: "comments"`, ...fallback ? [`fallback: ${JSON.stringify(fallback)}`] : []];
800
855
  return [
801
856
  `import { defineCommentsPlugin } from ${JSON.stringify(input.imports.runtime)}`,
802
857
  `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)}`,
858
+ ...definitionLines(input.definition, input.imports.runtime),
805
859
  ...session.imports,
806
860
  "",
807
861
  `const database = () => connectDatabase(${where === void 0 ? "undefined" : JSON.stringify(where)}, { ${options.join(", ")} })`,
808
862
  "",
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 ?? "")} })`,
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 ?? "")} })`,
810
864
  ""
811
865
  ].join("\n");
812
866
  }
813
867
  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)}`,
868
+ `import { defineCommentsPlugin, selectCommentsDatabase } from ${JSON.stringify(input.imports.runtime)}`,
869
+ ...definitionLines(input.definition, input.imports.runtime),
817
870
  ...session.imports,
818
871
  "",
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
- "}",
872
+ `const database = async () => selectCommentsDatabase((await import(${JSON.stringify(input.imports.databases)})).databases${input.database ? `, ${JSON.stringify(input.database)}` : ""})`,
831
873
  "",
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 ?? "")} })`,
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(", ")} })`,
833
891
  ""
834
892
  ].join("\n");
835
893
  }
894
+ /** The generated directory of Comments in a project. */
895
+ function generatedDirectory(projectRoot) {
896
+ return resolve(projectRoot, ".vitehub/nitro/comments");
897
+ }
836
898
  /** `server/comments.ts` for an app without one: Comments with its defaults. */
837
899
  async function writeDefaultDefinition(directory, imports) {
838
900
  const file = join(directory, "definition.mjs");
839
901
  const index = imports.runtime.replace(/\/runtime$/, "");
902
+ await mkdir(directory, { recursive: true });
840
903
  await writeFile(file, [
841
904
  `import { defineComments } from ${JSON.stringify(index)}`,
842
905
  "",
@@ -915,36 +978,38 @@ async function addD1Binding(projectRoot, nitro, where) {
915
978
  }
916
979
  };
917
980
  }
918
- /** Whether `vite-hub` is in the app, so it runs Comments and `comments()` steps aside. */
981
+ /** Whether `vite-hub` is in the app, so Comments runs through `vitehub()` and not `comments()`. */
919
982
  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";
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
+ };
921
989
  return find(config.plugins);
922
990
  }
923
991
  /**
924
992
  * 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.
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.
927
995
  */
928
996
  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
- ];
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 })];
939
1003
  }
940
1004
  /**
941
1005
  * Comments build integration. When the app has `server/comments.ts`, it serves the Comments API at
942
1006
  * `/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.
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.
944
1009
  */
945
- function hubComments$2(options = {}) {
1010
+ function hubComments$1(options = {}) {
946
1011
  const imports = {
947
- ...defaultImports$1,
1012
+ ...defaultImports,
948
1013
  ...options.imports
949
1014
  };
950
1015
  let projectRoot;
@@ -956,7 +1021,10 @@ function hubComments$2(options = {}) {
956
1021
  let appBase = "";
957
1022
  let development = false;
958
1023
  const discover = () => findCommentsEntry$2(projectRoot ?? process.cwd(), serverDirs);
959
- const enabled = () => Boolean(options.standalone) || Boolean(discover());
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);
960
1028
  async function writeComponents() {
961
1029
  if (!projectRoot || !componentsFile) return;
962
1030
  const components = await readCommentsComponents(projectRoot, 5e3, resolvedComponents);
@@ -964,6 +1032,10 @@ function hubComments$2(options = {}) {
964
1032
  }
965
1033
  const integration = {
966
1034
  name: options.standalone ? "@vite-hub/comments" : "@vite-hub/comments/vite",
1035
+ configEnvironment: options.standalone ? {
1036
+ order: "post",
1037
+ handler: workerdDependencyConfig
1038
+ } : void 0,
967
1039
  nitro: options.standalone ? { async setup(nitro) {
968
1040
  if (!projectRoot || !options.standalone) return;
969
1041
  const runner = nitro.options.devServer.runner || process.env.NITRO_DEV_RUNNER || "node-worker";
@@ -972,7 +1044,7 @@ function hubComments$2(options = {}) {
972
1044
  parseDatabaseLocation(standalone.where, "comments", { node: nitro.options.node });
973
1045
  standalone.node = nitro.options.node;
974
1046
  }
975
- const directory = resolve(projectRoot, ".vitehub/nitro/comments");
1047
+ const directory = generatedDirectory(projectRoot);
976
1048
  const definition = discover() ?? join(directory, "definition.mjs");
977
1049
  const build = await readCommentsBuild(projectRoot);
978
1050
  await writeFile(join(directory, "plugin.mjs"), renderCommentsPlugin({
@@ -988,12 +1060,13 @@ function hubComments$2(options = {}) {
988
1060
  await addD1Binding(projectRoot, nitro.options, standalone.fallback);
989
1061
  } } : void 0,
990
1062
  api: {
1063
+ deploymentEnv: (context) => enabled() ? commentsDeploymentEnv(options, context) : [],
991
1064
  async setComponents(components) {
992
1065
  resolvedComponents = components;
993
1066
  await writeComponents();
994
1067
  },
995
1068
  async contributeRealtime(context) {
996
- const definition = findCommentsEntry$2(context.projectRoot, context.serverDirs);
1069
+ const definition = await definitionOf(context.projectRoot, context.serverDirs);
997
1070
  if (!definition) return;
998
1071
  realtime = true;
999
1072
  const file = join(context.directory, "comments.mjs");
@@ -1002,10 +1075,10 @@ function hubComments$2(options = {}) {
1002
1075
  await mkdir(context.directory, { recursive: true });
1003
1076
  await writeFile(file, [
1004
1077
  `import { commentsRealtime } from ${JSON.stringify(imports.realtime)}`,
1005
- `import { comments } from ${JSON.stringify(pathToFileURL(definition).href)}`,
1078
+ ...definitionLines(definition, imports.runtime),
1006
1079
  ...session.imports,
1007
1080
  "",
1008
- `export default commentsRealtime(comments, { ${session.option}: ${session.value} })`,
1081
+ `export default commentsRealtime(comments, { session: ${session.value}${session.githubLogin ? ", githubLogin" : ""} })`,
1009
1082
  ""
1010
1083
  ].join("\n"));
1011
1084
  return { definitions: [{
@@ -1019,8 +1092,8 @@ function hubComments$2(options = {}) {
1019
1092
  kind: "comments",
1020
1093
  label: "Comments",
1021
1094
  list: () => {
1022
- const definition = discover();
1023
- if (!definition) return [];
1095
+ if (!enabled()) return [];
1096
+ const definition = discover() ?? join(generatedDirectory(projectRoot ?? process.cwd()), "definition.mjs");
1024
1097
  return [{
1025
1098
  fields: [
1026
1099
  {
@@ -1045,17 +1118,22 @@ function hubComments$2(options = {}) {
1045
1118
  async databases(context) {
1046
1119
  if (options.standalone) return [];
1047
1120
  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);
1121
+ if (!definition && !options.enabled) return [];
1122
+ const database = options.database ?? (definition ? await readCommentsDatabase(definition) : void 0);
1123
+ const postgres = options.dialect === "postgresql";
1050
1124
  return [{
1051
1125
  ...database ? { database } : {},
1052
- definition: {
1126
+ definition: postgres ? {
1127
+ export: "commentsPostgresSchema",
1128
+ module: `${imports.database}/postgres`
1129
+ } : {
1053
1130
  export: "commentsSchema",
1054
1131
  module: imports.database
1055
1132
  },
1056
- dialect: "sqlite",
1133
+ dialect: postgres ? "postgresql" : "sqlite",
1134
+ tables: commentsTableNames,
1057
1135
  name: "comments",
1058
- reason: "Stores the comment threads of `server/comments.ts`."
1136
+ reason: definition ? "Stores the comment threads of `server/comments.ts`." : "Stores the comment threads of `vitehub({ comments })`."
1059
1137
  }];
1060
1138
  }
1061
1139
  },
@@ -1068,7 +1146,7 @@ function hubComments$2(options = {}) {
1068
1146
  route = mountedCommentsRoute(base);
1069
1147
  projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(resolve(config.root || process.cwd()));
1070
1148
  serverDirs = viteConfig[VITEHUB_SERVER_DIRS]?.slice();
1071
- const directory = resolve(projectRoot, ".vitehub/nitro/comments");
1149
+ const directory = generatedDirectory(projectRoot);
1072
1150
  if (!enabled()) {
1073
1151
  componentsFile = void 0;
1074
1152
  await rm(directory, {
@@ -1086,7 +1164,7 @@ function hubComments$2(options = {}) {
1086
1164
  const build = await readCommentsBuild(projectRoot);
1087
1165
  const pluginInput = {
1088
1166
  definition,
1089
- database: await readCommentsDatabase(definition),
1167
+ database: options.database ?? await readCommentsDatabase(definition),
1090
1168
  session: options,
1091
1169
  imports,
1092
1170
  build,
@@ -1110,6 +1188,7 @@ function hubComments$2(options = {}) {
1110
1188
  const kit = createNitroServerKit(Reflect.get(config, "nitro"));
1111
1189
  kit.addHandler({
1112
1190
  handler,
1191
+ lazy: true,
1113
1192
  route: `${mount}${commentsRoute}/**`
1114
1193
  });
1115
1194
  kit.addPlugin(plugin);
@@ -1146,41 +1225,125 @@ function hubComments$2(options = {}) {
1146
1225
  return integration;
1147
1226
  }
1148
1227
  //#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
- }
1228
+ //#region src/operations-core/console.ts
1166
1229
  /**
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.
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>`.
1170
1232
  */
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;
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;
1184
1347
  if (/^https?:\/\//.test(pathname)) try {
1185
1348
  pathname = new URL(pathname).pathname;
1186
1349
  } catch {
@@ -1316,8 +1479,7 @@ function injectLoader(html, tag, found = createHtmlScanner()(html)) {
1316
1479
  }
1317
1480
  /**
1318
1481
  * 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.
1482
+ * prerenders them, the saved files. It is Nitro middleware `(event, next)`.
1321
1483
  *
1322
1484
  * It rewrites only what is safe to rewrite: UTF-8 `text/html` that is not compressed, with a `</body>` or `</html>`.
1323
1485
  * A stream is piped through a transform that holds back a short tail, so a tag split across chunks is still found.
@@ -1396,11 +1558,11 @@ function renderOverlayMiddleware(url) {
1396
1558
  "}",
1397
1559
  "",
1398
1560
  "export default async function injectCommentsLoader(event, next) {",
1399
- " if (typeof next !== \"function\") return",
1400
1561
  " const result = await next()",
1401
1562
  " try {",
1402
- " const path = new URL(event.req.url).pathname",
1403
- " if (event.req.method !== \"GET\" || path === consolePath || path.startsWith(`${consolePath}/`)) return result",
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",
1404
1566
  " if (result instanceof Response) {",
1405
1567
  " if (!result.body || result.status < 200 || result.status === 204 || result.status === 205 || result.status === 206 || result.status === 304 || !rewritable(result.headers)) return result",
1406
1568
  " const tag = tagFor(scriptNonce(result.headers.get(\"content-security-policy\")))",
@@ -1411,10 +1573,10 @@ function renderOverlayMiddleware(url) {
1411
1573
  " return new Response(result.body.pipeThrough(injector(tag)), { headers, status: result.status, statusText: result.statusText })",
1412
1574
  " }",
1413
1575
  " if (typeof result === \"string\") {",
1414
- " const headers = event.res.headers",
1576
+ " const headers = res.headers",
1415
1577
  " const type = headers.get(\"content-type\")",
1416
1578
  " // 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",
1579
+ " if (headers.has(\"content-range\") || res.status === 206 || (type && !rewritable(headers))) return result",
1418
1580
  " const injected = inject(result, tagFor(scriptNonce(headers.get(\"content-security-policy\"))))",
1419
1581
  " if (injected !== result) {",
1420
1582
  " headers.delete(\"content-length\")",
@@ -1432,490 +1594,67 @@ function renderOverlayMiddleware(url) {
1432
1594
  ].join("\n");
1433
1595
  }
1434
1596
  //#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
- }
1597
+ //#region src/vite.ts
1598
+ function findCommentsEntry(options, serverDirs) {
1599
+ return typeof options === "string" ? findCommentsEntry$2(options, serverDirs) : findCommentsEntry$1(options);
1658
1600
  }
1659
1601
  /**
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.
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.
1663
1605
  */
1664
- function hubComments$1(options = {}) {
1665
- const imports = {
1666
- ...defaultImports,
1667
- ...options.imports
1668
- };
1669
- const postgres = options.dialect === "postgresql";
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");
1670
1610
  let projectRoot;
1671
1611
  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
- };
1612
+ const config = live.config;
1703
1613
  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
- },
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
+ } },
1743
1621
  transformIndexHtml: {
1744
1622
  order: "post",
1745
- handler(html) {
1746
- const url = discover() ? overlayUrl() : void 0;
1747
- return url ? injectLoader(html, loaderTag(url)) : html;
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);
1748
1626
  }
1749
1627
  },
1750
- async configResolved(config) {
1751
- const entry = discover();
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 });
1752
1636
  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
1637
  const { runnerImport } = await import("vite");
1764
- const { module: app } = await runnerImport(entry, {
1638
+ const { module } = await runnerImport(entry, {
1765
1639
  configFile: false,
1766
1640
  root: projectRoot,
1767
- resolve: { alias: config.resolve?.alias },
1641
+ resolve: { alias: resolved.resolve?.alias },
1768
1642
  logLevel: "silent"
1769
1643
  });
1770
- validateCommentsDefinition(app.default, displayPath(entry, projectRoot ?? ""));
1644
+ validateCommentsDefinition(module.comments ?? module.default, display);
1771
1645
  },
1772
1646
  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() ? [{
1647
+ ...live.vitehub,
1648
+ operations: async () => liveOptions.enabled || findCommentsEntry({
1649
+ projectRoot: projectRoot ?? process.cwd(),
1650
+ ...serverDirs ? { serverDirs } : {}
1651
+ }) ? [{
1829
1652
  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
1653
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).commentsOperations,
1654
+ module
1832
1655
  }] : []
1833
1656
  }
1834
1657
  };
1835
1658
  }
1836
1659
  //#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 };
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 };