@lunora/platform-node 1.0.0-alpha.22 → 1.0.0-alpha.221

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +8 -1
  3. package/dist/conformance/index.mjs +1 -1
  4. package/dist/index.d.mts +853 -136
  5. package/dist/index.d.ts +853 -136
  6. package/dist/index.mjs +1 -1
  7. package/dist/packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs +1 -0
  8. package/dist/packem_shared/NODE_SCHEDULER_DISPATCH_PATH-uDl0zU2t.mjs +1 -0
  9. package/dist/packem_shared/bindShardSockets-9GvSocBW.mjs +1 -0
  10. package/dist/packem_shared/createNodeGlobalStore-CD4DiqeS.mjs +1 -0
  11. package/dist/packem_shared/createNodeHttpServer-cUx4J9Z9.mjs +4 -0
  12. package/dist/packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs +1 -0
  13. package/dist/packem_shared/createNodeMailHost-DrUo8de-.mjs +8 -0
  14. package/dist/packem_shared/createNodePlatform-BqtVmQqS.mjs +1 -0
  15. package/dist/packem_shared/createNodeProfileHandler-MX5xKPg0.mjs +1 -0
  16. package/dist/packem_shared/createNodeQueueHost-glQ8GNCA.mjs +17 -0
  17. package/dist/packem_shared/createNodeR2Bucket-D_jsnenX.mjs +1 -0
  18. package/dist/packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs +15 -0
  19. package/dist/packem_shared/createNodeSecretBindings-C7wh0fOm.mjs +1 -0
  20. package/dist/packem_shared/createNodeShardHost-VU8MPeba.mjs +1 -0
  21. package/dist/packem_shared/createNodeShardNamespace-BgQjDv7V.mjs +1 -0
  22. package/dist/packem_shared/createNodeShardRegistry-C1SRJQhd.mjs +1 -0
  23. package/dist/packem_shared/createNodeSocketHost-ByOmEGFe.mjs +2 -0
  24. package/dist/packem_shared/createNodeWorkflowHost-B76TKiw_.mjs +1 -0
  25. package/dist/packem_shared/hmac-url-Bogwm7I6.mjs +1 -0
  26. package/dist/packem_shared/node-dispatch-route-ByuCR26s.mjs +2 -0
  27. package/dist/packem_shared/node-socket-pair-0baNnoFw.mjs +1 -0
  28. package/dist/packem_shared/prepared-statement-3XBQZXtC.mjs +1 -0
  29. package/package.json +18 -10
  30. package/dist/packem_shared/createNodeGlobalStore-Cwi33XOk.mjs +0 -1
  31. package/dist/packem_shared/createNodePlatform-1fAQ_biu.mjs +0 -1
  32. package/dist/packem_shared/createNodeQueueHost--mBLGSxF.mjs +0 -17
  33. package/dist/packem_shared/createNodeR2Bucket-CmHYlIni.mjs +0 -1
  34. package/dist/packem_shared/createNodeSchedulerHost-vZgv1CEo.mjs +0 -15
  35. package/dist/packem_shared/createNodeShardHost-C0j8nvSU.mjs +0 -1
  36. package/dist/packem_shared/createNodeShardRegistry-DKdc0pV8.mjs +0 -1
  37. package/dist/packem_shared/createNodeShardState-CpUzvWwd.mjs +0 -1
  38. package/dist/packem_shared/createNodeSocketHost-DK3X5PlQ.mjs +0 -2
  39. package/dist/packem_shared/createNodeWorkflowHost-CTVBYiuj.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,9 +1,93 @@
1
1
  import { SchemaLike } from '@lunora/shard-engine';
