@velajs/cloudflare 1.24.0 → 1.29.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,9 +1,11 @@
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, CacheEntry, CacheEntryReader, CacheEntryWriter, CacheInvalidationStore, DynamicModule, InjectionToken, NonceStore, RuntimeAdapter, ThrottlerStore, Type, VelaApplication, VelaMiddlewareHandler, VelaSecurityOptions } from "@velajs/vela";
3
- import { BroadcastCommand, ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketGatewayOptions, WebSocketSendGate, WebSocketServer, WsClient, WsDispatcher, WsException, WsMessage, WsResponse, WsServer } from "@velajs/vela/websocket";
4
- import { DownloadResult, PresignMethod, PresignedUrlResult, StorageBody, StorageDriver, UploadOptions, UploadResult } from "@velajs/vela/storage";
1
+ import "./vela-env-DFvyoNT3.js";
2
+ 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-Df4CZi-0.js";
3
+ import { AsyncCacheStore, CacheEntry, CacheEntryReader, CacheEntryWriter, CacheInvalidationStore, DynamicModule, InjectionToken, NonceStore, RuntimeAdapter, ThrottlerStore, Type, VelaApplication, VelaEnv, VelaMiddlewareHandler, VelaSecurityOptions } from "@velajs/vela";
4
+ import { BroadcastCommand, ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, UpgradeAuthenticator, WebSocketGateway, WebSocketGatewayOptions, WebSocketSendGate, WebSocketServer, WebSocketUpgradeAuthenticationContext, WebSocketUpgradeIdentity, WsClient, WsDispatcher, WsException, WsMessage, WsResponse, WsServer } from "@velajs/vela/websocket";
5
5
  import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveEngine, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
6
+ import { DownloadResult, PresignMethod, PresignedUrlResult, StorageBody, StorageDriver, UploadOptions, UploadResult } from "@velajs/vela/storage";
6
7
  import { Context, ExecutionContext } from "hono";
8
+ import "@velajs/vela/internal";
7
9
  import { FeatureFlagDriver, FlagContext } from "@velajs/feature-flags";
8
10
  //#region src/websocket/room-id.d.ts
9
11
  /** Stable, collision-free Durable Object name for one gateway's room. */
@@ -14,8 +16,63 @@ interface WsGatewayRoute {
14
16
  path: string;
15
17
  binding: string;
16
18
  options: WebSocketGatewayOptions;
19
+ /** Container module that declares the gateway; its authenticator resolves from here. */
20
+ moduleId?: string;
17
21
  }
18
22
  //#endregion
23
+ //#region src/scheduled-event.d.ts
24
+ /**
25
+ * The event a Worker's `scheduled()` export receives. The native
26
+ * `ScheduledController` satisfies it; direct calls (tests, scripts) may omit
27
+ * `scheduledTime`, which then defaults to the current time, and `noRetry`.
28
+ */
29
+ interface ScheduledEvent {
30
+ readonly cron: string;
31
+ readonly scheduledTime?: number;
32
+ noRetry?(): void;
33
+ }
34
+ /** The Cloudflare trigger behind the current scheduled invocation. */
35
+ interface CloudflareScheduledEvent {
36
+ /** The trigger's exact cron string; it equals the invocation's `expression`. */
37
+ readonly cron: string;
38
+ /** The platform's scheduled time in Unix milliseconds. */
39
+ readonly scheduledTime: number;
40
+ /**
41
+ * Ask Cloudflare not to retry this trigger if the invocation fails. Already
42
+ * bound to the native controller, so it can be passed around or destructured.
43
+ * A no-op for direct calls that supplied no controller.
44
+ */
45
+ readonly noRetry: () => void;
46
+ }
47
+ /**
48
+ * Request-scoped Cloudflare view of the scheduled trigger, seeded into each
49
+ * `@Cron` job's invocation scope by the Cloudflare adapter. Inject it where a
50
+ * job needs platform controls such as `noRetry()`; the job's argument stays
51
+ * the portable `ScheduleInvocation`. It resolves only inside a scheduled
52
+ * invocation; resolving it anywhere else throws. A cron job fired on demand
53
+ * (Studio's run-now) receives a synthetic event: `cron` is the job's
54
+ * expression and `noRetry()` does nothing.
55
+ *
56
+ * The token provides itself as request-scoped in every container, so a class
57
+ * that injects it is request-scoped wherever the graph boots (a Worker, a
58
+ * Durable Object, the CLI or a testing module) and is built only for an
59
+ * invocation, never at bootstrap.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * @Injectable({ scope: Scope.REQUEST })
64
+ * class Reports {
65
+ * constructor(@Inject(CLOUDFLARE_SCHEDULED_EVENT) private readonly trigger: CloudflareScheduledEvent) {}
66
+ *
67
+ * @Cron('0 3 * * *', { dialect: 'cloudflare' })
68
+ * async nightly(tick: CronInvocation) {
69
+ * if (!(await this.upstreamAvailable(tick.signal))) this.trigger.noRetry();
70
+ * }
71
+ * }
72
+ * ```
73
+ */
74
+ export declare const CLOUDFLARE_SCHEDULED_EVENT: InjectionToken<CloudflareScheduledEvent>;
75
+ //#endregion
19
76
  //#region src/cloudflare-application.d.ts
