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