@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,261 @@
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 { docOf, moduleComment } from "../tsdoc.js";
21
+ // The flags of a symbol, as TypeScript numbers them.
22
+ const FUNCTION = 16;
23
+ const CLASS = 32;
24
+ const INTERFACE = 64;
25
+ const ENUM = 384;
26
+ const VALUE_MODULE = 512;
27
+ const TYPE_ALIAS = 524288;
28
+ const ALIAS = 2097152;
29
+ const VARIABLE = 3;
30
+ const OPTIONAL = 16777216;
31
+ // A type printed whole: TypeFormatFlags.NoTruncation.
32
+ const NO_TRUNCATION = 1;
33
+ /** The kinds of a symbol, by its flags. */
34
+ export function kindsOf(flags) {
35
+ const out = [];
36
+ if (flags & FUNCTION)
37
+ out.push("function");
38
+ if (flags & CLASS)
39
+ out.push("class");
40
+ if (flags & INTERFACE)
41
+ out.push("interface");
42
+ if (flags & TYPE_ALIAS)
43
+ out.push("type");
44
+ if (flags & ENUM)
45
+ out.push("enum");
46
+ if (flags & VALUE_MODULE)
47
+ out.push("namespace");
48
+ if (flags & VARIABLE && !(flags & (FUNCTION | CLASS)))
49
+ out.push("const");
50
+ return out;
51
+ }
52
+ /**
53
+ * 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.
54
+ *
55
+ * @param name - the function's name
56
+ * @param type - its type as the checker prints it
57
+ */
58
+ export function functionSignature(name, type) {
59
+ let depth = 0;
60
+ let arrow = -1;
61
+ for (let i = 0; i < type.length; i++) {
62
+ const c = type[i];
63
+ if (c === "(" || c === "<" || c === "{" || c === "[")
64
+ depth++;
65
+ else if ((c === ")" || c === ">" || c === "}" || c === "]") && type[i - 1] !== "=")
66
+ depth--;
67
+ else if (c === "=" && type[i + 1] === ">" && depth === 0) {
68
+ arrow = i;
69
+ break;
70
+ }
71
+ }
72
+ if (arrow < 0 || !/^[<(]/.test(type))
73
+ return `function ${name}: ${type}`;
74
+ return `function ${name}${type.slice(0, arrow).trimEnd()}: ${type.slice(arrow + 2).trimStart()}`;
75
+ }
76
+ /** A declaration's source text without the comments and blank lines before it, nor `export` and `declare`. */
77
+ export function declarationText(source) {
78
+ let s = source;
79
+ for (;;) {
80
+ const t = s.replace(/^\s+/, "");
81
+ if (t.startsWith("/*"))
82
+ s = t.slice(t.indexOf("*/") + 2);
83
+ else if (t.startsWith("//"))
84
+ s = t.slice(t.indexOf("\n") + 1 || t.length);
85
+ else {
86
+ s = t;
87
+ break;
88
+ }
89
+ }
90
+ return s.replace(/^export\s+(default\s+)?/, "").replace(/^declare\s+/, "").trimEnd();
91
+ }
92
+ /** The head of an interface or a class: its source up to the brace that opens its body. */
93
+ function headOf(text) {
94
+ let depth = 0;
95
+ for (let i = 0; i < text.length; i++) {
96
+ const c = text[i];
97
+ if (c === "<" || c === "(")
98
+ depth++;
99
+ else if (c === ">" || c === ")")
100
+ depth--;
101
+ else if (c === "{" && depth === 0)
102
+ return text.slice(0, i).trimEnd();
103
+ }
104
+ return text;
105
+ }
106
+ /** A tag as `tsdoc.ts` reads it, from the checker's tag. */
107
+ function tagOf(t) {
108
+ const text = typeof t.text === "string" ? t.text : (t.text ?? []).map((p) => p.text).join("");
109
+ return { name: t.name, text };
110
+ }
111
+ /**
112
+ * The folders of types a program of the repository reads: the first that hold `@types/node`, from the repository's root, the folders
113
+ * given, and the generator's own.
114
+ *
115
+ * @param root - the repository's root
116
+ * @param dirs - more folders, from the root (the packages')
117
+ */
118
+ export function typeRootsOf(root, dirs = []) {
119
+ const own = path.join(path.dirname(path.dirname(path.fromFileUrl(import.meta.url))), "node_modules/@types");
120
+ const candidates = [path.join(root, "node_modules/@types"), ...dirs.map((d) => path.join(root, d, "node_modules/@types")), own];
121
+ return [...new Set(candidates)].filter((d) => fs.existsSync(path.join(d, "node")));
122
+ }
123
+ /**
124
+ * The API of each area, read in one program of all their entry points.
125
+ *
126
+ * @param root - the repository's root
127
+ * @param areas - the areas
128
+ * @param dirs - the folders, from the root, whose `node_modules/@types` may hold Node's types (the packages')
129
+ */
130
+ export async function readApi(root, areas, dirs = []) {
131
+ const abs = (rel) => path.join(root, rel);
132
+ const relOf = (file) => path.relative(root, file).split(path.sep).join("/");
133
+ const api = new API({ cwd: root });
134
+ const entries = areas.flatMap((a) => a.entryPoints.map(abs));
135
+ const typeRoots = typeRootsOf(root, dirs).slice(0, 1);
136
+ const program = await api.createProgram(entries, {
137
+ strict: true,
138
+ target: 99,
139
+ module: 199,
140
+ moduleResolution: 99,
141
+ allowImportingTsExtensions: true,
142
+ noEmit: true,
143
+ types: typeRoots.length === 0 ? [] : ["node"],
144
+ typeRoots,
145
+ });
146
+ const checker = program.getProject().checker;
147
+ // A declaration names its file by the compiler's key, which is lower case where the file system ignores case (macOS, Windows): the
148
+ // 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.
149
+ const names = await program.getSourceFileNames();
150
+ const fileNames = new Map(names.map((f) => [program.getCanonicalFileName(f), f]));
151
+ const fileOf = (key) => fileNames.get(key) ?? key;
152
+ const texts = new Map();
153
+ const textOf = (file) => {
154
+ const t = texts.get(file) ?? fs.readTextFileSync(file);
155
+ texts.set(file, t);
156
+ return t;
157
+ };
158
+ const sourceOf = async (s) => {
159
+ const d = s.declarations[0];
160
+ if (d === undefined)
161
+ return { file: "", text: undefined };
162
+ const file = fileOf(String(d.path));
163
+ const node = await d.resolve();
164
+ const full = textOf(file);
165
+ const pos = node !== undefined && "pos" in node && typeof node.pos === "number" ? node.pos : -1;
166
+ const end = node !== undefined && "end" in node && typeof node.end === "number" ? node.end : -1;
167
+ const text = pos >= 0 && end > pos ? declarationText(full.slice(pos, end)) : undefined;
168
+ return { file, text: text !== undefined && text.includes(s.name) ? text : undefined };
169
+ };
170
+ const docOfSymbol = async (s) => {
171
+ const summary = await checker.getDocumentationCommentOfSymbol(s);
172
+ const tags = (await checker.getJsDocTagsOfSymbol(s)).map(tagOf);
173
+ return { doc: docOf(summary, tags), documented: summary.trim() !== "" || tags.length > 0 };
174
+ };
175
+ const membersOf = async (s) => {
176
+ const declared = await checker.getDeclaredTypeOfSymbol(s);
177
+ const props = await checker.getPropertiesOfType(declared);
178
+ const out = [];
179
+ for (const p of props) {
180
+ if (p.name.startsWith("__#") || p.name.startsWith("#"))
181
+ continue;
182
+ const optional = (p.flags & OPTIONAL) !== 0;
183
+ const type = await checker.typeToString(await checker.getTypeOfSymbol(p), undefined, NO_TRUNCATION);
184
+ out.push({
185
+ name: p.name,
186
+ type: optional ? type.replace(/ \| undefined$/, "") : type,
187
+ doc: (await checker.getDocumentationCommentOfSymbol(p)).trim(),
188
+ optional,
189
+ });
190
+ }
191
+ return out;
192
+ };
193
+ const exportOf = async (name, s) => {
194
+ const target = s.flags & ALIAS ? await checker.getAliasedSymbol(s) : s;
195
+ const kinds = kindsOf(target.flags);
196
+ if (kinds.length === 0)
197
+ return undefined;
198
+ const { file, text } = await sourceOf(target);
199
+ let { doc, documented } = await docOfSymbol(target);
200
+ if (!documented && target.flags & VALUE_MODULE && file.endsWith(".ts")) {
201
+ // a namespace (`export * as docs from "./docs.ts"`) is documented by the module comment of the file it names
202
+ const module = moduleComment(textOf(file));
203
+ if (module !== undefined)
204
+ ({ doc, documented } = { doc: module, documented: true });
205
+ }
206
+ let signature;
207
+ let members = [];
208
+ const typeText = async () => checker.typeToString(await checker.getTypeOfSymbol(target), undefined, NO_TRUNCATION);
209
+ if (kinds.includes("function"))
210
+ signature = functionSignature(name.split(".").pop() ?? name, await typeText());
211
+ else if (kinds.includes("interface") || kinds.includes("class")) {
212
+ signature = text === undefined ? `${kinds.includes("class") ? "class" : "interface"} ${name}` : headOf(text);
213
+ members = await membersOf(target);
214
+ if (kinds.includes("const"))
215
+ signature = `${signature}\nconst ${name}: ${await typeText()}`;
216
+ }
217
+ else if (kinds.includes("type")) {
218
+ signature = text ?? `type ${name}`;
219
+ if (kinds.includes("const"))
220
+ signature = `${signature}\nconst ${name}: ${await typeText()}`;
221
+ }
222
+ else if (kinds.includes("const"))
223
+ signature = `const ${name.split(".").pop() ?? name}: ${await typeText()}`;
224
+ else
225
+ signature = text ?? name;
226
+ const declared = target.name !== (name.split(".").pop() ?? name) ? { declared: target.name } : {};
227
+ return { name, kinds, file: relOf(file), signature, doc, documented, members, ...declared };
228
+ };
229
+ const out = [];
230
+ for (const area of areas) {
231
+ const exports = [];
232
+ for (const entry of area.entryPoints) {
233
+ const sf = await program.getSourceFile(abs(entry));
234
+ const mod = sf === undefined ? undefined : await checker.getSymbolAtLocation(sf);
235
+ if (mod === undefined)
236
+ continue;
237
+ for (const s of await checker.getExportsOfModule(mod)) {
238
+ const target = s.flags & ALIAS ? await checker.getAliasedSymbol(s) : s;
239
+ if (target.flags & VALUE_MODULE && target.declarations[0]?.path !== undefined && String(target.declarations[0].path).endsWith(".ts")) {
240
+ const nsFile = fileOf(String(target.declarations[0].path));
241
+ const inner = await checker.getExportsOfModule(target);
242
+ const doc = moduleComment(textOf(nsFile)) ?? docOf("", []);
243
+ exports.push({ name: s.name, kinds: ["namespace"], file: relOf(nsFile), signature: `namespace ${s.name}`, doc, documented: doc.isModule, members: [] });
244
+ for (const i of inner) {
245
+ const e = await exportOf(`${s.name}.${i.name}`, i);
246
+ if (e !== undefined)
247
+ exports.push(e);
248
+ }
249
+ continue;
250
+ }
251
+ const e = await exportOf(s.name, s);
252
+ if (e !== undefined)
253
+ exports.push(e);
254
+ }
255
+ }
256
+ const seen = new Set();
257
+ out.push({ slug: area.slug, exports: exports.filter((e) => (seen.has(e.name) ? false : (seen.add(e.name), true))) });
258
+ }
259
+ await api.close();
260
+ return out;
261
+ }
@@ -0,0 +1,141 @@
1
+ import type { Finding } from "../check.js";
2
+ import { type SpecKitSource } from "../config.js";
3
+ /** How a requirement is enforced, as `enforcement.tsv` says, or `review` where a `reviewed.tsv` gives its reason. */
4
+ export type Mechanism = "check" | "gate" | "review" | "none";
5
+ /** A row of `enforcement.tsv`, or of a `reviewed.tsv`. */
6
+ export interface Enforcement {
7
+ /** The requirement, as `0009-example FR-001`. */
8
+ readonly requirement: string;
9
+ /** How. */
10
+ readonly mechanism: Mechanism;
11
+ /** Who: `<repository>: <command>`, a requirement that defines the review, or `-`. */
12
+ readonly by: string;
13
+ /** The note, or the reason of a review. */
14
+ readonly note: string;
15
+ }
16
+ /** A numbered item of a specification: a requirement, a success criterion or an open question, and its text. */
17
+ export interface SpecItem {
18
+ /** `FR-001`, `SC-001` or `OQ-1`. */
19
+ readonly id: string;
20
+ /** Its text, after the number, as Markdown. */
21
+ readonly text: string;
22
+ }
23
+ /** The layout a specification was read in. */
24
+ export type Layout = SpecKitSource["layout"];
25
+ /** A specification in force. */
26
+ export interface Spec {
27
+ /** Its folder's name: `0009-example`. */
28
+ readonly id: string;
29
+ /** Its `spec.md`, from the root. */
30
+ readonly file: string;
31
+ /** The layout of its spec kit. */
32
+ readonly layout: Layout;
33
+ /** Its title, after `# Feature Specification: ` (or, in the plain layout, after `# NNN: `). */
34
+ readonly title: string;
35
+ /** `Draft`, `Adopted`, `Superseded`, or what a plain specification says; empty where it says nothing. */
36
+ readonly status: string;
37
+ /** Its owner, where it says. */
38
+ readonly owner: string;
39
+ /** Its domain, where it says. */
40
+ readonly domain: string;
41
+ /** The specification it is part of, where it says. */
42
+ readonly partOf?: string;
43
+ /** Its `**Input:**` line, as Markdown; empty where it has none. */
44
+ readonly input: string;
45
+ /** Its text after the header and the input, as Markdown. */
46
+ readonly body: string;
47
+ /** Its requirements, in order. */
48
+ readonly requirements: readonly SpecItem[];
49
+ }
50
+ /** Where a spec kit's specifications come from, as the register and the matrix say it. */
51
+ export interface KitSource {
52
+ /** Its layout. */
53
+ readonly layout: Layout;
54
+ /** Its folder, from the root. */
55
+ readonly dir: string;
56
+ }
57
+ /** A constitution: its file, its title and its text after the title. */
58
+ export interface Constitution {
59
+ /** Its file, from the root. */
60
+ readonly file: string;
61
+ /** Its title, from its first heading. */
62
+ readonly title: string;
63
+ /** Its text after the title, as Markdown. */
64
+ readonly body: string;
65
+ }
66
+ /** The spec kits: their specifications in force, in order, the enforcement of each requirement, where they come from, and a constitution. */
67
+ export interface SpecKit {
68
+ /** The specifications in force. */
69
+ readonly specs: readonly Spec[];
70
+ /** The rows of `enforcement.tsv` and of every `reviewed.tsv`, by requirement. */
71
+ readonly enforcement: ReadonlyMap<string, Enforcement>;
72
+ /** The kits read, in order. */
73
+ readonly sources: readonly KitSource[];
74
+ /** The constitution of a plain kit, where it has one. */
75
+ readonly constitution?: Constitution;
76
+ }
77
+ /** One spec kit read: its specifications, its enforcement, and its constitution where it has one. */
78
+ export interface KitRead {
79
+ /** The specifications in force, in order. */
80
+ readonly specs: readonly Spec[];
81
+ /** The rows of its enforcement, by requirement. */
82
+ readonly enforcement: ReadonlyMap<string, Enforcement>;
83
+ /** Its constitution. */
84
+ readonly constitution?: Constitution;
85
+ }
86
+ /** The requirements of a specification's text: `- **FR-001**: text` or `- **FR-001** text`, on one line or more. */
87
+ export declare function requirementsOf(body: string): SpecItem[];
88
+ /**
89
+ * A specification of commons' layout read into its parts.
90
+ *
91
+ * @param id - its folder's name
92
+ * @param text - the text of its `spec.md`
93
+ * @param file - its `spec.md`, from the root
94
+ */
95
+ export declare function parseSpec(id: string, text: string, file?: string): Spec;
96
+ /**
97
+ * 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
98
+ * header paragraph where it has one, and its requirements in either form.
99
+ *
100
+ * @param id - its folder's name
101
+ * @param text - the text of its `spec.md`
102
+ * @param file - its `spec.md`, from the root
103
+ */
104
+ export declare function parsePlainSpec(id: string, text: string, file?: string): Spec;
105
+ /**
106
+ * The rows of `enforcement.tsv`.
107
+ *
108
+ * @param text - its text
109
+ */
110
+ export declare function parseEnforcement(text: string): Map<string, Enforcement>;
111
+ /**
112
+ * 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.
113
+ *
114
+ * @param id - the specification beside which it is
115
+ * @param text - its text
116
+ */
117
+ export declare function parseReviewed(id: string, text: string): Map<string, Enforcement>;
118
+ /**
119
+ * A spec kit of commons' layout: its specifications in force, in the register's order, and its enforcement.
120
+ *
121
+ * @param root - the repository's root
122
+ * @param dir - the kit's folder, from the root (`commons/spec-kit`)
123
+ */
124
+ export declare function readCommonsKit(root: string, dir: string): KitRead;
125
+ /**
126
+ * 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
127
+ * the `reviewed.tsv` beside each, and the constitution where it exists.
128
+ *
129
+ * @param root - the repository's root
130
+ * @param dir - the folder of the specifications, from the root (`specs`)
131
+ * @param constitution - the constitution, from the root, where there is one
132
+ */
133
+ export declare function readPlainKit(root: string, dir: string, constitution: string | undefined): KitRead;
134
+ /**
135
+ * 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.
136
+ *
137
+ * @param root - the repository's root
138
+ * @param kits - the kits
139
+ * @param found - where findings go
140
+ */
141
+ export declare function readSpecKits(root: string, kits: readonly SpecKitSource[], found?: Finding[]): SpecKit;
@@ -0,0 +1,208 @@
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 { under } from "../config.js";
14
+ const MECHANISMS = ["check", "gate", "review", "none"];
15
+ const isMechanism = (s) => MECHANISMS.some((m) => m === s);
16
+ /** The value of a header line, `**Label:** value`. */
17
+ function header(text, label) {
18
+ const m = new RegExp(`^\\*\\*${label}:\\*\\*[ \\t]*(.*?)[ \\t]*$`, "m").exec(text);
19
+ return m?.[1];
20
+ }
21
+ /** The requirements of a specification's text: `- **FR-001**: text` or `- **FR-001** text`, on one line or more. */
22
+ export function requirementsOf(body) {
23
+ return [...body.matchAll(/^- \*\*(FR-\d{3}[a-z]?)\*\*:?[ \t]*([\s\S]*?)(?=\n- |\n\n|\n#|(?![\s\S]))/gm)].map((m) => ({
24
+ id: m[1] ?? "",
25
+ text: (m[2] ?? "").replace(/\n\s+/g, " ").trim(),
26
+ }));
27
+ }
28
+ /**
29
+ * A specification of commons' layout read into its parts.
30
+ *
31
+ * @param id - its folder's name
32
+ * @param text - the text of its `spec.md`
33
+ * @param file - its `spec.md`, from the root
34
+ */
35
+ export function parseSpec(id, text, file = `${id}/spec.md`) {
36
+ const title = /^# Feature Specification: (.*)$/m.exec(text)?.[1]?.trim() ?? id;
37
+ const inputAt = text.search(/^\*\*Input:\*\*/m);
38
+ const afterInput = inputAt < 0 ? -1 : text.indexOf("\n\n", inputAt);
39
+ const input = inputAt < 0 ? "" : text.slice(inputAt, afterInput < 0 ? text.length : afterInput).replace(/^\*\*Input:\*\*\s*/, "").trim();
40
+ const body = afterInput < 0 ? "" : text.slice(afterInput).trim();
41
+ const partOf = header(text, "Part of");
42
+ return {
43
+ id,
44
+ file,
45
+ layout: "commons",
46
+ title,
47
+ status: header(text, "Status") ?? "",
48
+ owner: header(text, "Owner") ?? "",
49
+ domain: header(text, "Domain") ?? "",
50
+ ...(partOf === undefined ? {} : { partOf }),
51
+ input,
52
+ body,
53
+ requirements: requirementsOf(body),
54
+ };
55
+ }
56
+ /** The value after a bold label in a header paragraph (`**Status**: Implemented`, `**Status:** Draft`), up to the next label. */
57
+ function field(para, label) {
58
+ const m = new RegExp(`\\*\\*${label}(?:\\*\\*:|:\\*\\*)\\s*([\\s\\S]*?)\\s*(?=\\*\\*[A-Z][\\w ]*(?:\\*\\*:|:\\*\\*)|$)`).exec(para);
59
+ return m?.[1]?.replace(/\s+/g, " ").trim();
60
+ }
61
+ /**
62
+ * 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
63
+ * header paragraph where it has one, and its requirements in either form.
64
+ *
65
+ * @param id - its folder's name
66
+ * @param text - the text of its `spec.md`
67
+ * @param file - its `spec.md`, from the root
68
+ */
69
+ export function parsePlainSpec(id, text, file = `${id}/spec.md`) {
70
+ const heading = /^# (.*)$/m.exec(text);
71
+ const title = (heading?.[1] ?? id).replace(/^Feature Specification:\s*/, "").replace(/^\d+:\s*/, "").trim();
72
+ const rest = heading === null ? text : text.slice(heading.index + heading[0].length);
73
+ const firstSection = rest.search(/^## /m);
74
+ const lead = firstSection < 0 ? rest : rest.slice(0, firstSection);
75
+ const paras = lead.split(/\n\s*\n/);
76
+ const headerAt = paras.findIndex((p) => /\*\*(?:Status|Input)(?:\*\*:|:\*\*)/.test(p));
77
+ const para = headerAt < 0 ? "" : paras[headerAt] ?? "";
78
+ const body = (headerAt < 0 ? rest : [...paras.slice(0, headerAt), ...paras.slice(headerAt + 1)].join("\n\n") + (firstSection < 0 ? "" : `\n\n${rest.slice(firstSection)}`)).trim();
79
+ const status = field(para, "Status")?.replace(/[.;,]$/, "") ?? "";
80
+ return {
81
+ id,
82
+ file,
83
+ layout: "spec-kit",
84
+ title,
85
+ status: /^[A-Za-z][\w -]{0,40}$/.test(status) ? status : "",
86
+ owner: "",
87
+ domain: "",
88
+ input: field(para, "Input") ?? "",
89
+ body,
90
+ requirements: requirementsOf(body),
91
+ };
92
+ }
93
+ /**
94
+ * The rows of `enforcement.tsv`.
95
+ *
96
+ * @param text - its text
97
+ */
98
+ export function parseEnforcement(text) {
99
+ const out = new Map();
100
+ for (const line of text.split("\n")) {
101
+ if (line === "" || line.startsWith("#") || line.startsWith("requirement\t"))
102
+ continue;
103
+ const [requirement, mechanism, by, note] = line.split("\t");
104
+ if (requirement === undefined || mechanism === undefined || !isMechanism(mechanism))
105
+ continue;
106
+ out.set(requirement, { requirement, mechanism, by: by ?? "-", note: note ?? "" });
107
+ }
108
+ return out;
109
+ }
110
+ /**
111
+ * 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.
112
+ *
113
+ * @param id - the specification beside which it is
114
+ * @param text - its text
115
+ */
116
+ export function parseReviewed(id, text) {
117
+ const out = new Map();
118
+ for (const line of text.split("\n")) {
119
+ if (line.trim() === "" || line.startsWith("#"))
120
+ continue;
121
+ const [first = "", ...rest] = line.split("\t");
122
+ const fr = /(?:^|\s)(FR-\d{3}[a-z]?)$/.exec(first.trim())?.[1];
123
+ const spec = first.trim().includes(" ") ? first.trim().split(/\s+/)[0] : id;
124
+ if (fr === undefined || spec !== id)
125
+ continue;
126
+ const requirement = `${id} ${fr}`;
127
+ out.set(requirement, { requirement, mechanism: "review", by: "-", note: rest.join("\t").trim() });
128
+ }
129
+ return out;
130
+ }
131
+ /**
132
+ * A spec kit of commons' layout: its specifications in force, in the register's order, and its enforcement.
133
+ *
134
+ * @param root - the repository's root
135
+ * @param dir - the kit's folder, from the root (`commons/spec-kit`)
136
+ */
137
+ export function readCommonsKit(root, dir) {
138
+ const abs = path.join(root, dir);
139
+ const specs = [];
140
+ for (const line of fs.readTextFileSync(path.join(abs, "registry.tsv")).split("\n").slice(1)) {
141
+ const [number, slug, state] = line.split("\t");
142
+ if (number === undefined || slug === undefined || state !== "in force")
143
+ continue;
144
+ const id = `${number}-${slug}`;
145
+ const file = under(dir, `specs/${id}/spec.md`);
146
+ specs.push(parseSpec(id, fs.readTextFileSync(path.join(root, file)), file));
147
+ }
148
+ return { specs, enforcement: parseEnforcement(fs.readTextFileSync(path.join(abs, "enforcement.tsv"))) };
149
+ }
150
+ /**
151
+ * 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
152
+ * the `reviewed.tsv` beside each, and the constitution where it exists.
153
+ *
154
+ * @param root - the repository's root
155
+ * @param dir - the folder of the specifications, from the root (`specs`)
156
+ * @param constitution - the constitution, from the root, where there is one
157
+ */
158
+ export function readPlainKit(root, dir, constitution) {
159
+ const abs = path.join(root, dir);
160
+ const specs = [];
161
+ const enforcement = new Map();
162
+ const names = fs.existsSync(abs) ? [...fs.readDirSync(abs)].filter((e) => e.isDirectory && /^\d+-[a-z]/.test(e.name)).map((e) => e.name).sort() : [];
163
+ for (const id of names) {
164
+ const file = under(dir, `${id}/spec.md`);
165
+ if (!fs.existsSync(path.join(root, file)))
166
+ continue;
167
+ specs.push(parsePlainSpec(id, fs.readTextFileSync(path.join(root, file)), file));
168
+ const reviewed = path.join(root, under(dir, `${id}/reviewed.tsv`));
169
+ if (fs.existsSync(reviewed))
170
+ for (const [k, v] of parseReviewed(id, fs.readTextFileSync(reviewed)))
171
+ enforcement.set(k, v);
172
+ }
173
+ if (constitution === undefined || !fs.existsSync(path.join(root, constitution)))
174
+ return { specs, enforcement };
175
+ const text = fs.readTextFileSync(path.join(root, constitution));
176
+ const heading = /^# (.*)$/m.exec(text);
177
+ const title = heading?.[1]?.trim() ?? "Constitution";
178
+ const body = (heading === null ? text : text.slice(heading.index + heading[0].length)).trim();
179
+ return { specs, enforcement, constitution: { file: constitution, title, body } };
180
+ }
181
+ /**
182
+ * 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.
183
+ *
184
+ * @param root - the repository's root
185
+ * @param kits - the kits
186
+ * @param found - where findings go
187
+ */
188
+ export function readSpecKits(root, kits, found = []) {
189
+ const specs = [];
190
+ const enforcement = new Map();
191
+ let constitution;
192
+ for (const k of kits) {
193
+ const read = k.layout === "commons" ? readCommonsKit(root, k.dir) : readPlainKit(root, k.dir, k.constitution);
194
+ for (const s of read.specs) {
195
+ if (specs.some((x) => x.id === s.id))
196
+ found.push({ where: s.file, problem: { kind: "duplicate-spec", id: s.id } });
197
+ else
198
+ specs.push(s);
199
+ }
200
+ for (const [key, v] of read.enforcement)
201
+ if (!enforcement.has(key))
202
+ enforcement.set(key, v);
203
+ if (constitution === undefined)
204
+ constitution = read.constitution;
205
+ }
206
+ const sources = kits.map((k) => ({ layout: k.layout, dir: k.dir }));
207
+ return constitution === undefined ? { specs, enforcement, sources } : { specs, enforcement, sources, constitution };
208
+ }
@@ -0,0 +1,22 @@
1
+ import type { Lang } from "./model.js";
2
+ /** The themes of the two schemes. */
3
+ export declare const THEMES: {
4
+ readonly light: "github-light";
5
+ readonly dark: "github-dark";
6
+ };
7
+ /** Code longer than this many characters is shown plain: a computed type of thousands of characters costs more to colour than it helps a reader, and the page folds it. */
8
+ export declare const LONGEST_COLOURED = 6000;
9
+ /** One coloured run of code. */
10
+ export interface Run {
11
+ readonly text: string;
12
+ /** Its colour in the light scheme and in the dark, or none where it is the theme's own text. */
13
+ readonly light?: string;
14
+ readonly dark?: string;
15
+ /** Italic, bold. */
16
+ readonly italic: boolean;
17
+ readonly bold: boolean;
18
+ }
19
+ /** The runs of the lines of code, by line, in the language given; one plain run for a language that is not coloured. */
20
+ export declare function runs(code: string, lang: Lang): readonly (readonly Run[])[];
21
+ /** Code as HTML: coloured runs as spans with their two colours, the rest as escaped text. */
22
+ export declare function highlightedHtml(code: string, lang: Lang): string;