@tsplc/compiler 0.2.16 → 0.2.18

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 (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -1,425 +1,559 @@
1
1
  import { runtimeSources } from "./module-graph.ts";
2
+ import { namesSdk, symbolAt } from "./sdk.ts";
2
3
  import ts from "typescript";
3
4
  import { dirname, join, relative } from "node:path";
4
5
  import { error, type Diagnostic } from "@tsplc/compiler/ir";
5
- import { edited, from, mapped, type Edit, type Mapped, type Positions } from "./positions.ts";
6
6
  import {
7
- isIntegerType,
8
- serviceContract,
9
- servicePath,
10
- wireLayout,
11
- wireRecord,
12
- type ServiceContract,
13
- type WireField,
14
- type WireScalar,
7
+ edited,
8
+ from,
9
+ mapped,
10
+ type Edit,
11
+ type Mapped,
12
+ type Positions,
13
+ } from "./positions.ts";
14
+ import {
15
+ isIntegerType,
16
+ serviceContract,
17
+ servicePath,
18
+ wireLayout,
19
+ wireRecord,
20
+ type ServiceContract,
21
+ type WireField,
22
+ type WireScalar,
15
23
  } from "@tsplc/server";
16
24
 
17
25
  /** The server section's transport; each client's type argument names its router. */
18
26
  export interface ServiceOptions {
19
- transport: "http" | "opcua";
20
- baseUrlEnv?: string;
27
+ transport: "http" | "opcua";
28
+ baseUrlEnv?: string;
21
29
  }
22
30
 
23
31
  /** A procedure record read from its type, with the PLC enum each enum field names. */
24
32
  interface RecordLayout {
25
- fields: Record<string, WireField>;
26
- enums: Record<string, ts.EnumDeclaration>;
33
+ fields: Record<string, WireField>;
34
+ enums: Record<string, ts.EnumDeclaration>;
27
35
  }
28
36
 
29
37
  const property = (checker: ts.TypeChecker, type: ts.Type, name: string) => {
30
- const symbol = type.getProperty(name);
31
- return symbol && checker.getTypeOfSymbol(symbol);
38
+ const symbol = type.getProperty(name);
39
+ return symbol && checker.getTypeOfSymbol(symbol);
32
40
  };
33
41
 
34
42
  /** An `iec.*` schema's layout, which its type carries as an optional phantom property. */
35
- const layoutNumber = (checker: ts.TypeChecker, type: ts.Type, name: string, label: string) => {
36
- const brand = property(checker, type, wireLayout);
37
- const value = brand && property(checker, checker.getNonNullableType(brand), name);
38
- if (!value) return undefined;
39
- if (!value.isNumberLiteral()) throw new Error(`${label}: ${name} must be a literal number.`);
40
- return value.value;
43
+ const layoutNumber = (
44
+ checker: ts.TypeChecker,
45
+ type: ts.Type,
46
+ name: string,
47
+ label: string,
48
+ ) => {
49
+ const brand = property(checker, type, wireLayout);
50
+ const value =
51
+ brand && property(checker, checker.getNonNullableType(brand), name);
52
+ if (!value) {
53
+ return undefined;
54
+ }
55
+ if (!value.isNumberLiteral()) {
56
+ throw new Error(`${label}: ${name} must be a literal number.`);
57
+ }
58
+ return value.value;
41
59
  };
42
60
 
43
61
  const scalarLayout = (
44
- checker: ts.TypeChecker,
45
- type: ts.Type,
46
- label: string,
62
+ checker: ts.TypeChecker,
63
+ type: ts.Type,
64
+ label: string,
47
65
  ): { field: WireScalar; enumeration?: ts.EnumDeclaration } => {
48
- if (type.flags & ts.TypeFlags.Boolean) return { field: { kind: "boolean" } };
49
- // An enum type is the union of its member literals.
50
- const first = type.isUnion() ? type.types[0] : type;
51
- const member = first?.symbol?.valueDeclaration;
52
- if (first && first.flags & ts.TypeFlags.EnumLiteral && member && ts.isEnumMember(member)) {
53
- const members: Record<string, number> = {};
54
- for (const item of member.parent.members) {
55
- const value = checker.getConstantValue(item);
56
- if (typeof value !== "number")
57
- throw new Error(`${label}: PLC enums require numeric members.`);
58
- members[item.name.getText()] = value;
59
- }
60
- return { field: { kind: "enum", members }, enumeration: member.parent };
61
- }
62
- const capacity = layoutNumber(checker, type, "capacity", label);
63
- if (capacity !== undefined) return { field: { kind: "string", capacity } };
64
- const brand = property(checker, type, wireLayout);
65
- const iec = brand && property(checker, checker.getNonNullableType(brand), "iec");
66
- if (iec?.isStringLiteral() && isIntegerType(iec.value)) {
67
- const minimum = layoutNumber(checker, type, "minimum", label);
68
- const maximum = layoutNumber(checker, type, "maximum", label);
69
- if (minimum !== undefined && maximum !== undefined)
70
- return { field: { kind: "integer", iec: iec.value, minimum, maximum } };
71
- }
72
- throw new Error(
73
- `${label}: use z.boolean(), z.enum() of a numeric enum, iec.STRING(), or an integer such as iec.INT().`,
74
- );
66
+ if (type.flags & ts.TypeFlags.Boolean) {
67
+ return { field: { kind: "boolean" } };
68
+ }
69
+ // An enum type is the union of its member literals.
70
+ const first = type.isUnion() ? type.types[0] : type;
71
+ const member = first?.symbol?.valueDeclaration;
72
+ if (
73
+ first &&
74
+ first.flags & ts.TypeFlags.EnumLiteral &&
75
+ member &&
76
+ ts.isEnumMember(member)
77
+ ) {
78
+ const members: Record<string, number> = {};
79
+ for (const item of member.parent.members) {
80
+ const value = checker.getConstantValue(item);
81
+ if (typeof value !== "number") {
82
+ throw new Error(`${label}: PLC enums require numeric members.`);
83
+ }
84
+ members[item.name.getText()] = value;
85
+ }
86
+ return { field: { kind: "enum", members }, enumeration: member.parent };
87
+ }
88
+ const capacity = layoutNumber(checker, type, "capacity", label);
89
+ if (capacity !== undefined) {
90
+ return { field: { kind: "string", capacity } };
91
+ }
92
+ const brand = property(checker, type, wireLayout);
93
+ const iec =
94
+ brand && property(checker, checker.getNonNullableType(brand), "iec");
95
+ if (iec?.isStringLiteral() && isIntegerType(iec.value)) {
96
+ const minimum = layoutNumber(checker, type, "minimum", label);
97
+ const maximum = layoutNumber(checker, type, "maximum", label);
98
+ if (minimum !== undefined && maximum !== undefined) {
99
+ return { field: { kind: "integer", iec: iec.value, minimum, maximum } };
100
+ }
101
+ }
102
+ throw new Error(
103
+ `${label}: use z.boolean(), z.enum() of a numeric enum, iec.STRING(), or an integer such as iec.INT().`,
104
+ );
75
105
  };
76
106
 
77
107
  const recordLayout = (
78
- checker: ts.TypeChecker,
79
- type: ts.Type,
80
- label: string,
81
- output: boolean,
108
+ checker: ts.TypeChecker,
109
+ type: ts.Type,
110
+ label: string,
111
+ output: boolean,
82
112
  ): RecordLayout => {
83
- const fields: Record<string, WireField> = {};
84
- const enums: Record<string, ts.EnumDeclaration> = {};
85
- // A procedure without `.input()` takes `void`.
86
- if (!(type.flags & ts.TypeFlags.Void)) {
87
- if (
88
- !(type.flags & ts.TypeFlags.Object) ||
89
- type.getStringIndexType() ||
90
- type.getNumberIndexType() ||
91
- type.getCallSignatures().length
92
- )
93
- throw new Error(`${label}: PLC procedures exchange one closed z.strictObject() record.`);
94
- for (const field of type.getProperties()) {
95
- const key = `${label}.${field.name}`;
96
- if (field.flags & ts.SymbolFlags.Optional)
97
- throw new Error(`${key}: optional wire fields are unsupported.`);
98
- const value = checker.getTypeOfSymbol(field);
99
- const length = layoutNumber(checker, value, "length", key);
100
- const element = length === undefined ? undefined : value.getNumberIndexType();
101
- const scalar = scalarLayout(checker, element ?? value, key);
102
- fields[field.name] =
103
- length === undefined ? scalar.field : { kind: "array", length, element: scalar.field };
104
- if (scalar.enumeration) enums[field.name] = scalar.enumeration;
105
- }
106
- }
107
- return { fields: wireRecord(fields, label, output).fields, enums };
113
+ const fields: Record<string, WireField> = {};
114
+ const enums: Record<string, ts.EnumDeclaration> = {};
115
+ // A procedure without `.input()` takes `void`.
116
+ if (!(type.flags & ts.TypeFlags.Void)) {
117
+ if (
118
+ !(type.flags & ts.TypeFlags.Object) ||
119
+ type.getStringIndexType() ||
120
+ type.getNumberIndexType() ||
121
+ type.getCallSignatures().length
122
+ ) {
123
+ throw new Error(
124
+ `${label}: PLC procedures exchange one closed z.strictObject() record.`,
125
+ );
126
+ }
127
+ for (const field of type.getProperties()) {
128
+ const key = `${label}.${field.name}`;
129
+ if (field.flags & ts.SymbolFlags.Optional) {
130
+ throw new Error(`${key}: optional wire fields are unsupported.`);
131
+ }
132
+ const value = checker.getTypeOfSymbol(field);
133
+ const length = layoutNumber(checker, value, "length", key);
134
+ const element =
135
+ length === undefined ? undefined : value.getNumberIndexType();
136
+ const scalar = scalarLayout(checker, element ?? value, key);
137
+ fields[field.name] =
138
+ length === undefined
139
+ ? scalar.field
140
+ : { kind: "array", length, element: scalar.field };
141
+ if (scalar.enumeration) {
142
+ enums[field.name] = scalar.enumeration;
143
+ }
144
+ }
145
+ }
146
+ return { fields: wireRecord(fields, label, output).fields, enums };
108
147
  };
109
148
 
110
149
  /** Identifies a record by layout, so every name for it lowers to one PLC struct. */
111
150
  const recordKey = (layout: RecordLayout) =>
112
- JSON.stringify([
113
- layout.fields,
114
- Object.entries(layout.enums)
115
- .map(([field, value]) => [field, value.getSourceFile().fileName, value.name.text])
116
- .sort(),
117
- ]);
151
+ JSON.stringify([
152
+ layout.fields,
153
+ Object.entries(layout.enums)
154
+ .map(([field, value]) => [
155
+ field,
156
+ value.getSourceFile().fileName,
157
+ value.name.text,
158
+ ])
159
+ .sort(),
160
+ ]);
118
161
 
119
- const procedureAt = (checker: ts.TypeChecker, router: ts.Type, path: readonly string[]) => {
120
- let type = property(checker, router, "_def");
121
- type = type && property(checker, type, "record");
122
- for (const part of path) type = type && property(checker, type, part);
123
- const definition = type && property(checker, type, "_def");
124
- if (!definition || !property(checker, definition, "procedure")) return undefined;
125
- const kind = property(checker, definition, "type");
126
- const types = property(checker, definition, "$types");
127
- const input = types && property(checker, types, "input");
128
- const output = types && property(checker, types, "output");
129
- if (!kind?.isStringLiteral() || !input || !output) return undefined;
130
- return { kind: kind.value, input, output };
162
+ const procedureAt = (
163
+ checker: ts.TypeChecker,
164
+ router: ts.Type,
165
+ path: readonly string[],
166
+ ) => {
167
+ let type = property(checker, router, "_def");
168
+ type = type && property(checker, type, "record");
169
+ for (const part of path) {
170
+ type = type && property(checker, type, part);
171
+ }
172
+ const definition = type && property(checker, type, "_def");
173
+ if (!definition || !property(checker, definition, "procedure")) {
174
+ return undefined;
175
+ }
176
+ const kind = property(checker, definition, "type");
177
+ const types = property(checker, definition, "$types");
178
+ const input = types && property(checker, types, "input");
179
+ const output = types && property(checker, types, "output");
180
+ if (!kind?.isStringLiteral() || !input || !output) {
181
+ return undefined;
182
+ }
183
+ return { kind: kind.value, input, output };
131
184
  };
132
185
 
133
- const pascal = (path: string) =>
134
- path
135
- .split(".")
136
- .map((part) => part[0]!.toUpperCase() + part.slice(1))
137
- .join("");
186
+ // Unlike the backend's pascalCase, this keeps underscores: `line_state.get` names `Line_stateGet`.
187
+ const pascalServicePath = (path: string) =>
188
+ path
189
+ .split(".")
190
+ .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
191
+ .join("");
138
192
 
139
193
  /**
140
194
  * Replaces each `createServiceClient<Router>()` call with an in-memory module of the called
141
195
  * procedures, read from the router's type: the server never runs and no file is written.
142
196
  */
143
197
  export const lowerServices = (
144
- program: ts.Program,
145
- sdk: string,
146
- positions: Positions,
147
- options: ServiceOptions | undefined,
198
+ program: ts.Program,
199
+ sdk: string,
200
+ positions: Positions,
201
+ options: ServiceOptions | undefined,
148
202
  ) => {
149
- const sources = new Map<string, Mapped>();
150
- const diagnostics: Diagnostic[] = [];
151
- const records = new Map<string, { name: string; layout: RecordLayout }>();
152
- const calls = new Map<string, { contract: ServiceContract; input: string; output: string }>();
153
- const checker = program.getTypeChecker();
154
- const symbol = (node: ts.Node) => {
155
- let value = checker.getSymbolAtLocation(node);
156
- while (value && value.flags & ts.SymbolFlags.Alias) value = checker.getAliasedSymbol(value);
157
- return value;
158
- };
159
- const fail = (node: ts.Node, code: string, message: string) =>
160
- diagnostics.push(error(code, message, positions.node(node)));
161
- const record = (layout: RecordLayout, name: string) => {
162
- const key = recordKey(layout);
163
- const existing = records.get(key);
164
- if (existing) return existing.name;
165
- records.set(key, { name, layout });
166
- return name;
167
- };
203
+ const sources = new Map<string, Mapped>();
204
+ const diagnostics: Diagnostic[] = [];
205
+ const records = new Map<string, { name: string; layout: RecordLayout }>();
206
+ const calls = new Map<
207
+ string,
208
+ { contract: ServiceContract; input: string; output: string }
209
+ >();
210
+ const checker = program.getTypeChecker();
211
+ const fail = (node: ts.Node, code: string, message: string) =>
212
+ diagnostics.push(error(code, message, positions.node(node)));
213
+ const record = (layout: RecordLayout, name: string) => {
214
+ const key = recordKey(layout);
215
+ const existing = records.get(key);
216
+ if (existing) {
217
+ return existing.name;
218
+ }
219
+ records.set(key, { name, layout });
220
+ return name;
221
+ };
168
222
 
169
- const clients = new Map<ts.Symbol, ts.Type>();
170
- /** The generated service module, and the first client's creation it stands for. */
171
- let module: { file: string; client: ts.CallExpression } | undefined;
172
- const sourceFiles = runtimeSources(program).filter((source) => !source.isDeclarationFile);
173
- for (const source of sourceFiles)
174
- for (const statement of source.statements) {
175
- if (!ts.isVariableStatement(statement)) continue;
176
- for (const declaration of statement.declarationList.declarations) {
177
- const call = declaration.initializer;
178
- if (
179
- !call ||
180
- !ts.isCallExpression(call) ||
181
- symbol(call.expression)?.name !== "createServiceClient" ||
182
- !symbol(call.expression)?.declarations?.some((value) =>
183
- value.getSourceFile().fileName.startsWith(dirname(sdk) + "/"),
184
- )
185
- )
186
- continue;
187
- const router = call.typeArguments?.[0];
188
- const client = symbol(declaration.name);
189
- if (!router || !client || !(statement.declarationList.flags & ts.NodeFlags.Const))
190
- fail(
191
- declaration,
192
- "PLC1013",
193
- "Create a service client as a module constant: const services = createServiceClient<AppRouter>().",
194
- );
195
- else if (!options)
196
- fail(call, "PLC1013", "Configure server in tsplc.config.ts to call the server.");
197
- else if (options.transport === "http" && !options.baseUrlEnv)
198
- fail(call, "PLC1013", "HTTP service transport requires server.baseUrlEnv.");
199
- else {
200
- clients.set(client, checker.getTypeFromTypeNode(router));
201
- module ??= { file: join(dirname(source.fileName), ".tsplc-services.ts"), client: call };
202
- }
203
- }
204
- }
223
+ const clients = new Map<ts.Symbol, ts.Type>();
224
+ /** The generated service module, and the first client's creation it stands for. */
225
+ let module: { file: string; client: ts.CallExpression } | undefined;
226
+ const sourceFiles = runtimeSources(program).filter(
227
+ (source) => !source.isDeclarationFile,
228
+ );
229
+ for (const source of sourceFiles) {
230
+ for (const statement of source.statements) {
231
+ if (!ts.isVariableStatement(statement)) {
232
+ continue;
233
+ }
234
+ for (const declaration of statement.declarationList.declarations) {
235
+ const call = declaration.initializer;
236
+ if (
237
+ !call ||
238
+ !ts.isCallExpression(call) ||
239
+ !namesSdk(checker, sdk, call.expression, "createServiceClient")
240
+ ) {
241
+ continue;
242
+ }
243
+ const router = call.typeArguments?.[0];
244
+ const client = symbolAt(checker, declaration.name);
245
+ if (
246
+ !router ||
247
+ !client ||
248
+ !(statement.declarationList.flags & ts.NodeFlags.Const)
249
+ ) {
250
+ fail(
251
+ declaration,
252
+ "PLC1013",
253
+ "Create a service client as a module constant: const services = createServiceClient<AppRouter>().",
254
+ );
255
+ } else if (!options) {
256
+ fail(
257
+ call,
258
+ "PLC1013",
259
+ "Configure server in tsplc.config.ts to call the server.",
260
+ );
261
+ } else if (options.transport === "http" && !options.baseUrlEnv) {
262
+ fail(
263
+ call,
264
+ "PLC1013",
265
+ "HTTP service transport requires server.baseUrlEnv.",
266
+ );
267
+ } else {
268
+ clients.set(client, checker.getTypeFromTypeNode(router));
269
+ module ??= {
270
+ file: join(dirname(source.fileName), ".tsplc-services.ts"),
271
+ client: call,
272
+ };
273
+ }
274
+ }
275
+ }
276
+ }
205
277
 
206
- for (const source of sourceFiles) {
207
- const edits: Edit[] = [];
208
- const imports = new Map<string, string>();
209
- const visit = (node: ts.Node): void => {
210
- if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
211
- const clause = node.importClause;
212
- const bindings = clause?.namedBindings;
213
- const typeOnly =
214
- clause?.isTypeOnly ||
215
- (!clause?.name &&
216
- bindings &&
217
- ts.isNamedImports(bindings) &&
218
- bindings.elements.every((element) => element.isTypeOnly));
219
- if (!typeOnly && clause && bindings && ts.isNamedImports(bindings)) {
220
- const elements = bindings.elements.filter((element) => {
221
- const imported = symbol(element.name);
222
- return !imported || !clients.has(imported);
223
- });
224
- if (elements.length !== bindings.elements.length)
225
- edits.push({
226
- start: node.getStart(source),
227
- end: node.end,
228
- text:
229
- elements.length || clause.name
230
- ? ts
231
- .createPrinter()
232
- .printNode(
233
- ts.EmitHint.Unspecified,
234
- ts.factory.updateImportDeclaration(
235
- node,
236
- node.modifiers,
237
- ts.factory.updateImportClause(
238
- clause,
239
- clause.isTypeOnly,
240
- clause.name,
241
- ts.factory.updateNamedImports(bindings, elements),
242
- ),
243
- node.moduleSpecifier,
244
- node.attributes,
245
- ),
246
- source,
247
- )
248
- : "",
249
- });
250
- }
251
- if (
252
- !typeOnly &&
253
- (node.moduleSpecifier.text.startsWith("node:") ||
254
- ["@tsplc/server", "@trpc/server", "zod", "fs", "http", "https", "net", "tls"].includes(
255
- node.moduleSpecifier.text,
256
- ))
257
- )
258
- fail(
259
- node,
260
- "PLC1013",
261
- `Server runtime import ${node.moduleSpecifier.text} cannot execute in PLC code. Expose a PLC procedure on the server router and call it through createServiceClient instead.`,
262
- );
263
- }
264
- if (ts.isVariableStatement(node)) {
265
- const clientStatement = node.declarationList.declarations.some((declaration) => {
266
- const declared = symbol(declaration.name);
267
- return declared && clients.has(declared);
268
- });
269
- if (clientStatement) {
270
- edits.push({ start: node.getStart(source), end: node.end, text: "" });
271
- return;
272
- }
273
- }
274
- if (clients.size && ts.isPropertyAccessExpression(node)) {
275
- const parts: string[] = [];
276
- let root: ts.Expression = node;
277
- while (ts.isPropertyAccessExpression(root)) {
278
- parts.unshift(root.name.text);
279
- root = root.expression;
280
- }
281
- const client = symbol(root);
282
- const router = client && clients.get(client);
283
- const procedure = router && procedureAt(checker, router, parts);
284
- if (router) {
285
- const path = parts.join(".");
286
- if (!procedure) {
287
- fail(node, "PLC1013", `${path} is not a procedure of the client's router.`);
288
- return;
289
- }
290
- let call = calls.get(path);
291
- if (!call) {
292
- try {
293
- if (procedure.kind !== "query" && procedure.kind !== "mutation")
294
- throw new Error(
295
- `${path}: subscriptions use a different transport; expose a query or mutation to the PLC.`,
296
- );
297
- const input = recordLayout(checker, procedure.input, `${path}.input`, false);
298
- const output = recordLayout(checker, procedure.output, `${path}.output`, true);
299
- call = {
300
- contract: serviceContract(
301
- path,
302
- procedure.kind,
303
- { fields: input.fields },
304
- { fields: output.fields },
305
- ),
306
- input: record(input, `${pascal(path)}Input`),
307
- output: record(output, `${pascal(path)}Output`),
308
- };
309
- calls.set(path, call);
310
- } catch (cause) {
311
- fail(node, "PLC2001", cause instanceof Error ? cause.message : String(cause));
312
- return;
313
- }
314
- }
315
- const name = `tsplcService_${path.replaceAll(".", "_")}`;
316
- const local = imports.get(name) ?? `tsplcRemote${imports.size}`;
317
- imports.set(name, local);
318
- edits.push({ start: node.getStart(source), end: node.end, text: local });
319
- return;
320
- }
321
- }
322
- ts.forEachChild(node, visit);
323
- };
324
- visit(source);
325
- if (!edits.length) continue;
326
- let text = edited(source, edits);
327
- if (imports.size && module) {
328
- const path = relative(dirname(source.fileName), module.file).replaceAll("\\", "/");
329
- text = mapped`${text}\nimport {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${JSON.stringify(path.startsWith("../") ? path : `./${path}`)};\n`;
330
- }
331
- sources.set(source.fileName, text);
332
- }
333
- if (module && options)
334
- sources.set(module.file, from(module.client, serviceModule(records, calls, options)));
335
- return {
336
- sources,
337
- diagnostics,
338
- file: module?.file,
339
- records: new Map([...records].map(([key, { name }]) => [key, name])),
340
- };
278
+ for (const source of sourceFiles) {
279
+ const edits: Edit[] = [];
280
+ const imports = new Map<string, string>();
281
+ const visit = (node: ts.Node): void => {
282
+ if (
283
+ ts.isImportDeclaration(node) &&
284
+ ts.isStringLiteral(node.moduleSpecifier)
285
+ ) {
286
+ const clause = node.importClause;
287
+ const bindings = clause?.namedBindings;
288
+ const typeOnly =
289
+ clause?.isTypeOnly ||
290
+ (!clause?.name &&
291
+ bindings &&
292
+ ts.isNamedImports(bindings) &&
293
+ bindings.elements.every((element) => element.isTypeOnly));
294
+ if (!typeOnly && clause && bindings && ts.isNamedImports(bindings)) {
295
+ const elements = bindings.elements.filter((element) => {
296
+ const imported = symbolAt(checker, element.name);
297
+ return !imported || !clients.has(imported);
298
+ });
299
+ if (elements.length !== bindings.elements.length) {
300
+ edits.push({
301
+ start: node.getStart(source),
302
+ end: node.end,
303
+ text:
304
+ elements.length || clause.name
305
+ ? ts
306
+ .createPrinter()
307
+ .printNode(
308
+ ts.EmitHint.Unspecified,
309
+ ts.factory.updateImportDeclaration(
310
+ node,
311
+ node.modifiers,
312
+ ts.factory.updateImportClause(
313
+ clause,
314
+ clause.isTypeOnly,
315
+ clause.name,
316
+ ts.factory.updateNamedImports(bindings, elements),
317
+ ),
318
+ node.moduleSpecifier,
319
+ node.attributes,
320
+ ),
321
+ source,
322
+ )
323
+ : "",
324
+ });
325
+ }
326
+ }
327
+ if (
328
+ !typeOnly &&
329
+ (node.moduleSpecifier.text.startsWith("node:") ||
330
+ [
331
+ "@tsplc/server",
332
+ "@trpc/server",
333
+ "zod",
334
+ "fs",
335
+ "http",
336
+ "https",
337
+ "net",
338
+ "tls",
339
+ ].includes(node.moduleSpecifier.text))
340
+ ) {
341
+ fail(
342
+ node,
343
+ "PLC1013",
344
+ `Server runtime import ${node.moduleSpecifier.text} cannot execute in PLC code. Expose a PLC procedure on the server router and call it through createServiceClient instead.`,
345
+ );
346
+ }
347
+ }
348
+ if (ts.isVariableStatement(node)) {
349
+ const clientStatement = node.declarationList.declarations.some(
350
+ (declaration) => {
351
+ const declared = symbolAt(checker, declaration.name);
352
+ return declared && clients.has(declared);
353
+ },
354
+ );
355
+ if (clientStatement) {
356
+ edits.push({ start: node.getStart(source), end: node.end, text: "" });
357
+ return;
358
+ }
359
+ }
360
+ if (clients.size && ts.isPropertyAccessExpression(node)) {
361
+ const parts: string[] = [];
362
+ let root: ts.Expression = node;
363
+ while (ts.isPropertyAccessExpression(root)) {
364
+ parts.unshift(root.name.text);
365
+ root = root.expression;
366
+ }
367
+ const client = symbolAt(checker, root);
368
+ const router = client && clients.get(client);
369
+ const procedure = router && procedureAt(checker, router, parts);
370
+ if (router) {
371
+ const path = parts.join(".");
372
+ if (!procedure) {
373
+ fail(
374
+ node,
375
+ "PLC1013",
376
+ `${path} is not a procedure of the client's router.`,
377
+ );
378
+ return;
379
+ }
380
+ let call = calls.get(path);
381
+ if (!call) {
382
+ try {
383
+ if (procedure.kind !== "query" && procedure.kind !== "mutation") {
384
+ throw new Error(
385
+ `${path}: subscriptions use a different transport; expose a query or mutation to the PLC.`,
386
+ );
387
+ }
388
+ const input = recordLayout(
389
+ checker,
390
+ procedure.input,
391
+ `${path}.input`,
392
+ false,
393
+ );
394
+ const output = recordLayout(
395
+ checker,
396
+ procedure.output,
397
+ `${path}.output`,
398
+ true,
399
+ );
400
+ call = {
401
+ contract: serviceContract(
402
+ path,
403
+ procedure.kind,
404
+ { fields: input.fields },
405
+ { fields: output.fields },
406
+ ),
407
+ input: record(input, `${pascalServicePath(path)}Input`),
408
+ output: record(output, `${pascalServicePath(path)}Output`),
409
+ };
410
+ calls.set(path, call);
411
+ } catch (cause) {
412
+ fail(
413
+ node,
414
+ "PLC2001",
415
+ cause instanceof Error ? cause.message : String(cause),
416
+ );
417
+ return;
418
+ }
419
+ }
420
+ const name = `tsplcService_${path.replaceAll(".", "_")}`;
421
+ const local = imports.get(name) ?? `tsplcRemote${imports.size}`;
422
+ imports.set(name, local);
423
+ edits.push({
424
+ start: node.getStart(source),
425
+ end: node.end,
426
+ text: local,
427
+ });
428
+ return;
429
+ }
430
+ }
431
+ ts.forEachChild(node, visit);
432
+ };
433
+ visit(source);
434
+ if (!edits.length) {
435
+ continue;
436
+ }
437
+ let text = edited(source, edits);
438
+ if (imports.size && module) {
439
+ const path = relative(dirname(source.fileName), module.file).replaceAll(
440
+ "\\",
441
+ "/",
442
+ );
443
+ text = mapped`${text}\nimport {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${JSON.stringify(path.startsWith("../") ? path : `./${path}`)};\n`;
444
+ }
445
+ sources.set(source.fileName, text);
446
+ }
447
+ if (module && options) {
448
+ sources.set(
449
+ module.file,
450
+ from(module.client, serviceModule(records, calls, options)),
451
+ );
452
+ }
453
+ return {
454
+ sources,
455
+ diagnostics,
456
+ file: module?.file,
457
+ records: new Map([...records].map(([key, { name }]) => [key, name])),
458
+ };
341
459
  };
342
460
 
343
461
  const serviceModule = (
344
- records: ReadonlyMap<string, { name: string; layout: RecordLayout }>,
345
- calls: ReadonlyMap<string, { contract: ServiceContract; input: string; output: string }>,
346
- options: ServiceOptions,
462
+ records: ReadonlyMap<string, { name: string; layout: RecordLayout }>,
463
+ calls: ReadonlyMap<
464
+ string,
465
+ { contract: ServiceContract; input: string; output: string }
466
+ >,
467
+ options: ServiceOptions,
347
468
  ) => {
348
- const enums = new Map<ts.EnumDeclaration, string>();
349
- const enumName = (declaration: ts.EnumDeclaration) => {
350
- const name = enums.get(declaration) ?? `tsplcEnum${enums.size}`;
351
- enums.set(declaration, name);
352
- return name;
353
- };
354
- const scalar = (field: WireScalar, enumeration: ts.EnumDeclaration | undefined) => {
355
- switch (field.kind) {
356
- case "boolean":
357
- return "BOOL";
358
- case "integer":
359
- return field.iec;
360
- case "string":
361
- return `STRING<${field.capacity}>`;
362
- case "enum":
363
- return enumName(enumeration!);
364
- }
365
- };
366
- const interfaces = [...records.values()].map(({ name, layout }) => {
367
- const fields = Object.entries(layout.fields).map(([key, field]) => {
368
- const enumeration = layout.enums[key];
369
- const type =
370
- field.kind === "array"
371
- ? `FixedArray<${scalar(field.element, enumeration)},${field.length}>`
372
- : scalar(field, enumeration);
373
- return `${key}:${type}`;
374
- });
375
- return `export interface ${name}{${fields.join(";")}}`;
376
- });
377
- const functions = [...calls.values()]
378
- .sort((left, right) => left.contract.path.localeCompare(right.contract.path))
379
- .map(({ contract, input, output }) => {
380
- const hasInput = Object.keys(contract.input.fields).length > 0;
381
- const request = hasInput ? "input" : `defaultValue<${input}>()`;
382
- const operation =
383
- options.transport === "http"
384
- ? `tsplcServiceFetch<${output}>(\`\${tsplcServiceBaseUrl}${servicePath(contract)}\`,{method:"POST",json:${request}})`
385
- : `tsplcServiceCall<${output},${input}>(${JSON.stringify(servicePath(contract))},${request})`;
386
- return `export const tsplcService_${contract.path.replaceAll(".", "_")}=async(${hasInput ? `input:${input}` : ""}):Promise<${output}>=>{return await ${operation};};`;
387
- });
388
- const transport =
389
- options.transport === "http"
390
- ? `import {fetch as tsplcServiceFetch} from "@tsplc/compiler/async";\nimport {env as tsplcServiceEnv} from "@tsplc/compiler/config";`
391
- : `import {opcuaCall as tsplcServiceCall} from "@tsplc/compiler/async";`;
392
- const enumImports = [...enums].map(
393
- ([declaration, name]) =>
394
- `import type {${declaration.name.text} as ${name}} from ${JSON.stringify(declaration.getSourceFile().fileName)};`,
395
- );
396
- const baseUrl =
397
- options.transport === "http"
398
- ? `const tsplcServiceBaseUrl:STRING<512>=tsplcServiceEnv<STRING<512>>(${JSON.stringify(options.baseUrlEnv)});`
399
- : "";
400
- return [transport, ...enumImports, baseUrl, ...interfaces, ...functions].join("\n") + "\n";
469
+ const enums = new Map<ts.EnumDeclaration, string>();
470
+ const enumName = (declaration: ts.EnumDeclaration) => {
471
+ const name = enums.get(declaration) ?? `tsplcEnum${enums.size}`;
472
+ enums.set(declaration, name);
473
+ return name;
474
+ };
475
+ const scalar = (
476
+ field: WireScalar,
477
+ enumeration: ts.EnumDeclaration | undefined,
478
+ ) => {
479
+ switch (field.kind) {
480
+ case "boolean":
481
+ return "BOOL";
482
+ case "integer":
483
+ return field.iec;
484
+ case "string":
485
+ return `STRING<${field.capacity}>`;
486
+ case "enum":
487
+ return enumName(enumeration!);
488
+ }
489
+ };
490
+ const interfaces = [...records.values()].map(({ name, layout }) => {
491
+ const fields = Object.entries(layout.fields).map(([key, field]) => {
492
+ const enumeration = layout.enums[key];
493
+ const type =
494
+ field.kind === "array"
495
+ ? `FixedArray<${scalar(field.element, enumeration)},${field.length}>`
496
+ : scalar(field, enumeration);
497
+ return `${key}:${type}`;
498
+ });
499
+ return `export interface ${name}{${fields.join(";")}}`;
500
+ });
501
+ const functions = [...calls.values()]
502
+ .sort((left, right) =>
503
+ left.contract.path.localeCompare(right.contract.path),
504
+ )
505
+ .map(({ contract, input, output }) => {
506
+ const hasInput = Object.keys(contract.input.fields).length > 0;
507
+ const request = hasInput ? "input" : `defaultValue<${input}>()`;
508
+ const operation =
509
+ options.transport === "http"
510
+ ? `tsplcServiceFetch<${output}>(\`\${tsplcServiceBaseUrl}${servicePath(contract)}\`,{method:"POST",json:${request}})`
511
+ : `tsplcServiceCall<${output},${input}>(${JSON.stringify(servicePath(contract))},${request})`;
512
+ return `export const tsplcService_${contract.path.replaceAll(".", "_")}=async(${hasInput ? `input:${input}` : ""}):Promise<${output}>=>{return await ${operation};};`;
513
+ });
514
+ const transport =
515
+ options.transport === "http"
516
+ ? `import {fetch as tsplcServiceFetch} from "@tsplc/compiler/async";\nimport {env as tsplcServiceEnv} from "@tsplc/compiler/config";`
517
+ : `import {opcuaCall as tsplcServiceCall} from "@tsplc/compiler/async";`;
518
+ const enumImports = [...enums].map(
519
+ ([declaration, name]) =>
520
+ `import type {${declaration.name.text} as ${name}} from ${JSON.stringify(declaration.getSourceFile().fileName)};`,
521
+ );
522
+ const baseUrl =
523
+ options.transport === "http"
524
+ ? `const tsplcServiceBaseUrl:STRING<512>=tsplcServiceEnv<STRING<512>>(${JSON.stringify(options.baseUrlEnv)});`
525
+ : "";
526
+ return (
527
+ [transport, ...enumImports, baseUrl, ...interfaces, ...functions].join(
528
+ "\n",
529
+ ) + "\n"
530
+ );
401
531
  };
402
532
 
403
533
  /** Lowers a type that names a called procedure's record, such as `inferRouterOutputs<AppRouter>["a"]["b"]`. */
404
534
  export const serviceRecords = (
405
- program: ts.Program,
406
- lowering: { file: string | undefined; records: ReadonlyMap<string, string> },
535
+ program: ts.Program,
536
+ lowering: { file: string | undefined; records: ReadonlyMap<string, string> },
407
537
  ) => {
408
- const source = lowering.file && program.getSourceFile(lowering.file);
409
- if (!source) return undefined;
410
- const checker = program.getTypeChecker();
411
- const declarations = new Map(
412
- source.statements.filter(ts.isInterfaceDeclaration).map((value) => [value.name.text, value]),
413
- );
414
- return (type: ts.Type): ts.Symbol | undefined => {
415
- let key: string;
416
- try {
417
- key = recordKey(recordLayout(checker, type, "record", false));
418
- } catch {
419
- return undefined;
420
- }
421
- const name = lowering.records.get(key);
422
- const declaration = name === undefined ? undefined : declarations.get(name);
423
- return declaration && checker.getSymbolAtLocation(declaration.name);
424
- };
538
+ const source = lowering.file && program.getSourceFile(lowering.file);
539
+ if (!source) {
540
+ return undefined;
541
+ }
542
+ const checker = program.getTypeChecker();
543
+ const declarations = new Map(
544
+ source.statements
545
+ .filter(ts.isInterfaceDeclaration)
546
+ .map((value) => [value.name.text, value]),
547
+ );
548
+ return (type: ts.Type): ts.Symbol | undefined => {
549
+ let key: string;
550
+ try {
551
+ key = recordKey(recordLayout(checker, type, "record", false));
552
+ } catch {
553
+ return undefined;
554
+ }
555
+ const name = lowering.records.get(key);
556
+ const declaration = name === undefined ? undefined : declarations.get(name);
557
+ return declaration && checker.getSymbolAtLocation(declaration.name);
558
+ };
425
559
  };