@vite-hub/realtime 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +71 -12
  2. package/dist/agent.d.ts +2 -0
  3. package/dist/agent.js +2 -0
  4. package/dist/bus-Bi-Ec414.js +476 -0
  5. package/dist/bus-protocol-wXkXW28q.d.ts +66 -0
  6. package/dist/bus.d.ts +85 -0
  7. package/dist/bus.js +2 -0
  8. package/dist/client/browser.js +53 -0
  9. package/dist/client.d.ts +25 -4
  10. package/dist/client.js +66 -8
  11. package/dist/conflict-Bg8vCisd.js +63 -0
  12. package/dist/{document-CtY6umWY.d.ts → document-DPaywuCO.d.ts} +2 -2
  13. package/dist/{document-BFaqcCAL.js → document-DjBrcgpY.js} +22 -10
  14. package/dist/durability.d.ts +10 -0
  15. package/dist/durability.js +46 -0
  16. package/dist/{layout-Br1aOL7o.js → editor-BM5-vHqf.js} +30 -36
  17. package/dist/error-diagnostics-B_66irmt.js +141 -0
  18. package/dist/index.d.ts +9 -4
  19. package/dist/index.js +3 -7
  20. package/dist/internal/runtime/unavailable.d.ts +5 -0
  21. package/dist/internal/runtime/unavailable.js +8 -0
  22. package/dist/keepalive-BCs-uXp4.js +33 -0
  23. package/dist/layout-DNaxppTZ.js +34 -0
  24. package/dist/{layout-WNWejwOY.d.ts → layout-fyQnhwCg.d.ts} +1 -1
  25. package/dist/{protocol-9ZDLEcSS.js → object-CzKyK0hX.js} +57 -58
  26. package/dist/presence-Tuy1y_l9.js +53 -0
  27. package/dist/request-BUwa359H.d.ts +48 -0
  28. package/dist/request-CWaHqW3R.js +192 -0
  29. package/dist/server.d.ts +64 -28
  30. package/dist/server.js +1002 -379
  31. package/dist/{types-Bw6-42Se.d.ts → types-1DVVG5ro.d.ts} +118 -14
  32. package/dist/vite.d.ts +109 -12
  33. package/dist/vite.js +469 -138
  34. package/dist/vue.d.ts +8 -5
  35. package/dist/vue.js +25 -11
  36. package/package.json +71 -19
  37. package/dist/application-path-CJblgbWK.js +0 -6
  38. package/dist/conflict-rguoaHlE.js +0 -34
  39. package/dist/durable-key-tnSw58ZK.js +0 -8
  40. package/dist/error-diagnostics-Cvm6vRXQ.js +0 -73
package/dist/vite.js CHANGED
@@ -1,9 +1,12 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cvm6vRXQ.js";
2
- import { t as realtimeDurableObjectKey } from "./durable-key-tnSw58ZK.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
+ import { o as realtimeNamespaceVariable, s as realtimePostgresUrlVariable } from "./bus-Bi-Ec414.js";
3
+ import { g as realtimeKeepalivePong, h as realtimeKeepalivePing, r as isRecordOrFunction, t as cloneRecord } from "./object-CzKyK0hX.js";
4
+ import availability from "./internal/runtime/unavailable.js";
3
5
  import { defineDiagnostics } from "nostics";
6
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
4
7
  import { mkdir, writeFile } from "node:fs/promises";
5
8
  import { basename, dirname, parse, relative, resolve } from "node:path";
6
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
9
+ import { fileURLToPath } from "node:url";
7
10
  import { tmpdir } from "node:os";
