@velajs/cloudflare 1.33.0 → 1.35.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 +43 -0
- package/README.md +218 -4
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +9 -0
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +6 -0
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +8 -0
- package/dist/bindings.js +25 -1
- package/dist/bindings.js.map +1 -1
- package/dist/{cloudflare-application-CXDy9C1R.d.ts → cloudflare-application-Dsscb3Mo.d.ts} +2 -2
- package/dist/cloudflare-application.js +1 -1
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/{cloudflare-factory-CuFNUJJD.d.ts → cloudflare-factory-DM9CBvNH.d.ts} +5 -5
- package/dist/cloudflare-factory.js +1 -1
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/durable-objects.d.ts +1 -1
- package/dist/email.d.ts +1 -1
- package/dist/entrypoints.d.ts +1 -1
- package/dist/index.d.ts +76 -11
- package/dist/index.js +2 -2
- package/dist/pipelines.d.ts +20 -0
- package/dist/pipelines.js +87 -0
- package/dist/pipelines.js.map +1 -0
- package/dist/queue/cloudflare-queues.js +3 -3
- package/dist/queue/cloudflare-queues.js.map +1 -1
- package/dist/queue-events/consume.js +120 -0
- package/dist/queue-events/consume.js.map +1 -0
- package/dist/queue-events.d.ts +71 -0
- package/dist/queue-events.js +2 -0
- package/dist/queues.d.ts +1 -1
- package/dist/services/flagship-flag.driver.js +64 -6
- package/dist/services/flagship-flag.driver.js.map +1 -1
- package/dist/storage/r2-storage.js +1 -1
- package/dist/storage/r2-storage.js.map +1 -1
- package/dist/storage.d.ts +1 -1
- package/dist/tail.d.ts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/tracing.d.ts +15 -0
- package/dist/tracing.js +24 -0
- package/dist/tracing.js.map +1 -0
- package/dist/workflow/portable-workflow-step.js +62 -0
- package/dist/workflow/portable-workflow-step.js.map +1 -0
- package/dist/workflow/vela-workflow-definition.js +78 -0
- package/dist/workflow/vela-workflow-definition.js.map +1 -0
- package/dist/workflow-definitions.d.ts +33 -0
- package/dist/workflow-definitions.js +2 -0
- package/dist/workflows.d.ts +1 -1
- package/package.json +32 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.35.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 9a00506: Align module APIs with instance ownership: shared facilities use forRoot, local and named services use register, and Queue, I18n and Seeder contribute declarations through forFeature. Remove replaced APIs. Local registrations receive independent identities; reused definitions share within an application, and explicit keys retain conflict checks.
|
|
8
|
+
|
|
9
|
+
Require applications to attach exported guards and interceptors explicitly. Remove automatic installation and guard options while preserving policy ownership, request scope, phase ordering, testing overrides and integration-route exemptions. Keep translation contributions and mutable runtime configuration isolated per application, and return runtime-only settings from async factories. Storage separates structural httpController mounting from runtime http options.
|
|
10
|
+
|
|
11
|
+
Add schema-first GraphQL resolver and parameter decorators with exact provider ownership, endpoint selection and duplicate binding validation. Add the optional Cloudflare workflow-definitions entrypoint to host portable workflows and compiled agents with validated input, per-run dependency resolution, explicit dispatch authority and native replay/error semantics.
|
|
12
|
+
|
|
13
|
+
Update CLI output, runnable examples, packed consumers and migration documentation together. Keep root Cloudflare declarations usable without installing the optional Feature Flags peer. See docs/module-api-migration.md for the new signatures and required application changes. This is a coordinated breaking change on the 1.x line; no compatibility aliases are retained.
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- Updated dependencies [9a00506]
|
|
18
|
+
- @velajs/vela@1.34.0
|
|
19
|
+
- @velajs/storage@1.34.0
|
|
20
|
+
- @velajs/feature-flags@1.33.0
|
|
21
|
+
- @velajs/testing@1.34.0
|
|
22
|
+
|
|
23
|
+
## 1.34.0
|
|
24
|
+
|
|
25
|
+
### Minor Changes
|
|
26
|
+
|
|
27
|
+
- 2c61e5b: Unify Wrangler binding discovery across resource addition, configuration sync and deployment checks. Cover current native binding shapes, detect cross-kind name collisions, respect environment inheritance exceptions, and preserve unknown configuration. Known malformed bindings now fail before resource creation or config edits.
|
|
28
|
+
|
|
29
|
+
Add `vela add binding <kind> <BINDING> --options <JSON>` for native JSON/JSONC declarations without provisioning resources or adding modules. Selected-environment type generation now calls Wrangler with `--env` instead of running an unqualified types script.
|
|
30
|
+
|
|
31
|
+
Expose `flagship({ binding })` and `secretsStoreSecret({ binding })` native references from `@velajs/cloudflare`, resolving the original handle separately for each environment without caching values.
|
|
32
|
+
- 3cc469d: Preserve native Flagship evaluation reasons, variants and error codes through optional driver detail methods and Studio responses. Value-only providers now report UNKNOWN instead of STATIC; native context accepts only scalar attributes, and route guards deny all evaluation errors. Existing object-validation callback signatures are unchanged.
|
|
33
|
+
|
|
34
|
+
Add the optional crypto/cloudflare SecretsStoreKeyProvider for immutable, versioned AES-KW key material, with explicit per-instance caching, refresh, retry and rotation using retained decryption keys. Secrets Store supplies material for local Web Crypto; it is not a remote KMS.
|
|
35
|
+
- 9ebb189: Add the optional `@velajs/cloudflare/queue-events` subpath for Cloudflare platform event subscriptions inside existing `@QueueConsumer` handlers. Validate the documented versioned envelope, source/account/subscription expectations and Standard Schema payloads before awaiting explicit handlers. Acknowledge each success individually and request native retries for malformed, unmatched or failing messages while preserving partial-batch progress and DLQ behavior. Include a Worker build example, native delivery identity, idempotency and producer trust guidance, and workerd coverage separate from signed Vela job dispatch.
|
|
36
|
+
- f1c7be8: Add the optional `@velajs/cloudflare/pipelines` writer with Standard Schema producer validation, schema transform inference, strict JSON snapshots, and UTF-8 ingestion payload limits. Validate the entire batch before awaiting one native stream send, preserving the configured binding and its ingestion-only guarantees.
|
|
37
|
+
|
|
38
|
+
### Patch Changes
|
|
39
|
+
|
|
40
|
+
- 5314b4e: Add the optional `/tracing` entrypoint with `CloudflareTracingInterceptor` for
|
|
41
|
+
native Workers spans around awaited HTTP and service RPC handler work. Span
|
|
42
|
+
names are fixed and labels contain only bounded class and method names.
|
|
43
|
+
- Updated dependencies [3cc469d]
|
|
44
|
+
- @velajs/feature-flags@1.32.0
|
|
45
|
+
|
|
3
46
|
## 1.33.0
|
|
4
47
|
|
|
5
48
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -4,6 +4,12 @@ Nest-style modules, dependency injection, controllers, queue consumers, cron tri
|
|
|
4
4
|
and live WebSockets on Cloudflare Workers. HTTP routing uses Hono. Bindings use the
|
|
5
5
|
platform's native types.
|
|
6
6
|
|
|
7
|
+
The [native composition example](../../apps/cloudflare-composition/README.md)
|
|
8
|
+
combines request-scoped `ENV` injection with Browser Run Quick Actions, Workers AI
|
|
9
|
+
and AI Gateway, VPC through `HttpService`, and authorized R2-to-WebP Images transforms.
|
|
10
|
+
It keeps destination/model policy on the server, bounds I/O and cancellation, and
|
|
11
|
+
separates local emulation from opt-in live acceptance without additional packages.
|
|
12
|
+
|
|
7
13
|
## Native environment and application lifetime
|
|
8
14
|
|
|
9
15
|
The Worker's native environment is the framework `ENV` from `@velajs/vela`.
|
|
@@ -218,7 +224,7 @@ class EmailProcessor {
|
|
|
218
224
|
}
|
|
219
225
|
|
|
220
226
|
@Module({
|
|
221
|
-
imports: [QueueModule.
|
|
227
|
+
imports: [QueueModule.forFeature([{ name: 'email', binding: 'EMAIL_QUEUE' }])],
|
|
222
228
|
providers: [Signup, EmailProcessor],
|
|
223
229
|
})
|
|
224
230
|
class EmailModule {}
|
|
@@ -241,7 +247,7 @@ share one physical queue. Each job runs through the module's dispatch policy,
|
|
|
241
247
|
including signed dispatch and its global guards. A message is acknowledged
|
|
242
248
|
after its processors succeed; a message that is not a job envelope, belongs to
|
|
243
249
|
an unregistered queue, or fails stays unacknowledged, so Cloudflare retries it
|
|
244
|
-
and then dead-letters it. `
|
|
250
|
+
and then dead-letters it. `forFeature({ name, consumer: 'email-production' })`
|
|
245
251
|
pins the queue to that physical queue: its jobs are accepted only from it, and
|
|
246
252
|
it carries only the queues pinned to it. A physical queue cannot be both a
|
|
247
253
|
`@QueueConsumer` queue and a pinned consumer. A `@QueueConsumer` owns its
|
|
@@ -287,6 +293,78 @@ handlers still need the idempotency appropriate to their delivery semantics.
|
|
|
287
293
|
See [execution scopes](../../docs/execution-scopes.md) for lifetime ownership,
|
|
288
294
|
stream boundaries, cancellation and optional transport integration.
|
|
289
295
|
|
|
296
|
+
## Native handler tracing
|
|
297
|
+
|
|
298
|
+
Import `CloudflareTracingInterceptor` from the optional
|
|
299
|
+
`@velajs/cloudflare/tracing` entrypoint and register it on HTTP controllers or
|
|
300
|
+
`VelaEntrypoint` hosts with `@UseInterceptors`. It uses the native
|
|
301
|
+
`cloudflare:workers` tracing API; the package root does not import it.
|
|
302
|
+
|
|
303
|
+
```ts
|
|
304
|
+
import { Controller, Get, Injectable, Module, UseInterceptors } from '@velajs/vela';
|
|
305
|
+
import { defineCloudflareApp } from '@velajs/cloudflare';
|
|
306
|
+
import { VelaEntrypoint } from '@velajs/cloudflare/entrypoints';
|
|
307
|
+
import { CloudflareTracingInterceptor } from '@velajs/cloudflare/tracing';
|
|
308
|
+
|
|
309
|
+
@Controller('/status')
|
|
310
|
+
@UseInterceptors(CloudflareTracingInterceptor)
|
|
311
|
+
class StatusController {
|
|
312
|
+
@Get()
|
|
313
|
+
async read() {
|
|
314
|
+
return { ready: true };
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
@Injectable()
|
|
319
|
+
@UseInterceptors(CloudflareTracingInterceptor)
|
|
320
|
+
class StatusHost {
|
|
321
|
+
async read() {
|
|
322
|
+
return { ready: true };
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
@Module({ controllers: [StatusController] })
|
|
327
|
+
class AppModule {}
|
|
328
|
+
|
|
329
|
+
const app = defineCloudflareApp(AppModule);
|
|
330
|
+
export class Status extends VelaEntrypoint(app, StatusHost, { rpc: ['read'] }) {}
|
|
331
|
+
export default app.worker;
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
Enable traces in Wrangler and choose an application sampling rate:
|
|
335
|
+
|
|
336
|
+
```toml
|
|
337
|
+
[observability.traces]
|
|
338
|
+
enabled = true
|
|
339
|
+
head_sampling_rate = 1
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
The interceptor calls `next.handle()` inside `tracing.enterSpan()` and returns
|
|
343
|
+
its promise. Native child spans and awaited platform calls run within that
|
|
344
|
+
callback's async context. Cloudflare owns sampling, span completion and export,
|
|
345
|
+
including its service RPC transport instrumentation. Unsampled calls still run
|
|
346
|
+
normally. Use a Workers runtime with the
|
|
347
|
+
[native custom-span API](https://developers.cloudflare.com/workers/observability/traces/custom-spans/).
|
|
348
|
+
|
|
349
|
+
Span names are fixed: `vela.http.handler` and `vela.rpc.handler`. Sampled spans
|
|
350
|
+
add only `vela.handler.class` and `vela.handler.method`, each limited to 128
|
|
351
|
+
characters. Symbol method names are omitted. Labels use runtime names, which
|
|
352
|
+
may change with minification. No request values, arguments, errors, identifiers,
|
|
353
|
+
HTTP status or outcome attributes are added by this interceptor. Other execution
|
|
354
|
+
kinds pass through without a span.
|
|
355
|
+
|
|
356
|
+
The span covers the handler and inner interceptors until their returned promise
|
|
357
|
+
settles. Guards and pipes run earlier; response streams, deferred work and scope
|
|
358
|
+
disposal can outlive it. This integration does not implement Vela's portable
|
|
359
|
+
`Telemetry` interface or expose parent selection, span IDs or trace-header
|
|
360
|
+
propagation. See [observability](../../docs/observability.md) for that separate API.
|
|
361
|
+
|
|
362
|
+
The workerd tests exercise nested HTTP/RPC and KV calls, concurrent environments,
|
|
363
|
+
errors and disabled sampling. They do not inspect exported span trees or assert
|
|
364
|
+
parent IDs. Inspect sampled traces with Wrangler's
|
|
365
|
+
[local tracing tools](https://developers.cloudflare.com/changelog/post/2026-08-04-local-tracing/)
|
|
366
|
+
when verifying the runtime's exported hierarchy.
|
|
367
|
+
|
|
290
368
|
## Typed provider factories
|
|
291
369
|
|
|
292
370
|
Bindings retain their full native API and generic parameters. There are no
|
|
@@ -316,6 +394,15 @@ Use native `env.DB`, `env.CACHE`, `env.FILES`, `env.JOBS`, `env.AI`,
|
|
|
316
394
|
(`@InjectEnv()`) and factories (`inject: [ENV]`); it works the same in HTTP,
|
|
317
395
|
queue, cron and Durable Object code.
|
|
318
396
|
|
|
397
|
+
## Platform event subscriptions
|
|
398
|
+
|
|
399
|
+
`@velajs/cloudflare/queue-events` composes inside `@QueueConsumer` to validate
|
|
400
|
+
Cloudflare event subscription envelopes and Standard Schema payloads. It awaits
|
|
401
|
+
explicit handlers, acknowledges each success and retries failed messages through
|
|
402
|
+
the native queue policy. Use a dedicated queue with trusted producer permissions;
|
|
403
|
+
metadata checks are not authentication and duplicate deliveries require consumer
|
|
404
|
+
idempotency. See the [Worker build example and settlement guide](../../docs/cloudflare-queue-events.md).
|
|
405
|
+
|
|
319
406
|
## Queues and cron
|
|
320
407
|
|
|
321
408
|
```ts
|
|
@@ -523,6 +610,17 @@ instances from module options and helpers; `WorkflowParams<T>` reads a
|
|
|
523
610
|
Workflow's params from its class or host. See
|
|
524
611
|
[Workflows](../../docs/workflows.md).
|
|
525
612
|
|
|
613
|
+
For portable `defineWorkflow(...)` and compiled `@velajs/agent` definitions,
|
|
614
|
+
import `VelaWorkflowDefinition` from `@velajs/cloudflare/workflow-definitions`.
|
|
615
|
+
This separate entrypoint requires the optional `@velajs/workflow` peer; importing
|
|
616
|
+
`/workflows` does not load it. The helper accepts `{ params, inject, useFactory }`:
|
|
617
|
+
validate trigger data with `params`, resolve the typed injection tuple per run,
|
|
618
|
+
and return `{ definition, run }` from the factory. `run` is an explicit application
|
|
619
|
+
dispatcher. Native steps preserve retries, checkpoints and compensation, including
|
|
620
|
+
portable terminal-error conversion inside step/rollback callbacks. Export a named
|
|
621
|
+
subclass and register it in Wrangler just as above. See the
|
|
622
|
+
[portable bridge example](../workflow/README.md#cloudflare-and-dependency-injection).
|
|
623
|
+
|
|
526
624
|
## Service entrypoints, email and tail
|
|
527
625
|
|
|
528
626
|
`VelaEntrypoint(app, Host, { rpc })` from `@velajs/cloudflare/entrypoints`
|
|
@@ -567,7 +665,8 @@ application that fails to start is logged to the console instead. See
|
|
|
567
665
|
## Bindings by name
|
|
568
666
|
|
|
569
667
|
Module options name a binding instead of holding it. `kv`, `r2`, `d1`,
|
|
570
|
-
`queue`, `durableObject`, `rateLimit
|
|
668
|
+
`queue`, `durableObject`, `rateLimit`, `workflow`, `flagship` and
|
|
669
|
+
`secretsStoreSecret` each take `{ binding }`, the name
|
|
571
670
|
declared in the Wrangler configuration, and read nothing when declared: calling
|
|
572
671
|
the reference with an application's `ENV` returns the typed native binding, or
|
|
573
672
|
fails naming the binding and the Wrangler key that declares it
|
|
@@ -575,6 +674,37 @@ fails naming the binding and the Wrangler key that declares it
|
|
|
575
674
|
The drivers and stores below are built on them, so one static module graph
|
|
576
675
|
serves every environment.
|
|
577
676
|
|
|
677
|
+
`flagship` returns the native `Flagship` handle, including typed value and detail
|
|
678
|
+
methods. `secretsStoreSecret` returns a native `SecretsStoreSecret` handle; call
|
|
679
|
+
`get()` to read its current value. References perform structural checks only:
|
|
680
|
+
they do not read secrets, evaluate flags, cache results, create resources or prove
|
|
681
|
+
remote availability. Native method errors and local-development behavior are
|
|
682
|
+
unchanged. Use current generated Wrangler types or Workers types containing
|
|
683
|
+
these native interfaces (validated with Wrangler 4.135.0 and Workers types
|
|
684
|
+
5.20260920.1).
|
|
685
|
+
|
|
686
|
+
```ts
|
|
687
|
+
import { flagship, secretsStoreSecret } from '@velajs/cloudflare';
|
|
688
|
+
|
|
689
|
+
const flags = flagship({ binding: 'FLAGS' });
|
|
690
|
+
const apiKey = secretsStoreSecret({ binding: 'API_KEY' });
|
|
691
|
+
|
|
692
|
+
// In request/application scope, using that application's environment:
|
|
693
|
+
async function readSettings(env: Env) {
|
|
694
|
+
const enabled = await flags(env).getBooleanValue('new-layout', false);
|
|
695
|
+
const key = await apiKey(env).get();
|
|
696
|
+
return { enabled, key };
|
|
697
|
+
}
|
|
698
|
+
```
|
|
699
|
+
|
|
700
|
+
Declare `FLAGS` under `flagship` with an `app_id`, and `API_KEY` under
|
|
701
|
+
`secrets_store_secrets` with a `store_id` and `secret_name`, separately for each
|
|
702
|
+
named environment. `vela add binding` can write those config declarations;
|
|
703
|
+
resource setup remains explicit. See Cloudflare's [Flagship binding API](https://developers.cloudflare.com/flagship/binding/)
|
|
704
|
+
and [Secrets Store Workers integration](https://developers.cloudflare.com/secrets-store/integrations/workers/)
|
|
705
|
+
for native methods and local setup. In particular, local Secrets Store values
|
|
706
|
+
are separate from production secrets.
|
|
707
|
+
|
|
578
708
|
## Rate limiting
|
|
579
709
|
|
|
580
710
|
`ThrottlerModule` from `@velajs/vela/throttler` counts through Workers Rate
|
|
@@ -620,7 +750,7 @@ is the one file-storage module. Its native R2 driver comes from the
|
|
|
620
750
|
import { StorageModule } from '@velajs/storage';
|
|
621
751
|
import { r2Storage } from '@velajs/cloudflare/storage';
|
|
622
752
|
|
|
623
|
-
StorageModule.
|
|
753
|
+
StorageModule.register({ driver: r2Storage({ binding: 'UPLOADS' }) });
|
|
624
754
|
```
|
|
625
755
|
|
|
626
756
|
The bucket is read from each application's `ENV` on its first storage
|
|
@@ -724,6 +854,90 @@ it('processes a created todo', async () => {
|
|
|
724
854
|
|
|
725
855
|
The subpath is not part of any Worker bundle: import it from tests only.
|
|
726
856
|
|
|
857
|
+
## Validated Pipelines producers
|
|
858
|
+
|
|
859
|
+
`@velajs/cloudflare/pipelines` adds producer validation to a configured native
|
|
860
|
+
stream handle. It is an optional adapter subpath: there is no module, queue
|
|
861
|
+
driver, or replacement for the native Pipelines API.
|
|
862
|
+
|
|
863
|
+
Configure the stream in Wrangler and regenerate your environment types:
|
|
864
|
+
|
|
865
|
+
```jsonc
|
|
866
|
+
{
|
|
867
|
+
"pipelines": [{ "binding": "EVENT_STREAM", "stream": "<STREAM_ID>" }],
|
|
868
|
+
}
|
|
869
|
+
```
|
|
870
|
+
|
|
871
|
+
Use a Standard Schema validator whose **output** matches the deployed stream
|
|
872
|
+
schema. Synchronous and asynchronous transforms are supported; `send()` takes
|
|
873
|
+
schema **inputs** and sends the validated outputs:
|
|
874
|
+
|
|
875
|
+
```ts
|
|
876
|
+
import { ENV, InjectionToken, defineProvider } from '@velajs/vela';
|
|
877
|
+
import { createPipelinesWriter, type PipelinesWriter } from '@velajs/cloudflare/pipelines';
|
|
878
|
+
import { z } from 'zod';
|
|
879
|
+
|
|
880
|
+
const event = z.object({
|
|
881
|
+
id: z.string().min(1),
|
|
882
|
+
count: z.string().regex(/^\d+$/).transform(Number).pipe(z.number().int().nonnegative()),
|
|
883
|
+
});
|
|
884
|
+
|
|
885
|
+
export const EVENTS = new InjectionToken<PipelinesWriter<z.input<typeof event>>>('events');
|
|
886
|
+
|
|
887
|
+
// Add this provider to your application's providers. ENV and the writer belong
|
|
888
|
+
// to that application; do not capture a request's environment at module scope.
|
|
889
|
+
export const eventsProvider = defineProvider(EVENTS, {
|
|
890
|
+
inject: [ENV],
|
|
891
|
+
useFactory: (env) => createPipelinesWriter(env.EVENT_STREAM, { schema: event }),
|
|
892
|
+
});
|
|
893
|
+
|
|
894
|
+
// In a provider that injects EVENTS:
|
|
895
|
+
// await this.events.send([{ id: 'sample-1', count: '2' }]);
|
|
896
|
+
```
|
|
897
|
+
|
|
898
|
+
The factory also works directly with `createPipelinesWriter(env.EVENT_STREAM,
|
|
899
|
+
{ schema: event })`. The binding is structural (`send(records): Promise<void>`),
|
|
900
|
+
remains available as `env.EVENT_STREAM`, and needs no `cloudflare:pipelines`
|
|
901
|
+
runtime import. Generated `Pipeline<RecordType>` bindings check schema output
|
|
902
|
+
compatibility at compile time. Select the stream through trusted configuration;
|
|
903
|
+
the writer does not accept a stream name or endpoint from a record or request.
|
|
904
|
+
|
|
905
|
+
Each nonempty `send(records)` validates all records before making one native
|
|
906
|
+
call. A failure rejects without sending any records; validation may stop at the
|
|
907
|
+
first error. Standard Schema failures use `SchemaValidationError` from
|
|
908
|
+
`@velajs/vela/validation`, with the record index prefixed to each issue path.
|
|
909
|
+
Validator exceptions and native failures propagate. There is no automatic retry,
|
|
910
|
+
batch splitting, rate limiter, or buffering. Empty batches reject.
|
|
911
|
+
|
|
912
|
+
After schema transforms, each record must be a plain JSON object. Nested objects
|
|
913
|
+
and dense arrays may contain strings, booleans, null, and finite numbers. The
|
|
914
|
+
writer rejects undefined values (including explicitly undefined optional fields),
|
|
915
|
+
functions, symbols, bigint, non-finite numbers, cycles, class instances, `Date`,
|
|
916
|
+
`Map`, `Set`, typed arrays, getters, non-enumerable or symbol properties, extra
|
|
917
|
+
array properties, and `toJSON` functions. Convert special values in your schema.
|
|
918
|
+
Validated outputs are copied before the next asynchronous validation, so later
|
|
919
|
+
mutations cannot alter already checked records. Callers must not mutate inputs
|
|
920
|
+
while their schema is validating them.
|
|
921
|
+
|
|
922
|
+
The writer measures the UTF-8 encoding of compact JSON outputs, including escapes,
|
|
923
|
+
commas and array brackets, against a conservative **5,000,000-byte request
|
|
924
|
+
ceiling**. A single record must fit inside that same JSON array (at most
|
|
925
|
+
4,999,998 bytes). The current [Cloudflare limits](https://developers.cloudflare.com/pipelines/platform/limits/)
|
|
926
|
+
document 5 MB per ingestion request without a separate record size cap; this
|
|
927
|
+
adapter does not invent one. Oversize records or batches reject with `RangeError`;
|
|
928
|
+
non-JSON output rejects with `TypeError`.
|
|
929
|
+
|
|
930
|
+
`send()` resolves to `void` only after native ingestion acceptance. Cloudflare
|
|
931
|
+
[accepts but later drops invalid structured events](https://developers.cloudflare.com/pipelines/streams/writing-to-streams/#schema-validation),
|
|
932
|
+
so keep your producer schema aligned with the configured stream. Resolution
|
|
933
|
+
provides no query visibility, transaction, application exactly-once, or terminal
|
|
934
|
+
storage guarantee. A failed native request may have reached the service; any
|
|
935
|
+
retry and deduplication policy belongs to the application.
|
|
936
|
+
|
|
937
|
+
Tests cover producer behavior and native type compatibility. Workerd tests also
|
|
938
|
+
exercise Miniflare's local Pipelines binding, whose `send()` is a no-op; they
|
|
939
|
+
provide no remote ingestion, schema enforcement, or downstream storage proof.
|
|
940
|
+
|
|
727
941
|
## Development
|
|
728
942
|
|
|
729
943
|
From the repository root:
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorate.js
|
|
2
|
+
function __decorate(decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
}
|
|
8
|
+
//#endregion
|
|
9
|
+
export { __decorate as default };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorateMetadata.js
|
|
2
|
+
function __decorateMetadata(k, v) {
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
4
|
+
}
|
|
5
|
+
//#endregion
|
|
6
|
+
export { __decorateMetadata as default };
|
package/dist/bindings.js
CHANGED
|
@@ -87,7 +87,31 @@ function workflow(ref) {
|
|
|
87
87
|
accepts: (value) => hasOperations(value, ["create", "get"])
|
|
88
88
|
})(ref);
|
|
89
89
|
}
|
|
90
|
+
/** A native Flagship binding declared under `flagship`. No flag values are cached. */
|
|
91
|
+
const FLAGSHIP = {
|
|
92
|
+
name: "Flagship",
|
|
93
|
+
configKey: "flagship",
|
|
94
|
+
accepts: (value) => hasOperations(value, [
|
|
95
|
+
"get",
|
|
96
|
+
"getBooleanValue",
|
|
97
|
+
"getStringValue",
|
|
98
|
+
"getNumberValue",
|
|
99
|
+
"getObjectValue",
|
|
100
|
+
"getBooleanDetails",
|
|
101
|
+
"getStringDetails",
|
|
102
|
+
"getNumberDetails",
|
|
103
|
+
"getObjectDetails"
|
|
104
|
+
])
|
|
105
|
+
};
|
|
106
|
+
const flagship = /* @__PURE__ */ defineBinding(FLAGSHIP);
|
|
107
|
+
/** A secret handle declared under `secrets_store_secrets`; resolve its value with `get()`. */
|
|
108
|
+
const SECRETS_STORE_SECRET = {
|
|
109
|
+
name: "Secrets Store secret",
|
|
110
|
+
configKey: "secrets_store_secrets",
|
|
111
|
+
accepts: (value) => hasOperations(value, ["get"])
|
|
112
|
+
};
|
|
113
|
+
const secretsStoreSecret = /* @__PURE__ */ defineBinding(SECRETS_STORE_SECRET);
|
|
90
114
|
//#endregion
|
|
91
|
-
export { D1_DATABASE, DURABLE_OBJECT_NAMESPACE, KV_NAMESPACE, QUEUE_PRODUCER, R2_BUCKET, RATE_LIMITER, d1, durableObject, kv, queue, r2, rateLimit, workflow };
|
|
115
|
+
export { D1_DATABASE, DURABLE_OBJECT_NAMESPACE, FLAGSHIP, KV_NAMESPACE, QUEUE_PRODUCER, R2_BUCKET, RATE_LIMITER, SECRETS_STORE_SECRET, d1, durableObject, flagship, kv, queue, r2, rateLimit, secretsStoreSecret, workflow };
|
|
92
116
|
|
|
93
117
|
//# sourceMappingURL=bindings.js.map
|
package/dist/bindings.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindings.js","names":[],"sources":["../src/bindings.ts"],"sourcesContent":["import {\n defineBinding,\n type Binding,\n type BindingKind,\n type BindingRef,\n} from '@velajs/vela/module-kit';\n\n/** Whether a value exposes every named operation as a function. */\nfunction hasOperations(value: unknown, operations: readonly string[]): boolean {\n if (typeof value !== 'object' || value === null) return false;\n return operations.every((operation) => typeof Reflect.get(value, operation) === 'function');\n}\n\n/**\n * Name-based Workers binding factories. Each takes `{ binding }`, the name\n * declared in the Wrangler configuration, and returns a reference that reads\n * and validates the native binding from an application's `ENV` when called.\n * Declaring one reads no environment, so references belong in static module\n * options: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\n\n/** A KV namespace declared under `kv_namespaces`. */\nexport const KV_NAMESPACE: BindingKind<KVNamespace> = {\n name: 'KV namespace',\n configKey: 'kv_namespaces',\n accepts: (value): value is KVNamespace =>\n hasOperations(value, ['get', 'put', 'delete', 'list', 'getWithMetadata']),\n};\nexport const kv = /* @__PURE__ */ defineBinding(KV_NAMESPACE);\n\n/** An R2 bucket declared under `r2_buckets`. */\nexport const R2_BUCKET: BindingKind<R2Bucket> = {\n name: 'R2 bucket',\n configKey: 'r2_buckets',\n accepts: (value): value is R2Bucket =>\n hasOperations(value, ['get', 'put', 'head', 'delete', 'list', 'createMultipartUpload']),\n};\nexport const r2 = /* @__PURE__ */ defineBinding(R2_BUCKET);\n\n/** A D1 database declared under `d1_databases`. */\nexport const D1_DATABASE: BindingKind<D1Database> = {\n name: 'D1 database',\n configKey: 'd1_databases',\n accepts: (value): value is D1Database => hasOperations(value, ['prepare', 'batch', 'exec']),\n};\nexport const d1 = /* @__PURE__ */ defineBinding(D1_DATABASE);\n\n/** A queue producer declared under `queues.producers`. */\nexport const QUEUE_PRODUCER: BindingKind<Queue> = {\n name: 'queue producer',\n configKey: 'queues.producers',\n accepts: (value): value is Queue => hasOperations(value, ['send']),\n};\nexport const queue = /* @__PURE__ */ defineBinding(QUEUE_PRODUCER);\n\n/** A Durable Object namespace declared under `durable_objects.bindings`. */\nexport const DURABLE_OBJECT_NAMESPACE: BindingKind<DurableObjectNamespace> = {\n name: 'Durable Object namespace',\n configKey: 'durable_objects.bindings',\n accepts: (value): value is DurableObjectNamespace => hasOperations(value, ['idFromName', 'get']),\n};\nexport const durableObject = /* @__PURE__ */ defineBinding(DURABLE_OBJECT_NAMESPACE);\n\n/** A Workers Rate Limiting binding declared under `ratelimits`. */\nexport const RATE_LIMITER: BindingKind<RateLimit> = {\n name: 'rate limiter',\n configKey: 'ratelimits',\n accepts: (value): value is RateLimit => hasOperations(value, ['limit']),\n};\nexport const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);\n\n/**\n * A reference to a Workflow binding declared under `workflows`, whose\n * instances take `Params`: for a class from `VelaWorkflow()`,\n * `workflow<WorkflowParams<SignupWorkflow>>({ binding: 'SIGNUP_WORKFLOW' })`.\n * Called with an application's ENV, it returns the native binding typed with\n * those params: `await signups(env).create({ params: { email } })`. The\n * runtime checks that the binding is a Workflow; its params are what the\n * Workflow class declares.\n */\nexport function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>> {\n return defineBinding<Workflow<Params>>({\n name: 'Workflow',\n configKey: 'workflows',\n accepts: (value): value is Workflow<Params> => hasOperations(value, ['create', 'get']),\n })(ref);\n}\n"],"mappings":";;;AAQA,SAAS,cAAc,OAAgB,YAAwC;CAC7E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,WAAW,OAAO,cAAc,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM,UAAU;AAC5F;;;;;;;;;AAWA,MAAa,eAAyC;CACpD,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAU;EAAQ;CAAiB,CAAC;AAC5E;AACA,MAAa,KAAqB,8BAAc,YAAY;;AAG5D,MAAa,YAAmC;CAC9C,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAQ;EAAU;EAAQ;CAAuB,CAAC;AAC1F;AACA,MAAa,KAAqB,8BAAc,SAAS;;AAGzD,MAAa,cAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA+B,cAAc,OAAO;EAAC;EAAW;EAAS;CAAM,CAAC;AAC5F;AACA,MAAa,KAAqB,8BAAc,WAAW;;AAG3D,MAAa,iBAAqC;CAChD,MAAM;CACN,WAAW;CACX,UAAU,UAA0B,cAAc,OAAO,CAAC,MAAM,CAAC;AACnE;AACA,MAAa,QAAwB,8BAAc,cAAc;;AAGjE,MAAa,2BAAgE;CAC3E,MAAM;CACN,WAAW;CACX,UAAU,UAA2C,cAAc,OAAO,CAAC,cAAc,KAAK,CAAC;AACjG;AACA,MAAa,gBAAgC,8BAAc,wBAAwB;;AAGnF,MAAa,eAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA8B,cAAc,OAAO,CAAC,OAAO,CAAC;AACxE;AACA,MAAa,YAA4B,8BAAc,YAAY;;;;;;;;;;AAWnE,SAAgB,SAA2B,KAA4C;CACrF,OAAO,cAAgC;EACrC,MAAM;EACN,WAAW;EACX,UAAU,UAAqC,cAAc,OAAO,CAAC,UAAU,KAAK,CAAC;CACvF,CAAC,CAAC,CAAC,GAAG;AACR"}
|
|
1
|
+
{"version":3,"file":"bindings.js","names":[],"sources":["../src/bindings.ts"],"sourcesContent":["import {\n defineBinding,\n type Binding,\n type BindingKind,\n type BindingRef,\n} from '@velajs/vela/module-kit';\n\n/** Whether a value exposes every named operation as a function. */\nfunction hasOperations(value: unknown, operations: readonly string[]): boolean {\n if (typeof value !== 'object' || value === null) return false;\n return operations.every((operation) => typeof Reflect.get(value, operation) === 'function');\n}\n\n/**\n * Name-based Workers binding factories. Each takes `{ binding }`, the name\n * declared in the Wrangler configuration, and returns a reference that reads\n * and validates the native binding from an application's `ENV` when called.\n * Declaring one reads no environment, so references belong in static module\n * options: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\n\n/** A KV namespace declared under `kv_namespaces`. */\nexport const KV_NAMESPACE: BindingKind<KVNamespace> = {\n name: 'KV namespace',\n configKey: 'kv_namespaces',\n accepts: (value): value is KVNamespace =>\n hasOperations(value, ['get', 'put', 'delete', 'list', 'getWithMetadata']),\n};\nexport const kv = /* @__PURE__ */ defineBinding(KV_NAMESPACE);\n\n/** An R2 bucket declared under `r2_buckets`. */\nexport const R2_BUCKET: BindingKind<R2Bucket> = {\n name: 'R2 bucket',\n configKey: 'r2_buckets',\n accepts: (value): value is R2Bucket =>\n hasOperations(value, ['get', 'put', 'head', 'delete', 'list', 'createMultipartUpload']),\n};\nexport const r2 = /* @__PURE__ */ defineBinding(R2_BUCKET);\n\n/** A D1 database declared under `d1_databases`. */\nexport const D1_DATABASE: BindingKind<D1Database> = {\n name: 'D1 database',\n configKey: 'd1_databases',\n accepts: (value): value is D1Database => hasOperations(value, ['prepare', 'batch', 'exec']),\n};\nexport const d1 = /* @__PURE__ */ defineBinding(D1_DATABASE);\n\n/** A queue producer declared under `queues.producers`. */\nexport const QUEUE_PRODUCER: BindingKind<Queue> = {\n name: 'queue producer',\n configKey: 'queues.producers',\n accepts: (value): value is Queue => hasOperations(value, ['send']),\n};\nexport const queue = /* @__PURE__ */ defineBinding(QUEUE_PRODUCER);\n\n/** A Durable Object namespace declared under `durable_objects.bindings`. */\nexport const DURABLE_OBJECT_NAMESPACE: BindingKind<DurableObjectNamespace> = {\n name: 'Durable Object namespace',\n configKey: 'durable_objects.bindings',\n accepts: (value): value is DurableObjectNamespace => hasOperations(value, ['idFromName', 'get']),\n};\nexport const durableObject = /* @__PURE__ */ defineBinding(DURABLE_OBJECT_NAMESPACE);\n\n/** A Workers Rate Limiting binding declared under `ratelimits`. */\nexport const RATE_LIMITER: BindingKind<RateLimit> = {\n name: 'rate limiter',\n configKey: 'ratelimits',\n accepts: (value): value is RateLimit => hasOperations(value, ['limit']),\n};\nexport const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);\n\n/**\n * A reference to a Workflow binding declared under `workflows`, whose\n * instances take `Params`: for a class from `VelaWorkflow()`,\n * `workflow<WorkflowParams<SignupWorkflow>>({ binding: 'SIGNUP_WORKFLOW' })`.\n * Called with an application's ENV, it returns the native binding typed with\n * those params: `await signups(env).create({ params: { email } })`. The\n * runtime checks that the binding is a Workflow; its params are what the\n * Workflow class declares.\n */\nexport function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>> {\n return defineBinding<Workflow<Params>>({\n name: 'Workflow',\n configKey: 'workflows',\n accepts: (value): value is Workflow<Params> => hasOperations(value, ['create', 'get']),\n })(ref);\n}\n\n/** A native Flagship binding declared under `flagship`. No flag values are cached. */\nexport const FLAGSHIP: BindingKind<Flagship> = {\n name: 'Flagship',\n configKey: 'flagship',\n accepts: (value): value is Flagship =>\n hasOperations(value, [\n 'get',\n 'getBooleanValue',\n 'getStringValue',\n 'getNumberValue',\n 'getObjectValue',\n 'getBooleanDetails',\n 'getStringDetails',\n 'getNumberDetails',\n 'getObjectDetails',\n ]),\n};\nexport const flagship = /* @__PURE__ */ defineBinding(FLAGSHIP);\n\n/** A secret handle declared under `secrets_store_secrets`; resolve its value with `get()`. */\nexport const SECRETS_STORE_SECRET: BindingKind<SecretsStoreSecret> = {\n name: 'Secrets Store secret',\n configKey: 'secrets_store_secrets',\n accepts: (value): value is SecretsStoreSecret => hasOperations(value, ['get']),\n};\nexport const secretsStoreSecret = /* @__PURE__ */ defineBinding(SECRETS_STORE_SECRET);\n"],"mappings":";;;AAQA,SAAS,cAAc,OAAgB,YAAwC;CAC7E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,WAAW,OAAO,cAAc,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM,UAAU;AAC5F;;;;;;;;;AAWA,MAAa,eAAyC;CACpD,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAU;EAAQ;CAAiB,CAAC;AAC5E;AACA,MAAa,KAAqB,8BAAc,YAAY;;AAG5D,MAAa,YAAmC;CAC9C,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAQ;EAAU;EAAQ;CAAuB,CAAC;AAC1F;AACA,MAAa,KAAqB,8BAAc,SAAS;;AAGzD,MAAa,cAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA+B,cAAc,OAAO;EAAC;EAAW;EAAS;CAAM,CAAC;AAC5F;AACA,MAAa,KAAqB,8BAAc,WAAW;;AAG3D,MAAa,iBAAqC;CAChD,MAAM;CACN,WAAW;CACX,UAAU,UAA0B,cAAc,OAAO,CAAC,MAAM,CAAC;AACnE;AACA,MAAa,QAAwB,8BAAc,cAAc;;AAGjE,MAAa,2BAAgE;CAC3E,MAAM;CACN,WAAW;CACX,UAAU,UAA2C,cAAc,OAAO,CAAC,cAAc,KAAK,CAAC;AACjG;AACA,MAAa,gBAAgC,8BAAc,wBAAwB;;AAGnF,MAAa,eAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA8B,cAAc,OAAO,CAAC,OAAO,CAAC;AACxE;AACA,MAAa,YAA4B,8BAAc,YAAY;;;;;;;;;;AAWnE,SAAgB,SAA2B,KAA4C;CACrF,OAAO,cAAgC;EACrC,MAAM;EACN,WAAW;EACX,UAAU,UAAqC,cAAc,OAAO,CAAC,UAAU,KAAK,CAAC;CACvF,CAAC,CAAC,CAAC,GAAG;AACR;;AAGA,MAAa,WAAkC;CAC7C,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACL;AACA,MAAa,WAA2B,8BAAc,QAAQ;;AAG9D,MAAa,uBAAwD;CACnE,MAAM;CACN,WAAW;CACX,UAAU,UAAuC,cAAc,OAAO,CAAC,KAAK,CAAC;AAC/E;AACA,MAAa,qBAAqC,8BAAc,oBAAoB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CorsOptions, InjectionToken, VelaApplication, VelaEnv } from "@velajs/vela";
|
|
2
2
|
import "@velajs/vela/module-kit";
|
|
3
|
-
import { ExecutionContext } from "hono";
|
|
3
|
+
import { ExecutionContext as ExecutionContext$1 } from "hono";
|
|
4
4
|
//#region src/scheduled-event.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* The event a Worker's `scheduled()` export receives. The native
|
|
@@ -97,7 +97,7 @@ declare class CloudflareApplication {
|
|
|
97
97
|
#private;
|
|
98
98
|
readonly env: VelaEnv;
|
|
99
99
|
constructor(app: VelaApplication, env: VelaEnv);
|
|
100
|
-
readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext) => Promise<Response>;
|
|
100
|
+
readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext$1) => Promise<Response>;
|
|
101
101
|
getHonoApp(): ReturnType<VelaApplication['getHonoApp']>;
|
|
102
102
|
/**
|
|
103
103
|
* Resolve a provider from the application's DI container (delegates to
|
|
@@ -250,7 +250,7 @@ var CloudflareApplication = class {
|
|
|
250
250
|
const raw = this.#app.entrypoints.ofKind("cf:queue").filter((ep) => entrypointString(ep.meta, "queueName") === batch.queue);
|
|
251
251
|
if (raw.length > 0) this.warnRawJobs(batch);
|
|
252
252
|
const handlers = raw.length > 0 ? raw : this.#app.entrypoints.ofKind("cf:queue:module");
|
|
253
|
-
if (handlers.length === 0) throw new Error(`No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) with a QueueModule.
|
|
253
|
+
if (handlers.length === 0) throw new Error(`No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) with a QueueModule.forFeature([]) for each queue it carries. The batch is rejected unacknowledged, so Cloudflare retries it and then routes it to the configured dead-letter queue.`);
|
|
254
254
|
await settleEntrypoints(handlers.map((ep) => this.dispatchEntrypoint(ep, batch, env, ctx)));
|
|
255
255
|
}
|
|
256
256
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-application.js","names":[],"sources":["../src/cloudflare-application.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport type { CorsOptions, VelaApplication, ExceptionFilter, VelaEnv } from '@velajs/vela';\nimport {\n PipelineRunner,\n buildEntrypointExecutionContext,\n getEntrypointModuleId,\n invokeScheduledJob,\n parseCronMetadata,\n resolveEntrypoint,\n resolveScopedComponentsAsync,\n resolveErrorReporter,\n runInEntrypointScope,\n shouldFilterCatch,\n} from '@velajs/vela/module-kit';\nimport type { ScheduleInvocation } from '@velajs/vela/schedule';\nimport type { Entrypoint } from '@velajs/vela/module-kit';\nimport { assertCloudflareEnvironment } from './environment';\nimport {\n CLOUDFLARE_SCHEDULED_EVENT,\n cloudflareScheduledEvent,\n type ScheduledEvent,\n} from './scheduled-event';\n\n/**\n * Options accepted by {@link CloudflareApplication.mountOpenApi}.\n *\n * Re-exposes vela's `MountOpenApiOptions` type — derived structurally from\n * the underlying `VelaApplication.mountOpenApi` signature so consumers don't\n * have to reach into vela's internal subpaths to type the argument.\n */\nexport type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];\n\nfunction invoke(instance: object, methodName: string | symbol, args: unknown[]): unknown {\n // Decorator metadata names an instance method; inspect it before invoking.\n const method: unknown = Reflect.get(instance, methodName);\n if (typeof method !== 'function') {\n throw new Error(\n `Method '${String(methodName)}' is not a function on ${instance.constructor.name}`,\n );\n }\n return Reflect.apply(method, instance, args);\n}\n\nfunction entrypointString(meta: unknown, property: string): string {\n if (typeof meta !== 'object' || meta === null) throw new Error('Invalid entrypoint metadata.');\n const value: unknown = Reflect.get(meta, property);\n if (typeof value !== 'string')\n throw new Error(`Invalid entrypoint metadata: ${property} must be a string.`);\n return value;\n}\n\n/**\n * `QueueModule`'s native consumer reports each failure of a batch once itself\n * (processor failures where they ran, transport failures on settlement), so\n * its rejection is not reported again here.\n */\nconst SELF_REPORTING_KINDS = new Set(['cf:queue:module']);\n\nconst warnedRawJobs = new Set<string>();\n\n/** The logical queue of a Vela job envelope, without importing the queue subsystem. */\nfunction envelopeQueue(body: unknown): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined;\n const queue: unknown = Reflect.get(body, 'queue');\n if (\n typeof queue !== 'string' ||\n typeof Reflect.get(body, 'id') !== 'string' ||\n typeof Reflect.get(body, 'name') !== 'string' ||\n !('data' in body)\n ) {\n return undefined;\n }\n return queue;\n}\n\n/** Wait for every matching handler, even when one fails before its siblings. */\nasync function settleEntrypoints(work: readonly Promise<void>[]): Promise<void> {\n const outcomes = await Promise.allSettled(work);\n const errors = outcomes.flatMap((outcome) =>\n outcome.status === 'rejected' ? [outcome.reason] : [],\n );\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Multiple entrypoint handlers failed.');\n}\n\n/**\n * Wraps VelaApplication with Cloudflare-specific handlers:\n * - `fetch` — HTTP request handler (from Hono)\n * - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose\n * expression is the trigger's exact string)\n * - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,\n * then `QueueModule`'s native consumer)\n * - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on\n * the underlying Hono app\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * export default {\n * fetch: app.fetch,\n * scheduled: app.scheduled.bind(app),\n * queue: app.queue.bind(app),\n * };\n * ```\n *\n * @example\n * ```ts\n * // Serve OpenAPI docs alongside your routes\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule);\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> JSON document\n * // GET /scalar -> Scalar UI (loads from CDN)\n * ```\n */\nexport class CloudflareApplication {\n readonly #app: VelaApplication;\n /** Scheduled triggers in flight; close() aborts their signals and awaits them. */\n readonly #scheduled = new Map<Promise<void>, AbortController>();\n\n constructor(\n app: VelaApplication,\n readonly env: VelaEnv,\n ) {\n this.#app = app;\n this.get = app.get.bind(app);\n }\n\n readonly fetch = async (\n request: Request,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ): Promise<Response> => {\n assertCloudflareEnvironment(this.env, env);\n return this.#app.fetch(request, env, ctx);\n };\n\n getHonoApp(): ReturnType<VelaApplication['getHonoApp']> {\n return this.#app.getHonoApp();\n }\n\n /**\n * Resolve a provider from the application's DI container (delegates to\n * `VelaApplication.get`). Handy in `createCloudflareWorker({ configure })`,\n * which finishes the HTTP surface outside the DI request pipeline.\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * const auth = app.get(BetterAuthService);\n * ```\n */\n readonly get: VelaApplication['get'];\n\n get entrypoints(): VelaApplication['entrypoints'] {\n return this.#app.entrypoints;\n }\n\n /**\n * The application's DI container (delegates to `VelaApplication.getContainer`),\n * for dispatch seams that take it with `entrypoints`, such as\n * `dispatchInboundEmail(app.getContainer(), app.entrypoints, email)`.\n */\n getContainer(): ReturnType<VelaApplication['getContainer']> {\n return this.#app.getContainer();\n }\n\n /** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */\n enableCors(options?: CorsOptions): this {\n this.#app.enableCors(options);\n return this;\n }\n\n /**\n * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the\n * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,\n * so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when\n * opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from\n * a CDN at runtime, nothing is bundled server-side.\n *\n * @example\n * ```ts\n * import { createOpenApiDocument } from '@velajs/vela/openapi';\n *\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule, {\n * info: { title: 'My API', version: '1.0.0' },\n * });\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> { openapi: '3.1.0', ... }\n * // GET /scalar -> Scalar UI HTML\n * ```\n */\n mountOpenApi(options: MountOpenApiOptions): this {\n this.#app.mountOpenApi(options);\n return this;\n }\n\n /**\n * Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose\n * expression is exactly `event.cron` (the trigger string is compared as\n * delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch\n * primitive every runtime shares. Each job receives only its\n * `ScheduleInvocation`, runs in a fresh invocation scope seeded with\n * {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`\n * dispatch. The trigger settles after every matching job and its managed\n * work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.\n */\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n _ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const jobs = this.#app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .filter((entry) => entry.meta.expression === event.cron);\n if (jobs.length === 0) return;\n\n const controller = new AbortController();\n const scheduledTime = event.scheduledTime ?? Date.now();\n // Shared by every matching job, so none of them can alter what another sees.\n const invocation: ScheduleInvocation = Object.freeze({\n kind: 'cron' as const,\n expression: event.cron,\n scheduledTime,\n signal: controller.signal,\n });\n const trigger = cloudflareScheduledEvent(event, scheduledTime);\n const container = this.#app.getContainer();\n const running = settleEntrypoints(\n jobs.map((entry) =>\n invokeScheduledJob(container, entry, invocation, {\n seed: (scope) => scope.setRequestInstance(CLOUDFLARE_SCHEDULED_EVENT, trigger),\n }),\n ),\n );\n this.#scheduled.set(running, controller);\n try {\n await running;\n } finally {\n this.#scheduled.delete(running);\n }\n }\n\n /**\n * Run one queue consumer inside a fresh request scope, through the shared\n * guard → interceptor pipeline (components declared with\n * `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or\n * method). HTTP-global components deliberately do NOT apply — an HTTP auth\n * guard has no business rejecting a queue batch. Unclaimed errors are\n * reported once (`QueueModule`'s consumer reports its own) and rethrow so\n * the platform's retry semantics stay intact.\n */\n private async dispatchEntrypoint(\n ep: Entrypoint,\n payload: unknown,\n env: VelaEnv,\n platformContext: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n const targetClass = ep.token;\n if (typeof targetClass !== 'function') throw new Error('Entrypoint token must be a class.');\n if (ep.methodName === undefined) throw new Error('Entrypoint must declare a handler method.');\n const methodName = ep.methodName;\n const reportContext = {\n edge: 'queue' as const,\n source: `${targetClass.name}.${String(methodName)}`,\n };\n let reported: { error: unknown } | undefined;\n // A self-reporting handler's own rejection was already reported.\n let delegated: { error: unknown } | undefined;\n try {\n await runInEntrypointScope(this.#app.getContainer(), async (scope, lifetime) => {\n const moduleId = getEntrypointModuleId(scope, ep);\n const context = buildEntrypointExecutionContext(\n ep.kind,\n targetClass,\n methodName,\n payload,\n moduleId,\n scope,\n );\n const invocationContext = {\n waitUntil(promise: Promise<unknown>): void {\n lifetime.waitUntil(promise);\n platformContext.waitUntil(promise);\n },\n };\n let filters: ExceptionFilter[] = [];\n try {\n filters = (\n await resolveScopedComponentsAsync('filter', targetClass, methodName, scope, moduleId)\n ).toReversed();\n const guards = await resolveScopedComponentsAsync(\n 'guard',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n const interceptors = await resolveScopedComponentsAsync(\n 'interceptor',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n await PipelineRunner.run({\n context,\n guards,\n interceptors,\n resolveArgs: async () => [payload, env, invocationContext],\n invoke: async (args) => {\n const instance = await resolveEntrypoint(scope, ep);\n if (typeof instance !== 'object' || instance === null) {\n throw new Error('Entrypoint must resolve to an object.');\n }\n try {\n return await invoke(instance, methodName, args);\n } catch (error) {\n if (SELF_REPORTING_KINDS.has(ep.kind)) delegated = { error };\n throw error;\n }\n },\n });\n } catch (error) {\n if (delegated?.error !== error) {\n resolveErrorReporter(scope).report(error, reportContext);\n }\n for (const filter of filters) {\n if (shouldFilterCatch(filter, error)) {\n // Filters run closest-first; this is the framework catch hook.\n // eslint-disable-next-line no-await-in-loop, promise/valid-params\n await filter.catch(error, context);\n return;\n }\n }\n reported = { error };\n throw error;\n }\n });\n } catch (error) {\n // Managed completion happens after the handler's filter boundary. Report\n // a new completion failure without reporting an already-observed handler\n // failure twice; preserve both errors in the rejected invocation.\n if (!reported || reported.error !== error) {\n const completionError =\n reported && error instanceof AggregateError && error.errors[0] === reported.error\n ? error.errors[1]\n : error;\n resolveErrorReporter(this.#app.getContainer()).report(completionError, reportContext);\n }\n throw error;\n }\n }\n\n /**\n * Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read\n * from `app.entrypoints` claim a batch by its physical queue name and\n * receive it whole. A batch no handler claims goes to `QueueModule`'s native\n * consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which\n * routes each job by its logical queue. Each dispatch runs inside a fresh\n * request-scoped child (request-scoped providers rebuild per batch — no\n * boot-time captives). A batch nothing claims rejects: resolving would let\n * Cloudflare acknowledge every message implicitly.\n */\n async queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const raw = this.#app.entrypoints\n .ofKind('cf:queue')\n .filter((ep) => entrypointString(ep.meta, 'queueName') === batch.queue);\n if (raw.length > 0) this.warnRawJobs(batch);\n const handlers = raw.length > 0 ? raw : this.#app.entrypoints.ofKind('cf:queue:module');\n\n if (handlers.length === 0) {\n throw new Error(\n `No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a ` +\n `provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) ` +\n `with a QueueModule.registerQueue() for each queue it carries. The batch is rejected ` +\n `unacknowledged, so Cloudflare retries it and then routes it to the configured ` +\n `dead-letter queue.`,\n );\n }\n\n await settleEntrypoints(handlers.map((ep) => this.dispatchEntrypoint(ep, batch, env, ctx)));\n }\n\n /**\n * A raw `@QueueConsumer` owns its physical queue's batches and must not carry\n * jobs of a queue registered with `QueueModule`: those reach their\n * `@Processor` only if the raw handler dispatches them itself, while\n * `cloudflareQueues()` delivers registered queues. Warn once per physical and\n * logical queue (unless diagnostics are silent); the raw consumer still\n * receives and settles the batch.\n */\n private warnRawJobs(batch: { queue: string; messages: readonly unknown[] }): void {\n if (this.#app.getContainer().getDiagnostics() === 'silent') return;\n const registered = new Set(\n this.#app.entrypoints\n .ofKind('queue:registration')\n .map((entry) =>\n typeof entry.meta === 'object' && entry.meta !== null\n ? Reflect.get(entry.meta, 'name')\n : undefined,\n ),\n );\n if (registered.size === 0) return;\n for (const message of batch.messages) {\n const body =\n typeof message === 'object' && message !== null ? Reflect.get(message, 'body') : undefined;\n const queue = envelopeQueue(body);\n if (queue === undefined || !registered.has(queue)) continue;\n const warning =\n `[vela] @QueueConsumer('${batch.queue}') received jobs of registered queue '${queue}'. ` +\n `The raw consumer owns '${batch.queue}' and must not carry jobs of registered queues: ` +\n `they reach @Processor('${queue}') only if the raw handler dispatches them itself. ` +\n `Deliver '${queue}' through cloudflareQueues() instead: send it to a physical queue ` +\n `that no @QueueConsumer claims.`;\n if (warnedRawJobs.has(warning)) continue;\n warnedRawJobs.add(warning);\n console.warn(warning);\n }\n }\n\n /**\n * Abort the signals of scheduled jobs still running, wait for them and their\n * managed work to settle, then close the application.\n */\n async close(signal?: string): Promise<void> {\n for (const controller of this.#scheduled.values()) controller.abort();\n await Promise.allSettled(this.#scheduled.keys());\n return this.#app.close(signal);\n }\n}\n"],"mappings":";;;;AAgCA,SAAS,OAAO,UAAkB,YAA6B,MAA0B;CAEvF,MAAM,SAAkB,QAAQ,IAAI,UAAU,UAAU;CACxD,IAAI,OAAO,WAAW,YACpB,MAAM,IAAI,MACR,WAAW,OAAO,UAAU,EAAE,yBAAyB,SAAS,YAAY,MAC9E;CAEF,OAAO,QAAQ,MAAM,QAAQ,UAAU,IAAI;AAC7C;AAEA,SAAS,iBAAiB,MAAe,UAA0B;CACjE,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,MAAM,IAAI,MAAM,8BAA8B;CAC7F,MAAM,QAAiB,QAAQ,IAAI,MAAM,QAAQ;CACjD,IAAI,OAAO,UAAU,UACnB,MAAM,IAAI,MAAM,gCAAgC,SAAS,mBAAmB;CAC9E,OAAO;AACT;;;;;;AAOA,MAAM,uCAAuB,IAAI,IAAI,CAAC,iBAAiB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C,KAAK,MAAM,cAAc,KAAK,WAAW,OAAO,GAAG,WAAW,MAAM;EACpE,MAAM,QAAQ,WAAW,KAAK,WAAW,KAAK,CAAC;EAC/C,OAAO,KAAK,KAAK,MAAM,MAAM;CAC/B;AACF"}
|
|
1
|
+
{"version":3,"file":"cloudflare-application.js","names":[],"sources":["../src/cloudflare-application.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport type { CorsOptions, VelaApplication, ExceptionFilter, VelaEnv } from '@velajs/vela';\nimport {\n PipelineRunner,\n buildEntrypointExecutionContext,\n getEntrypointModuleId,\n invokeScheduledJob,\n parseCronMetadata,\n resolveEntrypoint,\n resolveScopedComponentsAsync,\n resolveErrorReporter,\n runInEntrypointScope,\n shouldFilterCatch,\n} from '@velajs/vela/module-kit';\nimport type { ScheduleInvocation } from '@velajs/vela/schedule';\nimport type { Entrypoint } from '@velajs/vela/module-kit';\nimport { assertCloudflareEnvironment } from './environment';\nimport {\n CLOUDFLARE_SCHEDULED_EVENT,\n cloudflareScheduledEvent,\n type ScheduledEvent,\n} from './scheduled-event';\n\n/**\n * Options accepted by {@link CloudflareApplication.mountOpenApi}.\n *\n * Re-exposes vela's `MountOpenApiOptions` type — derived structurally from\n * the underlying `VelaApplication.mountOpenApi` signature so consumers don't\n * have to reach into vela's internal subpaths to type the argument.\n */\nexport type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];\n\nfunction invoke(instance: object, methodName: string | symbol, args: unknown[]): unknown {\n // Decorator metadata names an instance method; inspect it before invoking.\n const method: unknown = Reflect.get(instance, methodName);\n if (typeof method !== 'function') {\n throw new Error(\n `Method '${String(methodName)}' is not a function on ${instance.constructor.name}`,\n );\n }\n return Reflect.apply(method, instance, args);\n}\n\nfunction entrypointString(meta: unknown, property: string): string {\n if (typeof meta !== 'object' || meta === null) throw new Error('Invalid entrypoint metadata.');\n const value: unknown = Reflect.get(meta, property);\n if (typeof value !== 'string')\n throw new Error(`Invalid entrypoint metadata: ${property} must be a string.`);\n return value;\n}\n\n/**\n * `QueueModule`'s native consumer reports each failure of a batch once itself\n * (processor failures where they ran, transport failures on settlement), so\n * its rejection is not reported again here.\n */\nconst SELF_REPORTING_KINDS = new Set(['cf:queue:module']);\n\nconst warnedRawJobs = new Set<string>();\n\n/** The logical queue of a Vela job envelope, without importing the queue subsystem. */\nfunction envelopeQueue(body: unknown): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined;\n const queue: unknown = Reflect.get(body, 'queue');\n if (\n typeof queue !== 'string' ||\n typeof Reflect.get(body, 'id') !== 'string' ||\n typeof Reflect.get(body, 'name') !== 'string' ||\n !('data' in body)\n ) {\n return undefined;\n }\n return queue;\n}\n\n/** Wait for every matching handler, even when one fails before its siblings. */\nasync function settleEntrypoints(work: readonly Promise<void>[]): Promise<void> {\n const outcomes = await Promise.allSettled(work);\n const errors = outcomes.flatMap((outcome) =>\n outcome.status === 'rejected' ? [outcome.reason] : [],\n );\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Multiple entrypoint handlers failed.');\n}\n\n/**\n * Wraps VelaApplication with Cloudflare-specific handlers:\n * - `fetch` — HTTP request handler (from Hono)\n * - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose\n * expression is the trigger's exact string)\n * - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,\n * then `QueueModule`'s native consumer)\n * - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on\n * the underlying Hono app\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * export default {\n * fetch: app.fetch,\n * scheduled: app.scheduled.bind(app),\n * queue: app.queue.bind(app),\n * };\n * ```\n *\n * @example\n * ```ts\n * // Serve OpenAPI docs alongside your routes\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule);\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> JSON document\n * // GET /scalar -> Scalar UI (loads from CDN)\n * ```\n */\nexport class CloudflareApplication {\n readonly #app: VelaApplication;\n /** Scheduled triggers in flight; close() aborts their signals and awaits them. */\n readonly #scheduled = new Map<Promise<void>, AbortController>();\n\n constructor(\n app: VelaApplication,\n readonly env: VelaEnv,\n ) {\n this.#app = app;\n this.get = app.get.bind(app);\n }\n\n readonly fetch = async (\n request: Request,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ): Promise<Response> => {\n assertCloudflareEnvironment(this.env, env);\n return this.#app.fetch(request, env, ctx);\n };\n\n getHonoApp(): ReturnType<VelaApplication['getHonoApp']> {\n return this.#app.getHonoApp();\n }\n\n /**\n * Resolve a provider from the application's DI container (delegates to\n * `VelaApplication.get`). Handy in `createCloudflareWorker({ configure })`,\n * which finishes the HTTP surface outside the DI request pipeline.\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * const auth = app.get(BetterAuthService);\n * ```\n */\n readonly get: VelaApplication['get'];\n\n get entrypoints(): VelaApplication['entrypoints'] {\n return this.#app.entrypoints;\n }\n\n /**\n * The application's DI container (delegates to `VelaApplication.getContainer`),\n * for dispatch seams that take it with `entrypoints`, such as\n * `dispatchInboundEmail(app.getContainer(), app.entrypoints, email)`.\n */\n getContainer(): ReturnType<VelaApplication['getContainer']> {\n return this.#app.getContainer();\n }\n\n /** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */\n enableCors(options?: CorsOptions): this {\n this.#app.enableCors(options);\n return this;\n }\n\n /**\n * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the\n * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,\n * so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when\n * opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from\n * a CDN at runtime, nothing is bundled server-side.\n *\n * @example\n * ```ts\n * import { createOpenApiDocument } from '@velajs/vela/openapi';\n *\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule, {\n * info: { title: 'My API', version: '1.0.0' },\n * });\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> { openapi: '3.1.0', ... }\n * // GET /scalar -> Scalar UI HTML\n * ```\n */\n mountOpenApi(options: MountOpenApiOptions): this {\n this.#app.mountOpenApi(options);\n return this;\n }\n\n /**\n * Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose\n * expression is exactly `event.cron` (the trigger string is compared as\n * delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch\n * primitive every runtime shares. Each job receives only its\n * `ScheduleInvocation`, runs in a fresh invocation scope seeded with\n * {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`\n * dispatch. The trigger settles after every matching job and its managed\n * work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.\n */\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n _ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const jobs = this.#app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .filter((entry) => entry.meta.expression === event.cron);\n if (jobs.length === 0) return;\n\n const controller = new AbortController();\n const scheduledTime = event.scheduledTime ?? Date.now();\n // Shared by every matching job, so none of them can alter what another sees.\n const invocation: ScheduleInvocation = Object.freeze({\n kind: 'cron' as const,\n expression: event.cron,\n scheduledTime,\n signal: controller.signal,\n });\n const trigger = cloudflareScheduledEvent(event, scheduledTime);\n const container = this.#app.getContainer();\n const running = settleEntrypoints(\n jobs.map((entry) =>\n invokeScheduledJob(container, entry, invocation, {\n seed: (scope) => scope.setRequestInstance(CLOUDFLARE_SCHEDULED_EVENT, trigger),\n }),\n ),\n );\n this.#scheduled.set(running, controller);\n try {\n await running;\n } finally {\n this.#scheduled.delete(running);\n }\n }\n\n /**\n * Run one queue consumer inside a fresh request scope, through the shared\n * guard → interceptor pipeline (components declared with\n * `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or\n * method). HTTP-global components deliberately do NOT apply — an HTTP auth\n * guard has no business rejecting a queue batch. Unclaimed errors are\n * reported once (`QueueModule`'s consumer reports its own) and rethrow so\n * the platform's retry semantics stay intact.\n */\n private async dispatchEntrypoint(\n ep: Entrypoint,\n payload: unknown,\n env: VelaEnv,\n platformContext: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n const targetClass = ep.token;\n if (typeof targetClass !== 'function') throw new Error('Entrypoint token must be a class.');\n if (ep.methodName === undefined) throw new Error('Entrypoint must declare a handler method.');\n const methodName = ep.methodName;\n const reportContext = {\n edge: 'queue' as const,\n source: `${targetClass.name}.${String(methodName)}`,\n };\n let reported: { error: unknown } | undefined;\n // A self-reporting handler's own rejection was already reported.\n let delegated: { error: unknown } | undefined;\n try {\n await runInEntrypointScope(this.#app.getContainer(), async (scope, lifetime) => {\n const moduleId = getEntrypointModuleId(scope, ep);\n const context = buildEntrypointExecutionContext(\n ep.kind,\n targetClass,\n methodName,\n payload,\n moduleId,\n scope,\n );\n const invocationContext = {\n waitUntil(promise: Promise<unknown>): void {\n lifetime.waitUntil(promise);\n platformContext.waitUntil(promise);\n },\n };\n let filters: ExceptionFilter[] = [];\n try {\n filters = (\n await resolveScopedComponentsAsync('filter', targetClass, methodName, scope, moduleId)\n ).toReversed();\n const guards = await resolveScopedComponentsAsync(\n 'guard',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n const interceptors = await resolveScopedComponentsAsync(\n 'interceptor',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n await PipelineRunner.run({\n context,\n guards,\n interceptors,\n resolveArgs: async () => [payload, env, invocationContext],\n invoke: async (args) => {\n const instance = await resolveEntrypoint(scope, ep);\n if (typeof instance !== 'object' || instance === null) {\n throw new Error('Entrypoint must resolve to an object.');\n }\n try {\n return await invoke(instance, methodName, args);\n } catch (error) {\n if (SELF_REPORTING_KINDS.has(ep.kind)) delegated = { error };\n throw error;\n }\n },\n });\n } catch (error) {\n if (delegated?.error !== error) {\n resolveErrorReporter(scope).report(error, reportContext);\n }\n for (const filter of filters) {\n if (shouldFilterCatch(filter, error)) {\n // Filters run closest-first; this is the framework catch hook.\n // eslint-disable-next-line no-await-in-loop, promise/valid-params\n await filter.catch(error, context);\n return;\n }\n }\n reported = { error };\n throw error;\n }\n });\n } catch (error) {\n // Managed completion happens after the handler's filter boundary. Report\n // a new completion failure without reporting an already-observed handler\n // failure twice; preserve both errors in the rejected invocation.\n if (!reported || reported.error !== error) {\n const completionError =\n reported && error instanceof AggregateError && error.errors[0] === reported.error\n ? error.errors[1]\n : error;\n resolveErrorReporter(this.#app.getContainer()).report(completionError, reportContext);\n }\n throw error;\n }\n }\n\n /**\n * Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read\n * from `app.entrypoints` claim a batch by its physical queue name and\n * receive it whole. A batch no handler claims goes to `QueueModule`'s native\n * consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which\n * routes each job by its logical queue. Each dispatch runs inside a fresh\n * request-scoped child (request-scoped providers rebuild per batch — no\n * boot-time captives). A batch nothing claims rejects: resolving would let\n * Cloudflare acknowledge every message implicitly.\n */\n async queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const raw = this.#app.entrypoints\n .ofKind('cf:queue')\n .filter((ep) => entrypointString(ep.meta, 'queueName') === batch.queue);\n if (raw.length > 0) this.warnRawJobs(batch);\n const handlers = raw.length > 0 ? raw : this.#app.entrypoints.ofKind('cf:queue:module');\n\n if (handlers.length === 0) {\n throw new Error(\n `No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a ` +\n `provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) ` +\n `with a QueueModule.forFeature([]) for each queue it carries. The batch is rejected ` +\n `unacknowledged, so Cloudflare retries it and then routes it to the configured ` +\n `dead-letter queue.`,\n );\n }\n\n await settleEntrypoints(handlers.map((ep) => this.dispatchEntrypoint(ep, batch, env, ctx)));\n }\n\n /**\n * A raw `@QueueConsumer` owns its physical queue's batches and must not carry\n * jobs of a queue registered with `QueueModule`: those reach their\n * `@Processor` only if the raw handler dispatches them itself, while\n * `cloudflareQueues()` delivers registered queues. Warn once per physical and\n * logical queue (unless diagnostics are silent); the raw consumer still\n * receives and settles the batch.\n */\n private warnRawJobs(batch: { queue: string; messages: readonly unknown[] }): void {\n if (this.#app.getContainer().getDiagnostics() === 'silent') return;\n const registered = new Set(\n this.#app.entrypoints\n .ofKind('queue:registration')\n .map((entry) =>\n typeof entry.meta === 'object' && entry.meta !== null\n ? Reflect.get(entry.meta, 'name')\n : undefined,\n ),\n );\n if (registered.size === 0) return;\n for (const message of batch.messages) {\n const body =\n typeof message === 'object' && message !== null ? Reflect.get(message, 'body') : undefined;\n const queue = envelopeQueue(body);\n if (queue === undefined || !registered.has(queue)) continue;\n const warning =\n `[vela] @QueueConsumer('${batch.queue}') received jobs of registered queue '${queue}'. ` +\n `The raw consumer owns '${batch.queue}' and must not carry jobs of registered queues: ` +\n `they reach @Processor('${queue}') only if the raw handler dispatches them itself. ` +\n `Deliver '${queue}' through cloudflareQueues() instead: send it to a physical queue ` +\n `that no @QueueConsumer claims.`;\n if (warnedRawJobs.has(warning)) continue;\n warnedRawJobs.add(warning);\n console.warn(warning);\n }\n }\n\n /**\n * Abort the signals of scheduled jobs still running, wait for them and their\n * managed work to settle, then close the application.\n */\n async close(signal?: string): Promise<void> {\n for (const controller of this.#scheduled.values()) controller.abort();\n await Promise.allSettled(this.#scheduled.keys());\n return this.#app.close(signal);\n }\n}\n"],"mappings":";;;;AAgCA,SAAS,OAAO,UAAkB,YAA6B,MAA0B;CAEvF,MAAM,SAAkB,QAAQ,IAAI,UAAU,UAAU;CACxD,IAAI,OAAO,WAAW,YACpB,MAAM,IAAI,MACR,WAAW,OAAO,UAAU,EAAE,yBAAyB,SAAS,YAAY,MAC9E;CAEF,OAAO,QAAQ,MAAM,QAAQ,UA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I,KAAA,CACnD;GAChC,IAAI,UAAU,KAAA,KAAa,CAAC,WAAW,IAAI,KAAK,GAAG;GACnD,MAAM,UACJ,0BAA0B,MAAM,MAAM,wCAAwC,MAAM,4BAC1D,MAAM,MAAM,yEACZ,MAAM,8DACpB,MAAM;GAEpB,IAAI,cAAc,IAAI,OAAO,GAAG;GAChC,cAAc,IAAI,OAAO;GACzB,QAAQ,KAAK,OAAO;EACtB;CACF;;;;;CAMA,MAAM,MAAM,QAAgC;EAC1C,KAAK,MAAM,cAAc,KAAK,WAAW,OAAO,GAAG,WAAW,MAAM;EACpE,MAAM,QAAQ,WAAW,KAAK,WAAW,KAAK,CAAC;EAC/C,OAAO,KAAK,KAAK,MAAM,MAAM;CAC/B;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as ScheduledEvent, t as CloudflareApplication } from "./cloudflare-application-
|
|
1
|
+
import { a as ScheduledEvent, t as CloudflareApplication } from "./cloudflare-application-Dsscb3Mo.js";
|
|
2
2
|
import { CorsOptions, DynamicModule, GlobalPrefixOptions, Type, VelaApplication, VelaCreateOptions, VelaEnv, VelaSecurityOptions, VersioningOptions } from "@velajs/vela";
|
|
3
3
|
import { RuntimeAdapter } from "@velajs/vela/module-kit";
|
|
4
|
-
import { ExecutionContext } from "hono";
|
|
4
|
+
import { ExecutionContext as ExecutionContext$1 } from "hono";
|
|
5
5
|
//#region src/root-module.d.ts
|
|
6
6
|
/**
|
|
7
7
|
* The root a Worker or Durable Object is built from: a module class or a
|
|
@@ -149,7 +149,7 @@ interface CloudflareWorkerDescriptor {
|
|
|
149
149
|
}
|
|
150
150
|
/** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */
|
|
151
151
|
interface CloudflareWorker {
|
|
152
|
-
fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
|
|
152
|
+
fetch(request: Request, env: VelaEnv, ctx: ExecutionContext$1): Promise<Response>;
|
|
153
153
|
scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
|
|
154
154
|
waitUntil: (promise: Promise<unknown>) => void;
|
|
155
155
|
}): Promise<void>;
|
|
@@ -164,14 +164,14 @@ interface CloudflareWorker {
|
|
|
164
164
|
* `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`
|
|
165
165
|
* handlers, and rejects a message none of them accepts.
|
|
166
166
|
*/
|
|
167
|
-
readonly email?: (message: ForwardableEmailMessage, env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
|
|
167
|
+
readonly email?: (message: ForwardableEmailMessage, env: VelaEnv, ctx?: ExecutionContext$1) => Promise<void>;
|
|
168
168
|
/**
|
|
169
169
|
* The Tail Workers handler, present once a module imports `OnTail` from
|
|
170
170
|
* `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers
|
|
171
171
|
* and never rejects, even when the application fails to start (the error is
|
|
172
172
|
* logged to the console, and the next batch retries).
|
|
173
173
|
*/
|
|
174
|
-
readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
|
|
174
|
+
readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext$1) => Promise<void>;
|
|
175
175
|
/**
|
|
176
176
|
* Symbol-keyed, so the platform, which reads string-keyed handlers, ignores
|
|
177
177
|
* it; enumerable, so `{ ...worker, email }` keeps it for the CLI.
|
|
@@ -25,7 +25,7 @@ function assertQueueConsumerOwnership(entrypoints) {
|
|
|
25
25
|
const pinned = new Set(entrypoints.ofKind("cf:queue:module").flatMap((entry) => readStrings(entry.meta, "consumers")));
|
|
26
26
|
for (const entry of entrypoints.ofKind("cf:queue")) {
|
|
27
27
|
const [queue] = readStrings(entry.meta, "queueName");
|
|
28
|
-
if (queue !== void 0 && pinned.has(queue)) throw new Error(`Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a QueueModule.
|
|
28
|
+
if (queue !== void 0 && pinned.has(queue)) throw new Error(`Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a QueueModule.forFeature([{ consumer: '${queue}' }]) both claim it. Keep one owner.`);
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
31
|
/**
|