@velajs/cloudflare 1.10.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -3
- package/LICENSE +21 -0
- package/README.md +197 -322
- package/dist/durable-objects.d.ts +28 -0
- package/dist/durable-objects.js +494 -0
- package/dist/durable-objects.js.map +1 -0
- package/dist/index.d.ts +622 -41
- package/dist/index.js +1023 -39
- package/dist/index.js.map +1 -0
- package/dist/nonce-validation-LE0vFk-7.js +445 -0
- package/dist/nonce-validation-LE0vFk-7.js.map +1 -0
- package/dist/nonce.durable-object-Df3_42Sy.d.ts +141 -0
- package/package.json +66 -44
- package/dist/binding-ref.d.ts +0 -8
- package/dist/binding-ref.js +0 -19
- package/dist/cloudflare-application.d.ts +0 -125
- package/dist/cloudflare-application.js +0 -186
- package/dist/cloudflare-factory.d.ts +0 -88
- package/dist/cloudflare-factory.js +0 -107
- package/dist/decorators/env.d.ts +0 -16
- package/dist/decorators/env.js +0 -22
- package/dist/decorators/queue-consumer.d.ts +0 -23
- package/dist/decorators/queue-consumer.js +0 -40
- package/dist/decorators/scheduled.d.ts +0 -20
- package/dist/decorators/scheduled.js +0 -36
- package/dist/env-ref.d.ts +0 -10
- package/dist/env-ref.js +0 -13
- package/dist/modules/ai.module.d.ts +0 -1
- package/dist/modules/ai.module.js +0 -8
- package/dist/modules/create-binding-module.d.ts +0 -14
- package/dist/modules/create-binding-module.js +0 -42
- package/dist/modules/d1.module.d.ts +0 -1
- package/dist/modules/d1.module.js +0 -8
- package/dist/modules/durable-object.module.d.ts +0 -1
- package/dist/modules/durable-object.module.js +0 -8
- package/dist/modules/env.module.d.ts +0 -17
- package/dist/modules/env.module.js +0 -35
- package/dist/modules/hyperdrive.module.d.ts +0 -1
- package/dist/modules/hyperdrive.module.js +0 -8
- package/dist/modules/kv.module.d.ts +0 -1
- package/dist/modules/kv.module.js +0 -8
- package/dist/modules/queue.module.d.ts +0 -1
- package/dist/modules/queue.module.js +0 -8
- package/dist/modules/r2.module.d.ts +0 -1
- package/dist/modules/r2.module.js +0 -8
- package/dist/modules/vectorize.module.d.ts +0 -1
- package/dist/modules/vectorize.module.js +0 -8
- package/dist/services/ai.service.d.ts +0 -6
- package/dist/services/ai.service.js +0 -33
- package/dist/services/d1.service.d.ts +0 -6
- package/dist/services/d1.service.js +0 -33
- package/dist/services/durable-object.service.d.ts +0 -6
- package/dist/services/durable-object.service.js +0 -33
- package/dist/services/env.service.d.ts +0 -31
- package/dist/services/env.service.js +0 -36
- package/dist/services/flagship-flag.driver.d.ts +0 -57
- package/dist/services/flagship-flag.driver.js +0 -49
- package/dist/services/hyperdrive.service.d.ts +0 -12
- package/dist/services/hyperdrive.service.js +0 -51
- package/dist/services/kv-cache.store.d.ts +0 -19
- package/dist/services/kv-cache.store.js +0 -58
- package/dist/services/kv-flag.driver.d.ts +0 -48
- package/dist/services/kv-flag.driver.js +0 -62
- package/dist/services/kv.service.d.ts +0 -11
- package/dist/services/kv.service.js +0 -33
- package/dist/services/queue.service.d.ts +0 -6
- package/dist/services/queue.service.js +0 -33
- package/dist/services/r2.service.d.ts +0 -6
- package/dist/services/r2.service.js +0 -33
- package/dist/services/vectorize.service.d.ts +0 -6
- package/dist/services/vectorize.service.js +0 -33
- package/dist/storage/index.d.ts +0 -7
- package/dist/storage/index.js +0 -6
- package/dist/storage/r2-storage.driver.d.ts +0 -19
- package/dist/storage/r2-storage.driver.js +0 -61
- package/dist/storage/storage-manager.service.d.ts +0 -16
- package/dist/storage/storage-manager.service.js +0 -56
- package/dist/storage/storage.controller.d.ts +0 -16
- package/dist/storage/storage.controller.js +0 -88
- package/dist/storage/storage.module.d.ts +0 -7
- package/dist/storage/storage.module.js +0 -37
- package/dist/storage/storage.service.d.ts +0 -20
- package/dist/storage/storage.service.js +0 -78
- package/dist/storage/storage.tokens.d.ts +0 -3
- package/dist/storage/storage.tokens.js +0 -2
- package/dist/storage/storage.types.d.ts +0 -17
- package/dist/storage/storage.types.js +0 -1
- package/dist/tokens.d.ts +0 -12
- package/dist/tokens.js +0 -12
- package/dist/types.d.ts +0 -13
- package/dist/types.js +0 -1
- package/dist/websocket/broadcast.d.ts +0 -15
- package/dist/websocket/broadcast.js +0 -26
- package/dist/websocket/cf-room-registry.d.ts +0 -23
- package/dist/websocket/cf-room-registry.js +0 -65
- package/dist/websocket/cf-ws-client.d.ts +0 -28
- package/dist/websocket/cf-ws-client.js +0 -83
- package/dist/websocket/cloudflare-websocket.module.d.ts +0 -11
- package/dist/websocket/cloudflare-websocket.module.js +0 -27
- package/dist/websocket/do-bootstrap.d.ts +0 -24
- package/dist/websocket/do-bootstrap.js +0 -55
- package/dist/websocket/do-live.d.ts +0 -81
- package/dist/websocket/do-live.js +0 -197
- package/dist/websocket/do-state.d.ts +0 -35
- package/dist/websocket/do-state.js +0 -4
- package/dist/websocket/do-websocket-host.d.ts +0 -28
- package/dist/websocket/do-websocket-host.js +0 -69
- package/dist/websocket/index.d.ts +0 -15
- package/dist/websocket/index.js +0 -15
- package/dist/websocket/room-id.d.ts +0 -6
- package/dist/websocket/room-id.js +0 -12
- package/dist/websocket/websocket-routing.d.ts +0 -14
- package/dist/websocket/websocket-routing.js +0 -45
- package/dist/websocket/websocket.durable-object.d.ts +0 -15
- package/dist/websocket/websocket.durable-object.js +0 -83
- package/dist/websocket/ws-server-holder.d.ts +0 -16
- package/dist/websocket/ws-server-holder.js +0 -34
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nonce-validation-LE0vFk-7.js","names":["encoder","encoder"],"sources":["../src/websocket/room-id.ts","../src/environment.ts","../src/root-module.ts","../src/websocket/do-pitr.ts","../src/websocket/ws-server-holder.ts","../src/websocket/do-state.ts","../src/websocket/cf-ws-client.ts","../src/websocket/do-live.ts","../src/nonce/nonce-validation.ts"],"sourcesContent":["// Canonical room ↔ Durable Object mappings. The SAME functions are used by the\n// Worker upgrade route (to pick the DO) and by every server-initiated emit — so\n// a connection and a later broadcast always resolve to the same DO instance.\n\n/** Hibernation tag marking a socket's hub room (set at accept; immutable after). */\nexport function roomTag(roomId: string): string {\n return `room:${roomId}`;\n}\n\n/** Hibernation tag addressing one connection directly. */\nexport function connTag(connId: string): string {\n return `conn:${connId}`;\n}\n\nconst DO_ROOM_NAME_PREFIX = 'vela:ws:v2:';\nconst MAX_DO_ROOM_NAME_BYTES = 1_024;\nconst encoder = new TextEncoder();\n\n/** Stable, collision-free Durable Object name for one gateway's room. */\nexport function durableObjectRoomName(gatewayPath: string, roomId: string): string {\n if (\n typeof gatewayPath !== 'string' ||\n gatewayPath.length === 0 ||\n typeof roomId !== 'string' ||\n roomId.length === 0 ||\n /[\\u0000-\\u001f\\u007f]/.test(gatewayPath) ||\n /[\\u0000-\\u001f\\u007f]/.test(roomId)\n ) {\n throw new Error('A non-empty, control-free gateway path and room id are required');\n }\n const name = `${DO_ROOM_NAME_PREFIX}${encodeURIComponent(gatewayPath)}:${encodeURIComponent(roomId)}`;\n if (encoder.encode(name).byteLength > MAX_DO_ROOM_NAME_BYTES) {\n throw new Error('The gateway/room Durable Object name exceeds 1024 bytes');\n }\n return name;\n}\n\n/** One Durable Object instance per gateway + room, addressed by name. */\nexport function roomToDurableId(\n ns: Pick<DurableObjectNamespace, 'idFromName'>,\n gatewayPath: string,\n roomId: string,\n): DurableObjectId {\n return ns.idFromName(durableObjectRoomName(gatewayPath, roomId));\n}\n","import { defineProvider, InjectionToken } from '@velajs/vela';\nimport type { Container } from '@velajs/vela/internal';\n\n/** An application's native Workers environment, including bindings and secrets. */\nexport interface CloudflareEnvironment<T extends object> {\n /** Typed token used by @Inject and provider factories. */\n readonly token: InjectionToken<T>;\n /** The environment supplied by the current platform event or DO constructor. */\n readonly env: T;\n}\n\n/**\n * Register native bindings before provider factories or lifecycle hooks run.\n * No platform I/O is performed here; callers create applications inside an event.\n */\nexport function registerCloudflareEnvironment<T extends object>(\n container: Container,\n environment: CloudflareEnvironment<T>,\n): void {\n container.register(defineProvider(environment.token, { useValue: environment.env }));\n container.markGlobalToken(environment.token);\n}\n\n/** Reject accidental reuse of an application with another event's environment. */\nexport function assertCloudflareEnvironment<T extends object>(expected: T, actual: T): void {\n if (actual !== expected) {\n throw new Error(\n 'This Cloudflare application belongs to a different environment. ' +\n 'Create an application with the current event environment.',\n );\n }\n}\n","import type { Type } from '@velajs/vela';\n\n/** A static module, or a module graph built from this Worker's native environment. */\nexport type CloudflareRoot<T extends object> = Type | { create(env: T): Type };\n\nexport function resolveCloudflareRoot<T extends object>(root: CloudflareRoot<T>, env: T): Type {\n return typeof root === 'function' ? root : root.create(env);\n}\n","/**\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","import { Injectable } from '@velajs/vela';\nimport { resolveMaxFrameBytes } from '@velajs/vela/websocket';\nimport type { BroadcastOperator, WsServer } from '@velajs/vela/websocket';\n\n/**\n * Late-bound `WsServer`. Provided as `WS_SERVER` (one per DI container, i.e. per\n * Durable Object instance), then pointed at the ctx-backed server once the DO\n * builds. Gateways inject it via `@WebSocketServer()`; it throws if used before\n * a runtime binds it (e.g. from the stateless Worker isolate).\n */\n@Injectable()\nexport class WsServerHolder implements WsServer {\n private target?: WsServer;\n private maxFrameBytes?: number;\n\n setTarget(server: WsServer): void {\n this.target = server;\n if (this.maxFrameBytes !== undefined) server.setOutboundFrameLimit?.(this.maxFrameBytes);\n }\n\n setOutboundFrameLimit(maxFrameBytes: number): void {\n const resolved = resolveMaxFrameBytes({ maxFrameBytes });\n this.maxFrameBytes =\n this.maxFrameBytes === undefined ? resolved : Math.max(this.maxFrameBytes, resolved);\n this.target?.setOutboundFrameLimit?.(this.maxFrameBytes);\n }\n\n private get resolved(): WsServer {\n if (!this.target) {\n throw new Error(\n 'WebSocket server is only available inside a WebSocket Durable Object. To ' +\n 'push from a Worker HTTP handler, use broadcastToRoom(namespace, gatewayPath, room, ...).',\n );\n }\n return this.target;\n }\n\n emit(event: string, data?: unknown): void | Promise<void> {\n return this.resolved.emit(event, data);\n }\n to(room: string): BroadcastOperator {\n return this.resolved.to(room);\n }\n in(room: string): BroadcastOperator {\n return this.resolved.in(room);\n }\n except(room: string): BroadcastOperator {\n return this.resolved.except(room);\n }\n}\n","// Minimal structural views of the Durable Object runtime, so the transport\n// logic is unit-testable in Node with fakes. Real `DurableObjectState` and\n// `WebSocket` (from @cloudflare/workers-types) satisfy these structurally.\n\n/** Cloudflare's serialized WebSocket hibernation attachment ceiling. */\nexport const MAX_WS_ATTACHMENT_BYTES = 16_384;\n\nexport interface WsLike {\n send(message: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n serializeAttachment(value: unknown): void;\n deserializeAttachment(): unknown;\n}\n\n/** Structural view of the DO's SQLite handle (`ctx.storage.sql`, requires `new_sqlite_classes`). */\nexport interface SqlStorageLike {\n exec(query: string, ...bindings: unknown[]): { toArray(): Record<string, unknown>[] };\n}\n\nexport interface DoStateLike {\n readonly id: { toString(): string; readonly name?: string | null };\n acceptWebSocket(ws: WsLike, tags?: string[]): void;\n getWebSockets(tag?: string): WsLike[];\n setWebSocketAutoResponse?(pair: unknown): void;\n /** Present on SQLite-backed DOs — the live cursor log lives here. */\n readonly storage?: { sql?: SqlStorageLike };\n}\n\n/** Per-connection metadata persisted in the hibernation attachment (≤ 16 KiB). */\nexport interface WsAttachment {\n connId: string;\n /** Only active sockets may dispatch frames or receive fan-out. */\n state: 'pending' | 'active' | 'rejected';\n userId?: string;\n /** Verified, issuer-qualified connection principal. */\n principal?: {\n issuer: string;\n subject: string;\n principalType: 'user' | 'service';\n };\n /** Trusted server-derived tenant boundary for this connection. */\n tenantId?: string;\n /** Verified auth credential expiry in epoch milliseconds. */\n expiresAtMs?: number;\n /** The gateway route path this socket belongs to — used to route messages. */\n path: string;\n /** Validated inbound/outbound gateway frame ceiling, persisted across hibernation. */\n maxFrameBytes?: number;\n /** Dynamically-joined room names (the hub room is also a hibernation tag). */\n rooms: string[];\n data: Record<string, unknown>;\n}\n","import type { WsClient } from '@velajs/vela/websocket';\nimport {\n assertWebSocketRoomId,\n DEFAULT_WS_MAX_FRAME_BYTES,\n DEFAULT_WS_MAX_JOINED_ROOMS,\n webSocketFrameFits,\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\nconst EMPTY: WsAttachment = { connId: '', state: 'rejected', path: '', rooms: [], data: {} };\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 private readonly attachment: WsAttachment;\n\n constructor(\n private readonly ctx: DoStateLike,\n private readonly ws: WsLike,\n ) {\n const raw = ws.deserializeAttachment() as WsAttachment | null;\n this.attachment = raw ?? { ...EMPTY, data: {} };\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 if (!webSocketFrameFits(payload, this.maxFrameBytes)) {\n this.close(1009, 'Message too large');\n return;\n }\n this.ws.send(payload);\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 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","import type { Container } from '@velajs/vela';\nimport {\n LIVE_CURSOR_LOG,\n LIVE_DRIVER,\n LiveEngine,\n readPersistedLiveSubscriptions,\n} from '@velajs/vela/live';\nimport type {\n CommitStamp,\n CursorLog,\n InvalidationCommand,\n LiveDriver,\n LiveInvalidationSink,\n ResumeVerdict,\n} from '@velajs/vela/live';\nimport { CfWsClient } from './cf-ws-client';\nimport type { DoStateLike, SqlStorageLike } from './do-state';\nimport { roomToDurableId } from './room-id';\n\nconst DEFAULT_ROOM = 'default';\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 * Constructed un-initialized at module-composition time (the same app module\n * bootstraps in the Worker AND in each DO); `initDoLive` wires the SQLite\n * handle inside the DO. In the Worker isolate it stays un-initialized — and is\n * never consulted there, because `durableObjectLive()` routes every\n * invalidation to the room DO's log (one log scope per room, exactly the\n * protocol's model).\n */\nexport class DoCursorLog implements CursorLog {\n private sql?: SqlStorageLike;\n private epoch?: string;\n\n constructor(private readonly maxRows = DEFAULT_MAX_LOG_ROWS) {}\n\n /** @internal — called by `initDoLive` with the DO's `ctx.storage.sql`. */\n _initialize(sql: SqlStorageLike): void {\n this.sql = sql;\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 const sql = this.assertReady();\n 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 sql.exec('DELETE FROM __vela_live_log WHERE seq <= ?', stamp.cursor - this.maxRows);\n }\n return stamp;\n }\n\n current(): CommitStamp {\n const sql = this.assertReady();\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 = 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 if (!this.epoch) throw new Error('DoCursorLog epoch is not initialized.');\n return { cursor, epoch: this.epoch };\n }\n\n evaluateResume(\n sinceCursor: number,\n sinceEpoch: string,\n subscriptionTags: string[],\n ): ResumeVerdict {\n const sql = this.assertReady();\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 = 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 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 private assertReady(): SqlStorageLike {\n if (!this.sql) {\n throw new Error(\n 'DoCursorLog is not initialized. It only runs inside a SQLite-backed Durable Object ' +\n '(wrangler: new_sqlite_classes) — Worker-side invalidations must go through durableObjectLive(), ' +\n \"which routes them to the room DO's log.\",\n );\n }\n return this.sql;\n }\n}\n\nexport interface DurableObjectLiveOptions {\n /** Native, RPC-typed namespace supplied by the application's environment. */\n namespace: LiveNamespace;\n /** Exact `@WebSocketGateway()` path sharing this room/log namespace. */\n gatewayPath: string;\n /** Room used when an invalidation names none. Matches the client default. */\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/** One driver per application; construct from a LiveModule driver factory. */\nexport class CfLiveDriver implements LiveDriver {\n readonly kind = 'durable-object';\n private sink: LiveInvalidationSink | undefined;\n private localMode = false;\n\n constructor(private readonly options: DurableObjectLiveOptions) {}\n\n bind(sink: LiveInvalidationSink): void {\n this.sink = sink;\n }\n\n /** @internal — a DO dispatches to its own engine and SQLite log. */\n _setLocalMode(): void {\n this.localMode = true;\n }\n\n dispatch(cmd: InvalidationCommand): Promise<CommitStamp | undefined> | CommitStamp | undefined {\n if (this.localMode) return this.sink?.applyInvalidation(cmd);\n const { namespace, gatewayPath, defaultRoom } = this.options;\n const room = cmd.room ?? defaultRoom ?? DEFAULT_ROOM;\n return namespace\n .get(roomToDurableId(namespace, gatewayPath, room))\n .invalidate({ ...cmd, room });\n }\n}\n\n/** Use in LiveModule.forRootAsync: driver: () => durableObjectLive({ namespace: env.ROOMS, ... }). */\nexport function durableObjectLive(options: DurableObjectLiveOptions): CfLiveDriver {\n return new CfLiveDriver(options);\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/** @internal — prepare per-DO resources before user lifecycle hooks can invalidate. */\nexport function initializeDoLiveResources(container: Container, ctx: DoStateLike): void {\n if (container.has(LIVE_CURSOR_LOG)) {\n const log = container.resolve(LIVE_CURSOR_LOG);\n if (log instanceof DoCursorLog) {\n const sql = ctx.storage?.sql;\n if (!sql) {\n throw new Error(\n 'DoCursorLog requires a SQLite-backed Durable Object: add this class to ' +\n \"wrangler's `migrations[].new_sqlite_classes`. Falling back is not possible — \" +\n 'either enable SQLite or drop the `log: () => durableObjectCursorLog()` option ' +\n '(snapshot-on-reconnect semantics).',\n );\n }\n log._initialize(sql);\n }\n }\n\n if (container.has(LIVE_DRIVER)) {\n const driver = container.resolve(LIVE_DRIVER);\n if (driver instanceof CfLiveDriver) driver._setLocalMode();\n }\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(app: EntrypointsApp, ctx: DoStateLike): 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 = new CfWsClient(ctx, ws);\n for (const record of readPersistedLiveSubscriptions(client)) {\n engine.restoreSubscription(client.path, client, record);\n }\n }\n\n return engine;\n}\n\n/** Ergonomic alias: the log option for `LiveModule.forRoot` on Cloudflare. */\nexport function durableObjectCursorLog(maxRows?: number): DoCursorLog {\n return new DoCursorLog(maxRows);\n}\n\n/**\n * Invalidate live tags in a room from a Worker (controller / cron / queue\n * consumer) — the live sibling of `broadcastToRoom`. Returns the room log\n * scope's commit stamp for `Vela-Commit-Cursor` stamping.\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, room));\n return stub.invalidate({ room, tags });\n}\n","const encoder = new TextEncoder();\nexport const MAX_NONCE_BYTES = 512;\nexport function isCanonicalBoundedText(value: unknown, maxBytes: number): value is string {\n if (typeof value !== 'string') return false;\n for (const character of value) {\n const codePoint = character.codePointAt(0);\n if (\n codePoint !== undefined &&\n (codePoint <= 0x1f || codePoint === 0x7f || (codePoint >= 0xd800 && codePoint <= 0xdfff))\n ) {\n return false;\n }\n }\n return value.length > 0 && value === value.trim() && encoder.encode(value).byteLength <= maxBytes;\n}\n\nexport function isValidExpiry(\n expEpochSeconds: unknown,\n nowEpochSeconds: number,\n): expEpochSeconds is number {\n return (\n typeof expEpochSeconds === 'number' &&\n Number.isSafeInteger(expEpochSeconds) &&\n expEpochSeconds > 0 &&\n expEpochSeconds >= nowEpochSeconds\n );\n}\n"],"mappings":";;;;;AAKA,SAAgB,QAAQ,QAAwB;CAC9C,OAAO,QAAQ;AACjB;;AAGA,SAAgB,QAAQ,QAAwB;CAC9C,OAAO,QAAQ;AACjB;AAEA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAMA,YAAU,IAAI,YAAY;;AAGhC,SAAgB,sBAAsB,aAAqB,QAAwB;CACjF,IACE,OAAO,gBAAgB,YACvB,YAAY,WAAW,KACvB,OAAO,WAAW,YAClB,OAAO,WAAW,KAClB,wBAAwB,KAAK,WAAW,KACxC,wBAAwB,KAAK,MAAM,GAEnC,MAAM,IAAI,MAAM,iEAAiE;CAEnF,MAAM,OAAO,GAAG,sBAAsB,mBAAmB,WAAW,EAAE,GAAG,mBAAmB,MAAM;CAClG,IAAIA,UAAQ,OAAO,IAAI,CAAC,CAAC,aAAa,wBACpC,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;AACT;;AAGA,SAAgB,gBACd,IACA,aACA,QACiB;CACjB,OAAO,GAAG,WAAW,sBAAsB,aAAa,MAAM,CAAC;AACjE;;;;;;;AC7BA,SAAgB,8BACd,WACA,aACM;CACN,UAAU,SAAS,eAAe,Y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AY,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,IAAI,WAAW,KAAK,EAAE;EACrC,KAAK,MAAM,UAAU,+BAA+B,MAAM,GACxD,OAAO,oBAAoB,OAAO,MAAM,QAAQ,MAAM;CAE1D;CAEA,OAAO;AACT;;AAGA,SAAgB,uBAAuB,SAA+B;CACpE,OAAO,IAAI,YAAY,OAAO;AAChC;;;;;;AAOA,eAAsB,qBACpB,IACA,aACA,MACA,MACkC;CAElC,OADa,GAAG,IAAI,gBAAgB,IAAI,aAAa,IAAI,CAC/C,CAAC,CAAC,WAAW;EAAE;EAAM;CAAK,CAAC;AACvC;;;ACvQA,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAgB,uBAAuB,OAAgB,UAAmC;CACxF,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,KAAK,MAAM,aAAa,OAAO;EAC7B,MAAM,YAAY,UAAU,YAAY,CAAC;EACzC,IACE,cAAc,KAAA,MACb,aAAa,MAAQ,cAAc,OAAS,aAAa,SAAU,aAAa,QAEjF,OAAO;CAEX;CACA,OAAO,MAAM,SAAS,KAAK,UAAU,MAAM,KAAK,KAAK,QAAQ,OAAO,KAAK,CAAC,CAAC,cAAc;AAC3F;AAEA,SAAgB,cACd,iBACA,iBAC2B;CAC3B,OACE,OAAO,oBAAoB,YAC3B,OAAO,cAAc,eAAe,KACpC,kBAAkB,KAClB,mBAAmB;AAEvB"}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { Type } from "@velajs/vela";
|
|
2
|
+
import { DurableObject } from "cloudflare:workers";
|
|
3
|
+
//#region src/root-module.d.ts
|
|
4
|
+
/** A static module, or a module graph built from this Worker's native environment. */
|
|
5
|
+
type CloudflareRoot<T extends object> = Type | {
|
|
6
|
+
create(env: T): Type;
|
|
7
|
+
};
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/websocket/do-pitr.d.ts
|
|
10
|
+
/**
|
|
11
|
+
* Durable Object point-in-time recovery (PITR) — thin, testable wrappers over a
|
|
12
|
+
* SQLite-backed DO's native bookmark API. A SQLite Durable Object exposes three
|
|
13
|
+
* storage methods (last-30-days PITR):
|
|
14
|
+
*
|
|
15
|
+
* - `getCurrentBookmark()` — an opaque bookmark for the storage's current state.
|
|
16
|
+
* - `getBookmarkForTime(t)` — the bookmark closest to a wall-clock instant.
|
|
17
|
+
* - `onNextSessionRestoreBookmark(b)` — arm a restore to bookmark `b`; the DO
|
|
18
|
+
* restores to it the next time it starts a session, and the call RETURNS a
|
|
19
|
+
* bookmark for the state JUST BEFORE the restore (the undo handle).
|
|
20
|
+
*
|
|
21
|
+
* These methods are ABSENT on a non-SQLite DO (key-value storage) and in some
|
|
22
|
+
* local-dev runtimes, so this module models storage structurally with all three
|
|
23
|
+
* methods OPTIONAL and degrades to a typed {@link DoPitrUnavailableError} (a
|
|
24
|
+
* `code: 'PITR_UNAVAILABLE'`, HTTP 409 error) rather than an
|
|
25
|
+
* `undefined is not a function` TypeError when a needed method is missing.
|
|
26
|
+
*
|
|
27
|
+
* Neither wrapper aborts the DO — `armDoPitr` only ARMS the restore and returns
|
|
28
|
+
* the undo bookmark; the caller (the WS-DO RPC method) decides whether to
|
|
29
|
+
* `ctx.abort()` to apply it immediately vs. on the next natural restart.
|
|
30
|
+
*
|
|
31
|
+
* This file is `cloudflare:workers`-free and pulls in NOTHING from `@velajs/vela`
|
|
32
|
+
* or `@velajs/studio` — it is the raw capability the studio `TimeTravelPort`
|
|
33
|
+
* wraps. Dependency direction is one-way: studio → cloudflare, never the reverse.
|
|
34
|
+
*/
|
|
35
|
+
/**
|
|
36
|
+
* The subset of `DurableObjectStorage` this module touches, with every method
|
|
37
|
+
* OPTIONAL so it structurally models a non-SQLite DO whose storage has none of
|
|
38
|
+
* them. A real `DurableObjectStorage` (whose methods are required) is assignable
|
|
39
|
+
* to this shape.
|
|
40
|
+
*/
|
|
41
|
+
interface DoPitrStorage {
|
|
42
|
+
getCurrentBookmark?(): Promise<string>;
|
|
43
|
+
getBookmarkForTime?(timestamp: number | Date): Promise<string>;
|
|
44
|
+
onNextSessionRestoreBookmark?(bookmark: string): Promise<string>;
|
|
45
|
+
}
|
|
46
|
+
/** A read of a DO's current bookmark (+ the by-time bookmark when a time is given). */
|
|
47
|
+
interface DoPitrBookmarkRead {
|
|
48
|
+
/** The bookmark for the DO storage's current state. */
|
|
49
|
+
current: string;
|
|
50
|
+
/** The bookmark closest to the requested time (only when `time` was passed). */
|
|
51
|
+
forTime?: string;
|
|
52
|
+
}
|
|
53
|
+
/** Arming input for {@link armDoPitr}: a target (bookmark WINS over time) + restart intent. */
|
|
54
|
+
interface DoPitrArmOptions {
|
|
55
|
+
/** An explicit target bookmark. Takes precedence over `time`. */
|
|
56
|
+
bookmark?: string;
|
|
57
|
+
/** A wall-clock target (epoch ms, ISO string, or Date), resolved to a bookmark. */
|
|
58
|
+
time?: number | string | Date;
|
|
59
|
+
/** Caller intent to restart-now; recorded on the result. `armDoPitr` never aborts. */
|
|
60
|
+
restart?: boolean;
|
|
61
|
+
}
|
|
62
|
+
/** The result of arming a PITR restore (before any restart is applied). */
|
|
63
|
+
interface DoPitrArmResult {
|
|
64
|
+
/** The bookmark the restore is armed to. */
|
|
65
|
+
restoredTo: string;
|
|
66
|
+
/** The bookmark for the pre-restore state — restore to this to undo. */
|
|
67
|
+
undoBookmark: string;
|
|
68
|
+
/** Whether a restart-now was requested (the RPC layer performs the actual abort). */
|
|
69
|
+
restarted: boolean;
|
|
70
|
+
}
|
|
71
|
+
/** The RPC surface a PITR-capable Vela WebSocket DO stub exposes to a Worker. */
|
|
72
|
+
interface VelaDoPitrRpc {
|
|
73
|
+
pitrCurrentBookmark(): Promise<DoPitrBookmarkRead>;
|
|
74
|
+
pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead>;
|
|
75
|
+
pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult>;
|
|
76
|
+
}
|
|
77
|
+
/** Structural view of a DO id (avoids depending on `@cloudflare/workers-types` downstream). */
|
|
78
|
+
interface DoPitrId {
|
|
79
|
+
toString(): string;
|
|
80
|
+
readonly name?: string | null;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Structural view of a DO namespace binding whose stubs speak the PITR RPC. A
|
|
84
|
+
* downstream (the studio `@velajs/studio/cloudflare` port) types the app's
|
|
85
|
+
* namespace binding as this shape to reach the PITR methods without importing
|
|
86
|
+
* `@cloudflare/workers-types`.
|
|
87
|
+
*/
|
|
88
|
+
interface DoPitrNamespace {
|
|
89
|
+
idFromName(name: string): DoPitrId;
|
|
90
|
+
get(id: DoPitrId): VelaDoPitrRpc;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Thrown when a DO's storage lacks the SQLite bookmark API (non-SQLite DO, or a
|
|
94
|
+
* local runtime without PITR). Carries a stable `code` + HTTP 409 `status`, and
|
|
95
|
+
* a recognizable `name`/message so the studio port can map it to
|
|
96
|
+
* `TIMETRAVEL_UNAVAILABLE` even after the error crosses the Worker→DO RPC hop
|
|
97
|
+
* (which preserves `name` + `message`, not arbitrary own-properties).
|
|
98
|
+
*/
|
|
99
|
+
declare class DoPitrUnavailableError extends Error {
|
|
100
|
+
readonly code = "PITR_UNAVAILABLE";
|
|
101
|
+
readonly status = 409;
|
|
102
|
+
constructor(message?: string);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* True when `error` signals DO PITR unavailability. Robust across the Worker→DO
|
|
106
|
+
* RPC hop: checks the `code` own-property (same process) AND the `name` / message
|
|
107
|
+
* sentinel (survive RPC serialization) so a downstream can classify it either way.
|
|
108
|
+
*/
|
|
109
|
+
declare function isDoPitrUnavailable(error: unknown): boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Read a DO's current bookmark, and — when `time` is given — the bookmark closest
|
|
112
|
+
* to that instant. Throws {@link DoPitrUnavailableError} when a needed method is
|
|
113
|
+
* absent, never `undefined is not a function`.
|
|
114
|
+
*/
|
|
115
|
+
declare function readDoPitrBookmark(storage: DoPitrStorage, time?: number | string | Date): Promise<DoPitrBookmarkRead>;
|
|
116
|
+
/**
|
|
117
|
+
* Arm a PITR restore. Resolves the target (an explicit `bookmark` WINS over
|
|
118
|
+
* `time`), arms it via `onNextSessionRestoreBookmark`, and returns the undo
|
|
119
|
+
* bookmark the DO reports for the pre-restore state. Does NOT abort — the caller
|
|
120
|
+
* decides whether to restart now. Throws {@link DoPitrUnavailableError} when the
|
|
121
|
+
* arming API (or the by-time resolver a `time` target needs) is absent.
|
|
122
|
+
*/
|
|
123
|
+
declare function armDoPitr(storage: DoPitrStorage, opts: DoPitrArmOptions): Promise<DoPitrArmResult>;
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/nonce/nonce.durable-object.d.ts
|
|
126
|
+
/**
|
|
127
|
+
* SQLite Durable Object that atomically consumes nonces.
|
|
128
|
+
*
|
|
129
|
+
* Export this class from the Worker entry and register it through a Wrangler
|
|
130
|
+
* `new_sqlite_classes` migration. `INSERT ... ON CONFLICT DO NOTHING RETURNING`
|
|
131
|
+
* is the single-use decision; all SQL runs synchronously before the RPC method
|
|
132
|
+
* yields, and the nonce primary key is the final concurrency boundary.
|
|
133
|
+
*/
|
|
134
|
+
declare class VelaNonceDurableObject extends DurableObject<Record<string, unknown>> {
|
|
135
|
+
private sql?;
|
|
136
|
+
constructor(ctx: DurableObjectState, env: Record<string, unknown>);
|
|
137
|
+
claim(nonce: string, expEpochSeconds: number): Promise<boolean>;
|
|
138
|
+
}
|
|
139
|
+
//#endregion
|
|
140
|
+
export { DoPitrId as a, DoPitrUnavailableError as c, isDoPitrUnavailable as d, readDoPitrBookmark as f, DoPitrBookmarkRead as i, VelaDoPitrRpc as l, DoPitrArmOptions as n, DoPitrNamespace as o, CloudflareRoot as p, DoPitrArmResult as r, DoPitrStorage as s, VelaNonceDurableObject as t, armDoPitr as u };
|
|
141
|
+
//# sourceMappingURL=nonce.durable-object-Df3_42Sy.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,73 +1,95 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@velajs/cloudflare",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Cloudflare Workers integration for Vela framework",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "./dist/index.js",
|
|
7
|
-
"types": "./dist/index.d.ts",
|
|
8
|
-
"exports": {
|
|
9
|
-
".": {
|
|
10
|
-
"types": "./dist/index.d.ts",
|
|
11
|
-
"import": "./dist/index.js"
|
|
12
|
-
}
|
|
13
|
-
},
|
|
14
|
-
"files": [
|
|
15
|
-
"dist",
|
|
16
|
-
"README.md",
|
|
17
|
-
"LICENSE",
|
|
18
|
-
"CHANGELOG.md"
|
|
19
|
-
],
|
|
20
|
-
"sideEffects": false,
|
|
21
5
|
"keywords": [
|
|
22
|
-
"vela",
|
|
23
6
|
"cloudflare",
|
|
24
7
|
"cloudflare-workers",
|
|
25
|
-
"kv",
|
|
26
8
|
"d1",
|
|
27
|
-
"
|
|
28
|
-
"queues",
|
|
9
|
+
"decorators",
|
|
29
10
|
"edge",
|
|
30
11
|
"framework",
|
|
31
|
-
"
|
|
12
|
+
"kv",
|
|
13
|
+
"queues",
|
|
14
|
+
"r2",
|
|
15
|
+
"vela"
|
|
32
16
|
],
|
|
33
|
-
"
|
|
17
|
+
"homepage": "https://github.com/velajs/vela/tree/main/cloudflare#readme",
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/velajs/vela/issues"
|
|
20
|
+
},
|
|
34
21
|
"license": "MIT",
|
|
22
|
+
"author": "ksh",
|
|
35
23
|
"repository": {
|
|
36
24
|
"type": "git",
|
|
37
|
-
"url": "git+https://github.com/velajs/
|
|
25
|
+
"url": "git+https://github.com/velajs/vela.git",
|
|
26
|
+
"directory": "cloudflare"
|
|
38
27
|
},
|
|
39
|
-
"
|
|
40
|
-
|
|
41
|
-
"
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"README.md",
|
|
31
|
+
"LICENSE",
|
|
32
|
+
"CHANGELOG.md"
|
|
33
|
+
],
|
|
34
|
+
"type": "module",
|
|
35
|
+
"sideEffects": false,
|
|
36
|
+
"main": "./dist/index.js",
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"exports": {
|
|
39
|
+
".": {
|
|
40
|
+
"types": "./dist/index.d.ts",
|
|
41
|
+
"import": "./dist/index.js"
|
|
42
|
+
},
|
|
43
|
+
"./durable-objects": {
|
|
44
|
+
"types": "./dist/durable-objects.d.ts",
|
|
45
|
+
"import": "./dist/durable-objects.js"
|
|
46
|
+
}
|
|
42
47
|
},
|
|
43
|
-
"
|
|
44
|
-
"
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
50
|
+
"@changesets/cli": "2.31.0",
|
|
51
|
+
"@cloudflare/vitest-plugin": "1.1.13",
|
|
52
|
+
"@cloudflare/workers-types": "5.20260920.1",
|
|
53
|
+
"@swc/core": "1.15.43",
|
|
54
|
+
"hono": "4.13.8",
|
|
55
|
+
"oxfmt": "0.58.0",
|
|
56
|
+
"oxlint": "1.73.0",
|
|
57
|
+
"publint": "0.3.21",
|
|
58
|
+
"tsdown": "0.23.0",
|
|
59
|
+
"typescript": "7.0.2",
|
|
60
|
+
"unplugin-swc": "1.5.9",
|
|
61
|
+
"vitest": "4.1.10",
|
|
62
|
+
"zod": "^3.25.76",
|
|
63
|
+
"@velajs/feature-flags": "2.0.0",
|
|
64
|
+
"@velajs/vela": "2.0.0"
|
|
45
65
|
},
|
|
46
66
|
"peerDependencies": {
|
|
47
67
|
"@cloudflare/workers-types": ">=4",
|
|
48
|
-
"
|
|
49
|
-
"@velajs/
|
|
50
|
-
"
|
|
68
|
+
"hono": ">=4",
|
|
69
|
+
"@velajs/feature-flags": "^2.0.0",
|
|
70
|
+
"@velajs/vela": "^2.0.0"
|
|
51
71
|
},
|
|
52
72
|
"peerDependenciesMeta": {
|
|
53
73
|
"@velajs/feature-flags": {
|
|
54
74
|
"optional": true
|
|
55
75
|
}
|
|
56
76
|
},
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
"
|
|
62
|
-
"@velajs/vela": "^1.17.0",
|
|
63
|
-
"hono": "^4.12.27",
|
|
64
|
-
"typescript": "^6.0.3",
|
|
65
|
-
"unplugin-swc": "^1.5.9",
|
|
66
|
-
"vitest": "^4.1.9"
|
|
77
|
+
"engines": {
|
|
78
|
+
"node": ">=24"
|
|
79
|
+
},
|
|
80
|
+
"publishConfig": {
|
|
81
|
+
"access": "public"
|
|
67
82
|
},
|
|
68
83
|
"scripts": {
|
|
69
|
-
"build": "
|
|
84
|
+
"build": "tsdown",
|
|
70
85
|
"test": "vitest run",
|
|
71
|
-
"
|
|
86
|
+
"test:workers": "vitest run --config vitest.config.workers.ts",
|
|
87
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
|
|
88
|
+
"lint": "oxlint .",
|
|
89
|
+
"format": "oxfmt .",
|
|
90
|
+
"format:check": "oxfmt --check .",
|
|
91
|
+
"publint": "publint",
|
|
92
|
+
"attw": "attw --pack . --profile esm-only",
|
|
93
|
+
"verify": "pnpm lint && pnpm format:check && pnpm build && pnpm typecheck && pnpm test && pnpm test:workers && pnpm publint && pnpm attw"
|
|
72
94
|
}
|
|
73
95
|
}
|
package/dist/binding-ref.d.ts
DELETED
package/dist/binding-ref.js
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
// Mutable holder for a Cloudflare binding value. Created by each module's
|
|
2
|
-
// forRoot() and populated by createCloudflareApp's one-time middleware on
|
|
3
|
-
// the first request. Services access the binding lazily via .value.
|
|
4
|
-
export class BindingRef {
|
|
5
|
-
bindingName;
|
|
6
|
-
_value;
|
|
7
|
-
constructor(bindingName){
|
|
8
|
-
this.bindingName = bindingName;
|
|
9
|
-
}
|
|
10
|
-
get value() {
|
|
11
|
-
if (this._value === undefined) {
|
|
12
|
-
throw new Error(`Cloudflare binding '${this.bindingName}' not initialized. ` + `Ensure createCloudflareApp() is used and a request has been made.`);
|
|
13
|
-
}
|
|
14
|
-
return this._value;
|
|
15
|
-
}
|
|
16
|
-
/** @internal — called by createCloudflareApp middleware */ _initialize(value) {
|
|
17
|
-
this._value = value;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
import type { Hono } from 'hono';
|
|
2
|
-
import { type VelaApplication } from '@velajs/vela';
|
|
3
|
-
import { type WsGatewayRoute } from './websocket/websocket-routing';
|
|
4
|
-
import type { CloudflareEnv } from './types';
|
|
5
|
-
/**
|
|
6
|
-
* Options accepted by {@link CloudflareApplication.mountOpenApi}.
|
|
7
|
-
*
|
|
8
|
-
* Re-exposes vela's `MountOpenApiOptions` type — derived structurally from
|
|
9
|
-
* the underlying `VelaApplication.mountOpenApi` signature so consumers don't
|
|
10
|
-
* have to reach into vela's internal subpaths to type the argument.
|
|
11
|
-
*/
|
|
12
|
-
export type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
|
|
13
|
-
/**
|
|
14
|
-
* Wraps VelaApplication with Cloudflare-specific handlers:
|
|
15
|
-
* - `fetch` — HTTP request handler (from Hono)
|
|
16
|
-
* - `scheduled` — Cron trigger handler (matches `@Scheduled()` decorators
|
|
17
|
-
* AND vela's own `@Cron()` jobs)
|
|
18
|
-
* - `queue` — Queue consumer handler (matches `@QueueConsumer()` decorators)
|
|
19
|
-
* - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on
|
|
20
|
-
* the underlying Hono app
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
* ```ts
|
|
24
|
-
* const app = await createCloudflareApp(AppModule);
|
|
25
|
-
* export default {
|
|
26
|
-
* fetch: app.fetch,
|
|
27
|
-
* scheduled: app.scheduled.bind(app),
|
|
28
|
-
* queue: app.queue.bind(app),
|
|
29
|
-
* };
|
|
30
|
-
* ```
|
|
31
|
-
*
|
|
32
|
-
* @example
|
|
33
|
-
* ```ts
|
|
34
|
-
* // Serve OpenAPI docs alongside your routes
|
|
35
|
-
* const app = await createCloudflareApp(AppModule);
|
|
36
|
-
* const document = createOpenApiDocument(AppModule);
|
|
37
|
-
* app.mountOpenApi({ document, ui: 'scalar' });
|
|
38
|
-
* // GET /openapi.json -> JSON document
|
|
39
|
-
* // GET /scalar -> Scalar UI (loads from CDN)
|
|
40
|
-
* ```
|
|
41
|
-
*/
|
|
42
|
-
export declare class CloudflareApplication {
|
|
43
|
-
private app;
|
|
44
|
-
private wsGatewayRoutes;
|
|
45
|
-
constructor(app: VelaApplication);
|
|
46
|
-
get fetch(): Hono['fetch'];
|
|
47
|
-
getHonoApp(): Hono;
|
|
48
|
-
/**
|
|
49
|
-
* Resolve a provider from the application's DI container (delegates to
|
|
50
|
-
* `VelaApplication.get`). Handy for grabbing a service — e.g. an auth service —
|
|
51
|
-
* to use inside `createCloudflareApp({ middleware: [...] })` request middleware,
|
|
52
|
-
* which runs outside the DI request pipeline.
|
|
53
|
-
*
|
|
54
|
-
* @example
|
|
55
|
-
* ```ts
|
|
56
|
-
* const app = await createCloudflareApp(AppModule);
|
|
57
|
-
* const auth = app.get<BetterAuthService>(BetterAuthService);
|
|
58
|
-
* ```
|
|
59
|
-
*/
|
|
60
|
-
get<T>(token: Parameters<VelaApplication['get']>[0]): T;
|
|
61
|
-
/**
|
|
62
|
-
* Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the
|
|
63
|
-
* underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,
|
|
64
|
-
* so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when
|
|
65
|
-
* opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from
|
|
66
|
-
* a CDN at runtime, nothing is bundled server-side.
|
|
67
|
-
*
|
|
68
|
-
* @example
|
|
69
|
-
* ```ts
|
|
70
|
-
* import { createOpenApiDocument } from '@velajs/vela';
|
|
71
|
-
*
|
|
72
|
-
* const app = await createCloudflareApp(AppModule);
|
|
73
|
-
* const document = createOpenApiDocument(AppModule, {
|
|
74
|
-
* info: { title: 'My API', version: '1.0.0' },
|
|
75
|
-
* });
|
|
76
|
-
* app.mountOpenApi({ document, ui: 'scalar' });
|
|
77
|
-
* // GET /openapi.json -> { openapi: '3.1.0', ... }
|
|
78
|
-
* // GET /scalar -> Scalar UI HTML
|
|
79
|
-
* ```
|
|
80
|
-
*/
|
|
81
|
-
mountOpenApi(options: MountOpenApiOptions): this;
|
|
82
|
-
/**
|
|
83
|
-
* @internal — scans instances for `@WebSocketGateway({ path, binding })`
|
|
84
|
-
* upgrade routes. Queue/scheduled handlers are NOT scanned anymore: they
|
|
85
|
-
* come from `app.entrypoints` (`cf:queue` / `cf:scheduled` / `cf:vela-cron`
|
|
86
|
-
* kinds) at dispatch time.
|
|
87
|
-
*/
|
|
88
|
-
scanInstances(instances: unknown[]): void;
|
|
89
|
-
/** @internal — upgrade routes discovered from `@WebSocketGateway({ path, binding })`. */
|
|
90
|
-
getWsGatewayRoutes(): WsGatewayRoute[];
|
|
91
|
-
/**
|
|
92
|
-
* Handle Cloudflare scheduled (cron) events.
|
|
93
|
-
* Matches the event's cron expression to `@Scheduled()` and vela `@Cron()`
|
|
94
|
-
* handlers read from `app.entrypoints`; each handler runs inside a fresh
|
|
95
|
-
* request-scoped child (request-scoped providers rebuild per tick).
|
|
96
|
-
*/
|
|
97
|
-
scheduled(event: {
|
|
98
|
-
cron: string;
|
|
99
|
-
scheduledTime?: number;
|
|
100
|
-
}, env: CloudflareEnv, ctx: {
|
|
101
|
-
waitUntil: (promise: Promise<unknown>) => void;
|
|
102
|
-
}): Promise<void>;
|
|
103
|
-
/**
|
|
104
|
-
* Run one entrypoint handler inside a fresh request scope, through the
|
|
105
|
-
* shared guard → interceptor pipeline (components declared with
|
|
106
|
-
* `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or
|
|
107
|
-
* method). HTTP-global components deliberately do NOT apply — an HTTP auth
|
|
108
|
-
* guard has no business rejecting a queue batch. Unclaimed errors rethrow
|
|
109
|
-
* so the platform's retry semantics stay intact.
|
|
110
|
-
*/
|
|
111
|
-
private dispatchEntrypoint;
|
|
112
|
-
/**
|
|
113
|
-
* Handle Cloudflare Queue consumer events.
|
|
114
|
-
* Matches the batch queue name to `@QueueConsumer()` handlers read from
|
|
115
|
-
* `app.entrypoints`; each batch is processed inside a fresh request-scoped
|
|
116
|
-
* child (request-scoped providers rebuild per batch — no boot-time captives).
|
|
117
|
-
*/
|
|
118
|
-
queue(batch: {
|
|
119
|
-
queue: string;
|
|
120
|
-
messages: unknown[];
|
|
121
|
-
}, env: CloudflareEnv, ctx: {
|
|
122
|
-
waitUntil: (promise: Promise<unknown>) => void;
|
|
123
|
-
}): Promise<void>;
|
|
124
|
-
close(signal?: string): Promise<void>;
|
|
125
|
-
}
|