@tsplc/tmp-debug 0.0.0-stage → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +38 -2
  2. package/dist/api.js +744 -0
  3. package/dist/api.js.map +12 -0
  4. package/dist/constant.js +33 -0
  5. package/dist/constant.js.map +10 -0
  6. package/dist/explain-file.js +468 -0
  7. package/dist/explain-file.js.map +11 -0
  8. package/dist/explain.js +1310 -0
  9. package/dist/explain.js.map +19 -0
  10. package/dist/format.js +214 -0
  11. package/dist/format.js.map +12 -0
  12. package/dist/index.js +4066 -0
  13. package/dist/index.js.map +44 -0
  14. package/dist/manifest.js +240 -0
  15. package/dist/manifest.js.map +10 -0
  16. package/dist/paths.js +242 -0
  17. package/dist/paths.js.map +10 -0
  18. package/package.json +72 -4
  19. package/src/adapter.ts +77 -0
  20. package/src/api.ts +446 -0
  21. package/src/app-server.ts +151 -0
  22. package/src/build-files.ts +46 -0
  23. package/src/constant.ts +41 -0
  24. package/src/debugger.ts +237 -0
  25. package/src/errors.ts +13 -0
  26. package/src/explain-expressions.ts +484 -0
  27. package/src/explain-file.ts +325 -0
  28. package/src/explain-frames.ts +155 -0
  29. package/src/explain-loops.ts +151 -0
  30. package/src/explain-operations.ts +232 -0
  31. package/src/explain-tables.ts +345 -0
  32. package/src/explain-value.ts +203 -0
  33. package/src/explain-verdicts.ts +548 -0
  34. package/src/explain.ts +82 -0
  35. package/src/hardware.ts +159 -0
  36. package/src/http.ts +218 -0
  37. package/src/index.ts +44 -0
  38. package/src/jobs.ts +139 -0
  39. package/src/login-value.ts +165 -0
  40. package/src/login.ts +315 -0
  41. package/src/manifest.ts +328 -0
  42. package/src/opcua.ts +80 -0
  43. package/src/paths.ts +363 -0
  44. package/src/requests.ts +99 -0
  45. package/src/server-cursor.ts +22 -0
  46. package/src/shown.ts +229 -0
  47. package/src/telemetry.ts +125 -0
  48. package/src/timeline.ts +148 -0
  49. package/src/trace.ts +62 -0
  50. package/src/ui/bits.ts +48 -0
  51. package/src/ui/client.ts +87 -0
  52. package/src/ui/dom.ts +61 -0
  53. package/src/ui/explain-read.ts +105 -0
  54. package/src/ui/format.ts +261 -0
  55. package/src/ui/hardware.ts +425 -0
  56. package/src/ui/header.ts +207 -0
  57. package/src/ui/health.ts +64 -0
  58. package/src/ui/index.ts +27 -0
  59. package/src/ui/jobs.ts +263 -0
  60. package/src/ui/links.ts +59 -0
  61. package/src/ui/live-value.ts +85 -0
  62. package/src/ui/main.ts +76 -0
  63. package/src/ui/overview.ts +178 -0
  64. package/src/ui/page.ts +286 -0
  65. package/src/ui/pages.ts +64 -0
  66. package/src/ui/recent-window.ts +49 -0
  67. package/src/ui/recent.ts +355 -0
  68. package/src/ui/request-trace.ts +38 -0
  69. package/src/ui/requests.ts +80 -0
  70. package/src/ui/routes.ts +98 -0
  71. package/src/ui/store.ts +295 -0
  72. package/src/ui/success-cache.ts +11 -0
  73. package/src/ui/tree.ts +162 -0
  74. package/src/ui/variables.ts +597 -0
  75. package/src/ui/why-watch.ts +11 -0
  76. package/src/ui/why.ts +694 -0
  77. package/src/values.ts +170 -0
  78. package/src/watch.ts +32 -0