20
77
  /**
21
78
  * Options accepted by {@link CloudflareApplication.mountOpenApi}.
@@ -28,15 +85,16 @@ type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
28
85
  /**
29
86
  * Wraps VelaApplication with Cloudflare-specific handlers:
30
87
  * - `fetch` — HTTP request handler (from Hono)
31
- * - `scheduled` — Cron trigger handler (matches `@Scheduled()` decorators
32
- * AND vela's own `@Cron()` jobs)
33
- * - `queue` — Queue consumer handler (matches `@QueueConsumer()` decorators)
88
+ * - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose
89
+ * expression is the trigger's exact string)
90
+ * - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,
91
+ * then `QueueModule`'s native consumer)
34
92
  * - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on
35
93
  * the underlying Hono app
36
94
  *
37
95
  * @example
38
96
  * ```ts
39
- * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
97
+ * const app = await createCloudflareApp(AppModule, { env });
40
98
  * export default {
41
99
  * fetch: app.fetch,
42
100
  * scheduled: app.scheduled.bind(app),
@@ -47,18 +105,18 @@ type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
47
105
  * @example
48
106
  * ```ts
49
107
  * // Serve OpenAPI docs alongside your routes
50
- * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
108
+ * const app = await createCloudflareApp(AppModule, { env });
51
109
  * const document = createOpenApiDocument(AppModule);
52
110
  * app.mountOpenApi({ document, ui: 'scalar' });
53
111
  * // GET /openapi.json -> JSON document
54
112
  * // GET /scalar -> Scalar UI (loads from CDN)
55
113
  * ```
56
114
  */
