@tsplc/compiler 0.5.13 → 0.5.15

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 (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
@@ -1,53 +1,49 @@
1
- import { readFile } from "node:fs/promises";
1
+ import { readFile, realpath } from "node:fs/promises";
2
2
  import { isAbsolute, join, relative, resolve } from "node:path";
3
- import { errorName } from "@tsplc/compiler/ir";
4
- import { controllerDeviceName, loadTsplcConfig } from "@tsplc/config";
3
+ import { failureCode, failureName, jobError } from "@tsplc/compiler/ir";
4
+ import {
5
+ controllerDeviceName,
6
+ type Environment,
7
+ loadTsplcConfig,
8
+ } from "@tsplc/config";
9
+ import { opcuaPort } from "@tsplc/config/build";
5
10
  import { emittedStDirectory } from "@tsplc/config/project-files";
6
11
  import { debugManifest, debugManifestFile } from "@tsplc/debug/manifest";
12
+ import { nanosecondsPerMillisecond } from "@tsplc/iec";
7
13
  import {
8
14
  type PublishedScalar,
15
+ publishedScalars,
9
16
  servePublishedGlobals,
10
17
  } from "@tsplc/opcua/server";
18
+ import { telemetryPath } from "@tsplc/server/telemetry";
11
19
  import { readDeclarations } from "@tsplc/typegen/declarations";
12
20
  import { now } from "../../stdlib/clock";
13
- import { clamp, max, min } from "../../stdlib/math";
14
- import { retain } from "../../stdlib/retain";
21
+ import { plcTime } from "../../stdlib/plc-time";
22
+ import { persist, retain } from "../../stdlib/retain";
15
23
  import { onTelemetry, telemetry } from "../../stdlib/telemetry";
16
- import {
17
- createAsync,
18
- type HttpSettings,
19
- oneLaunchAtATime,
20
- unsupported,
21
- } from "./async";
24
+ import { createAsync, oneLaunchAtATime } from "./async";
22
25
  import { type Launch, runtimeDirectory, runtimeFiles } from "./launch";
23
- import { loadProgram } from "./program";
26
+ import { loadProgram, type SdkModule } from "./program";
24
27
  import { createRetention } from "./retain";
28
+ import { runtimeSettings } from "./settings";
25
29
  import { createStorage } from "./storage";
26
- import { plcGlobals, scalarPaths } from "./symbols";
30
+ import { plcGlobals } from "./symbols";
27
31
  import { createTelemetry } from "./telemetry";
28
32
  import { httpTransport, opcuaSlots, readServiceChannels } from "./transport";
29
33
 
30
34
  /** Where the runtime publishes OPC UA: the local CODESYS runtime's address and port. */
31
- export const runtimeEndpoint = { host: "127.0.0.1", port: 4840 } as const;
35
+ export const runtimeEndpoint = { host: "127.0.0.1", port: opcuaPort } as const;
32
36
 
33
37
  export interface RuntimeOptions {
34
38
  launch: Launch;
35
39
  /** The environment the config's variables resolve in, before the launch's target's values. */
36
- environment: Readonly<Record<string, string | undefined>>;
40
+ environment: Environment;
37
41
  /** Where OPC UA listens; `runtimeEndpoint` unless a test picks a free port. */
38
42
  port: number;
39
43
  log: (line: string) => void;
40
44
  }
41
45
 
42
- /** What an exception record calls a failure: a job error's meaning, or a thrown Error's message. */
43
- const failureName = (reason: unknown) => {
44
- if (typeof reason === "number") {
45
- return errorName(reason);
46
- }
47
- return reason instanceof Error ? reason.message : String(reason);
48
- };
49
-
50
- /** A telemetry record's `file:line`, relative to the project rather than to this process's directory. */
46
+ /** A telemetry record's `file:line`, relative to the project's real directory rather than to the working directory. */
51
47
  const projectSource = (root: string, source: unknown) => {
52
48
  if (typeof source !== "string" || !source) {
53
49
  return "";
@@ -81,20 +77,7 @@ export const startRuntime = async (options: RuntimeOptions) => {
81
77
  );
82
78
  const globals = plcGlobals(await readDeclarations(st));
83
79
 
84
- const http: HttpSettings = {
85
- tokens: new Map(
86
- (config.codesys?.http?.credentials ?? []).flatMap(
87
- ({ originEnv, bearerTokenEnv }) => {
88
- const origin = URL.parse(env[originEnv] ?? "")?.origin;
89
- const token = env[bearerTokenEnv];
90
- return origin && token ? [[origin, token] as const] : [];
91
- },
92
- ),
93
- ),
94
- timeoutMs: config.codesys?.http?.timeoutMs ?? 2000,
95
- };
96
- const baseUrlEnv = config.server?.baseUrlEnv;
97
- const baseUrl = (baseUrlEnv && env[baseUrlEnv]?.replace(/\/+$/, "")) || null;
80
+ const { http, baseUrl, telemetryCapacity } = runtimeSettings(config, env);
98
81
  // Over OPC UA the app server's gateway serves the slots this process publishes, as it serves a PLC's.
99
82
  const slots =
100
83
  config.server?.transport === "opcua"
@@ -109,22 +92,23 @@ export const startRuntime = async (options: RuntimeOptions) => {
109
92
  const diagnostics = { count: 0, lastError: 0 };
110
93
  const records = createTelemetry({
111
94
  build: manifest.build.id,
112
- capacity: config.telemetry?.capacity ?? 64,
113
- post: transport ? (body) => transport.call("/tsplc/telemetry", body) : null,
114
- clock: now,
95
+ capacity: telemetryCapacity,
96
+ post: transport ? (body) => transport.call(telemetryPath, body) : null,
97
+ clock: plcTime,
98
+ log,
115
99
  });
100
+ const realRoot = await realpath(root);
116
101
  const stopTelemetry = onTelemetry((record) =>
117
102
  records.record(current.task, {
118
103
  ...record,
119
104
  scan: current.scan,
120
- source: projectSource(root, record.source),
105
+ source: projectSource(realRoot, record.source),
121
106
  }),
122
107
  );
123
108
  const failed = new WeakMap<Promise<unknown>, string>();
124
109
  const unhandled = (reason: unknown, promise: Promise<unknown>) => {
125
- const code = typeof reason === "number" ? reason : 0;
126
- // A cancelled job is not a failure.
127
- if (code === 1) {
110
+ const code = failureCode(reason);
111
+ if (code === jobError.cancelled) {
128
112
  return;
129
113
  }
130
114
  diagnostics.count += 1;
@@ -140,7 +124,7 @@ export const startRuntime = async (options: RuntimeOptions) => {
140
124
  properties: {},
141
125
  source: "",
142
126
  scan: current.scan,
143
- time: Math.max(0, now()),
127
+ time: plcTime(),
144
128
  });
145
129
  if (typeof reason !== "number") {
146
130
  log(`An async call failed and nothing caught it: ${String(reason)}`);
@@ -157,14 +141,20 @@ export const startRuntime = async (options: RuntimeOptions) => {
157
141
  ]),
158
142
  ),
159
143
  sdk: {
160
- "@tsplc/compiler/clock": { now },
161
- "@tsplc/compiler/retain": { retain },
162
- "@tsplc/compiler/telemetry": { telemetry, onTelemetry },
163
- "@tsplc/compiler/math": { min, max, clamp },
144
+ "@tsplc/compiler/clock": { now } satisfies SdkModule<
145
+ typeof import("../../types/clock")
146
+ >,
147
+ "@tsplc/compiler/retain": { persist, retain } satisfies SdkModule<
148
+ typeof import("../../types/retain")
149
+ >,
150
+ "@tsplc/compiler/telemetry": {
151
+ telemetry,
152
+ onTelemetry,
153
+ } satisfies SdkModule<typeof import("../../types/telemetry")>,
164
154
  "@tsplc/compiler/async": createAsync(
165
155
  { http, services: { routes: launch.services, transport } },
166
156
  diagnostics,
167
- ),
157
+ ) satisfies SdkModule<typeof import("../../types/async")>,
168
158
  "@tsplc/compiler/config": {
169
159
  env: (name: string) => {
170
160
  const value = env[name];
@@ -173,14 +163,10 @@ export const startRuntime = async (options: RuntimeOptions) => {
173
163
  }
174
164
  return value;
175
165
  },
176
- },
177
- "@tsplc/compiler/plc": { expose: unsupported("expose") },
166
+ } satisfies SdkModule<typeof import("../../types/config")>,
178
167
  },
179
168
  }).catch((cause: unknown) => {
180
- throw new Error(
181
- "The program failed to load in Bun. The Bun runtime runs plain TypeScript programs (docs/language/plain-typescript.md); the tsPLC dialect's SDK has no Bun implementation.",
182
- { cause },
183
- );
169
+ throw new Error("The program failed to load in Bun.", { cause });
184
170
  });
