@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,4 +1,3 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  import {
3
2
  type CoreFunctionBlock,
4
3
  type FunctionBlock,
@@ -6,157 +5,170 @@ import {
6
5
  httpErrors,
7
6
  jobError,
8
7
  type PlcType,
8
+ type Variable,
9
9
  } from "@tsplc/compiler/ir";
10
- import { type HttpOptions, secretValue } from "@tsplc/config";
11
- import { elementaryType, integerRange } from "@tsplc/iec";
12
- import { plcBufferBytes } from "@tsplc/server/wire";
13
- import type { CodesysPlan } from "./plan";
10
+ import { instrumentationFields } from "@tsplc/debug/manifest";
11
+ import {
12
+ elementaryType,
13
+ elementaryTypes,
14
+ fitsNumber,
15
+ integerRange,
16
+ } from "@tsplc/iec";
17
+ import { maxRecordFields } from "@tsplc/server/contract";
18
+ import { requestHeader } from "@tsplc/server/requests";
14
19
  import {
15
- type CodesysSymbols,
16
- type EmissionContext,
17
- instrumentationFieldTypes,
18
- required,
19
- } from "./symbols";
20
+ epochLength,
21
+ plcBufferBytes,
22
+ type ServiceChannel,
23
+ serviceOfPath,
24
+ slotIdLength,
25
+ slotStatus,
26
+ } from "@tsplc/server/wire";
27
+ import type { NativeEndpoint } from "./endpoints";
28
+ import type { CodesysPlan } from "./plan";
29
+ import { required } from "./required";
30
+ import type { EmissionContext, GlobalSymbols } from "./symbols";
20
31
  import { type CodesysTypes, stStringLiteral } from "./types";
21
32
 
22
33
  const opcuaServiceCapacity = 16;
23
34
 
24
- /* SysSocket Interfaces' SOCKET_SOL, the socket level, and SOCKET_SO_KEEPALIVE. */
35
+ /** The native client's request and response buffers, in bytes, each with room for its terminating NUL. */
36
+ const wireBytes = 8192;
37
+ /** The most bytes a response's headers may take. */
38
+ const headerBytes = 4096;
39
+
40
+ /*
41
+ * SysSocket Interfaces' SOCKET_SOL, the socket level, and SOCKET_SO_KEEPALIVE, which the project
42
+ * doesn't reference by name.
43
+ */
25
44
  const socketLevel = "16#FFFF";
26
45
  const socketKeepAliveOption = "16#8";
27
46
  const keepAliveIdleMs = 2000;
28
47
  const keepAliveIntervalMs = 1000;
29
48
  const keepAliveProbes = 3;
30
49
 
31
- export interface HttpEndpoint {
32
- transport?: "http" | "opcua";
33
- host: string;
34
- port: number;
35
- authority: string;
36
- path: string;
37
- token: string;
38
- timeoutMs: number;
39
- tls: boolean;
40
- }
41
- export const resolveHttpEndpoint = (
42
- value: string,
43
- input: HttpOptions,
44
- environment: Readonly<Record<string, string | undefined>>,
45
- ): HttpEndpoint => {
46
- const url = new URL(value);
47
- if (
48
- !["http:", "https:"].includes(url.protocol) ||
49
- url.username ||
50
- url.password ||
51
- url.hash ||
52
- url.hostname.includes(":")
53
- ) {
54
- throw new Error(
55
- "fetch requires an HTTP(S) URL with an IPv4 address or DNS hostname, without credentials or fragment.",
56
- );
57
- }
58
- if (
59
- (url.pathname + url.search).length > 2048 ||
60
- url.hostname.length > 253 ||
61
- Number(url.port || (url.protocol === "https:" ? 443 : 80)) === 0
62
- ) {
63
- throw new Error(
64
- "HTTP URL exceeds the native host/path limits or has an invalid port.",
65
- );
66
- }
67
- let token = "";
68
- const origins = new Set<string>();
69
- for (const credential of input.credentials) {
70
- const configured = environment[credential.originEnv];
71
- const secret = environment[credential.bearerTokenEnv];
72
- if (!configured || !secret) {
73
- throw new Error(
74
- `HTTP credentials require ${credential.originEnv} and ${credential.bearerTokenEnv}.`,
75
- );
76
- }
77
- const origin = new URL(configured);
78
- if (
79
- !["http:", "https:"].includes(origin.protocol) ||
80
- origin.username ||
81
- origin.password ||
82
- origin.pathname !== "/" ||
83
- origin.search ||
84
- origin.hash
85
- ) {
86
- throw new Error(
87
- `HTTP credential origin ${credential.originEnv} must contain only a scheme, host and port.`,
88
- );
89
- }
90
- if (origins.has(origin.origin)) {
91
- throw new Error("HTTP credential origins must be unique.");
92
- }
93
- origins.add(origin.origin);
94
- if (!secretValue.safeParse(secret).success) {
95
- throw new Error(`Invalid bearer token in ${credential.bearerTokenEnv}.`);
96
- }
97
- if (origin.origin === url.origin) {
98
- token = secret;
99
- }
100
- }
101
- return {
102
- host: url.hostname,
103
- port: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
104
- authority: url.host,
105
- path: url.pathname + url.search,
106
- token,
107
- timeoutMs: input.timeoutMs,
108
- tls: url.protocol === "https:",
109
- };
110
- };
50
+ /** The procedure a service block calls, as the server names it; its path when that isn't a service path. */
51
+ export const serviceName = (path: string) => serviceOfPath(path) ?? path;
52
+
111
53
  /** The most characters an integer prints as in decimal, its sign included. */
112
- const decimalLength = (layout: Parameters<typeof integerRange>[0]) =>
54
+ export const decimalLength = (layout: Parameters<typeof integerRange>[0]) =>
113
55
  Math.max(...integerRange(layout).map((bound) => String(bound).length));
114
56
 
57
+ /** The unsigned IEC integer, at least DINT-wide, that ST widens a value of `bits` to. */
58
+ export const unsignedWidening = (bits: number): string => {
59
+ const type = elementaryTypes.find(
60
+ (item) =>
61
+ item.family === "integer" &&
62
+ !item.signed &&
63
+ item.bits >= Math.max(bits, 32),
64
+ );
65
+ if (!type) {
66
+ throw new Error(`No unsigned integer holds ${bits} bits.`);
67
+ }
68
+ return type.name;
69
+ };
70
+
115
71
  /**
116
- * The ST that appends a BOOL, integer, bit string or UTF-8 STRING `value` as JSON with the
117
- * encoder methods of `httpMethods`, and the most bytes it can append.
72
+ * A scalar as JSON: the most bytes it takes, the ST that appends `value` with the encoder methods
73
+ * of `jsonEncoders`, and, when a 32-bit read holds it, the ST that reads it into `value` from
74
+ * `payload`, flagging a malformed one.
118
75
  */
