@tsplc/compiler 0.5.5 → 0.5.7

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 (80) hide show
  1. package/dist/bun-runtime.js +152 -31
  2. package/dist/bun-runtime.js.map +10 -9
  3. package/dist/cli.js +8 -5
  4. package/dist/cli.js.map +3 -3
  5. package/dist/codesys.js +260 -85
  6. package/dist/codesys.js.map +9 -9
  7. package/dist/collections.js +395 -0
  8. package/dist/collections.js.map +10 -0
  9. package/dist/elaborate-capture.js +62 -4
  10. package/dist/elaborate-capture.js.map +4 -4
  11. package/dist/index.js +5322 -1058
  12. package/dist/index.js.map +30 -23
  13. package/dist/ir.js +122 -1
  14. package/dist/ir.js.map +6 -6
  15. package/dist/project.js +8 -5
  16. package/dist/project.js.map +3 -3
  17. package/package.json +14 -9
  18. package/src/codesys/emit.ts +8 -2
  19. package/src/codesys/http.ts +114 -72
  20. package/src/codesys/instrumentation.ts +30 -6
  21. package/src/codesys/numeric.ts +61 -0
  22. package/src/codesys/routines.ts +39 -9
  23. package/src/codesys/st-files.ts +73 -6
  24. package/src/codesys/telemetry.ts +70 -35
  25. package/src/frontend/control-flow.ts +752 -0
  26. package/src/frontend/coroutines.ts +171 -7
  27. package/src/frontend/elaborate/array-searches.ts +216 -0
  28. package/src/frontend/elaborate/assignments.ts +352 -0
  29. package/src/frontend/elaborate/calls.ts +467 -42
  30. package/src/frontend/elaborate/capture-protocol.ts +19 -0
  31. package/src/frontend/elaborate/capture.ts +80 -2
  32. package/src/frontend/elaborate/dialect.ts +116 -2
  33. package/src/frontend/elaborate/expressions.ts +927 -80
  34. package/src/frontend/elaborate/filtered-arrays.ts +607 -0
  35. package/src/frontend/elaborate/frame.ts +44 -1
  36. package/src/frontend/elaborate/generics.ts +137 -0
  37. package/src/frontend/elaborate/graph.ts +91 -0
  38. package/src/frontend/elaborate/index.ts +30 -5
  39. package/src/frontend/elaborate/initializers.ts +15 -1
  40. package/src/frontend/elaborate/iterators.ts +1677 -0
  41. package/src/frontend/elaborate/layouts.ts +41 -19
  42. package/src/frontend/elaborate/model.ts +64 -8
  43. package/src/frontend/elaborate/references.ts +749 -0
  44. package/src/frontend/elaborate/specialize.ts +459 -29
  45. package/src/frontend/elaborate/statements.ts +552 -133
  46. package/src/frontend/elaborate/storage.ts +151 -10
  47. package/src/frontend/elaborate/values.ts +72 -0
  48. package/src/frontend/elaborate/writes.ts +302 -1
  49. package/src/frontend/intrinsics.ts +32 -0
  50. package/src/frontend/module-graph.ts +2 -1
  51. package/src/frontend/positions.ts +12 -5
  52. package/src/frontend/typescript.ts +5 -1
  53. package/src/ir/core-model.ts +2 -6
  54. package/src/ir/fold.ts +30 -1
  55. package/src/ir/index.ts +5 -0
  56. package/src/ir/model.ts +53 -2
  57. package/src/ir/scalars.ts +126 -0
  58. package/src/runtime/.runtime-VaUSOu/server/router.ts +17 -0
  59. package/src/runtime/.runtime-VaUSOu/src/cell.ts +45 -0
  60. package/src/runtime/.runtime-VaUSOu/src/controller.ts +58 -0
  61. package/src/runtime/.runtime-VaUSOu/src/lane.ts +6 -0
  62. package/src/runtime/.runtime-VaUSOu/src/main.ts +11 -0
  63. package/src/runtime/.runtime-VaUSOu/src/services.ts +8 -0
  64. package/src/runtime/.runtime-VaUSOu/tsconfig.json +13 -0
  65. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +31 -0
  66. package/src/runtime/.runtime-ybIxYh/server/router.ts +17 -0
  67. package/src/runtime/.runtime-ybIxYh/src/cell.ts +45 -0
  68. package/src/runtime/.runtime-ybIxYh/src/controller.ts +58 -0
  69. package/src/runtime/.runtime-ybIxYh/src/lane.ts +6 -0
  70. package/src/runtime/.runtime-ybIxYh/src/main.ts +11 -0
  71. package/src/runtime/.runtime-ybIxYh/src/services.ts +8 -0
  72. package/src/runtime/.runtime-ybIxYh/tsconfig.json +13 -0
  73. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +31 -0
  74. package/src/runtime/async.ts +15 -12
  75. package/src/runtime/launch.ts +11 -4
  76. package/src/runtime/runtime.ts +26 -23
  77. package/src/runtime/telemetry.ts +14 -6
  78. package/src/runtime/transport.ts +172 -0
  79. package/stdlib/collections.ts +514 -0
  80. package/types/index.d.ts +18 -0
