@tsplc/compiler 0.5.0 → 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 +3 -3
- package/dist/index.js.map +4 -4
- 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/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,200 @@
|
|
|
1
|
+
import { httpErrors, jobError } from "@tsplc/compiler/ir";
|
|
2
|
+
import { plcBufferBytes } from "@tsplc/server/wire";
|
|
3
|
+
|
|
4
|
+
/** How the program's HTTP calls reach their servers, as the build compiled them. */
|
|
5
|
+
export interface HttpSettings {
|
|
6
|
+
/** The services' base URL, from `server.baseUrlEnv`; null without a server. */
|
|
7
|
+
baseUrl: string | null;
|
|
8
|
+
/** Each service procedure's route, by its path such as `catalog.resolve`. */
|
|
9
|
+
routes: Readonly<Record<string, string>>;
|
|
10
|
+
/** Bearer tokens by the exact origin they are sent to. */
|
|
11
|
+
tokens: ReadonlyMap<string, string>;
|
|
12
|
+
timeoutMs: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Why the program's call failed, as a compiled call reports it: a job error code. */
|
|
16
|
+
const failure = (cause: unknown) => {
|
|
17
|
+
if (cause instanceof Error && cause.name === "TimeoutError") {
|
|
18
|
+
return jobError.timeout;
|
|
19
|
+
}
|
|
20
|
+
const code =
|
|
21
|
+
cause instanceof Error && "code" in cause ? String(cause.code) : "";
|
|
22
|
+
return /CERT|SSL|TLS|SELF_SIGNED|UNABLE_TO_VERIFY/.test(code)
|
|
23
|
+
? jobError.tls
|
|
24
|
+
: jobError.network;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** The body of a response, at most the PLC's buffer; undefined when larger. */
|
|
28
|
+
const boundedBody = async (response: Response) => {
|
|
29
|
+
const declared = response.headers.get("content-length");
|
|
30
|
+
if (declared !== null && Number(declared) > plcBufferBytes) {
|
|
31
|
+
await response.body?.cancel();
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
const body = new Uint8Array(await response.arrayBuffer());
|
|
35
|
+
return body.length > plcBufferBytes ? undefined : body;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* One HTTP exchange as a compiled call makes it: bounded JSON both ways, the bearer token of the
|
|
40
|
+
* URL's origin, the configured timeout and no retry. It rejects with the compiled call's error
|
|
41
|
+
* code, a number, never an Error.
|
|
42
|
+
*/
|
|
43
|
+
export const httpCall = async (
|
|
44
|
+
settings: Pick<HttpSettings, "tokens" | "timeoutMs">,
|
|
45
|
+
url: string,
|
|
46
|
+
request: { method: string; body?: string },
|
|
47
|
+
): Promise<unknown> => {
|
|
48
|
+
const { body } = request;
|
|
49
|
+
if (body !== undefined && Buffer.byteLength(body, "utf8") > plcBufferBytes) {
|
|
50
|
+
throw jobError.tooLarge;
|
|
51
|
+
}
|
|
52
|
+
const token = settings.tokens.get(URL.parse(url)?.origin ?? "");
|
|
53
|
+
const response = await globalThis
|
|
54
|
+
.fetch(url, {
|
|
55
|
+
method: request.method,
|
|
56
|
+
headers: {
|
|
57
|
+
Accept: "application/json",
|
|
58
|
+
...(body !== undefined && { "Content-Type": "application/json" }),
|
|
59
|
+
...(token !== undefined && { Authorization: `Bearer ${token}` }),
|
|
60
|
+
},
|
|
61
|
+
...(body !== undefined && { body }),
|
|
62
|
+
signal: AbortSignal.timeout(settings.timeoutMs),
|
|
63
|
+
})
|
|
64
|
+
.catch((cause: unknown) => {
|
|
65
|
+
throw failure(cause);
|
|
66
|
+
});
|
|
67
|
+
const reply = await boundedBody(response).catch((cause: unknown) => {
|
|
68
|
+
throw failure(cause);
|
|
69
|
+
});
|
|
70
|
+
if (!reply) {
|
|
71
|
+
throw jobError.tooLarge;
|
|
72
|
+
}
|
|
73
|
+
if (!response.ok) {
|
|
74
|
+
throw Math.min(httpErrors.base + response.status, httpErrors.last);
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(reply));
|
|
78
|
+
} catch {
|
|
79
|
+
throw jobError.malformedResponse;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** An SDK function the Bun runtime has no implementation of: it throws when the program calls it. */
|
|
84
|
+
export const unsupported = (name: string) => () => {
|
|
85
|
+
throw new Error(
|
|
86
|
+
`${name} is not supported by the Bun runtime; run this program on CODESYS.`,
|
|
87
|
+
);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/** What the program's `@tsplc/compiler/async` does in the Bun runtime. */
|
|
91
|
+
export const createAsync = (
|
|
92
|
+
settings: HttpSettings,
|
|
93
|
+
diagnostics: { count: number; lastError: number },
|
|
94
|
+
) => {
|
|
95
|
+
const call = (path: string, input: unknown) => {
|
|
96
|
+
const route = settings.routes[path];
|
|
97
|
+
if (!route || settings.baseUrl === null) {
|
|
98
|
+
return Promise.reject(
|
|
99
|
+
new Error(`The build compiled no call to the service ${path}.`),
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
return httpCall(settings, `${settings.baseUrl}${route}`, {
|
|
103
|
+
method: "POST",
|
|
104
|
+
body: JSON.stringify(input),
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
/** A service client: any property is a deeper procedure path, and calling one calls that procedure. */
|
|
108
|
+
const client = (path: readonly string[]): unknown =>
|
|
109
|
+
new Proxy(() => undefined, {
|
|
110
|
+
get: (_, key) =>
|
|
111
|
+
typeof key === "string" ? client([...path, key]) : undefined,
|
|
112
|
+
apply: (_, __, [input]: unknown[]) => call(path.join("."), input),
|
|
113
|
+
});
|
|
114
|
+
return {
|
|
115
|
+
createServiceClient: () => client([]),
|
|
116
|
+
fetch: (url: string, options: { method?: string; json?: unknown } = {}) =>
|
|
117
|
+
httpCall(settings, url, {
|
|
118
|
+
method: options.method ?? "GET",
|
|
119
|
+
...(options.json !== undefined && {
|
|
120
|
+
body: JSON.stringify(options.json),
|
|
121
|
+
}),
|
|
122
|
+
}),
|
|
123
|
+
// A sleep resumes on a later scan, even `sleep(ms(0))`: scans never yield to timers.
|
|
124
|
+
sleep: (duration: number) =>
|
|
125
|
+
new Promise<void>((resolve) => setTimeout(resolve, duration)),
|
|
126
|
+
errorCode: (reason: unknown) => (typeof reason === "number" ? reason : 0),
|
|
127
|
+
asyncDiagnostics: () => ({ valid: true, ...diagnostics }),
|
|
128
|
+
cancelAsync: unsupported("cancelAsync"),
|
|
129
|
+
opcuaCall: unsupported("opcuaCall"),
|
|
130
|
+
tasks: { define: unsupported("tasks.define") },
|
|
131
|
+
backgroundTasks: { define: unsupported("backgroundTasks.define") },
|
|
132
|
+
cooperativeTasks: { define: unsupported("cooperativeTasks.define") },
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/** What a launch dropped because its call site was busy reports, as a compiled launch does. */
|
|
137
|
+
const capacityError = jobError.noRequestSlot;
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* A compiled program stores one invocation of each async method per instance: launching it
|
|
141
|
+
* from scan code while that invocation runs is dropped, counted with error 7 and never settles,
|
|
142
|
+
* so neither its `then` nor its `catch` runs. The program's classes get the same rule here.
|
|
143
|
+
* A launch from a continuation is an awaited child, which has storage of its own, so it runs.
|
|
144
|
+
* `failed` names a method's rejected promise for an unhandled-failure record.
|
|
145
|
+
*/
|
|
146
|
+
export const oneLaunchAtATime = (
|
|
147
|
+
classes: Iterable<{ name: string; prototype: object }>,
|
|
148
|
+
options: {
|
|
149
|
+
scanning: () => boolean;
|
|
150
|
+
diagnostics: { count: number; lastError: number };
|
|
151
|
+
failed: WeakMap<Promise<unknown>, string>;
|
|
152
|
+
},
|
|
153
|
+
) => {
|
|
154
|
+
const running = new WeakMap<object, Set<string>>();
|
|
155
|
+
for (const { name: className, prototype } of classes) {
|
|
156
|
+
for (const method of Object.getOwnPropertyNames(prototype)) {
|
|
157
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, method);
|
|
158
|
+
const original: unknown = descriptor?.value;
|
|
159
|
+
if (
|
|
160
|
+
typeof original !== "function" ||
|
|
161
|
+
original.constructor.name !== "AsyncFunction"
|
|
162
|
+
) {
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
const name = `${className}.${method}`;
|
|
166
|
+
Object.defineProperty(prototype, method, {
|
|
167
|
+
...descriptor,
|
|
168
|
+
value: function launch(this: object, ...input: unknown[]) {
|
|
169
|
+
if (!options.scanning()) {
|
|
170
|
+
return original.apply(this, input);
|
|
171
|
+
}
|
|
172
|
+
const methods = running.get(this) ?? new Set<string>();
|
|
173
|
+
running.set(this, methods);
|
|
174
|
+
if (methods.has(method)) {
|
|
175
|
+
options.diagnostics.count += 1;
|
|
176
|
+
options.diagnostics.lastError = capacityError;
|
|
177
|
+
return new Promise(() => {});
|
|
178
|
+
}
|
|
179
|
+
const started: unknown = original.apply(this, input);
|
|
180
|
+
if (!(started instanceof Promise)) {
|
|
181
|
+
return started;
|
|
182
|
+
}
|
|
183
|
+
methods.add(method);
|
|
184
|
+
const settled = started.then(
|
|
185
|
+
(value: unknown) => {
|
|
186
|
+
methods.delete(method);
|
|
187
|
+
return value;
|
|
188
|
+
},
|
|
189
|
+
(reason: unknown) => {
|
|
190
|
+
methods.delete(method);
|
|
191
|
+
throw reason;
|
|
192
|
+
},
|
|
193
|
+
);
|
|
194
|
+
options.failed.set(settled, name);
|
|
195
|
+
return settled;
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { VerifiedCoreModule } from "@tsplc/compiler/ir";
|
|
2
|
+
import { generatedDirectory } from "@tsplc/config/project-files";
|
|
3
|
+
import { serviceOfPath } from "@tsplc/server";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
|
|
6
|
+
/** The Bun runtime's files, relative to the directory that holds a project's config. */
|
|
7
|
+
export const runtimeDirectory = `${generatedDirectory}/runtime`;
|
|
8
|
+
export const runtimeFiles = {
|
|
9
|
+
/** What the runtime runs, written by `tsplc run --bun`. */
|
|
10
|
+
launch: "launch.json",
|
|
11
|
+
/** The running runtime, written once it serves and removed when it stops. */
|
|
12
|
+
state: "state.json",
|
|
13
|
+
/** Retained globals, written when the runtime stops. */
|
|
14
|
+
retain: "retain.json",
|
|
15
|
+
/** A detached runtime's output. */
|
|
16
|
+
log: "plc.log",
|
|
17
|
+
/** The OPC UA server's certificate store. */
|
|
18
|
+
certificates: "pki",
|
|
19
|
+
} as const;
|
|
20
|
+
|
|
21
|
+
/** What `tsplc run --bun` hands the runtime: the config to load, with its target, and how to reach the services the build compiled calls to. */
|
|
22
|
+
export const launchSchema = z.strictObject({
|
|
23
|
+
config: z.string().nonempty(),
|
|
24
|
+
target: z.string().nonempty().nullable(),
|
|
25
|
+
/** Each service procedure's route, with its wire-contract version: `/tsplc/services/<version>/<path>` by `<path>`. */
|
|
26
|
+
services: z.record(z.string(), z.string().startsWith("/tsplc/services/")),
|
|
27
|
+
});
|
|
28
|
+
export type Launch = z.infer<typeof launchSchema>;
|
|
29
|
+
|
|
30
|
+
/** A runtime that serves: its process and where it publishes OPC UA. */
|
|
31
|
+
export const runtimeStateSchema = z.strictObject({
|
|
32
|
+
pid: z.number().int().positive(),
|
|
33
|
+
endpoint: z.string().startsWith("opc.tcp://"),
|
|
34
|
+
startedAt: z.iso.datetime(),
|
|
35
|
+
});
|
|
36
|
+
export type RuntimeState = z.infer<typeof runtimeStateSchema>;
|
|
37
|
+
|
|
38
|
+
/** The route each service call the program makes goes to, as the build compiled it. */
|
|
39
|
+
export const serviceRoutes = (core: VerifiedCoreModule) =>
|
|
40
|
+
Object.fromEntries(
|
|
41
|
+
core.blocks.flatMap((block) => {
|
|
42
|
+
if (block.runtime?.kind !== "http") {
|
|
43
|
+
return [];
|
|
44
|
+
}
|
|
45
|
+
const route = URL.parse(block.runtime.url)?.pathname;
|
|
46
|
+
const procedure = route && serviceOfPath(route);
|
|
47
|
+
return route && procedure ? [[procedure, route] as const] : [];
|
|
48
|
+
}),
|
|
49
|
+
);
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* The Bun runtime's process: runs the program a launch file names until SIGINT or SIGTERM, and
|
|
4
|
+
* writes the state file beside the launch file while it serves.
|
|
5
|
+
*
|
|
6
|
+
* Usage: bun main.ts <launch.json> [port]
|
|
7
|
+
*/
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import { rm, writeFile } from "node:fs/promises";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { launchSchema, type RuntimeState, runtimeFiles } from "./launch.ts";
|
|
12
|
+
import { runtimeEndpoint, startRuntime } from "./runtime.ts";
|
|
13
|
+
|
|
14
|
+
const [launchFile, port] = process.argv.slice(2);
|
|
15
|
+
if (!launchFile) {
|
|
16
|
+
throw new Error("Usage: main.ts <launch.json> [port]");
|
|
17
|
+
}
|
|
18
|
+
const stateFile = join(dirname(launchFile), runtimeFiles.state);
|
|
19
|
+
const log = (line: string) => console.log(`[tsplc runtime] ${line}`);
|
|
20
|
+
try {
|
|
21
|
+
const runtime = await startRuntime({
|
|
22
|
+
launch: launchSchema.parse(JSON.parse(readFileSync(launchFile, "utf8"))),
|
|
23
|
+
environment: process.env,
|
|
24
|
+
port: port === undefined ? runtimeEndpoint.port : Number(port),
|
|
25
|
+
log,
|
|
26
|
+
});
|
|
27
|
+
await writeFile(
|
|
28
|
+
stateFile,
|
|
29
|
+
`${JSON.stringify({
|
|
30
|
+
pid: process.pid,
|
|
31
|
+
endpoint: runtime.endpoint,
|
|
32
|
+
startedAt: new Date().toISOString(),
|
|
33
|
+
} satisfies RuntimeState)}\n`,
|
|
34
|
+
);
|
|
35
|
+
const stop = async (signal: string) => {
|
|
36
|
+
log(`Stopping on ${signal}.`);
|
|
37
|
+
try {
|
|
38
|
+
await runtime.stop();
|
|
39
|
+
} finally {
|
|
40
|
+
await rm(stateFile, { force: true });
|
|
41
|
+
process.exit(0);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
process.once("SIGINT", stop);
|
|
45
|
+
process.once("SIGTERM", stop);
|
|
46
|
+
} catch (cause) {
|
|
47
|
+
console.error(
|
|
48
|
+
`[tsplc runtime] ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
49
|
+
);
|
|
50
|
+
if (cause instanceof Error && cause.cause) {
|
|
51
|
+
console.error(cause.cause);
|
|
52
|
+
}
|
|
53
|
+
process.exit(1);
|
|
54
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, openSync } from "node:fs";
|
|
3
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { join, relative } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { type ProgressStream, progressLog } from "@tsplc/build";
|
|
8
|
+
import {
|
|
9
|
+
type Launch,
|
|
10
|
+
type RuntimeState,
|
|
11
|
+
runtimeDirectory,
|
|
12
|
+
runtimeFiles,
|
|
13
|
+
runtimeStateSchema,
|
|
14
|
+
} from "./launch.ts";
|
|
15
|
+
|
|
16
|
+
/** How long a runtime has to start serving, and to stop. */
|
|
17
|
+
const startTimeoutMs = 60_000;
|
|
18
|
+
const stopTimeoutMs = 15_000;
|
|
19
|
+
|
|
20
|
+
/** The runtime's entry: this source tree's, or the bundle a built package ships beside the CLI. */
|
|
21
|
+
const runtimeScript = () => {
|
|
22
|
+
const script = ["./main.ts", "./bun-runtime.js"]
|
|
23
|
+
.map((path) => fileURLToPath(new URL(path, import.meta.url)))
|
|
24
|
+
.find((path) => existsSync(path));
|
|
25
|
+
if (!script) {
|
|
26
|
+
throw new Error("The Bun runtime's script is missing from this build.");
|
|
27
|
+
}
|
|
28
|
+
return script;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const alive = (pid: number) => {
|
|
32
|
+
try {
|
|
33
|
+
process.kill(pid, 0);
|
|
34
|
+
return true;
|
|
35
|
+
} catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** Whether `pid` still runs this project's runtime, rather than a process that took over its number after a crash. */
|
|
41
|
+
const isRuntime = (pid: number, launchFile: string) => {
|
|
42
|
+
if (!alive(pid)) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
if (process.platform === "win32") {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
const command = spawnSync("ps", ["-o", "command=", "-p", String(pid)], {
|
|
49
|
+
encoding: "utf8",
|
|
50
|
+
}).stdout;
|
|
51
|
+
return command.includes(launchFile);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const readState = async (file: string): Promise<RuntimeState | undefined> => {
|
|
55
|
+
const text = await readFile(file, "utf8").catch(() => undefined);
|
|
56
|
+
if (text === undefined) {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
return runtimeStateSchema.parse(JSON.parse(text));
|
|
61
|
+
} catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** Stops the project's runtime that an earlier `run --bun` left running, which saves its retained values. */
|
|
67
|
+
const stopRunning = async (directory: string, log: (line: string) => void) => {
|
|
68
|
+
const stateFile = join(directory, runtimeFiles.state);
|
|
69
|
+
const state = await readState(stateFile);
|
|
70
|
+
if (!state || !isRuntime(state.pid, join(directory, runtimeFiles.launch))) {
|
|
71
|
+
await rm(stateFile, { force: true });
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
log(`Stopping the Bun runtime that runs as process ${state.pid}`);
|
|
75
|
+
process.kill(state.pid, "SIGTERM");
|
|
76
|
+
const deadline = Date.now() + stopTimeoutMs;
|
|
77
|
+
while (alive(state.pid)) {
|
|
78
|
+
if (Date.now() >= deadline) {
|
|
79
|
+
process.kill(state.pid, "SIGKILL");
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
await delay(100);
|
|
83
|
+
}
|
|
84
|
+
await rm(stateFile, { force: true });
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Starts the program in the Bun runtime, as `tsplc run --simulate --bun` does, replacing the
|
|
89
|
+
* project's runtime that is running. Detached, the runtime keeps running after this returns,
|
|
90
|
+
* writing to its log, until the next `run --bun` replaces it or it is sent SIGTERM; in the
|
|
91
|
+
* foreground it runs, writing to this terminal, until it is interrupted.
|
|
92
|
+
*/
|
|
93
|
+
export const runInBun = async (options: {
|
|
94
|
+
root: string;
|
|
95
|
+
launch: Launch;
|
|
96
|
+
environment: Readonly<Record<string, string | undefined>>;
|
|
97
|
+
foreground: boolean;
|
|
98
|
+
progress: ProgressStream;
|
|
99
|
+
}) => {
|
|
100
|
+
const log = progressLog(options.progress);
|
|
101
|
+
const directory = join(options.root, runtimeDirectory);
|
|
102
|
+
await mkdir(directory, { recursive: true });
|
|
103
|
+
await stopRunning(directory, log);
|
|
104
|
+
const launchFile = join(directory, runtimeFiles.launch);
|
|
105
|
+
await writeFile(launchFile, `${JSON.stringify(options.launch, null, 2)}\n`);
|
|
106
|
+
const logFile = join(directory, runtimeFiles.log);
|
|
107
|
+
const command = [runtimeScript(), launchFile];
|
|
108
|
+
if (options.foreground) {
|
|
109
|
+
log("Running the program in Bun; stop it with Ctrl-C");
|
|
110
|
+
const child = spawn(process.execPath, command, {
|
|
111
|
+
cwd: options.root,
|
|
112
|
+
env: options.environment,
|
|
113
|
+
stdio: "inherit",
|
|
114
|
+
});
|
|
115
|
+
// The terminal's Ctrl-C reaches the runtime too, so this process only waits for it to stop;
|
|
116
|
+
// a SIGTERM sent to this process alone is passed on.
|
|
117
|
+
const wait = () => undefined;
|
|
118
|
+
const forward = () => child.kill("SIGTERM");
|
|
119
|
+
process.on("SIGINT", wait);
|
|
120
|
+
process.on("SIGTERM", forward);
|
|
121
|
+
const code = await new Promise<number | null>((resolve) =>
|
|
122
|
+
child.once("exit", resolve),
|
|
123
|
+
);
|
|
124
|
+
process.off("SIGINT", wait);
|
|
125
|
+
process.off("SIGTERM", forward);
|
|
126
|
+
if (code !== 0) {
|
|
127
|
+
throw new Error(`The Bun runtime exited with code ${code}.`);
|
|
128
|
+
}
|
|
129
|
+
return { stopped: true };
|
|
130
|
+
}
|
|
131
|
+
const output = openSync(logFile, "w");
|
|
132
|
+
const child = spawn(process.execPath, command, {
|
|
133
|
+
cwd: options.root,
|
|
134
|
+
env: options.environment,
|
|
135
|
+
detached: true,
|
|
136
|
+
stdio: ["ignore", output, output],
|
|
137
|
+
});
|
|
138
|
+
const exited: { code: number | null; done: boolean } = {
|
|
139
|
+
code: null,
|
|
140
|
+
done: false,
|
|
141
|
+
};
|
|
142
|
+
child.once("exit", (code) => {
|
|
143
|
+
Object.assign(exited, { code, done: true });
|
|
144
|
+
});
|
|
145
|
+
const stateFile = join(directory, runtimeFiles.state);
|
|
146
|
+
const deadline = Date.now() + startTimeoutMs;
|
|
147
|
+
while (true) {
|
|
148
|
+
const state = await readState(stateFile);
|
|
149
|
+
if (state && state.pid === child.pid) {
|
|
150
|
+
child.unref();
|
|
151
|
+
const shown = relative(process.cwd(), logFile) || logFile;
|
|
152
|
+
log(
|
|
153
|
+
`The program runs in Bun as process ${state.pid}: OPC UA at ${state.endpoint}, output in ${shown}`,
|
|
154
|
+
);
|
|
155
|
+
return { ...state, log: logFile };
|
|
156
|
+
}
|
|
157
|
+
if (exited.done || Date.now() >= deadline) {
|
|
158
|
+
if (!exited.done) {
|
|
159
|
+
child.kill("SIGTERM");
|
|
160
|
+
}
|
|
161
|
+
const tail = (await readFile(logFile, "utf8").catch(() => ""))
|
|
162
|
+
.trimEnd()
|
|
163
|
+
.split("\n")
|
|
164
|
+
.slice(-30)
|
|
165
|
+
.join("\n");
|
|
166
|
+
throw new Error(
|
|
167
|
+
`The Bun runtime ${exited.done ? `exited with code ${exited.code}` : "did not start in time"}:\n${tail}`,
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
await delay(100);
|
|
171
|
+
}
|
|
172
|
+
};
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
2
|
+
import { plugin } from "bun";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
import { withBindingRegistry } from "../frontend/elaborate/capture-protocol.ts";
|
|
5
|
+
import { bindingNames } from "../frontend/elaborate/graph.ts";
|
|
6
|
+
|
|
7
|
+
/** The SDK modules a program imports, as the runtime implements them, by export name. */
|
|
8
|
+
export type Sdk = Readonly<Record<string, Readonly<Record<string, unknown>>>>;
|
|
9
|
+
|
|
10
|
+
const sdkKey = Symbol.for("tsplc.runtime.sdk");
|
|
11
|
+
const registryExport = "__tsplcRuntime";
|
|
12
|
+
|
|
13
|
+
interface Registry {
|
|
14
|
+
values: Record<string, () => unknown>;
|
|
15
|
+
classes: Record<string, unknown>;
|
|
16
|
+
functions: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const isRegistry = (value: unknown): value is Registry =>
|
|
20
|
+
typeof value === "object" &&
|
|
21
|
+
value !== null &&
|
|
22
|
+
"values" in value &&
|
|
23
|
+
"classes" in value &&
|
|
24
|
+
"functions" in value;
|
|
25
|
+
|
|
26
|
+
const escapeRegExp = (text: string) =>
|
|
27
|
+
text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Loads the program's modules in this process: each `@tsplc/compiler/*` SDK module it imports
|
|
31
|
+
* is `sdk`'s, whatever version the project installed, and each of its own `sources` also
|
|
32
|
+
* exports its top-level bindings, which the runtime reads storage through.
|
|
33
|
+
*/
|
|
34
|
+
export const loadProgram = async (options: {
|
|
35
|
+
sdk: Sdk;
|
|
36
|
+
/** The program's own modules: the debug manifest's sources. */
|
|
37
|
+
sources: readonly string[];
|
|
38
|
+
/** Each scheduled program's module and export. */
|
|
39
|
+
entries: Readonly<Record<string, { module: string; export: string }>>;
|
|
40
|
+
}) => {
|
|
41
|
+
(globalThis as Record<symbol, unknown>)[sdkKey] = options.sdk;
|
|
42
|
+
const files = new Set(options.sources.map((file) => realpathSync(file)));
|
|
43
|
+
plugin({
|
|
44
|
+
name: "tsplc-runtime",
|
|
45
|
+
setup(build) {
|
|
46
|
+
for (const [specifier, exports] of Object.entries(options.sdk)) {
|
|
47
|
+
build.module(specifier, () => ({
|
|
48
|
+
contents: `const sdk = globalThis[Symbol.for("tsplc.runtime.sdk")][${JSON.stringify(specifier)}];\n${Object.keys(
|
|
49
|
+
exports,
|
|
50
|
+
)
|
|
51
|
+
.map((name) => `export const ${name} = sdk.${name};`)
|
|
52
|
+
.join("\n")}\n`,
|
|
53
|
+
loader: "js",
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
56
|
+
if (!files.size) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
build.onLoad(
|
|
60
|
+
{ filter: new RegExp(`^(${[...files].map(escapeRegExp).join("|")})$`) },
|
|
61
|
+
({ path }) => {
|
|
62
|
+
const text = readFileSync(path, "utf8");
|
|
63
|
+
return {
|
|
64
|
+
contents: withBindingRegistry(
|
|
65
|
+
text,
|
|
66
|
+
bindingNames(
|
|
67
|
+
ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true),
|
|
68
|
+
),
|
|
69
|
+
registryExport,
|
|
70
|
+
),
|
|
71
|
+
loader: path.endsWith("x") ? "tsx" : "ts",
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
);
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
const modules = new Map<string, Record<string, unknown>>();
|
|
78
|
+
const load = async (file: string) => {
|
|
79
|
+
const real = realpathSync(file);
|
|
80
|
+
const known = modules.get(real);
|
|
81
|
+
if (known) {
|
|
82
|
+
return known;
|
|
83
|
+
}
|
|
84
|
+
const loaded: Record<string, unknown> = await import(real);
|
|
85
|
+
modules.set(real, loaded);
|
|
86
|
+
return loaded;
|
|
87
|
+
};
|
|
88
|
+
const programs = new Map<string, VoidFunction>();
|
|
89
|
+
for (const [key, entry] of Object.entries(options.entries)) {
|
|
90
|
+
const exported = (await load(entry.module))[entry.export];
|
|
91
|
+
if (typeof exported !== "function") {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`Program ${key}: ${entry.module} exports no function ${entry.export}.`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
programs.set(key, () => {
|
|
97
|
+
exported();
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
for (const file of files) {
|
|
101
|
+
await load(file);
|
|
102
|
+
}
|
|
103
|
+
const registries = [...modules]
|
|
104
|
+
.flatMap(([file, loaded]) => {
|
|
105
|
+
const registry = loaded[registryExport];
|
|
106
|
+
return isRegistry(registry) ? [{ file, registry }] : [];
|
|
107
|
+
})
|
|
108
|
+
// The entries' modules first: their bindings win a name two modules share.
|
|
109
|
+
.sort(
|
|
110
|
+
(left, right) =>
|
|
111
|
+
Number(isEntry(right.file, options.entries)) -
|
|
112
|
+
Number(isEntry(left.file, options.entries)),
|
|
113
|
+
);
|
|
114
|
+
/** A module-level binding by name, as the program holds it now. */
|
|
115
|
+
const binding = (name: string): unknown => {
|
|
116
|
+
for (const { registry } of registries) {
|
|
117
|
+
const read = Object.hasOwn(registry.values, name)
|
|
118
|
+
? registry.values[name]
|
|
119
|
+
: undefined;
|
|
120
|
+
if (read) {
|
|
121
|
+
return read();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
};
|
|
126
|
+
const classes = registries.flatMap(({ registry }) =>
|
|
127
|
+
Object.entries(registry.classes).flatMap(([name, value]) => {
|
|
128
|
+
const prototype: unknown =
|
|
129
|
+
typeof value === "function" ? value.prototype : undefined;
|
|
130
|
+
return typeof prototype === "object" && prototype !== null
|
|
131
|
+
? [{ name, prototype }]
|
|
132
|
+
: [];
|
|
133
|
+
}),
|
|
134
|
+
);
|
|
135
|
+
return { programs, binding, classes };
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const isEntry = (
|
|
139
|
+
file: string,
|
|
140
|
+
entries: Readonly<Record<string, { module: string }>>,
|
|
141
|
+
) =>
|
|
142
|
+
Object.values(entries).some((entry) => realpathSync(entry.module) === file);
|