@intellectual-frontiers/docs 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/LICENSE +75 -0
  2. package/README.md +8 -2
  3. package/dist/build.d.ts +63 -0
  4. package/dist/build.js +103 -0
  5. package/dist/check.d.ts +63 -0
  6. package/dist/check.js +54 -0
  7. package/dist/cli.d.ts +51 -0
  8. package/dist/cli.js +165 -0
  9. package/dist/config.d.ts +196 -0
  10. package/dist/config.js +229 -0
  11. package/dist/emit/html.d.ts +67 -0
  12. package/dist/emit/html.js +338 -0
  13. package/dist/emit/markdown.d.ts +19 -0
  14. package/dist/emit/markdown.js +124 -0
  15. package/dist/emit/search.d.ts +15 -0
  16. package/dist/emit/search.js +29 -0
  17. package/dist/extract/api.d.ts +74 -0
  18. package/dist/extract/api.js +261 -0
  19. package/dist/extract/specs.d.ts +141 -0
  20. package/dist/extract/specs.js +208 -0
  21. package/dist/highlight.d.ts +22 -0
  22. package/dist/highlight.js +77 -0
  23. package/dist/layered.d.ts +94 -0
  24. package/dist/layered.js +14 -0
  25. package/dist/lens/guides.d.ts +23 -0
  26. package/dist/lens/guides.js +49 -0
  27. package/dist/lens/layered.d.ts +16 -0
  28. package/dist/lens/layered.js +354 -0
  29. package/dist/lens/program.d.ts +23 -0
  30. package/dist/lens/program.js +124 -0
  31. package/dist/lens/releases.d.ts +10 -0
  32. package/dist/lens/releases.js +37 -0
  33. package/dist/lens.d.ts +30 -0
  34. package/dist/lens.js +1 -0
  35. package/dist/links.d.ts +96 -0
  36. package/dist/links.js +182 -0
  37. package/dist/main.d.ts +1 -0
  38. package/dist/main.js +12 -0
  39. package/dist/markdown.d.ts +43 -0
  40. package/dist/markdown.js +301 -0
  41. package/dist/mod.d.ts +32 -0
  42. package/dist/mod.js +9 -0
  43. package/dist/model.d.ts +159 -0
  44. package/dist/model.js +39 -0
  45. package/dist/pages/api.d.ts +41 -0
  46. package/dist/pages/api.js +162 -0
  47. package/dist/pages/areas.d.ts +39 -0
  48. package/dist/pages/areas.js +119 -0
  49. package/dist/pages/overview.d.ts +24 -0
  50. package/dist/pages/overview.js +283 -0
  51. package/dist/pages/specs.d.ts +31 -0
  52. package/dist/pages/specs.js +358 -0
  53. package/dist/site.d.ts +31 -0
  54. package/dist/site.js +288 -0
  55. package/dist/sources.d.ts +53 -0
  56. package/dist/sources.js +159 -0
  57. package/dist/theme/site.css +275 -0
  58. package/dist/theme/site.js +174 -0
  59. package/dist/tsdoc.d.ts +67 -0
  60. package/dist/tsdoc.js +94 -0
  61. package/ifc-docs.mjs +4 -0
  62. package/package.json +66 -4
  63. package/src/build.ts +117 -0
  64. package/src/check.ts +84 -0
  65. package/src/cli.ts +145 -0
  66. package/src/config.ts +370 -0
  67. package/src/emit/html.ts +398 -0
  68. package/src/emit/markdown.ts +129 -0
  69. package/src/emit/search.ts +38 -0
  70. package/src/extract/api.ts +297 -0
  71. package/src/extract/specs.ts +299 -0
  72. package/src/highlight.ts +98 -0
  73. package/src/layered.ts +102 -0
  74. package/src/lens/guides.ts +70 -0
  75. package/src/lens/layered.ts +341 -0
  76. package/src/lens/program.ts +137 -0
  77. package/src/lens/releases.ts +54 -0
  78. package/src/lens.ts +34 -0
  79. package/src/links.ts +234 -0
  80. package/src/main.ts +12 -0
  81. package/src/markdown.ts +320 -0
  82. package/src/mod.ts +53 -0
  83. package/src/model.ts +154 -0
  84. package/src/pages/api.ts +179 -0
  85. package/src/pages/areas.ts +133 -0
  86. package/src/pages/overview.ts +276 -0
  87. package/src/pages/specs.ts +366 -0
  88. package/src/site.ts +285 -0
  89. package/src/sources.ts +157 -0
  90. package/src/theme/site.css +275 -0
  91. package/src/theme/site.js +174 -0
  92. package/src/tsdoc.ts +131 -0
