@tsplc/tmp-compiler 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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6558 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16076 -0
  12. package/dist/index.js.map +61 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1078 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,237 @@
1
+ import { readFileSync, realpathSync } from "node:fs";
2
+ import type { PluginBuilder } from "bun";
3
+ import ts from "typescript";
4
+ import { z } from "zod";
5
+
6
+ // The files the compiler and its setup subprocess (capture.ts) exchange: the request names the
7
+ // program's runtime files and the bindings each declares; the graph is what setup built. Setup
8
+ // and the Bun runtime both load the program's modules with a registry of those bindings.
9
+
10
+ /** An arrow or function expression setup may store, and the names it captures from around it. */
11
+ const closureSiteSchema = z.strictObject({
12
+ start: z.number().int().nonnegative(),
13
+ end: z.number().int().nonnegative(),
14
+ captures: z.array(z.string()),
15
+ });
16
+ export type ClosureSite = z.infer<typeof closureSiteSchema>;
17
+
18
+ const bindingNamesSchema = z.strictObject({
19
+ values: z.array(z.string()),
20
+ classes: z.array(z.string()),
21
+ functions: z.array(z.string()),
22
+ });
23
+ export type BindingNames = z.infer<typeof bindingNamesSchema>;
24
+
25
+ export const captureRequestSchema = z.strictObject({
26
+ entry: z.string().nonempty(),
27
+ files: z.array(z.string().nonempty()),
28
+ /** By file, each closure whose creation setup notes, with what it captured. */
29
+ closures: z.record(z.string(), z.array(closureSiteSchema)),
30
+ bindings: z.record(z.string(), bindingNamesSchema),
31
+ /**
32
+ * What each of the program's `env()` calls reads, by name. Only those values: the rest of the
33
+ * environment, secrets the program never reads among it, stays out of this file.
34
+ */
35
+ configuration: z.record(z.string(), z.string()),
36
+ });
37
+ export type CaptureRequest = z.infer<typeof captureRequestSchema>;
38
+
39
+ /** The names a declaration's name binds: itself, or every name in its destructuring pattern. */
40
+ export const boundNames = (name: ts.BindingName): ts.Identifier[] =>
41
+ ts.isIdentifier(name)
42
+ ? [name]
43
+ : name.elements.flatMap((element) =>
44
+ ts.isOmittedExpression(element) ? [] : boundNames(element.name),
45
+ );
46
+
47
+ /** The top-level bindings a module declares: values, classes and functions, arrow functions among them. */
48
+ export const bindingNames = (source: ts.SourceFile): BindingNames => {
49
+ const found: BindingNames = { values: [], classes: [], functions: [] };
50
+ for (const statement of source.statements) {
51
+ if (ts.isVariableStatement(statement)) {
52
+ for (const declaration of statement.declarationList.declarations) {
53
+ // A stored callback names its binding, so a function a variable holds is a function.
54
+ if (
55
+ ts.isIdentifier(declaration.name) &&
56
+ declaration.initializer &&
57
+ (ts.isArrowFunction(declaration.initializer) ||
58
+ ts.isFunctionExpression(declaration.initializer))
59
+ ) {
60
+ found.functions.push(declaration.name.text);
61
+ } else {
62
+ found.values.push(
63
+ ...boundNames(declaration.name).map((name) => name.text),
64
+ );
65
+ }
66
+ }
67
+ } else if (ts.isClassDeclaration(statement) && statement.name) {
68
+ found.classes.push(statement.name.text);
69
+ } else if (
70
+ ts.isFunctionDeclaration(statement) &&
71
+ statement.name &&
72
+ statement.body
73
+ ) {
74
+ found.functions.push(statement.name.text);
75
+ }
76
+ }
77
+ return found;
78
+ };
79
+
80
+ const registryExport = "__tsplcBindings";
81
+
82
+ /**
83
+ * A module's top-level bindings as a host reads them: each value through a getter, so a `let`
84
+ * reads as it is now, and its classes and functions themselves.
85
+ */
86
+ const registrySchema = z.object({
87
+ values: z.record(
88
+ z.string(),
89
+ z.custom<() => unknown>((value) => typeof value === "function"),
90
+ ),
91
+ classes: z.record(z.string(), z.unknown()),
92
+ functions: z.record(z.string(), z.unknown()),
93
+ });
94
+ export type Registry = z.infer<typeof registrySchema>;
95
+
96
+ /** The registry a module loaded through `loadWithBindingRegistry` exports; undefined for any other module. */
97
+ export const bindingRegistry = (
98
+ loaded: Record<string, unknown>,
99
+ ): Registry | undefined => {
100
+ const registry = registrySchema.safeParse(loaded[registryExport]);
101
+ return registry.success ? registry.data : undefined;
102
+ };
103
+
104
+ const withBindingRegistry = (source: string, names: BindingNames) =>
105
+ `${source}\n;export const ${registryExport} = { values: { ${names.values
106
+ .map((name) => `${JSON.stringify(name)}: () => ${name}`)
107
+ .join(", ")} }, classes: { ${names.classes
108
+ .map((name) => `${JSON.stringify(name)}: ${name}`)
109
+ .join(", ")} }, functions: { ${names.functions
110
+ .map((name) => `${JSON.stringify(name)}: ${name}`)
111
+ .join(", ")} } };\n`;
112
+
113
+ const escapeRegExp = (text: string) =>
114
+ text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
115
+
116
+ /**
117
+ * Has Bun load each of `files` with its binding registry: `module` turns the file's source into
118
+ * the source that runs and the bindings it exports.
119
+ */
120
+ export const loadWithBindingRegistry = (
121
+ build: PluginBuilder,
122
+ files: readonly string[],
123
+ module: (loaded: { file: string; source: string }) => {
124
+ source: string;
125
+ bindings: BindingNames;
126
+ },
127
+ ): void => {
128
+ // Bun loads modules by their real path; the compiler may name them through a symlink.
129
+ const named = new Map(files.map((file) => [realpathSync(file), file]));
130
+ for (const [path, file] of named) {
131
+ build.onLoad({ filter: new RegExp(`^${escapeRegExp(path)}$`) }, () => {
132
+ const { source, bindings } = module({
133
+ file,
134
+ source: readFileSync(path, "utf8"),
135
+ });
136
+ return {
137
+ contents: withBindingRegistry(source, bindings),
138
+ loader: path.endsWith(".tsx") ? "tsx" : "ts",
139
+ };
140
+ });
141
+ }
142
+ };
143
+
144
+ const capturedValueSchema = z.discriminatedUnion("kind", [
145
+ z.strictObject({ kind: z.literal("undefined") }),
146
+ // JSON has no NaN or infinity; capture rejects them rather than write null.
147
+ z.strictObject({ kind: z.literal("number"), value: z.number() }),
148
+ z.strictObject({ kind: z.literal("boolean"), value: z.boolean() }),
149
+ z.strictObject({ kind: z.literal("string"), value: z.string() }),
150
+ z.strictObject({
151
+ kind: z.literal("bigint"),
152
+ value: z.string().regex(/^-?\d+$/),
153
+ }),
154
+ z.strictObject({
155
+ kind: z.literal("node"),
156
+ id: z.number().int().nonnegative(),
157
+ }),
158
+ ]);
159
+ export type CapturedValue = z.infer<typeof capturedValueSchema>;
160
+
161
+ /** A captured value that is not an object setup built. */
162
+ export type CapturedPrimitive = Exclude<CapturedValue, { kind: "node" }>;
163
+
164
+ const fieldsSchema = z.record(z.string(), capturedValueSchema);
165
+
166
+ const capturedNodeSchema = z.discriminatedUnion("kind", [
167
+ z.strictObject({ kind: z.literal("object"), fields: fieldsSchema }),
168
+ z.strictObject({
169
+ kind: z.literal("instance"),
170
+ file: z.string(),
171
+ name: z.string(),
172
+ fields: fieldsSchema,
173
+ }),
174
+ z.strictObject({
175
+ kind: z.literal("array"),
176
+ items: z.array(capturedValueSchema),
177
+ }),
178
+ z.strictObject({
179
+ kind: z.literal("function"),
180
+ file: z.string(),
181
+ name: z.string(),
182
+ }),
183
+ z.strictObject({ kind: z.literal("service"), path: z.string() }),
184
+ /** What `tasks.define` or `backgroundTasks.define` returned: a task the PLC runs, which scan code calls through its binding. */
185
+ z.strictObject({ kind: z.literal("task") }),
186
+ /** A function setup made inside another, by where it is written, with the values it captured. */
187
+ z.strictObject({
188
+ kind: z.literal("closure"),
189
+ file: z.string(),
190
+ start: z.number().int().nonnegative(),
191
+ captures: z.array(
192
+ z.strictObject({ name: z.string(), value: capturedValueSchema }),
193
+ ),
194
+ }),
195
+ ]);
196
+ export type CapturedNode = z.infer<typeof capturedNodeSchema>;
197
+
198
+ export const capturedGraphSchema = z
199
+ .strictObject({
200
+ nodes: z.array(capturedNodeSchema),
201
+ /** Every module-level value binding, in module evaluation order. */
202
+ bindings: z.array(
203
+ z.strictObject({
204
+ file: z.string(),
205
+ name: z.string(),
206
+ value: capturedValueSchema,
207
+ }),
208
+ ),
209
+ /** The objects setup passed to `retain`. */
210
+ retained: z.array(z.number().int().nonnegative()),
211
+ })
212
+ .superRefine((graph, context) => {
213
+ const references = [
214
+ ...graph.bindings.map((binding) => binding.value),
215
+ ...graph.nodes.flatMap((node) => {
216
+ if (node.kind === "array") {
217
+ return node.items;
218
+ }
219
+ if (node.kind === "object" || node.kind === "instance") {
220
+ return Object.values(node.fields);
221
+ }
222
+ return [];
223
+ }),
224
+ ];
225
+ for (const id of graph.retained) {
226
+ references.push({ kind: "node", id });
227
+ }
228
+ for (const value of references) {
229
+ if (value.kind === "node" && value.id >= graph.nodes.length) {
230
+ context.addIssue({
231
+ code: "custom",
232
+ message: `Captured value refers to missing node ${value.id}.`,
233
+ });
234
+ }
235
+ }
236
+ });
237
+ export type CapturedGraph = z.infer<typeof capturedGraphSchema>;
@@ -0,0 +1,388 @@
1
+ /**
2
+ * Runs a program's setup code in Bun and writes the object graph it builds: every module binding,
3
+ * and every object, array, class instance and function reachable from them. The compiler runs
4
+ * this in a subprocess (graph.ts), so setup code never shares the compiler's process.
5
+ *
6
+ * Usage: bun capture.ts <request.json> <graph.json>
7
+ */
8
+
9
+ import { readFileSync, realpathSync, writeFileSync } from "node:fs";
10
+ import { nanosecondsPerMillisecond } from "@tsplc/iec";
11
+ import { elementaryValue } from "@tsplc/iec/arithmetic";
12
+ import { plugin } from "bun";
13
+ import { durationScales } from "../intrinsics";
14
+ import { sdkModules, telemetryMethods } from "../sdk";
15
+ import {
16
+ bindingRegistry,
17
+ type CapturedGraph,
18
+ type CapturedNode,
19
+ type CapturedValue,
20
+ type CaptureRequest,
21
+ type ClosureSite,
22
+ captureRequestSchema,
23
+ loadWithBindingRegistry,
24
+ type Registry,
25
+ } from "./capture-protocol";
26
+
27
+ const [, , requestFile, graphFile] = process.argv;
28
+ if (!requestFile || !graphFile) {
29
+ throw new Error("Usage: bun capture.ts <request.json> <graph.json>");
30
+ }
31
+ const request: CaptureRequest = captureRequestSchema.parse(
32
+ JSON.parse(readFileSync(requestFile, "utf8")),
33
+ );
34
+
35
+ const servicePath = Symbol("tsplc service path");
36
+ /** A service client: any property is a deeper procedure path, and its identity names that path. */
37
+ const service = (path: readonly string[]): unknown =>
38
+ new Proxy(function serviceProcedure() {}, {
39
+ get: (_, key) =>
40
+ key === servicePath ? path.join(".") : service([...path, String(key)]),
41
+ apply: () => {
42
+ throw new Error(`Setup code called the PLC service ${path.join(".")}.`);
43
+ },
44
+ });
45
+
46
+ const taskMark = Symbol("tsplc task");
47
+ /** A task `define` made: scan code starts and reads it, so setup may only store it. */
48
+ const task = (): unknown =>
49
+ Object.assign(
50
+ () => {
51
+ throw new Error("Setup code started a PLC task.");
52
+ },
53
+ { [taskMark]: true },
54
+ );
55
+
56
+ /** Objects setup passed to `retain`. A retained primitive has no identity; the compiler finds those in the source. */
57
+ const retainedObjects = new Set<object>();
58
+
59
+ const unsupported = (name: string) => (): never => {
60
+ throw new Error(`${name} cannot run during PLC setup.`);
61
+ };
62
+
63
+ /** A class setup can import, but not construct. */
64
+ const unsupportedClass = (name: string) =>
65
+ class {
66
+ constructor() {
67
+ throw new Error(`${name} cannot run during PLC setup.`);
68
+ }
69
+ };
70
+
71
+ /** A TIME constructor: setup holds a duration as milliseconds. */
72
+ const duration = (name: string) => {
73
+ const scale = durationScales.get(name);
74
+ if (scale === undefined) {
75
+ throw new Error(`The SDK has no duration ${name}.`);
76
+ }
77
+ return (value: number): number =>
78
+ value * Number(scale / nanosecondsPerMillisecond);
79
+ };
80
+
81
+ /** A stub for each value a declaration file exports; its brand symbols exist only as types. */
82
+ type Stubs<Module> = Record<
83
+ Exclude<keyof Module, "timeBrand" | "calendarBrand" | "textBrand">,
84
+ unknown
85
+ >;
86
+
87
+ /** The SDK's modules as setup runs them, by the specifier a program imports each by. */
88
+ const setupSdk: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
89
+ // Setup runs before the first scan, so the clock reads 0 there.
90
+ [sdkModules.clock]: {
91
+ now: () => 0,
92
+ } satisfies typeof import("../../../types/clock"),
93
+ // Records describe scans, so setup has none to make.
94
+ [sdkModules.telemetry]: {
95
+ telemetry: Object.fromEntries(
96
+ telemetryMethods.map((name) => [name, unsupported(`telemetry.${name}`)]),
97
+ ),
98
+ onTelemetry: () => () => {},
99
+ } satisfies Stubs<typeof import("../../../types/telemetry")>,
100
+ // Retention belongs to storage, so setup notes each object it retains for the compiler. What
101
+ // persists is a whole module binding, which the compiler finds in the source.
102
+ [sdkModules.retain]: {
103
+ retain: <T>(value: T): T => {
104
+ if (typeof value === "object" && value !== null) {
105
+ retainedObjects.add(value);
106
+ }
107
+ return value;
108
+ },
109
+ persist: <T>(value: T): T => value,
110
+ } satisfies typeof import("../../../types/retain"),
111
+ // The SDK's types module has no runtime of its own; a module importing a time constructor still loads.
112
+ [sdkModules.types]: {
113
+ ...elementaryValue,
114
+ ms: duration("ms"),
115
+ seconds: duration("seconds"),
116
+ minutes: duration("minutes"),
117
+ trunc: Math.trunc,
118
+ expt: Math.pow,
119
+ exact: unsupported("exact"),
120
+ wrap: unsupported("wrap"),
121
+ saturate: unsupported("saturate"),
122
+ wrapAdd: unsupported("wrapAdd"),
123
+ wrapSubtract: unsupported("wrapSubtract"),
124
+ wrapMultiply: unsupported("wrapMultiply"),
125
+ saturatingAdd: unsupported("saturatingAdd"),
126
+ saturatingSubtract: unsupported("saturatingSubtract"),
127
+ saturatingMultiply: unsupported("saturatingMultiply"),
128
+ div: unsupported("div"),
129
+ defaultValue: unsupported("defaultValue"),
130
+ copy: unsupported("copy"),
131
+ entries: unsupported("entries"),
132
+ ref: unsupported("ref"),
133
+ retain: unsupported("retain"),
134
+ persist: unsupported("persist"),
135
+ timeToMilliseconds: unsupported("timeToMilliseconds"),
136
+ // Setup holds a calendar value as the text it was written in, which the compiler checks.
137
+ date: (value: string): string => value,
138
+ timeOfDay: (value: string): string => value,
139
+ dateAndTime: (value: string): string => value,
140
+ FunctionBlock: unsupportedClass("FunctionBlock"),
141
+ Blinker: unsupportedClass("Blinker"),
142
+ OnDelayTimer: unsupportedClass("OnDelayTimer"),
143
+ OffDelayTimer: unsupportedClass("OffDelayTimer"),
144
+ PulseTimer: unsupportedClass("PulseTimer"),
145
+ RisingEdge: unsupportedClass("RisingEdge"),
146
+ FallingEdge: unsupportedClass("FallingEdge"),
147
+ UpCounter: unsupportedClass("UpCounter"),
148
+ DownCounter: unsupportedClass("DownCounter"),
149
+ UpDownCounter: unsupportedClass("UpDownCounter"),
150
+ } satisfies Stubs<typeof import("../../../types/index")>,
151
+ [sdkModules.async]: {
152
+ createServiceClient: () => service([]),
153
+ backgroundTasks: { define: task },
154
+ tasks: { define: task },
155
+ cooperativeTasks: { define: unsupported("cooperativeTasks.define") },
156
+ fetch: unsupported("fetch"),
157
+ sleep: unsupported("sleep"),
158
+ cancelAsync: unsupported("cancelAsync"),
159
+ asyncDiagnostics: unsupported("asyncDiagnostics"),
160
+ errorCode: unsupported("errorCode"),
161
+ opcuaCall: unsupported("opcuaCall"),
162
+ } satisfies Stubs<typeof import("../../../types/async")>,
163
+ // The compiler resolved each configuration read before setup, from the build's environment.
164
+ [sdkModules.config]: {
165
+ env: (name: string): string => {
166
+ const value = request.configuration[name];
167
+ if (value === undefined) {
168
+ throw new Error(`env cannot read ${name} during PLC setup.`);
169
+ }
170
+ return value;
171
+ },
172
+ } satisfies Stubs<typeof import("../../../types/config")>,
173
+ };
174
+
175
+ plugin({
176
+ name: "tsplc-capture",
177
+ setup(build) {
178
+ loadWithBindingRegistry(build, request.files, ({ file, source }) => {
179
+ const bindings = request.bindings[file];
180
+ if (!bindings) {
181
+ throw new Error(`The capture request names no bindings of ${file}.`);
182
+ }
183
+ return {
184
+ source: withClosureNotes(source, file, request.closures[file] ?? []),
185
+ bindings,
186
+ };
187
+ });
188
+ for (const [specifier, exports] of Object.entries(setupSdk)) {
189
+ build.module(specifier, () => ({ exports, loader: "object" }));
190
+ }
191
+ },
192
+ });
193
+
194
+ /** Closures setup made, with where each is written and a reader of what it captured. */
195
+ const closures = new Map<
196
+ unknown,
197
+ { file: string; start: number; names: string[]; captured: () => unknown[] }
198
+ >();
199
+ Object.assign(globalThis, {
200
+ __tsplcClosure: (
201
+ file: string,
202
+ start: number,
203
+ names: string[],
204
+ made: unknown,
205
+ captured: () => unknown[],
206
+ ) => {
207
+ closures.set(made, { file, start, names, captured });
208
+ return made;
209
+ },
210
+ });
211
+
212
+ /**
213
+ * Wraps each closure in the source so making it notes it. The wrapper keeps the expression's value,
214
+ * and its reader is an arrow beside it, so it reads the same variables and `this`.
215
+ */
216
+ const withClosureNotes = (
217
+ text: string,
218
+ file: string,
219
+ sites: readonly ClosureSite[],
220
+ ): string => {
221
+ const inserts = sites.flatMap((site) => [
222
+ {
223
+ at: site.start,
224
+ order: 1,
225
+ text: `globalThis.__tsplcClosure(${JSON.stringify(file)}, ${site.start}, ${JSON.stringify(site.captures)}, (`,
226
+ },
227
+ {
228
+ at: site.end,
229
+ order: 0,
230
+ text: `), () => [${site.captures.join(", ")}])`,
231
+ },
232
+ ]);
233
+ // At one offset, a closing wrapper goes before an opening one.
234
+ inserts.sort((left, right) => right.at - left.at || left.order - right.order);
235
+ return inserts.reduce(
236
+ (result, insert) =>
237
+ result.slice(0, insert.at) + insert.text + result.slice(insert.at),
238
+ text,
239
+ );
240
+ };
241
+ const modules = new Map<string, Registry>();
242
+ for (const file of [
243
+ request.entry,
244
+ ...request.files.filter((file) => file !== request.entry),
245
+ ]) {
246
+ const registry = bindingRegistry(await import(realpathSync(file)));
247
+ if (!registry) {
248
+ throw new Error(`${file} loaded without its bindings.`);
249
+ }
250
+ modules.set(file, registry);
251
+ }
252
+
253
+ const classes = new Map<unknown, { file: string; name: string }>();
254
+ const functions = new Map<unknown, { file: string; name: string }>();
255
+ for (const [file, registry] of modules) {
256
+ for (const [name, value] of Object.entries(registry.classes)) {
257
+ classes.set(value, { file, name });
258
+ }
259
+ for (const [name, value] of Object.entries(registry.functions)) {
260
+ functions.set(value, { file, name });
261
+ }
262
+ }
263
+
264
+ const nodes: CapturedNode[] = [];
265
+ const ids = new Map<object, number>();
266
+ const capture = (value: unknown, where: string): CapturedValue => {
267
+ // null is the PLC's one empty value, as undefined is.
268
+ if (value === undefined || value === null) {
269
+ return { kind: "undefined" };
270
+ }
271
+ if (typeof value === "number") {
272
+ if (!Number.isFinite(value)) {
273
+ throw new Error(`${where}: ${value} has no PLC value.`);
274
+ }
275
+ return { kind: "number", value };
276
+ }
277
+ if (typeof value === "boolean") {
278
+ return { kind: "boolean", value };
279
+ }
280
+ if (typeof value === "string") {
281
+ return { kind: "string", value };
282
+ }
283
+ if (typeof value === "bigint") {
284
+ return { kind: "bigint", value: String(value) };
285
+ }
286
+ if (typeof value !== "object" && typeof value !== "function") {
287
+ throw new Error(`${where}: a ${typeof value} has no PLC value.`);
288
+ }
289
+ const known = ids.get(value);
290
+ if (known !== undefined) {
291
+ return { kind: "node", id: known };
292
+ }
293
+ const id = nodes.length;
294
+ ids.set(value, id);
295
+ nodes.push({ kind: "object", fields: {} });
296
+ if (typeof value === "function") {
297
+ const path: unknown = Reflect.get(value, servicePath);
298
+ const named = functions.get(value) ?? classes.get(value);
299
+ const closure = closures.get(value);
300
+ if (typeof path === "string") {
301
+ nodes[id] = { kind: "service", path };
302
+ } else if (Reflect.get(value, taskMark) === true) {
303
+ nodes[id] = { kind: "task" };
304
+ } else if (named) {
305
+ nodes[id] = { kind: "function", ...named };
306
+ } else if (closure) {
307
+ const values = closure.captured();
308
+ nodes[id] = {
309
+ kind: "closure",
310
+ file: closure.file,
311
+ start: closure.start,
312
+ captures: closure.names.map((name, index) => ({
313
+ name,
314
+ value: capture(values[index], `${where} (captured ${name})`),
315
+ })),
316
+ };
317
+ } else {
318
+ throw new Error(
319
+ `${where}: setup stored a function that is not a module-level function, so the PLC can't call it.`,
320
+ );
321
+ }
322
+ return { kind: "node", id };
323
+ }
324
+ if (Array.isArray(value)) {
325
+ nodes[id] = {
326
+ kind: "array",
327
+ items: value.map((item, index) => capture(item, `${where}[${index}]`)),
328
+ };
329
+ return { kind: "node", id };
330
+ }
331
+ const prototype = Object.getPrototypeOf(value);
332
+ const owner =
333
+ prototype === Object.prototype || prototype === null
334
+ ? undefined
335
+ : prototype.constructor;
336
+ const registered = owner && classes.get(owner);
337
+ if (owner && !registered) {
338
+ throw new Error(
339
+ `${where}: a ${owner.name} has no PLC layout; use a class from the program.`,
340
+ );
341
+ }
342
+ const fields: Record<string, CapturedValue> = {};
343
+ for (const [key, field] of Object.entries(value)) {
344
+ fields[key] = capture(field, `${where}.${key}`);
345
+ }
346
+ nodes[id] = registered
347
+ ? { kind: "instance", ...registered, fields }
348
+ : { kind: "object", fields };
349
+ return { kind: "node", id };
350
+ };
351
+
352
+ /** What a binding holds; undefined for one the module never initialized, which reading throws on. */
353
+ const initializedValue = (
354
+ read: () => unknown,
355
+ ): { value: unknown } | undefined => {
356
+ try {
357
+ return { value: read() };
358
+ } catch (cause) {
359
+ if (cause instanceof ReferenceError) {
360
+ return undefined;
361
+ }
362
+ throw cause;
363
+ }
364
+ };
365
+
366
+ const graph: CapturedGraph = { nodes, bindings: [], retained: [] };
367
+ for (const [file, registry] of modules) {
368
+ for (const [name, read] of Object.entries(registry.values)) {
369
+ const initialized = initializedValue(read);
370
+ if (!initialized) {
371
+ continue;
372
+ }
373
+ const { value } = initialized;
374
+ if (
375
+ typeof value === "function" &&
376
+ (functions.has(value) || classes.has(value))
377
+ ) {
378
+ continue;
379
+ }
380
+ graph.bindings.push({ file, name, value: capture(value, name) });
381
+ }
382
+ }
383
+ // A retained object no binding reaches is stored nowhere, so it has no id.
384
+ graph.retained = [...retainedObjects].flatMap((value) => {
385
+ const id = ids.get(value);
386
+ return id === undefined ? [] : [id];
387
+ });
388
+ writeFileSync(graphFile, JSON.stringify(graph));