8
11
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
9
12
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
@@ -100,10 +103,16 @@ const relative$1 = function(from, to) {
100
103
  //#region ../internal/src/error-diagnostics.ts
101
104
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
102
105
  const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
103
- docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
106
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
104
107
  codes: {
105
- INTERNAL_R0012: dynamicError,
106
- INTERNAL_R0013: dynamicError,
108
+ INTERNAL_R0012: {
109
+ ...dynamicError,
110
+ fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
111
+ },
112
+ INTERNAL_R0013: {
113
+ ...dynamicError,
114
+ fix: "Check that the provider token can manage the resource in the path that the message names. `error.kind` and `error.codes` hold the provider failure."
115
+ },
107
116
  INTERNAL_R0014: {
108
117
  why: ({ path }) => `Cannot read Provision State from "${path}".`,
109
118
  fix: "Check file access and restore valid JSON while preserving existing resource IDs."
@@ -121,60 +130,101 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
121
130
  why: ({ message }) => message === void 0 ? "" : String(message)
122
131
  },
123
132
  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.",
133
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
125
134
  why: ({ message }) => message === void 0 ? "" : String(message)
126
135
  },
127
136
  INTERNAL_R0023: {
128
137
  fix: "Ask for access to the section of this operation.",
129
138
  why: ({ message }) => message === void 0 ? "" : String(message)
130
139
  },
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,
140
+ INTERNAL_B0001: {
141
+ ...dynamicError,
142
+ fix: "Give the resource that the message names another name or binding in the `vitehub()` options of its feature, so that two different Cloudflare resources do not share one name."
143
+ },
144
+ INTERNAL_B0015: {
145
+ ...dynamicError,
146
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
147
+ },
148
+ INTERNAL_B0016: {
149
+ ...dynamicError,
150
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
151
+ },
152
+ INTERNAL_B0017: {
153
+ ...dynamicError,
154
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
155
+ },
156
+ INTERNAL_B0018: {
157
+ ...dynamicError,
158
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
159
+ },
160
+ INTERNAL_B0019: {
161
+ ...dynamicError,
162
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
163
+ },
164
+ INTERNAL_B0020: {
165
+ ...dynamicError,
166
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
167
+ },
168
+ INTERNAL_B0021: {
169
+ ...dynamicError,
170
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
171
+ },
172
+ INTERNAL_B0022: {
173
+ ...dynamicError,
174
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
175
+ },
176
+ INTERNAL_B0025: {
177
+ ...dynamicError,
178
+ fix: "Replace the `new URL(\"./...\", import.meta.url)` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` of that file."
179
+ },
180
+ INTERNAL_B0026: {
181
+ ...dynamicError,
182
+ fix: "Replace the computed `import()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` or with `import(\"<literal path>\")`."
183
+ },
184
+ INTERNAL_B0027: {
185
+ ...dynamicError,
186
+ fix: "Replace the computed `require()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import`."
187
+ },
188
+ INTERNAL_B0028: {
189
+ ...dynamicError,
190
+ fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
191
+ },
192
+ INTERNAL_B0029: {
193
+ ...dynamicError,
194
+ fix: "Stop the other builds that write the same Deno output folder, delete the `.vitehub-lock` folder next to that output folder, such as `.output.vitehub-lock`, then build again."
195
+ },
196
+ INTERNAL_B0031: {
197
+ ...dynamicError,
198
+ fix: "Import `./schedule/deno-cron.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./schedule/deno-cron.mjs\", import.meta.url).href)` outside any condition."
199
+ },
200
+ INTERNAL_B0032: {
201
+ ...dynamicError,
202
+ fix: "Import `./server/index.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./server/index.mjs\", import.meta.url).href)` outside any condition."
203
+ },
204
+ INTERNAL_B0035: {
205
+ ...dynamicError,
206
+ fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
207
+ },
208
+ INTERNAL_B0039: {
209
+ ...dynamicError,
210
+ fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
211
+ },
212
+ INTERNAL_B0040: {
213
+ ...dynamicError,
214
+ fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
215
+ },
216
+ INTERNAL_B0043: {
217
+ ...dynamicError,
218
+ fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
219
+ },
220
+ INTERNAL_B0046: {
221
+ ...dynamicError,
222
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
223
+ },
224
+ INTERNAL_B0047: {
225
+ ...dynamicError,
226
+ fix: "Correct the `package.json` file that the message names so that it holds one JSON object, or run `pnpm install` again to restore an installed package."
227
+ },
178
228
  INTERNAL_B0048: {
179
229
  fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
180
230
  why: ({ message }) => message === void 0 ? "" : String(message)
@@ -187,6 +237,14 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
187
237
  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
238
  why: ({ message }) => message === void 0 ? "" : String(message)
189
239
  },
240
+ INTERNAL_B0051: {
241
+ why: ({ field, generated, name, path, project, scope }) => `The Cloudflare ${path} entry "${name}"${scope} is written by ViteHub and by the project's Wrangler config with a different ${field}: ${generated} and ${project}.`,
242
+ fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
243
+ },
244
+ INTERNAL_B0052: {
245
+ why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
246
+ fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
247
+ },
190
248
  INTERNAL_R0025: {
191
249
  fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
192
250
  why: ({ message }) => message === void 0 ? "" : String(message)
@@ -195,25 +253,121 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
195
253
  why: "The server parsed a destructive operation that the CLI did not confirm.",
196
254
  fix: "Review the operation, then run it again with --yes to confirm the change."
197
255
  },
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
256
+ INTERNAL_C0001: {
257
+ ...dynamicError,
258
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
259
+ },
260
+ INTERNAL_C0002: {
261
+ ...dynamicError,
262
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
263
+ },
264
+ INTERNAL_R0001: {
265
+ ...dynamicError,
266
+ fix: "Set `host` in `vitehub()`, or in the `vitehub` options of `nuxt.config.ts`, to `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. Or remove `host` so that ViteHub finds the host from the environment."
267
+ },
268
+ INTERNAL_R0002: {
269
+ ...dynamicError,
270
+ fix: "Stop using the feature that the message names, or set `host` in `vitehub()` to a host that provides it. For Blob, you can also set `blob: { driver: \"s3\" }` with a remote store."
271
+ },
272
+ INTERNAL_R0004: {
273
+ ...dynamicError,
274
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
275
+ },
276
+ INTERNAL_R0005: {
277
+ ...dynamicError,
278
+ fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
279
+ },
280
+ INTERNAL_R0006: {
281
+ ...dynamicError,
282
+ fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
283
+ },
284
+ INTERNAL_R0007: {
285
+ ...dynamicError,
286
+ fix: "Set `maxResponseBytes` of the HTTP request to a positive integer no greater than the limit that the message names, or remove it to use the default."
287
+ },
288
+ INTERNAL_R0008: {
289
+ ...dynamicError,
290
+ fix: "Make the value that the message names match its schema: the input, query, or body that you send, or the response schema that you declare for the request."
291
+ },
292
+ INTERNAL_R0009: {
293
+ ...dynamicError,
294
+ fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
295
+ },
296
+ INTERNAL_R0010: {
297
+ ...dynamicError,
298
+ fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
299
+ },
300
+ INTERNAL_R0011: {
301
+ ...dynamicError,
302
+ fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
303
+ },
304
+ INTERNAL_CONSOLE_KEY_NAME_INVALID: {
305
+ why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
306
+ fix: "Name the Console key with 1 to 64 characters from A-Z, 0-9, and _, such as `CI`. The app reads its public key from `VITEHUB_CONSOLE_KEY_<NAME>`."
307
+ },
308
+ INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
309
+ why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
310
+ fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
311
+ },
312
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
313
+ why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
314
+ fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
315
+ },
316
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
317
+ why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
318
+ fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
319
+ },
320
+ INTERNAL_FORGE_NOT_INSTALLED: {
321
+ why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
322
+ fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
323
+ },
324
+ INTERNAL_MCP_ARGUMENTS_INVALID: {
325
+ why: ({ detail }) => detail,
326
+ fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
327
+ },
328
+ INTERNAL_MCP_METHOD_FAILED: {
329
+ why: ({ name }) => `${name} failed on the server.`,
330
+ fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
331
+ },
332
+ INTERNAL_MCP_RESOURCE_NOT_FOUND: {
333
+ why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
334
+ fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
335
+ },
336
+ INTERNAL_PRESET_OPTION_UNKNOWN: {
337
+ why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
338
+ fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
339
+ },
340
+ INTERNAL_PRESET_TUPLE_INVALID: {
341
+ why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
342
+ fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
343
+ },
344
+ INTERNAL_SECRET_PURPOSE_MISSING: {
345
+ why: "[vitehub] A derived secret requires a purpose.",
346
+ fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
347
+ },
348
+ INTERNAL_SECRET_TOO_SHORT: {
349
+ why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
350
+ fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
351
+ },
352
+ INTERNAL_SQLITE_ARGUMENT_INVALID: {
353
+ why: ({ value }) => value === "undefined" ? "undefined cannot be passed as argument to the database" : "Only finite numbers (not Infinity or NaN) can be passed as arguments",
354
+ fix: "Pass query arguments as finite numbers, strings, booleans, bigints, dates, byte arrays, or null. Replace undefined with null, and check numbers with `Number.isFinite()` before the query."
355
+ },
356
+ INTERNAL_SQLITE_INTEGER_UNSAFE: {
357
+ why: "Received integer which cannot be safely represented as a JavaScript number",
358
+ fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
359
+ },
360
+ INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
361
+ why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
362
+ fix: "Ask for the `draft-07`, `draft-2020-12`, or `openapi-3.0` JSON Schema target, or pass one of them as `withValibotJsonSchema(schema, { target })`."
363
+ }
211
364
  }
