@velajs/cloudflare 1.30.0 → 1.32.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/CHANGELOG.md +174 -0
- package/README.md +407 -77
- package/dist/bindings.js +93 -0
- package/dist/bindings.js.map +1 -0
- package/dist/cloudflare-application-CXDy9C1R.d.ts +199 -0
- package/dist/cloudflare-application.js +15 -34
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
- package/dist/cloudflare-factory.js +227 -38
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/diagnostics.js +18 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/durable-object/boot.js +76 -0
- package/dist/durable-object/boot.js.map +1 -0
- package/dist/durable-object/host-dispatch.js +134 -0
- package/dist/durable-object/host-dispatch.js.map +1 -0
- package/dist/durable-object/host-methods.js +47 -0
- package/dist/durable-object/host-methods.js.map +1 -0
- package/dist/durable-object/tokens.js +17 -0
- package/dist/durable-object/tokens.js.map +1 -0
- package/dist/durable-object/vela-durable-object.js +121 -0
- package/dist/durable-object/vela-durable-object.js.map +1 -0
- package/dist/durable-objects.d.ts +136 -10
- package/dist/durable-objects.js +3 -1
- package/dist/email/email-dispatch.js +65 -0
- package/dist/email/email-dispatch.js.map +1 -0
- package/dist/email/on-email.js +57 -0
- package/dist/email/on-email.js.map +1 -0
- package/dist/email.d.ts +51 -0
- package/dist/email.js +3 -0
- package/dist/entrypoint/vela-entrypoint.js +160 -0
- package/dist/entrypoint/vela-entrypoint.js.map +1 -0
- package/dist/entrypoints.d.ts +93 -0
- package/dist/entrypoints.js +2 -0
- package/dist/host/host-invoker.js +276 -0
- package/dist/host/host-invoker.js.map +1 -0
- package/dist/host/host-members.js +73 -0
- package/dist/host/host-members.js.map +1 -0
- package/dist/host-members-DECj_4yz.d.ts +13 -0
- package/dist/index.d.ts +211 -445
- package/dist/index.js +8 -13
- package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
- package/dist/platform.js +22 -0
- package/dist/platform.js.map +1 -0
- package/dist/queue/cloudflare-queues.js +7 -7
- package/dist/queue/cloudflare-queues.js.map +1 -1
- package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
- package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
- package/dist/root-module.js +19 -0
- package/dist/root-module.js.map +1 -0
- package/dist/rpc/entrypoint-error.js +145 -0
- package/dist/rpc/entrypoint-error.js.map +1 -0
- package/dist/schedule-diagnostics.js +8 -15
- package/dist/schedule-diagnostics.js.map +1 -1
- package/dist/services/kv-cache.store.js +33 -7
- package/dist/services/kv-cache.store.js.map +1 -1
- package/dist/storage/r2-storage.js +30 -0
- package/dist/storage/r2-storage.js.map +1 -0
- package/dist/storage.d.ts +28 -0
- package/dist/storage.js +2 -0
- package/dist/tail/on-tail.js +46 -0
- package/dist/tail/on-tail.js.map +1 -0
- package/dist/tail/tail-dispatch.js +67 -0
- package/dist/tail/tail-dispatch.js.map +1 -0
- package/dist/tail.d.ts +39 -0
- package/dist/tail.js +2 -0
- package/dist/testing.d.ts +148 -0
- package/dist/testing.js +188 -0
- package/dist/testing.js.map +1 -0
- package/dist/websocket/binding-gateways.js +33 -0
- package/dist/websocket/binding-gateways.js.map +1 -0
- package/dist/websocket/cf-room-registry.js +3 -1
- package/dist/websocket/cf-room-registry.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +64 -40
- package/dist/websocket/do-bootstrap.js.map +1 -1
- package/dist/websocket/do-live.js +49 -90
- package/dist/websocket/do-live.js.map +1 -1
- package/dist/websocket/do-state.js.map +1 -1
- package/dist/websocket/live-driver.js +149 -0
- package/dist/websocket/live-driver.js.map +1 -0
- package/dist/websocket/room-id.js +11 -1
- package/dist/websocket/room-id.js.map +1 -1
- package/dist/websocket/websocket.durable-object.js +51 -18
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/websocket/worker-transport.js +80 -0
- package/dist/websocket/worker-transport.js.map +1 -0
- package/dist/worker-events.js +49 -0
- package/dist/worker-events.js.map +1 -0
- package/dist/workflow/vela-workflow.js +104 -0
- package/dist/workflow/vela-workflow.js.map +1 -0
- package/dist/workflows.d.ts +82 -0
- package/dist/workflows.js +2 -0
- package/package.json +39 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
- package/dist/storage/r2-storage.driver.js +0 -67
- package/dist/storage/r2-storage.driver.js.map +0 -1
- package/dist/storage/storage-key-claim.js +0 -74
- package/dist/storage/storage-key-claim.js.map +0 -1
- package/dist/storage/storage-manager.service.js +0 -38
- package/dist/storage/storage-manager.service.js.map +0 -1
- package/dist/storage/storage.controller.js +0 -64
- package/dist/storage/storage.controller.js.map +0 -1
- package/dist/storage/storage.module.js +0 -25
- package/dist/storage/storage.module.js.map +0 -1
- package/dist/storage/storage.service.js +0 -64
- package/dist/storage/storage.service.js.map +0 -1
- package/dist/storage/storage.tokens.js +0 -7
- package/dist/storage/storage.tokens.js.map +0 -1
- package/dist/websocket/broadcast.js +0 -32
- package/dist/websocket/broadcast.js.map +0 -1
- package/dist/websocket/cloudflare-websocket.module.js +0 -25
- package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
- package/dist/websocket/websocket-routing.js +0 -133
- package/dist/websocket/websocket-routing.js.map +0 -1
- package/dist/websocket/ws-server-holder.js +0 -38
- package/dist/websocket/ws-server-holder.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bindings.js","names":[],"sources":["../src/bindings.ts"],"sourcesContent":["import {\n defineBinding,\n type Binding,\n type BindingKind,\n type BindingRef,\n} from '@velajs/vela/module-kit';\n\n/** Whether a value exposes every named operation as a function. */\nfunction hasOperations(value: unknown, operations: readonly string[]): boolean {\n if (typeof value !== 'object' || value === null) return false;\n return operations.every((operation) => typeof Reflect.get(value, operation) === 'function');\n}\n\n/**\n * Name-based Workers binding factories. Each takes `{ binding }`, the name\n * declared in the Wrangler configuration, and returns a reference that reads\n * and validates the native binding from an application's `ENV` when called.\n * Declaring one reads no environment, so references belong in static module\n * options: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\n\n/** A KV namespace declared under `kv_namespaces`. */\nexport const KV_NAMESPACE: BindingKind<KVNamespace> = {\n name: 'KV namespace',\n configKey: 'kv_namespaces',\n accepts: (value): value is KVNamespace =>\n hasOperations(value, ['get', 'put', 'delete', 'list', 'getWithMetadata']),\n};\nexport const kv = /* @__PURE__ */ defineBinding(KV_NAMESPACE);\n\n/** An R2 bucket declared under `r2_buckets`. */\nexport const R2_BUCKET: BindingKind<R2Bucket> = {\n name: 'R2 bucket',\n configKey: 'r2_buckets',\n accepts: (value): value is R2Bucket =>\n hasOperations(value, ['get', 'put', 'head', 'delete', 'list', 'createMultipartUpload']),\n};\nexport const r2 = /* @__PURE__ */ defineBinding(R2_BUCKET);\n\n/** A D1 database declared under `d1_databases`. */\nexport const D1_DATABASE: BindingKind<D1Database> = {\n name: 'D1 database',\n configKey: 'd1_databases',\n accepts: (value): value is D1Database => hasOperations(value, ['prepare', 'batch', 'exec']),\n};\nexport const d1 = /* @__PURE__ */ defineBinding(D1_DATABASE);\n\n/** A queue producer declared under `queues.producers`. */\nexport const QUEUE_PRODUCER: BindingKind<Queue> = {\n name: 'queue producer',\n configKey: 'queues.producers',\n accepts: (value): value is Queue => hasOperations(value, ['send']),\n};\nexport const queue = /* @__PURE__ */ defineBinding(QUEUE_PRODUCER);\n\n/** A Durable Object namespace declared under `durable_objects.bindings`. */\nexport const DURABLE_OBJECT_NAMESPACE: BindingKind<DurableObjectNamespace> = {\n name: 'Durable Object namespace',\n configKey: 'durable_objects.bindings',\n accepts: (value): value is DurableObjectNamespace => hasOperations(value, ['idFromName', 'get']),\n};\nexport const durableObject = /* @__PURE__ */ defineBinding(DURABLE_OBJECT_NAMESPACE);\n\n/** A Workers Rate Limiting binding declared under `ratelimits`. */\nexport const RATE_LIMITER: BindingKind<RateLimit> = {\n name: 'rate limiter',\n configKey: 'ratelimits',\n accepts: (value): value is RateLimit => hasOperations(value, ['limit']),\n};\nexport const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);\n\n/**\n * A reference to a Workflow binding declared under `workflows`, whose\n * instances take `Params`: for a class from `VelaWorkflow()`,\n * `workflow<WorkflowParams<SignupWorkflow>>({ binding: 'SIGNUP_WORKFLOW' })`.\n * Called with an application's ENV, it returns the native binding typed with\n * those params: `await signups(env).create({ params: { email } })`. The\n * runtime checks that the binding is a Workflow; its params are what the\n * Workflow class declares.\n */\nexport function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>> {\n return defineBinding<Workflow<Params>>({\n name: 'Workflow',\n configKey: 'workflows',\n accepts: (value): value is Workflow<Params> => hasOperations(value, ['create', 'get']),\n })(ref);\n}\n"],"mappings":";;;AAQA,SAAS,cAAc,OAAgB,YAAwC;CAC7E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,WAAW,OAAO,cAAc,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM,UAAU;AAC5F;;;;;;;;;AAWA,MAAa,eAAyC;CACpD,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAU;EAAQ;CAAiB,CAAC;AAC5E;AACA,MAAa,KAAqB,8BAAc,YAAY;;AAG5D,MAAa,YAAmC;CAC9C,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAQ;EAAU;EAAQ;CAAuB,CAAC;AAC1F;AACA,MAAa,KAAqB,8BAAc,SAAS;;AAGzD,MAAa,cAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA+B,cAAc,OAAO;EAAC;EAAW;EAAS;CAAM,CAAC;AAC5F;AACA,MAAa,KAAqB,8BAAc,WAAW;;AAG3D,MAAa,iBAAqC;CAChD,MAAM;CACN,WAAW;CACX,UAAU,UAA0B,cAAc,OAAO,CAAC,MAAM,CAAC;AACnE;AACA,MAAa,QAAwB,8BAAc,cAAc;;AAGjE,MAAa,2BAAgE;CAC3E,MAAM;CACN,WAAW;CACX,UAAU,UAA2C,cAAc,OAAO,CAAC,cAAc,KAAK,CAAC;AACjG;AACA,MAAa,gBAAgC,8BAAc,wBAAwB;;AAGnF,MAAa,eAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA8B,cAAc,OAAO,CAAC,OAAO,CAAC;AACxE;AACA,MAAa,YAA4B,8BAAc,YAAY;;;;;;;;;;AAWnE,SAAgB,SAA2B,KAA4C;CACrF,OAAO,cAAgC;EACrC,MAAM;EACN,WAAW;EACX,UAAU,UAAqC,cAAc,OAAO,CAAC,UAAU,KAAK,CAAC;CACvF,CAAC,CAAC,CAAC,GAAG;AACR"}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { CorsOptions, InjectionToken, VelaApplication, VelaEnv } from "@velajs/vela";
|
|
2
|
+
import "@velajs/vela/module-kit";
|
|
3
|
+
import { ExecutionContext } from "hono";
|
|
4
|
+
//#region src/scheduled-event.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* The event a Worker's `scheduled()` export receives. The native
|
|
7
|
+
* `ScheduledController` satisfies it; direct calls (tests, scripts) may omit
|
|
8
|
+
* `scheduledTime`, which then defaults to the current time, and `noRetry`.
|
|
9
|
+
*/
|
|
10
|
+
interface ScheduledEvent {
|
|
11
|
+
readonly cron: string;
|
|
12
|
+
readonly scheduledTime?: number;
|
|
13
|
+
noRetry?(): void;
|
|
14
|
+
}
|
|
15
|
+
/** The Cloudflare trigger behind the current scheduled invocation. */
|
|
16
|
+
interface CloudflareScheduledEvent {
|
|
17
|
+
/** The trigger's exact cron string; it equals the invocation's `expression`. */
|
|
18
|
+
readonly cron: string;
|
|
19
|
+
/** The platform's scheduled time in Unix milliseconds. */
|
|
20
|
+
readonly scheduledTime: number;
|
|
21
|
+
/**
|
|
22
|
+
* Ask Cloudflare not to retry this trigger if the invocation fails. Already
|
|
23
|
+
* bound to the native controller, so it can be passed around or destructured.
|
|
24
|
+
* A no-op for direct calls that supplied no controller.
|
|
25
|
+
*/
|
|
26
|
+
readonly noRetry: () => void;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Request-scoped Cloudflare view of the scheduled trigger, seeded into each
|
|
30
|
+
* `@Cron` job's invocation scope by the Cloudflare adapter. Inject it where a
|
|
31
|
+
* job needs platform controls such as `noRetry()`; the job's argument stays
|
|
32
|
+
* the portable `ScheduleInvocation`. It resolves only inside a scheduled
|
|
33
|
+
* invocation; resolving it anywhere else throws. A cron job fired on demand
|
|
34
|
+
* (Studio's run-now) receives a synthetic event: `cron` is the job's
|
|
35
|
+
* expression and `noRetry()` does nothing.
|
|
36
|
+
*
|
|
37
|
+
* The token provides itself as request-scoped in every container, so a class
|
|
38
|
+
* that injects it is request-scoped wherever the graph boots (a Worker, a
|
|
39
|
+
* Durable Object, the CLI or a testing module) and is built only for an
|
|
40
|
+
* invocation, never at bootstrap.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* @Injectable({ scope: Scope.REQUEST })
|
|
45
|
+
* class Reports {
|
|
46
|
+
* constructor(@Inject(CLOUDFLARE_SCHEDULED_EVENT) private readonly trigger: CloudflareScheduledEvent) {}
|
|
47
|
+
*
|
|
48
|
+
* @Cron('0 3 * * *', { dialect: 'cloudflare' })
|
|
49
|
+
* async nightly(tick: CronInvocation) {
|
|
50
|
+
* if (!(await this.upstreamAvailable(tick.signal))) this.trigger.noRetry();
|
|
51
|
+
* }
|
|
52
|
+
* }
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
declare const CLOUDFLARE_SCHEDULED_EVENT: InjectionToken<CloudflareScheduledEvent>;
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/cloudflare-application.d.ts
|
|
58
|
+
/**
|
|
59
|
+
* Options accepted by {@link CloudflareApplication.mountOpenApi}.
|
|
60
|
+
*
|
|
61
|
+
* Re-exposes vela's `MountOpenApiOptions` type — derived structurally from
|
|
62
|
+
* the underlying `VelaApplication.mountOpenApi` signature so consumers don't
|
|
63
|
+
* have to reach into vela's internal subpaths to type the argument.
|
|
64
|
+
*/
|
|
65
|
+
type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
|
|
66
|
+
/**
|
|
67
|
+
* Wraps VelaApplication with Cloudflare-specific handlers:
|
|
68
|
+
* - `fetch` — HTTP request handler (from Hono)
|
|
69
|
+
* - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose
|
|
70
|
+
* expression is the trigger's exact string)
|
|
71
|
+
* - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,
|
|
72
|
+
* then `QueueModule`'s native consumer)
|
|
73
|
+
* - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on
|
|
74
|
+
* the underlying Hono app
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```ts
|
|
78
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
79
|
+
* export default {
|
|
80
|
+
* fetch: app.fetch,
|
|
81
|
+
* scheduled: app.scheduled.bind(app),
|
|
82
|
+
* queue: app.queue.bind(app),
|
|
83
|
+
* };
|
|
84
|
+
* ```
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```ts
|
|
88
|
+
* // Serve OpenAPI docs alongside your routes
|
|
89
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
90
|
+
* const document = createOpenApiDocument(AppModule);
|
|
91
|
+
* app.mountOpenApi({ document, ui: 'scalar' });
|
|
92
|
+
* // GET /openapi.json -> JSON document
|
|
93
|
+
* // GET /scalar -> Scalar UI (loads from CDN)
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
declare class CloudflareApplication {
|
|
97
|
+
#private;
|
|
98
|
+
readonly env: VelaEnv;
|
|
99
|
+
constructor(app: VelaApplication, env: VelaEnv);
|
|
100
|
+
readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext) => Promise<Response>;
|
|
101
|
+
getHonoApp(): ReturnType<VelaApplication['getHonoApp']>;
|
|
102
|
+
/**
|
|
103
|
+
* Resolve a provider from the application's DI container (delegates to
|
|
104
|
+
* `VelaApplication.get`). Handy in `createCloudflareWorker({ configure })`,
|
|
105
|
+
* which finishes the HTTP surface outside the DI request pipeline.
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* ```ts
|
|
109
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
110
|
+
* const auth = app.get(BetterAuthService);
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
readonly get: VelaApplication['get'];
|
|
114
|
+
get entrypoints(): VelaApplication['entrypoints'];
|
|
115
|
+
/**
|
|
116
|
+
* The application's DI container (delegates to `VelaApplication.getContainer`),
|
|
117
|
+
* for dispatch seams that take it with `entrypoints`, such as
|
|
118
|
+
* `dispatchInboundEmail(app.getContainer(), app.entrypoints, email)`.
|
|
119
|
+
*/
|
|
120
|
+
getContainer(): ReturnType<VelaApplication['getContainer']>;
|
|
121
|
+
/** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */
|
|
122
|
+
enableCors(options?: CorsOptions): this;
|
|
123
|
+
/**
|
|
124
|
+
* Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the
|
|
125
|
+
* underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,
|
|
126
|
+
* so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when
|
|
127
|
+
* opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from
|
|
128
|
+
* a CDN at runtime, nothing is bundled server-side.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* ```ts
|
|
132
|
+
* import { createOpenApiDocument } from '@velajs/vela/openapi';
|
|
133
|
+
*
|
|
134
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
135
|
+
* const document = createOpenApiDocument(AppModule, {
|
|
136
|
+
* info: { title: 'My API', version: '1.0.0' },
|
|
137
|
+
* });
|
|
138
|
+
* app.mountOpenApi({ document, ui: 'scalar' });
|
|
139
|
+
* // GET /openapi.json -> { openapi: '3.1.0', ... }
|
|
140
|
+
* // GET /scalar -> Scalar UI HTML
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
mountOpenApi(options: MountOpenApiOptions): this;
|
|
144
|
+
/**
|
|
145
|
+
* Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose
|
|
146
|
+
* expression is exactly `event.cron` (the trigger string is compared as
|
|
147
|
+
* delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch
|
|
148
|
+
* primitive every runtime shares. Each job receives only its
|
|
149
|
+
* `ScheduleInvocation`, runs in a fresh invocation scope seeded with
|
|
150
|
+
* {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`
|
|
151
|
+
* dispatch. The trigger settles after every matching job and its managed
|
|
152
|
+
* work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.
|
|
153
|
+
*/
|
|
154
|
+
scheduled(event: ScheduledEvent, env: VelaEnv, _ctx?: {
|
|
155
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
156
|
+
}): Promise<void>;
|
|
157
|
+
/**
|
|
158
|
+
* Run one queue consumer inside a fresh request scope, through the shared
|
|
159
|
+
* guard → interceptor pipeline (components declared with
|
|
160
|
+
* `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or
|
|
161
|
+
* method). HTTP-global components deliberately do NOT apply — an HTTP auth
|
|
162
|
+
* guard has no business rejecting a queue batch. Unclaimed errors are
|
|
163
|
+
* reported once (`QueueModule`'s consumer reports its own) and rethrow so
|
|
164
|
+
* the platform's retry semantics stay intact.
|
|
165
|
+
*/
|
|
166
|
+
private dispatchEntrypoint;
|
|
167
|
+
/**
|
|
168
|
+
* Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read
|
|
169
|
+
* from `app.entrypoints` claim a batch by its physical queue name and
|
|
170
|
+
* receive it whole. A batch no handler claims goes to `QueueModule`'s native
|
|
171
|
+
* consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which
|
|
172
|
+
* routes each job by its logical queue. Each dispatch runs inside a fresh
|
|
173
|
+
* request-scoped child (request-scoped providers rebuild per batch — no
|
|
174
|
+
* boot-time captives). A batch nothing claims rejects: resolving would let
|
|
175
|
+
* Cloudflare acknowledge every message implicitly.
|
|
176
|
+
*/
|
|
177
|
+
queue(batch: {
|
|
178
|
+
queue: string;
|
|
179
|
+
messages: readonly unknown[];
|
|
180
|
+
}, env: VelaEnv, ctx: {
|
|
181
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
182
|
+
}): Promise<void>;
|
|
183
|
+
/**
|
|
184
|
+
* A raw `@QueueConsumer` owns its physical queue's batches and must not carry
|
|
185
|
+
* jobs of a queue registered with `QueueModule`: those reach their
|
|
186
|
+
* `@Processor` only if the raw handler dispatches them itself, while
|
|
187
|
+
* `cloudflareQueues()` delivers registered queues. Warn once per physical and
|
|
188
|
+
* logical queue (unless diagnostics are silent); the raw consumer still
|
|
189
|
+
* receives and settles the batch.
|
|
190
|
+
*/
|
|
191
|
+
private warnRawJobs;
|
|
192
|
+
/**
|
|
193
|
+
* Abort the signals of scheduled jobs still running, wait for them and their
|
|
194
|
+
* managed work to settle, then close the application.
|
|
195
|
+
*/
|
|
196
|
+
close(signal?: string): Promise<void>;
|
|
197
|
+
}
|
|
198
|
+
//#endregion
|
|
199
|
+
export { ScheduledEvent as a, CloudflareScheduledEvent as i, MountOpenApiOptions as n, CLOUDFLARE_SCHEDULED_EVENT as r, CloudflareApplication as t };
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import { collectWsGatewayRoutes } from "./websocket/websocket-routing.js";
|
|
2
1
|
import { assertCloudflareEnvironment } from "./environment.js";
|
|
3
2
|
import { CLOUDFLARE_SCHEDULED_EVENT, cloudflareScheduledEvent } from "./scheduled-event.js";
|
|
4
3
|
import { PipelineRunner, buildEntrypointExecutionContext, getEntrypointModuleId, invokeScheduledJob, parseCronMetadata, resolveEntrypoint, resolveErrorReporter, resolveScopedComponentsAsync, runInEntrypointScope, shouldFilterCatch } from "@velajs/vela/module-kit";
|
|
5
|
-
import { readWsEntrypointMeta } from "@velajs/vela/websocket";
|
|
6
4
|
//#region src/cloudflare-application.ts
|
|
7
5
|
function invoke(instance, methodName, args) {
|
|
8
6
|
const method = Reflect.get(instance, methodName);
|
|
@@ -67,7 +65,6 @@ async function settleEntrypoints(work) {
|
|
|
67
65
|
*/
|
|
68
66
|
var CloudflareApplication = class {
|
|
69
67
|
env;
|
|
70
|
-
#wsGatewayRoutes = [];
|
|
71
68
|
#app;
|
|
72
69
|
/** Scheduled triggers in flight; close() aborts their signals and awaits them. */
|
|
73
70
|
#scheduled = /* @__PURE__ */ new Map();
|
|
@@ -85,9 +82,8 @@ var CloudflareApplication = class {
|
|
|
85
82
|
}
|
|
86
83
|
/**
|
|
87
84
|
* Resolve a provider from the application's DI container (delegates to
|
|
88
|
-
* `VelaApplication.get`). Handy
|
|
89
|
-
*
|
|
90
|
-
* which runs outside the DI request pipeline.
|
|
85
|
+
* `VelaApplication.get`). Handy in `createCloudflareWorker({ configure })`,
|
|
86
|
+
* which finishes the HTTP surface outside the DI request pipeline.
|
|
91
87
|
*
|
|
92
88
|
* @example
|
|
93
89
|
* ```ts
|
|
@@ -100,6 +96,19 @@ var CloudflareApplication = class {
|
|
|
100
96
|
return this.#app.entrypoints;
|
|
101
97
|
}
|
|
102
98
|
/**
|
|
99
|
+
* The application's DI container (delegates to `VelaApplication.getContainer`),
|
|
100
|
+
* for dispatch seams that take it with `entrypoints`, such as
|
|
101
|
+
* `dispatchInboundEmail(app.getContainer(), app.entrypoints, email)`.
|
|
102
|
+
*/
|
|
103
|
+
getContainer() {
|
|
104
|
+
return this.#app.getContainer();
|
|
105
|
+
}
|
|
106
|
+
/** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */
|
|
107
|
+
enableCors(options) {
|
|
108
|
+
this.#app.enableCors(options);
|
|
109
|
+
return this;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
103
112
|
* Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the
|
|
104
113
|
* underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,
|
|
105
114
|
* so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when
|
|
@@ -124,34 +133,6 @@ var CloudflareApplication = class {
|
|
|
124
133
|
return this;
|
|
125
134
|
}
|
|
126
135
|
/**
|
|
127
|
-
* @internal Upgrade routes come from validated gateway entrypoints, including
|
|
128
|
-
* request-scoped gateways without a bootstrap instance. Retain the instance
|
|
129
|
-
* scan for legacy applications that only declare forwarding metadata.
|
|
130
|
-
*/
|
|
131
|
-
scanInstances(instances) {
|
|
132
|
-
const routes = /* @__PURE__ */ new Map();
|
|
133
|
-
for (const ep of this.#app.entrypoints.ofKind("websocket")) {
|
|
134
|
-
if (typeof ep.meta !== "object" || ep.meta === null || !("dispatcher" in ep.meta)) continue;
|
|
135
|
-
const meta = readWsEntrypointMeta(ep.meta);
|
|
136
|
-
if (meta.options.binding) routes.set(meta.path, {
|
|
137
|
-
path: meta.path,
|
|
138
|
-
binding: meta.options.binding,
|
|
139
|
-
options: { ...meta.options },
|
|
140
|
-
moduleId: meta.moduleId
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
const container = this.#app.getContainer();
|
|
144
|
-
for (const instance of instances) {
|
|
145
|
-
if (!instance || typeof instance !== "object") continue;
|
|
146
|
-
for (const route of collectWsGatewayRoutes(instance, container)) if (!routes.has(route.path)) routes.set(route.path, route);
|
|
147
|
-
}
|
|
148
|
-
this.#wsGatewayRoutes.splice(0, this.#wsGatewayRoutes.length, ...routes.values());
|
|
149
|
-
}
|
|
150
|
-
/** @internal — upgrade routes discovered from the application's gateways. */
|
|
151
|
-
getWsGatewayRoutes() {
|
|
152
|
-
return [...this.#wsGatewayRoutes];
|
|
153
|
-
}
|
|
154
|
-
/**
|
|
155
136
|
* Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose
|
|
156
137
|
* expression is exactly `event.cron` (the trigger string is compared as
|
|
157
138
|
* delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-application.js","names":[],"sources":["../src/cloudflare-application.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport type { VelaApplication, ExceptionFilter, VelaEnv } from '@velajs/vela';\nimport {\n PipelineRunner,\n buildEntrypointExecutionContext,\n getEntrypointModuleId,\n invokeScheduledJob,\n parseCronMetadata,\n resolveEntrypoint,\n resolveScopedComponentsAsync,\n resolveErrorReporter,\n runInEntrypointScope,\n shouldFilterCatch,\n} from '@velajs/vela/module-kit';\nimport type { ScheduleInvocation } from '@velajs/vela/schedule';\nimport type { Entrypoint } from '@velajs/vela/module-kit';\nimport { readWsEntrypointMeta } from '@velajs/vela/websocket';\nimport { collectWsGatewayRoutes, type WsGatewayRoute } from './websocket/websocket-routing';\nimport { assertCloudflareEnvironment } from './environment';\nimport {\n CLOUDFLARE_SCHEDULED_EVENT,\n cloudflareScheduledEvent,\n type ScheduledEvent,\n} from './scheduled-event';\n\n/**\n * Options accepted by {@link CloudflareApplication.mountOpenApi}.\n *\n * Re-exposes vela's `MountOpenApiOptions` type — derived structurally from\n * the underlying `VelaApplication.mountOpenApi` signature so consumers don't\n * have to reach into vela's internal subpaths to type the argument.\n */\nexport type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];\n\nfunction invoke(instance: object, methodName: string | symbol, args: unknown[]): unknown {\n // Decorator metadata names an instance method; inspect it before invoking.\n const method: unknown = Reflect.get(instance, methodName);\n if (typeof method !== 'function') {\n throw new Error(\n `Method '${String(methodName)}' is not a function on ${instance.constructor.name}`,\n );\n }\n return Reflect.apply(method, instance, args);\n}\n\nfunction entrypointString(meta: unknown, property: string): string {\n if (typeof meta !== 'object' || meta === null) throw new Error('Invalid entrypoint metadata.');\n const value: unknown = Reflect.get(meta, property);\n if (typeof value !== 'string')\n throw new Error(`Invalid entrypoint metadata: ${property} must be a string.`);\n return value;\n}\n\n/**\n * `QueueModule`'s native consumer reports each failure of a batch once itself\n * (processor failures where they ran, transport failures on settlement), so\n * its rejection is not reported again here.\n */\nconst SELF_REPORTING_KINDS = new Set(['cf:queue:module']);\n\nconst warnedRawJobs = new Set<string>();\n\n/** The logical queue of a Vela job envelope, without importing the queue subsystem. */\nfunction envelopeQueue(body: unknown): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined;\n const queue: unknown = Reflect.get(body, 'queue');\n if (\n typeof queue !== 'string' ||\n typeof Reflect.get(body, 'id') !== 'string' ||\n typeof Reflect.get(body, 'name') !== 'string' ||\n !('data' in body)\n ) {\n return undefined;\n }\n return queue;\n}\n\n/** Wait for every matching handler, even when one fails before its siblings. */\nasync function settleEntrypoints(work: readonly Promise<void>[]): Promise<void> {\n const outcomes = await Promise.allSettled(work);\n const errors = outcomes.flatMap((outcome) =>\n outcome.status === 'rejected' ? [outcome.reason] : [],\n );\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Multiple entrypoint handlers failed.');\n}\n\n/**\n * Wraps VelaApplication with Cloudflare-specific handlers:\n * - `fetch` — HTTP request handler (from Hono)\n * - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose\n * expression is the trigger's exact string)\n * - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,\n * then `QueueModule`'s native consumer)\n * - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on\n * the underlying Hono app\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * export default {\n * fetch: app.fetch,\n * scheduled: app.scheduled.bind(app),\n * queue: app.queue.bind(app),\n * };\n * ```\n *\n * @example\n * ```ts\n * // Serve OpenAPI docs alongside your routes\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule);\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> JSON document\n * // GET /scalar -> Scalar UI (loads from CDN)\n * ```\n */\nexport class CloudflareApplication {\n readonly #wsGatewayRoutes: WsGatewayRoute[] = [];\n readonly #app: VelaApplication;\n /** Scheduled triggers in flight; close() aborts their signals and awaits them. */\n readonly #scheduled = new Map<Promise<void>, AbortController>();\n\n constructor(\n app: VelaApplication,\n readonly env: VelaEnv,\n ) {\n this.#app = app;\n this.get = app.get.bind(app);\n }\n\n readonly fetch = async (\n request: Request,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ): Promise<Response> => {\n assertCloudflareEnvironment(this.env, env);\n return this.#app.fetch(request, env, ctx);\n };\n\n getHonoApp(): ReturnType<VelaApplication['getHonoApp']> {\n return this.#app.getHonoApp();\n }\n\n /**\n * Resolve a provider from the application's DI container (delegates to\n * `VelaApplication.get`). Handy for grabbing a service — e.g. an auth service —\n * to use inside `createCloudflareApp({ middleware: env => [...] })` request middleware,\n * which runs outside the DI request pipeline.\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * const auth = app.get(BetterAuthService);\n * ```\n */\n readonly get: VelaApplication['get'];\n\n get entrypoints(): VelaApplication['entrypoints'] {\n return this.#app.entrypoints;\n }\n\n /**\n * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the\n * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,\n * so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when\n * opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from\n * a CDN at runtime, nothing is bundled server-side.\n *\n * @example\n * ```ts\n * import { createOpenApiDocument } from '@velajs/vela/openapi';\n *\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule, {\n * info: { title: 'My API', version: '1.0.0' },\n * });\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> { openapi: '3.1.0', ... }\n * // GET /scalar -> Scalar UI HTML\n * ```\n */\n mountOpenApi(options: MountOpenApiOptions): this {\n this.#app.mountOpenApi(options);\n return this;\n }\n\n /**\n * @internal Upgrade routes come from validated gateway entrypoints, including\n * request-scoped gateways without a bootstrap instance. Retain the instance\n * scan for legacy applications that only declare forwarding metadata.\n */\n scanInstances(instances: unknown[]): void {\n const routes = new Map<string, WsGatewayRoute>();\n for (const ep of this.#app.entrypoints.ofKind('websocket')) {\n if (typeof ep.meta !== 'object' || ep.meta === null || !('dispatcher' in ep.meta)) continue;\n const meta = readWsEntrypointMeta(ep.meta);\n if (meta.options.binding) {\n routes.set(meta.path, {\n path: meta.path,\n binding: meta.options.binding,\n options: { ...meta.options },\n moduleId: meta.moduleId,\n });\n }\n }\n const container = this.#app.getContainer();\n for (const instance of instances) {\n if (!instance || typeof instance !== 'object') continue;\n for (const route of collectWsGatewayRoutes(instance, container)) {\n if (!routes.has(route.path)) routes.set(route.path, route);\n }\n }\n this.#wsGatewayRoutes.splice(0, this.#wsGatewayRoutes.length, ...routes.values());\n }\n\n /** @internal — upgrade routes discovered from the application's gateways. */\n getWsGatewayRoutes(): WsGatewayRoute[] {\n return [...this.#wsGatewayRoutes];\n }\n\n /**\n * Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose\n * expression is exactly `event.cron` (the trigger string is compared as\n * delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch\n * primitive every runtime shares. Each job receives only its\n * `ScheduleInvocation`, runs in a fresh invocation scope seeded with\n * {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`\n * dispatch. The trigger settles after every matching job and its managed\n * work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.\n */\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n _ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const jobs = this.#app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .filter((entry) => entry.meta.expression === event.cron);\n if (jobs.length === 0) return;\n\n const controller = new AbortController();\n const scheduledTime = event.scheduledTime ?? Date.now();\n // Shared by every matching job, so none of them can alter what another sees.\n const invocation: ScheduleInvocation = Object.freeze({\n kind: 'cron' as const,\n expression: event.cron,\n scheduledTime,\n signal: controller.signal,\n });\n const trigger = cloudflareScheduledEvent(event, scheduledTime);\n const container = this.#app.getContainer();\n const running = settleEntrypoints(\n jobs.map((entry) =>\n invokeScheduledJob(container, entry, invocation, {\n seed: (scope) => scope.setRequestInstance(CLOUDFLARE_SCHEDULED_EVENT, trigger),\n }),\n ),\n );\n this.#scheduled.set(running, controller);\n try {\n await running;\n } finally {\n this.#scheduled.delete(running);\n }\n }\n\n /**\n * Run one queue consumer inside a fresh request scope, through the shared\n * guard → interceptor pipeline (components declared with\n * `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or\n * method). HTTP-global components deliberately do NOT apply — an HTTP auth\n * guard has no business rejecting a queue batch. Unclaimed errors are\n * reported once (`QueueModule`'s consumer reports its own) and rethrow so\n * the platform's retry semantics stay intact.\n */\n private async dispatchEntrypoint(\n ep: Entrypoint,\n payload: unknown,\n env: VelaEnv,\n platformContext: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n const targetClass = ep.token;\n if (typeof targetClass !== 'function') throw new Error('Entrypoint token must be a class.');\n if (ep.methodName === undefined) throw new Error('Entrypoint must declare a handler method.');\n const methodName = ep.methodName;\n const reportContext = {\n edge: 'queue' as const,\n source: `${targetClass.name}.${String(methodName)}`,\n };\n let reported: { error: unknown } | undefined;\n // A self-reporting handler's own rejection was already reported.\n let delegated: { error: unknown } | undefined;\n try {\n await runInEntrypointScope(this.#app.getContainer(), async (scope, lifetime) => {\n const moduleId = getEntrypointModuleId(scope, ep);\n const context = buildEntrypointExecutionContext(\n ep.kind,\n targetClass,\n methodName,\n payload,\n moduleId,\n scope,\n );\n const invocationContext = {\n waitUntil(promise: Promise<unknown>): void {\n lifetime.waitUntil(promise);\n platformContext.waitUntil(promise);\n },\n };\n let filters: ExceptionFilter[] = [];\n try {\n filters = (\n await resolveScopedComponentsAsync('filter', targetClass, methodName, scope, moduleId)\n ).toReversed();\n const guards = await resolveScopedComponentsAsync(\n 'guard',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n const interceptors = await resolveScopedComponentsAsync(\n 'interceptor',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n await PipelineRunner.run({\n context,\n guards,\n interceptors,\n resolveArgs: async () => [payload, env, invocationContext],\n invoke: async (args) => {\n const instance = await resolveEntrypoint(scope, ep);\n if (typeof instance !== 'object' || instance === null) {\n throw new Error('Entrypoint must resolve to an object.');\n }\n try {\n return await invoke(instance, methodName, args);\n } catch (error) {\n if (SELF_REPORTING_KINDS.has(ep.kind)) delegated = { error };\n throw error;\n }\n },\n });\n } catch (error) {\n if (delegated?.error !== error) {\n resolveErrorReporter(scope).report(error, reportContext);\n }\n for (const filter of filters) {\n if (shouldFilterCatch(filter, error)) {\n // Filters run closest-first; this is the framework catch hook.\n // eslint-disable-next-line no-await-in-loop, promise/valid-params\n await filter.catch(error, context);\n return;\n }\n }\n reported = { error };\n throw error;\n }\n });\n } catch (error) {\n // Managed completion happens after the handler's filter boundary. Report\n // a new completion failure without reporting an already-observed handler\n // failure twice; preserve both errors in the rejected invocation.\n if (!reported || reported.error !== error) {\n const completionError =\n reported && error instanceof AggregateError && error.errors[0] === reported.error\n ? error.errors[1]\n : error;\n resolveErrorReporter(this.#app.getContainer()).report(completionError, reportContext);\n }\n throw error;\n }\n }\n\n /**\n * Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read\n * from `app.entrypoints` claim a batch by its physical queue name and\n * receive it whole. A batch no handler claims goes to `QueueModule`'s native\n * consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which\n * routes each job by its logical queue. Each dispatch runs inside a fresh\n * request-scoped child (request-scoped providers rebuild per batch — no\n * boot-time captives). A batch nothing claims rejects: resolving would let\n * Cloudflare acknowledge every message implicitly.\n */\n async queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const raw = this.#app.entrypoints\n .ofKind('cf:queue')\n .filter((ep) => entrypointString(ep.meta, 'queueName') === batch.queue);\n if (raw.length > 0) this.warnRawJobs(batch);\n const handlers = raw.length > 0 ? raw : this.#app.entrypoints.ofKind('cf:queue:module');\n\n if (handlers.length === 0) {\n throw new Error(\n `No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a ` +\n `provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) ` +\n `with a QueueModule.registerQueue() for each queue it carries. The batch is rejected ` +\n `unacknowledged, so Cloudflare retries it and then routes it to the configured ` +\n `dead-letter queue.`,\n );\n }\n\n await settleEntrypoints(handlers.map((ep) => this.dispatchEntrypoint(ep, batch, env, ctx)));\n }\n\n /**\n * A raw `@QueueConsumer` owns its physical queue's batches and must not carry\n * jobs of a queue registered with `QueueModule`: those reach their\n * `@Processor` only if the raw handler dispatches them itself, while\n * `cloudflareQueues()` delivers registered queues. Warn once per physical and\n * logical queue (unless diagnostics are silent); the raw consumer still\n * receives and settles the batch.\n */\n private warnRawJobs(batch: { queue: string; messages: readonly unknown[] }): void {\n if (this.#app.getContainer().getDiagnostics() === 'silent') return;\n const registered = new Set(\n this.#app.entrypoints\n .ofKind('queue:registration')\n .map((entry) =>\n typeof entry.meta === 'object' && entry.meta !== null\n ? Reflect.get(entry.meta, 'name')\n : undefined,\n ),\n );\n if (registered.size === 0) return;\n for (const message of batch.messages) {\n const body =\n typeof message === 'object' && message !== null ? Reflect.get(message, 'body') : undefined;\n const queue = envelopeQueue(body);\n if (queue === undefined || !registered.has(queue)) continue;\n const warning =\n `[vela] @QueueConsumer('${batch.queue}') received jobs of registered queue '${queue}'. ` +\n `The raw consumer owns '${batch.queue}' and must not carry jobs of registered queues: ` +\n `they reach @Processor('${queue}') only if the raw handler dispatches them itself. ` +\n `Deliver '${queue}' through cloudflareQueues() instead: send it to a physical queue ` +\n `that no @QueueConsumer claims.`;\n if (warnedRawJobs.has(warning)) continue;\n warnedRawJobs.add(warning);\n console.warn(warning);\n }\n }\n\n /**\n * Abort the signals of scheduled jobs still running, wait for them and their\n * managed work to settle, then close the application.\n */\n async close(signal?: string): Promise<void> {\n for (const controller of this.#scheduled.values()) controller.abort();\n await Promise.allSettled(this.#scheduled.keys());\n return this.#app.close(signal);\n }\n}\n"],"mappings":";;;;;;AAkCA,SAAS,OAAO,UAAkB,YAA6B,MAA0B;CAEvF,MAAM,SAAkB,QAAQ,IAAI,UAAU,UAAU;CACxD,IAAI,OAAO,WAAW,YACpB,MAAM,IAAI,MACR,WAAW,OAAO,UAAU,EAAE,yBAAyB,SAAS,YAAY,MAC9E;CAEF,OAAO,QAAQ,MAAM,QAAQ,UAAU,IAAI;AAC7C;AAEA,SAAS,iBAAiB,MAAe,UAA0B;CACjE,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,MAAM,IAAI,MAAM,8BAA8B;CAC7F,MAAM,QAAiB,QAAQ,IAAI,MAAM,QAAQ;CACjD,IAAI,OAAO,UAAU,UACnB,MAAM,IAAI,MAAM,gCAAgC,SAAS,mBAAmB;CAC9E,OAAO;AACT;;;;;;AAOA,MAAM,uCAAuB,IAAI,IAAI,CAAC,iBAAiB,CAAC;AAExD,MAAM,gCAAgB,IAAI,IAAY;;AAGtC,SAAS,cAAc,MAAmC;CACxD,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,OAAO,KAAA;CACtD,MAAM,QAAiB,QAAQ,IAAI,MAAM,OAAO;CAChD,IACE,OAAO,UAAU,YACjB,OAA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MAAM,MAAM,IAC9B,KAAA,CACN,CACJ;EACA,IAAI,WAAW,SAAS,GAAG;EAC3B,KAAK,MAAM,WAAW,MAAM,UAAU;GAGpC,MAAM,QAAQ,cADZ,OAAO,YAAY,YAAY,YAAY,OAAO,QAAQ,IAAI,SAAS,MAAM,IAAI,KAAA,CACnD;GAChC,IAAI,UAAU,KAAA,KAAa,CAAC,WAAW,IAAI,KAAK,GAAG;GACnD,MAAM,UACJ,0BAA0B,MAAM,MAAM,wCAAwC,MAAM,4BAC1D,MAAM,MAAM,yEACZ,MAAM,8DACpB,MAAM;GAEpB,IAAI,cAAc,IAAI,OAAO,GAAG;GAChC,cAAc,IAAI,OAAO;GACzB,QAAQ,KAAK,OAAO;EACtB;CACF;;;;;CAMA,MAAM,MAAM,QAAgC;EAC1C,KAAK,MAAM,cAAc,KAAK,WAAW,OAAO,GAAG,WAAW,MAAM;EACpE,MAAM,QAAQ,WAAW,KAAK,WAAW,KAAK,CAAC;EAC/C,OAAO,KAAK,KAAK,MAAM,MAAM;CAC/B;AACF"}
|
|
1
|
+
{"version":3,"file":"cloudflare-application.js","names":[],"sources":["../src/cloudflare-application.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport type { CorsOptions, VelaApplication, ExceptionFilter, VelaEnv } from '@velajs/vela';\nimport {\n PipelineRunner,\n buildEntrypointExecutionContext,\n getEntrypointModuleId,\n invokeScheduledJob,\n parseCronMetadata,\n resolveEntrypoint,\n resolveScopedComponentsAsync,\n resolveErrorReporter,\n runInEntrypointScope,\n shouldFilterCatch,\n} from '@velajs/vela/module-kit';\nimport type { ScheduleInvocation } from '@velajs/vela/schedule';\nimport type { Entrypoint } from '@velajs/vela/module-kit';\nimport { assertCloudflareEnvironment } from './environment';\nimport {\n CLOUDFLARE_SCHEDULED_EVENT,\n cloudflareScheduledEvent,\n type ScheduledEvent,\n} from './scheduled-event';\n\n/**\n * Options accepted by {@link CloudflareApplication.mountOpenApi}.\n *\n * Re-exposes vela's `MountOpenApiOptions` type — derived structurally from\n * the underlying `VelaApplication.mountOpenApi` signature so consumers don't\n * have to reach into vela's internal subpaths to type the argument.\n */\nexport type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];\n\nfunction invoke(instance: object, methodName: string | symbol, args: unknown[]): unknown {\n // Decorator metadata names an instance method; inspect it before invoking.\n const method: unknown = Reflect.get(instance, methodName);\n if (typeof method !== 'function') {\n throw new Error(\n `Method '${String(methodName)}' is not a function on ${instance.constructor.name}`,\n );\n }\n return Reflect.apply(method, instance, args);\n}\n\nfunction entrypointString(meta: unknown, property: string): string {\n if (typeof meta !== 'object' || meta === null) throw new Error('Invalid entrypoint metadata.');\n const value: unknown = Reflect.get(meta, property);\n if (typeof value !== 'string')\n throw new Error(`Invalid entrypoint metadata: ${property} must be a string.`);\n return value;\n}\n\n/**\n * `QueueModule`'s native consumer reports each failure of a batch once itself\n * (processor failures where they ran, transport failures on settlement), so\n * its rejection is not reported again here.\n */\nconst SELF_REPORTING_KINDS = new Set(['cf:queue:module']);\n\nconst warnedRawJobs = new Set<string>();\n\n/** The logical queue of a Vela job envelope, without importing the queue subsystem. */\nfunction envelopeQueue(body: unknown): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined;\n const queue: unknown = Reflect.get(body, 'queue');\n if (\n typeof queue !== 'string' ||\n typeof Reflect.get(body, 'id') !== 'string' ||\n typeof Reflect.get(body, 'name') !== 'string' ||\n !('data' in body)\n ) {\n return undefined;\n }\n return queue;\n}\n\n/** Wait for every matching handler, even when one fails before its siblings. */\nasync function settleEntrypoints(work: readonly Promise<void>[]): Promise<void> {\n const outcomes = await Promise.allSettled(work);\n const errors = outcomes.flatMap((outcome) =>\n outcome.status === 'rejected' ? [outcome.reason] : [],\n );\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Multiple entrypoint handlers failed.');\n}\n\n/**\n * Wraps VelaApplication with Cloudflare-specific handlers:\n * - `fetch` — HTTP request handler (from Hono)\n * - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose\n * expression is the trigger's exact string)\n * - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,\n * then `QueueModule`'s native consumer)\n * - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on\n * the underlying Hono app\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * export default {\n * fetch: app.fetch,\n * scheduled: app.scheduled.bind(app),\n * queue: app.queue.bind(app),\n * };\n * ```\n *\n * @example\n * ```ts\n * // Serve OpenAPI docs alongside your routes\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule);\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> JSON document\n * // GET /scalar -> Scalar UI (loads from CDN)\n * ```\n */\nexport class CloudflareApplication {\n readonly #app: VelaApplication;\n /** Scheduled triggers in flight; close() aborts their signals and awaits them. */\n readonly #scheduled = new Map<Promise<void>, AbortController>();\n\n constructor(\n app: VelaApplication,\n readonly env: VelaEnv,\n ) {\n this.#app = app;\n this.get = app.get.bind(app);\n }\n\n readonly fetch = async (\n request: Request,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ): Promise<Response> => {\n assertCloudflareEnvironment(this.env, env);\n return this.#app.fetch(request, env, ctx);\n };\n\n getHonoApp(): ReturnType<VelaApplication['getHonoApp']> {\n return this.#app.getHonoApp();\n }\n\n /**\n * Resolve a provider from the application's DI container (delegates to\n * `VelaApplication.get`). Handy in `createCloudflareWorker({ configure })`,\n * which finishes the HTTP surface outside the DI request pipeline.\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * const auth = app.get(BetterAuthService);\n * ```\n */\n readonly get: VelaApplication['get'];\n\n get entrypoints(): VelaApplication['entrypoints'] {\n return this.#app.entrypoints;\n }\n\n /**\n * The application's DI container (delegates to `VelaApplication.getContainer`),\n * for dispatch seams that take it with `entrypoints`, such as\n * `dispatchInboundEmail(app.getContainer(), app.entrypoints, email)`.\n */\n getContainer(): ReturnType<VelaApplication['getContainer']> {\n return this.#app.getContainer();\n }\n\n /** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */\n enableCors(options?: CorsOptions): this {\n this.#app.enableCors(options);\n return this;\n }\n\n /**\n * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the\n * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,\n * so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when\n * opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from\n * a CDN at runtime, nothing is bundled server-side.\n *\n * @example\n * ```ts\n * import { createOpenApiDocument } from '@velajs/vela/openapi';\n *\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule, {\n * info: { title: 'My API', version: '1.0.0' },\n * });\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> { openapi: '3.1.0', ... }\n * // GET /scalar -> Scalar UI HTML\n * ```\n */\n mountOpenApi(options: MountOpenApiOptions): this {\n this.#app.mountOpenApi(options);\n return this;\n }\n\n /**\n * Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose\n * expression is exactly `event.cron` (the trigger string is compared as\n * delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch\n * primitive every runtime shares. Each job receives only its\n * `ScheduleInvocation`, runs in a fresh invocation scope seeded with\n * {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`\n * dispatch. The trigger settles after every matching job and its managed\n * work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.\n */\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n _ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const jobs = this.#app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .filter((entry) => entry.meta.expression === event.cron);\n if (jobs.length === 0) return;\n\n const controller = new AbortController();\n const scheduledTime = event.scheduledTime ?? Date.now();\n // Shared by every matching job, so none of them can alter what another sees.\n const invocation: ScheduleInvocation = Object.freeze({\n kind: 'cron' as const,\n expression: event.cron,\n scheduledTime,\n signal: controller.signal,\n });\n const trigger = cloudflareScheduledEvent(event, scheduledTime);\n const container = this.#app.getContainer();\n const running = settleEntrypoints(\n jobs.map((entry) =>\n invokeScheduledJob(container, entry, invocation, {\n seed: (scope) => scope.setRequestInstance(CLOUDFLARE_SCHEDULED_EVENT, trigger),\n }),\n ),\n );\n this.#scheduled.set(running, controller);\n try {\n await running;\n } finally {\n this.#scheduled.delete(running);\n }\n }\n\n /**\n * Run one queue consumer inside a fresh request scope, through the shared\n * guard → interceptor pipeline (components declared with\n * `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or\n * method). HTTP-global components deliberately do NOT apply — an HTTP auth\n * guard has no business rejecting a queue batch. Unclaimed errors are\n * reported once (`QueueModule`'s consumer reports its own) and rethrow so\n * the platform's retry semantics stay intact.\n */\n private async dispatchEntrypoint(\n ep: Entrypoint,\n payload: unknown,\n env: VelaEnv,\n platformContext: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n const targetClass = ep.token;\n if (typeof targetClass !== 'function') throw new Error('Entrypoint token must be a class.');\n if (ep.methodName === undefined) throw new Error('Entrypoint must declare a handler method.');\n const methodName = ep.methodName;\n const reportContext = {\n edge: 'queue' as const,\n source: `${targetClass.name}.${String(methodName)}`,\n };\n let reported: { error: unknown } | undefined;\n // A self-reporting handler's own rejection was already reported.\n let delegated: { error: unknown } | undefined;\n try {\n await runInEntrypointScope(this.#app.getContainer(), async (scope, lifetime) => {\n const moduleId = getEntrypointModuleId(scope, ep);\n const context = buildEntrypointExecutionContext(\n ep.kind,\n targetClass,\n methodName,\n payload,\n moduleId,\n scope,\n );\n const invocationContext = {\n waitUntil(promise: Promise<unknown>): void {\n lifetime.waitUntil(promise);\n platformContext.waitUntil(promise);\n },\n };\n let filters: ExceptionFilter[] = [];\n try {\n filters = (\n await resolveScopedComponentsAsync('filter', targetClass, methodName, scope, moduleId)\n ).toReversed();\n const guards = await resolveScopedComponentsAsync(\n 'guard',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n const interceptors = await resolveScopedComponentsAsync(\n 'interceptor',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n await PipelineRunner.run({\n context,\n guards,\n interceptors,\n resolveArgs: async () => [payload, env, invocationContext],\n invoke: async (args) => {\n const instance = await resolveEntrypoint(scope, ep);\n if (typeof instance !== 'object' || instance === null) {\n throw new Error('Entrypoint must resolve to an object.');\n }\n try {\n return await invoke(instance, methodName, args);\n } catch (error) {\n if (SELF_REPORTING_KINDS.has(ep.kind)) delegated = { error };\n throw error;\n }\n },\n });\n } catch (error) {\n if (delegated?.error !== error) {\n resolveErrorReporter(scope).report(error, reportContext);\n }\n for (const filter of filters) {\n if (shouldFilterCatch(filter, error)) {\n // Filters run closest-first; this is the framework catch hook.\n // eslint-disable-next-line no-await-in-loop, promise/valid-params\n await filter.catch(error, context);\n return;\n }\n }\n reported = { error };\n throw error;\n }\n });\n } catch (error) {\n // Managed completion happens after the handler's filter boundary. Report\n // a new completion failure without reporting an already-observed handler\n // failure twice; preserve both errors in the rejected invocation.\n if (!reported || reported.error !== error) {\n const completionError =\n reported && error instanceof AggregateError && error.errors[0] === reported.error\n ? error.errors[1]\n : error;\n resolveErrorReporter(this.#app.getContainer()).report(completionError, reportContext);\n }\n throw error;\n }\n }\n\n /**\n * Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read\n * from `app.entrypoints` claim a batch by its physical queue name and\n * receive it whole. A batch no handler claims goes to `QueueModule`'s native\n * consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which\n * routes each job by its logical queue. Each dispatch runs inside a fresh\n * request-scoped child (request-scoped providers rebuild per batch — no\n * boot-time captives). A batch nothing claims rejects: resolving would let\n * Cloudflare acknowledge every message implicitly.\n */\n async queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const raw = this.#app.entrypoints\n .ofKind('cf:queue')\n .filter((ep) => entrypointString(ep.meta, 'queueName') === batch.queue);\n if (raw.length > 0) this.warnRawJobs(batch);\n const handlers = raw.length > 0 ? raw : this.#app.entrypoints.ofKind('cf:queue:module');\n\n if (handlers.length === 0) {\n throw new Error(\n `No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a ` +\n `provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) ` +\n `with a QueueModule.registerQueue() for each queue it carries. The batch is rejected ` +\n `unacknowledged, so Cloudflare retries it and then routes it to the configured ` +\n `dead-letter queue.`,\n );\n }\n\n await settleEntrypoints(handlers.map((ep) => this.dispatchEntrypoint(ep, batch, env, ctx)));\n }\n\n /**\n * A raw `@QueueConsumer` owns its physical queue's batches and must not carry\n * jobs of a queue registered with `QueueModule`: those reach their\n * `@Processor` only if the raw handler dispatches them itself, while\n * `cloudflareQueues()` delivers registered queues. Warn once per physical and\n * logical queue (unless diagnostics are silent); the raw consumer still\n * receives and settles the batch.\n */\n private warnRawJobs(batch: { queue: string; messages: readonly unknown[] }): void {\n if (this.#app.getContainer().getDiagnostics() === 'silent') return;\n const registered = new Set(\n this.#app.entrypoints\n .ofKind('queue:registration')\n .map((entry) =>\n typeof entry.meta === 'object' && entry.meta !== null\n ? Reflect.get(entry.meta, 'name')\n : undefined,\n ),\n );\n if (registered.size === 0) return;\n for (const message of batch.messages) {\n const body =\n typeof message === 'object' && message !== null ? Reflect.get(message, 'body') : undefined;\n const queue = envelopeQueue(body);\n if (queue === undefined || !registered.has(queue)) continue;\n const warning =\n `[vela] @QueueConsumer('${batch.queue}') received jobs of registered queue '${queue}'. ` +\n `The raw consumer owns '${batch.queue}' and must not carry jobs of registered queues: ` +\n `they reach @Processor('${queue}') only if the raw handler dispatches them itself. ` +\n `Deliver '${queue}' through cloudflareQueues() instead: send it to a physical queue ` +\n `that no @QueueConsumer claims.`;\n if (warnedRawJobs.has(warning)) continue;\n warnedRawJobs.add(warning);\n console.warn(warning);\n }\n }\n\n /**\n * Abort the signals of scheduled jobs still running, wait for them and their\n * managed work to settle, then close the application.\n */\n async close(signal?: string): Promise<void> {\n for (const controller of this.#scheduled.values()) controller.abort();\n await Promise.allSettled(this.#scheduled.keys());\n return this.#app.close(signal);\n }\n}\n"],"mappings":";;;;AAgCA,SAAS,OAAO,UAAkB,YAA6B,MAA0B;CAEvF,MAAM,SAAkB,QAAQ,IAAI,UAAU,UAAU;CACxD,IAAI,OAAO,WAAW,YACpB,MAAM,IAAI,MACR,WAAW,OAAO,UAAU,EAAE,yBAAyB,SAAS,YAAY,MAC9E;CAEF,OAAO,QAAQ,MAAM,QAAQ,UAAU,IAAI;AAC7C;AAEA,SAAS,iBAAiB,MAAe,UAA0B;CACjE,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,MAAM,IAAI,MAAM,8BAA8B;CAC7F,MAAM,QAAiB,QAAQ,IAAI,MAAM,QAAQ;CACjD,IAAI,OAAO,UAAU,UACnB,MAAM,IAAI,MAAM,gCAAgC,SAAS,mBAAmB;CAC9E,OAAO;AACT;;;;;;AAOA,MAAM,uCAAuB,IAAI,IAAI,CAAC,iBAAiB,CAAC;AAExD,MAAM,gCAAgB,IAAI,IAAY;;AAGtC,SAAS,cAAc,MAAmC;CACxD,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,OAAO,KAAA;CACtD,MAAM,QAAiB,QAAQ,IAAI,MAAM,OAAO;CAChD,IACE,OAAO,UAAU,YACjB,OAAO,QAAQ,IAAI,MAAM,IAAI,MAAM,YACnC,OAAO,QAAQ,IAAI,MAAM,MAAM,MAAM,YACrC,EAAE,UAAU,OAEZ;CAEF,OAAO;AACT;;AAGA,eAAe,kBAAkB,MAA+C;CAE9E,MAAM,UAAS,MADQ,QAAQ,WAAW,IAAI,EAAA,CACtB,SAAS,YAC/B,QAAQ,WAAW,aA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,OAAO,KAAK,mBAAmB,IAAI,OAAO,KAAK,GAAG,CAAC,CAAC;CAC5F;;;;;;;;;CAUA,YAAoB,OAA8D;EAChF,IAAI,KAAK,KAAK,aAAa,CAAC,CAAC,eAAe,MAAM,UAAU;EAC5D,MAAM,aAAa,IAAI,IACrB,KAAK,KAAK,YACP,OAAO,oBAAoB,CAAC,CAC5B,KAAK,UACJ,OAAO,MAAM,SAAS,YAAY,MAAM,SAAS,OAC7C,QAAQ,IAAI,MAAM,MAAM,MAAM,IAC9B,KAAA,CACN,CACJ;EACA,IAAI,WAAW,SAAS,GAAG;EAC3B,KAAK,MAAM,WAAW,MAAM,UAAU;GAGpC,MAAM,QAAQ,cADZ,OAAO,YAAY,YAAY,YAAY,OAAO,QAAQ,IAAI,SAAS,MAAM,IAAI,KAAA,CACnD;GAChC,IAAI,UAAU,KAAA,KAAa,CAAC,WAAW,IAAI,KAAK,GAAG;GACnD,MAAM,UACJ,0BAA0B,MAAM,MAAM,wCAAwC,MAAM,4BAC1D,MAAM,MAAM,yEACZ,MAAM,8DACpB,MAAM;GAEpB,IAAI,cAAc,IAAI,OAAO,GAAG;GAChC,cAAc,IAAI,OAAO;GACzB,QAAQ,KAAK,OAAO;EACtB;CACF;;;;;CAMA,MAAM,MAAM,QAAgC;EAC1C,KAAK,MAAM,cAAc,KAAK,WAAW,OAAO,GAAG,WAAW,MAAM;EACpE,MAAM,QAAQ,WAAW,KAAK,WAAW,KAAK,CAAC;EAC/C,OAAO,KAAK,KAAK,MAAM,MAAM;CAC/B;AACF"}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { a as ScheduledEvent, t as CloudflareApplication } from "./cloudflare-application-CXDy9C1R.js";
|
|
2
|
+
import { CorsOptions, DynamicModule, GlobalPrefixOptions, Type, VelaApplication, VelaCreateOptions, VelaEnv, VelaSecurityOptions, VersioningOptions } from "@velajs/vela";
|
|
3
|
+
import { RuntimeAdapter } from "@velajs/vela/module-kit";
|
|
4
|
+
import { ExecutionContext } from "hono";
|
|
5
|
+
//#region src/root-module.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* The root a Worker or Durable Object is built from: a module class or a
|
|
8
|
+
* `DynamicModule`, declared once at module scope. Configuration that needs
|
|
9
|
+
* bindings belongs in providers and `forRootAsync({ inject: [ENV] })`
|
|
10
|
+
* factories, which run for each application with that application's ENV.
|
|
11
|
+
*/
|
|
12
|
+
type CloudflareRoot = Type | DynamicModule;
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/cloudflare-factory.d.ts
|
|
15
|
+
interface CloudflareAppOptions {
|
|
16
|
+
globalPrefix?: string;
|
|
17
|
+
/** Routes served without the global prefix (`{ exclude }`). */
|
|
18
|
+
globalPrefixOptions?: GlobalPrefixOptions;
|
|
19
|
+
/** URI versioning: the version segment prefix (default `'v'`). */
|
|
20
|
+
versioning?: VersioningOptions;
|
|
21
|
+
security?: VelaSecurityOptions;
|
|
22
|
+
/** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */
|
|
23
|
+
cors?: CorsOptions | boolean;
|
|
24
|
+
/** Further runtime adapters, composed after the Cloudflare adapter for each application. */
|
|
25
|
+
adapters?: RuntimeAdapter[];
|
|
26
|
+
}
|
|
27
|
+
interface CloudflareWorkerOptions extends CloudflareAppOptions {
|
|
28
|
+
/**
|
|
29
|
+
* Finish each application's HTTP surface, such as extra Hono routes, once per
|
|
30
|
+
* environment. It runs after the application is built and before any event,
|
|
31
|
+
* including concurrent cold events, reaches it; a throw fails that
|
|
32
|
+
* construction, and the next event retries. It must be synchronous and do no
|
|
33
|
+
* I/O (a returned promise fails the construction): read bindings in
|
|
34
|
+
* providers. Request middleware belongs in modules (`configure(consumer)`),
|
|
35
|
+
* which can inject `ENV`.
|
|
36
|
+
*/
|
|
37
|
+
configure?(app: CloudflareApplication, env: VelaEnv): void;
|
|
38
|
+
}
|
|
39
|
+
interface CreateCloudflareAppOptions extends CloudflareAppOptions {
|
|
40
|
+
/** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */
|
|
41
|
+
env: VelaEnv;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Bind an application to one environment: seeded as the global ENV before
|
|
45
|
+
* provider factories and lifecycle hooks, and asserted on every request. The
|
|
46
|
+
* adapter also registers the Worker's platform wiring: `WebSocketModule`
|
|
47
|
+
* forwards each authenticated gateway upgrade to the room's Durable Object,
|
|
48
|
+
* and `LiveModule` sends invalidations there. It supplies the
|
|
49
|
+
* `InternalDispatcher` transport, so signed queue and schedule dispatch
|
|
50
|
+
* re-enter this application's routes, and reports, through the diagnostics
|
|
51
|
+
* policy, schedule declarations a cron trigger cannot honor and binding-backed
|
|
52
|
+
* gateways without `WebSocketModule`.
|
|
53
|
+
*/
|
|
54
|
+
declare function cloudflareAdapter(options: {
|
|
55
|
+
env: VelaEnv;
|
|
56
|
+
}): RuntimeAdapter;
|
|
57
|
+
/**
|
|
58
|
+
* Build an application for one native Workers environment. Call inside a platform event.
|
|
59
|
+
* The root is static: a module class or a `DynamicModule` declared at module scope.
|
|
60
|
+
* Read bindings in providers (`@InjectEnv()`) and module factories
|
|
61
|
+
* (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
|
|
62
|
+
*/
|
|
63
|
+
declare function createCloudflareApp(rootModule: CloudflareRoot, options: CreateCloudflareAppOptions): Promise<CloudflareApplication>;
|
|
64
|
+
/**
|
|
65
|
+
* The well-known key under which a Worker entry (`defineCloudflareApp().worker`
|
|
66
|
+
* or `createCloudflareWorker()`) carries its {@link CloudflareWorkerDescriptor}:
|
|
67
|
+
* `Symbol.for('vela.cloudflare.worker')`.
|
|
68
|
+
*/
|
|
69
|
+
declare const CLOUDFLARE_WORKER: unique symbol;
|
|
70
|
+
/**
|
|
71
|
+
* The well-known static key under which a Durable Object class that
|
|
72
|
+
* `VelaDurableObject()` or `VelaWebSocketDurableObject()` returns (and every
|
|
73
|
+
* class extending it) carries its {@link CloudflareDurableObjectDescriptor}:
|
|
74
|
+
* `Symbol.for('vela.cloudflare.durableObject')`.
|
|
75
|
+
*/
|
|
76
|
+
declare const CLOUDFLARE_DURABLE_OBJECT: unique symbol;
|
|
77
|
+
/**
|
|
78
|
+
* The well-known static key under which a Workflow class that `VelaWorkflow()`
|
|
79
|
+
* returns (and every class extending it) carries its
|
|
80
|
+
* {@link CloudflareWorkflowDescriptor}: `Symbol.for('vela.cloudflare.workflow')`.
|
|
81
|
+
*/
|
|
82
|
+
declare const CLOUDFLARE_WORKFLOW: unique symbol;
|
|
83
|
+
/**
|
|
84
|
+
* The well-known static key under which a service entrypoint class that
|
|
85
|
+
* `VelaEntrypoint()` returns (and every class extending it) carries its
|
|
86
|
+
* {@link CloudflareEntrypointDescriptor}: `Symbol.for('vela.cloudflare.entrypoint')`.
|
|
87
|
+
*/
|
|
88
|
+
declare const CLOUDFLARE_ENTRYPOINT: unique symbol;
|
|
89
|
+
/** What a Vela Durable Object class is built from, for tools such as `vela cf sync`. */
|
|
90
|
+
interface CloudflareDurableObjectDescriptor {
|
|
91
|
+
/**
|
|
92
|
+
* `host`: `VelaDurableObject(root, Host, { rpc })`, whose RPC methods are
|
|
93
|
+
* the host methods `rpc` names.
|
|
94
|
+
* `websocket`: `VelaWebSocketDurableObject(root)`, a gateway room's sockets.
|
|
95
|
+
*/
|
|
96
|
+
readonly kind: 'host' | 'websocket';
|
|
97
|
+
readonly rootModule: CloudflareRoot;
|
|
98
|
+
/** The host class of a `host` Durable Object. */
|
|
99
|
+
readonly host?: Type;
|
|
100
|
+
/** The RPC methods the class exposes. */
|
|
101
|
+
readonly methods: readonly string[];
|
|
102
|
+
/** The class the factory returned: an exported Durable Object class extends it. */
|
|
103
|
+
readonly durableObject: abstract new (...args: never[]) => unknown;
|
|
104
|
+
}
|
|
105
|
+
/** What a Vela Workflow class is built from, for tools such as `vela cf sync`. */
|
|
106
|
+
interface CloudflareWorkflowDescriptor {
|
|
107
|
+
readonly rootModule: CloudflareRoot;
|
|
108
|
+
/** The host class whose `run(event, step)` each Workflow run calls. */
|
|
109
|
+
readonly host: Type;
|
|
110
|
+
/** The class `VelaWorkflow()` returned: an exported Workflow class extends it. */
|
|
111
|
+
readonly workflow: abstract new (...args: never[]) => unknown;
|
|
112
|
+
}
|
|
113
|
+
/** What a Vela service entrypoint class is built from, for tools such as `vela cf sync`. */
|
|
114
|
+
interface CloudflareEntrypointDescriptor {
|
|
115
|
+
readonly rootModule: CloudflareRoot;
|
|
116
|
+
/** The host class whose methods `methods` names. */
|
|
117
|
+
readonly host: Type;
|
|
118
|
+
/** The RPC methods the class exposes. */
|
|
119
|
+
readonly methods: readonly string[];
|
|
120
|
+
/** The class `VelaEntrypoint()` returned: an exported entrypoint class extends it. */
|
|
121
|
+
readonly entrypoint: abstract new (...args: never[]) => unknown;
|
|
122
|
+
}
|
|
123
|
+
/** What a Worker entry is built from, for tools that load it outside a platform event. */
|
|
124
|
+
interface CloudflareWorkerDescriptor {
|
|
125
|
+
readonly rootModule: CloudflareRoot;
|
|
126
|
+
readonly options: CloudflareWorkerOptions;
|
|
127
|
+
/**
|
|
128
|
+
* The Durable Object classes defined from the same {@link CloudflareApp}
|
|
129
|
+
* (`VelaDurableObject(app, Host)`, `VelaWebSocketDurableObject(app)`), in
|
|
130
|
+
* definition order; empty for `createCloudflareWorker()`.
|
|
131
|
+
*/
|
|
132
|
+
readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];
|
|
133
|
+
/** The Workflow classes defined from the app (`VelaWorkflow(app, Host)`), in definition order. */
|
|
134
|
+
readonly workflows: readonly CloudflareWorkflowDescriptor[];
|
|
135
|
+
/**
|
|
136
|
+
* The service entrypoint classes defined from the app
|
|
137
|
+
* (`VelaEntrypoint(app, Host, { rpc })`), in definition order.
|
|
138
|
+
*/
|
|
139
|
+
readonly entrypoints: readonly CloudflareEntrypointDescriptor[];
|
|
140
|
+
/** The `VelaFactory.create()` options the Worker builds its application with for `env`. */
|
|
141
|
+
createOptions(env: VelaEnv): VelaCreateOptions;
|
|
142
|
+
/**
|
|
143
|
+
* `VelaFactory.create()` of the Worker's root (the root module, with the
|
|
144
|
+
* hosts of the app's Workflow and service entrypoint classes among its
|
|
145
|
+
* providers) and `createOptions(env)`: the application without its Worker
|
|
146
|
+
* handlers or the `configure` hook, which receives the Workers application.
|
|
147
|
+
*/
|
|
148
|
+
createApplication(env: VelaEnv): Promise<VelaApplication>;
|
|
149
|
+
}
|
|
150
|
+
/** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */
|
|
151
|
+
interface CloudflareWorker {
|
|
152
|
+
fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
|
|
153
|
+
scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
|
|
154
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
155
|
+
}): Promise<void>;
|
|
156
|
+
queue(batch: {
|
|
157
|
+
queue: string;
|
|
158
|
+
messages: readonly unknown[];
|
|
159
|
+
}, env: VelaEnv, ctx: {
|
|
160
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
161
|
+
}): Promise<void>;
|
|
162
|
+
/**
|
|
163
|
+
* The Email Workers handler, present once a module imports `OnEmail` from
|
|
164
|
+
* `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`
|
|
165
|
+
* handlers, and rejects a message none of them accepts.
|
|
166
|
+
*/
|
|
167
|
+
readonly email?: (message: ForwardableEmailMessage, env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
|
|
168
|
+
/**
|
|
169
|
+
* The Tail Workers handler, present once a module imports `OnTail` from
|
|
170
|
+
* `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers
|
|
171
|
+
* and never rejects, even when the application fails to start (the error is
|
|
172
|
+
* logged to the console, and the next batch retries).
|
|
173
|
+
*/
|
|
174
|
+
readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
|
|
175
|
+
/**
|
|
176
|
+
* Symbol-keyed, so the platform, which reads string-keyed handlers, ignores
|
|
177
|
+
* it; enumerable, so `{ ...worker, email }` keeps it for the CLI.
|
|
178
|
+
*/
|
|
179
|
+
readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* One Cloudflare application: a static root module and its options, shared
|
|
183
|
+
* by the Worker's default export and every Durable Object, Workflow and
|
|
184
|
+
* service entrypoint class defined from it. Create it once, at module scope
|
|
185
|
+
* of the Worker entry, with {@link defineCloudflareApp}.
|
|
186
|
+
*/
|
|
187
|
+
interface CloudflareApp {
|
|
188
|
+
readonly rootModule: CloudflareRoot;
|
|
189
|
+
readonly options: CloudflareWorkerOptions;
|
|
190
|
+
/**
|
|
191
|
+
* The Worker's handlers (`export default app.worker`): one application per
|
|
192
|
+
* environment identity, built on the first event and shared by concurrent
|
|
193
|
+
* cold events, the app's Workflows and its service entrypoints.
|
|
194
|
+
*/
|
|
195
|
+
readonly worker: CloudflareWorker;
|
|
196
|
+
/** The Durable Object classes defined from this app, in definition order. */
|
|
197
|
+
readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];
|
|
198
|
+
/** The Workflow classes defined from this app, in definition order. */
|
|
199
|
+
readonly workflows: readonly CloudflareWorkflowDescriptor[];
|
|
200
|
+
/** The service entrypoint classes defined from this app, in definition order. */
|
|
201
|
+
readonly entrypoints: readonly CloudflareEntrypointDescriptor[];
|
|
202
|
+
}
|
|
203
|
+
/** Whether `value` is an app {@link defineCloudflareApp} returned. */
|
|
204
|
+
declare function isCloudflareApp(value: unknown): value is CloudflareApp;
|
|
205
|
+
/**
|
|
206
|
+
* Define one Cloudflare application from a static root module (a module class
|
|
207
|
+
* or a `DynamicModule`) and its options. The Worker entry exports its Worker
|
|
208
|
+
* and the Durable Object, Workflow and service entrypoint classes defined from
|
|
209
|
+
* it, which share the root and the options: runtime `adapters` configure every
|
|
210
|
+
* application and Durable Object context the app builds.
|
|
211
|
+
*
|
|
212
|
+
* ```ts
|
|
213
|
+
* import { defineCloudflareApp } from '@velajs/cloudflare';
|
|
214
|
+
* import { VelaDurableObject } from '@velajs/cloudflare/durable-objects';
|
|
215
|
+
*
|
|
216
|
+
* const app = defineCloudflareApp(AppModule, { globalPrefix: '/api' });
|
|
217
|
+
* export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}
|
|
218
|
+
* export default app.worker;
|
|
219
|
+
* ```
|
|
220
|
+
*
|
|
221
|
+
* The Worker builds one application per environment identity. The app's
|
|
222
|
+
* Workflows (`VelaWorkflow`) and service entrypoints (`VelaEntrypoint`) run in
|
|
223
|
+
* that application, with their hosts added to the root module's providers;
|
|
224
|
+
* each Durable Object instance boots its own application context. Declare the
|
|
225
|
+
* classes in the module that defines the app: a class file importing the app
|
|
226
|
+
* from the Worker entry would run before the entry defined it. Keep them in
|
|
227
|
+
* the entry, or define the app in a module of its own that the entry and the
|
|
228
|
+
* class files import. `createCloudflareWorker` is
|
|
229
|
+
* `defineCloudflareApp(rootModule, options).worker`.
|
|
230
|
+
*/
|
|
231
|
+
declare function defineCloudflareApp(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): CloudflareApp;
|
|
232
|
+
/**
|
|
233
|
+
* Worker entrypoint with one bootstrap per environment identity: the Worker of
|
|
234
|
+
* `defineCloudflareApp(rootModule, options)`. Concurrent cold events share
|
|
235
|
+
* construction, including `configure`; failed construction is evicted so the
|
|
236
|
+
* next event can retry. Define the app with {@link defineCloudflareApp} when the
|
|
237
|
+
* entry also exports Durable Object classes built from it.
|
|
238
|
+
*/
|
|
239
|
+
declare function createCloudflareWorker(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): CloudflareWorker;
|
|
240
|
+
//#endregion
|
|
241
|
+
export { defineCloudflareApp as _, CloudflareApp as a, CloudflareEntrypointDescriptor as c, CloudflareWorkerOptions as d, CloudflareWorkflowDescriptor as f, createCloudflareWorker as g, createCloudflareApp as h, CLOUDFLARE_WORKFLOW as i, CloudflareWorker as l, cloudflareAdapter as m, CLOUDFLARE_ENTRYPOINT as n, CloudflareAppOptions as o, CreateCloudflareAppOptions as p, CLOUDFLARE_WORKER as r, CloudflareDurableObjectDescriptor as s, CLOUDFLARE_DURABLE_OBJECT as t, CloudflareWorkerDescriptor as u, isCloudflareApp as v, CloudflareRoot as y };
|