57
- export declare class CloudflareApplication<T extends object = object> {
115
+ export declare class CloudflareApplication {
58
116
  #private;
59
- readonly env: T;
60
- constructor(app: VelaApplication, env: T);
61
- readonly fetch: (request: Request, env: T, ctx?: ExecutionContext) => Promise<Response>;
117
+ readonly env: VelaEnv;
118
+ constructor(app: VelaApplication, env: VelaEnv);
119
+ readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext) => Promise<Response>;
62
120
  getHonoApp(): ReturnType<VelaApplication['getHonoApp']>;
63
121
  /**
64
122
  * Resolve a provider from the application's DI container (delegates to
@@ -68,7 +126,7 @@ export declare class CloudflareApplication<T extends object = object> {
68
126
  *
69
127
  * @example
70
128
  * ```ts
71
- * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
129
+ * const app = await createCloudflareApp(AppModule, { env });
72
130
  * const auth = app.get(BetterAuthService);
73
131
  * ```
74
132
  */
@@ -85,7 +143,7 @@ export declare class CloudflareApplication<T extends object = object> {
85
143
  * ```ts
86
144
  * import { createOpenApiDocument } from '@velajs/vela';
87
145
  *
88
- * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
146
+ * const app = await createCloudflareApp(AppModule, { env });
89
147
  * const document = createOpenApiDocument(AppModule, {
90
148
  * info: { title: 'My API', version: '1.0.0' },
91
149
  * });
@@ -104,75 +162,104 @@ export declare class CloudflareApplication<T extends object = object> {
104
162
  /** @internal — upgrade routes discovered from the application's gateways. */
105
163
  getWsGatewayRoutes(): WsGatewayRoute[];
106
164
  /**
107
- * Handle Cloudflare scheduled (cron) events.
108
- * Matches the event's cron expression to `@Scheduled()` and vela `@Cron()`
109
- * handlers read from `app.entrypoints`; each handler runs inside a fresh
110
- * request-scoped child (request-scoped providers rebuild per tick).
165
+ * Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose
166
+ * expression is exactly `event.cron` (the trigger string is compared as
167
+ * delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch
168
+ * primitive every runtime shares. Each job receives only its
169
+ * `ScheduleInvocation`, runs in a fresh invocation scope seeded with
170
+ * {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`
171
+ * dispatch. The trigger settles after every matching job and its managed
172
+ * work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.
111
173
  */
112
- scheduled(event: {
113
- cron: string;
114
- scheduledTime?: number;
115
- }, env: T, ctx: {
174
+ scheduled(event: ScheduledEvent, env: VelaEnv, _ctx?: {
116
175
  waitUntil: (promise: Promise<unknown>) => void;
117
176
  }): Promise<void>;
118
177
  /**
119
- * Run one entrypoint handler inside a fresh request scope, through the
120
- * shared guard → interceptor pipeline (components declared with
178
+ * Run one queue consumer inside a fresh request scope, through the shared
179
+ * guard → interceptor pipeline (components declared with
121
180
  * `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or
122
181
  * method). HTTP-global components deliberately do NOT apply — an HTTP auth
123
- * guard has no business rejecting a queue batch. Unclaimed errors rethrow
124
- * so the platform's retry semantics stay intact.
182
+ * guard has no business rejecting a queue batch. Unclaimed errors are
183
+ * reported once (`QueueModule`'s consumer reports its own) and rethrow so
184
+ * the platform's retry semantics stay intact.
125
185
  */
126
186
  private dispatchEntrypoint;
127
187
  /**
128
- * Handle Cloudflare Queue consumer events.
129
- * Matches the batch queue name to `@QueueConsumer()` handlers read from
130
- * `app.entrypoints`; each batch is processed inside a fresh request-scoped
131
- * child (request-scoped providers rebuild per batch — no boot-time captives).
188
+ * Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read
189
+ * from `app.entrypoints` claim a batch by its physical queue name and
190
+ * receive it whole. A batch no handler claims goes to `QueueModule`'s native
191
+ * consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which
192
+ * routes each job by its logical queue. Each dispatch runs inside a fresh
193
+ * request-scoped child (request-scoped providers rebuild per batch — no
194
+ * boot-time captives). A batch nothing claims rejects: resolving would let
195
+ * Cloudflare acknowledge every message implicitly.
132
196
  */
133
197
  queue(batch: {
134
198
  queue: string;
135
199
  messages: readonly unknown[];
136
- }, env: T, ctx: {
200
+ }, env: VelaEnv, ctx: {
137
201
  waitUntil: (promise: Promise<unknown>) => void;
138
202
  }): Promise<void>;
203
+ /**
204
+ * A raw `@QueueConsumer` owns its physical queue's batches and must not carry
205
+ * jobs of a queue registered with `QueueModule`: those reach their
206
+ * `@Processor` only if the raw handler dispatches them itself, while
207
+ * `cloudflareQueues()` delivers registered queues. Warn once per physical and
208
+ * logical queue (unless diagnostics are silent); the raw consumer still
209
+ * receives and settles the batch.
210
+ */
211
+ private warnRawJobs;
212
+ /**
213
+ * Abort the signals of scheduled jobs still running, wait for them and their
214
+ * managed work to settle, then close the application.
215
+ */
139
216
  close(signal?: string): Promise<void>;
140
217
  }
141
218
  //#endregion
142
219
  //#region src/cloudflare-factory.d.ts
143
- interface CloudflareWorkerOptions<T extends object> {
144
- /** Global typed DI token for the platform's native environment. */
145
- envToken: InjectionToken<T>;
220
+ interface CloudflareWorkerOptions {
146
221
  globalPrefix?: string;
147
222
  security?: VelaSecurityOptions;
148
- /** Build request middleware from the same typed native environment as DI. */
149
- middleware?: (env: NoInfer<T>) => VelaMiddlewareHandler[];
223
+ /** Build request middleware from the same native environment DI receives as ENV. */
224
+ middleware?: (env: VelaEnv) => VelaMiddlewareHandler[];
225
+ /** Further runtime adapters, composed after the Cloudflare adapter for each application. */
226
+ adapters?: RuntimeAdapter[];
150
227
  }
151
- interface CreateCloudflareAppOptions<T extends object> extends CloudflareWorkerOptions<T> {
228
+ interface CreateCloudflareAppOptions extends CloudflareWorkerOptions {
152
229
  /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */
153
- env: NoInfer<T>;
230
+ env: VelaEnv;
154
231
  }
155
- /** Bind an application to one environment before provider factories and lifecycle hooks. */
156
- export declare function cloudflareAdapter<T extends object>(options: CreateCloudflareAppOptions<T>): RuntimeAdapter;
157
- /** Build an application for one native Workers environment. Call inside a platform event. */
158
- export declare function createCloudflareApp<T extends object>(rootModule: CloudflareRoot<NoInfer<T>>, options: CreateCloudflareAppOptions<T>): Promise<CloudflareApplication<T>>;
159
232
  /**
160
- * Worker entrypoint with one bootstrap per environment identity. Weak keys let
161
- * obsolete environments and secrets be collected. Concurrent cold events share
162
- * construction; failed construction is evicted so the next event can retry.
233
+ * Bind an application to one environment: seeded as the global ENV before
234
+ * provider factories and lifecycle hooks, and asserted on every request. The
235
+ * adapter also supplies the `InternalDispatcher` transport, so signed queue and
236
+ * schedule dispatch re-enter this application's routes, and reports schedule
237
+ * declarations a cron trigger cannot honor through the diagnostics policy.
163
238
  */
164
- export declare function createCloudflareWorker<T extends object>(rootModule: CloudflareRoot<NoInfer<T>>, options: CloudflareWorkerOptions<T>): {
165
- fetch(request: Request, env: T, ctx: ExecutionContext): Promise<Response>;
166
- scheduled(event: {
167
- cron: string;
168
- scheduledTime?: number;
169
- }, env: T, ctx: {
239
+ export declare function cloudflareAdapter(options: {
240
+ env: VelaEnv;
241
+ }): RuntimeAdapter;
242
+ /**
243
+ * Build an application for one native Workers environment. Call inside a platform event.
244
+ * The root is static: a module class or a `DynamicModule` declared at module scope.
245
+ * Read bindings in providers (`@InjectEnv()`) and module factories
246
+ * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
247
+ */
248
+ export declare function createCloudflareApp(rootModule: CloudflareRoot, options: CreateCloudflareAppOptions): Promise<CloudflareApplication>;
249
+ /**
250
+ * Worker entrypoint with one bootstrap per environment identity. Concurrent cold
251
+ * events share construction; failed construction is evicted so the next event
252
+ * can retry. Weak keys stop this cache from retaining a replaced environment.
253
+ */
254
+ export declare function createCloudflareWorker(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): {
255
+ fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
256
+ scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
170
257
  waitUntil: (promise: Promise<unknown>) => void;
171
258
  }): Promise<void>;
172
259
  queue(batch: {
173
260
  queue: string;
174
261
  messages: readonly unknown[];
175
- }, env: T, ctx: {
262
+ }, env: VelaEnv, ctx: {
176
263
  waitUntil: (promise: Promise<unknown>) => void;
177
264
  }): Promise<void>;
178
265
  };
@@ -403,60 +490,6 @@ export declare class KvFlagDriver implements FeatureFlagDriver {
403
490
  /** Convenience factory for {@link KvFlagDriver}. */
404
491
  export declare function kvFlagDriver(kv: KVNamespace, options?: KvFlagDriverOptions): KvFlagDriver;
405
492
  //#endregion
406
- //#region src/decorators/env.d.ts
407
- /**
408
- * Parameter decorator to inject Cloudflare environment bindings.
409
- *
410
- * Without arguments, returns the entire `env` object.
411
- * With a binding name, returns that specific binding.
412
- *
413
- * @example
414
- * ```ts
415
- * @Get()
416
- * handle(@Env() env: WorkerEnv) { ... }
417
- *
418
- * @Get()
419
- * handle(@Env('MY_KV') kv: KVNamespace) { ... }
420
- * ```
421
- */
422
- export declare const Env: (data?: string | undefined, ...pipes: import("@velajs/vela").PipeType[]) => ParameterDecorator;
423
- //#endregion
424
- //#region src/decorators/scheduled.d.ts
425
- interface ScheduledMetadata {
426
- cron: string;
427
- methodName: string;
428
- }
429
- /** Compatible with the existing programmatic scheduled() entrypoint. */
430
- interface ScheduledEvent {
431
- readonly cron: string;
432
- readonly scheduledTime?: number;
433
- }
434
- /** Native controller passed unchanged to a Worker handler. Call noRetry on its receiver. */
435
- interface ScheduledController extends ScheduledEvent {
436
- readonly scheduledTime: number;
437
- noRetry(): void;
438
- }
439
- interface ScheduledContext {
440
- waitUntil(promise: Promise<unknown>): void;
441
- }
442
- type ScheduledHandler<Env extends object = object> = (controller: ScheduledController, env: Env, context: ScheduledContext) => void | Promise<void>;
443
- export declare function parseScheduledMetadata(value: unknown): ScheduledMetadata;
444
- /**
445
- * Marks a method as a scheduled (cron) handler.
446
- *
447
- * @example
448
- * ```ts
449
- * @Injectable()
450
- * class WorkerService {
451
- * @Scheduled('0 * * * *')
452
- * async hourlyCron() {
453
- * console.log('Running hourly');
454
- * }
455
- * }
456
- * ```
457
- */
458
- export declare function Scheduled(cron: string): MethodDecorator;
459
- //#endregion
460
493
  //#region src/decorators/queue-consumer.d.ts
461
494
  interface QueueConsumerMetadata {
462
495
  queueName: string;
@@ -645,5 +678,5 @@ interface DurableObjectNonceStoreOptions {
645
678
  */
646
679
  export declare function durableObjectNonceStore(options: DurableObjectNonceStoreOptions): NonceStore;
647
680
  //#endregion
648
- 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 ScheduledContext, type ScheduledController, type ScheduledEvent, type ScheduledHandler, type ScheduledMetadata, type StorageModuleOptions, SubscribeMessage, type VelaDoPitrRpc, WebSocketGateway, WebSocketServer, type WsClient, WsException, type WsGatewayRoute, type WsMessage, type WsResponse, type WsServer, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark };
681
+ export { type BroadcastNamespace, type CfLiveDriver, type CloudflareRateLimitBinding, type CloudflareRateLimitStoreOptions, type CloudflareRoot, type CloudflareScheduledEvent, 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 ScheduledEvent, type StorageModuleOptions, SubscribeMessage, type UpgradeAuthenticator, type VelaDoPitrRpc, WebSocketGateway, WebSocketServer, type WebSocketUpgradeAuthenticationContext, type WebSocketUpgradeIdentity, type WsClient, WsException, type WsGatewayRoute, type WsMessage, type WsResponse, type WsServer, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark };
649
682
  //# sourceMappingURL=index.d.ts.map