185
171
  oneLaunchAtATime(program.classes, {
186
172
  scanning: () => current.scanning,
@@ -192,7 +178,7 @@ export const startRuntime = async (options: RuntimeOptions) => {
192
178
  storage.keepStoredValues();
193
179
  const scalars = new Map<string, PublishedScalar>();
194
180
  const bound = (global: (typeof globals.published)[number]) =>
195
- scalarPaths(global).every(({ path }) => {
181
+ publishedScalars(global).every(({ path }) => {
196
182
  const scalar = storage.scalar(path) ?? slots?.scalar(path);
197
183
  if (scalar) {
198
184
  scalars.set(path, scalar);
@@ -253,7 +239,9 @@ export const startRuntime = async (options: RuntimeOptions) => {
253
239
  }
254
240
  };
255
241
  for (const task of tasks) {
256
- const intervalMs = Number(task.schedule.interval.nanoseconds) / 1_000_000;
242
+ const intervalMs =
243
+ Number(task.schedule.interval.nanoseconds) /
244
+ Number(nanosecondsPerMillisecond);
257
245
  const entries = task.programs.flatMap((key) => {
258
246
  const entry = program.programs.get(key);
259
247
  return entry ? [entry] : [];
@@ -310,7 +298,6 @@ export const startRuntime = async (options: RuntimeOptions) => {
310
298
  );
311
299
  return {
312
300
  endpoint: server.endpoint,
313
- /** Stops the tasks and saves the retained globals, then stops serving, whatever the server's sessions do. */
314
301
  stop: async () => {
315
302
  stopTasks();
316
303
  stopTelemetry();
@@ -0,0 +1,27 @@
1
+ import {
2
+ type Environment,
3
+ httpOptionsSchema,
4
+ type ResolvedTsplcConfig,
5
+ serverBaseUrl,
6
+ } from "@tsplc/config";
7
+ import { resolveHttpCredentials, routeBase } from "../codesys/endpoints";
8
+ import { ringSettings } from "../codesys/telemetry-settings";
9
+ import type { HttpSettings } from "./async";
10
+
11
+ /** The runtime's HTTP settings, server URL and telemetry ring, resolved as the PLC build resolves them. */
12
+ export const runtimeSettings = (
13
+ config: ResolvedTsplcConfig,
14
+ env: Environment,
15
+ ) => {
16
+ const httpOptions = config.codesys?.http ?? httpOptionsSchema.parse({});
17
+ const http: HttpSettings = {
18
+ credentials: resolveHttpCredentials(httpOptions.credentials, env),
19
+ timeoutMs: httpOptions.timeoutMs,
20
+ };
21
+ return {
22
+ http,
23
+ baseUrl: routeBase(serverBaseUrl(config, env) ?? "") || null,
24
+ telemetryCapacity: ringSettings(config.telemetry, config.debug?.trace)
25
+ .capacity,
26
+ };
27
+ };
@@ -1,7 +1,13 @@
1
+ import { optionalRecord } from "@tsplc/compiler/ir";
1
2
  import type { DebugManifest, DebugType } from "@tsplc/debug/manifest";
2
3
  import { typeOf } from "@tsplc/debug/paths";
3
- import { elementaryType } from "@tsplc/iec";
4
- import { isArrayIndexSegment, symbolPathSegments } from "@tsplc/opcua/contract";
4
+ import { elementaryType, fitsNumber, isIntegerValued } from "@tsplc/iec";
5
+ import { applyIntegerPolicy, roundFloat } from "@tsplc/iec/arithmetic";
6
+ import {
7
+ arrayIndex,
8
+ joinPath,
9
+ symbolPathSegments,
10
+ } from "@tsplc/opcua/contract";
5
11
  import type { PublishedScalar, PublishedValue } from "@tsplc/opcua/server";
6
12
 
7
13
  /**
@@ -26,18 +32,17 @@ type ArrayType = Extract<DebugType, { kind: "array" }>;
26
32
  type EnumType = Extract<DebugType, { kind: "enum" }>;
27
33
 
28
34
  const joinSegments = (segments: readonly string[]) =>
29
- segments.reduce((prefix, segment) =>
30
- segment.startsWith("[") ? prefix + segment : `${prefix}.${segment}`,
31
- );
35
+ segments.reduce(joinPath, "");
32
36
 
33
37
  /** The property a TypeScript path segment names: a field, or an index or numeric key without brackets. */
34
- const propertyOf = (segment: string) =>
35
- isArrayIndexSegment(segment) ? segment.slice(1, -1) : segment;
38
+ const propertyOf = (segment: string) => {
39
+ const index = arrayIndex(segment);
40
+ return index === undefined ? segment : String(index);
41
+ };
36
42
 
37
43
  const isObject = (value: unknown): value is Record<string, unknown> =>
38
44
  typeof value === "object" && value !== null;
39
45
 
40
- /** The value at `key` of the object at `parent`; writing through a missing holder does nothing. */
41
46
  const fieldPlace = (parent: Place, key: string): Place => ({
42
47
  get: () => {
43
48
  const holder = parent.get();
@@ -52,36 +57,19 @@ const fieldPlace = (parent: Place, key: string): Place => ({
52
57
  });
53
58
 
54
59
  /**
55
- * `T | undefined` is stored as the record `{ has, value }`, which the compiler names
56
- * `Optional_<T>`; a literal union holds undefined as its enum's `Undefined` member instead.
60
+ * The value field of an optional's record: `T | undefined` is stored as `optionalRecord`; a
61
+ * literal union holds undefined as its enum's `Undefined` member instead.
57
62
  */
58
63
  const optionalValue = (type: RecordType) => {
59
64
  const [has, value, ...rest] = type.fields;
60
- return type.name.startsWith("Optional_") &&
61
- has?.name === "has" &&
62
- value?.name === "value" &&
65
+ return type.name.startsWith(optionalRecord.prefix) &&
66
+ has?.name === optionalRecord.has &&
67
+ value?.name === optionalRecord.value &&
63
68
  !rest.length
64
69
  ? value
65
70
  : undefined;
66
71
  };
67
72
 
68
- const integerWrap = (bits: number, signed: boolean) => {
69
- switch (bits) {
70
- case 8:
71
- return signed
72
- ? (value: number) => (value << 24) >> 24
73
- : (value: number) => value & 0xff;
74
- case 16:
75
- return signed
76
- ? (value: number) => (value << 16) >> 16
77
- : (value: number) => value & 0xffff;
78
- default:
79
- return signed
80
- ? (value: number) => value | 0
81
- : (value: number) => value >>> 0;
82
- }
83
- };
84
-
85
73
  /** `text` cut to at most `capacity` UTF-8 bytes, at a character boundary. */
86
74
  const truncateUtf8 = (text: string, capacity: number) => {
87
75
  if (Buffer.byteLength(text, "utf8") <= capacity) {
@@ -104,7 +92,7 @@ const truncateUtf8 = (text: string, capacity: number) => {
104
92
  * integers wrap to their width, a REAL rounds to single precision and a STRING keeps its first
105
93
  * `capacity` bytes. Undefined for types whose values TypeScript already stores as the PLC does.
106
94
  */
107
- export const storedValue = (
95
+ const storedValue = (
108
96
  type: DebugType,
109
97
  ): ((value: unknown) => unknown) | undefined => {
110
98
  if (type.kind !== "scalar") {
@@ -124,35 +112,32 @@ export const storedValue = (
124
112
  }
125
113
  if (elementary.family === "real") {
126
114
  return elementary.bits === 32
127
- ? (value) => (typeof value === "number" ? Math.fround(value) : value)
115
+ ? (value) =>
116
+ typeof value === "number" ? roundFloat(value, elementary) : value
128
117
  : undefined;
129
118
  }
130
- const integer =
131
- elementary.family === "integer" || elementary.family === "bits";
132
- const signed = elementary.family === "integer" && elementary.signed;
133
119
  if (elementary.family === "duration" && elementary.bits === 32) {
134
120
  return storedValue({ kind: "scalar", iec: "UDINT" });
135
121
  }
136
- if (!integer) {
122
+ if (!isIntegerValued(elementary)) {
137
123
  return undefined;
138
124
  }
139
- if (elementary.bits === 64) {
140
- return (value) => {
141
- if (typeof value !== "bigint") {
142
- return value;
143
- }
144
- return signed ? BigInt.asIntN(64, value) : BigInt.asUintN(64, value);
145
- };
125
+ const wrap = (value: bigint) => applyIntegerPolicy(value, elementary, "wrap");
126
+ if (!fitsNumber(elementary)) {
127
+ return (value) => (typeof value === "bigint" ? wrap(value) : value);
146
128
  }
147
- const wrap = integerWrap(elementary.bits, signed);
148
129
  return (value) =>
149
- typeof value === "number" && Number.isFinite(value) ? wrap(value) : value;
130
+ typeof value === "number" && Number.isFinite(value)
131
+ ? Number(wrap(BigInt(Math.trunc(value))))
132
+ : value;
150
133
  };
151
134
 
152
135
  /** A scalar's PLC value when the program holds nothing there, as for a variant field it lacks. */
153
136
  const scalarDefault = (type: DebugType): Scalar => {
154
137
  if (type.kind === "enum") {
155
- return Math.min(...Object.values(type.members));
138
+ // As the emitted ST initialises an enum (ir's `defaultValue`): its zero member, else its first.
139
+ const values = Object.values(type.members);
140
+ return values.includes(0) ? 0 : (values[0] ?? 0);
156
141
  }
157
142
  if (type.kind !== "scalar") {
158
143
  return 0;
@@ -164,10 +149,7 @@ const scalarDefault = (type: DebugType): Scalar => {
164
149
  if (elementary?.family === "bool") {
165
150
  return false;
166
151
  }
167
- const wide =
168
- (elementary?.family === "integer" || elementary?.family === "bits") &&
169
- elementary.bits === 64;
170
- return wide ? 0n : 0;
152
+ return isIntegerValued(elementary) && !fitsNumber(elementary) ? 0n : 0;
171
153
  };
172
154
 
173
155
  export const createStorage = (
@@ -275,8 +257,8 @@ export const createStorage = (
275
257
  segment: string,
276
258
  ): { type: DebugType; place: Place } | undefined => {
277
259
  const { place } = parent;
278
- if (parent.type.kind === "array" && isArrayIndexSegment(segment)) {
279
- const index = Number(segment.slice(1, -1));
260
+ const index = arrayIndex(segment);
261
+ if (parent.type.kind === "array" && index !== undefined) {
280
262
  const array = parent.type;
281
263
  if (index < array.lower || index >= array.lower + array.length) {
282
264
  return undefined;
@@ -290,7 +272,7 @@ export const createStorage = (
290
272
  return undefined;
291
273
  }
292
274
  const optional = optionalValue(parent.type);
293
- if (optional && segment === "has") {
275
+ if (optional && segment === optionalRecord.has) {
294
276
  return {
295
277
  type: { kind: "scalar", iec: "BOOL" },
296
278
  place: {
@@ -305,7 +287,7 @@ export const createStorage = (
305
287
  },
306
288
  };
307
289
  }
308
- if (optional && segment === "value") {
290
+ if (optional && segment === optionalRecord.value) {
309
291
  return { type: type(optional.type), place };
310
292
  }
311
293
  const field = parent.type.fields.find(
@@ -316,24 +298,24 @@ export const createStorage = (
316
298
  );
317
299
  };
318
300
 
319
- /** The place of a stored root, by its TypeScript path such as `program.diverters`. */
320
- const rootPlace = (path: string): Place | undefined => {
321
- const [name, ...steps] = symbolPathSegments(path);
322
- if (name === undefined || binding(name) === undefined) {
323
- return undefined;
324
- }
325
- const start: Place = {
301
+ /** The place `steps` below the module binding `name`. */
302
+ const placeBelow = (name: string, steps: readonly string[]): Place =>
303
+ steps.reduce<Place>((place, step) => fieldPlace(place, propertyOf(step)), {
326
304
  get: () => binding(name),
327
305
  set: () => {
328
306
  throw new Error(
329
307
  `${name} is a module binding; the runtime can't replace it.`,
330
308
  );
331
309
  },
332
- };
333
- return steps.reduce(
334
- (place, step) => fieldPlace(place, propertyOf(step)),
335
- start,
336
- );
310
+ });
311
+
312
+ /** The place of a stored root, by its TypeScript path such as `program.diverters`. */
313
+ const rootPlace = (path: string): Place | undefined => {
314
+ const [name, ...steps] = symbolPathSegments(path);
315
+ if (name === undefined || binding(name) === undefined) {
316
+ return undefined;
317
+ }
318
+ return placeBelow(name, steps);
337
319
  };
338
320
 
339
321
  const roots = manifest.roots.flatMap((root) => {
@@ -458,17 +440,12 @@ export const createStorage = (
458
440
  for (const root of roots) {
459
441
  const rootType = type(root.type);
460
442
  const [name, ...steps] = symbolPathSegments(root.path);
461
- const holderPath = steps.slice(0, -1);
462
443
  const last = steps.at(-1);
463
444
  if (name === undefined || last === undefined) {
464
- // A module binding itself has no holder to treat; what it holds still does.
465
445
  within(rootType, root.place.get());
466
446
  continue;
467
447
  }
468
- const start: Place = { get: () => binding(name), set: () => {} };
469
- const holder = holderPath
470
- .reduce((place, step) => fieldPlace(place, propertyOf(step)), start)
471
- .get();
448
+ const holder = placeBelow(name, steps.slice(0, -1)).get();
472
449
  if (isObject(holder)) {
473
450
  keep(holder, propertyOf(last), rootType);
474
451
  }
@@ -477,5 +454,3 @@ export const createStorage = (
477
454
 
478
455
  return { scalar, keepStoredValues };
479
456
  };
480
-
481
- export type Storage = ReturnType<typeof createStorage>;
@@ -1,34 +1,12 @@
1
- import { elementaryType } from "@tsplc/iec";
1
+ import { elementaryType, stringTypeText } from "@tsplc/iec";
2
2
  import type { PublishedGlobal, PublishedType } from "@tsplc/opcua/server";
3
- import type {
4
- Declaration,
5
- GlobalList,
6
- TypeReference,
3
+ import {
4
+ type Declaration,
5
+ type GlobalList,
6
+ resolveDeclarations,
7
+ type TypeReference,
7
8
  } from "@tsplc/typegen/declarations";
8
9
 
9
- /** An integer literal of an emitted declaration, such as an array bound or a STRING capacity. */
10
- const integer = (text: string, where: string) => {
11
- if (!/^-?\d+$/.test(text.trim())) {
12
- throw new Error(`${where}: ${text} is not an integer literal.`);
13
- }
14
- return Number(text);
15
- };
16
-
17
- /** An enum's members with their values: a member without one follows the member before it. */
18
- const enumMembers = (declaration: Extract<Declaration, { kind: "enum" }>) => {
19
- const members: { name: string; value: number }[] = [];
20
- for (const member of declaration.members) {
21
- members.push({
22
- name: member.name,
23
- value:
24
- member.value === undefined
25
- ? (members.at(-1)?.value ?? -1) + 1
26
- : integer(member.value, declaration.name),
27
- });
28
- }
29
- return members;
30
- };
31
-
32
10
  /**
33
11
  * The emitted program's globals as CODESYS declares them: the ones a symbol attribute publishes,
34
12
  * with the access it grants, and the retained ones.
@@ -37,21 +15,19 @@ export const plcGlobals = (declarations: {
37
15
  types: readonly Declaration[];
38
16
  globals: readonly GlobalList[];
39
17
  }) => {
40
- const types = new Map(
41
- declarations.types.map((declaration) => [
42
- declaration.name.toUpperCase(),
43
- declaration,
44
- ]),
45
- );
18
+ const resolved = resolveDeclarations(declarations);
46
19
  const resolve = (reference: TypeReference, where: string): PublishedType => {
47
20
  switch (reference.kind) {
48
21
  case "string":
49
22
  return {
50
23
  kind: "scalar",
51
- iec: `${reference.name}(${integer(reference.length, where)})`,
24
+ iec: stringTypeText({
25
+ wide: reference.name === "WSTRING",
26
+ capacity: resolved.integer(reference.length),
27
+ }),
52
28
  };
53
29
  case "array": {
54
- const [dimension, ...more] = reference.dimensions;
30
+ const [dimension, ...more] = resolved.bounds(reference);
55
31
  if (!dimension || more.length) {
56
32
  throw new Error(
57
33
  `${where}: only one-dimensional arrays are published.`,
@@ -59,21 +35,15 @@ export const plcGlobals = (declarations: {
59
35
  }
60
36
  return {
61
37
  kind: "array",
62
- lower: integer(dimension.lower, where),
63
- upper: integer(dimension.upper, where),
38
+ lower: dimension.start,
39
+ upper: dimension.end,
64
40
  element: resolve(reference.element, where),
65
41
  };
66
42
  }
67
- case "named": {
68
- if (elementaryType(reference.name)) {
69
- return { kind: "scalar", iec: reference.name.toUpperCase() };
70
- }
71
- const declaration = types.get(reference.name.toUpperCase());
72
- if (!declaration) {
73
- throw new Error(`${where}: type ${reference.name} is not declared.`);
74
- }
75
- return declared(declaration);
76
- }
43
+ case "named":
44
+ return elementaryType(reference.name)
45
+ ? { kind: "scalar", iec: reference.name.toUpperCase() }
46
+ : declared(resolved.declaration(reference.name));
77
47
  }
78
48
  };
79
49
  const declared = (declaration: Declaration): PublishedType => {
@@ -85,7 +55,7 @@ export const plcGlobals = (declarations: {
85
55
  kind: "enum",
86
56
  name: declaration.name,
87
57
  base: declaration.base,
88
- members: enumMembers(declaration),
58
+ members: resolved.enumMembers(declaration),
89
59
  };
90
60
  case "struct":
91
61
  return {
@@ -125,29 +95,3 @@ export const plcGlobals = (declarations: {
125
95
  ),
126
96
  };
127
97
  };
128
-
129
- /** Every scalar of a global, by symbol path, with its type: each struct member and array element. */
130
- export const scalarPaths = (
131
- global: Pick<PublishedGlobal, "list" | "name" | "type">,
132
- ): { path: string; type: PublishedType }[] => {
133
- const walk = (
134
- path: string,
135
- type: PublishedType,
136
- ): { path: string; type: PublishedType }[] => {
137
- switch (type.kind) {
138
- case "scalar":
139
- case "enum":
140
- return [{ path, type }];
141
- case "struct":
142
- return type.members.flatMap((member) =>
143
- walk(`${path}.${member.name}`, member.type),
144
- );
145
- case "array":
146
- return Array.from(
147
- { length: type.upper - type.lower + 1 },
148
- (_, offset) => walk(`${path}[${type.lower + offset}]`, type.element),
149
- ).flat();
150
- }
151
- };
152
- return walk(`${global.list}.${global.name}`, global.type);
153
- };