@tsplc/tmp-compiler 0.0.0-stage → 0.6.2
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/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/cli.js +2325 -0
- package/dist/cli.js.map +26 -0
- package/dist/clock.js +11 -0
- package/dist/clock.js.map +11 -0
- package/dist/codesys.js +6558 -0
- package/dist/codesys.js.map +51 -0
- package/dist/collections.js +399 -0
- package/dist/collections.js.map +10 -0
- package/dist/index.js +16076 -0
- package/dist/index.js.map +61 -0
- package/dist/ir.js +3948 -0
- package/dist/ir.js.map +35 -0
- package/dist/retain.js +10 -0
- package/dist/retain.js.map +10 -0
- package/dist/signals.js +115 -0
- package/dist/signals.js.map +10 -0
- package/dist/telemetry.js +121 -0
- package/dist/telemetry.js.map +12 -0
- package/package.json +122 -4
- package/src/codesys/config.ts +50 -0
- package/src/codesys/debug.ts +655 -0
- package/src/codesys/emit.ts +185 -0
- package/src/codesys/endpoints.ts +111 -0
- package/src/codesys/engineering.ts +96 -0
- package/src/codesys/explain/expressions.ts +445 -0
- package/src/codesys/explain/flags.ts +134 -0
- package/src/codesys/explain/parameters.ts +53 -0
- package/src/codesys/explain/rows.ts +182 -0
- package/src/codesys/explain/tables.ts +79 -0
- package/src/codesys/explain/tasks.ts +68 -0
- package/src/codesys/explain/writes.ts +497 -0
- package/src/codesys/explain.ts +149 -0
- package/src/codesys/expressions.ts +100 -0
- package/src/codesys/global-lists.ts +284 -0
- package/src/codesys/global-names.ts +66 -0
- package/src/codesys/http.ts +1078 -0
- package/src/codesys/index.ts +13 -0
- package/src/codesys/instrumentation.ts +574 -0
- package/src/codesys/io-paths.ts +149 -0
- package/src/codesys/loops.ts +101 -0
- package/src/codesys/manifest.ts +684 -0
- package/src/codesys/names.ts +58 -0
- package/src/codesys/numeric.ts +516 -0
- package/src/codesys/plan.ts +688 -0
- package/src/codesys/programs.ts +138 -0
- package/src/codesys/publication.ts +99 -0
- package/src/codesys/required.ts +8 -0
- package/src/codesys/routines.ts +247 -0
- package/src/codesys/scan-clock.ts +103 -0
- package/src/codesys/scheduling.ts +96 -0
- package/src/codesys/service-channels.ts +24 -0
- package/src/codesys/sources.ts +118 -0
- package/src/codesys/st-files.ts +219 -0
- package/src/codesys/statements.ts +409 -0
- package/src/codesys/storage.ts +150 -0
- package/src/codesys/symbols.ts +240 -0
- package/src/codesys/task-access.ts +186 -0
- package/src/codesys/telemetry-settings.ts +19 -0
- package/src/codesys/telemetry.ts +852 -0
- package/src/codesys/types.ts +310 -0
- package/src/codesys/vendor.ts +113 -0
- package/src/frontend/analyzer.ts +779 -0
- package/src/frontend/async.ts +530 -0
- package/src/frontend/blocks.ts +578 -0
- package/src/frontend/configuration.ts +83 -0
- package/src/frontend/const-functions.ts +204 -0
- package/src/frontend/control-flow.ts +787 -0
- package/src/frontend/cooperative.ts +114 -0
- package/src/frontend/coroutines.ts +1336 -0
- package/src/frontend/dialect-names.ts +104 -0
- package/src/frontend/elaborate/array-searches.ts +224 -0
- package/src/frontend/elaborate/assignments.ts +343 -0
- package/src/frontend/elaborate/calls.ts +1342 -0
- package/src/frontend/elaborate/capture-protocol.ts +237 -0
- package/src/frontend/elaborate/capture.ts +388 -0
- package/src/frontend/elaborate/declarations.ts +124 -0
- package/src/frontend/elaborate/dialect.ts +473 -0
- package/src/frontend/elaborate/expressions.ts +2171 -0
- package/src/frontend/elaborate/filtered-arrays.ts +643 -0
- package/src/frontend/elaborate/frame.ts +145 -0
- package/src/frontend/elaborate/generics.ts +123 -0
- package/src/frontend/elaborate/graph.ts +141 -0
- package/src/frontend/elaborate/imports.ts +105 -0
- package/src/frontend/elaborate/index.ts +851 -0
- package/src/frontend/elaborate/initializers.ts +235 -0
- package/src/frontend/elaborate/iterators.ts +1541 -0
- package/src/frontend/elaborate/layouts.ts +1025 -0
- package/src/frontend/elaborate/model.ts +478 -0
- package/src/frontend/elaborate/names.ts +134 -0
- package/src/frontend/elaborate/reduce.ts +900 -0
- package/src/frontend/elaborate/references.ts +727 -0
- package/src/frontend/elaborate/retention.ts +284 -0
- package/src/frontend/elaborate/specialize.ts +1137 -0
- package/src/frontend/elaborate/statements.ts +1220 -0
- package/src/frontend/elaborate/storage.ts +836 -0
- package/src/frontend/elaborate/time-constructors.ts +34 -0
- package/src/frontend/elaborate/values.ts +200 -0
- package/src/frontend/elaborate/writes.ts +415 -0
- package/src/frontend/expressions.ts +1382 -0
- package/src/frontend/generated-names.ts +95 -0
- package/src/frontend/intrinsics.ts +382 -0
- package/src/frontend/lowering-key.ts +23 -0
- package/src/frontend/module-graph.ts +156 -0
- package/src/frontend/positions.ts +359 -0
- package/src/frontend/promise-chains.ts +872 -0
- package/src/frontend/promises.ts +419 -0
- package/src/frontend/routines.ts +239 -0
- package/src/frontend/sdk.ts +187 -0
- package/src/frontend/services.ts +609 -0
- package/src/frontend/statements.ts +871 -0
- package/src/frontend/tasks.ts +526 -0
- package/src/frontend/telemetry.ts +174 -0
- package/src/frontend/types.ts +1073 -0
- package/src/frontend/typescript.ts +651 -0
- package/src/index.ts +9 -0
- package/src/ir/aggregates.ts +291 -0
- package/src/ir/allocation.ts +96 -0
- package/src/ir/conditions.ts +855 -0
- package/src/ir/core-model.ts +289 -0
- package/src/ir/declarations.ts +281 -0
- package/src/ir/diagnostics.ts +68 -0
- package/src/ir/domains.ts +151 -0
- package/src/ir/fold.ts +279 -0
- package/src/ir/identity.ts +19 -0
- package/src/ir/index.ts +137 -0
- package/src/ir/job-errors.ts +69 -0
- package/src/ir/layouts.ts +211 -0
- package/src/ir/link.ts +302 -0
- package/src/ir/model.ts +394 -0
- package/src/ir/normalization-error.ts +10 -0
- package/src/ir/normalize.ts +52 -0
- package/src/ir/numeric.ts +163 -0
- package/src/ir/operands.ts +160 -0
- package/src/ir/ranges.ts +420 -0
- package/src/ir/routine.ts +1116 -0
- package/src/ir/scalars.ts +453 -0
- package/src/ir/share.ts +790 -0
- package/src/ir/short-circuit.ts +140 -0
- package/src/ir/tables.ts +111 -0
- package/src/ir/temporaries.ts +138 -0
- package/src/ir/types.ts +151 -0
- package/src/project/artifacts.ts +424 -0
- package/src/project/cli.ts +211 -0
- package/src/project/debugger.ts +111 -0
- package/src/project/deployments.ts +387 -0
- package/src/project/flags.ts +14 -0
- package/src/project/git.ts +35 -0
- package/src/project/plant.ts +629 -0
- package/src/project/project-commands.ts +507 -0
- package/src/project/project.ts +559 -0
- package/src/project/release.ts +152 -0
- package/src/project/server-check.ts +54 -0
- package/src/project/server.ts +165 -0
- package/src/project/terminal.ts +45 -0
- package/src/runtime/async.ts +207 -0
- package/src/runtime/launch.ts +59 -0
- package/src/runtime/main.ts +59 -0
- package/src/runtime/missing-file.ts +3 -0
- package/src/runtime/process.ts +177 -0
- package/src/runtime/program.ts +109 -0
- package/src/runtime/retain.ts +108 -0
- package/src/runtime/runtime.ts +324 -0
- package/src/runtime/settings.ts +27 -0
- package/src/runtime/storage.ts +456 -0
- package/src/runtime/symbols.ts +97 -0
- package/src/runtime/telemetry.ts +154 -0
- package/src/runtime/transport.ts +168 -0
- package/stdlib/clock.ts +8 -0
- package/stdlib/collections.ts +534 -0
- package/stdlib/plc-time.ts +2 -0
- package/stdlib/retain.ts +4 -0
- package/stdlib/signals.ts +142 -0
- package/stdlib/telemetry.ts +89 -0
- package/types/async.d.ts +87 -0
- package/types/clock.d.ts +8 -0
- package/types/config.d.ts +2 -0
- package/types/data-types.d.ts +31 -0
- package/types/dialect.d.ts +49 -0
- package/types/globals.d.ts +10 -0
- package/types/index.d.ts +212 -0
- package/types/retain.d.ts +12 -0
- package/types/telemetry.d.ts +47 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { 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 type { Environment } from "@tsplc/config";
|
|
9
|
+
import {
|
|
10
|
+
type Launch,
|
|
11
|
+
type RuntimeState,
|
|
12
|
+
runtimeDirectory,
|
|
13
|
+
runtimeFiles,
|
|
14
|
+
runtimeStateSchema,
|
|
15
|
+
} from "./launch";
|
|
16
|
+
import { isMissingFile } from "./missing-file";
|
|
17
|
+
|
|
18
|
+
/** How long a runtime has to start serving, and to stop. */
|
|
19
|
+
const startTimeoutMs = 60_000;
|
|
20
|
+
const stopTimeoutMs = 15_000;
|
|
21
|
+
|
|
22
|
+
/** Whether `pid` runs: a process this user may not signal runs too. */
|
|
23
|
+
const alive = (pid: number) => {
|
|
24
|
+
try {
|
|
25
|
+
process.kill(pid, 0);
|
|
26
|
+
return true;
|
|
27
|
+
} catch (cause) {
|
|
28
|
+
return cause instanceof Error && "code" in cause && cause.code === "EPERM";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** Whether `pid` still runs this project's runtime, rather than a process that took over its number after a crash. */
|
|
33
|
+
const isRuntime = (pid: number, launchFile: string) => {
|
|
34
|
+
if (!alive(pid)) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
// Windows has no `ps` to name the process's command, so any process with the number counts.
|
|
38
|
+
if (process.platform === "win32") {
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
const command = spawnSync("ps", ["-o", "command=", "-p", String(pid)], {
|
|
42
|
+
encoding: "utf8",
|
|
43
|
+
}).stdout;
|
|
44
|
+
return command.includes(launchFile);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** The running runtime's state; undefined when no runtime serves. */
|
|
48
|
+
const readState = async (file: string): Promise<RuntimeState | undefined> => {
|
|
49
|
+
const text = await readFile(file, "utf8").catch((cause: unknown) => {
|
|
50
|
+
if (isMissingFile(cause)) {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
throw cause;
|
|
54
|
+
});
|
|
55
|
+
if (text === undefined) {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
return runtimeStateSchema.parse(JSON.parse(text));
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
`${file} is not a Bun runtime's state: delete it once no runtime runs.`,
|
|
63
|
+
{ cause },
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** Stops the project's runtime that an earlier `run --bun` left running, which saves its retained values. */
|
|
69
|
+
const stopRunning = async (directory: string, log: (line: string) => void) => {
|
|
70
|
+
const stateFile = join(directory, runtimeFiles.state);
|
|
71
|
+
const state = await readState(stateFile);
|
|
72
|
+
if (!state || !isRuntime(state.pid, join(directory, runtimeFiles.launch))) {
|
|
73
|
+
await rm(stateFile, { force: true });
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
log(`Stopping the Bun runtime that runs as process ${state.pid}`);
|
|
77
|
+
process.kill(state.pid, "SIGTERM");
|
|
78
|
+
const deadline = Date.now() + stopTimeoutMs;
|
|
79
|
+
while (alive(state.pid)) {
|
|
80
|
+
if (Date.now() >= deadline) {
|
|
81
|
+
process.kill(state.pid, "SIGKILL");
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
await delay(100);
|
|
85
|
+
}
|
|
86
|
+
await rm(stateFile, { force: true });
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Starts the program in the Bun runtime, as `tsplc run --simulate --bun` does, replacing the
|
|
91
|
+
* project's runtime that is running. Detached, the runtime keeps running after this returns,
|
|
92
|
+
* writing to its log, until the next `run --bun` replaces it or it is sent SIGTERM; in the
|
|
93
|
+
* foreground it runs, writing to this terminal, until it is interrupted.
|
|
94
|
+
*/
|
|
95
|
+
export const runInBun = async (options: {
|
|
96
|
+
root: string;
|
|
97
|
+
launch: Launch;
|
|
98
|
+
environment: Environment;
|
|
99
|
+
foreground: boolean;
|
|
100
|
+
progress: ProgressStream;
|
|
101
|
+
}) => {
|
|
102
|
+
const log = progressLog(options.progress);
|
|
103
|
+
const directory = join(options.root, runtimeDirectory);
|
|
104
|
+
await mkdir(directory, { recursive: true });
|
|
105
|
+
await stopRunning(directory, log);
|
|
106
|
+
const launchFile = join(directory, runtimeFiles.launch);
|
|
107
|
+
await writeFile(launchFile, `${JSON.stringify(options.launch, null, 2)}\n`);
|
|
108
|
+
const logFile = join(directory, runtimeFiles.log);
|
|
109
|
+
const command = [
|
|
110
|
+
fileURLToPath(import.meta.resolve("#bun-runtime")),
|
|
111
|
+
launchFile,
|
|
112
|
+
];
|
|
113
|
+
if (options.foreground) {
|
|
114
|
+
log("Running the program in Bun; stop it with Ctrl-C");
|
|
115
|
+
const child = spawn(process.execPath, command, {
|
|
116
|
+
cwd: options.root,
|
|
117
|
+
env: options.environment,
|
|
118
|
+
stdio: "inherit",
|
|
119
|
+
});
|
|
120
|
+
// The terminal's Ctrl-C reaches the runtime too, so this process only waits for it to stop;
|
|
121
|
+
// a SIGTERM sent to this process alone is passed on.
|
|
122
|
+
const wait = () => undefined;
|
|
123
|
+
const forward = () => child.kill("SIGTERM");
|
|
124
|
+
process.on("SIGINT", wait);
|
|
125
|
+
process.on("SIGTERM", forward);
|
|
126
|
+
const code = await new Promise<number | null>((resolve) =>
|
|
127
|
+
child.once("exit", resolve),
|
|
128
|
+
);
|
|
129
|
+
process.off("SIGINT", wait);
|
|
130
|
+
process.off("SIGTERM", forward);
|
|
131
|
+
if (code !== 0) {
|
|
132
|
+
throw new Error(`The Bun runtime exited with code ${code}.`);
|
|
133
|
+
}
|
|
134
|
+
return { stopped: true };
|
|
135
|
+
}
|
|
136
|
+
const output = openSync(logFile, "w");
|
|
137
|
+
const child = spawn(process.execPath, command, {
|
|
138
|
+
cwd: options.root,
|
|
139
|
+
env: options.environment,
|
|
140
|
+
detached: true,
|
|
141
|
+
stdio: ["ignore", output, output],
|
|
142
|
+
});
|
|
143
|
+
const exited: { code: number | null; done: boolean } = {
|
|
144
|
+
code: null,
|
|
145
|
+
done: false,
|
|
146
|
+
};
|
|
147
|
+
child.once("exit", (code) => {
|
|
148
|
+
Object.assign(exited, { code, done: true });
|
|
149
|
+
});
|
|
150
|
+
const stateFile = join(directory, runtimeFiles.state);
|
|
151
|
+
const deadline = Date.now() + startTimeoutMs;
|
|
152
|
+
while (true) {
|
|
153
|
+
const state = await readState(stateFile);
|
|
154
|
+
if (state && state.pid === child.pid) {
|
|
155
|
+
child.unref();
|
|
156
|
+
const shown = relative(process.cwd(), logFile) || logFile;
|
|
157
|
+
log(
|
|
158
|
+
`The program runs in Bun as process ${state.pid}: OPC UA at ${state.endpoint}, output in ${shown}`,
|
|
159
|
+
);
|
|
160
|
+
return { ...state, log: logFile };
|
|
161
|
+
}
|
|
162
|
+
if (exited.done || Date.now() >= deadline) {
|
|
163
|
+
if (!exited.done) {
|
|
164
|
+
child.kill("SIGTERM");
|
|
165
|
+
}
|
|
166
|
+
const tail = (await readFile(logFile, "utf8").catch(() => ""))
|
|
167
|
+
.trimEnd()
|
|
168
|
+
.split("\n")
|
|
169
|
+
.slice(-30)
|
|
170
|
+
.join("\n");
|
|
171
|
+
throw new Error(
|
|
172
|
+
`The Bun runtime ${exited.done ? `exited with code ${exited.code}` : "did not start in time"}:\n${tail}`,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
await delay(100);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { plugin } from "bun";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
import {
|
|
5
|
+
bindingNames,
|
|
6
|
+
bindingRegistry,
|
|
7
|
+
loadWithBindingRegistry,
|
|
8
|
+
} from "../frontend/elaborate/capture-protocol";
|
|
9
|
+
|
|
10
|
+
/** The SDK modules a program imports, as the runtime implements them, by export name. */
|
|
11
|
+
export type Sdk = Readonly<Record<string, Readonly<Record<string, unknown>>>>;
|
|
12
|
+
|
|
13
|
+
/** An SDK module's implementation: every value its declaration exports, and no other. */
|
|
14
|
+
export type SdkModule<Declared> = {
|
|
15
|
+
readonly [Name in keyof Declared]: unknown;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Loads the program's modules in this process: each `@tsplc/compiler/*` SDK module it imports
|
|
20
|
+
* is `sdk`'s, whatever version the project installed, and each of its own `sources` also
|
|
21
|
+
* exports its top-level bindings, which the runtime reads storage through.
|
|
22
|
+
*/
|
|
23
|
+
export const loadProgram = async (options: {
|
|
24
|
+
sdk: Sdk;
|
|
25
|
+
/** The program's own modules: the debug manifest's sources. */
|
|
26
|
+
sources: readonly string[];
|
|
27
|
+
/** Each scheduled program's module and export. */
|
|
28
|
+
entries: Readonly<Record<string, { module: string; export: string }>>;
|
|
29
|
+
}) => {
|
|
30
|
+
plugin({
|
|
31
|
+
name: "tsplc-runtime",
|
|
32
|
+
setup(build) {
|
|
33
|
+
for (const [specifier, exports] of Object.entries(options.sdk)) {
|
|
34
|
+
build.module(specifier, () => ({ exports, loader: "object" }));
|
|
35
|
+
}
|
|
36
|
+
loadWithBindingRegistry(build, options.sources, ({ file, source }) => ({
|
|
37
|
+
source,
|
|
38
|
+
bindings: bindingNames(
|
|
39
|
+
ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true),
|
|
40
|
+
),
|
|
41
|
+
}));
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
const modules = new Map<string, Record<string, unknown>>();
|
|
45
|
+
const load = async (file: string) => {
|
|
46
|
+
const real = realpathSync(file);
|
|
47
|
+
const known = modules.get(real);
|
|
48
|
+
if (known) {
|
|
49
|
+
return known;
|
|
50
|
+
}
|
|
51
|
+
const loaded: Record<string, unknown> = await import(real);
|
|
52
|
+
modules.set(real, loaded);
|
|
53
|
+
return loaded;
|
|
54
|
+
};
|
|
55
|
+
const programs = new Map<string, VoidFunction>();
|
|
56
|
+
for (const [key, entry] of Object.entries(options.entries)) {
|
|
57
|
+
const exported = (await load(entry.module))[entry.export];
|
|
58
|
+
if (typeof exported !== "function") {
|
|
59
|
+
throw new Error(
|
|
60
|
+
`Program ${key}: ${entry.module} exports no function ${entry.export}.`,
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
programs.set(key, () => {
|
|
64
|
+
exported();
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
for (const file of options.sources) {
|
|
68
|
+
await load(file);
|
|
69
|
+
}
|
|
70
|
+
const registries = [...modules]
|
|
71
|
+
.flatMap(([file, loaded]) => {
|
|
72
|
+
const registry = bindingRegistry(loaded);
|
|
73
|
+
return registry ? [{ file, registry }] : [];
|
|
74
|
+
})
|
|
75
|
+
// The entries' modules first: their bindings win a name two modules share.
|
|
76
|
+
.sort(
|
|
77
|
+
(left, right) =>
|
|
78
|
+
Number(isEntry(right.file, options.entries)) -
|
|
79
|
+
Number(isEntry(left.file, options.entries)),
|
|
80
|
+
);
|
|
81
|
+
/** A module-level binding by name, as the program holds it now. */
|
|
82
|
+
const binding = (name: string): unknown => {
|
|
83
|
+
for (const { registry } of registries) {
|
|
84
|
+
const read = Object.hasOwn(registry.values, name)
|
|
85
|
+
? registry.values[name]
|
|
86
|
+
: undefined;
|
|
87
|
+
if (read) {
|
|
88
|
+
return read();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return undefined;
|
|
92
|
+
};
|
|
93
|
+
const classes = registries.flatMap(({ registry }) =>
|
|
94
|
+
Object.entries(registry.classes).flatMap(([name, value]) => {
|
|
95
|
+
const prototype: unknown =
|
|
96
|
+
typeof value === "function" ? value.prototype : undefined;
|
|
97
|
+
return typeof prototype === "object" && prototype !== null
|
|
98
|
+
? [{ name, prototype }]
|
|
99
|
+
: [];
|
|
100
|
+
}),
|
|
101
|
+
);
|
|
102
|
+
return { programs, binding, classes };
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const isEntry = (
|
|
106
|
+
file: string,
|
|
107
|
+
entries: Readonly<Record<string, { module: string }>>,
|
|
108
|
+
) =>
|
|
109
|
+
Object.values(entries).some((entry) => realpathSync(entry.module) === file);
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
type PublishedGlobal,
|
|
6
|
+
type PublishedScalar,
|
|
7
|
+
type PublishedValue,
|
|
8
|
+
publishedScalars,
|
|
9
|
+
} from "@tsplc/opcua/server";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { isMissingFile } from "./missing-file";
|
|
12
|
+
|
|
13
|
+
const retainedValue = z.union([
|
|
14
|
+
z.boolean(),
|
|
15
|
+
z.number(),
|
|
16
|
+
z.string(),
|
|
17
|
+
z.strictObject({ bigint: z.string().regex(/^-?\d+$/) }),
|
|
18
|
+
]);
|
|
19
|
+
|
|
20
|
+
/** The values of the retained globals when the runtime last stopped, and the layout they had. */
|
|
21
|
+
const retainedSchema = z.strictObject({
|
|
22
|
+
layout: z.string(),
|
|
23
|
+
values: z.record(z.string(), retainedValue),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const parsedJson = (text: string): unknown => {
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(text);
|
|
29
|
+
} catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const stored = (value: PublishedValue): z.infer<typeof retainedValue> =>
|
|
35
|
+
typeof value === "bigint" ? { bigint: String(value) } : value;
|
|
36
|
+
|
|
37
|
+
const restored = (value: z.infer<typeof retainedValue>): PublishedValue =>
|
|
38
|
+
typeof value === "object" ? BigInt(value.bigint) : value;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The program's `VAR_GLOBAL RETAIN` globals across restarts of the runtime, as CODESYS keeps its
|
|
42
|
+
* retain area across a restart of its runtime: written when the runtime stops, and loaded before
|
|
43
|
+
* the first scan only when every retained global has the layout it was saved with. A changed
|
|
44
|
+
* layout starts them all from the program's initial values, as a retain mismatch does.
|
|
45
|
+
*/
|
|
46
|
+
export const createRetention = (
|
|
47
|
+
globals: readonly PublishedGlobal[],
|
|
48
|
+
scalar: (path: string) => PublishedScalar | undefined,
|
|
49
|
+
file: string,
|
|
50
|
+
) => {
|
|
51
|
+
const scalars = globals
|
|
52
|
+
.flatMap(publishedScalars)
|
|
53
|
+
.flatMap(({ path, type }) => {
|
|
54
|
+
const bound = scalar(path);
|
|
55
|
+
return bound ? [{ path, type, bound }] : [];
|
|
56
|
+
});
|
|
57
|
+
const layout = createHash("sha256")
|
|
58
|
+
.update(JSON.stringify(scalars.map(({ path, type }) => [path, type])))
|
|
59
|
+
.digest("hex");
|
|
60
|
+
return {
|
|
61
|
+
/** Loads the saved values: how many, or why none were. */
|
|
62
|
+
restore: async (): Promise<
|
|
63
|
+
{ restored: number } | { discarded: string } | { none: true }
|
|
64
|
+
> => {
|
|
65
|
+
if (!scalars.length) {
|
|
66
|
+
return { none: true };
|
|
67
|
+
}
|
|
68
|
+
const text = await readFile(file, "utf8").catch((cause: unknown) => {
|
|
69
|
+
if (isMissingFile(cause)) {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
throw cause;
|
|
73
|
+
});
|
|
74
|
+
if (text === undefined) {
|
|
75
|
+
return { none: true };
|
|
76
|
+
}
|
|
77
|
+
const saved = retainedSchema.safeParse(parsedJson(text));
|
|
78
|
+
if (!saved.success) {
|
|
79
|
+
return { discarded: `${file} is not a retain file` };
|
|
80
|
+
}
|
|
81
|
+
if (saved.data.layout !== layout) {
|
|
82
|
+
return { discarded: "the retained globals' layout changed" };
|
|
83
|
+
}
|
|
84
|
+
for (const { path, bound } of scalars) {
|
|
85
|
+
const value = saved.data.values[path];
|
|
86
|
+
if (value !== undefined) {
|
|
87
|
+
bound.write(restored(value));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { restored: scalars.length };
|
|
91
|
+
},
|
|
92
|
+
save: async () => {
|
|
93
|
+
if (!scalars.length) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
await mkdir(dirname(file), { recursive: true });
|
|
97
|
+
await writeFile(
|
|
98
|
+
file,
|
|
99
|
+
`${JSON.stringify({
|
|
100
|
+
layout,
|
|
101
|
+
values: Object.fromEntries(
|
|
102
|
+
scalars.map(({ path, bound }) => [path, stored(bound.read())]),
|
|
103
|
+
),
|
|
104
|
+
} satisfies z.input<typeof retainedSchema>)}\n`,
|
|
105
|
+
);
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
};
|