@tsplc/compiler 0.4.4 → 0.5.1
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.
- package/dist/bun-runtime.js +1345 -0
- package/dist/bun-runtime.js.map +25 -0
- package/dist/cli.js +251 -46
- package/dist/cli.js.map +8 -6
- package/dist/codesys.js +11 -6
- package/dist/codesys.js.map +3 -3
- package/dist/elaborate-capture.js +5 -5
- package/dist/elaborate-capture.js.map +4 -4
- package/dist/index.js +15 -9
- package/dist/index.js.map +5 -5
- package/dist/project.js +45 -20
- package/dist/project.js.map +5 -4
- package/package.json +13 -9
- package/src/codesys/manifest.ts +8 -1
- package/src/frontend/elaborate/capture-protocol.ts +18 -0
- package/src/frontend/elaborate/capture.ts +3 -11
- package/src/frontend/elaborate/graph.ts +3 -2
- package/src/frontend/statements.ts +23 -6
- package/src/project/cli.ts +5 -0
- package/src/project/project-commands.ts +60 -6
- package/src/project/project.ts +4 -0
- package/src/runtime/async.ts +200 -0
- package/src/runtime/launch.ts +49 -0
- package/src/runtime/main.ts +54 -0
- package/src/runtime/process.ts +172 -0
- package/src/runtime/program.ts +142 -0
- package/src/runtime/retain.ts +100 -0
- package/src/runtime/runtime.ts +329 -0
- package/src/runtime/storage.ts +481 -0
- package/src/runtime/symbols.ts +153 -0
- package/src/runtime/telemetry.ts +123 -0
|
@@ -0,0 +1,1345 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// packages/compiler/src/runtime/main.ts
|
|
5
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
6
|
+
import { rm, writeFile as writeFile2 } from "fs/promises";
|
|
7
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
8
|
+
|
|
9
|
+
// packages/compiler/src/runtime/launch.ts
|
|
10
|
+
import { generatedDirectory } from "@tsplc/config/project-files";
|
|
11
|
+
import { serviceOfPath } from "@tsplc/server";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
var runtimeDirectory = `${generatedDirectory}/runtime`;
|
|
14
|
+
var runtimeFiles = {
|
|
15
|
+
launch: "launch.json",
|
|
16
|
+
state: "state.json",
|
|
17
|
+
retain: "retain.json",
|
|
18
|
+
log: "plc.log",
|
|
19
|
+
certificates: "pki"
|
|
20
|
+
};
|
|
21
|
+
var launchSchema = z.strictObject({
|
|
22
|
+
config: z.string().nonempty(),
|
|
23
|
+
target: z.string().nonempty().nullable(),
|
|
24
|
+
services: z.record(z.string(), z.string().startsWith("/tsplc/services/"))
|
|
25
|
+
});
|
|
26
|
+
var runtimeStateSchema = z.strictObject({
|
|
27
|
+
pid: z.number().int().positive(),
|
|
28
|
+
endpoint: z.string().startsWith("opc.tcp://"),
|
|
29
|
+
startedAt: z.iso.datetime()
|
|
30
|
+
});
|
|
31
|
+
|
|
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";
|
|
35
|
+
import { errorName as errorName2 } from "@tsplc/compiler/ir";
|
|
36
|
+
import { controllerDeviceName, loadTsplcConfig } from "@tsplc/config";
|
|
37
|
+
import { emittedStDirectory } from "@tsplc/config/project-files";
|
|
38
|
+
import { debugManifest, debugManifestFile } from "@tsplc/debug/manifest";
|
|
39
|
+
import {
|
|
40
|
+
servePublishedGlobals
|
|
41
|
+
} from "@tsplc/opcua/server";
|
|
42
|
+
import { readDeclarations } from "@tsplc/typegen/declarations";
|
|
43
|
+
|
|
44
|
+
// packages/compiler/stdlib/clock.ts
|
|
45
|
+
var now = () => Math.floor(performance.now());
|
|
46
|
+
|
|
47
|
+
// packages/compiler/stdlib/math.ts
|
|
48
|
+
function min(left, right) {
|
|
49
|
+
return left < right ? left : right;
|
|
50
|
+
}
|
|
51
|
+
function max(left, right) {
|
|
52
|
+
return left > right ? left : right;
|
|
53
|
+
}
|
|
54
|
+
function clamp(value, lower, upper) {
|
|
55
|
+
if (value < lower) {
|
|
56
|
+
return lower;
|
|
57
|
+
}
|
|
58
|
+
if (value > upper) {
|
|
59
|
+
return upper;
|
|
60
|
+
}
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// packages/compiler/stdlib/retain.ts
|
|
65
|
+
var retain = (value) => value;
|
|
66
|
+
|
|
67
|
+
// packages/compiler/stdlib/telemetry.ts
|
|
68
|
+
import { relative } from "path";
|
|
69
|
+
import { fileURLToPath } from "url";
|
|
70
|
+
|
|
71
|
+
// packages/compiler/src/ir/job-errors.ts
|
|
72
|
+
var jobError = {
|
|
73
|
+
cancelled: 1,
|
|
74
|
+
timeout: 2,
|
|
75
|
+
tooLarge: 3,
|
|
76
|
+
malformedResponse: 4,
|
|
77
|
+
network: 5,
|
|
78
|
+
tls: 6,
|
|
79
|
+
noRequestSlot: 7
|
|
80
|
+
};
|
|
81
|
+
var httpErrors = { base: 1e4, last: 10999 };
|
|
82
|
+
var jobErrors = {
|
|
83
|
+
[jobError.cancelled]: "cancelled",
|
|
84
|
+
[jobError.timeout]: "timeout",
|
|
85
|
+
[jobError.tooLarge]: "request or response too large to encode",
|
|
86
|
+
[jobError.malformedResponse]: "malformed response",
|
|
87
|
+
[jobError.network]: "network error or server restarted",
|
|
88
|
+
[jobError.tls]: "TLS error",
|
|
89
|
+
[jobError.noRequestSlot]: "no free request slot",
|
|
90
|
+
[httpErrors.base]: "HTTP status: 10000 + status code"
|
|
91
|
+
};
|
|
92
|
+
var errorName = (code) => {
|
|
93
|
+
if (code > httpErrors.base && code <= httpErrors.last) {
|
|
94
|
+
return `HTTP ${code - httpErrors.base}`;
|
|
95
|
+
}
|
|
96
|
+
return code < httpErrors.base ? jobErrors[code] : undefined;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
// packages/compiler/stdlib/telemetry.ts
|
|
100
|
+
class Text {
|
|
101
|
+
value;
|
|
102
|
+
constructor(value) {
|
|
103
|
+
this.value = value;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
var module = fileURLToPath(import.meta.url);
|
|
107
|
+
var collector;
|
|
108
|
+
var source = () => {
|
|
109
|
+
for (const line of new Error().stack?.split(`
|
|
110
|
+
`) ?? []) {
|
|
111
|
+
const [, file, lineNumber] = /\(?((?:\/|[A-Za-z]:\\)[^():]+):(\d+):\d+\)?$/.exec(line) ?? [];
|
|
112
|
+
if (file && file !== module) {
|
|
113
|
+
return `${relative(process.cwd(), file).replaceAll("\\", "/")}:${lineNumber}`;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return "";
|
|
117
|
+
};
|
|
118
|
+
var reportedValue = (value) => {
|
|
119
|
+
if (value instanceof Text) {
|
|
120
|
+
return value.value;
|
|
121
|
+
}
|
|
122
|
+
if (typeof value === "bigint") {
|
|
123
|
+
return Number(value);
|
|
124
|
+
}
|
|
125
|
+
return value;
|
|
126
|
+
};
|
|
127
|
+
var exceptionName = (error) => {
|
|
128
|
+
if (typeof error === "number") {
|
|
129
|
+
return errorName(error);
|
|
130
|
+
}
|
|
131
|
+
return error instanceof Error ? error.message : String(error);
|
|
132
|
+
};
|
|
133
|
+
var report = (record, properties = {}) => collector?.({
|
|
134
|
+
...record,
|
|
135
|
+
properties: Object.fromEntries(Object.entries(properties).map(([name, value]) => [
|
|
136
|
+
name,
|
|
137
|
+
reportedValue(value)
|
|
138
|
+
])),
|
|
139
|
+
source: source(),
|
|
140
|
+
scan: 0,
|
|
141
|
+
time: now()
|
|
142
|
+
});
|
|
143
|
+
var telemetry = {
|
|
144
|
+
capture: (event, properties) => report({ kind: "event", event }, properties),
|
|
145
|
+
info: (message, properties) => report({ kind: "log", level: "info", message }, properties),
|
|
146
|
+
warn: (message, properties) => report({ kind: "log", level: "warn", message }, properties),
|
|
147
|
+
error: (message, properties) => report({ kind: "log", level: "error", message }, properties),
|
|
148
|
+
captureException: (error, properties) => {
|
|
149
|
+
const code = typeof error === "number" ? error : 0;
|
|
150
|
+
const name = exceptionName(error);
|
|
151
|
+
report({ kind: "exception", code, ...name && { name }, handled: true }, properties);
|
|
152
|
+
},
|
|
153
|
+
text: (bytes, length) => {
|
|
154
|
+
const sent = bytes.slice(0, Math.max(0, Math.min(length, bytes.length)));
|
|
155
|
+
const end = sent.indexOf(0);
|
|
156
|
+
return new Text(new TextDecoder().decode(Uint8Array.from(end < 0 ? sent : sent.slice(0, end))));
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
var onTelemetry = (next) => {
|
|
160
|
+
collector = next;
|
|
161
|
+
return () => {
|
|
162
|
+
if (collector === next) {
|
|
163
|
+
collector = undefined;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
// packages/compiler/src/runtime/async.ts
|
|
169
|
+
import { httpErrors as httpErrors2, jobError as jobError2 } from "@tsplc/compiler/ir";
|
|
170
|
+
import { plcBufferBytes } from "@tsplc/server/wire";
|
|
171
|
+
var failure = (cause) => {
|
|
172
|
+
if (cause instanceof Error && cause.name === "TimeoutError") {
|
|
173
|
+
return jobError2.timeout;
|
|
174
|
+
}
|
|
175
|
+
const code = cause instanceof Error && "code" in cause ? String(cause.code) : "";
|
|
176
|
+
return /CERT|SSL|TLS|SELF_SIGNED|UNABLE_TO_VERIFY/.test(code) ? jobError2.tls : jobError2.network;
|
|
177
|
+
};
|
|
178
|
+
var boundedBody = async (response) => {
|
|
179
|
+
const declared = response.headers.get("content-length");
|
|
180
|
+
if (declared !== null && Number(declared) > plcBufferBytes) {
|
|
181
|
+
await response.body?.cancel();
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const body = new Uint8Array(await response.arrayBuffer());
|
|
185
|
+
return body.length > plcBufferBytes ? undefined : body;
|
|
186
|
+
};
|
|
187
|
+
var httpCall = async (settings, url, request) => {
|
|
188
|
+
const { body } = request;
|
|
189
|
+
if (body !== undefined && Buffer.byteLength(body, "utf8") > plcBufferBytes) {
|
|
190
|
+
throw jobError2.tooLarge;
|
|
191
|
+
}
|
|
192
|
+
const token = settings.tokens.get(URL.parse(url)?.origin ?? "");
|
|
193
|
+
const response = await globalThis.fetch(url, {
|
|
194
|
+
method: request.method,
|
|
195
|
+
headers: {
|
|
196
|
+
Accept: "application/json",
|
|
197
|
+
...body !== undefined && { "Content-Type": "application/json" },
|
|
198
|
+
...token !== undefined && { Authorization: `Bearer ${token}` }
|
|
199
|
+
},
|
|
200
|
+
...body !== undefined && { body },
|
|
201
|
+
signal: AbortSignal.timeout(settings.timeoutMs)
|
|
202
|
+
}).catch((cause) => {
|
|
203
|
+
throw failure(cause);
|
|
204
|
+
});
|
|
205
|
+
const reply = await boundedBody(response).catch((cause) => {
|
|
206
|
+
throw failure(cause);
|
|
207
|
+
});
|
|
208
|
+
if (!reply) {
|
|
209
|
+
throw jobError2.tooLarge;
|
|
210
|
+
}
|
|
211
|
+
if (!response.ok) {
|
|
212
|
+
throw Math.min(httpErrors2.base + response.status, httpErrors2.last);
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(reply));
|
|
216
|
+
} catch {
|
|
217
|
+
throw jobError2.malformedResponse;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
var unsupported = (name) => () => {
|
|
221
|
+
throw new Error(`${name} is not supported by the Bun runtime; run this program on CODESYS.`);
|
|
222
|
+
};
|
|
223
|
+
var createAsync = (settings, diagnostics) => {
|
|
224
|
+
const call = (path, input) => {
|
|
225
|
+
const route = settings.routes[path];
|
|
226
|
+
if (!route || settings.baseUrl === null) {
|
|
227
|
+
return Promise.reject(new Error(`The build compiled no call to the service ${path}.`));
|
|
228
|
+
}
|
|
229
|
+
return httpCall(settings, `${settings.baseUrl}${route}`, {
|
|
230
|
+
method: "POST",
|
|
231
|
+
body: JSON.stringify(input)
|
|
232
|
+
});
|
|
233
|
+
};
|
|
234
|
+
const client = (path) => new Proxy(() => {
|
|
235
|
+
return;
|
|
236
|
+
}, {
|
|
237
|
+
get: (_, key) => typeof key === "string" ? client([...path, key]) : undefined,
|
|
238
|
+
apply: (_, __, [input]) => call(path.join("."), input)
|
|
239
|
+
});
|
|
240
|
+
return {
|
|
241
|
+
createServiceClient: () => client([]),
|
|
242
|
+
fetch: (url, options = {}) => httpCall(settings, url, {
|
|
243
|
+
method: options.method ?? "GET",
|
|
244
|
+
...options.json !== undefined && {
|
|
245
|
+
body: JSON.stringify(options.json)
|
|
246
|
+
}
|
|
247
|
+
}),
|
|
248
|
+
sleep: (duration) => new Promise((resolve) => setTimeout(resolve, duration)),
|
|
249
|
+
errorCode: (reason) => typeof reason === "number" ? reason : 0,
|
|
250
|
+
asyncDiagnostics: () => ({ valid: true, ...diagnostics }),
|
|
251
|
+
cancelAsync: unsupported("cancelAsync"),
|
|
252
|
+
opcuaCall: unsupported("opcuaCall"),
|
|
253
|
+
tasks: { define: unsupported("tasks.define") },
|
|
254
|
+
backgroundTasks: { define: unsupported("backgroundTasks.define") },
|
|
255
|
+
cooperativeTasks: { define: unsupported("cooperativeTasks.define") }
|
|
256
|
+
};
|
|
257
|
+
};
|
|
258
|
+
var capacityError = jobError2.noRequestSlot;
|
|
259
|
+
var oneLaunchAtATime = (classes, options) => {
|
|
260
|
+
const running = new WeakMap;
|
|
261
|
+
for (const { name: className, prototype } of classes) {
|
|
262
|
+
for (const method of Object.getOwnPropertyNames(prototype)) {
|
|
263
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, method);
|
|
264
|
+
const original = descriptor?.value;
|
|
265
|
+
if (typeof original !== "function" || original.constructor.name !== "AsyncFunction") {
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const name = `${className}.${method}`;
|
|
269
|
+
Object.defineProperty(prototype, method, {
|
|
270
|
+
...descriptor,
|
|
271
|
+
value: function launch(...input) {
|
|
272
|
+
if (!options.scanning()) {
|
|
273
|
+
return original.apply(this, input);
|
|
274
|
+
}
|
|
275
|
+
const methods = running.get(this) ?? new Set;
|
|
276
|
+
running.set(this, methods);
|
|
277
|
+
if (methods.has(method)) {
|
|
278
|
+
options.diagnostics.count += 1;
|
|
279
|
+
options.diagnostics.lastError = capacityError;
|
|
280
|
+
return new Promise(() => {});
|
|
281
|
+
}
|
|
282
|
+
const started = original.apply(this, input);
|
|
283
|
+
if (!(started instanceof Promise)) {
|
|
284
|
+
return started;
|
|
285
|
+
}
|
|
286
|
+
methods.add(method);
|
|
287
|
+
const settled = started.then((value) => {
|
|
288
|
+
methods.delete(method);
|
|
289
|
+
return value;
|
|
290
|
+
}, (reason) => {
|
|
291
|
+
methods.delete(method);
|
|
292
|
+
throw reason;
|
|
293
|
+
});
|
|
294
|
+
options.failed.set(settled, name);
|
|
295
|
+
return settled;
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
// packages/compiler/src/runtime/program.ts
|
|
303
|
+
import { readFileSync, realpathSync } from "fs";
|
|
304
|
+
var {plugin } = globalThis.Bun;
|
|
305
|
+
import ts2 from "typescript";
|
|
306
|
+
|
|
307
|
+
// packages/compiler/src/frontend/elaborate/capture-protocol.ts
|
|
308
|
+
import { z as z2 } from "zod";
|
|
309
|
+
var captureRequestSchema = z2.strictObject({
|
|
310
|
+
entry: z2.string().nonempty(),
|
|
311
|
+
files: z2.array(z2.string().nonempty()),
|
|
312
|
+
bindings: z2.record(z2.string(), z2.strictObject({
|
|
313
|
+
values: z2.array(z2.string()),
|
|
314
|
+
classes: z2.array(z2.string()),
|
|
315
|
+
functions: z2.array(z2.string())
|
|
316
|
+
}))
|
|
317
|
+
});
|
|
318
|
+
var withBindingRegistry = (source, names, exportName) => `${source}
|
|
319
|
+
;export const ${exportName} = { values: { ${names.values.map((name) => `${JSON.stringify(name)}: () => ${name}`).join(", ")} }, classes: { ${names.classes.map((name) => `${JSON.stringify(name)}: ${name}`).join(", ")} }, functions: { ${names.functions.map((name) => `${JSON.stringify(name)}: ${name}`).join(", ")} } };
|
|
320
|
+
`;
|
|
321
|
+
var capturedValueSchema = z2.discriminatedUnion("kind", [
|
|
322
|
+
z2.strictObject({ kind: z2.literal("undefined") }),
|
|
323
|
+
z2.strictObject({ kind: z2.literal("number"), value: z2.number() }),
|
|
324
|
+
z2.strictObject({ kind: z2.literal("boolean"), value: z2.boolean() }),
|
|
325
|
+
z2.strictObject({ kind: z2.literal("string"), value: z2.string() }),
|
|
326
|
+
z2.strictObject({
|
|
327
|
+
kind: z2.literal("bigint"),
|
|
328
|
+
value: z2.string().regex(/^-?\d+$/)
|
|
329
|
+
}),
|
|
330
|
+
z2.strictObject({
|
|
331
|
+
kind: z2.literal("node"),
|
|
332
|
+
id: z2.number().int().nonnegative()
|
|
333
|
+
})
|
|
334
|
+
]);
|
|
335
|
+
var fieldsSchema = z2.record(z2.string(), capturedValueSchema);
|
|
336
|
+
var capturedNodeSchema = z2.discriminatedUnion("kind", [
|
|
337
|
+
z2.strictObject({ kind: z2.literal("object"), fields: fieldsSchema }),
|
|
338
|
+
z2.strictObject({
|
|
339
|
+
kind: z2.literal("instance"),
|
|
340
|
+
file: z2.string(),
|
|
341
|
+
name: z2.string(),
|
|
342
|
+
fields: fieldsSchema
|
|
343
|
+
}),
|
|
344
|
+
z2.strictObject({
|
|
345
|
+
kind: z2.literal("array"),
|
|
346
|
+
items: z2.array(capturedValueSchema)
|
|
347
|
+
}),
|
|
348
|
+
z2.strictObject({
|
|
349
|
+
kind: z2.literal("function"),
|
|
350
|
+
file: z2.string(),
|
|
351
|
+
name: z2.string()
|
|
352
|
+
}),
|
|
353
|
+
z2.strictObject({ kind: z2.literal("service"), path: z2.string() })
|
|
354
|
+
]);
|
|
355
|
+
var capturedGraphSchema = z2.strictObject({
|
|
356
|
+
nodes: z2.array(capturedNodeSchema),
|
|
357
|
+
bindings: z2.array(z2.strictObject({
|
|
358
|
+
file: z2.string(),
|
|
359
|
+
name: z2.string(),
|
|
360
|
+
value: capturedValueSchema
|
|
361
|
+
})),
|
|
362
|
+
retained: z2.array(z2.number().int().nonnegative())
|
|
363
|
+
}).superRefine((graph, context) => {
|
|
364
|
+
const references = [
|
|
365
|
+
...graph.bindings.map((binding) => binding.value),
|
|
366
|
+
...graph.nodes.flatMap((node) => {
|
|
367
|
+
if (node.kind === "array") {
|
|
368
|
+
return node.items;
|
|
369
|
+
}
|
|
370
|
+
if (node.kind === "object" || node.kind === "instance") {
|
|
371
|
+
return Object.values(node.fields);
|
|
372
|
+
}
|
|
373
|
+
return [];
|
|
374
|
+
})
|
|
375
|
+
];
|
|
376
|
+
for (const id of graph.retained) {
|
|
377
|
+
references.push({ kind: "node", id });
|
|
378
|
+
}
|
|
379
|
+
for (const value of references) {
|
|
380
|
+
if (value.kind === "node" && value.id >= graph.nodes.length) {
|
|
381
|
+
context.addIssue({
|
|
382
|
+
code: "custom",
|
|
383
|
+
message: `Captured value refers to missing node ${value.id}.`
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
// packages/compiler/src/frontend/elaborate/graph.ts
|
|
390
|
+
import ts from "typescript";
|
|
391
|
+
import { z as z3 } from "zod";
|
|
392
|
+
var bindingNames = (source) => {
|
|
393
|
+
const found = {
|
|
394
|
+
values: [],
|
|
395
|
+
classes: [],
|
|
396
|
+
functions: []
|
|
397
|
+
};
|
|
398
|
+
const bind = (name) => {
|
|
399
|
+
if (ts.isIdentifier(name)) {
|
|
400
|
+
found.values.push(name.text);
|
|
401
|
+
} else {
|
|
402
|
+
for (const element of name.elements) {
|
|
403
|
+
if (!ts.isOmittedExpression(element)) {
|
|
404
|
+
bind(element.name);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
for (const statement of source.statements) {
|
|
410
|
+
if (ts.isVariableStatement(statement)) {
|
|
411
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
412
|
+
bind(declaration.name);
|
|
413
|
+
}
|
|
414
|
+
} else if (ts.isClassDeclaration(statement) && statement.name) {
|
|
415
|
+
found.classes.push(statement.name.text);
|
|
416
|
+
} else if (ts.isFunctionDeclaration(statement) && statement.name && statement.body) {
|
|
417
|
+
found.functions.push(statement.name.text);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
for (const statement of source.statements) {
|
|
421
|
+
if (ts.isVariableStatement(statement)) {
|
|
422
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
423
|
+
if (ts.isIdentifier(declaration.name) && declaration.initializer && (ts.isArrowFunction(declaration.initializer) || ts.isFunctionExpression(declaration.initializer))) {
|
|
424
|
+
found.values = found.values.filter((name) => name !== declaration.name.getText());
|
|
425
|
+
found.functions.push(declaration.name.text);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
return found;
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
// packages/compiler/src/runtime/program.ts
|
|
434
|
+
var sdkKey = Symbol.for("tsplc.runtime.sdk");
|
|
435
|
+
var registryExport = "__tsplcRuntime";
|
|
436
|
+
var isRegistry = (value) => typeof value === "object" && value !== null && ("values" in value) && ("classes" in value) && ("functions" in value);
|
|
437
|
+
var escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
438
|
+
var loadProgram = async (options) => {
|
|
439
|
+
globalThis[sdkKey] = options.sdk;
|
|
440
|
+
const files = new Set(options.sources.map((file) => realpathSync(file)));
|
|
441
|
+
plugin({
|
|
442
|
+
name: "tsplc-runtime",
|
|
443
|
+
setup(build) {
|
|
444
|
+
for (const [specifier, exports] of Object.entries(options.sdk)) {
|
|
445
|
+
build.module(specifier, () => ({
|
|
446
|
+
contents: `const sdk = globalThis[Symbol.for("tsplc.runtime.sdk")][${JSON.stringify(specifier)}];
|
|
447
|
+
${Object.keys(exports).map((name) => `export const ${name} = sdk.${name};`).join(`
|
|
448
|
+
`)}
|
|
449
|
+
`,
|
|
450
|
+
loader: "js"
|
|
451
|
+
}));
|
|
452
|
+
}
|
|
453
|
+
if (!files.size) {
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
build.onLoad({ filter: new RegExp(`^(${[...files].map(escapeRegExp).join("|")})$`) }, ({ path }) => {
|
|
457
|
+
const text = readFileSync(path, "utf8");
|
|
458
|
+
return {
|
|
459
|
+
contents: withBindingRegistry(text, bindingNames(ts2.createSourceFile(path, text, ts2.ScriptTarget.Latest, true)), registryExport),
|
|
460
|
+
loader: path.endsWith("x") ? "tsx" : "ts"
|
|
461
|
+
};
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
const modules = new Map;
|
|
466
|
+
const load = async (file) => {
|
|
467
|
+
const real = realpathSync(file);
|
|
468
|
+
const known = modules.get(real);
|
|
469
|
+
if (known) {
|
|
470
|
+
return known;
|
|
471
|
+
}
|
|
472
|
+
const loaded = await import(real);
|
|
473
|
+
modules.set(real, loaded);
|
|
474
|
+
return loaded;
|
|
475
|
+
};
|
|
476
|
+
const programs = new Map;
|
|
477
|
+
for (const [key, entry] of Object.entries(options.entries)) {
|
|
478
|
+
const exported = (await load(entry.module))[entry.export];
|
|
479
|
+
if (typeof exported !== "function") {
|
|
480
|
+
throw new Error(`Program ${key}: ${entry.module} exports no function ${entry.export}.`);
|
|
481
|
+
}
|
|
482
|
+
programs.set(key, () => {
|
|
483
|
+
exported();
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
for (const file of files) {
|
|
487
|
+
await load(file);
|
|
488
|
+
}
|
|
489
|
+
const registries = [...modules].flatMap(([file, loaded]) => {
|
|
490
|
+
const registry = loaded[registryExport];
|
|
491
|
+
return isRegistry(registry) ? [{ file, registry }] : [];
|
|
492
|
+
}).sort((left, right) => Number(isEntry(right.file, options.entries)) - Number(isEntry(left.file, options.entries)));
|
|
493
|
+
const binding = (name) => {
|
|
494
|
+
for (const { registry } of registries) {
|
|
495
|
+
const read = Object.hasOwn(registry.values, name) ? registry.values[name] : undefined;
|
|
496
|
+
if (read) {
|
|
497
|
+
return read();
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return;
|
|
501
|
+
};
|
|
502
|
+
const classes = registries.flatMap(({ registry }) => Object.entries(registry.classes).flatMap(([name, value]) => {
|
|
503
|
+
const prototype = typeof value === "function" ? value.prototype : undefined;
|
|
504
|
+
return typeof prototype === "object" && prototype !== null ? [{ name, prototype }] : [];
|
|
505
|
+
}));
|
|
506
|
+
return { programs, binding, classes };
|
|
507
|
+
};
|
|
508
|
+
var isEntry = (file, entries) => Object.values(entries).some((entry) => realpathSync(entry.module) === file);
|
|
509
|
+
|
|
510
|
+
// packages/compiler/src/runtime/retain.ts
|
|
511
|
+
import { createHash } from "crypto";
|
|
512
|
+
import { mkdir, readFile, writeFile } from "fs/promises";
|
|
513
|
+
import { dirname } from "path";
|
|
514
|
+
import { z as z4 } from "zod";
|
|
515
|
+
|
|
516
|
+
// packages/compiler/src/runtime/symbols.ts
|
|
517
|
+
import { elementaryType } from "@tsplc/iec";
|
|
518
|
+
var integer = (text, where) => {
|
|
519
|
+
if (!/^-?\d+$/.test(text.trim())) {
|
|
520
|
+
throw new Error(`${where}: ${text} is not an integer literal.`);
|
|
521
|
+
}
|
|
522
|
+
return Number(text);
|
|
523
|
+
};
|
|
524
|
+
var enumMembers = (declaration) => {
|
|
525
|
+
const members = [];
|
|
526
|
+
for (const member of declaration.members) {
|
|
527
|
+
members.push({
|
|
528
|
+
name: member.name,
|
|
529
|
+
value: member.value === undefined ? (members.at(-1)?.value ?? -1) + 1 : integer(member.value, declaration.name)
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
return members;
|
|
533
|
+
};
|
|
534
|
+
var plcGlobals = (declarations) => {
|
|
535
|
+
const types = new Map(declarations.types.map((declaration) => [
|
|
536
|
+
declaration.name.toUpperCase(),
|
|
537
|
+
declaration
|
|
538
|
+
]));
|
|
539
|
+
const resolve = (reference, where) => {
|
|
540
|
+
switch (reference.kind) {
|
|
541
|
+
case "string":
|
|
542
|
+
return {
|
|
543
|
+
kind: "scalar",
|
|
544
|
+
iec: `${reference.name}(${integer(reference.length, where)})`
|
|
545
|
+
};
|
|
546
|
+
case "array": {
|
|
547
|
+
const [dimension, ...more] = reference.dimensions;
|
|
548
|
+
if (!dimension || more.length) {
|
|
549
|
+
throw new Error(`${where}: only one-dimensional arrays are published.`);
|
|
550
|
+
}
|
|
551
|
+
return {
|
|
552
|
+
kind: "array",
|
|
553
|
+
lower: integer(dimension.lower, where),
|
|
554
|
+
upper: integer(dimension.upper, where),
|
|
555
|
+
element: resolve(reference.element, where)
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
case "named": {
|
|
559
|
+
if (elementaryType(reference.name)) {
|
|
560
|
+
return { kind: "scalar", iec: reference.name.toUpperCase() };
|
|
561
|
+
}
|
|
562
|
+
const declaration = types.get(reference.name.toUpperCase());
|
|
563
|
+
if (!declaration) {
|
|
564
|
+
throw new Error(`${where}: type ${reference.name} is not declared.`);
|
|
565
|
+
}
|
|
566
|
+
return declared(declaration);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
const declared = (declaration) => {
|
|
571
|
+
switch (declaration.kind) {
|
|
572
|
+
case "alias":
|
|
573
|
+
return resolve(declaration.type, declaration.name);
|
|
574
|
+
case "enum":
|
|
575
|
+
return {
|
|
576
|
+
kind: "enum",
|
|
577
|
+
name: declaration.name,
|
|
578
|
+
base: declaration.base,
|
|
579
|
+
members: enumMembers(declaration)
|
|
580
|
+
};
|
|
581
|
+
case "struct":
|
|
582
|
+
return {
|
|
583
|
+
kind: "struct",
|
|
584
|
+
name: declaration.name,
|
|
585
|
+
members: declaration.members.map((member) => ({
|
|
586
|
+
name: member.name,
|
|
587
|
+
type: resolve(member.type, `${declaration.name}.${member.name}`)
|
|
588
|
+
}))
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
const variables = declarations.globals.flatMap((list) => list.constant ? [] : list.members.map((member) => ({
|
|
593
|
+
list: list.name,
|
|
594
|
+
name: member.name,
|
|
595
|
+
member
|
|
596
|
+
})));
|
|
597
|
+
const global = (variable, access) => ({
|
|
598
|
+
list: variable.list,
|
|
599
|
+
name: variable.name,
|
|
600
|
+
access,
|
|
601
|
+
type: resolve(variable.member.type, `${variable.list}.${variable.name}`)
|
|
602
|
+
});
|
|
603
|
+
return {
|
|
604
|
+
published: variables.flatMap((variable) => variable.member.symbol ? [global(variable, variable.member.symbol)] : []),
|
|
605
|
+
retained: variables.flatMap((variable) => variable.member.retain ? [global(variable, "read")] : [])
|
|
606
|
+
};
|
|
607
|
+
};
|
|
608
|
+
var scalarPaths = (global) => {
|
|
609
|
+
const walk = (path, type) => {
|
|
610
|
+
switch (type.kind) {
|
|
611
|
+
case "scalar":
|
|
612
|
+
case "enum":
|
|
613
|
+
return [{ path, type }];
|
|
614
|
+
case "struct":
|
|
615
|
+
return type.members.flatMap((member) => walk(`${path}.${member.name}`, member.type));
|
|
616
|
+
case "array":
|
|
617
|
+
return Array.from({ length: type.upper - type.lower + 1 }, (_, offset) => walk(`${path}[${type.lower + offset}]`, type.element)).flat();
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
return walk(`${global.list}.${global.name}`, global.type);
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
// packages/compiler/src/runtime/retain.ts
|
|
624
|
+
var retainedValue = z4.union([
|
|
625
|
+
z4.boolean(),
|
|
626
|
+
z4.number(),
|
|
627
|
+
z4.string(),
|
|
628
|
+
z4.strictObject({ bigint: z4.string().regex(/^-?\d+$/) })
|
|
629
|
+
]);
|
|
630
|
+
var retainedSchema = z4.strictObject({
|
|
631
|
+
layout: z4.string(),
|
|
632
|
+
values: z4.record(z4.string(), retainedValue)
|
|
633
|
+
});
|
|
634
|
+
var parsedJson = (text) => {
|
|
635
|
+
try {
|
|
636
|
+
return JSON.parse(text);
|
|
637
|
+
} catch {
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
};
|
|
641
|
+
var stored = (value) => typeof value === "bigint" ? { bigint: String(value) } : value;
|
|
642
|
+
var restored = (value) => typeof value === "object" ? BigInt(value.bigint) : value;
|
|
643
|
+
var createRetention = (globals, scalar, file) => {
|
|
644
|
+
const scalars = globals.flatMap(scalarPaths).flatMap(({ path, type }) => {
|
|
645
|
+
const bound = scalar(path);
|
|
646
|
+
return bound ? [{ path, type, bound }] : [];
|
|
647
|
+
});
|
|
648
|
+
const layout = createHash("sha256").update(JSON.stringify(scalars.map(({ path, type }) => [path, type]))).digest("hex");
|
|
649
|
+
return {
|
|
650
|
+
restore: async () => {
|
|
651
|
+
if (!scalars.length) {
|
|
652
|
+
return { none: true };
|
|
653
|
+
}
|
|
654
|
+
const text = await readFile(file, "utf8").catch(() => {
|
|
655
|
+
return;
|
|
656
|
+
});
|
|
657
|
+
if (text === undefined) {
|
|
658
|
+
return { none: true };
|
|
659
|
+
}
|
|
660
|
+
const saved = retainedSchema.safeParse(parsedJson(text));
|
|
661
|
+
if (!saved.success) {
|
|
662
|
+
return { discarded: `${file} is not a retain file` };
|
|
663
|
+
}
|
|
664
|
+
if (saved.data.layout !== layout) {
|
|
665
|
+
return { discarded: "the retained globals' layout changed" };
|
|
666
|
+
}
|
|
667
|
+
for (const { path, bound } of scalars) {
|
|
668
|
+
const value = saved.data.values[path];
|
|
669
|
+
if (value !== undefined) {
|
|
670
|
+
bound.write(restored(value));
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
return { restored: scalars.length };
|
|
674
|
+
},
|
|
675
|
+
save: async () => {
|
|
676
|
+
if (!scalars.length) {
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
await mkdir(dirname(file), { recursive: true });
|
|
680
|
+
await writeFile(file, `${JSON.stringify({
|
|
681
|
+
layout,
|
|
682
|
+
values: Object.fromEntries(scalars.map(({ path, bound }) => [path, stored(bound.read())]))
|
|
683
|
+
})}
|
|
684
|
+
`);
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
};
|
|
688
|
+
|
|
689
|
+
// packages/compiler/src/runtime/storage.ts
|
|
690
|
+
import { typeOf } from "@tsplc/debug/paths";
|
|
691
|
+
import { elementaryType as elementaryType2 } from "@tsplc/iec";
|
|
692
|
+
import { isArrayIndexSegment, symbolPathSegments } from "@tsplc/opcua/contract";
|
|
693
|
+
var joinSegments = (segments) => segments.reduce((prefix, segment) => segment.startsWith("[") ? prefix + segment : `${prefix}.${segment}`);
|
|
694
|
+
var propertyOf = (segment) => isArrayIndexSegment(segment) ? segment.slice(1, -1) : segment;
|
|
695
|
+
var isObject = (value) => typeof value === "object" && value !== null;
|
|
696
|
+
var fieldPlace = (parent, key) => ({
|
|
697
|
+
get: () => {
|
|
698
|
+
const holder = parent.get();
|
|
699
|
+
return isObject(holder) ? holder[key] : undefined;
|
|
700
|
+
},
|
|
701
|
+
set: (value) => {
|
|
702
|
+
const holder = parent.get();
|
|
703
|
+
if (isObject(holder)) {
|
|
704
|
+
holder[key] = value;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
});
|
|
708
|
+
var optionalValue = (type) => {
|
|
709
|
+
const [has, value, ...rest] = type.fields;
|
|
710
|
+
return type.name.startsWith("Optional_") && has?.name === "has" && value?.name === "value" && !rest.length ? value : undefined;
|
|
711
|
+
};
|
|
712
|
+
var integerWrap = (bits, signed) => {
|
|
713
|
+
switch (bits) {
|
|
714
|
+
case 8:
|
|
715
|
+
return signed ? (value) => value << 24 >> 24 : (value) => value & 255;
|
|
716
|
+
case 16:
|
|
717
|
+
return signed ? (value) => value << 16 >> 16 : (value) => value & 65535;
|
|
718
|
+
default:
|
|
719
|
+
return signed ? (value) => value | 0 : (value) => value >>> 0;
|
|
720
|
+
}
|
|
721
|
+
};
|
|
722
|
+
var truncateUtf8 = (text, capacity) => {
|
|
723
|
+
if (Buffer.byteLength(text, "utf8") <= capacity) {
|
|
724
|
+
return text;
|
|
725
|
+
}
|
|
726
|
+
const kept = [];
|
|
727
|
+
let bytes = 0;
|
|
728
|
+
for (const character of text) {
|
|
729
|
+
bytes += Buffer.byteLength(character, "utf8");
|
|
730
|
+
if (bytes > capacity) {
|
|
731
|
+
break;
|
|
732
|
+
}
|
|
733
|
+
kept.push(character);
|
|
734
|
+
}
|
|
735
|
+
return kept.join("");
|
|
736
|
+
};
|
|
737
|
+
var storedValue = (type) => {
|
|
738
|
+
if (type.kind !== "scalar") {
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
if (type.capacity !== undefined) {
|
|
742
|
+
const { capacity } = type;
|
|
743
|
+
return type.iec === "WSTRING" ? (value) => typeof value === "string" ? value.slice(0, capacity) : value : (value) => typeof value === "string" ? truncateUtf8(value, capacity) : value;
|
|
744
|
+
}
|
|
745
|
+
const elementary = elementaryType2(type.iec);
|
|
746
|
+
if (!elementary) {
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
if (elementary.family === "real") {
|
|
750
|
+
return elementary.bits === 32 ? (value) => typeof value === "number" ? Math.fround(value) : value : undefined;
|
|
751
|
+
}
|
|
752
|
+
const integer = elementary.family === "integer" || elementary.family === "bits";
|
|
753
|
+
const signed = elementary.family === "integer" && elementary.signed;
|
|
754
|
+
if (elementary.family === "duration" && elementary.bits === 32) {
|
|
755
|
+
return storedValue({ kind: "scalar", iec: "UDINT" });
|
|
756
|
+
}
|
|
757
|
+
if (!integer) {
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
if (elementary.bits === 64) {
|
|
761
|
+
return (value) => {
|
|
762
|
+
if (typeof value !== "bigint") {
|
|
763
|
+
return value;
|
|
764
|
+
}
|
|
765
|
+
return signed ? BigInt.asIntN(64, value) : BigInt.asUintN(64, value);
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
const wrap = integerWrap(elementary.bits, signed);
|
|
769
|
+
return (value) => typeof value === "number" && Number.isFinite(value) ? wrap(value) : value;
|
|
770
|
+
};
|
|
771
|
+
var scalarDefault = (type) => {
|
|
772
|
+
if (type.kind === "enum") {
|
|
773
|
+
return Math.min(...Object.values(type.members));
|
|
774
|
+
}
|
|
775
|
+
if (type.kind !== "scalar") {
|
|
776
|
+
return 0;
|
|
777
|
+
}
|
|
778
|
+
if (type.capacity !== undefined) {
|
|
779
|
+
return "";
|
|
780
|
+
}
|
|
781
|
+
const elementary = elementaryType2(type.iec);
|
|
782
|
+
if (elementary?.family === "bool") {
|
|
783
|
+
return false;
|
|
784
|
+
}
|
|
785
|
+
const wide = (elementary?.family === "integer" || elementary?.family === "bits") && elementary.bits === 64;
|
|
786
|
+
return wide ? 0n : 0;
|
|
787
|
+
};
|
|
788
|
+
var createStorage = (manifest, binding) => {
|
|
789
|
+
const type = (id) => typeOf(manifest, id);
|
|
790
|
+
const textMaps = new Map;
|
|
791
|
+
const enumTexts = (enumeration) => {
|
|
792
|
+
if (!textMaps.has(enumeration)) {
|
|
793
|
+
textMaps.set(enumeration, textMapsOf(enumeration));
|
|
794
|
+
}
|
|
795
|
+
return textMaps.get(enumeration);
|
|
796
|
+
};
|
|
797
|
+
const textMapsOf = (enumeration) => {
|
|
798
|
+
const texts = enumeration.texts;
|
|
799
|
+
if (!texts) {
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
const byText = new Map(Object.entries(texts).flatMap(([member, text]) => {
|
|
803
|
+
const value = enumeration.members[member];
|
|
804
|
+
return value === undefined ? [] : [[text, value]];
|
|
805
|
+
}));
|
|
806
|
+
const byValue = new Map(Object.entries(enumeration.members).map(([member, value]) => [
|
|
807
|
+
value,
|
|
808
|
+
texts[member]
|
|
809
|
+
]));
|
|
810
|
+
return { byText, byValue };
|
|
811
|
+
};
|
|
812
|
+
const elementKey = (array, index) => {
|
|
813
|
+
const keyType = array.index === undefined ? undefined : type(array.index);
|
|
814
|
+
if (keyType?.kind !== "enum") {
|
|
815
|
+
return String(index - array.lower);
|
|
816
|
+
}
|
|
817
|
+
return enumTexts(keyType)?.byValue.get(index) ?? String(index);
|
|
818
|
+
};
|
|
819
|
+
const programValue = (scalarType, value) => {
|
|
820
|
+
if (scalarType.kind === "enum") {
|
|
821
|
+
const texts = enumTexts(scalarType);
|
|
822
|
+
return texts ? texts.byValue.get(Number(value)) : value;
|
|
823
|
+
}
|
|
824
|
+
return value;
|
|
825
|
+
};
|
|
826
|
+
const plcValue = (scalarType, value) => {
|
|
827
|
+
if (scalarType.kind === "enum") {
|
|
828
|
+
const texts = enumTexts(scalarType);
|
|
829
|
+
if (texts) {
|
|
830
|
+
return typeof value === "string" ? texts.byText.get(value) ?? scalarDefault(scalarType) : scalarType.members.Undefined ?? scalarDefault(scalarType);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
if (typeof value === "boolean" || typeof value === "number" || typeof value === "bigint" || typeof value === "string") {
|
|
834
|
+
return value;
|
|
835
|
+
}
|
|
836
|
+
return scalarDefault(scalarType);
|
|
837
|
+
};
|
|
838
|
+
const defaultValue = (valueType) => {
|
|
839
|
+
switch (valueType.kind) {
|
|
840
|
+
case "scalar":
|
|
841
|
+
case "enum":
|
|
842
|
+
return programValue(valueType, scalarDefault(valueType));
|
|
843
|
+
case "array":
|
|
844
|
+
return Array.from({ length: valueType.length }, () => defaultValue(type(valueType.element)));
|
|
845
|
+
case "record":
|
|
846
|
+
if (optionalValue(valueType)) {
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
return Object.fromEntries(valueType.fields.map((field) => [
|
|
850
|
+
field.name,
|
|
851
|
+
defaultValue(type(field.type))
|
|
852
|
+
]));
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
const child = (parent, segment) => {
|
|
856
|
+
const { place } = parent;
|
|
857
|
+
if (parent.type.kind === "array" && isArrayIndexSegment(segment)) {
|
|
858
|
+
const index = Number(segment.slice(1, -1));
|
|
859
|
+
const array = parent.type;
|
|
860
|
+
if (index < array.lower || index >= array.lower + array.length) {
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
return {
|
|
864
|
+
type: type(array.element),
|
|
865
|
+
place: fieldPlace(place, elementKey(array, index))
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
if (parent.type.kind !== "record") {
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
const optional = optionalValue(parent.type);
|
|
872
|
+
if (optional && segment === "has") {
|
|
873
|
+
return {
|
|
874
|
+
type: { kind: "scalar", iec: "BOOL" },
|
|
875
|
+
place: {
|
|
876
|
+
get: () => place.get() !== undefined,
|
|
877
|
+
set: (present) => {
|
|
878
|
+
if (!present) {
|
|
879
|
+
place.set(undefined);
|
|
880
|
+
} else if (place.get() === undefined) {
|
|
881
|
+
place.set(defaultValue(type(optional.type)));
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
if (optional && segment === "value") {
|
|
888
|
+
return { type: type(optional.type), place };
|
|
889
|
+
}
|
|
890
|
+
const field = parent.type.fields.find((candidate) => candidate.target === segment);
|
|
891
|
+
return field && { type: type(field.type), place: fieldPlace(place, field.name) };
|
|
892
|
+
};
|
|
893
|
+
const rootPlace = (path) => {
|
|
894
|
+
const [name, ...steps] = symbolPathSegments(path);
|
|
895
|
+
if (name === undefined || binding(name) === undefined) {
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
const start = {
|
|
899
|
+
get: () => binding(name),
|
|
900
|
+
set: () => {
|
|
901
|
+
throw new Error(`${name} is a module binding; the runtime can't replace it.`);
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
return steps.reduce((place, step) => fieldPlace(place, propertyOf(step)), start);
|
|
905
|
+
};
|
|
906
|
+
const roots = manifest.roots.flatMap((root) => {
|
|
907
|
+
const place = rootPlace(root.path);
|
|
908
|
+
return place ? [{ ...root, place }] : [];
|
|
909
|
+
});
|
|
910
|
+
const rootsByTarget = new Map(roots.map((root) => [root.target, root]));
|
|
911
|
+
const locate = (path) => {
|
|
912
|
+
const segments = symbolPathSegments(path);
|
|
913
|
+
const length = Array.from({ length: segments.length }, (_, offset) => segments.length - offset).find((prefix) => rootsByTarget.has(joinSegments(segments.slice(0, prefix))));
|
|
914
|
+
const root = length === undefined ? undefined : rootsByTarget.get(joinSegments(segments.slice(0, length)));
|
|
915
|
+
if (!root) {
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
return segments.slice(length).reduce((node, segment) => node && child(node, segment), { type: type(root.type), place: root.place });
|
|
919
|
+
};
|
|
920
|
+
const scalar = (path) => {
|
|
921
|
+
const node = locate(path);
|
|
922
|
+
if (!node || node.type.kind !== "scalar" && node.type.kind !== "enum") {
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
925
|
+
const { type: scalarType, place } = node;
|
|
926
|
+
return {
|
|
927
|
+
read: () => plcValue(scalarType, place.get()),
|
|
928
|
+
write: (value) => place.set(programValue(scalarType, value))
|
|
929
|
+
};
|
|
930
|
+
};
|
|
931
|
+
const keepStoredValues = () => {
|
|
932
|
+
const kept = new WeakSet;
|
|
933
|
+
const keep = (holder, key, valueType) => {
|
|
934
|
+
const descriptor = Object.getOwnPropertyDescriptor(holder, key);
|
|
935
|
+
if (!descriptor || !("value" in descriptor) || !descriptor.writable || !descriptor.configurable) {
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
const store = storing(valueType);
|
|
939
|
+
if (!store) {
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
let stored = store(descriptor.value);
|
|
943
|
+
Object.defineProperty(holder, key, {
|
|
944
|
+
configurable: true,
|
|
945
|
+
enumerable: descriptor.enumerable,
|
|
946
|
+
get: () => stored,
|
|
947
|
+
set: (value) => {
|
|
948
|
+
stored = store(value);
|
|
949
|
+
}
|
|
950
|
+
});
|
|
951
|
+
};
|
|
952
|
+
const storing = (valueType) => {
|
|
953
|
+
if (valueType.kind === "record") {
|
|
954
|
+
const optional = optionalValue(valueType);
|
|
955
|
+
if (optional) {
|
|
956
|
+
return storing(type(optional.type));
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
if (valueType.kind === "record" || valueType.kind === "array") {
|
|
960
|
+
return (value) => {
|
|
961
|
+
within(valueType, value);
|
|
962
|
+
return value;
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
return storedValue(valueType);
|
|
966
|
+
};
|
|
967
|
+
const within = (valueType, value) => {
|
|
968
|
+
if (!isObject(value) || kept.has(value)) {
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
kept.add(value);
|
|
972
|
+
if (valueType.kind === "record") {
|
|
973
|
+
for (const field of valueType.fields) {
|
|
974
|
+
keep(value, field.name, type(field.type));
|
|
975
|
+
}
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
if (valueType.kind === "array") {
|
|
979
|
+
for (let index = valueType.lower;index < valueType.lower + valueType.length; index++) {
|
|
980
|
+
keep(value, elementKey(valueType, index), type(valueType.element));
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
for (const root of roots) {
|
|
985
|
+
const rootType = type(root.type);
|
|
986
|
+
const [name, ...steps] = symbolPathSegments(root.path);
|
|
987
|
+
const holderPath = steps.slice(0, -1);
|
|
988
|
+
const last = steps.at(-1);
|
|
989
|
+
if (name === undefined || last === undefined) {
|
|
990
|
+
within(rootType, root.place.get());
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
const start = { get: () => binding(name), set: () => {} };
|
|
994
|
+
const holder = holderPath.reduce((place, step) => fieldPlace(place, propertyOf(step)), start).get();
|
|
995
|
+
if (isObject(holder)) {
|
|
996
|
+
keep(holder, propertyOf(last), rootType);
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
};
|
|
1000
|
+
return { scalar, keepStoredValues };
|
|
1001
|
+
};
|
|
1002
|
+
|
|
1003
|
+
// packages/compiler/src/runtime/telemetry.ts
|
|
1004
|
+
import { plcBufferBytes as plcBufferBytes2 } from "@tsplc/server/wire";
|
|
1005
|
+
var batchWaitMs = 200;
|
|
1006
|
+
var createTelemetry = (options) => {
|
|
1007
|
+
const tasks = new Map;
|
|
1008
|
+
const stateOf = (task) => {
|
|
1009
|
+
const known = tasks.get(task);
|
|
1010
|
+
if (known) {
|
|
1011
|
+
return known;
|
|
1012
|
+
}
|
|
1013
|
+
const created = {
|
|
1014
|
+
queued: [],
|
|
1015
|
+
next: 0,
|
|
1016
|
+
dropped: 0,
|
|
1017
|
+
sending: false,
|
|
1018
|
+
waitingSince: 0
|
|
1019
|
+
};
|
|
1020
|
+
tasks.set(task, created);
|
|
1021
|
+
return created;
|
|
1022
|
+
};
|
|
1023
|
+
const record = (task, value) => {
|
|
1024
|
+
const state = stateOf(task);
|
|
1025
|
+
const text = JSON.stringify(value);
|
|
1026
|
+
if (!state.queued.length) {
|
|
1027
|
+
state.waitingSince = options.clock();
|
|
1028
|
+
}
|
|
1029
|
+
state.queued.push({ sequence: state.next, text });
|
|
1030
|
+
state.next += 1;
|
|
1031
|
+
if (state.queued.length > options.capacity) {
|
|
1032
|
+
state.queued.shift();
|
|
1033
|
+
state.dropped += 1;
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
const batchOf = (task, scan) => {
|
|
1037
|
+
const state = stateOf(task);
|
|
1038
|
+
const envelope = (records, first) => `{"build":${JSON.stringify(options.build)},"task":${JSON.stringify(task)},"now":${Math.max(0, options.clock())},"scan":${scan},"first":${first},"dropped":${state.dropped},"records":[${records.join(",")}]}`;
|
|
1039
|
+
const first = state.queued[0]?.sequence ?? state.next;
|
|
1040
|
+
const texts = [];
|
|
1041
|
+
for (const queued of state.queued) {
|
|
1042
|
+
const candidate = envelope([...texts, queued.text], first);
|
|
1043
|
+
if (Buffer.byteLength(candidate, "utf8") > plcBufferBytes2) {
|
|
1044
|
+
break;
|
|
1045
|
+
}
|
|
1046
|
+
texts.push(queued.text);
|
|
1047
|
+
}
|
|
1048
|
+
return { body: envelope(texts, first), count: texts.length };
|
|
1049
|
+
};
|
|
1050
|
+
const send = (task, scan) => {
|
|
1051
|
+
const state = stateOf(task);
|
|
1052
|
+
const { post } = options;
|
|
1053
|
+
if (!post || state.sending || !state.queued.length) {
|
|
1054
|
+
if (!post) {
|
|
1055
|
+
state.queued = [];
|
|
1056
|
+
}
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
const batch = batchOf(task, scan);
|
|
1060
|
+
const full = batch.count < state.queued.length;
|
|
1061
|
+
if (!full && options.clock() - state.waitingSince < batchWaitMs) {
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
if (!batch.count) {
|
|
1065
|
+
state.queued.shift();
|
|
1066
|
+
state.dropped += 1;
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
const sent = state.queued.slice(0, batch.count);
|
|
1070
|
+
state.sending = true;
|
|
1071
|
+
post(batch.body).then(() => {
|
|
1072
|
+
state.queued = state.queued.filter((queued) => !sent.includes(queued));
|
|
1073
|
+
state.waitingSince = options.clock();
|
|
1074
|
+
}).catch(() => {
|
|
1075
|
+
state.waitingSince = options.clock();
|
|
1076
|
+
}).finally(() => {
|
|
1077
|
+
state.sending = false;
|
|
1078
|
+
});
|
|
1079
|
+
};
|
|
1080
|
+
return { record, send };
|
|
1081
|
+
};
|
|
1082
|
+
|
|
1083
|
+
// packages/compiler/src/runtime/runtime.ts
|
|
1084
|
+
var runtimeEndpoint = { host: "127.0.0.1", port: 4840 };
|
|
1085
|
+
var failureName = (reason) => {
|
|
1086
|
+
if (typeof reason === "number") {
|
|
1087
|
+
return errorName2(reason);
|
|
1088
|
+
}
|
|
1089
|
+
return reason instanceof Error ? reason.message : String(reason);
|
|
1090
|
+
};
|
|
1091
|
+
var projectSource = (root, source) => {
|
|
1092
|
+
if (typeof source !== "string" || !source) {
|
|
1093
|
+
return "";
|
|
1094
|
+
}
|
|
1095
|
+
const separator = source.lastIndexOf(":");
|
|
1096
|
+
const file = resolve(source.slice(0, separator));
|
|
1097
|
+
const path = relative2(root, file);
|
|
1098
|
+
return `${isAbsolute(path) ? file : path.replaceAll("\\", "/")}${source.slice(separator)}`;
|
|
1099
|
+
};
|
|
1100
|
+
var startRuntime = async (options) => {
|
|
1101
|
+
const { launch, log } = options;
|
|
1102
|
+
const { config, root, env } = await loadTsplcConfig(launch.config, {
|
|
1103
|
+
env: options.environment,
|
|
1104
|
+
target: launch.target ?? undefined,
|
|
1105
|
+
forAgent: false
|
|
1106
|
+
});
|
|
1107
|
+
const { compiler, tasks } = config;
|
|
1108
|
+
if (!compiler || !tasks) {
|
|
1109
|
+
throw new Error("The Bun runtime runs a TypeScript program.");
|
|
1110
|
+
}
|
|
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
|
+
const st = resolve(root, emittedStDirectory);
|
|
1115
|
+
const manifest = debugManifest.parse(JSON.parse(await readFile2(join(st, debugManifestFile), "utf8")));
|
|
1116
|
+
const globals = plcGlobals(await readDeclarations(st));
|
|
1117
|
+
const baseUrlEnv = config.server?.baseUrlEnv;
|
|
1118
|
+
const baseUrl = baseUrlEnv && env[baseUrlEnv]?.replace(/\/+$/, "") || null;
|
|
1119
|
+
const http = {
|
|
1120
|
+
baseUrl,
|
|
1121
|
+
routes: launch.services,
|
|
1122
|
+
tokens: new Map((config.codesys?.http?.credentials ?? []).flatMap(({ originEnv, bearerTokenEnv }) => {
|
|
1123
|
+
const origin = URL.parse(env[originEnv] ?? "")?.origin;
|
|
1124
|
+
const token = env[bearerTokenEnv];
|
|
1125
|
+
return origin && token ? [[origin, token]] : [];
|
|
1126
|
+
})),
|
|
1127
|
+
timeoutMs: config.codesys?.http?.timeoutMs ?? 2000
|
|
1128
|
+
};
|
|
1129
|
+
const current = { task: tasks[0]?.name ?? "", scan: 0, scanning: false };
|
|
1130
|
+
const diagnostics = { count: 0, lastError: 0 };
|
|
1131
|
+
const records = createTelemetry({
|
|
1132
|
+
build: manifest.build.id,
|
|
1133
|
+
capacity: config.telemetry?.capacity ?? 64,
|
|
1134
|
+
post: baseUrl === null ? null : (body) => httpCall(http, `${baseUrl}/tsplc/telemetry`, {
|
|
1135
|
+
method: "POST",
|
|
1136
|
+
body
|
|
1137
|
+
}),
|
|
1138
|
+
clock: now
|
|
1139
|
+
});
|
|
1140
|
+
const stopTelemetry = onTelemetry((record) => records.record(current.task, {
|
|
1141
|
+
...record,
|
|
1142
|
+
scan: current.scan,
|
|
1143
|
+
source: projectSource(root, record.source)
|
|
1144
|
+
}));
|
|
1145
|
+
const failed = new WeakMap;
|
|
1146
|
+
const unhandled = (reason, promise) => {
|
|
1147
|
+
const code = typeof reason === "number" ? reason : 0;
|
|
1148
|
+
if (code === 1) {
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
diagnostics.count += 1;
|
|
1152
|
+
diagnostics.lastError = code;
|
|
1153
|
+
const name = failureName(reason);
|
|
1154
|
+
const fn = failed.get(promise);
|
|
1155
|
+
records.record(current.task, {
|
|
1156
|
+
kind: "exception",
|
|
1157
|
+
code,
|
|
1158
|
+
...name && { name },
|
|
1159
|
+
handled: false,
|
|
1160
|
+
...fn && { function: fn },
|
|
1161
|
+
properties: {},
|
|
1162
|
+
source: "",
|
|
1163
|
+
scan: current.scan,
|
|
1164
|
+
time: Math.max(0, now())
|
|
1165
|
+
});
|
|
1166
|
+
if (typeof reason !== "number") {
|
|
1167
|
+
log(`An async call failed and nothing caught it: ${String(reason)}`);
|
|
1168
|
+
}
|
|
1169
|
+
};
|
|
1170
|
+
process.on("unhandledRejection", unhandled);
|
|
1171
|
+
const program = await loadProgram({
|
|
1172
|
+
sources: manifest.sources.map((source) => resolve(root, source)),
|
|
1173
|
+
entries: Object.fromEntries(Object.entries(compiler.programs).map(([key, entry]) => [
|
|
1174
|
+
key,
|
|
1175
|
+
{ module: resolve(root, entry.module), export: entry.export }
|
|
1176
|
+
])),
|
|
1177
|
+
sdk: {
|
|
1178
|
+
"@tsplc/compiler/clock": { now },
|
|
1179
|
+
"@tsplc/compiler/retain": { retain },
|
|
1180
|
+
"@tsplc/compiler/telemetry": { telemetry, onTelemetry },
|
|
1181
|
+
"@tsplc/compiler/math": { min, max, clamp },
|
|
1182
|
+
"@tsplc/compiler/async": createAsync(http, diagnostics),
|
|
1183
|
+
"@tsplc/compiler/config": {
|
|
1184
|
+
env: (name) => {
|
|
1185
|
+
const value = env[name];
|
|
1186
|
+
if (value === undefined) {
|
|
1187
|
+
throw new Error(`${name} is not set.`);
|
|
1188
|
+
}
|
|
1189
|
+
return value;
|
|
1190
|
+
}
|
|
1191
|
+
},
|
|
1192
|
+
"@tsplc/compiler/plc": { expose: unsupported("expose") }
|
|
1193
|
+
}
|
|
1194
|
+
}).catch((cause) => {
|
|
1195
|
+
throw new Error("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.", { cause });
|
|
1196
|
+
});
|
|
1197
|
+
oneLaunchAtATime(program.classes, {
|
|
1198
|
+
scanning: () => current.scanning,
|
|
1199
|
+
diagnostics,
|
|
1200
|
+
failed
|
|
1201
|
+
});
|
|
1202
|
+
const storage = createStorage(manifest, program.binding);
|
|
1203
|
+
storage.keepStoredValues();
|
|
1204
|
+
const scalars = new Map;
|
|
1205
|
+
const bound = (global) => scalarPaths(global).every(({ path }) => {
|
|
1206
|
+
const scalar = storage.scalar(path);
|
|
1207
|
+
if (scalar) {
|
|
1208
|
+
scalars.set(path, scalar);
|
|
1209
|
+
}
|
|
1210
|
+
return scalar !== undefined;
|
|
1211
|
+
});
|
|
1212
|
+
const published = globals.published.filter(bound);
|
|
1213
|
+
const unbound = globals.published.filter((global) => !published.includes(global));
|
|
1214
|
+
const retention = createRetention(globals.retained, storage.scalar, join(root, runtimeDirectory, runtimeFiles.retain));
|
|
1215
|
+
const restored = await retention.restore();
|
|
1216
|
+
if ("restored" in restored) {
|
|
1217
|
+
log(`Restored ${restored.restored} retained values.`);
|
|
1218
|
+
} else if ("discarded" in restored) {
|
|
1219
|
+
log(`Retained values start from their initial values: ${restored.discarded}.`);
|
|
1220
|
+
}
|
|
1221
|
+
const server = await servePublishedGlobals({
|
|
1222
|
+
host: runtimeEndpoint.host,
|
|
1223
|
+
port: options.port,
|
|
1224
|
+
device: controllerDeviceName(config, "run"),
|
|
1225
|
+
globals: published,
|
|
1226
|
+
scalar: (path) => {
|
|
1227
|
+
const scalar = scalars.get(path);
|
|
1228
|
+
if (!scalar) {
|
|
1229
|
+
throw new Error(`${path} has no storage in the program.`);
|
|
1230
|
+
}
|
|
1231
|
+
return scalar;
|
|
1232
|
+
},
|
|
1233
|
+
certificateDirectory: join(root, runtimeDirectory, runtimeFiles.certificates)
|
|
1234
|
+
}).catch((cause) => {
|
|
1235
|
+
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
|
+
});
|
|
1237
|
+
const timers = new Map;
|
|
1238
|
+
const stopped = { value: false };
|
|
1239
|
+
const stopTasks = () => {
|
|
1240
|
+
stopped.value = true;
|
|
1241
|
+
for (const timer of timers.values()) {
|
|
1242
|
+
clearTimeout(timer);
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
1245
|
+
for (const task of tasks) {
|
|
1246
|
+
const intervalMs = Number(task.schedule.interval.nanoseconds) / 1e6;
|
|
1247
|
+
const entries = task.programs.flatMap((key) => {
|
|
1248
|
+
const entry = program.programs.get(key);
|
|
1249
|
+
return entry ? [entry] : [];
|
|
1250
|
+
});
|
|
1251
|
+
const state = { scan: 0, due: performance.now() };
|
|
1252
|
+
const schedule = () => {
|
|
1253
|
+
timers.set(task.name, setTimeout(scan, Math.max(0, state.due - performance.now())));
|
|
1254
|
+
};
|
|
1255
|
+
const scan = () => {
|
|
1256
|
+
if (stopped.value) {
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
state.scan += 1;
|
|
1260
|
+
Object.assign(current, {
|
|
1261
|
+
task: task.name,
|
|
1262
|
+
scan: state.scan,
|
|
1263
|
+
scanning: true
|
|
1264
|
+
});
|
|
1265
|
+
try {
|
|
1266
|
+
records.send(task.name, state.scan);
|
|
1267
|
+
for (const entry of entries) {
|
|
1268
|
+
entry();
|
|
1269
|
+
}
|
|
1270
|
+
} catch (error) {
|
|
1271
|
+
stopTasks();
|
|
1272
|
+
log(`${task.name} stopped in scan ${state.scan}: the program threw, which stops the application as an exception stops it on CODESYS. Restart the runtime.
|
|
1273
|
+
${error instanceof Error ? error.stack ?? error.message : String(error)}`);
|
|
1274
|
+
return;
|
|
1275
|
+
} finally {
|
|
1276
|
+
current.scanning = false;
|
|
1277
|
+
}
|
|
1278
|
+
state.due = Math.max(state.due + intervalMs, performance.now());
|
|
1279
|
+
schedule();
|
|
1280
|
+
};
|
|
1281
|
+
schedule();
|
|
1282
|
+
log(`${task.name} scans ${task.programs.join(", ")} every ${intervalMs} ms.`);
|
|
1283
|
+
}
|
|
1284
|
+
if (unbound.length) {
|
|
1285
|
+
log(`Not published, because the program has no storage for them: ${unbound.map(({ list, name }) => `${list}.${name}`).join(", ")}.`);
|
|
1286
|
+
}
|
|
1287
|
+
log(`${config.name} runs in Bun. OPC UA: ${server.endpoint} (${server.scalars} published values).`);
|
|
1288
|
+
return {
|
|
1289
|
+
endpoint: server.endpoint,
|
|
1290
|
+
stop: async () => {
|
|
1291
|
+
stopTasks();
|
|
1292
|
+
stopTelemetry();
|
|
1293
|
+
try {
|
|
1294
|
+
await retention.save();
|
|
1295
|
+
} finally {
|
|
1296
|
+
await server.stop().catch((cause) => {
|
|
1297
|
+
log(`The OPC UA server failed to stop cleanly: ${String(cause)}`);
|
|
1298
|
+
});
|
|
1299
|
+
process.off("unhandledRejection", unhandled);
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
};
|
|
1303
|
+
};
|
|
1304
|
+
|
|
1305
|
+
// packages/compiler/src/runtime/main.ts
|
|
1306
|
+
var [launchFile, port] = process.argv.slice(2);
|
|
1307
|
+
if (!launchFile) {
|
|
1308
|
+
throw new Error("Usage: main.ts <launch.json> [port]");
|
|
1309
|
+
}
|
|
1310
|
+
var stateFile = join2(dirname2(launchFile), runtimeFiles.state);
|
|
1311
|
+
var log = (line) => console.log(`[tsplc runtime] ${line}`);
|
|
1312
|
+
try {
|
|
1313
|
+
const runtime = await startRuntime({
|
|
1314
|
+
launch: launchSchema.parse(JSON.parse(readFileSync2(launchFile, "utf8"))),
|
|
1315
|
+
environment: process.env,
|
|
1316
|
+
port: port === undefined ? runtimeEndpoint.port : Number(port),
|
|
1317
|
+
log
|
|
1318
|
+
});
|
|
1319
|
+
await writeFile2(stateFile, `${JSON.stringify({
|
|
1320
|
+
pid: process.pid,
|
|
1321
|
+
endpoint: runtime.endpoint,
|
|
1322
|
+
startedAt: new Date().toISOString()
|
|
1323
|
+
})}
|
|
1324
|
+
`);
|
|
1325
|
+
const stop = async (signal) => {
|
|
1326
|
+
log(`Stopping on ${signal}.`);
|
|
1327
|
+
try {
|
|
1328
|
+
await runtime.stop();
|
|
1329
|
+
} finally {
|
|
1330
|
+
await rm(stateFile, { force: true });
|
|
1331
|
+
process.exit(0);
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
process.once("SIGINT", stop);
|
|
1335
|
+
process.once("SIGTERM", stop);
|
|
1336
|
+
} catch (cause) {
|
|
1337
|
+
console.error(`[tsplc runtime] ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
1338
|
+
if (cause instanceof Error && cause.cause) {
|
|
1339
|
+
console.error(cause.cause);
|
|
1340
|
+
}
|
|
1341
|
+
process.exit(1);
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
//# debugId=D16BE9598D18F5E364756E2164756E21
|
|
1345
|
+
//# sourceMappingURL=bun-runtime.js.map
|