2
2
  import { SqlCtxDbOptions, SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
3
3
  import Database from 'better-sqlite3';
4
- import { ShardKvStore, QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHost, DirectShardDirectory, PlatformCapabilities, ShardDirectory, R2BucketLike, SocketHandle } from '@lunora/platform';
4
+ import { ShardKvStore, QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHandle, SocketHost, DirectShardDirectory, PlatformCapabilities, ShardDirectory, R2BucketLike } from '@lunora/platform';
5
+ import { Mailer, QueueLike, MailEnv, MailTransport } from '@lunora/mail';
5
6
  import { WorkflowBindingLike } from '@lunora/workflow';
6
7
  import { WorkflowRuntime, WorkflowStore } from '@visulima/workflow';
8
+ import { ShardNamespaceLike } from '@lunora/runtime';
9
+ /**
10
+ * The deadline every `drain()` in this package runs under. A shutdown that waits for work without a bound is held open by the
11
+ * one request or background task that never settles, until the supervisor's kill skips the database close the drain exists to
12
+ * reach. Each drain returns what was still pending when its deadline passed, so the caller can log it and close anyway.
13
+ */
14
+ /**
15
+ * Arms `onExpire` to run after `ms` and returns a function that disarms it. Injectable so a test drives the deadline by hand
16
+ * rather than waiting for a clock.
17
+ */
18
+ type DrainTimer = (ms: number, onExpire: () => void) => () => void;
19
+ /** Options every `drain()` accepts. */
20
+ interface DrainOptions {
21
+ /** Stop waiting after this many milliseconds. Defaults to {@link DEFAULT_DRAIN_TIMEOUT_MS}. */
22
+ timeoutMs?: number;
23
+ /** The clock the deadline runs on. Defaults to `setTimeout`, which keeps the process alive until the drain settles or expires. */
24
+ timer?: DrainTimer;
25
+ }
26
+ /** How a `drain()` ended. */
27
+ interface DrainResult {
28
+ /**
29
+ * Work that failed while the drain waited for it (an alarm retry that could not be written), one readable entry each. Each
30
+ * was also logged with its cause when it happened. A failure never stops the drain waiting for the rest.
31
+ */
32
+ failed: string[];
33
+ /** What was still running when the deadline passed, one human-readable entry each. Empty when the drain completed. */
34
+ pending: string[];
35
+ /** `true` when the deadline passed before the work settled. */
36
+ timedOut: boolean;
37
+ }
38
+ /** Long enough for an ordinary request or background write to finish; short enough that a stuck one cannot stall a shutdown. */
39
+ declare const DEFAULT_DRAIN_TIMEOUT_MS = 3e4;
40
+ /** Something that drains and can say, synchronously, whether it is idle: a registry, a platform. */
41
+ interface Drainable {
42
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
43
+ idle: () => boolean;
44
+ /** What is running right now, re-read when the deadline passes: a part that drained early can have gained work since. */
45
+ pending: () => string[];
46
+ }
47
+ /**
48
+ * Drain several parts under one deadline until a pass that began with every part idle also ends with every part idle. Work
49
+ * on one part can start work on another after that one finished draining (a request handed between registries), and a
50
+ * failure can be recorded after a part's own drain returned; the pass that begins idle collects it, and is held to the same
51
+ * deadline as any other.
52
+ */
53
+ declare const drainTogether: (parts: ReadonlyArray<Drainable>, options?: DrainOptions) => Promise<DrainResult>;
54
+ /** One function call the route has authenticated and parsed. */
55
+ interface NodeDispatchInvocation {
56
+ args: Record<string, unknown>;
57
+ functionPath: string;
58
+ /** The scheduler record or delivery id, used as the shard's idempotency key. */
59
+ id: string | undefined;
60
+ /** Identity the trusted caller forwarded, if any. */
61
+ identity: {
62
+ identity?: string;
63
+ userId?: string;
64
+ } | undefined;
65
+ /** The job's due time in epoch-ms, when the sender stamped one. */
66
+ scheduledFor?: number;
67
+ shardKey: string;
68
+ traceparent: string | undefined;
69
+ }
70
+ interface NodeDispatchRouteOptions {
71
+ /** `LUNORA_ADMIN_TOKEN`. Used as the bearer when no HMAC signature is presented. */
72
+ adminToken?: string;
73
+ /** The shard a body without `shardKey` is sent to. */
74
+ defaultShardKey: string;
75
+ /** Runs the call in-process and returns the shard's response, unchanged. */
76
+ invoke: (call: NodeDispatchInvocation) => Promise<Response>;
77
+ /** Epoch-ms clock for the signature window. Defaults to `Date.now`; tests inject one. */
78
+ now?: () => number;
79
+ /** `LUNORA_SCHEDULER_SECRET`. When set, a signed request is verified against it. */
80
+ schedulerSecret?: string;
81
+ }
82
+ /**
83
+ * Build the dispatch route. The returned function answers any request it is
84
+ * handed; mounting it at {@link NODE_SCHEDULER_DISPATCH_PATH} is the caller's job.
85
+ * With neither secret configured every request is refused, so an unconfigured
86
+ * route fails closed.
87
+ */
88
+ declare const createNodeDispatchRoute: (options: NodeDispatchRouteOptions) => ((request: Request) => Promise<Response>);
89
+ /** The path `@lunora/dispatch` and `@lunora/scheduler` POST to. */
90
+ declare const NODE_SCHEDULER_DISPATCH_PATH: "/_lunora/scheduler/dispatch";
7
91
  /**
8
92
  * The Node store options — the shared store options minus the two this binding
9
93
  * owns. `dialect` is fixed (SQLite) and `exec` is the store's own connection;
@@ -14,13 +98,21 @@ type NodeGlobalContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect" | "exec"
14
98
  /**
15
99
  * Wrap a `better-sqlite3` connection as the async exec the store core consumes.
16
100
  *
17
- * `batch` is deliberately **not** implemented. The contract lets an exec that
18
- * omits it fall back to a sequential `run()` loop, and that fallback is already
19
- * optimal here: `batch` exists to collapse network round trips (D1 does it
20
- * atomically in one request; the Hyperdrive adapters dispatch concurrently over
21
- * a pool), and an embedded database has no round trip to collapse. Declaring it
22
- * would buy nothing and would opt this exec into the "MAY reorder or
23
- * parallelize" licence for no reason.
101
+ * `batch` runs the statements in order inside one `better-sqlite3`
102
+ * transaction, which is synchronous, so nothing else runs between them. There is
103
+ * no round trip to save; atomicity is the point. The store core's FTS5 search
104
+ * companion writes each document as an ordered list of statements, and without
105
+ * this two async writers interleaved at every `await` between them: one could
106
+ * move a document's mapping while the other's entry was mid-write, leaving an
107
+ * entry no later write or purge could reach. The `sqlite` dialect's contract
108
+ * requires an ordered, atomic `batch` for exactly that reason.
109
+ *
110
+ * `transaction` holds `BEGIN IMMEDIATE` … `COMMIT` open across the awaits of
111
+ * an async `work`, which `better-sqlite3`'s own synchronous `transaction()`
112
+ * cannot. The connection is shared, so while one is open every other statement
113
+ * waits for it to settle: run in between, another writer's statement would land
114
+ * inside it and be rolled back with it. The wait and the statement (or the
115
+ * `BEGIN`) run with no `await` between them, so nothing slips in after the check.
24
116
  */
25
117
  declare const createNodeSqlExec: (database: Database.Database) => SqlCtxExec;
26
118
  /** Options for {@link createNodeGlobalStore}. */
@@ -63,8 +155,151 @@ interface NodeGlobalStore {
63
155
  * which is the whole point of the dialect seam.
64
156
  */
65
157
  declare const createNodeGlobalStore: (options?: NodeGlobalStoreOptions) => NodeGlobalStore;
158
+ /** Serve `options.fetch` over `node:http`. Resolves once the server is listening. */
159
+ declare const createNodeHttpServer: (options: NodeHttpServerOptions) => Promise<NodeHttpServer>;
160
+ /** Options for {@link createNodeHttpServer}. */
161
+ interface NodeHttpServerOptions {
162
+ /** The app worker's `fetch`, already bound to its env and context. */
163
+ fetch: (request: Request) => Promise<Response> | Response;
164
+ /** Host to bind. Defaults to the loopback interface. */
165
+ host?: string;
166
+ /**
167
+ * The public base URL the app is served at, e.g. `https://app.example`. Every request URL uses its origin, so origin-sensitive
168
+ * behaviour (CSRF, WebSocket origin checks, cookie rules) sees the public scheme behind a TLS proxy. The client's `Host` header is
169
+ * never used. Defaults to the bound `http://host:port`, which is only allowed for a loopback `host`: binding a non-loopback address
170
+ * (e.g. `0.0.0.0` or a LAN IP) without `origin` makes {@link createNodeHttpServer} reject, because browsers would send that address
171
+ * as `Origin` and fail the CSRF check. Set `origin` to the URL users open.
172
+ */
173
+ origin?: string;
174
+ /** Port to bind. `0` (the default) picks a free ephemeral port. */
175
+ port?: number;
176
+ }
177
+ /** A listening server. */
178
+ interface NodeHttpServer {
179
+ /** Stop accepting connections and end every open one, streams included. */
180
+ close: () => Promise<void>;
181
+ /**
182
+ * Stop accepting connections, then wait until every HTTP response that was in progress when the drain began has been written
183
+ * to the end or its client has gone, or until the deadline passes (`timeoutMs`, 30 s by default). A request that still
184
+ * arrives on an open connection is answered with keep-alive off and is not waited for. Event streams (`text/event-stream`)
185
+ * and WebSockets are endless by design and are not waited for; {@link NodeHttpServer.close} ends them. Resolves with what was
186
+ * still unfinished when the deadline passed, which it also logs.
187
+ */
188
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
189
+ /** The `http://host:port` origin the server answers on. */
190
+ origin: string;
191
+ }
192
+ /**
193
+ * The connection fields a Cloudflare `Hyperdrive` binding exposes, and the
194
+ * `HyperdriveLike` shape `@lunora/hyperdrive`'s `createHyperdrive` reads.
195
+ * Declared here structurally so this package does not depend on
196
+ * `@lunora/hyperdrive` for a type.
197
+ */
198
+ interface NodeHyperdriveBinding {
199
+ connectionString: string;
200
+ database: string;
201
+ host: string;
202
+ password: string;
203
+ port: number;
204
+ user: string;
205
+ }
206
+ /**
207
+ * Build the `HYPERDRIVE` binding for a Node host from a database URL, by
208
+ * default `process.env.DATABASE_URL`. Put it on the `env` the worker and shard
209
+ * are built over, under the binding name the app reads (`env.HYPERDRIVE`), and
210
+ * the app's own `.hyperdrive((env) => …)` wiring builds `ctx.sql` from it
211
+ * unchanged.
212
+ *
213
+ * There is no pool or query cache in front of the database here: the driver
214
+ * the app constructs from `connectionString` connects to it directly, so its own
215
+ * pool settings are the only ones that apply.
216
+ * A Postgres URL may name a Unix socket the libpq way: an empty host with the
217
+ * socket directory in a `host` query parameter (`postgres:///db?host=/var/run/postgresql`),
218
+ * which becomes the binding's `host`.
219
+ *
220
+ * A URL with any TLS option other than an explicit off (`sslmode=prefer` or
221
+ * `require`, `ssl=true`, `sslrootcert=…`) gets a binding whose discrete fields
222
+ * throw: they cannot carry it, so a pool built from them would silently connect
223
+ * without TLS. `sslmode=disable` and `ssl=false` keep them. Build the driver
224
+ * from `connectionString`, which keeps every query option.
225
+ * @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
226
+ */
227
+ declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
66
228
  /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
67
229
  declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
230
+ /** Options for {@link createNodeMailHost}. */
231
+ interface NodeMailHostOptions {
232
+ /**
233
+ * Where `MAIL_FROM`, `RESEND_API_KEY` and the capture switches
234
+ * (`LUNORA_MAIL_CAPTURE`, `WORKER_ENV`, …) are read, once, at construction.
235
+ * `process.env` unless given.
236
+ */
237
+ env?: MailEnv;
238
+ /** The host clock, shared with the queue host so a retry delay and `poll(now)` agree. Defaults to `Date.now`. */
239
+ now?: () => number;
240
+ /**
241
+ * Deliver through this, an SMTP client, another provider or a test double.
242
+ * It wins over `RESEND_API_KEY`, which is only read without it. Ignored while
243
+ * the env selects capture, as `createMailerFromEnv` ignores a transport then.
244
+ */
245
+ transport?: MailTransport;
246
+ }
247
+ /** Queued mail delivery for one Node process. */
248
+ /**
249
+ * Why a send sits in `deadLetters`: its retries ran out (`retries_exhausted`); its idempotency key
250
+ * belongs to other content (`idempotency_key_conflict`); an earlier delivery may have been sent
251
+ * and the provider no longer drops a repeat (`outcome_unknown`), so the provider's logs decide;
252
+ * or that may be so and the record of it has expired (`evidence_expired`). `unknown` is a row
253
+ * parked with no reason recorded (by a build before reasons, or a process that stopped first),
254
+ * which may be any of these, so treat it as `outcome_unknown` until the provider's logs say.
255
+ */
256
+ type MailParkReason = "evidence_expired" | "idempotency_key_conflict" | "outcome_unknown" | "retries_exhausted" | "unknown";
257
+ interface NodeMailHost {
258
+ /** Sends that failed past the queue's retries, parked by the queue host rather than dropped. */
259
+ deadLetters: {
260
+ /** Each parked send, with why it was parked, so an operator can decide whether to requeue it. */
261
+ list: () => {
262
+ attempts: number;
263
+ body: unknown;
264
+ id: string;
265
+ reason: MailParkReason;
266
+ }[];
267
+ /**
268
+ * Return a parked send to the queue for one more delivery. Its attempt
269
+ * count is kept, so a send an earlier attempt may have delivered is
270
+ * refused once the provider no longer dedupes it. `false` when no mail
271
+ * send with that id is parked. Throws for one queued 15 or more days ago,
272
+ * whose attempt record in the sent ledger has expired.
273
+ */
274
+ requeue: (id: string) => boolean;
275
+ };
276
+ /** Wait for every `poll()` in flight. `createNodePlatform`'s `drain()` calls it before the database can close. */
277
+ drain: () => Promise<void>;
278
+ /** Whether no `poll()` is in flight: what `createNodePlatform`'s `drain()` checks to end its passes. */
279
+ idle: () => boolean;
280
+ /** `queue()` enqueues onto {@link NodeMailHost.queue}; `send()` delivers now through the same transport. */
281
+ mailer: Mailer;
282
+ /** Deliver the queued sends that are due, and return how many batches went out. Nothing here runs on a timer. */
283
+ poll: (now?: number) => Promise<number>;
284
+ /**
285
+ * The producer: pass it as `createMailerFromEnv(env, { queue })` in your own
286
+ * module. A queued body needs an `idempotencyKey`, which `mailer.queue()` mints.
287
+ */
288
+ queue: QueueLike;
289
+ }
290
+ /**
291
+ * Create queued mail delivery over `database`: a durable `lunora-mail` queue, a
292
+ * mailer whose `queue()` writes to it, and `poll()` to drain it through the given
293
+ * `transport` or, without one, Resend (`RESEND_API_KEY`). In a dev environment
294
+ * the mailer captures instead, exactly as `createMailerFromEnv` decides on
295
+ * Cloudflare. Throws when `MAIL_FROM` is unset or nothing can deliver.
296
+ *
297
+ * Give it a connection nothing else opens a transaction on, ideally a file of
298
+ * its own, as `createNodePlatform({ mail: { path } })` does: on a shard host's
299
+ * connection, a poll during `shard.transaction()` writes inside it, and that
300
+ * transaction's rollback would undo the acks and sent records and resend.
301
+ */
302
+ declare const createNodeMailHost: (database: Database.Database, options?: NodeMailHostOptions) => NodeMailHost;
68
303
  /** Options for {@link createNodeQueueHost}. */
69
304
  interface NodeQueueHostOptions<Queues extends Record<string, {
70
305
  isLunoraQueue: true;
@@ -118,7 +353,7 @@ interface NodeQueueHost<Queues extends Record<string, {
118
353
  body: unknown;
119
354
  id: string;
120
355
  }[];
121
- /** Return a parked message to its queue with `attempts` reset. `false` when no such message is parked. */
356
+ /** Return a parked message to its queue with `attempts` reset. `false` when no message of a queue this host declared is parked under that id. */
122
357
  requeue: (id: string) => boolean;
123
358
  };
124
359
  /** The caller's `env` plus one `QUEUE_<EXPORT>` binding per queue. */
@@ -137,6 +372,14 @@ interface NodeQueueHost<Queues extends Record<string, {
137
372
  declare const createNodeQueueHost: <Queues extends Record<string, {
138
373
  isLunoraQueue: true;
139
374
  }>>(database: Database.Database, options: NodeQueueHostOptions<Queues>) => NodeQueueHost<Queues>;
375
+ /** One declared cron job, as {@link NodeSchedulerHost.declareCrons} takes it. */
376
+ interface NodeDeclaredCron {
377
+ args: Record<string, unknown>;
378
+ expression: string;
379
+ functionPath: string;
380
+ /** The job's `cronJobs()` name, unique across the app. Keys its row. */
381
+ name: string;
382
+ }
140
383
  /** Options for {@link createNodeSchedulerHost}. */
141
384
  interface NodeSchedulerHostOptions {
142
385
  /**
@@ -146,17 +389,22 @@ interface NodeSchedulerHostOptions {
146
389
  * A handler that **throws** marks the delivery failed, which is what drives
147
390
  * the retry/dead-letter machinery: the job's `attempts` increments and it is
148
391
  * either re-armed with backoff or parked. A handler that resolves marks the
149
- * job delivered and removes it.
392
+ * job `succeeded`.
150
393
  *
151
394
  * Omitting it makes every delivery trivially succeed, which means a caller
152
395
  * who forgets to pass one gets a scheduler that quietly drops work — the
153
396
  * precise failure plan 267 caught. Supply one in anything real; the
154
397
  * conformance host supplies one purely so the TCK can tell a delivery apart
155
398
  * from an expired timer.
399
+ *
400
+ * `job.scheduledFor` is the due time (a cron tick's planned fire time).
401
+ * Forwarding it as the dispatch body's `scheduledFor` is what lets the shard
402
+ * record the `scheduler.lag_ms` metric, as the Worker dispatch path does.
156
403
  */
157
404
  onDispatch?: (functionPath: string, args: Record<string, unknown>, job: {
158
405
  attempts: number;
159
406
  id: string;
407
+ scheduledFor: number;
160
408
  }) => Promise<void> | void;
161
409
  }
162
410
  /**
@@ -164,6 +412,14 @@ interface NodeSchedulerHostOptions {
164
412
  * TCK's dead-letter legs need.
165
413
  */
166
414
  interface NodeSchedulerHost {
415
+ /**
416
+ * Make `crons` the app's declared cron set: upsert each one, arm it, and
417
+ * delete and disarm any declared row not in the list (a job the app removed
418
+ * or renamed). Every expression is parsed before anything is written, so an
419
+ * invalid one throws and leaves the previous set in place. Throws after
420
+ * `dispose()`.
421
+ */
422
+ declareCrons: (crons: ReadonlyArray<NodeDeclaredCron>) => void;
167
423
  /**
168
424
  * Clear every armed `setTimeout` (one-shot jobs and cron ticks alike) and
169
425
  * put the host into a terminal, closed state: afterwards `schedule()` and
@@ -177,6 +433,14 @@ interface NodeSchedulerHost {
177
433
  * left uncleared.
178
434
  */
179
435
  dispose: () => void;
436
+ /**
437
+ * Deliveries running now, one-shot jobs and cron ticks alike, each from its timer firing until the scheduler has
438
+ * recorded the outcome, labelled by job. A drain waits for these before the database the scheduler writes to is closed.
439
+ */
440
+ pendingDispatches: () => {
441
+ labels: string[];
442
+ waits: Promise<unknown>[];
443
+ };
180
444
  scheduler: SchedulerHost;
181
445
  /**
182
446
  * Drive a pending job straight to its dead-letter state without waiting out
@@ -185,6 +449,12 @@ interface NodeSchedulerHost {
185
449
  * while how many failures it takes to get there is host policy.
186
450
  */
187
451
  simulateDeadLetter: (id: string) => Promise<boolean>;
452
+ /**
453
+ * Stop firing: clear every armed timer and arm none from then on, while rows are still written and kept. A shutdown calls
454
+ * it before draining, so no job or cron tick starts after the drain checked for running work; each then re-arms from its
455
+ * row after a restart. A delivery already running finishes. One-way; `dispose()` still ends the host.
456
+ */
457
+ suspend: () => void;
188
458
  }
189
459
  /** Build a durable, SQLite-backed scheduler over `database`. */
190
460
  declare const createNodeSchedulerHost: (database: Database.Database, options?: NodeSchedulerHostOptions) => NodeSchedulerHost;
@@ -197,9 +467,12 @@ interface NodeShardHostOptions {
197
467
  * `_lunora_alarm` when the host is constructed over an existing database,
198
468
  * including an alarm whose time elapsed while nothing was running.
199
469
  *
200
- * A handler that throws is isolated to its own delivery; it never reaches
470
+ * A handler that throws is isolated to its own delivery — it never reaches
201
471
  * the caller that set the alarm, because by then that call has long
202
- * returned.
472
+ * returned — and the wakeup is then re-delivered with backoff up to
473
+ * {@link ALARM_RETRY_LIMIT} times, the way workerd retries a throwing
474
+ * `alarm()`. Delivery is at-least-once, so the handler must tolerate
475
+ * running twice for one scheduled timestamp.
203
476
  */
204
477
  onAlarm?: () => Promise<void> | void;
205
478
  /**
@@ -218,25 +491,59 @@ interface NodeShardHostOptions {
218
491
  /**
219
492
  * Build a `ShardHost` over a real `better-sqlite3` database.
220
493
  *
221
- * `runSerialized` chains onto a single `tail` promise rather than the
222
- * reference host's explicit job-array-plus-drain-loop: every queued closure
223
- * runs once `tail` settles, and `tail` is reset to a version that always
224
- * resolves (never rejects) so one job's failure cannot wedge the queue for
225
- * every job after it — the same "no two closures interleave" guarantee,
226
- * fewer moving parts to get wrong.
227
- *
228
- * `transaction` issues raw `BEGIN`/`COMMIT`/`ROLLBACK` — legal here (unlike
229
- * inside a Cloudflare Durable Object, where the runtime forbids it and
230
- * callers must use `storage.transaction`) because better-sqlite3 is a plain
231
- * embedded database with no platform-level transaction primitive layered over
232
- * it. It runs on its own private `transactionTail` chain, the same shape as
233
- * `runSerialized`'s but never shared with it: two bare, overlapping
234
- * `transaction()` calls on this host serialize against each other rather than
235
- * corrupting each other's commits (raw `BEGIN` on a connection already inside
236
- * a transaction throws, or worse, interleaves). Routing `transaction` through
237
- * `runSerialized` itself would deadlock, since the engine already composes
238
- * `runSerialized(() => transaction(work))` — the inner enqueue would then wait
239
- * on the outer closure awaiting it.
494
+ * `runSerialized` and `transaction` share **one** boundary lock, because they
495
+ * write **one** `better-sqlite3` connection. `transaction` issues raw
496
+ * `BEGIN`/`COMMIT`/`ROLLBACK` — legal here (unlike inside a Cloudflare Durable
497
+ * Object, where the runtime forbids it and callers must use
498
+ * `storage.transaction`) because better-sqlite3 is a plain embedded database
499
+ * with no platform-level transaction primitive layered over it.
500
+ *
501
+ * ## Why one lane and not two
502
+ *
503
+ * This host shipped with two private tail chains, one per entry point, so each
504
+ * serialized against itself and neither against the other. `runSerialized`
505
+ * issues no `BEGIN` of its own, so one of its closures overlapping a bare
506
+ * `transaction()` wrote straight into that transaction's span. `assertOwnTurn`
507
+ * below catches the write — it is the only reason this host never silently lost
508
+ * one the way an unguarded connection would — but catching it is not the same
509
+ * as preventing it, and the refusal lands in the wrong place:
510
+ *
511
+ * 1. A `runSerialized` closure writes a row. Nothing is open, so it commits.
512
+ * 2. It awaits (a scheduler hop, an `onShardInit` read, any real I/O).
513
+ * 3. A bare `transaction()` runs `BEGIN` while it is parked. `transaction` is
514
+ * a public contract surface, and `./node-shard-state` re-exports it as the
515
+ * `storage.transaction` member `ShardDO` documents as "the platform
516
+ * primitive", so a subclass reaches one without going through the engine.
517
+ * 4. The closure resumes and its next write is refused with
518
+ * `SHARD_UNAVAILABLE`, so `runSerialized` **rejects** — with step 1 already
519
+ * durable.
520
+ *
521
+ * The boundary the contract promises is atomic-or-nothing to its caller tore in
522
+ * half: a rejection the caller will retry, on top of a write the retry now
523
+ * re-applies. That is `runSerialized`'s "no two closures interleave" guarantee
524
+ * broken by a `transaction` it was never serialized against.
525
+ *
526
+ * ## Why the lock is re-entrant, and why `AsyncLocalStorage` is what makes it so
527
+ *
528
+ * The engine composes the two, and stacks them: `ShardRunner.runInTransaction`
529
+ * is `runSerialized(() => transaction(work))` (`@lunora/shard-engine`), and
530
+ * `ShardDO.fetch` widens a mutation dispatch carrying `x-lunora-mutation-id`
531
+ * into a *further* `runSerialized` span around it (`@lunora/do`). Under two
532
+ * plain FIFO chains that outer span is already fatal on this host — the inner
533
+ * `runSerialized` waits on a `tail` that only settles when the outer closure it
534
+ * is running inside resolves, and because nothing ever resets that `tail`, the
535
+ * shard's write lane is wedged for the life of the process rather than for the
536
+ * life of the request.
537
+ *
538
+ * So the lock is skipped for a boundary opened from inside a boundary, and
539
+ * `AsyncLocalStorage` is the only thing that can tell that case from the one
540
+ * that must queue: its store follows a single call's own await chain without
541
+ * leaking into a sibling chain. A held boolean cannot — it reads `true` for an
542
+ * unrelated *second top-level* `transaction()` too, which would then nest a raw
543
+ * `BEGIN` on a connection already inside one. This is the same distinction
544
+ * workerd's `blockConcurrencyWhile` draws natively with "does not queue events
545
+ * initiated as part of the callback itself", which is what
546
+ * `@lunora/platform-cloudflare` leans on for the identical composition.
240
547
  *
241
548
  * The returned `dispose()` is this host's lifecycle owner: it clears the
242
549
  * pending alarm `setTimeout` (so it can never fire against a connection this
@@ -247,13 +554,68 @@ interface NodeShardHostOptions {
247
554
  * connection are always retired together.
248
555
  */
249
556
  declare const createNodeShardHost: (options?: NodeShardHostOptions) => {
557
+ /** Settles once every alarm delivery running now (its handler and any retry write) has; `undefined` when none is. */
558
+ alarmsSettled: () => Promise<unknown> | undefined;
250
559
  database: Database.Database;
251
560
  dispose: () => void;
252
561
  drain: () => Promise<void>;
253
562
  host: ShardHost;
563
+ pendingAlarms: () => number;
564
+ pendingBackground: () => number;
565
+ /** Stop arming and claiming alarms, leaving the durable row for a restart. One-way: a closing registry calls it. */
566
+ suspendAlarms: () => void;
567
+ /** The failures recorded since the last call, which a drain reports in its result; each is also logged when it happens. */
568
+ takeFailures: () => string[];
254
569
  };
570
+ /** The end a shard accepts. Its `send` and `close` are what the socket host calls through its handle. */
571
+ interface NodeServerEnd {
572
+ close: (code?: number, reason?: string) => void;
573
+ send: (data: string | ArrayBuffer) => void;
574
+ }
575
+ /**
576
+ * The socket-host half of a Node platform instance, plus the test-only hooks
577
+ * `@lunora/platform/conformance`'s `ConformanceHost` needs to drive a recycle
578
+ * from inside a test.
579
+ */
580
+ interface NodeSocketHost {
581
+ /**
582
+ * Wait for every close handler still running, including ones they start. `undefined` when none are,
583
+ * so a caller can dispose synchronously.
584
+ */
585
+ drain: () => Promise<void> | undefined;
586
+ /** Deliver a connection's close to `handler`, which calls `webSocketClose`. One handler per host. */
587
+ onClose: (handler: (socket: NodeServerEnd, code: number, reason: string, wasClean: boolean) => void | Promise<void>) => void;
588
+ /**
589
+ * Deliver a connection's inbound frames to `handler`. The handler is the
590
+ * shard that accepted the connection, so it calls `webSocketMessage`. One
591
+ * handler per host: a later call replaces the earlier one.
592
+ */
593
+ onMessage: (handler: (socket: NodeServerEnd, data: string | ArrayBuffer) => void) => void;
594
+ /** Read back the frames sent to a socket, oldest first, text frames only. */
595
+ readFrames: (handle: SocketHandle) => string[];
596
+ /**
597
+ * Re-create a runtime socket from durable state.
598
+ *
599
+ * `attachment` is a fallback only: this host restores what it persisted,
600
+ * because that is what a real wake looks like. The argument covers an id
601
+ * this host never durably tracked (a synthetic id a test constructs).
602
+ */
603
+ restoreSocket: (id: string, attachment: unknown) => SocketHandle;
604
+ /** Drop the runtime socket map while keeping durable attachments/tags. */
605
+ simulateRecycle: () => void;
606
+ /** The `SocketHost` contract implementation. */
607
+ socket: SocketHost;
608
+ }
609
+ /** Build the socket registry, persisting attachments and tags to `database`. */
610
+ declare const createNodeSocketHost: (database: Database.Database) => NodeSocketHost;
255
611
  /** The contracts scoped to one shard key. */
256
612
  interface NodeShard {
613
+ /**
614
+ * Inbound socket events for this shard's registry. Bind the shard that owns
615
+ * the sockets here, so a frame or close reaches its `webSocketMessage` and
616
+ * `webSocketClose`. See `bindShardSockets`.
617
+ */
618
+ inbound: Pick<NodeSocketHost, "onClose" | "onMessage">;
257
619
  /** Durable key-value storage on this shard's database. */
258
620
  kv: ShardKvStore;
259
621
  /** Single-writer execution, local SQL, transactions, durable alarms. */
@@ -289,10 +651,32 @@ interface NodeShardRegistryOptions {
289
651
  }
290
652
  /** An in-process shard registry: placement, hosting, and the fan-out key set. */
291
653
  interface NodeShardRegistry {
292
- /** Dispose every live shard. Safe to call more than once. */
293
- close: () => void;
654
+ /**
655
+ * Dispose every live shard, and refuse new work from then on: `shardFor`, a stub's `fetch` and `rearmPersistedAlarms`
656
+ * throw once this is called, so nothing reopens a shard. Safe to call more than once. A shard that a request or a socket
657
+ * close handler is still using is disposed once that work settles, unless `force` is set: then it is disposed now and
658
+ * named in a log line. A shard whose dispose fails stays live; a failure after close() returned is logged and reported by
659
+ * the next `drain()`, and the next `close()` retries it. A shutdown passes `force` after its drain has finished or
660
+ * reached its deadline, so work that never settles cannot keep a database open at exit.
661
+ */
662
+ close: (options?: {
663
+ force?: boolean;
664
+ }) => void;
294
665
  /** The `ShardDirectory` to hand the runtime. */
295
666
  directory: DirectShardDirectory;
667
+ /**
668
+ * Wait until every shard is idle: no `onFetch` or `onAlarm` call in flight (a cron or scheduled job's delivery is one), no
669
+ * promise handed to a shard's `waitUntil` pending, and no socket close handler still running, across every live shard,
670
+ * including one opened while draining. Work that starts more work is waited for too. Bounded by `timeoutMs` (30 s by
671
+ * default); resolves with what was still running when it passed, which it also logs. A graceful shutdown awaits this, then
672
+ * calls {@link NodeShardRegistry.close}; `close()` alone does not wait for any of it.
673
+ */
674
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
675
+ /**
676
+ * Whether every shard is idle right now (nothing a {@link NodeShardRegistry.drain} would wait for). Synchronous, so a caller
677
+ * that drained several things can confirm all of them are still idle at one instant before it closes anything.
678
+ */
679
+ idle: () => boolean;
296
680
  /**
297
681
  * Every shard key this registry knows about — the set `@lunora/runtime`'s
298
682
  * query coordinator fans out over.
@@ -305,27 +689,91 @@ interface NodeShardRegistry {
305
689
  * cost of visiting shards that had nothing to say.
306
690
  */
307
691
  listShardKeys: (table?: string) => ReadonlyArray<string>;
692
+ /** What is running right now, one label per shard with its counts, as a drain that timed out would report it. */
693
+ pending: () => string[];
694
+ /**
695
+ * Open every stored shard that has a persisted alarm, so the alarm is re-armed now rather than when something next sends
696
+ * that shard a request: after a restart an alarm would otherwise never fire on a shard nobody calls. Shards without one stay
697
+ * closed. Returns the keys it opened. A process serving the registry calls this once, before it takes traffic.
698
+ */
699
+ rearmPersistedAlarms: () => string[];
308
700
  /** Materialize (or reuse) the shard serving `key`. */
309
701
  shardFor: (key: string) => NodeShard;
702
+ /**
703
+ * Stop arming and claiming alarms on every shard, including one opened afterwards, leaving each durable row to re-arm after
704
+ * a restart. A shutdown calls it before draining, so no alarm starts after the drain checked for running work. One-way;
705
+ * `close()` does it too.
706
+ */
707
+ suspendAlarms: () => void;
310
708
  }
311
709
  /** Build the in-process shard registry. */
312
710
  declare const createNodeShardRegistry: (options?: NodeShardRegistryOptions) => NodeShardRegistry;
711
+ /** Options for {@link createNodeWorkflowHost}. */
712
+ interface NodeWorkflowHostOptions<Workflows extends Record<string, {
713
+ isLunoraWorkflow: true;
714
+ }>> {
715
+ /** Base env merged under the derived workflow bindings — surfaced to workflow bodies as `ctx.env` and used to resolve spawned children. */
716
+ env?: Record<string, unknown>;
717
+ /** How long (ms) the engine holds a cross-process lease while an activation runs, for stores that implement `acquire`. Defaults to 30000. */
718
+ leaseTtlMs?: number;
719
+ /** Where runs are persisted. Required — see the header for why there is no default. `createNodeWorkflowStore(database)` is the durable one. */
720
+ store: WorkflowStore;
721
+ /** The declared workflows keyed by their `lunora/workflows.ts` export name (e.g. `{ orderPipeline: orderPipeline }`). Values must be `defineWorkflow` results. */
722
+ workflows: Workflows;
723
+ }
724
+ /** A fully-wired Node workflow host. */
725
+ interface NodeWorkflowHost<Workflows extends Record<string, {
726
+ isLunoraWorkflow: true;
727
+ }>> {
728
+ /** Per-export-name `WorkflowBindingLike` — the map `ctx.workflows` consumes. */
729
+ readonly bindings: { [K in keyof Workflows]: WorkflowBindingLike; };
730
+ /**
731
+ * The caller's `env` plus one binding per workflow under its class name
732
+ * (`OrderPipelineWorkflow`), the key `ctx.exports` would carry on Cloudflare —
733
+ * merge this into a worker env so `ctx.spawn`/`ctx.parallel` resolve
734
+ * children through the same runtime.
735
+ */
736
+ readonly env: Record<string, unknown>;
737
+ /** The underlying visulima runtime — `sweep`/`signal` for a dev loop or tests. */
738
+ readonly runtime: WorkflowRuntime;
739
+ }
740
+ /**
741
+ * Create a Node workflow host: compile every declared Lunora workflow onto the
742
+ * visulima engine, derive the workflow env, and expose the per-workflow
743
+ * `WorkflowBindingLike` handles.
744
+ */
745
+ declare const createNodeWorkflowHost: <Workflows extends Record<string, {
746
+ isLunoraWorkflow: true;
747
+ }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
748
+ /** One entry of the generated `LUNORA_CRONS` map (`_generated/crons.ts`). */
749
+ interface NodeCronJob {
750
+ args?: Record<string, unknown>;
751
+ functionPath?: string;
752
+ name: string;
753
+ workflow?: string;
754
+ }
313
755
  /** Every contract this package provides, composed for one Node process. */
314
756
  interface NodePlatform<Queues extends Record<string, {
315
757
  isLunoraQueue: true;
758
+ }> = Record<string, never>, Workflows extends Record<string, {
759
+ isLunoraWorkflow: true;
316
760
  }> = Record<string, never>> {
317
761
  /** `using platform = createNodePlatform(...)` support — delegates to `close()`. */
318
762
  [Symbol.dispose]: () => void;
319
763
  /** What this target supports — see `NODE_CAPABILITIES` in `@lunora/platform`. */
320
764
  capabilities: PlatformCapabilities;
321
765
  /**
322
- * Tear this platform instance down: clears the shard host's pending alarm
323
- * timer and closes its `better-sqlite3` database (and, with it, `kv`'s
324
- * table — both live on the same connection), then clears every armed
325
- * scheduler job timer. Nothing in this package closes these resources on
326
- * its own — a `NodePlatform` a caller stops using without calling `close()`
327
- * leaks the open file handle (plus its WAL/SHM sidecar files) and keeps
328
- * the process alive on outstanding timers. Safe to call more than once.
766
+ * Tear this platform instance down: every resource this root built, in
767
+ * reverse construction order — the global store's own connection, every
768
+ * armed scheduler job timer, the registry's live shards, and last the shard
769
+ * host's pending alarm timer and its `better-sqlite3` database (and, with
770
+ * it, `kv`'s table — both live on the same connection). Nothing in this
771
+ * package closes these resources on its own — a `NodePlatform` a caller
772
+ * stops using without calling `close()` leaks the open file handles (plus
773
+ * their WAL/SHM sidecar files) and keeps the process alive on outstanding
774
+ * timers. Safe to call more than once. A `createNodePlatform` that throws
775
+ * unwinds the same list itself, so a failed construction leaks nothing and
776
+ * leaves nothing to call this on.
329
777
  *
330
778
  * **`close()` is a terminal state, not merely a cleanup step.** After it
331
779
  * runs: `scheduler.schedule()` throws instead of arming a fresh timer
@@ -340,21 +788,83 @@ interface NodePlatform<Queues extends Record<string, {
340
788
  * any runtime socket map or durable row. A no-op instead of a throw would
341
789
  * be indistinguishable from a working call — exactly the silent-vanishing
342
790
  * this lifecycle exists to end.
791
+ *
792
+ * `force` is for a shutdown whose drain has finished or reached its deadline:
793
+ * a shard whose socket close handler is still running is disposed now (and
794
+ * logged) instead of once the handler settles. See `NodeShardRegistry.close`.
343
795
  */
344
- close: () => void;
796
+ close: (options?: {
797
+ force?: boolean;
798
+ }) => void;
345
799
  /** In-process shard directory (see `createNodeShardRegistry` for what it can and cannot do). */
346
800
  directory: ShardDirectory;
347
801
  /**
348
- * Wait for every promise handed to `shard.waitUntil` to settle.
802
+ * The scheduler dispatch route, served in-process: `Request` in, shard
803
+ * response out, no listener. It answers the path `@lunora/dispatch` and
804
+ * `@lunora/scheduler` POST to. Pass it to `dispatchQueueBatch` as
805
+ * `queueFetchImpl` on `createWorker` so a queue handler's `message.run` /
806
+ * `ctx.run` reaches the shard; the env you pass there must carry `LUNORA_ORIGIN_URL` and the same
807
+ * `LUNORA_ADMIN_TOKEN` as `dispatch.adminToken`. Every request is refused
808
+ * unless `dispatch` supplies a secret.
809
+ */
810
+ dispatch: (request: Request) => Promise<Response>;
811
+ /**
812
+ * Wait for every promise handed to `shard.waitUntil` to settle, for every
813
+ * `mail.poll()` in flight, and for the registry's shards to go idle
814
+ * (`NodeShardRegistry.drain`): in-flight `onFetch` and `onAlarm` calls,
815
+ * including cron and scheduled-job deliveries, and each shard's own
816
+ * `waitUntil` work.
349
817
  *
350
818
  * Separate from `close()` because the two answer different questions:
351
819
  * `close()` releases handles and stays synchronous (it backs
352
820
  * `Symbol.dispose`), while draining is inherently awaitable. A graceful
353
- * shutdown is `await platform.drain()` then `platform.close()`.
821
+ * shutdown is `await platform.drain()` then `platform.close()`. Bounded by
822
+ * `timeoutMs` (30 s by default); resolves with what was still running when
823
+ * it passed.
824
+ *
825
+ * Draining is the start of shutdown: it first stops the scheduler's job and
826
+ * cron timers and every alarm timer, so nothing new starts once the drain
827
+ * has found the platform idle. Their rows are kept and re-armed after a
828
+ * restart.
354
829
  */
355
- drain: () => Promise<void>;
830
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
831
+ /**
832
+ * The `.global()` backend, or `undefined` when the caller named no database
833
+ * file for it. There is no default path, because a global store silently
834
+ * rooted at `:memory:` loses every row when the process exits.
835
+ *
836
+ * **A building block, not a wiring.** Unlike its three siblings, nothing
837
+ * downstream of this composition root reads it: a `.global()` read or write
838
+ * reaches its backend through exactly one seam, `createShardCtxDb({ globalDb
839
+ * })`, and the only thing that passes `globalDb` is the generated `shard.ts`,
840
+ * from its `d1` / `hyperdriveGlobal` config thunks. `createNodePlatform`
841
+ * constructs no shard DO, so it cannot make that hop itself. A caller that
842
+ * wants `.global()` on this host makes it: after `migrate(schema)` has
843
+ * provisioned the tables, give the generated `createShardDO` a `d1` thunk
844
+ * returning `platform.globalTables.writer({ schema, … })` — `writer` builds
845
+ * the `createSqlCtxDb` facade that seam expects, and `node-platform.test.ts`
846
+ * round-trips a row through exactly that object.
847
+ */
848
+ globalTables?: NodeGlobalStore;
849
+ /**
850
+ * Whether nothing a {@link NodePlatform.drain} would wait for is running right now. Synchronous, so a caller draining
851
+ * several platforms or registries together can confirm they are all idle at one instant.
852
+ */
853
+ idle: () => boolean;
356
854
  /** Durable key-value storage backed by the same `better-sqlite3` database as `shard`. */
357
855
  kv: ShardKvStore;
856
+ /**
857
+ * Queued mail delivery, or `undefined` when the caller passed no `mail`.
858
+ * Its queue, sent ledger and key records live in `mail.path`, a database file
859
+ * of its own on its own connection, never the shard's: construction refuses a
860
+ * path that is the shard's file, the `globalTablesPath` file, or a `.sqlite3`
861
+ * file in the shard registry's `directory`.
862
+ */
863
+ mail?: NodeMailHost;
864
+ /** The local-filesystem bucket, or `undefined` when the caller named no bucket directory. */
865
+ objectStorage?: R2BucketLike;
866
+ /** What is running right now (host work, scheduler deliveries, each shard's work), as a timed-out drain would report it. */
867
+ pending: () => string[];
358
868
  /**
359
869
  * The declared queues, or `undefined` when the caller declared none.
360
870
  *
@@ -363,12 +873,48 @@ interface NodePlatform<Queues extends Record<string, {
363
873
  * works when no queue exists to send to.
364
874
  */
365
875
  queues?: NodeQueueHost<Queues>;
876
+ /** Open every stored shard with a persisted alarm, so it is re-armed before traffic arrives. See `NodeShardRegistry.rearmPersistedAlarms`. */
877
+ rearmPersistedAlarms: () => string[];
366
878
  /** Delayed jobs and crons, persisted to the same database and re-armed on construction. */
367
879
  scheduler: SchedulerHost;
368
880
  /** Single-writer execution, local SQL, transactions, durable alarms. */
369
881
  shard: ShardHost;
370
882
  /** Socket registry with mutable tags and SQLite-persisted attachments. */
371
883
  sockets: SocketHost;
884
+ /**
885
+ * The declared workflows, or `undefined` when the caller declared none.
886
+ * Runs are persisted to the same `better-sqlite3` database as the shard, so
887
+ * they survive a restart without a second store to configure.
888
+ */
889
+ workflows?: NodeWorkflowHost<Workflows>;
890
+ }
891
+ /**
892
+ * `createNodePlatform`'s `mail` option: the {@link NodeMailHostOptions} plus the
893
+ * database file the mail host keeps its queue, sent ledger and key records in.
894
+ *
895
+ * Its own file, never the shard's, and there is no default: a shard transaction
896
+ * holds the shard file across awaits, and mail written inside it would be rolled
897
+ * back with it (see `composeMail`). The same reason `globalTablesPath` has none.
898
+ */
899
+ type NodePlatformMailOptions = NodeMailHostOptions & {
900
+ /** The mail database file, for example `./.lunora/mail.sqlite3`. */
901
+ path: string;
902
+ };
903
+ /**
904
+ * The secrets the dispatch route authenticates with. With neither, the route
905
+ * refuses everything.
906
+ *
907
+ * Queue and topic delivery authenticates with `adminToken` alone:
908
+ * `@lunora/dispatch` always sends `Bearer <LUNORA_ADMIN_TOKEN>` and never signs,
909
+ * so the value here must match the token the caller puts on the env it passes
910
+ * `dispatchQueueBatch`. `schedulerSecret` only verifies a signed body, which the
911
+ * scheduler's own delivery sends; queue delivery never does.
912
+ */
913
+ interface NodePlatformDispatchOptions {
914
+ /** `LUNORA_ADMIN_TOKEN`. The bearer queue and topic delivery sends, so it must match the caller's env. */
915
+ adminToken?: string;
916
+ /** `LUNORA_SCHEDULER_SECRET`. When set, a signed body is verified against it. Queue delivery does not sign. */
917
+ schedulerSecret?: string;
372
918
  }
373
919
  /**
374
920
  * Options for {@link createNodePlatform} — the shard host's (`path`,
@@ -378,23 +924,80 @@ interface NodePlatform<Queues extends Record<string, {
378
924
  * or job with nowhere to land is bookkeeping. `directory` makes the shards the
379
925
  * directory resolves for fan-out file-backed too, and `onAlarm` gives their
380
926
  * durable alarms somewhere to land.
927
+ *
928
+ * `queues`, `workflows`, `objectStorageDirectory` and `globalTablesPath` are the
929
+ * four declarations — each is absent from the returned platform when omitted.
381
930
  */
382
931
  type NodePlatformOptions<Queues extends Record<string, {
383
932
  isLunoraQueue: true;
933
+ }> = Record<string, never>, Workflows extends Record<string, {
934
+ isLunoraWorkflow: true;
384
935
  }> = Record<string, never>> = {
385
936
  /**
386
- * Deliver one assembled queue batch — wire this to `dispatchQueueBatch`.
387
- * Required alongside `queues`; without it the messages would be stored
388
- * and never consumed.
937
+ * The app's declared crons — pass the generated `LUNORA_CRONS` map
938
+ * (`_generated/crons.ts`). Each job is armed on the scheduler and delivered
939
+ * through the same `onDispatch` a scheduled job uses, so it needs `onFetch`
940
+ * (or your own `onDispatch`) to reach a shard; a non-empty map with neither
941
+ * throws. Job names must be unique, every schedule must have a next
942
+ * occurrence, and schedules are read as UTC. The map is the whole declared
943
+ * set: a job declared by an earlier run and absent here is deleted. Omit
944
+ * the option and this process neither fires nor deletes declared jobs, so
945
+ * a script opening the same file leaves a running server's crons alone.
946
+ * Crons registered through `scheduler.cron()` are re-armed either way.
947
+ */
948
+ crons?: Readonly<Record<string, ReadonlyArray<NodeCronJob>>>;
949
+ /** Secrets for the dispatch route. Omit to leave the route refusing every request. */
950
+ dispatch?: NodePlatformDispatchOptions;
951
+ /**
952
+ * Database file the `.global()` tables live in — its own file, never a
953
+ * shard's, because a table every shard reads must not be inside any one of
954
+ * them. Omit when the app declares no `.global()` table; there is no
955
+ * default, for the same reason the bucket has none.
956
+ */
957
+ globalTablesPath?: string;
958
+ /**
959
+ * Deliver `@lunora/mail` sends: a durable `lunora-mail` queue drained
960
+ * through the given `transport` or, without one, Resend (`RESEND_API_KEY`), exposed as
961
+ * `platform.mail`. Its queue, sent ledger and key records live in `path`, a
962
+ * database file of their own (see {@link NodePlatformMailOptions}). Omit when
963
+ * the app sends no mail. Throws here, not on the first send, when `MAIL_FROM`
964
+ * is unset or nothing can deliver.
965
+ */
966
+ mail?: NodePlatformMailOptions;
967
+ /**
968
+ * Directory the object-storage bucket keeps its objects in, one file per
969
+ * key. Omit when the app declares no buckets — there is no default,
970
+ * because a bucket silently rooted at the process's working directory is
971
+ * worse than an absent one.
972
+ */
973
+ objectStorageDirectory?: string;
974
+ /**
975
+ * Deliver one assembled queue batch — wire this to the app worker's `queue`
976
+ * export from `createWorker`, not to bare `dispatchQueueBatch`. That export
977
+ * is the only path that hands the consumer `ctx.live`, and it takes
978
+ * `queueFetchImpl` (this platform's `dispatch`, wrapped as a `fetch`) so
979
+ * `ctx.run` reaches the shard here rather than `LUNORA_ORIGIN_URL`. Required
980
+ * alongside `queues`; without it the messages would be stored and never consumed.
389
981
  */
390
982
  onQueueBatch?: NodeQueueHostOptions<Queues>["onBatch"];
391
983
  /** The app's `defineQueue` results, keyed by export name. Omit when the app declares no queues. */
392
984
  queues?: Queues;
985
+ /** The app's `defineWorkflow` results, keyed by export name. Omit when the app declares no workflows. */
986
+ workflows?: Workflows;
393
987
  } & NodeSchedulerHostOptions & NodeShardHostOptions & NodeShardRegistryOptions;
394
988
  /** Compose every contract this package provides over one `better-sqlite3` database. */
395
989
  declare const createNodePlatform: <Queues extends Record<string, {
396
990
  isLunoraQueue: true;
397
- }> = Record<string, never>>(options?: NodePlatformOptions<Queues>) => NodePlatform<Queues>;
991
+ }> = Record<string, never>, Workflows extends Record<string, {
992
+ isLunoraWorkflow: true;
993
+ }> = Record<string, never>>(options?: NodePlatformOptions<Queues, Workflows>) => NodePlatform<Queues, Workflows>;
994
+ interface NodeProfileHandlerOptions {
995
+ /** The bearer a caller must present. Required and non-empty: an empty token would make the endpoint open to anyone. */
996
+ token: string;
997
+ }
998
+ type NodeProfileHandler = (request: Request) => Promise<Response>;
999
+ /** The public handler: the real profiler, guarded by `token`. */
1000
+ declare const createNodeProfileHandler: ({ token }: NodeProfileHandlerOptions) => NodeProfileHandler;
398
1001
  /** Options for {@link createNodeR2Bucket}. */
399
1002
  interface NodeR2BucketOptions {
400
1003
  /** The bucket directory — created on first write. Objects live here, one file per key. */
@@ -402,10 +1005,41 @@ interface NodeR2BucketOptions {
402
1005
  }
403
1006
  /**
404
1007
  * Create an `R2BucketLike` over the local filesystem. Any object shape
405
- * `createStorage({ bucket })` accepts — `put`/`get`/`head`/`delete`/`list` —
1008
+ * `createStorage({ bucket, bucketName })` accepts — `put`/`get`/`head`/`delete`/`list` —
406
1009
  * maps directly onto a file operation.
407
1010
  */
408
1011
  declare const createNodeR2Bucket: (options: NodeR2BucketOptions) => R2BucketLike;
1012
+ /** The shape `ctx.secrets` reads off `env[name]`: a Cloudflare Secrets Store secret binding. */
1013
+ interface NodeSecretBinding {
1014
+ get: () => Promise<string>;
1015
+ }
1016
+ /**
1017
+ * Build the `ctx.secrets` bindings for a Node host from environment variables:
1018
+ * one binding per name, spread into the `env` the worker and shard are built
1019
+ * over. `ctx.secrets.get(name)` then reads `source[name]`.
1020
+ *
1021
+ * Names are listed rather than every variable in `source` being bound, for the
1022
+ * same reason a wrangler config lists `secrets_store_secrets[]`: `ctx.secrets`
1023
+ * reaches only what was granted to it. It also keeps the bindings off names the
1024
+ * env already carries as plain strings (`LUNORA_ADMIN_TOKEN` and the like),
1025
+ * which the runtime reads as strings and a binding object would break; a
1026
+ * `LUNORA_*` name is refused for that reason.
1027
+ *
1028
+ * The value is read when `get()` is called, so an unused secret never has to be
1029
+ * set. An unset or empty variable rejects the call.
1030
+ * @param names The secret names the app reads through `ctx.secrets`.
1031
+ * @param source Where values come from; `process.env` unless given.
1032
+ */
1033
+ declare const createNodeSecretBindings: (names: ReadonlyArray<string>, source?: Readonly<Record<string, string | undefined>>) => Record<string, NodeSecretBinding>;
1034
+ /**
1035
+ * Present the node shard registry as the `ShardNamespaceLike` a worker is built
1036
+ * over (`createWorker({ shardDO })`).
1037
+ *
1038
+ * The registry names its id derivation `idForName`, which is the
1039
+ * `ShardDirectory` spelling; the worker reads Cloudflare's `idFromName`. Both
1040
+ * return the key itself here, so a stub from either route reaches the same shard.
1041
+ */
1042
+ declare const createNodeShardNamespace: (directory: DirectShardDirectory) => ShardNamespaceLike;
409
1043
  /**
410
1044
  * The `DurableObjectState` subset `ShardDO` consumes.
411
1045
  *
@@ -422,6 +1056,11 @@ interface NodeShardState {
422
1056
  id: {
423
1057
  name?: string;
424
1058
  };
1059
+ /** Open a connection pair. Read by `@lunora/platform-cloudflare`'s socket host, which has no `WebSocketPair` here. */
1060
+ openSocketPair: () => {
1061
+ client: unknown;
1062
+ server: unknown;
1063
+ };
425
1064
  storage: {
426
1065
  delete: (key: string) => Promise<boolean>;
427
1066
  deleteAlarm: () => Promise<void>;
@@ -438,6 +1077,8 @@ interface NodeShardState {
438
1077
  };
439
1078
  transaction: <T>(closure: () => Promise<T>) => Promise<T>;
440
1079
  };
1080
+ /** Build the upgrade response for a pair's client end. A Node `Response` cannot carry status 101, so this is a marker. */
1081
+ upgradeResponse: (client: unknown) => Response;
441
1082
  waitUntil: (promise: Promise<unknown>) => void;
442
1083
  }
443
1084
  /**
@@ -452,71 +1093,78 @@ interface NodeShardState {
452
1093
  * report a point-in-time restore that never happened.
453
1094
  */
454
1095
  declare const createNodeShardState: (shard: NodeShard) => NodeShardState;
455
- /**
456
- * The socket-host half of a Node platform instance, plus the test-only hooks
457
- * `@lunora/platform/conformance`'s `ConformanceHost` needs to drive a recycle
458
- * from inside a test.
459
- */
460
- interface NodeSocketHost {
461
- /** Read back the frames sent to a socket, oldest first, text frames only. */
462
- readFrames: (handle: SocketHandle) => string[];
463
- /**
464
- * Re-create a runtime socket from durable state.
465
- *
466
- * `attachment` is a fallback only: this host restores what it persisted,
467
- * because that is what a real wake looks like. The argument covers an id
468
- * this host never durably tracked (a synthetic id a test constructs).
469
- */
470
- restoreSocket: (id: string, attachment: unknown) => SocketHandle;
471
- /** Drop the runtime socket map while keeping durable attachments/tags. */
472
- simulateRecycle: () => void;
473
- /** The `SocketHost` contract implementation. */
474
- socket: SocketHost;
475
- }
476
- /** Build the socket registry, persisting attachments and tags to `database`. */
477
- declare const createNodeSocketHost: (database: Database.Database) => NodeSocketHost;
478
- /** Options for {@link createNodeWorkflowHost}. */
479
- interface NodeWorkflowHostOptions<Workflows extends Record<string, {
480
- isLunoraWorkflow: true;
481
- }>> {
482
- /** Base env merged under the derived `WORKFLOW_*` bindings — surfaced to workflow bodies as `ctx.env` and used to resolve spawned children. */
483
- env?: Record<string, unknown>;
484
- /** How long (ms) the engine holds a cross-process lease while an activation runs, for stores that implement `acquire`. Defaults to 30000. */
485
- leaseTtlMs?: number;
486
- /** Where runs are persisted. Required — see the header for why there is no default. `createNodeWorkflowStore(database)` is the durable one. */
487
- store: WorkflowStore;
488
- /** The declared workflows keyed by their `lunora/workflows.ts` export name (e.g. `{ orderPipeline: orderPipeline }`). Values must be `defineWorkflow` results. */
489
- workflows: Workflows;
490
- }
491
- /** A fully-wired Node workflow host. */
492
- interface NodeWorkflowHost<Workflows extends Record<string, {
493
- isLunoraWorkflow: true;
494
- }>> {
495
- /** Per-export-name `WorkflowBindingLike` — the map `ctx.workflows` consumes. */
496
- readonly bindings: { [K in keyof Workflows]: WorkflowBindingLike; };
497
- /**
498
- * The caller's `env` plus one `WORKFLOW_&lt;EXPORT>` binding per workflow —
499
- * merge this into a worker env so `ctx.spawn`/`ctx.parallel` resolve
500
- * children through the same runtime.
501
- */
502
- readonly env: Record<string, unknown>;
503
- /** The underlying visulima runtime — `sweep`/`signal` for a dev loop or tests. */
504
- readonly runtime: WorkflowRuntime;
1096
+ /** The two socket hooks a `ShardDO` runs on the Cloudflare runtime's behalf. */
1097
+ interface ShardSocketHooks {
1098
+ webSocketClose(ws: unknown, code: number, reason: string, wasClean: boolean): unknown;
1099
+ webSocketMessage(ws: unknown, message: string | ArrayBuffer): unknown;
505
1100
  }
506
1101
  /**
507
- * Create a Node workflow host: compile every declared Lunora workflow onto the
508
- * visulima engine, derive the `WORKFLOW_*` env, and expose the per-workflow
509
- * `WorkflowBindingLike` handles.
1102
+ * Deliver a shard's inbound socket events. The Cloudflare runtime calls
1103
+ * `webSocketMessage` and `webSocketClose` on the Durable Object for a hibernated
1104
+ * socket. On Node nothing does, so the embedder calls this once per shard
1105
+ * instance, at the same point it builds the shard.
510
1106
  */
511
- declare const createNodeWorkflowHost: <Workflows extends Record<string, {
512
- isLunoraWorkflow: true;
513
- }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
1107
+ declare const bindShardSockets: (shard: ShardSocketHooks, inbound: Pick<NodeShard["inbound"], "onClose" | "onMessage">) => void;
514
1108
  /**
515
1109
  * Build a durable {@link WorkflowStore} over a `better-sqlite3` connection.
516
1110
  * Pass the result as `createNodeWorkflowHost({ store })`.
517
1111
  */
518
1112
  declare const createNodeWorkflowStore: (database: Database.Database) => WorkflowStore;
519
- export {
1113
+ export { DEFAULT_DRAIN_TIMEOUT_MS,
1114
+ /**
1115
+ * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
1116
+ * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
1117
+ * `SchedulerHost`) over `better-sqlite3` and an in-process socket/directory/
1118
+ * scheduler registry.
1119
+ *
1120
+ * Promoted from `@lunora/platform`'s `node:sqlite` reference host
1121
+ * (`src/conformance/reference-host.ts`) under plan 234, then hardened until the
1122
+ * durability half of each contract actually holds: alarms and scheduler jobs
1123
+ * are persisted **and re-armed on construction**, socket attachments and tags
1124
+ * live in SQLite rather than a `Map`, and `.global()` tables run the real
1125
+ * `@lunora/sql-store` core (`./node-global-store`). Each of those is pinned by
1126
+ * a restart test — a second host over the same database file — not only by the
1127
+ * TCK's simulated recycle.
1128
+ *
1129
+ * Three suites run against this package: `@lunora/platform/conformance`'s host
1130
+ * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
1131
+ * lifecycle/global-store tests.
1132
+ *
1133
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1134
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1135
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1136
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1137
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1138
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1139
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1140
+ * is the one combination that fails at runtime with no diagnostic before it.
1141
+ *
1142
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1143
+ * nothing here owns a timer, so queue delivery is driven by an explicit
1144
+ * `poll()`. What exists is the listener a dev server would sit on:
1145
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1146
+ * streaming the response body, and `createNodeShardNamespace` presents the
1147
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
1148
+ * the Cloudflare product bindings with no local
1149
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1150
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
1151
+ * `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
1152
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
1153
+ * `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
1154
+ * (`./node-mail-host`) through Resend or a caller-supplied transport.
1155
+ *
1156
+ * `lunora deploy --target node` bundles an app into a container build context
1157
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1158
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1159
+ *
1160
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1161
+ * for `provision` — which reports, once, which declared features this target
1162
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
1163
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1164
+ * server, which is why both statements above hold at once. See
1165
+ * `plans/234-node-host-findings.md`.
1166
+ */
1167
+ type DrainOptions,
520
1168
  /**
521
1169
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
522
1170
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -536,18 +1184,41 @@ export {
536
1184
  * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
537
1185
  * lifecycle/global-store tests.
538
1186
  *
539
- * **Still missing**, and rated accordingly in `NODE_CAPABILITIES`
540
- * (`@lunora/platform`): a dev server — so `lunora dev --target node` does not
541
- * exist yet — plus most Cloudflare product bindings (Queues, Vectorize, Workers
542
- * AI, Browser Rendering, Containers, Analytics Engine, Pipelines, Secrets Store,
543
- * Hyperdrive). R2 buckets are emulated over the local filesystem
544
- * (`./node-r2-bucket`) and Workflows over the `@visulima/workflow` engine
545
- * (`./node-workflow-host`). Cross-shard fan-out is emulated via
546
- * `@lunora/runtime`'s query coordinator over the in-process shard registry, and
547
- * a `@lunora/config` deploy driver makes `--target node` resolve. See
1187
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1188
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1189
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1190
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1191
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1192
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1193
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1194
+ * is the one combination that fails at runtime with no diagnostic before it.
1195
+ *
1196
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1197
+ * nothing here owns a timer, so queue delivery is driven by an explicit
1198
+ * `poll()`. What exists is the listener a dev server would sit on:
1199
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1200
+ * streaming the response body, and `createNodeShardNamespace` presents the
1201
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
1202
+ * the Cloudflare product bindings with no local
1203
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1204
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
1205
+ * `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
1206
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
1207
+ * `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
1208
+ * (`./node-mail-host`) through Resend or a caller-supplied transport.
1209
+ *
1210
+ * `lunora deploy --target node` bundles an app into a container build context
1211
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1212
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1213
+ *
1214
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1215
+ * for `provision` — which reports, once, which declared features this target
1216
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
1217
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1218
+ * server, which is why both statements above hold at once. See
548
1219
  * `plans/234-node-host-findings.md`.
549
1220
  */
550
- type NodeGlobalContextDatabaseOptions,
1221
+ type DrainResult,
551
1222
  /**
552
1223
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
553
1224
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -567,18 +1238,41 @@ type NodeGlobalContextDatabaseOptions,
567
1238
  * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
568
1239
  * lifecycle/global-store tests.
569
1240
  *
570
- * **Still missing**, and rated accordingly in `NODE_CAPABILITIES`
571
- * (`@lunora/platform`): a dev server — so `lunora dev --target node` does not
572
- * exist yet — plus most Cloudflare product bindings (Queues, Vectorize, Workers
573
- * AI, Browser Rendering, Containers, Analytics Engine, Pipelines, Secrets Store,
574
- * Hyperdrive). R2 buckets are emulated over the local filesystem
575
- * (`./node-r2-bucket`) and Workflows over the `@visulima/workflow` engine
576
- * (`./node-workflow-host`). Cross-shard fan-out is emulated via
577
- * `@lunora/runtime`'s query coordinator over the in-process shard registry, and
578
- * a `@lunora/config` deploy driver makes `--target node` resolve. See
1241
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1242
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1243
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1244
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1245
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1246
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1247
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1248
+ * is the one combination that fails at runtime with no diagnostic before it.
1249
+ *
1250
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1251
+ * nothing here owns a timer, so queue delivery is driven by an explicit
1252
+ * `poll()`. What exists is the listener a dev server would sit on:
1253
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1254
+ * streaming the response body, and `createNodeShardNamespace` presents the
1255
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
1256
+ * the Cloudflare product bindings with no local
1257
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1258
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
1259
+ * `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
1260
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
1261
+ * `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
1262
+ * (`./node-mail-host`) through Resend or a caller-supplied transport.
1263
+ *
1264
+ * `lunora deploy --target node` bundles an app into a container build context
1265
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1266
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1267
+ *
1268
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1269
+ * for `provision` — which reports, once, which declared features this target
1270
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
1271
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1272
+ * server, which is why both statements above hold at once. See
579
1273
  * `plans/234-node-host-findings.md`.
580
1274
  */
581
- type NodeGlobalStore,
1275
+ type DrainTimer,
582
1276
  /**
583
1277
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
584
1278
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -598,15 +1292,38 @@ type NodeGlobalStore,
598
1292
  * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
599
1293
  * lifecycle/global-store tests.
600
1294
  *
601
- * **Still missing**, and rated accordingly in `NODE_CAPABILITIES`
602
- * (`@lunora/platform`): a dev server — so `lunora dev --target node` does not
603
- * exist yet — plus most Cloudflare product bindings (Queues, Vectorize, Workers
604
- * AI, Browser Rendering, Containers, Analytics Engine, Pipelines, Secrets Store,
605
- * Hyperdrive). R2 buckets are emulated over the local filesystem
606
- * (`./node-r2-bucket`) and Workflows over the `@visulima/workflow` engine
607
- * (`./node-workflow-host`). Cross-shard fan-out is emulated via
608
- * `@lunora/runtime`'s query coordinator over the in-process shard registry, and
609
- * a `@lunora/config` deploy driver makes `--target node` resolve. See
1295
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1296
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1297
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1298
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1299
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1300
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1301
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1302
+ * is the one combination that fails at runtime with no diagnostic before it.
1303
+ *
1304
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1305
+ * nothing here owns a timer, so queue delivery is driven by an explicit
1306
+ * `poll()`. What exists is the listener a dev server would sit on:
1307
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1308
+ * streaming the response body, and `createNodeShardNamespace` presents the
1309
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
1310
+ * the Cloudflare product bindings with no local
1311
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1312
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
1313
+ * `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
1314
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
1315
+ * `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
1316
+ * (`./node-mail-host`) through Resend or a caller-supplied transport.
1317
+ *
1318
+ * `lunora deploy --target node` bundles an app into a container build context
1319
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1320
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1321
+ *
1322
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1323
+ * for `provision` — which reports, once, which declared features this target
1324
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
1325
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1326
+ * server, which is why both statements above hold at once. See
610
1327
  * `plans/234-node-host-findings.md`.
611
1328
  */
612
- type NodeGlobalStoreOptions, type NodePlatform, type NodePlatformOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, createNodeGlobalStore, createNodePlatform, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeShardHost, createNodeShardKvStore, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
1329
+ type Drainable, type MailParkReason, NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodeMailHost, type NodeMailHostOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformMailOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodeMailHost, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };