@tsplc/compiler 0.2.21 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +280 -223
  3. package/dist/cli.js.map +12 -12
  4. package/dist/codesys.js +452 -330
  5. package/dist/codesys.js.map +24 -24
  6. package/dist/elaborate-capture.js +112 -7
  7. package/dist/elaborate-capture.js.map +5 -4
  8. package/dist/index.js +5682 -5407
  9. package/dist/index.js.map +39 -37
  10. package/dist/ir.js +1154 -327
  11. package/dist/ir.js.map +23 -20
  12. package/dist/project.js +68 -29
  13. package/dist/project.js.map +4 -4
  14. package/dist/retain.js +8 -0
  15. package/dist/retain.js.map +10 -0
  16. package/dist/server-check.js +59 -0
  17. package/dist/server-check.js.map +11 -0
  18. package/dist/telemetry.js +19 -10
  19. package/dist/telemetry.js.map +3 -3
  20. package/package.json +33 -12
  21. package/src/codesys/config.ts +1 -1
  22. package/src/codesys/debug.ts +7 -21
  23. package/src/codesys/engineering.ts +8 -12
  24. package/src/codesys/global-lists.ts +19 -17
  25. package/src/codesys/global-names.ts +3 -3
  26. package/src/codesys/http.ts +37 -34
  27. package/src/codesys/index.ts +5 -22
  28. package/src/codesys/instrumentation.ts +3 -1
  29. package/src/codesys/io-paths.ts +2 -1
  30. package/src/codesys/manifest.ts +35 -18
  31. package/src/codesys/numeric.ts +2 -4
  32. package/src/codesys/plan.ts +94 -26
  33. package/src/codesys/publication.ts +4 -3
  34. package/src/codesys/routines.ts +2 -2
  35. package/src/codesys/sources.ts +1 -0
  36. package/src/codesys/st-files.ts +86 -50
  37. package/src/codesys/storage.ts +44 -9
  38. package/src/codesys/task-access.ts +32 -10
  39. package/src/codesys/telemetry.ts +93 -46
  40. package/src/codesys/types.ts +81 -3
  41. package/src/codesys/vendor.ts +1 -1
  42. package/src/frontend/analyzer.ts +15 -14
  43. package/src/frontend/async.ts +23 -21
  44. package/src/frontend/blocks.ts +7 -6
  45. package/src/frontend/configuration.ts +8 -6
  46. package/src/frontend/const-functions.ts +5 -5
  47. package/src/frontend/cooperative.ts +2 -1
  48. package/src/frontend/coroutines.ts +24 -21
  49. package/src/frontend/elaborate/calls.ts +12 -7
  50. package/src/frontend/elaborate/capture-protocol.ts +103 -0
  51. package/src/frontend/elaborate/capture.ts +48 -19
  52. package/src/frontend/elaborate/dialect.ts +2 -2
  53. package/src/frontend/elaborate/expressions.ts +9 -6
  54. package/src/frontend/elaborate/frame.ts +1 -1
  55. package/src/frontend/elaborate/graph.ts +27 -43
  56. package/src/frontend/elaborate/index.ts +52 -17
  57. package/src/frontend/elaborate/initializers.ts +3 -2
  58. package/src/frontend/elaborate/layouts.ts +2 -2
  59. package/src/frontend/elaborate/model.ts +34 -21
  60. package/src/frontend/elaborate/retention.ts +206 -0
  61. package/src/frontend/elaborate/specialize.ts +7 -6
  62. package/src/frontend/elaborate/statements.ts +47 -38
  63. package/src/frontend/elaborate/storage.ts +26 -6
  64. package/src/frontend/exposure.ts +6 -6
  65. package/src/frontend/expressions.ts +26 -25
  66. package/src/frontend/intrinsics.ts +3 -3
  67. package/src/frontend/module-graph.ts +1 -1
  68. package/src/frontend/positions.ts +2 -1
  69. package/src/frontend/promise-chains.ts +1 -0
  70. package/src/frontend/promises.ts +8 -7
  71. package/src/frontend/routines.ts +3 -2
  72. package/src/frontend/sdk.ts +2 -2
  73. package/src/frontend/services.ts +23 -20
  74. package/src/frontend/statements.ts +8 -6
  75. package/src/frontend/tasks.ts +11 -6
  76. package/src/frontend/telemetry.ts +1 -1
  77. package/src/frontend/types.ts +11 -9
  78. package/src/frontend/typescript.ts +92 -42
  79. package/src/index.ts +2 -1
  80. package/src/ir/aggregates.ts +4 -3
  81. package/src/ir/allocation.ts +2 -1
  82. package/src/ir/core-model.ts +38 -8
  83. package/src/ir/declarations.ts +12 -12
  84. package/src/ir/domains.ts +8 -8
  85. package/src/ir/fold.ts +2 -2
  86. package/src/ir/index.ts +53 -40
  87. package/src/ir/job-errors.ts +22 -11
  88. package/src/ir/layouts.ts +3 -2
  89. package/src/ir/link.ts +6 -24
  90. package/src/ir/model.ts +3 -2
  91. package/src/ir/normalization-error.ts +1 -1
  92. package/src/ir/normalize.ts +19 -12
  93. package/src/ir/numeric.ts +1 -0
  94. package/src/{codesys → ir}/operands.ts +2 -6
  95. package/src/ir/ranges.ts +2 -2
  96. package/src/ir/routine.ts +35 -20
  97. package/src/ir/scalars.ts +3 -3
  98. package/src/ir/share.ts +862 -0
  99. package/src/ir/temporaries.ts +236 -0
  100. package/src/ir/types.ts +1 -1
  101. package/src/project/artifacts.ts +12 -2
  102. package/src/project/cli.ts +42 -44
  103. package/src/project/debugger.ts +15 -9
  104. package/src/project/index.ts +1 -1
  105. package/src/project/plant.ts +34 -23
  106. package/src/project/project-commands.ts +92 -73
  107. package/src/project/project.ts +91 -42
  108. package/src/project/release.ts +50 -57
  109. package/src/project/server-check.ts +54 -0
  110. package/src/project/server.ts +60 -41
  111. package/src/project/terminal.ts +3 -1
  112. package/stdlib/retain.ts +2 -0
  113. package/types/globals.d.ts +1 -0
  114. package/types/retain.d.ts +6 -0
  115. package/types/telemetry.d.ts +2 -2
