@vite-hub/realtime 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js CHANGED
@@ -1,12 +1,220 @@
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cvm6vRXQ.js";
2
+ import { t as realtimeDurableObjectKey } from "./durable-key-tnSw58ZK.js";
3
+ import { defineDiagnostics } from "nostics";
1
4
  import { mkdir, writeFile } from "node:fs/promises";
2
5
  import { basename, dirname, parse, relative, resolve } from "node:path";
3
- import { existsSync, readdirSync, statSync } from "node:fs";
4
- import { relative as relative$1, resolve as resolve$1 } from "pathe";
6
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
5
7
  import { tmpdir } from "node:os";
8
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
9
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
10
+ function normalizeWindowsPath(input = "") {
11
+ if (!input) return input;
12
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
13
+ }
14
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
15
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
16
+ function cwd() {
17
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
18
+ return "/";
19
+ }
20
+ const resolve$1 = function(...arguments_) {
21
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
22
+ let resolvedPath = "";
23
+ let resolvedAbsolute = false;
24
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
25
+ const path = index >= 0 ? arguments_[index] : cwd();
26
+ if (!path || path.length === 0) continue;
27
+ resolvedPath = `${path}/${resolvedPath}`;
28
+ resolvedAbsolute = isAbsolute(path);
29
+ }
30
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
31
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
32
+ return resolvedPath.length > 0 ? resolvedPath : ".";
33
+ };
34
+ function normalizeString(path, allowAboveRoot) {
35
+ let res = "";
36
+ let lastSegmentLength = 0;
37
+ let lastSlash = -1;
38
+ let dots = 0;
39
+ let char = null;
40
+ for (let index = 0; index <= path.length; ++index) {
41
+ if (index < path.length) char = path[index];
42
+ else if (char === "/") break;
43
+ else char = "/";
44
+ if (char === "/") {
45
+ if (lastSlash === index - 1 || dots === 1);
46
+ else if (dots === 2) {
47
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
48
+ if (res.length > 2) {
49
+ const lastSlashIndex = res.lastIndexOf("/");
50
+ if (lastSlashIndex === -1) {
51
+ res = "";
52
+ lastSegmentLength = 0;
53
+ } else {
54
+ res = res.slice(0, lastSlashIndex);
55
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
56
+ }
57
+ lastSlash = index;
58
+ dots = 0;
59
+ continue;
60
+ } else if (res.length > 0) {
61
+ res = "";
62
+ lastSegmentLength = 0;
63
+ lastSlash = index;
64
+ dots = 0;
65
+ continue;
66
+ }
67
+ }
68
+ if (allowAboveRoot) {
69
+ res += res.length > 0 ? "/.." : "..";
70
+ lastSegmentLength = 2;
71
+ }
72
+ } else {
73
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
74
+ else res = path.slice(lastSlash + 1, index);
75
+ lastSegmentLength = index - lastSlash - 1;
76
+ }
77
+ lastSlash = index;
78
+ dots = 0;
79
+ } else if (char === "." && dots !== -1) ++dots;
80
+ else dots = -1;
81
+ }
82
+ return res;
83
+ }
84
+ const isAbsolute = function(p) {
85
+ return _IS_ABSOLUTE_RE.test(p);
86
+ };
87
+ const relative$1 = function(from, to) {
88
+ const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
89
+ const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
90
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
91
+ const _fromCopy = [..._from];
92
+ for (const segment of _fromCopy) {
93
+ if (_to[0] !== segment) break;
94
+ _from.shift();
95
+ _to.shift();
96
+ }
97
+ return [..._from.map(() => ".."), ..._to].join("/");
98
+ };
99
+ //#endregion
100
+ //#region ../internal/src/error-diagnostics.ts
101
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
102
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
103
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
104
+ codes: {
105
+ INTERNAL_R0012: dynamicError,
106
+ INTERNAL_R0013: dynamicError,
107
+ INTERNAL_R0014: {
108
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
109
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
110
+ },
111
+ INTERNAL_R0020: {
112
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
113
+ why: ({ message }) => message === void 0 ? "" : String(message)
114
+ },
115
+ INTERNAL_R0021: {
116
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
117
+ why: ({ message }) => message === void 0 ? "" : String(message)
118
+ },
119
+ INTERNAL_R0022: {
120
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
121
+ why: ({ message }) => message === void 0 ? "" : String(message)
122
+ },
123
+ INTERNAL_R0024: {
124
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
125
+ why: ({ message }) => message === void 0 ? "" : String(message)
126
+ },
127
+ INTERNAL_R0023: {
128
+ fix: "Ask for access to the section of this operation.",
129
+ why: ({ message }) => message === void 0 ? "" : String(message)
130
+ },
131
+ INTERNAL_B0001: dynamicError,
132
+ INTERNAL_B0002: dynamicError,
133
+ INTERNAL_B0003: dynamicError,
134
+ INTERNAL_B0004: dynamicError,
135
+ INTERNAL_B0005: dynamicError,
136
+ INTERNAL_B0006: dynamicError,
137
+ INTERNAL_B0007: dynamicError,
138
+ INTERNAL_B0008: dynamicError,
139
+ INTERNAL_B0009: dynamicError,
140
+ INTERNAL_B0010: dynamicError,
141
+ INTERNAL_B0011: dynamicError,
142
+ INTERNAL_B0012: dynamicError,
143
+ INTERNAL_B0013: dynamicError,
144
+ INTERNAL_B0014: dynamicError,
145
+ INTERNAL_B0015: dynamicError,
146
+ INTERNAL_B0016: dynamicError,
147
+ INTERNAL_B0017: dynamicError,
148
+ INTERNAL_B0018: dynamicError,
149
+ INTERNAL_B0019: dynamicError,
150
+ INTERNAL_B0020: dynamicError,
151
+ INTERNAL_B0021: dynamicError,
152
+ INTERNAL_B0022: dynamicError,
153
+ INTERNAL_B0023: dynamicError,
154
+ INTERNAL_B0024: dynamicError,
155
+ INTERNAL_B0025: dynamicError,
156
+ INTERNAL_B0026: dynamicError,
157
+ INTERNAL_B0027: dynamicError,
158
+ INTERNAL_B0028: dynamicError,
159
+ INTERNAL_B0029: dynamicError,
160
+ INTERNAL_B0030: dynamicError,
161
+ INTERNAL_B0031: dynamicError,
162
+ INTERNAL_B0032: dynamicError,
163
+ INTERNAL_B0033: dynamicError,
164
+ INTERNAL_B0034: dynamicError,
165
+ INTERNAL_B0035: dynamicError,
166
+ INTERNAL_B0036: dynamicError,
167
+ INTERNAL_B0037: dynamicError,
168
+ INTERNAL_B0038: dynamicError,
169
+ INTERNAL_B0039: dynamicError,
170
+ INTERNAL_B0040: dynamicError,
171
+ INTERNAL_B0041: dynamicError,
172
+ INTERNAL_B0042: dynamicError,
173
+ INTERNAL_B0043: dynamicError,
174
+ INTERNAL_B0044: dynamicError,
175
+ INTERNAL_B0045: dynamicError,
176
+ INTERNAL_B0046: dynamicError,
177
+ INTERNAL_B0047: dynamicError,
178
+ INTERNAL_B0048: {
179
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
180
+ why: ({ message }) => message === void 0 ? "" : String(message)
181
+ },
182
+ INTERNAL_B0049: {
183
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
184
+ why: ({ message }) => message === void 0 ? "" : String(message)
185
+ },
186
+ INTERNAL_B0050: {
187
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
188
+ why: ({ message }) => message === void 0 ? "" : String(message)
189
+ },
190
+ INTERNAL_R0025: {
191
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
192
+ why: ({ message }) => message === void 0 ? "" : String(message)
193
+ },
194
+ INTERNAL_R0026: {
195
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
196
+ fix: "Review the operation, then run it again with --yes to confirm the change."
197
+ },
198
+ INTERNAL_C0001: dynamicError,
199
+ INTERNAL_C0002: dynamicError,
200
+ INTERNAL_R0001: dynamicError,
201
+ INTERNAL_R0002: dynamicError,
202
+ INTERNAL_R0003: dynamicError,
203
+ INTERNAL_R0004: dynamicError,
204
+ INTERNAL_R0005: dynamicError,
205
+ INTERNAL_R0006: dynamicError,
206
+ INTERNAL_R0007: dynamicError,
207
+ INTERNAL_R0008: dynamicError,
208
+ INTERNAL_R0009: dynamicError,
209
+ INTERNAL_R0010: dynamicError,
210
+ INTERNAL_R0011: dynamicError
211
+ }
212
+ });
213
+ //#endregion
6
214
  //#region ../internal/src/definition-catalog.ts
