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,55 @@
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
+ import { CloudflareRequestContext } from './worker/request-context.js';
13
+ export { CloudflareRequestContext } from './worker/request-context.js';
14
+ /**
15
+ * Makes the native Cloudflare environment and its bindings available to Nest.
16
+ *
17
+ * @publicApi
18
+ */
19
+ let CloudflareModule = CloudflareModule_1 = class CloudflareModule {
20
+ /** Registers the environment's bindings once in the application's root module. */
21
+ static forRoot() {
22
+ const bindings = [];
23
+ for (const name of Object.keys(env)) {
24
+ const binding = Reflect.get(env, name);
25
+ if (hasModuleInitHook(binding)) {
26
+ continue;
27
+ }
28
+ bindings.push({ provide: getBindingToken(name), useValue: binding });
29
+ }
30
+ return {
31
+ module: CloudflareModule_1,
32
+ providers: [
33
+ CloudflareRequestContext,
34
+ { provide: CLOUDFLARE_ENV, useValue: env },
35
+ ...bindings,
36
+ ],
37
+ exports: [
38
+ CloudflareRequestContext,
39
+ CLOUDFLARE_ENV,
40
+ ...bindings.map(binding => binding.provide),
41
+ ],
42
+ };
43
+ }
44
+ };
45
+ CloudflareModule = CloudflareModule_1 = __decorate([
46
+ Global(),
47
+ Module({})
48
+ ], CloudflareModule);
49
+ export { CloudflareModule };
50
+ /** RPC stubs expose callable properties that Nest would invoke as lifecycle hooks. */
51
+ function hasModuleInitHook(binding) {
52
+ return (binding !== null &&
53
+ (typeof binding === 'object' || typeof binding === 'function') &&
54
+ typeof Reflect.get(binding, 'onModuleInit') === 'function');
55
+ }
@@ -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,13 @@
1
+ import { ClientProxy, type ReadPacket, type WritePacket } from '@nestjs/microservices';
2
+ import type { CloudflareDurableObjectClientOptions } from './interfaces/client-options.interface.js';
3
+ /** Publishes Nest packets through native Durable Object RPC. */
4
+ export declare class CloudflareDurableObjectClient extends ClientProxy {
5
+ private readonly options;
6
+ constructor(options: CloudflareDurableObjectClientOptions);
7
+ connect(): Promise<DurableObjectNamespace>;
8
+ close(): void;
9
+ unwrap<T>(): T;
10
+ protected publish(packet: ReadPacket, callback: (packet: WritePacket) => void): () => void;
11
+ protected dispatchEvent<T>(packet: ReadPacket): Promise<T>;
12
+ private request;
13
+ }
@@ -0,0 +1,67 @@
1
+ import { ClientProxy, } from '@nestjs/microservices';
2
+ import { CloudflareDurableObjectRecordSerializer } from './record.serializer.js';
3
+ /** Publishes Nest packets through native Durable Object RPC. */
4
+ export class CloudflareDurableObjectClient extends ClientProxy {
5
+ options;
6
+ constructor(options) {
7
+ super();
8
+ this.options = options;
9
+ this.initializeSerializer({
10
+ ...options,
11
+ serializer: options.serializer ?? new CloudflareDurableObjectRecordSerializer(),
12
+ });
13
+ this.initializeDeserializer(options);
14
+ }
15
+ async connect() {
16
+ return this.options.namespace;
17
+ }
18
+ close() { }
19
+ unwrap() {
20
+ return this.options.namespace;
21
+ }
22
+ publish(packet, callback) {
23
+ let active = true;
24
+ void this.request(this.assignPacketId(packet))
25
+ .then(async (replies) => {
26
+ for (const reply of replies) {
27
+ const response = await this.deserializer.deserialize(reply);
28
+ if (active) {
29
+ callback(response);
30
+ }
31
+ }
32
+ })
33
+ .catch((err) => {
34
+ if (active) {
35
+ callback({ err });
36
+ }
37
+ });
38
+ return () => {
39
+ active = false;
40
+ };
41
+ }
42
+ async dispatchEvent(packet) {
43
+ const replies = await this.request(packet);
44
+ const packets = await Promise.all(replies.map(reply => this.deserializer.deserialize(reply)));
45
+ const failure = packets.find(reply => reply.err !== undefined);
46
+ if (failure) {
47
+ throw failure.err;
48
+ }
49
+ return undefined;
50
+ }
51
+ async request(packet) {
52
+ const { options, ...message } = await this.serializer.serialize({
53
+ ...packet,
54
+ pattern: this.normalizePattern(packet.pattern),
55
+ });
56
+ if (!options ||
57
+ (typeof options.name !== 'string' && typeof options.id !== 'string')) {
58
+ throw new Error('Durable Object messages require a record with a name or ID');
59
+ }
60
+ const namespace = this.options.namespace;
61
+ const id = options.id === undefined
62
+ ? namespace.idFromName(options.name)
63
+ : namespace.idFromString(options.id);
64
+ const stub = namespace.get(id);
65
+ return stub.dispatch(message);
66
+ }
67
+ }
@@ -0,0 +1 @@
1
+ export declare const CLOUDFLARE_DURABLE_OBJECT_TRANSPORT: unique symbol;
@@ -0,0 +1 @@
1
+ export const CLOUDFLARE_DURABLE_OBJECT_TRANSPORT = Symbol('CLOUDFLARE_DURABLE_OBJECT_TRANSPORT');
@@ -0,0 +1,18 @@
1
+ import type { INestApplicationContext, InjectionToken } from '@nestjs/common';
2
+ import { type ContextId, type ContextIdStrategy, type HostComponentInfo } from '@nestjs/core';
3
+ /** Groups durable dependency trees by their owning Durable Object activation. */
4
+ export declare class DurableObjectContextIdStrategy implements ContextIdStrategy<object> {
5
+ attach(contextId: ContextId, request: object): {
6
+ resolve: (info: HostComponentInfo) => ContextId;
7
+ payload: {
8
+ durableObjectId: string;
9
+ ctx: DurableObjectState<unknown>;
10
+ };
11
+ } | undefined;
12
+ }
13
+ /** Associates a native event source with its object's Nest dependency tree. */
14
+ export declare function attachDurableObjectContext(source: object, ctx: DurableObjectState): void;
15
+ /** Creates an event context whose durable providers belong to this object. */
16
+ export declare function getDurableObjectContextId(ctx: DurableObjectState): ContextId;
17
+ /** Resolves a provider for fetch, alarm, or RPC in the current object. */
18
+ export declare function resolveForDurableObject<T>(app: INestApplicationContext, ctx: DurableObjectState, token: InjectionToken<T>): Promise<T>;
@@ -0,0 +1,53 @@
1
+ import { ContextIdFactory, } from '@nestjs/core';
2
+ const owners = new WeakMap();
3
+ const contexts = new WeakMap();
4
+ let installed = false;
5
+ /** Groups durable dependency trees by their owning Durable Object activation. */
6
+ export class DurableObjectContextIdStrategy {
7
+ attach(contextId, request) {
8
+ const ctx = owners.get(request) ?? getWrappedOwner(request);
9
+ if (!ctx) {
10
+ return;
11
+ }
12
+ let parent = contexts.get(ctx);
13
+ if (!parent) {
14
+ parent = ContextIdFactory.create();
15
+ contexts.set(ctx, parent);
16
+ }
17
+ const durableContextId = parent;
18
+ return {
19
+ resolve: (info) => info.isTreeDurable ? durableContextId : contextId,
20
+ payload: { durableObjectId: ctx.id.toString(), ctx },
21
+ };
22
+ }
23
+ }
24
+ /** Associates a native event source with its object's Nest dependency tree. */
25
+ export function attachDurableObjectContext(source, ctx) {
26
+ if (!installed) {
27
+ ContextIdFactory.apply(new DurableObjectContextIdStrategy());
28
+ installed = true;
29
+ }
30
+ owners.set(source, ctx);
31
+ }
32
+ /** Creates an event context whose durable providers belong to this object. */
33
+ export function getDurableObjectContextId(ctx) {
34
+ const event = {};
35
+ attachDurableObjectContext(event, ctx);
36
+ return ContextIdFactory.getByRequest(event);
37
+ }
38
+ /** Resolves a provider for fetch, alarm, or RPC in the current object. */
39
+ export function resolveForDurableObject(app, ctx, token) {
40
+ const contextId = getDurableObjectContextId(ctx);
41
+ app.registerRequestByContextId(contextId.payload, contextId);
42
+ return app.resolve(token, contextId, { strict: false });
43
+ }
44
+ /** Reads the public Nest RequestContext wrapper without depending on Nest internals. */
45
+ function getWrappedOwner(request) {
46
+ if (!('getContext' in request) || typeof request.getContext !== 'function') {
47
+ return;
48
+ }
49
+ const context = request.getContext();
50
+ return context !== null && typeof context === 'object'
51
+ ? owners.get(context)
52
+ : undefined;
53
+ }
@@ -0,0 +1,9 @@
1
+ import { BaseRpcContext } from '@nestjs/microservices';
2
+ type ContextArgs<Env> = [DurableObjectState, Env, string];
3
+ /** Exposes the native object event and matched Nest pattern. */
4
+ export declare class CloudflareDurableObjectContext<Env = Cloudflare.Env> extends BaseRpcContext<ContextArgs<Env>> {
5
+ getState(): DurableObjectState;
6
+ getEnv(): Env;
7
+ getPattern(): string;
8
+ }
9
+ export {};
@@ -0,0 +1,13 @@
1
+ import { BaseRpcContext } from '@nestjs/microservices';
2
+ /** Exposes the native object event and matched Nest pattern. */
3
+ export class CloudflareDurableObjectContext extends BaseRpcContext {
4
+ getState() {
5
+ return this.args[0];
6
+ }
7
+ getEnv() {
8
+ return this.args[1];
9
+ }
10
+ getPattern() {
11
+ return this.args[2];
12
+ }
13
+ }
@@ -0,0 +1,11 @@
1
+ import type { ReadPacket, WritePacket } from '@nestjs/microservices';
2
+ import { DurableObject } from 'cloudflare:workers';
3
+ import type { CloudflareDurableObjectOptions } from './interfaces/server-options.interface.js';
4
+ /** Hosts a Nest microservice transport inside a native Durable Object. */
5
+ export declare abstract class CloudflareDurableObject<Env = Cloudflare.Env> extends DurableObject<Env> {
6
+ private readonly options;
7
+ constructor(state: DurableObjectState, env: Env, options: CloudflareDurableObjectOptions);
8
+ dispatch(packet: ReadPacket): Promise<WritePacket[]>;
9
+ alarm(): Promise<void>;
10
+ private run;
11
+ }
@@ -0,0 +1,21 @@
1
+ import { DurableObject } from 'cloudflare:workers';
2
+ import { CloudflareRequestContext } from '../worker/request-context.js';
3
+ /** Hosts a Nest microservice transport inside a native Durable Object. */
4
+ export class CloudflareDurableObject extends DurableObject {
5
+ options;
6
+ constructor(state, env, options) {
7
+ super(state, env);
8
+ this.options = options;
9
+ }
10
+ async dispatch(packet) {
11
+ return this.run(() => this.options.server.dispatch(packet, this.ctx, this.env));
12
+ }
13
+ async alarm() {
14
+ await this.run(() => this.options.server.dispatchAlarm(this.options.alarmPattern ?? 'alarm', this.ctx, this.env));
15
+ }
16
+ async run(callback) {
17
+ const app = await this.options.getApplication();
18
+ const context = app.get(CloudflareRequestContext);
19
+ return context.run({ env: this.env, ctx: this.ctx }, callback);
20
+ }
21
+ }
@@ -0,0 +1,9 @@
1
+ export { CloudflareDurableObjectClient } from './client.js';
2
+ export { CLOUDFLARE_DURABLE_OBJECT_TRANSPORT } from './constants.js';
3
+ export { CloudflareDurableObjectContext } from './context.transport.js';
4
+ export { CloudflareDurableObject } from './durable-object.js';
5
+ export type * from './interfaces/client-options.interface.js';
6
+ export type * from './interfaces/server-options.interface.js';
7
+ export { CloudflareDurableObjectRecordSerializer } from './record.serializer.js';
8
+ export * from './record-builder.js';
9
+ export { CloudflareDurableObjectServer } from './server.js';
@@ -0,0 +1,7 @@
1
+ export { CloudflareDurableObjectClient } from './client.js';
2
+ export { CLOUDFLARE_DURABLE_OBJECT_TRANSPORT } from './constants.js';
3
+ export { CloudflareDurableObjectContext } from './context.transport.js';
4
+ export { CloudflareDurableObject } from './durable-object.js';
5
+ export { CloudflareDurableObjectRecordSerializer } from './record.serializer.js';
6
+ export * from './record-builder.js';
7
+ export { CloudflareDurableObjectServer } from './server.js';
@@ -0,0 +1,15 @@
1
+ import type { Deserializer, Serializer } from '@nestjs/microservices';
2
+ /** Configures a Durable Object client registered through ClientsModule. */
3
+ export interface CloudflareDurableObjectClientOptions {
4
+ namespace: DurableObjectNamespace;
5
+ serializer?: Serializer;
6
+ deserializer?: Deserializer;
7
+ }
8
+ /** Selects one object for an outgoing message. IDs use their string representation. */
9
+ export type CloudflareDurableObjectRecordOptions = {
10
+ name: string;
11
+ id?: never;
12
+ } | {
13
+ id: string;
14
+ name?: never;
15
+ };
@@ -0,0 +1,14 @@
1
+ import type { INestApplicationContext } from '@nestjs/common';
2
+ import type { Deserializer, MsPattern, Serializer } from '@nestjs/microservices';
3
+ import type { CloudflareDurableObjectServer } from '../server.js';
4
+ /** Configures Nest packet serialization. */
5
+ export interface CloudflareDurableObjectServerOptions {
6
+ serializer?: Serializer;
7
+ deserializer?: Deserializer;
8
+ }
9
+ /** Selects the application's transport and native alarm event pattern. */
10
+ export interface CloudflareDurableObjectOptions {
11
+ server: CloudflareDurableObjectServer;
12
+ getApplication: () => Promise<INestApplicationContext>;
13
+ alarmPattern?: MsPattern;
14
+ }
@@ -0,0 +1,16 @@
1
+ import type { CloudflareDurableObjectRecordOptions } from './interfaces/client-options.interface.js';
2
+ /** Carries message data and per-call object addressing. */
3
+ export declare class CloudflareDurableObjectRecord<T = unknown> {
4
+ readonly data: T;
5
+ readonly options?: CloudflareDurableObjectRecordOptions | undefined;
6
+ constructor(data: T, options?: CloudflareDurableObjectRecordOptions | undefined);
7
+ }
8
+ /** Builds transport records using Nest's record builder convention. */
9
+ export declare class CloudflareDurableObjectRecordBuilder<T = unknown> {
10
+ private data;
11
+ private options?;
12
+ constructor(data: T);
13
+ setData(data: T): this;
14
+ setOptions(options: CloudflareDurableObjectRecordOptions): this;
15
+ build(): CloudflareDurableObjectRecord<T>;
16
+ }
@@ -0,0 +1,28 @@
1
+ /** Carries message data and per-call object addressing. */
2
+ export class CloudflareDurableObjectRecord {
3
+ data;
4
+ options;
5
+ constructor(data, options) {
6
+ this.data = data;
7
+ this.options = options;
8
+ }
9
+ }
10
+ /** Builds transport records using Nest's record builder convention. */
11
+ export class CloudflareDurableObjectRecordBuilder {
12
+ data;
13
+ options;
14
+ constructor(data) {
15
+ this.data = data;
16
+ }
17
+ setData(data) {
18
+ this.data = data;
19
+ return this;
20
+ }
21
+ setOptions(options) {
22
+ this.options = options;
23
+ return this;
24
+ }
25
+ build() {
26
+ return new CloudflareDurableObjectRecord(this.data, this.options);
27
+ }
28
+ }
@@ -0,0 +1,10 @@
1
+ import type { ReadPacket, Serializer } from '@nestjs/microservices';
2
+ /** Removes native addressing options from the Nest message body. */
3
+ export declare class CloudflareDurableObjectRecordSerializer implements Serializer {
4
+ serialize(packet: ReadPacket): ReadPacket<any> | {
5
+ data: any;
6
+ options: import("./index.js").CloudflareDurableObjectRecordOptions | undefined;
7
+ pattern: any;
8
+ metadata?: import("@nestjs/microservices").PacketMetadata;
9
+ };
10
+ }
@@ -0,0 +1,10 @@
1
+ import { CloudflareDurableObjectRecord } from './record-builder.js';
2
+ /** Removes native addressing options from the Nest message body. */
3
+ export class CloudflareDurableObjectRecordSerializer {
4
+ serialize(packet) {
5
+ const record = packet.data;
6
+ return record instanceof CloudflareDurableObjectRecord
7
+ ? { ...packet, data: record.data, options: record.options }
8
+ : packet;
9
+ }
10
+ }
@@ -0,0 +1,16 @@
1
+ import { type CustomTransportStrategy, type MsPattern, type ReadPacket, Server, type WritePacket } from '@nestjs/microservices';
2
+ import { CloudflareDurableObjectContext } from './context.transport.js';
3
+ import type { CloudflareDurableObjectServerOptions } from './interfaces/server-options.interface.js';
4
+ /** Dispatches native object messages through Nest microservice handlers. */
5
+ export declare class CloudflareDurableObjectServer extends Server implements CustomTransportStrategy {
6
+ readonly propagatesEventHandlerErrors = true;
7
+ transportId: symbol;
8
+ constructor(options?: CloudflareDurableObjectServerOptions);
9
+ listen(callback: () => void): void;
10
+ close(): void;
11
+ on(): never;
12
+ unwrap<T>(): T;
13
+ dispatch(raw: ReadPacket, state: DurableObjectState, env: unknown): Promise<WritePacket[]>;
14
+ handleEvent(pattern: string, packet: ReadPacket, context: CloudflareDurableObjectContext<unknown>): Promise<void>;
15
+ dispatchAlarm(pattern: MsPattern, state: DurableObjectState, env: unknown): Promise<void>;
16
+ }
@@ -0,0 +1,101 @@
1
+ import { Server, } from '@nestjs/microservices';
2
+ import { finalize, isObservable, lastValueFrom } from 'rxjs';
3
+ import { CLOUDFLARE_DURABLE_OBJECT_TRANSPORT } from './constants.js';
4
+ import { attachDurableObjectContext } from './context.js';
5
+ import { CloudflareDurableObjectContext } from './context.transport.js';
6
+ /** Dispatches native object messages through Nest microservice handlers. */
7
+ export class CloudflareDurableObjectServer extends Server {
8
+ propagatesEventHandlerErrors = true;
9
+ transportId = CLOUDFLARE_DURABLE_OBJECT_TRANSPORT;
10
+ constructor(options = {}) {
11
+ super();
12
+ this.initializeSerializer(options);
13
+ this.initializeDeserializer(options);
14
+ }
15
+ listen(callback) {
16
+ callback();
17
+ }
18
+ close() { }
19
+ on() {
20
+ throw new Error('Durable Object transport has no connection events');
21
+ }
22
+ unwrap() {
23
+ return this;
24
+ }
25
+ async dispatch(raw, state, env) {
26
+ const packet = await this.deserializer.deserialize(raw);
27
+ const pattern = this.normalizePattern(packet.pattern);
28
+ const context = new CloudflareDurableObjectContext([state, env, pattern]);
29
+ attachDurableObjectContext(context, state);
30
+ const handler = this.getHandlerByPattern(pattern);
31
+ if (!handler) {
32
+ return [{ err: `No handler for pattern: ${pattern}`, isDisposed: true }];
33
+ }
34
+ if (!('id' in packet) || packet.id === undefined) {
35
+ try {
36
+ await this.handleEvent(pattern, packet, context);
37
+ return [];
38
+ }
39
+ catch (err) {
40
+ return [
41
+ await this.serializer.serialize({
42
+ err,
43
+ isDisposed: true,
44
+ id: '',
45
+ }),
46
+ ];
47
+ }
48
+ }
49
+ this.warnIfEventHandlerReplies(handler, pattern);
50
+ return new Promise((resolve, reject) => {
51
+ const replies = [];
52
+ this.runWithProcessingHooks(context, async (end) => {
53
+ try {
54
+ const result = await handler(packet.data, context);
55
+ this.send(this.transformToObservable(result).pipe(finalize(end)), async (reply) => {
56
+ try {
57
+ replies.push(await this.serializer.serialize({ ...reply, id: packet.id }));
58
+ if (reply.isDisposed) {
59
+ resolve(replies);
60
+ }
61
+ }
62
+ catch (error) {
63
+ reject(error);
64
+ }
65
+ });
66
+ }
67
+ catch (error) {
68
+ end();
69
+ reject(error);
70
+ }
71
+ });
72
+ });
73
+ }
74
+ async handleEvent(pattern, packet, context) {
75
+ const handler = this.getHandlerByPattern(pattern);
76
+ if (!handler?.isEventHandler) {
77
+ throw new Error(`No EventPattern handler for pattern: ${pattern}`);
78
+ }
79
+ await this.runWithProcessingHooks(context, async (end) => {
80
+ const result = await handler(packet.data, context);
81
+ if (isObservable(result)) {
82
+ await lastValueFrom(result.pipe(finalize(end)), {
83
+ defaultValue: undefined,
84
+ });
85
+ }
86
+ else {
87
+ end();
88
+ }
89
+ });
90
+ }
91
+ async dispatchAlarm(pattern, state, env) {
92
+ const normalized = this.normalizePattern(pattern);
93
+ const context = new CloudflareDurableObjectContext([
94
+ state,
95
+ env,
96
+ normalized,
97
+ ]);
98
+ attachDurableObjectContext(context, state);
99
+ await this.handleEvent(normalized, { pattern, data: undefined }, context);
100
+ }
101
+ }
@@ -0,0 +1,12 @@
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 { DurableObjectContextIdStrategy } from './durable-objects/context.js';
6
+ export { getDurableObjectContextId } from './durable-objects/context.js';
7
+ export { resolveForDurableObject } from './durable-objects/context.js';
8
+ export type { CloudflareWorker } from './interfaces/worker.interface.js';
9
+ export type { CloudflareWorkerOptions } from './interfaces/worker-options.interface.js';
10
+ export type { CloudflareWorkerWebSocketRoute } from './interfaces/worker-options.interface.js';
11
+ export { createWorker } from './worker/create-worker.js';
12
+ export { CloudflareRequestContext } from './worker/request-context.js';
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
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 { DurableObjectContextIdStrategy } from './durable-objects/context.js';
6
+ export { getDurableObjectContextId } from './durable-objects/context.js';
7
+ export { resolveForDurableObject } from './durable-objects/context.js';
8
+ export { createWorker } from './worker/create-worker.js';
9
+ export { CloudflareRequestContext } from './worker/request-context.js';
@@ -0,0 +1,45 @@
1
+ type WorkerExecutionContext = ExecutionContext;
2
+ type IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
3
+ /**
4
+ * Configures native event dispatch, routing, and fallbacks.
5
+ *
6
+ * @publicApi
7
+ */
8
+ export interface CloudflareWorkerOptions<Env = Cloudflare.Env> {
9
+ /** Wraps complete native event dispatch. */
10
+ around?: {
11
+ fetch?: CloudflareWorkerAroundFetch<Env>;
12
+ scheduled?: CloudflareWorkerAroundScheduled<Env>;
13
+ queue?: CloudflareWorkerAroundQueue<Env>;
14
+ };
15
+ /** Forwards matching paths directly to Durable Objects, including non-upgrade requests. */
16
+ websockets?: readonly CloudflareWorkerWebSocketRoute<Env>[];
17
+ /** Validates Express settings and controls implicit HEAD pre-matching. */
18
+ routing?: {
19
+ caseSensitive?: boolean;
20
+ strict?: boolean;
21
+ /** Allows HEAD to pre-match GET routes. Defaults to true. */
22
+ headImplicitMatch?: boolean;
23
+ caseSensitiveRouting?: boolean;
24
+ strictRouting?: boolean;
25
+ };
26
+ /** Native handlers for events not handled by a connected Nest transport. */
27
+ fallback?: {
28
+ fetch?: (request: IncomingRequest, env: Env, ctx: WorkerExecutionContext) => Response | Promise<Response>;
29
+ scheduled?: (controller: ScheduledController, env: Env, ctx: WorkerExecutionContext) => void | Promise<void>;
30
+ queue?: (batch: MessageBatch, env: Env, ctx: WorkerExecutionContext) => void | Promise<void>;
31
+ };
32
+ }
33
+ export type CloudflareWorkerAroundFetch<Env> = (request: Request<unknown, IncomingRequestCfProperties>, env: Env, ctx: ExecutionContext, next: () => Promise<Response>) => Response | Promise<Response>;
34
+ export type CloudflareWorkerAroundScheduled<Env> = (controller: ScheduledController, env: Env, ctx: ExecutionContext, next: () => Promise<void>) => void | Promise<void>;
35
+ export type CloudflareWorkerAroundQueue<Env> = (batch: MessageBatch, env: Env, ctx: ExecutionContext, next: () => Promise<void>) => void | Promise<void>;
36
+ /** Configures native WebSocket forwarding to one Durable Object. */
37
+ export interface CloudflareWorkerWebSocketRoute<Env = Cloudflare.Env> {
38
+ /** Exact URL pathnames, independent of Express routing settings. */
39
+ paths: readonly string[];
40
+ /** Durable Object namespace binding in the event environment. */
41
+ binding: Extract<keyof Env, string>;
42
+ /** A name for idFromName(), or a request resolver returning a name or native ID. */
43
+ object: string | ((request: IncomingRequest) => string | DurableObjectId);
44
+ }
45
+ export {};
@@ -0,0 +1 @@
1
+ export {};