@tinyactors/node 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/debug.js ADDED
@@ -0,0 +1,1434 @@
1
+ 'use strict';
2
+
3
+ // The debug adapter (docs/proposals/debug-adapter.md; napi ADR 0026): a
4
+ // Debug Adapter Protocol session over one attached actor of a System.
5
+ //
6
+ // napi opens no socket and checks no credentials (core ADR 0002, napi ADRs
7
+ // 0015 and 0016). The application puts a session behind its own transport
8
+ // and authentication, decides the permissions of the user before it creates
9
+ // the session, and passes each incoming DAP message to receive(); the
10
+ // session hands each outgoing one to `send`. An `audit` hook hears attach,
11
+ // detach, every console command, every evaluation and every mutation,
12
+ // before it happens: a hook that throws refuses it.
13
+ //
14
+ // The session watches and pokes, and the view updates live. It never stops
15
+ // the actor: a production actor is never held by a debugger. The actor is
16
+ // presented as stopped, because clients show a thread's stack and variables
17
+ // only then; after each macrostep the client hears the macrostep's summary
18
+ // and a stop that keeps the focus where it is, and reads the stack and the
19
+ // scopes again (see #presentStopped). A poke is
20
+ // what the permissions allow: `send` (an event through the mailbox), `set`
21
+ // (a data-model location), `goto` (an operator transition, abandon, cancel
22
+ // and replace), and `evaluate`. Each poke that moves the actor does it in a
23
+ // macrostep of its own, which the view shows like any other. With no
24
+ // permission the session only watches. Breakpoints of every kind are
25
+ // tracepoints: where one would have stopped, the console says so.
26
+ //
27
+ // Evaluating an expression runs arbitrary code in the process that hosts
28
+ // the actor. It is the `evaluate` permission, off unless granted: without
29
+ // it the Variables pane and the console commands still work.
30
+ //
31
+ // This module is host neutral, so the browser build can share it: it uses
32
+ // the System facade and core's generated bindings, and no Node.js module.
33
+
34
+ const { core } = require('./native');
35
+ const { TinyactorsError } = require('./errors');
36
+ const { ActorID } = require('./actor');
37
+ const { nativeOf, observe } = require('./system');
38
+ const { Labels } = require('./debug/labels');
39
+ const { Macrosteps, summarize } = require('./debug/macrosteps');
40
+ const { Breakpoints, EXCEPTION_FILTERS } = require('./debug/breakpoints');
41
+ const { Variables } = require('./debug/variables');
42
+ const { frames, leaves } = require('./debug/frames');
43
+ const { Sources } = require('./debug/sources');
44
+ const expressions = require('./debug/expressions');
45
+ const commands = require('./debug/console');
46
+ const { DAPReader, encodeDAPMessage } = require('./debug/protocol');
47
+
48
+ const PERMISSIONS = ['send', 'set', 'goto', 'evaluate'];
49
+ const CONDITION_NEEDS_EVALUATE =
50
+ 'a condition is an expression, which runs code in the process; it needs the "evaluate" permission';
51
+ const SCXML_INVOKER = 'http://www.w3.org/TR/scxml/';
52
+ const ATTACHED = 1; // the attached actor's thread ID
53
+ const OPERATOR_EVENT = 'operator.goto';
54
+ // Event-loop turns an abandon waits for the pump to finish a microstep in.
55
+ const MOST_TURNS = 100;
56
+
57
+ // No stepping, stepping back, restarting or exception details: the actor is
58
+ // never stopped. Breakpoints of every kind are declared, as tracepoints.
59
+ const CAPABILITIES = Object.freeze({
60
+ supportsConfigurationDoneRequest: true,
61
+ supportsFunctionBreakpoints: true,
62
+ supportsConditionalBreakpoints: true,
63
+ supportsHitConditionalBreakpoints: true,
64
+ supportsLogPoints: true,
65
+ supportsEvaluateForHovers: true,
66
+ exceptionBreakpointFilters: EXCEPTION_FILTERS.map(({ filter, label, description }) => ({ filter, label, description })),
67
+ supportsSetVariable: true,
68
+ supportsGotoTargetsRequest: true,
69
+ supportsCompletionsRequest: true,
70
+ completionTriggerCharacters: ['.', ' '],
71
+ supportsModulesRequest: true,
72
+ supportsDelayedStackTraceLoading: true,
73
+ supportsLoadedSourcesRequest: true,
74
+ supportsSetExpression: true,
75
+ supportsTerminateRequest: true,
76
+ supportsDataBreakpoints: true,
77
+ supportsBreakpointLocationsRequest: true,
78
+ supportsClipboardContext: true,
79
+ supportTerminateDebuggee: false,
80
+ supportSuspendDebuggee: false,
81
+ });
82
+
83
+ const NEVER_STOPPED = 'a live actor is never stopped: the session watches it and shows each macrostep as it ends; ' +
84
+ 'send, goto, abandon, cancel and setVariable poke it';
85
+
86
+ // Requests the adapter answers with an error, and why. Their capabilities
87
+ // are not declared.
88
+ const REFUSED = Object.freeze({
89
+ launch: 'napi\'s adapter attaches to a running actor: use "attach" with an address (the test host launches workbenches)',
90
+ restart: 'napi\'s adapter watches a running actor: disconnect and attach again',
91
+ pause: NEVER_STOPPED,
92
+ next: NEVER_STOPPED,
93
+ stepIn: NEVER_STOPPED,
94
+ stepOut: NEVER_STOPPED,
95
+ stepBack: 'a live actor is never stopped, and the session keeps no past to go back to',
96
+ reverseContinue: 'a live actor is never stopped, and the session keeps no past to go back to',
97
+ restartFrame: 'a live actor is never stopped, and the session keeps no past to go back to',
98
+ exceptionInfo: 'a live actor never stops for an exception: an exception breakpoint writes to the console instead',
99
+ cancel: 'every request answers at once, so there is nothing to cancel',
100
+ stepInTargets: 'an action has one way in',
101
+ terminateThreads: 'ending a thread would destroy an actor',
102
+ setInstructionBreakpoints: 'a chart has no instructions',
103
+ locations: 'no value in a chart names a place in a source',
104
+ readMemory: 'a chart has no memory to show',
105
+ writeMemory: 'a chart has no memory to show',
106
+ disassemble: 'a chart has no instructions',
107
+ });
108
+
109
+ // A request the session refuses; its message is what the client shows.
110
+ class Refusal extends Error {}
111
+
112
+ const refuse = (message) => new Refusal(message);
113
+ const jsonText = (value) => JSON.stringify(value, (key, inner) => (typeof inner === 'bigint' ? String(inner) : inner));
114
+ const nextTurn = () => new Promise((resolve) => setTimeout(resolve, 0));
115
+ const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
116
+
117
+ let sessionCount = 0;
118
+ // The request handlers, by command; set in the class's static block, where
119
+ // they can reach its private members.
120
+ let HANDLERS;
121
+
122
+ class DebugSession {
123
+ #system;
124
+ #allow;
125
+ #audit;
126
+ #send;
127
+ #seq = 0;
128
+ #queue = Promise.resolve();
129
+ #client = {};
130
+ #closed = false;
131
+
132
+ // While attached: { allow, actor, label, address, sessionID, args,
133
+ // labels, sources, observer, watch, console }.
134
+ #attached = null;
135
+ #threads = new Map();
136
+ #nextThread = ATTACHED + 1;
137
+ #macrosteps;
138
+ #lastEvent = new Map();
139
+ #lastMicrostep = new Map();
140
+ #breakpoints = new Breakpoints();
141
+ #variables;
142
+ #frames = new Map();
143
+ #nextFrame = 0;
144
+ // A frame's ID by thread and position. The actor is always at rest, so a
145
+ // frame names only its thread and depth: its ID stays valid across
146
+ // macrosteps, and a request a client made before a refresh still answers.
147
+ #frameIDs = new Map();
148
+ #gotoTargets = new Map();
149
+ #modules = new Map();
150
+ // sourceReference → { definition, source, virtual }: a definition's
151
+ // export, or the SCXML Sources writes for a chart with no file (napi ADR
152
+ // 0026). One count numbers both.
153
+ #sourceRefs = new Map();
154
+ #lastReference = 0;
155
+ #files = new Set();
156
+
157
+ constructor(system, options) {
158
+ if (system === null || typeof system !== 'object' || typeof system.withdrawSend !== 'function') {
159
+ throw new TinyactorsError('createDebugSession(): expected a System', 'invalid');
160
+ }
161
+ const { allow = [], audit, send } = options ?? {};
162
+ if (!Array.isArray(allow) || allow.some((entry) => !PERMISSIONS.includes(entry))) {
163
+ throw new TinyactorsError(`createDebugSession(): options.allow lists ${PERMISSIONS.join(', ')}`, 'invalid');
164
+ }
165
+ if (typeof send !== 'function') {
166
+ throw new TinyactorsError('createDebugSession(): options.send must be a function that takes each outgoing message',
167
+ 'invalid');
168
+ }
169
+ if (audit !== undefined && typeof audit !== 'function') {
170
+ throw new TinyactorsError('createDebugSession(): options.audit must be a function', 'invalid');
171
+ }
172
+ this.#system = system;
173
+ this.#allow = new Set(allow);
174
+ this.#audit = audit;
175
+ this.#send = send;
176
+ sessionCount += 1;
177
+ this.id = sessionCount;
178
+ this.#macrosteps = new Macrosteps((session) => this.#threadOfSession(session) !== undefined);
179
+ const session = this;
180
+ this.#variables = new Variables({
181
+ system,
182
+ native: nativeOf(system),
183
+ get labels() { return session.#attached.labels; },
184
+ thread: (id) => this.#thread(id),
185
+ eventOf: (thread, view) => this.#eventOf(thread, view),
186
+ mailboxNote: (message) => this.#mailboxNote(message),
187
+ threadOfInvocation: (invocation) => this.#threadOfInvocation(invocation),
188
+ documentName: (view) => this.#documentName(view),
189
+ });
190
+ }
191
+
192
+ /** The permissions this session was created with. */
193
+ get allow() {
194
+ return [...this.#allow];
195
+ }
196
+
197
+ /** True while an actor is attached. */
198
+ get attached() {
199
+ return this.#attached !== null;
200
+ }
201
+
202
+ /**
203
+ * Takes one incoming DAP message (an object). Requests are answered in
204
+ * the order they arrive; the promise settles once this one is answered.
205
+ */
206
+ receive(message) {
207
+ const run = this.#queue.then(() => this.#dispatch(message));
208
+ this.#queue = run.catch(() => {});
209
+ return run;
210
+ }
211
+
212
+ /** The transport closed: detach without answering. */
213
+ close() {
214
+ if (this.#closed) return;
215
+ this.#closed = true;
216
+ this.#detach('the connection closed');
217
+ }
218
+
219
+ // ------------------------------------------------------------------
220
+ // Messages
221
+
222
+ #write(message) {
223
+ if (this.#closed) return;
224
+ this.#seq += 1;
225
+ this.#send({ seq: this.#seq, ...message });
226
+ }
227
+
228
+ #event(event, body) {
229
+ this.#write(body === undefined ? { type: 'event', event } : { type: 'event', event, body });
230
+ }
231
+
232
+ #output(category, text) {
233
+ this.#event('output', { category, output: `${text}\n` });
234
+ }
235
+
236
+ async #dispatch(message) {
237
+ if (this.#closed || message === null || typeof message !== 'object' || message.type !== 'request') {
238
+ return;
239
+ }
240
+ const { command } = message;
241
+ const respond = (body, success = true, error) => this.#write({
242
+ type: 'response', request_seq: message.seq, success, command,
243
+ ...(success ? { body: body ?? {} } : { message: error, body: { error: { id: 1, format: error, showUser: true } } }),
244
+ });
245
+ if (Object.hasOwn(REFUSED, command)) {
246
+ respond(undefined, false, REFUSED[command]);
247
+ return;
248
+ }
249
+ const handler = HANDLERS[command];
250
+ if (handler === undefined) {
251
+ respond(undefined, false, `${command} is not supported by napi's debug adapter`);
252
+ return;
253
+ }
254
+ let after;
255
+ try {
256
+ const outcome = await handler.call(this, message.arguments ?? {});
257
+ after = outcome?.after;
258
+ respond(outcome?.body);
259
+ } catch (error) {
260
+ if (!(error instanceof Refusal || error instanceof TinyactorsError)) {
261
+ this.#output('stderr', `${command}: ${error?.stack ?? error}`);
262
+ }
263
+ respond(undefined, false, error?.message ?? String(error));
264
+ return;
265
+ }
266
+ try {
267
+ after?.();
268
+ } catch (error) {
269
+ this.#output('stderr', `${command}: ${error?.message ?? error}`);
270
+ }
271
+ }
272
+
273
+ // ------------------------------------------------------------------
274
+ // Audit and permissions
275
+
276
+ #record(entry) {
277
+ if (this.#audit === undefined) return;
278
+ const attached = this.#attached;
279
+ this.#audit({
280
+ ...entry,
281
+ time: Date.now(),
282
+ session: this.id,
283
+ ...(attached === null ? {} : { actor: attached.label, sessionID: attached.sessionID }),
284
+ });
285
+ }
286
+
287
+ // The audit hook hears it first; one that throws refuses it.
288
+ #audited(entry) {
289
+ try {
290
+ this.#record(entry);
291
+ } catch (error) {
292
+ throw refuse(`the audit hook refused it: ${error?.message ?? error}`);
293
+ }
294
+ }
295
+
296
+ #requireAttached() {
297
+ if (this.#attached === null) throw refuse('attach to an actor first');
298
+ return this.#attached;
299
+ }
300
+
301
+ // A poke: an operation that changes the actor, with its permission.
302
+ #requireChange(permission, what) {
303
+ const attached = this.#requireAttached();
304
+ if (!attached.allow.has(permission)) {
305
+ throw refuse(attached.allow.size === 0
306
+ ? `${what} changes the actor, and this session only watches it`
307
+ : `${what} needs the "${permission}" permission, which this session was not given`);
308
+ }
309
+ return attached;
310
+ }
311
+
312
+ #requireEvaluate(what) {
313
+ const attached = this.#requireAttached();
314
+ if (!attached.allow.has('evaluate')) {
315
+ throw refuse(`${what} evaluates an expression, which runs code in the process; it needs the "evaluate" permission`);
316
+ }
317
+ return attached;
318
+ }
319
+
320
+ // ------------------------------------------------------------------
321
+ // Attaching
322
+
323
+ #resolve(args) {
324
+ const system = this.#system;
325
+ const { address, actor, sessionID } = args;
326
+ if (address !== undefined) {
327
+ const parsed = parseAddress(address);
328
+ if (parsed === undefined) {
329
+ throw refuse('"address" is { family, name }, "family/name" or "#_actor_family/name"');
330
+ }
331
+ const found = system.findActor(parsed);
332
+ if (found === undefined) throw refuse(`no resident actor has the address ${parsed.family}/${parsed.name}`);
333
+ return { actor: found, address: parsed };
334
+ }
335
+ if (actor !== undefined) {
336
+ const id = new ActorID(system, Number(actor.slot), Number(actor.generation));
337
+ if (!system.exists(id)) throw refuse(`no resident actor is ${actor.slot}:${actor.generation}`);
338
+ return { actor: id, address: undefined };
339
+ }
340
+ if (sessionID !== undefined) {
341
+ let wanted;
342
+ try {
343
+ wanted = BigInt(sessionID);
344
+ } catch {
345
+ throw refuse('"sessionID" is a session ID in decimal');
346
+ }
347
+ const found = actorOfSession(system, wanted);
348
+ if (found === undefined) throw refuse(`no resident actor holds session ${wanted}`);
349
+ return { actor: found, address: undefined };
350
+ }
351
+ throw refuse('attach needs "address", "actor" { slot, generation } or "sessionID"');
352
+ }
353
+
354
+ // An attach may ask for fewer permissions than the session has, never
355
+ // more.
356
+ #attach(args) {
357
+ if (this.#attached !== null) throw refuse(`already attached to ${this.#attached.label}; disconnect first`);
358
+ if (args.allow !== undefined && !Array.isArray(args.allow)) throw refuse('"allow" is a list of permissions');
359
+ const asked = args.allow === undefined ? this.#allow : new Set(args.allow);
360
+ const allow = new Set([...this.#allow].filter((permission) => asked.has(permission)));
361
+ const { actor, address } = this.#resolve(args);
362
+ const view = this.#system.inspect(actor);
363
+ const label = address !== undefined ? `${address.family}/${address.name}` : `actor ${actor.slot}:${actor.generation}`;
364
+ const attached = { allow, actor, label, address, sessionID: String(view.sessionID), args };
365
+ this.#attached = attached;
366
+ try {
367
+ this.#audited({ type: 'attach', allow: [...allow] });
368
+ } catch (error) {
369
+ this.#attached = null;
370
+ throw error;
371
+ }
372
+ const system = this.#system;
373
+ const native = nativeOf(system);
374
+ attached.labels = new Labels(native);
375
+ attached.sources = new Sources(system, native, () => (this.#lastReference += 1));
376
+ this.#threads.set(ATTACHED, { id: ATTACHED, actor, label, session: attached.sessionID });
377
+ attached.observer = observe(system, {
378
+ traces: (traces) => this.#onTraces(traces),
379
+ log: (record) => this.#onLog(record),
380
+ runaway: (runaway) => this.#onRunaway(runaway),
381
+ defined: (id) => this.#onDefined(id),
382
+ deadLetter: (letter) => this.#onDeadLetter(letter),
383
+ dropped: (send) => this.#onDropped(send),
384
+ });
385
+ attached.watch = system.watchTraces({ sessions: [actor] });
386
+ if (allow.has('send') || allow.has('goto')) {
387
+ attached.console = commands.openConsole(system, `debug://session/${this.id}`, (request) => this.#onReply(request));
388
+ }
389
+ return attached;
390
+ }
391
+
392
+ // What attaching says, once its response is out. A DAP client shows a
393
+ // thread's stack and variables only while it is stopped, so the actor is
394
+ // reported stopped once, on entry, and every view refreshes after each
395
+ // of its macrosteps (`invalidated`); it never is stopped.
396
+ #announce(attached, verb) {
397
+ this.#event('process', { name: attached.label, startMethod: 'attach', isLocalProcess: true });
398
+ this.#refreshCatalog();
399
+ this.#refreshThreads();
400
+ const permissions = attached.allow.size === 0 ? 'watch only' : `allowed: ${[...attached.allow].join(', ')}`;
401
+ this.#output('console', `${verb} ${attached.label} (session ${attached.sessionID}), watched live and never ` +
402
+ `paused; ${permissions}`);
403
+ this.#relocateBreakpoints();
404
+ this.#presentStopped({ focus: true });
405
+ }
406
+
407
+ // Presents the actor as stopped, so the client shows its stack and
408
+ // variables. With `focus` (on attach, and after a `continue`) the client
409
+ // selects the top frame, and its Variables view has something to show;
410
+ // otherwise (after each macrostep) it only reads the stack again and
411
+ // leaves the focus where it is.
412
+ //
413
+ // The refresh after a macrostep is a stop that keeps the focus, followed
414
+ // by `invalidated` for the variables only, never for the stacks: VS Code
415
+ // answers a stacks invalidation by replaying the stops it holds, and the
416
+ // attach stop, which took the focus, would take it again after every
417
+ // macrostep, out of the Debug Console while an operator types in it.
418
+ #presentStopped({ focus }) {
419
+ if (this.#attached === null) return;
420
+ this.#event('stopped', { reason: 'entry', threadId: ATTACHED, allThreadsStopped: false, preserveFocusHint: !focus,
421
+ description: 'watched live, never paused: the view follows each macrostep' });
422
+ }
423
+
424
+ // The live view after a macrostep of the actor: the stack and the scopes
425
+ // are read again. Frames keep their IDs (#frameIDs), so the frame the
426
+ // client selected stays valid.
427
+ #refreshView() {
428
+ this.#resetViews();
429
+ this.#presentStopped({ focus: false });
430
+ if (this.#client.supportsInvalidatedEvent) this.#event('invalidated', { areas: ['variables'] });
431
+ }
432
+
433
+ // Ends the attachment: stops watching.
434
+ #detach(reason) {
435
+ const attached = this.#attached;
436
+ if (attached === null) return;
437
+ const system = this.#system;
438
+ attached.observer?.stop();
439
+ if (!system.closed) {
440
+ attached.watch?.stop();
441
+ attached.console?.close();
442
+ }
443
+ try {
444
+ this.#record({ type: 'detach', reason });
445
+ } catch {
446
+ // Detaching cannot be refused.
447
+ }
448
+ this.#attached = null;
449
+ this.#threads.clear();
450
+ this.#frames.clear();
451
+ this.#frameIDs.clear();
452
+ this.#resetViews();
453
+ }
454
+
455
+ // The attached actor went away: the session ends.
456
+ #ended(why) {
457
+ if (this.#attached === null) return;
458
+ const label = this.#attached.label;
459
+ this.#detach(why);
460
+ this.#output('important', `${label} ${why}; the debug session ended`);
461
+ this.#event('terminated');
462
+ }
463
+
464
+ // ------------------------------------------------------------------
465
+ // Threads
466
+
467
+ #thread(id) {
468
+ const thread = this.#threads.get(Number(id));
469
+ if (thread === undefined) throw refuse(`no thread ${id}`);
470
+ return thread;
471
+ }
472
+
473
+ #threadOfSession(session) {
474
+ const text = String(session);
475
+ for (const thread of this.#threads.values()) {
476
+ if (thread.session === text) return thread;
477
+ }
478
+ return undefined;
479
+ }
480
+
481
+ // The thread of an invocation's in-system child, or undefined: for other
482
+ // invokers, and for a child that is gone.
483
+ #threadOfInvocation(invocation) {
484
+ const child = invocation.type === SCXML_INVOKER ? childOf(this.#system, invocation.serviceHandle) : undefined;
485
+ return child === undefined ? undefined : this.#threadOfSession(child.session);
486
+ }
487
+
488
+ #threadArgument(args) {
489
+ this.#requireAttached();
490
+ return args.threadId === undefined ? this.#threads.get(ATTACHED) : this.#thread(args.threadId);
491
+ }
492
+
493
+ #inspect(thread) {
494
+ try {
495
+ return this.#system.inspect(thread.actor);
496
+ } catch (error) {
497
+ if (error instanceof TinyactorsError && error.code === 'not-found') return undefined;
498
+ throw error;
499
+ }
500
+ }
501
+
502
+ // The attached actor and the in-system children of its invocations, and
503
+ // the thread events for what changed.
504
+ #refreshThreads() {
505
+ const attached = this.#attached;
506
+ if (attached === null) return;
507
+ const view = this.#inspect(this.#threads.get(ATTACHED));
508
+ if (view === undefined) {
509
+ this.#ended('is gone');
510
+ return;
511
+ }
512
+ const children = new Map();
513
+ for (const invocation of view.invocations) {
514
+ if (invocation.type !== SCXML_INVOKER || !invocation.active) continue;
515
+ const child = childOf(this.#system, invocation.serviceHandle);
516
+ if (child !== undefined) children.set(child.session, { child: child.actor, invocation });
517
+ }
518
+ for (const thread of [...this.#threads.values()]) {
519
+ if (thread.id !== ATTACHED && !children.has(thread.session)) {
520
+ this.#threads.delete(thread.id);
521
+ this.#macrosteps.forget(thread.session);
522
+ this.#event('thread', { reason: 'exited', threadId: thread.id });
523
+ }
524
+ }
525
+ for (const [session, { child, invocation }] of children) {
526
+ if (this.#threadOfSession(session) === undefined) {
527
+ const id = this.#nextThread;
528
+ this.#nextThread += 1;
529
+ this.#threads.set(id, { id, actor: child, label: `${attached.label} invocation ${attached.labels.invocation(invocation.id)}`,
530
+ session });
531
+ this.#event('thread', { reason: 'started', threadId: id });
532
+ }
533
+ }
534
+ }
535
+
536
+ #threadName(thread) {
537
+ const view = this.#inspect(thread);
538
+ if (view === undefined) return `${thread.label} (gone)`;
539
+ const where = view.residency === 'done' ? `done in ${view.finalState ?? 'its final state'}`
540
+ : leaves(view, this.#attached.labels).join(' ') || 'starting';
541
+ return `${thread.label} · ${where}`;
542
+ }
543
+
544
+ // ------------------------------------------------------------------
545
+ // What the actor did: traces, <log> records, replies
546
+
547
+ #onTraces(bytes) {
548
+ if (this.#attached === null) return;
549
+ let read;
550
+ try {
551
+ read = this.#macrosteps.read(bytes);
552
+ } catch (error) {
553
+ this.#output('stderr', `reading the traces failed: ${error.message}`);
554
+ return;
555
+ }
556
+ for (const macrostep of read.macrosteps) {
557
+ this.#onMacrostep(macrostep);
558
+ }
559
+ let gone;
560
+ for (const entry of read.lifecycle) {
561
+ if (entry.session === this.#attached?.sessionID && ['finished', 'destroyed', 'unloaded'].includes(entry.kind)) {
562
+ gone = entry.kind;
563
+ }
564
+ }
565
+ if (read.macrosteps.length > 0) this.#refreshView();
566
+ const attached = this.#attached;
567
+ if (gone === 'finished' && attached !== null && this.#system.exists(attached.actor)) {
568
+ this.#output('important', `${attached.label} finished`);
569
+ } else if (gone !== undefined) {
570
+ this.#ended(gone === 'unloaded' ? 'was unloaded' : gone === 'finished' ? 'finished' : 'was destroyed');
571
+ return;
572
+ }
573
+ this.#refreshThreads();
574
+ this.#refreshCatalog();
575
+ }
576
+
577
+ // A macrostep's summary, and the breakpoints it would have stopped at:
578
+ // they are tracepoints, since a live actor is never stopped.
579
+ #onMacrostep(macrostep) {
580
+ const attached = this.#attached;
581
+ const thread = this.#threadOfSession(macrostep.session);
582
+ if (thread === undefined) return;
583
+ if (macrostep.event !== null) this.#lastEvent.set(macrostep.session, macrostep.event);
584
+ const last = macrostep.microsteps.at(-1);
585
+ if (last !== undefined) this.#lastMicrostep.set(macrostep.session, { macrostep: macrostep.number, microstep: last });
586
+ const location = (definition, id) => attached.labels.expression(BigInt(definition), id);
587
+ this.#output('console', summarize(macrostep, thread.label, location).join('\n'));
588
+ if (thread.id !== ATTACHED) return;
589
+ const hits = this.#breakpoints.hits(macrostep, {
590
+ label: thread.label,
591
+ location: (id) => {
592
+ const text = location(macrostep.definition, id);
593
+ return text === undefined ? undefined : expressions.pathOf(text);
594
+ },
595
+ fires: (breakpoint) => this.#condition(breakpoint, thread),
596
+ log: (breakpoint) => this.#logpoint(breakpoint, thread),
597
+ });
598
+ for (const hit of hits) {
599
+ this.#output('console', `would have stopped after macrostep ${macrostep.number}: ${hit.description}`);
600
+ }
601
+ this.#onFailedSends(macrostep, thread.label);
602
+ }
603
+
604
+ // A <send> of the actor that core could not route (an unknown target, a
605
+ // name with no actor) raises error.communication in it at once, or when
606
+ // a delayed one is due; the trace names the <send> that failed.
607
+ #onFailedSends(macrostep, label) {
608
+ for (const { name, attributes } of macrostep.records) {
609
+ if (name !== 'scxml.raise' || !String(attributes['scxml.event.name']).startsWith('error.communication')) continue;
610
+ const action = attributes['scxml.action'];
611
+ const which = action !== undefined ? action
612
+ : `a delayed <send> from macrostep ${attributes['scxml.cause.macrostep'] ?? '?'}, when it was due,`;
613
+ this.#output('important', `${label}: ${which} could not be delivered; it raised error.communication`);
614
+ }
615
+ }
616
+
617
+ // Whether `target` (an ActorID, or an address) is the attached actor.
618
+ #isAttached(target) {
619
+ const attached = this.#attached;
620
+ if (attached === null || target === undefined || target === null) return false;
621
+ if (target instanceof ActorID) return target.equals(attached.actor);
622
+ const { address } = attached;
623
+ return address !== undefined && target.family === address.family && target.name === address.name;
624
+ }
625
+
626
+ // Mail for the attached actor that it will never take (a dead letter,
627
+ // ADR 0008): the application's deadLetter hook hears it as well.
628
+ #onDeadLetter(letter) {
629
+ if (!this.#isAttached(letter.target)) return;
630
+ const detail = letter.detail === undefined ? '' : ` (${letter.detail})`;
631
+ this.#output('important', `${this.#attached.label}: ${letter.event} became a dead letter: ${letter.reason}${detail}`);
632
+ }
633
+
634
+ // A <send> of the attached actor that its I/O processor failed; the actor
635
+ // gets error.communication for it.
636
+ #onDropped(send) {
637
+ if (!this.#isAttached(send.source)) return;
638
+ const target = typeof send.target === 'string' && send.target !== '' ? ` to ${send.target}` : '';
639
+ const why = send.error instanceof Error ? send.error.message : jsonText(send.error);
640
+ this.#output('important', `${this.#attached.label}: the <send> of ${send.event} through ${send.type}${target} ` +
641
+ `failed: ${why}`);
642
+ }
643
+
644
+ // A breakpoint's condition, in the data model where it hit. It runs only
645
+ // with the `evaluate` permission the attach has now, and only once the
646
+ // audit hook has heard it; without either it never fires. One that
647
+ // throws counts as a hit, so its author sees it fail.
648
+ #condition(breakpoint, thread) {
649
+ if (!this.#attached.allow.has('evaluate')) return false;
650
+ if (!this.#auditEvaluation('condition', String(breakpoint.condition), `the condition of breakpoint ${breakpoint.id}`)) {
651
+ return false;
652
+ }
653
+ try {
654
+ return Boolean(expressions.evaluate(breakpoint.condition, this.#scope(thread)));
655
+ } catch (error) {
656
+ this.#output('stderr', `the condition of breakpoint ${breakpoint.id} failed: ${error.message}`);
657
+ return true;
658
+ }
659
+ }
660
+
661
+ // An evaluation the session makes on its own, at a hit: the audit hook
662
+ // hears it first. One it refuses does not run, and the console says so.
663
+ #auditEvaluation(context, expression, what) {
664
+ try {
665
+ this.#record({ type: 'evaluate', context, expression });
666
+ return true;
667
+ } catch (error) {
668
+ this.#output('stderr', `the audit hook refused ${what}: ${error?.message ?? error}`);
669
+ return false;
670
+ }
671
+ }
672
+
673
+ // A logpoint writes its message: {expression} parts are evaluated with
674
+ // the `evaluate` permission, and left as written without it; a part the
675
+ // audit hook refuses is written as <refused>.
676
+ #logpoint(breakpoint, thread) {
677
+ const evaluate = this.#attached.allow.has('evaluate');
678
+ const text = String(breakpoint.logMessage).replace(/\{([^{}]+)\}/g, (whole, expression) => {
679
+ if (!evaluate) return whole;
680
+ if (!this.#auditEvaluation('logpoint', expression, `a part of logpoint ${breakpoint.id}`)) return '<refused>';
681
+ try {
682
+ const value = expressions.evaluate(expression, this.#scope(thread));
683
+ return typeof value === 'string' ? value : jsonText(value);
684
+ } catch (error) {
685
+ return `<${error.message}>`;
686
+ }
687
+ });
688
+ this.#output('console', text);
689
+ }
690
+
691
+ #onLog(record) {
692
+ const attached = this.#attached;
693
+ if (attached === null) return;
694
+ const source = record.source;
695
+ const { address } = attached;
696
+ const ours = source instanceof ActorID ? source.equals(attached.actor)
697
+ : address !== undefined && source?.family === address.family && source?.name === address.name;
698
+ if (!ours) return;
699
+ const value = record.hasValue ? ` ${typeof record.value === 'string' ? record.value : jsonText(record.value)}` : '';
700
+ this.#output('stdout', `${record.label ?? 'log'}:${value}`);
701
+ }
702
+
703
+ #onReply(request) {
704
+ const data = request.data === undefined ? '' : ` ${jsonText(request.data)}`;
705
+ this.#output('console', `${this.#attached?.label ?? 'an actor'} replied ${request.event}${data}`);
706
+ }
707
+
708
+ // A macrostep of the actor ran its microstep limit, and the addon
709
+ // quarantined it (core ADR 0075): it stands between two microsteps of a
710
+ // macrostep it cannot finish. The console says what can be done; the
711
+ // `runaway` exception filter adds a tracepoint's line.
712
+ #onRunaway(actor) {
713
+ const attached = this.#attached;
714
+ if (attached === null || !actor.equals(attached.actor)) return;
715
+ this.#output('important', `${attached.label} is quarantined as a runaway: a macrostep ran its microstep limit ` +
716
+ '(core ADR 0075). `abandon` ends that macrostep and `goto` moves it out of the loop; ' +
717
+ 'the application\'s release() lets the macrostep go on');
718
+ if (this.#breakpoints.wants('runaway')) {
719
+ this.#output('console', 'would have stopped: a macrostep ran its microstep limit');
720
+ }
721
+ this.#refreshView();
722
+ }
723
+
724
+ // ------------------------------------------------------------------
725
+ // Views of the actor
726
+
727
+ #resetViews() {
728
+ this.#variables.reset();
729
+ }
730
+
731
+ #documentName(view) {
732
+ const system = this.#system;
733
+ try {
734
+ return core.definition_inspect(nativeOf(system), view.definitionID).document_name || view.definition.family;
735
+ } catch {
736
+ return view.definition.family;
737
+ }
738
+ }
739
+
740
+ // _event of the step the thread is in, or of its last macrostep, as the
741
+ // chart's expressions see it: `origin` is the URI, `originType` its type.
742
+ #eventOf(thread, view = this.#inspect(thread)) {
743
+ if (view?.currentEvent) {
744
+ const { origin, ...event } = view.currentEvent;
745
+ if (origin !== undefined) {
746
+ if (origin.uri !== undefined) event.origin = origin.uri;
747
+ event.originType = origin.type;
748
+ }
749
+ return event;
750
+ }
751
+ const last = this.#lastEvent.get(thread.session);
752
+ if (last === undefined) return undefined;
753
+ let data;
754
+ try {
755
+ data = last.data === undefined ? undefined : JSON.parse(last.data);
756
+ } catch {
757
+ data = last.data;
758
+ }
759
+ return { name: last.name, type: last.type, ...(data === undefined ? {} : { data }), taken: 'in its last macrostep' };
760
+ }
761
+
762
+ #mailboxNote(message) {
763
+ const scope = this.#attached?.console?.scope;
764
+ const console = scope !== undefined && message.scope?.index === scope.index &&
765
+ message.scope?.generation === scope.generation;
766
+ return {
767
+ event: message.event,
768
+ ...(message.data === undefined ? {} : { data: message.data }),
769
+ ...(message.transition === undefined ? {} : { transition: message.transition }),
770
+ ...(message.awaited ? { awaited: true } : {}),
771
+ ...(console ? { from: 'this console' } : {}),
772
+ };
773
+ }
774
+
775
+ // What an expression sees for a thread.
776
+ #scope(thread) {
777
+ const view = this.#inspect(thread);
778
+ if (view === undefined) throw refuse(`${thread.label} is gone`);
779
+ return {
780
+ data: view.data,
781
+ event: this.#eventOf(thread, view),
782
+ sessionID: String(view.sessionID),
783
+ name: this.#documentName(view),
784
+ activeStates: view.activeStates,
785
+ };
786
+ }
787
+
788
+ #frameThread(frameId) {
789
+ if (frameId === undefined) return this.#threads.get(ATTACHED);
790
+ const frame = this.#frames.get(Number(frameId));
791
+ if (frame === undefined) throw refuse(`frame ${frameId} is not valid (any more)`);
792
+ return this.#thread(frame.thread);
793
+ }
794
+
795
+ // ------------------------------------------------------------------
796
+ // Modules, sources and line breakpoints (core ADR 0085)
797
+
798
+ #refreshCatalog() {
799
+ const attached = this.#attached;
800
+ const seen = new Set();
801
+ for (const definition of this.#system.definitions()) {
802
+ const key = String(definition.id);
803
+ seen.add(key);
804
+ const revision = typeof definition.identity.revision === 'string' ? definition.identity.revision
805
+ : [...definition.identity.revision].map((byte) => byte.toString(16).padStart(2, '0')).join('');
806
+ const module = { id: key, name: `${definition.identity.family}${definition.retired ? ' (retired)' : ''}`,
807
+ version: revision };
808
+ const known = this.#modules.get(key);
809
+ if (known === undefined) {
810
+ this.#modules.set(key, module);
811
+ const reference = (this.#lastReference += 1);
812
+ this.#sourceRefs.set(reference, { definition: definition.id,
813
+ source: exportSource(definition, revision, reference) });
814
+ this.#event('module', { reason: 'new', module });
815
+ this.#event('loadedSource', { reason: 'new', source: this.#sourceRefs.get(reference).source });
816
+ for (const path of attached.sources.files(definition.id)) {
817
+ if (!this.#files.has(path)) {
818
+ this.#files.add(path);
819
+ this.#event('loadedSource', { reason: 'new', source: Sources.source({ path }) });
820
+ }
821
+ }
822
+ } else if (known.name !== module.name) {
823
+ this.#modules.set(key, module);
824
+ this.#event('module', { reason: 'changed', module });
825
+ }
826
+ this.#noteVirtual(definition.id, attached.sources.virtualSource(definition.id));
827
+ }
828
+ for (const [key, module] of [...this.#modules]) {
829
+ if (!seen.has(key)) {
830
+ this.#modules.delete(key);
831
+ this.#event('module', { reason: 'removed', module });
832
+ for (const [reference, entry] of [...this.#sourceRefs]) {
833
+ if (String(entry.definition) === key) {
834
+ this.#sourceRefs.delete(reference);
835
+ this.#event('loadedSource', { reason: 'removed', source: entry.source });
836
+ }
837
+ }
838
+ }
839
+ }
840
+ }
841
+
842
+ // A definition's virtual source (napi ADR 0026), or undefined: a new one
843
+ // is a loaded source, and one an earlier attach numbered is removed.
844
+ #noteVirtual(definition, virtual) {
845
+ for (const [reference, entry] of [...this.#sourceRefs]) {
846
+ if (entry.virtual && String(entry.definition) === String(definition) && reference !== virtual?.sourceReference) {
847
+ this.#sourceRefs.delete(reference);
848
+ this.#event('loadedSource', { reason: 'removed', source: entry.source });
849
+ }
850
+ }
851
+ if (virtual !== undefined && !this.#sourceRefs.has(virtual.sourceReference)) {
852
+ this.#sourceRefs.set(virtual.sourceReference, { definition, source: virtual, virtual: true });
853
+ this.#event('loadedSource', { reason: 'new', source: virtual });
854
+ }
855
+ }
856
+
857
+ // The element a line of `source` (a DAP Source) stands for, in the
858
+ // attached actor's chart, or why there is none.
859
+ #resolveLine(source, line) {
860
+ const attached = this.#attached;
861
+ if (attached === null) return 'attach first: lines are resolved against the attached actor\'s chart';
862
+ const definition = this.#system.inspect(attached.actor).definitionID;
863
+ const found = attached.sources.locate(definition, source, line);
864
+ if (found === undefined) {
865
+ return attached.sources.elements(definition).length === 0
866
+ ? 'the chart keeps no source spans (core ADR 0085) and SCXML cannot express it: statechart() records spans'
867
+ : `no state, transition or action of ${attached.label}'s chart at or after line ${line} of this source`;
868
+ }
869
+ const name = found.kind === 'state' ? attached.labels.state(definition, found.id)
870
+ : found.kind === 'transition' ? attached.labels.transition(definition, found.id)
871
+ : attached.labels.action(definition, found.id);
872
+ return { element: { kind: found.kind, id: found.id, name }, line: found.line, column: found.column,
873
+ source: Sources.source(found) };
874
+ }
875
+
876
+ // A chart defined again: its spans may have moved (core ADRs 0077 and
877
+ // 0085), so its lines are read again and the breakpoints placed again.
878
+ #onDefined(id) {
879
+ if (this.#attached === null) return;
880
+ this.#attached.sources.forget(id);
881
+ this.#relocateBreakpoints();
882
+ }
883
+
884
+ // Line breakpoints set before attaching are resolved against the
885
+ // attached actor's chart, and the client hears where they went.
886
+ #relocateBreakpoints() {
887
+ for (const { source } of this.#breakpoints.lineRequests) {
888
+ for (const breakpoint of this.#breakpoints.relocate(source, (line) => this.#resolveLine(source, line))) {
889
+ this.#event('breakpoint', { reason: 'changed', breakpoint });
890
+ }
891
+ }
892
+ this.#unverifyConditions();
893
+ }
894
+
895
+ // Conditions set before an attach that did not keep `evaluate` never run
896
+ // (#condition): the client hears those breakpoints are unverified.
897
+ #unverifyConditions() {
898
+ if (this.#attached === null || this.#attached.allow.has('evaluate')) return;
899
+ for (const { id } of this.#breakpoints.conditioned) {
900
+ this.#event('breakpoint', { reason: 'changed', breakpoint: { id, verified: false, message: CONDITION_NEEDS_EVALUATE } });
901
+ }
902
+ }
903
+
904
+ // ------------------------------------------------------------------
905
+ // Pokes: each queues behind the actor's mail, or acts between its
906
+ // macrosteps, and the view shows the macrostep it causes.
907
+
908
+ #post(event, data, options) {
909
+ const { actor, console } = this.#attached;
910
+ const origin = console === undefined ? undefined : { type: commands.TYPE, scope: console.scope };
911
+ this.#system.post(actor, event, data, { ...options, origin });
912
+ }
913
+
914
+ #consoleSend({ event, data }) {
915
+ const attached = this.#requireChange('send', 'send');
916
+ this.#audited({ type: 'mutation', operation: 'send', event, data });
917
+ this.#post(event, data);
918
+ return `sent ${event} to ${attached.label}`;
919
+ }
920
+
921
+ // An operator transition (core ADR 0082), queued behind the actor's mail.
922
+ #jump(targets, from) {
923
+ const attached = this.#requireChange('goto', 'goto');
924
+ const { actor, labels } = attached;
925
+ const definition = this.#system.inspect(actor).definitionID;
926
+ for (const state of [...targets, ...(from === undefined ? [] : [from])]) {
927
+ if (labels.stateID(definition, state) === undefined) throw refuse(`${state} is not a state of the chart`);
928
+ }
929
+ this.#audited({ type: 'mutation', operation: 'goto', targets, from });
930
+ const data = { targets, ...(from === undefined ? {} : { from }) };
931
+ this.#post(OPERATOR_EVENT, data, { transition: { targets, source: from } });
932
+ return `${attached.label}: goto ${targets.join(' ')}${from === undefined ? '' : ` from ${from}`} queued`;
933
+ }
934
+
935
+ // Core abandons only between microsteps (core ADR 0082): an actor the
936
+ // system's action budget paused inside one finishes it in the next turns,
937
+ // as it would anyway, and is abandoned as soon as it stands between two.
938
+ async #abandon() {
939
+ const attached = this.#requireChange('goto', 'abandon');
940
+ const { actor, label } = attached;
941
+ const system = this.#system;
942
+ const view = system.inspect(actor);
943
+ if (!view.macrostepInProgress) throw refuse(`${label} has no macrostep to abandon`);
944
+ this.#audited({ type: 'mutation', operation: 'abandon', macrostep: view.step.macrostep });
945
+ for (let turns = 0; turns < MOST_TURNS; turns += 1) {
946
+ if (!system.exists(actor) || !system.inspect(actor).macrostepInProgress) {
947
+ return `${label} finished its macrostep while finishing its microstep`;
948
+ }
949
+ try {
950
+ system.abandon(actor);
951
+ return `${label}: abandoned macrostep ${view.step.macrostep}; it keeps the configuration after its last ` +
952
+ 'completed microstep';
953
+ } catch (error) {
954
+ if (!(error instanceof TinyactorsError && error.code === 'busy')) throw error;
955
+ }
956
+ await nextTurn();
957
+ }
958
+ throw refuse(`${label} has not finished its bootstrap, or is still inside a microstep; try again`);
959
+ }
960
+
961
+ #cancel({ id }) {
962
+ const attached = this.#requireChange('goto', 'cancel');
963
+ this.#audited({ type: 'mutation', operation: 'cancel', sendID: id });
964
+ try {
965
+ this.#system.withdrawSend(attached.actor, id);
966
+ } catch (error) {
967
+ if (error instanceof TinyactorsError && error.code === 'not-found') {
968
+ throw refuse(`${attached.label} has no pending send ${id}`);
969
+ }
970
+ throw error;
971
+ }
972
+ return `${attached.label}: withdrew send ${id}`;
973
+ }
974
+
975
+ async #replace({ revision }) {
976
+ const attached = this.#requireChange('goto', 'replace');
977
+ if (attached.address === undefined) throw refuse('only a named actor can be replaced in place');
978
+ const system = this.#system;
979
+ const definition = system.findDefinition({ family: attached.address.family, revision });
980
+ if (definition === undefined) throw refuse(`no registered, unretired ${attached.address.family} revision ${revision}`);
981
+ const view = system.inspect(attached.actor);
982
+ if (view.macrostepInProgress) throw refuse(`${attached.label} is inside a macrostep: \`abandon\` it first`);
983
+ this.#audited({ type: 'mutation', operation: 'replace', revision });
984
+ const dropped = view.delayedSends.filter((send) => !send.submitted).map((send) => send.id ?? send.event);
985
+ const prepared = system.prepareReplacement(attached.actor, definition);
986
+ let replacement;
987
+ try {
988
+ // The replacement bootstraps in a pump turn before it can be activated.
989
+ for (let tries = 0; tries < MOST_TURNS && system.inspect(prepared).scheduling === 'runnable'; tries += 1) {
990
+ await nextTurn();
991
+ }
992
+ replacement = system.activate(prepared);
993
+ } catch (error) {
994
+ if (!system.closed && system.exists(prepared)) system.destroy(prepared);
995
+ throw error;
996
+ }
997
+ // Follow the address to the replacement.
998
+ const args = { address: attached.address, allow: [...attached.allow] };
999
+ this.#detach('replaced');
1000
+ const next = this.#attach(args);
1001
+ this.#refreshThreads();
1002
+ const lost = dropped.length === 0 ? '' : `; its delayed sends ${dropped.join(', ')} were dropped`;
1003
+ return `${next.label} now runs ${revision} from its initial state, with its data${lost} (actor ` +
1004
+ `${replacement.slot}:${replacement.generation})`;
1005
+ }
1006
+
1007
+ // A console line (evaluate, context repl).
1008
+ async #repl(line, thread) {
1009
+ const parsed = commands.parse(line);
1010
+ const text = (result) => ({ body: { result, variablesReference: 0 } });
1011
+ switch (parsed.command) {
1012
+ case 'help':
1013
+ return text(commands.HELP.join('\n'));
1014
+ case 'send':
1015
+ return text(this.#consoleSend(parsed));
1016
+ case 'goto':
1017
+ return text(this.#jump(parsed.targets, parsed.from));
1018
+ case 'abandon':
1019
+ return text(await this.#abandon());
1020
+ case 'cancel':
1021
+ return text(this.#cancel(parsed));
1022
+ case 'replace':
1023
+ return text(await this.#replace(parsed));
1024
+ default: {
1025
+ this.#requireEvaluate('an expression');
1026
+ return { body: this.#variables.present(expressions.evaluate(parsed.text, this.#scope(thread))) };
1027
+ }
1028
+ }
1029
+ }
1030
+
1031
+ // Why a function breakpoint cannot be verified, or undefined.
1032
+ #checkBreakpoint(breakpoint, definition) {
1033
+ if ((breakpoint.kind === 'entry' || breakpoint.kind === 'exit') && definition !== undefined &&
1034
+ this.#attached.labels.stateID(definition, breakpoint.target) === undefined) {
1035
+ return `${breakpoint.target} is not a state of the chart`;
1036
+ }
1037
+ return this.#checkCondition(breakpoint);
1038
+ }
1039
+
1040
+ #checkCondition(breakpoint) {
1041
+ const condition = breakpoint.condition;
1042
+ const allowed = this.#attached === null ? this.#allow.has('evaluate') : this.#attached.allow.has('evaluate');
1043
+ if (condition !== undefined && condition !== null && String(condition).trim() !== '' && !allowed) {
1044
+ return CONDITION_NEEDS_EVALUATE;
1045
+ }
1046
+ return undefined;
1047
+ }
1048
+
1049
+ // ----------------------------------------------------------------------
1050
+ // Requests. Each answers { body, after }: `after` runs once the response
1051
+ // is out, for events that must follow it.
1052
+
1053
+ static {
1054
+ HANDLERS = {
1055
+ initialize(args) {
1056
+ this.#client = args;
1057
+ return { body: CAPABILITIES, after: () => this.#event('initialized') };
1058
+ },
1059
+
1060
+ configurationDone() {
1061
+ return {};
1062
+ },
1063
+
1064
+ attach(args) {
1065
+ const attached = this.#attach(args);
1066
+ return { after: () => this.#announce(attached, 'attached to') };
1067
+ },
1068
+
1069
+ disconnect() {
1070
+ this.#detach('disconnect');
1071
+ return {};
1072
+ },
1073
+
1074
+ terminate() {
1075
+ this.#detach('terminate');
1076
+ return { after: () => this.#event('terminated') };
1077
+ },
1078
+
1079
+ // The actor was never stopped, so continuing changes nothing; the
1080
+ // client, which now thinks it runs, hears it stopped again so that it
1081
+ // keeps showing its stack and variables.
1082
+ continue() {
1083
+ const attached = this.#requireAttached();
1084
+ return { body: { allThreadsContinued: false }, after: () => {
1085
+ this.#output('console', `${attached.label} is watched live and never paused: continue changes nothing`);
1086
+ this.#presentStopped({ focus: true });
1087
+ } };
1088
+ },
1089
+
1090
+ threads() {
1091
+ if (this.#attached === null) return { body: { threads: [] } };
1092
+ this.#refreshThreads();
1093
+ const threads = [...this.#threads.values()].map((thread) => ({ id: thread.id, name: this.#threadName(thread) }));
1094
+ return { body: { threads } };
1095
+ },
1096
+
1097
+ stackTrace(args) {
1098
+ const thread = this.#threadArgument(args);
1099
+ const attached = this.#attached;
1100
+ const view = this.#inspect(thread);
1101
+ const waiting = view === undefined ? 0 : this.#system.mailbox(thread.actor).length;
1102
+ const list = frames({ view, labels: attached.labels, sources: attached.sources,
1103
+ seen: this.#lastMicrostep.get(thread.session),
1104
+ note: waiting === 0 ? undefined : `${plural(waiting, 'message')} waiting` });
1105
+ const start = Number(args.startFrame ?? 0);
1106
+ const levels = Number(args.levels ?? 0);
1107
+ const shown = list.slice(start, levels > 0 ? start + levels : undefined).map((frame, index) => {
1108
+ const key = `${thread.id}:${start + index}`;
1109
+ let id = this.#frameIDs.get(key);
1110
+ if (id === undefined) {
1111
+ this.#nextFrame += 1;
1112
+ id = this.#nextFrame;
1113
+ this.#frameIDs.set(key, id);
1114
+ this.#frames.set(id, { thread: thread.id });
1115
+ }
1116
+ const located = frame.place === undefined ? { line: 0, column: 0 }
1117
+ // DAP needs a column: the start of the line when the span has none.
1118
+ : { source: Sources.source(frame.place), line: frame.place.line, column: frame.place.column ?? 1 };
1119
+ return { id, name: frame.name, ...located, presentationHint: frame.hint };
1120
+ });
1121
+ return { body: { stackFrames: shown, totalFrames: list.length } };
1122
+ },
1123
+
1124
+ scopes(args) {
1125
+ this.#requireAttached();
1126
+ return { body: { scopes: this.#variables.scopes(this.#frameThread(args.frameId)) } };
1127
+ },
1128
+
1129
+ variables(args) {
1130
+ this.#requireAttached();
1131
+ return { body: { variables: this.#variables.variables(args.variablesReference, {
1132
+ start: Number(args.start ?? 0), count: Number(args.count ?? 0), filter: args.filter,
1133
+ }) } };
1134
+ },
1135
+
1136
+ setVariable(args) {
1137
+ this.#requireChange('set', 'setVariable');
1138
+ const text = String(args.value);
1139
+ const where = this.#variables.location(args.variablesReference, String(args.name));
1140
+ if (where === undefined) {
1141
+ throw refuse('only the Data model can be written; the other scopes are views of core state');
1142
+ }
1143
+ let value;
1144
+ try {
1145
+ value = JSON.parse(text);
1146
+ } catch {
1147
+ this.#requireEvaluate('a value that is not JSON');
1148
+ this.#audited({ type: 'evaluate', context: 'setVariable', expression: text });
1149
+ value = expressions.evaluate(text, this.#scope(where.thread));
1150
+ }
1151
+ this.#audited({ type: 'mutation', operation: 'set', location: expressions.locationText(where.path),
1152
+ value: jsonText(value) });
1153
+ return { body: this.#variables.set(args.variablesReference, String(args.name), value) };
1154
+ },
1155
+
1156
+ setExpression(args) {
1157
+ this.#requireChange('set', 'setExpression');
1158
+ this.#requireEvaluate('setExpression');
1159
+ const thread = this.#frameThread(args.frameId);
1160
+ const text = String(args.value);
1161
+ const scope = this.#scope(thread);
1162
+ let value;
1163
+ try {
1164
+ value = JSON.parse(text);
1165
+ } catch {
1166
+ this.#audited({ type: 'evaluate', context: 'setExpression', expression: text });
1167
+ value = expressions.evaluate(text, scope);
1168
+ }
1169
+ this.#audited({ type: 'mutation', operation: 'set', expression: String(args.expression), value: jsonText(value) });
1170
+ expressions.assign(String(args.expression), value, scope);
1171
+ const body = this.#variables.present(value);
1172
+ return { body: { value: body.result, type: body.type, variablesReference: body.variablesReference } };
1173
+ },
1174
+
1175
+ async evaluate(args) {
1176
+ this.#requireAttached();
1177
+ const expression = String(args.expression ?? '');
1178
+ const thread = this.#frameThread(args.frameId);
1179
+ if (args.context === 'repl') {
1180
+ this.#audited({ type: 'command', text: expression });
1181
+ return this.#repl(expression, thread);
1182
+ }
1183
+ this.#requireEvaluate(`evaluate (${args.context ?? 'watch'})`);
1184
+ this.#audited({ type: 'evaluate', context: args.context ?? 'watch', expression });
1185
+ const value = expressions.evaluate(expression, this.#scope(thread));
1186
+ if (args.context === 'clipboard') {
1187
+ return { body: { result: typeof value === 'string' ? value : JSON.stringify(value, null, 2) ?? String(value),
1188
+ variablesReference: 0 } };
1189
+ }
1190
+ return { body: this.#variables.present(value) };
1191
+ },
1192
+
1193
+ completions(args) {
1194
+ const attached = this.#requireAttached();
1195
+ const thread = this.#frameThread(args.frameId);
1196
+ const columnsFrom = this.#client.columnsStartAt1 === false ? 0 : 1;
1197
+ const column = Number(args.column) - columnsFrom;
1198
+ const view = this.#inspect(thread);
1199
+ const targets = commands.completions(String(args.text ?? ''), column, {
1200
+ events: () => (view === undefined ? [] : attached.labels.events(view.definitionID)),
1201
+ states: () => (view === undefined ? [] : attached.labels.states(view.definitionID).map((state) => state.name)),
1202
+ sendIDs: () => (view === undefined ? [] : view.delayedSends.map((send) => send.id).filter((id) => id !== null)),
1203
+ data: () => view?.data,
1204
+ });
1205
+ return { body: { targets: targets.map((target) => ({ ...target, start: target.start + columnsFrom })) } };
1206
+ },
1207
+
1208
+ gotoTargets(args) {
1209
+ const attached = this.#requireAttached();
1210
+ const definition = this.#system.inspect(attached.actor).definitionID;
1211
+ let states = attached.labels.states(definition);
1212
+ if (args.source !== undefined && args.line !== undefined) {
1213
+ const located = attached.sources.lines(definition, args.source, Number(args.line))
1214
+ .filter((element) => element.kind === 'state').map((element) => element.id);
1215
+ if (located.length > 0) states = states.filter((state) => located.includes(state.id));
1216
+ }
1217
+ const targets = states.map((state) => {
1218
+ const id = this.#gotoTargets.size + 1;
1219
+ this.#gotoTargets.set(id, { definition: String(definition), state: state.name });
1220
+ const place = attached.sources.place(definition, 'state', state.id);
1221
+ return { id, label: state.name, line: place?.line ?? 0, ...(place === undefined ? {} : { column: place.column }) };
1222
+ });
1223
+ return { body: { targets } };
1224
+ },
1225
+
1226
+ // A poke, as the console's `goto` is: an operator transition queued
1227
+ // behind the actor's mail. The actor is not stopped, so the client
1228
+ // hears nothing of a stop; the jump's macrostep shows like any other.
1229
+ goto(args) {
1230
+ const attached = this.#requireChange('goto', 'goto');
1231
+ const target = this.#gotoTargets.get(Number(args.targetId));
1232
+ if (target === undefined) throw refuse(`no goto target ${args.targetId}; ask gotoTargets first`);
1233
+ if (target.definition !== String(this.#system.inspect(attached.actor).definitionID)) {
1234
+ throw refuse(`${attached.label} runs another revision than the target's`);
1235
+ }
1236
+ const text = this.#jump([target.state]);
1237
+ return { after: () => this.#output('console', text) };
1238
+ },
1239
+
1240
+ setBreakpoints(args) {
1241
+ const reference = Number(args.source?.sourceReference ?? 0);
1242
+ const path = args.source?.path ?? (reference > 0 ? undefined : args.source?.name);
1243
+ if (path === undefined && !(reference > 0)) {
1244
+ throw refuse('setBreakpoints needs a source with a path or a sourceReference');
1245
+ }
1246
+ const source = path === undefined ? { sourceReference: reference } : { path };
1247
+ const specs = Array.isArray(args.breakpoints) ? args.breakpoints : (args.lines ?? []).map((line) => ({ line }));
1248
+ this.#audited({ type: 'breakpoints', kind: 'line', ...source,
1249
+ breakpoints: specs.map(({ line, condition, hitCondition, logMessage }) =>
1250
+ ({ line, condition, hitCondition, logMessage })) });
1251
+ const answered = this.#breakpoints.setLines(source, specs, (line) => {
1252
+ const problem = this.#checkCondition(specs.find((spec) => Number(spec.line) === line) ?? {});
1253
+ return problem ?? this.#resolveLine(source, line);
1254
+ });
1255
+ return { body: { breakpoints: answered } };
1256
+ },
1257
+
1258
+ breakpointLocations(args) {
1259
+ const attached = this.#requireAttached();
1260
+ if (args.source?.path === undefined && !(Number(args.source?.sourceReference) > 0)) {
1261
+ return { body: { breakpoints: [] } };
1262
+ }
1263
+ const definition = this.#system.inspect(attached.actor).definitionID;
1264
+ const found = attached.sources.lines(definition, args.source, Number(args.line),
1265
+ Number(args.endLine ?? args.line));
1266
+ const unique = new Map(found.map((element) => [`${element.line}:${element.column}`, element]));
1267
+ const breakpoints = [...unique.values()].map((element) => ({ line: element.line, column: element.column }));
1268
+ return { body: { breakpoints } };
1269
+ },
1270
+
1271
+ setFunctionBreakpoints(args) {
1272
+ const specs = Array.isArray(args.breakpoints) ? args.breakpoints : [];
1273
+ const attached = this.#attached;
1274
+ const definition = attached === null ? undefined : this.#system.inspect(attached.actor).definitionID;
1275
+ this.#audited({ type: 'breakpoints', kind: 'function',
1276
+ breakpoints: specs.map(({ name, condition, hitCondition }) =>
1277
+ ({ name, condition, hitCondition })) });
1278
+ const answered = this.#breakpoints.setFunctions(specs, (breakpoint) =>
1279
+ (attached === null ? this.#checkCondition(breakpoint) : this.#checkBreakpoint(breakpoint, definition)));
1280
+ return { body: { breakpoints: answered } };
1281
+ },
1282
+
1283
+ setExceptionBreakpoints(args) {
1284
+ const filters = [...(args.filters ?? []), ...(args.filterOptions ?? []).map((option) => option.filterId)];
1285
+ const unique = [...new Set(filters)];
1286
+ this.#audited({ type: 'breakpoints', kind: 'exception', filters: unique });
1287
+ this.#breakpoints.setFilters(unique);
1288
+ return { body: { breakpoints: unique.map(() => ({ verified: true })) } };
1289
+ },
1290
+
1291
+ dataBreakpointInfo(args) {
1292
+ this.#requireAttached();
1293
+ const name = String(args.name ?? '');
1294
+ let target;
1295
+ if (args.variablesReference !== undefined) {
1296
+ target = this.#variables.location(args.variablesReference, name);
1297
+ } else {
1298
+ const path = expressions.pathOf(name);
1299
+ target = path === undefined ? undefined : { thread: this.#frameThread(args.frameId), path };
1300
+ }
1301
+ if (target === undefined) {
1302
+ return { body: { dataId: null, description: `${name} is not a data-model location` } };
1303
+ }
1304
+ return { body: {
1305
+ dataId: Breakpoints.dataID(target.thread.label, target.path),
1306
+ description: `${target.thread.label} ${expressions.locationText(target.path)}`,
1307
+ accessTypes: ['write'],
1308
+ canPersist: true,
1309
+ } };
1310
+ },
1311
+
1312
+ setDataBreakpoints(args) {
1313
+ const specs = Array.isArray(args.breakpoints) ? args.breakpoints : [];
1314
+ this.#audited({ type: 'breakpoints', kind: 'data',
1315
+ breakpoints: specs.map(({ dataId, condition, hitCondition }) =>
1316
+ ({ dataId, condition, hitCondition })) });
1317
+ const answered = this.#breakpoints.setData(specs, (breakpoint) => {
1318
+ if (![...this.#threads.values()].some((thread) => thread.label === breakpoint.label)) {
1319
+ return `no thread is ${breakpoint.label}`;
1320
+ }
1321
+ return this.#checkCondition(breakpoint);
1322
+ });
1323
+ return { body: { breakpoints: answered } };
1324
+ },
1325
+
1326
+ modules(args) {
1327
+ if (this.#attached !== null) this.#refreshCatalog();
1328
+ const all = [...this.#modules.values()];
1329
+ const start = Number(args.startModule ?? 0);
1330
+ const count = Number(args.moduleCount ?? 0);
1331
+ return { body: { modules: all.slice(start, count > 0 ? start + count : undefined), totalModules: all.length } };
1332
+ },
1333
+
1334
+ loadedSources() {
1335
+ if (this.#attached !== null) this.#refreshCatalog();
1336
+ return { body: { sources: [...[...this.#sourceRefs.values()].map((entry) => entry.source),
1337
+ ...[...this.#files].map((path) => Sources.source({ path }))] } };
1338
+ },
1339
+
1340
+ source(args) {
1341
+ const reference = Number(args.sourceReference ?? args.source?.sourceReference ?? 0);
1342
+ const written = this.#attached?.sources.content(reference);
1343
+ if (written !== undefined) return { body: written };
1344
+ const entry = this.#sourceRefs.get(reference);
1345
+ if (entry?.virtual) throw refuse('attach first: the SCXML is written from the attached session\'s chart');
1346
+ if (entry === undefined) {
1347
+ throw refuse(args.source?.path !== undefined && this.#files.has(args.source.path)
1348
+ ? `${args.source.path} is a file the client reads itself` : 'no such source');
1349
+ }
1350
+ const spec = core.definition_export(nativeOf(this.#system), entry.definition);
1351
+ return { body: { content: exportText(spec), mimeType: 'application/json' } };
1352
+ },
1353
+ };
1354
+ }
1355
+ }
1356
+
1357
+ /** A debug session over `system` (see the top of this module). */
1358
+ function createDebugSession(system, options) {
1359
+ return new DebugSession(system, options);
1360
+ }
1361
+
1362
+ // { family, name } from an address in one of its spellings, or undefined.
1363
+ function parseAddress(address) {
1364
+ if (address !== null && typeof address === 'object') {
1365
+ const { family, name } = address;
1366
+ return typeof family === 'string' && typeof name === 'string' && family !== '' && name !== ''
1367
+ ? { family, name } : undefined;
1368
+ }
1369
+ if (typeof address !== 'string') return undefined;
1370
+ const text = address.startsWith('#_actor_') ? address.slice('#_actor_'.length) : address;
1371
+ const slash = text.indexOf('/');
1372
+ return slash > 0 && slash < text.length - 1 ? { family: text.slice(0, slash), name: text.slice(slash + 1) } : undefined;
1373
+ }
1374
+
1375
+ /*
1376
+ * The resident actor that holds session `wanted` (a bigint), or undefined.
1377
+ * A session ID is the runtime ID its session was spawned with (core ADR
1378
+ * 0066), so the actor that still has that ID is tried first and checked;
1379
+ * one reloaded since has another ID, so every resident actor is looked
1380
+ * through for it.
1381
+ */
1382
+ function actorOfSession(system, wanted) {
1383
+ const guess = new ActorID(system, Number(wanted & 0xffffffffn), Number(wanted >> 32n));
1384
+ try {
1385
+ if (system.inspect(guess).sessionID === wanted) return guess;
1386
+ } catch (error) {
1387
+ if (!(error instanceof TinyactorsError && (error.code === 'not-found' || error.code === 'invalid'))) throw error;
1388
+ }
1389
+ for (const view of system.actors()) {
1390
+ if (view.sessionID === wanted) return view.actor;
1391
+ }
1392
+ return undefined;
1393
+ }
1394
+
1395
+ /**
1396
+ * The child an in-system SCXML invocation runs, from its serviceHandle:
1397
+ * the child's runtime ID, (generation << 32) | slot (src/adapters/invoker.c),
1398
+ * not its session ID; they differ once slots are reused or an actor is
1399
+ * reloaded. Answers { actor, session } with the session in decimal, or
1400
+ * undefined when no resident actor has that ID any more.
1401
+ */
1402
+ function childOf(system, handle) {
1403
+ const actor = new ActorID(system, Number(handle & 0xffffffffn), Number(handle >> 32n));
1404
+ try {
1405
+ return { actor, session: String(system.inspect(actor).sessionID) };
1406
+ } catch (error) {
1407
+ if (error instanceof TinyactorsError && (error.code === 'not-found' || error.code === 'invalid')) return undefined;
1408
+ throw error;
1409
+ }
1410
+ }
1411
+
1412
+ // A definition's export as a loaded source the client asks for by reference.
1413
+ function exportSource(definition, revision, reference) {
1414
+ return { name: `${definition.identity.family} ${revision}.json`, sourceReference: reference, origin: 'definition export',
1415
+ presentationHint: definition.retired ? 'deemphasize' : 'normal' };
1416
+ }
1417
+
1418
+ // A definition's export as text: JavaScript functions as their source.
1419
+ function exportText(spec) {
1420
+ return JSON.stringify(spec, (key, value) => {
1421
+ if (typeof value === 'function') return String(value);
1422
+ if (typeof value === 'bigint') return String(value);
1423
+ if (value instanceof Uint8Array) {
1424
+ try {
1425
+ return new TextDecoder('utf-8', { fatal: true }).decode(value);
1426
+ } catch {
1427
+ return [...value];
1428
+ }
1429
+ }
1430
+ return value;
1431
+ }, 2);
1432
+ }
1433
+
1434
+ module.exports = { DebugSession, createDebugSession, DAPReader, encodeDAPMessage, CAPABILITIES };