@velajs/cloudflare 1.10.1 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,29 +1,19 @@
1
- import { AsyncCacheStore, DynamicModule, InjectionToken, RuntimeAdapter, Type, VelaApplication } from "@velajs/vela";
2
- import { ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketServer, WsClient, WsDispatcher, WsException, WsMessage, WsResponse, WsServer } from "@velajs/vela/websocket";
3
- import { CommitStamp, CursorLog, LiveDriver, ResumeVerdict } from "@velajs/vela/live";
1
+ import { a as DoPitrId, c as DoPitrUnavailableError, d as isDoPitrUnavailable, f as readDoPitrBookmark, i as DoPitrBookmarkRead, l as VelaDoPitrRpc, n as DoPitrArmOptions, o as DoPitrNamespace, p as CloudflareRoot, r as DoPitrArmResult, s as DoPitrStorage, t as VelaNonceDurableObject, u as armDoPitr } from "./nonce.durable-object-Df3_42Sy.js";
2
+ import { AsyncCacheStore, DynamicModule, InjectionToken, NonceStore, RuntimeAdapter, ThrottlerStore, Type, VelaApplication, VelaMiddlewareHandler, VelaSecurityOptions } from "@velajs/vela";
3
+ import { BroadcastCommand, ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketGatewayOptions, WebSocketServer, WsClient, WsDispatcher, WsException, WsMessage, WsResponse, WsServer } from "@velajs/vela/websocket";
4
4
  import { DownloadResult, PresignMethod, PresignedUrlResult, StorageBody, StorageDriver, UploadOptions, UploadResult } from "@velajs/vela/storage";
5
- import { DurableObject } from "cloudflare:workers";
6
- import { Context, Hono, MiddlewareHandler } from "hono";
5
+ import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveEngine, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
6
+ import { Context, ExecutionContext } from "hono";
7
7
  import { FeatureFlagDriver, FlagContext } from "@velajs/feature-flags";
8
+ //#region src/websocket/room-id.d.ts
9
+ /** Stable, collision-free Durable Object name for one gateway's room. */
10
+ export declare function durableObjectRoomName(gatewayPath: string, roomId: string): string;
11
+ //#endregion
8
12
  //#region src/websocket/websocket-routing.d.ts
9
13
  interface WsGatewayRoute {
10
14
  path: string;
11
15
  binding: string;
12
- }
13
- //#endregion
14
- //#region src/types.d.ts
15
- interface CloudflareEnv {
16
- [key: string]: unknown;
17
- }
18
- interface ScheduledRegistration {
19
- instance: unknown;
20
- methodName: string;
21
- cron: string;
22
- }
23
- interface QueueRegistration {
24
- instance: unknown;
25
- methodName: string;
26
- queueName: string;
16
+ options: WebSocketGatewayOptions;
27
17
  }
28
18
  //#endregion
29
19
  //#region src/cloudflare-application.d.ts
@@ -46,7 +36,7 @@ type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
46
36
  *
47
37
  * @example
48
38
  * ```ts
49
- * const app = await createCloudflareApp(AppModule);
39
+ * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
50
40
  * export default {
51
41
  * fetch: app.fetch,
52
42
  * scheduled: app.scheduled.bind(app),
@@ -57,32 +47,34 @@ type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
57
47
  * @example
58
48
  * ```ts
59
49
  * // Serve OpenAPI docs alongside your routes
60
- * const app = await createCloudflareApp(AppModule);
50
+ * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
61
51
  * const document = createOpenApiDocument(AppModule);
62
52
  * app.mountOpenApi({ document, ui: 'scalar' });
63
53
  * // GET /openapi.json -> JSON document
64
54
  * // GET /scalar -> Scalar UI (loads from CDN)
65
55
  * ```
66
56
  */
67
- declare class CloudflareApplication {
57
+ export declare class CloudflareApplication<T extends object = object> {
68
58
  private app;
59
+ readonly env: T;
69
60
  private wsGatewayRoutes;
70
- constructor(app: VelaApplication);
71
- get fetch(): Hono['fetch'];
72
- getHonoApp(): Hono;
61
+ constructor(app: VelaApplication, env: T);
62
+ readonly fetch: (request: Request, env: T, ctx?: ExecutionContext) => Promise<Response>;
63
+ getHonoApp(): ReturnType<VelaApplication['getHonoApp']>;
73
64
  /**
74
65
  * Resolve a provider from the application's DI container (delegates to
75
66
  * `VelaApplication.get`). Handy for grabbing a service — e.g. an auth service —
76
- * to use inside `createCloudflareApp({ middleware: [...] })` request middleware,
67
+ * to use inside `createCloudflareApp({ middleware: env => [...] })` request middleware,
77
68
  * which runs outside the DI request pipeline.
78
69
  *
79
70
  * @example
80
71
  * ```ts
81
- * const app = await createCloudflareApp(AppModule);
82
- * const auth = app.get<BetterAuthService>(BetterAuthService);
72
+ * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
73
+ * const auth = app.get(BetterAuthService);
83
74
  * ```
84
75
  */
85
- get<T>(token: Parameters<VelaApplication['get']>[0]): T;
76
+ readonly get: VelaApplication['get'];
77
+ get entrypoints(): VelaApplication['entrypoints'];
86
78
  /**
87
79
  * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the
88
80
  * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,
@@ -94,7 +86,7 @@ declare class CloudflareApplication {
94
86
  * ```ts
95
87
  * import { createOpenApiDocument } from '@velajs/vela';
96
88
  *
97
- * const app = await createCloudflareApp(AppModule);
89
+ * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
98
90
  * const document = createOpenApiDocument(AppModule, {
99
91
  * info: { title: 'My API', version: '1.0.0' },
100
92
  * });
