nestjs-cloudflare 0.0.0-stage → 0.4.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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +583 -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 +11 -0
  6. package/dist/cloudflare.module.js +55 -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/durable-objects/client.d.ts +13 -0
  12. package/dist/durable-objects/client.js +67 -0
  13. package/dist/durable-objects/constants.d.ts +1 -0
  14. package/dist/durable-objects/constants.js +1 -0
  15. package/dist/durable-objects/context.d.ts +18 -0
  16. package/dist/durable-objects/context.js +53 -0
  17. package/dist/durable-objects/context.transport.d.ts +9 -0
  18. package/dist/durable-objects/context.transport.js +13 -0
  19. package/dist/durable-objects/durable-object.d.ts +11 -0
  20. package/dist/durable-objects/durable-object.js +21 -0
  21. package/dist/durable-objects/index.d.ts +9 -0
  22. package/dist/durable-objects/index.js +7 -0
  23. package/dist/durable-objects/interfaces/client-options.interface.d.ts +15 -0
  24. package/dist/durable-objects/interfaces/client-options.interface.js +1 -0
  25. package/dist/durable-objects/interfaces/server-options.interface.d.ts +14 -0
  26. package/dist/durable-objects/interfaces/server-options.interface.js +1 -0
  27. package/dist/durable-objects/record-builder.d.ts +16 -0
  28. package/dist/durable-objects/record-builder.js +28 -0
  29. package/dist/durable-objects/record.serializer.d.ts +10 -0
  30. package/dist/durable-objects/record.serializer.js +10 -0
  31. package/dist/durable-objects/server.d.ts +16 -0
  32. package/dist/durable-objects/server.js +101 -0
  33. package/dist/index.d.ts +12 -0
  34. package/dist/index.js +9 -0
  35. package/dist/interfaces/worker-options.interface.d.ts +45 -0
  36. package/dist/interfaces/worker-options.interface.js +1 -0
  37. package/dist/interfaces/worker.interface.d.ts +21 -0
  38. package/dist/interfaces/worker.interface.js +1 -0
  39. package/dist/queue/client.d.ts +19 -0
  40. package/dist/queue/client.js +44 -0
  41. package/dist/queue/constants.d.ts +6 -0
  42. package/dist/queue/constants.js +6 -0
  43. package/dist/queue/context.d.ts +25 -0
  44. package/dist/queue/context.js +27 -0
  45. package/dist/queue/index.d.ts +8 -0
  46. package/dist/queue/index.js +6 -0
  47. package/dist/queue/interfaces/client-options.interface.d.ts +14 -0
  48. package/dist/queue/interfaces/client-options.interface.js +1 -0
  49. package/dist/queue/interfaces/server-options.interface.d.ts +16 -0
  50. package/dist/queue/interfaces/server-options.interface.js +1 -0
  51. package/dist/queue/record-builder.d.ts +19 -0
  52. package/dist/queue/record-builder.js +32 -0
  53. package/dist/queue/record.serializer.d.ts +10 -0
  54. package/dist/queue/record.serializer.js +14 -0
  55. package/dist/queue/server.d.ts +28 -0
  56. package/dist/queue/server.js +102 -0
  57. package/dist/schedule/constants.d.ts +3 -0
  58. package/dist/schedule/constants.js +3 -0
  59. package/dist/schedule/cron.explorer.d.ts +20 -0
  60. package/dist/schedule/cron.explorer.js +121 -0
  61. package/dist/schedule/index.d.ts +1 -0
  62. package/dist/schedule/index.js +1 -0
  63. package/dist/schedule/schedule.module.d.ts +10 -0
  64. package/dist/schedule/schedule.module.js +33 -0
  65. package/dist/websockets/adapter.d.ts +76 -0
  66. package/dist/websockets/adapter.js +186 -0
  67. package/dist/websockets/context.d.ts +12 -0
  68. package/dist/websockets/context.js +15 -0
  69. package/dist/websockets/durable-object.d.ts +24 -0
  70. package/dist/websockets/durable-object.js +77 -0
  71. package/dist/websockets/gateway-durable-object.d.ts +17 -0
  72. package/dist/websockets/gateway-durable-object.js +82 -0
  73. package/dist/websockets/index.d.ts +11 -0
  74. package/dist/websockets/index.js +5 -0
  75. package/dist/websockets/interfaces/adapter-options.interface.d.ts +14 -0
  76. package/dist/websockets/interfaces/adapter-options.interface.js +1 -0
  77. package/dist/websockets/interfaces/durable-object-options.interface.d.ts +15 -0
  78. package/dist/websockets/interfaces/durable-object-options.interface.js +1 -0
  79. package/dist/websockets/interfaces/gateway-options.interface.d.ts +11 -0
  80. package/dist/websockets/interfaces/gateway-options.interface.js +1 -0
  81. package/dist/websockets/interfaces/message.interface.d.ts +11 -0
  82. package/dist/websockets/interfaces/message.interface.js +1 -0
  83. package/dist/websockets/interfaces/server.interface.d.ts +9 -0
  84. package/dist/websockets/interfaces/server.interface.js +1 -0
  85. package/dist/websockets/invalid-message.exception.d.ts +8 -0
  86. package/dist/websockets/invalid-message.exception.js +11 -0
  87. package/dist/websockets/message-dispatcher.d.ts +8 -0
  88. package/dist/websockets/message-dispatcher.js +26 -0
  89. package/dist/worker/create-worker.d.ts +11 -0
  90. package/dist/worker/create-worker.js +223 -0
  91. package/dist/worker/request-context.d.ts +19 -0
  92. package/dist/worker/request-context.js +38 -0
  93. package/dist/worker/websocket-routing.d.ts +3 -0
  94. package/dist/worker/websocket-routing.js +10 -0
  95. package/package.json +111 -4
