@velajs/cloudflare 1.30.0 → 1.31.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 (76) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +260 -74
  3. package/dist/bindings.js +77 -0
  4. package/dist/bindings.js.map +1 -0
  5. package/dist/cloudflare-application.js +7 -34
  6. package/dist/cloudflare-application.js.map +1 -1
  7. package/dist/cloudflare-factory-eGiet0mg.d.ts +288 -0
  8. package/dist/cloudflare-factory.js +84 -28
  9. package/dist/cloudflare-factory.js.map +1 -1
  10. package/dist/diagnostics.js +18 -0
  11. package/dist/diagnostics.js.map +1 -0
  12. package/dist/durable-objects.d.ts +6 -2
  13. package/dist/index.d.ts +160 -455
  14. package/dist/index.js +7 -13
  15. package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
  16. package/dist/platform.js +22 -0
  17. package/dist/platform.js.map +1 -0
  18. package/dist/queue/cloudflare-queues.js +7 -7
  19. package/dist/queue/cloudflare-queues.js.map +1 -1
  20. package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
  21. package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
  22. package/dist/root-module-C23bUwt_.d.ts +11 -0
  23. package/dist/schedule-diagnostics.js +8 -15
  24. package/dist/schedule-diagnostics.js.map +1 -1
  25. package/dist/services/kv-cache.store.js +33 -7
  26. package/dist/services/kv-cache.store.js.map +1 -1
  27. package/dist/storage/r2-storage.js +30 -0
  28. package/dist/storage/r2-storage.js.map +1 -0
  29. package/dist/storage.d.ts +28 -0
  30. package/dist/storage.js +2 -0
  31. package/dist/testing.d.ts +96 -0
  32. package/dist/testing.js +111 -0
  33. package/dist/testing.js.map +1 -0
  34. package/dist/websocket/binding-gateways.js +33 -0
  35. package/dist/websocket/binding-gateways.js.map +1 -0
  36. package/dist/websocket/cf-room-registry.js +3 -1
  37. package/dist/websocket/cf-room-registry.js.map +1 -1
  38. package/dist/websocket/do-bootstrap.js +36 -15
  39. package/dist/websocket/do-bootstrap.js.map +1 -1
  40. package/dist/websocket/do-live.js +49 -90
  41. package/dist/websocket/do-live.js.map +1 -1
  42. package/dist/websocket/do-state.js.map +1 -1
  43. package/dist/websocket/live-driver.js +149 -0
  44. package/dist/websocket/live-driver.js.map +1 -0
  45. package/dist/websocket/room-id.js +11 -1
  46. package/dist/websocket/room-id.js.map +1 -1
  47. package/dist/websocket/websocket.durable-object.js +14 -10
  48. package/dist/websocket/websocket.durable-object.js.map +1 -1
  49. package/dist/websocket/worker-transport.js +80 -0
  50. package/dist/websocket/worker-transport.js.map +1 -0
  51. package/package.json +23 -6
  52. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
  53. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
  54. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
  55. package/dist/storage/r2-storage.driver.js +0 -67
  56. package/dist/storage/r2-storage.driver.js.map +0 -1
  57. package/dist/storage/storage-key-claim.js +0 -74
  58. package/dist/storage/storage-key-claim.js.map +0 -1
  59. package/dist/storage/storage-manager.service.js +0 -38
  60. package/dist/storage/storage-manager.service.js.map +0 -1
  61. package/dist/storage/storage.controller.js +0 -64
  62. package/dist/storage/storage.controller.js.map +0 -1
  63. package/dist/storage/storage.module.js +0 -25
  64. package/dist/storage/storage.module.js.map +0 -1
  65. package/dist/storage/storage.service.js +0 -64
  66. package/dist/storage/storage.service.js.map +0 -1
  67. package/dist/storage/storage.tokens.js +0 -7
  68. package/dist/storage/storage.tokens.js.map +0 -1
  69. package/dist/websocket/broadcast.js +0 -32
  70. package/dist/websocket/broadcast.js.map +0 -1
  71. package/dist/websocket/cloudflare-websocket.module.js +0 -25
  72. package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
  73. package/dist/websocket/websocket-routing.js +0 -133
  74. package/dist/websocket/websocket-routing.js.map +0 -1
  75. package/dist/websocket/ws-server-holder.js +0 -38
  76. package/dist/websocket/ws-server-holder.js.map +0 -1
@@ -0,0 +1,77 @@
1
+ import { defineBinding } from "@velajs/vela/module-kit";
2
+ //#region src/bindings.ts
3
+ /** Whether a value exposes every named operation as a function. */
4
+ function hasOperations(value, operations) {
5
+ if (typeof value !== "object" || value === null) return false;
6
+ return operations.every((operation) => typeof Reflect.get(value, operation) === "function");
7
+ }
8
+ /**
9
+ * Name-based Workers binding factories. Each takes `{ binding }`, the name
10
+ * declared in the Wrangler configuration, and returns a reference that reads
11
+ * and validates the native binding from an application's `ENV` when called.
12
+ * Declaring one reads no environment, so references belong in static module
13
+ * options: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.
14
+ */
15
+ /** A KV namespace declared under `kv_namespaces`. */
16
+ const KV_NAMESPACE = {
17
+ name: "KV namespace",
18
+ configKey: "kv_namespaces",
19
+ accepts: (value) => hasOperations(value, [
20
+ "get",
21
+ "put",
22
+ "delete",
23
+ "list",
24
+ "getWithMetadata"
25
+ ])
26
+ };
27
+ const kv = /* @__PURE__ */ defineBinding(KV_NAMESPACE);
28
+ /** An R2 bucket declared under `r2_buckets`. */
29
+ const R2_BUCKET = {
30
+ name: "R2 bucket",
31
+ configKey: "r2_buckets",
32
+ accepts: (value) => hasOperations(value, [
33
+ "get",
34
+ "put",
35
+ "head",
36
+ "delete",
37
+ "list",
38
+ "createMultipartUpload"
39
+ ])
40
+ };
41
+ const r2 = /* @__PURE__ */ defineBinding(R2_BUCKET);
42
+ /** A D1 database declared under `d1_databases`. */
43
+ const D1_DATABASE = {
44
+ name: "D1 database",
45
+ configKey: "d1_databases",
46
+ accepts: (value) => hasOperations(value, [
47
+ "prepare",
48
+ "batch",
49
+ "exec"
50
+ ])
51
+ };
52
+ const d1 = /* @__PURE__ */ defineBinding(D1_DATABASE);
53
+ /** A queue producer declared under `queues.producers`. */
54
+ const QUEUE_PRODUCER = {
55
+ name: "queue producer",
56
+ configKey: "queues.producers",
57
+ accepts: (value) => hasOperations(value, ["send"])
58
+ };
59
+ const queue = /* @__PURE__ */ defineBinding(QUEUE_PRODUCER);
60
+ /** A Durable Object namespace declared under `durable_objects.bindings`. */
61
+ const DURABLE_OBJECT_NAMESPACE = {
62
+ name: "Durable Object namespace",
63
+ configKey: "durable_objects.bindings",
64
+ accepts: (value) => hasOperations(value, ["idFromName", "get"])
65
+ };
66
+ const durableObject = /* @__PURE__ */ defineBinding(DURABLE_OBJECT_NAMESPACE);
67
+ /** A Workers Rate Limiting binding declared under `ratelimits`. */
68
+ const RATE_LIMITER = {
69
+ name: "rate limiter",
70
+ configKey: "ratelimits",
71
+ accepts: (value) => hasOperations(value, ["limit"])
72
+ };
73
+ const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);
74
+ //#endregion
75
+ export { D1_DATABASE, DURABLE_OBJECT_NAMESPACE, KV_NAMESPACE, QUEUE_PRODUCER, R2_BUCKET, RATE_LIMITER, d1, durableObject, kv, queue, r2, rateLimit };
76
+
77
+ //# sourceMappingURL=bindings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bindings.js","names":[],"sources":["../src/bindings.ts"],"sourcesContent":["import { defineBinding, type BindingKind } 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"],"mappings":";;;AAGA,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"}
@@ -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 for grabbing a service — e.g. an auth service —
89
- * to use inside `createCloudflareApp({ middleware: env => [...] })` request middleware,
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
@@ -99,6 +95,11 @@ var CloudflareApplication = class {
99
95
  get entrypoints() {
100
96
  return this.#app.entrypoints;
101
97
  }
98
+ /** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */
99
+ enableCors(options) {
100
+ this.#app.enableCors(options);
101
+ return this;
102
+ }
102
103
  /**
103
104
  * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the
104
105
  * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,
@@ -124,34 +125,6 @@ var CloudflareApplication = class {
124
125
  return this;
125
126
  }
126
127
  /**
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
128
  * Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose
156
129
  * expression is exactly `event.cron` (the trigger string is compared as
157
130
  * 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,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;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"}
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 /** 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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,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,288 @@
1
+ import { t as CloudflareRoot } from "./root-module-C23bUwt_.js";
2
+ import { CorsOptions, GlobalPrefixOptions, InjectionToken, VelaApplication, VelaCreateOptions, VelaEnv, VelaSecurityOptions, VersioningOptions } from "@velajs/vela";
3
+ import { ExecutionContext } from "hono";
4
+ import { RuntimeAdapter } from "@velajs/vela/module-kit";
5
+ //#region src/scheduled-event.d.ts
6
+ /**
7
+ * The event a Worker's `scheduled()` export receives. The native
8
+ * `ScheduledController` satisfies it; direct calls (tests, scripts) may omit
9
+ * `scheduledTime`, which then defaults to the current time, and `noRetry`.
10
+ */
11
+ interface ScheduledEvent {
12
+ readonly cron: string;
13
+ readonly scheduledTime?: number;
14
+ noRetry?(): void;
15
+ }
16
+ /** The Cloudflare trigger behind the current scheduled invocation. */
17
+ interface CloudflareScheduledEvent {
18
+ /** The trigger's exact cron string; it equals the invocation's `expression`. */
19
+ readonly cron: string;
20
+ /** The platform's scheduled time in Unix milliseconds. */
21
+ readonly scheduledTime: number;
22
+ /**
23
+ * Ask Cloudflare not to retry this trigger if the invocation fails. Already
24
+ * bound to the native controller, so it can be passed around or destructured.
25
+ * A no-op for direct calls that supplied no controller.
26
+ */
27
+ readonly noRetry: () => void;
28
+ }
29
+ /**
30
+ * Request-scoped Cloudflare view of the scheduled trigger, seeded into each
31
+ * `@Cron` job's invocation scope by the Cloudflare adapter. Inject it where a
32
+ * job needs platform controls such as `noRetry()`; the job's argument stays
33
+ * the portable `ScheduleInvocation`. It resolves only inside a scheduled
34
+ * invocation; resolving it anywhere else throws. A cron job fired on demand
35
+ * (Studio's run-now) receives a synthetic event: `cron` is the job's
36
+ * expression and `noRetry()` does nothing.
37
+ *
38
+ * The token provides itself as request-scoped in every container, so a class
39
+ * that injects it is request-scoped wherever the graph boots (a Worker, a
40
+ * Durable Object, the CLI or a testing module) and is built only for an
41
+ * invocation, never at bootstrap.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * @Injectable({ scope: Scope.REQUEST })
46
+ * class Reports {
47
+ * constructor(@Inject(CLOUDFLARE_SCHEDULED_EVENT) private readonly trigger: CloudflareScheduledEvent) {}
48
+ *
49
+ * @Cron('0 3 * * *', { dialect: 'cloudflare' })
50
+ * async nightly(tick: CronInvocation) {
51
+ * if (!(await this.upstreamAvailable(tick.signal))) this.trigger.noRetry();
52
+ * }
53
+ * }
54
+ * ```
55
+ */
56
+ declare const CLOUDFLARE_SCHEDULED_EVENT: InjectionToken<CloudflareScheduledEvent>;
57
+ //#endregion
58
+ //#region src/cloudflare-application.d.ts
59
+ /**
60
+ * Options accepted by {@link CloudflareApplication.mountOpenApi}.
61
+ *
62
+ * Re-exposes vela's `MountOpenApiOptions` type — derived structurally from
63
+ * the underlying `VelaApplication.mountOpenApi` signature so consumers don't
64
+ * have to reach into vela's internal subpaths to type the argument.
65
+ */
66
+ type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
67
+ /**
68
+ * Wraps VelaApplication with Cloudflare-specific handlers:
69
+ * - `fetch` — HTTP request handler (from Hono)
70
+ * - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose
71
+ * expression is the trigger's exact string)
72
+ * - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,
73
+ * then `QueueModule`'s native consumer)
74
+ * - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on
75
+ * the underlying Hono app
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * const app = await createCloudflareApp(AppModule, { env });
80
+ * export default {
81
+ * fetch: app.fetch,
82
+ * scheduled: app.scheduled.bind(app),
83
+ * queue: app.queue.bind(app),
84
+ * };
85
+ * ```
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * // Serve OpenAPI docs alongside your routes
90
+ * const app = await createCloudflareApp(AppModule, { env });
91
+ * const document = createOpenApiDocument(AppModule);
92
+ * app.mountOpenApi({ document, ui: 'scalar' });
93
+ * // GET /openapi.json -> JSON document
94
+ * // GET /scalar -> Scalar UI (loads from CDN)
95
+ * ```
96
+ */
97
+ declare class CloudflareApplication {
98
+ #private;
99
+ readonly env: VelaEnv;
100
+ constructor(app: VelaApplication, env: VelaEnv);
101
+ readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext) => Promise<Response>;
102
+ getHonoApp(): ReturnType<VelaApplication['getHonoApp']>;
103
+ /**
104
+ * Resolve a provider from the application's DI container (delegates to
105
+ * `VelaApplication.get`). Handy in `createCloudflareWorker({ configure })`,
106
+ * which finishes the HTTP surface outside the DI request pipeline.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * const app = await createCloudflareApp(AppModule, { env });
111
+ * const auth = app.get(BetterAuthService);
112
+ * ```
113
+ */
114
+ readonly get: VelaApplication['get'];
115
+ get entrypoints(): VelaApplication['entrypoints'];
116
+ /** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */
117
+ enableCors(options?: CorsOptions): this;
118
+ /**
119
+ * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the
120
+ * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,
121
+ * so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when
122
+ * opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from
123
+ * a CDN at runtime, nothing is bundled server-side.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * import { createOpenApiDocument } from '@velajs/vela/openapi';
128
+ *
129
+ * const app = await createCloudflareApp(AppModule, { env });
130
+ * const document = createOpenApiDocument(AppModule, {
131
+ * info: { title: 'My API', version: '1.0.0' },
132
+ * });
133
+ * app.mountOpenApi({ document, ui: 'scalar' });
134
+ * // GET /openapi.json -> { openapi: '3.1.0', ... }
135
+ * // GET /scalar -> Scalar UI HTML
136
+ * ```
137
+ */
138
+ mountOpenApi(options: MountOpenApiOptions): this;
139
+ /**
140
+ * Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose
141
+ * expression is exactly `event.cron` (the trigger string is compared as
142
+ * delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch
143
+ * primitive every runtime shares. Each job receives only its
144
+ * `ScheduleInvocation`, runs in a fresh invocation scope seeded with
145
+ * {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`
146
+ * dispatch. The trigger settles after every matching job and its managed
147
+ * work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.
148
+ */
149
+ scheduled(event: ScheduledEvent, env: VelaEnv, _ctx?: {
150
+ waitUntil: (promise: Promise<unknown>) => void;
151
+ }): Promise<void>;
152
+ /**
153
+ * Run one queue consumer inside a fresh request scope, through the shared
154
+ * guard → interceptor pipeline (components declared with
155
+ * `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or
156
+ * method). HTTP-global components deliberately do NOT apply — an HTTP auth
157
+ * guard has no business rejecting a queue batch. Unclaimed errors are
158
+ * reported once (`QueueModule`'s consumer reports its own) and rethrow so
159
+ * the platform's retry semantics stay intact.
160
+ */
161
+ private dispatchEntrypoint;
162
+ /**
163
+ * Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read
164
+ * from `app.entrypoints` claim a batch by its physical queue name and
165
+ * receive it whole. A batch no handler claims goes to `QueueModule`'s native
166
+ * consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which
167
+ * routes each job by its logical queue. Each dispatch runs inside a fresh
168
+ * request-scoped child (request-scoped providers rebuild per batch — no
169
+ * boot-time captives). A batch nothing claims rejects: resolving would let
170
+ * Cloudflare acknowledge every message implicitly.
171
+ */
172
+ queue(batch: {
173
+ queue: string;
174
+ messages: readonly unknown[];
175
+ }, env: VelaEnv, ctx: {
176
+ waitUntil: (promise: Promise<unknown>) => void;
177
+ }): Promise<void>;
178
+ /**
179
+ * A raw `@QueueConsumer` owns its physical queue's batches and must not carry
180
+ * jobs of a queue registered with `QueueModule`: those reach their
181
+ * `@Processor` only if the raw handler dispatches them itself, while
182
+ * `cloudflareQueues()` delivers registered queues. Warn once per physical and
183
+ * logical queue (unless diagnostics are silent); the raw consumer still
184
+ * receives and settles the batch.
185
+ */
186
+ private warnRawJobs;
187
+ /**
188
+ * Abort the signals of scheduled jobs still running, wait for them and their
189
+ * managed work to settle, then close the application.
190
+ */
191
+ close(signal?: string): Promise<void>;
192
+ }
193
+ //#endregion
194
+ //#region src/cloudflare-factory.d.ts
195
+ interface CloudflareAppOptions {
196
+ globalPrefix?: string;
197
+ /** Routes served without the global prefix (`{ exclude }`). */
198
+ globalPrefixOptions?: GlobalPrefixOptions;
199
+ /** URI versioning: the version segment prefix (default `'v'`). */
200
+ versioning?: VersioningOptions;
201
+ security?: VelaSecurityOptions;
202
+ /** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */
203
+ cors?: CorsOptions | boolean;
204
+ /** Further runtime adapters, composed after the Cloudflare adapter for each application. */
205
+ adapters?: RuntimeAdapter[];
206
+ }
207
+ interface CloudflareWorkerOptions extends CloudflareAppOptions {
208
+ /**
209
+ * Finish each application's HTTP surface, such as extra Hono routes, once per
210
+ * environment. It runs after the application is built and before any event,
211
+ * including concurrent cold events, reaches it; a throw fails that
212
+ * construction, and the next event retries. It must be synchronous and do no
213
+ * I/O (a returned promise fails the construction): read bindings in
214
+ * providers. Request middleware belongs in modules (`configure(consumer)`),
215
+ * which can inject `ENV`.
216
+ */
217
+ configure?(app: CloudflareApplication, env: VelaEnv): void;
218
+ }
219
+ interface CreateCloudflareAppOptions extends CloudflareAppOptions {
220
+ /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */
221
+ env: VelaEnv;
222
+ }
223
+ /**
224
+ * Bind an application to one environment: seeded as the global ENV before
225
+ * provider factories and lifecycle hooks, and asserted on every request. The
226
+ * adapter also registers the Worker's platform wiring: `WebSocketModule`
227
+ * forwards each authenticated gateway upgrade to the room's Durable Object,
228
+ * and `LiveModule` sends invalidations there. It supplies the
229
+ * `InternalDispatcher` transport, so signed queue and schedule dispatch
230
+ * re-enter this application's routes, and reports, through the diagnostics
231
+ * policy, schedule declarations a cron trigger cannot honor and binding-backed
232
+ * gateways without `WebSocketModule`.
233
+ */
234
+ declare function cloudflareAdapter(options: {
235
+ env: VelaEnv;
236
+ }): RuntimeAdapter;
237
+ /**
238
+ * Build an application for one native Workers environment. Call inside a platform event.
239
+ * The root is static: a module class or a `DynamicModule` declared at module scope.
240
+ * Read bindings in providers (`@InjectEnv()`) and module factories
241
+ * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
242
+ */
243
+ declare function createCloudflareApp(rootModule: CloudflareRoot, options: CreateCloudflareAppOptions): Promise<CloudflareApplication>;
244
+ /**
245
+ * The well-known key under which a `createCloudflareWorker()` entry carries
246
+ * its {@link CloudflareWorkerDescriptor}: `Symbol.for('vela.cloudflare.worker')`.
247
+ */
248
+ declare const CLOUDFLARE_WORKER: unique symbol;
249
+ /** What a Worker entry is built from, for tools that load it outside a platform event. */
250
+ interface CloudflareWorkerDescriptor {
251
+ readonly rootModule: CloudflareRoot;
252
+ readonly options: CloudflareWorkerOptions;
253
+ /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */
254
+ createOptions(env: VelaEnv): VelaCreateOptions;
255
+ /**
256
+ * `VelaFactory.create(rootModule, createOptions(env))`: the application
257
+ * without its Worker handlers or the `configure` hook, which receives the
258
+ * Workers application.
259
+ */
260
+ createApplication(env: VelaEnv): Promise<VelaApplication>;
261
+ }
262
+ /** The exported handlers of a `createCloudflareWorker()` entry. */
263
+ interface CloudflareWorker {
264
+ fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
265
+ scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
266
+ waitUntil: (promise: Promise<unknown>) => void;
267
+ }): Promise<void>;
268
+ queue(batch: {
269
+ queue: string;
270
+ messages: readonly unknown[];
271
+ }, env: VelaEnv, ctx: {
272
+ waitUntil: (promise: Promise<unknown>) => void;
273
+ }): Promise<void>;
274
+ /**
275
+ * Symbol-keyed, so the platform, which reads string-keyed handlers, ignores
276
+ * it; enumerable, so `{ ...worker, email }` keeps it for the CLI.
277
+ */
278
+ readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;
279
+ }
280
+ /**
281
+ * Worker entrypoint with one bootstrap per environment identity. Concurrent cold
282
+ * events share construction, including `configure`; failed construction is
283
+ * evicted so the next event can retry. Weak keys stop this cache from
284
+ * retaining a replaced environment.
285
+ */
286
+ declare function createCloudflareWorker(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): CloudflareWorker;
287
+ //#endregion
288
+ export { CloudflareWorkerOptions as a, createCloudflareApp as c, MountOpenApiOptions as d, CLOUDFLARE_SCHEDULED_EVENT as f, CloudflareWorkerDescriptor as i, createCloudflareWorker as l, ScheduledEvent as m, CloudflareAppOptions as n, CreateCloudflareAppOptions as o, CloudflareScheduledEvent as p, CloudflareWorker as r, cloudflareAdapter as s, CLOUDFLARE_WORKER as t, CloudflareApplication as u };