@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.
- package/CHANGELOG.md +112 -0
- package/README.md +260 -74
- package/dist/bindings.js +77 -0
- package/dist/bindings.js.map +1 -0
- package/dist/cloudflare-application.js +7 -34
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory-eGiet0mg.d.ts +288 -0
- package/dist/cloudflare-factory.js +84 -28
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/diagnostics.js +18 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/durable-objects.d.ts +6 -2
- package/dist/index.d.ts +160 -455
- package/dist/index.js +7 -13
- package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
- package/dist/platform.js +22 -0
- package/dist/platform.js.map +1 -0
- package/dist/queue/cloudflare-queues.js +7 -7
- package/dist/queue/cloudflare-queues.js.map +1 -1
- package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
- package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
- package/dist/root-module-C23bUwt_.d.ts +11 -0
- package/dist/schedule-diagnostics.js +8 -15
- package/dist/schedule-diagnostics.js.map +1 -1
- package/dist/services/kv-cache.store.js +33 -7
- package/dist/services/kv-cache.store.js.map +1 -1
- package/dist/storage/r2-storage.js +30 -0
- package/dist/storage/r2-storage.js.map +1 -0
- package/dist/storage.d.ts +28 -0
- package/dist/storage.js +2 -0
- package/dist/testing.d.ts +96 -0
- package/dist/testing.js +111 -0
- package/dist/testing.js.map +1 -0
- package/dist/websocket/binding-gateways.js +33 -0
- package/dist/websocket/binding-gateways.js.map +1 -0
- package/dist/websocket/cf-room-registry.js +3 -1
- package/dist/websocket/cf-room-registry.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +36 -15
- package/dist/websocket/do-bootstrap.js.map +1 -1
- package/dist/websocket/do-live.js +49 -90
- package/dist/websocket/do-live.js.map +1 -1
- package/dist/websocket/do-state.js.map +1 -1
- package/dist/websocket/live-driver.js +149 -0
- package/dist/websocket/live-driver.js.map +1 -0
- package/dist/websocket/room-id.js +11 -1
- package/dist/websocket/room-id.js.map +1 -1
- package/dist/websocket/websocket.durable-object.js +14 -10
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/websocket/worker-transport.js +80 -0
- package/dist/websocket/worker-transport.js.map +1 -0
- package/package.json +23 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
- package/dist/storage/r2-storage.driver.js +0 -67
- package/dist/storage/r2-storage.driver.js.map +0 -1
- package/dist/storage/storage-key-claim.js +0 -74
- package/dist/storage/storage-key-claim.js.map +0 -1
- package/dist/storage/storage-manager.service.js +0 -38
- package/dist/storage/storage-manager.service.js.map +0 -1
- package/dist/storage/storage.controller.js +0 -64
- package/dist/storage/storage.controller.js.map +0 -1
- package/dist/storage/storage.module.js +0 -25
- package/dist/storage/storage.module.js.map +0 -1
- package/dist/storage/storage.service.js +0 -64
- package/dist/storage/storage.service.js.map +0 -1
- package/dist/storage/storage.tokens.js +0 -7
- package/dist/storage/storage.tokens.js.map +0 -1
- package/dist/websocket/broadcast.js +0 -32
- package/dist/websocket/broadcast.js.map +0 -1
- package/dist/websocket/cloudflare-websocket.module.js +0 -25
- package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
- package/dist/websocket/websocket-routing.js +0 -133
- package/dist/websocket/websocket-routing.js.map +0 -1
- package/dist/websocket/ws-server-holder.js +0 -38
- package/dist/websocket/ws-server-holder.js.map +0 -1
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { assertCloudflareEnvironment, registerCloudflareEnvironment } from "./environment.js";
|
|
1
|
+
import { assertCloudflareEnvironment } from "./environment.js";
|
|
3
2
|
import { registerScheduledEventSeed } from "./scheduled-event.js";
|
|
4
3
|
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
4
|
+
import { registerCloudflarePlatform } from "./platform.js";
|
|
5
5
|
import { reportCloudflareScheduleDiagnostics } from "./schedule-diagnostics.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
6
|
+
import { reportUnservedGateways } from "./websocket/binding-gateways.js";
|
|
7
|
+
import { workerWebSocketTransport } from "./websocket/worker-transport.js";
|
|
8
|
+
import { workerLivePlatform } from "./websocket/live-driver.js";
|
|
8
9
|
import { VelaFactory } from "@velajs/vela";
|
|
9
10
|
//#region src/cloudflare-factory.ts
|
|
10
11
|
function readStrings(meta, property) {
|
|
@@ -28,9 +29,13 @@ function assertQueueConsumerOwnership(entrypoints) {
|
|
|
28
29
|
/**
|
|
29
30
|
* Bind an application to one environment: seeded as the global ENV before
|
|
30
31
|
* provider factories and lifecycle hooks, and asserted on every request. The
|
|
31
|
-
* adapter also
|
|
32
|
-
*
|
|
33
|
-
*
|
|
32
|
+
* adapter also registers the Worker's platform wiring: `WebSocketModule`
|
|
33
|
+
* forwards each authenticated gateway upgrade to the room's Durable Object,
|
|
34
|
+
* and `LiveModule` sends invalidations there. It supplies the
|
|
35
|
+
* `InternalDispatcher` transport, so signed queue and schedule dispatch
|
|
36
|
+
* re-enter this application's routes, and reports, through the diagnostics
|
|
37
|
+
* policy, schedule declarations a cron trigger cannot honor and binding-backed
|
|
38
|
+
* gateways without `WebSocketModule`.
|
|
34
39
|
*/
|
|
35
40
|
function cloudflareAdapter(options) {
|
|
36
41
|
const { env } = options;
|
|
@@ -41,56 +46,106 @@ function cloudflareAdapter(options) {
|
|
|
41
46
|
await next();
|
|
42
47
|
}],
|
|
43
48
|
invocationTransport: ({ app }) => (request) => Promise.resolve(app.fetch(request, env)),
|
|
44
|
-
getClientIp: (c) =>
|
|
49
|
+
getClientIp: (c) => c.req.header("cf-connecting-ip") ?? null,
|
|
45
50
|
configureContainer: (container) => {
|
|
46
|
-
|
|
51
|
+
registerCloudflarePlatform(container, env, {
|
|
52
|
+
websocket: workerWebSocketTransport(env),
|
|
53
|
+
live: workerLivePlatform(env, container)
|
|
54
|
+
});
|
|
47
55
|
registerScheduledEventSeed(container);
|
|
48
56
|
},
|
|
49
|
-
onBootstrap:
|
|
57
|
+
onBootstrap: ({ app, container, discovery }) => {
|
|
50
58
|
assertQueueConsumerOwnership(app.entrypoints);
|
|
51
59
|
reportCloudflareScheduleDiagnostics(container, app.entrypoints);
|
|
52
|
-
|
|
60
|
+
reportUnservedGateways(container, discovery);
|
|
53
61
|
}
|
|
54
62
|
};
|
|
55
63
|
}
|
|
56
64
|
/**
|
|
65
|
+
* The `VelaFactory.create()` options an application for `options.env` is built
|
|
66
|
+
* with: that environment (seeded as ENV and sent by test clients as `c.env`),
|
|
67
|
+
* the Cloudflare adapter bound to it, then any further adapters.
|
|
68
|
+
*/
|
|
69
|
+
function cloudflareCreateOptions(options) {
|
|
70
|
+
return {
|
|
71
|
+
env: options.env,
|
|
72
|
+
globalPrefix: options.globalPrefix,
|
|
73
|
+
globalPrefixOptions: options.globalPrefixOptions,
|
|
74
|
+
versioning: options.versioning,
|
|
75
|
+
security: options.security,
|
|
76
|
+
cors: options.cors,
|
|
77
|
+
adapters: [cloudflareAdapter(options), ...options.adapters ?? []]
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
57
81
|
* Build an application for one native Workers environment. Call inside a platform event.
|
|
58
82
|
* The root is static: a module class or a `DynamicModule` declared at module scope.
|
|
59
83
|
* Read bindings in providers (`@InjectEnv()`) and module factories
|
|
60
84
|
* (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
|
|
61
85
|
*/
|
|
62
86
|
async function createCloudflareApp(rootModule, options) {
|
|
63
|
-
const velaApp = await VelaFactory.create(rootModule,
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
87
|
+
const velaApp = await VelaFactory.create(rootModule, cloudflareCreateOptions(options));
|
|
88
|
+
return new CloudflareApplication(velaApp, options.env);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Run a Worker's `configure` hook on the application built for `env`, as
|
|
92
|
+
* `createCloudflareWorker()` does before any event reaches it: a throw or a
|
|
93
|
+
* returned promise closes the application and fails the construction.
|
|
94
|
+
*/
|
|
95
|
+
async function configureCloudflareApplication(app, env, configure) {
|
|
96
|
+
if (!configure) return app;
|
|
97
|
+
try {
|
|
98
|
+
const result = configure(app, env);
|
|
99
|
+
if (result instanceof Promise) {
|
|
100
|
+
result.catch(() => {});
|
|
101
|
+
throw new TypeError("createCloudflareWorker configure must finish synchronously: it runs before any event reaches the application, so read bindings and perform I/O in providers.");
|
|
102
|
+
}
|
|
103
|
+
} catch (error) {
|
|
104
|
+
await app.close().catch(() => {});
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
72
107
|
return app;
|
|
73
108
|
}
|
|
74
109
|
/**
|
|
110
|
+
* The well-known key under which a `createCloudflareWorker()` entry carries
|
|
111
|
+
* its {@link CloudflareWorkerDescriptor}: `Symbol.for('vela.cloudflare.worker')`.
|
|
112
|
+
*/
|
|
113
|
+
const CLOUDFLARE_WORKER = Symbol.for("vela.cloudflare.worker");
|
|
114
|
+
/**
|
|
75
115
|
* Worker entrypoint with one bootstrap per environment identity. Concurrent cold
|
|
76
|
-
* events share construction
|
|
77
|
-
* can retry. Weak keys stop this cache from
|
|
116
|
+
* events share construction, including `configure`; failed construction is
|
|
117
|
+
* evicted so the next event can retry. Weak keys stop this cache from
|
|
118
|
+
* retaining a replaced environment.
|
|
78
119
|
*/
|
|
79
120
|
function createCloudflareWorker(rootModule, options = {}) {
|
|
121
|
+
const { configure, ...appOptions } = options;
|
|
80
122
|
const applications = /* @__PURE__ */ new WeakMap();
|
|
123
|
+
const build = async (env) => configureCloudflareApplication(await createCloudflareApp(rootModule, {
|
|
124
|
+
...appOptions,
|
|
125
|
+
env
|
|
126
|
+
}), env, configure);
|
|
81
127
|
const application = (env) => {
|
|
82
128
|
const existing = applications.get(env);
|
|
83
129
|
if (existing) return existing;
|
|
84
|
-
const pending =
|
|
85
|
-
...options,
|
|
86
|
-
env
|
|
87
|
-
});
|
|
130
|
+
const pending = build(env);
|
|
88
131
|
applications.set(env, pending);
|
|
89
132
|
pending.catch(() => {
|
|
90
133
|
if (applications.get(env) === pending) applications.delete(env);
|
|
91
134
|
});
|
|
92
135
|
return pending;
|
|
93
136
|
};
|
|
137
|
+
const descriptor = {
|
|
138
|
+
rootModule,
|
|
139
|
+
options,
|
|
140
|
+
createOptions: (env) => cloudflareCreateOptions({
|
|
141
|
+
...appOptions,
|
|
142
|
+
env
|
|
143
|
+
}),
|
|
144
|
+
createApplication: (env) => VelaFactory.create(rootModule, cloudflareCreateOptions({
|
|
145
|
+
...appOptions,
|
|
146
|
+
env
|
|
147
|
+
}))
|
|
148
|
+
};
|
|
94
149
|
return {
|
|
95
150
|
async fetch(request, env, ctx) {
|
|
96
151
|
return (await application(env)).fetch(request, env, ctx);
|
|
@@ -100,10 +155,11 @@ function createCloudflareWorker(rootModule, options = {}) {
|
|
|
100
155
|
},
|
|
101
156
|
async queue(batch, env, ctx) {
|
|
102
157
|
return (await application(env)).queue(batch, env, ctx);
|
|
103
|
-
}
|
|
158
|
+
},
|
|
159
|
+
[CLOUDFLARE_WORKER]: descriptor
|
|
104
160
|
};
|
|
105
161
|
}
|
|
106
162
|
//#endregion
|
|
107
|
-
export { cloudflareAdapter, createCloudflareApp, createCloudflareWorker };
|
|
163
|
+
export { CLOUDFLARE_WORKER, cloudflareAdapter, cloudflareCreateOptions, configureCloudflareApplication, createCloudflareApp, createCloudflareWorker };
|
|
108
164
|
|
|
109
165
|
//# sourceMappingURL=cloudflare-factory.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-factory.js","names":[],"sources":["../src/cloudflare-factory.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport { getConnInfo } from 'hono/cloudflare-workers';\nimport { VelaFactory } from '@velajs/vela';\nimport type {\n VelaApplication,\n VelaEnv,\n VelaMiddlewareHandler,\n VelaSecurityOptions,\n} from '@velajs/vela';\nimport type { RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { CloudflareApplication } from './cloudflare-application';\nimport { assertCloudflareEnvironment, registerCloudflareEnvironment } from './environment';\nimport { reportCloudflareScheduleDiagnostics } from './schedule-diagnostics';\nimport { registerScheduledEventSeed, type ScheduledEvent } from './scheduled-event';\nimport { warnWorkerLocalLive } from './websocket/do-live';\nimport { registerWebSocketRoutes } from './websocket/websocket-routing';\nimport type { CloudflareRoot } from './root-module';\n\nexport interface CloudflareWorkerOptions {\n globalPrefix?: string;\n security?: VelaSecurityOptions;\n /** Build request middleware from the same native environment DI receives as ENV. */\n middleware?: (env: VelaEnv) => VelaMiddlewareHandler[];\n /** Further runtime adapters, composed after the Cloudflare adapter for each application. */\n adapters?: RuntimeAdapter[];\n}\n\nexport interface CreateCloudflareAppOptions extends CloudflareWorkerOptions {\n /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */\n env: VelaEnv;\n}\n\nfunction readStrings(meta: unknown, property: string): string[] {\n const value: unknown =\n typeof meta === 'object' && meta !== null ? Reflect.get(meta, property) : undefined;\n if (typeof value === 'string') return [value];\n if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value;\n throw new TypeError(`Invalid queue consumer metadata: ${property}.`);\n}\n\n/**\n * `@QueueConsumer` handlers own their physical queue. A `QueueModule`\n * registration that pins the same physical queue with `consumer` would never\n * see its batches, so bootstrap rejects the overlap.\n */\nfunction assertQueueConsumerOwnership(entrypoints: VelaApplication['entrypoints']): void {\n const pinned = new Set(\n entrypoints.ofKind('cf:queue:module').flatMap((entry) => readStrings(entry.meta, 'consumers')),\n );\n for (const entry of entrypoints.ofKind('cf:queue')) {\n const [queue] = readStrings(entry.meta, 'queueName');\n if (queue !== undefined && pinned.has(queue)) {\n throw new Error(\n `Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a ` +\n `QueueModule.registerQueue({ consumer: '${queue}' }) both claim it. Keep one owner.`,\n );\n }\n }\n}\n\n/**\n * Bind an application to one environment: seeded as the global ENV before\n * provider factories and lifecycle hooks, and asserted on every request. The\n * adapter also supplies the `InternalDispatcher` transport, so signed queue and\n * schedule dispatch re-enter this application's routes, and reports schedule\n * declarations a cron trigger cannot honor through the diagnostics policy.\n */\nexport function cloudflareAdapter(options: { env: VelaEnv }): RuntimeAdapter {\n const { env } = options;\n return {\n name: 'cloudflare',\n requestMiddleware: [\n async (context, next) => {\n assertCloudflareEnvironment(env, context.env);\n await next();\n },\n ],\n invocationTransport:\n ({ app }) =>\n (request) =>\n Promise.resolve(app.fetch(request, env)),\n getClientIp: (c) => getConnInfo(c).remote.address ?? null,\n configureContainer: (container) => {\n registerCloudflareEnvironment(container, env);\n registerScheduledEventSeed(container);\n },\n onBootstrap: async ({ app, container }) => {\n assertQueueConsumerOwnership(app.entrypoints);\n reportCloudflareScheduleDiagnostics(container, app.entrypoints);\n await warnWorkerLocalLive(container);\n },\n };\n}\n\n/**\n * Build an application for one native Workers environment. Call inside a platform event.\n * The root is static: a module class or a `DynamicModule` declared at module scope.\n * Read bindings in providers (`@InjectEnv()`) and module factories\n * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.\n */\nexport async function createCloudflareApp(\n rootModule: CloudflareRoot,\n options: CreateCloudflareAppOptions,\n): Promise<CloudflareApplication> {\n const velaApp = await VelaFactory.create(rootModule, {\n globalPrefix: options.globalPrefix,\n security: options.security,\n middleware: options.middleware?.(options.env),\n adapters: [cloudflareAdapter(options), ...(options.adapters ?? [])],\n });\n const app = new CloudflareApplication(velaApp, options.env);\n app.scanInstances(velaApp.getInstances());\n registerWebSocketRoutes(app.getHonoApp(), app.getWsGatewayRoutes(), velaApp.getContainer());\n return app;\n}\n\n/**\n * Worker entrypoint with one bootstrap per environment identity. Concurrent cold\n * events share construction; failed construction is evicted so the next event\n * can retry. Weak keys stop this cache from retaining a replaced environment.\n */\nexport function createCloudflareWorker(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n) {\n const applications = new WeakMap<VelaEnv, Promise<CloudflareApplication>>();\n const application = (env: VelaEnv): Promise<CloudflareApplication> => {\n const existing = applications.get(env);\n if (existing) return existing;\n const pending = createCloudflareApp(rootModule, { ...options, env });\n applications.set(env, pending);\n void pending.catch(() => {\n if (applications.get(env) === pending) applications.delete(env);\n });\n return pending;\n };\n return {\n async fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response> {\n return (await application(env)).fetch(request, env, ctx);\n },\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).scheduled(event, env, ctx);\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 return (await application(env)).queue(batch, env, ctx);\n },\n };\n}\n"],"mappings":";;;;;;;;;AAgCA,SAAS,YAAY,MAAe,UAA4B;CAC9D,MAAM,QACJ,OAAO,SAAS,YAAY,SAAS,OAAO,QAAQ,IAAI,MAAM,QAAQ,IAAI,KAAA;CAC5E,IAAI,OAAO,UAAU,UAAU,OAAO,CAAC,KAAK;CAC5C,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ,GAAG,OAAO;CACpF,MAAM,IAAI,UAAU,oCAAoC,SAAS,EAAE;AACrE;;;;;;AAOA,SAAS,6BAA6B,aAAmD;CACvF,MAAM,SAAS,IAAI,IACjB,YAAY,OAAO,iBAAiB,CAAC,CAAC,SAAS,UAAU,YAAY,MAAM,MAAM,WAAW,CAAC,CAC/F;CACA,KAAK,MAAM,SAAS,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CAC1E,MAAM,eAAe,QAAiD;EACpE,MAAM,WAAW,aAAa,IAAI,GAAG;EACrC,IAAI,UAAU,OAAO;EACrB,MAAM,UAAU,oBAAoB,YAAY;GAAE,GAAG;GAAS;EAAI,CAAC;EACnE,aAAa,IAAI,KAAK,OAAO;EAC7B,QAAa,YAAY;GACvB,IAAI,aAAa,IAAI,GAAG,MAAM,SAAS,aAAa,OAAO,GAAG;EAChE,CAAC;EACD,OAAO;CACT;CACA,OAAO;EACL,MAAM,MAAM,SAAkB,KAAc,KAA0C;GACpF,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,MAAM,SAAS,KAAK,GAAG;EACzD;EACA,MAAM,UACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,UAAU,OAAO,KAAK,GAAG;EAC3D;EACA,MAAM,MACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,MAAM,OAAO,KAAK,GAAG;EACvD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"cloudflare-factory.js","names":[],"sources":["../src/cloudflare-factory.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport { VelaFactory } from '@velajs/vela';\nimport type {\n CorsOptions,\n GlobalPrefixOptions,\n VelaApplication,\n VelaCreateOptions,\n VelaEnv,\n VelaSecurityOptions,\n VersioningOptions,\n} from '@velajs/vela';\nimport type { RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { CloudflareApplication } from './cloudflare-application';\nimport { assertCloudflareEnvironment } from './environment';\nimport { registerCloudflarePlatform } from './platform';\nimport { reportCloudflareScheduleDiagnostics } from './schedule-diagnostics';\nimport { registerScheduledEventSeed, type ScheduledEvent } from './scheduled-event';\nimport { reportUnservedGateways } from './websocket/binding-gateways';\nimport { workerLivePlatform } from './websocket/live-driver';\nimport { workerWebSocketTransport } from './websocket/worker-transport';\nimport type { CloudflareRoot } from './root-module';\n\nexport interface CloudflareAppOptions {\n globalPrefix?: string;\n /** Routes served without the global prefix (`{ exclude }`). */\n globalPrefixOptions?: GlobalPrefixOptions;\n /** URI versioning: the version segment prefix (default `'v'`). */\n versioning?: VersioningOptions;\n security?: VelaSecurityOptions;\n /** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */\n cors?: CorsOptions | boolean;\n /** Further runtime adapters, composed after the Cloudflare adapter for each application. */\n adapters?: RuntimeAdapter[];\n}\n\nexport interface CloudflareWorkerOptions extends CloudflareAppOptions {\n /**\n * Finish each application's HTTP surface, such as extra Hono routes, once per\n * environment. It runs after the application is built and before any event,\n * including concurrent cold events, reaches it; a throw fails that\n * construction, and the next event retries. It must be synchronous and do no\n * I/O (a returned promise fails the construction): read bindings in\n * providers. Request middleware belongs in modules (`configure(consumer)`),\n * which can inject `ENV`.\n */\n configure?(app: CloudflareApplication, env: VelaEnv): void;\n}\n\nexport interface CreateCloudflareAppOptions extends CloudflareAppOptions {\n /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */\n env: VelaEnv;\n}\n\nfunction readStrings(meta: unknown, property: string): string[] {\n const value: unknown =\n typeof meta === 'object' && meta !== null ? Reflect.get(meta, property) : undefined;\n if (typeof value === 'string') return [value];\n if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value;\n throw new TypeError(`Invalid queue consumer metadata: ${property}.`);\n}\n\n/**\n * `@QueueConsumer` handlers own their physical queue. A `QueueModule`\n * registration that pins the same physical queue with `consumer` would never\n * see its batches, so bootstrap rejects the overlap.\n */\nfunction assertQueueConsumerOwnership(entrypoints: VelaApplication['entrypoints']): void {\n const pinned = new Set(\n entrypoints.ofKind('cf:queue:module').flatMap((entry) => readStrings(entry.meta, 'consumers')),\n );\n for (const entry of entrypoints.ofKind('cf:queue')) {\n const [queue] = readStrings(entry.meta, 'queueName');\n if (queue !== undefined && pinned.has(queue)) {\n throw new Error(\n `Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a ` +\n `QueueModule.registerQueue({ consumer: '${queue}' }) both claim it. Keep one owner.`,\n );\n }\n }\n}\n\n/**\n * Bind an application to one environment: seeded as the global ENV before\n * provider factories and lifecycle hooks, and asserted on every request. The\n * adapter also registers the Worker's platform wiring: `WebSocketModule`\n * forwards each authenticated gateway upgrade to the room's Durable Object,\n * and `LiveModule` sends invalidations there. It supplies the\n * `InternalDispatcher` transport, so signed queue and schedule dispatch\n * re-enter this application's routes, and reports, through the diagnostics\n * policy, schedule declarations a cron trigger cannot honor and binding-backed\n * gateways without `WebSocketModule`.\n */\nexport function cloudflareAdapter(options: { env: VelaEnv }): RuntimeAdapter {\n const { env } = options;\n return {\n name: 'cloudflare',\n requestMiddleware: [\n async (context, next) => {\n assertCloudflareEnvironment(env, context.env);\n await next();\n },\n ],\n invocationTransport:\n ({ app }) =>\n (request) =>\n Promise.resolve(app.fetch(request, env)),\n // Cloudflare attests the client address in this header. Read directly:\n // hono/cloudflare-workers would also load its WebSocket upgrade helper.\n getClientIp: (c) => c.req.header('cf-connecting-ip') ?? null,\n configureContainer: (container) => {\n registerCloudflarePlatform(container, env, {\n websocket: workerWebSocketTransport(env),\n live: workerLivePlatform(env, container),\n });\n registerScheduledEventSeed(container);\n },\n onBootstrap: ({ app, container, discovery }) => {\n assertQueueConsumerOwnership(app.entrypoints);\n reportCloudflareScheduleDiagnostics(container, app.entrypoints);\n reportUnservedGateways(container, discovery);\n },\n };\n}\n\n/**\n * The `VelaFactory.create()` options an application for `options.env` is built\n * with: that environment (seeded as ENV and sent by test clients as `c.env`),\n * the Cloudflare adapter bound to it, then any further adapters.\n */\nexport function cloudflareCreateOptions(options: CreateCloudflareAppOptions): VelaCreateOptions {\n return {\n env: options.env,\n globalPrefix: options.globalPrefix,\n globalPrefixOptions: options.globalPrefixOptions,\n versioning: options.versioning,\n security: options.security,\n cors: options.cors,\n adapters: [cloudflareAdapter(options), ...(options.adapters ?? [])],\n };\n}\n\n/**\n * Build an application for one native Workers environment. Call inside a platform event.\n * The root is static: a module class or a `DynamicModule` declared at module scope.\n * Read bindings in providers (`@InjectEnv()`) and module factories\n * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.\n */\nexport async function createCloudflareApp(\n rootModule: CloudflareRoot,\n options: CreateCloudflareAppOptions,\n): Promise<CloudflareApplication> {\n const velaApp = await VelaFactory.create(rootModule, cloudflareCreateOptions(options));\n return new CloudflareApplication(velaApp, options.env);\n}\n\n/**\n * Run a Worker's `configure` hook on the application built for `env`, as\n * `createCloudflareWorker()` does before any event reaches it: a throw or a\n * returned promise closes the application and fails the construction.\n */\nexport async function configureCloudflareApplication(\n app: CloudflareApplication,\n env: VelaEnv,\n configure: CloudflareWorkerOptions['configure'],\n): Promise<CloudflareApplication> {\n if (!configure) return app;\n try {\n const result: unknown = configure(app, env);\n if (result instanceof Promise) {\n // Observe the rejected work; the construction fails either way.\n result.catch(() => {});\n throw new TypeError(\n 'createCloudflareWorker configure must finish synchronously: it runs before any ' +\n 'event reaches the application, so read bindings and perform I/O in providers.',\n );\n }\n } catch (error) {\n await app.close().catch(() => {});\n throw error;\n }\n return app;\n}\n\n/**\n * The well-known key under which a `createCloudflareWorker()` entry carries\n * its {@link CloudflareWorkerDescriptor}: `Symbol.for('vela.cloudflare.worker')`.\n */\nexport const CLOUDFLARE_WORKER: unique symbol = Symbol.for('vela.cloudflare.worker');\n\n/** What a Worker entry is built from, for tools that load it outside a platform event. */\nexport interface CloudflareWorkerDescriptor {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */\n createOptions(env: VelaEnv): VelaCreateOptions;\n /**\n * `VelaFactory.create(rootModule, createOptions(env))`: the application\n * without its Worker handlers or the `configure` hook, which receives the\n * Workers application.\n */\n createApplication(env: VelaEnv): Promise<VelaApplication>;\n}\n\n/** The exported handlers of a `createCloudflareWorker()` entry. */\nexport interface CloudflareWorker {\n fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;\n scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n /**\n * Symbol-keyed, so the platform, which reads string-keyed handlers, ignores\n * it; enumerable, so `{ ...worker, email }` keeps it for the CLI.\n */\n readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;\n}\n\n/**\n * Worker entrypoint with one bootstrap per environment identity. Concurrent cold\n * events share construction, including `configure`; failed construction is\n * evicted so the next event can retry. Weak keys stop this cache from\n * retaining a replaced environment.\n */\nexport function createCloudflareWorker(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareWorker {\n const { configure, ...appOptions } = options;\n const applications = new WeakMap<VelaEnv, Promise<CloudflareApplication>>();\n const build = async (env: VelaEnv): Promise<CloudflareApplication> =>\n configureCloudflareApplication(\n await createCloudflareApp(rootModule, { ...appOptions, env }),\n env,\n configure,\n );\n const application = (env: VelaEnv): Promise<CloudflareApplication> => {\n const existing = applications.get(env);\n if (existing) return existing;\n const pending = build(env);\n applications.set(env, pending);\n void pending.catch(() => {\n if (applications.get(env) === pending) applications.delete(env);\n });\n return pending;\n };\n const descriptor: CloudflareWorkerDescriptor = {\n rootModule,\n options,\n createOptions: (env) => cloudflareCreateOptions({ ...appOptions, env }),\n createApplication: (env) =>\n VelaFactory.create(rootModule, cloudflareCreateOptions({ ...appOptions, env })),\n };\n const worker: CloudflareWorker = {\n async fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response> {\n return (await application(env)).fetch(request, env, ctx);\n },\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).scheduled(event, env, ctx);\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 return (await application(env)).queue(batch, env, ctx);\n },\n [CLOUDFLARE_WORKER]: descriptor,\n };\n return worker;\n}\n"],"mappings":";;;;;;;;;;AAqDA,SAAS,YAAY,MAAe,UAA4B;CAC9D,MAAM,QACJ,OAAO,SAAS,YAAY,SAAS,OAAO,QAAQ,IAAI,MAAM,QAAQ,IAAI,KAAA;CAC5E,IAAI,OAAO,UAAU,UAAU,OAAO,CAAC,KAAK;CAC5C,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ,GAAG,OAAO;CACpF,MAAM,IAAI,UAAU,oCAAoC,SAAS,EAAE;AACrE;;;;;;AAOA,SAAS,6BAA6B,aAAmD;CACvF,MAAM,SAAS,IAAI,IACjB,YAAY,OAAO,iBAAiB,CAAC,CAAC,SAAS,UAAU,YAAY,MAAM,MAAM,WAAW,CAAC,CAC/F;CACA,KAAK,MAAM,SAAS,YAAY,OAAO,UAAU,GAAG;EAClD,MAAM,CAAC,SAAS,YAAY,MAAM,MAAM,WAAW;EACnD,IAAI,UAAU,KAAA,KAAa,OAAO,IAAI,KAAK,GACzC,MAAM,IAAI,MACR,2CAA2C,MAAM,qBAAqB,MAAM,kDAChC,MAAM,oCACpD;CAEJ;AACF;;;;;;;;;;;;AAaA,SAAgB,kBAAkB,SAA2C;CAC3E,MAAM,EAAE,QAAQ;CAChB,OAAO;EACL,MAAM;EACN,mBAAmB,CACjB,OAAO,SAAS,SAAS;GACvB,4BAA4B,KAAK,QAAQ,GAAG;GAC5C,MAAM,KAAK;EACb,CACF;EACA,sBACG,EAAE,WACF,YACC,QAAQ,QAAQ,IAAI,MAAM,SAAS,GAAG,CAAC;EAG3C,cAAc,MAAM,EAAE,IAAI,OAAO,kBAAkB,KAAK;EACxD,qBAAqB,cAAc;GACjC,2BAA2B,WAAW,KAAK;IACzC,WAAW,yBAAyB,GAAG;IACvC,MAAM,mBAAmB,KAAK,SAAS;GACzC,CAA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AU,OAAO;EACrB,MAAM,UAAU,MAAM,GAAG;EACzB,aAAa,IAAI,KAAK,OAAO;EAC7B,QAAa,YAAY;GACvB,IAAI,aAAa,IAAI,GAAG,MAAM,SAAS,aAAa,OAAO,GAAG;EAChE,CAAC;EACD,OAAO;CACT;CACA,MAAM,aAAyC;EAC7C;EACA;EACA,gBAAgB,QAAQ,wBAAwB;GAAE,GAAG;GAAY;EAAI,CAAC;EACtE,oBAAoB,QAClB,YAAY,OAAO,YAAY,wBAAwB;GAAE,GAAG;GAAY;EAAI,CAAC,CAAC;CAClF;CAqBA,OAAO;EAnBL,MAAM,MAAM,SAAkB,KAAc,KAA0C;GACpF,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,MAAM,SAAS,KAAK,GAAG;EACzD;EACA,MAAM,UACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,UAAU,OAAO,KAAK,GAAG;EAC3D;EACA,MAAM,MACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,MAAM,OAAO,KAAK,GAAG;EACvD;GACC,oBAAoB;CAEX;AACd"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
//#region src/diagnostics.ts
|
|
2
|
+
const reported = /* @__PURE__ */ new Set();
|
|
3
|
+
/**
|
|
4
|
+
* Report through the application's diagnostics policy: `'throw'` fails the
|
|
5
|
+
* caller, `'log'` warns once per message in this isolate, `'silent'` skips.
|
|
6
|
+
*/
|
|
7
|
+
function reportDiagnostic(container, message) {
|
|
8
|
+
const mode = container.getDiagnostics();
|
|
9
|
+
if (mode === "silent") return;
|
|
10
|
+
if (mode === "throw") throw new Error(message);
|
|
11
|
+
if (reported.has(message)) return;
|
|
12
|
+
reported.add(message);
|
|
13
|
+
console.warn(message);
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
export { reportDiagnostic };
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["import type { Container } from '@velajs/vela/module-kit';\n\nconst reported = new Set<string>();\n\n/**\n * Report through the application's diagnostics policy: `'throw'` fails the\n * caller, `'log'` warns once per message in this isolate, `'silent'` skips.\n */\nexport function reportDiagnostic(container: Container, message: string): void {\n const mode = container.getDiagnostics();\n if (mode === 'silent') return;\n if (mode === 'throw') throw new Error(message);\n if (reported.has(message)) return;\n reported.add(message);\n console.warn(message);\n}\n"],"mappings":";AAEA,MAAM,2BAAW,IAAI,IAAY;;;;;AAMjC,SAAgB,iBAAiB,WAAsB,SAAuB;CAC5E,MAAM,OAAO,UAAU,eAAe;CACtC,IAAI,SAAS,UAAU;CACvB,IAAI,SAAS,SAAS,MAAM,IAAI,MAAM,OAAO;CAC7C,IAAI,SAAS,IAAI,OAAO,GAAG;CAC3B,SAAS,IAAI,OAAO;CACpB,QAAQ,KAAK,OAAO;AACtB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import {
|
|
2
|
+
import { t as CloudflareRoot } from "./root-module-C23bUwt_.js";
|
|
3
|
+
import { l as VelaDoPitrRpc, t as VelaNonceDurableObject } from "./nonce.durable-object-Bg1e0BMD.js";
|
|
3
4
|
import { DurableObject } from "cloudflare:workers";
|
|
4
5
|
import { VelaEnv } from "@velajs/vela";
|
|
5
6
|
import { BroadcastCommand } from "@velajs/vela/websocket";
|
|
@@ -16,7 +17,10 @@ import { CommitStamp, InvalidationCommand, LiveInspection } from "@velajs/vela/l
|
|
|
16
17
|
*
|
|
17
18
|
* It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot
|
|
18
19
|
* bridge DO hibernation) and forwards every event into the runtime-agnostic
|
|
19
|
-
* `WsDispatcher` via {@link DoWebSocketHost}. The
|
|
20
|
+
* `WsDispatcher` via {@link DoWebSocketHost}. The application imports the core
|
|
21
|
+
* `WebSocketModule.forRoot()`: this object registers the platform that binds
|
|
22
|
+
* its server to these sockets, delivers live invalidations locally and keeps
|
|
23
|
+
* the live cursor log in its SQLite storage. The DO's `env` is the
|
|
20
24
|
* application's ENV, as in the Worker.
|
|
21
25
|
*/
|
|
22
26
|
export declare function VelaWebSocketDurableObject(rootModule: CloudflareRoot): new (ctx: DurableObjectState, env: VelaEnv) => DurableObject<VelaEnv> & VelaDoPitrRpc & {
|