package/dist/index.js ADDED
@@ -0,0 +1,4066 @@
1
+ // packages/debug/src/build-files.ts
2
+ import { createHash } from "node:crypto";
3
+ import { readFile } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+
6
+ // packages/debug/src/explain-file.ts
7
+ import {
8
+ valueBinaryOperators,
9
+ valueUnaryOperators
10
+ } from "@tsplc/iec/arithmetic";
11
+ import { z as z2 } from "zod";
12
+
13
+ // packages/debug/src/manifest.ts
14
+ import { z } from "zod";
15
+ var sourceRange = z.object({
16
+ file: z.number().int(),
17
+ line: z.number().int(),
18
+ column: z.number().int(),
19
+ endLine: z.number().int(),
20
+ endColumn: z.number().int()
21
+ });
22
+ var json = z.lazy(() => z.union([
23
+ z.string(),
24
+ z.number(),
25
+ z.boolean(),
26
+ z.null(),
27
+ z.array(json),
28
+ z.record(z.string(), json)
29
+ ]));
30
+ var debugField = z.object({
31
+ name: z.string(),
32
+ target: z.string(),
33
+ type: z.string(),
34
+ declaration: sourceRange.optional(),
35
+ generated: z.literal(true).optional()
36
+ });
37
+ var debugType = z.discriminatedUnion("kind", [
38
+ z.object({
39
+ kind: z.literal("scalar"),
40
+ iec: z.string(),
41
+ capacity: z.number().int().optional()
42
+ }),
43
+ z.object({
44
+ kind: z.literal("enum"),
45
+ name: z.string(),
46
+ members: z.record(z.string(), z.number().int()),
47
+ texts: z.record(z.string(), z.string()).optional()
48
+ }),
49
+ z.object({
50
+ kind: z.literal("record"),
51
+ name: z.string(),
52
+ declaration: sourceRange.optional(),
53
+ fields: z.array(debugField)
54
+ }),
55
+ z.object({
56
+ kind: z.literal("array"),
57
+ element: z.string(),
58
+ length: z.number().int(),
59
+ lower: z.number().int(),
60
+ index: z.string().optional()
61
+ })
62
+ ]);
63
+ var debugRoot = z.object({
64
+ path: z.string(),
65
+ target: z.string(),
66
+ type: z.string(),
67
+ declaration: sourceRange.optional(),
68
+ readable: z.boolean(),
69
+ generated: z.literal(true).optional()
70
+ });
71
+ var debugConstant = z.object({
72
+ path: z.string(),
73
+ type: z.string(),
74
+ value: json,
75
+ declaration: sourceRange.optional()
76
+ });
77
+ var debugIo = z.object({
78
+ path: z.string(),
79
+ target: z.string(),
80
+ direction: z.enum(["input", "output"]),
81
+ type: z.string(),
82
+ device: z.string().optional(),
83
+ channel: z.string().optional(),
84
+ address: z.string().optional(),
85
+ inverted: z.literal(true).optional(),
86
+ shared: z.literal(true).optional()
87
+ });
88
+ var debugChannel = z.object({
89
+ id: z.string(),
90
+ name: z.string(),
91
+ direction: z.enum(["input", "output"]),
92
+ type: z.string(),
93
+ offsetBits: z.number().int(),
94
+ bits: z.number().int(),
95
+ address: z.string().optional(),
96
+ unit: z.string().optional(),
97
+ description: z.string().optional()
98
+ });
99
+ var debugDevice = z.object({
100
+ id: z.string(),
101
+ product: z.string().optional(),
102
+ vendor: z.string().optional(),
103
+ productCode: z.string().optional(),
104
+ network: z.object({ address: z.string(), rpiMs: z.number().optional() }).optional(),
105
+ connection: z.string().optional(),
106
+ assemblies: z.array(z.object({
107
+ direction: z.enum(["input", "output"]),
108
+ bytes: z.number().int(),
109
+ address: z.string().optional(),
110
+ raw: z.string().optional()
111
+ })),
112
+ health: z.object({
113
+ state: z.string().optional(),
114
+ states: z.record(z.string(), z.number().int()).optional(),
115
+ diagnostic: z.string().optional(),
116
+ message: z.string().optional()
117
+ }).optional(),
118
+ status: z.record(z.string(), z.string()).optional(),
119
+ channels: z.array(debugChannel)
120
+ });
121
+ var debugFunction = z.object({
122
+ id: z.number().int(),
123
+ name: z.string(),
124
+ declaration: sourceRange,
125
+ instance: z.string().optional(),
126
+ task: z.string().optional(),
127
+ target: z.string(),
128
+ reads: z.array(z.object({ range: sourceRange, path: z.string() }))
129
+ });
130
+ var jobStateFields = {
131
+ step: "UINT",
132
+ cancelling: "BOOL",
133
+ busy: "BOOL",
134
+ done: "BOOL",
135
+ error: "UDINT"
136
+ };
137
+ var instrumentationFields = {
138
+ busy: jobStateFields.busy,
139
+ step: jobStateFields.step,
140
+ startedAt: "UDINT",
141
+ job: "UDINT",
142
+ sequence: "UDINT"
143
+ };
144
+ var debugJob = z.object({
145
+ id: z.number().int(),
146
+ name: z.string(),
147
+ declaration: sourceRange,
148
+ instance: z.string().optional(),
149
+ target: z.string(),
150
+ steps: z.array(z.object({
151
+ step: z.number().int(),
152
+ kind: z.enum(["await", "return", "throw", "statement"]),
153
+ range: sourceRange,
154
+ text: z.string()
155
+ })),
156
+ startedAt: z.string().optional(),
157
+ requests: z.array(z.object({
158
+ service: z.string(),
159
+ target: z.string(),
160
+ sequence: z.string(),
161
+ job: z.number().int().optional()
162
+ })),
163
+ generated: z.literal(true).optional()
164
+ });
165
+ var debugEventSite = z.object({
166
+ id: z.number().int(),
167
+ kind: z.enum(["state", "decision", "job"]),
168
+ job: z.number().int().optional(),
169
+ phase: z.enum(["started", "finished"]).optional(),
170
+ path: z.string(),
171
+ function: z.number().int().optional(),
172
+ type: z.string(),
173
+ range: sourceRange,
174
+ text: z.string(),
175
+ task: z.string(),
176
+ operands: z.array(z.object({
177
+ text: z.string(),
178
+ range: sourceRange,
179
+ type: z.string(),
180
+ path: z.string().optional(),
181
+ stable: z.boolean()
182
+ }))
183
+ });
184
+ var writerSlotType = "UINT";
185
+ var debugWriter = z.object({
186
+ output: z.string(),
187
+ target: z.string(),
188
+ exact: z.boolean().optional(),
189
+ sites: z.array(z.object({
190
+ id: z.number().int(),
191
+ range: sourceRange,
192
+ function: z.number().int(),
193
+ assignments: z.array(z.number().int()).optional()
194
+ }))
195
+ });
196
+ var scanClockType = "DINT";
197
+ var debugTask = z.object({
198
+ name: z.string(),
199
+ intervalMs: z.number(),
200
+ priority: z.number().int(),
201
+ clock: z.string().optional()
202
+ });
203
+ var debugManifest = z.object({
204
+ kind: z.literal("tsplc-debug"),
205
+ version: z.literal(1),
206
+ build: z.object({
207
+ id: z.string(),
208
+ target: z.string(),
209
+ compiler: z.string()
210
+ }),
211
+ sources: z.array(z.string()),
212
+ types: z.record(z.string(), debugType),
213
+ roots: z.array(debugRoot),
214
+ constants: z.array(debugConstant),
215
+ io: z.array(debugIo),
216
+ devices: z.array(debugDevice),
217
+ functions: z.array(debugFunction),
218
+ jobs: z.array(debugJob),
219
+ events: z.array(debugEventSite),
220
+ writers: z.array(debugWriter),
221
+ tasks: z.array(debugTask),
222
+ errors: z.record(z.string(), z.string()),
223
+ explain: z.object({ sha256: z.string() }).optional()
224
+ });
225
+
226
+ // packages/debug/src/explain-file.ts
227
+ var explainFileName = "explain.json";
228
+ var tableIndex = z2.number().int().nonnegative();
229
+ var position = z2.number().int().nonnegative();
230
+ var explainExpression = z2.discriminatedUnion("kind", [
231
+ z2.object({
232
+ kind: z2.literal("read"),
233
+ path: tableIndex,
234
+ capturedAt: position,
235
+ interleaved: z2.literal(true).optional(),
236
+ type: z2.string()
237
+ }),
238
+ z2.object({
239
+ kind: z2.literal("pattern"),
240
+ path: tableIndex,
241
+ indexes: z2.array(tableIndex),
242
+ capturedAt: position,
243
+ interleaved: z2.literal(true).optional(),
244
+ type: z2.string()
245
+ }),
246
+ z2.object({ kind: z2.literal("constant"), value: json, type: z2.string() }),
247
+ z2.object({
248
+ kind: z2.literal("record"),
249
+ fields: z2.record(z2.string(), tableIndex),
250
+ type: z2.string()
251
+ }),
252
+ z2.object({
253
+ kind: z2.literal("array"),
254
+ lower: z2.number().int(),
255
+ items: z2.array(tableIndex),
256
+ type: z2.string()
257
+ }),
258
+ z2.object({
259
+ kind: z2.literal("local"),
260
+ local: tableIndex,
261
+ path: z2.array(z2.string()),
262
+ at: position,
263
+ type: z2.string()
264
+ }),
265
+ z2.object({
266
+ kind: z2.literal("parameter"),
267
+ parameter: z2.number().int().nonnegative(),
268
+ path: z2.array(z2.string()),
269
+ at: position,
270
+ local: tableIndex.nullable(),
271
+ type: z2.string()
272
+ }),
273
+ z2.object({
274
+ kind: z2.literal("call"),
275
+ call: tableIndex,
276
+ path: z2.array(z2.string()),
277
+ type: z2.string()
278
+ }),
279
+ z2.object({ kind: z2.literal("clock"), type: z2.string() }),
280
+ z2.object({ kind: z2.literal("reference"), operand: tableIndex }),
281
+ z2.object({
282
+ kind: z2.literal("unary"),
283
+ operator: z2.enum(valueUnaryOperators),
284
+ operand: tableIndex,
285
+ type: z2.string()
286
+ }),
287
+ z2.object({
288
+ kind: z2.literal("binary"),
289
+ operator: z2.enum(valueBinaryOperators),
290
+ policy: z2.enum(["wrap", "saturate"]).optional(),
291
+ left: tableIndex,
292
+ right: tableIndex,
293
+ type: z2.string()
294
+ }),
295
+ z2.object({
296
+ kind: z2.literal("convert"),
297
+ policy: z2.enum(["exact", "wrap", "saturate"]),
298
+ operand: tableIndex,
299
+ type: z2.string()
300
+ }),
301
+ z2.object({
302
+ kind: z2.literal("logical"),
303
+ operator: z2.enum(["and", "or"]),
304
+ left: tableIndex,
305
+ right: tableIndex
306
+ }),
307
+ z2.object({
308
+ kind: z2.literal("select"),
309
+ condition: tableIndex,
310
+ then: tableIndex,
311
+ else: tableIndex,
312
+ type: z2.string()
313
+ }),
314
+ z2.object({
315
+ kind: z2.literal("opaque"),
316
+ text: tableIndex,
317
+ reads: z2.array(tableIndex),
318
+ type: z2.string()
319
+ })
320
+ ]);
321
+ var exitsCondition = z2.object({
322
+ kind: z2.literal("exits"),
323
+ get any() {
324
+ return z2.array(z2.array(explainCondition));
325
+ }
326
+ });
327
+ var explainCondition = z2.union([
328
+ z2.object({
329
+ kind: z2.literal("test"),
330
+ test: tableIndex,
331
+ holds: z2.boolean(),
332
+ at: position,
333
+ text: tableIndex.nullable()
334
+ }),
335
+ z2.object({
336
+ kind: z2.literal("cases"),
337
+ test: tableIndex,
338
+ values: z2.array(json),
339
+ member: z2.boolean(),
340
+ at: position,
341
+ text: tableIndex.nullable()
342
+ }),
343
+ exitsCondition,
344
+ z2.object({ kind: z2.literal("loop"), loop: tableIndex }),
345
+ z2.object({ kind: z2.literal("loopReturns"), loop: tableIndex }),
346
+ z2.object({ kind: z2.literal("job"), step: z2.number().int() }),
347
+ z2.object({ kind: z2.literal("jobBusy") })
348
+ ]);
349
+ var record = {
350
+ routine: tableIndex,
351
+ position,
352
+ conditions: tableIndex.nullable(),
353
+ site: tableIndex.nullable()
354
+ };
355
+ var written = z2.discriminatedUnion("kind", [
356
+ z2.object({ kind: z2.literal("path"), path: tableIndex }),
357
+ z2.object({
358
+ kind: z2.literal("pattern"),
359
+ path: tableIndex,
360
+ indexes: z2.array(tableIndex)
361
+ })
362
+ ]);
363
+ var explainAssignment = z2.object({
364
+ ...record,
365
+ kind: z2.enum(["assign", "call", "block", "input", "return", "counter"]),
366
+ writes: written,
367
+ whole: z2.boolean(),
368
+ value: tableIndex.nullable(),
369
+ block: z2.object({
370
+ kind: z2.string(),
371
+ inputs: z2.record(z2.string(), tableIndex),
372
+ elapsed: tableIndex.nullable()
373
+ }).nullable(),
374
+ via: z2.array(tableIndex),
375
+ loop: tableIndex.nullable()
376
+ });
377
+ var explainLocal = z2.object({
378
+ routine: tableIndex,
379
+ name: z2.string(),
380
+ parameter: z2.boolean(),
381
+ reference: z2.boolean(),
382
+ definitions: z2.array(z2.object({
383
+ ...record,
384
+ kind: z2.enum(["assign", "borrowed", "counter"]),
385
+ path: z2.array(z2.string()),
386
+ value: tableIndex.nullable(),
387
+ call: tableIndex.nullable(),
388
+ loop: tableIndex.nullable()
389
+ }))
390
+ });
391
+ var explainCall = z2.object({
392
+ ...record,
393
+ callee: z2.string(),
394
+ receiver: z2.discriminatedUnion("kind", [
395
+ z2.object({ kind: z2.literal("none") }),
396
+ z2.object({ kind: z2.literal("path"), path: tableIndex }),
397
+ z2.object({
398
+ kind: z2.literal("pattern"),
399
+ path: tableIndex,
400
+ indexes: z2.array(tableIndex)
401
+ })
402
+ ]),
403
+ arguments: z2.array(tableIndex),
404
+ loop: tableIndex.nullable()
405
+ });
406
+ var explainFlags = z2.object({
407
+ path: tableIndex,
408
+ input: z2.number().int().nullable(),
409
+ clientWritable: z2.boolean(),
410
+ hmiControl: z2.string().nullable(),
411
+ retained: z2.boolean(),
412
+ constantTable: z2.boolean(),
413
+ writerTasks: z2.array(z2.string()),
414
+ service: z2.object({ job: z2.number().int(), service: z2.string() }).nullable(),
415
+ initial: json.nullable(),
416
+ reference: z2.boolean()
417
+ });
418
+ var explainFile = z2.object({
419
+ kind: z2.literal("tsplc-explain"),
420
+ version: z2.literal(1),
421
+ paths: z2.array(z2.string()),
422
+ texts: z2.array(z2.string()),
423
+ expressions: z2.array(explainExpression),
424
+ conditions: z2.array(z2.object({ parent: tableIndex.nullable(), condition: explainCondition })),
425
+ sites: z2.array(z2.object({ range: sourceRange, text: tableIndex.nullable() })),
426
+ routines: z2.array(z2.object({
427
+ key: z2.string(),
428
+ function: z2.number().int().nullable(),
429
+ instance: tableIndex.nullable(),
430
+ name: z2.string(),
431
+ declaration: sourceRange.nullable(),
432
+ job: z2.number().int().nullable(),
433
+ paths: z2.array(tableIndex),
434
+ locals: z2.array(tableIndex),
435
+ calls: z2.array(tableIndex),
436
+ loops: z2.array(tableIndex)
437
+ })),
438
+ loops: z2.array(z2.object({
439
+ routine: tableIndex,
440
+ position,
441
+ counter: tableIndex,
442
+ first: tableIndex,
443
+ limit: tableIndex,
444
+ exclusive: z2.boolean(),
445
+ step: tableIndex,
446
+ maxIterations: z2.number().int().nonnegative(),
447
+ breaks: z2.array(z2.array(explainCondition)),
448
+ parent: tableIndex.nullable(),
449
+ site: tableIndex.nullable()
450
+ })),
451
+ assignments: z2.array(explainAssignment),
452
+ locals: z2.array(explainLocal),
453
+ returns: z2.array(z2.object({ ...record, value: tableIndex.nullable() })),
454
+ calls: z2.array(explainCall),
455
+ entries: z2.array(z2.object({
456
+ routine: tableIndex,
457
+ task: z2.string(),
458
+ order: z2.number().int().nonnegative()
459
+ })),
460
+ flags: z2.array(explainFlags),
461
+ references: z2.record(z2.string(), tableIndex)
462
+ });
463
+
464
+ // packages/debug/src/build-files.ts
465
+ var loadManifest = async (file) => debugManifest.parse(JSON.parse(await readFile(file, "utf8")));
466
+ var loadExplanations = async (manifestFile, manifest) => {
467
+ if (!manifest.explain) {
468
+ return null;
469
+ }
470
+ const text = await readFile(join(dirname(manifestFile), explainFileName), "utf8");
471
+ const sha256 = createHash("sha256").update(text).digest("hex");
472
+ if (sha256 !== manifest.explain.sha256) {
473
+ throw new Error(`${explainFileName} doesn't belong to this build`);
474
+ }
475
+ return { text, sha256, file: explainFile.parse(JSON.parse(text)) };
476
+ };
477
+ var loadDebugBuild = async (manifestFile) => {
478
+ const manifest = await loadManifest(manifestFile);
479
+ return {
480
+ manifest,
481
+ explanations: await loadExplanations(manifestFile, manifest)
482
+ };
483
+ };
484
+ // packages/debug/src/debugger.ts
485
+ import { join as join2 } from "node:path";
486
+
487
+ // packages/debug/src/adapter.ts
488
+ var scalarRead = (target, iec) => ({
489
+ target,
490
+ type: { kind: "scalar", iec }
491
+ });
492
+ var qualityRank = {
493
+ good: 0,
494
+ uncertain: 1,
495
+ bad: 2,
496
+ unavailable: 3
497
+ };
498
+ var worstQuality = (samples) => samples.reduce((worst, sample) => {
499
+ const quality = sample?.quality ?? "unavailable";
500
+ return qualityRank[quality] > qualityRank[worst] ? quality : worst;
501
+ }, "good");
502
+
503
+ // packages/debug/src/app-server.ts
504
+ import { sleep } from "@tsplc/opcua";
505
+ import { requestsPath, requestsReply } from "@tsplc/server/requests";
506
+ import { telemetryPath, telemetryReply } from "@tsplc/server/telemetry";
507
+
508
+ // packages/debug/src/errors.ts
509
+ var errorMessage = (error) => error instanceof Error ? error.message : String(error);
510
+
511
+ class DebugError extends Error {
512
+ status;
513
+ constructor(message, status) {
514
+ super(message);
515
+ this.status = status;
516
+ }
517
+ }
518
+
519
+ // packages/debug/src/server-cursor.ts
520
+ var createServerCursor = () => {
521
+ let newest = 0;
522
+ return {
523
+ newest: () => newest,
524
+ continues: (latest) => {
525
+ if (latest < newest) {
526
+ newest = 0;
527
+ return false;
528
+ }
529
+ return true;
530
+ },
531
+ take: (seq) => {
532
+ newest = Math.max(newest, seq);
533
+ }
534
+ };
535
+ };
536
+
537
+ // packages/debug/src/timeline.ts
538
+ var timelineEntries = {
539
+ app: (at, task, sequence, record) => ({
540
+ at,
541
+ approximate: true,
542
+ source: "plc",
543
+ kind: "app",
544
+ task,
545
+ sequence,
546
+ record
547
+ }),
548
+ trace: (at, trace) => ({
549
+ at,
550
+ approximate: true,
551
+ source: "plc",
552
+ kind: "trace",
553
+ trace
554
+ }),
555
+ request: (request) => ({
556
+ at: request.startedAt,
557
+ approximate: true,
558
+ source: "server",
559
+ kind: "request",
560
+ request
561
+ }),
562
+ deploy: (at, details) => ({
563
+ at,
564
+ approximate: false,
565
+ source: "agent",
566
+ kind: "deploy",
567
+ ...details
568
+ }),
569
+ audit: (at, details) => ({
570
+ at,
571
+ approximate: false,
572
+ source: "agent",
573
+ kind: "audit",
574
+ ...details
575
+ }),
576
+ connection: (at, state, error) => ({
577
+ at,
578
+ approximate: false,
579
+ source: "debugger",
580
+ kind: "connection",
581
+ state,
582
+ ...error && { error }
583
+ })
584
+ };
585
+ var insertInTimeOrder = (entries, entry) => {
586
+ for (let index = entries.length;index >= 0; index--) {
587
+ const before = entries[index - 1];
588
+ if (before === undefined || before.at <= entry.at) {
589
+ entries.splice(index, 0, entry);
590
+ return;
591
+ }
592
+ }
593
+ };
594
+ var cursorPattern = /^([0-9a-f]{8})\.(\d+)$/;
595
+ var isTimelineCursor = (text) => cursorPattern.test(text);
596
+ var timelineLimit = 1e4;
597
+ var createTimeline = () => {
598
+ const host = crypto.randomUUID().slice(0, 8);
599
+ const entries = [];
600
+ let taken = 0;
601
+ const takenAt = (cursor) => {
602
+ const [, issuer, count] = cursorPattern.exec(cursor) ?? [];
603
+ return issuer === host ? Number(count) : 0;
604
+ };
605
+ const stamp = (entry) => {
606
+ taken += 1;
607
+ return Object.assign(entry, { cursor: `${host}.${taken}` });
608
+ };
609
+ return {
610
+ add: (entry) => {
611
+ const stamped = stamp(entry);
612
+ insertInTimeOrder(entries, stamped);
613
+ if (entries.length > timelineLimit) {
614
+ entries.splice(0, entries.length - timelineLimit);
615
+ }
616
+ return stamped;
617
+ },
618
+ changed: stamp,
619
+ since: ({ since, after }) => {
620
+ if (after !== undefined) {
621
+ const resumed = takenAt(after);
622
+ return entries.filter((entry) => takenAt(entry.cursor) > resumed);
623
+ }
624
+ return since ? entries.filter((entry) => entry.at > since) : [...entries];
625
+ }
626
+ };
627
+ };
628
+
629
+ // packages/debug/src/requests.ts
630
+ var callsRemembered = 1000;
631
+ var taggedCall = ({
632
+ job,
633
+ service,
634
+ sequence
635
+ }) => job === undefined || sequence === undefined ? undefined : { job, service, sequence };
636
+ var callKey = ({ job, service, sequence }) => `${job}:${service}:${sequence}`;
637
+ var createRequestFollower = () => {
638
+ const cursor = createServerCursor();
639
+ const pending = new Map;
640
+ const calls = new Map;
641
+ return {
642
+ since: () => pending.size ? Math.min(...pending.keys()) - 1 : cursor.newest(),
643
+ accept: (reply, changed) => {
644
+ if (!cursor.continues(reply.latest)) {
645
+ pending.clear();
646
+ return;
647
+ }
648
+ const oldest = reply.requests[0]?.seq;
649
+ if (oldest !== undefined) {
650
+ for (const seq of pending.keys()) {
651
+ if (seq < oldest) {
652
+ pending.delete(seq);
653
+ }
654
+ }
655
+ }
656
+ for (const request of reply.requests) {
657
+ const waiting = pending.get(request.seq);
658
+ if (waiting && request.status === "pending") {
659
+ continue;
660
+ }
661
+ if (!waiting && request.seq <= cursor.newest()) {
662
+ continue;
663
+ }
664
+ const entry = waiting ?? timelineEntries.request(request);
665
+ entry.request = request;
666
+ cursor.take(request.seq);
667
+ if (request.status === "pending") {
668
+ pending.set(request.seq, entry);
669
+ } else {
670
+ pending.delete(request.seq);
671
+ }
672
+ const tagged = taggedCall(request);
673
+ if (tagged) {
674
+ calls.set(callKey(tagged), request);
675
+ for (const key of [...calls.keys()].slice(0, -callsRemembered)) {
676
+ calls.delete(key);
677
+ }
678
+ }
679
+ changed({ request, entry, added: !waiting });
680
+ }
681
+ },
682
+ call: (call) => calls.get(callKey(call))
683
+ };
684
+ };
685
+
686
+ // packages/debug/src/app-server.ts
687
+ var pullMs = 1000;
688
+ var followAppServer = (context) => {
689
+ const { server, manifest, telemetry, requests, trace, shown, signal } = context;
690
+ const receive = (received) => {
691
+ const { record, at } = received;
692
+ if (record.kind === "trace") {
693
+ const traced = { ...received, record };
694
+ const event = trace.decode(traced);
695
+ if (event) {
696
+ context.record(timelineEntries.trace(at, event));
697
+ }
698
+ const site = trace.job(traced);
699
+ if (site) {
700
+ shown.traced(site.job, site.started, at);
701
+ }
702
+ return;
703
+ }
704
+ context.record(timelineEntries.app(at, received.task, received.sequence, record));
705
+ if (record.kind !== "exception" || record.handled) {
706
+ return;
707
+ }
708
+ const job = manifest.jobs.find(({ name, instance }) => name === record.function && instance === record.instance);
709
+ if (job) {
710
+ shown.failed(job, {
711
+ at,
712
+ code: record.code,
713
+ ...record.name && { name: record.name },
714
+ source: record.source
715
+ });
716
+ }
717
+ };
718
+ const pull = async (path, since) => {
719
+ const url = new URL(path, server.url);
720
+ url.searchParams.set("since", String(since));
721
+ const response = await fetch(url, {
722
+ headers: { authorization: `Bearer ${server.token}` },
723
+ signal
724
+ });
725
+ if (!response.ok) {
726
+ throw new Error(`The server answered ${response.status}`);
727
+ }
728
+ return response.json();
729
+ };
730
+ const pullTelemetry = async () => {
731
+ const reply = telemetryReply.parse(await pull(telemetryPath, telemetry.since()));
732
+ for (const item of telemetry.accept(reply)) {
733
+ receive(item);
734
+ }
735
+ const build = telemetry.build();
736
+ if (build) {
737
+ context.setBuild(build);
738
+ }
739
+ if (reply.batches.length) {
740
+ context.sessionChanged();
741
+ }
742
+ };
743
+ const pullRequests = async () => {
744
+ const reply = requestsReply.parse(await pull(requestsPath, requests.since()));
745
+ requests.accept(reply, ({ request, entry, added }) => {
746
+ context.emit({ name: "request", data: request });
747
+ if (added) {
748
+ context.record(entry);
749
+ } else {
750
+ context.recordChange(entry);
751
+ }
752
+ const call = taggedCall(request);
753
+ if (!call) {
754
+ return;
755
+ }
756
+ const job = manifest.jobs.find(({ id }) => id === call.job);
757
+ if (job) {
758
+ shown.updateJob(job);
759
+ }
760
+ });
761
+ };
762
+ const repeat = async (name, work) => {
763
+ let failure;
764
+ while (!signal.aborted) {
765
+ try {
766
+ await work();
767
+ failure = undefined;
768
+ } catch (error) {
769
+ if (signal.aborted) {
770
+ return;
771
+ }
772
+ const message = errorMessage(error);
773
+ if (message !== failure) {
774
+ context.log(`${name} failed: ${message}`);
775
+ }
776
+ failure = message;
777
+ }
778
+ await sleep(pullMs, signal);
779
+ }
780
+ };
781
+ return Promise.all([
782
+ repeat("Reading the server's telemetry", pullTelemetry),
783
+ repeat("Reading the server's requests", pullRequests)
784
+ ]);
785
+ };
786
+
787
+ // packages/debug/src/explain-value.ts
788
+ import {
789
+ elementaryType,
790
+ isIntegerValued,
791
+ nanosecondsPerMillisecond as nanosecondsPerMillisecond2
792
+ } from "@tsplc/iec";
793
+
794
+ // packages/debug/src/constant.ts
795
+ import { nanosecondsPerMillisecond } from "@tsplc/iec";
796
+ var encodeConstant = (scalar) => {
797
+ switch (scalar.kind) {
798
+ case "integer":
799
+ return Number.isSafeInteger(Number(scalar.value)) ? Number(scalar.value) : String(scalar.value);
800
+ case "duration":
801
+ return `${scalar.nanoseconds / nanosecondsPerMillisecond}ms`;
802
+ }
803
+ };
804
+ var decodeConstant = (value) => {
805
+ if (typeof value === "number" && Number.isInteger(value)) {
806
+ return { kind: "integer", value: BigInt(value) };
807
+ }
808
+ if (typeof value !== "string") {
809
+ return;
810
+ }
811
+ if (/^-?\d+$/.test(value)) {
812
+ return { kind: "integer", value: BigInt(value) };
813
+ }
814
+ const milliseconds = /^(-?\d+)ms$/.exec(value)?.[1];
815
+ return milliseconds === undefined ? undefined : {
816
+ kind: "duration",
817
+ nanoseconds: BigInt(milliseconds) * nanosecondsPerMillisecond
818
+ };
819
+ };
820
+
821
+ // packages/debug/src/paths.ts
822
+ import { isWithin } from "@tsplc/iec/st";
823
+ import {
824
+ arrayIndex,
825
+ joinPath,
826
+ symbolPathSegments
827
+ } from "@tsplc/opcua/contract";
828
+ var anyIndex = "[*]";
829
+ class TooManyMatches extends RangeError {
830
+ constructor(limit) {
831
+ super(`More than ${limit} values match`);
832
+ }
833
+ }
834
+ var pathSegments = (path) => path.split(anyIndex).flatMap((part, index) => [
835
+ ...index > 0 ? [anyIndex] : [],
836
+ ...symbolPathSegments(part)
837
+ ]);
838
+ var typeOf = (manifest, id) => manifest.types[id] ?? { kind: "scalar", iec: id };
839
+ var createPaths = (manifest) => {
840
+ const typeOfId = (id) => typeOf(manifest, id);
841
+ const constants = new Map(manifest.constants.map(({ path, ...constant }) => [
842
+ path,
843
+ { kind: "constant", path, ...constant }
844
+ ]));
845
+ const roots = new Map(manifest.roots.map(({ path, ...root }) => [
846
+ path,
847
+ { kind: "target", path, ...root }
848
+ ]));
849
+ const walk = (bases, path) => {
850
+ const segments = pathSegments(path);
851
+ for (let length = segments.length;length > 0; length--) {
852
+ const base = bases.get(segments.slice(0, length).reduce(joinPath, ""));
853
+ if (!base) {
854
+ continue;
855
+ }
856
+ let resolved = base;
857
+ for (const segment of segments.slice(length)) {
858
+ const type = typeOfId(resolved.type);
859
+ if (type.kind === "record") {
860
+ const field = type.fields.find(({ name }) => name === segment);
861
+ if (!field) {
862
+ return;
863
+ }
864
+ resolved = {
865
+ kind: "target",
866
+ path: joinPath(resolved.path, segment),
867
+ target: `${resolved.target}.${field.target}`,
868
+ type: field.type,
869
+ readable: resolved.readable,
870
+ ...field.generated && { generated: true },
871
+ ...field.declaration && { declaration: field.declaration }
872
+ };
873
+ } else if (type.kind === "array") {
874
+ const index = arrayIndex(segment);
875
+ if (index === undefined || index < type.lower || index >= type.lower + type.length) {
876
+ return;
877
+ }
878
+ resolved = {
879
+ kind: "target",
880
+ path: joinPath(resolved.path, segment),
881
+ target: `${resolved.target}${segment}`,
882
+ type: type.element,
883
+ readable: resolved.readable,
884
+ ...resolved.declaration && { declaration: resolved.declaration }
885
+ };
886
+ } else {
887
+ return;
888
+ }
889
+ }
890
+ return resolved;
891
+ }
892
+ };
893
+ const bases = new Map([
894
+ ...roots,
895
+ ...manifest.io.map(({ path, target, type }) => {
896
+ const declared = walk(roots, path);
897
+ return [
898
+ path,
899
+ {
900
+ kind: "target",
901
+ path,
902
+ target,
903
+ type,
904
+ readable: true,
905
+ ...declared?.generated && { generated: true },
906
+ ...declared?.declaration && { declaration: declared.declaration }
907
+ }
908
+ ];
909
+ })
910
+ ]);
911
+ const groups = new Map;
912
+ for (const path of [...bases.keys(), ...constants.keys()]) {
913
+ let prefix = "";
914
+ for (const segment of pathSegments(path)) {
915
+ let children = groups.get(prefix);
916
+ if (!children) {
917
+ children = new Set;
918
+ groups.set(prefix, children);
919
+ }
920
+ children.add(segment);
921
+ prefix = joinPath(prefix, segment);
922
+ }
923
+ }
924
+ const resolve = (path) => constants.get(path) ?? walk(bases, path);
925
+ const typedChildren = (resolved) => {
926
+ const type = resolved?.kind === "target" ? typeOfId(resolved.type) : undefined;
927
+ if (type?.kind === "record") {
928
+ return type.fields.map(({ name }) => name);
929
+ }
930
+ if (type?.kind === "array") {
931
+ return Array.from({ length: type.length }, (_, index) => `[${type.lower + index}]`);
932
+ }
933
+ return [];
934
+ };
935
+ const children = (path) => {
936
+ const names = [
937
+ ...typedChildren(resolve(path)),
938
+ ...groups.get(path) ?? []
939
+ ];
940
+ return [...new Set(names)].map((name) => {
941
+ const child = joinPath(path, name);
942
+ return { name, ...resolve(child) ?? { kind: "group", path: child } };
943
+ });
944
+ };
945
+ const isLeaf = (node) => node.kind === "constant" || node.kind === "target" && ["scalar", "enum"].includes(typeOfId(node.type).kind);
946
+ const expand = (patterns, limit = 2000) => {
947
+ const leaves = new Set;
948
+ const add = (path) => {
949
+ leaves.add(path);
950
+ if (leaves.size > limit) {
951
+ throw new TooManyMatches(limit);
952
+ }
953
+ };
954
+ const below = (node) => {
955
+ if (isLeaf(node)) {
956
+ return add(node.path);
957
+ }
958
+ for (const child of children(node.path)) {
959
+ if (!(child.kind === "target" && child.generated)) {
960
+ below(child);
961
+ }
962
+ }
963
+ };
964
+ const match = (prefix, rest, wildcard) => {
965
+ const [head, ...tail] = rest;
966
+ if (head === undefined) {
967
+ const node = resolve(prefix) ?? (groups.has(prefix) ? { kind: "group", path: prefix } : undefined);
968
+ if (node) {
969
+ below(node);
970
+ } else if (!wildcard) {
971
+ add(prefix);
972
+ }
973
+ return;
974
+ }
975
+ if (head === "*" || head === anyIndex) {
976
+ for (const child of children(prefix)) {
977
+ if (!(child.kind === "target" && child.generated) && (head === "*" || child.name.startsWith("["))) {
978
+ match(child.path, tail, true);
979
+ }
980
+ }
981
+ } else {
982
+ match(joinPath(prefix, head), tail, wildcard);
983
+ }
984
+ };
985
+ for (const pattern of patterns) {
986
+ match("", pathSegments(pattern), false);
987
+ }
988
+ return [...leaves];
989
+ };
990
+ const decode = (typeId, raw) => {
991
+ const type = typeOfId(typeId);
992
+ if (type.kind === "enum") {
993
+ return Object.entries(type.members).find(([, value]) => value === raw)?.[0] ?? raw;
994
+ }
995
+ if (type.kind === "scalar" && type.iec === "BOOL" && typeof raw === "number") {
996
+ return raw !== 0;
997
+ }
998
+ return raw;
999
+ };
1000
+ const fromTarget = (expression) => {
1001
+ const upper = expression.trim().toUpperCase();
1002
+ const whole = targets.get(upper);
1003
+ if (whole) {
1004
+ return whole;
1005
+ }
1006
+ const root = manifest.roots.filter((item) => isWithin(item.target, upper)).sort((a, b) => b.target.length - a.target.length)[0];
1007
+ if (!root) {
1008
+ return;
1009
+ }
1010
+ let path = root.path;
1011
+ let type = root.type;
1012
+ for (const segment of pathSegments(expression.trim().slice(root.target.length).replace(/^\./, ""))) {
1013
+ const declared = typeOfId(type);
1014
+ if (segment.startsWith("[")) {
1015
+ if (declared.kind !== "array") {
1016
+ return;
1017
+ }
1018
+ path = joinPath(path, segment);
1019
+ type = declared.element;
1020
+ continue;
1021
+ }
1022
+ const field = declared.kind === "record" ? declared.fields.find((item) => item.target.toUpperCase() === segment.toUpperCase()) : undefined;
1023
+ if (!field) {
1024
+ return;
1025
+ }
1026
+ path = joinPath(path, field.name);
1027
+ type = field.type;
1028
+ }
1029
+ return path;
1030
+ };
1031
+ const targets = new Map([
1032
+ ...manifest.io.flatMap((io) => [
1033
+ [io.target.toUpperCase(), io.path],
1034
+ ...io.address ? [[io.address.toUpperCase(), io.path]] : []
1035
+ ]),
1036
+ ...manifest.roots.map((root) => [root.target.toUpperCase(), root.path])
1037
+ ]);
1038
+ return {
1039
+ typeOf: typeOfId,
1040
+ resolve,
1041
+ children,
1042
+ isLeaf,
1043
+ expand,
1044
+ decode,
1045
+ fromTarget
1046
+ };
1047
+ };
1048
+
1049
+ // packages/debug/src/explain-value.ts
1050
+ var unknown = (reason, estimate = []) => ({
1051
+ known: false,
1052
+ reason,
1053
+ estimate
1054
+ });
1055
+ var known = (value, estimate = []) => ({
1056
+ known: true,
1057
+ value,
1058
+ estimate
1059
+ });
1060
+ var withEstimate = (outcome, estimate) => estimate.length ? { ...outcome, estimate: [...new Set([...outcome.estimate, ...estimate])] } : outcome;
1061
+ var merge = (...lists) => [
1062
+ ...new Set(lists.flat())
1063
+ ];
1064
+ var and = (truths) => {
1065
+ if (truths.includes("false")) {
1066
+ return "false";
1067
+ }
1068
+ if (truths.includes("unknown")) {
1069
+ return "unknown";
1070
+ }
1071
+ return truths.includes("candidate") ? "candidate" : "true";
1072
+ };
1073
+ var fromConstant = (scalar) => ({
1074
+ kind: "integer",
1075
+ value: scalar.kind === "integer" ? scalar.value : scalar.nanoseconds
1076
+ });
1077
+ var sampleValue = (manifest, type, decoded) => {
1078
+ const declared = typeOf(manifest, type);
1079
+ if (declared.kind === "enum") {
1080
+ const member = typeof decoded === "string" ? declared.members[decoded] : undefined;
1081
+ if (typeof member === "number") {
1082
+ return { kind: "integer", value: BigInt(member) };
1083
+ }
1084
+ return typeof decoded === "number" || typeof decoded === "bigint" ? { kind: "integer", value: BigInt(decoded) } : undefined;
1085
+ }
1086
+ const scalar = declared.kind === "scalar" ? elementaryType(declared.iec) : undefined;
1087
+ const constant = decodeConstant(decoded);
1088
+ if (isIntegerValued(scalar)) {
1089
+ if (typeof decoded === "bigint") {
1090
+ return { kind: "integer", value: decoded };
1091
+ }
1092
+ return constant?.kind === "integer" ? fromConstant(constant) : undefined;
1093
+ }
1094
+ switch (scalar?.family) {
1095
+ case "bool":
1096
+ if (typeof decoded === "boolean") {
1097
+ return { kind: "bool", value: decoded };
1098
+ }
1099
+ return typeof decoded === "number" ? { kind: "bool", value: decoded !== 0 } : undefined;
1100
+ case "real":
1101
+ return typeof decoded === "number" ? { kind: "float", value: decoded } : undefined;
1102
+ case "duration":
1103
+ if (typeof decoded === "number") {
1104
+ return {
1105
+ kind: "integer",
1106
+ value: BigInt(Math.round(decoded * Number(nanosecondsPerMillisecond2)))
1107
+ };
1108
+ }
1109
+ return typeof decoded === "string" && constant?.kind === "duration" ? fromConstant(constant) : undefined;
1110
+ case "string":
1111
+ return typeof decoded === "string" ? { kind: "text", value: decoded } : undefined;
1112
+ default:
1113
+ return;
1114
+ }
1115
+ };
1116
+ var constantAggregate = (value) => {
1117
+ if (Array.isArray(value)) {
1118
+ return known({
1119
+ kind: "array",
1120
+ lower: 0,
1121
+ items: value.map((item) => constantAggregate(item))
1122
+ });
1123
+ }
1124
+ if (typeof value === "object" && value !== null) {
1125
+ return known({
1126
+ kind: "record",
1127
+ fields: Object.fromEntries(Object.entries(value).map(([name, item]) => [
1128
+ name,
1129
+ constantAggregate(item)
1130
+ ]))
1131
+ });
1132
+ }
1133
+ if (typeof value === "boolean") {
1134
+ return known({ kind: "bool", value });
1135
+ }
1136
+ if (typeof value !== "number" && typeof value !== "string") {
1137
+ return unknown("a constant this debugger can't show");
1138
+ }
1139
+ const constant = decodeConstant(value);
1140
+ if (constant) {
1141
+ return known(fromConstant(constant));
1142
+ }
1143
+ return known(typeof value === "number" ? { kind: "float", value } : { kind: "text", value });
1144
+ };
1145
+ var equalValues = (left, right) => {
1146
+ if (left.kind === "float" || right.kind === "float") {
1147
+ const leftNumber = left.kind === "float" || left.kind === "integer" ? Number(left.value) : Number.NaN;
1148
+ const rightNumber = right.kind === "float" || right.kind === "integer" ? Number(right.value) : Number.NaN;
1149
+ return Math.abs(leftNumber - rightNumber) <= Math.max(Math.abs(leftNumber), Math.abs(rightNumber)) * 0.000001 + 0.000000001;
1150
+ }
1151
+ if (left.kind === "bool" && right.kind === "bool") {
1152
+ return left.value === right.value;
1153
+ }
1154
+ if (left.kind === "integer" && right.kind === "integer") {
1155
+ return left.value === right.value;
1156
+ }
1157
+ if (left.kind === "text" && right.kind === "text") {
1158
+ return left.value === right.value;
1159
+ }
1160
+ if (left.kind === "instance" && right.kind === "instance") {
1161
+ return left.path === right.path;
1162
+ }
1163
+ return;
1164
+ };
1165
+
1166
+ // packages/debug/src/explain-frames.ts
1167
+ var compareOrder = (left, right) => {
1168
+ for (let index = 0;index < Math.min(left.length, right.length); index++) {
1169
+ const difference = (left[index] ?? 0) - (right[index] ?? 0);
1170
+ if (difference !== 0) {
1171
+ return difference;
1172
+ }
1173
+ }
1174
+ return left.length - right.length;
1175
+ };
1176
+ var frameKey = (frame) => `${frame.row}:${frame.caller ? `${frame.caller.call}@${frameKey(frame.caller.frame)}` : ""}:${[...frame.counters].join(",")}`;
1177
+ var callFrame = (row, call, position, frame) => ({
1178
+ row,
1179
+ caller: { call, frame },
1180
+ task: frame.task,
1181
+ order: [...frame.order, position],
1182
+ counters: new Map
1183
+ });
1184
+ var rootFrame = ({ file, tables }, chain) => {
1185
+ const start = {
1186
+ row: chain.entry,
1187
+ caller: null,
1188
+ task: chain.task,
1189
+ order: [tables.entries.get(chain.entry)?.order ?? 0],
1190
+ counters: new Map
1191
+ };
1192
+ return chain.calls.reduce((frame, call) => {
1193
+ const record = file.calls[call];
1194
+ const callee = record ? tables.calleesOf(record)[0]?.row : undefined;
1195
+ return callFrame(callee ?? frame.row, call, record?.position ?? 0, frame);
1196
+ }, start);
1197
+ };
1198
+ var calleeFrame = (evaluation, call, frame) => {
1199
+ const record = evaluation.file.calls[call];
1200
+ if (!record) {
1201
+ return unknown("a call that isn't traced");
1202
+ }
1203
+ const callees = evaluation.tables.calleesOf(record);
1204
+ if (record.receiver.kind === "pattern") {
1205
+ const indexes = record.receiver.indexes.map((item) => evaluation.expression(item, frame));
1206
+ const values = indexes.flatMap((item) => item.known && item.value.kind === "integer" ? [item.value.value] : []);
1207
+ if (values.length !== indexes.length) {
1208
+ return unknown("depends on which instance the call runs on", merge(...indexes.map((item) => item.estimate)));
1209
+ }
1210
+ const match = callees.find((callee) => callee.indexes.every((value, position) => value === values[position]));
1211
+ return match ? callFrame(match.row, call, record.position, frame) : unknown("an instance this build doesn't have");
1212
+ }
1213
+ const [only] = callees;
1214
+ return only && callees.length === 1 ? callFrame(only.row, call, record.position, frame) : unknown("a call this debugger can't follow");
1215
+ };
1216
+
1217
+ // packages/debug/src/explain-loops.ts
1218
+ import { loopIterations } from "@tsplc/iec/arithmetic";
1219
+ var maxLoopIterations = 64;
1220
+ var firstOf = (evaluation, loop, frame) => {
1221
+ const record = evaluation.file.loops[loop];
1222
+ return record ? evaluation.expression(record.first, frame) : unknown("a loop this debugger can't follow");
1223
+ };
1224
+ var executeLoop = (evaluation, loop, frame, watch) => {
1225
+ const { file, tables } = evaluation;
1226
+ const record = file.loops[loop];
1227
+ if (!record) {
1228
+ return {
1229
+ kind: "unknown",
1230
+ reason: "a loop this debugger can't follow",
1231
+ estimate: []
1232
+ };
1233
+ }
1234
+ if (record.parent !== null && !frame.counters.has(record.parent)) {
1235
+ return {
1236
+ kind: "unknown",
1237
+ reason: "a loop inside another loop",
1238
+ estimate: []
1239
+ };
1240
+ }
1241
+ const bounds = [record.first, record.limit, record.step].map((index) => evaluation.expression(index, frame));
1242
+ const estimate = merge(...bounds.map((item) => item.estimate));
1243
+ const missing = bounds.find((item) => !item.known);
1244
+ if (missing) {
1245
+ return { kind: "unknown", reason: missing.reason, estimate };
1246
+ }
1247
+ const [first, limit, step] = bounds.map((item) => item.known && item.value.kind === "integer" ? item.value.value : undefined);
1248
+ if (first === undefined || limit === undefined || step === undefined || step === 0n) {
1249
+ return {
1250
+ kind: "unknown",
1251
+ reason: "a loop this debugger can't follow",
1252
+ estimate
1253
+ };
1254
+ }
1255
+ const iterations = loopIterations(first, limit, record.exclusive, step);
1256
+ if (iterations > BigInt(Math.min(record.maxIterations, maxLoopIterations))) {
1257
+ return { kind: "unknown", reason: "loop too long", estimate };
1258
+ }
1259
+ const returns = file.returns.filter((item) => item.routine === frame.row && tables.conditionList(item.conditions).some((part) => part.kind === "loop" && tables.loopAt(frame.row, part.loop) === loop));
1260
+ let ran = null;
1261
+ const seen = [...estimate];
1262
+ for (let iteration = 0n;iteration < iterations; iteration++) {
1263
+ const inner = {
1264
+ ...frame,
1265
+ counters: new Map([...frame.counters, [loop, first + iteration * step]])
1266
+ };
1267
+ if (watch !== null) {
1268
+ const truth = watch(inner);
1269
+ seen.push(...truth.estimate);
1270
+ if (truth.truth === "true") {
1271
+ ran = inner;
1272
+ } else if (truth.truth !== "false") {
1273
+ return {
1274
+ kind: "unknown",
1275
+ reason: "depends on a condition inside the loop",
1276
+ estimate: merge(seen)
1277
+ };
1278
+ }
1279
+ }
1280
+ const breaks = record.breaks.map((all) => and(all.map((part) => evaluation.conditionTruth(part, inner).truth)));
1281
+ const returned = returns.map((item) => evaluation.conditionsTruth(item.conditions, inner).truth);
1282
+ const stops = [...breaks, ...returned];
1283
+ if (stops.includes("true")) {
1284
+ return {
1285
+ kind: "run",
1286
+ ran,
1287
+ returned: returned.includes("true"),
1288
+ estimate: merge(seen)
1289
+ };
1290
+ }
1291
+ if (stops.includes("unknown") || stops.includes("candidate")) {
1292
+ return {
1293
+ kind: "unknown",
1294
+ reason: "can't tell whether the loop stopped",
1295
+ estimate: merge(seen)
1296
+ };
1297
+ }
1298
+ }
1299
+ return { kind: "run", ran, returned: false, estimate: merge(seen) };
1300
+ };
1301
+
1302
+ // packages/debug/src/explain-operations.ts
1303
+ import { elementaryType as elementaryType2, isIntegerValued as isIntegerValued2 } from "@tsplc/iec";
1304
+ import {
1305
+ applyIntegerPolicy,
1306
+ compare,
1307
+ floatArithmetic,
1308
+ floatUnary,
1309
+ integerArithmetic,
1310
+ integerUnary,
1311
+ isElementary,
1312
+ roundFloat,
1313
+ saturateFloatToInteger
1314
+ } from "@tsplc/iec/arithmetic";
1315
+ var integerLayout = (type) => {
1316
+ const scalar = elementaryType2(type);
1317
+ return isIntegerValued2(scalar) ? { bits: scalar.bits, signed: scalar.signed } : undefined;
1318
+ };
1319
+ var floatLayout = (type) => {
1320
+ const scalar = elementaryType2(type);
1321
+ return scalar?.family === "real" ? { bits: scalar.bits } : undefined;
1322
+ };
1323
+ var typed = (value, type, policy = "wrap") => {
1324
+ const layout = integerLayout(type);
1325
+ return {
1326
+ kind: "integer",
1327
+ value: layout ? applyIntegerPolicy(value, layout, policy) : value
1328
+ };
1329
+ };
1330
+ var binary = (node, left, right) => {
1331
+ if (left.kind === "interval" || right.kind === "interval") {
1332
+ return intervalBinary(node, left, right);
1333
+ }
1334
+ if (left.kind === "instance" || right.kind === "instance") {
1335
+ const id = (value) => value.kind === "instance" ? { kind: "integer", value: value.id } : value;
1336
+ return binary(node, id(left), id(right));
1337
+ }
1338
+ if (left.kind === "bool" && right.kind === "bool") {
1339
+ const compared = compare(node.operator, Number(left.value), Number(right.value));
1340
+ return compared === undefined ? unknown("an operation this debugger can't evaluate") : known({ kind: "bool", value: compared });
1341
+ }
1342
+ if (left.kind === "integer" && right.kind === "integer") {
1343
+ const compared = compare(node.operator, left.value, right.value);
1344
+ if (compared !== undefined) {
1345
+ return known({ kind: "bool", value: compared });
1346
+ }
1347
+ const result = integerArithmetic(node.operator, left.value, right.value);
1348
+ if (result === undefined) {
1349
+ return unknown(right.value === 0n ? "a division by zero" : "an operation this debugger can't evaluate");
1350
+ }
1351
+ return known(typed(result, node.type, node.policy));
1352
+ }
1353
+ const leftNumber = left.kind === "float" || left.kind === "integer" ? Number(left.value) : undefined;
1354
+ const rightNumber = right.kind === "float" || right.kind === "integer" ? Number(right.value) : undefined;
1355
+ if (leftNumber === undefined || rightNumber === undefined) {
1356
+ if (left.kind === "text" && right.kind === "text") {
1357
+ const compared = compare(node.operator, left.value, right.value);
1358
+ return compared === undefined ? unknown("an operation on text") : known({ kind: "bool", value: compared });
1359
+ }
1360
+ return unknown("an operation this debugger can't evaluate");
1361
+ }
1362
+ const compared = compare(node.operator, leftNumber, rightNumber);
1363
+ if (compared !== undefined) {
1364
+ return known({ kind: "bool", value: compared }, [
1365
+ "a comparison of REAL values"
1366
+ ]);
1367
+ }
1368
+ const result = floatArithmetic(node.operator, leftNumber, rightNumber);
1369
+ const layout = floatLayout(node.type);
1370
+ return result === undefined ? unknown("an operation this debugger can't evaluate") : known({
1371
+ kind: "float",
1372
+ value: layout ? roundFloat(result, layout) : result
1373
+ });
1374
+ };
1375
+ var intervalBinary = (node, left, right) => {
1376
+ const ends = (value) => {
1377
+ if (value.kind === "interval") {
1378
+ return [value.low, value.high];
1379
+ }
1380
+ return value.kind === "integer" ? [value.value, value.value] : undefined;
1381
+ };
1382
+ const leftEnds = ends(left);
1383
+ const rightEnds = ends(right);
1384
+ if (!leftEnds || !rightEnds) {
1385
+ return unknown("an operation on the clock");
1386
+ }
1387
+ const low = binary(node, { kind: "integer", value: leftEnds[0] }, { kind: "integer", value: rightEnds[0] });
1388
+ const high = binary(node, { kind: "integer", value: leftEnds[1] }, { kind: "integer", value: rightEnds[1] });
1389
+ if (!low.known || !high.known) {
1390
+ return unknown("an operation on the clock");
1391
+ }
1392
+ if (low.value.kind === "bool" && high.value.kind === "bool") {
1393
+ return low.value.value === high.value.value ? known(low.value) : unknown("within one scan of the limit");
1394
+ }
1395
+ if (low.value.kind === "integer" && high.value.kind === "integer") {
1396
+ const monotonic = node.operator === "add" || node.operator === "subtract";
1397
+ const [from, to] = node.operator === "subtract" && right.kind === "interval" ? [high.value.value, low.value.value] : [low.value.value, high.value.value];
1398
+ return monotonic && from <= to ? known({ kind: "interval", low: from, high: to }) : unknown("within one scan of the clock");
1399
+ }
1400
+ return unknown("an operation on the clock");
1401
+ };
1402
+ var unary = (node, operand) => {
1403
+ if (node.operator === "not" && operand.kind === "bool") {
1404
+ return known({ kind: "bool", value: !operand.value });
1405
+ }
1406
+ if (operand.kind === "integer") {
1407
+ const result = integerUnary(node.operator, operand.value);
1408
+ if (result !== undefined) {
1409
+ return known(typed(result, node.type));
1410
+ }
1411
+ }
1412
+ if (operand.kind === "float") {
1413
+ const result = floatUnary(node.operator, operand.value);
1414
+ if (result === undefined) {
1415
+ return unknown("an operation this debugger can't evaluate");
1416
+ }
1417
+ if (node.operator === "truncate") {
1418
+ return known(typed(BigInt(result), node.type));
1419
+ }
1420
+ const layout = floatLayout(node.type);
1421
+ return known({
1422
+ kind: "float",
1423
+ value: layout && isElementary(node.operator) ? roundFloat(result, layout) : result
1424
+ });
1425
+ }
1426
+ return unknown("an operation this debugger can't evaluate");
1427
+ };
1428
+ var convert = (node, operand) => {
1429
+ const integer = integerLayout(node.type);
1430
+ const float = floatLayout(node.type);
1431
+ if (operand.kind === "integer" && integer) {
1432
+ return known({
1433
+ kind: "integer",
1434
+ value: node.policy === "exact" ? operand.value : applyIntegerPolicy(operand.value, integer, node.policy)
1435
+ });
1436
+ }
1437
+ if (operand.kind === "integer" && float) {
1438
+ return known({
1439
+ kind: "float",
1440
+ value: roundFloat(Number(operand.value), float)
1441
+ });
1442
+ }
1443
+ if (operand.kind === "float" && integer && node.policy === "saturate") {
1444
+ return known({
1445
+ kind: "integer",
1446
+ value: saturateFloatToInteger(operand.value, integer)
1447
+ });
1448
+ }
1449
+ if (operand.kind === "float" && float) {
1450
+ return known({
1451
+ kind: "float",
1452
+ value: roundFloat(operand.value, float)
1453
+ });
1454
+ }
1455
+ if (operand.kind === "interval" && integer) {
1456
+ return known(operand);
1457
+ }
1458
+ return node.policy === "exact" ? known(operand) : unknown("a conversion this debugger can't evaluate");
1459
+ };
1460
+
1461
+ // packages/debug/src/explain-expressions.ts
1462
+ var nodeBudget = 20000;
1463
+ var maxDepth = 400;
1464
+ var sampleOutcome = ({ manifest, tables, read, needs }, path, type) => {
1465
+ const flags = tables.flagsOf(path);
1466
+ if (flags.constantTable && flags.initial !== null) {
1467
+ const value = sampleValue(manifest, type, flags.initial);
1468
+ return value ? known(value) : unknown("a constant this debugger can't show");
1469
+ }
1470
+ const sample = read.sample(path);
1471
+ if (!sample) {
1472
+ needs.add(path);
1473
+ return unknown("reading");
1474
+ }
1475
+ if (sample.quality !== "good") {
1476
+ return unknown(`read ${sample.quality}`);
1477
+ }
1478
+ const value = sampleValue(manifest, type, sample.value);
1479
+ return value ? known(value) : unknown("a value this debugger can't evaluate");
1480
+ };
1481
+ var writtenAfter = ({ file, tables }, path, frame, at) => {
1482
+ const here = [...frame.order, at];
1483
+ return tables.writersOf(path).some((writer) => {
1484
+ const assignment = file.assignments[writer.assignment];
1485
+ return assignment !== undefined && writer.chains.some((chain) => chain.task === frame.task && compareOrder(tables.writeOrder(chain, assignment.position), here) > 0);
1486
+ });
1487
+ };
1488
+ var stored = (evaluation, path, type, capturedAt, frame, interleaved) => {
1489
+ const outcome = sampleOutcome(evaluation, path, type);
1490
+ const flags = evaluation.tables.flagsOf(path);
1491
+ const estimate = [
1492
+ ...flags.writerTasks.some((task) => task !== frame.task) ? ["also written by another task"] : [],
1493
+ ...writtenAfter(evaluation, path, frame, capturedAt) ? ["from the previous scan"] : [],
1494
+ ...interleaved && evaluation.tables.writersOf(path).length ? ["a call between its read and its use may have changed it"] : []
1495
+ ];
1496
+ return withEstimate(outcome, estimate);
1497
+ };
1498
+ var project = (outcome, path) => {
1499
+ const [first, ...rest] = path;
1500
+ if (first === undefined || !outcome.known) {
1501
+ return outcome;
1502
+ }
1503
+ const { value } = outcome;
1504
+ if (value.kind === "record") {
1505
+ const field = value.fields[first];
1506
+ return field ? project(withEstimate(field, outcome.estimate), rest) : unknown("a field this value lacks");
1507
+ }
1508
+ if (value.kind === "array") {
1509
+ const item = value.items[Number(first) - value.lower];
1510
+ return item ? project(withEstimate(item, outcome.estimate), rest) : unknown("an element this value lacks");
1511
+ }
1512
+ return unknown("a part of a scalar");
1513
+ };
1514
+ var clock = ({ read }, frame) => {
1515
+ const own = read.clock(frame.task);
1516
+ return own ? known({ kind: "interval", low: own.low, high: own.high }) : unknown("no PLC clock in this build");
1517
+ };
1518
+ var definitionsBefore = ({ file }, local, at) => (file.locals[local]?.definitions ?? []).filter((definition) => definition.position < at).sort((a, b) => b.position - a.position);
1519
+ var localValue = (evaluation, local, path, at, frame) => {
1520
+ const { file, tables } = evaluation;
1521
+ for (const [loop, value] of frame.counters) {
1522
+ if (tables.loopCounterLocal(loop) === local) {
1523
+ return known({ kind: "integer", value });
1524
+ }
1525
+ }
1526
+ for (const definition of file.locals[local]?.definitions ?? []) {
1527
+ const counter = definition.loop === null ? undefined : frame.counters.get(definition.loop);
1528
+ if (definition.position < at || definition.loop === null || counter === undefined) {
1529
+ continue;
1530
+ }
1531
+ const first = firstOf(evaluation, definition.loop, frame);
1532
+ if (!first.known) {
1533
+ return unknown(first.reason, first.estimate);
1534
+ }
1535
+ if (first.value.kind !== "integer" || counter !== first.value.value) {
1536
+ return unknown("changed inside this loop");
1537
+ }
1538
+ }
1539
+ for (const definition of definitionsBefore(evaluation, local, at)) {
1540
+ const prefix = definition.path.every((name, index) => path[index] === name);
1541
+ const part = !prefix && path.every((name, index) => definition.path[index] === name);
1542
+ if (!prefix && !part) {
1543
+ continue;
1544
+ }
1545
+ const truth = evaluation.conditionsTruth(definition.conditions, frame);
1546
+ if (truth.truth === "false") {
1547
+ continue;
1548
+ }
1549
+ const site = tables.siteText(definition.site);
1550
+ if (truth.truth !== "true") {
1551
+ return unknown(`depends on whether ${site} ran`, truth.estimate);
1552
+ }
1553
+ if (part) {
1554
+ return unknown(`partly set by ${site}`, truth.estimate);
1555
+ }
1556
+ if (definition.kind === "borrowed") {
1557
+ return unknown(`changed by the call ${site}`, truth.estimate);
1558
+ }
1559
+ if (definition.kind === "counter" || definition.value === null) {
1560
+ return unknown(`set by the loop ${site}`, truth.estimate);
1561
+ }
1562
+ return withEstimate(project(expression(evaluation, definition.value, frame), path.slice(definition.path.length)), truth.estimate);
1563
+ }
1564
+ return;
1565
+ };
1566
+ var callResult = (evaluation, call, frame) => {
1567
+ const inner = calleeFrame(evaluation, call, frame);
1568
+ if ("known" in inner) {
1569
+ return inner;
1570
+ }
1571
+ const returns = evaluation.file.returns.filter((item) => item.routine === inner.row).sort((a, b) => a.position - b.position);
1572
+ for (const returned of returns) {
1573
+ const truth = evaluation.conditionsTruth(returned.conditions, inner);
1574
+ if (truth.truth === "false") {
1575
+ continue;
1576
+ }
1577
+ if (truth.truth !== "true" || returned.value === null) {
1578
+ return unknown(`depends on whether ${evaluation.tables.siteText(returned.site)} returned`, truth.estimate);
1579
+ }
1580
+ return withEstimate(expression(evaluation, returned.value, inner), truth.estimate);
1581
+ }
1582
+ return unknown("returns nothing this debugger can follow");
1583
+ };
1584
+ var expression = (evaluation, index, frame) => {
1585
+ const { memo, budget } = evaluation;
1586
+ const key = `${index}|${frameKey(frame)}`;
1587
+ const cached = memo.get(key);
1588
+ if (cached) {
1589
+ return cached;
1590
+ }
1591
+ budget.spent += 1;
1592
+ if (budget.spent > nodeBudget || budget.depth >= maxDepth) {
1593
+ return unknown("too deep");
1594
+ }
1595
+ budget.depth += 1;
1596
+ try {
1597
+ const outcome = evaluate(evaluation, index, frame);
1598
+ memo.set(key, outcome);
1599
+ return outcome;
1600
+ } finally {
1601
+ budget.depth -= 1;
1602
+ }
1603
+ };
1604
+ var evaluate = (evaluation, index, frame) => {
1605
+ const { manifest, file, tables } = evaluation;
1606
+ const node = file.expressions[index];
1607
+ if (!node) {
1608
+ return unknown("not traced");
1609
+ }
1610
+ switch (node.kind) {
1611
+ case "read": {
1612
+ const path = tables.pathAt(frame.row, node.path);
1613
+ const bound = [...frame.counters].find(([loop]) => tables.loopCounterPath(loop) === path)?.[1];
1614
+ return bound === undefined ? stored(evaluation, path, node.type, node.capturedAt, frame, node.interleaved === true) : known({ kind: "integer", value: bound });
1615
+ }
1616
+ case "pattern": {
1617
+ const indexes = node.indexes.map((item) => expression(evaluation, item, frame));
1618
+ const estimate = merge(...indexes.map((item) => item.estimate));
1619
+ const missing = indexes.find((item) => !item.known);
1620
+ if (missing) {
1621
+ return unknown(missing.reason, estimate);
1622
+ }
1623
+ const values = indexes.flatMap((item) => item.known && item.value.kind === "integer" ? [item.value.value] : []);
1624
+ if (values.length !== indexes.length) {
1625
+ return unknown("an index this debugger can't evaluate", estimate);
1626
+ }
1627
+ const path = tables.pathAt(frame.row, node.path).split(anyIndex).reduce((built, part, position) => `${built}${position ? `[${values[position - 1]}]` : ""}${part}`, "");
1628
+ return withEstimate(stored(evaluation, path, node.type, node.capturedAt, frame, node.interleaved === true), estimate);
1629
+ }
1630
+ case "constant": {
1631
+ const value = sampleValue(manifest, node.type, node.value);
1632
+ return value ? known(value) : constantAggregate(node.value);
1633
+ }
1634
+ case "record":
1635
+ return known({
1636
+ kind: "record",
1637
+ fields: Object.fromEntries(Object.entries(node.fields).map(([name, field]) => [
1638
+ name,
1639
+ expression(evaluation, field, frame)
1640
+ ]))
1641
+ });
1642
+ case "array":
1643
+ return known({
1644
+ kind: "array",
1645
+ lower: node.lower,
1646
+ items: node.items.map((item) => expression(evaluation, item, frame))
1647
+ });
1648
+ case "local":
1649
+ return localValue(evaluation, tables.localAt(frame.row, node.local), node.path, node.at, frame) ?? unknown("no value before this point");
1650
+ case "parameter": {
1651
+ const own = node.local === null ? undefined : localValue(evaluation, tables.localAt(frame.row, node.local), node.path, node.at, frame);
1652
+ if (own) {
1653
+ return own;
1654
+ }
1655
+ const caller = frame.caller;
1656
+ const call = caller ? file.calls[caller.call] : undefined;
1657
+ const argument = call?.arguments[node.parameter];
1658
+ if (!caller || argument === undefined) {
1659
+ return unknown("depends on the call");
1660
+ }
1661
+ return project(expression(evaluation, argument, caller.frame), node.path);
1662
+ }
1663
+ case "call":
1664
+ return project(callResult(evaluation, tables.callAt(frame.row, node.call), frame), node.path);
1665
+ case "clock":
1666
+ return clock(evaluation, frame);
1667
+ case "reference": {
1668
+ const operand = expression(evaluation, node.operand, frame);
1669
+ if (!operand.known) {
1670
+ return operand;
1671
+ }
1672
+ if (operand.value.kind !== "integer") {
1673
+ return unknown("a reference this debugger can't follow", operand.estimate);
1674
+ }
1675
+ const id = operand.value.value;
1676
+ const path = id < 0n ? null : file.paths[file.references[String(id)] ?? -1];
1677
+ return known({ kind: "instance", id, path: path ?? null }, operand.estimate);
1678
+ }
1679
+ case "unary": {
1680
+ const operand = expression(evaluation, node.operand, frame);
1681
+ return operand.known ? withEstimate(unary(node, operand.value), operand.estimate) : operand;
1682
+ }
1683
+ case "convert": {
1684
+ const operand = expression(evaluation, node.operand, frame);
1685
+ return operand.known ? withEstimate(convert(node, operand.value), operand.estimate) : operand;
1686
+ }
1687
+ case "binary": {
1688
+ const left = expression(evaluation, node.left, frame);
1689
+ const right = expression(evaluation, node.right, frame);
1690
+ const estimate = merge(left.estimate, right.estimate);
1691
+ if (!left.known) {
1692
+ return withEstimate(left, right.estimate);
1693
+ }
1694
+ if (!right.known) {
1695
+ return withEstimate(right, left.estimate);
1696
+ }
1697
+ return withEstimate(binary(node, left.value, right.value), estimate);
1698
+ }
1699
+ case "logical": {
1700
+ const left = expression(evaluation, node.left, frame);
1701
+ const decided = node.operator === "or";
1702
+ if (left.known && left.value.kind === "bool" && left.value.value === decided) {
1703
+ return left;
1704
+ }
1705
+ const right = expression(evaluation, node.right, frame);
1706
+ if (right.known && right.value.kind === "bool" && right.value.value === decided) {
1707
+ return withEstimate(right, left.estimate);
1708
+ }
1709
+ if (!left.known) {
1710
+ return withEstimate(left, right.estimate);
1711
+ }
1712
+ return withEstimate(right, left.estimate);
1713
+ }
1714
+ case "select": {
1715
+ const condition = expression(evaluation, node.condition, frame);
1716
+ if (condition.known && condition.value.kind === "bool") {
1717
+ return withEstimate(expression(evaluation, condition.value.value ? node.then : node.else, frame), condition.estimate);
1718
+ }
1719
+ const then = expression(evaluation, node.then, frame);
1720
+ const otherwise = expression(evaluation, node.else, frame);
1721
+ if (then.known && otherwise.known && equalValues(then.value, otherwise.value)) {
1722
+ return withEstimate(then, merge(condition.estimate, otherwise.estimate));
1723
+ }
1724
+ return unknown(condition.known ? "a condition this debugger can't evaluate" : condition.reason, condition.estimate);
1725
+ }
1726
+ case "opaque":
1727
+ return unknown(`not traced: ${tables.text(node.text) ?? ""}`);
1728
+ }
1729
+ };
1730
+
1731
+ // packages/debug/src/explain-tables.ts
1732
+ import { arrayIndex as arrayIndex2, joinPath as joinPath2 } from "@tsplc/opcua/contract";
1733
+ var maxChains = 16;
1734
+ var matchPattern = (pattern, path) => {
1735
+ const segments = pathSegments(path);
1736
+ const indexes = [];
1737
+ for (const [position, part] of pattern.entries()) {
1738
+ const segment = segments[position];
1739
+ if (segment === undefined) {
1740
+ return;
1741
+ }
1742
+ if (part === anyIndex) {
1743
+ const index = arrayIndex2(segment);
1744
+ if (index === undefined) {
1745
+ return;
1746
+ }
1747
+ indexes.push(BigInt(index));
1748
+ } else if (part !== segment) {
1749
+ return;
1750
+ }
1751
+ }
1752
+ return { indexes, exact: segments.length === pattern.length };
1753
+ };
1754
+ var createExplainTables = (manifest, file) => {
1755
+ const text = (index) => index === null ? null : file.texts[index] ?? null;
1756
+ const siteText = (site) => {
1757
+ const found = site === null ? undefined : file.sites[site];
1758
+ const source = found ? text(found.text) : null;
1759
+ const sourceFile = found ? manifest.sources[found.range.file] : undefined;
1760
+ const where = found && sourceFile ? `${sourceFile.split("/").at(-1)}:${found.range.line}` : "";
1761
+ return [source, where && `at ${where}`].filter(Boolean).join(" ");
1762
+ };
1763
+ const byPath = new Map;
1764
+ const patterns = [];
1765
+ file.assignments.forEach((assignment, index) => {
1766
+ const written = file.paths[assignment.writes.path] ?? "";
1767
+ if (assignment.writes.kind === "pattern") {
1768
+ patterns.push({
1769
+ assignment: index,
1770
+ segments: pathSegments(written),
1771
+ whole: assignment.whole
1772
+ });
1773
+ return;
1774
+ }
1775
+ byPath.set(written, [...byPath.get(written) ?? [], index]);
1776
+ });
1777
+ const flagsByPath = new Map(file.flags.map((item) => [file.paths[item.path] ?? "", item]));
1778
+ const rowsByKey = new Map;
1779
+ file.routines.forEach((row, index) => {
1780
+ rowsByKey.set(row.key, [...rowsByKey.get(row.key) ?? [], index]);
1781
+ });
1782
+ const slots = (row) => file.routines[row];
1783
+ const pathAt = (row, slot) => file.paths[slots(row)?.paths[slot] ?? -1] ?? "";
1784
+ const localAt = (row, slot) => slots(row)?.locals[slot] ?? -1;
1785
+ const callAt = (row, slot) => slots(row)?.calls[slot] ?? -1;
1786
+ const loopAt = (row, slot) => slots(row)?.loops[slot] ?? -1;
1787
+ const loopSlot = (row, loop) => slots(row)?.loops.indexOf(loop) ?? -1;
1788
+ const instanceOf = (row) => {
1789
+ const instance = file.routines[row]?.instance;
1790
+ return instance === null || instance === undefined ? null : file.paths[instance] ?? null;
1791
+ };
1792
+ const calleesOf = (call) => {
1793
+ const rows = rowsByKey.get(call.callee) ?? [];
1794
+ const { receiver } = call;
1795
+ if (receiver.kind === "none") {
1796
+ return rows.filter((row) => instanceOf(row) === null).map((row) => ({ row, indexes: [] }));
1797
+ }
1798
+ const target = file.paths[receiver.path] ?? "";
1799
+ if (receiver.kind === "path") {
1800
+ return rows.filter((row) => instanceOf(row) === target).map((row) => ({ row, indexes: [] }));
1801
+ }
1802
+ const pattern = pathSegments(target);
1803
+ return rows.flatMap((row) => {
1804
+ const match = matchPattern(pattern, instanceOf(row) ?? "");
1805
+ return match?.exact ? [{ row, indexes: match.indexes }] : [];
1806
+ });
1807
+ };
1808
+ const callers = new Map;
1809
+ file.calls.forEach((call, index) => {
1810
+ for (const { row } of calleesOf(call)) {
1811
+ callers.set(row, [...callers.get(row) ?? [], index]);
1812
+ }
1813
+ });
1814
+ const entries = new Map(file.entries.map((entry) => [entry.routine, entry]));
1815
+ const chainsTo = (row) => {
1816
+ const found = [];
1817
+ const walk = (current, below, seen) => {
1818
+ if (found.length >= maxChains) {
1819
+ return;
1820
+ }
1821
+ const entry = entries.get(current);
1822
+ if (entry) {
1823
+ found.push({ task: entry.task, entry: current, calls: below });
1824
+ }
1825
+ for (const call of callers.get(current) ?? []) {
1826
+ const caller = file.calls[call]?.routine;
1827
+ if (caller !== undefined && !seen.has(caller)) {
1828
+ walk(caller, [call, ...below], new Set([...seen, caller]));
1829
+ }
1830
+ }
1831
+ };
1832
+ walk(row, [], new Set([row]));
1833
+ return found;
1834
+ };
1835
+ const chainCache = new Map;
1836
+ const chains = (row) => {
1837
+ const cached = chainCache.get(row);
1838
+ if (cached) {
1839
+ return cached;
1840
+ }
1841
+ const computed = chainsTo(row);
1842
+ chainCache.set(row, computed);
1843
+ return computed;
1844
+ };
1845
+ const writerChains = (assignment) => {
1846
+ const outermost = assignment.via.at(-1);
1847
+ if (outermost === undefined) {
1848
+ return chains(assignment.routine);
1849
+ }
1850
+ const passing = [...assignment.via].reverse();
1851
+ return chains(file.calls[outermost]?.routine ?? -1).map((chain) => ({
1852
+ ...chain,
1853
+ calls: [...chain.calls, ...passing]
1854
+ }));
1855
+ };
1856
+ const flagsOf = (path) => {
1857
+ const merged = {
1858
+ input: null,
1859
+ clientWritable: false,
1860
+ hmiControl: null,
1861
+ retained: false,
1862
+ constantTable: false,
1863
+ writerTasks: [],
1864
+ service: null,
1865
+ initial: null,
1866
+ reference: false
1867
+ };
1868
+ let prefix = "";
1869
+ for (const segment of pathSegments(path)) {
1870
+ prefix = joinPath2(prefix, segment);
1871
+ const item = flagsByPath.get(prefix);
1872
+ if (!item) {
1873
+ continue;
1874
+ }
1875
+ merged.input ??= item.input;
1876
+ merged.clientWritable ||= item.clientWritable;
1877
+ merged.hmiControl ??= item.hmiControl;
1878
+ merged.retained ||= item.retained;
1879
+ merged.constantTable ||= item.constantTable;
1880
+ merged.writerTasks = merge(merged.writerTasks, item.writerTasks);
1881
+ merged.service ??= item.service;
1882
+ merged.reference ||= item.reference;
1883
+ if (prefix === path) {
1884
+ merged.initial = item.initial;
1885
+ }
1886
+ }
1887
+ return merged;
1888
+ };
1889
+ const writersOf = (path) => {
1890
+ const found = [];
1891
+ const segments = pathSegments(path);
1892
+ let prefix = "";
1893
+ for (const [position, segment] of segments.entries()) {
1894
+ prefix = joinPath2(prefix, segment);
1895
+ const last = position === segments.length - 1;
1896
+ for (const assignment of byPath.get(prefix) ?? []) {
1897
+ if (last || file.assignments[assignment]?.whole) {
1898
+ found.push({ assignment, indexes: [] });
1899
+ }
1900
+ }
1901
+ }
1902
+ for (const pattern of patterns) {
1903
+ const match = matchPattern(pattern.segments, path);
1904
+ if (match && (match.exact || pattern.whole)) {
1905
+ found.push({ assignment: pattern.assignment, indexes: match.indexes });
1906
+ }
1907
+ }
1908
+ return found.map((item) => {
1909
+ const assignment = file.assignments[item.assignment];
1910
+ return {
1911
+ ...item,
1912
+ chains: assignment ? writerChains(assignment) : []
1913
+ };
1914
+ });
1915
+ };
1916
+ const writeOrder = (chain, position) => [
1917
+ entries.get(chain.entry)?.order ?? 0,
1918
+ ...chain.calls.map((call) => file.calls[call]?.position ?? 0),
1919
+ position
1920
+ ];
1921
+ const conditionList = (entry) => {
1922
+ const list = [];
1923
+ for (let current = entry;current !== null; current = file.conditions[current]?.parent ?? null) {
1924
+ const item = file.conditions[current];
1925
+ if (item) {
1926
+ list.unshift(item.condition);
1927
+ }
1928
+ }
1929
+ return list;
1930
+ };
1931
+ const counterNode = (loop) => {
1932
+ const record = file.loops[loop];
1933
+ const node = record ? file.expressions[record.counter] : undefined;
1934
+ return record && node && { routine: record.routine, node };
1935
+ };
1936
+ const loopCounterLocal = (loop) => {
1937
+ const counter = counterNode(loop);
1938
+ return counter?.node.kind === "local" ? localAt(counter.routine, counter.node.local) : undefined;
1939
+ };
1940
+ const loopCounterPath = (loop) => {
1941
+ const counter = counterNode(loop);
1942
+ return counter?.node.kind === "read" ? pathAt(counter.routine, counter.node.path) : undefined;
1943
+ };
1944
+ return {
1945
+ text,
1946
+ siteText,
1947
+ slots,
1948
+ pathAt,
1949
+ localAt,
1950
+ callAt,
1951
+ loopAt,
1952
+ loopSlot,
1953
+ calleesOf,
1954
+ entries,
1955
+ flagsOf,
1956
+ writersOf,
1957
+ writeOrder,
1958
+ conditionList,
1959
+ loopCounterLocal,
1960
+ loopCounterPath,
1961
+ explain: (path) => ({
1962
+ path,
1963
+ writers: writersOf(path),
1964
+ flags: flagsOf(path),
1965
+ io: manifest.io.find((item) => item.path === path) ?? null
1966
+ })
1967
+ };
1968
+ };
1969
+
1970
+ // packages/debug/src/explain-verdicts.ts
1971
+ var jobTruth = ({ manifest, read }, job, step, result) => {
1972
+ const state = read.job(job);
1973
+ const declared = manifest.jobs.find((item) => item.id === job);
1974
+ const steps = declared?.steps ?? [];
1975
+ const stepText = steps.find((item) => item.step === step)?.text ?? `step ${step}`;
1976
+ if (!state || state.busy === null) {
1977
+ return result("unknown", ["the job's state isn't known"]);
1978
+ }
1979
+ if (state.unread) {
1980
+ return result("unknown", ["over the jobs read per poll"]);
1981
+ }
1982
+ const current = steps.find((item) => item.step === state.step);
1983
+ const cancelling = state.cancelling ? ["the job is being cancelled"] : [];
1984
+ if (state.busy && state.step === step && current?.kind === "await") {
1985
+ return result("true", [`waiting at ${stepText}`], ["a job's step can change between scans", ...cancelling]);
1986
+ }
1987
+ return result("candidate", [
1988
+ `ran when job ${declared?.name ?? `job ${job}`} passed ${stepText}, this scan or earlier`
1989
+ ], cancelling);
1990
+ };
1991
+ var conditionTruth = (evaluation, condition, frame) => {
1992
+ const { tables, read } = evaluation;
1993
+ const result = (truth, reasons = [], estimate = []) => ({
1994
+ condition,
1995
+ row: frame.row,
1996
+ truth,
1997
+ reasons,
1998
+ estimate
1999
+ });
2000
+ switch (condition.kind) {
2001
+ case "test": {
2002
+ const outcome = evaluation.expression(condition.test, frame);
2003
+ if (!outcome.known) {
2004
+ return result("unknown", [outcome.reason], outcome.estimate);
2005
+ }
2006
+ if (outcome.value.kind !== "bool") {
2007
+ return result("unknown", ["a condition this debugger can't evaluate"], outcome.estimate);
2008
+ }
2009
+ return result(outcome.value.value === condition.holds ? "true" : "false", [], outcome.estimate);
2010
+ }
2011
+ case "cases": {
2012
+ const outcome = evaluation.expression(condition.test, frame);
2013
+ if (!outcome.known) {
2014
+ return result("unknown", [outcome.reason], outcome.estimate);
2015
+ }
2016
+ const member = condition.values.some((value) => {
2017
+ const constant = constantAggregate(value);
2018
+ return constant.known && equalValues(constant.value, outcome.value) === true;
2019
+ });
2020
+ return result(member === condition.member ? "true" : "false", [], outcome.estimate);
2021
+ }
2022
+ case "exits": {
2023
+ const parts = condition.any.map((all) => all.map((part) => conditionTruth(evaluation, part, frame)));
2024
+ const any = parts.map((all) => and(all.map((part) => part.truth)));
2025
+ const estimate = merge(...parts.flat().map((part) => part.estimate));
2026
+ if (any.includes("true")) {
2027
+ return result("false", [], estimate);
2028
+ }
2029
+ if (any.includes("unknown") || any.includes("candidate")) {
2030
+ return result("unknown", ["depends on whether an earlier statement left"], estimate);
2031
+ }
2032
+ return result("true", [], estimate);
2033
+ }
2034
+ case "loop":
2035
+ return frame.counters.has(tables.loopAt(frame.row, condition.loop)) ? result("true") : result("unknown", ["inside a loop"]);
2036
+ case "loopReturns": {
2037
+ const run = executeLoop(evaluation, tables.loopAt(frame.row, condition.loop), frame, null);
2038
+ if (run.kind === "unknown") {
2039
+ return result("unknown", [run.reason], run.estimate);
2040
+ }
2041
+ return result(run.returned ? "false" : "true", [], run.estimate);
2042
+ }
2043
+ case "job":
2044
+ return jobTruth(evaluation, tables.slots(frame.row)?.job ?? -1, condition.step, result);
2045
+ case "jobBusy": {
2046
+ const state = read.job(tables.slots(frame.row)?.job ?? -1);
2047
+ if (!state || state.busy === null) {
2048
+ return result("unknown", ["the job's state isn't known"]);
2049
+ }
2050
+ return state.busy ? result("true", [], ["the job may have moved on since"]) : result("candidate", ["the job isn't running now"]);
2051
+ }
2052
+ }
2053
+ };
2054
+ var conditionsTruth = (evaluation, entry, frame) => {
2055
+ const results = evaluation.tables.conditionList(entry).map((condition) => conditionTruth(evaluation, condition, frame));
2056
+ return {
2057
+ truth: and(results.map((item) => item.truth)),
2058
+ results,
2059
+ estimate: merge(...results.map((item) => item.estimate))
2060
+ };
2061
+ };
2062
+ var indexTruth = (outcome, wanted) => {
2063
+ if (!outcome.known) {
2064
+ return "unknown";
2065
+ }
2066
+ return outcome.value.kind === "integer" && outcome.value.value === wanted ? "true" : "false";
2067
+ };
2068
+ var loopResult = (run) => {
2069
+ if (run.kind === "unknown") {
2070
+ return { truth: "unknown", reasons: [run.reason] };
2071
+ }
2072
+ return run.ran ? { truth: "true", reasons: [] } : { truth: "false", reasons: ["no iteration ran it"] };
2073
+ };
2074
+ var states = {
2075
+ true: "runs",
2076
+ false: "blocked",
2077
+ unknown: "unknown",
2078
+ candidate: "candidate"
2079
+ };
2080
+ var verdict = (evaluation, writer, chain) => {
2081
+ const { file, tables } = evaluation;
2082
+ const assignment = file.assignments[writer.assignment];
2083
+ if (!assignment) {
2084
+ return {
2085
+ writer,
2086
+ chain,
2087
+ state: "unknown",
2088
+ reasons: ["not traced"],
2089
+ estimate: [],
2090
+ conditions: [],
2091
+ value: null
2092
+ };
2093
+ }
2094
+ const results = [];
2095
+ let frame = rootFrame(evaluation, { ...chain, calls: [] });
2096
+ const reasons = [];
2097
+ for (const call of chain.calls) {
2098
+ const record = file.calls[call];
2099
+ if (!record) {
2100
+ continue;
2101
+ }
2102
+ if (record.loop !== null) {
2103
+ reasons.push("called inside a loop");
2104
+ results.push({
2105
+ condition: {
2106
+ kind: "loop",
2107
+ loop: tables.loopSlot(frame.row, record.loop)
2108
+ },
2109
+ row: frame.row,
2110
+ truth: "unknown",
2111
+ reasons: ["called inside a loop"],
2112
+ estimate: []
2113
+ });
2114
+ } else {
2115
+ results.push(...conditionsTruth(evaluation, record.conditions, frame).results);
2116
+ }
2117
+ const next = calleeFrame(evaluation, call, frame);
2118
+ if ("known" in next) {
2119
+ return {
2120
+ writer,
2121
+ chain,
2122
+ state: "unknown",
2123
+ reasons: [next.reason],
2124
+ estimate: [...next.estimate],
2125
+ conditions: results,
2126
+ value: null
2127
+ };
2128
+ }
2129
+ frame = next;
2130
+ }
2131
+ const namingFrame = (inner) => assignment.via.reduce((frame) => frame.caller?.frame ?? frame, inner);
2132
+ const indexMatch = (inner) => assignment.writes.kind === "pattern" ? assignment.writes.indexes.map((index, position) => {
2133
+ const outcome = evaluation.expression(index, namingFrame(inner));
2134
+ return {
2135
+ condition: {
2136
+ kind: "test",
2137
+ test: index,
2138
+ holds: true,
2139
+ at: assignment.position,
2140
+ text: null
2141
+ },
2142
+ row: namingFrame(inner).row,
2143
+ truth: indexTruth(outcome, writer.indexes[position]),
2144
+ reasons: outcome.known ? [] : [outcome.reason],
2145
+ estimate: outcome.estimate
2146
+ };
2147
+ }) : [];
2148
+ const reaches = (inner) => {
2149
+ const own = conditionsTruth(evaluation, assignment.conditions, inner);
2150
+ const matched = indexMatch(inner);
2151
+ return {
2152
+ truth: and([own.truth, ...matched.map((item) => item.truth)]),
2153
+ estimate: merge(own.estimate, ...matched.map((item) => item.estimate)),
2154
+ results: [...own.results, ...matched]
2155
+ };
2156
+ };
2157
+ if (assignment.loop !== null) {
2158
+ const run = executeLoop(evaluation, assignment.loop, frame, reaches);
2159
+ results.push({
2160
+ condition: {
2161
+ kind: "loop",
2162
+ loop: tables.loopSlot(frame.row, assignment.loop)
2163
+ },
2164
+ row: frame.row,
2165
+ ...loopResult(run),
2166
+ estimate: run.estimate
2167
+ });
2168
+ if (run.kind === "run" && run.ran) {
2169
+ frame = run.ran;
2170
+ }
2171
+ } else {
2172
+ results.push(...reaches(frame).results);
2173
+ }
2174
+ const truth = and(results.map((item) => item.truth));
2175
+ return {
2176
+ writer,
2177
+ chain,
2178
+ state: states[truth],
2179
+ reasons: [
2180
+ ...reasons,
2181
+ ...results.filter((item) => item.truth === truth && truth !== "true").flatMap((item) => item.reasons)
2182
+ ],
2183
+ estimate: merge(...results.map((item) => item.estimate)),
2184
+ conditions: results,
2185
+ value: truth === "true" && assignment.value !== null ? evaluation.expression(assignment.value, frame) : null
2186
+ };
2187
+ };
2188
+ var answer = (evaluation, explanation, type) => {
2189
+ const { manifest, file, tables, read, needs } = evaluation;
2190
+ const current = sampleOutcome(evaluation, explanation.path, type);
2191
+ const verdicts = explanation.writers.flatMap((writer) => writer.chains.length ? writer.chains.map((chain) => verdict(evaluation, writer, chain)) : [
2192
+ {
2193
+ writer,
2194
+ chain: { task: "", entry: -1, calls: [] },
2195
+ state: "blocked",
2196
+ reasons: ["no task reaches it"],
2197
+ estimate: [],
2198
+ conditions: [],
2199
+ value: null
2200
+ }
2201
+ ]);
2202
+ const slot = read.slot(explanation.path);
2203
+ const slotted = verdicts.filter((item) => slot?.assignments?.includes(item.writer.assignment));
2204
+ const result = (answer) => ({
2205
+ answer,
2206
+ verdicts,
2207
+ clientWritable: explanation.flags.clientWritable,
2208
+ hmiControl: explanation.flags.hmiControl,
2209
+ retained: explanation.flags.retained,
2210
+ writerTasks: explanation.flags.writerTasks,
2211
+ needs: [...needs],
2212
+ hint: slot && !slot.exact ? slotted : []
2213
+ });
2214
+ if (read.forced?.has(explanation.path)) {
2215
+ return result({ kind: "forced", value: current });
2216
+ }
2217
+ if (slot?.exact) {
2218
+ return result({
2219
+ kind: "exact",
2220
+ writer: slot.assignments === null ? null : slotted.find((item) => item.state === "runs") ?? slotted[0] ?? null
2221
+ });
2222
+ }
2223
+ if (explanation.io?.direction === "input") {
2224
+ return result({ kind: "input", io: explanation.io, value: current });
2225
+ }
2226
+ const orderOf = (item) => tables.writeOrder(item.chain, file.assignments[item.writer.assignment]?.position ?? 0);
2227
+ const ordered = [...verdicts].sort((a, b) => compareOrder(orderOf(a), orderOf(b)));
2228
+ const consistent = (item) => {
2229
+ if (!item.value?.known || item.value.estimate.length || !current.known) {
2230
+ return true;
2231
+ }
2232
+ return equalValues(item.value.value, current.value) !== false;
2233
+ };
2234
+ const running = ordered.filter((item) => item.state === "runs");
2235
+ const excluded = running.filter((item) => !consistent(item));
2236
+ const candidates = running.filter((item) => consistent(item));
2237
+ const last = candidates.at(-1);
2238
+ if (last) {
2239
+ const tasks = new Set(running.map((item) => item.chain.task));
2240
+ const later = ordered.slice(ordered.indexOf(last) + 1).filter((item) => item.state === "unknown" || item.state === "candidate" || item.state === "runs" && item.chain.task !== last.chain.task);
2241
+ const others = tasks.size > 1 ? running.filter((item) => item !== last && item.chain.task !== last.chain.task) : [];
2242
+ const unless = [...new Set([...later, ...others])];
2243
+ return result({
2244
+ kind: "set",
2245
+ writer: last,
2246
+ unless,
2247
+ estimate: merge(last.estimate, unless.length ? ["another writer may have run after it"] : [], excluded.some((item) => ordered.indexOf(item) > ordered.indexOf(last)) ? ["a later writer's value didn't match"] : [])
2248
+ });
2249
+ }
2250
+ if (excluded.length) {
2251
+ return result({ kind: "changed", writers: excluded });
2252
+ }
2253
+ if (verdicts.every((item) => item.state === "blocked" || item.state === "candidate")) {
2254
+ const could = verdicts.filter((item) => {
2255
+ const assignment = file.assignments[item.writer.assignment];
2256
+ const constant = assignment?.value === null || assignment?.value === undefined ? undefined : file.expressions[assignment.value];
2257
+ if (constant?.kind !== "constant" || !current.known) {
2258
+ return true;
2259
+ }
2260
+ const value = sampleValue(manifest, constant.type, constant.value);
2261
+ return !value || equalValues(value, current.value) !== false;
2262
+ });
2263
+ const jobs = verdicts.filter((item) => item.state === "candidate");
2264
+ return result({
2265
+ kind: "held",
2266
+ writers: could,
2267
+ estimate: jobs.length ? ["set by a job step, this scan or earlier"] : []
2268
+ });
2269
+ }
2270
+ const open = verdicts.filter((item) => item.state === "unknown");
2271
+ return result({
2272
+ kind: "unknown",
2273
+ writers: open,
2274
+ reasons: merge(...open.map((item) => item.reasons))
2275
+ });
2276
+ };
2277
+
2278
+ // packages/debug/src/explain.ts
2279
+ var createExplainer = (manifest, file) => {
2280
+ const tables = createExplainTables(manifest, file);
2281
+ const evaluation = (read) => {
2282
+ const context = {
2283
+ manifest,
2284
+ file,
2285
+ tables,
2286
+ read,
2287
+ needs: new Set,
2288
+ memo: new Map,
2289
+ budget: { spent: 0, depth: 0 },
2290
+ expression: (index, frame) => expression(context, index, frame),
2291
+ conditionTruth: (condition, frame) => conditionTruth(context, condition, frame),
2292
+ conditionsTruth: (entry, frame) => conditionsTruth(context, entry, frame)
2293
+ };
2294
+ return context;
2295
+ };
2296
+ return {
2297
+ explain: tables.explain,
2298
+ answer: (explanation, type, read) => answer(evaluation(read), explanation, type),
2299
+ evaluate: (index, chain, read, row) => {
2300
+ const run = evaluation(read);
2301
+ const frames = chain.calls.map((_, depth) => rootFrame(run, { ...chain, calls: chain.calls.slice(0, depth + 1) }));
2302
+ const frame = [rootFrame(run, { ...chain, calls: [] }), ...frames].reverse().find((item) => item.row === row) ?? rootFrame(run, chain);
2303
+ return expression(run, index, frame);
2304
+ },
2305
+ pathAt: tables.pathAt,
2306
+ file
2307
+ };
2308
+ };
2309
+
2310
+ // packages/debug/src/hardware.ts
2311
+ var faultyState = /error|fault|fail|timeout|lost|closed/i;
2312
+ var healthReads = (device) => {
2313
+ const { state, states, diagnostic, message } = device.health ?? {};
2314
+ return [
2315
+ ...state ? [
2316
+ {
2317
+ target: state,
2318
+ type: {
2319
+ kind: "enum",
2320
+ name: "state",
2321
+ members: states ?? {}
2322
+ }
2323
+ }
2324
+ ] : [],
2325
+ ...diagnostic ? [scalarRead(diagnostic, "BOOL")] : [],
2326
+ ...message ? [scalarRead(message, "STRING")] : []
2327
+ ];
2328
+ };
2329
+ var deviceReads = (device, io, typeOf) => [
2330
+ ...healthReads(device),
2331
+ ...device.assemblies.flatMap(({ raw, bytes }) => raw ? [
2332
+ {
2333
+ target: raw,
2334
+ type: {
2335
+ kind: "array",
2336
+ element: "BYTE",
2337
+ length: bytes,
2338
+ lower: 0
2339
+ }
2340
+ }
2341
+ ] : []),
2342
+ ...io.filter((binding) => binding.device === device.id).map(({ target, type }) => ({ target, type: typeOf(type) })),
2343
+ ...Object.values(device.status ?? {}).map((target) => scalarRead(target, "ANY"))
2344
+ ];
2345
+ var healthState = (quality, faulted) => {
2346
+ if (quality !== "good") {
2347
+ return "stale";
2348
+ }
2349
+ return faulted ? "fault" : "ok";
2350
+ };
2351
+ var health = (device, value) => {
2352
+ const { state, states, diagnostic, message } = device.health ?? {};
2353
+ if (!state && !diagnostic) {
2354
+ return { state: "unknown", quality: "unavailable" };
2355
+ }
2356
+ const stateSample = state ? value(state) : undefined;
2357
+ const diagnosticSample = diagnostic ? value(diagnostic) : undefined;
2358
+ const messageSample = message ? value(message) : undefined;
2359
+ const quality = worstQuality([
2360
+ ...state ? [stateSample] : [],
2361
+ ...diagnostic ? [diagnosticSample] : []
2362
+ ]);
2363
+ const number = typeof stateSample?.value === "number" ? stateSample.value : undefined;
2364
+ const name = Object.entries(states ?? {}).find(([, member]) => member === number)?.[0] ?? (typeof stateSample?.value === "string" ? stateSample.value : undefined);
2365
+ const faulted = diagnosticSample?.value === true || name !== undefined && faultyState.test(name);
2366
+ return {
2367
+ state: healthState(quality, faulted),
2368
+ ...number !== undefined && { value: number },
2369
+ ...name && { name },
2370
+ ...typeof diagnosticSample?.value === "boolean" && {
2371
+ diagnostic: diagnosticSample.value
2372
+ },
2373
+ ...typeof messageSample?.value === "string" && {
2374
+ message: messageSample.value
2375
+ },
2376
+ quality
2377
+ };
2378
+ };
2379
+ var reading = (sample) => ({
2380
+ value: sample?.value ?? null,
2381
+ quality: sample?.quality ?? "unavailable"
2382
+ });
2383
+ var deviceState = (device, io, value) => ({
2384
+ id: device.id,
2385
+ health: health(device, value),
2386
+ assemblies: device.assemblies.map(({ direction, address, raw }) => {
2387
+ const sample = raw ? value(raw) : undefined;
2388
+ return {
2389
+ direction,
2390
+ ...address && { address },
2391
+ bytes: Array.isArray(sample?.value) && sample.value.every((byte) => typeof byte === "number") ? sample.value : null,
2392
+ quality: sample?.quality ?? "unavailable"
2393
+ };
2394
+ }),
2395
+ channels: io.flatMap((binding) => binding.device === device.id && binding.channel ? [
2396
+ {
2397
+ id: binding.channel,
2398
+ path: binding.path,
2399
+ ...reading(value(binding.target))
2400
+ }
2401
+ ] : []),
2402
+ status: Object.fromEntries(Object.entries(device.status ?? {}).map(([label, target]) => [
2403
+ label,
2404
+ reading(value(target))
2405
+ ]))
2406
+ });
2407
+
2408
+ // packages/debug/src/jobs.ts
2409
+ var stateRead = (job, field) => scalarRead(`${job.target}.${field}`, jobStateFields[field]);
2410
+ var busyRead = (job) => stateRead(job, "busy");
2411
+ var detailReads = (job) => [
2412
+ stateRead(job, "step"),
2413
+ stateRead(job, "cancelling"),
2414
+ ...job.startedAt ? [scalarRead(job.startedAt, instrumentationFields.startedAt)] : [],
2415
+ ...job.requests.map(({ sequence }) => scalarRead(sequence, instrumentationFields.sequence))
2416
+ ];
2417
+ var busyFrom = (read, traced) => read?.quality === "good" ? read.value === true : traced?.busy ?? null;
2418
+ var busyOf = (job, value, traced) => busyFrom(value(busyRead(job).target), traced);
2419
+ var numberOf = (sample) => sample?.quality === "good" && typeof sample.value === "number" ? sample.value : undefined;
2420
+ var jobState = (job, inputs) => {
2421
+ const { value, traced, clock, now } = inputs;
2422
+ const busySample = value(busyRead(job).target);
2423
+ const busy = busyFrom(busySample, traced);
2424
+ const startedPlc = job.startedAt === undefined ? undefined : numberOf(value(job.startedAt));
2425
+ const startedAt = traced?.startedAt ?? (clock && startedPlc !== undefined ? new Date(startedPlc - clock.offsetMs).toISOString() : undefined);
2426
+ const base = {
2427
+ id: job.id,
2428
+ quality: busySample?.quality ?? (traced ? "good" : "unavailable"),
2429
+ busy,
2430
+ ...startedAt && { startedAt },
2431
+ ...inputs.failure && { failure: inputs.failure }
2432
+ };
2433
+ if (!busy) {
2434
+ return base;
2435
+ }
2436
+ if (inputs.unread) {
2437
+ return { ...base, unread: true };
2438
+ }
2439
+ const step = numberOf(value(stateRead(job, "step").target));
2440
+ const current = job.steps.find((candidate) => candidate.step === step);
2441
+ const calls = job.requests.map((call) => {
2442
+ const sequence = numberOf(value(call.sequence)) ?? 0;
2443
+ const trace = inputs.request({
2444
+ job: call.job ?? job.id,
2445
+ service: call.service,
2446
+ sequence
2447
+ });
2448
+ return { service: call.service, sequence, trace };
2449
+ }).filter(({ sequence }) => sequence > 0);
2450
+ const later = (call, than) => call.trace && than.trace ? call.trace.startedAt > than.trace.startedAt : call.sequence > than.sequence;
2451
+ const latest = calls.reduce((latest, call) => latest && !later(call, latest) ? latest : call, undefined);
2452
+ const cancelling = value(stateRead(job, "cancelling").target);
2453
+ return {
2454
+ ...base,
2455
+ ...cancelling?.quality === "good" && {
2456
+ cancelling: cancelling.value === true
2457
+ },
2458
+ ...step !== undefined && { step },
2459
+ ...current && {
2460
+ current: { kind: current.kind, range: current.range, text: current.text }
2461
+ },
2462
+ ...startedAt && { elapsedMs: Math.max(0, now - Date.parse(startedAt)) },
2463
+ ...latest && {
2464
+ request: {
2465
+ service: latest.service,
2466
+ sequence: latest.sequence,
2467
+ ...latest.trace && { trace: latest.trace }
2468
+ }
2469
+ }
2470
+ };
2471
+ };
2472
+
2473
+ // packages/debug/src/shown.ts
2474
+ var hardwareMs = 5000;
2475
+ var detailedJobs = 16;
2476
+ var countShown = () => {
2477
+ const counts = new Map;
2478
+ return {
2479
+ has: (key) => counts.has(key),
2480
+ add: (keys) => {
2481
+ for (const key of keys) {
2482
+ counts.set(key, (counts.get(key) ?? 0) + 1);
2483
+ }
2484
+ return () => {
2485
+ for (const key of keys) {
2486
+ const count = (counts.get(key) ?? 1) - 1;
2487
+ if (count) {
2488
+ counts.set(key, count);
2489
+ } else {
2490
+ counts.delete(key);
2491
+ }
2492
+ }
2493
+ };
2494
+ }
2495
+ };
2496
+ };
2497
+ var createShownReads = ({
2498
+ manifest,
2499
+ paths,
2500
+ adapter,
2501
+ emit,
2502
+ clock,
2503
+ request
2504
+ }) => {
2505
+ const latest = new Map;
2506
+ const traced = new Map;
2507
+ const failures = new Map;
2508
+ let unread = new Set;
2509
+ const shownJobs = countShown();
2510
+ const shownHealth = countShown();
2511
+ const shownDevices = countShown();
2512
+ const sent = new Map;
2513
+ const value = (target) => latest.get(target);
2514
+ const jobOf = (job) => jobState(job, {
2515
+ value,
2516
+ traced: traced.get(job.id),
2517
+ failure: failures.get(job.id),
2518
+ unread: unread.has(job.id),
2519
+ clock: clock(),
2520
+ now: Date.now(),
2521
+ request
2522
+ });
2523
+ const deviceOf = (device) => deviceState(device, manifest.io, value);
2524
+ const send = (key, event) => {
2525
+ const json = JSON.stringify(event.data);
2526
+ if (sent.get(key) === json) {
2527
+ return;
2528
+ }
2529
+ sent.set(key, json);
2530
+ emit(event);
2531
+ };
2532
+ const updateJob = (job) => send(`job:${job.id}`, { name: "job", data: jobOf(job) });
2533
+ const updateDevice = (device) => send(`device:${device.id}`, { name: "device", data: deviceOf(device) });
2534
+ const reader = (intervalMs, update) => {
2535
+ let current = { key: "", stop: () => {} };
2536
+ return (reads) => {
2537
+ const key = reads.map(({ read }) => read.target).join(`
2538
+ `);
2539
+ if (key === current.key) {
2540
+ return;
2541
+ }
2542
+ current.stop();
2543
+ const owners = new Map;
2544
+ for (const { owner, read } of reads) {
2545
+ owners.set(read.target, [...owners.get(read.target) ?? [], owner]);
2546
+ }
2547
+ current = {
2548
+ key,
2549
+ stop: reads.length ? adapter.subscribe([
2550
+ ...new Map(reads.map(({ read }) => [read.target, read])).values()
2551
+ ], (target, sample) => {
2552
+ latest.set(target, sample);
2553
+ for (const owner of owners.get(target) ?? []) {
2554
+ update(owner);
2555
+ }
2556
+ schedule();
2557
+ }, intervalMs) : () => {}
2558
+ };
2559
+ };
2560
+ };
2561
+ const readJobs = reader(adapter.samplingMs, updateJob);
2562
+ const readDevices = reader(hardwareMs, updateDevice);
2563
+ const shownDeviceReads = (device) => {
2564
+ if (shownDevices.has(device.id)) {
2565
+ return deviceReads(device, manifest.io, paths.typeOf);
2566
+ }
2567
+ if (shownHealth.has(device.id)) {
2568
+ return healthReads(device);
2569
+ }
2570
+ return [];
2571
+ };
2572
+ const plan = () => {
2573
+ const shown = manifest.jobs.filter((job) => shownJobs.has(job.id));
2574
+ const busy = shown.filter((job) => busyOf(job, value, traced.get(job.id)));
2575
+ unread = new Set(busy.slice(detailedJobs).map(({ id }) => id));
2576
+ readJobs([
2577
+ ...shown.map((job) => ({ owner: job, read: busyRead(job) })),
2578
+ ...busy.slice(0, detailedJobs).flatMap((job) => detailReads(job).map((read) => ({ owner: job, read })))
2579
+ ]);
2580
+ readDevices(manifest.devices.flatMap((device) => shownDeviceReads(device).map((read) => ({ owner: device, read }))));
2581
+ };
2582
+ let planned = false;
2583
+ const schedule = () => {
2584
+ if (planned) {
2585
+ return;
2586
+ }
2587
+ planned = true;
2588
+ queueMicrotask(() => {
2589
+ planned = false;
2590
+ plan();
2591
+ });
2592
+ };
2593
+ return {
2594
+ jobs: () => manifest.jobs.map(jobOf),
2595
+ hardware: () => manifest.devices.map(deviceOf),
2596
+ updateJob,
2597
+ show: (interest) => {
2598
+ const stops = [
2599
+ shownJobs.add(interest.jobs),
2600
+ shownHealth.add(interest.health),
2601
+ shownDevices.add(interest.devices)
2602
+ ];
2603
+ schedule();
2604
+ return () => {
2605
+ for (const stop of stops) {
2606
+ stop();
2607
+ }
2608
+ schedule();
2609
+ };
2610
+ },
2611
+ traced: (job, started, at) => {
2612
+ const startedAt = started ? at : traced.get(job.id)?.startedAt;
2613
+ traced.set(job.id, { busy: started, ...startedAt && { startedAt } });
2614
+ updateJob(job);
2615
+ schedule();
2616
+ },
2617
+ failed: (job, failure) => {
2618
+ failures.set(job.id, failure);
2619
+ updateJob(job);
2620
+ },
2621
+ disconnected: (status) => {
2622
+ for (const [target, sample] of latest) {
2623
+ latest.set(target, { ...sample, quality: "unavailable", status });
2624
+ }
2625
+ for (const job of manifest.jobs) {
2626
+ updateJob(job);
2627
+ }
2628
+ for (const device of manifest.devices) {
2629
+ updateDevice(device);
2630
+ }
2631
+ },
2632
+ close: () => {
2633
+ readJobs([]);
2634
+ readDevices([]);
2635
+ }
2636
+ };
2637
+ };
2638
+
2639
+ // packages/debug/src/telemetry.ts
2640
+ import { recordedAt } from "@tsplc/server/telemetry-log";
2641
+ var clockWindowMs = 60000;
2642
+ var createTelemetryFollower = (manifest) => {
2643
+ const intervals = new Map(manifest.tasks.map(({ name, intervalMs }) => [name, intervalMs]));
2644
+ const tasks = new Map(manifest.tasks.map(({ name }) => [
2645
+ name,
2646
+ { name, scan: null, scansPerSecond: null, dropped: 0 }
2647
+ ]));
2648
+ const rates = new Map;
2649
+ let estimates = [];
2650
+ const cursor = createServerCursor();
2651
+ let build = null;
2652
+ const clock = () => {
2653
+ if (!estimates.length) {
2654
+ return null;
2655
+ }
2656
+ const offsets = estimates.map(({ offsetMs }) => offsetMs);
2657
+ const best = estimates.reduce((best, estimate) => estimate.offsetMs > best.offsetMs ? estimate : best);
2658
+ return {
2659
+ offsetMs: best.offsetMs,
2660
+ uncertaintyMs: best.offsetMs - Math.min(...offsets) + best.intervalMs
2661
+ };
2662
+ };
2663
+ const observe = (batch, receivedAt) => {
2664
+ const rate = rates.get(batch.task);
2665
+ if (rate !== undefined && batch.now < rate.now) {
2666
+ estimates = [];
2667
+ }
2668
+ estimates = estimates.filter(({ at }) => receivedAt - at < clockWindowMs);
2669
+ estimates.push({
2670
+ offsetMs: batch.now - receivedAt,
2671
+ intervalMs: intervals.get(batch.task) ?? 0,
2672
+ at: receivedAt
2673
+ });
2674
+ const stats = {
2675
+ name: batch.task,
2676
+ scansPerSecond: tasks.get(batch.task)?.scansPerSecond ?? null,
2677
+ scan: batch.scan,
2678
+ dropped: batch.dropped
2679
+ };
2680
+ const restarted = !rate || batch.scan < rate.scan;
2681
+ const elapsedMs = rate ? batch.now - rate.now >>> 0 : 0;
2682
+ if (restarted) {
2683
+ rates.set(batch.task, { scan: batch.scan, now: batch.now });
2684
+ } else if (elapsedMs >= 1000) {
2685
+ stats.scansPerSecond = (batch.scan - rate.scan) * 1000 / elapsedMs;
2686
+ rates.set(batch.task, { scan: batch.scan, now: batch.now });
2687
+ }
2688
+ tasks.set(batch.task, stats);
2689
+ };
2690
+ return {
2691
+ since: cursor.newest,
2692
+ accept: (reply) => {
2693
+ if (!cursor.continues(reply.latest)) {
2694
+ return [];
2695
+ }
2696
+ const received = [];
2697
+ for (const batch of reply.batches) {
2698
+ if (batch.seq <= cursor.newest()) {
2699
+ continue;
2700
+ }
2701
+ cursor.take(batch.seq);
2702
+ build = batch.build;
2703
+ const receivedAt = new Date(batch.receivedAt);
2704
+ observe(batch, receivedAt.getTime());
2705
+ batch.records.forEach((record, index) => {
2706
+ received.push({
2707
+ build: batch.build,
2708
+ task: batch.task,
2709
+ sequence: batch.first + index,
2710
+ at: recordedAt(batch, record, receivedAt).toISOString(),
2711
+ record
2712
+ });
2713
+ });
2714
+ }
2715
+ return received;
2716
+ },
2717
+ build: () => build,
2718
+ clock,
2719
+ tasks: () => [...tasks.values()].map((task) => ({ ...task }))
2720
+ };
2721
+ };
2722
+
2723
+ // packages/debug/src/trace.ts
2724
+ var createTraceDecoder = (manifest, paths) => {
2725
+ const sites = new Map(manifest.events.map((site) => [site.id, site]));
2726
+ const jobs = new Map(manifest.jobs.map((job) => [job.id, job]));
2727
+ const jobSites = new Map(manifest.events.flatMap(({ id, job: jobId, phase }) => {
2728
+ const job = jobId === undefined ? undefined : jobs.get(jobId);
2729
+ return job && phase ? [[id, { job, started: phase === "started" }]] : [];
2730
+ }));
2731
+ const ours = ({ build, record }) => build === manifest.build.id ? record : undefined;
2732
+ return {
2733
+ decode: (received) => {
2734
+ const record = ours(received);
2735
+ const site = record && sites.get(record.site);
2736
+ if (!record || !site) {
2737
+ return;
2738
+ }
2739
+ const { task, sequence } = received;
2740
+ return {
2741
+ sequence,
2742
+ task,
2743
+ scan: record.scan,
2744
+ plcTime: record.time,
2745
+ site: site.id,
2746
+ value: paths.decode(site.type, record.value),
2747
+ operands: site.operands.map(({ text, path, stable, type }, index) => ({
2748
+ text,
2749
+ ...path && { path },
2750
+ stable,
2751
+ value: paths.decode(type, record.operands[index])
2752
+ }))
2753
+ };
2754
+ },
2755
+ job: (received) => {
2756
+ const record = ours(received);
2757
+ return record && jobSites.get(record.site);
2758
+ }
2759
+ };
2760
+ };
2761
+
2762
+ // packages/debug/src/api.ts
2763
+ import { qualitySchema } from "@tsplc/opcua/contract";
2764
+ import { serviceCall } from "@tsplc/server/requests";
2765
+ import { appRecord } from "@tsplc/server/telemetry";
2766
+ import { z as z3 } from "zod";
2767
+ import { qualitySchema as qualitySchema2 } from "@tsplc/opcua/contract";
2768
+ var errorBodySchema = z3.object({ error: z3.string() });
2769
+ var sampleSchema = z3.object({
2770
+ path: z3.string(),
2771
+ value: z3.unknown(),
2772
+ quality: qualitySchema,
2773
+ status: z3.string(),
2774
+ receivedAt: z3.string(),
2775
+ read: z3.number().int().optional()
2776
+ });
2777
+ var connectionStateSchema = z3.enum([
2778
+ "connecting",
2779
+ "connected",
2780
+ "lost",
2781
+ "failed",
2782
+ "unavailable"
2783
+ ]);
2784
+ var sessionSchema = z3.object({
2785
+ build: z3.object({
2786
+ manifest: z3.string().nullable(),
2787
+ controller: z3.string().nullable(),
2788
+ matches: z3.boolean()
2789
+ }),
2790
+ connection: z3.object({
2791
+ state: connectionStateSchema,
2792
+ since: z3.string(),
2793
+ endpoint: z3.string(),
2794
+ error: z3.string().optional()
2795
+ }),
2796
+ reading: z3.object({ method: z3.string(), intervalMs: z3.number() }),
2797
+ tasks: z3.array(z3.object({
2798
+ name: z3.string(),
2799
+ scan: z3.number().nullable(),
2800
+ scansPerSecond: z3.number().nullable(),
2801
+ dropped: z3.number()
2802
+ })),
2803
+ clock: z3.object({ offsetMs: z3.number(), uncertaintyMs: z3.number() }).nullable(),
2804
+ release: z3.object({ id: z3.string(), deployedAt: z3.string(), operation: z3.string() }).optional(),
2805
+ projectRoot: z3.string().optional()
2806
+ });
2807
+ var traceEventSchema = z3.object({
2808
+ sequence: z3.number(),
2809
+ task: z3.string(),
2810
+ scan: z3.number(),
2811
+ plcTime: z3.number(),
2812
+ site: z3.number(),
2813
+ value: z3.unknown(),
2814
+ operands: z3.array(z3.object({
2815
+ text: z3.string(),
2816
+ path: z3.string().optional(),
2817
+ stable: z3.boolean(),
2818
+ value: z3.unknown()
2819
+ }))
2820
+ });
2821
+ var requestTraceSchema = serviceCall;
2822
+ var jobStateSchema = z3.object({
2823
+ id: z3.number(),
2824
+ quality: qualitySchema,
2825
+ busy: z3.boolean().nullable(),
2826
+ cancelling: z3.boolean().optional(),
2827
+ step: z3.number().optional(),
2828
+ current: z3.object({ kind: z3.string(), range: sourceRange, text: z3.string() }).optional(),
2829
+ startedAt: z3.string().optional(),
2830
+ elapsedMs: z3.number().optional(),
2831
+ request: z3.object({
2832
+ service: z3.string(),
2833
+ sequence: z3.number(),
2834
+ trace: requestTraceSchema.optional()
2835
+ }).optional(),
2836
+ unread: z3.literal(true).optional(),
2837
+ failure: z3.object({
2838
+ at: z3.string(),
2839
+ code: z3.number(),
2840
+ name: z3.string().optional(),
2841
+ source: z3.string()
2842
+ }).optional()
2843
+ });
2844
+ var healthStateSchema = z3.enum(["unknown", "ok", "fault", "stale"]);
2845
+ var deviceStateSchema = z3.object({
2846
+ id: z3.string(),
2847
+ health: z3.object({
2848
+ state: healthStateSchema,
2849
+ value: z3.number().optional(),
2850
+ name: z3.string().optional(),
2851
+ diagnostic: z3.boolean().optional(),
2852
+ message: z3.string().optional(),
2853
+ quality: qualitySchema
2854
+ }),
2855
+ assemblies: z3.array(z3.object({
2856
+ direction: z3.enum(["input", "output"]),
2857
+ address: z3.string().optional(),
2858
+ bytes: z3.array(z3.number()).nullable(),
2859
+ quality: qualitySchema
2860
+ })),
2861
+ channels: z3.array(z3.object({
2862
+ id: z3.string(),
2863
+ path: z3.string(),
2864
+ value: z3.unknown(),
2865
+ quality: qualitySchema
2866
+ })),
2867
+ status: z3.record(z3.string(), z3.object({ value: z3.unknown(), quality: qualitySchema }))
2868
+ });
2869
+ var timelineSourceSchema = z3.enum([
2870
+ "plc",
2871
+ "server",
2872
+ "agent",
2873
+ "debugger"
2874
+ ]);
2875
+ var timelinePlacement = {
2876
+ at: z3.string(),
2877
+ approximate: z3.boolean(),
2878
+ source: timelineSourceSchema,
2879
+ cursor: z3.string().optional()
2880
+ };
2881
+ var timelineEntrySchema = z3.discriminatedUnion("kind", [
2882
+ z3.object({
2883
+ ...timelinePlacement,
2884
+ kind: z3.literal("app"),
2885
+ task: z3.string(),
2886
+ sequence: z3.number(),
2887
+ record: appRecord
2888
+ }),
2889
+ z3.object({
2890
+ ...timelinePlacement,
2891
+ kind: z3.literal("trace"),
2892
+ trace: traceEventSchema
2893
+ }),
2894
+ z3.object({
2895
+ ...timelinePlacement,
2896
+ kind: z3.literal("request"),
2897
+ request: requestTraceSchema
2898
+ }),
2899
+ z3.object({
2900
+ ...timelinePlacement,
2901
+ kind: z3.literal("deploy"),
2902
+ release: z3.string(),
2903
+ operation: z3.string(),
2904
+ build: z3.string().optional(),
2905
+ user: z3.string().optional(),
2906
+ host: z3.string().optional()
2907
+ }),
2908
+ z3.object({
2909
+ ...timelinePlacement,
2910
+ kind: z3.literal("audit"),
2911
+ command: z3.string(),
2912
+ values: z3.record(z3.string(), z3.string()),
2913
+ previous: z3.record(z3.string(), z3.string()).optional(),
2914
+ user: z3.string().optional(),
2915
+ host: z3.string().optional(),
2916
+ release: z3.string().optional(),
2917
+ error: z3.string().optional()
2918
+ }),
2919
+ z3.object({
2920
+ ...timelinePlacement,
2921
+ kind: z3.literal("connection"),
2922
+ state: connectionStateSchema,
2923
+ error: z3.string().optional()
2924
+ })
2925
+ ]);
2926
+ var watchGroupsSchema = z3.strictObject({
2927
+ groups: z3.record(z3.string().nonempty(), z3.array(z3.string().nonempty()))
2928
+ });
2929
+ var clockSample = (task) => `tsplc:clock/${task}`;
2930
+ var slotSample = (writer) => `tsplc:writer/${writer}`;
2931
+ var explanationSchema = z3.object({
2932
+ path: z3.string(),
2933
+ type: z3.string(),
2934
+ writers: z3.array(z3.object({
2935
+ assignment: z3.number().int(),
2936
+ indexes: z3.array(z3.number().int()),
2937
+ chains: z3.array(z3.object({
2938
+ task: z3.string(),
2939
+ entry: z3.number().int(),
2940
+ calls: z3.array(z3.number().int())
2941
+ }))
2942
+ })),
2943
+ flags: explainFlags.omit({ path: true }),
2944
+ io: debugIo.nullable()
2945
+ });
2946
+ var forcedSchema = z3.object({
2947
+ forced: z3.array(z3.string()).nullable(),
2948
+ at: z3.string()
2949
+ });
2950
+ var apiResponseSchemas = {
2951
+ "GET /api/session": sessionSchema,
2952
+ "GET /api/manifest": debugManifest,
2953
+ "GET /api/values": z3.array(sampleSchema),
2954
+ "GET /api/jobs": z3.array(jobStateSchema),
2955
+ "GET /api/hardware": z3.array(deviceStateSchema),
2956
+ "GET /api/timeline": z3.array(timelineEntrySchema),
2957
+ "GET /api/watch": watchGroupsSchema,
2958
+ "PUT /api/watch": watchGroupsSchema,
2959
+ "GET /api/explain": explanationSchema,
2960
+ "GET /api/explain-file": explainFile,
2961
+ "GET /api/forced": forcedSchema
2962
+ };
2963
+
2964
+ // packages/debug/src/values.ts
2965
+ var createValueReader = ({
2966
+ manifest,
2967
+ paths,
2968
+ adapter
2969
+ }) => {
2970
+ const unavailable = (path, status) => ({
2971
+ path,
2972
+ value: null,
2973
+ quality: "unavailable",
2974
+ status,
2975
+ receivedAt: new Date().toISOString()
2976
+ });
2977
+ const locate = (path) => {
2978
+ const resolved = paths.resolve(path);
2979
+ if (!resolved) {
2980
+ return unavailable(path, "Unknown path");
2981
+ }
2982
+ if (resolved.kind === "constant") {
2983
+ return {
2984
+ path,
2985
+ value: resolved.value,
2986
+ quality: "good",
2987
+ status: "Constant",
2988
+ receivedAt: new Date().toISOString()
2989
+ };
2990
+ }
2991
+ if (!resolved.readable) {
2992
+ return unavailable(path, "Not readable");
2993
+ }
2994
+ return resolved;
2995
+ };
2996
+ const targetRead = ({ target, type }) => ({
2997
+ target,
2998
+ type: paths.typeOf(type)
2999
+ });
3000
+ const sampleOf = ({ path, type }, sample) => ({
3001
+ path,
3002
+ ...sample,
3003
+ value: paths.decode(type, sample.value)
3004
+ });
3005
+ const rawTargets = (raw) => [
3006
+ ...raw.clocks.flatMap((name) => {
3007
+ const target = manifest.tasks.find((task) => task.name === name)?.clock;
3008
+ return target ? [{ path: clockSample(name), target, type: scanClockType }] : [];
3009
+ }),
3010
+ ...raw.slots.flatMap((index) => {
3011
+ const target = manifest.writers[index]?.target;
3012
+ return target ? [{ path: slotSample(index), target, type: writerSlotType }] : [];
3013
+ })
3014
+ ];
3015
+ const watch = (patterns, listener, raw) => {
3016
+ const watched = new Map;
3017
+ const reads = [];
3018
+ const add = (located) => {
3019
+ if (!watched.has(located.target)) {
3020
+ reads.push(targetRead(located));
3021
+ }
3022
+ watched.set(located.target, [
3023
+ ...watched.get(located.target) ?? [],
3024
+ located
3025
+ ]);
3026
+ };
3027
+ for (const item of rawTargets(raw)) {
3028
+ add(item);
3029
+ }
3030
+ const unread = [];
3031
+ for (const path of paths.expand(patterns)) {
3032
+ const located = locate(path);
3033
+ if ("target" in located) {
3034
+ add(located);
3035
+ } else {
3036
+ unread.push(located);
3037
+ listener(located);
3038
+ }
3039
+ }
3040
+ const repeat = unread.length ? setInterval(() => {
3041
+ if (adapter.connection().state !== "connected") {
3042
+ return;
3043
+ }
3044
+ const receivedAt = new Date().toISOString();
3045
+ for (const sample of unread) {
3046
+ listener({ ...sample, receivedAt });
3047
+ }
3048
+ }, adapter.samplingMs) : undefined;
3049
+ const stop = reads.length ? adapter.subscribe(reads, (target, received) => {
3050
+ for (const located of watched.get(target) ?? []) {
3051
+ listener(sampleOf(located, received));
3052
+ }
3053
+ }) : () => {};
3054
+ return () => {
3055
+ clearInterval(repeat);
3056
+ stop();
3057
+ };
3058
+ };
3059
+ const read = async (patterns) => {
3060
+ const connection = adapter.connection();
3061
+ if (connection.state !== "connected") {
3062
+ throw new DebugError(connection.error ?? "The controller is not connected", 503);
3063
+ }
3064
+ const located = paths.expand(patterns).map((path) => ({ path, located: locate(path) }));
3065
+ const samples = await adapter.read(located.flatMap(({ located }) => ("target" in located) ? [targetRead(located)] : []));
3066
+ return located.map(({ path, located }) => {
3067
+ if (!("target" in located)) {
3068
+ return located;
3069
+ }
3070
+ const sample = samples.get(located.target);
3071
+ return sample ? sampleOf({ ...located, path }, sample) : unavailable(path, "Not read");
3072
+ });
3073
+ };
3074
+ return { watch, read };
3075
+ };
3076
+
3077
+ // packages/debug/src/watch.ts
3078
+ import { existsSync } from "node:fs";
3079
+ import { mkdir, readFile as readFile2, writeFile } from "node:fs/promises";
3080
+ import { dirname as dirname2 } from "node:path";
3081
+ import { isDeepStrictEqual } from "node:util";
3082
+ var loadWatchGroups = async (file, configured) => {
3083
+ let saved = existsSync(file) ? watchGroupsSchema.parse(JSON.parse(await readFile2(file, "utf8"))).groups : {};
3084
+ const groups = () => ({ groups: { ...configured, ...saved } });
3085
+ return {
3086
+ groups,
3087
+ save: async ({ groups: next }) => {
3088
+ saved = Object.fromEntries(Object.entries(next).filter(([name, paths]) => !isDeepStrictEqual(configured[name], paths)));
3089
+ await mkdir(dirname2(file), { recursive: true });
3090
+ await writeFile(file, JSON.stringify({ groups: saved }, null, 2));
3091
+ return groups();
3092
+ }
3093
+ };
3094
+ };
3095
+
3096
+ // packages/debug/src/debugger.ts
3097
+ var buildCheckMs = 1e4;
3098
+ var createDebugger = async (options) => {
3099
+ const { manifest, adapter } = options;
3100
+ const paths = createPaths(manifest);
3101
+ const telemetry = createTelemetryFollower(manifest);
3102
+ const requests = createRequestFollower();
3103
+ const timeline = createTimeline();
3104
+ const watchGroups = await loadWatchGroups(join2(options.stateDirectory, "watch.json"), options.watch);
3105
+ const listeners = new Set;
3106
+ const controller = new AbortController;
3107
+ let controllerBuild = null;
3108
+ const emit = (event) => {
3109
+ for (const listener of listeners) {
3110
+ listener(event);
3111
+ }
3112
+ };
3113
+ const record = (entry) => {
3114
+ emit({ name: "timeline", data: timeline.add(entry) });
3115
+ };
3116
+ for (const entry of options.timeline ?? []) {
3117
+ timeline.add(entry);
3118
+ }
3119
+ const session = () => ({
3120
+ build: {
3121
+ manifest: manifest.build.id,
3122
+ controller: controllerBuild,
3123
+ matches: controllerBuild === manifest.build.id
3124
+ },
3125
+ connection: { ...adapter.connection(), endpoint: adapter.endpoint },
3126
+ reading: { method: adapter.method, intervalMs: adapter.samplingMs },
3127
+ tasks: telemetry.tasks(),
3128
+ clock: telemetry.clock(),
3129
+ ...options.release && { release: options.release },
3130
+ ...options.projectRoot && { projectRoot: options.projectRoot }
3131
+ });
3132
+ const sessionChanged = () => emit({ name: "session", data: session() });
3133
+ const setBuild = (build) => {
3134
+ if (build === controllerBuild) {
3135
+ return;
3136
+ }
3137
+ controllerBuild = build;
3138
+ sessionChanged();
3139
+ };
3140
+ const values = createValueReader({ manifest, paths, adapter });
3141
+ const shown = createShownReads({
3142
+ manifest,
3143
+ paths,
3144
+ adapter,
3145
+ emit,
3146
+ clock: telemetry.clock,
3147
+ request: requests.call
3148
+ });
3149
+ const stopBuild = adapter.subscribe([scalarRead(manifest.build.target, "STRING")], (_, sample) => {
3150
+ if (sample.quality === "good" && typeof sample.value === "string") {
3151
+ setBuild(sample.value);
3152
+ }
3153
+ }, buildCheckMs);
3154
+ const stopConnection = adapter.onConnection((connection) => {
3155
+ record(timelineEntries.connection(connection.since, connection.state, connection.error));
3156
+ sessionChanged();
3157
+ if (connection.state !== "connected") {
3158
+ shown.disconnected(connection.error ?? "The controller is not connected");
3159
+ }
3160
+ });
3161
+ const running = options.server ? followAppServer({
3162
+ server: options.server,
3163
+ manifest,
3164
+ telemetry,
3165
+ requests,
3166
+ trace: createTraceDecoder(manifest, paths),
3167
+ shown,
3168
+ emit,
3169
+ record,
3170
+ recordChange: (entry) => emit({ name: "timeline", data: timeline.changed(entry) }),
3171
+ setBuild,
3172
+ sessionChanged,
3173
+ signal: controller.signal,
3174
+ log: options.log
3175
+ }) : undefined;
3176
+ const explained = options.explanations && {
3177
+ file: options.explanations,
3178
+ explainer: createExplainer(manifest, options.explanations.file)
3179
+ };
3180
+ const explanations = () => {
3181
+ if (!explained) {
3182
+ throw new DebugError("This build has no explanations", 404);
3183
+ }
3184
+ return explained;
3185
+ };
3186
+ const explain = (path) => {
3187
+ const { explainer } = explanations();
3188
+ const resolved = paths.resolve(path);
3189
+ if (resolved?.kind !== "target") {
3190
+ throw new DebugError(`Unknown path ${path}`, 400);
3191
+ }
3192
+ const explanation = explainer.explain(path);
3193
+ return {
3194
+ ...explanation,
3195
+ type: resolved.type,
3196
+ writers: explanation.writers.map((writer) => ({
3197
+ ...writer,
3198
+ indexes: writer.indexes.map(Number),
3199
+ chains: writer.chains.map((chain) => ({
3200
+ ...chain,
3201
+ calls: [...chain.calls]
3202
+ }))
3203
+ }))
3204
+ };
3205
+ };
3206
+ const forced = async () => {
3207
+ const at = new Date().toISOString();
3208
+ const expressions = options.forced ? await options.forced() : null;
3209
+ return {
3210
+ forced: expressions && [
3211
+ ...new Set(expressions.flatMap((expression) => paths.fromTarget(expression) ?? []))
3212
+ ],
3213
+ at
3214
+ };
3215
+ };
3216
+ return {
3217
+ manifest,
3218
+ paths,
3219
+ session,
3220
+ explain,
3221
+ forced,
3222
+ explanationFile: () => explanations().file,
3223
+ values: values.read,
3224
+ jobs: shown.jobs,
3225
+ hardware: shown.hardware,
3226
+ timeline: timeline.since,
3227
+ watchGroups: () => watchGroups.groups(),
3228
+ saveWatchGroups: (groups) => watchGroups.save(groups),
3229
+ record,
3230
+ watch: values.watch,
3231
+ show: shown.show,
3232
+ subscribe: (listener) => {
3233
+ listeners.add(listener);
3234
+ return () => listeners.delete(listener);
3235
+ },
3236
+ close: async () => {
3237
+ controller.abort();
3238
+ stopBuild();
3239
+ shown.close();
3240
+ stopConnection();
3241
+ await running;
3242
+ await adapter.close();
3243
+ }
3244
+ };
3245
+ };
3246
+ // packages/debug/src/http.ts
3247
+ import { z as z4 } from "zod";
3248
+
3249
+ // packages/debug/src/ui/index.ts
3250
+ import { createRequire } from "node:module";
3251
+ import { dirname as dirname3, resolve } from "node:path";
3252
+
3253
+ // packages/debug/src/ui/page.ts
3254
+ var hatch = "repeating-linear-gradient(135deg,transparent 0 4px,var(--hatch) 4px 8px)";
3255
+ var rules = (tones, selector, declaration) => Object.entries(tones).map(([value, tone]) => `${selector(value)}{${declaration(tone)}}`).join("");
3256
+ var connectionTones = {
3257
+ connecting: "uncertain",
3258
+ connected: "live",
3259
+ lost: "bad",
3260
+ failed: "bad",
3261
+ unavailable: "uncertain"
3262
+ };
3263
+ var statusTones = {
3264
+ ...connectionTones,
3265
+ busy: "uncertain",
3266
+ pending: "uncertain",
3267
+ cancelling: "uncertain",
3268
+ error: "bad",
3269
+ timeout: "bad",
3270
+ ok: "live",
3271
+ idle: "dim",
3272
+ unknown: "dim"
3273
+ };
3274
+ var sourceTones = {
3275
+ plc: "accent",
3276
+ server: "link",
3277
+ agent: "constant",
3278
+ debugger: "dim"
3279
+ };
3280
+ var levelTones = {
3281
+ info: "link",
3282
+ warn: "uncertain",
3283
+ error: "bad"
3284
+ };
3285
+ var verdictTones = {
3286
+ runs: "live",
3287
+ blocked: "dim",
3288
+ unknown: "uncertain",
3289
+ candidate: "constant"
3290
+ };
3291
+ var valueStateStyles = {
3292
+ live: { value: "", marker: "●" },
3293
+ uncertain: { value: "text-decoration:underline dotted", marker: "◐" },
3294
+ bad: { value: "text-decoration:line-through", marker: "✕" },
3295
+ stale: { value: `background:${hatch}`, marker: "○" },
3296
+ unavailable: { value: "", marker: "–" },
3297
+ constant: { value: "font-style:italic", marker: "◆" }
3298
+ };
3299
+ var healthStyles = {
3300
+ ok: "color:var(--live);border-color:var(--live)",
3301
+ fault: "color:#fff;background:var(--bad);border-color:var(--bad)",
3302
+ stale: `color:var(--stale);border-color:var(--stale);background:${hatch}`,
3303
+ unknown: "color:var(--dim);border-color:var(--dim);border-style:dashed"
3304
+ };
3305
+ var color = (tone) => `color:var(--${tone})`;
3306
+ var css = `
3307
+ :root{color-scheme:dark;
3308
+ --bg:#0c0e11;--grid:rgba(255,255,255,.025);--panel:#13161b;--panel-2:#191d23;--line:#262b33;--line-soft:#1d2128;
3309
+ --fg:#d8dce2;--dim:#7c848f;--accent:#f2a33a;--link:#79c0ff;
3310
+ --live:#5ee0a0;--uncertain:#f3c64a;--bad:#ff6b6b;--stale:#8a919b;--unavailable:#5a616b;--constant:#b8a2ff;
3311
+ --hatch:rgba(138,145,155,.16);
3312
+ --mono:"JetBrains Mono","Cascadia Mono","IBM Plex Mono","SF Mono",Menlo,Consolas,monospace;
3313
+ --sans:"IBM Plex Sans","Segoe UI Variable Text","Segoe UI","Helvetica Neue",sans-serif}
3314
+ @media (prefers-color-scheme:light){:root{color-scheme:light;
3315
+ --bg:#f3f1ec;--grid:rgba(0,0,0,.035);--panel:#fffefb;--panel-2:#f6f4ef;--line:#d8d3c8;--line-soft:#e7e3da;
3316
+ --fg:#1b1e22;--dim:#6a6e75;--accent:#b5650a;--link:#0a5bb0;
3317
+ --live:#0d8048;--uncertain:#9a6400;--bad:#c42525;--stale:#767b83;--unavailable:#a1a6ad;--constant:#6447cc;
3318
+ --hatch:rgba(118,123,131,.16)}}
3319
+ *{box-sizing:border-box}
3320
+ html,body{height:100%}
3321
+ body{margin:0;font:13px/1.45 var(--sans);color:var(--fg);background:var(--bg);
3322
+ background-image:linear-gradient(var(--grid) 1px,transparent 1px),linear-gradient(90deg,var(--grid) 1px,transparent 1px);
3323
+ background-size:24px 24px;display:grid;grid-template-rows:auto minmax(0,1fr);font-variant-numeric:tabular-nums}
3324
+ a{color:var(--link);text-decoration:none}a:hover{text-decoration:underline}
3325
+ code,.mono,.path,.src{font-family:var(--mono);font-size:12px}
3326
+ .src,.nowrap,.grid td.num{white-space:nowrap}
3327
+ code{color:var(--fg);background:var(--panel-2);border:1px solid var(--line-soft);border-radius:3px;padding:0 4px}
3328
+ .dim,.hint,.empty{color:var(--dim)}.hint{margin:4px 0 12px}.empty{margin:8px 0;font-style:italic}
3329
+ .err{color:var(--bad)}.num{text-align:right}
3330
+ button,input{font:inherit;color:inherit}
3331
+ button{background:var(--panel-2);border:1px solid var(--line);border-radius:4px;padding:3px 10px;cursor:pointer}
3332
+ button:hover{border-color:var(--dim)}button.primary{background:var(--accent);border-color:var(--accent);color:#16110a;font-weight:600}
3333
+ button:disabled{opacity:.5;cursor:default}
3334
+ input{background:var(--panel);border:1px solid var(--line);border-radius:4px;padding:4px 8px}
3335
+ input:focus,button:focus-visible,.vlist:focus-visible{outline:1px solid var(--accent);outline-offset:1px}
3336
+ h1{font:600 18px var(--sans);margin:0 0 12px;letter-spacing:-.01em}
3337
+ h2{font:600 10.5px var(--sans);text-transform:uppercase;letter-spacing:.14em;color:var(--dim);margin:0 0 10px}
3338
+ h2 a{color:inherit}h3{font:600 12px var(--sans);margin:14px 0 6px}
3339
+
3340
+ header{background:var(--panel);border-top:2px solid var(--accent);border-bottom:1px solid var(--line)}
3341
+ .bar{display:flex;align-items:stretch;gap:0;overflow-x:auto}
3342
+ .brand{display:flex;align-items:center;gap:6px;padding:8px 16px;border-right:1px solid var(--line);white-space:nowrap}
3343
+ .brand b{font:700 13px var(--mono);letter-spacing:.04em}.brand span{font:500 13px var(--mono);color:var(--accent)}
3344
+ .brand .ro{font:600 9.5px var(--sans);letter-spacing:.14em;text-transform:uppercase;color:var(--dim);border:1px solid var(--line);border-radius:3px;padding:1px 5px;margin-left:6px}
3345
+ .readouts{display:flex;flex:1}
3346
+ .readout{display:flex;flex-direction:column;justify-content:center;padding:6px 14px;border-right:1px solid var(--line-soft);white-space:nowrap}
3347
+ .readout .label{font:600 9px var(--sans);letter-spacing:.16em;text-transform:uppercase;color:var(--dim)}
3348
+ .readout .reading{font:12px var(--mono);display:flex;align-items:center;gap:8px}
3349
+ .build.match i{color:var(--live);font-style:normal}.build.mismatch{color:var(--bad)}.build.mismatch i{font-style:normal;font-weight:700}
3350
+ .task b{color:var(--fg);font-weight:600}
3351
+ .dot{width:8px;height:8px;border-radius:50%;display:inline-block;background:var(--unavailable)}
3352
+ ${rules(connectionTones, (state) => `.dot.c-${state}`, (tone) => `background:var(--${tone})`)}
3353
+ .dot.c-connected{box-shadow:0 0 6px var(--live)}.dot.c-connecting{animation:pulse 1s infinite alternate}
3354
+ @keyframes pulse{to{opacity:.3}}
3355
+ nav{display:flex;gap:2px;padding:0 10px;border-top:1px solid var(--line-soft)}
3356
+ nav a{color:var(--dim);padding:7px 12px 6px;text-transform:capitalize;border-bottom:2px solid transparent;font-weight:500}
3357
+ nav a:hover{color:var(--fg);text-decoration:none}nav a.on{color:var(--fg);border-bottom-color:var(--accent)}
3358
+ .banner{padding:7px 16px;font-weight:600;display:flex;gap:12px;align-items:center}
3359
+ .banner.danger{background:var(--bad);color:#fff}
3360
+ .banner.warn{background:repeating-linear-gradient(135deg,var(--uncertain) 0 14px,color-mix(in srgb,var(--uncertain) 85%,#000) 14px 28px);color:#1b1404}
3361
+ .banner.error{background:var(--panel-2);color:var(--bad);border-top:1px solid var(--bad)}
3362
+ .banner button{margin-left:auto}
3363
+
3364
+ main{overflow:auto;min-height:0}
3365
+ .page{padding:16px 18px 28px;animation:enter .18s ease-out}
3366
+ @keyframes enter{from{opacity:0;transform:translateY(3px)}}
3367
+ .panel{background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:12px 14px}
3368
+ .toolbar{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:10px}
3369
+ .check{display:inline-flex;gap:5px;align-items:center;color:var(--dim);cursor:pointer}.check input{margin:0}
3370
+ .sep{margin-left:8px}.count{color:var(--dim);font:12px var(--mono);margin-left:auto}
3371
+ .tabs{display:flex;flex-wrap:wrap;gap:4px;margin-bottom:10px;align-items:center}
3372
+ .tab{background:transparent}.tab.on{border-color:var(--accent);color:var(--fg)}
3373
+ .tab .n{color:var(--dim);margin-left:6px;font:11px var(--mono)}
3374
+ .tag{font:600 9.5px var(--sans);letter-spacing:.08em;text-transform:uppercase;color:var(--dim);border:1px solid var(--line);border-radius:3px;padding:0 4px;margin:0 4px}
3375
+ dl{display:grid;grid-template-columns:max-content 1fr;gap:3px 14px;margin:0}dt{color:var(--dim)}dd{margin:0;min-width:0;overflow-wrap:anywhere}
3376
+ .facts{margin-bottom:14px}.readings dd{display:flex;gap:8px;align-items:baseline}
3377
+ .crumbs{color:var(--dim);margin-bottom:4px}
3378
+
3379
+ table.grid{width:100%;border-collapse:collapse;background:var(--panel);border:1px solid var(--line);border-radius:6px}
3380
+ .grid th{font:600 9.5px var(--sans);letter-spacing:.14em;text-transform:uppercase;color:var(--dim);text-align:left;padding:7px 10px;border-bottom:1px solid var(--line);position:sticky;top:0;background:var(--panel)}
3381
+ .grid td{padding:6px 10px;border-bottom:1px solid var(--line-soft);vertical-align:top}
3382
+ .grid tr:last-child td{border-bottom:0}.link-row{cursor:pointer}.link-row:hover td{background:var(--panel-2)}
3383
+ tr.highlight td{background:color-mix(in srgb,var(--accent) 12%,transparent)}
3384
+
3385
+ .value{font:12.5px var(--mono);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
3386
+ .meta{font:11px var(--mono);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
3387
+ .meta::before{display:inline-block;width:1.4ch}
3388
+ ${Object.entries(valueStateStyles).map(([state, { value, marker }]) => `.s-${state}{color:var(--${state})}.value.s-${state}{${value}}.meta.s-${state}::before{content:"${marker}"}`).join(`
3389
+ `)}
3390
+ .s-group{color:var(--dim)}
3391
+
3392
+ .variables{height:100%;display:flex;flex-direction:column;padding-bottom:12px}
3393
+ .search{flex:1;min-width:280px;max-width:640px;font-family:var(--mono);font-size:12.5px;padding:6px 10px}
3394
+ .split{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 380px;gap:12px}
3395
+ .listwrap{display:flex;flex-direction:column;min-height:0;background:var(--panel);border:1px solid var(--line);border-radius:6px;overflow:hidden}
3396
+ .vlist{flex:1;overflow:auto;position:relative;outline:none}
3397
+ .vspacer{position:relative}.vwindow{position:absolute;left:0;right:0;top:0}
3398
+ .row{display:grid;grid-template-columns:minmax(220px,1fr) minmax(90px,15ch) 21ch 17ch 40px minmax(110px,19ch);gap:8px;align-items:center;height:26px;padding-right:10px;border-bottom:1px solid var(--line-soft);cursor:default}
3399
+ .row:hover{background:var(--panel-2)}.row.selected{background:color-mix(in srgb,var(--accent) 13%,transparent);box-shadow:inset 2px 0 0 var(--accent)}
3400
+ .row.head{font:600 9.5px var(--sans);letter-spacing:.14em;text-transform:uppercase;color:var(--dim);border-bottom:1px solid var(--line);padding-left:10px}
3401
+ .row.generated .name{opacity:.7}
3402
+ .name{font:12.5px var(--mono);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:flex;align-items:center}
3403
+ .name mark{background:color-mix(in srgb,var(--accent) 35%,transparent);color:inherit;border-radius:2px}
3404
+ .twisty{display:inline-grid;place-items:center;width:18px;height:18px;flex:none;padding:0;border:0;background:none;color:var(--dim);font-size:10px}
3405
+ .type{font:11.5px var(--mono);color:var(--dim);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
3406
+ .row .src{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:11px}
3407
+ .rec{padding:0;width:22px;height:18px;border:1px solid transparent;background:none;color:var(--line);font-size:11px}
3408
+ .rec:hover{color:var(--dim);border-color:var(--line)}.rec.on{color:var(--bad)}.rec.elsewhere{color:var(--dim)}
3409
+ .side{display:flex;flex-direction:column;gap:12px;overflow:auto;min-height:0}
3410
+ .detail-path{font-size:12.5px;overflow-wrap:anywhere;margin-bottom:8px;color:var(--fg)}
3411
+ .detail-value{display:flex;gap:12px;align-items:baseline;margin-bottom:10px;padding:8px 10px;background:var(--panel-2);border-radius:4px}
3412
+ .detail-value .value{font-size:20px}.detail .site{margin:3px 0}.detail button{margin-top:10px}
3413
+ .member{display:grid;grid-template-columns:minmax(0,1fr) auto auto 22px;gap:8px;align-items:center;padding:3px 0;border-bottom:1px solid var(--line-soft)}
3414
+ .member .path{font-size:11.5px}.remove{padding:0 5px;border:0;background:none;color:var(--dim)}
3415
+ .groups form input{width:110px;padding:2px 6px}
3416
+
3417
+ .badge{display:inline-block;font:600 10.5px var(--mono);letter-spacing:.04em;padding:1px 7px;border-radius:3px;border:1px solid;text-transform:uppercase}
3418
+ ${Object.entries(healthStyles).map(([health, style]) => `.h-${health}{${style}}`).join(`
3419
+ `)}
3420
+ .st{font:600 11px var(--mono);text-transform:lowercase}
3421
+ ${rules(statusTones, (status) => `.st-${status}`, color)}
3422
+ .await code{white-space:pre-wrap}
3423
+
3424
+ .overview{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;align-items:start}
3425
+ .overview .wide{grid-column:1/-1}
3426
+ .overview>*{animation:enter .25s ease-out backwards}.overview>:nth-child(2){animation-delay:.04s}.overview>:nth-child(3){animation-delay:.08s}.overview>:nth-child(4){animation-delay:.12s}
3427
+ .counts{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:10px}
3428
+ .count-box{border:1px solid;border-radius:5px;padding:6px 10px;display:flex;flex-direction:column}
3429
+ .count-box b{font:600 22px var(--mono)}.count-box span{font:600 9.5px var(--sans);letter-spacing:.14em;text-transform:uppercase}
3430
+ .count-box.h-fault{background:color-mix(in srgb,var(--bad) 12%,transparent);color:var(--bad)}
3431
+ .device-line{padding:3px 0}
3432
+
3433
+ .assemblies{display:flex;flex-direction:column;gap:12px;margin-bottom:18px}
3434
+ .assembly h3{margin:0 0 10px}
3435
+ .bitgrid{display:grid;grid-template-columns:4ch repeat(8,52px) 4ch minmax(0,1fr);gap:3px;align-items:stretch}
3436
+ .bh{font:600 9.5px var(--mono);color:var(--dim);text-align:center;letter-spacing:.06em}.legend-head{text-align:left;padding-left:6px}
3437
+ .byte,.hex{font-size:11.5px;color:var(--dim);align-self:center}
3438
+ .bit{position:relative;height:34px;display:flex;flex-direction:column;align-items:center;justify-content:center;font:600 13px var(--mono);
3439
+ border:1px dashed var(--line);border-radius:3px;color:var(--unavailable)}
3440
+ .bit small{font:9px var(--mono);color:var(--dim);max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0 2px}
3441
+ .bit.mapped{border-style:solid;color:var(--dim);background:var(--panel-2)}
3442
+ .bit.on{color:var(--fg)}
3443
+ .bit.mapped.on{color:var(--live);background:color-mix(in srgb,var(--live) 16%,transparent);border-color:color-mix(in srgb,var(--live) 60%,transparent);box-shadow:0 0 8px color-mix(in srgb,var(--live) 25%,transparent)}
3444
+ .bit.none{color:var(--unavailable)}
3445
+ .q-stale .bit,.q-uncertain .bit,.q-bad .bit{background-image:${hatch}}
3446
+ .q-stale .bit.on,.q-bad .bit.on{color:var(--stale);box-shadow:none;border-color:var(--line)}
3447
+ .legend{display:flex;flex-wrap:wrap;gap:4px 12px;align-items:center;font-size:11.5px;padding-left:6px}
3448
+ .legend-item{display:inline-flex;gap:6px;align-items:baseline}.legend-item b{font:600 11px var(--mono)}
3449
+ .mapped-path{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:baseline}
3450
+
3451
+ .recent .entries{display:flex;flex-direction:column;background:var(--panel);border:1px solid var(--line);border-radius:6px}
3452
+ .entry{display:grid;grid-template-columns:14ch 9ch minmax(0,1fr);gap:10px;padding:7px 12px;border-bottom:1px solid var(--line-soft)}
3453
+ .overview .entry{padding:6px 0}
3454
+ .when{color:var(--dim);font-size:11.5px}.approx{color:var(--uncertain);margin-left:4px;cursor:help}
3455
+ .source{font:600 9.5px var(--sans);letter-spacing:.12em;text-transform:uppercase;padding-top:2px}
3456
+ ${rules(sourceTones, (source) => `.src-${source}`, color)}
3457
+ .body>div{margin:1px 0}.val{font:600 12.5px var(--mono)}
3458
+ .chips{display:flex;flex-wrap:wrap;gap:5px;align-items:center;margin-top:3px}
3459
+ .chip{display:inline-flex;align-items:baseline;gap:3px;font:11.5px var(--mono);border:1px solid var(--line);border-radius:10px;padding:0 8px;background:var(--panel-2)}
3460
+ .chip.unstable{border-style:dashed}
3461
+ .why{display:grid;gap:12px;max-width:1100px}.why .trail{font:12px var(--mono);color:var(--dim)}
3462
+ .why-sentence{font-size:15px;margin:0}.why-writer .badge{margin-right:4px}
3463
+ .why-conditions{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:4px}.why-conditions .mark{display:inline-block;width:1.4em}
3464
+ .v-runs{border-color:var(--live)}${rules(verdictTones, (state) => `.badge.v-${state}`, color)}
3465
+ .why-link{margin-left:10px;font:600 11px var(--sans)}
3466
+ ${rules(levelTones, (level) => `.tag.lvl-${level}`, (tone) => `color:var(--${tone});border-color:var(--${tone})`)}
3467
+ .recent>button{margin-top:10px}
3468
+
3469
+ .fatal{padding:40px;max-width:720px}.fatal h1{color:var(--bad)}
3470
+ @media (max-width:1100px){.split{grid-template-columns:minmax(0,1fr)}.side{max-height:40vh}.overview{grid-template-columns:minmax(0,1fr)}}
3471
+ `;
3472
+ var html = `<!doctype html>
3473
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
3474
+ <title>tsPLC debug</title><link rel="icon" href="data:,">
3475
+ <script>if(!location.pathname.endsWith("/"))location.replace(location.pathname+"/"+location.search+location.hash)</script>
3476
+ <style>${css}</style></head>
3477
+ <body><p class="empty" style="padding:24px">Loading the debugger…</p>
3478
+ <script type="module" src="./ui.js"></script></body></html>`;
3479
+
3480
+ // packages/debug/src/ui/success-cache.ts
3481
+ var cacheSuccess = (load) => {
3482
+ let loaded;
3483
+ return () => {
3484
+ loaded ??= load().catch((error) => {
3485
+ loaded = undefined;
3486
+ throw error;
3487
+ });
3488
+ return loaded;
3489
+ };
3490
+ };
3491
+
3492
+ // packages/debug/src/ui/index.ts
3493
+ var build = async () => {
3494
+ const result = await Bun.build({
3495
+ entrypoints: [
3496
+ resolve(dirname3(createRequire(import.meta.url).resolve("@tsplc/debug")), "../src/ui/main.ts")
3497
+ ],
3498
+ target: "browser",
3499
+ conditions: ["bun"],
3500
+ minify: true
3501
+ });
3502
+ const [output] = result.outputs;
3503
+ if (!result.success || !output) {
3504
+ throw new AggregateError(result.logs, "Bundling the debugger UI failed");
3505
+ }
3506
+ return { html, script: await output.text() };
3507
+ };
3508
+ var loadUi = cacheSuccess(build);
3509
+
3510
+ // packages/debug/src/http.ts
3511
+ var heartbeatMs = 5000;
3512
+ var encoder = new TextEncoder;
3513
+ var json2 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
3514
+ var failure = (error, status) => json2({ error }, status);
3515
+ var list = (value) => (value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
3516
+ var interest = (search) => {
3517
+ const jobs = list(search.get("jobs")).map(Number);
3518
+ if (!jobs.every(Number.isInteger)) {
3519
+ throw new DebugError("jobs must be job ids", 400);
3520
+ }
3521
+ const slots = list(search.get("slots")).map(Number);
3522
+ if (!slots.every(Number.isInteger)) {
3523
+ throw new DebugError("slots must be writer indexes", 400);
3524
+ }
3525
+ return {
3526
+ watch: list(search.get("watch")),
3527
+ jobs,
3528
+ health: list(search.get("health")),
3529
+ devices: list(search.get("devices")),
3530
+ clocks: list(search.get("clocks")),
3531
+ slots
3532
+ };
3533
+ };
3534
+ var timelineQuery = (search) => {
3535
+ const after = search.get("after");
3536
+ if (after === null) {
3537
+ const since = search.get("since");
3538
+ return since === null ? {} : { since };
3539
+ }
3540
+ if (!isTimelineCursor(after)) {
3541
+ throw new DebugError("after must be a timeline cursor", 400);
3542
+ }
3543
+ return { after };
3544
+ };
3545
+ var explainedPath = (search) => {
3546
+ const path = search.get("path");
3547
+ if (!path) {
3548
+ throw new DebugError("path must name the path to explain", 400);
3549
+ }
3550
+ return path;
3551
+ };
3552
+ var stream = (debug, { watch, clocks, slots, ...shown }) => {
3553
+ debug.paths.expand(watch);
3554
+ let stop = () => {};
3555
+ return new Response(new ReadableStream({
3556
+ start: (controller) => {
3557
+ let open = true;
3558
+ const write = (text) => {
3559
+ if (open) {
3560
+ controller.enqueue(encoder.encode(text));
3561
+ }
3562
+ };
3563
+ const send = ({ name, data }) => write(`event: ${name}
3564
+ data: ${JSON.stringify(data)}
3565
+
3566
+ `);
3567
+ send({ name: "session", data: debug.session() });
3568
+ const unsubscribe = debug.subscribe(send);
3569
+ const unwatch = debug.watch(watch, (sample) => send({ name: "sample", data: sample }), { clocks, slots });
3570
+ const unshow = debug.show(shown);
3571
+ const heartbeat = setInterval(() => write(`: keepalive
3572
+
3573
+ `), heartbeatMs);
3574
+ stop = () => {
3575
+ open = false;
3576
+ clearInterval(heartbeat);
3577
+ unsubscribe();
3578
+ unwatch();
3579
+ unshow();
3580
+ };
3581
+ },
3582
+ cancel: () => stop()
3583
+ }), {
3584
+ headers: {
3585
+ "Content-Type": "text/event-stream",
3586
+ "Cache-Control": "no-store"
3587
+ }
3588
+ });
3589
+ };
3590
+ var createDebugHandler = (debug, log) => async (request, route) => {
3591
+ const { searchParams } = new URL(request.url);
3592
+ const key = `${request.method} ${route}`;
3593
+ try {
3594
+ switch (key) {
3595
+ case "GET /":
3596
+ return new Response((await loadUi()).html, {
3597
+ headers: { "Content-Type": "text/html; charset=utf-8" }
3598
+ });
3599
+ case "GET /ui.js":
3600
+ return new Response((await loadUi()).script, {
3601
+ headers: { "Content-Type": "text/javascript; charset=utf-8" }
3602
+ });
3603
+ case "GET /api/session":
3604
+ return json2(debug.session());
3605
+ case "GET /api/manifest":
3606
+ return json2(debug.manifest);
3607
+ case "GET /api/stream":
3608
+ return stream(debug, interest(searchParams));
3609
+ case "GET /api/values":
3610
+ return json2(await debug.values(list(searchParams.get("paths"))));
3611
+ case "GET /api/jobs":
3612
+ return json2(debug.jobs());
3613
+ case "GET /api/hardware":
3614
+ return json2(debug.hardware());
3615
+ case "GET /api/timeline":
3616
+ return json2(debug.timeline(timelineQuery(searchParams)));
3617
+ case "GET /api/watch":
3618
+ return json2(debug.watchGroups());
3619
+ case "GET /api/explain":
3620
+ return json2(debug.explain(explainedPath(searchParams)));
3621
+ case "GET /api/explain-file": {
3622
+ const loaded = debug.explanationFile();
3623
+ return new Response(loaded.text, {
3624
+ headers: {
3625
+ "Content-Type": "application/json",
3626
+ ETag: `"${loaded.sha256}"`,
3627
+ "Cache-Control": "private, max-age=31536000, immutable"
3628
+ }
3629
+ });
3630
+ }
3631
+ case "GET /api/forced":
3632
+ return json2(await debug.forced());
3633
+ case "PUT /api/watch":
3634
+ return json2(await debug.saveWatchGroups(watchGroupsSchema.parse(await request.json())));
3635
+ }
3636
+ return failure(`No route ${key}`, 404);
3637
+ } catch (error) {
3638
+ if (error instanceof DebugError) {
3639
+ return failure(error.message, error.status);
3640
+ }
3641
+ if (error instanceof TooManyMatches || error instanceof SyntaxError) {
3642
+ return failure(error.message, 400);
3643
+ }
3644
+ if (error instanceof z4.ZodError) {
3645
+ return failure(z4.prettifyError(error), 400);
3646
+ }
3647
+ log(`${key} failed: ${error instanceof Error ? error.stack : String(error)}`);
3648
+ return failure("The debugger failed; see its log", 500);
3649
+ }
3650
+ };
3651
+ var serveDebugger = (debug, options) => {
3652
+ const handle = createDebugHandler(debug, options.log);
3653
+ return Bun.serve({
3654
+ hostname: "127.0.0.1",
3655
+ port: options.port,
3656
+ fetch: (request) => {
3657
+ const host = request.headers.get("host")?.replace(/:\d+$/, "");
3658
+ if (host !== "127.0.0.1" && host !== "localhost") {
3659
+ return failure("Use http://127.0.0.1 or http://localhost", 403);
3660
+ }
3661
+ return handle(request, new URL(request.url).pathname);
3662
+ }
3663
+ });
3664
+ };
3665
+ // packages/debug/src/login.ts
3666
+ import { sleep as sleep2 } from "@tsplc/opcua";
3667
+
3668
+ // packages/debug/src/login-value.ts
3669
+ import {
3670
+ elementaryType as elementaryType3,
3671
+ isIntegerValued as isIntegerValued3,
3672
+ millisecondsPerDay,
3673
+ nanosecondsPerMillisecond as nanosecondsPerMillisecond3,
3674
+ secondsPerDay,
3675
+ stringType
3676
+ } from "@tsplc/iec";
3677
+ import {
3678
+ integerLiteral,
3679
+ temporalPrefixes,
3680
+ unescapeString
3681
+ } from "@tsplc/iec/st";
3682
+ var booleans = {
3683
+ TRUE: true,
3684
+ FALSE: false,
3685
+ "1": true,
3686
+ "0": false
3687
+ };
3688
+ var millisecondsPerSecond = Number(millisecondsPerDay / secondsPerDay);
3689
+ var timeUnits = {
3690
+ d: Number(millisecondsPerDay),
3691
+ h: 3600 * millisecondsPerSecond,
3692
+ m: 60 * millisecondsPerSecond,
3693
+ s: millisecondsPerSecond,
3694
+ ms: 1,
3695
+ us: 0.001,
3696
+ ns: 1 / Number(nanosecondsPerMillisecond3)
3697
+ };
3698
+ var durationPrefixes = [...temporalPrefixes].flatMap(([prefix, type]) => type.family === "duration" ? [prefix] : []).join("|");
3699
+ var durationLiteral = new RegExp(`^(?:${durationPrefixes})#(-?)(.+)$`, "i");
3700
+ var typePrefix = new RegExp(`^(?!(?:${durationPrefixes})#)[a-z_]+#(?=.)`, "i");
3701
+ var withoutTypePrefix = (text) => text.replace(typePrefix, "");
3702
+ var integer = (text) => {
3703
+ const value = integerLiteral(text);
3704
+ return value === undefined ? undefined : encodeConstant({ kind: "integer", value });
3705
+ };
3706
+ var real = (text) => {
3707
+ const number = Number(text);
3708
+ return text !== "" && !Number.isNaN(number) ? number : undefined;
3709
+ };
3710
+ var duration = (text) => {
3711
+ const [, sign, body] = durationLiteral.exec(text) ?? [];
3712
+ if (body === undefined) {
3713
+ return;
3714
+ }
3715
+ const units = body.replaceAll("_", "");
3716
+ const parts = [...units.matchAll(/(\d+(?:\.\d+)?)(ms|us|ns|d|h|m|s)/gi)];
3717
+ if (parts.map(([part]) => part).join("") !== units) {
3718
+ return;
3719
+ }
3720
+ const ms = parts.reduce((total, [, amount, unit]) => {
3721
+ const factor = unit === undefined ? undefined : timeUnits[unit.toLowerCase()];
3722
+ return total === undefined || factor === undefined ? undefined : total + Number(amount) * factor;
3723
+ }, 0);
3724
+ return ms !== undefined && sign ? -ms : ms;
3725
+ };
3726
+ var quoted = (text, wide) => {
3727
+ const [, , body] = /^(['"])(.*)\1$/s.exec(text) ?? [];
3728
+ return body === undefined ? undefined : unescapeString(body, { wide });
3729
+ };
3730
+ var enumValue = (type, text) => {
3731
+ const number = integer(text);
3732
+ if (typeof number === "number") {
3733
+ return number;
3734
+ }
3735
+ const [, name, value] = /^(?:\w+\.)*(\w+)(?:\s*\((-?\d+)\))?$/.exec(text) ?? [];
3736
+ if (name === undefined) {
3737
+ return;
3738
+ }
3739
+ return type.members[name] ?? (value === undefined ? name : Number(value));
3740
+ };
3741
+ var arrayValue = (type, text) => {
3742
+ const items = text.replace(/^\[/, "").replace(/\]$/, "").trim();
3743
+ if (!items) {
3744
+ return [];
3745
+ }
3746
+ const values = items.split(/\s*,\s*/).map((item) => scalarValue(type.element, item));
3747
+ return values.length === type.length && values.every((value) => value !== undefined) ? values : undefined;
3748
+ };
3749
+ var scalarValue = (iec, text) => {
3750
+ const untyped = withoutTypePrefix(text);
3751
+ const name = iec.toUpperCase();
3752
+ const type = elementaryType3(name);
3753
+ if (isIntegerValued3(type)) {
3754
+ return integer(untyped);
3755
+ }
3756
+ switch (type?.family) {
3757
+ case "bool":
3758
+ return booleans[untyped.toUpperCase()];
3759
+ case "real":
3760
+ return real(untyped);
3761
+ case "duration":
3762
+ return duration(text);
3763
+ case "string":
3764
+ return quoted(text, name === "WSTRING") ?? text;
3765
+ }
3766
+ const sized = stringType(name);
3767
+ return sized ? quoted(text, sized.wide) ?? text : text;
3768
+ };
3769
+ var parseLoginValue = (type, text) => {
3770
+ const trimmed = text.trim();
3771
+ switch (type.kind) {
3772
+ case "enum":
3773
+ return enumValue(type, withoutTypePrefix(trimmed));
3774
+ case "array":
3775
+ return arrayValue(type, withoutTypePrefix(trimmed));
3776
+ case "record":
3777
+ return;
3778
+ case "scalar":
3779
+ return scalarValue(type.iec, trimmed);
3780
+ }
3781
+ };
3782
+
3783
+ // packages/debug/src/login.ts
3784
+ class LoginUnavailable extends Error {
3785
+ constructor(message, options) {
3786
+ super(message, options);
3787
+ this.state = options?.state ?? "unavailable";
3788
+ }
3789
+ state;
3790
+ }
3791
+ var noLogin = "Live values need an engineering login: run `tsplc login`.";
3792
+ var retryMs = 5000;
3793
+ var stalledIntervals = 3;
3794
+ var dueTolerance = 0.5;
3795
+ var typeName = (type) => type.kind === "scalar" ? type.iec : type.kind;
3796
+ var createLoginAdapter = (options) => {
3797
+ const samplingMs = options.samplingMs ?? 1000;
3798
+ let connection = {
3799
+ state: "connecting",
3800
+ since: new Date().toISOString()
3801
+ };
3802
+ const connectionListeners = new Set;
3803
+ const subscriptions = new Set;
3804
+ const rejected = new Map;
3805
+ const controller = new AbortController;
3806
+ const setConnection = (state, error) => {
3807
+ if (controller.signal.aborted) {
3808
+ return;
3809
+ }
3810
+ if (connection.state === state && connection.error === error) {
3811
+ return;
3812
+ }
3813
+ if (state !== "connected") {
3814
+ rejected.clear();
3815
+ }
3816
+ connection = {
3817
+ state,
3818
+ since: new Date().toISOString(),
3819
+ ...error && { error }
3820
+ };
3821
+ for (const listener of connectionListeners) {
3822
+ listener(connection);
3823
+ }
3824
+ };
3825
+ let reads = 0;
3826
+ const readCall = async (expressions) => {
3827
+ const texts = await options.read(expressions);
3828
+ reads += 1;
3829
+ const read = reads;
3830
+ return Object.fromEntries(Object.entries(texts).map(([target, text]) => [target, { text, read }]));
3831
+ };
3832
+ const split = async (expressions) => {
3833
+ try {
3834
+ return await readCall(expressions);
3835
+ } catch (error) {
3836
+ if (error instanceof LoginUnavailable) {
3837
+ throw error;
3838
+ }
3839
+ const [only, ...others] = expressions;
3840
+ if (only !== undefined && !others.length) {
3841
+ rejected.set(only, errorMessage(error));
3842
+ return {};
3843
+ }
3844
+ const half = Math.ceil(expressions.length / 2);
3845
+ return {
3846
+ ...await split(expressions.slice(0, half)),
3847
+ ...await split(expressions.slice(half))
3848
+ };
3849
+ }
3850
+ };
3851
+ const readText = async (expressions) => {
3852
+ try {
3853
+ return await readCall(expressions);
3854
+ } catch (error) {
3855
+ if (error instanceof LoginUnavailable) {
3856
+ throw error;
3857
+ }
3858
+ await options.read([options.probe]);
3859
+ return split(expressions);
3860
+ }
3861
+ };
3862
+ const readTexts = async (expressions) => {
3863
+ const overdue = setTimeout(() => setConnection("lost", "The engineering login stopped answering"), stalledIntervals * samplingMs);
3864
+ try {
3865
+ const texts = expressions.length ? await readText(expressions) : {};
3866
+ setConnection("connected");
3867
+ return { texts };
3868
+ } catch (error) {
3869
+ setConnection(error instanceof LoginUnavailable ? error.state : "lost", errorMessage(error));
3870
+ return { error: errorMessage(error) };
3871
+ } finally {
3872
+ clearTimeout(overdue);
3873
+ }
3874
+ };
3875
+ const parsedSample = ({ target, type }, returned, receivedAt) => {
3876
+ const text = returned?.text;
3877
+ const value = text === undefined ? undefined : parseLoginValue(type, text);
3878
+ if (value !== undefined && returned) {
3879
+ return {
3880
+ value,
3881
+ quality: "good",
3882
+ status: "Good",
3883
+ receivedAt,
3884
+ read: returned.read
3885
+ };
3886
+ }
3887
+ const reason = text === undefined ? "Not returned by the login" : `Not a ${typeName(type)}`;
3888
+ return {
3889
+ value: text ?? null,
3890
+ quality: "bad",
3891
+ status: rejected.get(target) ?? reason,
3892
+ receivedAt
3893
+ };
3894
+ };
3895
+ const read = async (targets) => {
3896
+ const unique = [
3897
+ ...new Map(targets.map((target) => [target.target, target])).values()
3898
+ ];
3899
+ const result = await readTexts(unique.map(({ target }) => target).filter((target) => !rejected.has(target)));
3900
+ const receivedAt = new Date().toISOString();
3901
+ if ("error" in result) {
3902
+ return new Map(unique.map(({ target }) => [
3903
+ target,
3904
+ {
3905
+ value: null,
3906
+ quality: "unavailable",
3907
+ status: result.error,
3908
+ receivedAt
3909
+ }
3910
+ ]));
3911
+ }
3912
+ return new Map(unique.map((read) => [
3913
+ read.target,
3914
+ parsedSample(read, result.texts[read.target], receivedAt)
3915
+ ]));
3916
+ };
3917
+ const pauseAfter = (tookMs) => {
3918
+ if (connection.state !== "connected" && connection.state !== "connecting") {
3919
+ return retryMs;
3920
+ }
3921
+ return tookMs > samplingMs ? tookMs : samplingMs - tookMs;
3922
+ };
3923
+ const poll = async () => {
3924
+ while (!controller.signal.aborted) {
3925
+ const started = Date.now();
3926
+ const due = [...subscriptions].filter(({ due }) => due <= started + samplingMs * dueTolerance);
3927
+ if (due.length) {
3928
+ for (const subscription of due) {
3929
+ subscription.due = started + subscription.intervalMs;
3930
+ }
3931
+ const stopped = Promise.withResolvers();
3932
+ const stop = () => stopped.resolve();
3933
+ controller.signal.addEventListener("abort", stop, { once: true });
3934
+ const samples = await Promise.race([
3935
+ read(due.flatMap(({ targets }) => targets)),
3936
+ stopped.promise
3937
+ ]).finally(() => controller.signal.removeEventListener("abort", stop));
3938
+ if (!samples || controller.signal.aborted) {
3939
+ break;
3940
+ }
3941
+ for (const subscription of due) {
3942
+ if (subscriptions.has(subscription)) {
3943
+ for (const { target } of subscription.targets) {
3944
+ const sample = samples.get(target);
3945
+ if (sample) {
3946
+ subscription.listener(target, sample);
3947
+ }
3948
+ }
3949
+ }
3950
+ }
3951
+ }
3952
+ await sleep2(pauseAfter(Date.now() - started), controller.signal);
3953
+ }
3954
+ };
3955
+ const running = poll();
3956
+ return {
3957
+ method: "engineering login",
3958
+ endpoint: options.endpoint,
3959
+ samplingMs,
3960
+ connection: () => connection,
3961
+ onConnection: (listener) => {
3962
+ connectionListeners.add(listener);
3963
+ return () => connectionListeners.delete(listener);
3964
+ },
3965
+ read,
3966
+ subscribe: (targets, listener, intervalMs = samplingMs) => {
3967
+ const subscription = { targets, listener, intervalMs, due: 0 };
3968
+ subscriptions.add(subscription);
3969
+ return () => subscriptions.delete(subscription);
3970
+ },
3971
+ close: async () => {
3972
+ controller.abort();
3973
+ subscriptions.clear();
3974
+ connectionListeners.clear();
3975
+ await running;
3976
+ }
3977
+ };
3978
+ };
3979
+ var loginReader = (manifest, login) => ({
3980
+ adapter: createLoginAdapter({
3981
+ read: login.read,
3982
+ probe: manifest.build.target,
3983
+ endpoint: login.endpoint
3984
+ }),
3985
+ forced: async () => {
3986
+ const status = await login.status();
3987
+ return status && "forced" in status ? status.forced : null;
3988
+ }
3989
+ });
3990
+ // packages/debug/src/opcua.ts
3991
+ import {
3992
+ createMonitor,
3993
+ monitorConnection,
3994
+ monitorPassword
3995
+ } from "@tsplc/opcua";
3996
+ var opcUaConnection = (monitor, options) => monitorConnection(monitor, {
3997
+ root: options.root,
3998
+ password: monitorPassword(monitor, options.env)
3999
+ });
4000
+ var createOpcUaAdapter = (options) => {
4001
+ const monitor = createMonitor(options);
4002
+ const controller = new AbortController;
4003
+ const running = monitor.run(controller.signal);
4004
+ const sample = ({ value, quality, status }) => ({
4005
+ value,
4006
+ quality,
4007
+ status,
4008
+ receivedAt: new Date().toISOString()
4009
+ });
4010
+ const names = (targets) => targets.map(({ target }) => target);
4011
+ return {
4012
+ method: "OPC UA",
4013
+ endpoint: options.endpoint,
4014
+ samplingMs: monitor.samplingMs,
4015
+ connection: monitor.status,
4016
+ onConnection: monitor.onStatus,
4017
+ read: async (targets) => new Map(Object.entries(await monitor.read(names(targets))).map(([target, reading]) => [target, sample(reading)])),
4018
+ subscribe: (targets, listener, intervalMs = monitor.samplingMs) => {
4019
+ const latest = new Map;
4020
+ const report = (target, reading) => {
4021
+ latest.set(target, { reading, at: Date.now() });
4022
+ listener(target, sample(reading));
4023
+ };
4024
+ const stop = monitor.watch(names(targets), report);
4025
+ const repeat = setInterval(() => {
4026
+ if (monitor.status().state !== "connected") {
4027
+ return;
4028
+ }
4029
+ const now = Date.now();
4030
+ for (const [target, { reading, at }] of latest) {
4031
+ if (now - at >= intervalMs) {
4032
+ report(target, reading);
4033
+ }
4034
+ }
4035
+ }, intervalMs);
4036
+ return () => {
4037
+ clearInterval(repeat);
4038
+ stop();
4039
+ };
4040
+ },
4041
+ close: async () => {
4042
+ controller.abort();
4043
+ await running;
4044
+ }
4045
+ };
4046
+ };
4047
+ export {
4048
+ DebugError,
4049
+ LoginUnavailable,
4050
+ createDebugHandler,
4051
+ createDebugger,
4052
+ createLoginAdapter,
4053
+ createOpcUaAdapter,
4054
+ createPaths,
4055
+ loadDebugBuild,
4056
+ loadExplanations,
4057
+ loadManifest,
4058
+ loginReader,
4059
+ noLogin,
4060
+ opcUaConnection,
4061
+ serveDebugger,
4062
+ timelineEntries
4063
+ };
4064
+
4065
+ //# debugId=2CB1061E98ACA71064756E2164756E21
4066
+ //# sourceMappingURL=index.js.map