@@ -4,7 +4,7 @@
4
4
  // packages/compiler/src/runtime/main.ts
5
5
  import { readFileSync as readFileSync2 } from "fs";
6
6
  import { rm, writeFile as writeFile2 } from "fs/promises";
7
- import { dirname as dirname2, join as join2 } from "path";
7
+ import { dirname as dirname2, join as join3 } from "path";
8
8
 
9
9
  // packages/compiler/src/runtime/launch.ts
10
10
  import { generatedDirectory } from "@tsplc/config/project-files";
@@ -30,8 +30,8 @@ var runtimeStateSchema = z.strictObject({
30
30
  });
31
31
 
32
32
  // packages/compiler/src/runtime/runtime.ts
33
- import { readFile as readFile2 } from "fs/promises";
34
- import { isAbsolute, join, relative as relative2, resolve } from "path";
33
+ import { readFile as readFile3 } from "fs/promises";
34
+ import { isAbsolute, join as join2, relative as relative2, resolve } from "path";
35
35
  import { errorName as errorName2 } from "@tsplc/compiler/ir";
36
36
  import { controllerDeviceName, loadTsplcConfig } from "@tsplc/config";
37
37
  import { emittedStDirectory } from "@tsplc/config/project-files";
@@ -222,14 +222,12 @@ var unsupported = (name) => () => {
222
222
  };
