@tsplc/config 0.2.17 → 0.2.19

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/src/schema.ts CHANGED
@@ -1,318 +1,348 @@
1
1
  import { z } from "zod";
2
2
  import {
3
- configSchema,
4
- controllerDevices,
5
- controllerTargetSchema,
6
- cyclicTasksSchema,
7
- directIoBindingSchema,
8
- ioBindingOptions,
9
- ethernetSchema,
10
- type CodesysBuildConfig,
3
+ assemblyAddress,
4
+ configSchema,
5
+ controllerDevices,
6
+ controllerTargetSchema,
7
+ cyclicTasksSchema,
8
+ directIoBindingSchema,
9
+ envName,
10
+ fourPartVersion,
11
+ iecName,
12
+ ioBindingOptions,
13
+ ethernetSchema,
14
+ taskPriority,
15
+ tcpPort,
16
+ type CodesysBuildConfig,
11
17
  } from "./build-schema.ts";
12
18
  import {
13
- durationSchema,
14
- validateConfig as validateCompilerConfig,
15
- type PlcConfig,
19
+ durationSchema,
20
+ taskSchema,
21
+ validateConfig as validateCompilerConfig,
22
+ type PlcConfig,
16
23
  } from "./compiler.ts";
17
24
 
18
25
  export {
19
- ns,
20
- ms,
21
- seconds,
22
- definePlcConfig,
23
- validateConfig,
24
- type Duration,
25
- type NormalizedConfig,
26
- type PlcConfig,
27
- type SourceExport,
28
- type TargetDescriptor,
29
- type TaskConfig,
26
+ ns,
27
+ ms,
28
+ seconds,
29
+ definePlcConfig,
30
+ validateConfig,
31
+ type Duration,
32
+ type NormalizedConfig,
33
+ type PlcConfig,
34
+ type SourceExport,
35
+ type TargetDescriptor,
36
+ type TaskConfig,
30
37
  } from "./compiler.ts";
31
- export type { CodesysBuildConfig, Controller, DeviceTree } from "./build-schema.ts";
38
+ export type {
39
+ CodesysBuildConfig,
40
+ Controller,
41
+ DeviceTree,
42
+ } from "./build-schema.ts";
32
43
 
33
44
  export const httpOptionsSchema = z
34
- .strictObject({
35
- timeoutMs: z.number().int().positive().max(60000).default(2000),
36
- credentials: z
37
- .array(
38
- z.strictObject({
39
- originEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),
40
- bearerTokenEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),
41
- }),
42
- )
43
- .default([]),
44
- })
45
- .default({ timeoutMs: 2000, credentials: [] });
45
+ .strictObject({
46
+ timeoutMs: z.number().int().positive().max(60000).default(2000),
47
+ credentials: z
48
+ .array(
49
+ z.strictObject({
50
+ originEnv: envName,
51
+ bearerTokenEnv: envName,
52
+ }),
53
+ )
54
+ .default([]),
55
+ })
56
+ .prefault({});
46
57
  export type HttpOptions = z.infer<typeof httpOptionsSchema>;
47
58
 
48
59
  const ioBindingSchema = z.union([
49
- directIoBindingSchema,
50
- z.strictObject({
51
- device: z.string().min(1),
52
- channel: z.string().min(1),
53
- ...ioBindingOptions,
54
- }),
60
+ directIoBindingSchema,
61
+ z.strictObject({
62
+ device: z.string().min(1),
63
+ channel: z.string().min(1),
64
+ ...ioBindingOptions,
65
+ }),
55
66
  ]);
56
67
  // Each field defaults: the assembly from the connection, the size from the EDS and,
57
68
  // with a generated device tree, the address from tsPLC's process-image layout.
58
69
  const assemblySchema = z.strictObject({
59
- assembly: z.number().int().nonnegative().optional(),
60
- size: z.number().int().positive().optional(),
61
- address: z
62
- .string()
63
- .regex(/^%[IQ]B\d+$/)
64
- .optional(),
70
+ assembly: z.number().int().nonnegative().optional(),
71
+ size: z.number().int().positive().optional(),
72
+ address: assemblyAddress.optional(),
65
73
  });
