@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
package/README.md CHANGED
@@ -40,15 +40,34 @@ class AppModule {}
40
40
  export default createCloudflareWorker(AppModule);
41
41
  ```
42
42
 
43
- The worker exposes `fetch`, `queue`, and `scheduled`. Its first event builds an
44
- application with that event's environment. Concurrent events for the same
43
+ The worker exposes `fetch`, `queue`, and `scheduled`, plus `email` and `tail`
44
+ once a module imports `@OnEmail()` or `@OnTail()` (see
45
+ [Service entrypoints, email and tail](#service-entrypoints-email-and-tail)), and carries a
46
+ descriptor under the symbol key `CLOUDFLARE_WORKER`
47
+ (`Symbol.for('vela.cloudflare.worker')`), which the platform ignores and which
48
+ an entry adding handlers keeps (`export default { ...worker, email }`): the
49
+ root module, the options, the Durable Object, Workflow and service entrypoint
50
+ classes defined from the same app (each class also carries its descriptor
51
+ under `CLOUDFLARE_DURABLE_OBJECT`, `CLOUDFLARE_WORKFLOW` or
52
+ `CLOUDFLARE_ENTRYPOINT`), and
53
+ `createOptions(env)`/`createApplication(env)`, which build the application
54
+ exactly as the Worker does, short of the `configure(app, env)` hook, which
55
+ receives the Workers application. `@velajs/cli` loads the Worker entry and builds its
56
+ application from it, so a project needs no `vela.config`, and
57
+ `@velajs/cloudflare/testing` builds test applications from the same options.
58
+ Its first event builds an application with that event's environment. Concurrent events for the same
45
59
  environment object share construction. Different environment objects receive
46
60
  separate applications, including separate providers, lifecycle state, and live
47
61
  drivers. A failed construction is evicted and the next event retries.
48
62
 
49
63
  The root is static: a module class, or a `DynamicModule` such as
50
64
  `AppModule.forRoot(...)`, declared once at module scope. `createCloudflareWorker`,
51
- `createCloudflareApp` and `VelaWebSocketDurableObject` all take the same root.
65
+ `createCloudflareApp`, `VelaDurableObject` and `VelaWebSocketDurableObject` all
66
+ take the same root. An entry that exports Durable Object classes defines the app
67
+ once with `defineCloudflareApp(AppModule, options)`: its `worker` is the default
68
+ export, and the classes built from the app share its root, and its runtime
69
+ adapters configure their containers (`configureContainer`) (see [Durable Object hosts](#durable-object-hosts)); `createCloudflareWorker` is
70
+ `defineCloudflareApp(...).worker`.
52
71
  When module configuration needs bindings, read them where each application is
53
72
  built, from its own `ENV`:
54
73
 
@@ -80,29 +99,75 @@ factories that inject `ENV` rather than capturing them in module options.
80
99
  Providers with request scope still rebuild per HTTP request or queue/cron dispatch.
81
100
  Do not retain request objects or authentication state in singleton providers.
82
101
 
83
- For explicit construction inside a platform event:
102
+ Request middleware belongs in modules: a consumer middleware class resolves
103
+ through dependency injection, so it can inject `ENV` like any provider.
84
104
 
85
105
  ```ts
