@tsplc/config 0.5.14 → 0.5.16

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
@@ -2,11 +2,12 @@ import { z } from "zod";
2
2
  import {
3
3
  assemblyAddress,
4
4
  type CodesysBuildConfig,
5
+ channelAddress,
5
6
  configSchema,
6
- controllerDeviceNames,
7
- controllerDevices,
8
7
  controllerTargetSchema,
8
+ controllerTargets,
9
9
  cyclicTasksSchema,
10
+ type DirectIoBinding,
10
11
  directIoBindingSchema,
11
12
  engineeringBuildOptions,
12
13
  envName,
@@ -20,9 +21,11 @@ import {
20
21
  import {
21
22
  durationSchema,
22
23
  type PlcConfig,
24
+ sourceExportSchema,
23
25
  taskSchema,
24
26
  validateConfig as validateCompilerConfig,
25
27
  } from "./compiler";
28
+ import type { Environment } from "./environment";
26
29
  import { generatedDirectory } from "./project-files";
27
30
 
28
31
  export type {
@@ -44,6 +47,7 @@ export {
44
47
  type TaskConfig,
45
48
  validateConfig,
46
49
  } from "./compiler";
50
+ export { ioSymbolsSchema } from "./project-files";
47
51
 
48
52
  export const httpOptionsSchema = z
49
53
  .strictObject({
@@ -63,8 +67,8 @@ export type HttpOptions = z.infer<typeof httpOptionsSchema>;
63
67
  const ioBindingSchema = z.union([
64
68
  directIoBindingSchema,
65
69
  z.strictObject({
66
- device: z.string().min(1),
67
- channel: z.string().min(1),
70
+ device: z.string().nonempty(),
71
+ channel: z.string().nonempty(),
68
72
  ...ioBindingOptions,
69
73
  }),
70
74
  ]);
@@ -76,8 +80,8 @@ const assemblySchema = z.strictObject({
76
80
  address: assemblyAddress.optional(),
77
81
  });
78
82
  const hardwareDeviceSchema = z.strictObject({
79
- file: z.string().min(1),
80
- connection: z.string().min(1).optional(),
83
+ file: z.string().nonempty(),
84
+ connection: z.string().nonempty().optional(),
81
85
  inputs: assemblySchema.optional(),
82
86
  outputs: assemblySchema.optional(),
83
87
  // Registers the generated device tree writes over Modbus TCP, at network.address.
@@ -109,7 +113,10 @@ const dependencySchema = z.union([
109
113
  company: z.string().optional(),
110
114
  namespace: z.string().optional(),
111
115
  }),
112
- z.strictObject({ path: z.string().min(1), namespace: z.string().optional() }),
116
+ z.strictObject({
117
+ path: z.string().nonempty(),
118
+ namespace: z.string().optional(),
119
+ }),
113
120
  ]);
114
121
  // `backend` is always CODESYS, so tasks get its name and priority rules here, as raw ST schedules do in cyclicTasksSchema.
115
122
  const codesysTaskSchema = taskSchema.extend({
@@ -120,16 +127,16 @@ const monitorSchema = z
120
127
  .strictObject({
121
128
  endpoint: z.string().url(),
122
129
  namespaceUri: z.string().optional(),
123
- symbols: z.array(z.string().min(1)).optional(),
130
+ symbols: z.array(z.string().nonempty()).optional(),
124
131
  securityMode: z
125
132
  .enum(["None", "Sign", "SignAndEncrypt"])
126
133
  .default("SignAndEncrypt"),
127
134
  securityPolicy: z.enum(["None", "Basic256Sha256"]).optional(),
128
135
  certificateDirectory: z
129
136
  .string()
130
- .min(1)
137
+ .nonempty()
131
138
  .default(`${generatedDirectory}/opcua-pki`),
132
- username: z.string().min(1).optional(),
139
+ username: z.string().nonempty().optional(),
133
140
  passwordEnv: envName.optional(),
134
141
  })
135
142
  .superRefine((monitor, context) => {
@@ -168,7 +175,7 @@ const monitorSchema = z
168
175
  : ("Basic256Sha256" as const)),
169
176
  }));
170
177
  /**
171
- * The records each PLC task keeps for its sender (docs/language/telemetry.md): used whenever the
178
+ * The records each PLC task keeps for its sender (docs/03-guides/telemetry.md): used whenever the
172
179
  * program calls `@tsplc/compiler/telemetry`, records unhandled job failures or traces for the debugger.
173
180
  */
174
181
  export const telemetrySchema = z.strictObject({
@@ -182,7 +189,7 @@ export const telemetrySchema = z.strictObject({
182
189
  recordBytes: z.number().int().min(128).max(1024).default(512),
183
190
  });
184
191
  /**
185
- * The debugger's fixed-size instrumentation (docs/design/debugging.md). It reads state through
192
+ * The debugger's fixed-size instrumentation (docs/03-guides/debugging.md). It reads state through
186
193
  * the engineering login, so it publishes nothing. Without it a build only carries its build id.
187
194
  */
188
195
  const debugSchema = z.strictObject({
@@ -208,7 +215,7 @@ const debugSchema = z.strictObject({
208
215
  .default(true),
209
216
  jobs: z.boolean().default(true),
210
217
  /** Watch groups the debugger opens with: TypeScript paths, `*` matching one path segment. */
211
- watch: z.record(z.string(), z.array(z.string().min(1))).default({}),
218
+ watch: z.record(z.string(), z.array(z.string().nonempty())).default({}),
212
219
  requests: z
213
220
  .strictObject({
214
221
  capacity: z.number().int().min(1).max(100_000).default(1000),
@@ -233,9 +240,7 @@ export const publicationSchema = z.strictObject({
233
240
  production: z.array(z.string().nonempty()),
234
241
  development: z.array(z.string().nonempty()),
235
242
  });
236
- export type Publication = Readonly<Record<BuildTarget, readonly string[]>>;
237
- /** Each IO binding's name with the published symbol path the compiler gave it. */
238
- export const ioSymbolsSchema = z.record(z.string(), z.string());
243
+ export type Publication = z.infer<typeof publicationSchema>;
239
244
  /** A published PLC variable, as `Global.Field`. */
240
245
  const hmiTarget = z.string().regex(/^\w+(\.\w+|\[\d+\])+$/);
241
246
  /**
@@ -304,101 +309,107 @@ export const hmiSchema = z.strictObject({
304
309
  export type HmiConfig = z.input<typeof hmiSchema>;
305
310
  export type ResolvedHmiConfig = z.output<typeof hmiSchema>;
306
311
 
307
- export const tsplcConfigSchema = z.strictObject({
308
- name: z.string().default("Application"),
309
- backend: z.literal("codesys"),
310
- publish: publicationSchema.optional(),
311
- server: z
312
- .strictObject({
313
- baseUrlEnv: z.string().optional(),
314
- transport: z.enum(["http", "opcua"]).default("http"),
315
- runtime: z
316
- .strictObject({
317
- entry: z.string(),
318
- target: z
319
- .enum([
320
- "bun-linux-x64",
321
- "bun-linux-arm64",
322
- "bun-darwin-x64",
323
- "bun-darwin-arm64",
324
- "bun-windows-x64",
325
- ])
326
- .optional(),
327
- })
328
- .optional(),
329
- })
330
- .optional(),
331
- compiler: z
332
- .strictObject({
333
- tsconfig: z.string().default("tsconfig.json"),
334
- programs: z.record(
335
- z.string(),
336
- z.strictObject({ module: z.string(), export: z.string() }),
337
- ),
338
- })
339
- .optional(),
340
- tasks: z.array(codesysTaskSchema).nonempty().optional(),
341
- // Keep an authored legacy task distinguishable from resolveConfig's default.
342
- // An explicit shared schedule must have a single owner.
343
- build: configSchema
344
- .extend({ task: configSchema.shape.task.unwrap().optional() })
345
- .optional(),
346
- codesys: z
347
- .strictObject({
348
- http: httpOptionsSchema.optional(),
349
- programNames: z.record(z.string(), z.string()).optional(),
350
- // Generate an EtherNet/IP scanner with one adapter per entry in devices.
351
- deviceTree: z
352
- .strictObject({ ethernet: ethernetSchema.optional() })
353
- .optional(),
354
- // Each omitted controller keeps the template's device. See controllerFor.
355
- controllers: z
356
- .strictObject({
357
- production: controllerTargetSchema.optional(),
358
- development: controllerTargetSchema.optional(),
359
- })
360
- .optional(),
361
- })
362
- .optional(),
363
- eds: z.union([z.string(), z.array(z.string())]).default("eds"),
364
- devices: z.record(z.string(), hardwareDeviceSchema).default({}),
365
- io: z.record(z.string(), ioBindingSchema).default({}),
366
- dependencies: z.record(z.string(), dependencySchema).default({}),
367
- // Raw ST builds opt into PLC contract generation by configuring this section.
368
- typegen: typegenSchema.optional(),
369
- monitor: monitorSchema.optional(),
370
- hmi: hmiSchema.optional(),
371
- telemetry: telemetrySchema.optional(),
372
- debug: debugSchema.optional(),
373
- /**
374
- * Where the program runs, each with literal values for environment variables, which win over the
375
- * environment, and the plant agent that deploys to it.
376
- */
377
- targets: z
378
- .record(
379
- z.string().nonempty(),
380
- z.strictObject({
381
- values: z.record(envName, z.string()).default({}),
382
- agent: z.strictObject({ url: z.url() }).optional(),
383
- }),
384
- )
385
- .default({}),
386
- /** Variables a release for the plant agent leaves to it, which reads them from Bun.secrets on its own PC. */
387
- secrets: z
388
- .strictObject({
389
- service: z.string().nonempty(),
390
- names: z.array(envName).nonempty(),
391
- })
392
- .optional(),
393
- });
312
+ export const tsplcConfigSchema = z
313
+ .strictObject({
314
+ name: z.string().default("Application"),
315
+ backend: z.literal("codesys"),
316
+ publish: publicationSchema.optional(),
317
+ server: z
318
+ .strictObject({
319
+ baseUrlEnv: envName.optional(),
320
+ transport: z.enum(["http", "opcua"]).default("http"),
321
+ runtime: z
322
+ .strictObject({
323
+ entry: z.string(),
324
+ target: z
325
+ .enum([
326
+ "bun-linux-x64",
327
+ "bun-linux-arm64",
328
+ "bun-darwin-x64",
329
+ "bun-darwin-arm64",
330
+ "bun-windows-x64",
331
+ ])
332
+ .optional(),
333
+ })
334
+ .optional(),
335
+ })
336
+ .optional(),
337
+ compiler: z
338
+ .strictObject({
339
+ tsconfig: z.string().default("tsconfig.json"),
340
+ programs: z.record(z.string(), sourceExportSchema),
341
+ })
342
+ .optional(),
343
+ tasks: z.array(codesysTaskSchema).nonempty().optional(),
344
+ // Keep an authored legacy task distinguishable from resolveConfig's default.
345
+ // An explicit shared schedule must have a single owner.
346
+ build: configSchema
347
+ .extend({ task: configSchema.shape.task.unwrap().optional() })
348
+ .optional(),
349
+ codesys: z
350
+ .strictObject({
351
+ http: httpOptionsSchema.optional(),
352
+ programNames: z.record(z.string(), z.string()).optional(),
353
+ // Generate an EtherNet/IP scanner with one adapter per entry in devices.
354
+ deviceTree: z
355
+ .strictObject({ ethernet: ethernetSchema.optional() })
356
+ .optional(),
357
+ // Each omitted controller keeps the template's device. See controllerFor.
358
+ controllers: z
359
+ .strictObject({
360
+ production: controllerTargetSchema.optional(),
361
+ development: controllerTargetSchema.optional(),
362
+ })
363
+ .optional(),
364
+ })
365
+ .optional(),
366
+ eds: z.union([z.string(), z.array(z.string())]).default("eds"),
367
+ devices: z.record(z.string(), hardwareDeviceSchema).default({}),
368
+ io: z.record(z.string(), ioBindingSchema).default({}),
369
+ dependencies: z.record(z.string(), dependencySchema).default({}),
370
+ // Raw ST builds opt into PLC contract generation by configuring this section.
371
+ typegen: typegenSchema.optional(),
372
+ monitor: monitorSchema.optional(),
373
+ hmi: hmiSchema.optional(),
374
+ telemetry: telemetrySchema.optional(),
375
+ debug: debugSchema.optional(),
376
+ /**
377
+ * Where the program runs, each with literal values for environment variables, which win over the
378
+ * environment, and the plant agent that deploys to it.
379
+ */
380
+ targets: z
381
+ .record(
382
+ z.string().nonempty(),
383
+ z.strictObject({
384
+ values: z.record(envName, z.string()).default({}),
385
+ agent: z.strictObject({ url: z.url() }).optional(),
386
+ }),
387
+ )
388
+ .default({}),
389
+ /** Variables a release for the plant agent leaves to it, which reads them from Bun.secrets on its own PC. */
390
+ secrets: z
391
+ .strictObject({
392
+ service: z.string().nonempty(),
393
+ names: z.array(envName).nonempty(),
394
+ })
395
+ .optional(),
396
+ })
397
+ .superRefine((config, context) => {
398
+ if (config.compiler && !config.tasks) {
399
+ context.addIssue({
400
+ code: "custom",
401
+ path: ["tasks"],
402
+ message: "TypeScript programs require a tasks configuration.",
403
+ });
404
+ }
405
+ });
394
406
  export type TsplcConfig = z.input<typeof tsplcConfigSchema>;
395
407
  export type ResolvedTsplcConfig = z.output<typeof tsplcConfigSchema>;
408
+ export type ServerConfig = NonNullable<ResolvedTsplcConfig["server"]>;
396
409
  export type HardwareDevice = z.infer<typeof hardwareDeviceSchema>;
397
410
  export type ResolvedTelemetryConfig = z.output<typeof telemetrySchema>;
398
411
  export type ResolvedDebugConfig = z.output<typeof debugSchema>;
399
412
  export type LibraryDependency = z.infer<typeof dependencySchema>;
400
- /** A binding resolved to its process-image address, as `compilerConfig` receives it. */
401
- type DirectIoBinding = z.infer<typeof directIoBindingSchema>;
402
413
 
403
414
  /**
404
415
  * `build` compiles for the production controller. `run` and controller
@@ -412,7 +423,7 @@ export const controllerFor = (config: ResolvedTsplcConfig, command: string) => {
412
423
  const controller = config.codesys?.controllers?.[buildTargetFor(command)];
413
424
  return (
414
425
  controller && {
415
- ...controllerDevices[controller.target],
426
+ ...controllerTargets[controller.target].device,
416
427
  version: controller.version,
417
428
  }
418
429
  );
@@ -423,9 +434,9 @@ export const controllerDeviceName = (
423
434
  config: ResolvedTsplcConfig,
424
435
  command: string,
425
436
  ) =>
426
- controllerDeviceNames[
437
+ controllerTargets[
427
438
  config.codesys?.controllers?.[buildTargetFor(command)]?.target ?? "linux-sl"
428
- ];
439
+ ].deviceName;
429
440
 
430
441
  /**
431
442
  * The variable holding the bearer token the PLC sends the project's own server: the HTTP
@@ -436,6 +447,37 @@ export const serverTokenEnv = (config: ResolvedTsplcConfig) =>
436
447
  ({ originEnv }) => originEnv === config.server?.baseUrlEnv,
437
448
  )?.bearerTokenEnv;
438
449
 
450
+ /** The project's server's base URL as `env` holds it, before any normalisation. */
451
+ export const serverBaseUrl = (
452
+ config: { server?: Pick<ServerConfig, "baseUrlEnv"> },
453
+ env: Environment,
454
+ ) =>
455
+ config.server?.baseUrlEnv === undefined
456
+ ? undefined
457
+ : env[config.server.baseUrlEnv];
458
+
459
+ /** Typegen's settings, with their defaults when the config has no `typegen` section. */
460
+ export const typegenSettings = (config: ResolvedTsplcConfig) =>
461
+ config.typegen ?? typegenSchema.parse({});
462
+
463
+ /**
464
+ * The project's name as a slug: `kebab` splits acronyms (`PLCDemo` is `plc-demo`), `runtime` is
465
+ * the Docker Compose project name (`PLCDemo` is `plcdemo`).
466
+ */
467
+ export const projectSlugs = {
468
+ kebab: (name: string) =>
469
+ name
470
+ .replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, "$1$3-$2$4")
471
+ .replace(/[^A-Za-z0-9]+/g, "-")
472
+ .replace(/^-|-$/g, "")
473
+ .toLowerCase(),
474
+ runtime: (name: string) =>
475
+ name
476
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
477
+ .toLowerCase()
478
+ .replace(/[^a-z0-9_-]+/g, "-"),
479
+ };
480
+
439
481
  /**
440
482
  * The project without fieldbus I/O, for a plant simulator that writes inputs over
441
483
  * OPC UA: fieldbus input copies would overwrite those writes every scan.
@@ -455,7 +497,7 @@ export const simulationConfig = (
455
497
  }),
456
498
  });
457
499
 
458
- /** All paths are relative to this file; no package has a second project config. */
500
+ /** All paths are relative to this file. */
459
501
  export function defineConfig<const C extends TsplcConfig>(config: C): C {
460
502
  return config;
461
503
  }
@@ -480,17 +522,19 @@ export function rawBuildConfig(
480
522
  }
481
523
  return {
482
524
  ...config.build,
483
- tasks: cyclicTasksSchema.parse(
484
- config.tasks.map((task) => ({
485
- name: task.name,
486
- intervalNanoseconds: task.schedule.interval.nanoseconds,
487
- priority: task.priority,
488
- programs: task.programs,
489
- })),
490
- ),
525
+ tasks: cyclicTasksSchema.parse(taskPlan(config.tasks)),
491
526
  };
492
527
  }
493
528
 
529
+ /** The project's tasks as the CODESYS schedule states them. */
530
+ export const taskPlan = (tasks: NonNullable<ResolvedTsplcConfig["tasks"]>) =>
531
+ tasks.map((task) => ({
532
+ name: task.name,
533
+ intervalNanoseconds: task.schedule.interval.nanoseconds,
534
+ priority: task.priority,
535
+ programs: task.programs,
536
+ }));
537
+
494
538
  /** Adapt the shared project to the compiler's backend-independent scan model. */
495
539
  export function compilerConfig(
496
540
  config: ResolvedTsplcConfig,
@@ -564,7 +608,7 @@ function mappedChannel(
564
608
  // A channel maps to one variable as it stands, so these need an AT wire and a copy.
565
609
  !binding.inverted &&
566
610
  !binding.shared &&
567
- /^%[IQ][XB]/.test(binding.address) &&
611
+ channelAddress.safeParse(binding.address).success &&
568
612
  !/^ARRAY/i.test(binding.type ?? "")
569
613
  );
570
614
  }