66
74
  const hardwareDeviceSchema = z.strictObject({
67
- file: z.string().min(1),
68
- connection: z.string().min(1).optional(),
69
- inputs: assemblySchema.optional(),
70
- outputs: assemblySchema.optional(),
71
- // Registers the generated device tree writes over Modbus TCP, at network.address.
72
- // Each maps a name to its wire offset, and is written with FC06 when its write channel rises.
73
- modbus: z
74
- .strictObject({
75
- port: z.number().int().min(1).max(65535).default(502),
76
- registers: z.record(
77
- z.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),
78
- z.number().int().min(0).max(65535),
79
- ),
80
- })
81
- .optional(),
82
- statusSymbols: z.record(z.string(), z.string()).optional(),
83
- // The adapter's network identity in a generated device tree.
84
- network: z
85
- .strictObject({
86
- address: z.ipv4().optional(),
87
- rpi: durationSchema
88
- .refine(
89
- (rpi) => BigInt(rpi.nanoseconds) % 1000n === 0n,
90
- "An RPI must be a whole number of microseconds.",
91
- )
92
- .optional(),
93
- })
94
- .optional(),
75
+ file: z.string().min(1),
76
+ connection: z.string().min(1).optional(),
77
+ inputs: assemblySchema.optional(),
78
+ outputs: assemblySchema.optional(),
79
+ // Registers the generated device tree writes over Modbus TCP, at network.address.
80
+ // Each maps a name to its wire offset, and is written with FC06 when its write channel rises.
81
+ modbus: z
82
+ .strictObject({
83
+ port: tcpPort.default(502),
84
+ registers: z.record(iecName, z.number().int().min(0).max(65535)),
85
+ })
86
+ .optional(),
87
+ statusSymbols: z.record(z.string(), z.string()).optional(),
88
+ // The adapter's network identity in a generated device tree.
89
+ network: z
90
+ .strictObject({
91
+ address: z.ipv4().optional(),
92
+ rpi: durationSchema
93
+ .refine(
94
+ (rpi) => BigInt(rpi.nanoseconds) % 1000n === 0n,
95
+ "An RPI must be a whole number of microseconds.",
96
+ )
97
+ .optional(),
98
+ })
99
+ .optional(),
95
100
  });
96
101
  const dependencySchema = z.union([
97
- z.string().regex(/^\d+\.\d+\.\d+\.\d+$/),
98
- z.strictObject({
99
- version: z.string().regex(/^\d+\.\d+\.\d+\.\d+$/),
100
- company: z.string().optional(),
101
- namespace: z.string().optional(),
102
- }),
103
- z.strictObject({ path: z.string().min(1), namespace: z.string().optional() }),
102
+ fourPartVersion,
103
+ z.strictObject({
104
+ version: fourPartVersion,
105
+ company: z.string().optional(),
106
+ namespace: z.string().optional(),
107
+ }),
108
+ z.strictObject({ path: z.string().min(1), namespace: z.string().optional() }),
104
109
  ]);