@@ -1,25 +1,27 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
+ import { jobError } from "@tsplc/compiler/ir";
1
3
  import ts from "typescript";
2
- import { importSpecifier } from "./module-graph.ts";
4
+ import type {
5
+ AsyncContext,
6
+ Job,
7
+ MethodMembers,
8
+ Routine,
9
+ SourceRewrite,
10
+ } from "./async.ts";
3
11
  import { staticString } from "./configuration.ts";
4
12
  import { copyValue } from "./cooperative.ts";
13
+ import { importSpecifier } from "./module-graph.ts";
5
14
  import {
6
15
  copied,
16
+ type Edit,
7
17
  edited,
8
18
  from,
9
19
  joined,
10
- mapped,
11
- type Edit,
12
20
  type Mapped,
21
+ mapped,
13
22
  type Part,
14
23
  } from "./positions.ts";
15
24
  import { hasModifier } from "./types.ts";
16
- import type {
17
- AsyncContext,
18
- Job,
19
- MethodMembers,
20
- Routine,
21
- SourceRewrite,
22
- } from "./async.ts";
23
25
 
24
26
  type Step = Job["steps"][number];
25
27
  /** What a step does when the operation it waits on fails; `cancellable` failures may be a cancel. */
@@ -70,6 +72,7 @@ class Coroutine {
70
72
  private readonly method: MethodMembers | undefined;
71
73
  private readonly body: ts.Block;
72
74
  private readonly returnsVoid: boolean;
75
+ // biome-ignore lint/correctness/noUnusedPrivateClassMembers: Read through destructuring in the return emitter.
73
76
  private readonly returnType: string;
74
77
  private readonly resultAggregate: boolean;
75
78
  private readonly fields = new Map<ts.Symbol, Field>();
@@ -176,7 +179,7 @@ class Coroutine {
176
179
  const type = this.text(parameter.type);
177
180
  const aggregate = Boolean(
178
181
  this.context.checker.getTypeFromTypeNode(parameter.type).flags &
179
- ts.TypeFlags.Object,
182
+ ts.TypeFlags.Object,
180
183
  );
181
184
  this.fields.set(this.context.symbol(parameter.name)!, {
182
185
  name: `argument${index}`,
@@ -244,7 +247,7 @@ class Coroutine {
244
247
  type,
245
248
  aggregate: Boolean(
246
249
  this.context.checker.getTypeAtLocation(node).flags &
247
- ts.TypeFlags.Object,
250
+ ts.TypeFlags.Object,
248
251
  ),
249
252
  });
250
253
  }
@@ -384,7 +387,7 @@ class Coroutine {
384
387
  }
385
388
 
386
389
  private failure(error: Part): Mapped {
387
- return mapped`this.error = ${error}; if(this.error === 0)this.error=4; this.busy = false; this.done = true; this.step = 0;`;
390
+ return mapped`this.error = ${error}; if(this.error === 0)this.error=${jobError.malformedResponse}; this.busy = false; this.done = true; this.step = 0;`;
388
391
  }
389
392
 
390
393
  /** An awaited call's result as the target stores it: records and arrays are copied. */
@@ -394,7 +397,7 @@ class Coroutine {
394
397
  value,
395
398
  Boolean(
396
399
  checker.getAwaitedType(checker.getTypeAtLocation(call))!.flags &
397
- ts.TypeFlags.Object,
400
+ ts.TypeFlags.Object,
398
401
  ),
399
402
  );
400
403
  }
@@ -461,13 +464,13 @@ class Coroutine {
461
464
  : undefined;
462
465
  return Boolean(
463
466
  initializer &&
464
- ts.isCallExpression(initializer) &&
465
- ts.isPropertyAccessExpression(initializer.expression) &&
466
- this.context.namesSdk(
467
- initializer.expression.expression,
468
- "backgroundTasks",
469
- ) &&
470
- initializer.expression.name.text === "define",
467
+ ts.isCallExpression(initializer) &&
468
+ ts.isPropertyAccessExpression(initializer.expression) &&
469
+ this.context.namesSdk(
470
+ initializer.expression.expression,
471
+ "backgroundTasks",
472
+ ) &&
473
+ initializer.expression.name.text === "define",
471
474
  );
472
475
  }
473
476
 
@@ -1,27 +1,28 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import ts from "typescript";
2
3
  import {
3
4
  copied,
4
5
  from,
5
6
  joined,
6
- mapped,
7
7
  type Mapped,
8
+ mapped,
8
9
  type Part,
9
10
  } from "../positions.ts";
10
11
  import { declaredBySdk, inSdk, symbolAt } from "../sdk.ts";
12
+ import type { DialectText } from "./dialect.ts";
11
13
  import type {
12
14
  ExpressionSpecializer,
13
15
  SpecializeContext,
14
16
  } from "./expressions.ts";
15
- import type { DialectText } from "./dialect.ts";
16
17
  import type { Frame } from "./frame.ts";
17
18
  import type { EntryImports } from "./imports.ts";
18
19
  import type { Model } from "./model.ts";
19
20
  import type { Storage } from "./storage.ts";
20
21
  import {
21
22
  constant,
23
+ type FunctionLike,
22
24
  repeatable,
23
25
  SpecializeError,
24
- type FunctionLike,
25
26
  type Value,
26
27
  } from "./values.ts";
27
28
 
@@ -463,12 +464,16 @@ export class CallSpecializer {
463
464
  }
464
465
  case "reduce":
465
466
  case "reduceRight": {
466
- const order = name === "reduce" ? items : [...items].reverse();
467
+ const indexed = [...items.entries()];
468
+ const order = name === "reduce" ? indexed : indexed.reverse();
467
469
  let accumulator = node.arguments[1]
468
470
  ? this.expressions.expression(node.arguments[1], frame)
469
- : order.shift()!;
470
- for (const item of order) {
471
- accumulator = this.settle(apply([accumulator, item]), frame);
471
+ : order.shift()![1];
472
+ for (const [index, item] of order) {
473
+ accumulator = this.settle(
474
+ apply([accumulator, item, constant(index)]),
475
+ frame,
476
+ );
472
477
  }
473
478
  return accumulator;
474
479
  }
@@ -0,0 +1,103 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * The files the compiler and its setup subprocess (capture.ts) exchange: the request names the
5
+ * program's runtime files and the bindings each declares; the graph is what setup built.
6
+ */
7
+ export const captureRequestSchema = z.strictObject({
8
+ entry: z.string().nonempty(),
9
+ files: z.array(z.string().nonempty()),
10
+ bindings: z.record(
11
+ z.string(),
12
+ z.strictObject({
13
+ values: z.array(z.string()),
14
+ classes: z.array(z.string()),
15
+ functions: z.array(z.string()),
16
+ }),
17
+ ),
18
+ });
19
+ export type CaptureRequest = z.infer<typeof captureRequestSchema>;
20
+
21
+ const capturedValueSchema = z.discriminatedUnion("kind", [
22
+ z.strictObject({ kind: z.literal("undefined") }),
23
+ // JSON has no NaN or infinity; capture rejects them rather than write null.
24
+ z.strictObject({ kind: z.literal("number"), value: z.number() }),
25
+ z.strictObject({ kind: z.literal("boolean"), value: z.boolean() }),
26
+ z.strictObject({ kind: z.literal("string"), value: z.string() }),
27
+ z.strictObject({
28
+ kind: z.literal("bigint"),
29
+ value: z.string().regex(/^-?\d+$/),
30
+ }),
31
+ z.strictObject({
32
+ kind: z.literal("node"),
33
+ id: z.number().int().nonnegative(),
34
+ }),
35
+ ]);
36
+ export type CapturedValue = z.infer<typeof capturedValueSchema>;
37
+
38
+ /** A captured value that is not an object setup built. */
39
+ export type CapturedPrimitive = Exclude<CapturedValue, { kind: "node" }>;
40
+
41
+ const fieldsSchema = z.record(z.string(), capturedValueSchema);
42
+
43
+ const capturedNodeSchema = z.discriminatedUnion("kind", [
44
+ z.strictObject({ kind: z.literal("object"), fields: fieldsSchema }),
45
+ z.strictObject({
46
+ kind: z.literal("instance"),
47
+ file: z.string(),
48
+ name: z.string(),
49
+ fields: fieldsSchema,
50
+ }),
51
+ z.strictObject({
52
+ kind: z.literal("array"),
53
+ items: z.array(capturedValueSchema),
54
+ }),
55
+ z.strictObject({
56
+ kind: z.literal("function"),
57
+ file: z.string(),
58
+ name: z.string(),
59
+ }),
60
+ z.strictObject({ kind: z.literal("service"), path: z.string() }),
61
+ ]);
62
+ export type CapturedNode = z.infer<typeof capturedNodeSchema>;
63
+
64
+ export const capturedGraphSchema = z
65
+ .strictObject({
66
+ nodes: z.array(capturedNodeSchema),
67
+ /** Every module-level value binding, in module evaluation order. */
68
+ bindings: z.array(
69
+ z.strictObject({
70
+ file: z.string(),
71
+ name: z.string(),
72
+ value: capturedValueSchema,
73
+ }),
74
+ ),
75
+ /** The objects setup passed to `retain`. */
76
+ retained: z.array(z.number().int().nonnegative()),
77
+ })
78
+ .superRefine((graph, context) => {
79
+ const references = [
80
+ ...graph.bindings.map((binding) => binding.value),
81
+ ...graph.nodes.flatMap((node) => {
82
+ if (node.kind === "array") {
83
+ return node.items;
84
+ }
85
+ if (node.kind === "object" || node.kind === "instance") {
86
+ return Object.values(node.fields);
87
+ }
88
+ return [];
89
+ }),
90
+ ];
91
+ for (const id of graph.retained) {
92
+ references.push({ kind: "node", id });
93
+ }
94
+ for (const value of references) {
95
+ if (value.kind === "node" && value.id >= graph.nodes.length) {
96
+ context.addIssue({
97
+ code: "custom",
98
+ message: `Captured value refers to missing node ${value.id}.`,
99
+ });
100
+ }
101
+ }
102
+ });
103
+ export type CapturedGraph = z.infer<typeof capturedGraphSchema>;
@@ -1,21 +1,24 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  /**
2
- * Runs a program's setup code in Bun and prints the object graph it builds: every module binding,
3
+ * Runs a program's setup code in Bun and writes the object graph it builds: every module binding,
3
4
  * and every object, array, class instance and function reachable from them. The compiler runs
4
5
  * this in a subprocess (graph.ts), so setup code never shares the compiler's process.
5
6
  *
6
- * Usage: bun capture.ts <request.json>
7
+ * Usage: bun capture.ts <request.json> <graph.json>
7
8
  */
9
+
10
+ import { readFileSync, realpathSync, writeFileSync } from "node:fs";
8
11
  import { plugin } from "bun";
9
- import { readFileSync, realpathSync } from "node:fs";
10
- import type {
11
- CaptureRequest,
12
- CapturedGraph,
13
- CapturedValue,
14
- CapturedNode,
15
- } from "./graph.ts";
12
+ import {
13
+ type CapturedGraph,
14
+ type CapturedNode,
15
+ type CapturedValue,
16
+ type CaptureRequest,
17
+ captureRequestSchema,
18
+ } from "./capture-protocol.ts";
16
19
 
17
- const request: CaptureRequest = JSON.parse(
18
- readFileSync(process.argv[2]!, "utf8"),
20
+ const request: CaptureRequest = captureRequestSchema.parse(
21
+ JSON.parse(readFileSync(process.argv[2]!, "utf8")),
19
22
  );
20
23
  // Bun loads modules by their real path; the compiler may name them through a symlink.
21
24
  const real = new Map(request.files.map((file) => [realpathSync(file), file]));
@@ -72,6 +75,12 @@ plugin({
72
75
  export const onTelemetry = () => () => {};`,
73
76
  loader: "js",
74
77
  }));
78
+ // Retention belongs to storage, so setup notes each object it retains for the compiler.
79
+ build.module("@tsplc/compiler/retain", () => ({
80
+ contents:
81
+ "export const retain = (value) => globalThis.__tsplcRetain(value);",
82
+ loader: "js",
83
+ }));
75
84
  build.module("@tsplc/compiler/async", () => ({
76
85
  contents: `export const createServiceClient = () => globalThis.__tsplcService([]);
77
86
  const unsupported = (name) => () => { throw new Error(name + " cannot run during PLC setup."); };
@@ -81,6 +90,16 @@ plugin({
81
90
  },
82
91
  });
83
92
  (globalThis as { __tsplcService?: unknown }).__tsplcService = service;
93
+ /** Objects setup passed to `retain`. A retained primitive has no identity; the compiler finds those in the source. */
94
+ const retainedObjects = new Set<object>();
95
+ (globalThis as { __tsplcRetain?: unknown }).__tsplcRetain = (
96
+ value: unknown,
97
+ ) => {
98
+ if (typeof value === "object" && value !== null) {
99
+ retainedObjects.add(value);
100
+ }
101
+ return value;
102
+ };
84
103
 
85
104
  /** The bindings each runtime module exports for capture, as `bindings` above adds them. */
86
105
  interface Registry {
@@ -118,12 +137,17 @@ const capture = (value: unknown, where: string): CapturedValue => {
118
137
  if (value === null) {
119
138
  throw new Error(`${where}: null has no PLC value; use undefined.`);
120
139
  }
121
- if (
122
- typeof value === "number" ||
123
- typeof value === "boolean" ||
124
- typeof value === "string"
125
- ) {
126
- return { kind: typeof value, value } as CapturedValue;
140
+ if (typeof value === "number") {
141
+ if (!Number.isFinite(value)) {
142
+ throw new Error(`${where}: ${value} has no PLC value.`);
143
+ }
144
+ return { kind: "number", value };
145
+ }
146
+ if (typeof value === "boolean") {
147
+ return { kind: "boolean", value };
148
+ }
149
+ if (typeof value === "string") {
150
+ return { kind: "string", value };
127
151
  }
128
152
  if (typeof value === "bigint") {
129
153
  return { kind: "bigint", value: String(value) };
@@ -180,7 +204,7 @@ const capture = (value: unknown, where: string): CapturedValue => {
180
204
  return { kind: "node", id };
181
205
  };
182
206
 
183
- const graph: CapturedGraph = { nodes, bindings: [] };
207
+ const graph: CapturedGraph = { nodes, bindings: [], retained: [] };
184
208
  for (const [file, registry] of modules) {
185
209
  for (const [name, read] of Object.entries(registry.values)) {
186
210
  let value: unknown;
@@ -198,4 +222,9 @@ for (const [file, registry] of modules) {
198
222
  graph.bindings.push({ file, name, value: capture(value, name) });
199
223
  }
200
224
  }
201
- process.stdout.write(JSON.stringify(graph));
225
+ // A retained object no binding reaches is stored nowhere, so it has no id.
226
+ graph.retained = [...retainedObjects].flatMap((value) => {
227
+ const id = ids.get(value);
228
+ return id === undefined ? [] : [id];
229
+ });
230
+ writeFileSync(process.argv[3]!, JSON.stringify(graph));
@@ -1,6 +1,6 @@
1
- import ts from "typescript";
2
1
  import { canAssign, integerType, primitiveTypes } from "@tsplc/compiler/ir";
3
- import { joined, mapped, type Mapped } from "../positions.ts";
2
+ import ts from "typescript";
3
+ import { joined, type Mapped, mapped } from "../positions.ts";
4
4
  import type { EntryImports } from "./imports.ts";
5
5
  import type { Initializers } from "./initializers.ts";
6
6
  import type { Layouts } from "./layouts.ts";
@@ -1,20 +1,21 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import ts from "typescript";
2
- import { from, joined, mapped, type Mapped } from "../positions.ts";
3
+ import { from, joined, type Mapped, mapped } from "../positions.ts";
3
4
  import { unaliased } from "../sdk.ts";
4
5
  import { CallSpecializer } from "./calls.ts";
5
6
  import type { DialectText } from "./dialect.ts";
6
7
  import type { Frame } from "./frame.ts";
7
8
  import type { EntryImports } from "./imports.ts";
8
9
  import type { Initializers } from "./initializers.ts";
9
- import { recordTypes, type Layouts } from "./layouts.ts";
10
+ import { type Layouts, recordTypes } from "./layouts.ts";
10
11
  import type { Model, ModelNode } from "./model.ts";
11
12
  import type { Storage } from "./storage.ts";
12
13
  import {
13
14
  constant,
14
- repeatable,
15
- SpecializeError,
16
15
  type Env,
17
16
  type FunctionLike,
17
+ repeatable,
18
+ SpecializeError,
18
19
  type Value,
19
20
  } from "./values.ts";
20
21
  import { isAssignment } from "./writes.ts";
@@ -484,7 +485,7 @@ export class ExpressionSpecializer {
484
485
  : this.table(node, at);
485
486
  return {
486
487
  kind: "code",
487
- text: mapped`${text}[${this.dialect.code(index, undefined)}]`,
488
+ text: mapped`${text}[${this.dialect.code(index, node.type && recordTypes(node.type)?.key)}]`,
488
489
  declared,
489
490
  place: true,
490
491
  };
@@ -494,9 +495,11 @@ export class ExpressionSpecializer {
494
495
  object.declared &&
495
496
  (this.model.elementType(object.declared) ??
496
497
  recordTypes(object.declared)?.value);
498
+ // A key setup fixed reads as a number; an enum-keyed record takes its enum's member.
499
+ const key = object.declared && recordTypes(object.declared)?.key;
497
500
  return {
498
501
  kind: "code",
499
- text: mapped`${object.text}[${this.dialect.code(index, undefined)}]`,
502
+ text: mapped`${object.text}[${this.dialect.code(index, key)}]`,
500
503
  declared,
501
504
  place: object.place,
502
505
  iec: object.elementIec,
@@ -1,5 +1,5 @@
1
1
  import type ts from "typescript";
2
- import { from, mapped, type Mapped, type Part } from "../positions.ts";
2
+ import { from, type Mapped, mapped, type Part } from "../positions.ts";
3
3
  import { unusedName } from "./layouts.ts";
4
4
  import type { ModelNode } from "./model.ts";
5
5
  import type { Env } from "./values.ts";
@@ -1,48 +1,21 @@
1
- import ts from "typescript";
2
1
  import { spawnSync } from "node:child_process";
3
- import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import {
3
+ existsSync,
4
+ mkdtempSync,
5
+ readFileSync,
6
+ rmSync,
7
+ writeFileSync,
8
+ } from "node:fs";
4
9
  import { tmpdir } from "node:os";
5
10
  import { join } from "node:path";
6
11
  import { fileURLToPath } from "node:url";
7
-
8
- /** What capture.ts needs: the program's runtime files and the bindings each declares. */
9
- export interface CaptureRequest {
10
- entry: string;
11
- files: string[];
12
- bindings: Record<
13
- string,
14
- { values: string[]; classes: string[]; functions: string[] }
15
- >;
16
- }
17
-
18
- export type CapturedValue =
19
- | { kind: "undefined" }
20
- | { kind: "number"; value: number }
21
- | { kind: "boolean"; value: boolean }
22
- | { kind: "string"; value: string }
23
- | { kind: "bigint"; value: string }
24
- | { kind: "node"; id: number };
25
-
26
- /** A captured value that is not an object setup built. */
27
- export type CapturedPrimitive = Exclude<CapturedValue, { kind: "node" }>;
28
-
29
- export type CapturedNode =
30
- | { kind: "object"; fields: Record<string, CapturedValue> }
31
- | {
32
- kind: "instance";
33
- file: string;
34
- name: string;
35
- fields: Record<string, CapturedValue>;
36
- }
37
- | { kind: "array"; items: CapturedValue[] }
38
- | { kind: "function"; file: string; name: string }
39
- | { kind: "service"; path: string };
40
-
41
- export interface CapturedGraph {
42
- nodes: CapturedNode[];
43
- /** Every module-level value binding, in module evaluation order. */
44
- bindings: { file: string; name: string; value: CapturedValue }[];
45
- }
12
+ import ts from "typescript";
13
+ import { z } from "zod";
14
+ import {
15
+ type CapturedGraph,
16
+ type CaptureRequest,
17
+ capturedGraphSchema,
18
+ } from "./capture-protocol.ts";
46
19
 
47
20
  const names = (source: ts.SourceFile) => {
48
21
  const found: CaptureRequest["bindings"][string] = {
@@ -123,8 +96,11 @@ export const captureGraph = (
123
96
  "The elaboration capture script is missing from this build.",
124
97
  );
125
98
  }
126
- const result = spawnSync(process.execPath, [script, file], {
99
+ // The graph has its own file, so setup code is free to write to standard output.
100
+ const output = join(directory, "graph.json");
101
+ const result = spawnSync(process.execPath, [script, file, output], {
127
102
  encoding: "utf8",
103
+ stdio: ["ignore", "ignore", "pipe"],
128
104
  maxBuffer: 256 * 1024 * 1024,
129
105
  });
130
106
  if (result.status !== 0) {
@@ -132,7 +108,15 @@ export const captureGraph = (
132
108
  `Running the program's setup failed:\n${result.stderr.trim()}`,
133
109
  );
134
110
  }
135
- return JSON.parse(result.stdout) as CapturedGraph;
111
+ const graph = capturedGraphSchema.safeParse(
112
+ JSON.parse(readFileSync(output, "utf8")),
113
+ );
114
+ if (!graph.success) {
115
+ throw new Error(
116
+ `The program's setup produced an invalid object graph:\n${z.prettifyError(graph.error)}`,
117
+ );
118
+ }
119
+ return graph.data;
136
120
  } finally {
137
121
  rmSync(directory, { recursive: true, force: true });
138
122
  }