212
365
  });
213
366
  //#endregion
214
367
  //#region ../internal/src/definition-catalog.ts
215
368
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
216
369
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
370
+ const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
217
371
  const ignoredDirs = /* @__PURE__ */ new Set([
218
372
  "node_modules",
219
373
  "dist",
@@ -259,8 +413,12 @@ function listMatchingFiles(root, predicate, options = {}) {
259
413
  }
260
414
  return files.sort();
261
415
  }
416
+ /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
417
+ function isDefinitionSourceFile(name) {
418
+ return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
419
+ }
262
420
  function listSourceFiles(root, options = {}) {
263
- return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
421
+ return listMatchingFiles(root, isDefinitionSourceFile, options);
264
422
  }
265
423
  function normalizePathDefinitionName(rootDir, file) {
266
424
  return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
@@ -339,6 +497,12 @@ function createRuntimeRegistryContents(registryFile, definitions) {
339
497
  ].join("\n");
340
498
  }
341
499
  //#endregion
500
+ //#region ../internal/src/durability.ts
501
+ /** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
502
+ function durabilityModuleFile(importMetaUrl) {
503
+ return fileURLToPath(new URL(importMetaUrl.endsWith(".ts") ? "./durability.ts" : "./durability.js", importMetaUrl));
504
+ }
505
+ //#endregion
342
506
  //#region ../internal/src/build/vite.ts
343
507
  const projectRootDirectoryMarkers = [
344
508
  ["server", "agents"],
@@ -361,6 +525,10 @@ const projectRootFileMarkers = [
361
525
  * Later entries are Nuxt layers in Nuxt priority order.
362
526
  */
363
527
  const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
528
+ /** Reports a Vite config hook call for a production build. `nuxt prepare` is not a build: it only writes types. */
529
+ function isProductionBuild(config, environment) {
530
+ return environment?.command === "build" && Reflect.get(config, "__vitehubPrepare") !== true;
531
+ }
364
532
  function resolveViteHubProjectRoot(root, options = {}) {
365
533
  const resolvedRoot = resolve(root);
366
534
  const temporaryRoot = resolve(tmpdir());
@@ -454,15 +622,12 @@ function viteHubPageToolsBase(config, env = process.env) {
454
622
  function cloneArray(value) {
455
623
  return Array.isArray(value) ? [...value] : [];
456
624
  }
457
- function isRecord(value) {
458
- return Object(value) === value && !Array.isArray(value);
459
- }
460
625
  function sameHandler(left, right) {
461
626
  return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
462
627
  }
463
628
  /** Create a Nitro 3 configuration builder for generated ViteHub output. */
464
629
  function createNitroServerKit(value = {}) {
465
- const config = isRecord(value) ? { ...value } : {};
630
+ const config = isRecordOrFunction(value) ? { ...value } : {};
466
631
  const handlers = cloneArray(config.handlers);
467
632
  const plugins = cloneArray(config.plugins);
468
633
  config.handlers = handlers;
@@ -470,7 +635,7 @@ function createNitroServerKit(value = {}) {
470
635
  return {
471
636
  config,
472
637
  addHandler(handler, position = "end") {
473
- if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
638
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
474
639
  if (position === "start") handlers.unshift({ ...handler });
475
640
  else handlers.push({ ...handler });
476
641
  },
@@ -481,7 +646,8 @@ function createNitroServerKit(value = {}) {
481
646
  }
482
647
  };
483
648
  }
484
- function deploymentPresetFromNitro(value) {
649
+ /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
650
+ function hostFromNitroPreset(value) {
485
651
  const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
486
652
  if (!normalized) return;
487
653
  if (normalized.startsWith("cloudflare")) return "cloudflare";
@@ -494,7 +660,7 @@ function deploymentPresetFromNitro(value) {
494
660
  //#region ../internal/src/hosting.ts
495
661
  /**
496
662
  * 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`.
663
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOST`.
498
664
  * Empty values are skipped.
499
665
  */
500
666
  function resolveHostPreset(input = {}) {
@@ -505,17 +671,45 @@ function resolveHostPreset(input = {}) {
505
671
  input.hosting,
506
672
  env.NITRO_PRESET,
507
673
  env.SERVER_PRESET,
508
- env.VITEHUB_HOSTING
674
+ env.VITEHUB_HOST
509
675
  ]) if (typeof value === "string" && value.trim()) return value.trim();
510
676
  }
511
677
  /** Returns the host that this build targets: `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. */
512
678
  function resolveHost(input = {}) {
513
- return deploymentPresetFromNitro(resolveHostPreset(input));
679
+ return hostFromNitroPreset(resolveHostPreset(input));
514
680
  }
515
- /** Narrows a preset or host name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
681
+ /** Narrows a ViteHub host or Nitro preset name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
516
682
  function getHostingProvider(hosting) {
517
- const preset = deploymentPresetFromNitro(hosting);
518
- if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
683
+ const host = hostFromNitroPreset(hosting);
684
+ if (host === "cloudflare" || host === "netlify" || host === "vercel") return host;
685
+ }
686
+ //#endregion
687
+ //#region src/deployment-env.ts
688
+ const owners = ["realtime"];
689
+ function entry(names, required, secret, hasDefault = false) {
690
+ return {
691
+ names,
692
+ required,
693
+ secret,
694
+ hasDefault,
695
+ owners
696
+ };
697
+ }
698
+ /**
699
+ * The variables that Realtime reads on the deployed host. A Node server picks its bus at boot: `REDIS_URL`, then
700
+ * `REALTIME_POSTGRES_URL`, then a Postgres Default Database, else memory. An explicit `redis` or `postgres` driver
701
+ * requires its connection. `REALTIME_NAMESPACE` is optional. Durable Objects on Cloudflare and `memory` read none.
702
+ */
703
+ function realtimeDeploymentEnv(input, context) {
704
+ if (context.host !== "node" || input.driver === "cloudflare" || input.driver === "memory") return [];
705
+ const namespace = entry([realtimeNamespaceVariable], false, false, true);
706
+ if (input.driver === "redis") return [entry(["REDIS_URL"], true, true), namespace];
707
+ const postgres = entry([realtimePostgresUrlVariable], input.driver === "postgres" && !input.postgresDatabase, true, input.postgresDatabase);
708
+ return input.driver === "postgres" ? [postgres, namespace] : [
709
+ entry(["REDIS_URL"], false, true),
710
+ postgres,
711
+ namespace
712
+ ];
519
713
  }
520
714
  //#endregion
521
715
  //#region src/discovery.ts
@@ -539,11 +733,14 @@ new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\
539
733
  new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
540
734
  //#endregion
541
735
  //#region src/inspect.ts
542
- const authorityLabels = {
543
- auto: "auto: Cloudflare Durable Objects on Cloudflare, memory in development, build error elsewhere",
736
+ const driverLabels = {
737
+ auto: "auto: Cloudflare Durable Objects on Cloudflare, memory in development, shared rooms on a Node server, build error elsewhere",
544
738
  cloudflare: "cloudflare: one Durable Object per document, Yjs state in SQLite",
545
739
  memory: "memory: one Node process, rooms lost on restart",
546
- unsupported: "none: this host has no Realtime room authority"
740
+ node: "auto on Node: picked when the server starts. Redis with REDIS_URL, else Postgres on the Default Database or REALTIME_POSTGRES_URL, else memory in one process",
741
+ postgres: "postgres: a room in each Node instance, shared through Postgres LISTEN/NOTIFY on the Default Database or REALTIME_POSTGRES_URL",
742
+ redis: "redis: a room in each Node instance, shared through Redis pub/sub (REDIS_URL)",
743
+ unsupported: "none: this host has no Realtime driver"
547
744
  };
548
745
  function propertyName(property) {
549
746
  if (property.type !== "Property") return;
@@ -621,7 +818,24 @@ function describeRealtimeDefinitionSource(parse, file, source) {
621
818
  const values = properties(object);
622
819
  const editor = values.get("editor");
623
820
  const auth = literal(values.get("auth")) === true;
821
+ const publicAccess = literal(values.get("access")) === "public";
822
+ const authorization = (rule) => values.has("authorize") ? rule : publicAccess ? "public: anyone may read and write" : auth ? "every identified user" : "missing: the server rejects this definition";
624
823
  const perDocument = editor?.type === "ArrowFunctionExpression" || editor?.type === "FunctionExpression";
824
+ const identity = {
825
+ label: "Identity",
826
+ value: values.has("identify") ? `identify()${auth ? ", required" : ""}` : auth ? "ViteHub Auth session, required" : "anonymous; presence names are client-asserted"
827
+ };
828
+ if (literal(values.get("document")) === false) return [
829
+ {
830
+ label: "Document",
831
+ value: "none: presence only, nothing stored"
832
+ },
833
+ identity,
834
+ {
835
+ label: "Authorization",
836
+ value: authorization("authorize() per room, read only")
837
+ }
838
+ ];
625
839
  return [
626
840
  {
627
841
  label: "Document",
@@ -631,13 +845,10 @@ function describeRealtimeDefinitionSource(parse, file, source) {
631
845
  label: "Editor",
632
846
  value: editor ? perDocument ? "custom codec per document" : `custom codec${editor.type === "Identifier" ? ` (${editor.name})` : ""}` : "built-in Markdown kit"
633
847
  },
634
- {
635
- label: "Identity",
636
- value: values.has("identify") ? `identify()${auth ? ", required" : ""}` : auth ? "ViteHub Auth session, required" : "anonymous; presence names are client-asserted"
637
- },
848
+ identity,
638
849
  {
639
850
  label: "Authorization",
640
- value: values.has("authorize") ? "authorize() per document and mode" : "every connection may read and write"
851
+ value: authorization("authorize() per document and mode")
641
852
  },
642
853
  {
643
854
  label: "Persistence",
@@ -649,7 +860,7 @@ function describeRealtimeDefinitionSource(parse, file, source) {
649
860
  }
650
861
  ];
651
862
  }
652
- async function summarizeRealtimeDefinitions(projectRoot, definitions, authority) {
863
+ async function summarizeRealtimeDefinitions(projectRoot, definitions, driver) {
653
864
  const { parseSync } = await import("vite");
654
865
  return definitions.map((definition) => {
655
866
  let source = "";
@@ -658,8 +869,8 @@ async function summarizeRealtimeDefinitions(projectRoot, definitions, authority)
658
869
  } catch {}
659
870
  return {
660
871
  fields: [...describeRealtimeDefinitionSource(parseSync, definition.handler, source), {
661
- label: "Authority",
662
- value: authorityLabels[authority]
872
+ label: "Driver",
873
+ value: driverLabels[driver]
663
874
  }],
664
875
  file: relativeDefinitionFile(projectRoot, definition.handler),
665
876
  name: definition.name,
@@ -671,26 +882,23 @@ async function summarizeRealtimeDefinitions(projectRoot, definitions, authority)
671
882
  //#region src/vite.ts
672
883
  /**
673
884
  * Lists Realtime Definitions with their document adapter, editor codec, identity, authorization,
674
- * persistence, and room authority, read statically from each definition file.
885
+ * persistence, and driver, read statically from each definition file.
675
886
  */
676
887
  async function inspectRealtimeDefinitions(options) {
677
- return await summarizeRealtimeDefinitions(options.projectRoot, [...discoverRealtimeDefinitions(options.projectRoot, options.serverDirs), ...options.contributed ?? []], options.authority ?? "auto");
678
- }
679
- function record(value) {
680
- return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
888
+ return await summarizeRealtimeDefinitions(options.projectRoot, [...discoverRealtimeDefinitions(options.projectRoot, options.serverDirs), ...options.contributed ?? []], options.driver ?? "auto");
681
889
  }
682
890
  function configureCloudflareRealtime(nitro) {
683
- nitro.preset = "cloudflare-durable";
684
- const cloudflare = record(nitro.cloudflare);
685
- const wrangler = record(cloudflare.wrangler);
686
- const durableObjects = record(wrangler.durable_objects);
891
+ nitro.preset = "cloudflare-module";
892
+ const cloudflare = cloneRecord(nitro.cloudflare);
893
+ const wrangler = cloneRecord(cloudflare.wrangler);
894
+ const durableObjects = cloneRecord(wrangler.durable_objects);
687
895
  const bindings = Array.isArray(durableObjects.bindings) ? durableObjects.bindings : [];
688
- if (!bindings.some((binding) => record(binding).name === "$DurableObject")) durableObjects.bindings = [...bindings, {
896
+ if (!bindings.some((binding) => cloneRecord(binding).name === "$DurableObject")) durableObjects.bindings = [...bindings, {
689
897
  class_name: "$DurableObject",
690
898
  name: "$DurableObject"
691
899
  }];
692
900
  const migrations = Array.isArray(wrangler.migrations) ? wrangler.migrations : [];
693
- if (!migrations.some((migration) => record(migration).tag === "vitehub-realtime-v1")) wrangler.migrations = [...migrations, {
901
+ if (!migrations.some((migration) => cloneRecord(migration).tag === "vitehub-realtime-v1")) wrangler.migrations = [...migrations, {
694
902
  new_sqlite_classes: ["$DurableObject"],
695
903
  tag: "vitehub-realtime-v1"
696
904
  }];
@@ -714,25 +922,99 @@ function moduleSpecifier(from, to) {
714
922
  function applicationBaseURL(base) {
715
923
  return base?.startsWith("/") && !base.startsWith("//") ? base : "/";
716
924
  }
925
+ const databaseVitePluginName = "@vite-hub/database/vite";
926
+ function findDatabasePlugin(plugins) {
927
+ for (const plugin of plugins ?? []) if (Array.isArray(plugin)) {
928
+ const found = findDatabasePlugin(plugin);
929
+ if (found) return found;
930
+ } else if (plugin && typeof plugin === "object" && "name" in plugin && plugin.name === databaseVitePluginName) return plugin;
931
+ }
932
+ /** Whether the Database integration resolved the Default Database on Postgres. The Postgres bus then uses its client. */
933
+ function hasPostgresDefaultDatabase(plugin) {
934
+ return plugin?.api?.getConfig?.()?.databases.default?.dialect === "postgresql";
935
+ }
936
+ /**
937
+ * The handler and the Nitro plugin of a Node build. `database` is the module that exports the app's `databases`, when
938
+ * the Default Database is on Postgres: the bus then borrows the postgres.js client of that Database.
939
+ */
940
+ function renderNodeFiles(input) {
941
+ const { busPlugin, database, handlerFile, importBase, namespace, nodeDriver, registryFile } = input;
942
+ const busOptions = `, { ${database ? `databases: () => import(${JSON.stringify(database)}).then(module => module.databases), ` : ""}namespace: ${JSON.stringify(namespace)} }`;
943
+ const logOptions = `{ ${database ? "database: true, " : ""}namespace: ${JSON.stringify(namespace)} }`;
944
+ const handler = [
945
+ `import registry from ${JSON.stringify(moduleSpecifier(handlerFile, registryFile))}`,
946
+ `import { createRealtimeHandler } from ${JSON.stringify(`${importBase}/server`)}`,
947
+ ...nodeDriver ? [
948
+ `import { useRealtimeBus } from ${JSON.stringify(`${importBase}/bus`)}`,
949
+ "",
950
+ "// Shares rooms with the other instances of this app. The server picks the bus when it starts.",
951
+ `export default createRealtimeHandler(registry, { bus: () => useRealtimeBus(${JSON.stringify(nodeDriver)}${busOptions}) })`
952
+ ] : ["", "export default createRealtimeHandler(registry)"],
953
+ ""
954
+ ].join("\n");
955
+ if (!busPlugin || !nodeDriver) return [[handlerFile, handler]];
956
+ return [[handlerFile, handler], [busPlugin, [
957
+ `import { closeRealtimeBuses, logRealtimeNodeDriver } from ${JSON.stringify(`${importBase}/bus`)}`,
958
+ "",
959
+ "export default (nitroApp) => {",
960
+ " // Prints where the rooms of this server live.",
961
+ ` logRealtimeNodeDriver(${JSON.stringify(nodeDriver)}, ${logOptions})`,
962
+ " // Removes this instance's presence from the other instances, and lets the process exit. A borrowed Database client stays open.",
963
+ " nitroApp.hooks.hook(\"close\", () => closeRealtimeBuses())",
964
+ "}",
965
+ ""
966
+ ].join("\n")]];
967
+ }
968
+ /** The app name: the `name` in the root `package.json`, else the root folder name. */
969
+ function defaultNamespace(root) {
970
+ try {
971
+ const name = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).name;
972
+ if (typeof name === "string" && name.trim()) return name.trim();
973
+ } catch {}
974
+ return basename(root) || "default";
975
+ }
976
+ const realtimeAvailabilityId = "#vitehub/realtime/availability";
977
+ const resolvedRealtimeAvailabilityId = `\0${realtimeAvailabilityId}`;
717
978
  function hubRealtime(options = {}) {
979
+ if (options.driver === void 0 && Object.hasOwn(options, "authority")) {
980
+ const authority = options.authority;
981
+ throw realtimeErrorDiagnostics.REALTIME_RENAMED_AUTHORITY_KEY({ value: JSON.stringify(authority) ?? String(authority) });
982
+ }
718
983
  const importBase = options.importBase ?? "@vite-hub/realtime";
719
984
  let inspectionRoot;
720
985
  let inspectionServerDirs;
721
- let inspectionAuthority = options.authority ?? "auto";
986
+ let inspectionDriver = options.driver ?? "auto";
722
987
  let inspectionContributed = [];
988
+ let hasRoomDriver = false;
989
+ const databaseImport = options.databaseImport ?? "@vite-hub/database/drizzle";
990
+ let databasePlugin;
991
+ let postgresDatabase = false;
992
+ let nodeWrite;
723
993
  return {
724
994
  name: "@vite-hub/realtime/vite",
725
995
  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
- }] }) },
996
+ api: { deploymentEnv: (context) => hasRoomDriver ? realtimeDeploymentEnv({
997
+ driver: options.driver ?? "auto",
998
+ postgresDatabase
999
+ }, context) : [] },
1000
+ vitehub: {
1001
+ durability: () => hasRoomDriver ? [{
1002
+ export: "realtimeDurability",
1003
+ input: { driver: inspectionDriver },
1004
+ module: durabilityModuleFile(import.meta.url),
1005
+ primitive: "realtime"
1006
+ }] : [],
1007
+ inspect: () => ({ definitions: [{
1008
+ kind: "realtime",
1009
+ label: "Realtime",
1010
+ list: () => inspectRealtimeDefinitions({
1011
+ driver: inspectionDriver,
1012
+ projectRoot: inspectionRoot ?? resolveViteHubProjectRoot(process.cwd(), options),
1013
+ serverDirs: inspectionServerDirs,
1014
+ contributed: inspectionContributed
1015
+ })
1016
+ }] })
1017
+ },
736
1018
  async config(config, environment) {
737
1019
  const root = resolveViteHubProjectRoot(resolve(config.root || process.cwd()), options);
738
1020
  const serverDirs = config[VITEHUB_SERVER_DIRS];
@@ -740,13 +1022,17 @@ function hubRealtime(options = {}) {
740
1022
  inspectionServerDirs = serverDirs;
741
1023
  const discovered = discoverRealtimeDefinitions(root, serverDirs);
742
1024
  const nitro = { ...config.nitro };
743
- const deploymentPreset = resolveHost({ nitro });
744
- const provider = getHostingProvider(deploymentPreset);
745
- const authority = options.authority || "auto";
1025
+ const host = resolveHost({ nitro });
1026
+ const provider = getHostingProvider(host);
1027
+ const driver = options.driver || "auto";
746
1028
  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;
1029
+ const build = isProductionBuild(config, environment);
1030
+ const node = !host || host === "node";
1031
+ const nodeDriver = !build || !node ? void 0 : driver === "postgres" || driver === "redis" ? driver : driver === "auto" && provider !== "cloudflare" ? "auto" : void 0;
1032
+ const available = driver === "cloudflare" ? !host || host === "cloudflare" ? "cloudflare" : void 0 : driver === "auto" && provider === "cloudflare" ? "cloudflare" : driver !== "auto" ? node ? "memory" : void 0 : !build || nodeDriver ? "memory" : void 0;
1033
+ hasRoomDriver = Boolean(available);
748
1034
  const contribution = available && options.contribute ? await options.contribute({
749
- authority: available,
1035
+ driver: available,
750
1036
  directory,
751
1037
  projectRoot: root,
752
1038
  serverDirs
@@ -777,37 +1063,56 @@ function hubRealtime(options = {}) {
777
1063
  };
778
1064
  const registryFile = resolve(directory, "registry.mjs");
779
1065
  const handlerFile = resolve(directory, "handler.ts");
1066
+ const busPlugin = nodeDriver ? resolve(directory, "bus.mjs") : void 0;
1067
+ databasePlugin = findDatabasePlugin(config.plugins) ?? databasePlugin;
1068
+ postgresDatabase = !!nodeDriver && hasPostgresDefaultDatabase(databasePlugin);
1069
+ const namespace = options.namespace?.trim() || defaultNamespace(root);
1070
+ const nodeFiles = (files) => renderNodeFiles({
1071
+ ...files,
1072
+ database: postgresDatabase ? databaseImport : void 0,
1073
+ importBase,
1074
+ namespace,
1075
+ nodeDriver
1076
+ });
1077
+ nodeWrite = nodeDriver ? {
1078
+ busPlugin,
1079
+ handlerFile,
1080
+ namespace,
1081
+ nodeDriver,
1082
+ postgres: postgresDatabase,
1083
+ registryFile
1084
+ } : void 0;
780
1085
  await mkdir(directory, { recursive: true });
781
- await Promise.all([writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions)), writeFile(handlerFile, [
782
- `import registry from ${JSON.stringify(moduleSpecifier(handlerFile, registryFile))}`,
783
- `import { createRealtimeHandler } from ${JSON.stringify(`${importBase}/server`)}`,
784
- "",
785
- "export default createRealtimeHandler(registry)",
786
- ""
787
- ].join("\n"))]);
788
- if (authority === "cloudflare" && deploymentPreset && deploymentPreset !== "cloudflare") throw realtimeErrorDiagnostics.REALTIME_AUTHORITY_CONFLICT({
789
- authority: "cloudflare",
790
- preset: deploymentPreset
1086
+ await Promise.all([writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions)), ...nodeFiles({
1087
+ busPlugin,
1088
+ handlerFile,
1089
+ registryFile
1090
+ }).map(([file, contents]) => writeFile(file, contents))]);
1091
+ if (driver === "cloudflare" && host && host !== "cloudflare") throw realtimeErrorDiagnostics.REALTIME_DRIVER_CONFLICT({
1092
+ driver: "cloudflare",
1093
+ host
791
1094
  });
792
1095
  let durablePlugin;
793
- if (authority === "cloudflare" || authority === "auto" && provider === "cloudflare") {
794
- inspectionAuthority = "cloudflare";
1096
+ if (driver === "cloudflare" || driver === "auto" && provider === "cloudflare") {
1097
+ inspectionDriver = "cloudflare";
795
1098
  configureCloudflareRealtime(nitro);
796
1099
  durablePlugin = resolve(directory, "durable-object.mjs");
797
1100
  await writeFile(durablePlugin, [
798
1101
  "export default (nitroApp) => {",
799
- " nitroApp.hooks.hook(\"cloudflare:durable:init\", (_durable, { state, env }) => {",
800
- ` globalThis[Symbol.for(${JSON.stringify(realtimeDurableObjectKey)})] = { env, state }`,
1102
+ " nitroApp.hooks.hook(\"cloudflare:durable:init\", (_durable, { state }) => {",
1103
+ " // Answer the clients' keepalive without waking the Durable Object from hibernation.",
1104
+ ` if (typeof WebSocketRequestResponsePair === "function") state.setWebSocketAutoResponse(new WebSocketRequestResponsePair(${JSON.stringify(realtimeKeepalivePing)}, ${JSON.stringify(realtimeKeepalivePong)}))`,
801
1105
  " })",
802
1106
  "}",
803
1107
  ""
804
1108
  ].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
1109
+ } else if (build && driver === "auto" && !nodeDriver) throw realtimeErrorDiagnostics.REALTIME_MISSING_DRIVER();
1110
+ else if (driver !== "auto" && !node && host) throw realtimeErrorDiagnostics.REALTIME_DRIVER_CONFLICT({
1111
+ driver,
1112
+ host
809
1113
  });
810
- if (authority === "memory" || authority === "auto" && environment?.command !== "build" && inspectionAuthority !== "cloudflare") inspectionAuthority = "memory";
1114
+ if (nodeDriver) inspectionDriver = nodeDriver === "auto" ? "node" : nodeDriver;
1115
+ else if (driver === "memory" || driver === "postgres" || driver === "redis" || driver === "auto" && !build && inspectionDriver !== "cloudflare") inspectionDriver = "memory";
811
1116
  nitro.features = {
812
1117
  ...nitro.features,
813
1118
  websocket: true
@@ -820,11 +1125,37 @@ function hubRealtime(options = {}) {
820
1125
  route: `${mount}/api/_vitehub/realtime/**`
821
1126
  });
822
1127
  if (durablePlugin) kit.addPlugin(durablePlugin);
1128
+ if (busPlugin) kit.addPlugin(busPlugin);
823
1129
  for (const plugin of contribution?.plugins ?? []) kit.addPlugin(plugin);
824
1130
  Object.assign(nitro, kit.config);
825
1131
  config.nitro = nitro;
1132
+ },
1133
+ async buildStart() {
1134
+ const databaseConfig = databasePlugin?.api?.getConfig?.();
1135
+ if (!databaseConfig || !nodeWrite) return;
1136
+ postgresDatabase = databaseConfig.databases.default?.dialect === "postgresql";
1137
+ if (nodeWrite.postgres === postgresDatabase) return;
1138
+ nodeWrite.postgres = postgresDatabase;
1139
+ const files = renderNodeFiles({
1140
+ ...nodeWrite,
1141
+ database: postgresDatabase ? databaseImport : void 0,
1142
+ importBase
1143
+ });
1144
+ await Promise.all(files.map(([file, contents]) => writeFile(file, contents)));
1145
+ },
1146
+ resolveId: {
1147
+ filter: { id: /^#vitehub\/realtime\/availability$/ },
1148
+ handler(id) {
1149
+ if (id === realtimeAvailabilityId) return resolvedRealtimeAvailabilityId;
1150
+ }
1151
+ },
1152
+ load: {
1153
+ filter: { id: /^\0#vitehub\/realtime\/availability$/ },
1154
+ handler(id) {
1155
+ if (id === resolvedRealtimeAvailabilityId) return hasRoomDriver ? "export default { available: true }\n" : `export default ${JSON.stringify(availability)}\n`;
1156
+ }
826
1157
  }
827
1158
  };
828
1159
  }
829
1160
  //#endregion
830
- export { hubRealtime, inspectRealtimeDefinitions };
1161
+ export { discoverRealtimeDefinitions, hubRealtime, inspectRealtimeDefinitions };