nodalis-compiler 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +134 -0
  2. package/package.json +59 -0
  3. package/src/compilers/CPPCompiler.js +272 -0
  4. package/src/compilers/Compiler.js +108 -0
  5. package/src/compilers/JSCompiler.js +293 -0
  6. package/src/compilers/iec-parser/parser.js +4254 -0
  7. package/src/compilers/st-parser/expressionConverter.js +155 -0
  8. package/src/compilers/st-parser/gcctranspiler.js +237 -0
  9. package/src/compilers/st-parser/jstranspiler.js +254 -0
  10. package/src/compilers/st-parser/parser.js +367 -0
  11. package/src/compilers/st-parser/tokenizer.js +78 -0
  12. package/src/compilers/support/generic/json.hpp +25526 -0
  13. package/src/compilers/support/generic/modbus.cpp +378 -0
  14. package/src/compilers/support/generic/modbus.h +124 -0
  15. package/src/compilers/support/generic/nodalis.cpp +421 -0
  16. package/src/compilers/support/generic/nodalis.h +798 -0
  17. package/src/compilers/support/generic/opcua.cpp +267 -0
  18. package/src/compilers/support/generic/opcua.h +50 -0
  19. package/src/compilers/support/generic/open62541.c +151897 -0
  20. package/src/compilers/support/generic/open62541.h +50357 -0
  21. package/src/compilers/support/jint/nodalis/Nodalis.sln +28 -0
  22. package/src/compilers/support/jint/nodalis/NodalisEngine/ModbusClient.cs +200 -0
  23. package/src/compilers/support/jint/nodalis/NodalisEngine/NodalisEngine.cs +817 -0
  24. package/src/compilers/support/jint/nodalis/NodalisEngine/NodalisEngine.csproj +16 -0
  25. package/src/compilers/support/jint/nodalis/NodalisEngine/OPCClient.cs +172 -0
  26. package/src/compilers/support/jint/nodalis/NodalisEngine/OPCServer.cs +275 -0
  27. package/src/compilers/support/jint/nodalis/NodalisPLC/NodalisPLC.csproj +19 -0
  28. package/src/compilers/support/jint/nodalis/NodalisPLC/Program.cs +197 -0
  29. package/src/compilers/support/jint/nodalis/NodalisPLC/bootstrap.bat +5 -0
  30. package/src/compilers/support/jint/nodalis/NodalisPLC/bootstrap.sh +5 -0
  31. package/src/compilers/support/jint/nodalis/build.bat +25 -0
  32. package/src/compilers/support/jint/nodalis/build.sh +31 -0
  33. package/src/compilers/support/nodejs/IOClient.js +110 -0
  34. package/src/compilers/support/nodejs/modbus.js +115 -0
  35. package/src/compilers/support/nodejs/nodalis.js +662 -0
  36. package/src/compilers/support/nodejs/opcua.js +194 -0
  37. package/src/nodalis.js +174 -0
