@tinyactors/node 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts DELETED
@@ -1,1875 +0,0 @@
1
- /**
2
- * @file The desired public API of tinyactors: the design target, not a
3
- * description of what is built.
4
- *
5
- * Parts of this file are knowingly not implemented yet. Each declaration
6
- * that lib/ does not implement carries a marker on the line directly above
7
- * it (after its JSDoc, if it has one):
8
- *
9
- * // status: unimplemented
10
- * // status: partial: <what is missing>
11
- *
12
- * Do not delete a declaration because lib/ lacks it: implement it, or
13
- * leave it marked. `mise run check-api-status` (part of `mise run test`)
14
- * keeps the markers honest where the runtime can answer: a marked
15
- * declaration that exists fails, and an unmarked one that is missing
16
- * fails. `grep -n "// status:" index.d.ts` lists what is outstanding.
17
- */
18
-
19
- /** The package version. */
20
- export const version: string;
21
-
22
- /* --------------------------------------------------------------------------
23
- * Systems and scheduling
24
- * -------------------------------------------------------------------------- */
25
-
26
- export interface SystemOptions {
27
- /**
28
- * "realtime" (the default) follows a monotonic clock read natively; one
29
- * unreferenced timer fires due sends, so an idle system does not keep the
30
- * process alive. "manual" time moves only with advanceTo()/advanceBy()
31
- * (ADR 0007 point 3).
32
- */
33
- clock?: "realtime" | "manual";
34
- /** Core's logical time at creation, in milliseconds; default 0. */
35
- initialTime?: number;
36
- scheduling?: SchedulingOptions;
37
- /**
38
- * What happens to an actor that reaches a top-level final state (ADR 0012):
39
- * "destroy" (the default) destroys it after the `done` hook returns;
40
- * "retain" keeps it inspectable until it is destroyed.
41
- */
42
- finished?: "destroy" | "retain";
43
- /** Called at the end of the pump turn in which an actor finished. */
44
- done?: (record: DoneRecord) => void;
45
- /** Called at the end of the pump turn in which an actor faulted (ADR 0008). */
46
- fault?: (record: FaultRecord) => void;
47
- /**
48
- * Called for a message whose target is gone, finished, or refused it, at
49
- * most `messageBudget` times per pump turn (ADR 0008). Without a hook,
50
- * dead letters are only counted in stats().
51
- */
52
- deadLetter?: (record: DeadLetterRecord) => void;
53
- io?: Readonly<Record<string, IOProcessor>>;
54
- invokers?: Readonly<Record<string, Invoker>>;
55
- log?: LogSink;
56
- /**
57
- * How unload() keeps an actor's JavaScript values: "serialize" (the
58
- * default) writes them with v8.serialize, "handles" keeps each value by
59
- * handle in this process. unload() throws `unsupported` for a value it
60
- * can do neither with.
61
- */
62
- unloadValues?: "serialize" | "handles";
63
- }
64
-
65
- /** An actor finished (ADR 0012). The actor is still resident while the hook runs. */
66
- export interface DoneRecord<Data = unknown> {
67
- readonly actor: Actor;
68
- /** The top-level final state it reached (core ADR 0056). */
69
- readonly finalState: string;
70
- /** Its completion data (<donedata>), or undefined. */
71
- readonly data: Data | undefined;
72
- }
73
-
74
- /**
75
- * A core call for an actor failed; the actor is quarantined (ADR 0008). An
76
- * invoked child's parent also gets error.communication.invoke.<id>.quarantined
77
- * with `{ code, message }` from this record (napi ADR 0025).
78
- */
79
- export interface FaultRecord {
80
- readonly actor: Actor;
81
- readonly operation: string;
82
- readonly code: string;
83
- readonly message: string;
84
- }
85
-
86
- /**
87
- * A message that could not be delivered (ADR 0008). `target` is the actor it
88
- * was for, or the address when it was sent to a name with no resident actor
89
- * (ADR 0006).
90
- */
91
- export interface DeadLetterRecord {
92
- readonly target: ActorID | ActorAddress;
93
- readonly event: EventName;
94
- /** The message's data, absent when it had none: post it again with it. */
95
- readonly data?: unknown;
96
- /** The message's traceparent, absent when it was not traced. */
97
- readonly traceparent?: string;
98
- /**
99
- * `unloaded`: a name whose actor is unloaded and whose family has no
100
- * loader (setLoader), or mail left for an actor unloaded through the raw
101
- * layer. Mail that waited for a loader (napi ADR 0020) ends as `rejected`
102
- * (the loader said "not now"), `load-failed`, `load-timeout`, or
103
- * `waiting-full` (the address already had maxWaiting messages waiting).
104
- */
105
- readonly reason:
106
- | "not-found"
107
- | "done"
108
- | "destroyed"
109
- | "refused"
110
- | "unloaded"
111
- | "rejected"
112
- | "load-failed"
113
- | "load-timeout"
114
- | "waiting-full";
115
- /** Why the load failed: the rejection's reason, the loader's error, or the timeout. */
116
- readonly detail?: string;
117
- }
118
-
119
- /** Why a loader is called (setLoader). */
120
- export type LoadReason = "mail" | "timer";
121
-
122
- /**
123
- * What a loader returns (setLoader, napi ADR 0020). Session images are
124
- * process-local: after a process exit, rebuild an actor from the data the
125
- * application stored ({ spawn, binding }), or replay a log.
126
- */
127
- export type LoadResult<Data extends object = object> =
128
- | SessionImage<Data>
129
- | { readonly image: SessionImage<Data>; readonly restore?: (actor: ActorID) => unknown }
130
- | "offloaded"
131
- | {
132
- readonly spawn: Definition<Data>;
133
- readonly binding?: Partial<Data> | Data;
134
- readonly pendingSends?: readonly DelayedSendInspection[];
135
- }
136
- | "not-found"
137
- | "reject"
138
- | { readonly reject: unknown };
139
-
140
- export interface LoaderOptions {
141
- /** Milliseconds the loader may take; after that its mail is `load-timeout` (default 5000). */
142
- readonly timeout?: number;
143
- /** Messages that may wait for one address; the rest are `waiting-full` (default 1000). */
144
- readonly maxWaiting?: number;
145
- }
146
-
147
- export interface SchedulingOptions {
148
- /** Microsteps one resume may run before the actor yields (core's `budget`); default 64. */
149
- resumeBudget?: number;
150
- /**
151
- * Units of executable content one resume may run before the actor pauses
152
- * inside a microstep (core ADR 0061); 0 means no limit; default 1024.
153
- */
154
- actionBudget?: number;
155
- /** Runnable actors resumed in one pump turn; default 1024. */
156
- resumesPerTurn?: number;
157
- /** Maximum due sends dispatched during one pump turn; at least 1, default 1024. */
158
- dueBudget?: number;
159
- /**
160
- * Microsteps one macrostep may run before its actor is quarantined with
161
- * fault code `runaway` (core ADR 0075); 0 for no limit, default 100000. A
162
- * tenth of it writes a `tinyactors.macrostep.long` log. `release()` lets a
163
- * runaway finish its macrostep; the next one has the limit again.
164
- */
165
- microstepLimit?: number;
166
- /**
167
- * Deliveries started during one pump turn, and dead letters reported in
168
- * one turn; at least 1, default 1024.
169
- */
170
- messageBudget?: number;
171
- /**
172
- * Maximum accepted messages not yet delivered or reported; post() throws
173
- * `queue-full` beyond it. 0 or absent: no limit.
174
- */
175
- maxQueuedMessages?: number;
176
- /**
177
- * Maximum retained-bytes estimate of the data of accepted messages not yet
178
- * delivered or reported (ADR 0005 point 9); 0 or absent: no limit. The
179
- * estimate: `options.bytes`, or 2 bytes per string code unit, byteLength
180
- * for buffers, 64 for other objects, 0 for primitives. Mail between actors
181
- * carries no estimate.
182
- */
183
- maxRetainedBytes?: number;
184
- }
185
-
186
- export declare function createSystem(options?: SystemOptions): System;
187
-
188
- export interface System {
189
- /** The one member besides close() that works after close(); the others throw `closed`. */
190
- readonly closed: boolean;
191
- readonly clock: "realtime" | "manual";
192
- readonly time: number;
193
-
194
- /**
195
- * Compile and register a chart: a statechart() builder, or a spec in the
196
- * generated shape (the shape core's definition export returns). A refused
197
- * chart throws `invalid` or `unsupported`, with core's compile error as
198
- * `detail` (ChartRefusal). `options.microstepLimit` overrides the system's
199
- * `scheduling.microstepLimit` for this definition; 0 for no limit.
200
- */
201
- define<Data extends object = Record<string, unknown>>(
202
- source: DefinitionSpec | DefinitionBuilder<Data>,
203
- options?: { microstepLimit?: number },
204
- ): Definition<Data>;
205
- /**
206
- * Import an SCXML document (napi ADR 0019). Its `<scxml name>` is the
207
- * definition's family and is required; the revision is a hash of the
208
- * document. Its `datamodel` attribute picks `javascript` (also for a
209
- * document without one) or a data model registerDatamodel() registered;
210
- * `datamodel="null"` opts into core's null data model, which keeps no
211
- * data. lib/ ships no ECMAScript compiler, so under `javascript` an
212
- * expression may only be `In(state)` or a data name: register a data
213
- * model to compile others. A refused document throws `invalid` or
214
- * `unsupported` with ImportRefusal as `detail`, which says where.
215
- */
216
- define<Data extends object = Record<string, unknown>>(
217
- source: string | Uint8Array,
218
- options: {
219
- format: "scxml";
220
- /**
221
- * Fetches `<data src>` and `<script src>` while the document is
222
- * defined: the content as a string or a Uint8Array, or undefined for a
223
- * src it does not know, which refuses the document there. It also
224
- * fetches a literal `<invoke type="scxml" src>`, whose child chart is
225
- * compiled with the parent (napi ADR 0024). The definition keeps it
226
- * for children compiled at invoke time from `srcexpr`, and its
227
- * children inherit it.
228
- */
229
- resolve?: (src: string) => string | Uint8Array | undefined;
230
- /**
231
- * What the document is called, such as its path or a file:// URL: the
232
- * source its spans name (core ADR 0085), which sourceOf() answers and
233
- * a debugger opens (napi ADR 0026). Without it the spans name no
234
- * source, and a debug session shows the chart as SCXML it writes from
235
- * the definition, by `sourceReference`. A child fetched by `src` or `srcexpr` is named by
236
- * that src; a child inline in `<content>` has no name, since its lines
237
- * count from the start of its content.
238
- */
239
- name?: string;
240
- microstepLimit?: number;
241
- },
242
- ): Definition<Data>;
243
-
244
- /**
245
- * Register a data model for imported documents (ADR 0019): `compile`
246
- * turns each source expression into what a builder chart would pass, and
247
- * the built-in data model runs it. `javascript` and `null` are reserved.
248
- */
249
- registerDatamodel(name: string, datamodel: DatamodelCompiler): void;
250
-
251
- /**
252
- * The unretired definition with this identity. define() of an identity
253
- * already registered returns that definition and takes another hold;
254
- * different content under it throws `definition-mismatch`.
255
- */
256
- findDefinition(identity: DefinitionIdentity): Definition | undefined;
257
-
258
- spawn<Data extends object>(
259
- definition: Definition<Data>,
260
- options?: SpawnOptions<Data>,
261
- ): Actor<Data>;
262
-
263
- /** The resident actor the directory has at `address`, or undefined (ADR 0006). */
264
- findActor(address: ActorAddress): Actor | undefined;
265
-
266
- /** A snapshot of core's view of `actor`. Throws `not-found` once it is gone. */
267
- inspect<Data extends object>(actor: ActorID): ActorInspection<Data>;
268
- /** True while a resident actor has this ID. */
269
- exists(actor: ActorID): boolean;
270
- /** Terminate `actor`. Throws `not-found` once it is gone. */
271
- destroy(actor: ActorID): void;
272
- /** Put an actor that faulted back into scheduling (ADR 0008). */
273
- release(actor: ActorID): void;
274
-
275
- /** The messages waiting in `actor`'s mailbox, oldest first, at most `limit` (default 100). */
276
- mailbox(actor: ActorID, options?: { readonly limit?: number }): readonly QueuedMessage[];
277
- /**
278
- * Abandon `actor`'s macrostep (core ADR 0082): the actor keeps the
279
- * configuration after its last completed microstep, and the send() that
280
- * follows the macrostep rejects with `abandoned`. `busy` while it is
281
- * paused inside a microstep (the pump finishes that microstep in its next
282
- * turns) or before its bootstrap finished; `invalid` with no macrostep in
283
- * progress.
284
- */
285
- abandon(actor: ActorID): void;
286
- /**
287
- * Withdraw `actor`'s pending delayed sends with this ID (core ADR 0084),
288
- * the `id` DelayedSendInspection shows. `not-found` when it has none;
289
- * `done` when the only ones were refused once and belong to their
290
- * receiver now.
291
- */
292
- withdrawSend(actor: ActorID, sendID: string): void;
293
-
294
- /**
295
- * Capture `actor` in memory (core ADR 0013), with the data-model root it
296
- * has now. `busy` for an unpublished (prepared) actor.
297
- */
298
- capture<Data extends object>(actor: ActorID): SessionImage<Data>;
299
-
300
- /**
301
- * Offload a stable named actor from memory (core ADR 0074): its data,
302
- * history and pending delayed sends go to bytes this system keeps, and
303
- * mail to its address or its own next delayed send loads it back (the
304
- * family's loader decides when it has one; see setLoader). Throws `busy`
305
- * while it has mail waiting, is inside a macrostep or is quarantined. The
306
- * bytes are for this process only: to survive a restart, store its data
307
- * and inspect().delayedSends, and spawn it again with
308
- * { binding, pendingSends }.
309
- */
310
- unload(actor: ActorID): void;
311
-
312
- /**
313
- * Bring an unloaded named actor back: from the bytes unload() kept for an
314
- * address, or from a SessionImage; the same session ID, a new runtime ID
315
- * (core ADR 0066). `binding` replaces the data root outright, it is not
316
- * merged: for an address it replaces the data the actor was unloaded
317
- * with, which it keeps without one; from an image it defaults to the
318
- * image's root. A chart on the null data model has no root, and a binding
319
- * for it throws `unsupported`. An invocation active at capture is
320
- * reported to the actor as `error.communication.invoke.<id>.unavailable`
321
- * (core ADR 0038).
322
- */
323
- load<Data extends object>(
324
- target: SessionImage<Data> | ActorAddress,
325
- options?: { readonly binding?: Partial<Data> | Data },
326
- ): Actor<Data>;
327
-
328
- /**
329
- * Restore an image under a fresh runtime ID without touching the directory
330
- * (core ADR 0052). `binding` defaults to the root the image kept, which is
331
- * shared with the captured actor if it still runs.
332
- */
333
- reconstruct<Data extends object>(
334
- image: SessionImage<Data>,
335
- options?: { readonly binding?: Partial<Data> | Data },
336
- ): Actor<Data>;
337
-
338
- /** Release the address of an actor that stays unloaded; load() of its image then fails with `stale`. */
339
- removeUnloaded(address: ActorAddress): void;
340
-
341
- /**
342
- * Bring actors of `family` back when mail arrives for them (napi ADR
343
- * 0020). Mail for a name in `family` with no resident actor (unloaded, or
344
- * never seen here: the family is virtual) waits while the loader runs,
345
- * and is delivered first, in order, once it has loaded or spawned the
346
- * actor. One load runs per address. `why` is "timer" when an unloaded
347
- * actor's own delayed send is due. `null` removes the loader.
348
- */
349
- setLoader(
350
- family: string,
351
- loader:
352
- | ((
353
- address: ActorAddress,
354
- why: LoadReason,
355
- load: { readonly offloaded: boolean },
356
- ) => LoadResult | Promise<LoadResult>)
357
- | null,
358
- options?: LoaderOptions,
359
- ): void;
360
-
361
- /**
362
- * Wake the unloaded actor at `address` through its family's loader at
363
- * `time` (core's clock). unload() does this for the image's next deadline.
364
- * Nothing happens at `time` for an address with no unloaded actor and no
365
- * loader.
366
- */
367
- wakeAt(address: ActorAddress, time: number): void;
368
-
369
- /** Create an unpublished replacement for the named actor `incumbent` (Actor.prepareReplacement). */
370
- prepareReplacement<Data extends object>(
371
- incumbent: ActorID,
372
- definition: Definition<Data>,
373
- options?: ReplacementOptions<Data>,
374
- ): PreparedActor<Data>;
375
-
376
- /** Publish a prepared actor and destroy its incumbent (PreparedActor.activate). */
377
- activate<Data extends object>(prepared: PreparedActor<Data>): Actor<Data>;
378
-
379
- registerIO(type: string, processor: IOProcessor, options?: IOProcessorOptions): void;
380
- /** Open a scope that stores `uri` once, for a connection or a session (core ADR 0068). */
381
- openScope(type: string, uri: string): IOScope;
382
- /** Close a scope; events naming it then carry no origin. Idempotent. */
383
- closeScope(scope: IOScope): void;
384
- registerInvoker(type: string, invoker: Invoker): void;
385
- setLogSink(sink?: LogSink): void;
386
- /**
387
- * Hand traces to `sink` as OTLP protobuf (napi ADR 0016): once per pump
388
- * turn, one Uint8Array holding one ExportTraceServiceRequest with the
389
- * spans that ended. Post it to an OTLP/HTTP `/v1/traces` endpoint as it
390
- * is, or read it with decodeTraces(). Without a sink core builds no record.
391
- */
392
- setTraceSink(sink?: (traces: Uint8Array, logs?: Uint8Array) => void, options?: TraceSinkOptions): void;
393
- /** Changes `detail`, `kinds` and `sample` of the installed sink in place; open spans are kept. */
394
- configureTraces(options: TraceConfiguration): void;
395
- /**
396
- * Traces matching deliveries in full, sampled whatever the ratio, until
397
- * stop(): to these sessions (IDs or actors), to the actors at these
398
- * addresses, and to the actors of these definition families. What a
399
- * watched delivery causes is watched too. An address is resolved once,
400
- * now, to its resident actor's session: an address with none throws
401
- * `not-found`, and a later session at it is not watched.
402
- */
403
- watchTraces(watch: {
404
- sessions?: (bigint | number | ActorID)[];
405
- families?: string[];
406
- addresses?: { family: string; name: string }[];
407
- }): { stop(): void };
408
- /** Metrics as plain data: core's counters and occupancy, and napi's messages and memory. */
409
- metrics(): MetricsSnapshot;
410
-
411
- /**
412
- * Queue a message and return; a later pump turn delivers it (ADR 0005).
413
- * Messages to one target are delivered in the order they were accepted.
414
- * Mail for an actor that is gone is a dead letter, not an error. An
415
- * address is resolved through the directory when the post is accepted; a
416
- * name with no resident actor is a dead letter too (ADR 0006). Throws
417
- * `queue-full` at maxQueuedMessages or maxRetainedBytes. `data` is any JavaScript value, shared
418
- * with the receiver, not copied (ADR 0011); the receiver's expressions see
419
- * it as `context.event.data`.
420
- */
421
- post(target: ActorTarget, event: EventName, data?: unknown, options?: PostOptions): void;
422
-
423
- /**
424
- * Queue a message and return a promise (ADR 0005 point 11). With
425
- * `until: "completed"` (the default) it resolves once the macrostep the
426
- * message starts has ended, with the actor stable or done; with
427
- * `until: "accepted"` once the message is queued. It rejects when the
428
- * message becomes a dead letter, when its macrostep faults, on `signal`
429
- * (`aborted`), after `timeout` (`timeout`), when the queue is full
430
- * (`queue-full`), and on close() (`closed`) while it is pending. Abort
431
- * and timeout withdraw a message still queued; a delivered one is not
432
- * undone. Only misuse throws, and a call after close() throws `closed`.
433
- * A send() whose message becomes a dead letter rejects with the reason's
434
- * code: `not-found` (also for `destroyed`), `done`, `unloaded`,
435
- * `rejected`, `load-failed`, `load-timeout`, `waiting-full`, or `invalid`
436
- * for `refused`; a macrostep quarantined as a runaway rejects with
437
- * `runaway`.
438
- */
439
- send(
440
- target: ActorTarget,
441
- event: EventName,
442
- data?: unknown,
443
- options?: SendOptions,
444
- ): Promise<SendResult>;
445
-
446
- /** Resolve after all currently reachable work is quiescent. */
447
- flush(): Promise<void>;
448
-
449
- /**
450
- * Available only with a manual clock; throws `invalid` otherwise, or when
451
- * time would move backwards. Resolves once everything due has been
452
- * dispatched and the system is quiet.
453
- */
454
- advanceTo(time: number): Promise<void>;
455
- advanceBy(milliseconds: number): Promise<void>;
456
-
457
- /**
458
- * Resident actors as pages of IDs: each page is a Uint32Array of
459
- * interleaved [slot, generation] pairs (ADR 0003). Pages continue from
460
- * core's cursor, in slot order; a page is a snapshot (core ADR 0062).
461
- * This and actors() and definitions() are generators: `reentrant` inside
462
- * a core call, and an invalid `pageSize`, throw from the first next(),
463
- * not from the call.
464
- */
465
- actorIDs(options?: PageOptions): IterableIterator<Uint32Array>;
466
- /**
467
- * Resident actors' inspections, taken when the iterator reaches each
468
- * actor. Holds one page of IDs at a time; an actor destroyed after its
469
- * page was taken is skipped.
470
- */
471
- actors(options?: PageOptions): IterableIterator<ActorInspection>;
472
- /**
473
- * Every definition the system holds, as inspections, one page of IDs at
474
- * a time (core ADR 0078): builder and imported charts, their nested
475
- * inline children, and children compiled when an <invoke> ran. Retired
476
- * definitions still in use are included. A definition freed after its
477
- * page was taken is skipped.
478
- */
479
- definitions(options?: PageOptions): IterableIterator<DefinitionInspection>;
480
-
481
- /** Memory by category and allocator calls (ADRs 0009, 0014). Throws `closed` after close(). */
482
- stats(): SystemStats;
483
-
484
- /**
485
- * Stop scheduling, reject pending sends, destroy the native system, and
486
- * release every retained JavaScript value. Idempotent.
487
- */
488
- close(): void;
489
- [Symbol.dispose](): void;
490
- }
491
-
492
- export interface MemoryCounters {
493
- readonly bytesInUse: number;
494
- /** High-water mark of bytesInUse. */
495
- readonly peakBytes: number;
496
- /** The largest single allocation so far; in `total`, the largest of any category. */
497
- readonly largestBlock: number;
498
- readonly allocations: number;
499
- readonly frees: number;
500
- }
501
-
502
- export interface PageOptions {
503
- /** Items per page; default 1024, at most 65536. */
504
- readonly pageSize?: number;
505
- }
506
-
507
- export interface SystemStats {
508
- readonly memory: {
509
- readonly total: MemoryCounters;
510
- readonly core: MemoryCounters;
511
- readonly envelopes: MemoryCounters;
512
- readonly scheduling: MemoryCounters;
513
- readonly values: MemoryCounters;
514
- readonly directory: MemoryCounters;
515
- readonly scratch: MemoryCounters;
516
- readonly other: MemoryCounters;
517
- };
518
- /** Allocations plus frees: zero growth in steady state is the test signal. */
519
- readonly allocatorCalls: number;
520
- readonly messages: {
521
- /** Accepted messages not yet delivered or reported as dead letters. */
522
- readonly queued: number;
523
- readonly delivered: number;
524
- readonly deadLetters: number;
525
- };
526
- /** JavaScript values core and the mailboxes hold (ADR 0011). */
527
- readonly values: {
528
- /** Value boxes live now; numbers, booleans, null and undefined need none. */
529
- readonly live: number;
530
- /** Value boxes made since the system was created. */
531
- readonly made: number;
532
- };
533
- }
534
-
535
- export type EventName = string;
536
- export type ActorTarget = Actor | ActorID | ActorAddress;
537
-
538
- export interface ActorAddress {
539
- readonly family: string;
540
- readonly name: string;
541
- }
542
-
543
- declare const definitionIDBrand: unique symbol;
544
- declare const invocationIDBrand: unique symbol;
545
-
546
- /**
547
- * An actor's ID: its slot and generation in the actor table, two small
548
- * integers (ADR 0002). Equality is by value; among live actors the slot alone
549
- * is unique.
550
- */
551
- export interface ActorID {
552
- readonly system: System;
553
- readonly slot: number;
554
- readonly generation: number;
555
- }
556
- export type DefinitionID = bigint & { readonly [definitionIDBrand]: true };
557
- export type InvocationID = bigint & { readonly [invocationIDBrand]: true };
558
-
559
- export interface PostOptions {
560
- /** A W3C traceparent: the macrostep this message starts runs under it (ADR 0015). */
561
- traceparent?: string;
562
- /**
563
- * post() only checks it when called, throwing `aborted` if it already
564
- * aborted; send() also withdraws a message still queued when it aborts.
565
- */
566
- signal?: AbortSignal;
567
- /** The retained-bytes estimate of `data`, instead of the default (ADR 0005 point 9). */
568
- bytes?: number;
569
- /**
570
- * Who the receiver answers with `event.origin` and `event.originType`
571
- * (core ADR 0068): an I/O processor's type plus one request's reply URI,
572
- * a scope from openScope(), or a token its origin template renders.
573
- */
574
- origin?: IOOrigin;
575
- /**
576
- * An operator transition (core ADR 0082, ADR 0026): the message is taken
577
- * by a transition to `targets`, states of the target actor's chart, from
578
- * the active state `source` or the root, instead of by the chart's
579
- * transitions, with every exit, entry, history and invocation a chart
580
- * transition would have. It queues behind the mail before it. When it
581
- * arrives, an actor whose `source` is no longer active, or that runs
582
- * another revision by then, refuses it: a dead letter with reason
583
- * `refused` (a send() rejects with `invalid`), and the actor is not
584
- * quarantined. Only for an ActorID target.
585
- */
586
- transition?: { readonly targets: readonly string[]; readonly source?: string };
587
- }
588
-
589
- /** A message waiting in a mailbox (System.mailbox). */
590
- export interface QueuedMessage {
591
- readonly event: EventName;
592
- readonly data?: unknown;
593
- /** A send() waits for it. */
594
- readonly awaited: boolean;
595
- /** Its origin's scope, when it was posted with `origin: { type, scope }`. */
596
- readonly scope?: { readonly index: number; readonly generation: number };
597
- /** The operator transition it carries, by state names; `source` null is the root. */
598
- readonly transition?: { readonly source: string | null; readonly targets: readonly string[] };
599
- }
600
-
601
- export type IOOrigin =
602
- | { readonly type: string; readonly uri: string }
603
- | { readonly type: string; readonly scope: IOScope }
604
- | { readonly type: string; readonly token: number | bigint };
605
-
606
- /** A scope from System.openScope(); stale once closed. */
607
- export interface IOScope {
608
- readonly type: string;
609
- readonly uri: string;
610
- readonly index: number;
611
- readonly generation: number;
612
- }
613
-
614
- /**
615
- * Templates the native adapter renders without running JavaScript (core ADR
616
- * 0068): `location` is this session's address through the processor,
617
- * listed in `ioProcessors` ({session}, {family}, {name}); `origin` is the
618
- * URI of a computed origin ({token}).
619
- */
620
- export interface IOProcessorOptions {
621
- location?: string;
622
- origin?: string;
623
- }
624
-
625
- export interface SendOptions extends PostOptions {
626
- /** "completed" (default): the message's macrostep ended; "accepted": it is queued. */
627
- until?: "completed" | "accepted";
628
- /** Reject with `timeout`, and withdraw the message if still queued, after this many milliseconds. */
629
- timeout?: number;
630
- }
631
-
632
- export interface SendResult {
633
- /** The actor that ran the macrostep; for "accepted", the target when it was an ActorID. */
634
- readonly actor?: Actor;
635
- readonly status: "accepted" | "stable" | "done";
636
- /** "done": the actor's done data. */
637
- readonly completion?: unknown;
638
- }
639
-
640
- /* --------------------------------------------------------------------------
641
- * Definitions
642
- * -------------------------------------------------------------------------- */
643
-
644
- /**
645
- * A revision is stored as bytes. It reads back as a string when the bytes are
646
- * valid UTF-8, and as a Uint8Array otherwise.
647
- */
648
- export interface DefinitionIdentity {
649
- readonly family: string;
650
- readonly revision: string | Uint8Array;
651
- }
652
-
653
- /** How the chart uses a source expression (core ADR 0076). */
654
- export type ExpressionRole = "value" | "condition" | "location" | "script";
655
-
656
- /**
657
- * A data model for imported documents (napi ADR 0019). For "value",
658
- * "condition" and "script", compile returns a function called with `this` =
659
- * the data and one argument, the context; for "location", a data name or
660
- * `{ get(context), set(value, context) }`. Throwing refuses the chart; an
661
- * error with numeric `offset` and `length` points into `source`.
662
- */
663
- export interface DatamodelCompiler {
664
- compile(
665
- source: string,
666
- role: ExpressionRole,
667
- ): ((this: any, context: any) => unknown) | string | { get(this: any, context: any): unknown; set(this: any, value: unknown, context: any): void };
668
- }
669
-
670
- /** Why define(xml, { format: "scxml" }) refused a document, as `detail`. */
671
- export interface ImportRefusal {
672
- /** "decode": the document is not SCXML the codec reads; "compile": core refused the chart. */
673
- readonly stage: "decode" | "compile";
674
- readonly message: string;
675
- /** Where in the document, 1-based, when the refusal names a place. */
676
- readonly line?: number;
677
- readonly column?: number;
678
- /** The byte offset in the UTF-8 document. */
679
- readonly offset?: number;
680
- }
681
-
682
- /** Core's compile error, attached as `detail` when define() refuses a chart. */
683
- export interface ChartRefusal {
684
- /** The compile error code, e.g. "expression_rejected" or "unknown_state". */
685
- readonly code: string;
686
- /** Where in the spec, e.g. "states[0].transitions[1].condition". */
687
- readonly path: string;
688
- /** Core's compile error as the generated layer returns it. */
689
- readonly error: {
690
- readonly code: string;
691
- readonly path: readonly { readonly member: string; readonly index: number }[];
692
- readonly subject?: string;
693
- readonly related?: string;
694
- readonly message: string;
695
- };
696
- }
697
-
698
- export interface Definition<Data extends object = Record<string, unknown>> {
699
- readonly system: System;
700
- readonly id: DefinitionID;
701
- readonly identity: DefinitionIdentity;
702
- /**
703
- * True once retire() has run. Core frees a retired definition when no
704
- * actor uses it; a freed definition still reads as retired.
705
- */
706
- readonly retired: boolean;
707
-
708
- /** Read from core. Throws `not-found` once a retired definition is freed. */
709
- inspect(): DefinitionInspection;
710
-
711
- /**
712
- * Where element `id` of `kind` was written (core ADR 0085), or undefined
713
- * when the definition keeps no span for it. statechart() records the file,
714
- * line and column of the call that wrote each state, transition, initial
715
- * transition and action.
716
- */
717
- sourceOf(kind: ElementKind, id: number): SourcePlace | undefined;
718
-
719
- /** Prevent new actors from using this definition. Existing actors continue. */
720
- retire(): void;
721
- }
722
-
723
- /** The kinds of compiled element core numbers, as trace records name them. */
724
- export type ElementKind = "state" | "transition" | "action" | "expression";
725
-
726
- /**
727
- * A place in a source. Lines and columns count from 1; a column is the
728
- * engine's (UTF-16 code units in JavaScript). The column, the end and the
729
- * byte range are present when the front end knew them: statechart() and a
730
- * document codec record the column; a spec's span may give only a line.
731
- */
732
- export interface SourcePlace {
733
- /** The source's name: a file, a URL, or "" when the spec named none. */
734
- readonly source: string;
735
- readonly line: number;
736
- readonly column?: number;
737
- readonly endLine?: number;
738
- readonly endColumn?: number;
739
- readonly offset?: number;
740
- readonly length?: number;
741
- }
742
-
743
- export interface DefinitionInspection {
744
- readonly id: DefinitionID;
745
- readonly identity: DefinitionIdentity;
746
- /** StatechartOptions.name, or an imported document's `<scxml name>`. */
747
- readonly name?: string;
748
- /** The data model the chart was compiled against, e.g. "javascript". */
749
- readonly datamodel: string;
750
- readonly binding: "early" | "late";
751
- readonly retired: boolean;
752
- readonly actorCount: number;
753
- readonly stateCount: number;
754
- readonly actorFixedBytes: number;
755
- readonly definitionBytes: number;
756
- /** Holds taken by define() and not given back (core ADR 0077). */
757
- readonly holds: number;
758
- /** How many definitions nest this one as an inline child. */
759
- readonly nestedBy: number;
760
- /** The children this chart's <invoke>s nest, when it has any (core ADR 0078). */
761
- readonly nested?: readonly DefinitionID[];
762
- }
763
-
764
- /* --------------------------------------------------------------------------
765
- * Fluent definition builder
766
- * -------------------------------------------------------------------------- */
767
-
768
- export interface StatechartOptions extends DefinitionIdentity {
769
- readonly name?: string;
770
- readonly binding?: "early" | "late";
771
- }
772
-
773
- /**
774
- * Begin an ordered JavaScript-authored statechart definition. The builder is
775
- * mutable until build() or System.define() consumes it.
776
- */
777
- export declare function statechart<Data extends object>(
778
- options: StatechartOptions,
779
- ): DefinitionBuilder<Data>;
780
-
781
- export type Target = string | readonly string[];
782
- declare const literalValueBrand: unique symbol;
783
- export interface LiteralValue<Value> {
784
- readonly [literalValueBrand]: true;
785
- readonly value: Value;
786
- }
787
-
788
- /** Force a callable JavaScript value to be data rather than an expression. */
789
- export declare function literal<Value>(value: Value): LiteralValue<Value>;
790
-
791
- declare const contentValueBrand: unique symbol;
792
- export interface ContentValue {
793
- readonly [contentValueBrand]: true;
794
- /** The content's bytes: a string's UTF-8, or a copy of the Uint8Array. */
795
- readonly bytes: Uint8Array;
796
- readonly mediaType?: string;
797
- }
798
-
799
- /**
800
- * Literal SCXML `<content>`, kept in the definition as bytes with an
801
- * optional media type; accepted wherever a value is. A send's data reaches
802
- * its I/O processor, and an invoke's content its invoker, as text with
803
- * `contentType` (IORequest, InvokeRequest). Anywhere else the content is a
804
- * value: parsed as JSON when it parses, otherwise the text with each run of
805
- * whitespace made one space and none leading or trailing (SCXML B.2.2).
806
- */
807
- export declare function content(
808
- body: string | Uint8Array,
809
- options?: { readonly mediaType?: string },
810
- ): ContentValue;
811
-
812
- export type ValueInput<Data extends object, Value = unknown> =
813
- | (Value extends (...arguments_: never[]) => unknown ? never : Value)
814
- | LiteralValue<Value>
815
- | ContentValue
816
- | Expression<Data, Value>;
817
-
818
- export interface DefinitionBuilder<Data extends object>
819
- extends StateContainerBuilder<Data, DefinitionBuilder<Data>> {
820
- /** `initial` is data even when it is a function; content() is parsed (see content()). */
821
- data<Key extends keyof Data & string>(name: Key, initial: Data[Key] | ContentValue): this;
822
- dataExpression<Key extends keyof Data & string>(
823
- name: Key,
824
- initial: Expression<Data, Data[Key]>,
825
- ): this;
826
- initial(target: Target, actions?: ActionBlock<Data>): this;
827
- /** A script run once at initialization, after early-bound data (SCXML 3.2.2). */
828
- script(run: Script<Data>): this;
829
- build(): DefinitionSpec;
830
- }
831
-
832
- export type ActionBlock<Data extends object> = (
833
- actions: ActionBuilder<Data>,
834
- ) => void;
835
-
836
- export type StateBlock<Data extends object> = (
837
- state: StateBuilder<Data>,
838
- ) => void;
839
-
840
- export interface StateContainerBuilder<Data extends object, Self> {
841
- state(id: string, build?: StateBlock<Data>): Self;
842
- parallel(id: string, build: StateBlock<Data>): Self;
843
- final(id: string, build?: StateBlock<Data>): Self;
844
- /**
845
- * A history state. `build` gives it its default transition, which it
846
- * needs exactly one of, with always(): `h => h.always(t => t.target("a"))`.
847
- */
848
- history(
849
- id: string,
850
- depth: "shallow" | "deep",
851
- build: StateBlock<Data>,
852
- ): Self;
853
- }
854
-
855
- export interface StateBuilder<Data extends object>
856
- extends StateContainerBuilder<Data, StateBuilder<Data>> {
857
- /** Override the kind normally inferred from the builder method and children. */
858
- kind(kind: StateKind): this;
859
- initial(target: Target, actions?: ActionBlock<Data>): this;
860
-
861
- /** `initial` is data even when it is a function; content() is parsed (see content()). */
862
- data<Key extends keyof Data & string>(name: Key, initial: Data[Key] | ContentValue): this;
863
- dataExpression<Key extends keyof Data & string>(
864
- name: Key,
865
- initial: Expression<Data, Data[Key]>,
866
- ): this;
867
-
868
- /** Each call creates one separately-failing executable-content block. */
869
- entry(build: ActionBlock<Data>): this;
870
- exit(build: ActionBlock<Data>): this;
871
-
872
- /** Add an external transition in document order. */
873
- on(event: EventName, build?: TransitionBlock<Data>): this;
874
- /** Add an eventless transition in document order. */
875
- always(build: TransitionBlock<Data>): this;
876
- invoke(build: InvokeBlock<Data>): this;
877
- doneData(build: DoneDataBlock<Data>): this;
878
- }
879
-
880
- export type TransitionBlock<Data extends object> = (
881
- transition: TransitionBuilder<Data>,
882
- ) => void;
883
-
884
- export interface TransitionBuilder<Data extends object>
885
- extends ActionSequenceBuilder<Data, TransitionBuilder<Data>> {
886
- /** A function, or source text: "In('s')" or a data name. */
887
- when(condition: Condition<Data> | string): this;
888
- target(target: Target): this;
889
- internal(): this;
890
- external(): this;
891
- }
892
-
893
- export interface ActionBuilder<Data extends object>
894
- extends ActionSequenceBuilder<Data, ActionBuilder<Data>> {}
895
-
896
- export interface ActionSequenceBuilder<Data extends object, Self> {
897
- raise(event: EventName, data?: ValueInput<Data>): Self;
898
-
899
- send(event: StringSpec<Data>, build?: SendBlock<Data>): Self;
900
- cancel(sendID: StringSpec<Data>): Self;
901
-
902
- /** Assign a declared top-level data property. */
903
- assign<Key extends keyof Data & string>(
904
- location: Key,
905
- value: ValueInput<Data, Data[Key]>,
906
- ): Self;
907
- /** Assign through an explicit location, for nested or computed storage. */
908
- assignAt<Value>(
909
- location: Location<Data, Value>,
910
- value: ValueInput<Data, Value>,
911
- ): Self;
912
-
913
- script(run: Script<Data>): Self;
914
- log(label?: string, value?: Expression<Data> | string): Self;
915
-
916
- choose(
917
- condition: Condition<Data> | string,
918
- then: ActionBlock<Data>,
919
- otherwise?: ActionBlock<Data>,
920
- ): Self;
921
-
922
- forEach<Item>(
923
- array: Expression<Data, readonly Item[]> | (keyof Data & string) | LiteralValue<readonly Item[]>,
924
- item: keyof Data & string,
925
- build: ActionBlock<Data>,
926
- index?: keyof Data & string,
927
- ): Self;
928
- }
929
-
930
- export type SendBlock<Data extends object> = (send: SendBuilder<Data>) => void;
931
-
932
- export interface SendBuilder<Data extends object> {
933
- to(target: StringSpec<Data>): this;
934
- via(ioType: StringSpec<Data>): this;
935
- after(delay: DelaySpec<Data>): this;
936
- /** id() and idLocation() replace each other: the last one called wins. */
937
- id(id: string): this;
938
- idLocation(location: keyof Data & string | Location<Data, string>): this;
939
- data(value: ValueInput<Data>): this;
940
- param(name: string, value: ValueInput<Data>): this;
941
- }
942
-
943
- export type InvokeBlock<Data extends object> = (
944
- invoke: InvokeBuilder<Data>,
945
- ) => void;
946
-
947
- export interface InvokeBuilder<Data extends object> {
948
- /** id() and idLocation() replace each other: the last one called wins. */
949
- id(id: string): this;
950
- idLocation(location: keyof Data & string | Location<Data, string>): this;
951
- type(type: StringSpec<Data>): this;
952
- source(source: StringSpec<Data>): this;
953
- content(value: ValueInput<Data>): this;
954
- param(name: string, value: ValueInput<Data>): this;
955
- autoforward(enabled?: boolean): this;
956
- finalize(build: ActionBlock<Data>): this;
957
- }
958
-
959
- export type DoneDataBlock<Data extends object> = (
960
- done: DoneDataBuilder<Data>,
961
- ) => void;
962
-
963
- export interface DoneDataBuilder<Data extends object> {
964
- content(value: ValueInput<Data>): this;
965
- param(name: string, value: ValueInput<Data>): this;
966
- }
967
-
968
- /* --------------------------------------------------------------------------
969
- * Actors and lifecycle
970
- * -------------------------------------------------------------------------- */
971
-
972
- export interface SpawnOptions<Data extends object> {
973
- /** A W3C traceparent: the bootstrap runs under it (ADR 0015). */
974
- traceparent?: string;
975
- /** Omit both name and address for an anonymous actor. */
976
- readonly name?: string;
977
- readonly address?: ActorAddress;
978
- readonly binding?: Partial<Data>;
979
- /**
980
- * Delayed sends to re-arm before the actor bootstraps (core ADR 0074
981
- * section 8): entries of inspect().delayedSends from an earlier session
982
- * of this actor, stored with its data; they survive JSON and structured
983
- * clone, and may be re-armed in another system or process. They keep
984
- * their IDs, due times and traces; a due time already past fires on the
985
- * next dispatch. A `destination` of "self" goes to this new actor, and an
986
- * address to whatever actor has that address when the send is due. An
987
- * ActorID destination (a send to an unnamed other actor) re-arms only as
988
- * a live ActorID of this system; any other form of it throws `invalid`
989
- * naming the entry, since a stored slot and generation would name
990
- * whichever actor holds that slot by then.
991
- */
992
- readonly pendingSends?: readonly DelayedSendInspection[];
993
- }
994
-
995
- /**
996
- * The view spawn() returns (ADR 0002): an ActorID with methods that ask the
997
- * system. It holds no native resource and no finalizer.
998
- */
999
- export interface Actor<Data extends object = Record<string, unknown>> extends ActorID {
1000
- /**
1001
- * True once no resident actor has this ID: destroyed, finished and
1002
- * destroyed, or unloaded. Throws `closed` after close() of its system.
1003
- */
1004
- readonly destroyed: boolean;
1005
- equals(other: ActorID): boolean;
1006
-
1007
- post(event: EventName, data?: unknown, options?: PostOptions): void;
1008
- send(event: EventName, data?: unknown, options?: SendOptions): Promise<SendResult>;
1009
- inspect(): ActorInspection<Data>;
1010
-
1011
- /** A retained reference to the actor's live data-model root. */
1012
- data(): Data;
1013
-
1014
- /** Capture Tinyactors-owned state and the data-model root in memory (System.capture). */
1015
- capture(): SessionImage<Data>;
1016
-
1017
- /** Offload this stable named actor from memory (System.unload, core ADR 0074). */
1018
- unload(): void;
1019
-
1020
- /**
1021
- * Prepare a fresh unpublished actor of `definition` to replace this named
1022
- * actor in place. It bootstraps like a spawned actor, and core holds its
1023
- * visible bootstrap effects until activation. `binding` defaults to this
1024
- * actor's live data root when `definition` uses the JavaScript data model.
1025
- */
1026
- prepareReplacement(
1027
- definition: Definition<Data>,
1028
- options?: ReplacementOptions<Data>,
1029
- ): PreparedActor<Data>;
1030
-
1031
- /**
1032
- * Terminate this interpreter. Its active invocations are cancelled: an
1033
- * in-system SCXML child is destroyed with it, and a JavaScript invoker's
1034
- * service gets cancel().
1035
- */
1036
- destroy(): void;
1037
- [Symbol.dispose](): void;
1038
- }
1039
-
1040
- export interface PreparedActor<Data extends object> extends Actor<Data> {
1041
- /** False until activate() publishes it. */
1042
- readonly published: boolean;
1043
- readonly incumbent: ActorID;
1044
-
1045
- /**
1046
- * Publish this actor at the incumbent's address, then destroy the
1047
- * incumbent. Mail still waiting for the incumbent, and the send()s it
1048
- * carries, move in order to the front of this actor's mailbox, so nothing
1049
- * accepted for the address is lost; the incumbent's delayed sends are
1050
- * discarded. Throws `busy` while the incumbent is inside a macrostep. If
1051
- * activation fails, the incumbent keeps the address and this actor is left
1052
- * for the caller to destroy.
1053
- */
1054
- activate(): Actor<Data>;
1055
- }
1056
-
1057
- export interface ReplacementOptions<Data extends object> {
1058
- /** Defaults to the incumbent actor's current data-model root. */
1059
- readonly binding?: Partial<Data> | Data;
1060
- }
1061
-
1062
- /**
1063
- * Core's residency: "idle" between macrosteps, "running" inside one, "done"
1064
- * once finished. An unloaded actor is not resident: inspecting it throws
1065
- * `not-found`.
1066
- */
1067
- export type ActorResidency = "idle" | "running" | "done";
1068
-
1069
- /**
1070
- * A snapshot of core's view of one actor (ADR 0054: O(size of the actor)).
1071
- */
1072
- export interface ActorInspection<Data = unknown> {
1073
- readonly actor: Actor;
1074
- /** Stable across unload and load; the runtime ID is not (core ADR 0066). */
1075
- readonly sessionID: bigint;
1076
- readonly definition: DefinitionIdentity;
1077
- /** The definition's ID (Definition.id), which names its compiled states, transitions and actions. */
1078
- readonly definitionID: DefinitionID;
1079
- readonly residency: ActorResidency;
1080
- readonly published: boolean;
1081
- readonly activeStates: readonly string[];
1082
- readonly macrostepInProgress: boolean;
1083
- /** Paused inside a microstep, in executable content (core ADR 0061). */
1084
- readonly microstepInProgress: boolean;
1085
- /**
1086
- * The step key of where a paused macrostep stands (core ADR 0083);
1087
- * (session, 0, 0) outside a macrostep and before one begins.
1088
- */
1089
- readonly step: { readonly session: bigint; readonly macrostep: number; readonly microstep: number };
1090
- /**
1091
- * The unit a paused macrostep runs next (core ADR 0083): `at` is "none"
1092
- * between microsteps and outside a macrostep; otherwise the phase, the
1093
- * state, and the transition and action by compiled ID (core ADR 0071).
1094
- */
1095
- readonly position: TracePosition;
1096
- /** The external event of the macrostep in progress, or null. */
1097
- readonly currentEvent: InspectedEvent | null;
1098
- /** The internal queue, oldest first. */
1099
- readonly internalEvents: readonly InspectedEvent[];
1100
- readonly internalEventCount: number;
1101
- /** Active and finished invocations of active states. */
1102
- readonly invocations: readonly InvocationInspection[];
1103
- readonly delayedSendCount: number;
1104
- /** Pending delayed sends, by due time then send order (core ADR 0054). */
1105
- readonly delayedSends: readonly DelayedSendInspection[];
1106
- /** The addon's scheduling state (ADR 0005). */
1107
- readonly scheduling: "none" | "idle" | "ready" | "runnable" | "quarantined";
1108
- /** The top-level final state it reached, or null (core ADR 0056). */
1109
- readonly finalState: string | null;
1110
- readonly allocatedBytes: number;
1111
- /** The live data object (JavaScript data model), shared, not copied; undefined under the null data model. */
1112
- readonly data?: Data;
1113
- /** A finished actor's completion data (<donedata>), or undefined. */
1114
- readonly completion?: unknown;
1115
- }
1116
-
1117
- export interface InvocationInspection {
1118
- readonly id: InvocationID;
1119
- readonly type: string;
1120
- readonly active: boolean;
1121
- readonly autoforward: boolean;
1122
- /**
1123
- * The invoker's handle for the service. For the in-system SCXML invoker,
1124
- * the child's runtime ID as one integer, (generation << 32) | slot: it
1125
- * matches no actor once the child is unloaded or reconstructed.
1126
- */
1127
- readonly serviceHandle: bigint;
1128
- }
1129
-
1130
- export interface TracePosition {
1131
- readonly at: "none" | "select" | "exit" | "transition" | "enter" | "bootstrap" | "finalize" | "invoke";
1132
- readonly state: string | null;
1133
- readonly transition: number | null;
1134
- readonly action: number | null;
1135
- readonly iteration: number;
1136
- }
1137
-
1138
- /** An event as inspection reports it. */
1139
- export interface InspectedEvent {
1140
- readonly name: EventName;
1141
- readonly type: "external" | "internal" | "platform";
1142
- readonly sendID?: string;
1143
- /** Who sent it; absent when it has no origin, as after a post() without `origin`. */
1144
- readonly origin?: EventOrigin;
1145
- readonly data?: unknown;
1146
- }
1147
-
1148
- /**
1149
- * Who sent an event (core ADR 0068). `type` and `uri` are what the
1150
- * receiver's expressions see as `event.originType` and `event.origin`, so a
1151
- * reply can go to them; `uri` is absent once the origin's scope is closed.
1152
- * `invocation` is the InvocationInspection.id of the invocation whose
1153
- * service sent it; `scope` is the IOScope it was posted through.
1154
- */
1155
- export type EventOrigin = { readonly type: string; readonly uri?: string } & (
1156
- | { readonly kind: "actor"; readonly actor: ActorID | ActorAddress }
1157
- | { readonly kind: "invocation"; readonly invocation: InvocationID }
1158
- | { readonly kind: "io"; readonly scope?: { readonly index: number; readonly generation: number } }
1159
- );
1160
-
1161
- /** One pending delayed send; `delayedSends` is ordered by due time, then send order. */
1162
- export interface DelayedSendInspection {
1163
- /** The send ID as the chart names it (core ADR 0048), or null when it has none. */
1164
- readonly id: string | null;
1165
- readonly due: number;
1166
- readonly event: EventName;
1167
- readonly ioType: string;
1168
- /**
1169
- * The resolved receiver for the built-in SCXML processor: "self" for the
1170
- * actor itself (a send without a target, or to its own session), an
1171
- * address for a named receiver, or an ActorID for an unnamed other actor.
1172
- * null for custom processors, which use `target`.
1173
- */
1174
- readonly destination: "self" | ActorAddress | ActorID | null;
1175
- readonly target: unknown;
1176
- readonly data: unknown;
1177
- /** The router refused this send once; it is waiting to be offered again. */
1178
- readonly submitted: boolean;
1179
- /** A literal target's content ID in the definition, or null (core ADR 0074 section 8). */
1180
- readonly targetContent: number | null;
1181
- /** A literal <content>'s ID in the definition, or null. */
1182
- readonly content: number | null;
1183
- /** The sending step's trace, or null. */
1184
- readonly traceparent: string | null;
1185
- }
1186
-
1187
- /* --------------------------------------------------------------------------
1188
- * In-memory capture, unload, and reconstruction
1189
- * -------------------------------------------------------------------------- */
1190
-
1191
- /**
1192
- * A capture held in memory (ROADMAP step 14). Its handle is destroyed by
1193
- * destroy(), by its finalizer, or by close() of its system, whichever comes
1194
- * first; it never outlives its system (ADR 0012). Serializing it across
1195
- * processes is not supported: model network handoff with I/O processors.
1196
- */
1197
- export interface SessionImage<Data extends object = Record<string, unknown>> {
1198
- readonly origin: System;
1199
- /** The actor at capture; its ID is stale once the actor is unloaded. */
1200
- readonly actor: ActorID;
1201
- /** Stable across unload and load (core ADR 0066). */
1202
- readonly sessionID: bigint;
1203
- readonly definition: DefinitionIdentity;
1204
- readonly address?: ActorAddress;
1205
- /** The data-model root at capture (shared, not copied), or undefined under the null data model. */
1206
- readonly data?: Data;
1207
- /** The earliest pending delayed send's due time, or undefined. */
1208
- readonly nextDeadline?: number;
1209
- /** True after destroy() or close() of its system. */
1210
- readonly destroyed: boolean;
1211
-
1212
- destroy(): void;
1213
- [Symbol.dispose](): void;
1214
- }
1215
-
1216
- /* --------------------------------------------------------------------------
1217
- * JavaScript data-model callbacks
1218
- * -------------------------------------------------------------------------- */
1219
-
1220
- export interface EvaluationContext<Data extends object> {
1221
- readonly data: Data;
1222
- readonly event?: ActorEvent;
1223
- readonly sessionID: string;
1224
- readonly name?: string;
1225
- readonly ioProcessors: Readonly<Record<string, { readonly location: string }>>;
1226
- inState(state: string): boolean;
1227
- }
1228
-
1229
- export type Expression<Data extends object, Result = unknown> = (
1230
- this: Data,
1231
- context: EvaluationContext<Data>,
1232
- ) => Result;
1233
-
1234
- export type Condition<Data extends object> = Expression<Data, unknown>;
1235
-
1236
- export type Script<Data extends object> = (
1237
- this: Data,
1238
- context: EvaluationContext<Data>,
1239
- ) => void;
1240
-
1241
- export interface Location<Data extends object, Value = unknown> {
1242
- get(this: Data, context: EvaluationContext<Data>): Value;
1243
- set(this: Data, value: Value, context: EvaluationContext<Data>): void;
1244
- }
1245
-
1246
- export type StringSpec<Data extends object> = string | Expression<Data, string>;
1247
-
1248
- /**
1249
- * A number is milliseconds, written as `${number}ms` for core, which takes
1250
- * an SCXML duration: a non-negative decimal without an exponent, so a
1251
- * number JavaScript prints with one (1e21, 1e-7) is refused at define(). A
1252
- * function's result is checked only when the send runs; a negative or NaN
1253
- * delay then raises `error.execution`.
1254
- */
1255
- export type DelaySpec<Data extends object> =
1256
- | number
1257
- | `${number}ms`
1258
- | `${number}s`
1259
- | Expression<Data, number | string>;
1260
-
1261
- /**
1262
- * The event an expression sees as `context.event` (SCXML _event). `origin`
1263
- * is a URI a send can target: `#_scxml_<sessionID>` or
1264
- * `#_actor_<family>/<name>` (core ADR 0044), so replying is
1265
- * `send("reply").to(({ event }) => event.origin)`.
1266
- */
1267
- export interface ActorEvent<Data = unknown> {
1268
- readonly name: EventName;
1269
- readonly type: "external" | "internal" | "platform";
1270
- readonly sendID?: string;
1271
- readonly origin?: string;
1272
- readonly originType?: string;
1273
- readonly invocationID?: string;
1274
- readonly data: Data;
1275
- }
1276
-
1277
- /* --------------------------------------------------------------------------
1278
- * Statechart specs: the generated shape (ADR 0013)
1279
- *
1280
- * System.define() accepts this shape as a plain object; statechart() emits
1281
- * it; core's definition export returns it. Member names follow core's C
1282
- * spelling, and a tagged union is { kind, <member>: ... }.
1283
- *
1284
- * An expression is a JavaScript function (a condition, value or script,
1285
- * called with `this` bound to the actor's data), a literal() value, or source
1286
- * text: `In(state)`, or a data name, which reads that property (ADR 0011). A
1287
- * location is a data name or a { get, set } object. A spec compiles against
1288
- * the JavaScript data model ("javascript") unless it opts into core's null
1289
- * data model with `datamodel: "null"`. A script, unlike other expressions,
1290
- * must be a function.
1291
- * -------------------------------------------------------------------------- */
1292
-
1293
- /** A function, a literal(), or source text (In(state) or a data name). */
1294
- export type ExpressionSpec =
1295
- | string
1296
- | ((this: any, context: EvaluationContext<any>) => unknown)
1297
- | LiteralValue<unknown>;
1298
- /**
1299
- * A script. Source text and literal() compile, but running them fails with
1300
- * an internal `error.execution` (a script must be a function).
1301
- */
1302
- export type ScriptSpec = (this: any, context: EvaluationContext<any>) => void;
1303
- /** A data name, or a { get, set } location. */
1304
- export type LocationSpec = string | Location<any, unknown>;
1305
-
1306
- export type StateKind =
1307
- | "atomic"
1308
- | "compound"
1309
- | "parallel"
1310
- | "final"
1311
- | "history_shallow"
1312
- | "history_deep";
1313
-
1314
- export interface DefinitionSpec {
1315
- /** The statechart document name. */
1316
- readonly name?: string;
1317
- /**
1318
- * "javascript" when absent. "null" opts into core's null data model: no
1319
- * data, no functions, and content that cannot become a value. define()
1320
- * compiles every other name as "javascript", which core then refuses: a
1321
- * data model registerDatamodel() registered is only for imported SCXML.
1322
- */
1323
- readonly datamodel?: "null" | "javascript";
1324
- readonly identity?: {
1325
- readonly family: { readonly name: string };
1326
- readonly revision: string | Uint8Array;
1327
- };
1328
- /** "default" is early binding: inspection reports it as "early". */
1329
- readonly binding?: "default" | "early" | "late";
1330
- readonly initial?: InitialSpec;
1331
- /** Document order is semantically significant. */
1332
- readonly states?: readonly StateSpec[];
1333
- readonly data?: readonly DataSpec[];
1334
- readonly script?: ScriptSpec;
1335
- /** Where the script was written: an index into `spans`, from 1. */
1336
- readonly script_span?: number;
1337
- /**
1338
- * Where elements were written (core ADR 0085): each element's `span` is an
1339
- * index into this list, from 1, and each span's `source` an index into
1340
- * `sources`. None of it changes the revision. statechart() fills them in.
1341
- */
1342
- readonly spans?: readonly SpanSpec[];
1343
- readonly sources?: readonly { readonly name: string }[];
1344
- }
1345
-
1346
- export interface SpanSpec {
1347
- readonly source?: number;
1348
- readonly line: number;
1349
- readonly column?: number;
1350
- readonly end_line?: number;
1351
- readonly end_column?: number;
1352
- readonly offset?: bigint;
1353
- readonly length?: number;
1354
- }
1355
-
1356
- export interface StateSpec {
1357
- readonly kind: StateKind;
1358
- readonly span?: number;
1359
- readonly id: string;
1360
- readonly states?: readonly StateSpec[];
1361
- readonly initial?: InitialSpec;
1362
- readonly transitions?: readonly TransitionSpec[];
1363
- /** Each handler is one separately-failing executable-content block. */
1364
- readonly onentry?: readonly HandlerSpec[];
1365
- readonly onexit?: readonly HandlerSpec[];
1366
- readonly data?: readonly DataSpec[];
1367
- readonly invokes?: readonly InvokeSpec[];
1368
- readonly done_data?: DoneDataSpec;
1369
- }
1370
-
1371
- export interface InitialSpec {
1372
- readonly targets: readonly string[];
1373
- readonly actions?: readonly ActionSpec[];
1374
- readonly span?: number;
1375
- }
1376
-
1377
- export interface TransitionSpec {
1378
- readonly kind: "external" | "internal";
1379
- readonly span?: number;
1380
- /** Omit for an eventless transition. Wildcard segments are supported. */
1381
- readonly event?: string;
1382
- readonly condition?: ExpressionSpec;
1383
- readonly targets?: readonly string[];
1384
- readonly actions?: readonly ActionSpec[];
1385
- }
1386
-
1387
- export interface HandlerSpec {
1388
- readonly actions: readonly ActionSpec[];
1389
- }
1390
-
1391
- export interface DataSpec {
1392
- readonly name: string;
1393
- readonly initializer?: ValueSourceSpec;
1394
- }
1395
-
1396
- export type ValueSourceSpec =
1397
- | { readonly kind: "expr"; readonly expr: ExpressionSpec }
1398
- | { readonly kind: "location"; readonly location: LocationSpec }
1399
- | { readonly kind: "content"; readonly content: { readonly media_type?: string; readonly bytes: Uint8Array } };
1400
-
1401
- /** An `x` / `xexpr` attribute pair. */
1402
- export type StringAttributeSpec =
1403
- | { readonly kind: "literal"; readonly literal: string }
1404
- | { readonly kind: "expr"; readonly expr: ExpressionSpec };
1405
-
1406
- export type ActionSpec = { readonly span?: number } & (
1407
- | { readonly kind: "raise"; readonly raise: { readonly event: string; readonly data?: ValueSourceSpec } }
1408
- | { readonly kind: "send"; readonly send: SendSpec }
1409
- | { readonly kind: "cancel"; readonly cancel: { readonly sendid: StringAttributeSpec } }
1410
- | { readonly kind: "assign"; readonly assign: { readonly location: LocationSpec; readonly value?: ValueSourceSpec } }
1411
- | { readonly kind: "script"; readonly script: { readonly script: ScriptSpec } }
1412
- | { readonly kind: "log"; readonly log: { readonly label?: string; readonly expr?: ExpressionSpec } }
1413
- | {
1414
- readonly kind: "if";
1415
- readonly conditional: {
1416
- readonly condition: ExpressionSpec;
1417
- readonly then_actions?: readonly ActionSpec[];
1418
- readonly else_actions?: readonly ActionSpec[];
1419
- };
1420
- }
1421
- | {
1422
- readonly kind: "foreach";
1423
- readonly foreach: {
1424
- readonly array: ExpressionSpec;
1425
- readonly item: string;
1426
- readonly index?: string;
1427
- readonly body?: readonly ActionSpec[];
1428
- };
1429
- }
1430
- );
1431
-
1432
- export interface SendSpec {
1433
- readonly id?: { readonly kind: "literal"; readonly literal: string } | { readonly kind: "location"; readonly location: LocationSpec };
1434
- readonly type?: StringAttributeSpec;
1435
- readonly event?: { readonly kind: "name"; readonly name: string } | { readonly kind: "expr"; readonly expr: ExpressionSpec };
1436
- readonly target?: StringAttributeSpec;
1437
- /** A literal delay is an SCXML duration such as "500ms" or "5s". */
1438
- readonly delay?: StringAttributeSpec;
1439
- readonly data?: ValueSourceSpec;
1440
- readonly params?: readonly ParamSpec[];
1441
- }
1442
-
1443
- export interface ParamSpec {
1444
- readonly name: string;
1445
- readonly value?: ValueSourceSpec;
1446
- }
1447
-
1448
- export interface InvokeSpec {
1449
- readonly kind: "invoke";
1450
- readonly id?: { readonly kind: "literal"; readonly literal: string } | { readonly kind: "location"; readonly location: LocationSpec };
1451
- readonly type?: StringAttributeSpec;
1452
- readonly src?: StringAttributeSpec;
1453
- readonly data?: ValueSourceSpec;
1454
- readonly autoforward?: boolean;
1455
- readonly params?: readonly ParamSpec[];
1456
- readonly finalize?: readonly ActionSpec[];
1457
- }
1458
-
1459
- export interface DoneDataSpec {
1460
- readonly content?: ValueSourceSpec;
1461
- readonly params?: readonly ParamSpec[];
1462
- }
1463
-
1464
- /* --------------------------------------------------------------------------
1465
- * Host extensions
1466
- * -------------------------------------------------------------------------- */
1467
-
1468
- /**
1469
- * An I/O processor for `<send type>` (ROADMAP step 13). Core calls it while an
1470
- * actor runs, so the call is queued and send() runs at the end of that pump
1471
- * turn, never inside core. A reply is an event the processor posts, now or
1472
- * later. Throwing, or returning a promise that rejects, fails the send: the
1473
- * sender gets an external `error.communication` event with data
1474
- * { sendID, type, error }.
1475
- */
1476
- export interface IOProcessor extends IOProcessorOptions {
1477
- send(request: IORequest, context: EffectContext): void | Promise<void>;
1478
- }
1479
-
1480
- export interface IORequest {
1481
- /** The sending actor: an ActorID, or its address when it is named. */
1482
- readonly source: ActorID | ActorAddress;
1483
- /** The send's ID text (`<send id>` or core's generated one), or null for a send without one. */
1484
- readonly sendID: string | null;
1485
- readonly event: EventName;
1486
- readonly type: string;
1487
- readonly target: unknown;
1488
- readonly data: unknown;
1489
- /** A literal <content>, as text, with its media type. */
1490
- readonly content?: string;
1491
- readonly contentType?: string;
1492
- }
1493
-
1494
- /**
1495
- * One per system, except that a request carrying a traceparent gets its
1496
- * own, whose post() carries that traceparent unless given another.
1497
- * `signal` aborts on close().
1498
- */
1499
- export interface EffectContext {
1500
- readonly system: System;
1501
- readonly signal: AbortSignal;
1502
- post(target: ActorTarget, event: EventName, data?: unknown, options?: PostOptions): void;
1503
- }
1504
-
1505
- /**
1506
- * An invoker for `<invoke type>` (ROADMAP step 13). start() runs at the end
1507
- * of the pump turn in which core started the invocation; the service's
1508
- * cancel() runs when the invoking state exits, and forward() gets
1509
- * autoforwarded events.
1510
- */
1511
- export interface Invoker {
1512
- start(request: InvokeRequest, reporter: InvocationReporter): InvokedService | void;
1513
- }
1514
-
1515
- export interface InvokeRequest {
1516
- readonly system: System;
1517
- readonly parent: Actor;
1518
- readonly invocationID: InvocationID;
1519
- /** The invoke ID's text: `<invoke id>` or the one core generated. */
1520
- readonly invokeID?: string;
1521
- readonly type: string;
1522
- /**
1523
- * A literal `<invoke src>` as the text the chart wrote, never imported into
1524
- * the data model, so a chart on the null data model can name one; or
1525
- * `srcexpr`'s value.
1526
- */
1527
- readonly source?: unknown;
1528
- /** `<content expr>`'s value, or a literal <content> as text (then `contentType` is set). */
1529
- readonly content?: unknown;
1530
- readonly contentType?: string;
1531
- readonly params?: unknown;
1532
- readonly autoforward: boolean;
1533
- }
1534
-
1535
- export interface InvokedService {
1536
- cancel?(reason?: unknown): void | Promise<void>;
1537
- forward?(event: { readonly name: EventName; readonly data?: unknown }): void | Promise<void>;
1538
- }
1539
-
1540
- /**
1541
- * Reports from an invocation to its parent. event() and done() arrive as
1542
- * external events (done as done.invoke.<id>); unavailable() retires the
1543
- * invocation and the parent gets error.communication. Each returns true
1544
- * when the report was taken, and false once the invocation has ended (done,
1545
- * unavailable, cancelled, closed) or its parent is gone.
1546
- *
1547
- * A report that could not be taken throws and changes nothing: event() and
1548
- * done() throw `queue-full` when the parent's mailbox is at
1549
- * maxQueuedMessages or maxRetainedBytes, and any report throws
1550
- * `out-of-memory` when the addon or core cannot allocate. The invocation
1551
- * stays alive and its signal unaborted, so the service can report again,
1552
- * for example once the parent has drained its mailbox.
1553
- */
1554
- export interface InvocationReporter {
1555
- /** Aborts when the invocation ends: cancel, a taken done() or unavailable(), or close(). */
1556
- readonly signal: AbortSignal;
1557
- event(name: EventName, data?: unknown): boolean;
1558
- /** Ends the invocation once the report is taken. */
1559
- done(data?: unknown): boolean;
1560
- /** Ends the invocation once the report is taken. */
1561
- unavailable(error?: unknown): boolean;
1562
- }
1563
-
1564
- export interface LogRecord {
1565
- readonly source: ActorID | ActorAddress;
1566
- readonly label?: string;
1567
- readonly hasValue: boolean;
1568
- readonly value?: unknown;
1569
- }
1570
-
1571
- export type LogSink = (record: LogRecord) => void;
1572
-
1573
- /* --------------------------------------------------------------------------
1574
- * Public errors
1575
- * -------------------------------------------------------------------------- */
1576
-
1577
- export type TinyactorsErrorCode =
1578
- | "done"
1579
- | "invalid"
1580
- | "out-of-memory"
1581
- | "not-found"
1582
- | "busy"
1583
- | "unsupported"
1584
- | "definition-mismatch"
1585
- | "unloaded"
1586
- | "stale"
1587
- | "queue-full"
1588
- | "closed"
1589
- | "reentrant"
1590
- | "aborted"
1591
- | "timeout"
1592
- | "abandoned"
1593
- | "runaway"
1594
- /** A send()'s message became a dead letter with this reason (DeadLetterRecord). */
1595
- | "rejected"
1596
- | "load-failed"
1597
- | "load-timeout"
1598
- | "waiting-full";
1599
-
1600
- export class TinyactorsError extends Error {
1601
- readonly code: TinyactorsErrorCode;
1602
- readonly detail?: unknown;
1603
- }
1604
-
1605
- // ---------------------------------------------------------------------------
1606
- // Tracing (core ADR 0067, napi ADR 0016). OTLP bytes and a decoder; no
1607
- // telemetry dependency.
1608
-
1609
- /**
1610
- * Core's trace record kinds, in core's order (TRACE_KINDS). The three
1611
- * `definition*` kinds (core ADR 0080) are for hosts that follow core's
1612
- * record stream; the addon's OTLP output reports definitions through the
1613
- * `tinyactors.definition.*` logs instead, so no detail preset asks for them,
1614
- * and naming them in `kinds` adds nothing to the output.
1615
- */
1616
- export type TraceKind =
1617
- | 'spawned' | 'loaded' | 'unloaded' | 'finished' | 'destroyed'
1618
- | 'macrostepBegin' | 'macrostepEnd' | 'condition' | 'microstep' | 'raised'
1619
- | 'dataInit' | 'assign' | 'script' | 'foreach' | 'actionFailed'
1620
- | 'sent' | 'cancelled' | 'invoked' | 'invokeCancelled'
1621
- | 'paused' | 'resumed' | 'stopped' | 'ignored' | 'forwarded' | 'longMacrostep' | 'runaway'
1622
- | 'definitionRegistered' | 'definitionRetired' | 'definitionFreed'
1623
- | 'abandoned' | 'withdrawn';
1624
-
1625
- export declare const TRACE_KINDS: readonly TraceKind[];
1626
-
1627
- export interface TraceConfiguration {
1628
- /**
1629
- * "summary" (default): a span per macrostep, lifecycle spans, failures
1630
- * (`actionFailed`, `stopped`, `longMacrostep`, `runaway`) and an
1631
- * operator's interventions (`abandoned`, `withdrawn`); "decisions": adds
1632
- * microsteps, conditions and raised events; "full": every kind. Watched
1633
- * actors (watchTraces) always get every kind.
1634
- */
1635
- detail?: 'summary' | 'decisions' | 'full';
1636
- /** The record kinds wanted, overriding `detail`. Core builds no other record. */
1637
- kinds?: TraceKind[];
1638
- /**
1639
- * The ratio (0 to 1, default 1) of the traces this system starts that are
1640
- * sampled, decided as OpenTelemetry's TraceIDRatioBased does. A
1641
- * traceparent keeps its caller's decision. Lifecycle spans (spawned,
1642
- * loaded, unloaded, finished, destroyed) are kept whatever the decision.
1643
- */
1644
- sample?: number;
1645
- }
1646
-
1647
- export interface TraceSinkOptions extends TraceConfiguration {
1648
- /** Failures and <log> as OTLP log records, the sink's second argument (default true). */
1649
- logs?: boolean;
1650
- /** At most this many logs per definition and name per second (default 20). */
1651
- logLimit?: number;
1652
- /** Also trace macrosteps whose traceparent is not sampled. */
1653
- unsampled?: boolean;
1654
- /** Resource attributes every request carries, such as `service.name`. */
1655
- resource?: Record<string, string>;
1656
- /** Event data and assigned values as JSON attributes, cut at `valueLimit` (default 256, at most 1023). */
1657
- values?: boolean;
1658
- valueLimit?: number;
1659
- /** "cause" (default): a macrostep's parent is its cause; "link": a root, linked to its cause. */
1660
- parent?: 'cause' | 'link';
1661
- /** Trace IDs the system starts become a fixed sequence (tests). */
1662
- seed?: bigint;
1663
- }
1664
-
1665
- export interface MetricPoint {
1666
- attributes: Record<string, string>;
1667
- value: number;
1668
- }
1669
-
1670
- /** A bucket's latest sample, with the sampled trace step it happened in. */
1671
- export interface Exemplar {
1672
- /** The bucket's index in `buckets`. */
1673
- bucket: number;
1674
- value: number;
1675
- /** Milliseconds since the epoch. */
1676
- time: number;
1677
- traceID: string;
1678
- spanID: string;
1679
- }
1680
-
1681
- /** A distribution with explicit bucket bounds (OTLP Histogram). */
1682
- export interface HistogramPoint {
1683
- attributes: Record<string, string>;
1684
- count: number;
1685
- sum: number;
1686
- /** Present once something was recorded. */
1687
- min?: number;
1688
- max?: number;
1689
- /** Inclusive upper bounds; `buckets` has one more entry, for the rest. */
1690
- bounds: number[];
1691
- buckets: number[];
1692
- exemplars: Exemplar[];
1693
- }
1694
-
1695
- /** One metric: a cumulative monotonic sum, a gauge, or a histogram. */
1696
- export type Metric =
1697
- | { name: string; unit: string; kind: 'sum' | 'gauge'; points: MetricPoint[] }
1698
- | { name: string; unit: string; kind: 'histogram'; points: HistogramPoint[] };
1699
-
1700
- export interface MetricsSnapshot {
1701
- /** Milliseconds since the epoch: when the system started counting, and now. */
1702
- startTime: number;
1703
- time: number;
1704
- /** Core's totals, freed definitions included (core ADR 0072). */
1705
- system: Record<string, number>;
1706
- metrics: Metric[];
1707
- }
1708
-
1709
- /** One OTLP ExportMetricsServiceRequest, to post to `/v1/metrics`. */
1710
- export declare function metricsToOTLP(
1711
- snapshot: MetricsSnapshot,
1712
- options?: { resource?: Record<string, string>; version?: string },
1713
- ): Uint8Array;
1714
-
1715
- /**
1716
- * A span as decodeTraces() reads it. IDs are lowercase hex. The addon's own
1717
- * spans are all `internal`, with status `unset` or `error` (no message) and
1718
- * links without attributes; the other values come from other producers'
1719
- * bytes.
1720
- */
1721
- export interface DecodedSpan {
1722
- traceID: string;
1723
- spanID: string;
1724
- parentSpanID?: string;
1725
- name: string;
1726
- kind: 'unspecified' | 'internal' | 'server' | 'client' | 'producer' | 'consumer';
1727
- /** Milliseconds since the epoch. */
1728
- startTime: number;
1729
- endTime: number;
1730
- startTimeUnixNano: bigint;
1731
- endTimeUnixNano: bigint;
1732
- attributes: Record<string, unknown>;
1733
- events: { name: string; time: number; timeUnixNano: bigint; attributes: Record<string, unknown> }[];
1734
- links: { traceID: string; spanID: string; attributes: Record<string, unknown> }[];
1735
- status: { code: 'unset' | 'ok' | 'error'; message?: string };
1736
- /** Shared by the spans of one resource. */
1737
- resource: { attributes: Record<string, unknown> };
1738
- scope: { name: string; version: string };
1739
- }
1740
-
1741
- /** Reads OTLP protobuf trace bytes; throws on a malformed message. */
1742
- export declare function decodeTraces(bytes: Uint8Array): DecodedSpan[];
1743
-
1744
- /**
1745
- * A W3C `traceparent` header's fields, or undefined when it is not a valid
1746
- * one; parsed by core, as a traceparent given to post(), send() or spawn()
1747
- * is. Spaces and tabs around it are ignored and hex is lowercase. Version
1748
- * ff, an all-zero trace or parent ID, and version 00 with anything after
1749
- * the flags are refused. A later version is read by its first four fields,
1750
- * ignoring what follows a dash after the flags (W3C Trace Context,
1751
- * "Versioning of traceparent").
1752
- */
1753
- export declare function parseTraceparent(header: string | undefined):
1754
- { traceID: string; parentSpanID: string; flags: number; sampled: boolean } | undefined;
1755
- export declare function formatTraceparent(span: { traceID: string; spanID: string; sampled?: boolean; flags?: number }): string;
1756
- export declare function stepSpanID(session: bigint | number, macrostep: bigint | number, microstep?: number): string;
1757
-
1758
- // ---------------------------------------------------------------------------
1759
- // The debug adapter (napi ADR 0026)
1760
-
1761
- /**
1762
- * A poke a debug session may be allowed on the live actor: `send` an event,
1763
- * `set` its data model, `goto` (operator transitions, abandon, cancel and
1764
- * replace), and `evaluate` expressions. With none, the session only watches.
1765
- */
1766
- export type DebugPermission = 'send' | 'set' | 'goto' | 'evaluate';
1767
-
1768
- /** One record for the audit hook. `time` is milliseconds since the epoch. */
1769
- export type DebugAuditEntry = {
1770
- time: number;
1771
- /** DebugSession.id. */
1772
- session: number;
1773
- /** While attached: the actor's label and its session ID. */
1774
- actor?: string;
1775
- /** In decimal. */
1776
- sessionID?: string;
1777
- } & (
1778
- | { type: 'attach'; allow: DebugPermission[]; [detail: string]: unknown }
1779
- | { type: 'detach'; reason: string }
1780
- /** A line breakpoint's source is `path`, or `sourceReference` for SCXML the session wrote. */
1781
- | { type: 'breakpoints'; kind: 'line' | 'function' | 'data' | 'exception'; [detail: string]: unknown }
1782
- /** A console line, before it runs. */
1783
- | { type: 'command'; text: string }
1784
- | { type: 'evaluate'; context: string; expression: string }
1785
- /** A poke: send, set, goto, abandon, cancel, replace. */
1786
- | { type: 'mutation'; operation: string; [detail: string]: unknown }
1787
- );
1788
-
1789
- export interface DebugSessionOptions {
1790
- /**
1791
- * The pokes an attach may ask for (default none: watch only).
1792
- *
1793
- * `evaluate` runs arbitrary JavaScript in this process: watch, hover and
1794
- * console expressions, breakpoint conditions and logpoint `{expression}`
1795
- * parts. Grant it only to someone who may run code on the host. Without
1796
- * it the Variables pane, the console commands and setVariable still work.
1797
- * Each evaluation checks the permissions of the attach it runs under: a
1798
- * condition set before an attach that did not keep `evaluate` never runs,
1799
- * and the client hears that breakpoint changed to unverified; a logpoint's
1800
- * parts are then written as they are.
1801
- */
1802
- allow?: DebugPermission[];
1803
- /**
1804
- * Hears every attach, detach, breakpoint change (exception filters
1805
- * included), console command, evaluation and mutation before it happens;
1806
- * throwing refuses it. Evaluations include a breakpoint condition and a
1807
- * logpoint part at each hit (context "condition", "logpoint"), and a
1808
- * setVariable or setExpression value that is not JSON (context
1809
- * "setVariable", "setExpression"), before it runs. A refused condition
1810
- * does not fire, a refused logpoint part is written as `<refused>`, and
1811
- * the console says why. A detach is recorded after it happens and cannot
1812
- * be refused.
1813
- */
1814
- audit?: (entry: DebugAuditEntry) => void;
1815
- /** Takes each outgoing DAP message (an object). */
1816
- send: (message: DAPMessage) => void;
1817
- }
1818
-
1819
- /** A Debug Adapter Protocol message: a request, response or event. */
1820
- export interface DAPMessage {
1821
- seq: number;
1822
- type: 'request' | 'response' | 'event';
1823
- [field: string]: unknown;
1824
- }
1825
-
1826
- /**
1827
- * A DAP session over one attached actor, which it watches and pokes and
1828
- * never stops (ADR 0026): the client hears it stopped on entry, and after
1829
- * each of its macrosteps a stop that keeps the focus and an `invalidated`
1830
- * event for the variables; breakpoints are
1831
- * tracepoints. It opens no socket and checks no credentials: put it behind
1832
- * the application's transport and authentication, and decide each user's
1833
- * permissions before creating it.
1834
- */
1835
- export interface DebugSession {
1836
- readonly id: number;
1837
- readonly allow: DebugPermission[];
1838
- /** True while an actor is attached. */
1839
- readonly attached: boolean;
1840
- /**
1841
- * Takes one incoming message. Requests are answered in the order they
1842
- * arrive; the promise settles once this one is answered.
1843
- */
1844
- receive(message: DAPMessage): Promise<void>;
1845
- /** The transport closed: detach without answering. */
1846
- close(): void;
1847
- }
1848
-
1849
- export declare function createDebugSession(system: System, options: DebugSessionOptions): DebugSession;
1850
-
1851
- /**
1852
- * The base protocol's framing for a byte stream (stdio, a TCP socket):
1853
- * push() each chunk; `onMessage` gets each whole message in order. Chunks
1854
- * may split a header, a body or a UTF-8 sequence anywhere, and a string
1855
- * chunk may split a surrogate pair. Header fields other than
1856
- * Content-Length are ignored.
1857
- *
1858
- * A malformed stream throws an `invalid` TinyactorsError from push(), and
1859
- * every later push() throws `invalid` too: a stream cannot be
1860
- * resynchronized once a length is in doubt, so close the connection.
1861
- * Malformed is: headers that are not UTF-8, longer than 8 KiB without the
1862
- * blank line, or with a line that is not `Name: value`; no Content-Length,
1863
- * two, or one that is not a decimal number of at most 64 MiB; a body that
1864
- * is not UTF-8 JSON, or not an object with an integer `seq` and a `type`
1865
- * of "request", "response" or "event". An exception from `onMessage`
1866
- * propagates from push() but leaves the reader usable; messages already
1867
- * buffered behind it arrive with the next push().
1868
- */
1869
- export declare class DAPReader {
1870
- constructor(onMessage: (message: DAPMessage) => void);
1871
- push(chunk: Uint8Array | string): void;
1872
- }
1873
-
1874
- /** One message as bytes: the Content-Length header, then its JSON. */
1875
- export declare function encodeDAPMessage(message: object): Uint8Array;