@velajs/cloudflare 1.28.0 → 1.30.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 (91) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.md +190 -69
  3. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +9 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +6 -0
  5. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +8 -0
  6. package/dist/cloudflare-application.js +309 -0
  7. package/dist/cloudflare-application.js.map +1 -0
  8. package/dist/cloudflare-factory.js +109 -0
  9. package/dist/cloudflare-factory.js.map +1 -0
  10. package/dist/decorators/queue-consumer.js +39 -0
  11. package/dist/decorators/queue-consumer.js.map +1 -0
  12. package/dist/durable-objects.d.ts +11 -11
  13. package/dist/durable-objects.js +2 -512
  14. package/dist/environment.js +19 -0
  15. package/dist/environment.js.map +1 -0
  16. package/dist/index.d.ts +146 -111
  17. package/dist/index.js +21 -1130
  18. package/dist/nonce/durable-object-nonce.store.js +33 -0
  19. package/dist/nonce/durable-object-nonce.store.js.map +1 -0
  20. package/dist/nonce/nonce-validation.js +18 -0
  21. package/dist/nonce/nonce-validation.js.map +1 -0
  22. package/dist/nonce/nonce.durable-object.js +54 -0
  23. package/dist/nonce/nonce.durable-object.js.map +1 -0
  24. package/dist/{nonce.durable-object-DffHMRnU.d.ts → nonce.durable-object-Ci9AGssY.d.ts} +9 -7
  25. package/dist/queue/cloudflare-queues.js +215 -0
  26. package/dist/queue/cloudflare-queues.js.map +1 -0
  27. package/dist/queues.d.ts +48 -0
  28. package/dist/queues.js +2 -0
  29. package/dist/rate-limit/cloudflare-rate-limit.store.js +40 -0
  30. package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -0
  31. package/dist/schedule-diagnostics.js +51 -0
  32. package/dist/schedule-diagnostics.js.map +1 -0
  33. package/dist/scheduled-event.js +68 -0
  34. package/dist/scheduled-event.js.map +1 -0
  35. package/dist/services/flagship-flag.driver.js +52 -0
  36. package/dist/services/flagship-flag.driver.js.map +1 -0
  37. package/dist/services/kv-cache.store.js +82 -0
  38. package/dist/services/kv-cache.store.js.map +1 -0
  39. package/dist/services/kv-flag.driver.js +62 -0
  40. package/dist/services/kv-flag.driver.js.map +1 -0
  41. package/dist/storage/r2-storage.driver.js +67 -0
  42. package/dist/storage/r2-storage.driver.js.map +1 -0
  43. package/dist/storage/storage-key-claim.js +74 -0
  44. package/dist/storage/storage-key-claim.js.map +1 -0
  45. package/dist/storage/storage-manager.service.js +38 -0
  46. package/dist/storage/storage-manager.service.js.map +1 -0
  47. package/dist/storage/storage.controller.js +64 -0
  48. package/dist/storage/storage.controller.js.map +1 -0
  49. package/dist/storage/storage.module.js +25 -0
  50. package/dist/storage/storage.module.js.map +1 -0
  51. package/dist/storage/storage.service.js +64 -0
  52. package/dist/storage/storage.service.js.map +1 -0
  53. package/dist/storage/storage.tokens.js +7 -0
  54. package/dist/storage/storage.tokens.js.map +1 -0
  55. package/dist/vela-env-DFvyoNT3.d.ts +9 -0
  56. package/dist/websocket/broadcast.js +32 -0
  57. package/dist/websocket/broadcast.js.map +1 -0
  58. package/dist/websocket/cf-room-registry.js +137 -0
  59. package/dist/websocket/cf-room-registry.js.map +1 -0
  60. package/dist/websocket/cf-ws-client.js +94 -0
  61. package/dist/websocket/cf-ws-client.js.map +1 -0
  62. package/dist/websocket/cloudflare-websocket.module.js +25 -0
  63. package/dist/websocket/cloudflare-websocket.module.js.map +1 -0
  64. package/dist/websocket/do-bootstrap.js +56 -0
  65. package/dist/websocket/do-bootstrap.js.map +1 -0
  66. package/dist/websocket/do-live.js +184 -0
  67. package/dist/websocket/do-live.js.map +1 -0
  68. package/dist/websocket/do-pitr.js +81 -0
  69. package/dist/websocket/do-pitr.js.map +1 -0
  70. package/dist/websocket/do-state.js +7 -0
  71. package/dist/websocket/do-state.js.map +1 -0
  72. package/dist/websocket/do-websocket-host.js +169 -0
  73. package/dist/websocket/do-websocket-host.js.map +1 -0
  74. package/dist/websocket/room-id.js +27 -0
  75. package/dist/websocket/room-id.js.map +1 -0
  76. package/dist/websocket/websocket-routing.js +133 -0
  77. package/dist/websocket/websocket-routing.js.map +1 -0
  78. package/dist/websocket/websocket.durable-object.js +138 -0
  79. package/dist/websocket/websocket.durable-object.js.map +1 -0
  80. package/dist/websocket/ws-attachment.js +79 -0
  81. package/dist/websocket/ws-attachment.js.map +1 -0
  82. package/dist/websocket/ws-server-holder.js +38 -0
  83. package/dist/websocket/ws-server-holder.js.map +1 -0
  84. package/package.json +14 -11
  85. package/dist/durable-objects.js.map +0 -1
  86. package/dist/index.js.map +0 -1
  87. package/dist/nonce-validation-CeVihShV.js +0 -517
  88. package/dist/nonce-validation-CeVihShV.js.map +0 -1
  89. package/dist/queue.d.ts +0 -32
  90. package/dist/queue.js +0 -78
  91. package/dist/queue.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,1130 +1,21 @@
1
- import { C as durableObjectRoomName, T as roomToDurableId, _ as readDoPitrBookmark, a as durableObjectLive, b as assertCloudflareEnvironment, c as liveInvalidateToRoom, g as isDoPitrUnavailable, h as armDoPitr, i as durableObjectCursorLog, m as DoPitrUnavailableError, n as isValidExpiry, p as WsServerHolder, r as DoCursorLog, t as isCanonicalBoundedText, v as __decorate, x as registerCloudflareEnvironment, y as resolveCloudflareRoot } from "./nonce-validation-CeVihShV.js";
2
- import { getConnInfo } from "hono/cloudflare-workers";
3
- import { CRON_METADATA, ConfigurableModuleBuilder, Controller, Get, Inject, Injectable, InjectionToken, Module, PipelineRunner, Req, VelaFactory, buildEntrypointExecutionContext, createParamDecorator, defineMetadata, defineProvider, getEntrypointModuleId, getMetadata, getTrustedRequestIdentity, parseCron, registerEntrypointKind, resolveEntrypoint, resolveErrorReporter, resolveScopedComponentsAsync, runInEntrypointScope, shouldFilterCatch } from "@velajs/vela";
4
- import { ConnectedSocket, DEFAULT_WS_MAX_FRAME_BYTES, MessageBody, SubscribeMessage, WS_GATEWAY_METADATA, WS_SERVER, WebSocketGateway, WebSocketServer, WsDispatcher, WsException, assertBroadcastCommandFits, authenticateWebSocketUpgrade, readWsEntrypointMeta, resolveGatewayRoomId, resolveGatewayRoomParam, resolveMaxFrameBytes } from "@velajs/vela/websocket";
5
- import { STORAGE_SIGNED_URL_PURPOSE, joinStoragePath, signUrl, verifySignedUrl } from "@velajs/vela/storage";
6
- //#region src/websocket/websocket-routing.ts
7
- const MAX_IDENTITY_FIELD_BYTES = 2048;
8
- const encoder = new TextEncoder();
9
- function isIdentityField(value) {
10
- return typeof value === "string" && value.length > 0 && !value.includes("\r") && !value.includes("\n") && encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES;
11
- }
12
- /** `null` means an identity was present but violated the transport contract. */
13
- function accessIdentity(c) {
14
- const value = getTrustedRequestIdentity(c.req.raw);
15
- if (!value) return void 0;
16
- const { principal, tenantId, expiresAtMs } = value;
17
- if (!isIdentityField(principal.issuer) || !isIdentityField(principal.subject) || !isIdentityField(tenantId) || typeof expiresAtMs !== "number" || !Number.isSafeInteger(expiresAtMs) || expiresAtMs <= 0) return null;
18
- return {
19
- principal,
20
- tenantId,
21
- expiresAtMs
22
- };
23
- }
24
- /** `null` means two independently verified identities disagree. */
25
- function combineIdentities(requestIdentity, upgradeIdentity) {
26
- if (!requestIdentity && !upgradeIdentity) return void 0;
27
- if (!requestIdentity) return upgradeIdentity;
28
- if (!upgradeIdentity) return requestIdentity;
29
- if (requestIdentity.principal.issuer !== upgradeIdentity.principal.issuer || requestIdentity.principal.subject !== upgradeIdentity.principal.subject || requestIdentity.principal.principalType !== upgradeIdentity.principal.principalType || requestIdentity.tenantId !== upgradeIdentity.tenantId) return null;
30
- return {
31
- principal: { ...upgradeIdentity.principal },
32
- tenantId: upgradeIdentity.tenantId,
33
- expiresAtMs: Math.min(requestIdentity.expiresAtMs, upgradeIdentity.expiresAtMs)
34
- };
35
- }
36
- /** Read `@WebSocketGateway({ path, binding })` off a resolved instance (CF-hosted gateways only). */
37
- function collectWsGatewayRoutes(instance) {
38
- const options = getMetadata(WS_GATEWAY_METADATA, instance.constructor);
39
- if (!options?.path || !options?.binding) return [];
40
- resolveGatewayRoomParam(options);
41
- resolveMaxFrameBytes(options);
42
- return [{
43
- path: options.path,
44
- binding: options.binding,
45
- options: { ...options }
46
- }];
47
- }
48
- /**
49
- * Registers the upgrade routes on the Worker's Hono app. Each route validates
50
- * the `Upgrade` header, resolves the room's Durable Object, and forwards the raw
51
- * request — injecting spoof-safe `x-vela-*` headers the DO reads. The DO returns
52
- * the `101` with the client socket.
53
- */
54
- function registerWebSocketRoutes(hono, routes) {
55
- for (const route of routes) hono.get(route.path, async (c) => {
56
- if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return c.text("Expected WebSocket upgrade", 426);
57
- const headers = new Headers(c.req.raw.headers);
58
- headers.delete("x-vela-room");
59
- headers.delete("x-vela-path");
60
- headers.delete("x-vela-user");
61
- headers.delete("x-vela-expires-at");
62
- headers.delete("x-vela-expires-at-ms");
63
- headers.delete("x-vela-issuer");
64
- headers.delete("x-vela-subject");
65
- headers.delete("x-vela-principal-type");
66
- headers.delete("x-vela-tenant");
67
- const sanitizedRequest = new Request(c.req.raw, { headers });
68
- let roomId;
69
- try {
70
- roomId = resolveGatewayRoomId(route.options, (name) => c.req.param(name));
71
- } catch {
72
- return c.text("Invalid WebSocket room", 400);
73
- }
74
- const upgrade = await authenticateWebSocketUpgrade(route.options, sanitizedRequest, roomId);
75
- if (upgrade === false) return c.text("WebSocket upgrade forbidden", 403);
76
- const requestIdentity = accessIdentity(c);
77
- if (requestIdentity === null) return c.text("Invalid WebSocket identity", 403);
78
- const identity = combineIdentities(requestIdentity, upgrade.identity);
79
- if (identity === null) return c.text("Conflicting WebSocket identities", 403);
80
- if (identity && identity.expiresAtMs <= Date.now()) return c.text("WebSocket identity expired", 403);
81
- const forwardHeaders = new Headers(upgrade.request.headers);
82
- forwardHeaders.set("x-vela-room", roomId);
83
- forwardHeaders.set("x-vela-path", route.path);
84
- if (identity) {
85
- forwardHeaders.set("x-vela-user", identity.principal.subject);
86
- forwardHeaders.set("x-vela-issuer", identity.principal.issuer);
87
- forwardHeaders.set("x-vela-subject", identity.principal.subject);
88
- forwardHeaders.set("x-vela-principal-type", identity.principal.principalType);
89
- forwardHeaders.set("x-vela-tenant", identity.tenantId);
90
- forwardHeaders.set("x-vela-expires-at-ms", String(identity.expiresAtMs));
91
- }
92
- return forwardToRoom(c.env, route.binding, route.path, roomId, new Request(upgrade.request, { headers: forwardHeaders }));
93
- });
94
- }
95
- /**
96
- * Gateway metadata contains a runtime binding name, so the native type is
97
- * erased. Validate only the operations consumed here and their observable
98
- * results; never assert that an arbitrary value implements a native namespace.
99
- */
100
- async function forwardToRoom(env, binding, path, room, request) {
101
- if (typeof env !== "object" || env === null) throw new Error("Worker environment is missing");
102
- const namespace = Reflect.get(env, binding);
103
- if (typeof namespace !== "object" || namespace === null) return new Response(`Durable Object binding '${binding}' is not configured`, { status: 500 });
104
- const idFromName = Reflect.get(namespace, "idFromName");
105
- const get = Reflect.get(namespace, "get");
106
- if (typeof idFromName !== "function" || typeof get !== "function") throw new Error("Invalid Durable Object namespace");
107
- const id = Reflect.apply(idFromName, namespace, [durableObjectRoomName(path, room)]);
108
- const stub = Reflect.apply(get, namespace, [id]);
109
- if (typeof stub !== "object" || stub === null) throw new Error("Invalid Durable Object stub");
110
- const fetch = Reflect.get(stub, "fetch");
111
- if (typeof fetch !== "function") throw new Error("Durable Object stub has no fetch operation");
112
- const response = await Reflect.apply(fetch, stub, [request]);
113
- if (!(response instanceof Response)) throw new Error("Durable Object returned an invalid response");
114
- return response;
115
- }
116
- //#endregion
117
- //#region src/cloudflare-application.ts
118
- registerEntrypointKind({
119
- kind: "cf:vela-cron",
120
- metaKey: CRON_METADATA,
121
- level: "method"
122
- });
123
- function invoke(instance, methodName, args) {
124
- const method = Reflect.get(instance, methodName);
125
- if (typeof method !== "function") throw new Error(`Method '${String(methodName)}' is not a function on ${instance.constructor.name}`);
126
- return Reflect.apply(method, instance, args);
127
- }
128
- function entrypointString(meta, property) {
129
- if (typeof meta !== "object" || meta === null) throw new Error("Invalid entrypoint metadata.");
130
- const value = Reflect.get(meta, property);
131
- if (typeof value !== "string") throw new Error(`Invalid entrypoint metadata: ${property} must be a string.`);
132
- return value;
133
- }
134
- /** Wait for every matching handler, even when one fails before its siblings. */
135
- async function settleEntrypoints(work) {
136
- const errors = (await Promise.allSettled(work)).flatMap((outcome) => outcome.status === "rejected" ? [outcome.reason] : []);
137
- if (errors.length === 1) throw errors[0];
138
- if (errors.length > 1) throw new AggregateError(errors, "Multiple entrypoint handlers failed.");
139
- }
140
- /**
141
- * Wraps VelaApplication with Cloudflare-specific handlers:
142
- * - `fetch` — HTTP request handler (from Hono)
143
- * - `scheduled` — Cron trigger handler (matches `@Scheduled()` decorators
144
- * AND vela's own `@Cron()` jobs)
145
- * - `queue` — Queue consumer handler (matches `@QueueConsumer()` decorators)
146
- * - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on
147
- * the underlying Hono app
148
- *
149
- * @example
150
- * ```ts
151
- * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
152
- * export default {
153
- * fetch: app.fetch,
154
- * scheduled: app.scheduled.bind(app),
155
- * queue: app.queue.bind(app),
156
- * };
157
- * ```
158
- *
159
- * @example
160
- * ```ts
161
- * // Serve OpenAPI docs alongside your routes
162
- * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
163
- * const document = createOpenApiDocument(AppModule);
164
- * app.mountOpenApi({ document, ui: 'scalar' });
165
- * // GET /openapi.json -> JSON document
166
- * // GET /scalar -> Scalar UI (loads from CDN)
167
- * ```
168
- */
169
- var CloudflareApplication = class {
170
- env;
171
- #wsGatewayRoutes = [];
172
- #app;
173
- constructor(app, env) {
174
- this.env = env;
175
- this.#app = app;
176
- this.get = app.get.bind(app);
177
- }
178
- fetch = async (request, env, ctx) => {
179
- assertCloudflareEnvironment(this.env, env);
180
- return this.#app.fetch(request, env, ctx);
181
- };
182
- getHonoApp() {
183
- return this.#app.getHonoApp();
184
- }
185
- /**
186
- * Resolve a provider from the application's DI container (delegates to
187
- * `VelaApplication.get`). Handy for grabbing a service — e.g. an auth service —
188
- * to use inside `createCloudflareApp({ middleware: env => [...] })` request middleware,
189
- * which runs outside the DI request pipeline.
190
- *
191
- * @example
192
- * ```ts
193
- * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
194
- * const auth = app.get(BetterAuthService);
195
- * ```
196
- */
197
- get;
198
- get entrypoints() {
199
- return this.#app.entrypoints;
200
- }
201
- /**
202
- * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the
203
- * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,
204
- * so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when
205
- * opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from
206
- * a CDN at runtime, nothing is bundled server-side.
207
- *
208
- * @example
209
- * ```ts
210
- * import { createOpenApiDocument } from '@velajs/vela';
211
- *
212
- * const app = await createCloudflareApp(AppModule, { env, envToken: ENV });
213
- * const document = createOpenApiDocument(AppModule, {
214
- * info: { title: 'My API', version: '1.0.0' },
215
- * });
216
- * app.mountOpenApi({ document, ui: 'scalar' });
217
- * // GET /openapi.json -> { openapi: '3.1.0', ... }
218
- * // GET /scalar -> Scalar UI HTML
219
- * ```
220
- */
221
- mountOpenApi(options) {
222
- this.#app.mountOpenApi(options);
223
- return this;
224
- }
225
- /**
226
- * @internal Upgrade routes come from validated gateway entrypoints, including
227
- * request-scoped gateways without a bootstrap instance. Retain the instance
228
- * scan for legacy applications that only declare forwarding metadata.
229
- */
230
- scanInstances(instances) {
231
- const routes = /* @__PURE__ */ new Map();
232
- for (const ep of this.#app.entrypoints.ofKind("websocket")) {
233
- if (typeof ep.meta !== "object" || ep.meta === null || !("dispatcher" in ep.meta)) continue;
234
- const meta = readWsEntrypointMeta(ep.meta);
235
- if (meta.options.binding) routes.set(meta.path, {
236
- path: meta.path,
237
- binding: meta.options.binding,
238
- options: { ...meta.options }
239
- });
240
- }
241
- for (const instance of instances) {
242
- if (!instance || typeof instance !== "object") continue;
243
- for (const route of collectWsGatewayRoutes(instance)) if (!routes.has(route.path)) routes.set(route.path, route);
244
- }
245
- this.#wsGatewayRoutes.splice(0, this.#wsGatewayRoutes.length, ...routes.values());
246
- }
247
- /** @internal — upgrade routes discovered from the application's gateways. */
248
- getWsGatewayRoutes() {
249
- return [...this.#wsGatewayRoutes];
250
- }
251
- /**
252
- * Handle Cloudflare scheduled (cron) events.
253
- * Matches the event's cron expression to `@Scheduled()` and vela `@Cron()`
254
- * handlers read from `app.entrypoints`; each handler runs inside a fresh
255
- * request-scoped child (request-scoped providers rebuild per tick).
256
- */
257
- async scheduled(event, env, ctx) {
258
- assertCloudflareEnvironment(this.env, env);
259
- await settleEntrypoints([...this.#app.entrypoints.ofKind("cf:scheduled").map((ep) => ({
260
- ep,
261
- cron: entrypointString(ep.meta, "cron")
262
- })), ...this.#app.entrypoints.ofKind("cf:vela-cron").map((ep) => ({
263
- ep,
264
- cron: entrypointString(ep.meta, "expression")
265
- }))].filter((h) => h.cron === event.cron).map(({ ep }) => this.dispatchEntrypoint(ep, event, env, ctx)));
266
- }
267
- /**
268
- * Run one entrypoint handler inside a fresh request scope, through the
269
- * shared guard → interceptor pipeline (components declared with
270
- * `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or
271
- * method). HTTP-global components deliberately do NOT apply — an HTTP auth
272
- * guard has no business rejecting a queue batch. Unclaimed errors rethrow
273
- * so the platform's retry semantics stay intact.
274
- */
275
- async dispatchEntrypoint(ep, payload, env, platformContext) {
276
- const targetClass = ep.token;
277
- if (typeof targetClass !== "function") throw new Error("Entrypoint token must be a class.");
278
- if (ep.methodName === void 0) throw new Error("Entrypoint must declare a handler method.");
279
- const methodName = ep.methodName;
280
- const reportContext = {
281
- edge: ep.kind.startsWith("cf:queue") ? "queue" : "schedule",
282
- source: `${targetClass.name}.${String(methodName)}`
283
- };
284
- let reported;
285
- try {
286
- await runInEntrypointScope(this.#app.getContainer(), async (scope, lifetime) => {
287
- const moduleId = getEntrypointModuleId(scope, ep);
288
- const context = buildEntrypointExecutionContext(ep.kind, targetClass, methodName, payload, moduleId, scope);
289
- const invocationContext = { waitUntil(promise) {
290
- lifetime.waitUntil(promise);
291
- platformContext.waitUntil(promise);
292
- } };
293
- let filters = [];
294
- try {
295
- filters = (await resolveScopedComponentsAsync("filter", targetClass, methodName, scope, moduleId)).toReversed();
296
- const guards = await resolveScopedComponentsAsync("guard", targetClass, methodName, scope, moduleId);
297
- const interceptors = await resolveScopedComponentsAsync("interceptor", targetClass, methodName, scope, moduleId);
298
- await PipelineRunner.run({
299
- context,
300
- guards,
301
- interceptors,
302
- resolveArgs: async () => [
303
- payload,
304
- env,
305
- invocationContext
306
- ],
307
- invoke: async (args) => {
308
- const instance = await resolveEntrypoint(scope, ep);
309
- if (typeof instance !== "object" || instance === null) throw new Error("Entrypoint must resolve to an object.");
310
- return invoke(instance, methodName, args);
311
- }
312
- });
313
- } catch (error) {
314
- resolveErrorReporter(scope).report(error, reportContext);
315
- for (const filter of filters) if (shouldFilterCatch(filter, error)) {
316
- await filter.catch(error, context);
317
- return;
318
- }
319
- reported = { error };
320
- throw error;
321
- }
322
- });
323
- } catch (error) {
324
- if (!reported || reported.error !== error) {
325
- const completionError = reported && error instanceof AggregateError && error.errors[0] === reported.error ? error.errors[1] : error;
326
- resolveErrorReporter(this.#app.getContainer()).report(completionError, reportContext);
327
- }
328
- throw error;
329
- }
330
- }
331
- /**
332
- * Handle Cloudflare Queue consumer events.
333
- * Matches the batch queue name to `@QueueConsumer()` handlers read from
334
- * `app.entrypoints`; each batch is processed inside a fresh request-scoped
335
- * child (request-scoped providers rebuild per batch — no boot-time captives).
336
- */
337
- async queue(batch, env, ctx) {
338
- assertCloudflareEnvironment(this.env, env);
339
- const handlers = [...this.#app.entrypoints.ofKind("cf:queue"), ...this.#app.entrypoints.ofKind("cf:queue:module")].filter((ep) => entrypointString(ep.meta, "queueName") === batch.queue);
340
- if (handlers.length === 0) throw new Error(`No consumer for queue '${batch.queue}'.`);
341
- await settleEntrypoints(handlers.map((ep) => this.dispatchEntrypoint(ep, batch, env, ctx)));
342
- }
343
- async close(signal) {
344
- return this.#app.close(signal);
345
- }
346
- };
347
- //#endregion
348
- //#region src/cloudflare-factory.ts
349
- /** Bind an application to one environment before provider factories and lifecycle hooks. */
350
- function cloudflareAdapter(options) {
351
- return {
352
- name: "cloudflare",
353
- requestMiddleware: [async (context, next) => {
354
- assertCloudflareEnvironment(options.env, context.env);
355
- await next();
356
- }],
357
- invocationTransport: ({ app }) => (request) => Promise.resolve(app.fetch(request, options.env)),
358
- getClientIp: (c) => getConnInfo(c).remote.address ?? null,
359
- configureContainer: (container) => {
360
- registerCloudflareEnvironment(container, {
361
- token: options.envToken,
362
- env: options.env
363
- });
364
- }
365
- };
366
- }
367
- /** Build an application for one native Workers environment. Call inside a platform event. */
368
- async function createCloudflareApp(rootModule, options) {
369
- const velaApp = await VelaFactory.create(await resolveCloudflareRoot(rootModule, options.env), {
370
- globalPrefix: options.globalPrefix,
371
- security: options.security,
372
- middleware: options.middleware?.(options.env),
373
- adapters: [cloudflareAdapter(options)]
374
- });
375
- const app = new CloudflareApplication(velaApp, options.env);
376
- const consumers = /* @__PURE__ */ new Map();
377
- for (const entry of [...app.entrypoints.ofKind("cf:queue"), ...app.entrypoints.ofKind("cf:queue:module")]) {
378
- const meta = entry.meta;
379
- if (typeof meta !== "object" || meta === null || !("queueName" in meta) || typeof meta.queueName !== "string") {
380
- await app.close();
381
- throw new TypeError("Invalid queue consumer metadata.");
382
- }
383
- const previous = consumers.get(meta.queueName);
384
- if (previous && (previous === "cf:queue:module" || entry.kind === "cf:queue:module")) {
385
- await app.close();
386
- throw new Error(`Ambiguous consumer ownership for queue '${meta.queueName}'.`);
387
- }
388
- consumers.set(meta.queueName, entry.kind);
389
- }
390
- app.scanInstances(velaApp.getInstances());
391
- registerWebSocketRoutes(app.getHonoApp(), app.getWsGatewayRoutes());
392
- return app;
393
- }
394
- /**
395
- * Worker entrypoint with one bootstrap per environment identity. Weak keys let
396
- * obsolete environments and secrets be collected. Concurrent cold events share
397
- * construction; failed construction is evicted so the next event can retry.
398
- */
399
- function createCloudflareWorker(rootModule, options) {
400
- const applications = /* @__PURE__ */ new WeakMap();
401
- const application = (env) => {
402
- const existing = applications.get(env);
403
- if (existing) return existing;
404
- const pending = createCloudflareApp(rootModule, {
405
- ...options,
406
- env
407
- });
408
- applications.set(env, pending);
409
- pending.catch(() => {
410
- if (applications.get(env) === pending) applications.delete(env);
411
- });
412
- return pending;
413
- };
414
- return {
415
- async fetch(request, env, ctx) {
416
- return (await application(env)).fetch(request, env, ctx);
417
- },
418
- async scheduled(event, env, ctx) {
419
- return (await application(env)).scheduled(event, env, ctx);
420
- },
421
- async queue(batch, env, ctx) {
422
- return (await application(env)).queue(batch, env, ctx);
423
- }
424
- };
425
- }
426
- //#endregion
427
- //#region src/storage/storage.tokens.ts
428
- const STORAGE_OPTIONS = new InjectionToken("STORAGE_OPTIONS");
429
- //#endregion
430
- //#region src/storage/storage-key-claim.ts
431
- /** R2-compatible object-key claim bound. Keeps decode work predictably small. */
432
- const MAX_STORAGE_KEY_BYTES = 1024;
433
- const BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
434
- const ROOT_TOKEN_PATTERNS = {
435
- date: "\\d{4}-\\d{2}-\\d{2}",
436
- year: "\\d{4}",
437
- month: "(?:0[1-9]|1[0-2])",
438
- day: "(?:0[1-9]|[12]\\d|3[01])",
439
- uuid: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}"
440
- };
441
- /** Encode an object key as an opaque, canonical base64url query claim. */
442
- function encodeStorageKeyClaim(key) {
443
- const bytes = new TextEncoder().encode(key);
444
- if (bytes.byteLength === 0 || bytes.byteLength > 1024) throw new Error(`Storage key must be 1–${MAX_STORAGE_KEY_BYTES} UTF-8 bytes`);
445
- let binary = "";
446
- for (const byte of bytes) binary += String.fromCharCode(byte);
447
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
448
- }
449
- /** Decode exactly one canonical base64url layer. Malformed/non-UTF-8 claims return undefined. */
450
- function decodeStorageKeyClaim(claim) {
451
- try {
452
- if (claim.length === 0 || claim.length > Math.ceil(4096 / 3) || !BASE64URL_RE.test(claim) || claim.length % 4 === 1) return;
453
- const base64 = claim.replace(/-/g, "+").replace(/_/g, "/");
454
- const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
455
- const binary = atob(padded);
456
- const bytes = new Uint8Array(new ArrayBuffer(binary.length));
457
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
458
- if (bytes.byteLength === 0 || bytes.byteLength > 1024) return void 0;
459
- const decoded = new TextDecoder("utf-8", {
460
- fatal: true,
461
- ignoreBOM: false
462
- }).decode(bytes);
463
- return encodeStorageKeyClaim(decoded) === claim ? decoded : void 0;
464
- } catch {
465
- return;
466
- }
467
- }
468
- function isDotSegment(segment) {
469
- let decoded = segment;
470
- for (let i = 0; i < 2; i++) {
471
- if (decoded === "" || decoded === "." || decoded === "..") return true;
472
- try {
473
- const next = decodeURIComponent(decoded);
474
- if (next === decoded) break;
475
- decoded = next;
476
- } catch {
477
- break;
478
- }
479
- }
480
- return decoded === "" || decoded === "." || decoded === "..";
481
- }
482
- function rootSegmentPattern(segment) {
483
- let pattern = "";
484
- let cursor = 0;
485
- for (const match of segment.matchAll(/\{(date|year|month|day|uuid)\}/g)) {
486
- pattern += segment.slice(cursor, match.index).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
487
- pattern += ROOT_TOKEN_PATTERNS[match[1]];
488
- cursor = match.index + match[0].length;
489
- }
490
- pattern += segment.slice(cursor).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
491
- return pattern;
492
- }
493
- /** Assert a canonical key is beneath a static or templated configured root. */
494
- function isStorageKeyWithinRoot(key, root) {
495
- const segments = (root ?? "").split(/[/\\]+/).filter((segment) => !isDotSegment(segment));
496
- if (segments.length === 0) return key.length > 0;
497
- const rootPattern = segments.map(rootSegmentPattern).join("/");
498
- return new RegExp(`^(?:${rootPattern})(?:/|$)`).test(key);
499
- }
500
- //#endregion
501
- //#region src/storage/r2-storage.driver.ts
502
- /** Base path of the StorageController presign-proxy route. */
503
- const STORAGE_ROUTE_BASE = "/storage";
504
- /** {@link StorageDriver} over a Cloudflare R2 bucket. */
505
- var R2StorageDriver = class {
506
- config;
507
- constructor(config) {
508
- this.config = config;
509
- }
510
- async upload(body, path, options) {
511
- await this.config.bucket.put(path, body, {
512
- httpMetadata: options.mimeType ? { contentType: options.mimeType } : void 0,
513
- customMetadata: options.metadata
514
- });
515
- return {
516
- path,
517
- disk: this.config.disk,
518
- size: options.size,
519
- mimeType: options.mimeType ?? "application/octet-stream",
520
- uploadedAt: /* @__PURE__ */ new Date()
521
- };
522
- }
523
- async download(path) {
524
- const obj = await this.config.bucket.get(path);
525
- if (!obj) throw new Error(`Storage object not found at "${path}".`);
526
- return {
527
- toStream: () => obj.body,
528
- toArrayBuffer: () => obj.arrayBuffer(),
529
- toText: () => obj.text(),
530
- contentType: obj.httpMetadata?.contentType ?? "application/octet-stream",
531
- size: obj.size,
532
- metadata: obj.customMetadata
533
- };
534
- }
535
- async delete(path) {
536
- await this.config.bucket.delete(path);
537
- }
538
- async exists(path) {
539
- return await this.config.bucket.head(path) !== null;
540
- }
541
- async getPresignedUrl(path, method, expiresIn) {
542
- if (!this.config.secret) throw new Error("A signing secret is required for presigned URLs (set APP_SECRET).");
543
- if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0) throw new Error(`Invalid presigned URL expiry: ${expiresIn}s (must be a positive safe integer).`);
544
- const claim = encodeStorageKeyClaim(path);
545
- const routePath = `${STORAGE_ROUTE_BASE}/${encodeURIComponent(this.config.disk)}`;
546
- const query = new URLSearchParams({
547
- key: claim,
548
- method
549
- });
550
- return {
551
- url: await signUrl(`${routePath}?${query}`, this.config.secret, {
552
- expiresIn,
553
- method,
554
- purpose: STORAGE_SIGNED_URL_PURPOSE
555
- }),
556
- method,
557
- expiresIn,
558
- expiresAt: new Date(Date.now() + expiresIn * 1e3)
559
- };
560
- }
561
- };
562
- //#endregion
563
- //#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorateMetadata.js
564
- function __decorateMetadata(k, v) {
565
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
566
- }
567
- //#endregion
568
- //#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorateParam.js
569
- function __decorateParam(paramIndex, decorator) {
570
- return function(target, key) {
571
- decorator(target, key, paramIndex);
572
- };
573
- }
574
- //#endregion
575
- //#region src/storage/storage-manager.service.ts
576
- let StorageManagerService = class StorageManagerService {
577
- options;
578
- constructor(options) {
579
- this.options = options;
580
- }
581
- hasDisk(disk) {
582
- return this.options.disks.some((d) => d.disk === disk);
583
- }
584
- getDiskConfig(disk) {
585
- const config = this.options.disks.find((d) => d.disk === disk);
586
- if (!config) throw new Error(`Storage disk "${disk}" is not configured.`);
587
- return config;
588
- }
589
- getDriver(disk) {
590
- return new R2StorageDriver({
591
- disk,
592
- bucket: this.getDiskConfig(disk).bucket,
593
- secret: this.options.secret
594
- });
595
- }
596
- };
597
- StorageManagerService = __decorate([
598
- Injectable(),
599
- __decorateParam(0, Inject(STORAGE_OPTIONS)),
600
- __decorateMetadata("design:paramtypes", [Object])
601
- ], StorageManagerService);
602
- //#endregion
603
- //#region src/storage/storage.controller.ts
604
- let StorageController = class StorageController {
605
- manager;
606
- options;
607
- constructor(manager, options) {
608
- this.manager = manager;
609
- this.options = options;
610
- }
611
- async download(c) {
612
- const secret = this.options.secret;
613
- if (!secret) return new Response("Storage signing is not configured", { status: 500 });
614
- if (!await verifySignedUrl(c.req.url, secret, {
615
- method: c.req.method,
616
- purpose: STORAGE_SIGNED_URL_PURPOSE
617
- })) return new Response("Invalid or expired URL", { status: 403 });
618
- const url = new URL(c.req.url);
619
- if (url.searchParams.get("method") !== "GET") return new Response("URL is not scoped for reads", { status: 403 });
620
- const disk = c.req.param("disk");
621
- if (!disk || !this.manager.hasDisk(disk)) return new Response("Unknown disk", { status: 404 });
622
- const claim = url.searchParams.get("key");
623
- const decoded = claim ? decodeStorageKeyClaim(claim) : void 0;
624
- if (!decoded) return new Response("Malformed storage key claim", { status: 400 });
625
- const fullPath = joinStoragePath(void 0, decoded);
626
- if (fullPath !== decoded) return new Response("Invalid storage key", { status: 403 });
627
- if (!isStorageKeyWithinRoot(fullPath, this.manager.getDiskConfig(disk).root)) return new Response("Storage key is outside the configured root", { status: 403 });
628
- try {
629
- const result = await this.manager.getDriver(disk).download(fullPath);
630
- const filename = fullPath.split("/").at(-1) || "download";
631
- return new Response(result.toStream(), { headers: {
632
- "content-type": result.contentType || "application/octet-stream",
633
- "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,
634
- "x-content-type-options": "nosniff"
635
- } });
636
- } catch {
637
- return new Response("Not found", { status: 404 });
638
- }
639
- }
640
- };
641
- __decorate([
642
- Get("/:disk"),
643
- __decorateParam(0, Req()),
644
- __decorateMetadata("design:type", Function),
645
- __decorateMetadata("design:paramtypes", [Object]),
646
- __decorateMetadata("design:returntype", Promise)
647
- ], StorageController.prototype, "download", null);
648
- StorageController = __decorate([
649
- Controller("storage"),
650
- __decorateParam(0, Inject(StorageManagerService)),
651
- __decorateParam(1, Inject(STORAGE_OPTIONS)),
652
- __decorateMetadata("design:paramtypes", [typeof StorageManagerService === "undefined" ? Object : StorageManagerService, Object])
653
- ], StorageController);
654
- //#endregion
655
- //#region src/storage/storage.service.ts
656
- const DEFAULT_PRESIGN = {
657
- defaultExpiry: 3600,
658
- maxExpiry: 86400
659
- };
660
- let StorageService = class StorageService {
661
- options;
662
- manager;
663
- constructor(options, manager) {
664
- this.options = options;
665
- this.manager = manager;
666
- }
667
- put(relativePath, body, options = {}, disk) {
668
- const name = this.resolveDisk(disk);
669
- return this.manager.getDriver(name).upload(body, this.fullPath(relativePath, name), options);
670
- }
671
- get(relativePath, disk) {
672
- const name = this.resolveDisk(disk);
673
- return this.manager.getDriver(name).download(this.fullPath(relativePath, name));
674
- }
675
- delete(relativePath, disk) {
676
- const name = this.resolveDisk(disk);
677
- return this.manager.getDriver(name).delete(this.fullPath(relativePath, name));
678
- }
679
- exists(relativePath, disk) {
680
- const name = this.resolveDisk(disk);
681
- return this.manager.getDriver(name).exists(this.fullPath(relativePath, name));
682
- }
683
- url(relativePath, method = "GET", expiresIn, disk) {
684
- const name = this.resolveDisk(disk);
685
- return this.manager.getDriver(name).getPresignedUrl(this.fullPath(relativePath, name), method, this.validateExpiry(expiresIn));
686
- }
687
- resolveDisk(disk) {
688
- const name = disk ?? this.options.defaultDisk;
689
- if (!this.manager.hasDisk(name)) throw new Error(`Storage disk "${name}" is not configured.`);
690
- return name;
691
- }
692
- fullPath(relativePath, disk) {
693
- return joinStoragePath(this.manager.getDiskConfig(disk).root, relativePath);
694
- }
695
- validateExpiry(expiresIn) {
696
- const cfg = this.options.presignedUrl ?? DEFAULT_PRESIGN;
697
- const value = expiresIn ?? cfg.defaultExpiry;
698
- if (!Number.isSafeInteger(value) || value < 1 || value > cfg.maxExpiry) throw new Error(`Presigned URL expiry ${value}s is out of range (1–${cfg.maxExpiry}s).`);
699
- return value;
700
- }
701
- };
702
- StorageService = __decorate([
703
- Injectable(),
704
- __decorateParam(0, Inject(STORAGE_OPTIONS)),
705
- __decorateParam(1, Inject(StorageManagerService)),
706
- __decorateMetadata("design:paramtypes", [Object, typeof StorageManagerService === "undefined" ? Object : StorageManagerService])
707
- ], StorageService);
708
- //#endregion
709
- //#region src/storage/storage.module.ts
710
- const { ConfigurableModuleClass } = new ConfigurableModuleBuilder({
711
- moduleName: "Storage",
712
- optionsInjectionToken: STORAGE_OPTIONS
713
- }).build();
714
- let StorageModule = class StorageModule extends ConfigurableModuleClass {};
715
- StorageModule = __decorate([Module({
716
- providers: [StorageManagerService, StorageService],
717
- controllers: [StorageController],
718
- exports: [
719
- StorageService,
720
- StorageManagerService,
721
- STORAGE_OPTIONS
722
- ]
723
- })], StorageModule);
724
- //#endregion
725
- //#region src/services/kv-cache.store.ts
726
- /**
727
- * Native KV JSON value store. Metadata retains logical expiry even when KV's
728
- * physical retention rounds up to its 60-second minimum. Legacy values without
729
- * metadata remain readable, but cannot safely backfill another tier.
730
- */
731
- var KVCacheStore = class {
732
- ns;
733
- constructor(ns) {
734
- this.ns = ns;
735
- }
736
- async get(key) {
737
- return (await this.getEntry(key))?.value;
738
- }
739
- async getEntry(key) {
740
- const { value, metadata } = await this.ns.getWithMetadata(key, "json");
741
- if (value === null) return void 0;
742
- if (typeof metadata === "object" && metadata !== null && "velaCacheExpiresAt" in metadata) {
743
- const expiresAt = metadata.velaCacheExpiresAt;
744
- if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) return void 0;
745
- return {
746
- value,
747
- expiresAt
748
- };
749
- }
750
- return { value };
751
- }
752
- async set(key, value, ttl) {
753
- if (ttl !== void 0 && (!Number.isFinite(ttl) || ttl < 0)) throw new TypeError("Cache TTL must be finite and nonnegative.");
754
- if (ttl !== void 0) return this.setEntry(key, {
755
- value,
756
- expiresAt: Date.now() + ttl * 1e3
757
- });
758
- await this.ns.put(key, JSON.stringify(value));
759
- }
760
- async setEntry(key, entry) {
761
- if (!Number.isFinite(entry.expiresAt)) throw new TypeError("Cache expiry must be finite.");
762
- const remaining = (entry.expiresAt - Date.now()) / 1e3;
763
- if (remaining <= 0) return this.del(key);
764
- await this.ns.put(key, JSON.stringify(entry.value), {
765
- expirationTtl: Math.max(60, Math.ceil(remaining)),
766
- metadata: { velaCacheExpiresAt: entry.expiresAt }
767
- });
768
- }
769
- async del(key) {
770
- await this.ns.delete(key);
771
- }
772
- /** Namespace-wide, best effort. Use a dedicated value namespace; never use for scoped invalidation. */
773
- async clear() {
774
- let cursor;
775
- do {
776
- const list = await this.ns.list(cursor ? { cursor } : void 0);
777
- await Promise.all(list.keys.map((entry) => this.ns.delete(entry.name)));
778
- cursor = list.list_complete ? void 0 : list.cursor;
779
- } while (cursor);
780
- }
781
- };
782
- /**
783
- * Optional, eventually consistent generation store. Use a dedicated KV namespace
784
- * without TTL/lifecycle cleanup. Never delete/reset generations while entries can
785
- * survive. Concurrent writes and cached/negative reads prevent strong invalidation;
786
- * this is unsuitable for strict read-after-write or authorization revocation.
787
- */
788
- var KVCacheInvalidationStore = class {
789
- ns;
790
- constructor(ns) {
791
- this.ns = ns;
792
- }
793
- async getVersion(key) {
794
- const value = await this.ns.get(key, "json");
795
- if (value === null) return "initial";
796
- if (typeof value !== "string" || value.length === 0 || value.length > 2048) throw new TypeError("Invalid cache generation.");
797
- return value;
798
- }
799
- async invalidate(key) {
800
- await this.ns.put(key, JSON.stringify(crypto.randomUUID()));
801
- }
802
- };
803
- //#endregion
804
- //#region src/services/flagship-flag.driver.ts
805
- /**
806
- * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.
807
- *
808
- * A thin, honest wrapper: each contract method maps 1:1 onto the binding's
809
- * corresponding value method, forwarding the caller's `fallback` (the binding's
810
- * `defaultValue`) and evaluation context. The binding resolves the fallback on
811
- * evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`
812
- * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns
813
- * the never-throw guarantee.
814
- *
815
- * Build the driver inside a provider factory with the native environment:
816
- *
817
- * ```ts
818
- * FeatureFlagsModule.forRootAsync({
819
- * inject: [ENV],
820
- * useFactory: (env: WorkerEnv) => ({ drivers: [flagshipFlagDriver(env.FLAGS)] }),
821
- * });
822
- * ```
823
- *
824
- * Evaluation ergonomics (the 1:1 binding-method mapping) are ported from the
825
- * Stratal feature-flags service (MIT, © Temitayo Fadojutimi), reshaped as a
826
- * bare driver.
827
- */
828
- var FlagshipFlagDriver = class {
829
- name;
830
- resolve;
831
- constructor(binding, options = {}) {
832
- this.resolve = typeof binding === "function" ? binding : () => binding;
833
- this.name = options.name ?? "flagship";
834
- }
835
- getBoolean(key, fallback, ctx) {
836
- return this.resolve().getBooleanValue(key, fallback, ctx);
837
- }
838
- getString(key, fallback, ctx) {
839
- return this.resolve().getStringValue(key, fallback, ctx);
840
- }
841
- getNumber(key, fallback, ctx) {
842
- return this.resolve().getNumberValue(key, fallback, ctx);
843
- }
844
- getObject(key, fallback, ctx) {
845
- return this.resolve().getObjectValue(key, fallback, ctx);
846
- }
847
- };
848
- /** Convenience factory for {@link FlagshipFlagDriver}. */
849
- function flagshipFlagDriver(binding, options) {
850
- return new FlagshipFlagDriver(binding, options);
851
- }
852
- //#endregion
853
- //#region src/services/kv-flag.driver.ts
854
- /**
855
- * Cloudflare KV-backed {@link FeatureFlagDriver}. Flags are stored as JSON
856
- * values under an optional key prefix and read with `get(key, 'json')`. Reads
857
- * are type-checked against the requested type: a missing key or a value of the
858
- * wrong JSON type returns the caller's `fallback`. KV has no targeting, so the
859
- * evaluation context is ignored.
860
- *
861
- * The driver stays honest — it does **not** swallow errors. A KV failure (or a
862
- * `SyntaxError` from a malformed stored value) propagates; the never-throw
863
- * guarantee lives in `@velajs/feature-flags`'s service layer.
864
- *
865
- * Placed like {@link KVCacheStore}: construct it in a wiring factory over a
866
- * resolved {@link KVNamespace}.
867
- *
868
- * ```ts
869
- * FeatureFlagsModule.forRootAsync({
870
- * inject: [ENV],
871
- * useFactory: (env: WorkerEnv) => ({ drivers: [new KvFlagDriver(env.CACHE, { prefix: 'flag:' })] }),
872
- * });
873
- * ```
874
- */
875
- var KvFlagDriver = class {
876
- ns;
877
- name;
878
- prefix;
879
- constructor(ns, options = {}) {
880
- this.ns = ns;
881
- this.name = options.name ?? "kv";
882
- this.prefix = options.prefix ?? "";
883
- }
884
- getBoolean(key, fallback, _ctx) {
885
- return this.read(key, fallback, (v) => typeof v === "boolean");
886
- }
887
- getString(key, fallback, _ctx) {
888
- return this.read(key, fallback, (v) => typeof v === "string");
889
- }
890
- getNumber(key, fallback, _ctx) {
891
- return this.read(key, fallback, (v) => typeof v === "number");
892
- }
893
- getObject(key, fallback, _ctx) {
894
- return this.read(key, fallback, (v) => typeof v === "object" && v !== null);
895
- }
896
- /**
897
- * Reads and JSON-parses the (prefixed) key, returning the parsed value only
898
- * when `matches` accepts its type; otherwise the caller's fallback. A missing
899
- * key reads as `null` → fallback. Read/parse errors are left to propagate.
900
- */
901
- async read(key, fallback, matches) {
902
- const value = await this.ns.get(this.prefix + key, "json");
903
- if (value === null || value === void 0) return fallback;
904
- return matches(value) ? value : fallback;
905
- }
906
- };
907
- /** Convenience factory for {@link KvFlagDriver}. */
908
- function kvFlagDriver(kv, options) {
909
- return new KvFlagDriver(kv, options);
910
- }
911
- //#endregion
912
- //#region src/decorators/env.ts
913
- /**
914
- * Parameter decorator to inject Cloudflare environment bindings.
915
- *
916
- * Without arguments, returns the entire `env` object.
917
- * With a binding name, returns that specific binding.
918
- *
919
- * @example
920
- * ```ts
921
- * @Get()
922
- * handle(@Env() env: WorkerEnv) { ... }
923
- *
924
- * @Get()
925
- * handle(@Env('MY_KV') kv: KVNamespace) { ... }
926
- * ```
927
- */
928
- const Env = createParamDecorator((bindingName, ctx) => {
929
- const env = ctx.getContext().env;
930
- if (typeof env !== "object" || env === null) return void 0;
931
- return bindingName ? Reflect.get(env, bindingName) : env;
932
- });
933
- //#endregion
934
- //#region src/decorators/scheduled.ts
935
- const SCHEDULED_METADATA_KEY = "cloudflare:scheduled";
936
- registerEntrypointKind({
937
- kind: "cf:scheduled",
938
- metaKey: SCHEDULED_METADATA_KEY,
939
- level: "method"
940
- });
941
- function parseScheduledMetadata(value) {
942
- if (typeof value !== "object" || value === null || !("cron" in value) || typeof value.cron !== "string" || !("methodName" in value) || typeof value.methodName !== "string" || !parseCron(value.cron, { dialect: "cloudflare" })) throw new TypeError("Invalid Cloudflare scheduled metadata");
943
- return {
944
- cron: value.cron,
945
- methodName: value.methodName
946
- };
947
- }
948
- /**
949
- * Marks a method as a scheduled (cron) handler.
950
- *
951
- * @example
952
- * ```ts
953
- * @Injectable()
954
- * class WorkerService {
955
- * @Scheduled('0 * * * *')
956
- * async hourlyCron() {
957
- * console.log('Running hourly');
958
- * }
959
- * }
960
- * ```
961
- */
962
- function Scheduled(cron) {
963
- if (!parseCron(cron, { dialect: "cloudflare" })) throw new TypeError(`Invalid Cloudflare cron expression: ${cron}`);
964
- return (target, propertyKey, _descriptor) => {
965
- const existing = getScheduledMetadata(target);
966
- existing.push({
967
- cron,
968
- methodName: String(propertyKey)
969
- });
970
- defineMetadata(SCHEDULED_METADATA_KEY, existing, target.constructor);
971
- };
972
- }
973
- function getScheduledMetadata(target) {
974
- const ctor = typeof target === "function" ? target : target.constructor;
975
- const value = getMetadata(SCHEDULED_METADATA_KEY, ctor);
976
- if (value === void 0) return [];
977
- if (!Array.isArray(value)) throw new TypeError("Invalid Cloudflare scheduled metadata list");
978
- return value.map(parseScheduledMetadata);
979
- }
980
- //#endregion
981
- //#region src/decorators/queue-consumer.ts
982
- const QUEUE_CONSUMER_METADATA_KEY = "cloudflare:queue-consumer";
983
- registerEntrypointKind({
984
- kind: "cf:queue",
985
- metaKey: QUEUE_CONSUMER_METADATA_KEY,
986
- level: "method"
987
- });
988
- /**
989
- * Marks a method as a queue consumer handler.
990
- *
991
- * @example
992
- * ```ts
993
- * @Injectable()
994
- * class WorkerService {
995
- * @QueueConsumer('email-queue')
996
- * async processEmails(batch: MessageBatch) {
997
- * for (const msg of batch.messages) {
998
- * console.log('Processing:', msg.body);
999
- * msg.ack();
1000
- * }
1001
- * }
1002
- * }
1003
- * ```
1004
- */
1005
- function QueueConsumer(queueName) {
1006
- return (target, propertyKey, _descriptor) => {
1007
- const existing = getMetadata(QUEUE_CONSUMER_METADATA_KEY, target.constructor) ?? [];
1008
- existing.push({
1009
- queueName,
1010
- methodName: String(propertyKey)
1011
- });
1012
- defineMetadata(QUEUE_CONSUMER_METADATA_KEY, existing, target.constructor);
1013
- };
1014
- }
1015
- //#endregion
1016
- //#region src/websocket/cloudflare-websocket.module.ts
1017
- /**
1018
- * Cloudflare counterpart to the core `WebSocketModule.forRoot()`. Import this in
1019
- * your `AppModule` instead: it provides the gateway dispatcher plus a late-bound
1020
- * `WS_SERVER` (`WsServerHolder`) that the WebSocket Durable Object wires to a
1021
- * ctx-backed server per instance. `useClass` ensures a fresh holder per DI
1022
- * container so colocated DO instances never share a server.
1023
- */
1024
- var CloudflareWebSocketModule = class CloudflareWebSocketModule {
1025
- static forRoot() {
1026
- const providers = [defineProvider(WS_SERVER, { useClass: WsServerHolder }), WsDispatcher];
1027
- return {
1028
- module: CloudflareWebSocketModule,
1029
- providers,
1030
- exports: [WS_SERVER, WsDispatcher]
1031
- };
1032
- }
1033
- };
1034
- //#endregion
1035
- //#region src/websocket/broadcast.ts
1036
- /**
1037
- * Push to a room from a Worker HTTP handler / cron / queue consumer (server-
1038
- * initiated emit). Resolves the room's Durable Object and calls its `broadcast`
1039
- * RPC method — the same canonical room→DO mapping the upgrade route uses, so it
1040
- * always reaches the DO holding those sockets.
1041
- *
1042
- * @example
1043
- * ```ts
1044
- * // In a controller — ns from the typed Worker environment
1045
- * await broadcastToRoom(ns, '/orgs/:orgId/ws', `org:${id}`, 'order.created', order);
1046
- * ```
1047
- */
1048
- async function broadcastToRoom(ns, gatewayPath, room, event, data, options) {
1049
- const cmd = {
1050
- rooms: [room],
1051
- exceptIds: options?.exceptIds,
1052
- frame: JSON.stringify({
1053
- event,
1054
- data
1055
- })
1056
- };
1057
- const maxFrameBytes = resolveMaxFrameBytes({ maxFrameBytes: options?.maxFrameBytes ?? DEFAULT_WS_MAX_FRAME_BYTES });
1058
- assertBroadcastCommandFits(cmd, maxFrameBytes);
1059
- await ns.get(roomToDurableId(ns, gatewayPath, room)).broadcast(cmd);
1060
- }
1061
- //#endregion
1062
- //#region src/rate-limit/cloudflare-rate-limit.store.ts
1063
- /**
1064
- * Adapt a Cloudflare Workers Rate Limiting binding to Vela's throttler store.
1065
- *
1066
- * The platform binding makes the allow/deny decision. It does not expose exact
1067
- * counters or reset timestamps, so this adapter intentionally omits `remaining`.
1068
- */
1069
- function cloudflareRateLimitStore(binding, options) {
1070
- if (!binding || typeof binding !== "function" && typeof binding.limit !== "function") throw new TypeError("A Cloudflare Rate Limiting binding is required");
1071
- if (!Number.isSafeInteger(options.limit) || options.limit <= 0 || options.limit >= Number.MAX_SAFE_INTEGER) throw new RangeError("Rate limit must be a positive safe integer");
1072
- if (options.periodSeconds !== 10 && options.periodSeconds !== 60) throw new RangeError("Cloudflare rate-limit periods must be 10 or 60 seconds");
1073
- const maxKeyBytes = options.maxKeyBytes ?? 1024;
1074
- if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes <= 0 || maxKeyBytes > 4096) throw new RangeError("maxKeyBytes must be between 1 and 4096");
1075
- const ttlMs = options.periodSeconds * 1e3;
1076
- const encoder = new TextEncoder();
1077
- const resolveBinding = typeof binding === "function" ? binding : () => binding;
1078
- return {
1079
- async increment(key, requestedTtlMs) {
1080
- if (requestedTtlMs !== ttlMs) throw new Error(`Cloudflare binding period mismatch: expected ${ttlMs}ms, received ${requestedTtlMs}ms`);
1081
- if (typeof key !== "string" || key.length === 0 || /[\u0000-\u001f\u007f]/.test(key) || encoder.encode(key).byteLength > maxKeyBytes) throw new Error("Refusing an invalid or oversized rate-limit key");
1082
- const currentBinding = resolveBinding();
1083
- if (!currentBinding || typeof currentBinding.limit !== "function") throw new Error("Cloudflare Rate Limiting binding is unavailable");
1084
- const decision = await currentBinding.limit({ key });
1085
- if (!decision || typeof decision.success !== "boolean") throw new Error("Cloudflare rate-limit binding returned an invalid decision");
1086
- return {
1087
- count: decision.success ? 0 : options.limit + 1,
1088
- ttlMs,
1089
- allowed: decision.success,
1090
- enforcedLimit: options.limit
1091
- };
1092
- },
1093
- reset() {
1094
- throw new Error("Cloudflare Rate Limiting bindings do not support counter reset");
1095
- }
1096
- };
1097
- }
1098
- //#endregion
1099
- //#region src/nonce/durable-object-nonce.store.ts
1100
- const APP_NAMESPACE_PREFIX = "vela:nonce:v1:";
1101
- const MAX_APP_NAMESPACE_BYTES = 128;
1102
- /**
1103
- * Strict, cross-isolate {@link NonceStore} backed by one SQLite Durable Object
1104
- * per explicit application namespace.
1105
- *
1106
- * Invalid input, an unavailable/malformed binding, RPC failure, or a malformed
1107
- * RPC result all deny the claim (`false`). Only the literal boolean `true` from
1108
- * the Durable Object is accepted.
1109
- */
1110
- function durableObjectNonceStore(options) {
1111
- if (!options || typeof options !== "object") throw new TypeError("Durable Object nonce-store options are required");
1112
- if (!isCanonicalBoundedText(options.appNamespace, MAX_APP_NAMESPACE_BYTES)) throw new TypeError(`appNamespace must be canonical, non-empty, and at most ${MAX_APP_NAMESPACE_BYTES} UTF-8 bytes`);
1113
- if (typeof options.binding !== "function") throw new TypeError("A lazy Durable Object namespace binding resolver is required");
1114
- const objectName = `${APP_NAMESPACE_PREFIX}${options.appNamespace}`;
1115
- return { async claim(nonce, expEpochSeconds) {
1116
- const now = Math.floor(Date.now() / 1e3);
1117
- if (!isCanonicalBoundedText(nonce, 512) || !isValidExpiry(expEpochSeconds, now)) return false;
1118
- try {
1119
- const namespace = await options.binding();
1120
- const id = namespace.idFromName(objectName);
1121
- return await namespace.get(id).claim(nonce, expEpochSeconds) === true;
1122
- } catch {
1123
- return false;
1124
- }
1125
- } };
1126
- }
1127
- //#endregion
1128
- export { CloudflareApplication, CloudflareWebSocketModule, ConnectedSocket, DoCursorLog, DoPitrUnavailableError, Env, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, MessageBody, QueueConsumer, R2StorageDriver, STORAGE_OPTIONS, Scheduled, StorageController, StorageManagerService, StorageModule, StorageService, SubscribeMessage, WebSocketGateway, WebSocketServer, WsException, armDoPitr, broadcastToRoom, cloudflareAdapter, cloudflareRateLimitStore, createCloudflareApp, createCloudflareWorker, durableObjectCursorLog, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagshipFlagDriver, isDoPitrUnavailable, kvFlagDriver, liveInvalidateToRoom, parseScheduledMetadata, readDoPitrBookmark };
1129
-
1130
- //# sourceMappingURL=index.js.map
1
+ import { durableObjectRoomName } from "./websocket/room-id.js";
2
+ import { CLOUDFLARE_SCHEDULED_EVENT } from "./scheduled-event.js";
3
+ import { CloudflareApplication } from "./cloudflare-application.js";
4
+ import { DoCursorLog, durableObjectCursorLog, durableObjectLive, liveInvalidateToRoom } from "./websocket/do-live.js";
5
+ import { cloudflareAdapter, createCloudflareApp, createCloudflareWorker } from "./cloudflare-factory.js";
6
+ import { STORAGE_OPTIONS } from "./storage/storage.tokens.js";
7
+ import { R2StorageDriver } from "./storage/r2-storage.driver.js";
8
+ import { StorageManagerService } from "./storage/storage-manager.service.js";
9
+ import { StorageController } from "./storage/storage.controller.js";
10
+ import { StorageService } from "./storage/storage.service.js";
11
+ import { StorageModule } from "./storage/storage.module.js";
12
+ import { KVCacheInvalidationStore, KVCacheStore } from "./services/kv-cache.store.js";
13
+ import { FlagshipFlagDriver, flagshipFlagDriver } from "./services/flagship-flag.driver.js";
14
+ import { KvFlagDriver, kvFlagDriver } from "./services/kv-flag.driver.js";
15
+ import { QueueConsumer } from "./decorators/queue-consumer.js";
16
+ import { DoPitrUnavailableError, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark } from "./websocket/do-pitr.js";
17
+ import { CloudflareWebSocketModule } from "./websocket/cloudflare-websocket.module.js";
18
+ import { broadcastToRoom } from "./websocket/broadcast.js";
19
+ import { cloudflareRateLimitStore } from "./rate-limit/cloudflare-rate-limit.store.js";
20
+ import { durableObjectNonceStore } from "./nonce/durable-object-nonce.store.js";
21
+ export { CLOUDFLARE_SCHEDULED_EVENT, CloudflareApplication, CloudflareWebSocketModule, DoCursorLog, DoPitrUnavailableError, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, QueueConsumer, R2StorageDriver, STORAGE_OPTIONS, StorageController, StorageManagerService, StorageModule, StorageService, armDoPitr, broadcastToRoom, cloudflareAdapter, cloudflareRateLimitStore, createCloudflareApp, createCloudflareWorker, durableObjectCursorLog, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagshipFlagDriver, isDoPitrUnavailable, kvFlagDriver, liveInvalidateToRoom, readDoPitrBookmark };