@@ -0,0 +1,11 @@
1
+ import 'reflect-metadata';
2
+ import { type INestApplication } from '@nestjs/common';
3
+ import type { CloudflareWorker } from '../interfaces/worker.interface.js';
4
+ import type { CloudflareWorkerOptions } from '../interfaces/worker-options.interface.js';
5
+ export { CloudflareRequestContext, type CloudflareRequestContextValue, } from './request-context.js';
6
+ /**
7
+ * Defers Nest bootstrap until the first event and caches the initialized application.
8
+ *
9
+ * @publicApi
10
+ */
11
+ export declare function createWorker<Env = Cloudflare.Env>(bootstrap: () => Promise<INestApplication>, options?: CloudflareWorkerOptions<Env>): CloudflareWorker<Env>;
@@ -0,0 +1,223 @@
1
+ import 'reflect-metadata';
2
+ import { Logger } from '@nestjs/common';
3
+ import { ModuleRef } from '@nestjs/core';
4
+ import { httpServerHandler } from 'cloudflare:node';
5
+ import { CLOUDFLARE_ENV } from '../constants.js';
6
+ import { CLOUDFLARE_QUEUE_TRANSPORT } from '../queue/constants.js';
7
+ import { CRON_EXPLORER } from '../schedule/constants.js';
8
+ import { CloudflareRequestContext } from './request-context.js';
9
+ import { findWebSocketRoute, forwardWebSocketRequest, } from './websocket-routing.js';
10
+ export { CloudflareRequestContext, } from './request-context.js';
11
+ /**
12
+ * Defers Nest bootstrap until the first event and caches the initialized application.
13
+ *
14
+ * @publicApi
15
+ */
16
+ export function createWorker(bootstrap, options = {}) {
17
+ const logger = new Logger('CloudflareWorker');
18
+ let application;
19
+ let http;
20
+ let routeMatcher;
21
+ const getApplication = () => {
22
+ if (application) {
23
+ return application;
24
+ }
25
+ const startup = (async () => {
26
+ const app = await bootstrap();
27
+ try {
28
+ app.get(CLOUDFLARE_ENV);
29
+ }
30
+ catch (cause) {
31
+ await app.close();
32
+ throw new Error('Import CloudflareModule.forRoot() in the application root module', { cause });
33
+ }
34
+ try {
35
+ validateRouting(app, options);
36
+ await app.init();
37
+ await app.startAllMicroservices();
38
+ if (!app.getHttpServer().listening) {
39
+ await app.listen(0);
40
+ }
41
+ http = httpServerHandler(app.getHttpServer());
42
+ routeMatcher = createRouteMatcher(app, options);
43
+ return app;
44
+ }
45
+ catch (error) {
46
+ await app.close();
47
+ throw error;
48
+ }
49
+ })();
50
+ application = startup;
51
+ startup.catch(() => {
52
+ if (application === startup) {
53
+ application = undefined;
54
+ }
55
+ });
56
+ return application;
57
+ };
58
+ const runWithContext = (app, value, callback) => app.get(CloudflareRequestContext).run(value, callback);
59
+ const matches = async (request) => {
60
+ if (findWebSocketRoute(request, options.websockets)) {
61
+ return true;
62
+ }
63
+ await getApplication();
64
+ return routeMatcher?.(request).matched ?? false;
65
+ };
66
+ return {
67
+ getApplication,
68
+ matches,
69
+ async fetch(request, env, ctx) {
70
+ const dispatch = async () => {
71
+ const websocket = findWebSocketRoute(request, options.websockets);
72
+ if (websocket) {
73
+ return forwardWebSocketRequest(request, env, websocket);
74
+ }
75
+ const app = await getApplication();
76
+ const route = routeMatcher?.(request) ?? { matched: false };
77
+ const fallback = options.fallback?.fetch;
78
+ if (!route.matched && fallback) {
79
+ return runWithContext(app, { request, env, ctx, routeError: route.routeError }, () => fallback(request, env, ctx));
80
+ }
81
+ return runWithContext(app, { request, env, ctx }, () => http.fetch(request, env, ctx));
82
+ };
83
+ const around = options.around?.fetch;
84
+ return around ? around(request, env, ctx, dispatch) : dispatch();
85
+ },
86
+ async scheduled(controller, env, ctx) {
87
+ const dispatch = async () => {
88
+ const app = await getApplication();
89
+ const moduleRef = app.get(ModuleRef);
90
+ let scheduled;
91
+ try {
92
+ // ModuleRef lookups bypass the application's logging exception proxy.
93
+ scheduled = moduleRef.get(CRON_EXPLORER, {
94
+ strict: false,
95
+ });
96
+ }
97
+ catch {
98
+ // The schedule integration is optional for applications without cron handlers.
99
+ }
100
+ if (scheduled?.dispatchAndWait) {
101
+ if (await scheduled.dispatchAndWait(controller, ctx)) {
102
+ return;
103
+ }
104
+ }
105
+ else if (scheduled?.dispatch(controller, ctx)) {
106
+ return;
107
+ }
108
+ if (options.fallback?.scheduled) {
109
+ await options.fallback.scheduled(controller, env, ctx);
110
+ }
111
+ else {
112
+ logger.warn(`No Cloudflare cron handler for expression: ${controller.cron}. Import CloudflareScheduleModule.forRoot() and declare a matching @Cron method`);
113
+ }
114
+ };
115
+ const invoke = async () => {
116
+ const app = await getApplication();
117
+ await runWithContext(app, { env, ctx }, () => dispatch());
118
+ };
119
+ const around = options.around?.scheduled;
120
+ return around ? around(controller, env, ctx, invoke) : invoke();
121
+ },
122
+ async queue(batch, env, ctx) {
123
+ const dispatch = async () => {
124
+ const app = await getApplication();
125
+ const transports = [];
126
+ for (const microservice of app.getMicroservices()) {
127
+ let transport;
128
+ try {
129
+ transport = microservice.unwrap();
130
+ }
131
+ catch {
132
+ continue;
133
+ }
134
+ if (typeof transport === 'object' &&
135
+ transport !== null &&
136
+ 'transportId' in transport &&
137
+ transport.transportId === CLOUDFLARE_QUEUE_TRANSPORT) {
138
+ transports.push(transport);
139
+ }
140
+ }
141
+ if (transports.length > 1) {
142
+ throw new Error('Connect exactly one CloudflareQueueServer to dispatch Worker queue events');
143
+ }
144
+ const fallback = options.fallback?.queue;
145
+ if (!transports[0]) {
146
+ if (fallback) {
147
+ await fallback(batch, env, ctx);
148
+ return;
149
+ }
150
+ throw new Error('Connect a CloudflareQueueServer with app.connectMicroservice() before handling queue events');
151
+ }
152
+ await transports[0].consume(batch, ctx, fallback ? () => fallback(batch, env, ctx) : undefined);
153
+ };
154
+ const invoke = async () => {
155
+ const app = await getApplication();
156
+ await runWithContext(app, { env, ctx }, () => dispatch());
157
+ };
158
+ const around = options.around?.queue;
159
+ return around ? around(batch, env, ctx, invoke) : invoke();
160
+ },
161
+ };
162
+ }
163
+ function validateRouting(app, options) {
164
+ const instance = app.getHttpAdapter().getInstance();
165
+ const settings = [
166
+ [
167
+ 'case sensitive routing',
168
+ options.routing?.caseSensitive ?? options.routing?.caseSensitiveRouting,
169
+ ],
170
+ [
171
+ 'strict routing',
172
+ options.routing?.strict ?? options.routing?.strictRouting,
173
+ ],
174
+ ];
175
+ for (const [name, expected] of settings) {
176
+ if (expected !== undefined && instance.enabled(name) !== expected) {
177
+ throw new Error(`Configure Express with instance.set('${name}', ${expected}) before passing it to new ExpressAdapter(instance) in bootstrap`);
178
+ }
179
+ }
180
+ }
181
+ function createRouteMatcher(app, options) {
182
+ const instance = app.getHttpAdapter().getInstance();
183
+ const stack = instance._router?.stack ?? instance.router?.stack ?? [];
184
+ const headImplicitMatch = options.routing?.headImplicitMatch ?? true;
185
+ return request => {
186
+ const url = new URL(request.url);
187
+ for (const layer of stack) {
188
+ if (!layer.route) {
189
+ continue;
190
+ }
191
+ let pathMatches;
192
+ try {
193
+ pathMatches = layer.match(url.pathname);
194
+ }
195
+ catch (error) {
196
+ if (error instanceof URIError) {
197
+ return { matched: false, routeError: error };
198
+ }
199
+ throw error;
200
+ }
201
+ if (!pathMatches) {
202
+ continue;
203
+ }
204
+ if (matchesMethod(layer.route, request.method, headImplicitMatch)) {
205
+ return { matched: true };
206
+ }
207
+ }
208
+ return { matched: false };
209
+ };
210
+ }
211
+ function matchesMethod(route, method, headImplicitMatch) {
212
+ const name = method.toLowerCase();
213
+ if (name === 'head' && !headImplicitMatch) {
214
+ return Boolean(route.methods?.head);
215
+ }
216
+ const handlesMethod = route._handlesMethod ?? route._handles_method;
217
+ if (handlesMethod) {
218
+ return handlesMethod.call(route, method);
219
+ }
220
+ return Boolean(route.methods?._all ||
221
+ route.methods?.[name] ||
222
+ (name === 'head' && route.methods?.get));
223
+ }
@@ -0,0 +1,19 @@
1
+ type CloudflareExecutionContext = ExecutionContext | DurableObjectState;
2
+ type IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
3
+ export interface CloudflareRequestContextValue<Env = unknown> {
4
+ readonly request?: IncomingRequest;
5
+ readonly env: Env;
6
+ readonly ctx: CloudflareExecutionContext;
7
+ readonly routeError?: URIError;
8
+ }
9
+ /** Provides the native event values for the current Nest invocation. */
10
+ export declare class CloudflareRequestContext<Env = unknown> {
11
+ private readonly storage;
12
+ run<T>(value: CloudflareRequestContextValue<Env>, callback: () => T): T;
13
+ get(): CloudflareRequestContextValue<Env>;
14
+ getRequest(): IncomingRequest | undefined;
15
+ getEnv(): Env;
16
+ getExecutionContext(): CloudflareExecutionContext;
17
+ getRouteError(): URIError | undefined;
18
+ }
19
+ export {};
@@ -0,0 +1,38 @@
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
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
+ import { Injectable } from '@nestjs/common';
9
+ /** Provides the native event values for the current Nest invocation. */
10
+ let CloudflareRequestContext = class CloudflareRequestContext {
11
+ storage = new AsyncLocalStorage();
12
+ run(value, callback) {
13
+ return this.storage.run(value, callback);
14
+ }
15
+ get() {
16
+ const value = this.storage.getStore();
17
+ if (!value) {
18
+ throw new Error('Cloudflare request context is unavailable outside an event');
19
+ }
20
+ return value;
21
+ }
22
+ getRequest() {
23
+ return this.get().request;
24
+ }
25
+ getEnv() {
26
+ return this.get().env;
27
+ }
28
+ getExecutionContext() {
29
+ return this.get().ctx;
30
+ }
31
+ getRouteError() {
32
+ return this.get().routeError;
33
+ }
34
+ };
35
+ CloudflareRequestContext = __decorate([
36
+ Injectable()
37
+ ], CloudflareRequestContext);
38
+ export { CloudflareRequestContext };
@@ -0,0 +1,3 @@
1
+ import type { CloudflareWorkerWebSocketRoute } from '../interfaces/worker-options.interface.js';
2
+ export declare function findWebSocketRoute<Env>(request: Request, routes?: readonly CloudflareWorkerWebSocketRoute<Env>[]): CloudflareWorkerWebSocketRoute<Env> | undefined;
3
+ export declare function forwardWebSocketRequest<Env>(request: Request<unknown, IncomingRequestCfProperties>, env: Env, route: CloudflareWorkerWebSocketRoute<Env>): Promise<Response>;
@@ -0,0 +1,10 @@
1
+ export function findWebSocketRoute(request, routes = []) {
2
+ const path = new URL(request.url).pathname;
3
+ return routes.find(route => route.paths.includes(path));
4
+ }
5
+ export function forwardWebSocketRequest(request, env, route) {
6
+ const namespace = env[route.binding];
7
+ const object = typeof route.object === 'function' ? route.object(request) : route.object;
8
+ const id = typeof object === 'string' ? namespace.idFromName(object) : object;
9
+ return namespace.get(id).fetch(request);
10
+ }
package/package.json CHANGED
@@ -1,6 +1,113 @@
1
1
  {
2
2
  "name": "nestjs-cloudflare",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "import": "./dist/index.js"
9
+ },
10
+ "./durable-objects": {
11
+ "types": "./dist/durable-objects/index.d.ts",
12
+ "import": "./dist/durable-objects/index.js"
13
+ },
14
+ "./queue": {
15
+ "types": "./dist/queue/index.d.ts",
16
+ "import": "./dist/queue/index.js"
17
+ },
18
+ "./schedule": {
19
+ "types": "./dist/schedule/index.d.ts",
20
+ "import": "./dist/schedule/index.js"
21
+ },
22
+ "./websockets": {
23
+ "types": "./dist/websockets/index.d.ts",
24
+ "import": "./dist/websockets/index.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.build.json",
32
+ "prepare": "tsc",
33
+ "build:example": "tsc -p tsconfig.example.json",
34
+ "test:types": "tsc -p tsconfig.test.json",
35
+ "lint": "eslint . && prettier --check .",
36
+ "test": "vitest run",
37
+ "format": "prettier --write .",
38
+ "prepublishOnly": "npm run build"
39
+ },
40
+ "devDependencies": {
41
+ "@cloudflare/vitest-plugin": "1.7.0",
42
+ "@cloudflare/workers-types": "5.20261110.1",
43
+ "@eslint/js": "^9.39.0",
44
+ "@nestjs/common": "12.4.2",
45
+ "@nestjs/core": "12.4.2",
46
+ "@nestjs/microservices": "12.4.2",
47
+ "@nestjs/platform-express": "12.4.2",
48
+ "@nestjs/schedule": "12.0.3",
49
+ "@nestjs/testing": "12.4.2",
50
+ "@nestjs/websockets": "12.4.2",
51
+ "@stylistic/eslint-plugin": "5.10.0",
52
+ "@vitest/eslint-plugin": "1.6.28",
53
+ "@types/node": "26.6.6",
54
+ "eslint": "^9.39.0",
55
+ "eslint-config-prettier": "^10.1.8",
56
+ "eslint-plugin-simple-import-sort": "14.0.0",
57
+ "prettier": "^3.9.10",
58
+ "reflect-metadata": "0.2.2",
59
+ "rxjs": "7.8.2",
60
+ "typescript": "^6.0.0",
61
+ "typescript-eslint": "^8.72.2",
62
+ "vite": "8.3.8",
63
+ "vitest": "4.1.0",
64
+ "wrangler": "4.159.0"
65
+ },
66
+ "repository": {
67
+ "type": "git",
68
+ "url": "git+https://github.com/blockchainian/nestjs-cloudflare.git"
69
+ },
70
+ "peerDependencies": {
71
+ "@nestjs/common": "^12.0.0",
72
+ "@nestjs/core": "^12.0.0",
73
+ "@nestjs/microservices": "^12.0.0",
74
+ "reflect-metadata": "^0.2.2",
75
+ "rxjs": "^7.8.0",
76
+ "@nestjs/schedule": "^12.0.0",
77
+ "@nestjs/websockets": "^12.0.0",
78
+ "@cloudflare/workers-types": "5.20261110.1"
79
+ },
80
+ "peerDependenciesMeta": {
81
+ "@cloudflare/workers-types": {
82
+ "optional": true
83
+ },
84
+ "@nestjs/microservices": {
85
+ "optional": true
86
+ },
87
+ "@nestjs/schedule": {
88
+ "optional": true
89
+ },
90
+ "@nestjs/websockets": {
91
+ "optional": true
92
+ }
93
+ },
94
+ "description": "NestJS integrations for Cloudflare Workers, Queues, scheduled events, and Durable Objects.",
95
+ "keywords": [
96
+ "nestjs",
97
+ "cloudflare",
98
+ "workers",
99
+ "queues",
100
+ "durable-objects"
101
+ ],
102
+ "engines": {
103
+ "node": ">=22.12.0"
104
+ },
105
+ "license": "MIT",
106
+ "homepage": "https://github.com/blockchainian/nestjs-cloudflare#readme",
107
+ "bugs": {
108
+ "url": "https://github.com/blockchainian/nestjs-cloudflare/issues"
109
+ },
110
+ "publishConfig": {
111
+ "access": "public"
112
+ }
113
+ }