105
- const taskSchema = z.strictObject({
106
- name: z.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),
107
- schedule: z.strictObject({ kind: z.literal("cyclic"), interval: durationSchema }),
108
- priority: z.number().int().min(0).max(31),
109
- programs: z.array(z.string().min(1)).nonempty(),
110
+ // `backend` is always CODESYS, so tasks get its name and priority rules here, as raw ST schedules do in cyclicTasksSchema.
111
+ const codesysTaskSchema = taskSchema.extend({
112
+ name: iecName,
113
+ priority: taskPriority,
110
114
  });
111
115
  const monitorSchema = z
112
- .strictObject({
113
- endpoint: z.string().url(),
114
- namespaceUri: z.string().optional(),
115
- symbols: z.array(z.string().min(1)).optional(),
116
- securityMode: z.enum(["None", "Sign", "SignAndEncrypt"]).default("SignAndEncrypt"),
117
- securityPolicy: z.enum(["None", "Basic256Sha256"]).optional(),
118
- certificateDirectory: z.string().min(1).default(".tsplc/opcua-pki"),
119
- username: z.string().min(1).optional(),
120
- passwordEnv: z
121
- .string()
122
- .regex(/^[A-Za-z_][A-Za-z_0-9]*$/)
123
- .optional(),
124
- })
125
- .superRefine((monitor, context) => {
126
- if (
127
- monitor.securityPolicy &&
128
- (monitor.securityMode === "None") !== (monitor.securityPolicy === "None")
129
- )
130
- context.addIssue({
131
- code: "custom",
132
- path: ["securityPolicy"],
133
- message: "None mode requires None policy; secure modes require Basic256Sha256.",
134
- });
135
- if (monitor.passwordEnv && !monitor.username)
136
- context.addIssue({
137
- code: "custom",
138
- path: ["username"],
139
- message: "Configure username when passwordEnv is used.",
140
- });
141
- if (monitor.username && monitor.securityMode === "None")
142
- context.addIssue({
143
- code: "custom",
144
- path: ["securityMode"],
145
- message: "Username authentication requires a secure OPC-UA connection.",
146
- });
147
- })
148
- .transform((monitor) => ({
149
- ...monitor,
150
- securityPolicy:
151
- monitor.securityPolicy ??
152
- (monitor.securityMode === "None" ? ("None" as const) : ("Basic256Sha256" as const)),
153
- }));
116
+ .strictObject({
117
+ endpoint: z.string().url(),
118
+ namespaceUri: z.string().optional(),
119
+ symbols: z.array(z.string().min(1)).optional(),
120
+ securityMode: z
121
+ .enum(["None", "Sign", "SignAndEncrypt"])
122
+ .default("SignAndEncrypt"),
123
+ securityPolicy: z.enum(["None", "Basic256Sha256"]).optional(),
124
+ certificateDirectory: z.string().min(1).default(".tsplc/opcua-pki"),
125
+ username: z.string().min(1).optional(),
126
+ passwordEnv: envName.optional(),
127
+ })
128
+ .superRefine((monitor, context) => {
129
+ if (
130
+ monitor.securityPolicy &&
131
+ (monitor.securityMode === "None") !== (monitor.securityPolicy === "None")
132
+ ) {
133
+ context.addIssue({
134
+ code: "custom",
135
+ path: ["securityPolicy"],
136
+ message:
137
+ "None mode requires None policy; secure modes require Basic256Sha256.",
138
+ });
139
+ }
140
+ if (monitor.passwordEnv && !monitor.username) {
141
+ context.addIssue({
142
+ code: "custom",
143
+ path: ["username"],
144
+ message: "Configure username when passwordEnv is used.",
145
+ });
146
+ }
147
+ if (monitor.username && monitor.securityMode === "None") {
148
+ context.addIssue({
149
+ code: "custom",
150
+ path: ["securityMode"],
151
+ message: "Username authentication requires a secure OPC-UA connection.",
152
+ });
153
+ }
154
+ })
155
+ .transform((monitor) => ({
156
+ ...monitor,
157
+ securityPolicy:
158
+ monitor.securityPolicy ??
159
+ (monitor.securityMode === "None"
160
+ ? ("None" as const)
161
+ : ("Basic256Sha256" as const)),
162
+ }));
154
163
  /**
155
164
  * The records each PLC task keeps for its sender (docs/language/telemetry.md): used whenever the
156
165
  * program calls `@tsplc/compiler/telemetry`, records unhandled job failures or traces for the debugger.
157
166
  */
158
167
  export const telemetrySchema = z.strictObject({
159
- /** Records in each task's ring; older unsent records are overwritten and counted as dropped. */
160
- capacity: z.number().int().min(4).max(4096).default(64),
161
- /**
162
- * The largest encoded JSON of one record, checked for every call when the program compiles.
163
- * It is fixed rather than fitted to the program, so that a ring keeps its layout from one build
164
- * to the next: CODESYS cannot apply an online change that moves a ring.
165
- */
166
- recordBytes: z.number().int().min(128).max(1024).default(512),
168
+ /** Records in each task's ring; older unsent records are overwritten and counted as dropped. */
169
+ capacity: z.number().int().min(4).max(4096).default(64),
170
+ /**
171
+ * The largest encoded JSON of one record, checked for every call when the program compiles.
172
+ * It is fixed rather than fitted to the program, so that a ring keeps its layout from one build
173
+ * to the next: CODESYS cannot apply an online change that moves a ring.
174
+ */
175
+ recordBytes: z.number().int().min(128).max(1024).default(512),
167
176
  });
168
177
  /**
169
178
  * The debugger's fixed-size instrumentation (docs/design/debugging.md). It reads state through
170
179
  * the engineering login, so it publishes nothing. Without it a build only carries its build id.
171
180
  */
172
181
  const debugSchema = z.strictObject({
173
- /** Records enum state changes, decisions and job starts and ends; for local debugging sessions. */
174
- trace: z
175
- .union([
176
- z.literal(false),
177
- z.strictObject({
178
- capacity: z.number().int().min(16).max(4096).default(256),
179
- operands: z.number().int().min(0).max(8).default(4),
180
- }),
181
- ])
182
- .default(false),
183
- writers: z.boolean().default(true),
184
- jobs: z.boolean().default(true),
185
- /** Watch groups the debugger opens with: TypeScript paths, `*` matching one path segment. */
186
- watch: z.record(z.string(), z.array(z.string().min(1))).default({}),
187
- requests: z
188
- .strictObject({
189
- capacity: z.number().int().min(1).max(100_000).default(1000),
190
- /** Keep service call inputs and outputs; off by default because they may carry data that isn't the debugger's to show. */
191
- bodies: z.boolean().default(false),
192
- })
193
- .default({ capacity: 1000, bodies: false }),
182
+ /** Records enum state changes, decisions and job starts and ends; for local debugging sessions. */
183
+ trace: z
184
+ .union([
185
+ z.literal(false),
186
+ z.strictObject({
187
+ capacity: z.number().int().min(16).max(4096).default(256),
188
+ operands: z.number().int().min(0).max(8).default(4),
189
+ }),
190
+ ])
191
+ .default(false),
192
+ writers: z.boolean().default(true),
193
+ jobs: z.boolean().default(true),
194
+ /** Watch groups the debugger opens with: TypeScript paths, `*` matching one path segment. */
195
+ watch: z.record(z.string(), z.array(z.string().min(1))).default({}),
196
+ requests: z
197
+ .strictObject({
198
+ capacity: z.number().int().min(1).max(100_000).default(1000),
199
+ /** Keep service call inputs and outputs; off by default because they may carry data that isn't the debugger's to show. */
200
+ bodies: z.boolean().default(false),
201
+ })
202
+ .prefault({}),
194
203
  });
195
204
  export const typegenSchema = z.strictObject({
196
- types: z.union([z.string(), z.array(z.string())]).optional(),
197
- globals: z.union([z.string(), z.array(z.string())]).optional(),
198
- /** Directory for the generated `plc.ts`, `hardware.ts` and `machines.ts`. */
199
- dir: z.string().default("generated"),
200
- /** Emit TypeScript declarations in `plc.ts`, not just the runtime field and symbol tables. */
201
- declarations: z.boolean().default(true),
202
- /** Emit the I/O binding types and device catalog in `hardware.ts`, not just the publication selectors. */
203
- ioTypes: z.boolean().default(true),
205
+ types: z.union([z.string(), z.array(z.string())]).optional(),
206
+ globals: z.union([z.string(), z.array(z.string())]).optional(),
207
+ /** Directory for the generated `plc.ts`, `hardware.ts` and `machines.ts`. */
208
+ dir: z.string().default("generated"),
209
+ /** Emit TypeScript declarations in `plc.ts`, not just the runtime field and symbol tables. */
210
+ declarations: z.boolean().default(true),
211
+ /** Emit the I/O binding types and device catalog in `hardware.ts`, not just the publication selectors. */
212
+ ioTypes: z.boolean().default(true),
204
213
  });
205
214
  export const buildTargetSchema = z.enum(["production", "development"]);
206
215
  export type BuildTarget = z.infer<typeof buildTargetSchema>;
207
216
  export const publicationSchema = z.strictObject({
208
- production: z.array(z.string().nonempty()),
209
- development: z.array(z.string().nonempty()),
217
+ production: z.array(z.string().nonempty()),
218
+ development: z.array(z.string().nonempty()),
210
219
  });
211
220
  export type Publication = Readonly<Record<BuildTarget, readonly string[]>>;
212
221
  /** A published PLC variable, as `Global.Field`. */
213
222
  const hmiTarget = z.string().regex(/^\w+(\.\w+|\[\d+\])+$/);
214
223
  const hmiControlSchema = z.discriminatedUnion("kind", [
215
- /** Pulses a BOOL on for 200 ms, like a pushbutton. */
216
- z.strictObject({
217
- kind: z.literal("button"),
218
- label: z.string().nonempty(),
219
- target: hmiTarget,
220
- tone: z.enum(["start", "stop"]).optional(),
221
- /** Ask before pressing, for controls that start motion. */
222
- confirm: z.boolean().optional(),
223
- }),
224
- /** Switches a BOOL on or off, and shows its current state. */
225
- z.strictObject({
226
- kind: z.literal("toggle"),
227
- label: z.string().nonempty(),
228
- target: hmiTarget,
229
- }),
230
- /** Writes an integer when released, and shows its current value. */
231
- z.strictObject({
232
- kind: z.literal("slider"),
233
- label: z.string().nonempty(),
234
- target: hmiTarget,
235
- min: z.number().int(),
236
- max: z.number().int(),
237
- }),
224
+ /** Pulses a BOOL on for 200 ms, like a pushbutton. */
225
+ z.strictObject({
226
+ kind: z.literal("button"),
227
+ label: z.string().nonempty(),
228
+ target: hmiTarget,
229
+ tone: z.enum(["start", "stop"]).optional(),
230
+ /** Ask before pressing, for controls that start motion. */
231
+ confirm: z.boolean().optional(),
232
+ }),
233
+ /** Switches a BOOL on or off, and shows its current state. */
234
+ z.strictObject({
235
+ kind: z.literal("toggle"),
236
+ label: z.string().nonempty(),
237
+ target: hmiTarget,
238
+ }),
239
+ /** Writes an integer when released, and shows its current value. */
240
+ z.strictObject({
241
+ kind: z.literal("slider"),
242
+ label: z.string().nonempty(),
243
+ target: hmiTarget,
244
+ min: z.number().int(),
245
+ max: z.number().int(),
246
+ }),
238
247
  ]);
239
248
  export const hmiSchema = z.strictObject({
240
- title: z.string().nonempty(),
241
- controls: z.array(hmiControlSchema).default([]),
242
- /** The PLC reports whether each position of these conveyors is occupied, in this order. */
243
- conveyors: z
244
- .array(
245
- z.strictObject({
246
- label: z.string().nonempty(),
247
- positions: z.number().int().positive(),
248
- /** Positions that are diverters, drawn differently. */
249
- diverters: z.array(z.number().int().nonnegative()).default([]),
250
- }),
251
- )
252
- .default([]),
249
+ title: z.string().nonempty(),
250
+ controls: z.array(hmiControlSchema).default([]),
251
+ /** The PLC reports whether each position of these conveyors is occupied, in this order. */
252
+ conveyors: z
253
+ .array(
254
+ z.strictObject({
255
+ label: z.string().nonempty(),
256
+ positions: z.number().int().positive(),
257
+ /** Positions that are diverters, drawn differently. */
258
+ diverters: z.array(z.number().int().nonnegative()).default([]),
259
+ }),
260
+ )
261
+ .default([]),
253
262
  });
254
263
  export type HmiConfig = z.input<typeof hmiSchema>;
255
264
  export type ResolvedHmiConfig = z.output<typeof hmiSchema>;
256
265
 
257
266
  export const tsplcConfigSchema = z.strictObject({
258
- name: z.string().default("Application"),
259
- backend: z.literal("codesys"),
260
- publish: publicationSchema.optional(),
261
- server: z
262
- .strictObject({
263
- baseUrlEnv: z.string().optional(),
264
- transport: z.enum(["http", "opcua"]).default("http"),
265
- runtime: z
266
- .strictObject({
267
- entry: z.string(),
268
- target: z
269
- .enum([
270
- "bun-linux-x64",
271
- "bun-linux-arm64",
272
- "bun-darwin-x64",
273
- "bun-darwin-arm64",
274
- "bun-windows-x64",
275
- ])
276
- .optional(),
277
- })
278
- .optional(),
279
- })
280
- .optional(),
281
- compiler: z
282
- .strictObject({
283
- tsconfig: z.string().default("tsconfig.json"),
284
- programs: z.record(z.string(), z.strictObject({ module: z.string(), export: z.string() })),
285
- })
286
- .optional(),
287
- tasks: z.array(taskSchema).nonempty().optional(),
288
- // Keep an authored legacy task distinguishable from resolveConfig's default.
289
- // An explicit shared schedule must have a single owner.
290
- build: configSchema.extend({ task: configSchema.shape.task.unwrap().optional() }).optional(),
291
- codesys: z
292
- .strictObject({
293
- http: httpOptionsSchema.optional(),
294
- programNames: z.record(z.string(), z.string()).optional(),
295
- // Generate an EtherNet/IP scanner with one adapter per entry in devices.
296
- deviceTree: z.strictObject({ ethernet: ethernetSchema.optional() }).optional(),
297
- // Each omitted controller keeps the template's device. See controllerFor.
298
- controllers: z
299
- .strictObject({
300
- production: controllerTargetSchema.optional(),
301
- development: controllerTargetSchema.optional(),
302
- })
303
- .optional(),
304
- })
305
- .optional(),
306
- eds: z.union([z.string(), z.array(z.string())]).default("eds"),
307
- devices: z.record(z.string(), hardwareDeviceSchema).default({}),
308
- io: z.record(z.string(), ioBindingSchema).default({}),
309
- dependencies: z.record(z.string(), dependencySchema).default({}),
310
- // Raw ST builds opt into PLC contract generation by configuring this section.
311
- typegen: typegenSchema.optional(),
312
- monitor: monitorSchema.optional(),
313
- hmi: hmiSchema.optional(),
314
- telemetry: telemetrySchema.optional(),
315
- debug: debugSchema.optional(),
267
+ name: z.string().default("Application"),
268
+ backend: z.literal("codesys"),
269
+ publish: publicationSchema.optional(),
270
+ server: z
271
+ .strictObject({
272
+ baseUrlEnv: z.string().optional(),
273
+ transport: z.enum(["http", "opcua"]).default("http"),
274
+ runtime: z
275
+ .strictObject({
276
+ entry: z.string(),
277
+ target: z
278
+ .enum([
279
+ "bun-linux-x64",
280
+ "bun-linux-arm64",
281
+ "bun-darwin-x64",
282
+ "bun-darwin-arm64",
283
+ "bun-windows-x64",
284
+ ])
285
+ .optional(),
286
+ })
287
+ .optional(),
288
+ })
289
+ .optional(),
290
+ compiler: z
291
+ .strictObject({
292
+ tsconfig: z.string().default("tsconfig.json"),
293
+ programs: z.record(
294
+ z.string(),
295
+ z.strictObject({ module: z.string(), export: z.string() }),
296
+ ),
297
+ })
298
+ .optional(),
299
+ tasks: z.array(codesysTaskSchema).nonempty().optional(),
300
+ // Keep an authored legacy task distinguishable from resolveConfig's default.
301
+ // An explicit shared schedule must have a single owner.
302
+ build: configSchema
303
+ .extend({ task: configSchema.shape.task.unwrap().optional() })
304
+ .optional(),
305
+ codesys: z
306
+ .strictObject({
307
+ http: httpOptionsSchema.optional(),
308
+ programNames: z.record(z.string(), z.string()).optional(),
309
+ // Generate an EtherNet/IP scanner with one adapter per entry in devices.
310
+ deviceTree: z
311
+ .strictObject({ ethernet: ethernetSchema.optional() })
312
+ .optional(),
313
+ // Each omitted controller keeps the template's device. See controllerFor.
314
+ controllers: z
315
+ .strictObject({
316
+ production: controllerTargetSchema.optional(),
317
+ development: controllerTargetSchema.optional(),
318
+ })
319
+ .optional(),
320
+ })
321
+ .optional(),
322
+ eds: z.union([z.string(), z.array(z.string())]).default("eds"),
323
+ devices: z.record(z.string(), hardwareDeviceSchema).default({}),
324
+ io: z.record(z.string(), ioBindingSchema).default({}),
325
+ dependencies: z.record(z.string(), dependencySchema).default({}),
326
+ // Raw ST builds opt into PLC contract generation by configuring this section.
327
+ typegen: typegenSchema.optional(),
328
+ monitor: monitorSchema.optional(),
329
+ hmi: hmiSchema.optional(),
330
+ telemetry: telemetrySchema.optional(),
331
+ debug: debugSchema.optional(),
332
+ /** Where the program runs, each with literal values for environment variables, which win over the environment. */
333
+ targets: z
334
+ .record(
335
+ z.string().nonempty(),
336
+ z.strictObject({ values: z.record(envName, z.string()) }),
337
+ )
338
+ .default({}),
339
+ /** Variables a release for the plant agent leaves to it, which reads them from Bun.secrets on its own PC. */
340
+ secrets: z
341
+ .strictObject({
342
+ service: z.string().nonempty(),
343
+ names: z.array(envName).nonempty(),
344
+ })
345
+ .optional(),
316
346
  });
317
347
  export type TsplcConfig = z.input<typeof tsplcConfigSchema>;
318
348
  export type ResolvedTsplcConfig = z.output<typeof tsplcConfigSchema>;
@@ -320,102 +350,145 @@ export type HardwareDevice = z.infer<typeof hardwareDeviceSchema>;
320
350
  export type ResolvedTelemetryConfig = z.output<typeof telemetrySchema>;
321
351
  export type ResolvedDebugConfig = z.output<typeof debugSchema>;
322
352
  export type LibraryDependency = z.infer<typeof dependencySchema>;
353
+ /** A binding resolved to its process-image address, as `compilerConfig` receives it. */
354
+ type DirectIoBinding = z.infer<typeof directIoBindingSchema>;
323
355
 
324
356
  /**
325
357
  * `build` compiles for the production controller. `run` and controller
326
358
  * operations target the local runtime, so they compile for the development one.
327
359
  */
328
360
  export const buildTargetFor = (command: string): BuildTarget =>
329
- ["run", "download", "online-change", "inspect"].includes(command) ? "development" : "production";
361
+ ["run", "download", "online-change", "inspect"].includes(command)
362
+ ? "development"
363
+ : "production";
330
364
  export const controllerFor = (config: ResolvedTsplcConfig, command: string) => {
331
- const controller = config.codesys?.controllers?.[buildTargetFor(command)];
332
- return controller && { ...controllerDevices[controller.target], version: controller.version };
365
+ const controller = config.codesys?.controllers?.[buildTargetFor(command)];
366
+ return (
367
+ controller && {
368
+ ...controllerDevices[controller.target],
369
+ version: controller.version,
370
+ }
371
+ );
333
372
  };
334
373
 
374
+ /**
375
+ * The variable holding the bearer token the PLC sends the project's own server: the HTTP
376
+ * credential for the server's base URL.
377
+ */
378
+ export const serverTokenEnv = (config: ResolvedTsplcConfig) =>
379
+ config.codesys?.http?.credentials.find(
380
+ ({ originEnv }) => originEnv === config.server?.baseUrlEnv,
381
+ )?.bearerTokenEnv;
382
+
335
383
  /**
336
384
  * The project without fieldbus I/O, for a plant simulator that writes inputs over
337
385
  * OPC UA: fieldbus input copies would overwrite those writes every scan.
338
386
  */
339
- export const simulationConfig = (config: ResolvedTsplcConfig): ResolvedTsplcConfig => ({
340
- ...config,
341
- eds: [],
342
- devices: {},
343
- io: {},
344
- ...(config.codesys && {
345
- codesys: {
346
- ...config.codesys,
347
- deviceTree: undefined,
348
- },
349
- }),
387
+ export const simulationConfig = (
388
+ config: ResolvedTsplcConfig,
389
+ ): ResolvedTsplcConfig => ({
390
+ ...config,
391
+ eds: [],
392
+ devices: {},
393
+ io: {},
394
+ ...(config.codesys && {
395
+ codesys: {
396
+ ...config.codesys,
397
+ deviceTree: undefined,
398
+ },
399
+ }),
350
400
  });
351
401
 
352
402
  /** All paths are relative to this file; no package has a second project config. */
353
403
  export function defineConfig<const C extends TsplcConfig>(config: C): C {
354
- return config;
404
+ return config;
355
405
  }
356
406
 
357
407
  /** Raw ST program names already are IEC names; use the shared schedule directly. */
358
- export function rawBuildConfig(config: ResolvedTsplcConfig): CodesysBuildConfig {
359
- if (config.compiler) throw new Error("Use the compiler build plan for TypeScript projects.");
360
- if (!config.build) throw new Error("Configure build settings.");
361
- if (!config.tasks) return config.build;
362
- if (config.build.tasks || config.build.task !== undefined)
363
- throw new Error("Configure the raw ST schedule in tasks or build.tasks/build.task, not both.");
364
- return {
365
- ...config.build,
366
- tasks: cyclicTasksSchema.parse(
367
- config.tasks.map((task) => ({
368
- name: task.name,
369
- intervalNanoseconds: task.schedule.interval.nanoseconds,
370
- priority: task.priority,
371
- programs: task.programs,
372
- })),
373
- ),
374
- };
408
+ export function rawBuildConfig(
409
+ config: ResolvedTsplcConfig,
410
+ ): CodesysBuildConfig {
411
+ if (config.compiler) {
412
+ throw new Error("Use the compiler build plan for TypeScript projects.");
413
+ }
414
+ if (!config.build) {
415
+ throw new Error("Configure build settings.");
416
+ }
417
+ if (!config.tasks) {
418
+ return config.build;
419
+ }
420
+ if (config.build.tasks || config.build.task !== undefined) {
421
+ throw new Error(
422
+ "Configure the raw ST schedule in tasks or build.tasks/build.task, not both.",
423
+ );
424
+ }
425
+ return {
426
+ ...config.build,
427
+ tasks: cyclicTasksSchema.parse(
428
+ config.tasks.map((task) => ({
429
+ name: task.name,
430
+ intervalNanoseconds: task.schedule.interval.nanoseconds,
431
+ priority: task.priority,
432
+ programs: task.programs,
433
+ })),
434
+ ),
435
+ };
375
436
  }
376
437
 
377
438
  /** Adapt the shared project to the compiler's backend-independent scan model. */
378
439
  export function compilerConfig(
379
- config: ResolvedTsplcConfig,
380
- io: Record<string, { address: string; type?: string }>,
381
- buildTarget: BuildTarget = "production",
440
+ config: ResolvedTsplcConfig,
441
+ io: Record<string, DirectIoBinding>,
442
+ buildTarget: BuildTarget = "production",
382
443
  ) {
383
- if (!config.compiler || !config.tasks)
384
- throw new Error("This project uses raw Structured Text; no TypeScript compiler is configured.");
385
- // The device tree and controllers are build-time engineering; the compiler only sees addresses.
386
- const { deviceTree: _deviceTree, controllers: _controllers, ...codesys } = config.codesys ?? {};
387
- const value: PlcConfig = {
388
- name: config.name,
389
- tsconfig: config.compiler.tsconfig,
390
- programs: config.compiler.programs,
391
- tasks: config.tasks,
392
- target: {
393
- kind: config.backend,
394
- options: {
395
- ...codesys,
396
- publish: config.publish,
397
- buildTarget,
398
- io: Object.fromEntries(
399
- Object.entries(io).map(([name, binding]) => [
400
- name,
401
- {
402
- kind: "direct",
403
- ...binding,
404
- ...(mappedChannel(config, name, binding) && { mapped: true }),
405
- },
406
- ]),
407
- ),
408
- engineering: {
409
- kind: "v3.5",
410
- ...(config.build ? { build: compilerBuildOptions(config.build) } : {}),
411
- },
412
- },
413
- },
414
- };
415
- const validated = validateCompilerConfig(value);
416
- if (!validated.config)
417
- throw new Error(validated.diagnostics.map((item) => item.message).join("\n"));
418
- return validated.config;
444
+ if (!config.compiler || !config.tasks) {
445
+ throw new Error(
446
+ "This project uses raw Structured Text; no TypeScript compiler is configured.",
447
+ );
448
+ }
449
+ // The device tree and controllers are build-time engineering; the compiler only sees addresses.
450
+ const {
451
+ deviceTree: _deviceTree,
452
+ controllers: _controllers,
453
+ ...codesys
454
+ } = config.codesys ?? {};
455
+ const value: PlcConfig = {
456
+ name: config.name,
457
+ tsconfig: config.compiler.tsconfig,
458
+ programs: config.compiler.programs,
459
+ tasks: config.tasks,
460
+ target: {
461
+ kind: config.backend,
462
+ options: {
463
+ ...codesys,
464
+ publish: config.publish,
465
+ buildTarget,
466
+ io: Object.fromEntries(
467
+ Object.entries(io).map(([name, binding]) => [
468
+ name,
469
+ {
470
+ kind: "direct",
471
+ ...binding,
472
+ ...(mappedChannel(config, name, binding) && { mapped: true }),
473
+ },
474
+ ]),
475
+ ),
476
+ engineering: {
477
+ kind: "v3.5",
478
+ ...(config.build
479
+ ? { build: compilerBuildOptions(config.build) }
480
+ : {}),
481
+ },
482
+ },
483
+ },
484
+ };
485
+ const validated = validateCompilerConfig(value);
486
+ if (!validated.config) {
487
+ throw new Error(
488
+ validated.diagnostics.map((item) => item.message).join("\n"),
489
+ );
490
+ }
491
+ return validated.config;
419
492
  }
420
493
 
421
494
  /**
@@ -423,31 +496,31 @@ export function compilerConfig(
423
496
  * I/O mapping. Wider values span several byte channels and keep an AT declaration.
424
497
  */
425
498
  function mappedChannel(
426
- config: ResolvedTsplcConfig,
427
- name: string,
428
- binding: { address: string; type?: string; inverted?: boolean; shared?: boolean },
499
+ config: ResolvedTsplcConfig,
500
+ name: string,
501
+ binding: DirectIoBinding,
429
502
  ) {
430
- const source = config.io[name];
431
- return (
432
- config.codesys?.deviceTree !== undefined &&
433
- source !== undefined &&
434
- "device" in source &&
435
- // A channel maps to one variable as it stands, so these need an AT wire and a copy.
436
- !binding.inverted &&
437
- !binding.shared &&
438
- /^%[IQ][XB]/.test(binding.address) &&
439
- !/^ARRAY/i.test(binding.type ?? "")
440
- );
503
+ const source = config.io[name];
504
+ return (
505
+ config.codesys?.deviceTree !== undefined &&
506
+ source !== undefined &&
507
+ "device" in source &&
508
+ // A channel maps to one variable as it stands, so these need an AT wire and a copy.
509
+ !binding.inverted &&
510
+ !binding.shared &&
511
+ /^%[IQ][XB]/.test(binding.address) &&
512
+ !/^ARRAY/i.test(binding.type ?? "")
513
+ );
441
514
  }
442
515
 
443
516
  function compilerBuildOptions(build: CodesysBuildConfig) {
444
- const {
445
- sourceDir: _source,
446
- entry: _entry,
447
- outDir: _out,
448
- task: _task,
449
- tasks: _tasks,
450
- ...settings
451
- } = build;
452
- return settings;
517
+ const {
518
+ sourceDir: _source,
519
+ entry: _entry,
520
+ outDir: _out,
521
+ task: _task,
522
+ tasks: _tasks,
523
+ ...settings
524
+ } = build;
525
+ return settings;
453
526
  }