@tsplc/tmp-compiler 0.0.0-stage → 0.6.3
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 +6563 -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 +16198 -0
- package/dist/index.js.map +62 -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 +1090 -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-enums.ts +196 -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 +1344 -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 +2177 -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 +612 -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 +659 -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,54 @@
|
|
|
1
|
+
import { dirname } from "node:path";
|
|
2
|
+
import { typeCheckOnly } from "@tsplc/compiler";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
import type { z } from "zod";
|
|
5
|
+
import {
|
|
6
|
+
serverCheckRequestSchema,
|
|
7
|
+
type serverCheckResultSchema,
|
|
8
|
+
} from "./server";
|
|
9
|
+
|
|
10
|
+
/** Type-checks the server entry under the tsconfig beside it, as it will be built. */
|
|
11
|
+
const serverFailure = ({
|
|
12
|
+
entry,
|
|
13
|
+
root,
|
|
14
|
+
}: z.infer<typeof serverCheckRequestSchema>): string | null => {
|
|
15
|
+
const tsconfig = ts.findConfigFile(dirname(entry), ts.sys.fileExists);
|
|
16
|
+
if (!tsconfig) {
|
|
17
|
+
return "Server entry requires a tsconfig.json.";
|
|
18
|
+
}
|
|
19
|
+
const read = ts.readConfigFile(tsconfig, ts.sys.readFile);
|
|
20
|
+
if (read.error) {
|
|
21
|
+
return ts.flattenDiagnosticMessageText(read.error.messageText, "\n");
|
|
22
|
+
}
|
|
23
|
+
const parsed = ts.parseJsonConfigFileContent(
|
|
24
|
+
read.config,
|
|
25
|
+
ts.sys,
|
|
26
|
+
dirname(tsconfig),
|
|
27
|
+
);
|
|
28
|
+
const program = ts.createProgram({
|
|
29
|
+
rootNames: [
|
|
30
|
+
entry,
|
|
31
|
+
...parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file)),
|
|
32
|
+
],
|
|
33
|
+
options: { ...parsed.options, ...typeCheckOnly },
|
|
34
|
+
projectReferences: parsed.projectReferences,
|
|
35
|
+
});
|
|
36
|
+
const diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];
|
|
37
|
+
if (!diagnostics.length) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
return ts.formatDiagnosticsWithColorAndContext(diagnostics, {
|
|
41
|
+
getCanonicalFileName: (path) => path,
|
|
42
|
+
getCurrentDirectory: () => root,
|
|
43
|
+
getNewLine: () => "\n",
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// A worker thread runs this module, so the check of a server's thousands of files overlaps the PLC build.
|
|
48
|
+
declare const self: Worker;
|
|
49
|
+
self.onmessage = (event: MessageEvent) => {
|
|
50
|
+
const result: z.infer<typeof serverCheckResultSchema> = {
|
|
51
|
+
failure: serverFailure(serverCheckRequestSchema.parse(event.data)),
|
|
52
|
+
};
|
|
53
|
+
self.postMessage(result);
|
|
54
|
+
};
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { projectSlugs, type ResolvedTsplcConfig } from "@tsplc/config";
|
|
6
|
+
import { generatedDirectory } from "@tsplc/config/project-files";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
|
|
9
|
+
const resolveServerModule = (root: string, name: string) =>
|
|
10
|
+
name.startsWith(".") ||
|
|
11
|
+
name.startsWith("/") ||
|
|
12
|
+
existsSync(resolve(root, name))
|
|
13
|
+
? resolve(root, name)
|
|
14
|
+
: createRequire(join(root, "package.json")).resolve(name);
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* `.tsplc/server/<name>-services<extension>`, where the server's script or executable goes: beside
|
|
18
|
+
* the other generated outputs, never inside `build.outDir`, the CODESYS engineering cache.
|
|
19
|
+
*/
|
|
20
|
+
const serverOutput = (
|
|
21
|
+
config: ResolvedTsplcConfig,
|
|
22
|
+
root: string,
|
|
23
|
+
extension: string,
|
|
24
|
+
) =>
|
|
25
|
+
resolve(
|
|
26
|
+
root,
|
|
27
|
+
generatedDirectory,
|
|
28
|
+
"server",
|
|
29
|
+
`${projectSlugs.kebab(config.name)}-services${extension}`,
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
/** What `checkServer` posts to its worker: the server entry and the project root diagnostics are relative to. */
|
|
33
|
+
export const serverCheckRequestSchema = z.strictObject({
|
|
34
|
+
entry: z.string(),
|
|
35
|
+
root: z.string(),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
/** The worker's answer: why the server entry fails its type check, or null when it passes. */
|
|
39
|
+
export const serverCheckResultSchema = z.strictObject({
|
|
40
|
+
failure: z.string().nullable(),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
/** A server entry that passed its type check, and the runtime it is built for. */
|
|
44
|
+
export interface CheckedServer {
|
|
45
|
+
entry: string;
|
|
46
|
+
runtime: NonNullable<NonNullable<ResolvedTsplcConfig["server"]>["runtime"]>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Type-checks the host entry as it will be built, on a worker thread: a caller that builds the
|
|
51
|
+
* PLC program meanwhile awaits the result after it. The check rejects with the diagnostics.
|
|
52
|
+
*/
|
|
53
|
+
export const checkServer = async (
|
|
54
|
+
config: ResolvedTsplcConfig,
|
|
55
|
+
root: string,
|
|
56
|
+
): Promise<CheckedServer> => {
|
|
57
|
+
const runtime = config.server?.runtime;
|
|
58
|
+
if (!runtime) {
|
|
59
|
+
throw new Error("Configure server.runtime to build the server.");
|
|
60
|
+
}
|
|
61
|
+
const entry = resolveServerModule(root, runtime.entry);
|
|
62
|
+
const worker = new Worker(import.meta.resolve("#server-check"));
|
|
63
|
+
try {
|
|
64
|
+
const answer = await new Promise<unknown>((resolve, reject) => {
|
|
65
|
+
worker.onmessage = (event: MessageEvent) => resolve(event.data);
|
|
66
|
+
worker.onerror = (event) => reject(new Error(event.message));
|
|
67
|
+
const request: z.infer<typeof serverCheckRequestSchema> = {
|
|
68
|
+
entry,
|
|
69
|
+
root,
|
|
70
|
+
};
|
|
71
|
+
worker.postMessage(request);
|
|
72
|
+
});
|
|
73
|
+
const { failure } = serverCheckResultSchema.parse(answer);
|
|
74
|
+
if (failure !== null) {
|
|
75
|
+
throw new Error(failure);
|
|
76
|
+
}
|
|
77
|
+
return { entry, runtime };
|
|
78
|
+
} finally {
|
|
79
|
+
worker.terminate();
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* `checkServer` started now, for a caller that builds the PLC program meanwhile: a failed PLC
|
|
85
|
+
* build reports its own diagnostics, so the check's outcome is read only after a success.
|
|
86
|
+
*/
|
|
87
|
+
export const startServerCheck = (config: ResolvedTsplcConfig, root: string) => {
|
|
88
|
+
const check = checkServer(config, root);
|
|
89
|
+
check.catch(() => undefined);
|
|
90
|
+
return check;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Bundles the host entry, which starts its own listener, into one minified script,
|
|
95
|
+
* `.tsplc/server/<name>-services.js`, which the plant agent runs on its own Bun. It is a few MB
|
|
96
|
+
* where an executable, which embeds Bun, is over 100, and deployments upload it.
|
|
97
|
+
*/
|
|
98
|
+
export const bundleServer = async (
|
|
99
|
+
{ entry }: CheckedServer,
|
|
100
|
+
config: ResolvedTsplcConfig,
|
|
101
|
+
root: string,
|
|
102
|
+
) => {
|
|
103
|
+
const outFile = serverOutput(config, root, ".js");
|
|
104
|
+
const result = await Bun.build({
|
|
105
|
+
entrypoints: [entry],
|
|
106
|
+
target: "bun",
|
|
107
|
+
minify: true,
|
|
108
|
+
env: "disable",
|
|
109
|
+
});
|
|
110
|
+
if (!result.success) {
|
|
111
|
+
throw new AggregateError(result.logs, "Server bundle build failed.");
|
|
112
|
+
}
|
|
113
|
+
const [script, ...assets] = result.outputs;
|
|
114
|
+
if (!script || assets.length) {
|
|
115
|
+
throw new Error(
|
|
116
|
+
`The server bundle needs files beside its script (${assets.map(({ path }) => path).join(", ")}), which deployments don't carry.`,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
await mkdir(dirname(outFile), { recursive: true });
|
|
120
|
+
await Bun.write(outFile, script);
|
|
121
|
+
return outFile;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
/** Compiles the host entry, which starts its own listener, into `.tsplc/server/<name>-services`. */
|
|
125
|
+
export const buildServer = async (
|
|
126
|
+
{ entry, runtime }: CheckedServer,
|
|
127
|
+
config: ResolvedTsplcConfig,
|
|
128
|
+
root: string,
|
|
129
|
+
) => {
|
|
130
|
+
const windows = runtime.target
|
|
131
|
+
? runtime.target.includes("windows")
|
|
132
|
+
: process.platform === "win32";
|
|
133
|
+
const outFile = serverOutput(config, root, windows ? ".exe" : "");
|
|
134
|
+
await mkdir(dirname(outFile), { recursive: true });
|
|
135
|
+
// Compile beside the output so dependency resolution starts from the owning project.
|
|
136
|
+
const staging = await mkdtemp(join(dirname(outFile), ".tsplc-server-"));
|
|
137
|
+
try {
|
|
138
|
+
const binary = join(staging, "server");
|
|
139
|
+
const result = await Bun.build({
|
|
140
|
+
entrypoints: [entry],
|
|
141
|
+
env: "disable",
|
|
142
|
+
compile: {
|
|
143
|
+
outfile: binary,
|
|
144
|
+
...(runtime.target ? { target: runtime.target } : {}),
|
|
145
|
+
autoloadDotenv: false,
|
|
146
|
+
autoloadBunfig: false,
|
|
147
|
+
autoloadTsconfig: false,
|
|
148
|
+
autoloadPackageJson: false,
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
if (!result.success) {
|
|
152
|
+
throw new AggregateError(result.logs, "Server executable build failed.");
|
|
153
|
+
}
|
|
154
|
+
// Bun names a Windows executable itself.
|
|
155
|
+
await rename(windows ? `${binary}.exe` : binary, outFile);
|
|
156
|
+
return {
|
|
157
|
+
server: {
|
|
158
|
+
executable: outFile,
|
|
159
|
+
target: runtime.target ?? `bun-${process.platform}-${process.arch}`,
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
} finally {
|
|
163
|
+
await rm(staging, { recursive: true, force: true });
|
|
164
|
+
}
|
|
165
|
+
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { ask } from "@tsplc/agent";
|
|
2
|
+
|
|
3
|
+
export const choose = async <T>(
|
|
4
|
+
question: string,
|
|
5
|
+
items: readonly T[],
|
|
6
|
+
label: (item: T) => string,
|
|
7
|
+
) => {
|
|
8
|
+
items.forEach((item, index) => {
|
|
9
|
+
console.log(` ${index + 1}. ${label(item)}`);
|
|
10
|
+
});
|
|
11
|
+
while (true) {
|
|
12
|
+
const item =
|
|
13
|
+
items[Number(await ask(`${question} [1-${items.length}]: `)) - 1];
|
|
14
|
+
if (item !== undefined) {
|
|
15
|
+
return item;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** Asks a yes-or-no question; no unless the answer is yes. */
|
|
21
|
+
export const confirm = async (question: string) =>
|
|
22
|
+
/^y(es)?$/i.test(await ask(`${question} [y/N]: `));
|
|
23
|
+
|
|
24
|
+
/** Goes on when `--yes` is given or the answer is yes, else stops the command as cancelled. */
|
|
25
|
+
export const confirmOrCancel = async (
|
|
26
|
+
question: string,
|
|
27
|
+
flags: { yes?: boolean },
|
|
28
|
+
) => {
|
|
29
|
+
if (!flags.yes && !(await confirm(question))) {
|
|
30
|
+
throw new Error("Cancelled.");
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export const progress = (message: string) => console.log(` ${message}`);
|
|
35
|
+
|
|
36
|
+
/** Prints progress with the minutes and seconds since it was made, so the slow steps show. */
|
|
37
|
+
export const timedProgress = () => {
|
|
38
|
+
const start = Date.now();
|
|
39
|
+
return (message: string) => {
|
|
40
|
+
const seconds = Math.round((Date.now() - start) / 1000);
|
|
41
|
+
progress(
|
|
42
|
+
`${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")} ${message}`,
|
|
43
|
+
);
|
|
44
|
+
};
|
|
45
|
+
};
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { failureCode, httpErrors, jobError } from "@tsplc/compiler/ir";
|
|
2
|
+
import { plcBufferBytes } from "@tsplc/server/wire";
|
|
3
|
+
import type { resolveHttpCredentials } from "../codesys/endpoints";
|
|
4
|
+
import type { Transport } from "./transport";
|
|
5
|
+
|
|
6
|
+
/** How the program's HTTP calls reach their servers, as the build compiled them. */
|
|
7
|
+
export interface HttpSettings {
|
|
8
|
+
/** Bearer tokens by the exact origin they are sent to, or why the build refuses the credentials. */
|
|
9
|
+
credentials: ReturnType<typeof resolveHttpCredentials>;
|
|
10
|
+
timeoutMs: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** How the program's service calls reach the app server. */
|
|
14
|
+
export interface ServiceSettings {
|
|
15
|
+
/** Each service procedure's route, by its path such as `catalog.resolve`. */
|
|
16
|
+
routes: Readonly<Record<string, string>>;
|
|
17
|
+
/** The configured transport; null when HTTP has no server base URL to send to. */
|
|
18
|
+
transport: Transport | null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Why the program's call failed, as a compiled call reports it: a job error code. */
|
|
22
|
+
const failure = (cause: unknown) => {
|
|
23
|
+
if (cause instanceof Error && cause.name === "TimeoutError") {
|
|
24
|
+
return jobError.timeout;
|
|
25
|
+
}
|
|
26
|
+
const code =
|
|
27
|
+
cause instanceof Error && "code" in cause ? String(cause.code) : "";
|
|
28
|
+
return /CERT|SSL|TLS|SELF_SIGNED|UNABLE_TO_VERIFY/.test(code)
|
|
29
|
+
? jobError.tls
|
|
30
|
+
: jobError.network;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** The body of a response, at most the PLC's buffer; undefined when larger. */
|
|
34
|
+
const boundedBody = async (response: Response) => {
|
|
35
|
+
const declared = response.headers.get("content-length");
|
|
36
|
+
if (declared !== null && Number(declared) > plcBufferBytes) {
|
|
37
|
+
await response.body?.cancel();
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
const body = new Uint8Array(await response.arrayBuffer());
|
|
41
|
+
return body.length > plcBufferBytes ? undefined : body;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* One HTTP exchange as a compiled call makes it: bounded JSON both ways, the bearer token of the
|
|
46
|
+
* URL's origin, the configured timeout and no retry. It rejects with the compiled call's error
|
|
47
|
+
* code, a number; with credentials the build refuses, a program can't call at all, so it rejects
|
|
48
|
+
* with that refusal as an Error.
|
|
49
|
+
*/
|
|
50
|
+
export const httpCall = async (
|
|
51
|
+
settings: HttpSettings,
|
|
52
|
+
url: string,
|
|
53
|
+
request: { method: string; body?: string },
|
|
54
|
+
): Promise<unknown> => {
|
|
55
|
+
const { credentials } = settings;
|
|
56
|
+
if ("error" in credentials) {
|
|
57
|
+
throw new Error(credentials.error);
|
|
58
|
+
}
|
|
59
|
+
const { body } = request;
|
|
60
|
+
if (body !== undefined && Buffer.byteLength(body, "utf8") > plcBufferBytes) {
|
|
61
|
+
throw jobError.tooLarge;
|
|
62
|
+
}
|
|
63
|
+
const token = credentials.tokens.get(URL.parse(url)?.origin ?? "");
|
|
64
|
+
const response = await globalThis
|
|
65
|
+
.fetch(url, {
|
|
66
|
+
method: request.method,
|
|
67
|
+
headers: {
|
|
68
|
+
Accept: "application/json",
|
|
69
|
+
...(body !== undefined && { "Content-Type": "application/json" }),
|
|
70
|
+
...(token !== undefined && { Authorization: `Bearer ${token}` }),
|
|
71
|
+
},
|
|
72
|
+
...(body !== undefined && { body }),
|
|
73
|
+
signal: AbortSignal.timeout(settings.timeoutMs),
|
|
74
|
+
})
|
|
75
|
+
.catch((cause: unknown) => {
|
|
76
|
+
throw failure(cause);
|
|
77
|
+
});
|
|
78
|
+
const reply = await boundedBody(response).catch((cause: unknown) => {
|
|
79
|
+
throw failure(cause);
|
|
80
|
+
});
|
|
81
|
+
if (!reply) {
|
|
82
|
+
throw jobError.tooLarge;
|
|
83
|
+
}
|
|
84
|
+
if (!response.ok) {
|
|
85
|
+
throw Math.min(httpErrors.base + response.status, httpErrors.last);
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(reply));
|
|
89
|
+
} catch {
|
|
90
|
+
throw jobError.malformedResponse;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** An SDK function the Bun runtime has no implementation of: it throws when the program calls it. */
|
|
95
|
+
export const unsupported = (name: string) => () => {
|
|
96
|
+
throw new Error(
|
|
97
|
+
`${name} is not supported by the Bun runtime; run this program on CODESYS.`,
|
|
98
|
+
);
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** What the program's `@tsplc/compiler/async` does in the Bun runtime. */
|
|
102
|
+
export const createAsync = (
|
|
103
|
+
settings: { http: HttpSettings; services: ServiceSettings },
|
|
104
|
+
diagnostics: { count: number; lastError: number },
|
|
105
|
+
) => {
|
|
106
|
+
const call = (path: string, input: unknown) => {
|
|
107
|
+
const route = settings.services.routes[path];
|
|
108
|
+
const { transport } = settings.services;
|
|
109
|
+
if (!route || !transport) {
|
|
110
|
+
return Promise.reject(
|
|
111
|
+
new Error(`The build compiled no call to the service ${path}.`),
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
return transport.call(route, JSON.stringify(input));
|
|
115
|
+
};
|
|
116
|
+
/** A service client: any property is a deeper procedure path, and calling one calls that procedure. */
|
|
117
|
+
const client = (path: readonly string[]): unknown =>
|
|
118
|
+
new Proxy(() => undefined, {
|
|
119
|
+
get: (_, key) =>
|
|
120
|
+
typeof key === "string" ? client([...path, key]) : undefined,
|
|
121
|
+
apply: (_, __, [input]: unknown[]) => call(path.join("."), input),
|
|
122
|
+
});
|
|
123
|
+
return {
|
|
124
|
+
createServiceClient: () => client([]),
|
|
125
|
+
fetch: (url: string, options: { method?: string; json?: unknown } = {}) =>
|
|
126
|
+
httpCall(settings.http, url, {
|
|
127
|
+
method: options.method ?? "GET",
|
|
128
|
+
...(options.json !== undefined && {
|
|
129
|
+
body: JSON.stringify(options.json),
|
|
130
|
+
}),
|
|
131
|
+
}),
|
|
132
|
+
// A sleep resumes on a later scan, even `sleep(ms(0))`: scans never yield to timers.
|
|
133
|
+
sleep: (duration: number) =>
|
|
134
|
+
new Promise<void>((resolve) => setTimeout(resolve, duration)),
|
|
135
|
+
errorCode: failureCode,
|
|
136
|
+
asyncDiagnostics: () => ({ valid: true, ...diagnostics }),
|
|
137
|
+
cancelAsync: unsupported("cancelAsync"),
|
|
138
|
+
opcuaCall: unsupported("opcuaCall"),
|
|
139
|
+
tasks: { define: unsupported("tasks.define") },
|
|
140
|
+
backgroundTasks: { define: unsupported("backgroundTasks.define") },
|
|
141
|
+
cooperativeTasks: { define: unsupported("cooperativeTasks.define") },
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* A compiled program stores one invocation of each async method per instance: launching it
|
|
147
|
+
* from scan code while that invocation runs is dropped, counted with `jobError.noRequestSlot`
|
|
148
|
+
* and never settles, so neither its `then` nor its `catch` runs. The program's classes get the
|
|
149
|
+
* same rule here.
|
|
150
|
+
* A launch from a continuation is an awaited child, which has storage of its own, so it runs.
|
|
151
|
+
* `failed` names a method's rejected promise for an unhandled-failure record.
|
|
152
|
+
*/
|
|
153
|
+
export const oneLaunchAtATime = (
|
|
154
|
+
classes: Iterable<{ name: string; prototype: object }>,
|
|
155
|
+
options: {
|
|
156
|
+
scanning: () => boolean;
|
|
157
|
+
diagnostics: { count: number; lastError: number };
|
|
158
|
+
failed: WeakMap<Promise<unknown>, string>;
|
|
159
|
+
},
|
|
160
|
+
) => {
|
|
161
|
+
const running = new WeakMap<object, Set<string>>();
|
|
162
|
+
for (const { name: className, prototype } of classes) {
|
|
163
|
+
for (const method of Object.getOwnPropertyNames(prototype)) {
|
|
164
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, method);
|
|
165
|
+
const original: unknown = descriptor?.value;
|
|
166
|
+
if (
|
|
167
|
+
typeof original !== "function" ||
|
|
168
|
+
original.constructor.name !== "AsyncFunction"
|
|
169
|
+
) {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const name = `${className}.${method}`;
|
|
173
|
+
Object.defineProperty(prototype, method, {
|
|
174
|
+
...descriptor,
|
|
175
|
+
value: function launch(this: object, ...input: unknown[]) {
|
|
176
|
+
if (!options.scanning()) {
|
|
177
|
+
return original.apply(this, input);
|
|
178
|
+
}
|
|
179
|
+
const methods = running.get(this) ?? new Set<string>();
|
|
180
|
+
running.set(this, methods);
|
|
181
|
+
if (methods.has(method)) {
|
|
182
|
+
options.diagnostics.count += 1;
|
|
183
|
+
options.diagnostics.lastError = jobError.noRequestSlot;
|
|
184
|
+
return new Promise(() => {});
|
|
185
|
+
}
|
|
186
|
+
const started: unknown = original.apply(this, input);
|
|
187
|
+
if (!(started instanceof Promise)) {
|
|
188
|
+
return started;
|
|
189
|
+
}
|
|
190
|
+
methods.add(method);
|
|
191
|
+
const settled = started.then(
|
|
192
|
+
(value: unknown) => {
|
|
193
|
+
methods.delete(method);
|
|
194
|
+
return value;
|
|
195
|
+
},
|
|
196
|
+
(reason: unknown) => {
|
|
197
|
+
methods.delete(method);
|
|
198
|
+
throw reason;
|
|
199
|
+
},
|
|
200
|
+
);
|
|
201
|
+
options.failed.set(settled, name);
|
|
202
|
+
return settled;
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { VerifiedCoreModule } from "@tsplc/compiler/ir";
|
|
2
|
+
import { generatedDirectory } from "@tsplc/config/project-files";
|
|
3
|
+
import { serviceOfPath } from "@tsplc/server/wire";
|
|
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(
|
|
27
|
+
z.string(),
|
|
28
|
+
z.string().refine((route) => serviceOfPath(route) !== undefined),
|
|
29
|
+
),
|
|
30
|
+
});
|
|
31
|
+
export type Launch = z.infer<typeof launchSchema>;
|
|
32
|
+
|
|
33
|
+
/** A runtime that serves: its process and where it publishes OPC UA. */
|
|
34
|
+
export const runtimeStateSchema = z.strictObject({
|
|
35
|
+
pid: z.number().int().positive(),
|
|
36
|
+
endpoint: z.string().startsWith("opc.tcp://"),
|
|
37
|
+
startedAt: z.iso.datetime(),
|
|
38
|
+
});
|
|
39
|
+
export type RuntimeState = z.infer<typeof runtimeStateSchema>;
|
|
40
|
+
|
|
41
|
+
/** A service block's route: its URL's path over HTTP, the path its slots carry over OPC UA. */
|
|
42
|
+
const blockRoute = (
|
|
43
|
+
runtime: VerifiedCoreModule["blocks"][number]["runtime"],
|
|
44
|
+
) => {
|
|
45
|
+
if (runtime?.kind === "http") {
|
|
46
|
+
return URL.parse(runtime.url)?.pathname;
|
|
47
|
+
}
|
|
48
|
+
return runtime?.kind === "rpc" ? runtime.path : undefined;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** The route each service call the program makes goes to, as the build compiled it. */
|
|
52
|
+
export const serviceRoutes = (core: VerifiedCoreModule) =>
|
|
53
|
+
Object.fromEntries(
|
|
54
|
+
core.blocks.flatMap((block) => {
|
|
55
|
+
const route = blockRoute(block.runtime);
|
|
56
|
+
const procedure = route && serviceOfPath(route);
|
|
57
|
+
return route && procedure ? [[procedure, route] as const] : [];
|
|
58
|
+
}),
|
|
59
|
+
);
|
|
@@ -0,0 +1,59 @@
|
|
|
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 { rename, rm, writeFile } from "node:fs/promises";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { tcpPort } from "@tsplc/config/build";
|
|
12
|
+
import { launchSchema, type RuntimeState, runtimeFiles } from "./launch";
|
|
13
|
+
import { runtimeEndpoint, startRuntime } from "./runtime";
|
|
14
|
+
|
|
15
|
+
const [launchFile, port] = process.argv.slice(2);
|
|
16
|
+
if (!launchFile) {
|
|
17
|
+
throw new Error("Usage: main.ts <launch.json> [port]");
|
|
18
|
+
}
|
|
19
|
+
const stateFile = join(dirname(launchFile), runtimeFiles.state);
|
|
20
|
+
const log = (line: string) => console.log(`[tsplc runtime] ${line}`);
|
|
21
|
+
try {
|
|
22
|
+
const runtime = await startRuntime({
|
|
23
|
+
launch: launchSchema.parse(JSON.parse(readFileSync(launchFile, "utf8"))),
|
|
24
|
+
environment: process.env,
|
|
25
|
+
port:
|
|
26
|
+
port === undefined ? runtimeEndpoint.port : tcpPort.parse(Number(port)),
|
|
27
|
+
log,
|
|
28
|
+
});
|
|
29
|
+
// Written whole under another name first, so a reader never sees half of it.
|
|
30
|
+
const written = `${stateFile}.${process.pid}`;
|
|
31
|
+
await writeFile(
|
|
32
|
+
written,
|
|
33
|
+
`${JSON.stringify({
|
|
34
|
+
pid: process.pid,
|
|
35
|
+
endpoint: runtime.endpoint,
|
|
36
|
+
startedAt: new Date().toISOString(),
|
|
37
|
+
} satisfies RuntimeState)}\n`,
|
|
38
|
+
);
|
|
39
|
+
await rename(written, stateFile);
|
|
40
|
+
const stop = async (signal: string) => {
|
|
41
|
+
log(`Stopping on ${signal}.`);
|
|
42
|
+
try {
|
|
43
|
+
await runtime.stop();
|
|
44
|
+
} finally {
|
|
45
|
+
await rm(stateFile, { force: true });
|
|
46
|
+
process.exit(0);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
process.once("SIGINT", stop);
|
|
50
|
+
process.once("SIGTERM", stop);
|
|
51
|
+
} catch (cause) {
|
|
52
|
+
console.error(
|
|
53
|
+
`[tsplc runtime] ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
54
|
+
);
|
|
55
|
+
if (cause instanceof Error && cause.cause) {
|
|
56
|
+
console.error(cause.cause);
|
|
57
|
+
}
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|