119
- export const jsonScalar = (
120
- type: PlcType,
121
- value: string,
122
- ): { code: string; size: number } | undefined => {
76
+ interface JsonScalar {
77
+ size: number;
78
+ encode: (value: string) => string;
79
+ decode?: (value: string, target: CodesysTypes) => string;
80
+ }
81
+
82
+ /** The ST that reads a JSON integer into `assign`'s target, flagging one outside `range` as malformed. */
83
+ const readInteger = (range: readonly [bigint, bigint], assign: string) =>
84
+ `ReadInteger(); IF numberValue < ${range[0]} OR numberValue > ${range[1]} THEN malformed:=TRUE; ELSE ${assign} END_IF;`;
85
+
86
+ /** A BOOL, integer, bit string or UTF-8 STRING as JSON. */
87
+ export const jsonScalar = (type: PlcType): JsonScalar | undefined => {
123
88
  if (
124
89
  type.kind === "string" &&
125
90
  type.encoding === "utf8" &&
126
91
  type.capacity <= plcBufferBytes
127
92
  ) {
128
- return { code: `WriteString(${value});`, size: type.capacity * 6 + 2 };
93
+ return {
94
+ size: type.capacity * 6 + 2,
95
+ encode: (value) => `WriteString(${value});`,
96
+ decode: (value) =>
97
+ `ReadString(); IF ByteLength(token) > ${type.capacity} THEN malformed := TRUE; ELSE ${value} := token; END_IF;`,
98
+ };
129
99
  }
130
100
  if (type.kind === "bool") {
131
101
  return {
132
- code: `IF ${value} THEN Append('true'); ELSE Append('false'); END_IF;`,
133
102
  size: 5,
103
+ encode: (value) =>
104
+ `IF ${value} THEN Append('true'); ELSE Append('false'); END_IF;`,
105
+ decode: (value) =>
106
+ `IF MatchLiteral('true') THEN ${value}:=TRUE; ELSIF MatchLiteral('false') THEN ${value}:=FALSE; ELSE malformed:=TRUE;END_IF;`,
134
107
  };
135
108
  }
136
- if (type.kind === "bits") {
137
- const wide = type.bits <= 32 ? "UDINT" : "ULINT";
138
- return {
139
- code: `Append(${wide}_TO_STRING(TO_${wide}(${value})));`,
140
- size: decimalLength({ bits: type.bits, signed: false }),
141
- };
109
+ if (type.kind !== "bits" && type.kind !== "integer") {
110
+ return undefined;
142
111
  }
143
- if (type.kind === "integer") {
112
+ const layout = {
113
+ bits: type.bits,
114
+ signed: type.kind === "integer" && type.signed,
115
+ };
116
+ const wide = unsignedWidening(type.bits);
117
+ return {
118
+ size: decimalLength(layout),
119
+ encode: (value) =>
120
+ type.kind === "bits"
121
+ ? `Append(${wide}_TO_STRING(TO_${wide}(${value})));`
122
+ : `Append(${type.id}_TO_STRING(${value}));`,
123
+ ...(fitsNumber(elementaryType(type.id)) && {
124
+ decode: (value: string, target: CodesysTypes) =>
125
+ readInteger(
126
+ integerRange(layout),
127
+ `${value}:=TO_${target.name(type.id)}(numberValue);`,
128
+ ),
129
+ }),
130
+ };
131
+ };
132
+
133
+ /** A scalar a service record carries: a strict enum as its DINT base, else a scalar a 32-bit read holds. */
134
+ const serviceScalar = (type: PlcType): Required<JsonScalar> | undefined => {
135
+ if (type.kind === "enum") {
144
136
  return {
145
- code: `Append(${type.id}_TO_STRING(${value}));`,
146
- size: decimalLength(type),
137
+ size: Math.max(...type.members.map((member) => member.value.length)),
138
+ encode: (value) => `Append(DINT_TO_STRING(TO_DINT(${value})));`,
139
+ decode: (value, target) =>
140
+ readInteger(
141
+ integerRange(elementaryType("DINT")),
142
+ `CASE numberValue OF ${type.members.map((m) => `${m.value}: ${value}:=${target.name(type.id)}.${target.field(type.id, m.name)};`).join(" ")} ELSE malformed:=TRUE; END_CASE;`,
143
+ ),
147
144
  };
148
145
  }
149
- return undefined;
146
+ const scalar = jsonScalar(type);
147
+ return scalar?.decode && { ...scalar, decode: scalar.decode };
150
148
  };
151
149
 
152
- const httpLayouts = (
150
+ type RecordLayout = Extract<PlcType, { kind: "record" }>;
151
+
152
+ /** A service block's request and response ports and their records. */
153
+ interface HttpLayout {
154
+ request: Variable;
155
+ response: Variable;
156
+ requestLayout: RecordLayout;
157
+ responseLayout: RecordLayout;
158
+ }
159
+
160
+ /**
161
+ * A service block's layout, or why its JSON cannot be exchanged: a record the codecs cannot
162
+ * encode, or one whose worst case overflows the buffer.
163
+ */
164
+ export const httpLayout = (
153
165
  block: CoreFunctionBlock,
154
166
  types: ReadonlyMap<string, PlcType>,
155
- ) => {
167
+ ): HttpLayout | { error: string } => {
156
168
  const request = block.inputs.find((v) => v.name === "request");
157
169
  const response = block.outputs.find((v) => v.name === "result");
158
170
  if (!request || !response) {
159
- throw new Error("Missing HTTP record ports.");
171
+ return { error: "Missing HTTP record ports." };
160
172
  }
161
173
  const requestLayout = types.get(request.type);
162
174
  const responseLayout = types.get(response.type);
@@ -164,101 +176,57 @@ const httpLayouts = (
164
176
  requestLayout?.kind !== "record" ||
165
177
  responseLayout?.kind !== "record" ||
166
178
  responseLayout.fields.length === 0 ||
167
- responseLayout.fields.length > 31
179
+ responseLayout.fields.length > maxRecordFields
168
180
  ) {
169
- throw new Error(
170
- "HTTP requires closed request/response records with 1..31 response fields.",
171
- );
181
+ return {
182
+ error: `HTTP requires closed request/response records with 1..${maxRecordFields} response fields.`,
183
+ };
172
184
  }
173
- const scalarSize = (id: string): number => {
185
+ const scalarSize = (id: string): number | undefined => {
174
186
  const type = types.get(id);
175
- if (type?.kind === "enum") {
176
- return Math.max(...type.members.map((member) => member.value.length));
177
- }
178
- const scalar =
179
- type &&
180
- !((type.kind === "integer" || type.kind === "bits") && type.bits > 32)
181
- ? jsonScalar(type, "")
182
- : undefined;
183
- if (!scalar) {
184
- throw new Error(
185
- "HTTP JSON supports bounded UTF-8 strings, BOOL, enums, and integers up to 32 bits.",
186
- );
187
+ return type && serviceScalar(type)?.size;
188
+ };
189
+ const fieldSize = (
190
+ field: RecordLayout["fields"][number],
191
+ response: boolean,
192
+ ): number | undefined => {
193
+ const type = types.get(field.type);
194
+ if (type?.kind !== "array" || response) {
195
+ return scalarSize(field.type);
187
196
  }
188
- return scalar.size;
197
+ const element = scalarSize(type.element);
198
+ return element === undefined ? undefined : 2 + type.length * (element + 1);
189
199
  };
190
- const recordSize = (record: typeof requestLayout, response: boolean) =>
191
- 2 +
192
- record.fields.reduce((size, field) => {
193
- const type = types.get(field.type);
194
- const valueSize =
195
- type?.kind === "array" && !response
196
- ? 2 + type.length * (scalarSize(type.element) + 1)
197
- : scalarSize(field.type);
198
- return size + field.name.length + 4 + valueSize;
199
- }, 0);
200
- if (
201
- recordSize(requestLayout, false) > plcBufferBytes ||
202
- recordSize(responseLayout, true) > plcBufferBytes
203
- ) {
204
- throw new Error(
205
- `The worst-case HTTP JSON payload exceeds the native ${plcBufferBytes}-byte buffer; reduce record/string/array bounds.`,
200
+ for (const [record, response] of [
201
+ [requestLayout, false],
202
+ [responseLayout, true],
203
+ ] as const) {
204
+ const sizes = record.fields.map((field) => fieldSize(field, response));
205
+ if (!sizes.every((size): size is number => size !== undefined)) {
206
+ return {
207
+ error:
208
+ "HTTP JSON supports bounded UTF-8 strings, BOOL, enums, and integers up to 32 bits.",
209
+ };
210
+ }
211
+ const size = record.fields.reduce(
212
+ (total, field) => total + field.name.length + 4,
213
+ sizes.reduce((total, value) => total + value, 2),
206
214
  );
215
+ if (size > plcBufferBytes) {
216
+ return {
217
+ error: `The worst-case HTTP JSON payload exceeds the native ${plcBufferBytes}-byte buffer; reduce record/string/array bounds.`,
218
+ };
219
+ }
207
220
  }
208
221
  return { request, response, requestLayout, responseLayout };
209
222
  };
210
- export const validateHttpLayout = (
211
- block: CoreFunctionBlock,
212
- types: ReadonlyMap<string, PlcType>,
213
- ): void => {
214
- httpLayouts(block, types);
215
- };
216
-
217
- /** The ST that reads a JSON integer into `assign`'s target, flagging one outside `range` as malformed. */
218
- const readInteger = (range: readonly [bigint, bigint], assign: string) =>
219
- `ReadInteger(); IF numberValue < ${range[0]} OR numberValue > ${range[1]} THEN malformed:=TRUE; ELSE ${assign} END_IF;`;
220
-
221
- /** The ST that reads a response field's JSON value into `value`, flagging a malformed one. */
222
- const decodeField = (
223
- type: PlcType,
224
- value: string,
225
- target: CodesysTypes,
226
- ): string => {
227
- if (
228
- type.kind === "string" &&
229
- type.encoding === "utf8" &&
230
- type.capacity <= plcBufferBytes
231
- ) {
232
- return `ReadString(); IF ByteLength(token) > ${type.capacity} THEN malformed := TRUE; ELSE ${value} := token; END_IF;`;
233
- }
234
- if (type.kind === "bool") {
235
- return `IF MatchLiteral('true') THEN ${value}:=TRUE; ELSIF MatchLiteral('false') THEN ${value}:=FALSE; ELSE malformed:=TRUE;END_IF;`;
236
- }
237
- // A strict enum is read as its DINT base.
238
- if (type.kind === "enum") {
239
- return readInteger(
240
- integerRange(elementaryType("DINT")),
241
- `CASE numberValue OF ${type.members.map((m) => `${m.value}: ${value}:=${target.name(type.id)}.${target.field(type.id, m.name)};`).join(" ")} ELSE malformed:=TRUE; END_CASE;`,
242
- );
243
- }
244
- if ((type.kind === "integer" || type.kind === "bits") && type.bits <= 32) {
245
- return readInteger(
246
- integerRange({
247
- bits: type.bits,
248
- signed: type.kind === "integer" && type.signed,
249
- }),
250
- `${value}:=TO_${target.name(type.id)}(numberValue);`,
251
- );
252
- }
253
- throw new Error("HTTP responses currently require flat scalar records.");
254
- };
255
223
 
256
224
  /** A service block's typed JSON codecs and ports; no application protocol lives here. */
257
225
  interface ServiceCodecs {
258
226
  port: (label: string) => string;
259
227
  /** Appends the request record's fields as JSON. */
260
228
  requestCode: string;
261
- /** Decodes the response record from `payload`, setting `error` to 4 when it is malformed. */
229
+ /** Decodes the response record from `payload`, setting `error` to `jobError.malformedResponse` when it is malformed. */
262
230
  decodeResponse: string;
263
231
  inputs: string;
264
232
  outputs: string;
@@ -277,53 +245,44 @@ const serviceCodecs = (
277
245
  if (!variable) {
278
246
  throw new Error(`Missing HTTP port ${label}`);
279
247
  }
280
- return fields.get(variable.id)!;
281
- };
282
- const { request, response, requestLayout, responseLayout } = httpLayouts(
283
- block,
284
- types,
285
- );
286
- const encode = (typeId: string, value: string): string => {
287
- const type = types.get(typeId)!;
288
- if (type.kind === "array") {
289
- return Array.from(
290
- { length: type.length },
291
- (_, i) =>
292
- `${i ? "Append(',');" : ""}${encode(type.element, `${value}[${i + type.lowerBound}]`)}`,
293
- ).join("\n");
294
- }
295
- if (type.kind === "enum") {
296
- return `Append(DINT_TO_STRING(TO_DINT(${value})));`;
297
- }
298
- const scalar = jsonScalar(type, value);
299
- if (scalar) {
300
- return scalar.code;
301
- }
302
- throw new Error(
303
- "HTTP JSON supports bounded UTF-8 strings, BOOL, enums, integers up to 32 bits and fixed arrays.",
304
- );
248
+ return required(fields.get(variable.id));
305
249
  };
250
+ const layout = httpLayout(block, types);
251
+ if ("error" in layout) {
252
+ throw new Error(layout.error);
253
+ }
254
+ const { request, response, requestLayout, responseLayout } = layout;
255
+ const typeOf = (id: string) => required(types.get(id));
256
+ const scalarOf = (type: PlcType) => required(serviceScalar(type));
257
+ const encode = (type: PlcType, value: string): string =>
258
+ type.kind === "array"
259
+ ? Array.from(
260
+ { length: type.length },
261
+ (_, i) =>
262
+ `${i ? "Append(',');" : ""}${encode(typeOf(type.element), `${value}[${i + type.lowerBound}]`)}`,
263
+ ).join("\n")
264
+ : scalarOf(type).encode(value);
306
265
  const requestCode = requestLayout.fields
307
266
  .map((field, i) => {
308
- const type = types.get(field.type)!;
267
+ const type = typeOf(field.type);
309
268
  const value = `${port("request")}.${target.field(request.type, field.name)}`;
310
- return `Append(${stStringLiteral(`${i ? "," : ""}"${field.name}":`)});${type.kind === "array" ? "Append('[');" : ""}${encode(field.type, value)}${type.kind === "array" ? "Append(']');" : ""}`;
269
+ return `Append(${stStringLiteral(`${i ? "," : ""}"${field.name}":`)});${type.kind === "array" ? "Append('[');" : ""}${encode(type, value)}${type.kind === "array" ? "Append(']');" : ""}`;
311
270
  })
312
271
  .join("\n");
272
+ // `seen` has a bit for each response field, so a record has at most `maxRecordFields`.
313
273
  const responseCode = responseLayout.fields
314
274
  .map((field, i) => {
315
- const type = types.get(field.type)!;
316
275
  const value = `${port("result")}.${target.field(response.type, field.name)}`;
317
- const decode = decodeField(type, value, target);
276
+ const decode = scalarOf(typeOf(field.type)).decode(value, target);
318
277
  return `${i === 0 ? "IF" : "ELSIF"} part = ${stStringLiteral(field.name)} THEN IF (seen AND SHL(DWORD#1,${i})) <> 0 THEN malformed:=TRUE; END_IF; seen:=seen OR SHL(DWORD#1,${i}); ${decode}`;
319
278
  })
320
279
  .join("\n");
321
- const inputs = block.inputs
322
- .map((v) => `${fields.get(v.id)} : ${target.name(v.type)};`)
323
- .join("\n");
324
- const outputs = block.outputs
325
- .map((v) => `${fields.get(v.id)} : ${target.name(v.type)};`)
326
- .join("\n");
280
+ const declarations = (variables: readonly Variable[]) =>
281
+ variables
282
+ .map((v) => `${required(fields.get(v.id))} : ${target.name(v.type)};`)
283
+ .join("\n");
284
+ const inputs = declarations(block.inputs);
285
+ const outputs = declarations(block.outputs);
327
286
  const decodeResponse = `cursor:=1;malformed:=FALSE;seen:=0;
328
287
  SkipWhitespace();Expect(123);SkipWhitespace();
329
288
  WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
@@ -339,26 +298,16 @@ IF malformed OR cursor<>TO_UINT(ByteLength(payload))+1 OR seen<>DWORD#${2 ** res
339
298
  return { port, requestCode, decodeResponse, inputs, outputs };
340
299
  };
341
300
 
342
- /** A slot of an OPC UA client: the request and reply strings the server exchanges through it. */
343
- export interface RpcChannel {
344
- path: string;
345
- request: string;
346
- requestId: string;
347
- reply: string;
348
- replyId: string;
349
- epoch: string;
350
- }
351
-
352
301
  /**
353
302
  * The global list an OPC UA client's calls to `path` go through, and its slots as channels for the
354
303
  * server's gateway. Requests are read-only to the gateway; replies and connection epochs it writes.
355
304
  */
356
305
  export const rpcSlots = (
357
- symbols: CodesysSymbols,
306
+ symbols: GlobalSymbols,
358
307
  id: string,
359
308
  owner: string,
360
309
  path: string,
361
- ): { list: GeneratedObject; channels: RpcChannel[] } => {
310
+ ): { list: GeneratedObject; channels: ServiceChannel[] } => {
362
311
  const name = symbols.names.allocateObject("GVL", `TsplcRpc_${owner}`);
363
312
  return {
364
313
  list: {
@@ -368,10 +317,10 @@ export const rpcSlots = (
368
317
  declaration: `{attribute 'qualified_only'}
369
318
  VAR_GLOBAL
370
319
  {attribute 'symbol' := 'read'} requests:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
371
- {attribute 'symbol' := 'read'} requestIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
372
- {attribute 'symbol' := 'readwrite'} replyIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
320
+ {attribute 'symbol' := 'read'} requestIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${slotIdLength});
321
+ {attribute 'symbol' := 'readwrite'} replyIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${slotIdLength});
373
322
  {attribute 'symbol' := 'readwrite'} replies:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
374
- {attribute 'symbol' := 'readwrite'} epochs:ARRAY[1..${opcuaServiceCapacity}] OF STRING(32);
323
+ {attribute 'symbol' := 'readwrite'} epochs:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${epochLength});
375
324
  inUse:ARRAY[1..${opcuaServiceCapacity}] OF __XWORD;
376
325
  sequence:ARRAY[1..${opcuaServiceCapacity}] OF UDINT;
377
326
  END_VAR`,
@@ -387,11 +336,14 @@ END_VAR`,
387
336
  };
388
337
  };
389
338
 
339
+ /** The ASCII code of a one-character string, as a reply's bytes are compared. */
340
+ const ascii = (character: string) => character.charCodeAt(0);
341
+
390
342
  /**
391
343
  * A client block that exchanges what `body` appends to `payload` and its reply through a slot of
392
- * `rpcGlobal`, as `nativeHttp` does over HTTP. A reply's status is 0 when the server's handler
393
- * succeeded, 4 when it refused the request as an HTTP 4xx would, reported as HTTP 400, and
394
- * anything else a network error. On success `decode` runs over the reply's body in `payload`.
344
+ * `rpcGlobal`, as `nativeHttp` does over HTTP. A reply whose status is `slotStatus.refused` is
345
+ * reported as HTTP 400, and any status but `slotStatus.ok` as a network error. On success `decode`
346
+ * runs over the reply's body in `payload`.
395
347
  */
396
348
  export const opcuaClient = ({
397
349
  id,
@@ -423,7 +375,7 @@ export const opcuaClient = ({
423
375
  ${ports}
424
376
  VAR
425
377
  timeout:TON;stage:UINT;slotIndex:UINT;candidate:UINT;
426
- identity:STRING(64);epoch:STRING(32);prefix:STRING(80);
378
+ identity:STRING(${slotIdLength});epoch:STRING(${epochLength});prefix:STRING(80);
427
379
  payload:STRING(${plcBufferBytes});token:STRING(${plcBufferBytes});part:STRING(${plcBufferBytes});
428
380
  cursor:UINT;malformed:BOOL;seen:DWORD;numberValue:LINT;tokenUsed:UINT;
429
381
  END_VAR`,
@@ -464,9 +416,9 @@ IF stage=1 THEN
464
416
  ELSIF ${channel("replyIds")}=identity AND_THEN LEFT(${channel("replies")},LEN(prefix))=prefix THEN
465
417
  payload:='';cursor:=LEN(prefix);
466
418
  IF ByteLength(${channel("replies")})<cursor+4 THEN ${port("error")}:=${jobError.malformedResponse};
467
- ELSIF ${channel("replies")}[cursor+1]<>124 THEN ${port("error")}:=${jobError.network};
468
- ELSIF ${channel("replies")}[cursor]=52 THEN ${port("error")}:=${httpErrors.base + 400};
469
- ELSIF ${channel("replies")}[cursor]<>48 THEN ${port("error")}:=${jobError.network};
419
+ ELSIF ${channel("replies")}[cursor+1]<>${ascii("|")} THEN ${port("error")}:=${jobError.network};
420
+ ELSIF ${channel("replies")}[cursor]=${ascii(String(slotStatus.refused))} THEN ${port("error")}:=${httpErrors.refused};
421
+ ELSIF ${channel("replies")}[cursor]<>${ascii(String(slotStatus.ok))} THEN ${port("error")}:=${jobError.network};
470
422
  ELSE
471
423
  FOR candidate:=cursor+2 TO ByteLength(${channel("replies")})-1 DO payload[candidate-cursor-2]:=${channel("replies")}[candidate];END_FOR;
472
424
  payload[ByteLength(${channel("replies")})-cursor-2]:=0;
@@ -483,21 +435,27 @@ END_IF;`,
483
435
  };
484
436
  };
485
437
 
438
+ type HttpRuntime = Extract<
439
+ NonNullable<FunctionBlock["runtime"]>,
440
+ { kind: "http" }
441
+ >;
442
+
486
443
  /** An HTTP service block: a native client that sends the request record and decodes the response. */
487
444
  const httpServiceBlock = (
488
- block: CoreFunctionBlock,
445
+ id: string,
446
+ runtime: HttpRuntime,
489
447
  name: string,
490
448
  { port, requestCode, decodeResponse, inputs, outputs }: ServiceCodecs,
491
- endpoint: HttpEndpoint,
449
+ endpoint: NativeEndpoint,
492
450
  network: string,
493
- /** The requesting job's id input and this block's request counter, sent as `x-tsplc-request`. */
451
+ /** The requesting job's id input and this block's request counter, sent as `requestHeader`. */
494
452
  trace: { job: string; sequence: string } | undefined,
495
453
  ): [GeneratedObject, ...GeneratedObject[]] =>
496
454
  nativeHttp({
497
- id: block.id,
455
+ id,
498
456
  name,
499
457
  ports: `VAR_INPUT
500
- ${inputs}${trace ? `\n${trace.job} : ${instrumentationFieldTypes.job};` : ""}
458
+ ${inputs}${trace ? `\n${trace.job} : ${instrumentationFields.job};` : ""}
501
459
  END_VAR
502
460
  VAR_OUTPUT
503
461
  ${outputs}
@@ -505,12 +463,9 @@ END_VAR`,
505
463
  port,
506
464
  endpoint,
507
465
  network,
508
- method: block.runtime?.kind === "http" ? block.runtime.method : "GET",
509
- json: block.runtime?.kind === "http" && block.runtime.json,
510
- body:
511
- block.runtime?.kind === "http" && block.runtime.json
512
- ? `Append('{'); ${requestCode} Append('}');`
513
- : "",
466
+ method: runtime.method,
467
+ json: runtime.json,
468
+ body: runtime.json ? `Append('{'); ${requestCode} Append('}');` : "",
514
469
  decode: decodeResponse,
515
470
  ...(trace && { trace }),
516
471
  });
@@ -537,21 +492,20 @@ export const nativeHttp = ({
537
492
  /** Its input and output declarations, with `start`, `cancel`, `busy`, `done` and `error`. */
538
493
  ports: string;
539
494
  port: (label: string) => string;
540
- endpoint: HttpEndpoint;
495
+ endpoint: NativeEndpoint;
541
496
  network: string;
542
497
  method: string;
543
498
  json: boolean;
544
499
  body: string;
545
500
  decode: string;
546
- /** The requesting job's id input and this block's request counter, sent as `x-tsplc-request`. */
501
+ /** The requesting job's id input and this block's request counter, sent as `requestHeader`. */
547
502
  trace?: { job: string; sequence: string };
548
503
  }): [GeneratedObject, ...GeneratedObject[]] => {
549
- const requestHeader = trace
504
+ const tracedRequest = trace
550
505
  ? `AppendWire(UDINT_TO_STRING(${trace.job}));AppendWire(':');AppendWire(UDINT_TO_STRING(${trace.sequence}));AppendWire('$R$NContent-Length: ');`
551
506
  : "";
552
507
  const release =
553
508
  "resolver(xExecute:=FALSE,itfIPAddress:=remoteIP);client(xEnable:=FALSE);writer(xExecute:=FALSE);reader(xEnable:=FALSE);timeout(IN:=FALSE);";
554
- // Helpers are emitted as native methods under the HTTP block by the emitter.
555
509
  const block: GeneratedObject = {
556
510
  id,
557
511
  kind: "functionBlock",
@@ -569,9 +523,9 @@ VAR
569
523
  timeout : TON;
570
524
  keepAlive : ${name}_KeepAlive;
571
525
  stage : UINT;
572
- wire : STRING(8192);
573
- received : STRING(8192);
574
- chunk : ARRAY[0..8191] OF BYTE;
526
+ wire : STRING(${wireBytes});
527
+ received : STRING(${wireBytes});
528
+ chunk : ARRAY[0..${wireBytes - 1}] OF BYTE;
575
529
  payload : STRING(${plcBufferBytes});
576
530
  token : STRING(${plcBufferBytes});
577
531
  part : STRING(${plcBufferBytes});
@@ -585,7 +539,7 @@ VAR
585
539
  numberValue : LINT;
586
540
  wireUsed : UINT;
587
541
  tokenUsed : UINT;
588
- index : UINT;${trace ? `\n ${trace.sequence} : ${instrumentationFieldTypes.sequence};` : ""}
542
+ index : UINT;${trace ? `\n ${trace.sequence} : ${instrumentationFields.sequence};` : ""}
589
543
  END_VAR
590
544
  `,
591
545
  // The host goes in the resolver call, not an initial value: an online change keeps the values
@@ -602,7 +556,7 @@ IF stage=0 THEN
602
556
  IF malformed THEN ${port("error")}:=${jobError.tooLarge}; stage:=90;
603
557
  ELSE
604
558
  wire:='';wireUsed:=0;
605
- AppendWire(${stStringLiteral(`${method} ${endpoint.path} HTTP/1.1\r\nHost: ${endpoint.authority}\r\n${endpoint.token ? `Authorization: Bearer ${endpoint.token}\r\n` : ""}${json ? "Content-Type: application/json\r\n" : ""}Accept: application/json\r\nConnection: close\r\n${trace ? "x-tsplc-request: " : "Content-Length: "}`)});${requestHeader}
559
+ AppendWire(${stStringLiteral(`${method} ${endpoint.path} HTTP/1.1\r\nHost: ${endpoint.authority}\r\n${endpoint.token ? `Authorization: Bearer ${endpoint.token}\r\n` : ""}${json ? "Content-Type: application/json\r\n" : ""}Accept: application/json\r\nConnection: close\r\n${trace ? `${requestHeader}: ` : "Content-Length: "}`)});${tracedRequest}
606
560
  AppendWire(UINT_TO_STRING(ByteLength(payload)));AppendWire('$R$N$R$N');AppendWire(payload); stage:=10;
607
561
  END_IF;
608
562
  END_IF;
@@ -622,19 +576,19 @@ IF stage=2 THEN
622
576
  IF writer.xError THEN ${port("error")}:=${jobError.network};stage:=90;ELSIF writer.xDone THEN stage:=3;END_IF;
623
577
  END_IF;
624
578
  IF stage=3 THEN
625
- IF used>=8191 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
579
+ IF used>=${wireBytes - 1} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
626
580
  ELSE
627
- reader(xEnable:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(chunk),udiSize:=8191);
581
+ reader(xEnable:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(chunk),udiSize:=${wireBytes - 1});
628
582
  IF reader.xError THEN ${port("error")}:=${jobError.network};stage:=90;
629
583
  ELSIF reader.xReady AND reader.udiCount>0 THEN
630
- IF TO_UDINT(used)+reader.udiCount>8191 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
584
+ IF TO_UDINT(used)+reader.udiCount>${wireBytes - 1} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
631
585
  ELSE
632
586
  FOR index:=0 TO TO_UINT(reader.udiCount)-1 DO received[used+index]:=chunk[index];END_FOR;
633
587
  used:=used+TO_UINT(reader.udiCount);received[used]:=0;
634
588
  FindHeaders();
635
- IF headerEnd=0 AND used>4096 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;END_IF;
589
+ IF headerEnd=0 AND used>${headerBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;END_IF;
636
590
  IF headerEnd>0 THEN
637
- IF headerEnd>4096 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
591
+ IF headerEnd>${headerBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
638
592
  ELSE
639
593
  ReadHeaders();
640
594
  IF malformed OR contentLength<0 OR contentLength>${plcBufferBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
@@ -679,10 +633,10 @@ FB_exit:=TRUE;`,
679
633
  /**
680
634
  * TCP keep-alive for an HTTP client's connection, as an option provider the client applies to each socket it opens. A
681
635
  * connection whose peer vanished without closing it, as when the server's PC drops off the network, otherwise stays active
682
- * (Net Base Services' TCP_Client documentation), and a read on it holds the Net Base Services task every client shares: for
683
- * two hours on the frame-assembly line, cutting the PLC off from its server until a download found the task unable to stop.
684
- * With keep-alive, such a connection fails within seconds and the task moves on. A live peer's TCP stack answers the
685
- * probes however long its server takes to reply, so they never end a slow request.
636
+ * (Net Base Services' TCP_Client documentation), and a read on it holds the Net Base Services task every client shares,
637
+ * cutting the PLC off from its server, and a download then finds the task unable to stop. With keep-alive, such a
638
+ * connection fails within seconds and the task moves on. A live peer's TCP stack answers the probes however long its
639
+ * server takes to reply, so they never end a slow request.
686
640
  */
687
641
  const tcpKeepAlive = (owner: string, name: string): GeneratedObject[] => {
688
642
  const id = `${owner}:keepAlive`;
@@ -717,7 +671,6 @@ VAR_OUTPUT eErrorID : NBS.ERROR; END_VAR`,
717
671
  declaration: `METHOD PUBLIC GetParams : NBS.ERROR
718
672
  VAR_INPUT usiIndex : USINT; END_VAR
719
673
  VAR_OUTPUT eOperation : NBS.OPERATION; optOption : NBS.OPTION; END_VAR`,
720
- // SOCKET_SOL and SOCKET_SO_KEEPALIVE from SysSocket Interfaces, which the project doesn't reference by name.
721
674
  implementation: `eOperation:=NBS.OPERATION.SET_OPTION;
722
675
  optOption.diLevel:=${socketLevel};
723
676
  optOption.diOption:=${socketKeepAliveOption};
@@ -741,7 +694,7 @@ VAR_INPUT usiIndex : USINT; udiResult : UDINT; END_VAR`,
741
694
  export const httpCertificateVerifier = (
742
695
  owner: string,
743
696
  name: string,
744
- endpoint: HttpEndpoint,
697
+ endpoint: NativeEndpoint,
745
698
  ): GeneratedObject[] => {
746
699
  if (!endpoint.tls) {
747
700
  return [];
@@ -777,58 +730,72 @@ IF result<>0 THEN VerifyCertificate:=result;ELSIF NOT matched THEN VerifyCertifi
777
730
  ];
778
731
  };
779
732
 
780
- export const httpMethods = (
733
+ const privateMethod = (
781
734
  owner: string,
782
- transport: "http" | "opcua" = "http",
783
- ): GeneratedObject[] => {
784
- const method = (
785
- name: string,
786
- declaration: string,
787
- implementation: string,
788
- result?: string,
789
- ): GeneratedObject => ({
790
- id: `${owner}:${name}`,
791
- parent: owner,
792
- kind: "method",
793
- name,
794
- declaration: `METHOD PRIVATE ${name}${result ? ` : ${result}` : ""}\n${declaration}`,
795
- implementation,
796
- });
797
- return [
798
- // Standard string helpers accept STRING(255); native buffers must retain their full byte length.
799
- method(
800
- "ByteLength",
801
- "VAR_INPUT value:STRING(8192);END_VAR\nVAR i:UINT;END_VAR",
802
- "ByteLength:=0;FOR i:=0 TO 8191 DO IF value[i]=0 THEN ByteLength:=i;RETURN;END_IF;END_FOR;ByteLength:=8192;",
803
- "UINT",
804
- ),
805
- method(
806
- "Append",
807
- `VAR_INPUT value : STRING(${plcBufferBytes}); END_VAR\nVAR offset:UINT;i:UINT;END_VAR`,
808
- `offset:=TO_UINT(ByteLength(payload));IF offset+TO_UINT(ByteLength(value))>${plcBufferBytes} THEN malformed:=TRUE; ELSE IF ByteLength(value)>0 THEN FOR i:=0 TO TO_UINT(ByteLength(value))-1 DO payload[offset+i]:=value[i];END_FOR;END_IF;payload[offset+TO_UINT(ByteLength(value))]:=0;END_IF;`,
809
- ),
810
- method(
811
- "AppendWire",
812
- "VAR_INPUT value:STRING(8192);END_VAR\nVAR i:UINT;END_VAR",
813
- `IF wireUsed+TO_UINT(ByteLength(value))>8191 THEN malformed:=TRUE;RETURN;END_IF;IF ByteLength(value)>0 THEN FOR i:=0 TO TO_UINT(ByteLength(value))-1 DO wire[wireUsed+i]:=value[i];END_FOR;END_IF;wireUsed:=wireUsed+TO_UINT(ByteLength(value));wire[wireUsed]:=0;`,
814
- ),
815
- method(
816
- "FindHeaders",
817
- "VAR i:UINT;END_VAR",
818
- `headerEnd:=0;IF used<4 THEN RETURN;END_IF;
735
+ name: string,
736
+ declaration: string,
737
+ implementation: string,
738
+ result?: string,
739
+ ): GeneratedObject => ({
740
+ id: `${owner}:${name}`,
741
+ parent: owner,
742
+ kind: "method",
743
+ name,
744
+ declaration: `METHOD PRIVATE ${name}${result ? ` : ${result}` : ""}\n${declaration}`,
745
+ implementation,
746
+ });
747
+
748
+ // Standard string helpers accept STRING(255); native buffers must retain their full byte length.
749
+ const byteLengthMethod = (owner: string) =>
750
+ privateMethod(
751
+ owner,
752
+ "ByteLength",
753
+ `VAR_INPUT value:STRING(${wireBytes});END_VAR\nVAR i:UINT;END_VAR`,
754
+ `ByteLength:=0;FOR i:=0 TO ${wireBytes - 1} DO IF value[i]=0 THEN ByteLength:=i;RETURN;END_IF;END_FOR;ByteLength:=${wireBytes};`,
755
+ "UINT",
756
+ );
757
+
758
+ const appendMethod = (owner: string) =>
759
+ privateMethod(
760
+ owner,
761
+ "Append",
762
+ `VAR_INPUT value : STRING(${plcBufferBytes}); END_VAR\nVAR offset:UINT;i:UINT;END_VAR`,
763
+ `offset:=TO_UINT(ByteLength(payload));IF offset+TO_UINT(ByteLength(value))>${plcBufferBytes} THEN malformed:=TRUE; ELSE IF ByteLength(value)>0 THEN FOR i:=0 TO TO_UINT(ByteLength(value))-1 DO payload[offset+i]:=value[i];END_FOR;END_IF;payload[offset+TO_UINT(ByteLength(value))]:=0;END_IF;`,
764
+ );
765
+
766
+ const appendWireMethod = (owner: string) =>
767
+ privateMethod(
768
+ owner,
769
+ "AppendWire",
770
+ `VAR_INPUT value:STRING(${wireBytes});END_VAR\nVAR i:UINT;END_VAR`,
771
+ `IF wireUsed+TO_UINT(ByteLength(value))>${wireBytes - 1} THEN malformed:=TRUE;RETURN;END_IF;IF ByteLength(value)>0 THEN FOR i:=0 TO TO_UINT(ByteLength(value))-1 DO wire[wireUsed+i]:=value[i];END_FOR;END_IF;wireUsed:=wireUsed+TO_UINT(ByteLength(value));wire[wireUsed]:=0;`,
772
+ );
773
+
774
+ const findHeadersMethod = (owner: string) =>
775
+ privateMethod(
776
+ owner,
777
+ "FindHeaders",
778
+ "VAR i:UINT;END_VAR",
779
+ `headerEnd:=0;IF used<4 THEN RETURN;END_IF;
819
780
  FOR i:=0 TO used-4 DO IF received[i]=13 AND received[i+1]=10 AND received[i+2]=13 AND received[i+3]=10 THEN headerEnd:=i+1;RETURN;END_IF;END_FOR;`,
820
- ),
821
- method(
822
- "MatchLiteral",
823
- "VAR_INPUT value:STRING(8);END_VAR\nVAR i:UINT;size:UINT;END_VAR",
824
- `MatchLiteral:=FALSE;size:=TO_UINT(ByteLength(value));IF cursor+size-1>TO_UINT(ByteLength(payload)) THEN RETURN;END_IF;
781
+ );
782
+
783
+ const matchLiteralMethod = (owner: string) =>
784
+ privateMethod(
785
+ owner,
786
+ "MatchLiteral",
787
+ "VAR_INPUT value:STRING(8);END_VAR\nVAR i:UINT;size:UINT;END_VAR",
788
+ `MatchLiteral:=FALSE;size:=TO_UINT(ByteLength(value));IF cursor+size-1>TO_UINT(ByteLength(payload)) THEN RETURN;END_IF;
825
789
  FOR i:=0 TO size-1 DO IF payload[cursor-1+i]<>value[i] THEN RETURN;END_IF;END_FOR;cursor:=cursor+size;MatchLiteral:=TRUE;`,
826
- "BOOL",
827
- ),
828
- method(
829
- "ReadHeaders",
830
- `VAR lineStart:UINT;lineEnd:UINT;i:UINT;j:UINT;key:STRING(64);octet:BYTE;found:BOOL;digits:UINT;END_VAR`,
831
- `malformed:=FALSE;found:=FALSE;contentLength:=-1;
790
+ "BOOL",
791
+ );
792
+
793
+ const readHeadersMethod = (owner: string) =>
794
+ privateMethod(
795
+ owner,
796
+ "ReadHeaders",
797
+ `VAR lineStart:UINT;lineEnd:UINT;i:UINT;j:UINT;key:STRING(64);octet:BYTE;found:BOOL;digits:UINT;END_VAR`,
798
+ `malformed:=FALSE;found:=FALSE;contentLength:=-1;
832
799
  IF LEFT(received,9)<>'HTTP/1.1 ' AND LEFT(received,9)<>'HTTP/1.0 ' THEN malformed:=TRUE;RETURN;END_IF;
833
800
  status:=0;FOR i:=9 TO 11 DO IF received[i]<48 OR received[i]>57 THEN malformed:=TRUE;RETURN;END_IF;status:=status*10+TO_UINT(received[i]-48);END_FOR;
834
801
  lineStart:=1;
@@ -845,45 +812,63 @@ WHILE lineStart<headerEnd DO
845
812
  END_IF;
846
813
  lineStart:=lineEnd+2;
847
814
  END_WHILE;`,
848
- ),
849
- method(
850
- "WriteString",
851
- `VAR_INPUT value : STRING(${plcBufferBytes}); END_VAR\nVAR i:UINT; one:STRING(1); hex:STRING(16):='0123456789abcdef'; END_VAR`,
852
- `Append('"');IF ByteLength(value)>0 THEN FOR i:=0 TO ByteLength(value)-1 DO
815
+ );
816
+
817
+ const writeStringMethod = (owner: string) =>
818
+ privateMethod(
819
+ owner,
820
+ "WriteString",
821
+ `VAR_INPUT value : STRING(${plcBufferBytes}); END_VAR\nVAR i:UINT; one:STRING(1); hex:STRING(16):='0123456789abcdef'; END_VAR`,
822
+ `Append('"');IF ByteLength(value)>0 THEN FOR i:=0 TO ByteLength(value)-1 DO
853
823
  one[0]:=value[i];one[1]:=0;
854
824
  IF value[i]=34 OR value[i]=92 THEN Append('\\');Append(one);
855
825
  ELSIF value[i]<32 THEN Append('\\u00');one[0]:=hex[SHR(value[i],4)];Append(one);one[0]:=hex[value[i] AND 15];Append(one);
856
826
  ELSE Append(one);END_IF;
857
827
  END_FOR;END_IF;Append('"');`,
858
- ),
859
- method(
860
- "SkipWhitespace",
861
- "",
862
- `WHILE cursor<=TO_UINT(ByteLength(payload)) DO IF payload[cursor-1]<>32 AND payload[cursor-1]<>9 AND payload[cursor-1]<>10 AND payload[cursor-1]<>13 THEN EXIT;END_IF;cursor:=cursor+1;END_WHILE;`,
863
- ),
864
- method(
865
- "Expect",
866
- "VAR_INPUT value:BYTE; END_VAR",
867
- `IF cursor>TO_UINT(ByteLength(payload)) OR_ELSE payload[cursor-1]<>value THEN malformed:=TRUE;ELSE cursor:=cursor+1;END_IF;`,
868
- ),
869
- method(
870
- "TokenByte",
871
- "VAR_INPUT value:BYTE;END_VAR",
872
- `IF tokenUsed>=${plcBufferBytes} OR value=0 THEN malformed:=TRUE;RETURN;END_IF;token[tokenUsed]:=value;tokenUsed:=tokenUsed+1;token[tokenUsed]:=0;`,
873
- ),
874
- method(
875
- "ReadHex",
876
- "VAR value:UDINT;i:UINT;octet:BYTE;END_VAR",
877
- `numberValue:=0;FOR i:=1 TO 4 DO
828
+ );
829
+
830
+ const skipWhitespaceMethod = (owner: string) =>
831
+ privateMethod(
832
+ owner,
833
+ "SkipWhitespace",
834
+ "",
835
+ `WHILE cursor<=TO_UINT(ByteLength(payload)) DO IF payload[cursor-1]<>32 AND payload[cursor-1]<>9 AND payload[cursor-1]<>10 AND payload[cursor-1]<>13 THEN EXIT;END_IF;cursor:=cursor+1;END_WHILE;`,
836
+ );
837
+
838
+ const expectMethod = (owner: string) =>
839
+ privateMethod(
840
+ owner,
841
+ "Expect",
842
+ "VAR_INPUT value:BYTE; END_VAR",
843
+ `IF cursor>TO_UINT(ByteLength(payload)) OR_ELSE payload[cursor-1]<>value THEN malformed:=TRUE;ELSE cursor:=cursor+1;END_IF;`,
844
+ );
845
+
846
+ const tokenByteMethod = (owner: string) =>
847
+ privateMethod(
848
+ owner,
849
+ "TokenByte",
850
+ "VAR_INPUT value:BYTE;END_VAR",
851
+ `IF tokenUsed>=${plcBufferBytes} OR value=0 THEN malformed:=TRUE;RETURN;END_IF;token[tokenUsed]:=value;tokenUsed:=tokenUsed+1;token[tokenUsed]:=0;`,
852
+ );
853
+
854
+ const readHexMethod = (owner: string) =>
855
+ privateMethod(
856
+ owner,
857
+ "ReadHex",
858
+ "VAR value:UDINT;i:UINT;octet:BYTE;END_VAR",
859
+ `numberValue:=0;FOR i:=1 TO 4 DO
878
860
  IF cursor>TO_UINT(ByteLength(payload)) THEN malformed:=TRUE;RETURN;END_IF;
879
861
  octet:=payload[cursor-1];cursor:=cursor+1;
880
862
  IF octet>=48 AND octet<=57 THEN value:=TO_UDINT(octet-48);ELSIF octet>=65 AND octet<=70 THEN value:=TO_UDINT(octet-55);ELSIF octet>=97 AND octet<=102 THEN value:=TO_UDINT(octet-87);ELSE malformed:=TRUE;RETURN;END_IF;
881
863
  numberValue:=numberValue*16+TO_LINT(value);END_FOR;`,
882
- ),
883
- method(
884
- "ReadString",
885
- `VAR octet:BYTE;point:UDINT;high:UDINT;END_VAR`,
886
- `token:='';tokenUsed:=0;Expect(34);
864
+ );
865
+
866
+ const readStringMethod = (owner: string) =>
867
+ privateMethod(
868
+ owner,
869
+ "ReadString",
870
+ `VAR octet:BYTE;point:UDINT;high:UDINT;END_VAR`,
871
+ `token:='';tokenUsed:=0;Expect(34);
887
872
  WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
888
873
  octet:=payload[cursor-1];cursor:=cursor+1;
889
874
  IF octet=34 THEN ValidateUtf8();RETURN;END_IF;
@@ -908,11 +893,14 @@ WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
908
893
  END_CASE;
909
894
  ELSIF octet<32 THEN malformed:=TRUE;RETURN;ELSE TokenByte(octet);END_IF;
910
895
  END_WHILE;malformed:=TRUE;`,
911
- ),
912
- method(
913
- "ValidateUtf8",
914
- "VAR i:UINT;j:UINT;count:UINT;first:BYTE;next:BYTE;END_VAR",
915
- `i:=0;
896
+ );
897
+
898
+ const validateUtf8Method = (owner: string) =>
899
+ privateMethod(
900
+ owner,
901
+ "ValidateUtf8",
902
+ "VAR i:UINT;j:UINT;count:UINT;first:BYTE;next:BYTE;END_VAR",
903
+ `i:=0;
916
904
  WHILE i<tokenUsed AND NOT malformed DO
917
905
  first:=token[i];
918
906
  IF first<128 THEN i:=i+1;
@@ -925,11 +913,14 @@ WHILE i<tokenUsed AND NOT malformed DO
925
913
  i:=i+count+1;
926
914
  END_IF;
927
915
  END_WHILE;`,
928
- ),
929
- method(
930
- "ReadInteger",
931
- "VAR negative:BOOL;digits:UINT;octet:BYTE;END_VAR",
932
- `numberValue:=0;negative:=FALSE;digits:=0;
916
+ );
917
+
918
+ const readIntegerMethod = (owner: string) =>
919
+ privateMethod(
920
+ owner,
921
+ "ReadInteger",
922
+ "VAR negative:BOOL;digits:UINT;octet:BYTE;END_VAR",
923
+ `numberValue:=0;negative:=FALSE;digits:=0;
933
924
  IF payload[cursor-1]=45 THEN negative:=TRUE;cursor:=cursor+1;END_IF;
934
925
  WHILE cursor<=TO_UINT(ByteLength(payload)) DO
935
926
  octet:=payload[cursor-1];IF octet<48 OR octet>57 THEN EXIT;END_IF;
@@ -937,13 +928,45 @@ WHILE cursor<=TO_UINT(ByteLength(payload)) DO
937
928
  IF digits>0 AND numberValue=0 THEN malformed:=TRUE;RETURN;END_IF;numberValue:=numberValue*10+TO_LINT(octet-48);digits:=digits+1;cursor:=cursor+1;
938
929
  END_WHILE;
939
930
  IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberValue;END_IF;`,
940
- ),
941
- ].filter(
942
- (item) =>
943
- transport === "http" ||
944
- !["AppendWire", "FindHeaders", "ReadHeaders"].includes(item.name),
945
931
  );
946
- };
932
+
933
+ /** What the telemetry writer appends its records with. */
934
+ export const jsonEncoders = (owner: string): GeneratedObject[] => [
935
+ byteLengthMethod(owner),
936
+ appendMethod(owner),
937
+ writeStringMethod(owner),
938
+ ];
939
+
940
+ const jsonDecoders = (owner: string): GeneratedObject[] => [
941
+ skipWhitespaceMethod(owner),
942
+ expectMethod(owner),
943
+ tokenByteMethod(owner),
944
+ readHexMethod(owner),
945
+ readStringMethod(owner),
946
+ validateUtf8Method(owner),
947
+ readIntegerMethod(owner),
948
+ ];
949
+
950
+ /** The methods of a native HTTP client: the JSON codec's and those that frame its request and read the response's headers. */
951
+ export const httpClientMethods = (owner: string): GeneratedObject[] => [
952
+ byteLengthMethod(owner),
953
+ appendMethod(owner),
954
+ appendWireMethod(owner),
955
+ findHeadersMethod(owner),
956
+ matchLiteralMethod(owner),
957
+ readHeadersMethod(owner),
958
+ writeStringMethod(owner),
959
+ ...jsonDecoders(owner),
960
+ ];
961
+
962
+ /** The methods of an OPC UA client: the JSON codec's. */
963
+ export const opcuaClientMethods = (owner: string): GeneratedObject[] => [
964
+ byteLengthMethod(owner),
965
+ appendMethod(owner),
966
+ matchLiteralMethod(owner),
967
+ writeStringMethod(owner),
968
+ ...jsonDecoders(owner),
969
+ ];
947
970
 
948
971
  type ServiceRuntime = Extract<
949
972
  NonNullable<FunctionBlock["runtime"]>,
@@ -961,19 +984,16 @@ export function emitServiceBlock(
961
984
  { plan, symbols, instrumentation }: EmissionContext,
962
985
  networkName: string | undefined,
963
986
  fn: CoreFunctionBlock,
964
- ): { objects: GeneratedObject[]; rpcChannels: RpcChannel[] } {
987
+ ): { objects: GeneratedObject[]; rpcChannels: ServiceChannel[] } {
965
988
  const endpoint = required(plan.http[fn.id]);
966
989
  const name = required(symbols.blockNames.get(fn.id));
990
+ const runtime = fn.runtime;
967
991
  const codecs = serviceCodecs(
968
992
  fn,
969
993
  required(symbols.blockFields.get(fn.id)),
970
994
  symbols.typeMap,
971
995
  symbols.targetTypes,
972
996
  );
973
- const methods = [
974
- ...httpMethods(fn.id, endpoint.transport),
975
- ...httpCertificateVerifier(fn.id, name, endpoint),
976
- ];
977
997
  if (endpoint.transport === "opcua") {
978
998
  const slots = rpcSlots(symbols, fn.id, name, endpoint.path);
979
999
  return {
@@ -989,16 +1009,20 @@ export function emitServiceBlock(
989
1009
  body: `Append('{');${codecs.requestCode}Append('}');`,
990
1010
  decode: codecs.decodeResponse,
991
1011
  }),
992
- ...methods,
1012
+ ...opcuaClientMethods(fn.id),
993
1013
  ],
994
1014
  rpcChannels: slots.channels,
995
1015
  };
996
1016
  }
1017
+ if (runtime?.kind !== "http") {
1018
+ throw new Error(`Service block ${fn.id} has no HTTP runtime.`);
1019
+ }
997
1020
  const requestFields = instrumentation.fields.get(fn.id);
998
1021
  return {
999
1022
  objects: [
1000
1023
  ...httpServiceBlock(
1001
- fn,
1024
+ fn.id,
1025
+ runtime,
1002
1026
  name,
1003
1027
  codecs,
1004
1028
  endpoint,
@@ -1007,20 +1031,36 @@ export function emitServiceBlock(
1007
1031
  ? { job: requestFields.job, sequence: requestFields.sequence }
1008
1032
  : undefined,
1009
1033
  ),
1010
- ...methods,
1034
+ ...httpClientMethods(fn.id),
1035
+ ...httpCertificateVerifier(fn.id, name, endpoint),
1011
1036
  ],
1012
1037
  rpcChannels: [],
1013
1038
  };
1014
1039
  }
1015
1040
 
1041
+ /** The endpoints the program's HTTP clients call: its service blocks' and the telemetry sender's. */
1042
+ const nativeEndpoints = ({ http, telemetry }: CodesysPlan): NativeEndpoint[] =>
1043
+ [...Object.values(http), ...(telemetry ? [telemetry.endpoint] : [])].filter(
1044
+ (endpoint) => endpoint.transport === "http",
1045
+ );
1046
+
1047
+ /** The libraries the program's HTTP clients reference, beyond what the project template does. */
1048
+ export function httpLibraryReferences(plan: CodesysPlan): string[] {
1049
+ const endpoints = nativeEndpoints(plan);
1050
+ return [
1051
+ ...(endpoints.length ? ["Net Base Services, 4.0.0.0 (CODESYS)"] : []),
1052
+ ...(endpoints.some((endpoint) => endpoint.tls)
1053
+ ? ["CmpX509Cert Implementation, 3.5.22.0 (System)"]
1054
+ : []),
1055
+ ];
1056
+ }
1057
+
1016
1058
  /** `GVL_TsplcNetwork`, the Net Base Services task every HTTP client runs on, when one does. */
1017
1059
  export function httpNetwork(
1018
1060
  plan: CodesysPlan,
1019
- symbols: CodesysSymbols,
1061
+ symbols: GlobalSymbols,
1020
1062
  ): GeneratedObject | undefined {
1021
- if (
1022
- !Object.values(plan.http).some((endpoint) => endpoint.transport !== "opcua")
1023
- ) {
1063
+ if (!nativeEndpoints(plan).length) {
1024
1064
  return undefined;
1025
1065
  }
1026
1066
  return {