@velajs/cloudflare 1.35.0 → 1.36.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 (109) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +28 -6
  3. package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorate.js +1 -2
  4. package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorateMetadata.js +1 -2
  5. package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorateParam.js +1 -2
  6. package/dist/bindings.js +1 -2
  7. package/dist/{cloudflare-application-Dsscb3Mo.d.ts → cloudflare-application-Zw9th_-h.d.ts} +2 -7
  8. package/dist/cloudflare-application.js +2 -3
  9. package/dist/cloudflare-application.js.map +1 -1
  10. package/dist/{cloudflare-factory-DM9CBvNH.d.ts → cloudflare-factory-Ab6XoKqO.d.ts} +5 -9
  11. package/dist/cloudflare-factory.js +5 -6
  12. package/dist/cloudflare-factory.js.map +1 -1
  13. package/dist/decorators/queue-consumer.js +1 -2
  14. package/dist/diagnostics.js +1 -2
  15. package/dist/durable-object/boot.js +5 -6
  16. package/dist/durable-object/host-dispatch.js +4 -5
  17. package/dist/durable-object/host-dispatch.js.map +1 -1
  18. package/dist/durable-object/host-methods.js +1 -2
  19. package/dist/durable-object/tokens.js +1 -2
  20. package/dist/durable-object/vela-durable-object.js +3 -4
  21. package/dist/durable-objects.d.ts +7 -19
  22. package/dist/durable-objects.js +1 -1
  23. package/dist/email/email-dispatch.js +1 -2
  24. package/dist/email/on-email.js +2 -3
  25. package/dist/email.d.ts +2 -6
  26. package/dist/email.js +1 -1
  27. package/dist/entrypoint/vela-entrypoint.js +4 -5
  28. package/dist/entrypoints.d.ts +3 -5
  29. package/dist/entrypoints.js +1 -2
  30. package/dist/environment.js +1 -2
  31. package/dist/host/host-invoker.js +2 -3
  32. package/dist/host/host-invoker.js.map +1 -1
  33. package/dist/host/host-members.js +1 -2
  34. package/dist/{host-members-DECj_4yz.d.ts → host-members-bKCWuJP2.d.ts} +0 -2
  35. package/dist/index.d.ts +53 -42
  36. package/dist/index.js +6 -5
  37. package/dist/nonce/durable-object-nonce.store.js +1 -2
  38. package/dist/nonce/nonce-validation.js +1 -2
  39. package/dist/nonce/nonce.durable-object.js +2 -3
  40. package/dist/nonce/nonce.durable-object.js.map +1 -1
  41. package/dist/{nonce.durable-object-Bg1e0BMD.d.ts → nonce.durable-object-Csuy3U9e.d.ts} +0 -4
  42. package/dist/pipelines.d.ts +1 -3
  43. package/dist/pipelines.js +1 -2
  44. package/dist/platform.js +2 -3
  45. package/dist/queue/cloudflare-queues.js +3 -4
  46. package/dist/queue-events/consume.js +1 -2
  47. package/dist/queue-events/consume.js.map +1 -1
  48. package/dist/queue-events.d.ts +1 -2
  49. package/dist/queue-events.js +1 -2
  50. package/dist/queues.d.ts +1 -3
  51. package/dist/queues.js +1 -2
  52. package/dist/rate-limit/cloudflare-rate-limit.store.js +1 -2
  53. package/dist/rate-limit/d1-throttler.store.js +96 -0
  54. package/dist/rate-limit/d1-throttler.store.js.map +1 -0
  55. package/dist/root-module.js +1 -2
  56. package/dist/rpc/entrypoint-error.js +1 -2
  57. package/dist/rpc/entrypoint-error.js.map +1 -1
  58. package/dist/schedule-diagnostics.js +2 -3
  59. package/dist/schedule-diagnostics.js.map +1 -1
  60. package/dist/scheduled-event.js +1 -2
  61. package/dist/services/flagship-flag.driver.js +1 -2
  62. package/dist/services/flagship-flag.driver.js.map +1 -1
  63. package/dist/services/kv-cache.store.js +1 -2
  64. package/dist/services/kv-cache.store.js.map +1 -1
  65. package/dist/services/kv-flag.driver.js +1 -2
  66. package/dist/services/kv-flag.driver.js.map +1 -1
  67. package/dist/storage/r2-storage.js +2 -3
  68. package/dist/storage.d.ts +1 -3
  69. package/dist/storage.js +1 -2
  70. package/dist/tail/on-tail.js +2 -3
  71. package/dist/tail/tail-dispatch.js +2 -3
  72. package/dist/tail.d.ts +2 -6
  73. package/dist/tail.js +1 -2
  74. package/dist/testing.d.ts +5 -5
  75. package/dist/testing.js +6 -6
  76. package/dist/testing.js.map +1 -1
  77. package/dist/tracing.d.ts +1 -3
  78. package/dist/tracing.js +3 -4
  79. package/dist/{vela-env-DFvyoNT3.d.ts → vela-env-5graXefc.d.ts} +0 -1
  80. package/dist/websocket/binding-gateways.js +2 -3
  81. package/dist/websocket/cf-room-registry.js +2 -3
  82. package/dist/websocket/cf-room-registry.js.map +1 -1
  83. package/dist/websocket/cf-ws-client.js +2 -3
  84. package/dist/websocket/cf-ws-client.js.map +1 -1
  85. package/dist/websocket/do-bootstrap.js +5 -6
  86. package/dist/websocket/do-live.js +4 -5
  87. package/dist/websocket/do-live.js.map +1 -1
  88. package/dist/websocket/do-pitr.js +1 -2
  89. package/dist/websocket/do-pitr.js.map +1 -1
  90. package/dist/websocket/do-state.js +1 -2
  91. package/dist/websocket/do-websocket-host.js +3 -4
  92. package/dist/websocket/do-websocket-host.js.map +1 -1
  93. package/dist/websocket/live-driver.js +3 -4
  94. package/dist/websocket/live-driver.js.map +1 -1
  95. package/dist/websocket/room-id.js +1 -2
  96. package/dist/websocket/websocket.durable-object.js +5 -6
  97. package/dist/websocket/websocket.durable-object.js.map +1 -1
  98. package/dist/websocket/worker-transport.js +3 -4
  99. package/dist/websocket/ws-attachment.js +1 -2
  100. package/dist/worker-events.js +1 -2
  101. package/dist/workflow/portable-workflow-step.js +1 -2
  102. package/dist/workflow/vela-workflow-definition.js +7 -8
  103. package/dist/workflow/vela-workflow-definition.js.map +1 -1
  104. package/dist/workflow/vela-workflow.js +2 -3
  105. package/dist/workflow-definitions.d.ts +2 -4
  106. package/dist/workflow-definitions.js +1 -2
  107. package/dist/workflows.d.ts +2 -4
  108. package/dist/workflows.js +1 -2
  109. package/package.json +19 -19
package/dist/tracing.js CHANGED
@@ -1,7 +1,7 @@
1
- import __decorate from "./_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
2
- import { Injectable } from "@velajs/vela";
3
1
  import { tracing } from "cloudflare:workers";
4
- //#region src/tracing.ts
2
+ import { Injectable } from "@velajs/vela";
3
+ import __decorate from "./_virtual/_@oxc-project_runtime@0.160.0/helpers/esm/decorate.js";
4
+ // src/tracing.ts
5
5
  const MAX_LABEL_LENGTH = 128;
