@vite-hub/realtime 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 (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/index.js CHANGED
@@ -1,8 +1,4 @@
1
- import { n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-rguoaHlE.js";
2
- import { a as realtimeMarkdownEditor, i as defineRealtimeEditor, n as realtimeDocumentLayout, r as createRealtimeEditorExtensions, t as readRealtimeStatus } from "./layout-Br1aOL7o.js";
3
- //#region src/definition.ts
4
- function defineRealtime(definition) {
5
- return definition;
6
- }
7
- //#endregion
1
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
2
+ import { a as defineRealtime, n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-Bg8vCisd.js";
3
+ import { n as defineRealtimeEditor, r as realtimeMarkdownEditor, t as createRealtimeEditorExtensions } from "./editor-BM5-vHqf.js";
8
4
  export { RealtimeDocumentConflict, createRealtimeEditorExtensions, defineRealtime, defineRealtimeEditor, isRealtimeDocumentConflict, readRealtimeStatus, realtimeDocumentLayout, realtimeMarkdownEditor };
@@ -0,0 +1,5 @@
1
+ import { r as RealtimeAvailability } from "../../types-1DVVG5ro.js";
2
+ //#region src/internal/runtime/unavailable.d.ts
3
+ declare const availability: RealtimeAvailability;
4
+ //#endregion
5
+ export { availability as default };
@@ -0,0 +1,8 @@
1
+ //#region src/internal/runtime/unavailable.ts
2
+ const availability = {
3
+ available: false,
4
+ reason: "This build does not enable Realtime.",
5
+ fix: "Enable `realtime` in vitehub() with the Cloudflare or Node preset."
6
+ };
7
+ //#endregion
8
+ export { availability as default };
@@ -0,0 +1,33 @@
1
+ import { h as realtimeKeepalivePing } from "./object-CzKyK0hX.js";
2
+ import * as time from "lib0/time";
3
+ //#region src/application-path.ts
4
+ function resolveRealtimeApplicationPath(path, baseURL = typeof __VITEHUB_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_APP_BASE_URL__) {
5
+ return baseURL === "/" ? path : `${baseURL.replace(/\/+$/, "")}${path}`;
6
+ }
7
+ //#endregion
8
+ //#region src/keepalive.ts
9
+ const keepaliveIntervalMs = 15e3;
10
+ /**
11
+ * y-websocket closes a socket that received nothing for 30 seconds, then connects again. A room with nobody else in it,
12
+ * and the workspace events room, can stay silent for much longer. So the provider pings every 15 seconds while it is
13
+ * connected, and the pong counts as a received message.
14
+ */
15
+ function keepRealtimeSocketAlive(provider) {
16
+ let timer;
17
+ provider.on("status", ({ status }) => {
18
+ clearInterval(timer);
19
+ timer = void 0;
20
+ const socket = provider.ws;
21
+ if (status !== "connected" || !socket) return;
22
+ const receive = socket.onmessage;
23
+ socket.onmessage = function(event) {
24
+ if (event.data !== "pong") return receive?.call(this, event);
25
+ if (provider.ws === socket) provider.wsLastMessageReceived = time.getUnixTime();
26
+ };
27
+ timer = setInterval(() => {
28
+ if (provider.ws === socket && socket.readyState === socket.OPEN) socket.send(realtimeKeepalivePing);
29
+ }, keepaliveIntervalMs);
30
+ });
31
+ }
32
+ //#endregion
33
+ export { resolveRealtimeApplicationPath as n, keepRealtimeSocketAlive as t };
@@ -0,0 +1,34 @@
1
+ //#region src/layout.ts
2
+ /**
3
+ * Root types of every Realtime Y.Doc:
4
+ * - `body`: Y.XmlFragment bound to the editor through TipTap Collaboration.
5
+ * - `fields`: Y.Map with one JSON value per field; concurrent writes to one key resolve last-write-wins.
6
+ * - `status`: Y.Map written only by the server (`digest`, `error`, `issues`, `savedAt`, `savedBy`).
7
+ * The server closes connections whose updates change it.
8
+ */
9
+ const realtimeDocumentLayout = Object.freeze({
10
+ body: "body",
11
+ fields: "fields",
12
+ status: "status"
13
+ });
14
+ function text(value) {
15
+ return typeof value === "string" ? value : null;
16
+ }
17
+ function readRealtimeStatus(document) {
18
+ const map = document.getMap(realtimeDocumentLayout.status);
19
+ const issues = map.get("issues");
20
+ const savedBy = map.get("savedBy");
21
+ const status = {
22
+ issues: Array.isArray(issues) ? issues : [],
23
+ savedBy: savedBy && !Array.isArray(savedBy) && savedBy instanceof Object ? savedBy : null
24
+ };
25
+ return {
26
+ digest: text(map.get("digest")),
27
+ error: text(map.get("error")),
28
+ issues: status.issues,
29
+ savedAt: text(map.get("savedAt")),
30
+ savedBy: status.savedBy
31
+ };
32
+ }
33
+ //#endregion
34
+ export { realtimeDocumentLayout as n, readRealtimeStatus as t };
@@ -1,4 +1,4 @@
1
- import { c as RealtimeDocumentStatus } from "./types-Bw6-42Se.js";
1
+ import { d as RealtimeDocumentStatus } from "./types-1DVVG5ro.js";
2
2
  import * as Y from "yjs";
3
3
  //#region src/layout.d.ts
4
4
  /**
@@ -1,68 +1,21 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cvm6vRXQ.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
2
  import * as decoding from "lib0/decoding";
3
3
  import * as encoding from "lib0/encoding";
4
4
  import { normalizeSafeWorkspacePath } from "@vite-hub/workspace/internal/path";
5
- //#region ../internal/src/object.ts
6
- function isPlainObject(value) {
7
- if (value === null || Object(value) !== value || Array.isArray(value)) return false;
8
- return typeof value === "object";
9
- }
10
- //#endregion
11
- //#region src/presence.ts
12
- const personColors = [
13
- "#E11D48",
14
- "#D97706",
15
- "#059669",
16
- "#0891B2",
17
- "#2563EB",
18
- "#7C3AED",
19
- "#C026D3"
20
- ];
21
- function isString(value) {
22
- try {
23
- return String(value) === value;
24
- } catch {
25
- return false;
26
- }
27
- }
28
- function createRealtimeIdentity(user) {
29
- if (!isString(user.id) || !user.id || user.id.length > 256) throw realtimeErrorDiagnostics.REALTIME_INVALID_USER();
30
- let hash = 0;
31
- for (let index = 0; index < user.id.length; index++) hash = Math.imul(31, hash) + user.id.charCodeAt(index) | 0;
32
- const name = (isString(user.name) && user.name || isString(user.email) && user.email || "Anonymous").slice(0, 256);
33
- const identity = {
34
- color: personColors[Math.abs(hash) % personColors.length],
35
- id: user.id,
36
- name
37
- };
38
- if (isString(user.image) && user.image && user.image.length <= 2048) identity.image = user.image;
39
- return identity;
40
- }
41
- function isRealtimeIdentity(value) {
42
- if (!isPlainObject(value)) return false;
43
- return isString(value.id) && value.id.length > 0 && value.id.length <= 256 && isString(value.name) && value.name.length > 0 && value.name.length <= 256 && isString(value.color) && /^#[\da-f]{6}$/i.test(value.color) && (value.image === void 0 || isString(value.image) && value.image.length <= 2048);
44
- }
45
- function getRealtimePeople(states) {
46
- const people = [];
47
- for (const [clientId, state] of states) if (isRealtimeIdentity(state.user)) {
48
- const { color, id, image, name } = state.user;
49
- const person = {
50
- color,
51
- id,
52
- name,
53
- clientId
54
- };
55
- if (image !== void 0) person.image = image;
56
- people.push(person);
57
- }
58
- return people;
59
- }
60
5
  const workspaceRoomId = "@workspace";
6
+ /**
7
+ * Text frames that keep an idle socket open. The client sends the ping, and the server answers with the pong. On
8
+ * Cloudflare the Durable Object answers it without waking.
9
+ */
10
+ const realtimeKeepalivePing = "ping";
11
+ const realtimeKeepalivePong = "pong";
61
12
  const maxAwarenessClients = 1024;
62
13
  const realtimeSyncPendingCode = "REALTIME_SYNC_PENDING";
63
14
  const realtimeSourceChangedCode = "REALTIME_SOURCE_CHANGED";
64
15
  /** A save or checkpoint asked a room whose codec cannot edit the stored document without loss. */
65
16
  const realtimeReadOnlyCode = "REALTIME_READ_ONLY";
17
+ /** A save found that the room body does not fit the editor schema, so writing it would lose content. */
18
+ const realtimeInvalidDocumentCode = "REALTIME_INVALID_DOCUMENT";
66
19
  /** Close code sent after a reset control frame. The client must drop its Y.Doc. */
67
20
  const realtimeResetCloseCode = 4409;
68
21
  /** Close code for updates a peer may not write: read-only access or the server-written status. */
@@ -82,7 +35,7 @@ function decodeRealtimeControlPayload(decoder) {
82
35
  if (!value || typeof value !== "object" || !("epoch" in value) || !("type" in value)) return;
83
36
  if (typeof value.epoch !== "string" || !value.epoch) return;
84
37
  if (value.type === "session" && "access" in value && (value.access === "read" || value.access === "write")) {
85
- if (value.access === "read" && "reason" in value && (value.reason === "access" || value.reason === "document")) return {
38
+ if (value.access === "read" && "reason" in value && (value.reason === "access" || value.reason === "document" || value.reason === "version")) return {
86
39
  type: "session",
87
40
  access: value.access,
88
41
  epoch: value.epoch,
@@ -142,5 +95,51 @@ function readAwarenessClientIds(update) {
142
95
  }
143
96
  return clients;
144
97
  }
98
+ function encodeRealtimeRequestFrame(frame) {
99
+ const encoder = encoding.createEncoder();
100
+ encoding.writeVarUint(encoder, 6);
101
+ encoding.writeVarString(encoder, JSON.stringify(frame));
102
+ return encoding.toUint8Array(encoder);
103
+ }
104
+ /** Reads a request frame after its message type, or `undefined` when it is not one. */
105
+ function decodeRealtimeRequestFramePayload(decoder) {
106
+ try {
107
+ const value = JSON.parse(decoding.readVarString(decoder));
108
+ if (!value || typeof value !== "object" || !("id" in value) || typeof value.id !== "string" || !value.id || value.id.length > 128) return;
109
+ if (!("kind" in value)) return;
110
+ if (value.kind === "request") return {
111
+ kind: "request",
112
+ id: value.id,
113
+ body: "body" in value ? value.body : void 0
114
+ };
115
+ if (value.kind !== "answer" || !("ok" in value)) return;
116
+ if (value.ok === true) return {
117
+ kind: "answer",
118
+ id: value.id,
119
+ ok: true,
120
+ body: "body" in value ? value.body : void 0
121
+ };
122
+ if (value.ok === false && "why" in value && typeof value.why === "string") return {
123
+ kind: "answer",
124
+ id: value.id,
125
+ ok: false,
126
+ why: value.why
127
+ };
128
+ } catch {}
129
+ }
130
+ //#endregion
131
+ //#region ../internal/src/object.ts
132
+ /** A non-null object that is not an array. Functions do not pass. */
133
+ function isRecord(value) {
134
+ return typeof value === "object" && value !== null && !Array.isArray(value);
135
+ }
136
+ /** A non-null object or a function that is not an array. */
137
+ function isRecordOrFunction(value) {
138
+ return Object(value) === value && !Array.isArray(value);
139
+ }
140
+ /** A shallow copy of a non-array object, or an empty object for any other value. */
141
+ function cloneRecord(value) {
142
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
143
+ }
145
144
  //#endregion
146
- export { isRetryableRealtimeRequestCode as a, realtimeForbiddenWriteCloseCode as c, realtimeSourceChangedCode as d, realtimeSyncPendingCode as f, isPlainObject as g, getRealtimePeople as h, encodeWorkspaceChange as i, realtimeReadOnlyCode as l, createRealtimeIdentity as m, decodeWorkspaceChangePayload as n, maxAwarenessClients as o, workspaceRoomId as p, encodeRealtimeControl as r, readAwarenessClientIds as s, decodeRealtimeControlPayload as t, realtimeResetCloseCode as u };
145
+ export { realtimeReadOnlyCode as _, decodeRealtimeRequestFramePayload as a, realtimeSyncPendingCode as b, encodeRealtimeRequestFrame as c, maxAwarenessClients as d, readAwarenessClientIds as f, realtimeKeepalivePong as g, realtimeKeepalivePing as h, decodeRealtimeControlPayload as i, encodeWorkspaceChange as l, realtimeInvalidDocumentCode as m, isRecord as n, decodeWorkspaceChangePayload as o, realtimeForbiddenWriteCloseCode as p, isRecordOrFunction as r, encodeRealtimeControl as s, cloneRecord as t, isRetryableRealtimeRequestCode as u, realtimeResetCloseCode as v, workspaceRoomId as x, realtimeSourceChangedCode as y };
@@ -0,0 +1,53 @@
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
+ import { n as isRecord } from "./object-CzKyK0hX.js";
3
+ //#region src/presence.ts
4
+ const personColors = [
5
+ "#E11D48",
6
+ "#D97706",
7
+ "#059669",
8
+ "#0891B2",
9
+ "#2563EB",
10
+ "#7C3AED",
11
+ "#C026D3"
12
+ ];
13
+ function isString(value) {
14
+ try {
15
+ return String(value) === value;
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
20
+ function createRealtimeIdentity(user) {
21
+ if (!isString(user.id) || !user.id || user.id.length > 256) throw realtimeErrorDiagnostics.REALTIME_INVALID_USER();
22
+ let hash = 0;
23
+ for (let index = 0; index < user.id.length; index++) hash = Math.imul(31, hash) + user.id.charCodeAt(index) | 0;
24
+ const name = (isString(user.name) && user.name || isString(user.email) && user.email || "Anonymous").slice(0, 256);
25
+ const identity = {
26
+ color: personColors[Math.abs(hash) % personColors.length],
27
+ id: user.id,
28
+ name
29
+ };
30
+ if (isString(user.image) && user.image && user.image.length <= 2048) identity.image = user.image;
31
+ return identity;
32
+ }
33
+ function isRealtimeIdentity(value) {
34
+ if (!isRecord(value)) return false;
35
+ return isString(value.id) && value.id.length > 0 && value.id.length <= 256 && isString(value.name) && value.name.length > 0 && value.name.length <= 256 && isString(value.color) && /^#[\da-f]{6}$/i.test(value.color) && (value.image === void 0 || isString(value.image) && value.image.length <= 2048);
36
+ }
37
+ function getRealtimePeople(states) {
38
+ const people = [];
39
+ for (const [clientId, state] of states) if (isRealtimeIdentity(state.user)) {
40
+ const { color, id, image, name } = state.user;
41
+ const person = {
42
+ color,
43
+ id,
44
+ name,
45
+ clientId
46
+ };
47
+ if (image !== void 0) person.image = image;
48
+ people.push(person);
49
+ }
50
+ return people;
51
+ }
52
+ //#endregion
53
+ export { getRealtimePeople as n, createRealtimeIdentity as t };
@@ -0,0 +1,48 @@
1
+ import { k as RealtimeRoomRequestErrorCode } from "./types-1DVVG5ro.js";
2
+ import { Result } from "@vite-hub/runtime";
3
+ //#region src/request.d.ts
4
+ /** The `$DurableObject` namespace binding that holds Realtime rooms on Cloudflare. */
5
+ interface RealtimeDurableObjectNamespace {
6
+ get(id: unknown): {
7
+ fetch(request: Request): Promise<Response>;
8
+ };
9
+ idFromName(name: string): unknown;
10
+ }
11
+ interface RealtimeRoomRequestOptions {
12
+ /** How long to wait for the browser's answer, in milliseconds. Default 30 seconds. */
13
+ timeout?: number;
14
+ /** How long to wait for a browser to join or rejoin the room before the request fails, in milliseconds. Default 5 seconds. */
15
+ wait?: number;
16
+ /** Stops the request, such as when the caller's run is cancelled. */
17
+ signal?: AbortSignal;
18
+ /**
19
+ * The person whose room this is, for a Definition with `scope: "user"`: their Auth user id, or `null` for the shared
20
+ * anonymous scope. Required there; ignored elsewhere.
21
+ */
22
+ user?: string | null;
23
+ /** On Cloudflare, the `$DurableObject` binding that holds the rooms. Defaults to the binding of the running Worker. */
24
+ durableObjects?: RealtimeDurableObjectNamespace;
25
+ }
26
+ /** `[error, answer]` of `requestRealtimeRoom()`. */
27
+ type RealtimeRoomRequestResult = Result<unknown, RealtimeRoomRequestErrorCode>;
28
+ /**
29
+ * Asks the one browser in a room of a presence Definition with `requests: true`, and resolves its answer. The browser
30
+ * answers with `room.onRequest()` from `@vite-hub/realtime/client`. A room with no browser waits `wait` milliseconds for
31
+ * one to join, such as after a reload, before it returns `REALTIME_ROOM_EMPTY`. A room with more than one browser
32
+ * returns `REALTIME_ROOM_CROWDED`. On Cloudflare the request goes to the Durable Object that holds the rooms. On Node it
33
+ * reaches the rooms of this process; with Redis or Postgres, a browser on another instance gives `REALTIME_ROOM_ELSEWHERE`.
34
+ * A Definition with `scope: "user"` keeps a room per person: pass `{ user }`, and only that person's room is asked.
35
+ * Returns `[error, answer]` and never throws.
36
+ */
37
+ declare function requestRealtimeRoom(definition: string, documentId: string, body: unknown, options?: RealtimeRoomRequestOptions): Promise<RealtimeRoomRequestResult>;
38
+ /**
39
+ * The Realtime handle of an Agent's `page()` Capability. ViteHub passes it to the Agent routes when the app has
40
+ * Realtime, as `capabilities.realtime`.
41
+ */
42
+ interface AgentRealtime {
43
+ available: () => boolean;
44
+ request: typeof requestRealtimeRoom;
45
+ }
46
+ declare const agentRealtime: AgentRealtime;
47
+ //#endregion
48
+ export { agentRealtime as a, RealtimeRoomRequestResult as i, RealtimeDurableObjectNamespace as n, requestRealtimeRoom as o, RealtimeRoomRequestOptions as r, AgentRealtime as t };
@@ -0,0 +1,192 @@
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import availability from "#vitehub/realtime/availability";
4
+ //#region ../internal/src/runtime/cloudflare-env-lookup.ts
5
+ /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
6
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
7
+ let activeEnv;
8
+ /** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
9
+ function getScopedCloudflareEnv() {
10
+ return globalThis[activeEnvStorageKey]?.getStore();
11
+ }
12
+ function getActiveCloudflareEnv() {
13
+ const scoped = getScopedCloudflareEnv();
14
+ if (scoped) return scoped.env;
15
+ const host = globalThis;
16
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
17
+ }
18
+ //#endregion
19
+ //#region ../internal/src/runtime/cloudflare-env.ts
20
+ const runtimeGlobal = globalThis;
21
+ runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
22
+ function getActiveCloudflareBinding(name) {
23
+ const env = getActiveCloudflareEnv();
24
+ return env && Object.hasOwn(env, name) ? env[name] : void 0;
25
+ }
26
+ //#endregion
27
+ //#region src/availability.ts
28
+ /**
29
+ * Returns `true` when this build has a Realtime room driver: Durable Objects on Cloudflare, a Node server, or memory
30
+ * on the dev server. Without one, no room opens and `refreshRealtimeDocument()` resolves `false`.
31
+ */
32
+ function isRealtimeAvailable() {
33
+ return availability.available;
34
+ }
35
+ //#endregion
36
+ //#region src/request.ts
37
+ const routePrefix = "/api/_vitehub/realtime/";
38
+ /** Marks the request that `requestRealtimeRoom()` sends to a Durable Object. The Worker strips it from client requests. */
39
+ const internalRequestHeader = "x-vitehub-realtime-request";
40
+ const defaultRequestTimeout = 3e4;
41
+ const defaultRequestWait = 5e3;
42
+ /**
43
+ * The one Durable Object instance that holds every room. Nitro's Cloudflare entry hands each WebSocket upgrade
44
+ * to this instance before the application runs, so saves, checkpoints, and refreshes must reach it too: a Durable
45
+ * Object per room would have no peers and never match a room's state.
46
+ */
47
+ const durableRoomsInstance = "server";
48
+ /**
49
+ * Accepts the namespace that holds Realtime rooms, and nothing that only inherits `get` and `idFromName` from an
50
+ * arbitrary prototype. Workerd's binding owns no methods: they belong to its `DurableObjectNamespace` class prototype,
51
+ * and Workers have no global `DurableObjectNamespace` to compare with. Any other namespace, such as a test double,
52
+ * must own both methods.
53
+ */
54
+ function isRealtimeDurableObjectNamespace(value) {
55
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
56
+ const methods = (target) => ["get", "idFromName"].map((name) => Object.getOwnPropertyDescriptor(target, name));
57
+ const callable = (method) => !!method && !method.get && typeof method.value === "function" && Function.prototype.toString.call(method.value) !== "function () { [native code] }";
58
+ try {
59
+ const own = methods(value);
60
+ if (own.every(callable)) return true;
61
+ const prototype = Object.getPrototypeOf(value);
62
+ if (own.some(Boolean) || prototype === null || typeof prototype !== "object" || Object.getPrototypeOf(prototype) !== Object.prototype) return false;
63
+ return Object.prototype.toString.call(value) === "[object DurableObjectNamespace]" && methods(prototype).every(callable);
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+ /** The `$DurableObject` binding of the running Worker. Nitro's Cloudflare entry stores each request's bindings in `globalThis.__env__`. */
69
+ function workerDurableObjects() {
70
+ try {
71
+ const binding = getActiveCloudflareBinding("$DurableObject");
72
+ return isRealtimeDurableObjectNamespace(binding) ? binding : void 0;
73
+ } catch {
74
+ return;
75
+ }
76
+ }
77
+ const localRequestKey = Symbol.for("vitehub.realtime.local-request");
78
+ const requestScope = globalThis;
79
+ function localRequesters() {
80
+ requestScope[localRequestKey] ??= /* @__PURE__ */ new Set();
81
+ return requestScope[localRequestKey];
82
+ }
83
+ /** The parameters each request error was made with, so a Durable Object can send the same error to the Worker. */
84
+ const roomRequestErrorParams = /* @__PURE__ */ new WeakMap();
85
+ function roomRequestError(code, params = {}) {
86
+ const result = createRoomRequestError(code, params);
87
+ if (result[0]) roomRequestErrorParams.set(result[0], params);
88
+ return result;
89
+ }
90
+ function createRoomRequestError(code, params) {
91
+ switch (code) {
92
+ case "REALTIME_ROOM_ABORTED": return [realtimeErrorDiagnostics.REALTIME_ROOM_ABORTED(), void 0];
93
+ case "REALTIME_ROOM_CROWDED": return [realtimeErrorDiagnostics.REALTIME_ROOM_CROWDED({ count: params.count ?? 2 }), void 0];
94
+ case "REALTIME_ROOM_ELSEWHERE": return [realtimeErrorDiagnostics.REALTIME_ROOM_ELSEWHERE(), void 0];
95
+ case "REALTIME_ROOM_EMPTY": return [realtimeErrorDiagnostics.REALTIME_ROOM_EMPTY(), void 0];
96
+ case "REALTIME_ROOM_REFUSED": return [realtimeErrorDiagnostics.REALTIME_ROOM_REFUSED({ reason: params.reason ?? "no reason given." }), void 0];
97
+ case "REALTIME_ROOM_REQUESTS_OFF": return [realtimeErrorDiagnostics.REALTIME_ROOM_REQUESTS_OFF({ definition: params.definition ?? "" }), void 0];
98
+ case "REALTIME_ROOM_TIMEOUT": return [realtimeErrorDiagnostics.REALTIME_ROOM_TIMEOUT({ timeout: params.timeout ?? 3e4 }), void 0];
99
+ }
100
+ }
101
+ const roomRequestErrorCodes = /* @__PURE__ */ new Set([
102
+ "REALTIME_ROOM_ABORTED",
103
+ "REALTIME_ROOM_CROWDED",
104
+ "REALTIME_ROOM_ELSEWHERE",
105
+ "REALTIME_ROOM_EMPTY",
106
+ "REALTIME_ROOM_REFUSED",
107
+ "REALTIME_ROOM_REQUESTS_OFF",
108
+ "REALTIME_ROOM_TIMEOUT"
109
+ ]);
110
+ function isRoomRequestErrorCode(value) {
111
+ return typeof value === "string" && roomRequestErrorCodes.has(value);
112
+ }
113
+ function toDurableRequestReply(result) {
114
+ const [error, body] = result;
115
+ return error ? {
116
+ ok: false,
117
+ code: error.code,
118
+ params: roomRequestErrorParams.get(error) ?? {}
119
+ } : {
120
+ ok: true,
121
+ body
122
+ };
123
+ }
124
+ function isDurableSockets(value) {
125
+ return typeof value === "object" && value !== null && "getWebSockets" in value && typeof value.getWebSockets === "function";
126
+ }
127
+ /**
128
+ * Asks the one browser in a room of a presence Definition with `requests: true`, and resolves its answer. The browser
129
+ * answers with `room.onRequest()` from `@vite-hub/realtime/client`. A room with no browser waits `wait` milliseconds for
130
+ * one to join, such as after a reload, before it returns `REALTIME_ROOM_EMPTY`. A room with more than one browser
131
+ * returns `REALTIME_ROOM_CROWDED`. On Cloudflare the request goes to the Durable Object that holds the rooms. On Node it
132
+ * reaches the rooms of this process; with Redis or Postgres, a browser on another instance gives `REALTIME_ROOM_ELSEWHERE`.
133
+ * A Definition with `scope: "user"` keeps a room per person: pass `{ user }`, and only that person's room is asked.
134
+ * Returns `[error, answer]` and never throws.
135
+ */
136
+ async function requestRealtimeRoom(definition, documentId, body, options = {}) {
137
+ const local = {
138
+ timeout: options.timeout ?? 3e4,
139
+ wait: options.wait ?? 5e3,
140
+ ...options.signal ? { signal: options.signal } : {},
141
+ ...options.user !== void 0 ? { user: options.user } : {}
142
+ };
143
+ if (local.signal?.aborted) return roomRequestError("REALTIME_ROOM_ABORTED");
144
+ const binding = options.durableObjects ?? workerDurableObjects();
145
+ if (binding) return await requestDurableRoom(binding, definition, documentId, body, local);
146
+ for (const reference of [...localRequesters()].reverse()) {
147
+ const request = reference.deref();
148
+ if (!request) {
149
+ localRequesters().delete(reference);
150
+ continue;
151
+ }
152
+ return await request(definition, documentId, body, local);
153
+ }
154
+ return roomRequestError("REALTIME_ROOM_EMPTY");
155
+ }
156
+ async function requestDurableRoom(binding, definition, documentId, body, options) {
157
+ const room = documentId.split("/").map(encodeURIComponent).join("/");
158
+ let response;
159
+ try {
160
+ response = await binding.get(binding.idFromName(durableRoomsInstance)).fetch(new Request(`https://vitehub.internal${routePrefix}${encodeURIComponent(definition)}/${room}?request=1`, {
161
+ method: "POST",
162
+ headers: {
163
+ [internalRequestHeader]: "1",
164
+ "content-type": "application/json"
165
+ },
166
+ body: JSON.stringify({
167
+ body,
168
+ timeout: options.timeout,
169
+ wait: options.wait,
170
+ ...options.user !== void 0 ? { user: options.user } : {}
171
+ }),
172
+ ...options.signal ? { signal: options.signal } : {}
173
+ }));
174
+ } catch {
175
+ return roomRequestError(options.signal?.aborted ? "REALTIME_ROOM_ABORTED" : "REALTIME_ROOM_EMPTY");
176
+ }
177
+ const reply = response.ok ? await response.json().catch(() => void 0) : void 0;
178
+ if (reply && typeof reply === "object" && "ok" in reply) {
179
+ if (reply.ok === true) return [void 0, "body" in reply ? reply.body : void 0];
180
+ if ("code" in reply && isRoomRequestErrorCode(reply.code)) {
181
+ const params = "params" in reply && reply.params && typeof reply.params === "object" ? reply.params : {};
182
+ return roomRequestError(reply.code, params);
183
+ }
184
+ }
185
+ return roomRequestError("REALTIME_ROOM_REFUSED", { reason: `the Durable Object answered HTTP ${response.status}.` });
186
+ }
187
+ const agentRealtime = {
188
+ available: isRealtimeAvailable,
189
+ request: requestRealtimeRoom
190
+ };
191
+ //#endregion
192
+ export { internalRequestHeader as a, localRequesters as c, routePrefix as d, toDurableRequestReply as f, durableRoomsInstance as i, requestRealtimeRoom as l, isRealtimeAvailable as m, defaultRequestTimeout as n, isDurableSockets as o, workerDurableObjects as p, defaultRequestWait as r, isRealtimeDurableObjectNamespace as s, agentRealtime as t, roomRequestError as u };