@@ -122,7 +114,7 @@ declare class CloudflareApplication {
122
114
  scheduled(event: {
123
115
  cron: string;
124
116
  scheduledTime?: number;
125
- }, env: CloudflareEnv, ctx: {
117
+ }, env: T, ctx: {
126
118
  waitUntil: (promise: Promise<unknown>) => void;
127
119
  }): Promise<void>;
128
120
  /**
@@ -142,165 +134,57 @@ declare class CloudflareApplication {
142
134
  */
143
135
  queue(batch: {
144
136
  queue: string;
145
- messages: unknown[];
146
- }, env: CloudflareEnv, ctx: {
137
+ messages: readonly unknown[];
138
+ }, env: T, ctx: {
147
139
  waitUntil: (promise: Promise<unknown>) => void;
148
140
  }): Promise<void>;
149
141
  close(signal?: string): Promise<void>;
150
142
  }
151
143
  //#endregion
152
144
  //#region src/cloudflare-factory.d.ts
153
- /**
154
- * Options for {@link createCloudflareApp}.
155
- *
156
- * Mirrors a tight subset of vela's `BootstrapOptions` — only the surface
157
- * that makes sense for a Workers consumer is re-exposed.
158
- */
159
- interface CreateCloudflareAppOptions {
160
- /**
161
- * Forwarded to `VelaFactory.create({ globalPrefix })`. Prepended to every
162
- * route registered by `@Controller(...)` (and any other route emitter)
163
- * inside the application, so a value of `'/v1'` turns `@Controller('/users')`
164
- * into `/v1/users`.
165
- *
166
- * @example
167
- * ```ts
168
- * const app = await createCloudflareApp(AppModule, { globalPrefix: '/v1' });
169
- * ```
170
- */
145
+ interface CloudflareWorkerOptions<T extends object> {
146
+ /** Global typed DI token for the platform's native environment. */
147
+ envToken: InjectionToken<T>;
171
148
  globalPrefix?: string;
172
- /**
173
- * Extra Hono middleware to register on the underlying Hono app. Runs
174
- * AFTER the one-time binding-init middleware this adapter mounts
175
- * internally, so any handler in `middleware` can safely read from
176
- * `BindingRef` instances and Cloudflare env bindings.
177
- *
178
- * @example
179
- * ```ts
180
- * const app = await createCloudflareApp(AppModule, {
181
- * middleware: [
182
- * async (c, next) => {
183
- * c.set('requestId', crypto.randomUUID());
184
- * await next();
185
- * },
186
- * ],
187
- * });
188
- * ```
189
- */
190
- middleware?: MiddlewareHandler[];
191
- }
192
- /**
193
- * Create a Cloudflare Workers application.
194
- *
195
- * Sets up a one-time Hono middleware that captures `c.env` on the first
196
- * request and initializes all configured binding refs. Optional
197
- * {@link CreateCloudflareAppOptions} are forwarded to the underlying
198
- * `VelaFactory.create` so consumers don't have to wrap the resulting
199
- * application in an outer Hono just to set a `globalPrefix` or attach
200
- * extra request middleware.
201
- *
202
- * @example
203
- * ```ts
204
- * // Minimal — backwards compatible
205
- * const app = await createCloudflareApp(AppModule);
206
- * export default app; // has .fetch, .scheduled, .queue
207
- * ```
208
- *
209
- * @example
210
- * ```ts
211
- * // With a global prefix and outer middleware
212
- * const app = await createCloudflareApp(AppModule, {
213
- * globalPrefix: '/v1',
214
- * middleware: [
215
- * async (c, next) => {
216
- * c.set('tenantId', c.req.header('x-tenant-id') ?? 'public');
217
- * await next();
218
- * },
219
- * ],
220
- * });
221
- * ```
222
- */
149
+ security?: VelaSecurityOptions;
150
+ /** Build request middleware from the same typed native environment as DI. */
151
+ middleware?: (env: NoInfer<T>) => VelaMiddlewareHandler[];
152
+ }
153
+ interface CreateCloudflareAppOptions<T extends object> extends CloudflareWorkerOptions<T> {
154
+ /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */
155
+ env: NoInfer<T>;
156
+ }
157
+ /** Bind an application to one environment before provider factories and lifecycle hooks. */
158
+ export declare function cloudflareAdapter<T extends object>(options: CreateCloudflareAppOptions<T>): RuntimeAdapter;
159
+ /** Build an application for one native Workers environment. Call inside a platform event. */
160
+ export declare function createCloudflareApp<T extends object>(rootModule: CloudflareRoot<NoInfer<T>>, options: CreateCloudflareAppOptions<T>): Promise<CloudflareApplication<T>>;
223
161
  /**
224
- * The Cloudflare platform binding as a vela {@link RuntimeAdapter}: a one-time
225
- * request middleware captures `c.env` on the first request and initializes
226
- * every `BindingRef`/`EnvRef` (collected at `onBootstrap`, before any request
227
- * can arrive). Adapter `requestMiddleware` is prepended to the global chain by
228
- * `VelaFactory.create`, so user middleware can safely read binding refs.
229
- *
230
- * Exposed so consumers composing `VelaFactory.create` themselves can opt in:
231
- *
232
- * ```ts
233
- * const app = await VelaFactory.create(AppModule, { adapters: [cloudflareAdapter()] });
234
- * ```
162
+ * Worker entrypoint with one bootstrap per environment identity. Weak keys let
163
+ * obsolete environments and secrets be collected. Concurrent cold events share
164
+ * construction; failed construction is evicted so the next event can retry.
235
165
  */