6
6
  let CloudflareTracingInterceptor = class CloudflareTracingInterceptor {
7
7
  intercept(context, next) {
@@ -18,7 +18,6 @@ let CloudflareTracingInterceptor = class CloudflareTracingInterceptor {
18
18
  }
19
19
  };
20
20
  CloudflareTracingInterceptor = __decorate([Injectable()], CloudflareTracingInterceptor);
21
- //#endregion
22
21
  export { CloudflareTracingInterceptor };
23
22
 
24
23
  //# sourceMappingURL=tracing.js.map
@@ -1,4 +1,3 @@
1
- //#region src/vela-env.d.ts
2
1
  declare module '@velajs/vela' {
3
2
  /**
4
3
  * On Workers the framework ENV is the native environment: the bindings,
@@ -1,6 +1,6 @@
1
- import { reportDiagnostic } from "../diagnostics.js";
2
1
  import { WS_GATEWAY_METADATA, WS_SERVER } from "@velajs/vela/websocket";
3
- //#region src/websocket/binding-gateways.ts
2
+ import { reportDiagnostic } from "../diagnostics.js";
3
+ // src/websocket/binding-gateways.ts
4
4
  /**
5
5
  * The application's gateways that name a `binding`, in discovery order, once
6
6
  * per path. Read from decorator metadata, so lifecycle hooks can use it.
@@ -27,7 +27,6 @@ function reportUnservedGateways(container, discovery) {
27
27
  if (container.has(WS_SERVER)) return;
28
28
  for (const { name, binding, path } of bindingGateways(discovery)) reportDiagnostic(container, `[vela] ${name} is a @WebSocketGateway with binding '${binding}', but the application does not import WebSocketModule.forRoot() from @velajs/vela/websocket, so upgrades to '${path}' answer 404 instead of reaching its Durable Object.`);
29
29
  }
30
- //#endregion
31
30
  export { bindingGateways, reportUnservedGateways };
32
31
 
33
32
  //# sourceMappingURL=binding-gateways.js.map
@@ -1,7 +1,7 @@
1
+ import { WebSocketSendGate } from "@velajs/vela/websocket";
1
2
  import { rejectedAttachment, socketAttachment } from "./ws-attachment.js";
2
3
  import { CfWsClient } from "./cf-ws-client.js";
3
- import { WebSocketSendGate } from "@velajs/vela/websocket";
4
- //#region src/websocket/cf-room-registry.ts
4
+ // src/websocket/cf-room-registry.ts
5
5
  /**
6
6
  * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room
7
7
  * membership lives in tags (hub room, set at accept) + the attachment (dynamic
@@ -133,7 +133,6 @@ var CfRoomRegistry = class {
133
133
  } catch {}
134
134
  }
135
135
  };
136
- //#endregion
137
136
  export { CfRoomRegistry };
138
137
 
139
138
  //# sourceMappingURL=cf-room-registry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cf-room-registry.js","names":[],"sources":["../../src/websocket/cf-room-registry.ts"],"sourcesContent":["import { WebSocketSendGate, type WebSocketSendPolicy } from '@velajs/vela/websocket';\nimport { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { BroadcastCommand, RoomRegistry, WsClient } from '@velajs/vela/websocket';\nimport type { DoStateLike, WsAttachment, WsLike } from './do-state';\nimport { CfWsClient } from './cf-ws-client';\n\n/**\n * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room\n * membership lives in tags (hub room, set at accept) + the attachment (dynamic\n * `join()`), never in DO instance fields — so it survives hibernation with zero\n * rehydration.\n */\nexport class CfRoomRegistry implements RoomRegistry {\n readonly #sendGates = new WeakMap<WsLike, WebSocketSendGate>();\n // Sockets whose OnGatewayConnection hook is running in this instance. They\n // are still `pending`, so broadcasts skip them; any other pending socket\n // never finished admission and is closed when a broadcast reaches it.\n readonly #admitting = new WeakSet<WsLike>();\n #sendPolicyForPath?: (path: string) => WebSocketSendPolicy | undefined;\n\n setSendPolicyResolver(resolve: (path: string) => WebSocketSendPolicy | undefined): void {\n this.#sendPolicyForPath = resolve;\n }\n\n private deliveryAuthorizer?: (client: WsClient) => boolean | Promise<boolean>;\n private frameLimitForPath?: (path: string) => number | undefined;\n\n constructor(private readonly ctx: DoStateLike) {}\n\n setDeliveryAuthorizer(authorizer: (client: WsClient) => boolean | Promise<boolean>): void {\n this.deliveryAuthorizer = authorizer;\n }\n\n /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */\n setFrameLimitResolver(resolver: (path: string) => number | undefined): void {\n this.frameLimitForPath = resolver;\n }\n\n /**\n * Run `admit` (the connection hook) with `ws` marked as being admitted, so a\n * broadcast issued meanwhile (for example `server.emit()` announcing the new\n * connection) skips the still-pending socket instead of rejecting it.\n */\n async admitting<T>(ws: WsLike, admit: () => Promise<T>): Promise<T> {\n this.#admitting.add(ws);\n try {\n return await admit();\n } finally {\n this.#admitting.delete(ws);\n }\n }\n\n // CF sockets are registered with the DO by `acceptWebSocket`; nothing to track.\n register(_client: WsClient): void {}\n leaveAll(_client: WsClient): void {}\n\n join(client: WsClient, room: string): void | Promise<void> {\n return client.join(room);\n }\n\n leave(client: WsClient, room: string): void | Promise<void> {\n return client.leave(room);\n }\n\n localIdsInRoom(room: string): string[] {\n return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);\n }\n\n deliverLocal(cmd: BroadcastCommand): void | Promise<void> {\n const excludeIds = new Set(cmd.exceptIds ?? []);\n const excludeRooms = cmd.exceptRooms ?? [];\n\n // Empty `rooms` => GLOBAL (every socket in this DO). Otherwise the union of\n // targeted rooms, deduped per connection.\n const targets =\n cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);\n\n const seen = new Set<string>();\n const selected: Array<{ ws: WsLike; client: WsClient }> = [];\n for (const ws of targets) {\n const stored = this.attachmentOf(ws);\n // A gateway-scoped push never touches another gateway's sockets.\n if (cmd.gatewayPath !== undefined && stored.path !== cmd.gatewayPath) continue;\n const att = this.reconcileFrameLimit(ws, stored);\n // A socket still in its connection hook is not admitted yet: it receives no\n // room frames, and its own accept() settles it. Rejecting it here would\n // close every client whose handleConnection broadcasts to the room. Other\n // pending sockets fall through and are rejected below.\n if (att.state === 'pending' && this.#admitting.has(ws)) continue;\n if (\n att.state !== 'active' ||\n (att.expiresAtMs !== undefined &&\n (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now()))\n ) {\n try {\n att.state = 'rejected';\n ws.serializeAttachment(att);\n ws.close(1008, 'identity expired or connection rejected');\n } catch {\n // already closed or malformed attachment\n }\n continue;\n }\n if (seen.has(att.connId)) continue;\n seen.add(att.connId);\n if (excludeIds.has(att.connId)) continue;\n if (excludeRooms.some((r) => att.rooms.includes(r))) continue;\n selected.push({ ws, client: this.clientFor(ws) });\n }\n\n if (!this.deliveryAuthorizer) {\n for (const { client } of selected) client.sendRaw(cmd.frame);\n return;\n }\n return Promise.all(\n selected.map(async ({ ws, client }) => {\n let allowed = false;\n try {\n allowed = (await this.deliveryAuthorizer!(client)) === true;\n } catch {\n allowed = false;\n }\n if (allowed) client.sendRaw(cmd.frame);\n else this.reject(ws, 'delivery authorization revoked');\n }),\n ).then(() => undefined);\n }\n\n private collectRooms(rooms: string[]): WsLike[] {\n const set = new Set<WsLike>();\n for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);\n return [...set];\n }\n\n private socketsForRoom(room: string): WsLike[] {\n // Membership is the attachment's `rooms`, NOT the hibernation tag: tags are\n // immutable after acceptWebSocket, so a socket that left its hub room still\n // carries the tag. Since one DO ≈ one room, scanning all sockets in the DO\n // and filtering by attachment is both correct and cheap.\n return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));\n }\n\n private attachmentOf(ws: WsLike): WsAttachment {\n return socketAttachment(ws) ?? rejectedAttachment();\n }\n\n /** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */\n clientFor(ws: WsLike): CfWsClient {\n this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n let gate = this.#sendGates.get(ws);\n if (!gate) {\n gate = new WebSocketSendGate(this.#sendPolicyForPath?.(this.attachmentOf(ws).path));\n this.#sendGates.set(ws, gate);\n }\n return new CfWsClient(this.ctx, ws, gate);\n }\n\n private reconcileFrameLimit(ws: WsLike, attachment: WsAttachment): WsAttachment {\n const expected = this.frameLimitForPath?.(attachment.path);\n if (expected !== undefined && attachment.maxFrameBytes !== expected) {\n attachment.maxFrameBytes = expected;\n ws.serializeAttachment(attachment);\n }\n return attachment;\n }\n\n private reject(ws: WsLike, reason: string): void {\n try {\n const attachment = this.attachmentOf(ws);\n attachment.state = 'rejected';\n ws.serializeAttachment(attachment);\n ws.close(1008, reason);\n } catch {\n // already closed or malformed attachment\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,iBAAb,MAAoD;CAerB;CAd7B,6BAAsB,IAAI,QAAmC;CAI7D,6BAAsB,IAAI,QAAgB;CAC1C;CAEA,sBAAsB,SAAkE;EACtF,KAAK,qBAAqB;CAC5B;CAEA;CACA;CAEA,YAAY,KAAmC;EAAlB,KAAA,MAAA;CAAmB;CAEhD,sBAAsB,YAAoE;EACxF,KAAK,qBAAqB;CAC5B;;CAGA,sBAAsB,UAAsD;EAC1E,KAAK,oBAAoB;CAC3B;;;;;;CAOA,MAAM,UAAa,IAAY,OAAqC;EAClE,KAAK,WAAW,IAAI,EAAE;EACtB,IAAI;GACF,OAAO,MAAM,MAAM;EACrB,UAAU;GACR,KAAK,WAAW,OAAO,EAAE;EAC3B;CACF;CAGA,SAAS,SAAyB,CAAC;CACnC,SAAS,SAAyB,CAAC;CAEnC,KAAK,QAAkB,MAAoC;EACzD,OAAO,OAAO,KAAK,IAAI;CACzB;CAEA,MAAM,QAAkB,MAAoC;EAC1D,OAAO,OAAO,MAAM,IAAI;CAC1B;CAEA,eAAe,MAAwB;EACrC,OAAO,KAAK,eAAe,IAAI,CAAC,CAAC,KAAK,OAAO,KAAK,aAAa,EAAE,CAAC,CAAC,MAAM;CAC3E;CAEA,aAAa,KAA6C;EACxD,MAAM,aAAa,IAAI,IAAI,IAAI,aAAa,CAAC,CAAC;EAC9C,MAAM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Gate, type WebSocketSendPolicy } from '@velajs/vela/websocket';\nimport { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { BroadcastCommand, RoomRegistry, WsClient } from '@velajs/vela/websocket';\nimport type { DoStateLike, WsAttachment, WsLike } from './do-state';\nimport { CfWsClient } from './cf-ws-client';\n\n/**\n * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room\n * membership lives in tags (hub room, set at accept) + the attachment (dynamic\n * `join()`), never in DO instance fields — so it survives hibernation with zero\n * rehydration.\n */\nexport class CfRoomRegistry implements RoomRegistry {\n readonly #sendGates = new WeakMap<WsLike, WebSocketSendGate>();\n // Sockets whose OnGatewayConnection hook is running in this instance. They\n // are still `pending`, so broadcasts skip them; any other pending socket\n // never finished admission and is closed when a broadcast reaches it.\n readonly #admitting = new WeakSet<WsLike>();\n #sendPolicyForPath?: (path: string) => WebSocketSendPolicy | undefined;\n\n setSendPolicyResolver(resolve: (path: string) => WebSocketSendPolicy | undefined): void {\n this.#sendPolicyForPath = resolve;\n }\n\n private deliveryAuthorizer?: (client: WsClient) => boolean | Promise<boolean>;\n private frameLimitForPath?: (path: string) => number | undefined;\n\n constructor(private readonly ctx: DoStateLike) {}\n\n setDeliveryAuthorizer(authorizer: (client: WsClient) => boolean | Promise<boolean>): void {\n this.deliveryAuthorizer = authorizer;\n }\n\n /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */\n setFrameLimitResolver(resolver: (path: string) => number | undefined): void {\n this.frameLimitForPath = resolver;\n }\n\n /**\n * Run `admit` (the connection hook) with `ws` marked as being admitted, so a\n * broadcast issued meanwhile (for example `server.emit()` announcing the new\n * connection) skips the still-pending socket instead of rejecting it.\n */\n async admitting<T>(ws: WsLike, admit: () => Promise<T>): Promise<T> {\n this.#admitting.add(ws);\n try {\n return await admit();\n } finally {\n this.#admitting.delete(ws);\n }\n }\n\n // CF sockets are registered with the DO by `acceptWebSocket`; nothing to track.\n register(_client: WsClient): void {}\n leaveAll(_client: WsClient): void {}\n\n join(client: WsClient, room: string): void | Promise<void> {\n return client.join(room);\n }\n\n leave(client: WsClient, room: string): void | Promise<void> {\n return client.leave(room);\n }\n\n localIdsInRoom(room: string): string[] {\n return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);\n }\n\n deliverLocal(cmd: BroadcastCommand): void | Promise<void> {\n const excludeIds = new Set(cmd.exceptIds ?? []);\n const excludeRooms = cmd.exceptRooms ?? [];\n\n // Empty `rooms` => GLOBAL (every socket in this DO). Otherwise the union of\n // targeted rooms, deduped per connection.\n const targets =\n cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);\n\n const seen = new Set<string>();\n const selected: Array<{ ws: WsLike; client: WsClient }> = [];\n for (const ws of targets) {\n const stored = this.attachmentOf(ws);\n // A gateway-scoped push never touches another gateway's sockets.\n if (cmd.gatewayPath !== undefined && stored.path !== cmd.gatewayPath) continue;\n const att = this.reconcileFrameLimit(ws, stored);\n // A socket still in its connection hook is not admitted yet: it receives no\n // room frames, and its own accept() settles it. Rejecting it here would\n // close every client whose handleConnection broadcasts to the room. Other\n // pending sockets fall through and are rejected below.\n if (att.state === 'pending' && this.#admitting.has(ws)) continue;\n if (\n att.state !== 'active' ||\n (att.expiresAtMs !== undefined &&\n (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now()))\n ) {\n try {\n att.state = 'rejected';\n ws.serializeAttachment(att);\n ws.close(1008, 'identity expired or connection rejected');\n } catch {\n // already closed or malformed attachment\n }\n continue;\n }\n if (seen.has(att.connId)) continue;\n seen.add(att.connId);\n if (excludeIds.has(att.connId)) continue;\n if (excludeRooms.some((r) => att.rooms.includes(r))) continue;\n selected.push({ ws, client: this.clientFor(ws) });\n }\n\n if (!this.deliveryAuthorizer) {\n for (const { client } of selected) client.sendRaw(cmd.frame);\n return;\n }\n return Promise.all(\n selected.map(async ({ ws, client }) => {\n let allowed = false;\n try {\n allowed = (await this.deliveryAuthorizer!(client)) === true;\n } catch {\n allowed = false;\n }\n if (allowed) client.sendRaw(cmd.frame);\n else this.reject(ws, 'delivery authorization revoked');\n }),\n ).then(() => undefined);\n }\n\n private collectRooms(rooms: string[]): WsLike[] {\n const set = new Set<WsLike>();\n for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);\n return [...set];\n }\n\n private socketsForRoom(room: string): WsLike[] {\n // Membership is the attachment's `rooms`, NOT the hibernation tag: tags are\n // immutable after acceptWebSocket, so a socket that left its hub room still\n // carries the tag. Since one DO ≈ one room, scanning all sockets in the DO\n // and filtering by attachment is both correct and cheap.\n return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));\n }\n\n private attachmentOf(ws: WsLike): WsAttachment {\n return socketAttachment(ws) ?? rejectedAttachment();\n }\n\n /** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */\n clientFor(ws: WsLike): CfWsClient {\n this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n let gate = this.#sendGates.get(ws);\n if (!gate) {\n gate = new WebSocketSendGate(this.#sendPolicyForPath?.(this.attachmentOf(ws).path));\n this.#sendGates.set(ws, gate);\n }\n return new CfWsClient(this.ctx, ws, gate);\n }\n\n private reconcileFrameLimit(ws: WsLike, attachment: WsAttachment): WsAttachment {\n const expected = this.frameLimitForPath?.(attachment.path);\n if (expected !== undefined && attachment.maxFrameBytes !== expected) {\n attachment.maxFrameBytes = expected;\n ws.serializeAttachment(attachment);\n }\n return attachment;\n }\n\n private reject(ws: WsLike, reason: string): void {\n try {\n const attachment = this.attachmentOf(ws);\n attachment.state = 'rejected';\n ws.serializeAttachment(attachment);\n ws.close(1008, reason);\n } catch {\n // already closed or malformed attachment\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,iBAAb,MAAoD;CAerB;CAdpB,6BAAa,IAAI,QAAmC;CAIpD,6BAAa,IAAI,QAAgB;CAC1C;CAEA,sBAAsB,SAAkE;EACtF,KAAK,qBAAqB;CAC5B;CAEQ;CACA;CA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K,WAAW,IAAI,EAAE;EACjC,IAAI,CAAC,MAAM;GACT,OAAO,IAAI,kBAAkB,KAAK,qBAAqB,KAAK,aAAa,EAAE,CAAC,CAAC,IAAI,CAAC;GAClF,KAAK,WAAW,IAAI,IAAI,IAAI;EAC9B;EACA,OAAO,IAAI,WAAW,KAAK,KAAK,IAAI,IAAI;CAC1C;CAEQ,oBAAoB,IAAY,YAAwC;EAC9E,MAAM,WAAW,KAAK,oBAAoB,WAAW,IAAI;EACzD,IAAI,aAAa,KAAA,KAAa,WAAW,kBAAkB,UAAU;GACnE,WAAW,gBAAgB;GAC3B,GAAG,oBAAoB,UAAU;EACnC;EACA,OAAO;CACT;CAEQ,OAAO,IAAY,QAAsB;EAC/C,IAAI;GACF,MAAM,aAAa,KAAK,aAAa,EAAE;GACvC,WAAW,QAAQ;GACnB,GAAG,oBAAoB,UAAU;GACjC,GAAG,MAAM,MAAM,MAAM;EACvB,QAAQ,CAER;CACF;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { rejectedAttachment, socketAttachment } from "./ws-attachment.js";
2
- import { MAX_WS_ATTACHMENT_BYTES } from "./do-state.js";
3
2
  import { DEFAULT_WS_MAX_FRAME_BYTES, DEFAULT_WS_MAX_JOINED_ROOMS, WebSocketSendGate, assertWebSocketRoomId } from "@velajs/vela/websocket";
4
- //#region src/websocket/cf-ws-client.ts
3
+ import { MAX_WS_ATTACHMENT_BYTES } from "./do-state.js";
4
+ // src/websocket/cf-ws-client.ts
5
5
  const encoder = new TextEncoder();
6
6
  /**
7
7
  * Core `WsClient` over a native Cloudflare `WebSocket` inside a Durable Object.
@@ -88,7 +88,6 @@ var CfWsClient = class {
88
88
  this.ws.serializeAttachment(this.#attachment);
89
89
  }
90
90
  };
91
- //#endregion
92
91
  export { CfWsClient };
93
92
 
94
93
  //# sourceMappingURL=cf-ws-client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cf-ws-client.js","names":[],"sources":["../../src/websocket/cf-ws-client.ts"],"sourcesContent":["import { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { WebSocketSendResult, WsClient } from '@velajs/vela/websocket';\nimport {\n assertWebSocketRoomId,\n DEFAULT_WS_MAX_FRAME_BYTES,\n DEFAULT_WS_MAX_JOINED_ROOMS,\n WebSocketSendGate,\n} from '@velajs/vela/websocket';\nimport {\n MAX_WS_ATTACHMENT_BYTES,\n type DoStateLike,\n type WsAttachment,\n type WsLike,\n} from './do-state';\nconst encoder = new TextEncoder();\n\n/**\n * Core `WsClient` over a native Cloudflare `WebSocket` inside a Durable Object.\n * Per-connection state lives in the hibernation attachment (survives eviction),\n * so a fresh `CfWsClient` is reconstructed per message with no in-memory state.\n */\nexport class CfWsClient<\n TData extends Record<string, unknown> = Record<string, unknown>,\n> implements WsClient<TData> {\n readonly #attachment: WsAttachment;\n\n constructor(\n private readonly ctx: DoStateLike,\n private readonly ws: WsLike,\n private readonly sendGate = new WebSocketSendGate(),\n ) {\n this.#attachment = socketAttachment(ws) ?? rejectedAttachment();\n }\n\n get id(): string {\n return this.#attachment.connId;\n }\n\n /** The gateway route path this socket connected on (used to route messages). */\n get path(): string {\n return this.#attachment.path;\n }\n\n get rooms(): ReadonlySet<string> {\n return new Set(this.#attachment.rooms);\n }\n\n get data(): TData {\n return this.#attachment.data as TData;\n }\n\n set data(value: TData) {\n this.#attachment.data = value;\n }\n\n get raw(): unknown {\n return this.ws;\n }\n\n get maxFrameBytes(): number {\n const value = this.#attachment.maxFrameBytes;\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n ? value\n : DEFAULT_WS_MAX_FRAME_BYTES;\n }\n\n send(event: string, data?: unknown, id?: string): void {\n this.sendRaw(JSON.stringify(id !== undefined ? { id, event, data } : { event, data }));\n }\n\n sendRaw(payload: string): void {\n this.trySendRaw(payload);\n }\n\n trySendRaw(payload: string): WebSocketSendResult {\n if (this.#attachment.state === 'rejected') return 'closed';\n return this.sendGate.trySend(this.ws, payload, this.maxFrameBytes);\n }\n\n join(room: string): void {\n assertWebSocketRoomId(room);\n if (!this.#attachment.rooms.includes(room)) {\n if (this.#attachment.rooms.length >= DEFAULT_WS_MAX_JOINED_ROOMS) {\n throw new Error(`A WebSocket may join at most ${DEFAULT_WS_MAX_JOINED_ROOMS} rooms`);\n }\n this.#attachment.rooms.push(room);\n this.persist();\n }\n }\n\n leave(room: string): void {\n const next = this.#attachment.rooms.filter((r) => r !== room);\n if (next.length !== this.#attachment.rooms.length) {\n this.#attachment.rooms = next;\n this.persist();\n }\n }\n\n /** Persist `data`/room mutations to the hibernation attachment. */\n commit(): void {\n this.persist();\n }\n\n close(code?: number, reason?: string): void {\n this.ws.close(code, reason);\n }\n\n private persist(): void {\n if (this.#attachment.state === 'rejected') throw new Error('Invalid WebSocket attachment');\n const serialized = JSON.stringify(this.#attachment);\n if (encoder.encode(serialized).length > MAX_WS_ATTACHMENT_BYTES) {\n throw new Error(\n `WebSocket attachment exceeds the 16 KiB Cloudflare limit. Store large ` +\n `per-connection state in Durable Object storage keyed by connId instead.`,\n );\n }\n this.ws.serializeAttachment(this.#attachment);\n }\n}\n"],"mappings":";;;;AAcA,MAAM,UAAU,IAAI,YAAY;;;;;;AAOhC,IAAa,aAAb,MAE6B;CAIR;CACA;CACA;CALnB;CAEA,YACE,KACA,IACA,WAA4B,IAAI,kBAAkB,GAClD;EAHiB,KAAA,MAAA;EACA,KAAA,KAAA;EACA,KAAA,WAAA;EAEjB,KAAK,cAAc,iBAAiB,EAAE,KAAK,mBAAmB;CAChE;CAEA,IAAI,KAAa;EACf,OAAO,KAAK,YAAY;CAC1B;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK,YAAY;CAC1B;CAEA,IAAI,QAA6B;EAC/B,OAAO,IAAI,IAAI,KAAK,YAAY,KAAK;CACvC;CAEA,IAAI,OAAc;EAChB,OAAO,KAAK,YAAY;CAC1B;CAEA,IAAI,KAAK,OAAc;EACrB,KAAK,YAAY,OAAO;CAC1B;CAEA,IAAI,MAAe;EACjB,OAAO,KAAK;C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WAAW;CAC9C;AACF"}
1
+ {"version":3,"file":"cf-ws-client.js","names":[],"sources":["../../src/websocket/cf-ws-client.ts"],"sourcesContent":["import { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { WebSocketSendResult, WsClient } from '@velajs/vela/websocket';\nimport {\n assertWebSocketRoomId,\n DEFAULT_WS_MAX_FRAME_BYTES,\n DEFAULT_WS_MAX_JOINED_ROOMS,\n WebSocketSendGate,\n} from '@velajs/vela/websocket';\nimport {\n MAX_WS_ATTACHMENT_BYTES,\n type DoStateLike,\n type WsAttachment,\n type WsLike,\n} from './do-state';\nconst encoder = new TextEncoder();\n\n/**\n * Core `WsClient` over a native Cloudflare `WebSocket` inside a Durable Object.\n * Per-connection state lives in the hibernation attachment (survives eviction),\n * so a fresh `CfWsClient` is reconstructed per message with no in-memory state.\n */\nexport class CfWsClient<\n TData extends Record<string, unknown> = Record<string, unknown>,\n> implements WsClient<TData> {\n readonly #attachment: WsAttachment;\n\n constructor(\n private readonly ctx: DoStateLike,\n private readonly ws: WsLike,\n private readonly sendGate = new WebSocketSendGate(),\n ) {\n this.#attachment = socketAttachment(ws) ?? rejectedAttachment();\n }\n\n get id(): string {\n return this.#attachment.connId;\n }\n\n /** The gateway route path this socket connected on (used to route messages). */\n get path(): string {\n return this.#attachment.path;\n }\n\n get rooms(): ReadonlySet<string> {\n return new Set(this.#attachment.rooms);\n }\n\n get data(): TData {\n return this.#attachment.data as TData;\n }\n\n set data(value: TData) {\n this.#attachment.data = value;\n }\n\n get raw(): unknown {\n return this.ws;\n }\n\n get maxFrameBytes(): number {\n const value = this.#attachment.maxFrameBytes;\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n ? value\n : DEFAULT_WS_MAX_FRAME_BYTES;\n }\n\n send(event: string, data?: unknown, id?: string): void {\n this.sendRaw(JSON.stringify(id !== undefined ? { id, event, data } : { event, data }));\n }\n\n sendRaw(payload: string): void {\n this.trySendRaw(payload);\n }\n\n trySendRaw(payload: string): WebSocketSendResult {\n if (this.#attachment.state === 'rejected') return 'closed';\n return this.sendGate.trySend(this.ws, payload, this.maxFrameBytes);\n }\n\n join(room: string): void {\n assertWebSocketRoomId(room);\n if (!this.#attachment.rooms.includes(room)) {\n if (this.#attachment.rooms.length >= DEFAULT_WS_MAX_JOINED_ROOMS) {\n throw new Error(`A WebSocket may join at most ${DEFAULT_WS_MAX_JOINED_ROOMS} rooms`);\n }\n this.#attachment.rooms.push(room);\n this.persist();\n }\n }\n\n leave(room: string): void {\n const next = this.#attachment.rooms.filter((r) => r !== room);\n if (next.length !== this.#attachment.rooms.length) {\n this.#attachment.rooms = next;\n this.persist();\n }\n }\n\n /** Persist `data`/room mutations to the hibernation attachment. */\n commit(): void {\n this.persist();\n }\n\n close(code?: number, reason?: string): void {\n this.ws.close(code, reason);\n }\n\n private persist(): void {\n if (this.#attachment.state === 'rejected') throw new Error('Invalid WebSocket attachment');\n const serialized = JSON.stringify(this.#attachment);\n if (encoder.encode(serialized).length > MAX_WS_ATTACHMENT_BYTES) {\n throw new Error(\n `WebSocket attachment exceeds the 16 KiB Cloudflare limit. Store large ` +\n `per-connection state in Durable Object storage keyed by connId instead.`,\n );\n }\n this.ws.serializeAttachment(this.#attachment);\n }\n}\n"],"mappings":";;;;AAcA,MAAM,UAAU,IAAI,YAAY;;;;;;AAOhC,IAAa,aAAb,MAE6B;CAIR;CACA;CACA;CALV;CAET,YACmB,KACA,IACA,WAAW,IAAI,kBAAkB,GAClD;EAHiB,KAAA,MAAA;EACA,KAAA,KAAA;EACA,KAAA,WAAA;EAEjB,KAAK,cAAc,iBAAiB,EAAE,KAAK,mBAAmB;CAChE;CAEA,IAAI,KAAa;EACf,OAAO,KAAK,YAAY;CAC1B;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK,YAAY;CAC1B;CAEA,IAAI,QAA6B;EAC/B,OAAO,IAAI,IAAI,KAAK,YAAY,KAAK;CACvC;CAEA,IAAI,OAAc;EAChB,OAAO,KAAK,YAAY;CAC1B;CA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AO,UAAU,CAAC,CAAC,SAAS,yBACtC,MAAM,IAAI,MACR,+IAEF;EAEF,KAAK,GAAG,oBAAoB,KAAK,WAAW;CAC9C;AACF"}
@@ -1,10 +1,10 @@
1
- import { gatewayRoomObject } from "./worker-transport.js";
1
+ import { WsDispatcher, WsServerImpl, local, readWsEntrypointMeta } from "@velajs/vela/websocket";
2
+ import { createDurableObjectContext } from "../durable-object/boot.js";
2
3
  import { CfWsClient } from "./cf-ws-client.js";
3
- import { durableObjectLivePlatform, initDoLive } from "./do-live.js";
4
4
  import { CfRoomRegistry } from "./cf-room-registry.js";
5
- import { createDurableObjectContext } from "../durable-object/boot.js";
6
- import { WsDispatcher, WsServerImpl, local, readWsEntrypointMeta } from "@velajs/vela/websocket";
7
- //#region src/websocket/do-bootstrap.ts
5
+ import { durableObjectLivePlatform, initDoLive } from "./do-live.js";
6
+ import { gatewayRoomObject } from "./worker-transport.js";
7
+ // src/websocket/do-bootstrap.ts
8
8
  /** Whether a Durable Object id names this object. */
9
9
  function isThisObject(id, ctx) {
10
10
  const equals = typeof id === "object" && id !== null ? Reflect.get(id, "equals") : void 0;
@@ -74,7 +74,6 @@ async function buildDoRuntime(rootModule, ctx, options) {
74
74
  throw error;
75
75
  }
76
76
  }
77
- //#endregion
78
77
  export { buildDoRuntime };
79
78
 
80
79
  //# sourceMappingURL=do-bootstrap.js.map
@@ -1,8 +1,8 @@
1
- import { gatewayObjectRoom, roomToDurableId } from "./room-id.js";
2
- import { CfLiveDriver } from "./live-driver.js";
3
- import { CfWsClient } from "./cf-ws-client.js";
4
1
  import { LiveEngine, localLive, readPersistedLiveSubscriptions } from "@velajs/vela/live";
5
- //#region src/websocket/do-live.ts
2
+ import { CfWsClient } from "./cf-ws-client.js";
3
+ import { CfLiveDriver } from "./live-driver.js";
4
+ import { gatewayObjectRoom, roomToDurableId } from "./room-id.js";
5
+ // src/websocket/do-live.ts
6
6
  const DEFAULT_MAX_LOG_ROWS = 4096;
7
7
  /**
8
8
  * The durable `CursorLog`: an append-only tag-invalidation log in the DO's
@@ -137,7 +137,6 @@ async function liveInvalidateToRoom(ns, gatewayPath, room, tags) {
137
137
  tags
138
138
  });
139
139
  }
140
- //#endregion
141
140
  export { DoCursorLog, durableObjectLivePlatform, initDoLive, liveInvalidateToRoom };
142
141
 
143
142
  //# sourceMappingURL=do-live.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"do-live.js","names":[],"sources":["../../src/websocket/do-live.ts"],"sourcesContent":["import type { CfRoomRegistry } from './cf-room-registry';\nimport { LiveEngine, localLive, readPersistedLiveSubscriptions } from '@velajs/vela/live';\nimport type { CommitStamp, CursorLog, LivePlatform, ResumeVerdict } from '@velajs/vela/live';\nimport { CfWsClient } from './cf-ws-client';\nimport type { DoStateLike, SqlStorageLike } from './do-state';\nimport { CfLiveDriver, type LiveNamespace } from './live-driver';\nimport { gatewayObjectRoom, roomToDurableId } from './room-id';\n\nconst DEFAULT_MAX_LOG_ROWS = 4096;\n\n/**\n * The durable `CursorLog`: an append-only tag-invalidation log in the DO's\n * SQLite (`__vela_live_log`, AUTOINCREMENT seq = cursor) plus an epoch UUID in\n * `__vela_live_meta`. Because the cursor survives hibernation AND trims (it is\n * read from `sqlite_sequence`, lunora's `ctx-db-cdc.ts` trick), a reconnecting\n * client whose gap the log still covers gets a tiny `resume` instead of a\n * re-run — the real-resume half of the live protocol.\n *\n * The Cloudflare adapter gives `LiveModule` one inside every SQLite-backed\n * WebSocket Durable Object (wrangler: `new_sqlite_classes`); a class without\n * SQLite keeps an in-memory log. The Worker never consults a log: its\n * invalidations go to the room Durable Object, one log scope per room, exactly\n * the protocol's model.\n */\nexport class DoCursorLog implements CursorLog {\n private readonly epoch: string;\n\n constructor(\n private readonly sql: SqlStorageLike,\n private readonly maxRows = DEFAULT_MAX_LOG_ROWS,\n ) {\n sql.exec(\n 'CREATE TABLE IF NOT EXISTS __vela_live_log (seq INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL NOT NULL, tags TEXT NOT NULL)',\n );\n sql.exec('CREATE TABLE IF NOT EXISTS __vela_live_meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)');\n const row = sql.exec(\"SELECT v FROM __vela_live_meta WHERE k = 'epoch'\").toArray()[0];\n if (row && typeof row.v === 'string') {\n this.epoch = row.v;\n } else {\n this.epoch = crypto.randomUUID();\n sql.exec(\"INSERT INTO __vela_live_meta (k, v) VALUES ('epoch', ?)\", this.epoch);\n }\n }\n\n append(tags: string[]): CommitStamp {\n this.sql.exec(\n 'INSERT INTO __vela_live_log (ts, tags) VALUES (?, ?)',\n Date.now(),\n JSON.stringify(tags),\n );\n const stamp = this.current();\n // Bounded retention: trimmed gaps degrade to snapshot-on-reconnect.\n if (stamp.cursor > this.maxRows) {\n this.sql.exec('DELETE FROM __vela_live_log WHERE seq <= ?', stamp.cursor - this.maxRows);\n }\n return stamp;\n }\n\n current(): CommitStamp {\n // sqlite_sequence survives DELETE-based trims, so the cursor never\n // rewinds. The table itself only materializes on the first AUTOINCREMENT\n // insert — before that the log is empty and the cursor is 0.\n let cursor = 0;\n try {\n const row = this.sql\n .exec(\"SELECT seq FROM sqlite_sequence WHERE name = '__vela_live_log'\")\n .toArray()[0];\n cursor = typeof row?.seq === 'number' ? row.seq : Number(row?.seq ?? 0);\n } catch {\n cursor = 0;\n }\n return { cursor, epoch: this.epoch };\n }\n\n evaluateResume(\n sinceCursor: number,\n sinceEpoch: string,\n subscriptionTags: string[],\n ): ResumeVerdict {\n const { cursor, epoch } = this.current();\n if (sinceEpoch !== epoch) return 'snapshot'; // forked timeline (reset/recreated DO)\n if (sinceCursor > cursor) return 'snapshot'; // rollback guard\n if (sinceCursor === cursor) return 'resume';\n\n const minRow = this.sql.exec('SELECT MIN(seq) AS m FROM __vela_live_log').toArray()[0];\n const min = minRow?.m == null ? undefined : Number(minRow.m);\n // The log must still cover (sinceCursor, cursor] — a trimmed gap cannot be reasoned about.\n if (min === undefined || min > sinceCursor + 1) return 'snapshot';\n\n const subTags = new Set(subscriptionTags);\n for (const row of this.sql\n .exec('SELECT tags FROM __vela_live_log WHERE seq > ?', sinceCursor)\n .toArray()) {\n let tags: unknown;\n try {\n tags = JSON.parse(String(row.tags));\n } catch {\n return 'snapshot';\n }\n if (\n Array.isArray(tags) &&\n tags.some((tag: unknown) => typeof tag === 'string' && subTags.has(tag))\n )\n return 'rerun';\n }\n return 'resume';\n }\n}\n\n/**\n * The object's SQLite handle, or undefined when its class is not SQLite-backed.\n * workerd exposes `ctx.storage.sql` on every class; without SQLite (wrangler\n * `new_classes`) each statement throws, so probe with one.\n */\nfunction sqliteStorage(ctx: DoStateLike): SqlStorageLike | undefined {\n try {\n const sql = ctx.storage?.sql;\n sql?.exec('SELECT 1');\n return sql;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The live platform inside a WebSocket Durable Object: invalidations apply to\n * this object's own engine (a `durableObjectLive()` driver switches to local\n * delivery), and the cursor log lives in its SQLite storage when the class is\n * SQLite-backed, in memory otherwise (snapshot-on-reconnect after eviction).\n */\nexport function durableObjectLivePlatform(ctx: DoStateLike): LivePlatform {\n return {\n liveDriver: () => localLive(),\n cursorLog() {\n const sql = sqliteStorage(ctx);\n return sql ? new DoCursorLog(sql) : undefined;\n },\n bindDriver(driver) {\n if (driver instanceof CfLiveDriver) driver._setLocalMode();\n },\n };\n}\n\n/** The app-facing surface of the engine reached through `app.entrypoints.ofKind('live')`. */\ninterface EntrypointsApp {\n entrypoints: { ofKind(kind: string): Array<{ meta: unknown }> };\n}\n\n/**\n * DO-side wiring after lifecycle, called from `buildDoRuntime`: replay every hibernation-persisted\n * subscription into the (fresh) engine so an eviction is invisible to\n * subscribers. Returns the engine for the `invalidate` RPC, or undefined when\n * the app doesn't use LiveModule.\n */\nexport function initDoLive(\n app: EntrypointsApp,\n ctx: DoStateLike,\n registry?: CfRoomRegistry,\n): LiveEngine | undefined {\n const entry = app.entrypoints.ofKind('live')[0];\n if (!entry) return undefined;\n if (typeof entry.meta !== 'object' || entry.meta === null || !('engine' in entry.meta)) {\n throw new Error('Invalid live entrypoint metadata.');\n }\n const engine = entry.meta.engine;\n if (!(engine instanceof LiveEngine)) throw new Error('Invalid live entrypoint engine.');\n\n // Wake-time replay: subscriptions ride the hibernation attachments.\n for (const ws of ctx.getWebSockets()) {\n const client = registry?.clientFor(ws) ?? new CfWsClient(ctx, ws);\n if (!client.id) continue;\n for (const record of readPersistedLiveSubscriptions(client)) {\n engine.restoreSubscription(client.path, client, record);\n }\n }\n\n return engine;\n}\n\n/**\n * Invalidate live tags in a room from a Worker (controller / cron / queue\n * consumer) through an explicit namespace. Returns the room log scope's\n * commit stamp for `Vela-Commit-Cursor` stamping. As with the live driver, a\n * gateway without roomParam keeps every room in one object, named by its path.\n */\nexport async function liveInvalidateToRoom(\n ns: LiveNamespace,\n gatewayPath: string,\n room: string,\n tags: string[],\n): Promise<CommitStamp | undefined> {\n const stub = ns.get(roomToDurableId(ns, gatewayPath, gatewayObjectRoom(gatewayPath, room)));\n return stub.invalidate({ room, tags });\n}\n"],"mappings":";;;;;AAQA,MAAM,uBAAuB;;;;;;;;;;;;;;;AAgB7B,IAAa,cAAb,MAA8C;CAIzB;CACA;CAJnB;CAEA,YACE,KACA,UAA2B,sBAC3B;EAFiB,KAAA,MAAA;EACA,KAAA,UAAA;EAEjB,IAAI,KACF,0HACF;EACA,IAAI,KAAK,mFAAmF;EAC5F,MAAM,MAAM,IAAI,KAAK,kDAAkD,CAAC,CAAC,QAAQ,CAAC,CAAC;EACnF,IAAI,OAAO,OAAO,IAAI,MAAM,UAC1B,KAAK,QAAQ,IAAI;OACZ;GACL,KAAK,QAAQ,OAAO,WAAW;GAC/B,IAAI,KAAK,2DAA2D,KAAK,KAAK;EAChF;CACF;CAEA,OAAO,MAA6B;EAClC,KAAK,IAAI,KACP,wDACA,KAAK,IAAI,GACT,KAAK,UAAU,IAAI,CACrB;EACA,MAAM,QAAQ,KAAK,QAAQ;EAE3B,IAAI,MAAM,SAAS,KAAK,SACtB,KAAK,IAAI,K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,kBAAkB,UAAU;EAC5B,YAAY;GACV,MAAM,MAAM,cAAc,GAAG;GAC7B,OAAO,MAAM,IAAI,YAAY,GAAG,IAAI,KAAA;EACtC;EACA,WAAW,QAAQ;GACjB,IAAI,kBAAkB,cAAc,OAAO,cAAc;EAC3D;CACF;AACF;;;;;;;AAaA,SAAgB,WACd,KACA,KACA,UACwB;CACxB,MAAM,QAAQ,IAAI,YAAY,OAAO,MAAM,CAAC,CAAC;CAC7C,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,OAAO,MAAM,SAAS,YAAY,MAAM,SAAS,QAAQ,EAAE,YAAY,MAAM,OAC/E,MAAM,IAAI,MAAM,mCAAmC;CAErD,MAAM,SAAS,MAAM,KAAK;CAC1B,IAAI,EAAE,kBAAkB,aAAa,MAAM,IAAI,MAAM,iCAAiC;CAGtF,KAAK,MAAM,MAAM,IAAI,cAAc,GAAG;EACpC,MAAM,SAAS,UAAU,UAAU,EAAE,KAAK,IAAI,WAAW,KAAK,EAAE;EAChE,IAAI,CAAC,OAAO,IAAI;EAChB,KAAK,MAAM,UAAU,+BAA+B,MAAM,GACxD,OAAO,oBAAoB,OAAO,MAAM,QAAQ,MAAM;CAE1D;CAEA,OAAO;AACT;;;;;;;AAQA,eAAsB,qBACpB,IACA,aACA,MACA,MACkC;CAElC,OADa,GAAG,IAAI,gBAAgB,IAAI,aAAa,kBAAkB,aAAa,IAAI,CAAC,CAC/E,CAAC,CAAC,WAAW;EAAE;EAAM;CAAK,CAAC;AACvC"}
1
+ {"version":3,"file":"do-live.js","names":[],"sources":["../../src/websocket/do-live.ts"],"sourcesContent":["import type { CfRoomRegistry } from './cf-room-registry';\nimport { LiveEngine, localLive, readPersistedLiveSubscriptions } from '@velajs/vela/live';\nimport type { CommitStamp, CursorLog, LivePlatform, ResumeVerdict } from '@velajs/vela/live';\nimport { CfWsClient } from './cf-ws-client';\nimport type { DoStateLike, SqlStorageLike } from './do-state';\nimport { CfLiveDriver, type LiveNamespace } from './live-driver';\nimport { gatewayObjectRoom, roomToDurableId } from './room-id';\n\nconst DEFAULT_MAX_LOG_ROWS = 4096;\n\n/**\n * The durable `CursorLog`: an append-only tag-invalidation log in the DO's\n * SQLite (`__vela_live_log`, AUTOINCREMENT seq = cursor) plus an epoch UUID in\n * `__vela_live_meta`. Because the cursor survives hibernation AND trims (it is\n * read from `sqlite_sequence`, lunora's `ctx-db-cdc.ts` trick), a reconnecting\n * client whose gap the log still covers gets a tiny `resume` instead of a\n * re-run — the real-resume half of the live protocol.\n *\n * The Cloudflare adapter gives `LiveModule` one inside every SQLite-backed\n * WebSocket Durable Object (wrangler: `new_sqlite_classes`); a class without\n * SQLite keeps an in-memory log. The Worker never consults a log: its\n * invalidations go to the room Durable Object, one log scope per room, exactly\n * the protocol's model.\n */\nexport class DoCursorLog implements CursorLog {\n private readonly epoch: string;\n\n constructor(\n private readonly sql: SqlStorageLike,\n private readonly maxRows = DEFAULT_MAX_LOG_ROWS,\n ) {\n sql.exec(\n 'CREATE TABLE IF NOT EXISTS __vela_live_log (seq INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL NOT NULL, tags TEXT NOT NULL)',\n );\n sql.exec('CREATE TABLE IF NOT EXISTS __vela_live_meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)');\n const row = sql.exec(\"SELECT v FROM __vela_live_meta WHERE k = 'epoch'\").toArray()[0];\n if (row && typeof row.v === 'string') {\n this.epoch = row.v;\n } else {\n this.epoch = crypto.randomUUID();\n sql.exec(\"INSERT INTO __vela_live_meta (k, v) VALUES ('epoch', ?)\", this.epoch);\n }\n }\n\n append(tags: string[]): CommitStamp {\n this.sql.exec(\n 'INSERT INTO __vela_live_log (ts, tags) VALUES (?, ?)',\n Date.now(),\n JSON.stringify(tags),\n );\n const stamp = this.current();\n // Bounded retention: trimmed gaps degrade to snapshot-on-reconnect.\n if (stamp.cursor > this.maxRows) {\n this.sql.exec('DELETE FROM __vela_live_log WHERE seq <= ?', stamp.cursor - this.maxRows);\n }\n return stamp;\n }\n\n current(): CommitStamp {\n // sqlite_sequence survives DELETE-based trims, so the cursor never\n // rewinds. The table itself only materializes on the first AUTOINCREMENT\n // insert — before that the log is empty and the cursor is 0.\n let cursor = 0;\n try {\n const row = this.sql\n .exec(\"SELECT seq FROM sqlite_sequence WHERE name = '__vela_live_log'\")\n .toArray()[0];\n cursor = typeof row?.seq === 'number' ? row.seq : Number(row?.seq ?? 0);\n } catch {\n cursor = 0;\n }\n return { cursor, epoch: this.epoch };\n }\n\n evaluateResume(\n sinceCursor: number,\n sinceEpoch: string,\n subscriptionTags: string[],\n ): ResumeVerdict {\n const { cursor, epoch } = this.current();\n if (sinceEpoch !== epoch) return 'snapshot'; // forked timeline (reset/recreated DO)\n if (sinceCursor > cursor) return 'snapshot'; // rollback guard\n if (sinceCursor === cursor) return 'resume';\n\n const minRow = this.sql.exec('SELECT MIN(seq) AS m FROM __vela_live_log').toArray()[0];\n const min = minRow?.m == null ? undefined : Number(minRow.m);\n // The log must still cover (sinceCursor, cursor] — a trimmed gap cannot be reasoned about.\n if (min === undefined || min > sinceCursor + 1) return 'snapshot';\n\n const subTags = new Set(subscriptionTags);\n for (const row of this.sql\n .exec('SELECT tags FROM __vela_live_log WHERE seq > ?', sinceCursor)\n .toArray()) {\n let tags: unknown;\n try {\n tags = JSON.parse(String(row.tags));\n } catch {\n return 'snapshot';\n }\n if (\n Array.isArray(tags) &&\n tags.some((tag: unknown) => typeof tag === 'string' && subTags.has(tag))\n )\n return 'rerun';\n }\n return 'resume';\n }\n}\n\n/**\n * The object's SQLite handle, or undefined when its class is not SQLite-backed.\n * workerd exposes `ctx.storage.sql` on every class; without SQLite (wrangler\n * `new_classes`) each statement throws, so probe with one.\n */\nfunction sqliteStorage(ctx: DoStateLike): SqlStorageLike | undefined {\n try {\n const sql = ctx.storage?.sql;\n sql?.exec('SELECT 1');\n return sql;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The live platform inside a WebSocket Durable Object: invalidations apply to\n * this object's own engine (a `durableObjectLive()` driver switches to local\n * delivery), and the cursor log lives in its SQLite storage when the class is\n * SQLite-backed, in memory otherwise (snapshot-on-reconnect after eviction).\n */\nexport function durableObjectLivePlatform(ctx: DoStateLike): LivePlatform {\n return {\n liveDriver: () => localLive(),\n cursorLog() {\n const sql = sqliteStorage(ctx);\n return sql ? new DoCursorLog(sql) : undefined;\n },\n bindDriver(driver) {\n if (driver instanceof CfLiveDriver) driver._setLocalMode();\n },\n };\n}\n\n/** The app-facing surface of the engine reached through `app.entrypoints.ofKind('live')`. */\ninterface EntrypointsApp {\n entrypoints: { ofKind(kind: string): Array<{ meta: unknown }> };\n}\n\n/**\n * DO-side wiring after lifecycle, called from `buildDoRuntime`: replay every hibernation-persisted\n * subscription into the (fresh) engine so an eviction is invisible to\n * subscribers. Returns the engine for the `invalidate` RPC, or undefined when\n * the app doesn't use LiveModule.\n */\nexport function initDoLive(\n app: EntrypointsApp,\n ctx: DoStateLike,\n registry?: CfRoomRegistry,\n): LiveEngine | undefined {\n const entry = app.entrypoints.ofKind('live')[0];\n if (!entry) return undefined;\n if (typeof entry.meta !== 'object' || entry.meta === null || !('engine' in entry.meta)) {\n throw new Error('Invalid live entrypoint metadata.');\n }\n const engine = entry.meta.engine;\n if (!(engine instanceof LiveEngine)) throw new Error('Invalid live entrypoint engine.');\n\n // Wake-time replay: subscriptions ride the hibernation attachments.\n for (const ws of ctx.getWebSockets()) {\n const client = registry?.clientFor(ws) ?? new CfWsClient(ctx, ws);\n if (!client.id) continue;\n for (const record of readPersistedLiveSubscriptions(client)) {\n engine.restoreSubscription(client.path, client, record);\n }\n }\n\n return engine;\n}\n\n/**\n * Invalidate live tags in a room from a Worker (controller / cron / queue\n * consumer) through an explicit namespace. Returns the room log scope's\n * commit stamp for `Vela-Commit-Cursor` stamping. As with the live driver, a\n * gateway without roomParam keeps every room in one object, named by its path.\n */\nexport async function liveInvalidateToRoom(\n ns: LiveNamespace,\n gatewayPath: string,\n room: string,\n tags: string[],\n): Promise<CommitStamp | undefined> {\n const stub = ns.get(roomToDurableId(ns, gatewayPath, gatewayObjectRoom(gatewayPath, room)));\n return stub.invalidate({ room, tags });\n}\n"],"mappings":";;;;;AAQA,MAAM,uBAAuB;;;;;;;;;;;;;;;AAgB7B,IAAa,cAAb,MAA8C;CAIzB;CACA;CAJF;CAEjB,YACmB,KACA,UAAU,sBAC3B;EAFiB,KAAA,MAAA;EACA,KAAA,UAAA;EAEjB,IAAI,KACF,0HACF;EACA,IAAI,KAAK,mFAAmF;EAC5F,MAAM,MAAM,IAAI,KAAK,kDAAkD,CAAC,CAAC,QAAQ,CAAC,CAAC;EACnF,IAAI,OAAO,OAAO,IAAI,MAAM,UAC1B,KAAK,QAAQ,IAAI;OACZ;GACL,KAAK,QAAQ,OAAO,WAAW;GAC/B,IAAI,KAAK,2DAA2D,KAAK,KAAK;EAChF;CACF;CAEA,OAAO,MAA6B;EAClC,KAAK,IAAI,KACP,wDACA,KAAK,IAAI,GACT,KAAK,UAAU,IAAI,CACrB;EACA,MAAM,QAAQ,KAAK,QAAQ;EAE3B,IAAI,MAAM,SAAS,KAAK,SACtB,KAAK,IAAI,KAAK,8CAA8C,MAAM,SAAS,KAAK,OAAO;EAEzF,OAAO;CACT;CAEA,UAAuB;EAIrB,IAAI,SAAS;EACb,IAAI;GACF,MAAM,MAAM,KAAK,IACd,KAAK,gEAAgE,CAAC,CACtE,QAAQ,CAAC,CAAC;GACb,SAAS,OAAO,KAAK,QAAQ,WAAW,IAAI,MAAM,OAAO,KAAK,OAAO,CAAC;EACxE,QAAQ;GACN,SAAS;EACX;EACA,OAAO;GAAE;GAAQ,OAAO,KAAK;EAAM;CACrC;CAEA,eACE,aACA,YACA,kBACe;EACf,MAAM,EAAE,QAAQ,UAAU,KAAK,QAAQ;EACvC,IAAI,eAAe,OAAO,OAAO;EACjC,IAAI,cAAc,QAAQ,OAAO;EACjC,IAAI,gBAAgB,QAAQ,OAAO;EAEnC,MAAM,SAAS,KAAK,IAAI,KAAK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F,KAAK,MAAM,MAAM,IAAI,cAAc,GAAG;EACpC,MAAM,SAAS,UAAU,UAAU,EAAE,KAAK,IAAI,WAAW,KAAK,EAAE;EAChE,IAAI,CAAC,OAAO,IAAI;EAChB,KAAK,MAAM,UAAU,+BAA+B,MAAM,GACxD,OAAO,oBAAoB,OAAO,MAAM,QAAQ,MAAM;CAE1D;CAEA,OAAO;AACT;;;;;;;AAQA,eAAsB,qBACpB,IACA,aACA,MACA,MACkC;CAElC,OADa,GAAG,IAAI,gBAAgB,IAAI,aAAa,kBAAkB,aAAa,IAAI,CAAC,CAC/E,CAAC,CAAC,WAAW;EAAE;EAAM;CAAK,CAAC;AACvC"}
@@ -1,4 +1,4 @@
1
- //#region src/websocket/do-pitr.ts
1
+ // src/websocket/do-pitr.ts
2
2
  const PITR_UNAVAILABLE_CODE = "PITR_UNAVAILABLE";
3
3
  /**
4
4
  * Thrown when a DO's storage lacks the SQLite bookmark API (non-SQLite DO, or a
@@ -75,7 +75,6 @@ async function armDoPitr(storage, opts) {
75
75
  restarted: opts.restart === true
76
76
  };
77
77
  }
78
- //#endregion
79
78
  export { DoPitrUnavailableError, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark };
80
79
 
81
80
  //# sourceMappingURL=do-pitr.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"do-pitr.js","names":[],"sources":["../../src/websocket/do-pitr.ts"],"sourcesContent":["/**\n * Durable Object point-in-time recovery (PITR) — thin, testable wrappers over a\n * SQLite-backed DO's native bookmark API. A SQLite Durable Object exposes three\n * storage methods (last-30-days PITR):\n *\n * - `getCurrentBookmark()` — an opaque bookmark for the storage's current state.\n * - `getBookmarkForTime(t)` — the bookmark closest to a wall-clock instant.\n * - `onNextSessionRestoreBookmark(b)` — arm a restore to bookmark `b`; the DO\n * restores to it the next time it starts a session, and the call RETURNS a\n * bookmark for the state JUST BEFORE the restore (the undo handle).\n *\n * These methods are ABSENT on a non-SQLite DO (key-value storage) and in some\n * local-dev runtimes, so this module models storage structurally with all three\n * methods OPTIONAL and degrades to a typed {@link DoPitrUnavailableError} (a\n * `code: 'PITR_UNAVAILABLE'`, HTTP 409 error) rather than an\n * `undefined is not a function` TypeError when a needed method is missing.\n *\n * Neither wrapper aborts the DO — `armDoPitr` only ARMS the restore and returns\n * the undo bookmark; the caller (the WS-DO RPC method) decides whether to\n * `ctx.abort()` to apply it immediately vs. on the next natural restart.\n *\n * This file is `cloudflare:workers`-free and pulls in NOTHING from `@velajs/vela`\n * or `@velajs/studio` — it is the raw capability the studio `TimeTravelPort`\n * wraps. Dependency direction is one-way: studio → cloudflare, never the reverse.\n */\n\n/**\n * The subset of `DurableObjectStorage` this module touches, with every method\n * OPTIONAL so it structurally models a non-SQLite DO whose storage has none of\n * them. A real `DurableObjectStorage` (whose methods are required) is assignable\n * to this shape.\n */\nexport interface DoPitrStorage {\n getCurrentBookmark?(): Promise<string>;\n getBookmarkForTime?(timestamp: number | Date): Promise<string>;\n onNextSessionRestoreBookmark?(bookmark: string): Promise<string>;\n}\n\n/** A read of a DO's current bookmark (+ the by-time bookmark when a time is given). */\nexport interface DoPitrBookmarkRead {\n /** The bookmark for the DO storage's current state. */\n current: string;\n /** The bookmark closest to the requested time (only when `time` was passed). */\n forTime?: string;\n}\n\n/** Arming input for {@link armDoPitr}: a target (bookmark WINS over time) + restart intent. */\nexport interface DoPitrArmOptions {\n /** An explicit target bookmark. Takes precedence over `time`. */\n bookmark?: string;\n /** A wall-clock target (epoch ms, ISO string, or Date), resolved to a bookmark. */\n time?: number | string | Date;\n /** Caller intent to restart-now; recorded on the result. `armDoPitr` never aborts. */\n restart?: boolean;\n}\n\n/** The result of arming a PITR restore (before any restart is applied). */\nexport interface DoPitrArmResult {\n /** The bookmark the restore is armed to. */\n restoredTo: string;\n /** The bookmark for the pre-restore state — restore to this to undo. */\n undoBookmark: string;\n /** Whether a restart-now was requested (the RPC layer performs the actual abort). */\n restarted: boolean;\n}\n\n/** The RPC surface a PITR-capable Vela WebSocket DO stub exposes to a Worker. */\nexport interface VelaDoPitrRpc {\n pitrCurrentBookmark(): Promise<DoPitrBookmarkRead>;\n pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead>;\n pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult>;\n}\n\n/** Structural view of a DO id (avoids depending on `@cloudflare/workers-types` downstream). */\nexport interface DoPitrId {\n toString(): string;\n readonly name?: string | null;\n}\n\n/**\n * Structural view of a DO namespace binding whose stubs speak the PITR RPC. A\n * downstream (the studio `@velajs/studio/cloudflare` port) types the app's\n * namespace binding as this shape to reach the PITR methods without importing\n * `@cloudflare/workers-types`.\n */\nexport interface DoPitrNamespace {\n idFromName(name: string): DoPitrId;\n get(id: DoPitrId): VelaDoPitrRpc;\n}\n\nconst PITR_UNAVAILABLE_CODE = 'PITR_UNAVAILABLE';\n\n/**\n * Thrown when a DO's storage lacks the SQLite bookmark API (non-SQLite DO, or a\n * local runtime without PITR). Carries a stable `code` + HTTP 409 `status`, and\n * a recognizable `name`/message so the studio port can map it to\n * `TIMETRAVEL_UNAVAILABLE` even after the error crosses the Worker→DO RPC hop\n * (which preserves `name` + `message`, not arbitrary own-properties).\n */\nexport class DoPitrUnavailableError extends Error {\n readonly code = PITR_UNAVAILABLE_CODE;\n readonly status = 409;\n\n constructor(message = 'Durable Object point-in-time recovery is unavailable on this storage') {\n super(`${PITR_UNAVAILABLE_CODE}: ${message}`);\n this.name = 'DoPitrUnavailableError';\n }\n}\n\n/**\n * True when `error` signals DO PITR unavailability. Robust across the Worker→DO\n * RPC hop: checks the `code` own-property (same process) AND the `name` / message\n * sentinel (survive RPC serialization) so a downstream can classify it either way.\n */\nexport function isDoPitrUnavailable(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const record = error as { code?: unknown; name?: unknown; message?: unknown };\n if (record.code === PITR_UNAVAILABLE_CODE) return true;\n if (record.name === 'DoPitrUnavailableError') return true;\n return (\n typeof record.message === 'string' && record.message.startsWith(`${PITR_UNAVAILABLE_CODE}:`)\n );\n}\n\n/** Normalize an epoch-ms number / ISO string / Date to the `number | Date` the DO API accepts. */\nfunction toStorageTime(time: number | string | Date): number | Date {\n if (typeof time === 'number') return time;\n if (time instanceof Date) return time;\n const asNumber = Number(time);\n return time.trim() !== '' && Number.isFinite(asNumber) ? asNumber : new Date(time);\n}\n\n/**\n * Read a DO's current bookmark, and — when `time` is given — the bookmark closest\n * to that instant. Throws {@link DoPitrUnavailableError} when a needed method is\n * absent, never `undefined is not a function`.\n */\nexport async function readDoPitrBookmark(\n storage: DoPitrStorage,\n time?: number | string | Date,\n): Promise<DoPitrBookmarkRead> {\n const getCurrent = storage.getCurrentBookmark;\n if (typeof getCurrent !== 'function') throw new DoPitrUnavailableError();\n const current = await getCurrent.call(storage);\n if (time === undefined) return { current };\n const getForTime = storage.getBookmarkForTime;\n if (typeof getForTime !== 'function') throw new DoPitrUnavailableError();\n const forTime = await getForTime.call(storage, toStorageTime(time));\n return { current, forTime };\n}\n\n/**\n * Arm a PITR restore. Resolves the target (an explicit `bookmark` WINS over\n * `time`), arms it via `onNextSessionRestoreBookmark`, and returns the undo\n * bookmark the DO reports for the pre-restore state. Does NOT abort — the caller\n * decides whether to restart now. Throws {@link DoPitrUnavailableError} when the\n * arming API (or the by-time resolver a `time` target needs) is absent.\n */\nexport async function armDoPitr(\n storage: DoPitrStorage,\n opts: DoPitrArmOptions,\n): Promise<DoPitrArmResult> {\n const armRestore = storage.onNextSessionRestoreBookmark;\n if (typeof armRestore !== 'function') throw new DoPitrUnavailableError();\n\n let target: string;\n if (opts.bookmark !== undefined) {\n target = opts.bookmark;\n } else if (opts.time !== undefined) {\n const getForTime = storage.getBookmarkForTime;\n if (typeof getForTime !== 'function') throw new DoPitrUnavailableError();\n target = await getForTime.call(storage, toStorageTime(opts.time));\n } else {\n throw new DoPitrUnavailableError('a target bookmark or time is required to arm a restore');\n }\n\n const undoBookmark = await armRestore.call(storage, target);\n return { restoredTo: target, undoBookmark, restarted: opts.restart === true };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,IAAI,KAAK,SAAS,KAAA,GAAW;EAClC,MAAM,aAAa,QAAQ;EAC3B,IAAI,OAAO,eAAe,YAAY,MAAM,IAAI,uBAAuB;EACvE,SAAS,MAAM,WAAW,KAAK,SAAS,cAAc,KAAK,IAAI,CAAC;CAClE,OACE,MAAM,IAAI,uBAAuB,wDAAwD;CAG3F,MAAM,eAAe,MAAM,WAAW,KAAK,SAAS,MAAM;CAC1D,OAAO;EAAE,YAAY;EAAQ;EAAc,WAAW,KAAK,YAAY;CAAK;AAC9E"}
1
+ {"version":3,"file":"do-pitr.js","names":[],"sources":["../../src/websocket/do-pitr.ts"],"sourcesContent":["/**\n * Durable Object point-in-time recovery (PITR) — thin, testable wrappers over a\n * SQLite-backed DO's native bookmark API. A SQLite Durable Object exposes three\n * storage methods (last-30-days PITR):\n *\n * - `getCurrentBookmark()` — an opaque bookmark for the storage's current state.\n * - `getBookmarkForTime(t)` — the bookmark closest to a wall-clock instant.\n * - `onNextSessionRestoreBookmark(b)` — arm a restore to bookmark `b`; the DO\n * restores to it the next time it starts a session, and the call RETURNS a\n * bookmark for the state JUST BEFORE the restore (the undo handle).\n *\n * These methods are ABSENT on a non-SQLite DO (key-value storage) and in some\n * local-dev runtimes, so this module models storage structurally with all three\n * methods OPTIONAL and degrades to a typed {@link DoPitrUnavailableError} (a\n * `code: 'PITR_UNAVAILABLE'`, HTTP 409 error) rather than an\n * `undefined is not a function` TypeError when a needed method is missing.\n *\n * Neither wrapper aborts the DO — `armDoPitr` only ARMS the restore and returns\n * the undo bookmark; the caller (the WS-DO RPC method) decides whether to\n * `ctx.abort()` to apply it immediately vs. on the next natural restart.\n *\n * This file is `cloudflare:workers`-free and pulls in NOTHING from `@velajs/vela`\n * or `@velajs/studio` — it is the raw capability the studio `TimeTravelPort`\n * wraps. Dependency direction is one-way: studio → cloudflare, never the reverse.\n */\n\n/**\n * The subset of `DurableObjectStorage` this module touches, with every method\n * OPTIONAL so it structurally models a non-SQLite DO whose storage has none of\n * them. A real `DurableObjectStorage` (whose methods are required) is assignable\n * to this shape.\n */\nexport interface DoPitrStorage {\n getCurrentBookmark?(): Promise<string>;\n getBookmarkForTime?(timestamp: number | Date): Promise<string>;\n onNextSessionRestoreBookmark?(bookmark: string): Promise<string>;\n}\n\n/** A read of a DO's current bookmark (+ the by-time bookmark when a time is given). */\nexport interface DoPitrBookmarkRead {\n /** The bookmark for the DO storage's current state. */\n current: string;\n /** The bookmark closest to the requested time (only when `time` was passed). */\n forTime?: string;\n}\n\n/** Arming input for {@link armDoPitr}: a target (bookmark WINS over time) + restart intent. */\nexport interface DoPitrArmOptions {\n /** An explicit target bookmark. Takes precedence over `time`. */\n bookmark?: string;\n /** A wall-clock target (epoch ms, ISO string, or Date), resolved to a bookmark. */\n time?: number | string | Date;\n /** Caller intent to restart-now; recorded on the result. `armDoPitr` never aborts. */\n restart?: boolean;\n}\n\n/** The result of arming a PITR restore (before any restart is applied). */\nexport interface DoPitrArmResult {\n /** The bookmark the restore is armed to. */\n restoredTo: string;\n /** The bookmark for the pre-restore state — restore to this to undo. */\n undoBookmark: string;\n /** Whether a restart-now was requested (the RPC layer performs the actual abort). */\n restarted: boolean;\n}\n\n/** The RPC surface a PITR-capable Vela WebSocket DO stub exposes to a Worker. */\nexport interface VelaDoPitrRpc {\n pitrCurrentBookmark(): Promise<DoPitrBookmarkRead>;\n pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead>;\n pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult>;\n}\n\n/** Structural view of a DO id (avoids depending on `@cloudflare/workers-types` downstream). */\nexport interface DoPitrId {\n toString(): string;\n readonly name?: string | null;\n}\n\n/**\n * Structural view of a DO namespace binding whose stubs speak the PITR RPC. A\n * downstream (the studio `@velajs/studio/cloudflare` port) types the app's\n * namespace binding as this shape to reach the PITR methods without importing\n * `@cloudflare/workers-types`.\n */\nexport interface DoPitrNamespace {\n idFromName(name: string): DoPitrId;\n get(id: DoPitrId): VelaDoPitrRpc;\n}\n\nconst PITR_UNAVAILABLE_CODE = 'PITR_UNAVAILABLE';\n\n/**\n * Thrown when a DO's storage lacks the SQLite bookmark API (non-SQLite DO, or a\n * local runtime without PITR). Carries a stable `code` + HTTP 409 `status`, and\n * a recognizable `name`/message so the studio port can map it to\n * `TIMETRAVEL_UNAVAILABLE` even after the error crosses the Worker→DO RPC hop\n * (which preserves `name` + `message`, not arbitrary own-properties).\n */\nexport class DoPitrUnavailableError extends Error {\n readonly code = PITR_UNAVAILABLE_CODE;\n readonly status = 409;\n\n constructor(message = 'Durable Object point-in-time recovery is unavailable on this storage') {\n super(`${PITR_UNAVAILABLE_CODE}: ${message}`);\n this.name = 'DoPitrUnavailableError';\n }\n}\n\n/**\n * True when `error` signals DO PITR unavailability. Robust across the Worker→DO\n * RPC hop: checks the `code` own-property (same process) AND the `name` / message\n * sentinel (survive RPC serialization) so a downstream can classify it either way.\n */\nexport function isDoPitrUnavailable(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const record = error as { code?: unknown; name?: unknown; message?: unknown };\n if (record.code === PITR_UNAVAILABLE_CODE) return true;\n if (record.name === 'DoPitrUnavailableError') return true;\n return (\n typeof record.message === 'string' && record.message.startsWith(`${PITR_UNAVAILABLE_CODE}:`)\n );\n}\n\n/** Normalize an epoch-ms number / ISO string / Date to the `number | Date` the DO API accepts. */\nfunction toStorageTime(time: number | string | Date): number | Date {\n if (typeof time === 'number') return time;\n if (time instanceof Date) return time;\n const asNumber = Number(time);\n return time.trim() !== '' && Number.isFinite(asNumber) ? asNumber : new Date(time);\n}\n\n/**\n * Read a DO's current bookmark, and — when `time` is given — the bookmark closest\n * to that instant. Throws {@link DoPitrUnavailableError} when a needed method is\n * absent, never `undefined is not a function`.\n */\nexport async function readDoPitrBookmark(\n storage: DoPitrStorage,\n time?: number | string | Date,\n): Promise<DoPitrBookmarkRead> {\n const getCurrent = storage.getCurrentBookmark;\n if (typeof getCurrent !== 'function') throw new DoPitrUnavailableError();\n const current = await getCurrent.call(storage);\n if (time === undefined) return { current };\n const getForTime = storage.getBookmarkForTime;\n if (typeof getForTime !== 'function') throw new DoPitrUnavailableError();\n const forTime = await getForTime.call(storage, toStorageTime(time));\n return { current, forTime };\n}\n\n/**\n * Arm a PITR restore. Resolves the target (an explicit `bookmark` WINS over\n * `time`), arms it via `onNextSessionRestoreBookmark`, and returns the undo\n * bookmark the DO reports for the pre-restore state. Does NOT abort — the caller\n * decides whether to restart now. Throws {@link DoPitrUnavailableError} when the\n * arming API (or the by-time resolver a `time` target needs) is absent.\n */\nexport async function armDoPitr(\n storage: DoPitrStorage,\n opts: DoPitrArmOptions,\n): Promise<DoPitrArmResult> {\n const armRestore = storage.onNextSessionRestoreBookmark;\n if (typeof armRestore !== 'function') throw new DoPitrUnavailableError();\n\n let target: string;\n if (opts.bookmark !== undefined) {\n target = opts.bookmark;\n } else if (opts.time !== undefined) {\n const getForTime = storage.getBookmarkForTime;\n if (typeof getForTime !== 'function') throw new DoPitrUnavailableError();\n target = await getForTime.call(storage, toStorageTime(opts.time));\n } else {\n throw new DoPitrUnavailableError('a target bookmark or time is required to arm a restore');\n }\n\n const undoBookmark = await armRestore.call(storage, target);\n return { restoredTo: target, undoBookmark, restarted: opts.restart === true };\n}\n"],"mappings":";AA0FA,MAAM,wBAAwB;;;;;;;;AAS9B,IAAa,yBAAb,cAA4C,MAAM;CACvC,OAAO;CACP,SAAS;CAElB,YAAY,UAAU,wEAAwE;EAC5F,MAAM,GAAG,sBAAsB,IAAI,SAAS;EAC5C,KAAK,OAAO;CACd;AACF;;;;;;AAOA,SAAgB,oBAAoB,OAAyB;CAC3D,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,SAAS;CACf,IAAI,OAAO,SAAS,uBAAuB,OAAO;CAClD,IAAI,OAAO,SAAS,0BAA0B,OAAO;CACrD,OACE,OAAO,OAAO,YAAY,YAAY,OAAO,QAAQ,WAAW,GAAG,sBAAsB,EAAE;AAE/F;;AAGA,SA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16384;
4
- //#endregion
5
4
  export { MAX_WS_ATTACHMENT_BYTES };
6
5
 
7
6
  //# sourceMappingURL=do-state.js.map
@@ -1,8 +1,8 @@
1
- import { connTag, roomTag } from "./room-id.js";
2
1
  import { socketAttachment } from "./ws-attachment.js";
3
- import { MAX_WS_ATTACHMENT_BYTES } from "./do-state.js";
4
2
  import { WsMessageQueue, assertBroadcastCommandFits } from "@velajs/vela/websocket";
5
- //#region src/websocket/do-websocket-host.ts
3
+ import { MAX_WS_ATTACHMENT_BYTES } from "./do-state.js";
4
+ import { connTag, roomTag } from "./room-id.js";
5
+ // src/websocket/do-websocket-host.ts
6
6
  /**
7
7
  * The socket lifecycle inside a WebSocket Durable Object, decoupled from the
8
8
  * `cloudflare:workers` base class so it is unit-testable with fakes. The thin
@@ -163,7 +163,6 @@ var DoWebSocketHost = class {
163
163
  } catch {}
164
164
  }
165
165
  };
166
- //#endregion
167
166
  export { DoWebSocketHost };
168
167
 
169
168
  //# sourceMappingURL=do-websocket-host.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"do-websocket-host.js","names":[],"sources":["../../src/websocket/do-websocket-host.ts"],"sourcesContent":["import { socketAttachment } from './ws-attachment';\nimport { WsMessageQueue, assertBroadcastCommandFits } from '@velajs/vela/websocket';\nimport type { BroadcastCommand, WsDispatcher } from '@velajs/vela/websocket';\nimport type { CfRoomRegistry } from './cf-room-registry';\nimport {\n MAX_WS_ATTACHMENT_BYTES,\n type DoStateLike,\n type WsAttachment,\n type WsLike,\n} from './do-state';\nimport { connTag, roomTag } from './room-id';\n\nexport interface WsConnectionPrincipal {\n issuer: string;\n subject: string;\n principalType: 'user' | 'service';\n tenantId: string;\n}\n\n/**\n * The socket lifecycle inside a WebSocket Durable Object, decoupled from the\n * `cloudflare:workers` base class so it is unit-testable with fakes. The thin\n * `VelaWebSocketDurableObject` shell forwards its hibernation callbacks here.\n */\nexport class DoWebSocketHost {\n readonly #messages = new WeakMap<WsLike, WsMessageQueue>();\n constructor(\n private readonly ctx: DoStateLike,\n private readonly dispatcher: WsDispatcher,\n private readonly registry: CfRoomRegistry,\n private readonly gatewayPaths: readonly string[] = [],\n ) {}\n\n /** The single registered gateway's path — a fallback when the Worker didn't forward `x-vela-path`. */\n defaultPath(): string | undefined {\n return this.gatewayPaths[0];\n }\n\n /**\n * Accept a hibernatable socket: tag it with its hub room + connection id,\n * persist the attachment, then await `OnGatewayConnection` before the caller\n * returns 101. A rejected lifecycle hook closes and fails the upgrade.\n */\n async accept(\n ws: WsLike,\n path: string,\n roomId: string,\n userId?: string,\n expiresAtMs?: number,\n principal?: WsConnectionPrincipal,\n ): Promise<boolean> {\n const maxFrameBytes = this.dispatcher.getGatewayMaxFrameBytes(path);\n if (maxFrameBytes === undefined) return false;\n if (\n expiresAtMs !== undefined &&\n (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= Date.now())\n ) {\n return false;\n }\n if (\n (principal !== undefined &&\n (expiresAtMs === undefined ||\n userId !== principal.subject ||\n !principal.issuer ||\n !principal.tenantId)) ||\n (expiresAtMs !== undefined && principal === undefined)\n ) {\n return false;\n }\n\n const connId = crypto.randomUUID();\n const attachment: WsAttachment = {\n version: 1,\n connId,\n state: 'pending',\n userId,\n principal:\n principal === undefined\n ? undefined\n : {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal?.tenantId,\n expiresAtMs,\n path,\n maxFrameBytes,\n rooms: [roomId],\n data: {\n ...(userId ? { userId } : {}),\n ...(principal\n ? {\n principal: {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal.tenantId,\n }\n : {}),\n ...(expiresAtMs !== undefined ? { expiresAtMs } : {}),\n },\n };\n if (new TextEncoder().encode(JSON.stringify(attachment)).byteLength > MAX_WS_ATTACHMENT_BYTES) {\n return false;\n }\n try {\n this.ctx.acceptWebSocket(ws, [roomTag(roomId), connTag(connId)]);\n ws.serializeAttachment(attachment);\n } catch {\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n\n const client = this.registry.clientFor(ws);\n try {\n // Broadcasts the hook issues skip this still-pending socket.\n await this.registry.admitting(ws, () => this.dispatcher.handleOpen(path, client));\n // Another callback may have rejected the socket while the asynchronous\n // connection hook was still pending. Never resurrect that terminal state\n // after the hook resolves.\n if (!this.transition(ws, 'active', 'pending')) {\n throw new Error(\n socketAttachment(ws)?.state === 'rejected'\n ? 'WebSocket was rejected while OnGatewayConnection was running: a frame ' +\n 'arrived before the connection hook completed, or the connection closed or failed'\n : 'Unable to persist authorized WebSocket state',\n );\n }\n return true;\n } catch (err) {\n await this.dispatcher.handleError(path, client, err).catch(() => {});\n this.transition(ws, 'rejected');\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n }\n\n async onMessage(ws: WsLike, message: string | ArrayBuffer): Promise<void> {\n if (!this.isActive(ws)) {\n this.reject(ws, 'Connection is not authorized');\n return;\n }\n let queue = this.#messages.get(ws);\n if (!queue) {\n const path = socketAttachment(ws)?.path;\n const options = this.dispatcher.collectEntrypoints().find((entry) => entry.meta.path === path)\n ?.meta.options;\n queue = new WsMessageQueue(\n () => this.reject(ws, 'WebSocket message budget exceeded', 1013),\n options?.maxPendingMessages,\n options?.maxPendingBytes,\n );\n this.#messages.set(ws, queue);\n }\n await queue.run(message, async () => {\n if (!this.isActive(ws)) return;\n const client = this.registry.clientFor(ws);\n await this.dispatcher.dispatchMessage(client.path, client, message);\n });\n }\n\n async onClose(ws: WsLike, code: number, reason: string): Promise<void> {\n this.#messages.get(ws)?.stop();\n if (!this.isActive(ws, false)) {\n this.transition(ws, 'rejected');\n try {\n ws.close();\n } catch {\n // already closed\n }\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleClose(client.path, client, code, reason);\n // Complete the closing handshake. Only 1000 and 3000-4999 are valid for\n // close(); reserved/abnormal codes (1005/1006/1015, etc.) throw a RangeError,\n // so fall back to a codeless close on those.\n try {\n if (code === 1000 || (code >= 3000 && code <= 4999)) ws.close(code, reason);\n else ws.close();\n } catch {\n // socket already closed\n }\n }\n\n async onError(ws: WsLike, err: unknown): Promise<void> {\n if (!this.isActive(ws, false)) {\n this.reject(ws, 'Connection failed before authorization');\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleError(client.path, client, err);\n }\n\n /** Deliver a broadcast command to this DO's local sockets (RPC entry point). */\n broadcast(cmd: BroadcastCommand): void | Promise<void> {\n assertBroadcastCommandFits(cmd, this.dispatcher.getMaximumGatewayFrameBytes());\n return this.registry.deliverLocal(cmd);\n }\n\n private transition(\n ws: WsLike,\n state: WsAttachment['state'],\n expectedState?: WsAttachment['state'],\n ): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment) return false;\n if (expectedState !== undefined && attachment.state !== expectedState) return false;\n attachment.state = state;\n ws.serializeAttachment(attachment);\n return true;\n } catch {\n return false;\n }\n }\n\n private isActive(ws: WsLike, checkExpiry = true): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment || attachment.state !== 'active') return false;\n return (\n !checkExpiry ||\n attachment.expiresAtMs === undefined ||\n (Number.isSafeInteger(attachment.expiresAtMs) && attachment.expiresAtMs > Date.now())\n );\n } catch {\n return false;\n }\n }\n\n private reject(ws: WsLike, reason: string, code = 1008): void {\n this.#messages.get(ws)?.stop();\n this.transition(ws, 'rejected');\n try {\n ws.close(code, reason);\n } catch {\n // already closed\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAa,kBAAb,MAA6B;CAGR;CACA;CACA;CACA;CALnB,4BAAqB,IAAI,QAAgC;CACzD,YACE,KACA,YACA,UACA,eAAmD,CAAC,GACpD;EAJiB,KAAA,MAAA;EACA,KAAA,aAAA;EACA,KAAA,WAAA;EACA,KAAA,eAAA;CAChB;;CAGH,cAAkC;EAChC,OAAO,KAAK,aAAa;CAC3B;;;;;;CAOA,MAAM,OACJ,IACA,MACA,QACA,QACA,aACA,WACkB;EAClB,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,QAAQ,CAER;CACF;AACF"}
1
+ {"version":3,"file":"do-websocket-host.js","names":[],"sources":["../../src/websocket/do-websocket-host.ts"],"sourcesContent":["import { socketAttachment } from './ws-attachment';\nimport { WsMessageQueue, assertBroadcastCommandFits } from '@velajs/vela/websocket';\nimport type { BroadcastCommand, WsDispatcher } from '@velajs/vela/websocket';\nimport type { CfRoomRegistry } from './cf-room-registry';\nimport {\n MAX_WS_ATTACHMENT_BYTES,\n type DoStateLike,\n type WsAttachment,\n type WsLike,\n} from './do-state';\nimport { connTag, roomTag } from './room-id';\n\nexport interface WsConnectionPrincipal {\n issuer: string;\n subject: string;\n principalType: 'user' | 'service';\n tenantId: string;\n}\n\n/**\n * The socket lifecycle inside a WebSocket Durable Object, decoupled from the\n * `cloudflare:workers` base class so it is unit-testable with fakes. The thin\n * `VelaWebSocketDurableObject` shell forwards its hibernation callbacks here.\n */\nexport class DoWebSocketHost {\n readonly #messages = new WeakMap<WsLike, WsMessageQueue>();\n constructor(\n private readonly ctx: DoStateLike,\n private readonly dispatcher: WsDispatcher,\n private readonly registry: CfRoomRegistry,\n private readonly gatewayPaths: readonly string[] = [],\n ) {}\n\n /** The single registered gateway's path — a fallback when the Worker didn't forward `x-vela-path`. */\n defaultPath(): string | undefined {\n return this.gatewayPaths[0];\n }\n\n /**\n * Accept a hibernatable socket: tag it with its hub room + connection id,\n * persist the attachment, then await `OnGatewayConnection` before the caller\n * returns 101. A rejected lifecycle hook closes and fails the upgrade.\n */\n async accept(\n ws: WsLike,\n path: string,\n roomId: string,\n userId?: string,\n expiresAtMs?: number,\n principal?: WsConnectionPrincipal,\n ): Promise<boolean> {\n const maxFrameBytes = this.dispatcher.getGatewayMaxFrameBytes(path);\n if (maxFrameBytes === undefined) return false;\n if (\n expiresAtMs !== undefined &&\n (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= Date.now())\n ) {\n return false;\n }\n if (\n (principal !== undefined &&\n (expiresAtMs === undefined ||\n userId !== principal.subject ||\n !principal.issuer ||\n !principal.tenantId)) ||\n (expiresAtMs !== undefined && principal === undefined)\n ) {\n return false;\n }\n\n const connId = crypto.randomUUID();\n const attachment: WsAttachment = {\n version: 1,\n connId,\n state: 'pending',\n userId,\n principal:\n principal === undefined\n ? undefined\n : {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal?.tenantId,\n expiresAtMs,\n path,\n maxFrameBytes,\n rooms: [roomId],\n data: {\n ...(userId ? { userId } : {}),\n ...(principal\n ? {\n principal: {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal.tenantId,\n }\n : {}),\n ...(expiresAtMs !== undefined ? { expiresAtMs } : {}),\n },\n };\n if (new TextEncoder().encode(JSON.stringify(attachment)).byteLength > MAX_WS_ATTACHMENT_BYTES) {\n return false;\n }\n try {\n this.ctx.acceptWebSocket(ws, [roomTag(roomId), connTag(connId)]);\n ws.serializeAttachment(attachment);\n } catch {\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n\n const client = this.registry.clientFor(ws);\n try {\n // Broadcasts the hook issues skip this still-pending socket.\n await this.registry.admitting(ws, () => this.dispatcher.handleOpen(path, client));\n // Another callback may have rejected the socket while the asynchronous\n // connection hook was still pending. Never resurrect that terminal state\n // after the hook resolves.\n if (!this.transition(ws, 'active', 'pending')) {\n throw new Error(\n socketAttachment(ws)?.state === 'rejected'\n ? 'WebSocket was rejected while OnGatewayConnection was running: a frame ' +\n 'arrived before the connection hook completed, or the connection closed or failed'\n : 'Unable to persist authorized WebSocket state',\n );\n }\n return true;\n } catch (err) {\n await this.dispatcher.handleError(path, client, err).catch(() => {});\n this.transition(ws, 'rejected');\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n }\n\n async onMessage(ws: WsLike, message: string | ArrayBuffer): Promise<void> {\n if (!this.isActive(ws)) {\n this.reject(ws, 'Connection is not authorized');\n return;\n }\n let queue = this.#messages.get(ws);\n if (!queue) {\n const path = socketAttachment(ws)?.path;\n const options = this.dispatcher.collectEntrypoints().find((entry) => entry.meta.path === path)\n ?.meta.options;\n queue = new WsMessageQueue(\n () => this.reject(ws, 'WebSocket message budget exceeded', 1013),\n options?.maxPendingMessages,\n options?.maxPendingBytes,\n );\n this.#messages.set(ws, queue);\n }\n await queue.run(message, async () => {\n if (!this.isActive(ws)) return;\n const client = this.registry.clientFor(ws);\n await this.dispatcher.dispatchMessage(client.path, client, message);\n });\n }\n\n async onClose(ws: WsLike, code: number, reason: string): Promise<void> {\n this.#messages.get(ws)?.stop();\n if (!this.isActive(ws, false)) {\n this.transition(ws, 'rejected');\n try {\n ws.close();\n } catch {\n // already closed\n }\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleClose(client.path, client, code, reason);\n // Complete the closing handshake. Only 1000 and 3000-4999 are valid for\n // close(); reserved/abnormal codes (1005/1006/1015, etc.) throw a RangeError,\n // so fall back to a codeless close on those.\n try {\n if (code === 1000 || (code >= 3000 && code <= 4999)) ws.close(code, reason);\n else ws.close();\n } catch {\n // socket already closed\n }\n }\n\n async onError(ws: WsLike, err: unknown): Promise<void> {\n if (!this.isActive(ws, false)) {\n this.reject(ws, 'Connection failed before authorization');\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleError(client.path, client, err);\n }\n\n /** Deliver a broadcast command to this DO's local sockets (RPC entry point). */\n broadcast(cmd: BroadcastCommand): void | Promise<void> {\n assertBroadcastCommandFits(cmd, this.dispatcher.getMaximumGatewayFrameBytes());\n return this.registry.deliverLocal(cmd);\n }\n\n private transition(\n ws: WsLike,\n state: WsAttachment['state'],\n expectedState?: WsAttachment['state'],\n ): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment) return false;\n if (expectedState !== undefined && attachment.state !== expectedState) return false;\n attachment.state = state;\n ws.serializeAttachment(attachment);\n return true;\n } catch {\n return false;\n }\n }\n\n private isActive(ws: WsLike, checkExpiry = true): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment || attachment.state !== 'active') return false;\n return (\n !checkExpiry ||\n attachment.expiresAtMs === undefined ||\n (Number.isSafeInteger(attachment.expiresAtMs) && attachment.expiresAtMs > Date.now())\n );\n } catch {\n return false;\n }\n }\n\n private reject(ws: WsLike, reason: string, code = 1008): void {\n this.#messages.get(ws)?.stop();\n this.transition(ws, 'rejected');\n try {\n ws.close(code, reason);\n } catch {\n // already closed\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAa,kBAAb,MAA6B;CAGR;CACA;CACA;CACA;CALV,4BAAY,IAAI,QAAgC;CACzD,YACmB,KACA,YACA,UACA,eAAkC,CAAC,GACpD;EAJiB,KAAA,MAAA;EACA,KAAA,aAAA;EACA,KAAA,WAAA;EACA,KAAA,eAAA;CAChB;;CAGH,cAAkC;EAChC,OAAO,KAAK,aAAa;CAC3B;;;;;;CAOA,MAAM,OACJ,IACA,MACA,QACA,QACA,aACA,WACkB;EAClB,MAAM,gBAAgB,KAAK,WAAW,wBAAwB,IAAI;EAClE,IAAI,kBAAkB,KAAA,GAAW,OAAO;EACxC,IACE,gBAAgB,KAAA,MACf,CAAC,OAAO,cAAc,WAAW,KAAK,eAAe,KAAK,IAAI,IAE/D,OAAO;EAET,IACG,cAAc,KAAA,MACZ,gBAAgB,KAAA,KACf,WAAW,UAAU,WACrB,CAAC,UAAU,UACX,CAAC,UAAU,aACd,gBAAgB,KAAA,KAAa,cAAc,KAAA,GAE5C,OAAO;EAGT,MAAM,SAAS,OAAO,WAAW;EACjC,MAAM,aAA2B;GAC/B,SAAS;GACT;GACA,OAAO;GACP;GACA,WACE,cAAc,KAAA,IACV,KAAA,IACA;IACE,QAAQ,UAAU;IAClB,SAAS,UAAU;IACnB,eAAe,UAAU;GAC3B;GACN,UAAU,WAAW;GACrB;GACA;GACA;GACA,OAAO,CAAC,MAAM;GACd,MAAM;IACJ,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;IAC3B,GA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iBAAiB,EAAE;GACtC,IAAI,CAAC,YAAY,OAAO;GACxB,IAAI,kBAAkB,KAAA,KAAa,WAAW,UAAU,eAAe,OAAO;GAC9E,WAAW,QAAQ;GACnB,GAAG,oBAAoB,UAAU;GACjC,OAAO;EACT,QAAQ;GACN,OAAO;EACT;CACF;CAEQ,SAAS,IAAY,cAAc,MAAe;EACxD,IAAI;GACF,MAAM,aAAa,iBAAiB,EAAE;GACtC,IAAI,CAAC,cAAc,WAAW,UAAU,UAAU,OAAO;GACzD,OACE,CAAC,eACD,WAAW,gBAAgB,KAAA,KAC1B,OAAO,cAAc,WAAW,WAAW,KAAK,WAAW,cAAc,KAAK,IAAI;EAEvF,QAAQ;GACN,OAAO;EACT;CACF;CAEQ,OAAO,IAAY,QAAgB,OAAO,MAAY;EAC5D,KAAK,UAAU,IAAI,EAAE,CAAC,EAAE,KAAK;EAC7B,KAAK,WAAW,IAAI,UAAU;EAC9B,IAAI;GACF,GAAG,MAAM,MAAM,MAAM;EACvB,QAAQ,CAER;CACF;AACF"}
@@ -1,8 +1,8 @@
1
- import { gatewayObjectRoom } from "./room-id.js";
1
+ import { DiscoveryService } from "@velajs/vela/module-kit";
2
2
  import { bindingGateways } from "./binding-gateways.js";
3
+ import { gatewayObjectRoom } from "./room-id.js";
3
4
  import { gatewayRoomObject } from "./worker-transport.js";
4
- import { DiscoveryService } from "@velajs/vela/module-kit";
5
- //#region src/websocket/live-driver.ts
5
+ // src/websocket/live-driver.ts
6
6
  const DEFAULT_ROOM = "default";
7
7
  function describeFilter({ binding, gatewayPath }) {
8
8
  return [...binding === void 0 ? [] : [`binding '${binding}'`], ...gatewayPath === void 0 ? [] : [`path '${gatewayPath}'`]].join(" and ");
@@ -143,7 +143,6 @@ function workerLivePlatform(env, container) {
143
143
  }
144
144
  };
145
145
  }
146
- //#endregion
147
146
  export { CfLiveDriver, durableObjectLive, workerLivePlatform };
148
147
 
149
148
  //# sourceMappingURL=live-driver.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"live-driver.js","names":[],"sources":["../../src/websocket/live-driver.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport { DiscoveryService, type Container } from '@velajs/vela/module-kit';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveDriver,\n LiveInvalidationSink,\n LivePlatform,\n} from '@velajs/vela/live';\nimport { bindingGateways, type BindingGateway } from './binding-gateways';\nimport { gatewayObjectRoom } from './room-id';\nimport { gatewayRoomObject, type GatewayRoomObject } from './worker-transport';\n\nconst DEFAULT_ROOM = 'default';\n\nexport interface DurableObjectLiveOptions {\n /**\n * Durable Object namespace binding that holds the gateway's rooms, read from\n * the application's `ENV` when an invalidation first needs it. Defaults to\n * the `binding` of the chosen gateway.\n */\n binding?: string;\n /**\n * Exact `@WebSocketGateway()` path whose rooms hold the subscriptions.\n * Defaults to the single gateway backed by `binding` (or by any binding).\n */\n gatewayPath?: string;\n /**\n * Room used when an invalidation names none. Matches the client default. A\n * gateway without `roomParam` has one room, its path, which every\n * invalidation reaches.\n */\n defaultRoom?: string;\n}\n\nexport interface LiveInvalidateStub {\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n}\n\n/** Only the native namespace operations required for live invalidation. */\nexport interface LiveNamespace {\n idFromName(name: string): DurableObjectId;\n get(id: DurableObjectId): LiveInvalidateStub;\n}\n\n/** @internal What the Worker's live platform hands a driver. */\ninterface WorkerLiveContext {\n env: VelaEnv;\n gateways(): readonly Pick<BindingGateway, 'path' | 'binding'>[];\n}\n\n/** Where the Worker delivers invalidations: one gateway's room objects. */\ninterface LiveTarget {\n env: VelaEnv;\n binding: string;\n gatewayPath: string;\n}\n\nfunction describeFilter({ binding, gatewayPath }: DurableObjectLiveOptions): string {\n const parts = [\n ...(binding === undefined ? [] : [`binding '${binding}'`]),\n ...(gatewayPath === undefined ? [] : [`path '${gatewayPath}'`]),\n ];\n return parts.join(' and ');\n}\n\n/** A commit stamp a room object returned, validated before it reaches headers. */\nfunction commitStamp(value: unknown): CommitStamp | undefined {\n if (value === undefined) return undefined;\n const cursor: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'cursor') : undefined;\n const epoch: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'epoch') : undefined;\n if (typeof cursor !== 'number' || typeof epoch !== 'string') {\n throw new Error('Durable Object invalidate() returned an invalid commit stamp');\n }\n return { cursor, epoch };\n}\n\n/**\n * Delivers live invalidations to the room Durable Object of a\n * `@WebSocketGateway({ binding })`, whose SQLite log stamps the commit. Inside\n * that Durable Object the same driver applies invalidations locally.\n */\nexport class CfLiveDriver implements LiveDriver {\n readonly kind = 'durable-object';\n #sink: LiveInvalidationSink | undefined;\n #local = false;\n #context: WorkerLiveContext | undefined;\n #target: LiveTarget | undefined;\n\n constructor(private readonly options: DurableObjectLiveOptions = {}) {}\n\n bind(sink: LiveInvalidationSink): void {\n this.#sink = sink;\n }\n\n /** @internal The Worker's live platform supplies its environment and gateways. */\n _attach(context: WorkerLiveContext): void {\n this.#context = context;\n this.#target = undefined;\n }\n\n /** @internal A Durable Object dispatches to its own engine and SQLite log. */\n _setLocalMode(): void {\n this.#local = true;\n }\n\n /**\n * @internal The Durable Object that holds one room's subscriptions. As for\n * upgrades and `Gateways` pushes, a gateway without `roomParam` keeps every\n * socket in one room, its path, so each of its rooms is in that object.\n */\n _room(room: string): GatewayRoomObject {\n const { env, binding, gatewayPath } = this.#resolveTarget();\n return gatewayRoomObject(env, gatewayPath, binding, gatewayObjectRoom(gatewayPath, room));\n }\n\n dispatch(cmd: InvalidationCommand): Promise<CommitStamp | undefined> | CommitStamp | undefined {\n if (this.#local) return this.#sink?.applyInvalidation(cmd);\n const room = cmd.room ?? this.options.defaultRoom ?? DEFAULT_ROOM;\n return this._room(room)\n .call('invalidate', { ...cmd, room })\n .then(commitStamp);\n }\n\n #resolveTarget(): LiveTarget {\n if (this.#target) return this.#target;\n const context = this.#context;\n if (!context) {\n throw new Error(\n 'durableObjectLive() needs the Cloudflare adapter: create the application with ' +\n 'createCloudflareWorker(), createCloudflareApp() or cloudflareAdapter().',\n );\n }\n let { binding, gatewayPath } = this.options;\n const gateways = context.gateways();\n if (binding === undefined || gatewayPath === undefined) {\n const candidates = gateways.filter(\n (gateway) =>\n (binding === undefined || gateway.binding === binding) &&\n (gatewayPath === undefined || gateway.path === gatewayPath),\n );\n const [chosen, ...others] = candidates;\n if (!chosen) {\n const filter = describeFilter(this.options);\n throw new Error(\n filter\n ? `durableObjectLive() found no @WebSocketGateway with ${filter}. Name the gateway ` +\n 'that holds the subscriptions, with its binding.'\n : 'LiveModule delivers Worker invalidations to the room Durable Object of a ' +\n 'gateway, but no @WebSocketGateway names a binding. Declare one with ' +\n '{ binding }, or pass driver: () => durableObjectLive({ binding, gatewayPath }).',\n );\n }\n if (others.length > 0) {\n const paths = candidates.map((gateway) => `'${gateway.path}'`).join(', ');\n throw new Error(\n `LiveModule must choose where Worker invalidations go, but several binding-backed ` +\n `gateways (${paths}) could hold the subscriptions. Pass ` +\n 'driver: () => durableObjectLive({ gatewayPath }) to LiveModule.',\n );\n }\n binding ??= chosen.binding;\n gatewayPath ??= chosen.path;\n }\n const target: LiveTarget = { env: context.env, binding, gatewayPath };\n this.#target = target;\n return target;\n }\n}\n\n/**\n * The Cloudflare live driver, for `LiveModule.forRoot({ driver })`. It is the\n * default on Cloudflare, so name it only to choose a gateway, binding or\n * default room:\n *\n * ```ts\n * LiveModule.forRoot({ driver: () => durableObjectLive({ gatewayPath: '/rooms/:id/ws' }) })\n * ```\n */\nexport function durableObjectLive(options: DurableObjectLiveOptions = {}): CfLiveDriver {\n return new CfLiveDriver(options);\n}\n\nlet workerLocalLiveWarned = false;\n\n/**\n * The Worker isolate's live platform: invalidations default to the room\n * Durable Object of the application's binding-backed gateway, chosen and read\n * from `ENV` when first needed, and `LiveInspector` reads each room from that\n * object. A configured local driver is warned about once per isolate:\n * subscriptions live in the Durable Object, so it would reach none.\n */\nexport function workerLivePlatform(env: VelaEnv, container: Container): LivePlatform {\n const context: WorkerLiveContext = {\n env,\n gateways: () => bindingGateways(container.resolve(DiscoveryService)),\n };\n let bound: CfLiveDriver | undefined;\n return {\n liveDriver: () => durableObjectLive(),\n async inspect(room) {\n if (!bound) throw new Error('LiveModule delivers locally in this Worker: no room to inspect');\n const value: unknown = await bound._room(room).call('inspectLive');\n const subscriptions: unknown =\n typeof value === 'object' && value !== null\n ? Reflect.get(value, 'subscriptions')\n : undefined;\n const rooms: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'rooms') : undefined;\n if (!Array.isArray(subscriptions) || !Array.isArray(rooms)) {\n throw new Error('Durable Object inspectLive() returned an invalid snapshot');\n }\n return { subscriptions, rooms };\n },\n bindDriver(driver) {\n if (driver instanceof CfLiveDriver) {\n driver._attach(context);\n bound = driver;\n return;\n }\n if (driver.kind !== 'local' || workerLocalLiveWarned) return;\n if (container.getDiagnostics() === 'silent') return;\n workerLocalLiveWarned = true;\n console.warn(\n '[vela] LiveModule is running localLive() in the Worker isolate: its subscriptions live ' +\n 'in the WebSocket Durable Object, so invalidations sent from the Worker never reach ' +\n 'them. Remove the driver option to deliver through the gateway room Durable Object.',\n );\n },\n };\n}\n"],"mappings":";;;;;AAaA,MAAM,eAAe;AA6CrB,SAAS,eAAe,EAAE,SAAS,eAAiD;CAKlF,OAAO,CAHL,GAAI,YAAY,KAAA,IAAY,CAAC,IAAI,CAAC,YAAY,QAAQ,EAAE,GACxD,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,CAAC,SAAS,YAAY,EAAE,CAEpD,CAAC,CAAC,KAAK,OAAO;AAC3B;;AAGA,SAAS,YAAY,OAAyC;CAC5D,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,SACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,QAAQ,IAAI,KAAA;CAC/E,MAAM,QACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,OAAO,IAAI,KAAA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AS,WAAW,uBAAuB;GACtD,IAAI,UAAU,eAAe,MAAM,UAAU;GAC7C,wBAAwB;GACxB,QAAQ,KACN,8PAGF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"live-driver.js","names":[],"sources":["../../src/websocket/live-driver.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport { DiscoveryService, type Container } from '@velajs/vela/module-kit';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveDriver,\n LiveInvalidationSink,\n LivePlatform,\n} from '@velajs/vela/live';\nimport { bindingGateways, type BindingGateway } from './binding-gateways';\nimport { gatewayObjectRoom } from './room-id';\nimport { gatewayRoomObject, type GatewayRoomObject } from './worker-transport';\n\nconst DEFAULT_ROOM = 'default';\n\nexport interface DurableObjectLiveOptions {\n /**\n * Durable Object namespace binding that holds the gateway's rooms, read from\n * the application's `ENV` when an invalidation first needs it. Defaults to\n * the `binding` of the chosen gateway.\n */\n binding?: string;\n /**\n * Exact `@WebSocketGateway()` path whose rooms hold the subscriptions.\n * Defaults to the single gateway backed by `binding` (or by any binding).\n */\n gatewayPath?: string;\n /**\n * Room used when an invalidation names none. Matches the client default. A\n * gateway without `roomParam` has one room, its path, which every\n * invalidation reaches.\n */\n defaultRoom?: string;\n}\n\nexport interface LiveInvalidateStub {\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n}\n\n/** Only the native namespace operations required for live invalidation. */\nexport interface LiveNamespace {\n idFromName(name: string): DurableObjectId;\n get(id: DurableObjectId): LiveInvalidateStub;\n}\n\n/** @internal What the Worker's live platform hands a driver. */\ninterface WorkerLiveContext {\n env: VelaEnv;\n gateways(): readonly Pick<BindingGateway, 'path' | 'binding'>[];\n}\n\n/** Where the Worker delivers invalidations: one gateway's room objects. */\ninterface LiveTarget {\n env: VelaEnv;\n binding: string;\n gatewayPath: string;\n}\n\nfunction describeFilter({ binding, gatewayPath }: DurableObjectLiveOptions): string {\n const parts = [\n ...(binding === undefined ? [] : [`binding '${binding}'`]),\n ...(gatewayPath === undefined ? [] : [`path '${gatewayPath}'`]),\n ];\n return parts.join(' and ');\n}\n\n/** A commit stamp a room object returned, validated before it reaches headers. */\nfunction commitStamp(value: unknown): CommitStamp | undefined {\n if (value === undefined) return undefined;\n const cursor: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'cursor') : undefined;\n const epoch: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'epoch') : undefined;\n if (typeof cursor !== 'number' || typeof epoch !== 'string') {\n throw new Error('Durable Object invalidate() returned an invalid commit stamp');\n }\n return { cursor, epoch };\n}\n\n/**\n * Delivers live invalidations to the room Durable Object of a\n * `@WebSocketGateway({ binding })`, whose SQLite log stamps the commit. Inside\n * that Durable Object the same driver applies invalidations locally.\n */\nexport class CfLiveDriver implements LiveDriver {\n readonly kind = 'durable-object';\n #sink: LiveInvalidationSink | undefined;\n #local = false;\n #context: WorkerLiveContext | undefined;\n #target: LiveTarget | undefined;\n\n constructor(private readonly options: DurableObjectLiveOptions = {}) {}\n\n bind(sink: LiveInvalidationSink): void {\n this.#sink = sink;\n }\n\n /** @internal The Worker's live platform supplies its environment and gateways. */\n _attach(context: WorkerLiveContext): void {\n this.#context = context;\n this.#target = undefined;\n }\n\n /** @internal A Durable Object dispatches to its own engine and SQLite log. */\n _setLocalMode(): void {\n this.#local = true;\n }\n\n /**\n * @internal The Durable Object that holds one room's subscriptions. As for\n * upgrades and `Gateways` pushes, a gateway without `roomParam` keeps every\n * socket in one room, its path, so each of its rooms is in that object.\n */\n _room(room: string): GatewayRoomObject {\n const { env, binding, gatewayPath } = this.#resolveTarget();\n return gatewayRoomObject(env, gatewayPath, binding, gatewayObjectRoom(gatewayPath, room));\n }\n\n dispatch(cmd: InvalidationCommand): Promise<CommitStamp | undefined> | CommitStamp | undefined {\n if (this.#local) return this.#sink?.applyInvalidation(cmd);\n const room = cmd.room ?? this.options.defaultRoom ?? DEFAULT_ROOM;\n return this._room(room)\n .call('invalidate', { ...cmd, room })\n .then(commitStamp);\n }\n\n #resolveTarget(): LiveTarget {\n if (this.#target) return this.#target;\n const context = this.#context;\n if (!context) {\n throw new Error(\n 'durableObjectLive() needs the Cloudflare adapter: create the application with ' +\n 'createCloudflareWorker(), createCloudflareApp() or cloudflareAdapter().',\n );\n }\n let { binding, gatewayPath } = this.options;\n const gateways = context.gateways();\n if (binding === undefined || gatewayPath === undefined) {\n const candidates = gateways.filter(\n (gateway) =>\n (binding === undefined || gateway.binding === binding) &&\n (gatewayPath === undefined || gateway.path === gatewayPath),\n );\n const [chosen, ...others] = candidates;\n if (!chosen) {\n const filter = describeFilter(this.options);\n throw new Error(\n filter\n ? `durableObjectLive() found no @WebSocketGateway with ${filter}. Name the gateway ` +\n 'that holds the subscriptions, with its binding.'\n : 'LiveModule delivers Worker invalidations to the room Durable Object of a ' +\n 'gateway, but no @WebSocketGateway names a binding. Declare one with ' +\n '{ binding }, or pass driver: () => durableObjectLive({ binding, gatewayPath }).',\n );\n }\n if (others.length > 0) {\n const paths = candidates.map((gateway) => `'${gateway.path}'`).join(', ');\n throw new Error(\n `LiveModule must choose where Worker invalidations go, but several binding-backed ` +\n `gateways (${paths}) could hold the subscriptions. Pass ` +\n 'driver: () => durableObjectLive({ gatewayPath }) to LiveModule.',\n );\n }\n binding ??= chosen.binding;\n gatewayPath ??= chosen.path;\n }\n const target: LiveTarget = { env: context.env, binding, gatewayPath };\n this.#target = target;\n return target;\n }\n}\n\n/**\n * The Cloudflare live driver, for `LiveModule.forRoot({ driver })`. It is the\n * default on Cloudflare, so name it only to choose a gateway, binding or\n * default room:\n *\n * ```ts\n * LiveModule.forRoot({ driver: () => durableObjectLive({ gatewayPath: '/rooms/:id/ws' }) })\n * ```\n */\nexport function durableObjectLive(options: DurableObjectLiveOptions = {}): CfLiveDriver {\n return new CfLiveDriver(options);\n}\n\nlet workerLocalLiveWarned = false;\n\n/**\n * The Worker isolate's live platform: invalidations default to the room\n * Durable Object of the application's binding-backed gateway, chosen and read\n * from `ENV` when first needed, and `LiveInspector` reads each room from that\n * object. A configured local driver is warned about once per isolate:\n * subscriptions live in the Durable Object, so it would reach none.\n */\nexport function workerLivePlatform(env: VelaEnv, container: Container): LivePlatform {\n const context: WorkerLiveContext = {\n env,\n gateways: () => bindingGateways(container.resolve(DiscoveryService)),\n };\n let bound: CfLiveDriver | undefined;\n return {\n liveDriver: () => durableObjectLive(),\n async inspect(room) {\n if (!bound) throw new Error('LiveModule delivers locally in this Worker: no room to inspect');\n const value: unknown = await bound._room(room).call('inspectLive');\n const subscriptions: unknown =\n typeof value === 'object' && value !== null\n ? Reflect.get(value, 'subscriptions')\n : undefined;\n const rooms: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'rooms') : undefined;\n if (!Array.isArray(subscriptions) || !Array.isArray(rooms)) {\n throw new Error('Durable Object inspectLive() returned an invalid snapshot');\n }\n return { subscriptions, rooms };\n },\n bindDriver(driver) {\n if (driver instanceof CfLiveDriver) {\n driver._attach(context);\n bound = driver;\n return;\n }\n if (driver.kind !== 'local' || workerLocalLiveWarned) return;\n if (container.getDiagnostics() === 'silent') return;\n workerLocalLiveWarned = true;\n console.warn(\n '[vela] LiveModule is running localLive() in the Worker isolate: its subscriptions live ' +\n 'in the WebSocket Durable Object, so invalidations sent from the Worker never reach ' +\n 'them. Remove the driver option to deliver through the gateway room Durable Object.',\n );\n },\n };\n}\n"],"mappings":";;;;;AAaA,MAAM,eAAe;AA6CrB,SAAS,eAAe,EAAE,SAAS,eAAiD;CAKlF,OAAO,CAHL,GAAI,YAAY,KAAA,IAAY,CAAC,IAAI,CAAC,YAAY,QAAQ,EAAE,GACxD,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,CAAC,SAAS,YAAY,EAAE,CAEpD,CAAC,CAAC,KAAK,OAAO;AAC3B;;AAGA,SAAS,YAAY,OAAyC;CAC5D,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,SACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ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EAChC;EACA,WAAW,QAAQ;GACjB,IAAI,kBAAkB,cAAc;IAClC,OAAO,QAAQ,OAAO;IACtB,QAAQ;IACR;GACF;GACA,IAAI,OAAO,SAAS,WAAW,uBAAuB;GACtD,IAAI,UAAU,eAAe,MAAM,UAAU;GAC7C,wBAAwB;GACxB,QAAQ,KACN,8PAGF;EACF;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- //#region src/websocket/room-id.ts
1
+ // src/websocket/room-id.ts
2
2
  /** Hibernation tag marking a socket's hub room (set at accept; immutable after). */
3
3
  function roomTag(roomId) {
4
4
  return `room:${roomId}`;
@@ -31,7 +31,6 @@ function gatewayObjectRoom(gatewayPath, room) {
31
31
  function roomToDurableId(ns, gatewayPath, roomId) {
32
32
  return ns.idFromName(durableObjectRoomName(gatewayPath, roomId));
33
33
  }
34
- //#endregion
35
34
  export { connTag, durableObjectRoomName, gatewayObjectRoom, roomTag, roomToDurableId };
36
35
 
37
36
  //# sourceMappingURL=room-id.js.map
@@ -1,11 +1,11 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import { buildDoRuntime } from "./do-bootstrap.js";
3
+ import { DoWebSocketHost } from "./do-websocket-host.js";
4
+ import { armDoPitr, readDoPitrBookmark } from "./do-pitr.js";
1
5
  import { FORWARDED_UPGRADE_HEADERS } from "./worker-transport.js";
2
6
  import { CLOUDFLARE_DURABLE_OBJECT, registerDurableObject } from "../cloudflare-factory.js";
3
- import { armDoPitr, readDoPitrBookmark } from "./do-pitr.js";
4
- import { DoWebSocketHost } from "./do-websocket-host.js";
5
7
  import { durableObjectDefinition, startDurableObject } from "../durable-object/boot.js";
6
- import { buildDoRuntime } from "./do-bootstrap.js";
7
- import { DurableObject } from "cloudflare:workers";
8
- //#region src/websocket/websocket.durable-object.ts
8
+ // src/websocket/websocket.durable-object.ts
9
9
  const PING = "{\"event\":\"$ping\"}";
10
10
  const PONG = "{\"event\":\"$pong\"}";
11
11
  const MAX_IDENTITY_FIELD_BYTES = 2048;
@@ -165,7 +165,6 @@ function VelaWebSocketDurableObject(root) {
165
165
  if (definition.app) registerDurableObject(definition.app, descriptor);
166
166
  return VelaWsDurableObject;
167
167
  }
168
- //#endregion
169
168
  export { VelaWebSocketDurableObject };
170
169
 
171
170
  //# sourceMappingURL=websocket.durable-object.js.map