@@ -0,0 +1,293 @@
1
+ /* eslint-disable curly */
2
+ /* eslint-disable eqeqeq */
3
+ // Copyright [2025] Nathan Skipper
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+ import { execSync } from 'child_process';
17
+ import fs from 'fs';
18
+ import os from "os";
19
+ import path from "path";
20
+ import { Compiler, IECLanguage, OutputType, CommunicationProtocol } from './Compiler.js';
21
+ import * as iec from "./iec-parser/parser.js";
22
+ import { parseStructuredText } from './st-parser/parser.js';
23
+ import { transpile } from './st-parser/jstranspiler.js';
24
+ import which from "which";
25
+ import { fileURLToPath } from "url";
26
+
27
+ const __filename = fileURLToPath(import.meta.url);
28
+ const __dirname = path.dirname(__filename);
29
+
30
+ export class JSCompiler extends Compiler {
31
+ constructor(options) {
32
+ super(options);
33
+ this.name = 'JSCompiler';
34
+ }
35
+
36
+ get supportedLanguages() {
37
+ return [IECLanguage.STRUCTURED_TEXT, IECLanguage.LADDER_DIAGRAM];
38
+ }
39
+
40
+ get supportedOutputTypes() {
41
+ return [OutputType.SOURCE_CODE, OutputType.EXECUTABLE];
42
+ }
43
+
44
+ get supportedTargetDevices() {
45
+ return ["jint", "nodejs"];
46
+ }
47
+
48
+ get supportedProtocols() {
49
+ return [CommunicationProtocol.MODBUS, CommunicationProtocol.OPC_UA, CommunicationProtocol.BACNET];
50
+ }
51
+
52
+ get compilerVersion() {
53
+ return '1.0.0';
54
+ }
55
+
56
+ compile() {
57
+ const { sourcePath, outputPath, target, outputType, resourceName } = this.options;
58
+ var sourceCode = fs.readFileSync(sourcePath, 'utf-8');
59
+ const filename = path.basename(sourcePath, path.extname(sourcePath));
60
+ const jsFile = path.join(outputPath, `${filename}.js`);
61
+ const stFile = path.join(outputPath, `${filename}.st`);
62
+ if(sourcePath.toLowerCase().endsWith(".iec") || sourcePath.toLowerCase().endsWith(".xml")){
63
+ if(typeof resourceName === "undefined" || resourceName === null || resourceName.length === 0){
64
+ throw new Error("You must provide the resourceName option for an IEC project file.");
65
+ }
66
+ var stcode = "";
67
+ const iecProj = iec.Project.fromXML(sourceCode);
68
+ iecProj.Instances.Configurations.forEach(
69
+ /**
70
+ * @param {iec.Configuration} c
71
+ */
72
+ (c) => {
73
+ if(stcode.length > 0) return;
74
+ /**
75
+ * @type {iec.Resource}
76
+ */
77
+ const res = c.Resources.find(r => r.Name === resourceName);
78
+ if(res){
79
+ stcode = res.toST();
80
+ }
81
+ }
82
+ );
83
+ if(stcode.length > 0){
84
+ sourceCode = stcode;
85
+ }
86
+ else{
87
+ throw new Error("No resource was found by the name " + resourceName + " or the resource could not be parsed.");
88
+ }
89
+ }
90
+ const parsed = parseStructuredText(sourceCode);
91
+ const transpiledCode = transpile(parsed);
92
+
93
+ let tasks = [];
94
+ let programs = [];
95
+ let globals = [];
96
+ let taskCode = "";
97
+ let mapCode = "";
98
+ let plcname = "NodalisPLC";
99
+ if(typeof resourceName !== "undefined" && resourceName !== null){
100
+ plcname = resourceName;
101
+ }
102
+ const lines = sourceCode.split("\n");
103
+ lines.forEach((line) => {
104
+ if(line.trim().startsWith("//Task=")){
105
+ var task = JSON.parse(line.substring(line.indexOf("=") + 1).trim());
106
+ task["Instances"] = [];
107
+ tasks.push(task);
108
+ }
109
+ else if(line.trim().startsWith("//Instance=")){
110
+ var instance = JSON.parse(line.substring(line.indexOf("=") + 1).trim());
111
+ var task = tasks.find((t) => t.Name === instance.AssociatedTaskName);
112
+ if(task){
113
+ task.Instances.push(instance);
114
+ }
115
+ }
116
+ else if(line.trim().startsWith("//Map=")){
117
+ mapCode += `mapIO("${line.substring(line.indexOf("=") + 1).trim()}");\n`;
118
+
119
+ }
120
+ else if(line.indexOf("//Global=") > -1){
121
+ let global = JSON.parse(line.substring(line.indexOf("=") + 1).trim());
122
+ globals.push(`opcServer.mapVariable("${global.Name}", "${global.Address}");`)
123
+
124
+ }
125
+ else if(line.trim().startsWith("PROGRAM")){
126
+ var pname = line.trim().substring(line.trim().indexOf(" ") + 1).trim();
127
+ if(pname.includes(" ")){
128
+ pname = pname.substring(pname.indexOf(" ") + 1);
129
+ }
130
+ if(pname.includes("//")){
131
+ pname = pname.substring(pname.indexOf("//") + 1);
132
+ }
133
+ if(pname.includes("(*")){
134
+ pname = pname.substring(pname.indexOf("(*") + 1);
135
+ }
136
+ programs.push(pname);
137
+ }
138
+ });
139
+ if(tasks.length > 0){
140
+ tasks.forEach((t) => {
141
+ var progCode = "";
142
+ t.Instances.forEach((i) => {
143
+ progCode += i.TypeName + "();\n";
144
+ });
145
+ taskCode +=
146
+ `
147
+ ${target === "nodejs" ? `setInterval(() => {` : ""}
148
+ ${progCode}
149
+ ${target === "nodejs" ? `}, ${t.Interval});` : ""}
150
+ `;
151
+ });
152
+ }
153
+ else{
154
+ if(target === "nodejs") taskCode = "setInterval(() => {\n";
155
+ programs.forEach((p) => {
156
+ taskCode += p + "();\n";
157
+ });
158
+ if(target === "nodejs") taskCode += "}, 100);"
159
+ }
160
+ let includes =
161
+ `import {
162
+ readBit, writeBit, readByte, writeByte, readWord, writeWord, readDWord, writeDWord, readAddress, writeAddress,
163
+ getBit, setBit, resolve, newStatic, RefVar, superviseIO, mapIO, createReference,
164
+ TON, TOF, TP, R_TRIG, F_TRIG, CTU, CTD, CTUD,
165
+ AND, OR, XOR, NOR, NAND, NOT, ASSIGNMENT,
166
+ EQ, NE, LT, GT, GE, LE,
167
+ MOVE, SEL, MUX, MIN, MAX, LIMIT
168
+ } from "./nodalis.js";
169
+ import {OPCServer} from "./opcua.js";`;
170
+ if(target === "jint"){
171
+ includes = "";
172
+ }
173
+ let jsCode =
174
+ `${includes}
175
+ ${transpiledCode}
176
+ ${target === "nodejs" ? `let opcServer = new OPCServer();`: ""}
177
+ export async function setup(){
178
+ ${mapCode}
179
+
180
+ ${target === "nodejs" ? "opcServer.setReadWriteHandlers(readAddress, writeAddress);\n" + `await opcServer.start();\n` + globals.join("\n") : ""}
181
+ console.log("${plcname} is running!");
182
+ }
183
+
184
+ export function run(){
185
+ ${target === "nodejs" ? "setInterval(superviseIO, 1);" : ""}
186
+ ${taskCode}
187
+
188
+ }
189
+ `;
190
+ if(target === "nodejs"){
191
+ jsCode += "\nsetup();\nrun();";
192
+ }
193
+ if(target === "jint"){
194
+ jsCode = jsCode.replaceAll("export ", "").replaceAll("console.log", "log").replaceAll("console.error", "error");
195
+ }
196
+ fs.mkdirSync(outputPath, { recursive: true });
197
+ fs.writeFileSync(jsFile, jsCode);
198
+ if(sourcePath.toLowerCase().endsWith(".iec") || sourcePath.toLowerCase().endsWith(".xml")){
199
+ fs.writeFileSync(stFile, sourceCode);
200
+ }
201
+ if(target === "nodejs"){
202
+ // Copy core headers and cpp support files
203
+ const coreFiles = [
204
+ 'nodalis.js',
205
+ 'modbus.js',
206
+ "IOClient.js",
207
+ "opcua.js"
208
+ ];
209
+
210
+ let coreDir = path.resolve('./src/compilers/support/nodejs');
211
+
212
+ for (const file of coreFiles) {
213
+ fs.copyFileSync(path.join(coreDir, file), path.join(outputPath, file));
214
+ }
215
+
216
+ writePackageJson(outputPath, plcname);
217
+ installDependencies(outputPath);
218
+ }
219
+
220
+
221
+ if (target === "jint" && outputType === "executable") {
222
+ const supportDir = path.resolve(__dirname, "support/jint/Nodalis");
223
+ const buildScript = os.platform() === "win32" ? "build.bat" : "build.sh";
224
+
225
+ // 1. Copy all files from support/jint/nodalis to the output directory
226
+ fs.cpSync(supportDir, outputPath, { recursive: true });
227
+
228
+ // 2. Run the build script inside the output directory
229
+ const buildPath = path.resolve(path.join(outputPath, buildScript));
230
+ if(buildPath.endsWith(".sh")){
231
+ fs.chmodSync(buildPath, 0o755); // make executable
232
+ }
233
+ execSync(buildPath, { cwd: path.resolve(outputPath), stdio: "inherit", shell: true });
234
+
235
+ // 3. Copy the generated JS file to each publish folder
236
+ const publishRoot = path.join(outputPath, "publish");
237
+
238
+ const platforms = fs.readdirSync(publishRoot, { withFileTypes: true })
239
+ .filter(d => d.isDirectory())
240
+ .map(d => path.join(publishRoot, d.name));
241
+ const scriptName = filename + ".js"
242
+ for (const platformDir of platforms) {
243
+ const dest = path.join(platformDir, scriptName);
244
+ fs.copyFileSync(jsFile, dest);
245
+
246
+ // 2. Patch bootstrap.sh if present
247
+ const shFile = path.join(platformDir, "bootstrap.sh");
248
+ if (fs.existsSync(shFile)) {
249
+ let content = fs.readFileSync(shFile, "utf-8");
250
+ content = content.replace("{script}", scriptName);
251
+ fs.writeFileSync(shFile, content, "utf-8");
252
+ fs.chmodSync(shFile, 0o755); // make executable
253
+ }
254
+
255
+ // 3. Patch bootstrap.bat if present
256
+ const batFile = path.join(platformDir, "bootstrap.bat");
257
+ if (fs.existsSync(batFile)) {
258
+ let content = fs.readFileSync(batFile, "utf-8");
259
+ content = content.replace("{script}", scriptName);
260
+ fs.writeFileSync(batFile, content, "utf-8");
261
+ }
262
+
263
+ }
264
+ }
265
+ }
266
+
267
+ }
268
+
269
+ function writePackageJson(outputDir,plcname) {
270
+ const pkg = {
271
+ name: "nodalis-" + plcname,
272
+ version: "1.0.0",
273
+ type: "module",
274
+ main: plcname + ".js",
275
+ dependencies: {
276
+ "jsmodbus": "^4.0.6",
277
+ "node-opcua": "^2.156.0"
278
+ }
279
+ };
280
+ fs.writeFileSync(path.join(outputDir, "package.json"), JSON.stringify(pkg, null, 2));
281
+ }
282
+
283
+ function installDependencies(outputDir) {
284
+ const npmPath = which.sync('npm'); // find actual npm binary
285
+ console.log(`Running npm from: ${npmPath}`);
286
+
287
+ execSync(`"${npmPath}" install`, {
288
+ cwd: outputDir,
289
+ stdio: 'inherit',
290
+ shell: true
291
+ });
292
+ }
293
+