@@ -0,0 +1,297 @@
1
+ // Spec: 0001-docs FR-001
2
+ /**
3
+ * The API of each area, read through the TypeScript 7.1 programmatic API (commons 0011-documentation FR-010): every export of the area's
4
+ * entry points, an alias followed to what it names, a namespace (`export * as fs`) walked into, with its kinds, the source file it is
5
+ * declared in, its signature as the checker prints it (or, for a type or an interface, as its source writes it), the members of an
6
+ * interface, and its TSDoc. It uses `typescript/async`, whose channel to the compiler runs under Bun and under Node; the compiler is the
7
+ * one the package's `package.json` pins. The program is the repository's: its modules resolve from its own `node_modules`, and Node's
8
+ * types are the first `@types/node` found in the repository's root, in a package's folder, or beside the generator.
9
+ *
10
+ * @limits
11
+ * A type in a signature is printed as text and is not yet a link to its page. A signature is the checker's own printing, with no
12
+ * truncation, so the computed types of a data model can be thousands of characters long; the page folds them. Positions in the
13
+ * source are read as the compiler gives them and checked against the declaration's name; where they do not match, the checker's printing
14
+ * is shown instead of the source.
15
+ *
16
+ * @module
17
+ */
18
+ import { API } from "typescript/async";
19
+ import { fs, path } from "@intellectual-frontiers/system";
20
+ import { type DocComment, docOf, type DocTag, moduleComment } from "../tsdoc.ts";
21
+
22
+ /** What an export is. */
23
+ export type ExportKind = "function" | "const" | "class" | "interface" | "type" | "namespace" | "enum";
24
+
25
+ /** A member of an interface or a class: its name, its type and its TSDoc. */
26
+ export interface ApiMember {
27
+ /** Its name. */
28
+ readonly name: string;
29
+ /** Its type, as the checker prints it. */
30
+ readonly type: string;
31
+ /** What its TSDoc says. */
32
+ readonly doc: string;
33
+ /** Whether it may be left out. */
34
+ readonly optional: boolean;
35
+ }
36
+
37
+ /** An export of an area. */
38
+ export interface ApiExport {
39
+ /** Its name, with its namespace before a dot where it is a namespace's (`fs.readTextFile`). */
40
+ readonly name: string;
41
+ /** What it is: more than one where a type and a value share the name. */
42
+ readonly kinds: readonly ExportKind[];
43
+ /** The file it is declared in, from the checkout's root. */
44
+ readonly file: string;
45
+ /** Its signature. */
46
+ readonly signature: string;
47
+ /** Its TSDoc. */
48
+ readonly doc: DocComment;
49
+ /** Whether it has any TSDoc at all. */
50
+ readonly documented: boolean;
51
+ /** The members of an interface or a class. */
52
+ readonly members: readonly ApiMember[];
53
+ /** The name it is declared with, where it is exported under another (`export { a as b }`). */
54
+ readonly declared?: string;
55
+ }
56
+
57
+ /** The API of an area: its exports, in the order its entry points export them. */
58
+ export interface AreaApi {
59
+ /** The area. */
60
+ readonly slug: string;
61
+ /** Its exports. */
62
+ readonly exports: readonly ApiExport[];
63
+ }
64
+
65
+ /** An area to read: its name and its entry points, from the checkout's root. */
66
+ export interface AreaEntry {
67
+ /** Its name in the site's addresses. */
68
+ readonly slug: string;
69
+ /** Its entry points, from the checkout's root. */
70
+ readonly entryPoints: readonly string[];
71
+ }
72
+
73
+ // The flags of a symbol, as TypeScript numbers them.
74
+ const FUNCTION = 16;
75
+ const CLASS = 32;
76
+ const INTERFACE = 64;
77
+ const ENUM = 384;
78
+ const VALUE_MODULE = 512;
79
+ const TYPE_ALIAS = 524288;
80
+ const ALIAS = 2097152;
81
+ const VARIABLE = 3;
82
+ const OPTIONAL = 16777216;
83
+ // A type printed whole: TypeFormatFlags.NoTruncation.
84
+ const NO_TRUNCATION = 1;
85
+
86
+ /** The kinds of a symbol, by its flags. */
87
+ export function kindsOf(flags: number): ExportKind[] {
88
+ const out: ExportKind[] = [];
89
+ if (flags & FUNCTION) out.push("function");
90
+ if (flags & CLASS) out.push("class");
91
+ if (flags & INTERFACE) out.push("interface");
92
+ if (flags & TYPE_ALIAS) out.push("type");
93
+ if (flags & ENUM) out.push("enum");
94
+ if (flags & VALUE_MODULE) out.push("namespace");
95
+ if (flags & VARIABLE && !(flags & (FUNCTION | CLASS))) out.push("const");
96
+ return out;
97
+ }
98
+
99
+ /**
100
+ * A function's type as a declaration: `<T>(a: A) => R` becomes `function name<T>(a: A): R`; anything else is kept, after the name.
101
+ *
102
+ * @param name - the function's name
103
+ * @param type - its type as the checker prints it
104
+ */
105
+ export function functionSignature(name: string, type: string): string {
106
+ let depth = 0;
107
+ let arrow = -1;
108
+ for (let i = 0; i < type.length; i++) {
109
+ const c = type[i];
110
+ if (c === "(" || c === "<" || c === "{" || c === "[") depth++;
111
+ else if ((c === ")" || c === ">" || c === "}" || c === "]") && type[i - 1] !== "=") depth--;
112
+ else if (c === "=" && type[i + 1] === ">" && depth === 0) {
113
+ arrow = i;
114
+ break;
115
+ }
116
+ }
117
+ if (arrow < 0 || !/^[<(]/.test(type)) return `function ${name}: ${type}`;
118
+ return `function ${name}${type.slice(0, arrow).trimEnd()}: ${type.slice(arrow + 2).trimStart()}`;
119
+ }
120
+
121
+ /** A declaration's source text without the comments and blank lines before it, nor `export` and `declare`. */
122
+ export function declarationText(source: string): string {
123
+ let s = source;
124
+ for (;;) {
125
+ const t = s.replace(/^\s+/, "");
126
+ if (t.startsWith("/*")) s = t.slice(t.indexOf("*/") + 2);
127
+ else if (t.startsWith("//")) s = t.slice(t.indexOf("\n") + 1 || t.length);
128
+ else {
129
+ s = t;
130
+ break;
131
+ }
132
+ }
133
+ return s.replace(/^export\s+(default\s+)?/, "").replace(/^declare\s+/, "").trimEnd();
134
+ }
135
+
136
+ /** The head of an interface or a class: its source up to the brace that opens its body. */
137
+ function headOf(text: string): string {
138
+ let depth = 0;
139
+ for (let i = 0; i < text.length; i++) {
140
+ const c = text[i];
141
+ if (c === "<" || c === "(") depth++;
142
+ else if (c === ">" || c === ")") depth--;
143
+ else if (c === "{" && depth === 0) return text.slice(0, i).trimEnd();
144
+ }
145
+ return text;
146
+ }
147
+
148
+ /** A tag as `tsdoc.ts` reads it, from the checker's tag. */
149
+ function tagOf(t: { readonly name: string; readonly text?: readonly { readonly text: string }[] | string | undefined }): DocTag {
150
+ const text = typeof t.text === "string" ? t.text : (t.text ?? []).map((p) => p.text).join("");
151
+ return { name: t.name, text };
152
+ }
153
+
154
+ /**
155
+ * The folders of types a program of the repository reads: the first that hold `@types/node`, from the repository's root, the folders
156
+ * given, and the generator's own.
157
+ *
158
+ * @param root - the repository's root
159
+ * @param dirs - more folders, from the root (the packages')
160
+ */
161
+ export function typeRootsOf(root: string, dirs: readonly string[] = []): string[] {
162
+ const own = path.join(path.dirname(path.dirname(path.fromFileUrl(import.meta.url))), "node_modules/@types");
163
+ const candidates = [path.join(root, "node_modules/@types"), ...dirs.map((d) => path.join(root, d, "node_modules/@types")), own];
164
+ return [...new Set(candidates)].filter((d) => fs.existsSync(path.join(d, "node")));
165
+ }
166
+
167
+ /**
168
+ * The API of each area, read in one program of all their entry points.
169
+ *
170
+ * @param root - the repository's root
171
+ * @param areas - the areas
172
+ * @param dirs - the folders, from the root, whose `node_modules/@types` may hold Node's types (the packages')
173
+ */
174
+ export async function readApi(root: string, areas: readonly AreaEntry[], dirs: readonly string[] = []): Promise<AreaApi[]> {
175
+ const abs = (rel: string): string => path.join(root, rel);
176
+ const relOf = (file: string): string => path.relative(root, file).split(path.sep).join("/");
177
+ const api = new API({ cwd: root });
178
+ const entries = areas.flatMap((a) => a.entryPoints.map(abs));
179
+ const typeRoots = typeRootsOf(root, dirs).slice(0, 1);
180
+ const program = await api.createProgram(entries, {
181
+ strict: true,
182
+ target: 99,
183
+ module: 199,
184
+ moduleResolution: 99,
185
+ allowImportingTsExtensions: true,
186
+ noEmit: true,
187
+ types: typeRoots.length === 0 ? [] : ["node"],
188
+ typeRoots,
189
+ });
190
+ const checker = program.getProject().checker;
191
+ // A declaration names its file by the compiler's key, which is lower case where the file system ignores case (macOS, Windows): the
192
+ // program's own file names give each key back its real spelling, so that the page of `src/Mod.ts` under `/var/folders/Ab/` is that.
193
+ const names = await program.getSourceFileNames();
194
+ const fileNames = new Map(names.map((f): readonly [string, string] => [program.getCanonicalFileName(f), f]));
195
+ const fileOf = (key: string): string => fileNames.get(key) ?? key;
196
+ const texts = new Map<string, string>();
197
+ const textOf = (file: string): string => {
198
+ const t = texts.get(file) ?? fs.readTextFileSync(file);
199
+ texts.set(file, t);
200
+ return t;
201
+ };
202
+ type Sym = Awaited<ReturnType<typeof checker.getExportsOfModule>>[number];
203
+
204
+ const sourceOf = async (s: Sym): Promise<{ file: string; text: string | undefined }> => {
205
+ const d = s.declarations[0];
206
+ if (d === undefined) return { file: "", text: undefined };
207
+ const file = fileOf(String(d.path));
208
+ const node = await d.resolve();
209
+ const full = textOf(file);
210
+ const pos = node !== undefined && "pos" in node && typeof node.pos === "number" ? node.pos : -1;
211
+ const end = node !== undefined && "end" in node && typeof node.end === "number" ? node.end : -1;
212
+ const text = pos >= 0 && end > pos ? declarationText(full.slice(pos, end)) : undefined;
213
+ return { file, text: text !== undefined && text.includes(s.name) ? text : undefined };
214
+ };
215
+
216
+ const docOfSymbol = async (s: Sym): Promise<{ doc: DocComment; documented: boolean }> => {
217
+ const summary = await checker.getDocumentationCommentOfSymbol(s);
218
+ const tags = (await checker.getJsDocTagsOfSymbol(s)).map(tagOf);
219
+ return { doc: docOf(summary, tags), documented: summary.trim() !== "" || tags.length > 0 };
220
+ };
221
+
222
+ const membersOf = async (s: Sym): Promise<ApiMember[]> => {
223
+ const declared = await checker.getDeclaredTypeOfSymbol(s);
224
+ const props = await checker.getPropertiesOfType(declared);
225
+ const out: ApiMember[] = [];
226
+ for (const p of props) {
227
+ if (p.name.startsWith("__#") || p.name.startsWith("#")) continue;
228
+ const optional = (p.flags & OPTIONAL) !== 0;
229
+ const type = await checker.typeToString(await checker.getTypeOfSymbol(p), undefined, NO_TRUNCATION);
230
+ out.push({
231
+ name: p.name,
232
+ type: optional ? type.replace(/ \| undefined$/, "") : type,
233
+ doc: (await checker.getDocumentationCommentOfSymbol(p)).trim(),
234
+ optional,
235
+ });
236
+ }
237
+ return out;
238
+ };
239
+
240
+ const exportOf = async (name: string, s: Sym): Promise<ApiExport | undefined> => {
241
+ const target = s.flags & ALIAS ? await checker.getAliasedSymbol(s) : s;
242
+ const kinds = kindsOf(target.flags);
243
+ if (kinds.length === 0) return undefined;
244
+ const { file, text } = await sourceOf(target);
245
+ let { doc, documented } = await docOfSymbol(target);
246
+ if (!documented && target.flags & VALUE_MODULE && file.endsWith(".ts")) {
247
+ // a namespace (`export * as docs from "./docs.ts"`) is documented by the module comment of the file it names
248
+ const module = moduleComment(textOf(file));
249
+ if (module !== undefined) ({ doc, documented } = { doc: module, documented: true });
250
+ }
251
+ let signature: string;
252
+ let members: ApiMember[] = [];
253
+ const typeText = async (): Promise<string> => checker.typeToString(await checker.getTypeOfSymbol(target), undefined, NO_TRUNCATION);
254
+ if (kinds.includes("function")) signature = functionSignature(name.split(".").pop() ?? name, await typeText());
255
+ else if (kinds.includes("interface") || kinds.includes("class")) {
256
+ signature = text === undefined ? `${kinds.includes("class") ? "class" : "interface"} ${name}` : headOf(text);
257
+ members = await membersOf(target);
258
+ if (kinds.includes("const")) signature = `${signature}\nconst ${name}: ${await typeText()}`;
259
+ } else if (kinds.includes("type")) {
260
+ signature = text ?? `type ${name}`;
261
+ if (kinds.includes("const")) signature = `${signature}\nconst ${name}: ${await typeText()}`;
262
+ } else if (kinds.includes("const")) signature = `const ${name.split(".").pop() ?? name}: ${await typeText()}`;
263
+ else signature = text ?? name;
264
+ const declared = target.name !== (name.split(".").pop() ?? name) ? { declared: target.name } : {};
265
+ return { name, kinds, file: relOf(file), signature, doc, documented, members, ...declared };
266
+ };
267
+
268
+ const out: AreaApi[] = [];
269
+ for (const area of areas) {
270
+ const exports: ApiExport[] = [];
271
+ for (const entry of area.entryPoints) {
272
+ const sf = await program.getSourceFile(abs(entry));
273
+ const mod = sf === undefined ? undefined : await checker.getSymbolAtLocation(sf);
274
+ if (mod === undefined) continue;
275
+ for (const s of await checker.getExportsOfModule(mod)) {
276
+ const target = s.flags & ALIAS ? await checker.getAliasedSymbol(s) : s;
277
+ if (target.flags & VALUE_MODULE && target.declarations[0]?.path !== undefined && String(target.declarations[0].path).endsWith(".ts")) {
278
+ const nsFile = fileOf(String(target.declarations[0].path));
279
+ const inner = await checker.getExportsOfModule(target);
280
+ const doc = moduleComment(textOf(nsFile)) ?? docOf("", []);
281
+ exports.push({ name: s.name, kinds: ["namespace"], file: relOf(nsFile), signature: `namespace ${s.name}`, doc, documented: doc.isModule, members: [] });
282
+ for (const i of inner) {
283
+ const e = await exportOf(`${s.name}.${i.name}`, i);
284
+ if (e !== undefined) exports.push(e);
285
+ }
286
+ continue;
287
+ }
288
+ const e = await exportOf(s.name, s);
289
+ if (e !== undefined) exports.push(e);
290
+ }
291
+ }
292
+ const seen = new Set<string>();
293
+ out.push({ slug: area.slug, exports: exports.filter((e) => (seen.has(e.name) ? false : (seen.add(e.name), true))) });
294
+ }
295
+ await api.close();
296
+ return out;
297
+ }
@@ -0,0 +1,299 @@
1
+ // Spec: 0001-docs FR-001
2
+ /**
3
+ * The spec kits read for the site (commons 0011-documentation FR-015, FR-024), in either of their two layouts. Commons' layout: the
4
+ * register of numbers, the register of what enforces each requirement, and each specification in force with its header (title, status,
5
+ * owner, domain, part), its `**Input:**` line, its requirements, success criteria and open questions, and its text; it reads what
6
+ * `commons/tools/mizan-check.ts` checks, and assumes the folder passes that check. The plain layout of Spec Kit: every folder of the
7
+ * specifications that holds a `spec.md`, its title, status and input where it has them, its requirements in either form
8
+ * (`- **FR-001** text` or `- **FR-001**: text`), the `reviewed.tsv` beside it, and the constitution.
9
+ *
10
+ * @module
11
+ */
12
+ import { fs, path } from "@intellectual-frontiers/system";
13
+ import type { Finding } from "../check.ts";
14
+ import { type SpecKitSource, under } from "../config.ts";
15
+
16
+ /** How a requirement is enforced, as `enforcement.tsv` says, or `review` where a `reviewed.tsv` gives its reason. */
17
+ export type Mechanism = "check" | "gate" | "review" | "none";
18
+
19
+ /** A row of `enforcement.tsv`, or of a `reviewed.tsv`. */
20
+ export interface Enforcement {
21
+ /** The requirement, as `0009-example FR-001`. */
22
+ readonly requirement: string;
23
+ /** How. */
24
+ readonly mechanism: Mechanism;
25
+ /** Who: `<repository>: <command>`, a requirement that defines the review, or `-`. */
26
+ readonly by: string;
27
+ /** The note, or the reason of a review. */
28
+ readonly note: string;
29
+ }
30
+
31
+ /** A numbered item of a specification: a requirement, a success criterion or an open question, and its text. */
32
+ export interface SpecItem {
33
+ /** `FR-001`, `SC-001` or `OQ-1`. */
34
+ readonly id: string;
35
+ /** Its text, after the number, as Markdown. */
36
+ readonly text: string;
37
+ }
38
+
39
+ /** The layout a specification was read in. */
40
+ export type Layout = SpecKitSource["layout"];
41
+
42
+ /** A specification in force. */
43
+ export interface Spec {
44
+ /** Its folder's name: `0009-example`. */
45
+ readonly id: string;
46
+ /** Its `spec.md`, from the root. */
47
+ readonly file: string;
48
+ /** The layout of its spec kit. */
49
+ readonly layout: Layout;
50
+ /** Its title, after `# Feature Specification: ` (or, in the plain layout, after `# NNN: `). */
51
+ readonly title: string;
52
+ /** `Draft`, `Adopted`, `Superseded`, or what a plain specification says; empty where it says nothing. */
53
+ readonly status: string;
54
+ /** Its owner, where it says. */
55
+ readonly owner: string;
56
+ /** Its domain, where it says. */
57
+ readonly domain: string;
58
+ /** The specification it is part of, where it says. */
59
+ readonly partOf?: string;
60
+ /** Its `**Input:**` line, as Markdown; empty where it has none. */
61
+ readonly input: string;
62
+ /** Its text after the header and the input, as Markdown. */
63
+ readonly body: string;
64
+ /** Its requirements, in order. */
65
+ readonly requirements: readonly SpecItem[];
66
+ }
67
+
68
+ /** Where a spec kit's specifications come from, as the register and the matrix say it. */
69
+ export interface KitSource {
70
+ /** Its layout. */
71
+ readonly layout: Layout;
72
+ /** Its folder, from the root. */
73
+ readonly dir: string;
74
+ }
75
+
76
+ /** A constitution: its file, its title and its text after the title. */
77
+ export interface Constitution {
78
+ /** Its file, from the root. */
79
+ readonly file: string;
80
+ /** Its title, from its first heading. */
81
+ readonly title: string;
82
+ /** Its text after the title, as Markdown. */
83
+ readonly body: string;
84
+ }
85
+
86
+ /** The spec kits: their specifications in force, in order, the enforcement of each requirement, where they come from, and a constitution. */
87
+ export interface SpecKit {
88
+ /** The specifications in force. */
89
+ readonly specs: readonly Spec[];
90
+ /** The rows of `enforcement.tsv` and of every `reviewed.tsv`, by requirement. */
91
+ readonly enforcement: ReadonlyMap<string, Enforcement>;
92
+ /** The kits read, in order. */
93
+ readonly sources: readonly KitSource[];
94
+ /** The constitution of a plain kit, where it has one. */
95
+ readonly constitution?: Constitution;
96
+ }
97
+
98
+ /** One spec kit read: its specifications, its enforcement, and its constitution where it has one. */
99
+ export interface KitRead {
100
+ /** The specifications in force, in order. */
101
+ readonly specs: readonly Spec[];
102
+ /** The rows of its enforcement, by requirement. */
103
+ readonly enforcement: ReadonlyMap<string, Enforcement>;
104
+ /** Its constitution. */
105
+ readonly constitution?: Constitution;
106
+ }
107
+
108
+ const MECHANISMS: readonly Mechanism[] = ["check", "gate", "review", "none"];
109
+ const isMechanism = (s: string): s is Mechanism => MECHANISMS.some((m) => m === s);
110
+
111
+ /** The value of a header line, `**Label:** value`. */
112
+ function header(text: string, label: string): string | undefined {
113
+ const m = new RegExp(`^\\*\\*${label}:\\*\\*[ \\t]*(.*?)[ \\t]*$`, "m").exec(text);
114
+ return m?.[1];
115
+ }
116
+
117
+ /** The requirements of a specification's text: `- **FR-001**: text` or `- **FR-001** text`, on one line or more. */
118
+ export function requirementsOf(body: string): SpecItem[] {
119
+ return [...body.matchAll(/^- \*\*(FR-\d{3}[a-z]?)\*\*:?[ \t]*([\s\S]*?)(?=\n- |\n\n|\n#|(?![\s\S]))/gm)].map((m) => ({
120
+ id: m[1] ?? "",
121
+ text: (m[2] ?? "").replace(/\n\s+/g, " ").trim(),
122
+ }));
123
+ }
124
+
125
+ /**
126
+ * A specification of commons' layout read into its parts.
127
+ *
128
+ * @param id - its folder's name
129
+ * @param text - the text of its `spec.md`
130
+ * @param file - its `spec.md`, from the root
131
+ */
132
+ export function parseSpec(id: string, text: string, file = `${id}/spec.md`): Spec {
133
+ const title = /^# Feature Specification: (.*)$/m.exec(text)?.[1]?.trim() ?? id;
134
+ const inputAt = text.search(/^\*\*Input:\*\*/m);
135
+ const afterInput = inputAt < 0 ? -1 : text.indexOf("\n\n", inputAt);
136
+ const input = inputAt < 0 ? "" : text.slice(inputAt, afterInput < 0 ? text.length : afterInput).replace(/^\*\*Input:\*\*\s*/, "").trim();
137
+ const body = afterInput < 0 ? "" : text.slice(afterInput).trim();
138
+ const partOf = header(text, "Part of");
139
+ return {
140
+ id,
141
+ file,
142
+ layout: "commons",
143
+ title,
144
+ status: header(text, "Status") ?? "",
145
+ owner: header(text, "Owner") ?? "",
146
+ domain: header(text, "Domain") ?? "",
147
+ ...(partOf === undefined ? {} : { partOf }),
148
+ input,
149
+ body,
150
+ requirements: requirementsOf(body),
151
+ };
152
+ }
153
+
154
+ /** The value after a bold label in a header paragraph (`**Status**: Implemented`, `**Status:** Draft`), up to the next label. */
155
+ function field(para: string, label: string): string | undefined {
156
+ const m = new RegExp(`\\*\\*${label}(?:\\*\\*:|:\\*\\*)\\s*([\\s\\S]*?)\\s*(?=\\*\\*[A-Z][\\w ]*(?:\\*\\*:|:\\*\\*)|$)`).exec(para);
157
+ return m?.[1]?.replace(/\s+/g, " ").trim();
158
+ }
159
+
160
+ /**
161
+ * A specification of the plain layout of Spec Kit read into its parts: the title from its first heading, the status and input of the
162
+ * header paragraph where it has one, and its requirements in either form.
163
+ *
164
+ * @param id - its folder's name
165
+ * @param text - the text of its `spec.md`
166
+ * @param file - its `spec.md`, from the root
167
+ */
168
+ export function parsePlainSpec(id: string, text: string, file = `${id}/spec.md`): Spec {
169
+ const heading = /^# (.*)$/m.exec(text);
170
+ const title = (heading?.[1] ?? id).replace(/^Feature Specification:\s*/, "").replace(/^\d+:\s*/, "").trim();
171
+ const rest = heading === null ? text : text.slice(heading.index + heading[0].length);
172
+ const firstSection = rest.search(/^## /m);
173
+ const lead = firstSection < 0 ? rest : rest.slice(0, firstSection);
174
+ const paras = lead.split(/\n\s*\n/);
175
+ const headerAt = paras.findIndex((p) => /\*\*(?:Status|Input)(?:\*\*:|:\*\*)/.test(p));
176
+ const para = headerAt < 0 ? "" : paras[headerAt] ?? "";
177
+ const body = (headerAt < 0 ? rest : [...paras.slice(0, headerAt), ...paras.slice(headerAt + 1)].join("\n\n") + (firstSection < 0 ? "" : `\n\n${rest.slice(firstSection)}`)).trim();
178
+ const status = field(para, "Status")?.replace(/[.;,]$/, "") ?? "";
179
+ return {
180
+ id,
181
+ file,
182
+ layout: "spec-kit",
183
+ title,
184
+ status: /^[A-Za-z][\w -]{0,40}$/.test(status) ? status : "",
185
+ owner: "",
186
+ domain: "",
187
+ input: field(para, "Input") ?? "",
188
+ body,
189
+ requirements: requirementsOf(body),
190
+ };
191
+ }
192
+
193
+ /**
194
+ * The rows of `enforcement.tsv`.
195
+ *
196
+ * @param text - its text
197
+ */
198
+ export function parseEnforcement(text: string): Map<string, Enforcement> {
199
+ const out = new Map<string, Enforcement>();
200
+ for (const line of text.split("\n")) {
201
+ if (line === "" || line.startsWith("#") || line.startsWith("requirement\t")) continue;
202
+ const [requirement, mechanism, by, note] = line.split("\t");
203
+ if (requirement === undefined || mechanism === undefined || !isMechanism(mechanism)) continue;
204
+ out.set(requirement, { requirement, mechanism, by: by ?? "-", note: note ?? "" });
205
+ }
206
+ return out;
207
+ }
208
+
209
+ /**
210
+ * The rows of a `reviewed.tsv`: a requirement (`FR-003`, or `096-bun-runtime FR-003`), a tab and the reason it is proven by review.
211
+ *
212
+ * @param id - the specification beside which it is
213
+ * @param text - its text
214
+ */
215
+ export function parseReviewed(id: string, text: string): Map<string, Enforcement> {
216
+ const out = new Map<string, Enforcement>();
217
+ for (const line of text.split("\n")) {
218
+ if (line.trim() === "" || line.startsWith("#")) continue;
219
+ const [first = "", ...rest] = line.split("\t");
220
+ const fr = /(?:^|\s)(FR-\d{3}[a-z]?)$/.exec(first.trim())?.[1];
221
+ const spec = first.trim().includes(" ") ? first.trim().split(/\s+/)[0] : id;
222
+ if (fr === undefined || spec !== id) continue;
223
+ const requirement = `${id} ${fr}`;
224
+ out.set(requirement, { requirement, mechanism: "review", by: "-", note: rest.join("\t").trim() });
225
+ }
226
+ return out;
227
+ }
228
+
229
+ /**
230
+ * A spec kit of commons' layout: its specifications in force, in the register's order, and its enforcement.
231
+ *
232
+ * @param root - the repository's root
233
+ * @param dir - the kit's folder, from the root (`commons/spec-kit`)
234
+ */
235
+ export function readCommonsKit(root: string, dir: string): KitRead {
236
+ const abs = path.join(root, dir);
237
+ const specs: Spec[] = [];
238
+ for (const line of fs.readTextFileSync(path.join(abs, "registry.tsv")).split("\n").slice(1)) {
239
+ const [number, slug, state] = line.split("\t");
240
+ if (number === undefined || slug === undefined || state !== "in force") continue;
241
+ const id = `${number}-${slug}`;
242
+ const file = under(dir, `specs/${id}/spec.md`);
243
+ specs.push(parseSpec(id, fs.readTextFileSync(path.join(root, file)), file));
244
+ }
245
+ return { specs, enforcement: parseEnforcement(fs.readTextFileSync(path.join(abs, "enforcement.tsv"))) };
246
+ }
247
+
248
+ /**
249
+ * A spec kit of the plain layout: every folder `NNN-slug/` of the folder that holds a `spec.md`, in the order of their names, the rows of
250
+ * the `reviewed.tsv` beside each, and the constitution where it exists.
251
+ *
252
+ * @param root - the repository's root
253
+ * @param dir - the folder of the specifications, from the root (`specs`)
254
+ * @param constitution - the constitution, from the root, where there is one
255
+ */
256
+ export function readPlainKit(root: string, dir: string, constitution: string | undefined): KitRead {
257
+ const abs = path.join(root, dir);
258
+ const specs: Spec[] = [];
259
+ const enforcement = new Map<string, Enforcement>();
260
+ const names = fs.existsSync(abs) ? [...fs.readDirSync(abs)].filter((e) => e.isDirectory && /^\d+-[a-z]/.test(e.name)).map((e) => e.name).sort() : [];
261
+ for (const id of names) {
262
+ const file = under(dir, `${id}/spec.md`);
263
+ if (!fs.existsSync(path.join(root, file))) continue;
264
+ specs.push(parsePlainSpec(id, fs.readTextFileSync(path.join(root, file)), file));
265
+ const reviewed = path.join(root, under(dir, `${id}/reviewed.tsv`));
266
+ if (fs.existsSync(reviewed)) for (const [k, v] of parseReviewed(id, fs.readTextFileSync(reviewed))) enforcement.set(k, v);
267
+ }
268
+ if (constitution === undefined || !fs.existsSync(path.join(root, constitution))) return { specs, enforcement };
269
+ const text = fs.readTextFileSync(path.join(root, constitution));
270
+ const heading = /^# (.*)$/m.exec(text);
271
+ const title = heading?.[1]?.trim() ?? "Constitution";
272
+ const body = (heading === null ? text : text.slice(heading.index + heading[0].length)).trim();
273
+ return { specs, enforcement, constitution: { file: constitution, title, body } };
274
+ }
275
+
276
+ /**
277
+ * The spec kits of a configuration, read and merged in order; a specification a kit before already holds is a finding, and is left out.
278
+ *
279
+ * @param root - the repository's root
280
+ * @param kits - the kits
281
+ * @param found - where findings go
282
+ */
283
+ export function readSpecKits(root: string, kits: readonly SpecKitSource[], found: Finding[] = []): SpecKit {
284
+ const specs: Spec[] = [];
285
+ const enforcement = new Map<string, Enforcement>();
286
+ let constitution: Constitution | undefined;
287
+ for (const k of kits) {
288
+ const read: KitRead = k.layout === "commons" ? readCommonsKit(root, k.dir) : readPlainKit(root, k.dir, k.constitution);
289
+ for (const s of read.specs) {
290
+ if (specs.some((x) => x.id === s.id)) found.push({ where: s.file, problem: { kind: "duplicate-spec", id: s.id } });
291
+ else specs.push(s);
292
+ }
293
+ for (const [key, v] of read.enforcement) if (!enforcement.has(key)) enforcement.set(key, v);
294
+ if (constitution === undefined) constitution = read.constitution;
295
+ }
296
+ const sources = kits.map((k) => ({ layout: k.layout, dir: k.dir }));
297
+ return constitution === undefined ? { specs, enforcement, sources } : { specs, enforcement, sources, constitution };
298
+ }
299
+