@moku-labs/worker 0.1.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.
@@ -0,0 +1,962 @@
1
+ import { n as WorkerEnv, r as WorkerEvents, t as WorkerConfig } from "./config-AjH57AmD.cjs";
2
+ import { PluginCtx, PluginInstance } from "@moku-labs/core";
3
+ import { envPlugin, logPlugin } from "@moku-labs/common";
4
+
5
+ //#region \0rolldown/runtime.js
6
+ //#endregion
7
+ //#region src/plugins/bindings/index.d.ts
8
+ /**
9
+ * bindings config. Flat (spec/05 §3,§6) — a complete default so omission
10
+ * never yields undefined.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * { required: ["MY_KV", "DB"] }
15
+ * ```
16
+ */
17
+ type Config$4 = {
18
+ required: string[];
19
+ };
20
+ /**
21
+ * The app.bindings surface — a stateless resolver over a request-supplied env.
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const kv = app.bindings.require<KVNamespace>(env, "MY_KV");
26
+ * const ok = app.bindings.has(env, "DB");
27
+ * ```
28
+ */
29
+ type BindingsApi = {
30
+ /**
31
+ * Resolve binding `name` off the request-supplied env, narrowed to T.
32
+ *
33
+ * @param env - The Cloudflare request env object.
34
+ * @param name - The binding name to resolve.
35
+ * @returns The binding value narrowed to T.
36
+ * @throws {Error} With a `[moku-worker]` prefix when the binding is nullish.
37
+ */
38
+ require<T>(env: WorkerEnv, name: string): T;
39
+ /**
40
+ * True when `name` resolves to a non-nullish value on the request-supplied env.
41
+ *
42
+ * @param env - The Cloudflare request env object.
43
+ * @param name - The binding name to check.
44
+ * @returns Whether the binding is present and non-nullish.
45
+ */
46
+ has(env: WorkerEnv, name: string): boolean;
47
+ };
48
+ /**
49
+ * Micro-tier stateless resolver — the binding-family dependency root.
50
+ *
51
+ * Exposes `require<T>(env, name)` and `has(env, name)` off a per-request env
52
+ * object. Regular plugin so downstream binding plugins can declare
53
+ * `depends: [bindingsPlugin]` and reach it via `ctx.require(bindingsPlugin)`.
54
+ *
55
+ * @see README.md
56
+ */
57
+ declare const bindingsPlugin: import("@moku-labs/core").PluginInstance<"bindings", Config$4, Record<string, never>, BindingsApi, {}> & Record<never, never>;
58
+ declare namespace types_d_exports$3 {
59
+ export { Api$3 as Api, CompiledEndpoint, Endpoint, EndpointHandler, MatchResult, Method, PathSegment, RequestContext, RequireFn, ServerConfig, ServerCtx, ServerEvents, ServerState };
60
+ }
61
+ /** HTTP method an endpoint matches; "ALL" matches any verb. */
62
+ type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS" | "ALL";
63
+ /** One parsed path segment: a literal, a required `{name}`, or an optional `{name?}`. */
64
+ type PathSegment = {
65
+ /** The literal text, or the param name when a param. */readonly value: string; /** Whether this segment is a `{name}` / `{name?}` parameter. */
66
+ readonly param: boolean; /** Whether the param is optional (`{name?}`). */
67
+ readonly optional: boolean;
68
+ };
69
+ /** A declarative endpoint produced by the pure endpoint() builder. */
70
+ type Endpoint = {
71
+ /** Endpoint path, optionally with `{name}` / `{name?}` params. */readonly path: string; /** HTTP method or "ALL". */
72
+ readonly method: Method; /** The handler invoked on a match. */
73
+ readonly handler: EndpointHandler;
74
+ };
75
+ /** A compiled endpoint with pre-parsed segments and a specificity score. */
76
+ type CompiledEndpoint = {
77
+ /** Original endpoint, returned to the dispatch site. */readonly endpoint: Endpoint; /** Pre-parsed path segments for fast matching. */
78
+ readonly segments: ReadonlyArray<PathSegment>; /** Specificity score — higher = more literal segments, sorted first. */
79
+ readonly specificity: number;
80
+ };
81
+ /** Server config — the declarative endpoint table. */
82
+ type ServerConfig = {
83
+ /** Endpoints compiled into the matcher table. Default []. */endpoints: Endpoint[];
84
+ };
85
+ /** A successful endpoint match: the endpoint plus its extracted path params. */
86
+ type MatchResult = {
87
+ /** The matched endpoint. */readonly endpoint: Endpoint; /** Path params extracted from the request path. */
88
+ readonly params: Record<string, string | undefined>;
89
+ };
90
+ /** Server state — the compiled matcher table, built once at onInit. */
91
+ type ServerState = {
92
+ /** Endpoints sorted by specificity. Populated from config at onInit. */table: CompiledEndpoint[]; /** True once onInit has compiled the table; guards double-compilation. */
93
+ compiled: boolean;
94
+ /**
95
+ * Match a method + pathname against the compiled table (literal beats param,
96
+ * method-specific beats ALL). Returns the matched endpoint + params, or null.
97
+ *
98
+ * @param method - The request method (or "ALL" for cron dispatch).
99
+ * @param path - The request URL pathname (or cron string).
100
+ * @returns The matched endpoint and its params, or null.
101
+ */
102
+ match(method: string, path: string): MatchResult | null;
103
+ };
104
+ /** Any plugin instance — mirrors core's un-exported RequireFunction constraint. */
105
+ type AnyPlugin = PluginInstance<string, any, any, any, any>;
106
+ /**
107
+ * Extract a plugin instance's API type. Extracts via the `_phantom.api` slot —
108
+ * identical to core's un-exported `ExtractPluginApi`, so this `RequireFn` is
109
+ * assignable FROM core's real `ctx.require` (whose return is `ExtractPluginApi<P>`).
110
+ * Extracting via the `PluginInstance<…, infer A, …>` pattern would NOT unify with
111
+ * `ExtractPluginApi<P>` for an unresolved generic `P`.
112
+ */
113
+ type ApiOf<P> = P extends {
114
+ readonly _phantom: {
115
+ readonly api: infer A;
116
+ };
117
+ } ? A : never;
118
+ /** Cross-plugin reach used inside handlers: require(plugin) returns that plugin's API. Mirrors ctx.require. */
119
+ type RequireFn = <P extends AnyPlugin>(plugin: P) => ApiOf<P>;
120
+ /** A request handler: receives the per-request context, returns a Response. */
121
+ type EndpointHandler = (ctx: RequestContext) => Response | Promise<Response>;
122
+ /** Fresh per-request object threaded to each EndpointHandler. */
123
+ type RequestContext = {
124
+ /** The incoming request. */readonly request: Request; /** Per-request Cloudflare bindings — threaded on the stack, NEVER stored in state. */
125
+ readonly env: WorkerEnv; /** waitUntil / passThroughOnException. */
126
+ readonly exec: ExecutionContext; /** Path params extracted from the matched endpoint. */
127
+ readonly params: Record<string, string | undefined>; /** Parsed request URL. */
128
+ readonly url: URL; /** Cross-plugin reach for handlers (e.g. require(bindingsPlugin)). */
129
+ readonly require: RequireFn; /** Presence check for an optional plugin. */
130
+ readonly has: (name: string) => boolean;
131
+ };
132
+ /** Per-plugin event map merged into the server context. */
133
+ type ServerEvents = {
134
+ "server:matched": {
135
+ path: string;
136
+ method: string;
137
+ };
138
+ };
139
+ /** Full server plugin context (own config + state + merged events + cross-plugin reach). */
140
+ type ServerCtx = PluginCtx<ServerConfig, ServerState, WorkerEvents & ServerEvents> & {
141
+ /** Cross-plugin require threaded into each RequestContext. */require: RequireFn; /** Presence check for an optional plugin. */
142
+ has: (name: string) => boolean;
143
+ };
144
+ /** Public api surface of the server plugin. */
145
+ type Api$3 = {
146
+ /**
147
+ * Route one HTTP request and return its Response (or 404).
148
+ *
149
+ * @param request - The incoming request.
150
+ * @param env - Per-request Cloudflare bindings (threaded, never stored).
151
+ * @param exec - waitUntil / passThroughOnException.
152
+ * @returns The handler's response, or 404 Not Found.
153
+ */
154
+ handle(request: Request, env: WorkerEnv, exec: ExecutionContext): Promise<Response>;
155
+ /**
156
+ * Cron entry. Dispatches the controller through the endpoint table and awaits it.
157
+ *
158
+ * @param controller - The cron controller.
159
+ * @param env - Per-request bindings (threaded, never stored).
160
+ * @param exec - waitUntil / passThroughOnException.
161
+ * @returns Resolves after all matched cron work completes.
162
+ */
163
+ scheduled(controller: ScheduledController, env: WorkerEnv, exec: ExecutionContext): Promise<void>;
164
+ };
165
+ //#endregion
166
+ //#region src/plugins/server/helpers.d.ts
167
+ /**
168
+ * Fluent builder whose verb methods each return a typed `Endpoint`.
169
+ *
170
+ * @example
171
+ * ```typescript
172
+ * const e = endpoint("/api/{id}").get(handler);
173
+ * ```
174
+ */
175
+ type EndpointBuilder = {
176
+ /**
177
+ * Build a GET endpoint bound to this path.
178
+ *
179
+ * @param handler - The handler invoked when a GET request matches.
180
+ * @returns A GET `Endpoint`.
181
+ * @example
182
+ * ```typescript
183
+ * endpoint("/health").get(() => new Response("ok"));
184
+ * ```
185
+ */
186
+ get(handler: EndpointHandler): Endpoint;
187
+ /**
188
+ * Build a POST endpoint bound to this path.
189
+ *
190
+ * @param handler - The handler invoked when a POST request matches.
191
+ * @returns A POST `Endpoint`.
192
+ * @example
193
+ * ```typescript
194
+ * endpoint("/users").post(({ request }) => Response.json({ created: true }, { status: 201 }));
195
+ * ```
196
+ */
197
+ post(handler: EndpointHandler): Endpoint;
198
+ /**
199
+ * Build a PUT endpoint bound to this path.
200
+ *
201
+ * @param handler - The handler invoked when a PUT request matches.
202
+ * @returns A PUT `Endpoint`.
203
+ * @example
204
+ * ```typescript
205
+ * endpoint("/users/{id}").put(({ params }) => Response.json({ updated: params.id }));
206
+ * ```
207
+ */
208
+ put(handler: EndpointHandler): Endpoint;
209
+ /**
210
+ * Build a PATCH endpoint bound to this path.
211
+ *
212
+ * @param handler - The handler invoked when a PATCH request matches.
213
+ * @returns A PATCH `Endpoint`.
214
+ * @example
215
+ * ```typescript
216
+ * endpoint("/users/{id}").patch(({ params }) => Response.json({ patched: params.id }));
217
+ * ```
218
+ */
219
+ patch(handler: EndpointHandler): Endpoint;
220
+ /**
221
+ * Build a DELETE endpoint bound to this path.
222
+ *
223
+ * @param handler - The handler invoked when a DELETE request matches.
224
+ * @returns A DELETE `Endpoint`.
225
+ * @example
226
+ * ```typescript
227
+ * endpoint("/users/{id}").delete(() => new Response(null, { status: 204 }));
228
+ * ```
229
+ */
230
+ delete(handler: EndpointHandler): Endpoint;
231
+ /**
232
+ * Build a HEAD endpoint bound to this path.
233
+ *
234
+ * @param handler - The handler invoked when a HEAD request matches.
235
+ * @returns A HEAD `Endpoint`.
236
+ * @example
237
+ * ```typescript
238
+ * endpoint("/health").head(() => new Response(null, { status: 200 }));
239
+ * ```
240
+ */
241
+ head(handler: EndpointHandler): Endpoint;
242
+ /**
243
+ * Build an OPTIONS endpoint bound to this path.
244
+ *
245
+ * @param handler - The handler invoked when an OPTIONS request matches.
246
+ * @returns An OPTIONS `Endpoint`.
247
+ * @example
248
+ * ```typescript
249
+ * endpoint("/api").options(() => new Response(null, { headers: { Allow: "GET, POST" } }));
250
+ * ```
251
+ */
252
+ options(handler: EndpointHandler): Endpoint;
253
+ /**
254
+ * Build an ALL-method endpoint bound to this path (`method: "ALL"` — matches any verb).
255
+ *
256
+ * @param handler - The handler invoked when any request method matches.
257
+ * @returns An ALL-method `Endpoint`.
258
+ * @example
259
+ * ```typescript
260
+ * endpoint("0 * * * *").all(async () => new Response("cron done"));
261
+ * ```
262
+ */
263
+ all(handler: EndpointHandler): Endpoint;
264
+ };
265
+ /**
266
+ * Build a typed `Endpoint`. `{name}` → required param; `{name?}` → optional param.
267
+ *
268
+ * PURE factory (spec/03 §1): no ctx, no lifecycle, no side effects; safe to run
269
+ * before `createApp`. Each verb method (`get`, `post`, …, `all`) returns the
270
+ * truthful Endpoint value — `method: "ALL"` is never used as a `"get"` sentinel.
271
+ *
272
+ * @param path - Endpoint path, optionally with `{name}` / `{name?}` params.
273
+ * @returns A builder whose verb methods each return a typed `Endpoint`.
274
+ * @example
275
+ * ```typescript
276
+ * endpoint("/api/data/{lang?}").get(({ params }) =>
277
+ * Response.json({ lang: params.lang ?? "en" })
278
+ * );
279
+ * ```
280
+ */
281
+ declare const endpoint: (path: string) => EndpointBuilder;
282
+ declare namespace types_d_exports {
283
+ export { Api$2 as Api, Config$3 as Config, D1Ctx, DeployManifest$2 as DeployManifest };
284
+ }
285
+ /**
286
+ * d1 plugin configuration.
287
+ *
288
+ * @example
289
+ * ```ts
290
+ * { binding: "DB", migrations: "./migrations" }
291
+ * ```
292
+ */
293
+ type Config$3 = {
294
+ /** D1 binding name resolved off the per-request env. */binding: string; /** Migrations directory; deploy-time metadata only. */
295
+ migrations: string;
296
+ };
297
+ /**
298
+ * Deploy metadata entry for a D1 database, read by the deploy plugin.
299
+ *
300
+ * @example
301
+ * ```ts
302
+ * { kind: "d1", binding: "DB", migrations: "./migrations" }
303
+ * ```
304
+ */
305
+ type DeployManifest$2 = {
306
+ /** Discriminant identifying this as a D1 resource. */kind: "d1"; /** D1 binding name. */
307
+ binding: string; /** Migrations directory (or "" if none). */
308
+ migrations: string;
309
+ };
310
+ /** Public api surface of the d1 plugin (thin typed wrappers over prepare().bind()). */
311
+ type Api$2 = {
312
+ /**
313
+ * Run a statement and return all rows.
314
+ *
315
+ * @param env - Per-request Cloudflare bindings.
316
+ * @param sql - SQL with `?` placeholders.
317
+ * @param params - Bind parameters.
318
+ * @returns All rows in a D1 result.
319
+ */
320
+ query: <T = unknown>(env: WorkerEnv, sql: string, ...params: unknown[]) => Promise<D1Result<T>>;
321
+ /**
322
+ * Run a statement and return the first row or null.
323
+ *
324
+ * @param env - Per-request Cloudflare bindings.
325
+ * @param sql - SQL with `?` placeholders.
326
+ * @param params - Bind parameters.
327
+ * @returns The first row, or null if none.
328
+ */
329
+ first: <T = unknown>(env: WorkerEnv, sql: string, ...params: unknown[]) => Promise<T | null>;
330
+ /**
331
+ * Run a write/DDL statement and return its result meta.
332
+ *
333
+ * @param env - Per-request Cloudflare bindings.
334
+ * @param sql - SQL with `?` placeholders.
335
+ * @param params - Bind parameters.
336
+ * @returns Result carrying `.meta`.
337
+ */
338
+ run: (env: WorkerEnv, sql: string, ...params: unknown[]) => Promise<D1Result>;
339
+ /**
340
+ * Execute prepared statements atomically in one round-trip.
341
+ *
342
+ * @param env - Per-request Cloudflare bindings.
343
+ * @param stmts - Caller-built prepared statements.
344
+ * @returns One result per statement, order preserved.
345
+ */
346
+ batch: (env: WorkerEnv, stmts: D1PreparedStatement[]) => Promise<D1Result[]>;
347
+ /**
348
+ * Resolve the request D1Database so callers can build statements for batch().
349
+ *
350
+ * @param env - Per-request Cloudflare bindings.
351
+ * @returns The request-resolved database handle.
352
+ */
353
+ prepare: (env: WorkerEnv) => D1Database;
354
+ /**
355
+ * Return this plugin's deploy metadata (read by the deploy plugin).
356
+ *
357
+ * @returns Deploy manifest entry `{ kind: "d1", binding, migrations }`.
358
+ */
359
+ deployManifest: () => DeployManifest$2;
360
+ };
361
+ /**
362
+ * Internal context type — own config first, no state, no d1-local events.
363
+ * Intersected with a narrow `require` typed to the one dependency d1 resolves.
364
+ */
365
+ type D1Ctx = PluginCtx<Config$3, Record<string, never>, WorkerEvents> & {
366
+ /**
367
+ * Resolve a dependency plugin's api. d1 only ever resolves `bindingsPlugin`.
368
+ *
369
+ * @param plugin - The bindingsPlugin instance.
370
+ * @returns The resolved bindings api.
371
+ */
372
+ require(plugin: typeof bindingsPlugin): BindingsApi;
373
+ };
374
+ //#endregion
375
+ //#region src/plugins/d1/index.d.ts
376
+ /**
377
+ * Standard tier — Cloudflare D1 SQL access (thin typed wrappers, not an ORM).
378
+ *
379
+ * Exposes `query`, `first`, `run`, `batch`, `prepare`, and `deployManifest`.
380
+ * Resolves the D1 binding off the per-request `env` via the bindings plugin.
381
+ * No state, no events, no lifecycle hooks (request-scoped, spec/06 §3).
382
+ *
383
+ * @see README.md
384
+ */
385
+ declare const d1Plugin: import("@moku-labs/core").PluginInstance<"d1", Config$3, Record<string, never>, {
386
+ query: <T = unknown>(env: WorkerEnv, sql: string, ...params: unknown[]) => Promise<D1Result<T>>;
387
+ first: <T = unknown>(env: WorkerEnv, sql: string, ...params: unknown[]) => Promise<T | null>;
388
+ run: (env: WorkerEnv, sql: string, ...params: unknown[]) => Promise<D1Result<Record<string, unknown>>>;
389
+ batch: (env: WorkerEnv, stmts: D1PreparedStatement[]) => Promise<D1Result<unknown>[]>;
390
+ prepare: (env: WorkerEnv) => D1Database;
391
+ deployManifest: () => DeployManifest$2;
392
+ }, {}> & Record<never, never>;
393
+ declare namespace types_d_exports$1 {
394
+ export { Api$1 as Api, Config$2 as Config, Ctx$1 as Ctx, DeployManifest$1 as DeployManifest };
395
+ }
396
+ /**
397
+ * durableObjects plugin configuration. Flat; complete default so omission never yields undefined.
398
+ *
399
+ * @example
400
+ * ```ts
401
+ * { bindings: { counter: "COUNTER" } }
402
+ * ```
403
+ */
404
+ type Config$2 = {
405
+ /** Logical name -> Cloudflare DO binding name. A missing logical name falls back to itself. Default {}. */bindings: Record<string, string>;
406
+ };
407
+ /**
408
+ * Deploy metadata entry for Durable Objects, read by the deploy plugin.
409
+ *
410
+ * @example
411
+ * ```ts
412
+ * { kind: "do", bindings: { counter: "COUNTER" } }
413
+ * ```
414
+ */
415
+ type DeployManifest$1 = {
416
+ /** Discriminant identifying this as a Durable Objects resource. */kind: "do"; /** Logical name -> Cloudflare DO binding name. */
417
+ bindings: Record<string, string>;
418
+ };
419
+ /** Public api surface of the durableObjects plugin. */
420
+ type Api$1 = {
421
+ /**
422
+ * Resolve a DurableObjectStub off the request env (logical name -> configured binding).
423
+ *
424
+ * @param env - Per-request Cloudflare bindings.
425
+ * @param logicalName - Logical DO name used in code.
426
+ * @param idName - Stable id name passed to idFromName.
427
+ * @returns The addressed Durable Object stub.
428
+ */
429
+ get(env: WorkerEnv, logicalName: string, idName: string): DurableObjectStub;
430
+ /**
431
+ * Return this plugin's deploy metadata (read by the deploy plugin).
432
+ *
433
+ * @returns Deploy manifest entry `{ kind: "do", bindings }`.
434
+ */
435
+ deployManifest(): DeployManifest$1;
436
+ };
437
+ /** Internal context type — own config first, no state, no DO events. */
438
+ type Ctx$1 = PluginCtx<Config$2, Record<string, never>, WorkerEvents>;
439
+ //#endregion
440
+ //#region src/plugins/durable-objects/helpers.d.ts
441
+ /**
442
+ * Constructor contract of the base class returned by `defineDurableObject`.
443
+ *
444
+ * @example
445
+ * ```typescript
446
+ * class Counter extends defineDurableObject("Counter") implements DurableObjectBase {
447
+ * async fetch(): Promise<Response> { return new Response("ok"); }
448
+ * }
449
+ * ```
450
+ */
451
+ interface DurableObjectBase {
452
+ /** Cloudflare per-object storage/alarm context. */
453
+ readonly ctx: DurableObjectState;
454
+ /** Per-object Cloudflare bindings (per-request env). */
455
+ readonly env: WorkerEnv;
456
+ }
457
+ /**
458
+ * Constructor type produced by `defineDurableObject`. The consumer `extends` this
459
+ * and exports the resulting class from `worker.ts`.
460
+ *
461
+ * @example
462
+ * ```typescript
463
+ * const Base: DurableObjectBaseConstructor = defineDurableObject("Counter");
464
+ * class Counter extends Base {}
465
+ * ```
466
+ */
467
+ type DurableObjectBaseConstructor = new (ctx: DurableObjectState, env: WorkerEnv) => DurableObjectBase;
468
+ /**
469
+ * Returns a base class the consumer extends and exports from `worker.ts`.
470
+ *
471
+ * PURE (spec/03 §1): takes no `ctx`, has no side effects, and may be called before
472
+ * `createApp`. The static `doName` property captures `name` for diagnostics and
473
+ * binding correlation. The constructor stores `(state, env)` as `this.ctx` / `this.env`,
474
+ * satisfying the Cloudflare Durable Object constructor contract. The plugin NEVER
475
+ * generates the final exported class — the consumer owns that class.
476
+ *
477
+ * @param name - Logical DO name; captured as `static doName` for diagnostics.
478
+ * @returns A base class (constructor) the consumer extends.
479
+ * @example
480
+ * ```typescript
481
+ * // src/counter.ts
482
+ * import { defineDurableObject } from "@moku-labs/worker";
483
+ *
484
+ * export class Counter extends defineDurableObject("Counter") {
485
+ * async fetch(): Promise<Response> {
486
+ * const n = ((await this.ctx.storage.get<number>("n")) ?? 0) + 1;
487
+ * await this.ctx.storage.put("n", n);
488
+ * return Response.json({ n });
489
+ * }
490
+ * }
491
+ * ```
492
+ */
493
+ declare const defineDurableObject: (name: string) => DurableObjectBaseConstructor & {
494
+ readonly doName: string;
495
+ };
496
+ //#endregion
497
+ //#region src/plugins/durable-objects/index.d.ts
498
+ /**
499
+ * Cloudflare Durable Objects plugin — Standard tier.
500
+ *
501
+ * Exposes `get(env, logicalName, idName)` (synchronous stub accessor, threaded env) and
502
+ * `deployManifest()` (build-time metadata). Depends on `bindingsPlugin` for namespace
503
+ * resolution. The `defineDurableObject` helper is mounted under `helpers` and re-exported
504
+ * at the top level for consumer use.
505
+ *
506
+ * @example
507
+ * ```typescript
508
+ * // Consumer endpoint handler:
509
+ * const stub = app.durableObjects.get(env, "counter", params.room!);
510
+ * const res = await stub.fetch("https://do/increment");
511
+ * // Consumer DO class:
512
+ * export class Counter extends defineDurableObject("Counter") {
513
+ * async fetch(): Promise<Response> { return new Response("ok"); }
514
+ * }
515
+ * ```
516
+ * @see README.md
517
+ */
518
+ declare const durableObjectsPlugin: import("@moku-labs/core").PluginInstance<"durableObjects", Config$2, Record<string, never>, {
519
+ get: (env: WorkerEnv, logicalName: string, idName: string) => DurableObjectStub;
520
+ deployManifest: () => DeployManifest$1;
521
+ }, {}> & {
522
+ defineDurableObject: (name: string) => DurableObjectBaseConstructor & {
523
+ readonly doName: string;
524
+ };
525
+ };
526
+ //#endregion
527
+ //#region src/plugins/kv/api.d.ts
528
+ /**
529
+ * The app.kv surface — env-first key/value access plus deploy metadata.
530
+ *
531
+ * @example
532
+ * ```typescript
533
+ * const value = await app.kv.get(env, "feature-flags");
534
+ * await app.kv.put(env, "session:1", "data", { expirationTtl: 3600 });
535
+ * ```
536
+ */
537
+ type KvApi = {
538
+ /**
539
+ * Reads a value by key from the KV namespace. Returns null when absent.
540
+ *
541
+ * @param env - The per-request Cloudflare env (threaded, never stored).
542
+ * @param key - The key to read.
543
+ * @returns The stored value, or null when absent.
544
+ */
545
+ get(env: WorkerEnv, key: string): Promise<string | null>;
546
+ /**
547
+ * Writes a string value under a key, optionally with KV put options.
548
+ *
549
+ * @param env - The per-request Cloudflare env.
550
+ * @param key - The key to write.
551
+ * @param value - The string value to store.
552
+ * @param opts - Optional expiration / metadata.
553
+ * @returns Resolves once the write is acknowledged.
554
+ */
555
+ put(env: WorkerEnv, key: string, value: string, opts?: KVNamespacePutOptions): Promise<void>;
556
+ /**
557
+ * Removes a key from the namespace (no-op if absent).
558
+ *
559
+ * @param env - The per-request Cloudflare env.
560
+ * @param key - The key to delete.
561
+ * @returns Resolves once the delete is acknowledged.
562
+ */
563
+ delete(env: WorkerEnv, key: string): Promise<void>;
564
+ /**
565
+ * Lists keys in the namespace, optionally filtered/paginated.
566
+ *
567
+ * @param env - The per-request Cloudflare env.
568
+ * @param opts - Optional prefix / cursor / limit.
569
+ * @returns The list result.
570
+ */
571
+ list(env: WorkerEnv, opts?: KVNamespaceListOptions): Promise<KVNamespaceListResult<unknown, string>>;
572
+ /**
573
+ * Returns this plugin's own deploy metadata, read by the deploy plugin.
574
+ * Build-time only — takes no env.
575
+ *
576
+ * @returns The kv deploy descriptor.
577
+ */
578
+ deployManifest(): {
579
+ kind: "kv";
580
+ binding: string;
581
+ };
582
+ };
583
+ //#endregion
584
+ //#region src/plugins/kv/index.d.ts
585
+ /**
586
+ * Micro tier — thin env-first wrapper over a Cloudflare KV namespace.
587
+ *
588
+ * Resolves the KV namespace per request via `ctx.require(bindingsPlugin)`;
589
+ * never stores env in state (design §1a / SB4). No lifecycle hooks —
590
+ * request-scoped; nothing to open or close.
591
+ *
592
+ * @see README.md
593
+ */
594
+ declare const kvPlugin: import("@moku-labs/core").PluginInstance<"kv", {
595
+ binding: string;
596
+ }, Record<string, never>, KvApi, {}> & Record<never, never>;
597
+ declare namespace types_d_exports$2 {
598
+ export { Api, Config$1 as Config, Ctx, DeployManifest, QueueEvents };
599
+ }
600
+ /**
601
+ * queues plugin configuration. Flat; complete defaults so omission never yields undefined.
602
+ */
603
+ type Config$1 = {
604
+ /** Queue names this Worker produces to; surfaced by deployManifest(). Default []. */producers: string[]; /** Declarative consumer handler — awaited once per message in consume(). Default no-op. */
605
+ onMessage: (message: Message, env: WorkerEnv) => Promise<void>;
606
+ };
607
+ /**
608
+ * Deploy metadata entry for a queue, read by the deploy plugin.
609
+ *
610
+ * @example
611
+ * ```ts
612
+ * { kind: "queue", producers: ["orders"] }
613
+ * ```
614
+ */
615
+ type DeployManifest = {
616
+ /** Discriminant identifying this as a queue resource. */kind: "queue"; /** Queue names produced to. */
617
+ producers: string[];
618
+ };
619
+ /** Per-plugin event map for queues. */
620
+ type QueueEvents = {
621
+ "queue:message": {
622
+ queue: string;
623
+ messageId: string;
624
+ };
625
+ };
626
+ /** Public api surface of the queues plugin (producer + consumer). */
627
+ type Api = {
628
+ /**
629
+ * Enqueue a single message onto the named queue.
630
+ *
631
+ * @param env - Per-request Cloudflare bindings.
632
+ * @param queue - Target queue binding name.
633
+ * @param body - Message body.
634
+ * @returns Resolves once enqueued.
635
+ */
636
+ send(env: WorkerEnv, queue: string, body: unknown): Promise<void>;
637
+ /**
638
+ * Enqueue many messages; each element becomes one message.
639
+ *
640
+ * @param env - Per-request Cloudflare bindings.
641
+ * @param queue - Target queue binding name.
642
+ * @param bodies - Message bodies.
643
+ * @returns Resolves once enqueued.
644
+ */
645
+ sendBatch(env: WorkerEnv, queue: string, bodies: unknown[]): Promise<void>;
646
+ /**
647
+ * Consumer dispatch — the Worker's queue() export delegates here.
648
+ *
649
+ * @param batch - The incoming message batch.
650
+ * @param env - Per-request Cloudflare bindings.
651
+ * @param exec - waitUntil / passThroughOnException.
652
+ * @returns Resolves after all messages settle.
653
+ */
654
+ consume(batch: MessageBatch, env: WorkerEnv, exec: ExecutionContext): Promise<void>;
655
+ /**
656
+ * Return this plugin's deploy metadata (read by the deploy plugin).
657
+ *
658
+ * @returns Deploy manifest entry `{ kind: "queue", producers }`.
659
+ */
660
+ deployManifest(): DeployManifest;
661
+ };
662
+ /**
663
+ * Internal context type — own config first, no state, merged queue events.
664
+ *
665
+ * `PluginCtx` exposes only `config`/`state`/`emit`; `require` is composed in here
666
+ * (core's "advanced composition" note), typed to the one dependency queues resolves —
667
+ * `require(bindingsPlugin)` → `BindingsApi`. Core does not export `RequireFunction`.
668
+ */
669
+ type Ctx = PluginCtx<Config$1, Record<string, never>, WorkerEvents & QueueEvents> & {
670
+ /**
671
+ * Resolve a dependency plugin's api. queues only ever resolves `bindingsPlugin`.
672
+ *
673
+ * @param plugin - The bindings plugin instance.
674
+ * @returns The resolved bindings api.
675
+ */
676
+ require(plugin: typeof bindingsPlugin): BindingsApi;
677
+ };
678
+ //#endregion
679
+ //#region src/plugins/queues/index.d.ts
680
+ /**
681
+ * Standard tier — Cloudflare Queues producer + consumer dispatch.
682
+ *
683
+ * `events` is declared first and via `register.map<QueueEvents>` so the plugin's own events infer
684
+ * into the factory context; the api wiring is therefore arrow-wrapped (contextually typed).
685
+ *
686
+ * @see README.md
687
+ */
688
+ declare const queuesPlugin: import("@moku-labs/core").PluginInstance<"queues", Config$1, Record<string, never>, {
689
+ send: (env: Parameters<(message: Message, env: WorkerEnv) => Promise<void>>[1], q: string, body: unknown) => Promise<void>;
690
+ sendBatch: (env: Parameters<(message: Message, env: WorkerEnv) => Promise<void>>[1], q: string, bodies: unknown[]) => Promise<void>;
691
+ consume: (batch: MessageBatch, env: Parameters<(message: Message, env: WorkerEnv) => Promise<void>>[1], _exec: ExecutionContext) => Promise<void>;
692
+ deployManifest: () => {
693
+ kind: "queue";
694
+ producers: string[];
695
+ };
696
+ }, {
697
+ "queue:message": {
698
+ queue: string;
699
+ messageId: string;
700
+ };
701
+ }> & Record<never, never>;
702
+ //#endregion
703
+ //#region src/plugins/server/index.d.ts
704
+ /**
705
+ * Standard tier — HTTP routing + request/scheduled dispatch over a compiled
706
+ * endpoint table. Emits `server:matched` (per-plugin) plus global
707
+ * `request:start` / `request:end` declared in `WorkerEvents`.
708
+ *
709
+ * @see README.md
710
+ */
711
+ declare const serverPlugin: import("@moku-labs/core").PluginInstance<"server", ServerConfig, ServerState, Api$3, {
712
+ "server:matched": {
713
+ path: string;
714
+ method: string;
715
+ };
716
+ }> & {
717
+ endpoint: (path: string) => EndpointBuilder;
718
+ };
719
+ //#endregion
720
+ //#region src/plugins/storage/providers/types.d.ts
721
+ /**
722
+ * @file storage plugin — provider adapter seam (the StorageProvider interface).
723
+ *
724
+ * R2ListOptions / R2Object / R2ObjectBody / R2Objects are ambient globals from
725
+ * `@cloudflare/workers-types` (tsconfig "types") — used unqualified, never imported.
726
+ */
727
+ /**
728
+ * The adapter seam. Both the real R2 provider and the in-memory test double
729
+ * implement this so api.ts is provider-agnostic.
730
+ *
731
+ * @example
732
+ * ```ts
733
+ * const provider = createMemoryProvider();
734
+ * await provider.put("k", "v");
735
+ * ```
736
+ */
737
+ type StorageProvider = {
738
+ /** Read an object; null when absent. */get(key: string): Promise<R2ObjectBody | null>; /** Write an object. */
739
+ put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | Blob | null): Promise<R2Object>; /** Remove an object (or keys). */
740
+ delete(key: string | string[]): Promise<void>; /** List objects. */
741
+ list(opts?: R2ListOptions): Promise<R2Objects>;
742
+ };
743
+ declare namespace types_d_exports$4 {
744
+ export { StorageApi, StorageConfig, StorageCtx, StorageManifest, StorageProvider };
745
+ }
746
+ /**
747
+ * storage plugin configuration. Flat; complete defaults so omission never yields undefined.
748
+ *
749
+ * @example
750
+ * ```ts
751
+ * { upload: "./public", bucket: "ASSETS" }
752
+ * ```
753
+ */
754
+ type StorageConfig = {
755
+ /** Directory uploaded to R2 at deploy (deploy metadata only). Default "". */upload: string; /** R2 bucket binding name resolved off the per-request env. Default "ASSETS". */
756
+ bucket: string;
757
+ };
758
+ /** Deploy metadata returned to the deploy plugin. */
759
+ type StorageManifest = {
760
+ /** Discriminant identifying this as an R2 resource. */readonly kind: "r2"; /** R2 bucket binding name. */
761
+ readonly bucket: string; /** Directory uploaded to R2 at deploy. */
762
+ readonly upload: string;
763
+ };
764
+ /** Public storage API surface (env-first). */
765
+ type StorageApi = {
766
+ /**
767
+ * Read an object; resolves null when the key is absent.
768
+ *
769
+ * @param env - Per-request Cloudflare bindings.
770
+ * @param key - Object key.
771
+ * @returns The object body, or null.
772
+ */
773
+ get(env: WorkerEnv, key: string): Promise<R2ObjectBody | null>;
774
+ /**
775
+ * Write an object.
776
+ *
777
+ * @param env - Per-request Cloudflare bindings.
778
+ * @param key - Object key.
779
+ * @param value - Object contents.
780
+ * @returns The written object metadata.
781
+ */
782
+ put(env: WorkerEnv, key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | Blob | null): Promise<R2Object>;
783
+ /**
784
+ * Remove an object (or keys). No-op when absent.
785
+ *
786
+ * @param env - Per-request Cloudflare bindings.
787
+ * @param key - Object key or keys.
788
+ * @returns Resolves once removed.
789
+ */
790
+ delete(env: WorkerEnv, key: string | string[]): Promise<void>;
791
+ /**
792
+ * List objects, optionally filtered by R2ListOptions.
793
+ *
794
+ * @param env - Per-request Cloudflare bindings.
795
+ * @param opts - Optional prefix / limit / cursor / delimiter.
796
+ * @returns The list result.
797
+ */
798
+ list(env: WorkerEnv, opts?: R2ListOptions): Promise<R2Objects>;
799
+ /**
800
+ * Build-time deploy metadata for the deploy plugin.
801
+ *
802
+ * @returns Deploy manifest entry `{ kind: "r2", bucket, upload }`.
803
+ */
804
+ deployManifest(): StorageManifest;
805
+ };
806
+ /**
807
+ * Internal context type — own config first, no state, no storage events.
808
+ * Intersected with a narrow `require` typed to the one dependency storage
809
+ * resolves — mirrors the kv/api.ts pattern (PluginCtx has no `require` by
810
+ * default; core does not export a generic RequireFunction).
811
+ */
812
+ type StorageCtx = PluginCtx<StorageConfig, Record<string, never>, WorkerEvents> & {
813
+ /**
814
+ * Resolve a dependency plugin's api. storage only ever resolves bindingsPlugin.
815
+ *
816
+ * @param plugin - The bindingsPlugin instance.
817
+ * @returns The resolved bindings api.
818
+ */
819
+ require(plugin: typeof bindingsPlugin): BindingsApi;
820
+ };
821
+ //#endregion
822
+ //#region src/plugins/storage/index.d.ts
823
+ /**
824
+ * Complex tier — Cloudflare R2 object storage behind a provider adapter seam.
825
+ *
826
+ * Exposes `get`, `put`, `delete`, `list` (all env-first) and `deployManifest()`
827
+ * (build-time). Depends on `bindingsPlugin` to resolve the `R2Bucket` binding
828
+ * per request. No state, no events, no lifecycle hooks.
829
+ *
830
+ * @see README.md
831
+ */
832
+ declare const storagePlugin: import("@moku-labs/core").PluginInstance<"storage", StorageConfig, Record<string, never>, StorageApi, {}> & Record<never, never>;
833
+ //#endregion
834
+ //#region src/plugins/stage/index.d.ts
835
+ /** This plugin's own config type (Nano tier — declared inline, no types.ts). */
836
+ type Config = {
837
+ /**
838
+ * Deployment stage for this Worker.
839
+ * - "production" — live deploy; isDev() === false, isProduction() === true
840
+ * - "development" — local `wrangler dev`; isDev() === true
841
+ * - "test" — automated tests; isDev() === false, isProduction() === false
842
+ * Default: "production" (fail-safe — an unspecified app behaves as production).
843
+ */
844
+ stage: "production" | "development" | "test";
845
+ };
846
+ /** The ctx.stage accessor surface injected on every regular plugin's context. */
847
+ type StageApi = {
848
+ /**
849
+ * Whether this Worker runs in the development stage.
850
+ *
851
+ * @returns True iff `stage === "development"`.
852
+ * @example
853
+ * ```typescript
854
+ * if (ctx.stage.isDev()) return Response.json({ stack: err.stack });
855
+ * ```
856
+ */
857
+ isDev(): boolean;
858
+ /**
859
+ * Whether this Worker runs in the production stage. Note: false in "test".
860
+ *
861
+ * @returns True iff `stage === "production"`.
862
+ * @example
863
+ * ```typescript
864
+ * const cc = ctx.stage.isProduction() ? "public, max-age=31536000" : "no-store";
865
+ * ```
866
+ */
867
+ isProduction(): boolean;
868
+ /**
869
+ * The raw deployment stage, as the literal union (not `string`).
870
+ *
871
+ * @returns The resolved stage value.
872
+ * @example
873
+ * ```typescript
874
+ * ctx.log.info("startup", { stage: ctx.stage.current() });
875
+ * ```
876
+ */
877
+ current(): "production" | "development" | "test";
878
+ };
879
+ /**
880
+ * stage core plugin — deployment-stage / dev-mode detection, flat-injected on
881
+ * every regular plugin's context as `ctx.stage` (spec/02 §6). No state, no
882
+ * events, no depends, no lifecycle hooks.
883
+ *
884
+ * @see README.md
885
+ * @example
886
+ * ```typescript
887
+ * // Inside any regular plugin's api factory:
888
+ * api: (ctx) => ({
889
+ * errorBody: (e: Error) =>
890
+ * ctx.stage.isDev() ? e.stack ?? e.message : "Internal Error",
891
+ * })
892
+ * ```
893
+ */
894
+ declare const stagePlugin: import("@moku-labs/core").CorePluginInstance<"stage", Config, Record<string, never>, {
895
+ /**
896
+ * Whether this Worker runs in the development stage.
897
+ *
898
+ * @returns True iff `stage === "development"`.
899
+ * @example
900
+ * ```typescript
901
+ * if (ctx.stage.isDev()) return Response.json({ stack: err.stack });
902
+ * ```
903
+ */
904
+ isDev: () => boolean;
905
+ /**
906
+ * Whether this Worker runs in the production stage. Note: false in "test".
907
+ *
908
+ * @returns True iff `stage === "production"`.
909
+ * @example
910
+ * ```typescript
911
+ * const cc = ctx.stage.isProduction() ? "public, max-age=31536000" : "no-store";
912
+ * ```
913
+ */
914
+ isProduction: () => boolean;
915
+ /**
916
+ * The raw deployment stage, as the literal union (not `string`).
917
+ *
918
+ * @returns The resolved stage.
919
+ * @example
920
+ * ```typescript
921
+ * ctx.log.info("startup", { stage: ctx.stage.current() });
922
+ * ```
923
+ */
924
+ current: () => "production" | "development" | "test";
925
+ }>;
926
+ //#endregion
927
+ //#region src/index.d.ts
928
+ declare const createApp: <const ExtraPlugins extends readonly import("@moku-labs/core").AnyPluginInstance[] = readonly []>(options?: import("@moku-labs/core").CreateAppOptions<WorkerConfig, WorkerEvents, (import("@moku-labs/core").PluginInstance<"bindings", Config$4, Record<string, never>, BindingsApi, {}> & Record<never, never>) | (import("@moku-labs/core").PluginInstance<"server", ServerConfig, ServerState, Api$3, {
929
+ "server:matched": {
930
+ path: string;
931
+ method: string;
932
+ };
933
+ }> & {
934
+ endpoint: (path: string) => EndpointBuilder;
935
+ }) | ExtraPlugins[number], [...ExtraPlugins], import("@moku-labs/core").CoreApisFromTuple<[import("@moku-labs/core").CorePluginInstance<"log", import("@moku-labs/common").LogConfig, import("@moku-labs/common").LogState, import("@moku-labs/common").LogApi>, import("@moku-labs/core").CorePluginInstance<"env", import("@moku-labs/common").EnvConfig, import("@moku-labs/common").EnvState, import("@moku-labs/common").EnvApi>, import("@moku-labs/core").CorePluginInstance<"stage", {
936
+ stage: "production" | "development" | "test";
937
+ }, Record<string, never>, {
938
+ isDev: () => boolean;
939
+ isProduction: () => boolean;
940
+ current: () => "production" | "development" | "test";
941
+ }>]>> | undefined) => import("@moku-labs/core").App<WorkerConfig, WorkerEvents, (import("@moku-labs/core").PluginInstance<"bindings", Config$4, Record<string, never>, BindingsApi, {}> & Record<never, never>) | (import("@moku-labs/core").PluginInstance<"server", ServerConfig, ServerState, Api$3, {
942
+ "server:matched": {
943
+ path: string;
944
+ method: string;
945
+ };
946
+ }> & {
947
+ endpoint: (path: string) => EndpointBuilder;
948
+ }) | ExtraPlugins[number], import("@moku-labs/core").CoreApisFromTuple<[import("@moku-labs/core").CorePluginInstance<"log", import("@moku-labs/common").LogConfig, import("@moku-labs/common").LogState, import("@moku-labs/common").LogApi>, import("@moku-labs/core").CorePluginInstance<"env", import("@moku-labs/common").EnvConfig, import("@moku-labs/common").EnvState, import("@moku-labs/common").EnvApi>, import("@moku-labs/core").CorePluginInstance<"stage", {
949
+ stage: "production" | "development" | "test";
950
+ }, Record<string, never>, {
951
+ isDev: () => boolean;
952
+ isProduction: () => boolean;
953
+ current: () => "production" | "development" | "test";
954
+ }>]>>, createPlugin: import("@moku-labs/core").BoundCreatePluginFunction<WorkerConfig, WorkerEvents, import("@moku-labs/core").CoreApisFromTuple<[import("@moku-labs/core").CorePluginInstance<"log", import("@moku-labs/common").LogConfig, import("@moku-labs/common").LogState, import("@moku-labs/common").LogApi>, import("@moku-labs/core").CorePluginInstance<"env", import("@moku-labs/common").EnvConfig, import("@moku-labs/common").EnvState, import("@moku-labs/common").EnvApi>, import("@moku-labs/core").CorePluginInstance<"stage", {
955
+ stage: "production" | "development" | "test";
956
+ }, Record<string, never>, {
957
+ isDev: () => boolean;
958
+ isProduction: () => boolean;
959
+ current: () => "production" | "development" | "test";
960
+ }>]>>;
961
+ //#endregion
962
+ export { types_d_exports as D1, types_d_exports$1 as DurableObjects, types_d_exports$2 as Queues, types_d_exports$3 as Server, type StageApi, types_d_exports$4 as Storage, type WorkerConfig, type WorkerEnv, type WorkerEvents, bindingsPlugin, createApp, createPlugin, d1Plugin, defineDurableObject, durableObjectsPlugin, endpoint, envPlugin, kvPlugin, logPlugin, queuesPlugin, serverPlugin, stagePlugin, storagePlugin };