@velajs/cloudflare 1.30.0 → 1.32.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 (118) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/README.md +407 -77
  3. package/dist/bindings.js +93 -0
  4. package/dist/bindings.js.map +1 -0
  5. package/dist/cloudflare-application-CXDy9C1R.d.ts +199 -0
  6. package/dist/cloudflare-application.js +15 -34
  7. package/dist/cloudflare-application.js.map +1 -1
  8. package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
  9. package/dist/cloudflare-factory.js +227 -38
  10. package/dist/cloudflare-factory.js.map +1 -1
  11. package/dist/diagnostics.js +18 -0
  12. package/dist/diagnostics.js.map +1 -0
  13. package/dist/durable-object/boot.js +76 -0
  14. package/dist/durable-object/boot.js.map +1 -0
  15. package/dist/durable-object/host-dispatch.js +134 -0
  16. package/dist/durable-object/host-dispatch.js.map +1 -0
  17. package/dist/durable-object/host-methods.js +47 -0
  18. package/dist/durable-object/host-methods.js.map +1 -0
  19. package/dist/durable-object/tokens.js +17 -0
  20. package/dist/durable-object/tokens.js.map +1 -0
  21. package/dist/durable-object/vela-durable-object.js +121 -0
  22. package/dist/durable-object/vela-durable-object.js.map +1 -0
  23. package/dist/durable-objects.d.ts +136 -10
  24. package/dist/durable-objects.js +3 -1
  25. package/dist/email/email-dispatch.js +65 -0
  26. package/dist/email/email-dispatch.js.map +1 -0
  27. package/dist/email/on-email.js +57 -0
  28. package/dist/email/on-email.js.map +1 -0
  29. package/dist/email.d.ts +51 -0
  30. package/dist/email.js +3 -0
  31. package/dist/entrypoint/vela-entrypoint.js +160 -0
  32. package/dist/entrypoint/vela-entrypoint.js.map +1 -0
  33. package/dist/entrypoints.d.ts +93 -0
  34. package/dist/entrypoints.js +2 -0
  35. package/dist/host/host-invoker.js +276 -0
  36. package/dist/host/host-invoker.js.map +1 -0
  37. package/dist/host/host-members.js +73 -0
  38. package/dist/host/host-members.js.map +1 -0
  39. package/dist/host-members-DECj_4yz.d.ts +13 -0
  40. package/dist/index.d.ts +211 -445
  41. package/dist/index.js +8 -13
  42. package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
  43. package/dist/platform.js +22 -0
  44. package/dist/platform.js.map +1 -0
  45. package/dist/queue/cloudflare-queues.js +7 -7
  46. package/dist/queue/cloudflare-queues.js.map +1 -1
  47. package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
  48. package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
  49. package/dist/root-module.js +19 -0
  50. package/dist/root-module.js.map +1 -0
  51. package/dist/rpc/entrypoint-error.js +145 -0
  52. package/dist/rpc/entrypoint-error.js.map +1 -0
  53. package/dist/schedule-diagnostics.js +8 -15
  54. package/dist/schedule-diagnostics.js.map +1 -1
  55. package/dist/services/kv-cache.store.js +33 -7
  56. package/dist/services/kv-cache.store.js.map +1 -1
  57. package/dist/storage/r2-storage.js +30 -0
  58. package/dist/storage/r2-storage.js.map +1 -0
  59. package/dist/storage.d.ts +28 -0
  60. package/dist/storage.js +2 -0
  61. package/dist/tail/on-tail.js +46 -0
  62. package/dist/tail/on-tail.js.map +1 -0
  63. package/dist/tail/tail-dispatch.js +67 -0
  64. package/dist/tail/tail-dispatch.js.map +1 -0
  65. package/dist/tail.d.ts +39 -0
  66. package/dist/tail.js +2 -0
  67. package/dist/testing.d.ts +148 -0
  68. package/dist/testing.js +188 -0
  69. package/dist/testing.js.map +1 -0
  70. package/dist/websocket/binding-gateways.js +33 -0
  71. package/dist/websocket/binding-gateways.js.map +1 -0
  72. package/dist/websocket/cf-room-registry.js +3 -1
  73. package/dist/websocket/cf-room-registry.js.map +1 -1
  74. package/dist/websocket/do-bootstrap.js +64 -40
  75. package/dist/websocket/do-bootstrap.js.map +1 -1
  76. package/dist/websocket/do-live.js +49 -90
  77. package/dist/websocket/do-live.js.map +1 -1
  78. package/dist/websocket/do-state.js.map +1 -1
  79. package/dist/websocket/live-driver.js +149 -0
  80. package/dist/websocket/live-driver.js.map +1 -0
  81. package/dist/websocket/room-id.js +11 -1
  82. package/dist/websocket/room-id.js.map +1 -1
  83. package/dist/websocket/websocket.durable-object.js +51 -18
  84. package/dist/websocket/websocket.durable-object.js.map +1 -1
  85. package/dist/websocket/worker-transport.js +80 -0
  86. package/dist/websocket/worker-transport.js.map +1 -0
  87. package/dist/worker-events.js +49 -0
  88. package/dist/worker-events.js.map +1 -0
  89. package/dist/workflow/vela-workflow.js +104 -0
  90. package/dist/workflow/vela-workflow.js.map +1 -0
  91. package/dist/workflows.d.ts +82 -0
  92. package/dist/workflows.js +2 -0
  93. package/package.json +39 -6
  94. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
  95. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
  96. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
  97. package/dist/storage/r2-storage.driver.js +0 -67
  98. package/dist/storage/r2-storage.driver.js.map +0 -1
  99. package/dist/storage/storage-key-claim.js +0 -74
  100. package/dist/storage/storage-key-claim.js.map +0 -1
  101. package/dist/storage/storage-manager.service.js +0 -38
  102. package/dist/storage/storage-manager.service.js.map +0 -1
  103. package/dist/storage/storage.controller.js +0 -64
  104. package/dist/storage/storage.controller.js.map +0 -1
  105. package/dist/storage/storage.module.js +0 -25
  106. package/dist/storage/storage.module.js.map +0 -1
  107. package/dist/storage/storage.service.js +0 -64
  108. package/dist/storage/storage.service.js.map +0 -1
  109. package/dist/storage/storage.tokens.js +0 -7
  110. package/dist/storage/storage.tokens.js.map +0 -1
  111. package/dist/websocket/broadcast.js +0 -32
  112. package/dist/websocket/broadcast.js.map +0 -1
  113. package/dist/websocket/cloudflare-websocket.module.js +0 -25
  114. package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
  115. package/dist/websocket/websocket-routing.js +0 -133
  116. package/dist/websocket/websocket-routing.js.map +0 -1
  117. package/dist/websocket/ws-server-holder.js +0 -38
  118. package/dist/websocket/ws-server-holder.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"websocket.durable-object.js","names":[],"sources":["../../src/websocket/websocket.durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport type { BroadcastCommand } from '@velajs/vela/websocket';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveEngine,\n LiveInspection,\n} from '@velajs/vela/live';\nimport { buildDoRuntime } from './do-bootstrap';\nimport { DoWebSocketHost, type WsConnectionPrincipal } from './do-websocket-host';\nimport { armDoPitr, readDoPitrBookmark } from './do-pitr';\nimport type { CloudflareRoot } from '../root-module';\nimport type {\n DoPitrArmOptions,\n DoPitrArmResult,\n DoPitrBookmarkRead,\n VelaDoPitrRpc,\n} from './do-pitr';\n\nconst PING = '{\"event\":\"$ping\"}';\nconst PONG = '{\"event\":\"$pong\"}';\nconst MAX_IDENTITY_FIELD_BYTES = 2048;\nconst encoder = new TextEncoder();\n\nfunction isIdentityField(value: string | null): value is string {\n return (\n value !== null &&\n value.length > 0 &&\n encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES\n );\n}\n\n/**\n * Base class for the WebSocket Durable Object. The user exports a named subclass\n * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, or\n * from a `DynamicModule` declared at module scope:\n *\n * ```ts\n * export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}\n * ```\n *\n * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot\n * bridge DO hibernation) and forwards every event into the runtime-agnostic\n * `WsDispatcher` via {@link DoWebSocketHost}. The DO's `env` is the\n * application's ENV, as in the Worker.\n */\nexport function VelaWebSocketDurableObject(rootModule: CloudflareRoot): new (\n ctx: DurableObjectState,\n env: VelaEnv,\n) => DurableObject<VelaEnv> &\n VelaDoPitrRpc & {\n broadcast(cmd: BroadcastCommand): Promise<void>;\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n inspectLive(): Promise<LiveInspection>;\n } {\n return class VelaWsDurableObject extends DurableObject<VelaEnv> {\n private host!: DoWebSocketHost;\n private liveEngine?: LiveEngine;\n private readonly ready: Promise<void>;\n\n constructor(ctx: DurableObjectState, env: VelaEnv) {\n super(ctx, env);\n // Application-level ping/pong answered WITHOUT waking a hibernated DO.\n try {\n ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));\n } catch {\n // Older runtimes without auto-response — fine, protocol pings still work.\n }\n this.ready = ctx.blockConcurrencyWhile(async () => {\n // The root is static, so constructing another instance declares no new\n // classes in the isolate-global metadata registry.\n const runtime = await buildDoRuntime(rootModule, ctx, { env });\n this.host = new DoWebSocketHost(\n ctx,\n runtime.dispatcher,\n runtime.registry,\n runtime.gatewayPaths,\n );\n this.liveEngine = runtime.live;\n });\n }\n\n /** Intra-worker RPC only; HTTP fetch never exposes this admin snapshot. */\n async inspectLive(): Promise<LiveInspection> {\n await this.ready;\n return this.liveEngine?.inspect() ?? { subscriptions: [], rooms: [] };\n }\n\n override async fetch(request: Request): Promise<Response> {\n await this.ready;\n if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {\n return new Response('Expected WebSocket upgrade', { status: 426 });\n }\n\n const url = new URL(request.url);\n // Headers are primary (carry auth + multi-gateway routing); fall back to the\n // DO's own name (set via idFromName(room)) and the single gateway path so a\n // plain `stub.fetch(request)` forward still works.\n const roomId = request.headers.get('x-vela-room') ?? this.ctx.id.name ?? url.pathname;\n const path = request.headers.get('x-vela-path') ?? this.host.defaultPath() ?? url.pathname;\n const userId = request.headers.get('x-vela-user') || undefined;\n const rawExpiresAtMs = request.headers.get('x-vela-expires-at-ms');\n const parsedExpiresAtMs = rawExpiresAtMs === null ? undefined : Number(rawExpiresAtMs);\n if (\n parsedExpiresAtMs !== undefined &&\n (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)\n ) {\n return new Response('Invalid WebSocket identity expiry', { status: 403 });\n }\n\n const issuer = request.headers.get('x-vela-issuer');\n const subject = request.headers.get('x-vela-subject');\n const principalType = request.headers.get('x-vela-principal-type');\n const tenantId = request.headers.get('x-vela-tenant');\n const hasPrincipalHeader =\n issuer !== null || subject !== null || principalType !== null || tenantId !== null;\n let principal: WsConnectionPrincipal | undefined;\n if (hasPrincipalHeader) {\n if (\n !isIdentityField(issuer) ||\n !isIdentityField(subject) ||\n (principalType !== 'user' && principalType !== 'service') ||\n !isIdentityField(tenantId) ||\n parsedExpiresAtMs === undefined ||\n (userId !== undefined && userId !== subject)\n ) {\n return new Response('Invalid WebSocket principal', { status: 403 });\n }\n principal = { issuer, subject, principalType, tenantId };\n } else if (parsedExpiresAtMs !== undefined) {\n return new Response('WebSocket identity tuple is missing', { status: 403 });\n }\n\n if (parsedExpiresAtMs !== undefined && parsedExpiresAtMs <= Date.now()) {\n return new Response('WebSocket identity expired', { status: 403 });\n }\n\n const { 0: client, 1: server } = new WebSocketPair();\n const accepted = await this.host.accept(\n server,\n path,\n roomId,\n userId,\n parsedExpiresAtMs,\n principal,\n );\n if (!accepted) return new Response('WebSocket connection rejected', { status: 403 });\n return new Response(null, { status: 101, webSocket: client });\n }\n\n override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {\n await this.ready;\n await this.host.onMessage(ws, message);\n }\n\n override async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {\n await this.ready;\n await this.host.onClose(ws, code, reason);\n }\n\n override async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n await this.ready;\n await this.host.onError(ws, error);\n }\n\n /** DO RPC — server-initiated broadcast forwarded from a Worker (see `broadcastToRoom`). */\n async broadcast(cmd: BroadcastCommand): Promise<void> {\n await this.ready;\n await this.host.broadcast(cmd);\n }\n\n /**\n * DO RPC — live tag invalidation forwarded from a Worker (durableObjectLive /\n * liveInvalidateToRoom). Appends to THIS log scope's cursor log and returns\n * the commit stamp (what `Vela-Commit-Cursor` carries); the subscription\n * refreshes fan out asynchronously.\n */\n async invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined> {\n await this.ready;\n return this.liveEngine?.applyInvalidation(cmd);\n }\n\n // -- Durable Object PITR (point-in-time recovery) RPC ---------------------\n //\n // GUARD / reachability: these are admin-privileged operations (a restore can\n // roll the DO's SQLite state back up to 30 days and, with `restart`, abort\n // the DO to apply it now). They are safe to expose here because a Durable\n // Object's RPC methods are NOT network-reachable: a `DurableObjectStub` is\n // obtainable ONLY from a Worker that binds this DO namespace, and RPC calls\n // travel Cloudflare's internal capability channel — never the public\n // internet. A WebSocket/HTTP client reaches only `fetch()` above, never these\n // methods. The security boundary is therefore the WORKER-SIDE studio admin\n // gate that fronts the `CloudflareDoTimeTravelPort` (master admin token + the\n // 428 confirm challenge) — the identical trust model as `broadcast()` /\n // `invalidate()` on this same DO. See `do-pitr.ts` for the storage wrappers.\n\n /** DO RPC — the current PITR bookmark (typed-unavailable on a non-SQLite DO). */\n async pitrCurrentBookmark(): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage);\n }\n\n /** DO RPC — the PITR bookmark closest to `time` (+ the current bookmark). */\n async pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage, time);\n }\n\n /**\n * DO RPC — arm a PITR restore and return the undo bookmark. When `restart` is\n * requested, `ctx.abort()` is called AFTER the undo bookmark is computed so\n * the recovery applies on the immediately-following session; otherwise the\n * restore applies on the next natural restart (`restarted: false`).\n */\n async pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult> {\n await this.ready;\n const result = await armDoPitr(this.ctx.storage, opts);\n if (opts.restart === true) this.ctx.abort('vela PITR restore');\n return result;\n }\n };\n}\n"],"mappings":";;;;;AAoBA,MAAM,OAAO;AACb,MAAM,OAAO;AACb,MAAM,2BAA2B;AACjC,MAAM,UAAU,IAA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AO;EACvC;EAEA,MAAe,eAAe,IAAe,MAAc,QAA+B;GACxF,MAAM,KAAK;GACX,MAAM,KAAK,KAAK,QAAQ,IAAI,MAAM,MAAM;EAC1C;EAEA,MAAe,eAAe,IAAe,OAA+B;GAC1E,MAAM,KAAK;GACX,MAAM,KAAK,KAAK,QAAQ,IAAI,KAAK;EACnC;;EAGA,MAAM,UAAU,KAAsC;GACpD,MAAM,KAAK;GACX,MAAM,KAAK,KAAK,UAAU,GAAG;EAC/B;;;;;;;EAQA,MAAM,WAAW,KAA4D;GAC3E,MAAM,KAAK;GACX,OAAO,KAAK,YAAY,kBAAkB,GAAG;EAC/C;;EAiBA,MAAM,sBAAmD;GACvD,MAAM,KAAK;GACX,OAAO,mBAAmB,KAAK,IAAI,OAAO;EAC5C;;EAGA,MAAM,oBAAoB,MAAoD;GAC5E,MAAM,KAAK;GACX,OAAO,mBAAmB,KAAK,IAAI,SAAS,IAAI;EAClD;;;;;;;EAQA,MAAM,eAAe,MAAkD;GACrE,MAAM,KAAK;GACX,MAAM,SAAS,MAAM,UAAU,KAAK,IAAI,SAAS,IAAI;GACrD,IAAI,KAAK,YAAY,MAAM,KAAK,IAAI,MAAM,mBAAmB;GAC7D,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"websocket.durable-object.js","names":["FORWARDED"],"sources":["../../src/websocket/websocket.durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport type { BroadcastCommand } from '@velajs/vela/websocket';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveEngine,\n LiveInspection,\n} from '@velajs/vela/live';\nimport { buildDoRuntime } from './do-bootstrap';\nimport { DoWebSocketHost, type WsConnectionPrincipal } from './do-websocket-host';\nimport { armDoPitr, readDoPitrBookmark } from './do-pitr';\nimport { FORWARDED_UPGRADE_HEADERS as FORWARDED } from './worker-transport';\nimport {\n CLOUDFLARE_DURABLE_OBJECT,\n registerDurableObject,\n type CloudflareDurableObjectDescriptor,\n} from '../cloudflare-factory';\nimport {\n durableObjectDefinition,\n startDurableObject,\n type DurableObjectRoot,\n} from '../durable-object/boot';\nimport type {\n DoPitrArmOptions,\n DoPitrArmResult,\n DoPitrBookmarkRead,\n VelaDoPitrRpc,\n} from './do-pitr';\n\nconst PING = '{\"event\":\"$ping\"}';\nconst PONG = '{\"event\":\"$pong\"}';\nconst MAX_IDENTITY_FIELD_BYTES = 2048;\nconst encoder = new TextEncoder();\n\nfunction isIdentityField(value: string | null): value is string {\n return (\n value !== null &&\n value.length > 0 &&\n encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES\n );\n}\n\n/** The RPC methods a WebSocket Durable Object exposes to the Worker and other objects. */\nconst WEBSOCKET_RPC_METHODS = [\n 'broadcast',\n 'invalidate',\n 'inspectLive',\n 'pitrCurrentBookmark',\n 'pitrBookmarkForTime',\n 'pitrArmRestore',\n] as const;\n\n/**\n * Base class for the WebSocket Durable Object. The user exports a named subclass\n * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, a\n * `DynamicModule` declared at module scope, or the app from\n * `defineCloudflareApp`, whose runtime adapters the object shares:\n *\n * ```ts\n * const app = defineCloudflareApp(AppModule);\n * export class ChatRoom extends VelaWebSocketDurableObject(app) {}\n * export default app.worker;\n * ```\n *\n * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot\n * bridge DO hibernation) and forwards every event into the runtime-agnostic\n * `WsDispatcher` via {@link DoWebSocketHost}. The application imports the core\n * `WebSocketModule.forRoot()`: this object registers the platform that binds\n * its server to these sockets, delivers live invalidations locally and keeps\n * the live cursor log in its SQLite storage. The DO's `env` is the\n * application's ENV, as in the Worker, and its application context injects\n * `DO_STATE`, `DO_STORAGE` and `DO_ID` like every Vela Durable Object's.\n */\nexport function VelaWebSocketDurableObject(root: DurableObjectRoot): new (\n ctx: DurableObjectState,\n env: VelaEnv,\n) => DurableObject<VelaEnv> &\n VelaDoPitrRpc & {\n broadcast(cmd: BroadcastCommand): Promise<void>;\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n inspectLive(): Promise<LiveInspection>;\n } {\n const definition = durableObjectDefinition(root);\n class VelaWsDurableObject extends DurableObject<VelaEnv> {\n private host!: DoWebSocketHost;\n private liveEngine?: LiveEngine;\n private readonly ready: Promise<void>;\n\n constructor(ctx: DurableObjectState, env: VelaEnv) {\n super(ctx, env);\n // Application-level ping/pong answered WITHOUT waking a hibernated DO.\n try {\n ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));\n } catch {\n // Older runtimes without auto-response — fine, protocol pings still work.\n }\n this.ready = startDurableObject(ctx, 'WebSocket', async () => {\n // The root is static, so constructing another instance declares no new\n // classes in the isolate-global metadata registry.\n const runtime = await buildDoRuntime(definition.rootModule, ctx, {\n env,\n adapters: definition.adapters,\n state: ctx,\n });\n this.host = new DoWebSocketHost(\n ctx,\n runtime.dispatcher,\n runtime.registry,\n runtime.gatewayPaths,\n );\n this.liveEngine = runtime.live;\n });\n }\n\n /** Intra-worker RPC only; HTTP fetch never exposes this admin snapshot. */\n async inspectLive(): Promise<LiveInspection> {\n await this.ready;\n return this.liveEngine?.inspect() ?? { subscriptions: [], rooms: [] };\n }\n\n override async fetch(request: Request): Promise<Response> {\n await this.ready;\n if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {\n return new Response('Expected WebSocket upgrade', { status: 426 });\n }\n\n const url = new URL(request.url);\n // Headers are primary (carry auth + multi-gateway routing); fall back to the\n // DO's own name (set via idFromName(room)) and the single gateway path so a\n // plain `stub.fetch(request)` forward still works.\n const roomId = request.headers.get(FORWARDED.room) ?? this.ctx.id.name ?? url.pathname;\n const path = request.headers.get(FORWARDED.path) ?? this.host.defaultPath() ?? url.pathname;\n const userId = request.headers.get(FORWARDED.user) || undefined;\n const rawExpiresAtMs = request.headers.get(FORWARDED.expiresAtMs);\n const parsedExpiresAtMs = rawExpiresAtMs === null ? undefined : Number(rawExpiresAtMs);\n if (\n parsedExpiresAtMs !== undefined &&\n (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)\n ) {\n return new Response('Invalid WebSocket identity expiry', { status: 403 });\n }\n\n const issuer = request.headers.get(FORWARDED.issuer);\n const subject = request.headers.get(FORWARDED.subject);\n const principalType = request.headers.get(FORWARDED.principalType);\n const tenantId = request.headers.get(FORWARDED.tenant);\n const hasPrincipalHeader =\n issuer !== null || subject !== null || principalType !== null || tenantId !== null;\n let principal: WsConnectionPrincipal | undefined;\n if (hasPrincipalHeader) {\n if (\n !isIdentityField(issuer) ||\n !isIdentityField(subject) ||\n (principalType !== 'user' && principalType !== 'service') ||\n !isIdentityField(tenantId) ||\n parsedExpiresAtMs === undefined ||\n (userId !== undefined && userId !== subject)\n ) {\n return new Response('Invalid WebSocket principal', { status: 403 });\n }\n principal = { issuer, subject, principalType, tenantId };\n } else if (parsedExpiresAtMs !== undefined) {\n return new Response('WebSocket identity tuple is missing', { status: 403 });\n }\n\n if (parsedExpiresAtMs !== undefined && parsedExpiresAtMs <= Date.now()) {\n return new Response('WebSocket identity expired', { status: 403 });\n }\n\n const { 0: client, 1: server } = new WebSocketPair();\n const accepted = await this.host.accept(\n server,\n path,\n roomId,\n userId,\n parsedExpiresAtMs,\n principal,\n );\n if (!accepted) return new Response('WebSocket connection rejected', { status: 403 });\n return new Response(null, { status: 101, webSocket: client });\n }\n\n override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {\n await this.ready;\n await this.host.onMessage(ws, message);\n }\n\n override async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {\n await this.ready;\n await this.host.onClose(ws, code, reason);\n }\n\n override async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n await this.ready;\n await this.host.onError(ws, error);\n }\n\n /** DO RPC — a `Gateways` push forwarded from the Worker or another room's object. */\n async broadcast(cmd: BroadcastCommand): Promise<void> {\n await this.ready;\n await this.host.broadcast(cmd);\n }\n\n /**\n * DO RPC — live tag invalidation forwarded from a Worker (durableObjectLive /\n * liveInvalidateToRoom). Appends to THIS log scope's cursor log and returns\n * the commit stamp (what `Vela-Commit-Cursor` carries); the subscription\n * refreshes fan out asynchronously.\n */\n async invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined> {\n await this.ready;\n return this.liveEngine?.applyInvalidation(cmd);\n }\n\n // -- Durable Object PITR (point-in-time recovery) RPC ---------------------\n //\n // GUARD / reachability: these are admin-privileged operations (a restore can\n // roll the DO's SQLite state back up to 30 days and, with `restart`, abort\n // the DO to apply it now). They are safe to expose here because a Durable\n // Object's RPC methods are NOT network-reachable: a `DurableObjectStub` is\n // obtainable ONLY from a Worker that binds this DO namespace, and RPC calls\n // travel Cloudflare's internal capability channel — never the public\n // internet. A WebSocket/HTTP client reaches only `fetch()` above, never these\n // methods. The security boundary is therefore the WORKER-SIDE studio admin\n // gate that fronts the `CloudflareDoTimeTravelPort` (master admin token + the\n // 428 confirm challenge) — the identical trust model as `broadcast()` /\n // `invalidate()` on this same DO. See `do-pitr.ts` for the storage wrappers.\n\n /** DO RPC — the current PITR bookmark (typed-unavailable on a non-SQLite DO). */\n async pitrCurrentBookmark(): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage);\n }\n\n /** DO RPC — the PITR bookmark closest to `time` (+ the current bookmark). */\n async pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage, time);\n }\n\n /**\n * DO RPC — arm a PITR restore and return the undo bookmark. When `restart` is\n * requested, `ctx.abort()` is called AFTER the undo bookmark is computed so\n * the recovery applies on the immediately-following session; otherwise the\n * restore applies on the next natural restart (`restarted: false`).\n */\n async pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult> {\n await this.ready;\n const result = await armDoPitr(this.ctx.storage, opts);\n if (opts.restart === true) this.ctx.abort('vela PITR restore');\n return result;\n }\n }\n\n const descriptor: CloudflareDurableObjectDescriptor = {\n kind: 'websocket',\n rootModule: definition.rootModule,\n methods: WEBSOCKET_RPC_METHODS,\n durableObject: VelaWsDurableObject,\n };\n // Static and non-enumerable: tools read it from the exported class.\n Object.defineProperty(VelaWsDurableObject, CLOUDFLARE_DURABLE_OBJECT, { value: descriptor });\n if (definition.app) registerDurableObject(definition.app, descriptor);\n return VelaWsDurableObject;\n}\n"],"mappings":";;;;;;;;AA8BA,MAAM,OAAO;AACb,MAAM,OAAO;AACb,MAAM,2BAA2B;AACjC,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAS,gBAAgB,OAAuC;CAC9D,OACE,UAAU,QACV,MAAM,SAAS,KACf,QAAQ,OAAO,KAAK,CAAC,CAAC,cAAc;AAExC;;AAGA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,2BAA2B,MAQvC;CACF,MAAM,aAAa,wBAAwB,IAAI;CAC/C,MAAM,4BAA4B,cAAuB;EACvD;EACA;EACA;EAEA,YAAY,KAAyB,KAAc;GACjD,MAAM,KAAK,GAAG;GAEd,IAAI;IACF,IAAI,yBAAyB,IAAI,6BAA6B,MAAM,IAAI,CAAC;GAC3E,QAAQ,CAER;GACA,KAAK,QAAQ,mBAAmB,KAAK,aAAa,YAAY;IAG5D,MAAM,UAAU,MAAM,eAAe,WAAW,YAAY,KAAK;KAC/D;KACA,UAAU,WAAW;KACrB,OAAO;IACT,CAAC;IACD,KAAK,OAAO,IAAI,gBACd,KACA,QAAQ,YACR,QAAQ,UACR,QAAQ,YACV;IACA,KAAK,aAAa,QAAQ;GAC5B,CAAC;EACH;;EAGA,MAAM,cAAuC;GAC3C,MAAM,KAAK;GACX,OAAO,KAAK,YAAY,QAAQ,KAAK;IAAE,eAAe,CAAC;IAAG,OAAO,CAAC;GAAE;EACtE;EAEA,MAAe,MAAM,SAAqC;GACxD,MAAM,KAAK;GACX,IAAI,QAAQ,QAAQ,IAAI,SAAS,CA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Y,MAAM,KAAK,IAAI,MAAM,mBAAmB;GAC7D,OAAO;EACT;CACF;CAEA,MAAM,aAAgD;EACpD,MAAM;EACN,YAAY,WAAW;EACvB,SAAS;EACT,eAAe;CACjB;CAEA,OAAO,eAAe,qBAAqB,2BAA2B,EAAE,OAAO,WAAW,CAAC;CAC3F,IAAI,WAAW,KAAK,sBAAsB,WAAW,KAAK,UAAU;CACpE,OAAO;AACT"}
@@ -0,0 +1,80 @@
1
+ import { durableObjectRoomName } from "./room-id.js";
2
+ import { DURABLE_OBJECT_NAMESPACE } from "../bindings.js";
3
+ import { resolveBinding } from "@velajs/vela/module-kit";
4
+ //#region src/websocket/worker-transport.ts
5
+ /**
6
+ * Headers that carry trusted upgrade values from the Worker's upgrade route to
7
+ * the room's Durable Object. The route removes client copies before any
8
+ * application hook runs; the Durable Object reads only these.
9
+ */
10
+ const FORWARDED_UPGRADE_HEADERS = {
11
+ room: "x-vela-room",
12
+ path: "x-vela-path",
13
+ user: "x-vela-user",
14
+ issuer: "x-vela-issuer",
15
+ subject: "x-vela-subject",
16
+ principalType: "x-vela-principal-type",
17
+ tenant: "x-vela-tenant",
18
+ expiresAtMs: "x-vela-expires-at-ms"
19
+ };
20
+ const FORWARDING_HEADERS = [...Object.values(FORWARDED_UPGRADE_HEADERS), "x-vela-expires-at"];
21
+ function operation(target, name) {
22
+ const value = Reflect.get(target, name);
23
+ if (typeof value !== "function") throw new Error(`Durable Object ${name}() is unavailable`);
24
+ return value;
25
+ }
26
+ /**
27
+ * The Durable Object that holds one gateway room, one object per gateway and
28
+ * room, in the namespace the gateway's `binding` names in ENV, resolved through
29
+ * the binding seam. Room objects are application classes, so validate only
30
+ * the stub operations called here.
31
+ */
32
+ function gatewayRoomObject(env, gatewayPath, binding, room) {
33
+ if (binding === void 0) throw new Error(`Gateway '${gatewayPath}' names no binding: declare @WebSocketGateway({ binding })`);
34
+ const namespace = resolveBinding(env, { binding }, DURABLE_OBJECT_NAMESPACE);
35
+ const id = namespace.idFromName(durableObjectRoomName(gatewayPath, room));
36
+ return {
37
+ id,
38
+ async call(method, ...args) {
39
+ const stub = namespace.get(id);
40
+ if (typeof stub !== "object" || stub === null) throw new Error("Invalid Durable Object stub");
41
+ return Reflect.apply(operation(stub, method), stub, args);
42
+ }
43
+ };
44
+ }
45
+ /**
46
+ * The Worker isolate's WebSocket transport. Sockets live in each gateway
47
+ * room's Durable Object, so the Worker keeps none: `Gateways` pushes become a
48
+ * `broadcast` RPC to the room's object (the server gateways inject refuses
49
+ * pushes with guidance to `Gateways`), and each authenticated upgrade goes to
50
+ * the object named by the gateway's `binding`, carrying the verified identity
51
+ * in {@link FORWARDED_UPGRADE_HEADERS}. The Durable Object returns the `101`
52
+ * with the client socket.
53
+ */
54
+ function workerWebSocketTransport(env) {
55
+ return {
56
+ forwardingHeaders: FORWARDING_HEADERS,
57
+ async deliver({ gatewayPath, binding, room, command }) {
58
+ await gatewayRoomObject(env, gatewayPath, binding, room).call("broadcast", command);
59
+ },
60
+ async forwardUpgrade({ request, gatewayPath, room, binding, identity }) {
61
+ const headers = new Headers(request.headers);
62
+ const names = FORWARDED_UPGRADE_HEADERS;
63
+ headers.set(names.room, room);
64
+ headers.set(names.path, gatewayPath);
65
+ headers.set(names.user, identity.principal.subject);
66
+ headers.set(names.issuer, identity.principal.issuer);
67
+ headers.set(names.subject, identity.principal.subject);
68
+ headers.set(names.principalType, identity.principal.principalType);
69
+ headers.set(names.tenant, identity.tenantId);
70
+ headers.set(names.expiresAtMs, String(identity.expiresAtMs));
71
+ const response = await gatewayRoomObject(env, gatewayPath, binding, room).call("fetch", new Request(request, { headers }));
72
+ if (!(response instanceof Response)) throw new Error("Durable Object returned an invalid response");
73
+ return response;
74
+ }
75
+ };
76
+ }
77
+ //#endregion
78
+ export { FORWARDED_UPGRADE_HEADERS, gatewayRoomObject, workerWebSocketTransport };
79
+
80
+ //# sourceMappingURL=worker-transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-transport.js","names":[],"sources":["../../src/websocket/worker-transport.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport type { ForwardedWebSocketUpgrade, WebSocketTransport } from '@velajs/vela/websocket';\nimport { resolveBinding } from '@velajs/vela/module-kit';\nimport { DURABLE_OBJECT_NAMESPACE } from '../bindings';\nimport { durableObjectRoomName } from './room-id';\n\n/**\n * Headers that carry trusted upgrade values from the Worker's upgrade route to\n * the room's Durable Object. The route removes client copies before any\n * application hook runs; the Durable Object reads only these.\n */\nexport const FORWARDED_UPGRADE_HEADERS = {\n room: 'x-vela-room',\n path: 'x-vela-path',\n user: 'x-vela-user',\n issuer: 'x-vela-issuer',\n subject: 'x-vela-subject',\n principalType: 'x-vela-principal-type',\n tenant: 'x-vela-tenant',\n expiresAtMs: 'x-vela-expires-at-ms',\n} as const;\n\nconst FORWARDING_HEADERS: readonly string[] = [\n ...Object.values(FORWARDED_UPGRADE_HEADERS),\n // Retired header name: still removed so a client can never supply it.\n 'x-vela-expires-at',\n];\n\nfunction operation(target: object, name: string): Function {\n const value: unknown = Reflect.get(target, name);\n if (typeof value !== 'function') throw new Error(`Durable Object ${name}() is unavailable`);\n return value;\n}\n\n/** One gateway room's Durable Object: its id, and calls to its operations. */\nexport interface GatewayRoomObject {\n readonly id: unknown;\n call(method: string, ...args: unknown[]): Promise<unknown>;\n}\n\n/**\n * The Durable Object that holds one gateway room, one object per gateway and\n * room, in the namespace the gateway's `binding` names in ENV, resolved through\n * the binding seam. Room objects are application classes, so validate only\n * the stub operations called here.\n */\nexport function gatewayRoomObject(\n env: VelaEnv,\n gatewayPath: string,\n binding: string | undefined,\n room: string,\n): GatewayRoomObject {\n if (binding === undefined) {\n throw new Error(\n `Gateway '${gatewayPath}' names no binding: declare @WebSocketGateway({ binding })`,\n );\n }\n const namespace = resolveBinding(env, { binding }, DURABLE_OBJECT_NAMESPACE);\n const id = namespace.idFromName(durableObjectRoomName(gatewayPath, room));\n return {\n id,\n async call(method, ...args) {\n const stub: unknown = namespace.get(id);\n if (typeof stub !== 'object' || stub === null) throw new Error('Invalid Durable Object stub');\n return Reflect.apply(operation(stub, method), stub, args);\n },\n };\n}\n\n/**\n * The Worker isolate's WebSocket transport. Sockets live in each gateway\n * room's Durable Object, so the Worker keeps none: `Gateways` pushes become a\n * `broadcast` RPC to the room's object (the server gateways inject refuses\n * pushes with guidance to `Gateways`), and each authenticated upgrade goes to\n * the object named by the gateway's `binding`, carrying the verified identity\n * in {@link FORWARDED_UPGRADE_HEADERS}. The Durable Object returns the `101`\n * with the client socket.\n */\nexport function workerWebSocketTransport(env: VelaEnv): WebSocketTransport {\n return {\n forwardingHeaders: FORWARDING_HEADERS,\n async deliver({ gatewayPath, binding, room, command }) {\n await gatewayRoomObject(env, gatewayPath, binding, room).call('broadcast', command);\n },\n async forwardUpgrade({\n request,\n gatewayPath,\n room,\n binding,\n identity,\n }: ForwardedWebSocketUpgrade) {\n const headers = new Headers(request.headers);\n const names = FORWARDED_UPGRADE_HEADERS;\n headers.set(names.room, room);\n headers.set(names.path, gatewayPath);\n headers.set(names.user, identity.principal.subject);\n headers.set(names.issuer, identity.principal.issuer);\n headers.set(names.subject, identity.principal.subject);\n headers.set(names.principalType, identity.principal.principalType);\n headers.set(names.tenant, identity.tenantId);\n headers.set(names.expiresAtMs, String(identity.expiresAtMs));\n const response: unknown = await gatewayRoomObject(env, gatewayPath, binding, room).call(\n 'fetch',\n new Request(request, { headers }),\n );\n if (!(response instanceof Response)) {\n throw new Error('Durable Object returned an invalid response');\n }\n return response;\n },\n };\n}\n"],"mappings":";;;;;;;;;AAWA,MAAa,4BAA4B;CACvC,MAAM;CACN,MAAM;CACN,MAAM;CACN,QAAQ;CACR,SAAS;CACT,eAAe;CACf,QAAQ;CACR,aAAa;AACf;AAEA,MAAM,qBAAwC,CAC5C,GAAG,OAAO,OAAO,yBAAyB,GAE1C,mBACF;AAEA,SAAS,UAAU,QAAgB,MAAwB;CACzD,MAAM,QAAiB,QAAQ,IAAI,QAAQ,IAAI;C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AAW,CAAC;GAC3D,MAAM,WAAoB,MAAM,kBAAkB,KAAK,aAAa,SAAS,IAAI,CAAC,CAAC,KACjF,SACA,IAAI,QAAQ,SAAS,EAAE,QAAQ,CAAC,CAClC;GACA,IAAI,EAAE,oBAAoB,WACxB,MAAM,IAAI,MAAM,6CAA6C;GAE/D,OAAO;EACT;CACF;AACF"}
@@ -0,0 +1,49 @@
1
+ //#region src/worker-events.ts
2
+ /** How many optional events there are: `email` and `tail`. */
3
+ const EVENTS = 2;
4
+ const dispatchers = /* @__PURE__ */ new Map();
5
+ /** Each Worker's per-environment cache, while the Worker lives. */
6
+ const applications = /* @__PURE__ */ new WeakMap();
7
+ /**
8
+ * Workers defined before every event's module loaded: they get its handler
9
+ * when it does. workerd has no `WeakRef`, so they are held until then; a
10
+ * Worker entry defines one Worker, at module scope.
11
+ */
12
+ const pending = /* @__PURE__ */ new Set();
13
+ /** Give `worker` the `name` handler, delivered by `dispatch`, unless its object already has one. */
14
+ function defineHandler(worker, name, dispatch) {
15
+ const application = applications.get(worker);
16
+ if (application === void 0 || Object.hasOwn(worker, name)) return;
17
+ Object.defineProperty(worker, name, {
18
+ enumerable: true,
19
+ configurable: true,
20
+ writable: true,
21
+ value: async (payload, env, ctx) => dispatch(() => application(env), payload, ctx)
22
+ });
23
+ }
24
+ /**
25
+ * @internal Give every Worker the `name` handler, delivered by `dispatcher`.
26
+ * The decorator modules of `@velajs/cloudflare/email` and
27
+ * `@velajs/cloudflare/tail` call it when they load, so a Worker has the
28
+ * handler exactly when its code declares such handlers.
29
+ */
30
+ function registerWorkerEvent(name, dispatcher) {
31
+ dispatchers.set(name, dispatcher);
32
+ for (const worker of pending) defineHandler(worker, name, dispatcher);
33
+ if (dispatchers.size === EVENTS) pending.clear();
34
+ }
35
+ /**
36
+ * @internal Define the optional handlers of a Worker's exported object: one
37
+ * for each event a loaded module handles, and later ones as their modules
38
+ * load. An event no loaded module handles gets no handler, so the platform
39
+ * sees none. `application` is the Worker's per-environment cache.
40
+ */
41
+ function defineWorkerEvents(worker, application) {
42
+ applications.set(worker, application);
43
+ for (const [name, dispatcher] of dispatchers) defineHandler(worker, name, dispatcher);
44
+ if (dispatchers.size < EVENTS) pending.add(worker);
45
+ }
46
+ //#endregion
47
+ export { defineWorkerEvents, registerWorkerEvent };
48
+
49
+ //# sourceMappingURL=worker-events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-events.js","names":[],"sources":["../src/worker-events.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport type { CloudflareApplication } from './cloudflare-application';\n\n/** Worker handlers a feature subpath adds to every Worker when a module imports it. */\nexport type WorkerEventName = 'email' | 'tail';\n\n/**\n * @internal Deliver one platform event to the application built for its\n * environment: `application` returns it, built on first use (it rejects when\n * the application fails to start, and the next event retries), `payload` is\n * the handler's first argument (the email message, the tail events), `ctx`\n * the platform's execution context.\n */\nexport type WorkerEventDispatcher = (\n application: () => Promise<CloudflareApplication>,\n payload: unknown,\n ctx: ExecutionContext | undefined,\n) => Promise<void>;\n\ntype ApplicationCache = (env: VelaEnv) => Promise<CloudflareApplication>;\n\n/** How many optional events there are: `email` and `tail`. */\nconst EVENTS = 2;\n\nconst dispatchers = new Map<WorkerEventName, WorkerEventDispatcher>();\n/** Each Worker's per-environment cache, while the Worker lives. */\nconst applications = new WeakMap<object, ApplicationCache>();\n/**\n * Workers defined before every event's module loaded: they get its handler\n * when it does. workerd has no `WeakRef`, so they are held until then; a\n * Worker entry defines one Worker, at module scope.\n */\nconst pending = new Set<object>();\n\n/** Give `worker` the `name` handler, delivered by `dispatch`, unless its object already has one. */\nfunction defineHandler(\n worker: object,\n name: WorkerEventName,\n dispatch: WorkerEventDispatcher,\n): void {\n const application = applications.get(worker);\n if (application === undefined || Object.hasOwn(worker, name)) return;\n Object.defineProperty(worker, name, {\n enumerable: true,\n configurable: true,\n writable: true,\n value: async (payload: unknown, env: VelaEnv, ctx?: ExecutionContext): Promise<void> =>\n dispatch(() => application(env), payload, ctx),\n });\n}\n\n/**\n * @internal Give every Worker the `name` handler, delivered by `dispatcher`.\n * The decorator modules of `@velajs/cloudflare/email` and\n * `@velajs/cloudflare/tail` call it when they load, so a Worker has the\n * handler exactly when its code declares such handlers.\n */\nexport function registerWorkerEvent(\n name: WorkerEventName,\n dispatcher: WorkerEventDispatcher,\n): void {\n dispatchers.set(name, dispatcher);\n for (const worker of pending) defineHandler(worker, name, dispatcher);\n if (dispatchers.size === EVENTS) pending.clear();\n}\n\n/**\n * @internal Define the optional handlers of a Worker's exported object: one\n * for each event a loaded module handles, and later ones as their modules\n * load. An event no loaded module handles gets no handler, so the platform\n * sees none. `application` is the Worker's per-environment cache.\n */\nexport function defineWorkerEvents(worker: object, application: ApplicationCache): void {\n applications.set(worker, application);\n for (const [name, dispatcher] of dispatchers) defineHandler(worker, name, dispatcher);\n if (dispatchers.size < EVENTS) pending.add(worker);\n}\n"],"mappings":";;AAsBA,MAAM,SAAS;AAEf,MAAM,8BAAc,IAAI,IAA4C;;AAEpE,MAAM,+BAAe,IAAI,QAAkC;;;;;;AAM3D,MAAM,0BAAU,IAAI,IAAY;;AAGhC,SAAS,cACP,QACA,MACA,UACM;CACN,MAAM,cAAc,aAAa,IAAI,MAAM;CAC3C,IAAI,gBAAgB,KAAA,KAAa,OAAO,OAAO,QAAQ,IAAI,GAAG;CAC9D,OAAO,eAAe,QAAQ,MAAM;EAClC,YAAY;EACZ,cAAc;EACd,UAAU;EACV,OAAO,OAAO,SAAkB,KAAc,QAC5C,eAAe,YAAY,GAAG,GAAG,SAAS,GAAG;CACjD,CAAC;AACH;;;;;;;AAQA,SAAgB,oBACd,MACA,YACM;CACN,YAAY,IAAI,MAAM,UAAU;CAChC,KAAK,MAAM,UAAU,SAAS,cAAc,QAAQ,MAAM,UAAU;CACpE,IAAI,YAAY,SAAS,QAAQ,QAAQ,MAAM;AACjD;;;;;;;AAQA,SAAgB,mBAAmB,QAAgB,aAAqC;CACtF,aAAa,IAAI,QAAQ,WAAW;CACpC,KAAK,MAAM,CAAC,MAAM,eAAe,aAAa,cAAc,QAAQ,MAAM,UAAU;CACpF,IAAI,YAAY,OAAO,QAAQ,QAAQ,IAAI,MAAM;AACnD"}
@@ -0,0 +1,104 @@
1
+ import { CLOUDFLARE_WORKFLOW, cloudflareApplication, isCloudflareApp, registerWorkflow } from "../cloudflare-factory.js";
2
+ import { HostInvoker, hostModuleId, platformSettlement } from "../host/host-invoker.js";
3
+ import { assertNotThenable, hasPrototypeMethod } from "../host/host-members.js";
4
+ import { WorkflowEntrypoint } from "cloudflare:workers";
5
+ //#region src/workflow/vela-workflow.ts
6
+ const workflowSettlement = platformSettlement(false);
7
+ /**
8
+ * Whether `error` is the Workflows engine interrupting a run: when an instance
9
+ * is paused, restarted or terminated, `step.do`, `step.sleep` and a retry wait
10
+ * reject with an `Error('Aborting engine: ...')`, and the engine recognizes
11
+ * the rejection of `run()` by that message. It must reach the engine as it is.
12
+ */
13
+ function isEngineAbort(error) {
14
+ const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : void 0;
15
+ return typeof message === "string" && message.startsWith("Aborting engine:");
16
+ }
17
+ /**
18
+ * A Workflow class (a `WorkflowEntrypoint`) whose `run(event, step)` is the
19
+ * `run` method of `host`, an `@Injectable()` class, resolved in the Worker's
20
+ * application for the run's environment: the same application the app's
21
+ * Worker handlers use. The host is added to the root module's providers, so
22
+ * it injects `ENV` and what the root module can see. Export a named subclass
23
+ * matching the Wrangler `class_name`:
24
+ *
25
+ * ```ts
26
+ * @Injectable()
27
+ * export class SignupWorkflowHost {
28
+ * constructor(private readonly users: UsersService) {}
29
+ *
30
+ * async run(event: WorkflowEvent<{ email: string }>, step: WorkflowStep) {
31
+ * const user = await step.do('create user', () => this.users.create(event.payload.email));
32
+ * await step.sleep('grace period', '1 day');
33
+ * return step.do('send welcome', () => this.users.welcome(user.id));
34
+ * }
35
+ * }
36
+ * export class SignupWorkflow extends VelaWorkflow(app, SignupWorkflowHost) {}
37
+ * // Worker code: await env.SIGNUP_WORKFLOW.create({ params: { email } })
38
+ * ```
39
+ *
40
+ * - Each run executes in its own execution scope, so request-scoped providers
41
+ * are built per run, through the host's scoped guards, interceptors and
42
+ * exception filters (`getType()` is `'cf:workflow'`, `getPayload()` the
43
+ * event). The engine may run `run()` again for the same instance (after a
44
+ * sleep, an event or an eviction), replaying completed steps from their
45
+ * stored results: each call is a new run.
46
+ * - `event` and `step` are the platform's own objects, passed through
47
+ * untouched, so `step.do`, `step.sleep` and `step.waitForEvent` keep their
48
+ * retry and replay semantics.
49
+ * - A failure is reported (`edge: 'workflow'`) and rethrown as it is, so the
50
+ * engine applies its own semantics, including `NonRetryableError`. A scoped
51
+ * exception filter that catches it settles the run with what it returns.
52
+ * - The engine's own interruptions (an `Error('Aborting engine: ...')` that a
53
+ * step rejects with when the instance is paused, restarted or terminated)
54
+ * are not failures: they pass through unreported, and no filter sees them.
55
+ * - `host` must declare `run` on its prototype; a host whose prototype
56
+ * defines `then()` is rejected, since an instance would be a thenable.
57
+ */
58
+ function VelaWorkflow(app, host) {
59
+ if (!isCloudflareApp(app)) throw new TypeError("VelaWorkflow() takes the app from defineCloudflareApp(AppModule, options): each run executes in the Worker application that app builds.");
60
+ if (typeof host !== "function") throw new TypeError("VelaWorkflow(app, Host) takes the @Injectable() host class.");
61
+ assertNotThenable(host);
62
+ if (!hasPrototypeMethod(host, "run")) throw new TypeError(`${host.name} has no prototype method run(event, step): declare run in the class body as the Workflow body, not as an accessor or an instance field.`);
63
+ const rootClass = typeof app.rootModule === "function" ? app.rootModule : app.rootModule.module;
64
+ const invokers = /* @__PURE__ */ new WeakMap();
65
+ const invokerOf = (application) => {
66
+ const existing = invokers.get(application);
67
+ if (existing) return existing;
68
+ const container = application.getContainer();
69
+ const invoker = new HostInvoker({
70
+ container,
71
+ host,
72
+ moduleId: hostModuleId(container, host, rootClass),
73
+ edge: "workflow"
74
+ });
75
+ invokers.set(application, invoker);
76
+ return invoker;
77
+ };
78
+ class VelaHostWorkflow extends WorkflowEntrypoint {
79
+ async run(event, step) {
80
+ const application = await cloudflareApplication(app, this.env);
81
+ return invokerOf(application).invoke({
82
+ kind: "cf:workflow",
83
+ method: "run",
84
+ args: [event, step],
85
+ payload: event,
86
+ settlement: workflowSettlement,
87
+ passthrough: isEngineAbort
88
+ });
89
+ }
90
+ }
91
+ const descriptor = {
92
+ rootModule: app.rootModule,
93
+ host,
94
+ workflow: VelaHostWorkflow
95
+ };
96
+ registerWorkflow(app, descriptor);
97
+ Object.defineProperty(VelaHostWorkflow, "name", { value: `${host.name}Workflow` });
98
+ Object.defineProperty(VelaHostWorkflow, CLOUDFLARE_WORKFLOW, { value: descriptor });
99
+ return VelaHostWorkflow;
100
+ }
101
+ //#endregion
102
+ export { VelaWorkflow };
103
+
104
+ //# sourceMappingURL=vela-workflow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vela-workflow.js","names":[],"sources":["../../src/workflow/vela-workflow.ts"],"sourcesContent":["import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from 'cloudflare:workers';\nimport type { Type, VelaEnv } from '@velajs/vela';\nimport type { EntrypointExecutionContext } from '@velajs/vela/module-kit';\nimport type { CloudflareApplication } from '../cloudflare-application';\nimport {\n CLOUDFLARE_WORKFLOW,\n cloudflareApplication,\n isCloudflareApp,\n registerWorkflow,\n type CloudflareApp,\n type CloudflareWorkflowDescriptor,\n} from '../cloudflare-factory';\nimport { HostInvoker, hostModuleId, platformSettlement } from '../host/host-invoker';\nimport { assertNotThenable, hasPrototypeMethod } from '../host/host-members';\n\n/**\n * A class `VelaWorkflow()` runs: an `@Injectable()` whose\n * `run(event, step)` is the Workflow's body, typed with the params in\n * `event.payload`.\n */\nexport interface WorkflowHost {\n run(event: never, step: never): unknown;\n}\n\n/**\n * The params a Workflow takes: the `event.payload` type of its host's\n * `run(event, step)`, or of the `run` of a class from `VelaWorkflow()`.\n * `workflow<WorkflowParams<SignupWorkflow>>({ binding })` types the binding\n * that creates its instances.\n */\nexport type WorkflowParams<Target> = Target extends abstract new (\n ...args: never[]\n) => infer Instance\n ? WorkflowParams<Instance>\n : Target extends { run(event: infer Event, ...rest: never[]): unknown }\n ? Event extends { readonly payload: infer Payload }\n ? Payload\n : unknown\n : never;\n\n/** What a Workflow host's `run(event, step)` resolves to: the instance's output. */\nexport type WorkflowOutput<Host extends WorkflowHost> = Awaited<ReturnType<Host['run']>>;\n\n/** The ExecutionContext guards, interceptors and filters receive around a Workflow run. */\nexport type WorkflowExecutionContext = EntrypointExecutionContext<'cf:workflow'>;\n\n/**\n * The class `VelaWorkflow(app, Host)` returns: export a named subclass of it,\n * matching the Wrangler `workflows` entry's `class_name`. It also carries its\n * `CloudflareWorkflowDescriptor` under the static `CLOUDFLARE_WORKFLOW` key,\n * for tools.\n */\nexport type VelaWorkflowClass<Host extends WorkflowHost> = new (\n ctx: ExecutionContext,\n env: VelaEnv,\n) => {\n // First, so a call resolves to the host's output rather than the base class's unknown.\n run(\n event: Readonly<WorkflowEvent<WorkflowParams<Host>>>,\n step: WorkflowStep,\n ): Promise<WorkflowOutput<Host>>;\n} & WorkflowEntrypoint<VelaEnv, WorkflowParams<Host>>;\n\n// A filter that catches a failure settles the run with what it returns;\n// managed work that fails after a successful run is reported, never retried.\nconst workflowSettlement = platformSettlement(false);\n\n/**\n * Whether `error` is the Workflows engine interrupting a run: when an instance\n * is paused, restarted or terminated, `step.do`, `step.sleep` and a retry wait\n * reject with an `Error('Aborting engine: ...')`, and the engine recognizes\n * the rejection of `run()` by that message. It must reach the engine as it is.\n */\nfunction isEngineAbort(error: unknown): boolean {\n const message: unknown =\n typeof error === 'object' && error !== null ? Reflect.get(error, 'message') : undefined;\n return typeof message === 'string' && message.startsWith('Aborting engine:');\n}\n\n/**\n * A Workflow class (a `WorkflowEntrypoint`) whose `run(event, step)` is the\n * `run` method of `host`, an `@Injectable()` class, resolved in the Worker's\n * application for the run's environment: the same application the app's\n * Worker handlers use. The host is added to the root module's providers, so\n * it injects `ENV` and what the root module can see. Export a named subclass\n * matching the Wrangler `class_name`:\n *\n * ```ts\n * @Injectable()\n * export class SignupWorkflowHost {\n * constructor(private readonly users: UsersService) {}\n *\n * async run(event: WorkflowEvent<{ email: string }>, step: WorkflowStep) {\n * const user = await step.do('create user', () => this.users.create(event.payload.email));\n * await step.sleep('grace period', '1 day');\n * return step.do('send welcome', () => this.users.welcome(user.id));\n * }\n * }\n * export class SignupWorkflow extends VelaWorkflow(app, SignupWorkflowHost) {}\n * // Worker code: await env.SIGNUP_WORKFLOW.create({ params: { email } })\n * ```\n *\n * - Each run executes in its own execution scope, so request-scoped providers\n * are built per run, through the host's scoped guards, interceptors and\n * exception filters (`getType()` is `'cf:workflow'`, `getPayload()` the\n * event). The engine may run `run()` again for the same instance (after a\n * sleep, an event or an eviction), replaying completed steps from their\n * stored results: each call is a new run.\n * - `event` and `step` are the platform's own objects, passed through\n * untouched, so `step.do`, `step.sleep` and `step.waitForEvent` keep their\n * retry and replay semantics.\n * - A failure is reported (`edge: 'workflow'`) and rethrown as it is, so the\n * engine applies its own semantics, including `NonRetryableError`. A scoped\n * exception filter that catches it settles the run with what it returns.\n * - The engine's own interruptions (an `Error('Aborting engine: ...')` that a\n * step rejects with when the instance is paused, restarted or terminated)\n * are not failures: they pass through unreported, and no filter sees them.\n * - `host` must declare `run` on its prototype; a host whose prototype\n * defines `then()` is rejected, since an instance would be a thenable.\n */\nexport function VelaWorkflow<Host extends WorkflowHost>(\n app: CloudflareApp,\n host: Type<Host>,\n): VelaWorkflowClass<Host> {\n if (!isCloudflareApp(app)) {\n throw new TypeError(\n 'VelaWorkflow() takes the app from defineCloudflareApp(AppModule, options): each run ' +\n 'executes in the Worker application that app builds.',\n );\n }\n if (typeof host !== 'function') {\n throw new TypeError('VelaWorkflow(app, Host) takes the @Injectable() host class.');\n }\n assertNotThenable(host);\n if (!hasPrototypeMethod(host, 'run')) {\n throw new TypeError(\n `${host.name} has no prototype method run(event, step): declare run in the class body ` +\n 'as the Workflow body, not as an accessor or an instance field.',\n );\n }\n const rootClass = typeof app.rootModule === 'function' ? app.rootModule : app.rootModule.module;\n const invokers = new WeakMap<CloudflareApplication, HostInvoker>();\n const invokerOf = (application: CloudflareApplication): HostInvoker => {\n const existing = invokers.get(application);\n if (existing) return existing;\n const container = application.getContainer();\n const invoker = new HostInvoker({\n container,\n host,\n moduleId: hostModuleId(container, host, rootClass),\n edge: 'workflow',\n });\n invokers.set(application, invoker);\n return invoker;\n };\n\n class VelaHostWorkflow extends WorkflowEntrypoint<VelaEnv, WorkflowParams<Host>> {\n override async run(\n event: Readonly<WorkflowEvent<WorkflowParams<Host>>>,\n step: WorkflowStep,\n ): Promise<unknown> {\n const application = await cloudflareApplication(app, this.env);\n return invokerOf(application).invoke({\n kind: 'cf:workflow',\n method: 'run',\n args: [event, step],\n payload: event,\n settlement: workflowSettlement,\n passthrough: isEngineAbort,\n });\n }\n }\n\n const descriptor: CloudflareWorkflowDescriptor = {\n rootModule: app.rootModule,\n host,\n workflow: VelaHostWorkflow,\n };\n registerWorkflow(app, descriptor);\n Object.defineProperty(VelaHostWorkflow, 'name', { value: `${host.name}Workflow` });\n Object.defineProperty(VelaHostWorkflow, CLOUDFLARE_WORKFLOW, { value: descriptor });\n // `run` resolves to the host's output; the class type says so for bindings and tests.\n return VelaHostWorkflow as unknown as VelaWorkflowClass<Host>;\n}\n"],"mappings":";;;;;AAiEA,MAAM,qBAAqB,mBAAmB,KAAK;;;;;;;AAQnD,SAAS,cAAc,OAAyB;CAC9C,MAAM,UACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,SAAS,IAAI,KAAA;CAChF,OAAO,OAAO,YAAY,YAAY,QAAQ,WAAW,kBAAkB;AAC7E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aACd,KACA,MACyB;CACzB,IAAI,CAAC,gBAAgB,GAAG,GACtB,MAAM,IAAI,UACR,yIAEF;CAEF,IAAI,OAAO,SAAS,YAClB,MAAM,IAAI,UAAU,6DAA6D;CAEnF,kBAAkB,IAAI;CACtB,IAAI,CAAC,mBAAmB,MAAM,KAAK,GACjC,MAAM,IAAI,UACR,GAAG,KAAK,KAAK,wIAEf;CAEF,MAAM,YAAY,OAAO,IAAI,eAAe,aAAa,IAAI,aAAa,IAAI,WAAW;CACzF,MAAM,2BAAW,IAAI,QAA4C;CACjE,MAAM,aAAa,gBAAoD;EACrE,MAAM,WAAW,SAAS,IAAI,WAAW;EACzC,IAAI,UAAU,OAAO;EACrB,MAAM,YAAY,YAAY,aAAa;EAC3C,MAAM,UAAU,IAAI,YAAY;GAC9B;GACA;GACA,UAAU,aAAa,WAAW,MAAM,SAAS;GACjD,MAAM;EACR,CAAC;EACD,SAAS,IAAI,aAAa,OAAO;EACjC,OAAO;CACT;CAEA,MAAM,yBAAyB,mBAAkD;EAC/E,MAAe,IACb,OACA,MACkB;GAClB,MAAM,cAAc,MAAM,sBAAsB,KAAK,KAAK,GAAG;GAC7D,OAAO,UAAU,WAAW,CAAC,CAAC,OAAO;IACnC,MAAM;IACN,QAAQ;IACR,MAAM,CAAC,OAAO,IAAI;IAClB,SAAS;IACT,YAAY;IACZ,aAAa;GACf,CAAC;EACH;CACF;CAEA,MAAM,aAA2C;EAC/C,YAAY,IAAI;EAChB;EACA,UAAU;CACZ;CACA,iBAAiB,KAAK,UAAU;CAChC,OAAO,eAAe,kBAAkB,QAAQ,EAAE,OAAO,GAAG,KAAK,KAAK,UAAU,CAAC;CACjF,OAAO,eAAe,kBAAkB,qBAAqB,EAAE,OAAO,WAAW,CAAC;CAElF,OAAO;AACT"}
@@ -0,0 +1,82 @@
1
+ import "./vela-env-DFvyoNT3.js";
2
+ import { a as CloudflareApp } from "./cloudflare-factory-CuFNUJJD.js";
3
+ import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from "cloudflare:workers";
4
+ import { Type, VelaEnv } from "@velajs/vela";
5
+ import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
6
+ //#region src/workflow/vela-workflow.d.ts
7
+ /**
8
+ * A class `VelaWorkflow()` runs: an `@Injectable()` whose
9
+ * `run(event, step)` is the Workflow's body, typed with the params in
10
+ * `event.payload`.
11
+ */
12
+ interface WorkflowHost {
13
+ run(event: never, step: never): unknown;
14
+ }
15
+ /**
16
+ * The params a Workflow takes: the `event.payload` type of its host's
17
+ * `run(event, step)`, or of the `run` of a class from `VelaWorkflow()`.
18
+ * `workflow<WorkflowParams<SignupWorkflow>>({ binding })` types the binding
19
+ * that creates its instances.
20
+ */
21
+ type WorkflowParams<Target> = Target extends (abstract new (...args: never[]) => infer Instance) ? WorkflowParams<Instance> : Target extends {
22
+ run(event: infer Event, ...rest: never[]): unknown;
23
+ } ? Event extends {
24
+ readonly payload: infer Payload;
25
+ } ? Payload : unknown : never;
26
+ /** What a Workflow host's `run(event, step)` resolves to: the instance's output. */
27
+ type WorkflowOutput<Host extends WorkflowHost> = Awaited<ReturnType<Host['run']>>;
28
+ /** The ExecutionContext guards, interceptors and filters receive around a Workflow run. */
29
+ type WorkflowExecutionContext = EntrypointExecutionContext<'cf:workflow'>;
30
+ /**
31
+ * The class `VelaWorkflow(app, Host)` returns: export a named subclass of it,
32
+ * matching the Wrangler `workflows` entry's `class_name`. It also carries its
33
+ * `CloudflareWorkflowDescriptor` under the static `CLOUDFLARE_WORKFLOW` key,
34
+ * for tools.
35
+ */
36
+ type VelaWorkflowClass<Host extends WorkflowHost> = new (ctx: ExecutionContext, env: VelaEnv) => {
37
+ run(event: Readonly<WorkflowEvent<WorkflowParams<Host>>>, step: WorkflowStep): Promise<WorkflowOutput<Host>>;
38
+ } & WorkflowEntrypoint<VelaEnv, WorkflowParams<Host>>;
39
+ /**
40
+ * A Workflow class (a `WorkflowEntrypoint`) whose `run(event, step)` is the
41
+ * `run` method of `host`, an `@Injectable()` class, resolved in the Worker's
42
+ * application for the run's environment: the same application the app's
43
+ * Worker handlers use. The host is added to the root module's providers, so
44
+ * it injects `ENV` and what the root module can see. Export a named subclass
45
+ * matching the Wrangler `class_name`:
46
+ *
47
+ * ```ts
48
+ * @Injectable()
49
+ * export class SignupWorkflowHost {
50
+ * constructor(private readonly users: UsersService) {}
51
+ *
52
+ * async run(event: WorkflowEvent<{ email: string }>, step: WorkflowStep) {
53
+ * const user = await step.do('create user', () => this.users.create(event.payload.email));
54
+ * await step.sleep('grace period', '1 day');
55
+ * return step.do('send welcome', () => this.users.welcome(user.id));
56
+ * }
57
+ * }
58
+ * export class SignupWorkflow extends VelaWorkflow(app, SignupWorkflowHost) {}
59
+ * // Worker code: await env.SIGNUP_WORKFLOW.create({ params: { email } })
60
+ * ```
61
+ *
62
+ * - Each run executes in its own execution scope, so request-scoped providers
63
+ * are built per run, through the host's scoped guards, interceptors and
64
+ * exception filters (`getType()` is `'cf:workflow'`, `getPayload()` the
65
+ * event). The engine may run `run()` again for the same instance (after a
66
+ * sleep, an event or an eviction), replaying completed steps from their
67
+ * stored results: each call is a new run.
68
+ * - `event` and `step` are the platform's own objects, passed through
69
+ * untouched, so `step.do`, `step.sleep` and `step.waitForEvent` keep their
70
+ * retry and replay semantics.
71
+ * - A failure is reported (`edge: 'workflow'`) and rethrown as it is, so the
72
+ * engine applies its own semantics, including `NonRetryableError`. A scoped
73
+ * exception filter that catches it settles the run with what it returns.
74
+ * - The engine's own interruptions (an `Error('Aborting engine: ...')` that a
75
+ * step rejects with when the instance is paused, restarted or terminated)
76
+ * are not failures: they pass through unreported, and no filter sees them.
77
+ * - `host` must declare `run` on its prototype; a host whose prototype
78
+ * defines `then()` is rejected, since an instance would be a thenable.
79
+ */
80
+ export declare function VelaWorkflow<Host extends WorkflowHost>(app: CloudflareApp, host: Type<Host>): VelaWorkflowClass<Host>;
81
+ //#endregion
82
+ export type { VelaWorkflowClass, WorkflowExecutionContext, WorkflowHost, WorkflowOutput, WorkflowParams };
@@ -0,0 +1,2 @@
1
+ import { VelaWorkflow } from "./workflow/vela-workflow.js";
2
+ export { VelaWorkflow };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velajs/cloudflare",
3
- "version": "1.30.0",
3
+ "version": "1.32.0",
4
4
  "description": "Cloudflare Workers integration for Vela framework",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -44,9 +44,33 @@
44
44
  "types": "./dist/durable-objects.d.ts",
45
45
  "import": "./dist/durable-objects.js"
46
46
  },
47
+ "./email": {
48
+ "types": "./dist/email.d.ts",
49
+ "import": "./dist/email.js"
50
+ },
51
+ "./entrypoints": {
52
+ "types": "./dist/entrypoints.d.ts",
53
+ "import": "./dist/entrypoints.js"
54
+ },
47
55
  "./queues": {
48
56
  "types": "./dist/queues.d.ts",
49
57
  "import": "./dist/queues.js"
58
+ },
59
+ "./storage": {
60
+ "types": "./dist/storage.d.ts",
61
+ "import": "./dist/storage.js"
62
+ },
63
+ "./tail": {
64
+ "types": "./dist/tail.d.ts",
65
+ "import": "./dist/tail.js"
66
+ },
67
+ "./testing": {
68
+ "types": "./dist/testing.d.ts",
69
+ "import": "./dist/testing.js"
70
+ },
71
+ "./workflows": {
72
+ "types": "./dist/workflows.d.ts",
73
+ "import": "./dist/workflows.js"
50
74
  }
51
75
  },
52
76
  "publishConfig": {
@@ -67,19 +91,28 @@
67
91
  "unplugin-swc": "1.5.9",
68
92
  "vitest": "4.1.11",
69
93
  "zod": "^3.25.76",
70
- "@velajs/feature-flags": "1.30.0",
71
- "@velajs/testing": "1.30.0",
72
- "@velajs/vela": "1.30.0"
94
+ "@velajs/feature-flags": "1.31.0",
95
+ "@velajs/storage": "1.32.0",
96
+ "@velajs/testing": "1.32.0",
97
+ "@velajs/vela": "1.32.0"
73
98
  },
74
99
  "peerDependencies": {
75
100
  "@cloudflare/workers-types": ">=4",
76
101
  "hono": ">=4",
77
- "@velajs/feature-flags": "^1.30.0",
78
- "@velajs/vela": "^1.30.0"
102
+ "@velajs/feature-flags": "^1.31.0",
103
+ "@velajs/storage": "^1.32.0",
104
+ "@velajs/testing": "^1.32.0",
105
+ "@velajs/vela": "^1.32.0"
79
106
  },
80
107
  "peerDependenciesMeta": {
81
108
  "@velajs/feature-flags": {
82
109
  "optional": true
110
+ },
111
+ "@velajs/storage": {
112
+ "optional": true
113
+ },
114
+ "@velajs/testing": {
115
+ "optional": true
83
116
  }
84
117
  },
85
118
  "engines": {
@@ -1,9 +0,0 @@
1
- //#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorate.js
2
- function __decorate(decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- }
8
- //#endregion
9
- export { __decorate as default };
@@ -1,6 +0,0 @@
1
- //#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorateMetadata.js
2
- function __decorateMetadata(k, v) {
3
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
4
- }
5
- //#endregion
6
- export { __decorateMetadata as default };
@@ -1,8 +0,0 @@
1
- //#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorateParam.js
2
- function __decorateParam(paramIndex, decorator) {
3
- return function(target, key) {
4
- decorator(target, key, paramIndex);
5
- };
6
- }
7
- //#endregion
8
- export { __decorateParam as default };
@@ -1,67 +0,0 @@
1
- import { encodeStorageKeyClaim } from "./storage-key-claim.js";
2
- import { STORAGE_SIGNED_URL_PURPOSE, signUrl } from "@velajs/vela/security";
3
- //#region src/storage/r2-storage.driver.ts
4
- /** Base path of the StorageController presign-proxy route. */
5
- const STORAGE_ROUTE_BASE = "/storage";
6
- /** {@link StorageDriver} over a Cloudflare R2 bucket. */
7
- var R2StorageDriver = class {
8
- config;
9
- constructor(config) {
10
- this.config = config;
11
- }
12
- async upload(body, path, options) {
13
- await this.config.bucket.put(path, body, {
14
- httpMetadata: options.mimeType ? { contentType: options.mimeType } : void 0,
15
- customMetadata: options.metadata
16
- });
17
- return {
18
- path,
19
- disk: this.config.disk,
20
- size: options.size,
21
- mimeType: options.mimeType ?? "application/octet-stream",
22
- uploadedAt: /* @__PURE__ */ new Date()
23
- };
24
- }
25
- async download(path) {
26
- const obj = await this.config.bucket.get(path);
27
- if (!obj) throw new Error(`Storage object not found at "${path}".`);
28
- return {
29
- toStream: () => obj.body,
30
- toArrayBuffer: () => obj.arrayBuffer(),
31
- toText: () => obj.text(),
32
- contentType: obj.httpMetadata?.contentType ?? "application/octet-stream",
33
- size: obj.size,
34
- metadata: obj.customMetadata
35
- };
36
- }
37
- async delete(path) {
38
- await this.config.bucket.delete(path);
39
- }
40
- async exists(path) {
41
- return await this.config.bucket.head(path) !== null;
42
- }
43
- async getPresignedUrl(path, method, expiresIn) {
44
- if (!this.config.secret) throw new Error("A signing secret is required for presigned URLs (set APP_SECRET).");
45
- if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0) throw new Error(`Invalid presigned URL expiry: ${expiresIn}s (must be a positive safe integer).`);
46
- const claim = encodeStorageKeyClaim(path);
47
- const routePath = `${STORAGE_ROUTE_BASE}/${encodeURIComponent(this.config.disk)}`;
48
- const query = new URLSearchParams({
49
- key: claim,
50
- method
51
- });
52
- return {
53
- url: await signUrl(`${routePath}?${query}`, this.config.secret, {
54
- expiresIn,
55
- method,
56
- purpose: STORAGE_SIGNED_URL_PURPOSE
57
- }),
58
- method,
59
- expiresIn,
60
- expiresAt: new Date(Date.now() + expiresIn * 1e3)
61
- };
62
- }
63
- };
64
- //#endregion
65
- export { R2StorageDriver, STORAGE_ROUTE_BASE };
66
-
67
- //# sourceMappingURL=r2-storage.driver.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"r2-storage.driver.js","names":[],"sources":["../../src/storage/r2-storage.driver.ts"],"sourcesContent":["import type {\n DownloadResult,\n PresignedUrlResult,\n PresignMethod,\n StorageBody,\n StorageDriver,\n UploadOptions,\n UploadResult,\n} from '@velajs/vela/storage';\nimport { signUrl, STORAGE_SIGNED_URL_PURPOSE } from '@velajs/vela/security';\nimport { encodeStorageKeyClaim } from './storage-key-claim';\n\n/** Base path of the StorageController presign-proxy route. */\nexport const STORAGE_ROUTE_BASE = '/storage';\n\nexport interface R2StorageDriverConfig {\n disk: string;\n bucket: R2Bucket;\n /** HMAC secret for presigned URLs (typically env.APP_SECRET). */\n secret?: string;\n}\n\n/** {@link StorageDriver} over a Cloudflare R2 bucket. */\nexport class R2StorageDriver implements StorageDriver {\n constructor(private readonly config: R2StorageDriverConfig) {}\n\n async upload(body: StorageBody, path: string, options: UploadOptions): Promise<UploadResult> {\n await this.config.bucket.put(\n path,\n body as ReadableStream | ArrayBuffer | ArrayBufferView | string | Blob | null,\n {\n httpMetadata: options.mimeType ? { contentType: options.mimeType } : undefined,\n customMetadata: options.metadata,\n },\n );\n return {\n path,\n disk: this.config.disk,\n size: options.size,\n mimeType: options.mimeType ?? 'application/octet-stream',\n uploadedAt: new Date(),\n };\n }\n\n async download(path: string): Promise<DownloadResult> {\n const obj = await this.config.bucket.get(path);\n if (!obj) throw new Error(`Storage object not found at \"${path}\".`);\n return {\n toStream: () => obj.body as ReadableStream,\n toArrayBuffer: () => obj.arrayBuffer(),\n toText: () => obj.text(),\n contentType: obj.httpMetadata?.contentType ?? 'application/octet-stream',\n size: obj.size,\n metadata: obj.customMetadata,\n };\n }\n\n async delete(path: string): Promise<void> {\n await this.config.bucket.delete(path);\n }\n\n async exists(path: string): Promise<boolean> {\n return (await this.config.bucket.head(path)) !== null;\n }\n\n async getPresignedUrl(\n path: string,\n method: PresignMethod,\n expiresIn: number,\n ): Promise<PresignedUrlResult> {\n if (!this.config.secret) {\n throw new Error('A signing secret is required for presigned URLs (set APP_SECRET).');\n }\n // Defend the direct-driver path too: a non-finite/non-positive expiry would\n // make signUrl omit `expires`, yielding a never-expiring URL.\n if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0) {\n throw new Error(\n `Invalid presigned URL expiry: ${expiresIn}s (must be a positive safe integer).`,\n );\n }\n // The object key is an opaque signed query claim, never a URL path. This\n // prevents WHATWG path normalization / multi-decode behavior from turning\n // an encoded key into a different storage capability.\n const claim = encodeStorageKeyClaim(path);\n const routePath = `${STORAGE_ROUTE_BASE}/${encodeURIComponent(this.config.disk)}`;\n const query = new URLSearchParams({ key: claim, method });\n const url = await signUrl(`${routePath}?${query}`, this.config.secret, {\n expiresIn,\n method,\n purpose: STORAGE_SIGNED_URL_PURPOSE,\n });\n return { url, method, expiresIn, expiresAt: new Date(Date.now() + expiresIn * 1000) };\n }\n}\n"],"mappings":";;;;AAaA,MAAa,qBAAqB;;AAUlC,IAAa,kBAAb,MAAsD;CACvB;CAA7B,YAAY,QAAgD;EAA/B,KAAA,SAAA;CAAgC;CAE7D,MAAM,OAAO,MAAmB,MAAc,SAA+C;EAC3F,MAAM,KAAK,OAAO,OAAO,IACvB,MACA,MACA;GACE,cAAc,QAAQ,WAAW,EAAE,aAAa,QAAQ,SAAS,IAAI,KAAA;GACrE,gBAAgB,QAAQ;EAC1B,CACF;EACA,OAAO;GACL;GACA,MAAM,KAAK,OAAO;GAClB,MAAM,QAAQ;GACd,UAAU,QAAQ,YAAY;GAC9B,4BAAY,IAAI,KAAK;EACvB;CACF;CAEA,MAAM,SAAS,MAAuC;EACpD,MAAM,MAAM,MAAM,KAAK,OAAO,OAAO,IAAI,IAAI;EAC7C,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,gCAAgC,KAAK,GAAG;EAClE,OAAO;GACL,gBAAgB,IAAI;GACpB,qBAAqB,IAAI,YAAY;GACrC,cAAc,IAAI,KAAK;GACvB,aAAa,IAAI,cAAc,eAAe;GAC9C,MAAM,IAAI;GACV,UAAU,IAAI;EAChB;CACF;CAEA,MAAM,OAAO,MAA6B;EACxC,MAAM,KAAK,OAAO,OAAO,OAAO,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