223
223
  var createAsync = (settings, diagnostics) => {
224
224
  const call = (path, input) => {
225
- const route = settings.routes[path];
226
- if (!route || settings.baseUrl === null) {
225
+ const route = settings.services.routes[path];
226
+ const { transport } = settings.services;
227
+ if (!route || !transport) {
227
228
  return Promise.reject(new Error(`The build compiled no call to the service ${path}.`));
228
229
  }
229
- return httpCall(settings, `${settings.baseUrl}${route}`, {
230
- method: "POST",
231
- body: JSON.stringify(input)
232
- });
230
+ return transport.call(route, JSON.stringify(input));
233
231
  };
234
232
  const client = (path) => new Proxy(() => {
235
233
  return;
@@ -239,7 +237,7 @@ var createAsync = (settings, diagnostics) => {
239
237
  });
240
238
  return {
241
239
  createServiceClient: () => client([]),
242
- fetch: (url, options = {}) => httpCall(settings, url, {
240
+ fetch: (url, options = {}) => httpCall(settings.http, url, {
243
241
  method: options.method ?? "GET",
244
242
  ...options.json !== undefined && {
245
243
  body: JSON.stringify(options.json)
@@ -306,9 +304,15 @@ import ts2 from "typescript";
306
304
 
307
305
  // packages/compiler/src/frontend/elaborate/capture-protocol.ts
308
306
  import { z as z2 } from "zod";
307
+ var closureSiteSchema = z2.strictObject({
308
+ start: z2.number().int().nonnegative(),
309
+ end: z2.number().int().nonnegative(),
310
+ captures: z2.array(z2.string())
311
+ });
309
312
  var captureRequestSchema = z2.strictObject({
310
313
  entry: z2.string().nonempty(),
311
314
  files: z2.array(z2.string().nonempty()),
315
+ closures: z2.record(z2.string(), z2.array(closureSiteSchema)),
312
316
  bindings: z2.record(z2.string(), z2.strictObject({
313
317
  values: z2.array(z2.string()),
314
318
  classes: z2.array(z2.string()),
@@ -350,7 +354,13 @@ var capturedNodeSchema = z2.discriminatedUnion("kind", [
350
354
  file: z2.string(),
351
355
  name: z2.string()
352
356
  }),
353
- z2.strictObject({ kind: z2.literal("service"), path: z2.string() })
357
+ z2.strictObject({ kind: z2.literal("service"), path: z2.string() }),
358
+ z2.strictObject({
359
+ kind: z2.literal("closure"),
360
+ file: z2.string(),
361
+ start: z2.number().int().nonnegative(),
362
+ captures: z2.array(z2.strictObject({ name: z2.string(), value: capturedValueSchema }))
363
+ })
354
364
  ]);
355
365
  var capturedGraphSchema = z2.strictObject({
356
366
  nodes: z2.array(capturedNodeSchema),
@@ -1001,6 +1011,7 @@ var createStorage = (manifest, binding) => {
1001
1011
  };
1002
1012
 
1003
1013
  // packages/compiler/src/runtime/telemetry.ts
1014
+ import { httpErrors as httpErrors3 } from "@tsplc/compiler/ir";
1004
1015
  import { plcBufferBytes as plcBufferBytes2 } from "@tsplc/server/wire";
1005
1016
  var batchWaitMs = 200;
1006
1017
  var createTelemetry = (options) => {
@@ -1068,10 +1079,16 @@ var createTelemetry = (options) => {
1068
1079
  }
1069
1080
  const sent = state.queued.slice(0, batch.count);
1070
1081
  state.sending = true;
1071
- post(batch.body).then(() => {
1082
+ const settle = () => {
1072
1083
  state.queued = state.queued.filter((queued) => !sent.includes(queued));
1073
1084
  state.waitingSince = options.clock();
1074
- }).catch(() => {
1085
+ };
1086
+ post(batch.body).then(settle).catch((reason) => {
1087
+ if (reason === httpErrors3.base + 400) {
1088
+ state.dropped += sent.length;
1089
+ settle();
1090
+ return;
1091
+ }
1075
1092
  state.waitingSince = options.clock();
1076
1093
  }).finally(() => {
1077
1094
  state.sending = false;
@@ -1080,6 +1097,116 @@ var createTelemetry = (options) => {
1080
1097
  return { record, send };
1081
1098
  };
1082
1099
 
1100
+ // packages/compiler/src/runtime/transport.ts
1101
+ import { readFile as readFile2 } from "fs/promises";
1102
+ import { join } from "path";
1103
+ import { httpErrors as httpErrors4, jobError as jobError3 } from "@tsplc/compiler/ir";
1104
+ import { emittedFiles } from "@tsplc/config/project-files";
1105
+ import { plcBufferBytes as plcBufferBytes3 } from "@tsplc/server/wire";
1106
+ import { z as z5 } from "zod";
1107
+ var httpTransport = (settings, baseUrl) => ({
1108
+ call: (route, body) => httpCall(settings, `${baseUrl}${route}`, { method: "POST", body })
1109
+ });
1110
+ var serviceChannel = z5.strictObject({
1111
+ path: z5.string(),
1112
+ request: z5.string(),
1113
+ requestId: z5.string(),
1114
+ reply: z5.string(),
1115
+ replyId: z5.string(),
1116
+ epoch: z5.string()
1117
+ });
1118
+ var readServiceChannels = async (st) => {
1119
+ const text = await readFile2(join(st, emittedFiles.machines), "utf8");
1120
+ const listed = /export const serviceChannels=([\s\S]*?) as const;/.exec(text);
1121
+ if (!listed?.[1]) {
1122
+ throw new Error(`${emittedFiles.machines} lists no service channels.`);
1123
+ }
1124
+ return z5.array(serviceChannel).parse(JSON.parse(listed[1]));
1125
+ };
1126
+ var sequenceLimit = 2 ** 32;
1127
+ var replyPollMs = 5;
1128
+ var decodeReply = (rest) => {
1129
+ if (Buffer.byteLength(rest, "utf8") < 4) {
1130
+ throw jobError3.malformedResponse;
1131
+ }
1132
+ if (rest.startsWith("4|")) {
1133
+ throw httpErrors4.base + 400;
1134
+ }
1135
+ if (!rest.startsWith("0|")) {
1136
+ throw jobError3.network;
1137
+ }
1138
+ try {
1139
+ return JSON.parse(rest.slice(2));
1140
+ } catch {
1141
+ throw jobError3.malformedResponse;
1142
+ }
1143
+ };
1144
+ var opcuaSlots = (channels, timeoutMs) => {
1145
+ const values = new Map(channels.flatMap((channel) => [
1146
+ channel.request,
1147
+ channel.requestId,
1148
+ channel.reply,
1149
+ channel.replyId,
1150
+ channel.epoch
1151
+ ].map((path) => [path, ""])));
1152
+ const read = (path) => values.get(path) ?? "";
1153
+ const slots = new Map(channels.map((channel) => [channel, { inUse: false, sequence: 0 }]));
1154
+ const awaitReply = async (channel, epoch, identity, deadline) => {
1155
+ const prefix = `${identity}|`;
1156
+ for (;; ) {
1157
+ if (performance.now() >= deadline) {
1158
+ throw jobError3.timeout;
1159
+ }
1160
+ if (read(channel.epoch) !== epoch) {
1161
+ throw jobError3.network;
1162
+ }
1163
+ const reply = read(channel.reply);
1164
+ if (read(channel.replyId) === identity && reply.startsWith(prefix)) {
1165
+ return decodeReply(reply.slice(prefix.length));
1166
+ }
1167
+ await Bun.sleep(replyPollMs);
1168
+ }
1169
+ };
1170
+ const call = async (route, body) => {
1171
+ const deadline = performance.now() + timeoutMs;
1172
+ const channel = channels.find((candidate) => candidate.path === route && read(candidate.epoch) !== "" && !slots.get(candidate)?.inUse);
1173
+ const slot = channel && slots.get(channel);
1174
+ if (!channel || !slot) {
1175
+ throw jobError3.noRequestSlot;
1176
+ }
1177
+ slot.inUse = true;
1178
+ try {
1179
+ slot.sequence = (slot.sequence + 1) % sequenceLimit;
1180
+ if (slot.sequence === 0) {
1181
+ values.set(channel.epoch, "");
1182
+ throw jobError3.network;
1183
+ }
1184
+ const epoch = read(channel.epoch);
1185
+ const identity = `${epoch}:${slot.sequence}`;
1186
+ const request = `${identity}|${body}`;
1187
+ if (Buffer.byteLength(request, "utf8") > plcBufferBytes3) {
1188
+ throw jobError3.tooLarge;
1189
+ }
1190
+ values.set(channel.request, request);
1191
+ values.set(channel.requestId, identity);
1192
+ return await awaitReply(channel, epoch, identity, deadline);
1193
+ } finally {
1194
+ values.set(channel.requestId, "");
1195
+ values.set(channel.request, "");
1196
+ slot.inUse = false;
1197
+ }
1198
+ };
1199
+ return {
1200
+ transport: { call },
1201
+ scalar: (path) => values.has(path) ? {
1202
+ read: () => read(path),
1203
+ write: (value) => {
1204
+ values.set(path, String(value));
1205
+ }
1206
+ } : undefined
1207
+ };
1208
+ };
1209
+
1083
1210
  // packages/compiler/src/runtime/runtime.ts
1084
1211
  var runtimeEndpoint = { host: "127.0.0.1", port: 4840 };
1085
1212
  var failureName = (reason) => {
@@ -1108,17 +1235,10 @@ var startRuntime = async (options) => {
1108
1235
  if (!compiler || !tasks) {
1109
1236
  throw new Error("The Bun runtime runs a TypeScript program.");
1110
1237
  }
1111
- if (config.server?.transport === "opcua") {
1112
- throw new Error("The Bun runtime calls services over HTTP; this program calls them through the OPC UA gateway.");
1113
- }
1114
1238
  const st = resolve(root, emittedStDirectory);
1115
- const manifest = debugManifest.parse(JSON.parse(await readFile2(join(st, debugManifestFile), "utf8")));
1239
+ const manifest = debugManifest.parse(JSON.parse(await readFile3(join2(st, debugManifestFile), "utf8")));
1116
1240
  const globals = plcGlobals(await readDeclarations(st));
1117
- const baseUrlEnv = config.server?.baseUrlEnv;
1118
- const baseUrl = baseUrlEnv && env[baseUrlEnv]?.replace(/\/+$/, "") || null;
1119
1241
  const http = {
1120
- baseUrl,
1121
- routes: launch.services,
1122
1242
  tokens: new Map((config.codesys?.http?.credentials ?? []).flatMap(({ originEnv, bearerTokenEnv }) => {
1123
1243
  const origin = URL.parse(env[originEnv] ?? "")?.origin;
1124
1244
  const token = env[bearerTokenEnv];
@@ -1126,15 +1246,16 @@ var startRuntime = async (options) => {
1126
1246
  })),
1127
1247
  timeoutMs: config.codesys?.http?.timeoutMs ?? 2000
1128
1248
  };
1249
+ const baseUrlEnv = config.server?.baseUrlEnv;
1250
+ const baseUrl = baseUrlEnv && env[baseUrlEnv]?.replace(/\/+$/, "") || null;
1251
+ const slots = config.server?.transport === "opcua" ? opcuaSlots(await readServiceChannels(st), http.timeoutMs) : null;
1252
+ const transport = slots?.transport ?? (baseUrl === null ? null : httpTransport(http, baseUrl));
1129
1253
  const current = { task: tasks[0]?.name ?? "", scan: 0, scanning: false };
1130
1254
  const diagnostics = { count: 0, lastError: 0 };
1131
1255
  const records = createTelemetry({
1132
1256
  build: manifest.build.id,
1133
1257
  capacity: config.telemetry?.capacity ?? 64,
1134
- post: baseUrl === null ? null : (body) => httpCall(http, `${baseUrl}/tsplc/telemetry`, {
1135
- method: "POST",
1136
- body
1137
- }),
1258
+ post: transport ? (body) => transport.call("/tsplc/telemetry", body) : null,
1138
1259
  clock: now
1139
1260
  });
1140
1261
  const stopTelemetry = onTelemetry((record) => records.record(current.task, {
@@ -1179,7 +1300,7 @@ var startRuntime = async (options) => {
1179
1300
  "@tsplc/compiler/retain": { retain },
1180
1301
  "@tsplc/compiler/telemetry": { telemetry, onTelemetry },
1181
1302
  "@tsplc/compiler/math": { min, max, clamp },
1182
- "@tsplc/compiler/async": createAsync(http, diagnostics),
1303
+ "@tsplc/compiler/async": createAsync({ http, services: { routes: launch.services, transport } }, diagnostics),
1183
1304
  "@tsplc/compiler/config": {
1184
1305
  env: (name) => {
1185
1306
  const value = env[name];
@@ -1203,7 +1324,7 @@ var startRuntime = async (options) => {
1203
1324
  storage.keepStoredValues();
1204
1325
  const scalars = new Map;
1205
1326
  const bound = (global) => scalarPaths(global).every(({ path }) => {
1206
- const scalar = storage.scalar(path);
1327
+ const scalar = storage.scalar(path) ?? slots?.scalar(path);
1207
1328
  if (scalar) {
1208
1329
  scalars.set(path, scalar);
1209
1330
  }
@@ -1211,7 +1332,7 @@ var startRuntime = async (options) => {
1211
1332
  });
1212
1333
  const published = globals.published.filter(bound);
1213
1334
  const unbound = globals.published.filter((global) => !published.includes(global));
1214
- const retention = createRetention(globals.retained, storage.scalar, join(root, runtimeDirectory, runtimeFiles.retain));
1335
+ const retention = createRetention(globals.retained, storage.scalar, join2(root, runtimeDirectory, runtimeFiles.retain));
1215
1336
  const restored = await retention.restore();
1216
1337
  if ("restored" in restored) {
1217
1338
  log(`Restored ${restored.restored} retained values.`);
@@ -1230,7 +1351,7 @@ var startRuntime = async (options) => {
1230
1351
  }
1231
1352
  return scalar;
1232
1353
  },
1233
- certificateDirectory: join(root, runtimeDirectory, runtimeFiles.certificates)
1354
+ certificateDirectory: join2(root, runtimeDirectory, runtimeFiles.certificates)
1234
1355
  }).catch((cause) => {
1235
1356
  throw cause instanceof Error && "code" in cause && cause.code === "EADDRINUSE" ? new Error(`Port ${options.port} is taken: stop the other PLC first, such as the CODESYS runtime \`tsplc run\` starts.`) : cause;
1236
1357
  });
@@ -1307,7 +1428,7 @@ var [launchFile, port] = process.argv.slice(2);
1307
1428
  if (!launchFile) {
1308
1429
  throw new Error("Usage: main.ts <launch.json> [port]");
1309
1430
  }
1310
- var stateFile = join2(dirname2(launchFile), runtimeFiles.state);
1431
+ var stateFile = join3(dirname2(launchFile), runtimeFiles.state);
1311
1432
  var log = (line) => console.log(`[tsplc runtime] ${line}`);
1312
1433
  try {
1313
1434
  const runtime = await startRuntime({
@@ -1341,5 +1462,5 @@ try {
1341
1462
  process.exit(1);
1342
1463
  }
1343
1464
 
1344
- //# debugId=D16BE9598D18F5E364756E2164756E21
1465
+ //# debugId=1A73F16FFD98272F64756E2164756E21
1345
1466
  //# sourceMappingURL=bun-runtime.js.map