86
- const app = await createCloudflareApp(AppModule, {
87
- env,
88
- globalPrefix: '/api',
89
- middleware: (bindings) => [async (context, next) => {
90
- context.header('x-service', bindings.SERVICE_NAME);
106
+ import {
107
+ InjectEnv,
108
+ Injectable,
109
+ Module,
110
+ type MiddlewareConsumer,
111
+ type NestMiddleware,
112
+ type NestModule,
113
+ type VelaContext,
114
+ type VelaEnv,
115
+ } from '@velajs/vela';
116
+
117
+ @Injectable()
118
+ class ServiceHeader implements NestMiddleware {
119
+ constructor(@InjectEnv() private readonly env: VelaEnv) {}
120
+ async use(context: VelaContext, next: () => Promise<void>) {
121
+ context.header('x-service', this.env.SERVICE_NAME);
91
122
  await next();
92
- }],
123
+ }
124
+ }
125
+
126
+ @Module({ providers: [ServiceHeader] })
127
+ export class AppModule implements NestModule {
128
+ configure(consumer: MiddlewareConsumer) {
129
+ consumer.apply(ServiceHeader).forRoutes('*');
130
+ }
131
+ }
132
+ ```
133
+
134
+ `createCloudflareWorker(AppModule, { configure })` finishes each application's
135
+ HTTP surface, for example with extra Hono routes, once per environment. It runs
136
+ after the application is built and before any event reaches it, including
137
+ concurrent cold events; a throw fails that construction and the next event
138
+ retries. It must be synchronous and do no I/O (a returned promise fails the
139
+ construction):
140
+
141
+ ```ts
142
+ export default createCloudflareWorker(AppModule, {
143
+ configure(app, env) {
144
+ app.getHonoApp().get('/version', (c) => c.text(env.SERVICE_VERSION));
145
+ },
93
146
  });
147
+ ```
148
+
149
+ Enable CORS as in Nest, with the `cors` option or `app.enableCors()` inside
150
+ `configure`; Hono's `cors` middleware then answers preflights ahead of every
151
+ route and guard:
152
+
153
+ ```ts
154
+ export default createCloudflareWorker(AppModule, { cors: { origin: ['https://app.example.com'] } });
155
+ ```
156
+
157
+ For explicit construction inside a platform event:
158
+
159
+ ```ts
160
+ const app = await createCloudflareApp(AppModule, { env, globalPrefix: '/api' });
94
161
  const bindings = app.get(ENV); // VelaEnv
95
162
  return app.fetch(request, env, executionContext);
96
163
  ```
97
164
 
98
165
  `env` is registered as `ENV` before provider factories and lifecycle hooks.
99
- Bindings inside `middleware(env)` are typed as `VelaEnv` too; request callbacks
100
- capture the native environment without retyping Hono's context. Referencing a
101
- binding is safe during construction; platform I/O must still happen inside a
102
- Workers event or Durable Object context. An explicitly built application rejects
103
- requests or events carrying another environment object, including calls through
104
- the underlying Hono app. Internal `ctx.run` reentry retains the application's
105
- environment.
166
+ Referencing a binding is safe during construction; platform I/O must still
167
+ happen inside a Workers event or Durable Object context. An explicitly built
168
+ application rejects requests or events carrying another environment object,
169
+ including calls through the underlying Hono app. Internal `ctx.run` reentry
170
+ retains the application's environment.
106
171
 
107
172
  `cloudflareAdapter({ env })` provides the same bootstrap and request contract
108
173
  when composing `VelaFactory.create` directly. `createCloudflareWorker` and
@@ -291,43 +356,54 @@ native bindings and live invalidation capabilities as HTTP. See
291
356
 
292
357
  ## WebSockets, live queries, and Durable Objects
293
358
 
359
+ Import the core modules; the Cloudflare adapter wires them to Durable Objects.
294
360
  Use the native Durable Object entrypoint only in your Worker entry file:
295
361
 
296
362
  ```ts
297
- import { ENV, Module } from '@velajs/vela';
363
+ import { Module } from '@velajs/vela';
298
364
  import { LiveModule } from '@velajs/vela/live';
299
- import {
300
- CloudflareWebSocketModule,
301
- createCloudflareWorker,
302
- durableObjectCursorLog,
303
- durableObjectLive,
304
- } from '@velajs/cloudflare';
365
+ import { WebSocketModule } from '@velajs/vela/websocket';
366
+ import { defineCloudflareApp } from '@velajs/cloudflare';
305
367
  import { VelaWebSocketDurableObject } from '@velajs/cloudflare/durable-objects';
306
368
 
307
369
  @Module({
308
- imports: [
309
- CloudflareWebSocketModule.forRoot(),
310
- LiveModule.forRootAsync({
311
- // ROOMS is typed DurableObjectNamespace<Room> by `wrangler types`.
312
- inject: [ENV],
313
- useFactory: (env) => ({
314
- driver: () => durableObjectLive({
315
- namespace: env.ROOMS,
316
- gatewayPath: '/rooms/:room/ws',
317
- }),
318
- log: () => durableObjectCursorLog(),
319
- }),
320
- }),
321
- ],
322
- // Add your @WebSocketGateway and @LiveResolver classes here.
370
+ imports: [WebSocketModule.forRoot(), LiveModule.forRoot()],
371
+ // Your @WebSocketGateway({ binding: 'ROOMS', ... }) and @LiveResolver classes.
323
372
  providers: [],
324
373
  })
325
374
  class RoomModule {}
326
375
 
327
- export class Room extends VelaWebSocketDurableObject(RoomModule) {}
328
- export default createCloudflareWorker(RoomModule);
376
+ const app = defineCloudflareApp(RoomModule);
377
+ export class Room extends VelaWebSocketDurableObject(app) {}
378
+ export default app.worker;
329
379
  ```
330
380
 
381
+ `cloudflareAdapter` registers the platform as the global `WS_TRANSPORT` and
382
+ `LIVE_PLATFORM` tokens before modules load; it never replaces module providers.
383
+ In the Worker, `WebSocketModule` serves an upgrade route for each gateway that
384
+ names a `binding` and forwards the authenticated upgrade to that room's Durable
385
+ Object. The Worker keeps no sockets, so a gateway's `@WebSocketServer()`
386
+ refuses pushes there; `Gateways` from `@velajs/vela/websocket`
387
+ (`gateways.of(ChatGateway).to(room).emit(event, data)`) calls the `broadcast`
388
+ RPC of the gateway + room Durable Object, read by the gateway's `binding` from
389
+ `ENV`. Inside a Durable Object, a `Gateways` push to its own room reaches its
390
+ sockets and a push to another room goes to that room's object. `LiveModule`
391
+ sends invalidations to the room Durable
392
+ Object of the single binding-backed gateway, reading the namespace from `ENV`
393
+ when first needed; with several, the first invalidation reports the ambiguity,
394
+ and `driver: () => durableObjectLive({ gatewayPath })` (or `{ binding }`)
395
+ chooses. A gateway without `roomParam` has one room Durable Object, named by
396
+ its path, so its invalidations and inspections go there whatever room they
397
+ name. Inside the Durable Object, the gateway server broadcasts to its
398
+ hibernatable sockets, invalidations apply locally, and the cursor log is a
399
+ `DoCursorLog` in the object's SQLite storage (in memory when the class is not
400
+ SQLite-backed). `LiveInspector` reads a named room through the same gateway
401
+ binding with the object's `inspectLive` RPC, which
402
+ Studio's `livePanel({ rooms })` uses. The same `RoomModule` serves the Worker, every Durable Object
403
+ and a node host. Without `WebSocketModule`, the Worker mounts no upgrade route,
404
+ and the adapter reports each binding-backed gateway through the diagnostics
405
+ policy.
406
+
331
407
  Declare gateways with `@WebSocketGateway({ path, roomParam, binding, ... })` and
332
408
  configure origins and upgrade authentication for your application.
333
409
  `authenticator` names an `UpgradeAuthenticator` class that the Worker resolves
@@ -341,57 +417,312 @@ routing consumes the core trusted request identity, checks conflicts with the
341
417
  upgrade credential, and forwards issuer, subject, tenant, and expiry to the DO.
342
418
  Client-supplied internal identity headers are stripped before authorization.
343
419
 
344
- Declare live query argument and result schemas once with `defineLiveQuery({ args,
345
- result })` from `@velajs/vela/live`. Both entries accept a parser object such as a
346
- Zod schema. Use `@LiveQuery('todos.list', definition, { tags: ['todos'] })` on the
347
- resolver and share the definition with its client. Restored hibernation arguments
420
+ Declare each live query once with `defineLiveQuery({ name, args, result })` from
421
+ `@velajs/vela/live`. Both schemas accept a parser object such as a Zod schema.
422
+ Use `@LiveQuery(definition, { tags: ['todos'] })` on the resolver and share the
423
+ definition with its client. Restored hibernation arguments
348
424
  and final query results use the same validation boundary.
349
425
 
350
426
  Each application constructs its own driver and cursor log. Workers send
351
- invalidations through the typed DO namespace; the DO uses its own live engine
427
+ invalidations through the gateway's DO namespace; the DO uses its own live engine
352
428
  and SQLite cursor log. Configure the class in Wrangler `new_sqlite_classes` to
353
429
  retain cursor/epoch state across hibernation. Hibernated subscriptions are
354
430
  restored on wake; the shared live protocol handles resume or snapshot fallback.
355
431
 
356
432
  The DO class preserves its RPC types, so `DurableObjectNamespace<Room>` exposes
357
- `invalidate`, `broadcast`, and PITR methods without assertions. `broadcastToRoom`,
358
- `liveInvalidateToRoom`, and the PITR helpers remain available from the root
433
+ `invalidate`, `broadcast`, `inspectLive`, and PITR methods without assertions.
434
+ `liveInvalidateToRoom` and the PITR helpers remain available from the root
359
435
  package. `VelaNonceDurableObject` is exported from `/durable-objects`; its
360
436
  `durableObjectNonceStore` factory remains on the root entrypoint.
361
437
 
362
438
  The root package contains no runtime `cloudflare:workers` import and can be
363
439
  loaded by Node tooling. Native classes belong to `/durable-objects`.
364
440
 
441
+ ## Durable Object hosts
442
+
443
+ `VelaDurableObject(app, Host)` from `/durable-objects` returns a Durable Object
444
+ class whose instances each boot one application context from the app's root
445
+ (`VelaFactory.createApplicationContext`, under `blockConcurrencyWhile`), with
446
+ `Host`, an `@Injectable()`, added to the root module's providers. The host
447
+ methods the `rpc` option names become the class's JS-RPC methods, typed on the
448
+ binding; no other method, TypeScript `private` helpers included, is reachable
449
+ over RPC. Its `fetch`, `alarm` and WebSocket handlers become the object's:
450
+
451
+ ```ts
452
+ import { Inject, Injectable } from '@velajs/vela';
453
+ import { DO_STORAGE, VelaDurableObject } from '@velajs/cloudflare/durable-objects';
454
+
455
+ @Injectable()
456
+ export class CounterHost {
457
+ constructor(@Inject(DO_STORAGE) private readonly storage: DurableObjectStorage) {}
458
+
459
+ async increment(by: number): Promise<number> {
460
+ const value = ((await this.storage.get<number>('value')) ?? 0) + by;
461
+ await this.storage.put('value', value);
462
+ return value;
463
+ }
464
+ }
465
+
466
+ export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}
467
+ // Anywhere with the COUNTER binding: await env.COUNTER.getByName('orders').increment(1)
468
+ ```
469
+
470
+ The context injects `ENV`, `DO_STATE`, `DO_STORAGE` and `DO_ID`. Each call and
471
+ event runs in its own execution scope (request-scoped providers per call)
472
+ through the host's scoped guards, pipes, interceptors and filters, with an
473
+ `ExecutionContext` of type `rpc` (or `cf:do:fetch`, `cf:do:alarm`,
474
+ `cf:do:websocket`); a streamed `fetch()` body keeps its scope open until it is
475
+ sent. Failures are reported first; an RPC call rejects only with an
476
+ `EntrypointError` (`status`, `code`, `message`, and `details` for a client
477
+ fault), which `isEntrypointError()` from the root entry recognizes on the
478
+ caller's side from `compatibility_date` 2026-04-21 (or with
479
+ `enhanced_error_serialization`). A host whose prototype defines `then()` is
480
+ rejected when the class is defined. See
481
+ [Durable Objects](../../docs/durable-objects.md).
482
+
483
+ ## Workflows
484
+
485
+ `VelaWorkflow(app, Host)` from `@velajs/cloudflare/workflows` returns a
486
+ `WorkflowEntrypoint` class whose `run(event, step)` is the `run` method of an
487
+ `@Injectable()` host, resolved in the Worker's application for the run's
488
+ environment (the one the Worker's handlers use), with the host added to the
489
+ root module's providers:
490
+
491
+ ```ts
492
+ import { Injectable } from '@velajs/vela';
493
+ import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers';
494
+ import { VelaWorkflow } from '@velajs/cloudflare/workflows';
495
+
496
+ @Injectable()
497
+ export class SignupHost {
498
+ constructor(private readonly users: UsersService) {}
499
+
500
+ async run(event: WorkflowEvent<{ email: string }>, step: WorkflowStep) {
501
+ const userId = await step.do(
502
+ 'create user',
503
+ async (): Promise<string> => this.users.create(event.payload.email),
504
+ );
505
+ await step.sleep('grace period', '1 day');
506
+ return { userId };
507
+ }
508
+ }
509
+
510
+ export class SignupWorkflow extends VelaWorkflow(app, SignupHost) {}
511
+ // Worker code: await env.SIGNUP_WORKFLOW.create({ params: { email } })
512
+ ```
513
+
514
+ `event` and `step` pass through untouched, so step retries and replays keep
515
+ their semantics. Each run gets its own execution scope (request-scoped
516
+ providers per run) and runs the host's scoped guards, interceptors and filters
517
+ (`getType()` `'cf:workflow'`). A failure is reported (`edge: 'workflow'`) and
518
+ rethrown as it is, so the engine honors `NonRetryableError`. The engine's own
519
+ interruptions (`Aborting engine: ...` when an instance is paused, restarted or
520
+ terminated) pass through unreported and unfiltered. The typed
521
+ `workflow<Params>({ binding })` reference (root entry) creates and reads
522
+ instances from module options and helpers; `WorkflowParams<T>` reads a
523
+ Workflow's params from its class or host. See
524
+ [Workflows](../../docs/workflows.md).
525
+
526
+ ## Service entrypoints, email and tail
527
+
528
+ `VelaEntrypoint(app, Host, { rpc })` from `@velajs/cloudflare/entrypoints`
529
+ returns a `WorkerEntrypoint` class whose JS-RPC methods are the host methods
530
+ `rpc` names, typed on a `Service<typeof Billing>` binding. Each call runs in the
531
+ Worker's application through the host's scoped guards, pipes, interceptors and
532
+ filters (`getType()` `'rpc'`), with the caller's `ctx.props` injectable as
533
+ `ENTRYPOINT_PROPS`; failures are reported (`edge: 'rpc'`) and reject only with
534
+ an `EntrypointError`:
535
+
536
+ ```ts
537
+ import { Inject, Injectable } from '@velajs/vela';
538
+ import { ENTRYPOINT_PROPS, VelaEntrypoint } from '@velajs/cloudflare/entrypoints';
539
+
540
+ @Injectable()
541
+ export class BillingHost {
542
+ constructor(@Inject(ENTRYPOINT_PROPS) private readonly props: unknown) {}
543
+
544
+ async charge(customerId: string, cents: number): Promise<{ invoiceId: string }> {
545
+ return { invoiceId: `${customerId}-${cents}` };
546
+ }
547
+ }
548
+
549
+ export class Billing extends VelaEntrypoint(app, BillingHost, { rpc: ['charge'] }) {}
550
+ // Another Worker: services: [{ binding: 'BILLING', service: 'billing', entrypoint: 'Billing' }]
551
+ // await env.BILLING.charge('customer-1', 500)
552
+ ```
553
+
554
+ `fetch`, `connect`, `then`, `ctx`, `env`, `dup`, hooks and the
555
+ `WorkerEntrypoint` handlers are never RPC methods.
556
+
557
+ `@OnEmail({ to? })` from `@velajs/cloudflare/email` and `@OnTail()` from
558
+ `@velajs/cloudflare/tail` make provider methods the Worker's Email Workers and
559
+ Tail Workers handlers (entrypoint kinds `cf:email` and `cf:tail`); importing
560
+ them gives `app.worker` its `email` and `tail` handlers. An email goes to the
561
+ handlers whose `to` lists its envelope recipient, else to those without `to`,
562
+ and a message no handler accepts is rejected with `setReject()`. Tail handler
563
+ failures are reported and never thrown into the platform's loop; an
564
+ application that fails to start is logged to the console instead. See
565
+ [Service entrypoints, email and tail](../../docs/entrypoints.md).
566
+
567
+ ## Bindings by name
568
+
569
+ Module options name a binding instead of holding it. `kv`, `r2`, `d1`,
570
+ `queue`, `durableObject`, `rateLimit` and `workflow` each take `{ binding }`, the name
571
+ declared in the Wrangler configuration, and read nothing when declared: calling
572
+ the reference with an application's `ENV` returns the typed native binding, or
573
+ fails naming the binding and the Wrangler key that declares it
574
+ (`ENV.UPLOADS is not set: declare the R2 bucket binding 'UPLOADS' under r2_buckets …`).
575
+ The drivers and stores below are built on them, so one static module graph
576
+ serves every environment.
577
+
578
+ ## Rate limiting
579
+
580
+ `ThrottlerModule` from `@velajs/vela/throttler` counts through Workers Rate
581
+ Limiting bindings named in `rateLimitStore`:
582
+
583
+ ```ts
584
+ import { ThrottlerModule } from '@velajs/vela/throttler';
585
+ import { rateLimitStore } from '@velajs/cloudflare';
586
+
587
+ ThrottlerModule.forRoot({
588
+ throttlers: [
589
+ { name: 'burst', ttl: 10_000, limit: 20 },
590
+ { name: 'sustained', ttl: 60_000, limit: 100 },
591
+ ],
592
+ storage: rateLimitStore({ binding: { burst: 'BURST_LIMITER', sustained: 'API_LIMITER' } }),
593
+ });
594
+ ```
595
+
596
+ `rateLimitStore({ binding: 'API_LIMITER' })` serves every throttler from one
597
+ binding. Each binding's `simple.limit` and `simple.period` in the Wrangler
598
+ `ratelimits` block must equal its throttler's `limit` and `ttl` (10 or 60
599
+ seconds): the platform enforces them, so a `@Throttle()` override that changes
600
+ them fails at bootstrap, and one binding serves only throttlers that share a
601
+ `limit` and `ttl`. The store checks the declared throttlers at bootstrap: another
602
+ period, different values on one binding, or a throttler the per-name map leaves
603
+ out fails the application before any binding is charged. The platform exposes no
604
+ counters, so responses carry no `X-RateLimit-Remaining`, and no reset time, so
605
+ `X-RateLimit-Reset` and `Retry-After` report the configured period.
606
+
607
+ Workers Rate Limiting counts per Cloudflare location, and its counters are
608
+ eventually consistent: limits are approximate, not a global or exact quota. A
609
+ client spread across locations can exceed them. For strict limits such as login
610
+ attempts per account, implement a `ThrottlerStore` that counts in a Durable
611
+ Object.
612
+
365
613
  ## R2 storage and caches
366
614
 
367
- For new object/file storage, prefer the independently imported
368
- [`@velajs/storage`](../storage/README.md#portable-storage-and-the-cloudflare-proxy)
369
- with a native R2 or hybrid driver. The storage module below remains the supported
370
- 1.x Worker HMAC proxy API; its signed routes differ from provider-signed URLs.
615
+ `StorageModule` from [`@velajs/storage`](../storage/README.md#storage-on-cloudflare-workers)
616
+ is the one file-storage module. Its native R2 driver comes from the
617
+ `@velajs/cloudflare/storage` subpath:
371
618
 
372
- Configure named disks from an async factory using actual bucket values:
619
+ ```ts
620
+ import { StorageModule } from '@velajs/storage';
621
+ import { r2Storage } from '@velajs/cloudflare/storage';
622
+
623
+ StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) });
624
+ ```
625
+
626
+ The bucket is read from each application's `ENV` on its first storage
627
+ operation. The native binding cannot presign; use `publicBaseUrl`, the storage
628
+ HTTP controller with `http: { download: 'proxy' }`, or the R2 HTTP/hybrid
629
+ drivers for provider-signed URLs.
630
+
631
+ `CacheModule` from `@velajs/vela/cache` takes its KV stores by binding name:
373
632
 
374
633
  ```ts
