nestjs-cloudflare 0.0.0-stage → 0.1.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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +317 -2
  3. package/dist/bindings/get-binding-token.d.ts +6 -0
  4. package/dist/bindings/get-binding-token.js +8 -0
  5. package/dist/cloudflare.module.d.ts +10 -0
  6. package/dist/cloudflare.module.js +45 -0
  7. package/dist/constants.d.ts +6 -0
  8. package/dist/constants.js +6 -0
  9. package/dist/decorators/inject-binding.decorator.d.ts +7 -0
  10. package/dist/decorators/inject-binding.decorator.js +10 -0
  11. package/dist/index.d.ts +7 -0
  12. package/dist/index.js +5 -0
  13. package/dist/interfaces/worker-options.interface.d.ts +14 -0
  14. package/dist/interfaces/worker-options.interface.js +1 -0
  15. package/dist/interfaces/worker.interface.d.ts +19 -0
  16. package/dist/interfaces/worker.interface.js +1 -0
  17. package/dist/queue/client.d.ts +19 -0
  18. package/dist/queue/client.js +36 -0
  19. package/dist/queue/constants.d.ts +6 -0
  20. package/dist/queue/constants.js +6 -0
  21. package/dist/queue/context.d.ts +25 -0
  22. package/dist/queue/context.js +27 -0
  23. package/dist/queue/index.d.ts +6 -0
  24. package/dist/queue/index.js +4 -0
  25. package/dist/queue/interfaces/client-options.interface.d.ts +14 -0
  26. package/dist/queue/interfaces/client-options.interface.js +1 -0
  27. package/dist/queue/interfaces/server-options.interface.d.ts +16 -0
  28. package/dist/queue/interfaces/server-options.interface.js +1 -0
  29. package/dist/queue/server.d.ts +28 -0
  30. package/dist/queue/server.js +102 -0
  31. package/dist/schedule/constants.d.ts +3 -0
  32. package/dist/schedule/constants.js +3 -0
  33. package/dist/schedule/cron.explorer.d.ts +17 -0
  34. package/dist/schedule/cron.explorer.js +105 -0
  35. package/dist/schedule/index.d.ts +1 -0
  36. package/dist/schedule/index.js +1 -0
  37. package/dist/schedule/schedule.module.d.ts +10 -0
  38. package/dist/schedule/schedule.module.js +33 -0
  39. package/dist/websockets/adapter.d.ts +69 -0
  40. package/dist/websockets/adapter.js +161 -0
  41. package/dist/websockets/durable-object.d.ts +21 -0
  42. package/dist/websockets/durable-object.js +70 -0
  43. package/dist/websockets/index.d.ts +7 -0
  44. package/dist/websockets/index.js +3 -0
  45. package/dist/websockets/interfaces/adapter-options.interface.d.ts +10 -0
  46. package/dist/websockets/interfaces/adapter-options.interface.js +1 -0
  47. package/dist/websockets/interfaces/durable-object-options.interface.d.ts +15 -0
  48. package/dist/websockets/interfaces/durable-object-options.interface.js +1 -0
  49. package/dist/websockets/interfaces/message.interface.d.ts +11 -0
  50. package/dist/websockets/interfaces/message.interface.js +1 -0
  51. package/dist/websockets/interfaces/server.interface.d.ts +9 -0
  52. package/dist/websockets/interfaces/server.interface.js +1 -0
  53. package/dist/websockets/invalid-message.exception.d.ts +8 -0
  54. package/dist/websockets/invalid-message.exception.js +11 -0
  55. package/dist/worker/create-worker.d.ts +10 -0
  56. package/dist/worker/create-worker.js +99 -0
  57. package/package.json +107 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 blockchainian
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,318 @@
1
- # Temporary Holding Version
1
+ # nestjs-cloudflare
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run a Nest application on Cloudflare Workers with binding injection, scheduled events, Queues, and hibernating Durable Object WebSockets.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm install nestjs-cloudflare
9
+ npm install @nestjs/common @nestjs/core reflect-metadata rxjs
10
+ ```
11
+
12
+ Install your chosen Nest HTTP platform, such as `@nestjs/platform-express`. Queues require `@nestjs/microservices`, scheduled handlers require `@nestjs/schedule`, and gateways require `@nestjs/websockets`. These integrations are optional peers exposed through separate package entry points. Use versions compatible with this package's peer dependency ranges.
13
+
14
+ The npm package includes compiled JavaScript and type declarations. Applications also need Cloudflare's runtime type declarations, supplied by `wrangler types` or a compatible `@cloudflare/workers-types` package.
15
+
16
+ ## Application
17
+
18
+ ```ts
19
+ import 'reflect-metadata';
20
+ import { Controller, Get, Module } from '@nestjs/common';
21
+ import { NestFactory } from '@nestjs/core';
22
+ import { CloudflareModule, createWorker } from 'nestjs-cloudflare';
23
+
24
+ @Controller()
25
+ class AppController {
26
+ @Get()
27
+ hello(): string {
28
+ return 'Hello from Nest';
29
+ }
30
+ }
31
+
32
+ @Module({
33
+ imports: [CloudflareModule.forRoot()],
34
+ controllers: [AppController],
35
+ })
36
+ class AppModule {}
37
+
38
+ async function bootstrap() {
39
+ return NestFactory.create(AppModule, { rawBody: true });
40
+ }
41
+
42
+ export default createWorker(bootstrap);
43
+ ```
44
+
45
+ `createWorker` synchronously returns Worker handlers. The first event runs `bootstrap` once, initializes the application, starts connected microservices, and opens its Node HTTP server on an ephemeral port. Later events share the same application. `worker.getApplication()` returns a promise for that application and also starts it when called by a Durable Object.
46
+
47
+ Keep Nest creation inside `bootstrap`. Cloudflare's upload validation runs module initialization without all bindings and disallows I/O and random number generation. Deferring Nest startup to an event avoids those restrictions. Choose HTTP adapters, application options, global guards, pipes, filters, and interceptors in your bootstrap function.
48
+
49
+ ## Bindings
50
+
51
+ `CloudflareModule.forRoot()` registers global providers for the bindings in `cloudflare:workers`' imported `env`. Import it once in the root module. Bindings are injected directly, including primitive variables.
52
+
53
+ ```ts
54
+ import { Inject, Injectable } from '@nestjs/common';
55
+ import {
56
+ CLOUDFLARE_ENV,
57
+ InjectBinding,
58
+ getBindingToken,
59
+ } from 'nestjs-cloudflare';
60
+
61
+ interface Env {
62
+ STATE: KVNamespace;
63
+ LABEL: string;
64
+ }
65
+
66
+ @Injectable()
67
+ class StateService {
68
+ constructor(
69
+ @InjectBinding<Env>('STATE') private readonly state: KVNamespace,
70
+ @Inject(CLOUDFLARE_ENV) private readonly env: Env,
71
+ ) {}
72
+
73
+ read(): Promise<string | null> {
74
+ return this.state.get(this.env.LABEL);
75
+ }
76
+ }
77
+
78
+ const stateToken = getBindingToken<Env>('STATE');
79
+ ```
80
+
81
+ RPC bindings expose callable lifecycle properties, so they are excluded from individual providers to prevent Nest from invoking remote lifecycle methods. Inject `CLOUDFLARE_ENV` and call the binding through `env.MY_SERVICE` instead. Using `@InjectBinding` for an RPC binding produces Nest's unresolved-dependency error.
82
+
83
+ The optional generic restricts binding names to keys of the application's environment. Injecting a binding absent from the runtime environment produces Nest's unresolved-dependency error. Tests can configure bindings in Miniflare or scope imported `env` with `withEnv` from `cloudflare:workers` before creating the application.
84
+
85
+ ## Scheduled events
86
+
87
+ Install `@nestjs/schedule`, import `CloudflareScheduleModule.forRoot()` from `nestjs-cloudflare/schedule`, and use the official decorator:
88
+
89
+ ```ts
90
+ import { Injectable } from '@nestjs/common';
91
+ import { Cron } from '@nestjs/schedule';
92
+ import { env } from 'cloudflare:workers';
93
+
94
+ @Injectable()
95
+ class DigestService {
96
+ @Cron(env.DIGEST_CRON as string)
97
+ async digest(controller: ScheduledController): Promise<void> {
98
+ await env.STATE.put('last-cron', controller.cron);
99
+ }
100
+ }
101
+ ```
102
+
103
+ Register the service as a provider. Do not import Nest's `ScheduleModule`: Cloudflare supplies scheduled events, so no in-process timer is needed. Configure the variable and trigger together in Wrangler:
104
+
105
+ ```jsonc
106
+ {
107
+ "vars": { "DIGEST_CRON": "0 8 * * *" },
108
+ "triggers": { "crons": ["0 8 * * *"] },
109
+ }
110
+ ```
111
+
112
+ Expressions must have five fields and match `ScheduledController.cron` exactly. Workers schedules use UTC. Empty and six-field expressions produce startup warnings; six-field values from Nest's `CronExpression` enum cannot match Workers triggers. Every matching method runs. Non-static providers are skipped with a warning.
113
+
114
+ `disabled` suppresses a handler. `waitForCompletion` skips overlapping invocations within one isolate. Timer-specific options such as `timeZone` do not configure Cloudflare triggers. Scheduled processing is registered with `ctx.waitUntil`; handler failures are reported after `scheduled()` returns. Unmatched events use `fallback.scheduled` when provided and otherwise produce a warning.
115
+
116
+ ## Queues
117
+
118
+ Install `@nestjs/microservices`. Connect the queue transport during bootstrap so Nest can register handlers and inherit application configuration:
119
+
120
+ ```ts
121
+ import { CloudflareQueueServer } from 'nestjs-cloudflare/queue';
122
+
123
+ async function bootstrap() {
124
+ const app = await NestFactory.create(AppModule);
125
+ app.connectMicroservice(
126
+ { strategy: new CloudflareQueueServer({ noAck: true }) },
127
+ { inheritAppConfig: true },
128
+ );
129
+ return app;
130
+ }
131
+ ```
132
+
133
+ Register a producer through Nest's `ClientsModule` and inject its client:
134
+
135
+ ```ts
136
+ import { Inject, Injectable, Module } from '@nestjs/common';
137
+ import { ClientProxy, ClientsModule } from '@nestjs/microservices';
138
+ import { env } from 'cloudflare:workers';
139
+ import { firstValueFrom } from 'rxjs';
140
+ import { CloudflareQueueClient } from 'nestjs-cloudflare/queue';
141
+
142
+ @Injectable()
143
+ class NotificationsService {
144
+ constructor(@Inject('NOTIFICATIONS') private readonly client: ClientProxy) {}
145
+
146
+ async notify(text: string): Promise<void> {
147
+ await firstValueFrom(this.client.emit('notifications', text));
148
+ }
149
+ }
150
+
151
+ @Module({
152
+ imports: [
153
+ ClientsModule.register([
154
+ {
155
+ name: 'NOTIFICATIONS',
156
+ customClass: CloudflareQueueClient,
157
+ options: { queue: env.NOTIFICATIONS },
158
+ },
159
+ ]),
160
+ ],
161
+ providers: [NotificationsService],
162
+ })
163
+ class NotificationsModule {}
164
+ ```
165
+
166
+ For dependency injection into the client factory, use `ClientsModule.registerAsync` with `inject: [getBindingToken<Env>('NOTIFICATIONS')]` and return `{ customClass: CloudflareQueueClient, options: { queue } }`. Client and server options accept Nest serializers and deserializers. `emit` sends the Nest event packet, preserving its pattern and metadata. One Queue can carry multiple patterns. `send` rejects because Cloudflare Queues do not support request-response messaging.
167
+
168
+ ```ts
169
+ import { Controller } from '@nestjs/common';
170
+ import { InjectBinding } from 'nestjs-cloudflare';
171
+ import { Ctx, EventPattern, Payload } from '@nestjs/microservices';
172
+ import {
173
+ CLOUDFLARE_QUEUE_TRANSPORT,
174
+ CloudflareQueueContext,
175
+ } from 'nestjs-cloudflare/queue';
176
+
177
+ @Controller()
178
+ class NotificationsController {
179
+ constructor(@InjectBinding('STATE') private readonly state: KVNamespace) {}
180
+
181
+ @EventPattern('notifications', CLOUDFLARE_QUEUE_TRANSPORT)
182
+ async receive(
183
+ @Payload() text: string,
184
+ @Ctx() context: CloudflareQueueContext,
185
+ ): Promise<void> {
186
+ await this.state.put('last-notification', text);
187
+ }
188
+ }
189
+ ```
190
+
191
+ The context exposes the original message, batch, execution context, and pattern. For messages sent by other producers without a Nest packet, the Queue name is the event pattern. Successful messages are acknowledged automatically by default. Set `noAck: false` and call `context.getMessage().ack()` for manual acknowledgement. Failed handlers request retries in either mode.
192
+
193
+ Batches are sequential by default. Set `concurrency: 'parallel'` on the server to process messages concurrently. Unhandled messages use `fallback.queue` when supplied. Missing transports and unhandled events are reported explicitly. Fallbacks are passed as the second argument to `createWorker`:
194
+
195
+ ```ts
196
+ const worker = createWorker(bootstrap, {
197
+ fallback: {
198
+ async queue(batch, env, ctx) {
199
+ batch.ackAll();
200
+ },
201
+ async scheduled(controller, env, ctx) {
202
+ await env.STATE.put('unmatched-cron', controller.cron);
203
+ },
204
+ },
205
+ });
206
+ ```
207
+
208
+ ## Durable Objects
209
+
210
+ A native Durable Object can resolve Nest services through the application's asynchronous accessor:
211
+
212
+ ```ts
213
+ import { DurableObject } from 'cloudflare:workers';
214
+
215
+ const worker = createWorker(bootstrap);
216
+
217
+ export class Greeter extends DurableObject<Env> {
218
+ async fetch(): Promise<Response> {
219
+ const app = await worker.getApplication();
220
+ return new Response(app.get(GreetingService).greet());
221
+ }
222
+ }
223
+
224
+ export default worker;
225
+ ```
226
+
227
+ Register the service as an application provider. Register `Greeter` in Wrangler's `durable_objects.bindings` and add a SQLite migration, as shown in `example/wrangler.jsonc`. Durable Object storage remains available through the object's own context.
228
+
229
+ ## WebSockets and hibernation
230
+
231
+ Install `@nestjs/websockets` and import the adapter and Durable Object base class from `nestjs-cloudflare/websockets`. Socket.IO and `@nestjs/platform-ws` are not needed.
232
+
233
+ ```ts
234
+ import {
235
+ MessageBody,
236
+ SubscribeMessage,
237
+ WebSocketGateway,
238
+ } from '@nestjs/websockets';
239
+ import {
240
+ CloudflareWebSocketAdapter,
241
+ CloudflareWebSocketDurableObject,
242
+ } from 'nestjs-cloudflare/websockets';
243
+
244
+ @WebSocketGateway({ path: '/chat' })
245
+ class ChatGateway {
246
+ @SubscribeMessage('echo')
247
+ echo(@MessageBody() data: unknown): unknown {
248
+ return data;
249
+ }
250
+ }
251
+
252
+ const adapter = new CloudflareWebSocketAdapter();
253
+
254
+ async function bootstrap() {
255
+ const app = await NestFactory.create(AppModule);
256
+ app.useWebSocketAdapter(adapter);
257
+ return app;
258
+ }
259
+
260
+ const worker = createWorker(bootstrap);
261
+
262
+ export class ChatRoom extends CloudflareWebSocketDurableObject<Env> {
263
+ constructor(ctx: DurableObjectState, env: Env) {
264
+ super(ctx, env, {
265
+ adapter,
266
+ path: '/chat',
267
+ getApplication: worker.getApplication,
268
+ });
269
+ }
270
+ }
271
+ ```
272
+
273
+ Register the gateway as an application provider. Route upgrade requests to `env.CHAT.get(id).fetch(request)` and configure the Durable Object binding and migration. Gateways use port `0`, the default. Separate listening ports and Socket.IO namespaces are unsupported.
274
+
275
+ The base class implements `fetch`, `webSocketMessage`, `webSocketClose`, and `webSocketError`. It accepts connections through `ctx.acceptWebSocket` and waits for Nest startup before dispatching events after hibernation. Restored connections are registered with Nest again, so `handleConnection` can run more than once for a socket. Gateways are application singletons; keep persistent room state in Durable Object storage or socket attachments.
276
+
277
+ Clients send `{"event":"echo","data":"hello"}`. The handler receives `data` and its return value is JSON-serialized directly to the client. Promise and observable results are supported. Configure `messageParser` for another wire protocol:
278
+
279
+ ```ts
280
+ const adapter = new CloudflareWebSocketAdapter({
281
+ messageParser: frame => {
282
+ if (typeof frame !== 'string') {
283
+ return;
284
+ }
285
+ return { event: 'echo', data: frame };
286
+ },
287
+ });
288
+ ```
289
+
290
+ A parser can return `undefined` to ignore a frame. The default parser closes malformed JSON messages with code `1007`. A custom parser can throw `InvalidWebSocketMessageException` for that close code; unexpected failures close with `1011`.
291
+
292
+ ## Build and local development
293
+
294
+ Compile application TypeScript with `experimentalDecorators` and `emitDecoratorMetadata` before Wrangler bundles the emitted JavaScript. Wrangler's esbuild compilation does not emit the metadata Nest needs for dependency injection. Enable `nodejs_compat` and `enable_nodejs_http_server_modules` for Node HTTP support.
295
+
296
+ ```sh
297
+ yarn install
298
+ yarn build
299
+ yarn lint
300
+ yarn test
301
+ yarn wrangler dev --config example/wrangler.jsonc --test-scheduled
302
+ ```
303
+
304
+ Wrangler runs `yarn build:example` and loads `dist-example/example/index.js`. Local KV, Queues, and Durable Objects need no remote resources. The placeholder KV namespace ID is for local use.
305
+
306
+ ```sh
307
+ curl http://localhost:8787/
308
+ curl http://localhost:8787/durable
309
+ curl -X POST http://localhost:8787/notifications \
310
+ -H 'content-type: application/json' -d '{"text":"Hello"}'
311
+ curl 'http://localhost:8787/cdn-cgi/handler/scheduled?cron=*/15%20*%20*%20*%20*'
312
+ curl http://localhost:8787/state/last-cron
313
+ curl http://localhost:8787/state/last-notification
314
+ ```
315
+
316
+ Run the gateway example with `yarn wrangler dev --config example/websockets/wrangler.jsonc`, then connect to `ws://localhost:8787/chat` and send the JSON echo message above.
317
+
318
+ Wrangler aliases resolve unused optional Nest integrations to `unsupported-dependency.ts`. Nest references optional transport and validation packages while bundling even when an application does not enable them. The alias target throws if evaluated. Remove an integration's alias and install its actual dependencies before enabling it. The gateway example keeps Nest's real WebSocket module; copying the basic example's WebSocket-module alias would disable gateway registration.
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Returns the Nest injection token for a native Cloudflare binding.
3
+ *
4
+ * @publicApi
5
+ */
6
+ export declare function getBindingToken<Env extends object = Record<string, unknown>>(name: Extract<keyof Env, string>): string;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Returns the Nest injection token for a native Cloudflare binding.
3
+ *
4
+ * @publicApi
5
+ */
6
+ export function getBindingToken(name) {
7
+ return `cloudflare:binding:${name}`;
8
+ }
@@ -0,0 +1,10 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ /**
3
+ * Makes the native Cloudflare environment and its bindings available to Nest.
4
+ *
5
+ * @publicApi
6
+ */
7
+ export declare class CloudflareModule {
8
+ /** Registers the environment's bindings once in the application's root module. */
9
+ static forRoot(): DynamicModule;
10
+ }
@@ -0,0 +1,45 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var CloudflareModule_1;
8
+ import { Global, Module, } from '@nestjs/common';
9
+ import { env } from 'cloudflare:workers';
10
+ import { getBindingToken } from './bindings/get-binding-token.js';
11
+ import { CLOUDFLARE_ENV } from './constants.js';
12
+ /**
13
+ * Makes the native Cloudflare environment and its bindings available to Nest.
14
+ *
15
+ * @publicApi
16
+ */
17
+ let CloudflareModule = CloudflareModule_1 = class CloudflareModule {
18
+ /** Registers the environment's bindings once in the application's root module. */
19
+ static forRoot() {
20
+ const bindings = [];
21
+ for (const name of Object.keys(env)) {
22
+ const binding = Reflect.get(env, name);
23
+ if (hasModuleInitHook(binding)) {
24
+ continue;
25
+ }
26
+ bindings.push({ provide: getBindingToken(name), useValue: binding });
27
+ }
28
+ return {
29
+ module: CloudflareModule_1,
30
+ providers: [{ provide: CLOUDFLARE_ENV, useValue: env }, ...bindings],
31
+ exports: [CLOUDFLARE_ENV, ...bindings.map(binding => binding.provide)],
32
+ };
33
+ }
34
+ };
35
+ CloudflareModule = CloudflareModule_1 = __decorate([
36
+ Global(),
37
+ Module({})
38
+ ], CloudflareModule);
39
+ export { CloudflareModule };
40
+ /** RPC stubs expose callable properties that Nest would invoke as lifecycle hooks. */
41
+ function hasModuleInitHook(binding) {
42
+ return (binding !== null &&
43
+ (typeof binding === 'object' || typeof binding === 'function') &&
44
+ typeof Reflect.get(binding, 'onModuleInit') === 'function');
45
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Injection token for the native Cloudflare environment.
3
+ *
4
+ * @publicApi
5
+ */
6
+ export declare const CLOUDFLARE_ENV: unique symbol;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Injection token for the native Cloudflare environment.
3
+ *
4
+ * @publicApi
5
+ */
6
+ export const CLOUDFLARE_ENV = Symbol('CLOUDFLARE_ENV');
@@ -0,0 +1,7 @@
1
+ import { Inject } from '@nestjs/common';
2
+ /**
3
+ * Injects a binding registered from the native Cloudflare environment.
4
+ *
5
+ * @publicApi
6
+ */
7
+ export declare function InjectBinding<Env extends object = Record<string, unknown>>(name: Extract<keyof Env, string>): ReturnType<typeof Inject>;
@@ -0,0 +1,10 @@
1
+ import { Inject } from '@nestjs/common';
2
+ import { getBindingToken } from '../bindings/get-binding-token.js';
3
+ /**
4
+ * Injects a binding registered from the native Cloudflare environment.
5
+ *
6
+ * @publicApi
7
+ */
8
+ export function InjectBinding(name) {
9
+ return Inject(getBindingToken(name));
10
+ }
@@ -0,0 +1,7 @@
1
+ export { getBindingToken } from './bindings/get-binding-token.js';
2
+ export { CloudflareModule } from './cloudflare.module.js';
3
+ export { CLOUDFLARE_ENV } from './constants.js';
4
+ export { InjectBinding } from './decorators/inject-binding.decorator.js';
5
+ export type { CloudflareWorker } from './interfaces/worker.interface.js';
6
+ export type { CloudflareWorkerOptions } from './interfaces/worker-options.interface.js';
7
+ export { createWorker } from './worker/create-worker.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { getBindingToken } from './bindings/get-binding-token.js';
2
+ export { CloudflareModule } from './cloudflare.module.js';
3
+ export { CLOUDFLARE_ENV } from './constants.js';
4
+ export { InjectBinding } from './decorators/inject-binding.decorator.js';
5
+ export { createWorker } from './worker/create-worker.js';
@@ -0,0 +1,14 @@
1
+ type WorkerExecutionContext = ExecutionContext;
2
+ /**
3
+ * Configures native event fallbacks when no Nest transport handles an event.
4
+ *
5
+ * @publicApi
6
+ */
7
+ export interface CloudflareWorkerOptions<Env = Cloudflare.Env> {
8
+ /** Native handlers for events not handled by a connected Nest transport. */
9
+ fallback?: {
10
+ scheduled?: (controller: ScheduledController, env: Env, ctx: WorkerExecutionContext) => void | Promise<void>;
11
+ queue?: (batch: MessageBatch, env: Env, ctx: WorkerExecutionContext) => void | Promise<void>;
12
+ };
13
+ }
14
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { INestApplication } from '@nestjs/common';
2
+ type WorkerExecutionContext = ExecutionContext;
3
+ type IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
4
+ /**
5
+ * Worker event handlers backed by one lazily initialized Nest application.
6
+ *
7
+ * @publicApi
8
+ */
9
+ export interface CloudflareWorker<Env = Cloudflare.Env> {
10
+ /** Starts the application once and returns it to native Worker or Durable Object code. */
11
+ getApplication(): Promise<INestApplication>;
12
+ /** Serves an HTTP request through the application's HTTP adapter. */
13
+ fetch(request: IncomingRequest, env: Env, ctx: WorkerExecutionContext): Promise<Response>;
14
+ /** Dispatches an event to registered Nest cron methods or the native fallback. */
15
+ scheduled(controller: ScheduledController, env: Env, ctx: WorkerExecutionContext): Promise<void>;
16
+ /** Dispatches a batch to the application's Cloudflare Queue transport. */
17
+ queue(batch: MessageBatch, env: Env, ctx: WorkerExecutionContext): Promise<void>;
18
+ }
19
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { ClientProxy, type ReadPacket, type WritePacket } from '@nestjs/microservices';
2
+ import type { CloudflareQueueClientOptions } from './interfaces/client-options.interface.js';
3
+ /**
4
+ * Publishes Nest event packets through a Cloudflare Queue binding.
5
+ *
6
+ * @publicApi
7
+ */
8
+ export declare class CloudflareQueueClient extends ClientProxy {
9
+ private readonly options;
10
+ constructor(options: CloudflareQueueClientOptions);
11
+ /** Returns the Queue binding without opening a broker connection. */
12
+ connect(): Promise<Queue>;
13
+ /** Releases no resources because Workers owns the Queue binding. */
14
+ close(): void;
15
+ /** Returns the underlying Queue binding. */
16
+ unwrap<T>(): T;
17
+ protected publish(_packet: ReadPacket, callback: (packet: WritePacket) => void): () => void;
18
+ protected dispatchEvent<T>(packet: ReadPacket): Promise<T>;
19
+ }
@@ -0,0 +1,36 @@
1
+ import { ClientProxy, } from '@nestjs/microservices';
2
+ /**
3
+ * Publishes Nest event packets through a Cloudflare Queue binding.
4
+ *
5
+ * @publicApi
6
+ */
7
+ export class CloudflareQueueClient extends ClientProxy {
8
+ options;
9
+ constructor(options) {
10
+ super();
11
+ this.options = options;
12
+ this.initializeSerializer(options);
13
+ this.initializeDeserializer(options);
14
+ }
15
+ /** Returns the Queue binding without opening a broker connection. */
16
+ async connect() {
17
+ return this.options.queue;
18
+ }
19
+ /** Releases no resources because Workers owns the Queue binding. */
20
+ close() { }
21
+ /** Returns the underlying Queue binding. */
22
+ unwrap() {
23
+ return this.options.queue;
24
+ }
25
+ publish(_packet, callback) {
26
+ callback({
27
+ err: new Error('Cloudflare Queues supports emit(), not request-response send()'),
28
+ });
29
+ return () => { };
30
+ }
31
+ async dispatchEvent(packet) {
32
+ const pattern = this.normalizePattern(packet.pattern);
33
+ await this.options.queue.send(await this.serializer.serialize({ ...packet, pattern }));
34
+ return undefined;
35
+ }
36
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Identifies Cloudflare Queue handlers in Nest hybrid applications.
3
+ *
4
+ * @publicApi
5
+ */
6
+ export declare const CLOUDFLARE_QUEUE_TRANSPORT: unique symbol;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Identifies Cloudflare Queue handlers in Nest hybrid applications.
3
+ *
4
+ * @publicApi
5
+ */
6
+ export const CLOUDFLARE_QUEUE_TRANSPORT = Symbol.for('nestjs-cloudflare:queue');
@@ -0,0 +1,25 @@
1
+ import { BaseRpcContext } from '@nestjs/microservices';
2
+ type WorkerExecutionContext = ExecutionContext;
3
+ type CloudflareQueueContextArgs = [
4
+ Message,
5
+ MessageBatch,
6
+ WorkerExecutionContext,
7
+ string
8
+ ];
9
+ /**
10
+ * Exposes the native Queue event and matched Nest pattern to a handler.
11
+ *
12
+ * @publicApi
13
+ */
14
+ export declare class CloudflareQueueContext extends BaseRpcContext<CloudflareQueueContextArgs> {
15
+ constructor(args: CloudflareQueueContextArgs);
16
+ /** Returns the message, including acknowledgement and retry methods. */
17
+ getMessage(): Message;
18
+ /** Returns the batch containing this message. */
19
+ getBatch(): MessageBatch;
20
+ /** Returns the Worker execution context for background work. */
21
+ getExecutionContext(): WorkerExecutionContext;
22
+ /** Returns the normalized Nest event pattern. */
23
+ getPattern(): string;
24
+ }
25
+ export {};
@@ -0,0 +1,27 @@
1
+ import { BaseRpcContext } from '@nestjs/microservices';
2
+ /**
3
+ * Exposes the native Queue event and matched Nest pattern to a handler.
4
+ *
5
+ * @publicApi
6
+ */
7
+ export class CloudflareQueueContext extends BaseRpcContext {
8
+ constructor(args) {
9
+ super(args);
10
+ }
11
+ /** Returns the message, including acknowledgement and retry methods. */
12
+ getMessage() {
13
+ return this.args[0];
14
+ }
15
+ /** Returns the batch containing this message. */
16
+ getBatch() {
17
+ return this.args[1];
18
+ }
19
+ /** Returns the Worker execution context for background work. */
20
+ getExecutionContext() {
21
+ return this.args[2];
22
+ }
23
+ /** Returns the normalized Nest event pattern. */
24
+ getPattern() {
25
+ return this.args[3];
26
+ }
27
+ }
@@ -0,0 +1,6 @@
1
+ export { CloudflareQueueClient } from './client.js';
2
+ export { CLOUDFLARE_QUEUE_TRANSPORT } from './constants.js';
3
+ export { CloudflareQueueContext } from './context.js';
4
+ export type { CloudflareQueueClientOptions } from './interfaces/client-options.interface.js';
5
+ export type { CloudflareQueueServerOptions } from './interfaces/server-options.interface.js';
6
+ export { CloudflareQueueServer } from './server.js';
@@ -0,0 +1,4 @@
1
+ export { CloudflareQueueClient } from './client.js';
2
+ export { CLOUDFLARE_QUEUE_TRANSPORT } from './constants.js';
3
+ export { CloudflareQueueContext } from './context.js';
4
+ export { CloudflareQueueServer } from './server.js';