@tsplc/typegen 0.5.13 → 0.5.15

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.
@@ -1,34 +1,32 @@
1
1
  // packages/typegen/src/project-snapshot.ts
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { dirname, resolve } from "node:path";
4
- import { projectSnapshotFile } from "@tsplc/config/project-files";
5
- import { ioSymbolsSchema, tsplcConfigSchema } from "@tsplc/config/schema";
4
+ import {
5
+ ioSymbolsSchema,
6
+ projectSnapshotFile
7
+ } from "@tsplc/config/project-files";
8
+ import { tsplcConfigSchema } from "@tsplc/config/schema";
6
9
  import { z } from "zod";
10
+
11
+ // packages/typegen/src/files.ts
12
+ var isMissingFile = (error) => error instanceof Error && ("code" in error) && error.code === "ENOENT";
13
+
14
+ // packages/typegen/src/project-snapshot.ts
7
15
  var projectSnapshotSchema = z.object({
8
16
  version: z.literal(1),
9
17
  configFile: z.string().nonempty(),
10
18
  config: tsplcConfigSchema,
11
19
  symbols: ioSymbolsSchema
12
20
  });
13
- var missing = (error) => error instanceof Error && ("code" in error) && error.code === "ENOENT";
14
- var parseJson = (text) => {
15
- try {
16
- return { json: JSON.parse(text) };
17
- } catch (error) {
18
- return { error };
19
- }
20
- };
21
21
  async function readProjectSnapshot(configFile) {
22
22
  const file = resolve(dirname(configFile), projectSnapshotFile);
23
- const read = await readFile(file, "utf8").then((text) => ({ text }), (error) => ({ error }));
24
- if ("error" in read) {
25
- return missing(read.error) ? { kind: "absent" } : { kind: "invalid", reason: `${file}: ${String(read.error)}` };
26
- }
27
- const decoded = parseJson(read.text);
28
- if ("error" in decoded) {
29
- return { kind: "invalid", reason: `${file}: ${String(decoded.error)}` };
23
+ let json;
24
+ try {
25
+ json = JSON.parse(await readFile(file, "utf8"));
26
+ } catch (error) {
27
+ return isMissingFile(error) ? { kind: "absent" } : { kind: "invalid", reason: `${file}: ${String(error)}` };
30
28
  }
31
- const parsed = projectSnapshotSchema.safeParse(decoded.json);
29
+ const parsed = projectSnapshotSchema.safeParse(json);
32
30
  if (!parsed.success) {
33
31
  return {
34
32
  kind: "invalid",
@@ -42,5 +40,5 @@ export {
42
40
  readProjectSnapshot
43
41
  };
44
42
 
45
- //# debugId=FA7CACDC419D733464756E2164756E21
43
+ //# debugId=203563BEF0EC467964756E2164756E21
46
44
  //# sourceMappingURL=project-snapshot.js.map
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/project-snapshot.ts"],
3
+ "sources": ["../src/project-snapshot.ts", "../src/files.ts"],
4
4
  "sourcesContent": [
5
- "import { readFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { projectSnapshotFile } from \"@tsplc/config/project-files\";\nimport { ioSymbolsSchema, tsplcConfigSchema } from \"@tsplc/config/schema\";\nimport { z } from \"zod\";\n\n/** What `tsplc typegen` materializes at `projectSnapshotFile` for readers that never execute the config. */\nexport const projectSnapshotSchema = z.object({\n\tversion: z.literal(1),\n\tconfigFile: z.string().nonempty(),\n\tconfig: tsplcConfigSchema,\n\tsymbols: ioSymbolsSchema,\n});\nexport type ProjectSnapshot = z.output<typeof projectSnapshotSchema>;\n\n/**\n * A config's snapshot: `absent` before the first type generation, `stale` when it was generated\n * for another config file, `invalid` when it cannot be read or does not match the schema.\n */\nexport type SnapshotRead =\n\t| { kind: \"valid\"; snapshot: ProjectSnapshot }\n\t| { kind: \"absent\" | \"stale\" }\n\t| { kind: \"invalid\"; reason: string };\n\nconst missing = (error: unknown) =>\n\terror instanceof Error && \"code\" in error && error.code === \"ENOENT\";\n\nconst parseJson = (text: string): { json: unknown } | { error: unknown } => {\n\ttry {\n\t\treturn { json: JSON.parse(text) };\n\t} catch (error) {\n\t\treturn { error };\n\t}\n};\n\nexport async function readProjectSnapshot(\n\tconfigFile: string,\n): Promise<SnapshotRead> {\n\tconst file = resolve(dirname(configFile), projectSnapshotFile);\n\tconst read = await readFile(file, \"utf8\").then(\n\t\t(text) => ({ text }),\n\t\t(error: unknown) => ({ error }),\n\t);\n\tif (\"error\" in read) {\n\t\treturn missing(read.error)\n\t\t\t? { kind: \"absent\" }\n\t\t\t: { kind: \"invalid\", reason: `${file}: ${String(read.error)}` };\n\t}\n\tconst decoded = parseJson(read.text);\n\tif (\"error\" in decoded) {\n\t\treturn { kind: \"invalid\", reason: `${file}: ${String(decoded.error)}` };\n\t}\n\tconst parsed = projectSnapshotSchema.safeParse(decoded.json);\n\tif (!parsed.success) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\treason: `${file}: ${z.prettifyError(parsed.error)}`,\n\t\t};\n\t}\n\treturn parsed.data.configFile === configFile\n\t\t? { kind: \"valid\", snapshot: parsed.data }\n\t\t: { kind: \"stale\" };\n}\n"
5
+ "import { readFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport {\n\tioSymbolsSchema,\n\tprojectSnapshotFile,\n} from \"@tsplc/config/project-files\";\nimport { tsplcConfigSchema } from \"@tsplc/config/schema\";\nimport { z } from \"zod\";\nimport { isMissingFile } from \"./files\";\n\n/** What `tsplc typegen` materializes at `projectSnapshotFile` for readers that never execute the config. */\nexport const projectSnapshotSchema = z.object({\n\tversion: z.literal(1),\n\tconfigFile: z.string().nonempty(),\n\tconfig: tsplcConfigSchema,\n\tsymbols: ioSymbolsSchema,\n});\nexport type ProjectSnapshot = z.output<typeof projectSnapshotSchema>;\n\n/**\n * A config's snapshot: `absent` before the first type generation, `stale` when it was generated\n * for another config file, `invalid` when it cannot be read or does not match the schema.\n */\nexport type SnapshotRead =\n\t| { kind: \"valid\"; snapshot: ProjectSnapshot }\n\t| { kind: \"absent\" | \"stale\" }\n\t| { kind: \"invalid\"; reason: string };\n\nexport async function readProjectSnapshot(\n\tconfigFile: string,\n): Promise<SnapshotRead> {\n\tconst file = resolve(dirname(configFile), projectSnapshotFile);\n\tlet json: unknown;\n\ttry {\n\t\tjson = JSON.parse(await readFile(file, \"utf8\"));\n\t} catch (error) {\n\t\treturn isMissingFile(error)\n\t\t\t? { kind: \"absent\" }\n\t\t\t: { kind: \"invalid\", reason: `${file}: ${String(error)}` };\n\t}\n\tconst parsed = projectSnapshotSchema.safeParse(json);\n\tif (!parsed.success) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\treason: `${file}: ${z.prettifyError(parsed.error)}`,\n\t\t};\n\t}\n\treturn parsed.data.configFile === configFile\n\t\t? { kind: \"valid\", snapshot: parsed.data }\n\t\t: { kind: \"stale\" };\n}\n",
6
+ "import { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nexport const isMissingFile = (error: unknown) =>\n\terror instanceof Error && \"code\" in error && error.code === \"ENOENT\";\n\n/** The text of the file at `path`, or null when there is none. */\nexport const readIfPresent = (path: string) =>\n\treadFile(path, \"utf8\").catch((error: unknown) => {\n\t\tif (isMissingFile(error)) {\n\t\t\treturn null;\n\t\t}\n\t\tthrow error;\n\t});\n\n/** Every file under `directory` whose name ends in `.extension`, any case, each directory's entries in `order`. */\nexport async function filesUnder(\n\tdirectory: string,\n\textension: string,\n\torder: (a: string, b: string) => number,\n): Promise<string[]> {\n\tconst pattern = new RegExp(`\\\\.${extension}$`, \"i\");\n\tconst entries = await readdir(directory, { withFileTypes: true });\n\tconst paths = await Promise.all(\n\t\tentries\n\t\t\t.sort((a, b) => order(a.name, b.name))\n\t\t\t.map(async (entry) => {\n\t\t\t\tconst path = join(directory, entry.name);\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\treturn filesUnder(path, extension, order);\n\t\t\t\t}\n\t\t\t\treturn entry.isFile() && pattern.test(entry.name) ? [path] : [];\n\t\t\t}),\n\t);\n\treturn paths.flat();\n}\n\n/** Every Structured Text source under `directory`, in name order. */\nexport const stFiles = (directory: string) =>\n\tfilesUnder(directory, \"st\", (a, b) => (a < b ? -1 : 1));\n"
6
7
  ],
7
- "mappings": ";AAAA;AACA;AACA;AACA;AACA;AAGO,IAAM,wBAAwB,EAAE,OAAO;AAAA,EAC7C,SAAS,EAAE,QAAQ,CAAC;AAAA,EACpB,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,QAAQ;AAAA,EACR,SAAS;AACV,CAAC;AAYD,IAAM,UAAU,CAAC,UAChB,iBAAiB,UAAS,UAAU,UAAS,MAAM,SAAS;AAE7D,IAAM,YAAY,CAAC,SAAyD;AAAA,EAC3E,IAAI;AAAA,IACH,OAAO,EAAE,MAAM,KAAK,MAAM,IAAI,EAAE;AAAA,IAC/B,OAAO,OAAO;AAAA,IACf,OAAO,EAAE,MAAM;AAAA;AAAA;AAIV,eAAe,mBAAmB,CACxC,YACwB;AAAA,EACxB,MAAM,OAAO,QAAQ,QAAQ,UAAU,GAAG,mBAAmB;AAAA,EAC7D,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM,EAAE,KACzC,CAAC,UAAU,EAAE,KAAK,IAClB,CAAC,WAAoB,EAAE,MAAM,EAC9B;AAAA,EACA,IAAI,WAAW,MAAM;AAAA,IACpB,OAAO,QAAQ,KAAK,KAAK,IACtB,EAAE,MAAM,SAAS,IACjB,EAAE,MAAM,WAAW,QAAQ,GAAG,SAAS,OAAO,KAAK,KAAK,IAAI;AAAA,EAChE;AAAA,EACA,MAAM,UAAU,UAAU,KAAK,IAAI;AAAA,EACnC,IAAI,WAAW,SAAS;AAAA,IACvB,OAAO,EAAE,MAAM,WAAW,QAAQ,GAAG,SAAS,OAAO,QAAQ,KAAK,IAAI;AAAA,EACvE;AAAA,EACA,MAAM,SAAS,sBAAsB,UAAU,QAAQ,IAAI;AAAA,EAC3D,IAAI,CAAC,OAAO,SAAS;AAAA,IACpB,OAAO;AAAA,MACN,MAAM;AAAA,MACN,QAAQ,GAAG,SAAS,EAAE,cAAc,OAAO,KAAK;AAAA,IACjD;AAAA,EACD;AAAA,EACA,OAAO,OAAO,KAAK,eAAe,aAC/B,EAAE,MAAM,SAAS,UAAU,OAAO,KAAK,IACvC,EAAE,MAAM,QAAQ;AAAA;",
8
- "debugId": "FA7CACDC419D733464756E2164756E21",
8
+ "mappings": ";AAAA;AACA;AACA;AAAA;AAAA;AAAA;AAIA;AACA;;;ACJO,IAAM,gBAAgB,CAAC,UAC7B,iBAAiB,UAAS,UAAU,UAAS,MAAM,SAAS;;;ADOtD,IAAM,wBAAwB,EAAE,OAAO;AAAA,EAC7C,SAAS,EAAE,QAAQ,CAAC;AAAA,EACpB,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,QAAQ;AAAA,EACR,SAAS;AACV,CAAC;AAYM,eAAe,mBAAmB,CACxC,YACwB;AAAA,EACxB,MAAM,OAAO,QAAQ,QAAQ,UAAU,GAAG,mBAAmB;AAAA,EAC7D,IAAI;AAAA,EACJ,IAAI;AAAA,IACH,OAAO,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC;AAAA,IAC7C,OAAO,OAAO;AAAA,IACf,OAAO,cAAc,KAAK,IACvB,EAAE,MAAM,SAAS,IACjB,EAAE,MAAM,WAAW,QAAQ,GAAG,SAAS,OAAO,KAAK,IAAI;AAAA;AAAA,EAE3D,MAAM,SAAS,sBAAsB,UAAU,IAAI;AAAA,EACnD,IAAI,CAAC,OAAO,SAAS;AAAA,IACpB,OAAO;AAAA,MACN,MAAM;AAAA,MACN,QAAQ,GAAG,SAAS,EAAE,cAAc,OAAO,KAAK;AAAA,IACjD;AAAA,EACD;AAAA,EACA,OAAO,OAAO,KAAK,eAAe,aAC/B,EAAE,MAAM,SAAS,UAAU,OAAO,KAAK,IACvC,EAAE,MAAM,QAAQ;AAAA;",
9
+ "debugId": "203563BEF0EC467964756E2164756E21",
9
10
  "names": []
10
11
  }
package/package.json CHANGED
@@ -16,7 +16,7 @@
16
16
  "url": "git+https://github.com/rip-technologies/tsplc.git",
17
17
  "directory": "packages/typegen"
18
18
  },
19
- "version": "0.5.13",
19
+ "version": "0.5.15",
20
20
  "type": "module",
21
21
  "exports": {
22
22
  ".": {
@@ -59,10 +59,10 @@
59
59
  "bun": ">=1.4.3"
60
60
  },
61
61
  "dependencies": {
62
- "@tsplc/config": "0.5.13",
62
+ "@tsplc/config": "0.5.15",
63
63
  "prettier": "3.9.10",
64
64
  "zod": "4.3.6",
65
- "@tsplc/iec": "0.5.13"
65
+ "@tsplc/iec": "0.5.15"
66
66
  },
67
67
  "bin": {
68
68
  "tsplc-typegen": "./dist/cli.js"
package/src/cli.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
- import { dirname, resolve } from "node:path";
2
+ import { resolve } from "node:path";
4
3
  import { parseArgs } from "node:util";
4
+ import { loadTsplcConfig } from "@tsplc/config";
5
+ import { configFileName } from "@tsplc/config/project-files";
5
6
  import { generateTypes } from "./codegen/generate";
7
+ import { checkOutputs, formatTypeScript, writeOutputs } from "./outputs";
6
8
  import { generateProject } from "./project";
7
9
 
8
10
  async function main(): Promise<void> {
@@ -18,15 +20,19 @@ async function main(): Promise<void> {
18
20
  });
19
21
  if (values.help) {
20
22
  console.log(
21
- "Usage: tsplc-typegen --types src/types [--globals src/globals] --out generated.ts [--check]\n\nGenerate TypeScript types and runtime field metadata from CODESYS ST declarations.\n--check exits unsuccessfully if the output is missing or stale, without writing files.",
23
+ `Usage: tsplc-typegen [--config ${configFileName}] [--check]\n tsplc-typegen --types src/types [--globals src/globals] --out generated.ts [--check]\n\nGenerate TypeScript types and runtime field metadata from CODESYS ST declarations.\nWithout --types and --out, generates the files the project's config names.\n--check exits unsuccessfully if the output is missing or stale, without writing files.`,
22
24
  );
23
25
  return;
24
26
  }
25
27
  if (!values.types && !values.out) {
26
- const result = await generateProject(values.config, {
27
- check: values.check,
28
+ const loaded = await loadTsplcConfig(values.config ?? configFileName, {
29
+ env: process.env,
30
+ target: undefined,
31
+ forAgent: false,
28
32
  });
29
- console.log(`Generated ${result.files.join(", ")}`);
33
+ const result = await generateProject(loaded, { check: values.check });
34
+ const files = result.files.join(", ");
35
+ console.log(values.check ? `Up to date: ${files}` : `Generated ${files}`);
30
36
  return;
31
37
  }
32
38
  if (!values.types || !values.out) {
@@ -38,37 +44,23 @@ async function main(): Promise<void> {
38
44
  "--out must be a .ts file (the generated file contains runtime metadata)",
39
45
  );
40
46
  }
41
- const result = await generateTypes({
42
- types: resolve(values.types),
43
- globals: values.globals ? resolve(values.globals) : undefined,
44
- });
47
+ const contract = {
48
+ path: out,
49
+ content: await formatTypeScript(
50
+ await generateTypes({
51
+ types: resolve(values.types),
52
+ globals: values.globals ? resolve(values.globals) : [],
53
+ publication: null,
54
+ declarations: true,
55
+ }),
56
+ ),
57
+ };
45
58
  if (values.check) {
46
- const existing = await readFile(out, "utf8").catch((error: unknown) => {
47
- if (
48
- error instanceof Error &&
49
- "code" in error &&
50
- error.code === "ENOENT"
51
- ) {
52
- return undefined;
53
- }
54
- throw error;
55
- });
56
- if (existing !== result) {
57
- throw new Error(
58
- `${out} is missing or stale; rerun tsplc-typegen without --check`,
59
- );
60
- }
59
+ await checkOutputs([contract]);
61
60
  console.log(`Up to date: ${out}`);
62
61
  return;
63
62
  }
64
- await mkdir(dirname(out), { recursive: true });
65
- const temporary = `${out}.${process.pid}.tmp`;
66
- try {
67
- await writeFile(temporary, result, { flag: "wx" });
68
- await rename(temporary, out);
69
- } finally {
70
- await rm(temporary, { force: true });
71
- }
63
+ await writeOutputs([contract]);
72
64
  console.log(`Generated ${out}`);
73
65
  }
74
66
 
@@ -1,24 +1,22 @@
1
1
  import {
2
2
  elementaryType,
3
3
  elementaryTypes,
4
+ fitsNumber,
4
5
  integerRange,
5
6
  isIntegerValued,
6
7
  } from "@tsplc/iec";
7
- import type { GlobalList } from "./parser";
8
-
9
- // Constants and enum values are emitted as numbers, so they take integer types of 32 bits and under.
10
- export const isNumberInteger = (name: string) => {
11
- const type = elementaryType(name);
12
- return isIntegerValued(type) && type.bits <= 32;
13
- };
8
+ import { identifierPart, identifierStart, integerLiteral } from "@tsplc/iec/st";
9
+ import type { GlobalList, Member } from "./parser";
14
10
 
15
11
  const integerRanges = new Map(
16
12
  elementaryTypes
17
13
  .filter(isIntegerValued)
18
14
  .map((type) => [type.name, integerRange(type)] as const),
19
15
  );
16
+ const identifier = `${identifierStart}${identifierPart}*`;
17
+ const startsWithIdentifier = new RegExp(`^${identifierStart}`);
20
18
  const integerToken = new RegExp(
21
- String.raw`(?:${[...integerRanges.keys()].join("|")})\s*#\s*[+-]?(?:(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*)|(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*|[A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)?|[()+\-*/]`,
19
+ String.raw`(?:${[...integerRanges.keys()].join("|")})\s*#\s*[+-]?(?:(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*)|(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*|${identifier}(?:\s*\.\s*${identifier})?|[()+\-*/]`,
22
20
  "g",
23
21
  );
24
22
 
@@ -70,18 +68,13 @@ export function integerExpression(
70
68
  return value;
71
69
  }
72
70
  if (token && /^\d/.test(token)) {
73
- const [base, digits] = token.replace(/_/g, "").split("#");
74
- if (
75
- digits !== undefined &&
76
- ![...digits].every((digit) => parseInt(digit, 16) < Number(base))
77
- ) {
78
- throw new Error(`invalid base-${base} literal: ${token}`);
71
+ const literal = integerLiteral(token);
72
+ if (literal === undefined) {
73
+ throw new Error(`invalid integer literal: ${token}`);
79
74
  }
80
- return safe(
81
- digits === undefined ? Number(base) : parseInt(digits, Number(base)),
82
- );
75
+ return safe(Number(literal));
83
76
  }
84
- if (token && /^[A-Za-z_]/.test(token)) {
77
+ if (token && startsWithIdentifier.test(token)) {
85
78
  return lookup(token);
86
79
  }
87
80
  throw new Error(`invalid integer expression: ${text}`);
@@ -110,12 +103,17 @@ export function integerExpression(
110
103
  return value;
111
104
  }
112
105
  const value = sum();
113
- if (position !== tokens.length || !Number.isSafeInteger(value)) {
114
- throw new Error(`invalid or unsafe integer expression: ${text}`);
106
+ if (position !== tokens.length) {
107
+ throw new Error(`invalid integer expression: ${text}`);
115
108
  }
116
109
  return value;
117
110
  }
118
111
 
112
+ /** Whether a constant has a type a JavaScript number holds exactly: the only constants typegen evaluates and exports. */
113
+ export const isIntegerConstant = (member: Member) =>
114
+ member.type.kind === "named" &&
115
+ fitsNumber(elementaryType(member.type.name.toUpperCase()));
116
+
119
117
  /**
120
118
  * Looks constants of CONSTANT global lists up by qualified name, or by a bare name that
121
119
  * only one list declares; inside a list's own initializers (`scope`), its members come
@@ -160,11 +158,7 @@ export function constantResolver(
160
158
  throw new Error(`cyclic constant ${name}`);
161
159
  }
162
160
  const { member, list } = definition;
163
- if (
164
- member.initial === undefined ||
165
- member.type.kind !== "named" ||
166
- !isNumberInteger(member.type.name.toUpperCase())
167
- ) {
161
+ if (member.initial === undefined || !isIntegerConstant(member)) {
168
162
  throw new Error(
169
163
  `${list.source}: constant ${member.name} must have an integer type and initializer`,
170
164
  );
@@ -1,12 +1,10 @@
1
1
  import { readFile } from "node:fs/promises";
2
- import { basename } from "node:path";
3
- import { blockCommentEnd, lineCommentEnd } from "@tsplc/iec/st";
4
- import { stFiles } from "./generate";
2
+ import { stFiles } from "../files";
5
3
  import {
6
4
  type Declaration,
5
+ firstCodeToken,
7
6
  type GlobalList,
8
- parseDeclarations,
9
- parseGlobals,
7
+ parseSources,
10
8
  } from "./parser";
11
9
 
12
10
  export type {
@@ -16,23 +14,7 @@ export type {
16
14
  SymbolAccess,
17
15
  TypeReference,
18
16
  } from "./parser";
19
-
20
- /** Where ST code begins at or after `offset`: past whitespace, comments and pragmas. */
21
- const codeStart = (text: string, offset: number): number => {
22
- const start = offset + text.slice(offset).search(/\S|$/);
23
- if (text.startsWith("(*", start)) {
24
- const end = blockCommentEnd(text, start);
25
- return end === null ? start : codeStart(text, end);
26
- }
27
- if (text.startsWith("//", start)) {
28
- return codeStart(text, lineCommentEnd(text, start));
29
- }
30
- if (text.startsWith("{", start)) {
31
- const end = text.indexOf("}", start);
32
- return end < 0 ? start : codeStart(text, end + 1);
33
- }
34
- return start;
35
- };
17
+ export { resolveDeclarations } from "./resolution";
36
18
 
37
19
  /** The files among `files` that declare TYPEs and those that declare VAR_GLOBAL lists; other POUs are neither. */
38
20
  export const declarationFiles = async (files: readonly string[]) => {
@@ -41,11 +23,13 @@ export const declarationFiles = async (files: readonly string[]) => {
41
23
  globals: [],
42
24
  };
43
25
  for (const file of files) {
44
- const text = await readFile(file, "utf8");
45
- const code = text.slice(codeStart(text, 0));
46
- if (/^TYPE\b/i.test(code)) {
26
+ const keyword = firstCodeToken({
27
+ name: file,
28
+ text: await readFile(file, "utf8"),
29
+ })?.toUpperCase();
30
+ if (keyword === "TYPE") {
47
31
  sorted.types.push(file);
48
- } else if (/^VAR_GLOBAL\b/i.test(code)) {
32
+ } else if (keyword === "VAR_GLOBAL") {
49
33
  sorted.globals.push(file);
50
34
  }
51
35
  }
@@ -58,16 +42,5 @@ export const declarationFiles = async (files: readonly string[]) => {
58
42
  */
59
43
  export const readDeclarations = async (
60
44
  directory: string,
61
- ): Promise<{ types: Declaration[]; globals: GlobalList[] }> => {
62
- const files = await declarationFiles(await stFiles(directory));
63
- const read = (file: string) =>
64
- readFile(file, "utf8").then((text) => ({ name: file, text }));
65
- return {
66
- types: (await Promise.all(files.types.map(read))).flatMap(
67
- parseDeclarations,
68
- ),
69
- globals: (await Promise.all(files.globals.map(read))).map((source) =>
70
- parseGlobals(source, basename(source.name).replace(/\.st$/i, "")),
71
- ),
72
- };
73
- };
45
+ ): Promise<{ types: Declaration[]; globals: GlobalList[] }> =>
46
+ parseSources(await declarationFiles(await stFiles(directory)));