7
215
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
8
216
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
9
- const ignoredDirs = new Set([
217
+ const ignoredDirs = /* @__PURE__ */ new Set([
10
218
  "node_modules",
11
219
  "dist",
12
220
  ".output",
@@ -62,7 +270,7 @@ function sortDefinitions(definitions) {
62
270
  }
63
271
  function registerDefinition(definitions, definition, sourceLabel) {
64
272
  const existing = definitions.get(definition.name);
65
- if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
273
+ if (existing) throw internalErrorDiagnostics.INTERNAL_C0001({ message: `Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}` });
66
274
  definitions.set(definition.name, definition);
67
275
  }
68
276
  function mergeDefinitions(feature, ...sources) {
@@ -71,7 +279,7 @@ function mergeDefinitions(feature, ...sources) {
71
279
  if (!source) continue;
72
280
  for (const definition of source) {
73
281
  const existing = definitions.get(definition.name);
74
- if (existing && existing.handler !== definition.handler) throw new Error(`Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})`);
282
+ if (existing && existing.handler !== definition.handler) throw internalErrorDiagnostics.INTERNAL_C0002({ message: `Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})` });
75
283
  if (!existing) definitions.set(definition.name, definition);
76
284
  }
77
285
  }
@@ -90,7 +298,10 @@ function createDefinition(source, file, name) {
90
298
  }
91
299
  function scanSuffixDefinitions(feature, source) {
92
300
  const definitions = /* @__PURE__ */ new Map();
93
- for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
301
+ for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => {
302
+ source.pattern.lastIndex = 0;
303
+ return source.pattern.test(name);
304
+ }, { includeHidden: source.includeHidden })) {
94
305
  const name = source.normalizeName(root, file);
95
306
  if (!name) continue;
96
307
  registerDefinition(definitions, createDefinition(source, file, name), feature);
@@ -120,33 +331,35 @@ function createRuntimeRegistryContents(registryFile, definitions) {
120
331
  return [
121
332
  "",
122
333
  "const registry = {",
123
- ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: async () => ${createImportExpression(registryFile, definition.handler)},`),
334
+ ...definitions.map((definition) => ` [${JSON.stringify(definition.name)}]: async () => ${createImportExpression(registryFile, definition.handler)},`),
124
335
  "}",
125
336
  "",
126
337
  "export default registry",
127
338
  ""
128
339
  ].join("\n");
129
340
  }
130
- function deploymentPresetFromNitro(value) {
131
- const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
132
- if (!normalized) return;
133
- if (normalized.startsWith("cloudflare")) return "cloudflare";
134
- if (normalized.startsWith("deno")) return "deno";
135
- if (normalized.startsWith("netlify")) return "netlify";
136
- if (normalized === "node" || normalized.startsWith("node-")) return "node";
137
- if (normalized.startsWith("vercel")) return "vercel";
138
- }
139
341
  //#endregion
140
342
  //#region ../internal/src/build/vite.ts
141
343
  const projectRootDirectoryMarkers = [
142
344
  ["server", "agents"],
143
345
  ["server", "channels"],
346
+ ["server", "connections"],
144
347
  ["server", "browsers"],
145
348
  ["server", "emails"],
146
349
  ["server", "schedules"],
147
350
  ["server", "workspaces"]
148
351
  ];
149
- const projectRootFileMarkers = [["package.json"]];
352
+ const projectRootFileMarkers = [
353
+ ["package.json"],
354
+ ["nuxt.config.ts"],
355
+ ["nuxt.config.mts"],
356
+ ["nuxt.config.js"],
357
+ ["nuxt.config.mjs"]
358
+ ];
359
+ /**
360
+ * Server directories that ViteHub scans for Definitions. The first entry is the application.
361
+ * Later entries are Nuxt layers in Nuxt priority order.
362
+ */
150
363
  const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
151
364
  function resolveViteHubProjectRoot(root, options = {}) {
152
365
  const resolvedRoot = resolve(root);
@@ -155,7 +368,12 @@ function resolveViteHubProjectRoot(root, options = {}) {
155
368
  if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
156
369
  if (basename(resolvedRoot) === "app") {
157
370
  const parent = dirname(resolvedRoot);
158
- if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
371
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
372
+ "nuxt.config.ts",
373
+ "nuxt.config.mts",
374
+ "nuxt.config.js",
375
+ "nuxt.config.mjs"
376
+ ]))) return parent;
159
377
  }
160
378
  let current = resolvedRoot;
161
379
  while (true) {
@@ -176,15 +394,125 @@ function hasProjectRootDirectoryMarker(root) {
176
394
  }
177
395
  function hasProjectRootMarker(root) {
178
396
  if (hasProjectRootDirectoryMarker(root)) return true;
179
- for (const marker of projectRootFileMarkers) try {
180
- if (statSync(resolve(root, ...marker)).isFile()) return true;
181
- } catch (error) {
182
- if (error.code !== "ENOENT") throw error;
397
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
398
+ }
399
+ function hasProjectRootFileMarker(root, markers) {
400
+ for (const marker of markers) {
401
+ const path = Array.isArray(marker) ? marker : [marker];
402
+ try {
403
+ if (statSync(resolve(root, ...path)).isFile()) return true;
404
+ } catch (error) {
405
+ if (error.code !== "ENOENT") throw error;
406
+ }
183
407
  }
184
408
  return false;
185
409
  }
410
+ /**
411
+ * The path of an app base, without the trailing slash: `/portal/` and `https://cdn.example/portal/` give `/portal`.
412
+ * The root and relative bases (`""`, `"./"`) give `""`. The Console mounts its routes with the same rule.
413
+ */
414
+ function viteHubBasePath(base) {
415
+ if (!base || base === "./") return "";
416
+ let pathname = base;
417
+ if (/^https?:\/\//.test(pathname)) try {
418
+ pathname = new URL(pathname).pathname;
419
+ } catch {
420
+ return "";
421
+ }
422
+ if (!pathname.startsWith("/") || pathname.startsWith("//")) return "";
423
+ return pathname.replace(/\/+$/, "");
424
+ }
425
+ //#endregion
426
+ //#region ../internal/src/build/page-tools.ts
427
+ function readString(value, key) {
428
+ const field = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
429
+ return typeof field === "string" ? field : void 0;
430
+ }
431
+ /**
432
+ * The app base of a Vite configuration. ViteHub's application-base config field or `__VITEHUB_APP_BASE_URL__` constant
433
+ * takes precedence over the Vite `base`; the Nuxt module sets both from `app.baseURL`. Only a root-relative Vite `base`
434
+ * supplies an application path; absolute and protocol-relative URLs are asset CDN bases. The Nitro base is
435
+ * `nitro.baseURL`, else `NITRO_APP_BASE_URL`.
436
+ */
437
+ function viteHubPageToolsBase(config, env = process.env) {
438
+ const defined = readString(config !== null && typeof config === "object" ? Reflect.get(config, "define") : void 0, "__VITEHUB_APP_BASE_URL__");
439
+ const viteBase = readString(config, "base");
440
+ let appBase = viteBase?.startsWith("/") && !viteBase.startsWith("//") ? viteBase : void 0;
441
+ if (defined) try {
442
+ const value = JSON.parse(defined);
443
+ if (typeof value === "string") appBase = value;
444
+ } catch {}
445
+ const base = viteHubBasePath(readString(config, "__vitehubAppBaseURL") ?? appBase);
446
+ const nitroBase = viteHubBasePath(readString(config !== null && typeof config === "object" ? Reflect.get(config, "nitro") : void 0, "baseURL") ?? env.NITRO_APP_BASE_URL);
447
+ return {
448
+ base,
449
+ mount: nitroBase && (base === nitroBase || base.startsWith(`${nitroBase}/`)) ? base.slice(nitroBase.length) : base
450
+ };
451
+ }
452
+ //#endregion
453
+ //#region ../internal/src/nitro-kit.ts
454
+ function cloneArray(value) {
455
+ return Array.isArray(value) ? [...value] : [];
456
+ }
457
+ function isRecord(value) {
458
+ return Object(value) === value && !Array.isArray(value);
459
+ }
460
+ function sameHandler(left, right) {
461
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
462
+ }
463
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
464
+ function createNitroServerKit(value = {}) {
465
+ const config = isRecord(value) ? { ...value } : {};
466
+ const handlers = cloneArray(config.handlers);
467
+ const plugins = cloneArray(config.plugins);
468
+ config.handlers = handlers;
469
+ config.plugins = plugins;
470
+ return {
471
+ config,
472
+ addHandler(handler, position = "end") {
473
+ if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
474
+ if (position === "start") handlers.unshift({ ...handler });
475
+ else handlers.push({ ...handler });
476
+ },
477
+ addPlugin(plugin, position = "end") {
478
+ if (plugins.includes(plugin)) return;
479
+ if (position === "start") plugins.unshift(plugin);
480
+ else plugins.push(plugin);
481
+ }
482
+ };
483
+ }
484
+ function deploymentPresetFromNitro(value) {
485
+ const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
486
+ if (!normalized) return;
487
+ if (normalized.startsWith("cloudflare")) return "cloudflare";
488
+ if (normalized.startsWith("deno")) return "deno";
489
+ if (normalized.startsWith("netlify")) return "netlify";
490
+ if (normalized === "node" || normalized.startsWith("node-")) return "node";
491
+ if (normalized.startsWith("vercel")) return "vercel";
492
+ }
186
493
  //#endregion
187
494
  //#region ../internal/src/hosting.ts
495
+ /**
496
+ * Returns the Nitro preset name that this build targets, as the developer wrote it.
497
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
498
+ * Empty values are skipped.
499
+ */
500
+ function resolveHostPreset(input = {}) {
501
+ const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
502
+ const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
503
+ for (const value of [
504
+ nitroPreset,
505
+ input.hosting,
506
+ env.NITRO_PRESET,
507
+ env.SERVER_PRESET,
508
+ env.VITEHUB_HOSTING
509
+ ]) if (typeof value === "string" && value.trim()) return value.trim();
510
+ }
511
+ /** Returns the host that this build targets: `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. */
512
+ function resolveHost(input = {}) {
513
+ return deploymentPresetFromNitro(resolveHostPreset(input));
514
+ }
515
+ /** Narrows a preset or host name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
188
516
  function getHostingProvider(hosting) {
189
517
  const preset = deploymentPresetFromNitro(hosting);
190
518
  if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
@@ -202,7 +530,152 @@ function discoverRealtimeDefinitions(rootDir, serverDirs) {
202
530
  })]);
203
531
  }
204
532
  //#endregion
533
+ //#region ../internal/src/inspect.ts
534
+ function relativeDefinitionFile(projectRoot, file) {
535
+ return relative$1(projectRoot, file).replaceAll("\\", "/");
536
+ }
537
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
538
+ 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");
539
+ new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
540
+ //#endregion
541
+ //#region src/inspect.ts
542
+ const authorityLabels = {
543
+ auto: "auto: Cloudflare Durable Objects on Cloudflare, memory in development, build error elsewhere",
544
+ cloudflare: "cloudflare: one Durable Object per document, Yjs state in SQLite",
545
+ memory: "memory: one Node process, rooms lost on restart",
546
+ unsupported: "none: this host has no Realtime room authority"
547
+ };
548
+ function propertyName(property) {
549
+ if (property.type !== "Property") return;
550
+ const key = property.key;
551
+ if (key.type === "Identifier") return key.name;
552
+ if (key.type === "Literal" && typeof key.value === "string") return key.value;
553
+ }
554
+ function findDefinitionObject(program) {
555
+ for (const statement of program.body) {
556
+ if (statement.type !== "ExportDefaultDeclaration") continue;
557
+ let node = statement.declaration;
558
+ if (node.type === "CallExpression" && node.arguments[0]?.type === "ObjectExpression") node = node.arguments[0];
559
+ if (node.type === "ObjectExpression") return node;
560
+ }
561
+ }
562
+ function properties(object) {
563
+ const values = /* @__PURE__ */ new Map();
564
+ for (const property of object.properties) {
565
+ const name = propertyName(property);
566
+ if (name && property.type === "Property") values.set(name, property.value);
567
+ }
568
+ return values;
569
+ }
570
+ function literal(node) {
571
+ return node?.type === "Literal" ? node.value : void 0;
572
+ }
573
+ function calleeName(node) {
574
+ if (node.type !== "CallExpression") return;
575
+ if (node.callee.type === "Identifier") return node.callee.name;
576
+ if (node.callee.type === "MemberExpression" && node.callee.property.type === "Identifier") return node.callee.property.name;
577
+ }
578
+ function describeDocument(node) {
579
+ if (!node) return "missing";
580
+ if (node.type === "ObjectExpression") {
581
+ const values = properties(node);
582
+ const workspace = literal(values.get("workspace"));
583
+ if (typeof workspace === "string") return `Workspace ${JSON.stringify(workspace)} (Markdown file per path)`;
584
+ if (values.has("load") && values.has("save")) return "custom adapter (inline load/save)";
585
+ }
586
+ const callee = calleeName(node);
587
+ if (callee === "workspaceDocument") {
588
+ const argument = node.type === "CallExpression" ? node.arguments[0] : void 0;
589
+ const name = argument && argument.type !== "SpreadElement" ? literal(argument) : void 0;
590
+ return typeof name === "string" ? `Workspace ${JSON.stringify(name)} (Markdown file per path)` : "Workspace (dynamic name)";
591
+ }
592
+ if (callee) return `custom adapter (${callee}())`;
593
+ if (node.type === "Identifier") return `custom adapter (${node.name})`;
594
+ return "custom adapter";
595
+ }
596
+ function describePersistence(node) {
597
+ if (literal(node) === false) return "explicit saves only";
598
+ let debounce = String(2e3);
599
+ let maxWait = String(1e4);
600
+ if (node?.type === "ObjectExpression") {
601
+ const values = properties(node);
602
+ if (values.has("debounce")) debounce = String(literal(values.get("debounce")) ?? "dynamic");
603
+ if (values.has("maxWait")) maxWait = String(literal(values.get("maxWait")) ?? "dynamic");
604
+ } else if (node) return "dynamic";
605
+ return `idle save after ${debounce} ms (at most ${maxWait} ms) and when the last client leaves`;
606
+ }
607
+ /** Reads the static shape of one Realtime Definition file without executing it. */
608
+ function describeRealtimeDefinitionSource(parse, file, source) {
609
+ let object;
610
+ let builder;
611
+ try {
612
+ const program = parse(file, source).program;
613
+ object = findDefinitionObject(program);
614
+ const exported = program.body.find((statement) => statement.type === "ExportDefaultDeclaration");
615
+ builder = exported?.type === "ExportDefaultDeclaration" ? calleeName(exported.declaration) : void 0;
616
+ } catch {}
617
+ if (!object) return [{
618
+ label: "Document",
619
+ value: builder && builder !== "defineRealtime" ? `built by ${builder}() (not statically inspectable)` : "dynamic definition (not statically inspectable)"
620
+ }];
621
+ const values = properties(object);
622
+ const editor = values.get("editor");
623
+ const auth = literal(values.get("auth")) === true;
624
+ const perDocument = editor?.type === "ArrowFunctionExpression" || editor?.type === "FunctionExpression";
625
+ return [
626
+ {
627
+ label: "Document",
628
+ value: describeDocument(values.get("document"))
629
+ },
630
+ {
631
+ label: "Editor",
632
+ value: editor ? perDocument ? "custom codec per document" : `custom codec${editor.type === "Identifier" ? ` (${editor.name})` : ""}` : "built-in Markdown kit"
633
+ },
634
+ {
635
+ label: "Identity",
636
+ value: values.has("identify") ? `identify()${auth ? ", required" : ""}` : auth ? "ViteHub Auth session, required" : "anonymous; presence names are client-asserted"
637
+ },
638
+ {
639
+ label: "Authorization",
640
+ value: values.has("authorize") ? "authorize() per document and mode" : "every connection may read and write"
641
+ },
642
+ {
643
+ label: "Persistence",
644
+ value: describePersistence(values.get("persistence"))
645
+ },
646
+ {
647
+ label: "History",
648
+ value: values.has("history") ? "history.checkpoint() enabled" : "none"
649
+ }
650
+ ];
651
+ }
652
+ async function summarizeRealtimeDefinitions(projectRoot, definitions, authority) {
653
+ const { parseSync } = await import("vite");
654
+ return definitions.map((definition) => {
655
+ let source = "";
656
+ try {
657
+ source = readFileSync(definition.handler, "utf8");
658
+ } catch {}
659
+ return {
660
+ fields: [...describeRealtimeDefinitionSource(parseSync, definition.handler, source), {
661
+ label: "Authority",
662
+ value: authorityLabels[authority]
663
+ }],
664
+ file: relativeDefinitionFile(projectRoot, definition.handler),
665
+ name: definition.name,
666
+ source: definition.source
667
+ };
668
+ });
669
+ }
670
+ //#endregion
205
671
  //#region src/vite.ts
672
+ /**
673
+ * Lists Realtime Definitions with their document adapter, editor codec, identity, authorization,
674
+ * persistence, and room authority, read statically from each definition file.
675
+ */
676
+ async function inspectRealtimeDefinitions(options) {
677
+ return await summarizeRealtimeDefinitions(options.projectRoot, [...discoverRealtimeDefinitions(options.projectRoot, options.serverDirs), ...options.contributed ?? []], options.authority ?? "auto");
678
+ }
206
679
  function record(value) {
207
680
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
208
681
  }
@@ -225,6 +698,15 @@ function configureCloudflareRealtime(nitro) {
225
698
  cloudflare.wrangler = wrangler;
226
699
  nitro.cloudflare = cloudflare;
227
700
  }
701
+ /** Packages that share the Yjs runtime on the server. They must load as one module graph. */
702
+ const realtimeServerYjsPackages = [
703
+ "yjs",
704
+ "y-protocols",
705
+ "lib0",
706
+ "@tiptap/y-tiptap",
707
+ /^y-protocols\//,
708
+ /^lib0\//
709
+ ];
228
710
  function moduleSpecifier(from, to) {
229
711
  const value = relative(dirname(from), to).replaceAll("\\", "/");
230
712
  return value.startsWith(".") ? value : `./${value}`;
@@ -234,23 +716,65 @@ function applicationBaseURL(base) {
234
716
  }
235
717
  function hubRealtime(options = {}) {
236
718
  const importBase = options.importBase ?? "@vite-hub/realtime";
719
+ let inspectionRoot;
720
+ let inspectionServerDirs;
721
+ let inspectionAuthority = options.authority ?? "auto";
722
+ let inspectionContributed = [];
237
723
  return {
238
724
  name: "@vite-hub/realtime/vite",
239
725
  enforce: "pre",
726
+ vitehub: { inspect: () => ({ definitions: [{
727
+ kind: "realtime",
728
+ label: "Realtime",
729
+ list: () => inspectRealtimeDefinitions({
730
+ authority: inspectionAuthority,
731
+ projectRoot: inspectionRoot ?? resolveViteHubProjectRoot(process.cwd(), options),
732
+ serverDirs: inspectionServerDirs,
733
+ contributed: inspectionContributed
734
+ })
735
+ }] }) },
240
736
  async config(config, environment) {
241
737
  const root = resolveViteHubProjectRoot(resolve(config.root || process.cwd()), options);
242
738
  const serverDirs = config[VITEHUB_SERVER_DIRS];
243
- const definitions = discoverRealtimeDefinitions(root, serverDirs);
739
+ inspectionRoot = root;
740
+ inspectionServerDirs = serverDirs;
741
+ const discovered = discoverRealtimeDefinitions(root, serverDirs);
742
+ const nitro = { ...config.nitro };
743
+ const deploymentPreset = resolveHost({ nitro });
744
+ const provider = getHostingProvider(deploymentPreset);
745
+ const authority = options.authority || "auto";
746
+ const directory = resolve(root, ".vitehub/nitro/realtime");
747
+ const available = authority === "cloudflare" ? !deploymentPreset || deploymentPreset === "cloudflare" ? "cloudflare" : void 0 : authority === "auto" && provider === "cloudflare" ? "cloudflare" : authority === "memory" ? !deploymentPreset || deploymentPreset === "node" ? "memory" : void 0 : environment?.command !== "build" ? "memory" : void 0;
748
+ const contribution = available && options.contribute ? await options.contribute({
749
+ authority: available,
750
+ directory,
751
+ projectRoot: root,
752
+ serverDirs
753
+ }) : void 0;
754
+ const definitions = [...discovered, ...(contribution?.definitions ?? []).filter((definition) => !discovered.some((entry) => entry.name === definition.name)).map((definition) => ({
755
+ ...definition,
756
+ source: "contributed"
757
+ }))];
758
+ inspectionContributed = definitions.filter((definition) => definition.source === "contributed");
244
759
  if (definitions.length === 0) return;
245
760
  config.resolve = {
246
761
  ...config.resolve,
247
- dedupe: [...new Set([...config.resolve?.dedupe || [], "yjs"])]
762
+ dedupe: [.../* @__PURE__ */ new Set([...config.resolve?.dedupe || [], "yjs"])]
248
763
  };
764
+ const environments = { ...config.environments };
765
+ const nitroEnvironment = { ...environments.nitro };
766
+ const nitroResolve = { ...nitroEnvironment.resolve };
767
+ const noExternal = nitroResolve.noExternal;
768
+ if (noExternal !== true) {
769
+ nitroResolve.noExternal = [...Array.isArray(noExternal) ? noExternal : noExternal ? [noExternal] : [], ...realtimeServerYjsPackages];
770
+ nitroEnvironment.resolve = nitroResolve;
771
+ environments.nitro = nitroEnvironment;
772
+ config.environments = environments;
773
+ }
249
774
  config.define = {
250
775
  __VITEHUB_APP_BASE_URL__: JSON.stringify(applicationBaseURL(config.base)),
251
776
  ...config.define
252
777
  };
253
- const directory = resolve(root, ".vitehub/nitro/realtime");
254
778
  const registryFile = resolve(directory, "registry.mjs");
255
779
  const handlerFile = resolve(directory, "handler.ts");
256
780
  await mkdir(directory, { recursive: true });
@@ -261,26 +785,46 @@ function hubRealtime(options = {}) {
261
785
  "export default createRealtimeHandler(registry)",
262
786
  ""
263
787
  ].join("\n"))]);
264
- const nitro = { ...config.nitro || {} };
265
- const configuredPreset = nitro.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING;
266
- const deploymentPreset = deploymentPresetFromNitro(configuredPreset);
267
- const provider = getHostingProvider(configuredPreset);
268
- const authority = options.authority || "auto";
269
- if (authority === "cloudflare" && deploymentPreset && deploymentPreset !== "cloudflare") throw new Error(`[vitehub] Realtime authority "cloudflare" conflicts with the ${deploymentPreset} deployment preset.`);
270
- if (authority === "cloudflare" || authority === "auto" && provider === "cloudflare") configureCloudflareRealtime(nitro);
271
- else if (environment?.command === "build" && authority === "auto") throw new Error("[vitehub] Realtime production builds require one room authority. Deploy to Cloudflare Durable Objects or explicitly set realtime.authority to \"memory\" for a single-process server.");
272
- else if (authority === "memory" && deploymentPreset && deploymentPreset !== "node") throw new Error(`[vitehub] Realtime authority "memory" is single-process only and cannot use the ${deploymentPreset} deployment preset.`);
788
+ if (authority === "cloudflare" && deploymentPreset && deploymentPreset !== "cloudflare") throw realtimeErrorDiagnostics.REALTIME_AUTHORITY_CONFLICT({
789
+ authority: "cloudflare",
790
+ preset: deploymentPreset
791
+ });
792
+ let durablePlugin;
793
+ if (authority === "cloudflare" || authority === "auto" && provider === "cloudflare") {
794
+ inspectionAuthority = "cloudflare";
795
+ configureCloudflareRealtime(nitro);
796
+ durablePlugin = resolve(directory, "durable-object.mjs");
797
+ await writeFile(durablePlugin, [
798
+ "export default (nitroApp) => {",
799
+ " nitroApp.hooks.hook(\"cloudflare:durable:init\", (_durable, { state, env }) => {",
800
+ ` globalThis[Symbol.for(${JSON.stringify(realtimeDurableObjectKey)})] = { env, state }`,
801
+ " })",
802
+ "}",
803
+ ""
804
+ ].join("\n"));
805
+ } else if (environment?.command === "build" && authority === "auto") throw realtimeErrorDiagnostics.REALTIME_MISSING_AUTHORITY();
806
+ else if (authority === "memory" && deploymentPreset && deploymentPreset !== "node") throw realtimeErrorDiagnostics.REALTIME_AUTHORITY_CONFLICT({
807
+ authority: "memory",
808
+ preset: deploymentPreset
809
+ });
810
+ if (authority === "memory" || authority === "auto" && environment?.command !== "build" && inspectionAuthority !== "cloudflare") inspectionAuthority = "memory";
273
811
  nitro.features = {
274
812
  ...nitro.features,
275
813
  websocket: true
276
814
  };
277
- nitro.handlers = [...nitro.handlers || [], {
815
+ const kit = createNitroServerKit(nitro);
816
+ const { mount } = viteHubPageToolsBase(config);
817
+ kit.addHandler({
278
818
  handler: handlerFile,
279
- route: "/api/_vitehub/realtime/**"
280
- }];
819
+ lazy: true,
820
+ route: `${mount}/api/_vitehub/realtime/**`
821
+ });
822
+ if (durablePlugin) kit.addPlugin(durablePlugin);
823
+ for (const plugin of contribution?.plugins ?? []) kit.addPlugin(plugin);
824
+ Object.assign(nitro, kit.config);
281
825
  config.nitro = nitro;
282
826
  }
283
827
  };
284
828
  }
285
829
  //#endregion
286
- export { hubRealtime };
830
+ export { hubRealtime, inspectRealtimeDefinitions };