236
- declare function cloudflareAdapter(): RuntimeAdapter;
237
- declare function createCloudflareApp(rootModule: Type, options?: CreateCloudflareAppOptions): Promise<CloudflareApplication>;
238
- //#endregion
239
- //#region src/binding-ref.d.ts
240
- declare class BindingRef<T = unknown> {
241
- readonly bindingName: string;
242
- private _value;
243
- constructor(bindingName: string);
244
- get value(): T;
245
- /** @internal — called by createCloudflareApp middleware */
246
- _initialize(value: T): void;
247
- }
248
- //#endregion
249
- //#region src/modules/create-binding-module.d.ts
250
- interface BindingModuleStatic {
251
- forRoot(options: {
252
- binding: string;
253
- }): DynamicModule;
254
- }
255
- //#endregion
256
- //#region src/modules/kv.module.d.ts
257
- declare const KVModule: BindingModuleStatic;
258
- //#endregion
259
- //#region src/modules/d1.module.d.ts
260
- declare const D1Module: BindingModuleStatic;
261
- //#endregion
262
- //#region src/modules/r2.module.d.ts
263
- declare const R2Module: BindingModuleStatic;
264
- //#endregion
265
- //#region src/modules/queue.module.d.ts
266
- declare const QueueModule: BindingModuleStatic;
267
- //#endregion
268
- //#region src/modules/durable-object.module.d.ts
269
- declare const DurableObjectModule: BindingModuleStatic;
270
- //#endregion
271
- //#region src/modules/ai.module.d.ts
272
- declare const AIModule: BindingModuleStatic;
273
- //#endregion
274
- //#region src/modules/vectorize.module.d.ts
275
- declare const VectorizeModule: BindingModuleStatic;
276
- //#endregion
277
- //#region src/modules/hyperdrive.module.d.ts
278
- declare const HyperdriveModule: BindingModuleStatic;
279
- //#endregion
280
- //#region src/modules/env.module.d.ts
281
- /**
282
- * Provides {@link EnvService} GLOBALLY so any module's provider factories can
283
- * `inject: [EnvService]`. Register once on the root module:
284
- *
285
- * ```ts
286
- * @Module({ imports: [EnvModule.forRoot(), AuthModule.forRootAsync({ ... })] })
287
- * class AppModule {}
288
- * ```
289
- *
290
- * The {@link EnvRef} it provides is collected and initialized by
291
- * createCloudflareApp's binding-init middleware on the first request (the
292
- * factory passes it the full `env`, not a single binding).
293
- */
294
- declare class EnvModule {
295
- static forRoot(): DynamicModule;
296
- }
166
+ export declare function createCloudflareWorker<T extends object>(rootModule: CloudflareRoot<NoInfer<T>>, options: CloudflareWorkerOptions<T>): {
167
+ fetch(request: Request, env: T, ctx: ExecutionContext): Promise<Response>;
168
+ scheduled(event: {
169
+ cron: string;
170
+ scheduledTime?: number;
171
+ }, env: T, ctx: {
172
+ waitUntil: (promise: Promise<unknown>) => void;
173
+ }): Promise<void>;
174
+ queue(batch: {
175
+ queue: string;
176
+ messages: readonly unknown[];
177
+ }, env: T, ctx: {
178
+ waitUntil: (promise: Promise<unknown>) => void;
179
+ }): Promise<void>;
180
+ };
297
181
  //#endregion
298
182
  //#region src/storage/storage.types.d.ts
299
183
  /** A named storage disk backed by an R2 bucket binding. */
300
184
  interface DiskConfig {
301
185
  disk: string;
302
- /** R2Bucket binding name from wrangler.toml. */
303
- binding: string;
186
+ /** Native bucket supplied by a typed environment provider factory. */
187
+ bucket: R2Bucket;
304
188
  /** Optional root prefix; supports path-template tokens ({date}/{year}/…). */
305
189
  root?: string;
306
190
  }
@@ -309,6 +193,8 @@ interface PresignedUrlConfig {
309
193
  maxExpiry: number;
310
194
  }