375
- StorageModule.forRootAsync({
376
- inject: [ENV],
377
- useFactory: (env) => ({
378
- defaultDisk: 'uploads',
379
- secret: env.APP_SECRET,
380
- disks: [{ disk: 'uploads', bucket: env.FILES, root: 'uploads/{year}' }],
381
- presignedUrl: { defaultExpiry: 3600, maxExpiry: 86400 },
382
- }),
634
+ import { CacheModule } from '@velajs/vela/cache';
635
+ import { kvCache, kvCacheInvalidation } from '@velajs/cloudflare';
636
+
637
+ CacheModule.forRoot({
638
+ namespace: 'catalog-v1',
639
+ scope: trustedCacheScope,
640
+ store: kvCache({ binding: 'CACHE' }),
641
+ invalidation: kvCacheInvalidation({ binding: 'CACHE_GENERATIONS' }),
383
642
  });
384
643
  ```
385
644
 
386
- `StorageService` supports upload, download, delete, existence checks, and expiring
387
- signed download URLs. The proxy validates signatures, HTTP method, expiry, and
388
- the configured root; returned files download as attachments.
645
+ Each operation reads the namespace from the application's `ENV`. A binding that
646
+ is not declared fails the operation with an error naming it and
647
+ `kv_namespaces`; the cache treats that as a miss and sends the error to the
648
+ application's error reporter (edge `'cache'`).
649
+
650
+ `kvCache({ binding })` is a function of `ENV`, so a tier composes it without
651
+ reading `ENV` directly:
652
+ `store: (env) => new TieredCacheStore([new MemoryCacheStore(), kvCache({ binding: 'CACHE' })(env)])`.
653
+ `KVCacheStore` and `KVCacheInvalidationStore` also take a namespace or a
654
+ function returning one.
655
+ Construct `KvFlagDriver` with a native namespace: `new KvFlagDriver(env.CACHE)`.
656
+ Cache reads and object-valued flag reads return `unknown`; validate them with an
657
+ application parser (`cache.scope(scope).getParsed(key, parser)`).
658
+
659
+ ## Testing Worker handlers
660
+
661
+ `@velajs/cloudflare/testing` runs inside the Workers Vitest pool
662
+ (`@cloudflare/vitest-plugin`) and needs `@velajs/testing`.
663
+ `createTestingWorker(AppModule, { env?, overrides?, ...workerOptions })` builds
664
+ the module as `createCloudflareWorker(AppModule, workerOptions)` does (its
665
+ adapters, then its `configure(app, env)` hook), through
666
+ `Test.createTestingModule()`, and drives the Worker's handlers:
667
+
668
+ ```ts
669
+ import { env } from 'cloudflare:workers';
670
+ import { createTestingWorker, queueJob } from '@velajs/cloudflare/testing';
671
+ import { expect, it } from 'vitest';
672
+
673
+ it('processes a created todo', async () => {
674
+ const worker = await createTestingWorker(AppModule, {
675
+ env,
676
+ overrides: (module) =>
677
+ module
678
+ .overrideModule(NotificationsModule)
679
+ .useModule(SilentNotifications)
680
+ .useMocker((token) => (token === Notifier ? fakeNotifier : undefined)),
681
+ });
682
+ try {
683
+ const created = await worker.fetch('/todos', {
684
+ method: 'POST',
685
+ headers: { 'content-type': 'application/json' },
686
+ body: JSON.stringify({ title: 'Write tests' }),
687
+ });
688
+ expect(created.ok).toBe(true);
689
+
690
+ const result = await worker.queue('todo-events', [
691
+ queueJob('todo-events', todoCreated, { id: '1', title: 'Write tests' }),
692
+ ]);
693
+ expect(result.outcome).toBe('ok');
694
+ expect(result.explicitAcks).toHaveLength(1);
695
+
696
+ await worker.scheduled('0 3 * * *');
697
+ } finally {
698
+ await worker.close();
699
+ }
700
+ });
701
+ ```
389
702
 
390
- Construct `KVCacheStore` and `KvFlagDriver` with a native namespace:
391
- `new KVCacheStore(env.CACHE)` and `new KvFlagDriver(env.CACHE)`. Cache reads and
392
- object-valued flag reads return `unknown`; validate them with an application
393
- parser. Core `CacheService.getParsed(key, parser)` infers the result from that
394
- parser. Memory and tiered cache reads use the same unknown-value contract.
703
+ - `env` defaults to the pool's `env` from `cloudflare:workers`; every event
704
+ carries it, so the Cloudflare adapter accepts the requests.
705
+ - `overrides` receives the `@velajs/testing` builder: `overrideProvider()`,
706
+ `overrideGuard()` and the other enhancer overrides, `overrideModule().useModule()`
707
+ and `useMocker()`. `worker.module` is the compiled `TestingModule`; its
708
+ `fetch()` and `http` client send the same `env` as `c.env`.
709
+ - `fetch(input, init?)` resolves a path against `http://localhost`.
710
+ - `queue(physicalQueue, messages)` delivers one batch built with `cloudflare:test`'s
711
+ `createMessageBatch()` and returns its `getQueueResult()` plus `outcome`
712
+ (`'exception'`, with `error`, when the handler rejected: Cloudflare would retry
713
+ the unacknowledged messages). `queueJob(queue, jobOrName, data, { id?, attempts? })`
714
+ builds the envelope `QueueClient.add()` sends.
715
+ - `scheduled(cron, { scheduledTime? })` fires a cron trigger with
716
+ `createScheduledController()`, and rejects when no `@Cron` job declares `cron`.
717
+ - `email(message)` and `tail(events)` deliver to the `@OnEmail()` and
718
+ `@OnTail()` handlers. `emailMessage({ from, to, subject?, text?, headers?, raw? })`
719
+ builds a `ForwardableEmailMessage` that records `setReject()`, `forward()` and
720
+ `reply()` (`rejectReason`, `forwards`, `replies`); `traceItem(overrides?)`
721
+ builds a `TraceItem`.
722
+ - `close()` cancels response bodies a test never read, waits for background
723
+ work (`waitUntil`) and closes the application.
724
+
725
+ The subpath is not part of any Worker bundle: import it from tests only.
395
726
 
396
727
  ## Development
397
728
 
@@ -407,13 +738,12 @@ The Workers suite uses real KV, D1, R2, WebSockets, SQLite Durable Objects, and
407
738
  cold event dispatch. See the [security guide](https://github.com/velajs/vela/blob/main/docs/cloudflare-security.md) for trusted identity,
408
739
  URL signing, and WebSocket boundaries.
409
740
 
410
- ### Asynchronous response caches
741
+ ### KV caches
411
742
 
412
- `KVCacheStore` works directly in core `ResponseCacheModule` or as a tier beneath
413
- `TieredCacheStore`. The adapter retains absolute logical expiry in KV metadata;
414
- KV's minimum physical retention does not extend the requested TTL. For optional
415
- generic tags/scoped invalidation, configure `KVCacheInvalidationStore` with a
416
- separate dedicated KV namespace without TTLs or lifecycle cleanup. It is eventually
743
+ `kvCache` works directly as `CacheModule`'s store or, through `KVCacheStore`, as
744
+ a tier beneath `TieredCacheStore`. The adapter retains absolute logical expiry in
745
+ KV metadata; KV's minimum physical retention does not extend the requested TTL.
746
+ For tags and scoped invalidation, configure `kvCacheInvalidation` with a separate
747
+ dedicated KV namespace without TTLs or lifecycle cleanup. It is eventually
417
748
  consistent, including concurrent writes and cached negative reads, and does not
418
- promise globally strong invalidation. Construct both in an environment-injected
419
- factory. See the [caching guide](../../docs/caching.md).
749
+ promise globally strong invalidation. See the [caching guide](../../docs/caching.md).
@@ -0,0 +1,93 @@
1
+ import { defineBinding } from "@velajs/vela/module-kit";
2
+ //#region src/bindings.ts
3
+ /** Whether a value exposes every named operation as a function. */
4
+ function hasOperations(value, operations) {
5
+ if (typeof value !== "object" || value === null) return false;
6
+ return operations.every((operation) => typeof Reflect.get(value, operation) === "function");
7
+ }
8
+ /**
9
+ * Name-based Workers binding factories. Each takes `{ binding }`, the name
10
+ * declared in the Wrangler configuration, and returns a reference that reads
11
+ * and validates the native binding from an application's `ENV` when called.
12
+ * Declaring one reads no environment, so references belong in static module
13
+ * options: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.
14
+ */
15
+ /** A KV namespace declared under `kv_namespaces`. */
16
+ const KV_NAMESPACE = {
17
+ name: "KV namespace",
18
+ configKey: "kv_namespaces",
19
+ accepts: (value) => hasOperations(value, [
20
+ "get",
21
+ "put",
22
+ "delete",
23
+ "list",
24
+ "getWithMetadata"
25
+ ])
26
+ };
27
+ const kv = /* @__PURE__ */ defineBinding(KV_NAMESPACE);
28
+ /** An R2 bucket declared under `r2_buckets`. */
29
+ const R2_BUCKET = {
30
+ name: "R2 bucket",
31
+ configKey: "r2_buckets",
32
+ accepts: (value) => hasOperations(value, [
33
+ "get",
34
+ "put",
35
+ "head",
36
+ "delete",
37
+ "list",
38
+ "createMultipartUpload"
39
+ ])
40
+ };
41
+ const r2 = /* @__PURE__ */ defineBinding(R2_BUCKET);
42
+ /** A D1 database declared under `d1_databases`. */
43
+ const D1_DATABASE = {
44
+ name: "D1 database",
45
+ configKey: "d1_databases",
46
+ accepts: (value) => hasOperations(value, [
47
+ "prepare",
48
+ "batch",
49
+ "exec"
50
+ ])
51
+ };
52
+ const d1 = /* @__PURE__ */ defineBinding(D1_DATABASE);
53
+ /** A queue producer declared under `queues.producers`. */
54
+ const QUEUE_PRODUCER = {
55
+ name: "queue producer",
56
+ configKey: "queues.producers",
57
+ accepts: (value) => hasOperations(value, ["send"])
58
+ };
59
+ const queue = /* @__PURE__ */ defineBinding(QUEUE_PRODUCER);
60
+ /** A Durable Object namespace declared under `durable_objects.bindings`. */
61
+ const DURABLE_OBJECT_NAMESPACE = {
62
+ name: "Durable Object namespace",
63
+ configKey: "durable_objects.bindings",
64
+ accepts: (value) => hasOperations(value, ["idFromName", "get"])
65
+ };
66
+ const durableObject = /* @__PURE__ */ defineBinding(DURABLE_OBJECT_NAMESPACE);
67
+ /** A Workers Rate Limiting binding declared under `ratelimits`. */
68
+ const RATE_LIMITER = {
69
+ name: "rate limiter",
70
+ configKey: "ratelimits",
71
+ accepts: (value) => hasOperations(value, ["limit"])
72
+ };
73
+ const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);
74
+ /**
75
+ * A reference to a Workflow binding declared under `workflows`, whose
76
+ * instances take `Params`: for a class from `VelaWorkflow()`,
77
+ * `workflow<WorkflowParams<SignupWorkflow>>({ binding: 'SIGNUP_WORKFLOW' })`.
78
+ * Called with an application's ENV, it returns the native binding typed with
79
+ * those params: `await signups(env).create({ params: { email } })`. The
80
+ * runtime checks that the binding is a Workflow; its params are what the
81
+ * Workflow class declares.
82
+ */
83
+ function workflow(ref) {
84
+ return defineBinding({
85
+ name: "Workflow",
86
+ configKey: "workflows",
87
+ accepts: (value) => hasOperations(value, ["create", "get"])
88
+ })(ref);
89
+ }
90
+ //#endregion
91
+ export { D1_DATABASE, DURABLE_OBJECT_NAMESPACE, KV_NAMESPACE, QUEUE_PRODUCER, R2_BUCKET, RATE_LIMITER, d1, durableObject, kv, queue, r2, rateLimit, workflow };
92
+
93
+ //# sourceMappingURL=bindings.js.map