311
195
  interface StorageModuleOptions {
196
+ /** HMAC secret used for signed downloads. */
197
+ secret?: string;
312
198
  disks: DiskConfig[];
313
199
  defaultDisk: string;
314
200
  presignedUrl?: PresignedUrlConfig;
@@ -318,50 +204,7 @@ interface StorageModuleOptions {
318
204
  declare const ConfigurableModuleClass: import("@velajs/vela").ConfigurableModuleClassType<StorageModuleOptions, "forRoot", "create", {
319
205
  isGlobal?: boolean;
320
206
  }>;
321
- declare class StorageModule extends ConfigurableModuleClass {}
322
- //#endregion
323
- //#region src/env-ref.d.ts
324
- /**
325
- * Holds the entire Cloudflare Worker `env` record (bindings + vars/secrets),
326
- * not a single binding. Subclasses {@link BindingRef} so createCloudflareApp's
327
- * binding-init middleware collects and initializes it through the same path;
328
- * the factory special-cases it to pass the full `env` instead of one binding.
329
- */
330
- declare class EnvRef extends BindingRef<Record<string, unknown>> {
331
- constructor();
332
- }
333
- //#endregion
334
- //#region src/services/env.service.d.ts
335
- /**
336
- * Injectable access to the full Cloudflare Worker `env` (bindings + vars +
337
- * secrets).
338
- *
339
- * The per-binding services (`D1Service`, `KVService`, …) each expose a single
340
- * binding, and the `@Env()` param decorator only works inside a request-scoped
341
- * controller handler. `EnvService` fills the gap: it can be injected into
342
- * PROVIDER FACTORIES — e.g. `SomeModule.forRootAsync({ inject: [EnvService] })`
343
- * — so a factory can read secrets/origins without reaching for the request.
344
- *
345
- * Reads are lazy. `env` only exists per request, so a factory (which runs at
346
- * bootstrap) must capture the `EnvService` and read inside its callback:
347
- *
348
- * ```ts
349
- * AuthModule.forRootAsync({
350
- * inject: [EnvService],
351
- * useFactory: (env: EnvService) => buildAuth(() => env.get<string>('AUTH_SECRET')),
352
- * });
353
- * ```
354
- *
355
- * Reading eagerly at bootstrap (`env.get(...)` before any request) throws.
356
- */
357
- declare class EnvService {
358
- private ref;
359
- constructor(ref: EnvRef);
360
- /** The full env record. Throws if read before the first request. */
361
- get env(): Record<string, unknown>;
362
- /** Read a single env entry (binding, var, or secret) by name. */
363
- get<T = unknown>(key: string): T | undefined;
364
- }
207
+ export declare class StorageModule extends ConfigurableModuleClass {}
365
208
  //#endregion
366
209
  //#region src/storage/r2-storage.driver.d.ts
367
210
  interface R2StorageDriverConfig {
@@ -371,7 +214,7 @@ interface R2StorageDriverConfig {
371
214
  secret?: string;
372
215
  }
373
216
  /** {@link StorageDriver} over a Cloudflare R2 bucket. */
374
- declare class R2StorageDriver implements StorageDriver {
217
+ export declare class R2StorageDriver implements StorageDriver {
375
218
  private readonly config;
376
219
  constructor(config: R2StorageDriverConfig);
377
220
  upload(body: StorageBody, path: string, options: UploadOptions): Promise<UploadResult>;
@@ -382,15 +225,9 @@ declare class R2StorageDriver implements StorageDriver {
382
225
  }
383
226
  //#endregion
384
227
  //#region src/storage/storage-manager.service.d.ts
385
- /**
386
- * Resolves R2 buckets by binding NAME (via {@link EnvService}) so multiple disks
387
- * coexist without registering N R2Modules. Drivers are created per call — cheap,
388
- * and avoids caching a per-request env value on this singleton.
389
- */
390
- declare class StorageManagerService {
228
+ export declare class StorageManagerService {
391
229
  private readonly options;
392
- private readonly env;
393
- constructor(options: StorageModuleOptions, env: EnvService);
230
+ constructor(options: StorageModuleOptions);
394
231
  hasDisk(disk: string): boolean;
395
232
  getDiskConfig(disk: string): DiskConfig;
396
233
  getDriver(disk: string): R2StorageDriver;
@@ -401,7 +238,7 @@ declare class StorageManagerService {
401
238
  * Multi-disk storage facade. Applies each disk's (templated) root, resolves the
402
239
  * driver, and validates presign expiry. Injectable anywhere via `StorageService`.
403
240
  */
404
- declare class StorageService {
241
+ export declare class StorageService {
405
242
  private readonly options;
406
243
  private readonly manager;
407
244
  constructor(options: StorageModuleOptions, manager: StorageManagerService);
@@ -420,105 +257,39 @@ declare class StorageService {
420
257
  * Presign-proxy: serves objects for HMAC-signed URLs produced by
421
258
  * `StorageService.url()`. R2 has no native presign, so a signed URL points here;
422
259
  * this route verifies the signature (+expiry) before streaming the object.
423
- * The wildcard is the FULL object path (root already applied at sign time), so
424
- * it is passed straight to the driver.
260
+ * The FULL object key (root already applied at sign time) is carried as an
261
+ * opaque base64url query claim. The signature is verified before the claim is
262
+ * decoded exactly once and checked against the configured disk root.
425
263
  */
426
- declare class StorageController {
264
+ export declare class StorageController {
427
265
  private readonly manager;
428
- private readonly env;
429
- constructor(manager: StorageManagerService, env: EnvService);
266
+ private readonly options;
267
+ constructor(manager: StorageManagerService, options: StorageModuleOptions);
430
268
  download(c: Context): Promise<Response>;
431
269
  }
432
270
  //#endregion
433
271
  //#region src/storage/storage.tokens.d.ts
434
- declare const STORAGE_OPTIONS: InjectionToken<StorageModuleOptions>;
435
- //#endregion
436
- //#region src/services/kv.service.d.ts
437
- /**
438
- * Wrapper around a Cloudflare KV namespace binding.
439
- * Use `kv.namespace.get(...)`, `kv.namespace.put(...)`, etc. — the namespace
440
- * is the standard @cloudflare/workers-types `KVNamespace`.
441
- */
442
- declare class KVService {
443
- private ref;
444
- constructor(ref: BindingRef<KVNamespace>);
445
- get namespace(): KVNamespace;
446
- }
272
+ export declare const STORAGE_OPTIONS: InjectionToken<StorageModuleOptions>;
447
273
  //#endregion
448
274
  //#region src/services/kv-cache.store.d.ts
449
275
  /**
450
276
  * Cloudflare KV-backed {@link CacheStore}. Values are JSON-encoded. Intended as
451
277
  * the slow tier under a `TieredCacheStore` (memory L1 → KV L2), but usable
452
- * standalone as `CacheModule.forRootAsync({ inject: [KVService], useFactory: (kv) => ({ store: new KVCacheStore(kv) }) })`.
278
+ * standalone from a typed environment factory: `new KVCacheStore(env.CACHE)`.
279
+ * Reads return unknown JSON; validate values at the consuming boundary.
453
280
  *
454
281
  * Note: Cloudflare KV requires `expirationTtl >= 60s`, so sub-minute TTLs are
455
282
  * clamped up. Keep short TTLs on the memory tier; use KV for longer-lived entries.
456
283
  */
457
- declare class KVCacheStore implements AsyncCacheStore {
458
- private readonly kv;
459
- constructor(kv: KVService);
460
- private get ns();
461
- get<T = unknown>(key: string): Promise<T | undefined>;
462
- set<T = unknown>(key: string, value: T, ttl?: number): Promise<void>;
284
+ export declare class KVCacheStore implements AsyncCacheStore {
285
+ private readonly ns;
286
+ constructor(ns: KVNamespace);
287
+ get(key: string): Promise<unknown>;
288
+ set(key: string, value: unknown, ttl?: number): Promise<void>;
463
289
  del(key: string): Promise<void>;
464
290
  clear(): Promise<void>;
465
291
  }
466
292
  //#endregion
467
- //#region src/services/d1.service.d.ts
468
- declare class D1Service {
469
- private ref;
470
- constructor(ref: BindingRef<D1Database>);
471
- get database(): D1Database;
472
- }
473
- //#endregion
474
- //#region src/services/r2.service.d.ts
475
- declare class R2Service {
476
- private ref;
477
- constructor(ref: BindingRef<R2Bucket>);
478
- get bucket(): R2Bucket;
479
- }
480
- //#endregion
481
- //#region src/services/queue.service.d.ts
482
- declare class QueueService<Body = unknown> {
483
- private ref;
484
- constructor(ref: BindingRef<Queue<Body>>);
485
- get queue(): Queue<Body>;
486
- }
487
- //#endregion
488
- //#region src/services/durable-object.service.d.ts
489
- declare class DurableObjectService {
490
- private ref;
491
- constructor(ref: BindingRef<DurableObjectNamespace>);
492
- get namespace(): DurableObjectNamespace;
493
- }
494
- //#endregion
495
- //#region src/services/ai.service.d.ts
496
- declare class AIService {
497
- private ref;
498
- constructor(ref: BindingRef<Ai>);
499
- get binding(): Ai;
500
- }
501
- //#endregion
502
- //#region src/services/vectorize.service.d.ts
503
- declare class VectorizeService {
504
- private ref;
505
- constructor(ref: BindingRef<VectorizeIndex>);
506
- get index(): VectorizeIndex;
507
- }
508
- //#endregion
509
- //#region src/services/hyperdrive.service.d.ts
510
- declare class HyperdriveService {
511
- private ref;
512
- constructor(ref: BindingRef<Hyperdrive>);
513
- get binding(): Hyperdrive;
514
- get connectionString(): string;
515
- get host(): string;
516
- get port(): number;
517
- get user(): string;
518
- get password(): string;
519
- get database(): string;
520
- }
521
- //#endregion
522
293
  //#region src/services/flagship-flag.driver.d.ts
523
294
  /**
524
295
  * The subset of a Cloudflare **Flagship** binding this driver evaluates against
@@ -532,7 +303,7 @@ interface FlagshipBinding {
532
303
  getBooleanValue(key: string, defaultValue: boolean, context?: FlagContext): Promise<boolean>;
533
304
  getStringValue(key: string, defaultValue: string, context?: FlagContext): Promise<string>;
534
305
  getNumberValue(key: string, defaultValue: number, context?: FlagContext): Promise<number>;
535
- getObjectValue<T extends object>(key: string, defaultValue: T, context?: FlagContext): Promise<T>;
306
+ getObjectValue(key: string, defaultValue: object, context?: FlagContext): Promise<unknown>;
536
307
  }
537
308
  interface FlagshipFlagDriverOptions {
538
309
  /** Driver name used for `use(name)` / default-driver selection. Default `"flagship"`. */
@@ -548,16 +319,12 @@ interface FlagshipFlagDriverOptions {
548
319
  * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns
549
320
  * the never-throw guarantee.
550
321
  *
551
- * The binding only exists per request in a Worker, so pass a lazy accessor when
552
- * wiring from a bootstrap factory (mirroring how {@link EnvService} reads are
553
- * deferred); a resolved binding may be passed directly in tests.
322
+ * Build the driver inside a provider factory with the native environment:
554
323
  *
555
324
  * ```ts
556
325
  * FeatureFlagsModule.forRootAsync({
557
- * inject: [EnvService],
558
- * useFactory: (env: EnvService) => ({
559
- * drivers: [flagshipFlagDriver(() => env.get<FlagshipBinding>('FLAGS')!)],
560
- * }),
326
+ * inject: [ENV],
327
+ * useFactory: (env: WorkerEnv) => ({ drivers: [flagshipFlagDriver(env.FLAGS)] }),
561
328
  * });
562
329
  * ```
563
330
  *
@@ -565,17 +332,17 @@ interface FlagshipFlagDriverOptions {
565
332
  * Stratal feature-flags service (MIT, © Temitayo Fadojutimi), reshaped as a
566
333
  * bare driver.
567
334
  */
568
- declare class FlagshipFlagDriver implements FeatureFlagDriver {
335
+ export declare class FlagshipFlagDriver implements FeatureFlagDriver {
569
336
  readonly name: string;
570
337
  private readonly resolve;
571
338
  constructor(binding: FlagshipBinding | (() => FlagshipBinding), options?: FlagshipFlagDriverOptions);
572
339
  getBoolean(key: string, fallback: boolean, ctx?: FlagContext): Promise<boolean>;
573
340
  getString(key: string, fallback: string, ctx?: FlagContext): Promise<string>;
574
341
  getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number>;
575
- getObject<T extends object>(key: string, fallback: T, ctx?: FlagContext): Promise<T>;
342
+ getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown>;
576
343
  }
577
344
  /** Convenience factory for {@link FlagshipFlagDriver}. */
578
- declare function flagshipFlagDriver(binding: FlagshipBinding | (() => FlagshipBinding), options?: FlagshipFlagDriverOptions): FlagshipFlagDriver;
345
+ export declare function flagshipFlagDriver(binding: FlagshipBinding | (() => FlagshipBinding), options?: FlagshipFlagDriverOptions): FlagshipFlagDriver;
579
346
  //#endregion
580
347
  //#region src/services/kv-flag.driver.d.ts
581
348
  interface KvFlagDriverOptions {
@@ -596,25 +363,24 @@ interface KvFlagDriverOptions {
596
363
  * guarantee lives in `@velajs/feature-flags`'s service layer.
597
364
  *
598
365
  * Placed like {@link KVCacheStore}: construct it in a wiring factory over a
599
- * resolved {@link KVService}.
366
+ * resolved {@link KVNamespace}.
600
367
  *
601
368
  * ```ts
602
369
  * FeatureFlagsModule.forRootAsync({
603
- * inject: [KVService],
604
- * useFactory: (kv: KVService) => ({ drivers: [new KvFlagDriver(kv, { prefix: 'flag:' })] }),
370
+ * inject: [ENV],
371
+ * useFactory: (env: WorkerEnv) => ({ drivers: [new KvFlagDriver(env.CACHE, { prefix: 'flag:' })] }),
605
372
  * });
606
373
  * ```
607
374
  */
608
- declare class KvFlagDriver implements FeatureFlagDriver {
609
- private readonly kv;
375
+ export declare class KvFlagDriver implements FeatureFlagDriver {
376
+ private readonly ns;
610
377
  readonly name: string;
611
378
  private readonly prefix;
612
- constructor(kv: KVService, options?: KvFlagDriverOptions);
613
- private get ns();
379
+ constructor(ns: KVNamespace, options?: KvFlagDriverOptions);
614
380
  getBoolean(key: string, fallback: boolean, _ctx?: FlagContext): Promise<boolean>;
615
381
  getString(key: string, fallback: string, _ctx?: FlagContext): Promise<string>;
616
382
  getNumber(key: string, fallback: number, _ctx?: FlagContext): Promise<number>;
617
- getObject<T extends object>(key: string, fallback: T, _ctx?: FlagContext): Promise<T>;
383
+ getObject(key: string, fallback: object, _ctx?: FlagContext): Promise<unknown>;
618
384
  /**
619
385
  * Reads and JSON-parses the (prefixed) key, returning the parsed value only
620
386
  * when `matches` accepts its type; otherwise the caller's fallback. A missing
@@ -623,7 +389,7 @@ declare class KvFlagDriver implements FeatureFlagDriver {
623
389
  private read;
624
390
  }
625
391
  /** Convenience factory for {@link KvFlagDriver}. */
626
- declare function kvFlagDriver(kv: KVService, options?: KvFlagDriverOptions): KvFlagDriver;
392
+ export declare function kvFlagDriver(kv: KVNamespace, options?: KvFlagDriverOptions): KvFlagDriver;
627
393
  //#endregion
628
394
  //#region src/decorators/env.d.ts
629
395
  /**
@@ -635,13 +401,13 @@ declare function kvFlagDriver(kv: KVService, options?: KvFlagDriverOptions): KvF
635
401
  * @example
636
402
  * ```ts
637
403
  * @Get()
638
- * handle(@Env() env: CloudflareEnv) { ... }
404
+ * handle(@Env() env: WorkerEnv) { ... }
639
405
  *
640
406
  * @Get()
641
407
  * handle(@Env('MY_KV') kv: KVNamespace) { ... }
642
408
  * ```
643
409
  */
644
- declare const Env: (data?: string | undefined, ...pipes: import("@velajs/vela").PipeType[]) => ParameterDecorator;
410
+ export declare const Env: (data?: string | undefined, ...pipes: import("@velajs/vela").PipeType[]) => ParameterDecorator;
645
411
  //#endregion
646
412
  //#region src/decorators/scheduled.d.ts
647
413
  interface ScheduledMetadata {
@@ -662,7 +428,7 @@ interface ScheduledMetadata {
662
428
  * }
663
429
  * ```
664
430
  */
665
- declare function Scheduled(cron: string): MethodDecorator;
431
+ export declare function Scheduled(cron: string): MethodDecorator;
666
432
  //#endregion
667
433
  //#region src/decorators/queue-consumer.d.ts
668
434
  interface QueueConsumerMetadata {
@@ -686,22 +452,7 @@ interface QueueConsumerMetadata {
686
452
  * }
687
453
  * ```
688
454
  */
689
- declare function QueueConsumer(queueName: string): MethodDecorator;
690
- //#endregion
691
- //#region src/websocket/websocket.durable-object.d.ts
692
- /**
693
- * Base class for the WebSocket Durable Object. The user exports a named subclass
694
- * (matching their `wrangler.toml` `class_name`) built from their `AppModule`:
695
- *
696
- * ```ts
697
- * export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}
698
- * ```
699
- *
700
- * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot
701
- * bridge DO hibernation) and forwards every event into the runtime-agnostic
702
- * `WsDispatcher` via {@link DoWebSocketHost}.
703
- */
704
- declare function VelaWebSocketDurableObject(rootModule: Type): new (ctx: DurableObjectState, env: Record<string, unknown>) => DurableObject<Record<string, unknown>>;
455
+ export declare function QueueConsumer(queueName: string): MethodDecorator;
705
456
  //#endregion
706
457
  //#region src/websocket/cloudflare-websocket.module.d.ts
707
458
  /**
@@ -711,11 +462,18 @@ declare function VelaWebSocketDurableObject(rootModule: Type): new (ctx: Durable
711
462
  * ctx-backed server per instance. `useClass` ensures a fresh holder per DI
712
463
  * container so colocated DO instances never share a server.
713
464
  */
714
- declare class CloudflareWebSocketModule {
465
+ export declare class CloudflareWebSocketModule {
715
466
  static forRoot(): DynamicModule;
716
467
  }
717
468
  //#endregion
718
469
  //#region src/websocket/broadcast.d.ts
470
+ interface WsBroadcastStub {
471
+ broadcast(cmd: BroadcastCommand): Promise<void>;
472
+ }
473
+ interface BroadcastNamespace {
474
+ idFromName(name: string): DurableObjectId;
475
+ get(id: DurableObjectId): WsBroadcastStub;
476
+ }
719
477
  /**
720
478
  * Push to a room from a Worker HTTP handler / cron / queue consumer (server-
721
479
  * initiated emit). Resolves the room's Durable Object and calls its `broadcast`
@@ -724,12 +482,13 @@ declare class CloudflareWebSocketModule {
724
482
  *
725
483
  * @example
726
484
  * ```ts
727
- * // In a controller — ns from DurableObjectService.namespace
728
- * await broadcastToRoom(ns, `org:${id}`, 'order.created', order);
485
+ * // In a controller — ns from the typed Worker environment
486
+ * await broadcastToRoom(ns, '/orgs/:orgId/ws', `org:${id}`, 'order.created', order);
729
487
  * ```
730
488
  */
731
- declare function broadcastToRoom(ns: DurableObjectNamespace, room: string, event: string, data?: unknown, options?: {
489
+ export declare function broadcastToRoom(ns: BroadcastNamespace, gatewayPath: string, room: string, event: string, data?: unknown, options?: {
732
490
  exceptIds?: string[];
491
+ maxFrameBytes?: number;
733
492
  }): Promise<void>;
734
493
  //#endregion
735
494
  //#region src/websocket/do-state.d.ts
@@ -756,7 +515,7 @@ interface SqlStorageLike {
756
515
  * invalidation to the room DO's log (one log scope per room, exactly the
757
516
  * protocol's model).
758
517
  */
759
- declare class DoCursorLog implements CursorLog {
518
+ export declare class DoCursorLog implements CursorLog {
760
519
  private readonly maxRows;
761
520
  private sql?;
762
521
  private epoch?;
@@ -769,37 +528,95 @@ declare class DoCursorLog implements CursorLog {
769
528
  private assertReady;
770
529
  }
771
530
  interface DurableObjectLiveOptions {
772
- /** The wrangler binding name of the WebSocket DO namespace (e.g. `'CHAT_ROOM'`). */
773
- binding: string;
531
+ /** Native, RPC-typed namespace supplied by the application's environment. */
532
+ namespace: LiveNamespace;
533
+ /** Exact `@WebSocketGateway()` path sharing this room/log namespace. */
534
+ gatewayPath: string;
774
535
  /** Room used when an invalidation names none. Matches the client default. */
775
536
  defaultRoom?: string;
776
537
  }
777
- interface CfLiveDriver extends LiveDriver {
778
- /** @internal — Worker isolate: capture `env` so the namespace binding resolves per dispatch. */
779
- _initializeEnv(env: Record<string, unknown>): void;
780
- /** @internal — DO isolate: deliver invalidations straight to this DO's engine. */
538
+ interface LiveInvalidateStub {
539
+ invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;
540
+ }
541
+ /** Only the native namespace operations required for live invalidation. */
542
+ interface LiveNamespace {
543
+ idFromName(name: string): DurableObjectId;
544
+ get(id: DurableObjectId): LiveInvalidateStub;
545
+ }
546
+ /** One driver per application; construct from a LiveModule driver factory. */
547
+ declare class CfLiveDriver implements LiveDriver {
548
+ private readonly options;
549
+ readonly kind = "durable-object";
550
+ private sink;
551
+ private localMode;
552
+ constructor(options: DurableObjectLiveOptions);
553
+ bind(sink: LiveInvalidationSink): void;
554
+ /** @internal — a DO dispatches to its own engine and SQLite log. */
781
555
  _setLocalMode(): void;
556
+ dispatch(cmd: InvalidationCommand): Promise<CommitStamp | undefined> | CommitStamp | undefined;
782
557
  }
783
- /**
784
- * The Cloudflare `LiveDriver`. Dual-mode, because the SAME app module
785
- * bootstraps in both isolates:
786
- *
787
- * - **Worker** (HTTP mutations, queue consumers, crons): route the command to
788
- * the room's Durable Object over the `invalidate` RPC — the same canonical
789
- * `roomToDurableId` mapping the upgrade route and `broadcastToRoom` use —
790
- * and return THAT log scope's commit stamp (what `Vela-Commit-Cursor`
791
- * must carry).
792
- * - **DO** (writes issued from inside the object): apply to the local engine.
793
- */
794
- declare function durableObjectLive(options: DurableObjectLiveOptions): CfLiveDriver;
558
+ /** Use in LiveModule.forRootAsync: driver: () => durableObjectLive({ namespace: env.ROOMS, ... }). */
559
+ export declare function durableObjectLive(options: DurableObjectLiveOptions): CfLiveDriver;
795
560
  /** Ergonomic alias: the log option for `LiveModule.forRoot` on Cloudflare. */
796
- declare function durableObjectCursorLog(maxRows?: number): DoCursorLog;
561
+ export declare function durableObjectCursorLog(maxRows?: number): DoCursorLog;
797
562
  /**
798
563
  * Invalidate live tags in a room from a Worker (controller / cron / queue
799
564
  * consumer) — the live sibling of `broadcastToRoom`. Returns the room log
800
565
  * scope's commit stamp for `Vela-Commit-Cursor` stamping.
801
566
  */
802
- declare function liveInvalidateToRoom(ns: DurableObjectNamespace, room: string, tags: string[]): Promise<CommitStamp | undefined>;
567
+ export declare function liveInvalidateToRoom(ns: LiveNamespace, gatewayPath: string, room: string, tags: string[]): Promise<CommitStamp | undefined>;
568
+ //#endregion
569
+ //#region src/rate-limit/cloudflare-rate-limit.store.d.ts
570
+ /** The deliberately small surface exposed by a Workers Rate Limiting binding. */
571
+ interface CloudflareRateLimitBinding {
572
+ limit(input: {
573
+ key: string;
574
+ }): Promise<{
575
+ success: boolean;
576
+ }>;
577
+ }
578
+ interface CloudflareRateLimitStoreOptions {
579
+ /** Must match the binding's configured `simple.limit`. */
580
+ limit: number;
581
+ /** Must match the binding's configured `simple.period`. */
582
+ periodSeconds: 10 | 60;
583
+ /** Bound attacker-influenced tracking keys before calling the platform. */
584
+ maxKeyBytes?: number;
585
+ }
586
+ /**
587
+ * Adapt a Cloudflare Workers Rate Limiting binding to Vela's throttler store.
588
+ *
589
+ * The platform binding makes the allow/deny decision. It does not expose exact
590
+ * counters or reset timestamps, so this adapter intentionally omits `remaining`.
591
+ */
592
+ export declare function cloudflareRateLimitStore(binding: CloudflareRateLimitBinding | (() => CloudflareRateLimitBinding), options: CloudflareRateLimitStoreOptions): ThrottlerStore;
593
+ //#endregion
594
+ //#region src/nonce/durable-object-nonce.store.d.ts
595
+ /** The generated Workers binding type for {@link VelaNonceDurableObject}. */
596
+ type DurableObjectNonceNamespace = DurableObjectNamespace<VelaNonceDurableObject>;
597
+ interface DurableObjectNonceStoreOptions {
598
+ /**
599
+ * Stable application/environment boundary (for example `billing-api:prod`).
600
+ * Claims are globally single-use inside this namespace and isolated from all
601
+ * other application namespaces. It must be non-empty, canonical, and at most
602
+ * 128 UTF-8 bytes.
603
+ */
604
+ appNamespace: string;
605
+ /**
606
+ * Resolve the Workers Durable Object namespace at claim time. The resolver is
607
+ * intentionally not cached so request-scoped env/binding references stay safe.
608
+ */
609
+ binding: () => DurableObjectNonceNamespace | Promise<DurableObjectNonceNamespace>;
610
+ }
611
+ /**
612
+ * Strict, cross-isolate {@link NonceStore} backed by one SQLite Durable Object
613
+ * per explicit application namespace.
614
+ *
615
+ * Invalid input, an unavailable/malformed binding, RPC failure, or a malformed
616
+ * RPC result all deny the claim (`false`). Only the literal boolean `true` from
617
+ * the Durable Object is accepted.
618
+ */
619
+ export declare function durableObjectNonceStore(options: DurableObjectNonceStoreOptions): NonceStore;
803
620
  //#endregion
804
- export { AIModule, AIService, type CfLiveDriver, CloudflareApplication, type CloudflareEnv, CloudflareWebSocketModule, ConnectedSocket, type CreateCloudflareAppOptions, D1Module, D1Service, type DiskConfig, DoCursorLog, type DurableObjectLiveOptions, DurableObjectModule, DurableObjectService, Env, EnvModule, EnvService, type FlagshipBinding, FlagshipFlagDriver, type FlagshipFlagDriverOptions, HyperdriveModule, HyperdriveService, KVCacheStore, KVModule, KVService, KvFlagDriver, type KvFlagDriverOptions, MessageBody, type MountOpenApiOptions, type OnGatewayConnection, type OnGatewayDisconnect, type OnGatewayInit, type PresignedUrlConfig, QueueConsumer, type QueueConsumerMetadata, QueueModule, type QueueRegistration, QueueService, R2Module, R2Service, R2StorageDriver, STORAGE_OPTIONS, Scheduled, type ScheduledMetadata, type ScheduledRegistration, StorageController, StorageManagerService, StorageModule, type StorageModuleOptions, StorageService, SubscribeMessage, VectorizeModule, VectorizeService, VelaWebSocketDurableObject, WebSocketGateway, WebSocketServer, type WsClient, WsException, type WsGatewayRoute, type WsMessage, type WsResponse, type WsServer, broadcastToRoom, cloudflareAdapter, createCloudflareApp, durableObjectCursorLog, durableObjectLive, flagshipFlagDriver, kvFlagDriver, liveInvalidateToRoom };
621
+ export { type BroadcastNamespace, type CfLiveDriver, type CloudflareRateLimitBinding, type CloudflareRateLimitStoreOptions, type CloudflareRoot, type CloudflareWorkerOptions, ConnectedSocket, type CreateCloudflareAppOptions, type DiskConfig, type DoPitrArmOptions, type DoPitrArmResult, type DoPitrBookmarkRead, type DoPitrId, type DoPitrNamespace, type DoPitrStorage, DoPitrUnavailableError, type DurableObjectLiveOptions, type DurableObjectNonceNamespace, type DurableObjectNonceStoreOptions, type FlagshipBinding, type FlagshipFlagDriverOptions, type KvFlagDriverOptions, type LiveNamespace, MessageBody, type MountOpenApiOptions, type OnGatewayConnection, type OnGatewayDisconnect, type OnGatewayInit, type PresignedUrlConfig, type QueueConsumerMetadata, type ScheduledMetadata, type StorageModuleOptions, SubscribeMessage, type VelaDoPitrRpc, WebSocketGateway, WebSocketServer, type WsClient, WsException, type WsGatewayRoute, type WsMessage, type WsResponse, type WsServer, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark };
805
622
  //# sourceMappingURL=index.d.ts.map