liarliar 0.0.0 → 0.1.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.
package/README.md CHANGED
@@ -2,4 +2,29 @@
2
2
 
3
3
  Docs that can't lie about the code, even with ten agents editing it.
4
4
 
5
- Coming soon. Built at [Pidgeon](https://pidgeon.fyi).
5
+ When several people and agents change a codebase at once, its docs fall behind: a limit changes in code and
6
+ the doc still says the old one, a constant is renamed and the doc names the old one, a file changes and its doc
7
+ doesn't. liarliar finds those in a second, without a model, and says how to fix each one.
8
+
9
+ ```bash
10
+ npx liarliar init # writes liarliar.config.ts
11
+ npx liarliar check # every failure, with its fix
12
+ npx liarliar write # rewrites generated text from the code
13
+ ```
14
+
15
+ ## What it checks
16
+
17
+ - **Numbers the docs state.** A number written next to a code name is a claim about it:
18
+ "a cart is kept 14 days (`CART_KEPT_DAYS`)" fails when the code says 21. Units come from the name
19
+ (`_MS`, `_DAYS`, `_USD`, `_HOUR`, `_MB`), so "fifteen minutes (`HOLD_MS`)" is checked against 900000.
20
+ Loose numbers ("about 45 seconds") and ruled-out ones ("08:30, not 08:00") are never held to the code.
21
+ - **Names the docs give.** A `SCREAMING_CASE` name in backticks that the code no longer has fails, unless
22
+ the sentence says it went ("renamed", "removed").
23
+ - **Docs that own the code.** A doc owns the files it names. A branch that changes an owned file changes
24
+ its doc too, or each commit says why not: `Docs-unchanged: <reason>`.
25
+ - **Text written from the code.** A region (`<!-- liarliar:generate NAME -->` … `<!-- liarliar:end -->`)
26
+ or a whole file (`.env.example`) is written by a function of yours and fails when it goes stale.
27
+
28
+ CI never calls a model: every check is deterministic, offline and free.
29
+
30
+ Built at [Pidgeon](https://pidgeon.fyi). Apache-2.0.
@@ -0,0 +1,5 @@
1
+ import type { Config, Report } from './types.js';
2
+ /** Every check on a repository: claims, names, owners and generated text. With write, generated text is written instead of checked. */
3
+ export declare function check(config: Config, options?: {
4
+ write?: boolean;
5
+ }): Promise<Report>;
package/dist/check.js ADDED
@@ -0,0 +1,38 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join, resolve as resolvePath } from 'node:path';
3
+ import { checkClaims } from './claims.js';
4
+ import { indexCode, indexWords } from './code.js';
5
+ import { list } from './files.js';
6
+ import { checkGenerated } from './generated.js';
7
+ import { readDoc } from './markdown.js';
8
+ import { checkNames, DEFAULT_GONE } from './names.js';
9
+ import { checkOwners } from './owners.js';
10
+ import { checkTables } from './tables.js';
11
+ const CODE = /\.(m|c)?[jt]sx?$/;
12
+ /** Every check on a repository: claims, names, owners and generated text. With write, generated text is written instead of checked. */
13
+ export async function check(config, options = {}) {
14
+ const root = resolvePath(config.root ?? process.cwd());
15
+ const ignore = ['**/*.d.ts', 'dist/**', '.next/**', ...(config.ignore ?? [])];
16
+ const codeFiles = list(root, config.code, ignore).filter((f) => CODE.test(f));
17
+ const docFiles = list(root, config.docs, config.ignore);
18
+ const index = indexCode(codeFiles, root);
19
+ indexWords(index, list(root, config.words ?? [], config.ignore), root);
20
+ const context = { root, index };
21
+ const generated = await checkGenerated(context, config, docFiles, options.write ?? false);
22
+ const report = { findings: [...generated], claims: { bound: 0, passed: 0, unbound: 0 } };
23
+ const allow = new Set(config.names?.allow ?? []);
24
+ const gone = config.names?.gone ?? DEFAULT_GONE;
25
+ for (const file of docFiles) {
26
+ if (!existsSync(join(root, file)))
27
+ continue;
28
+ const doc = readDoc(file, root);
29
+ const claims = checkClaims(doc, index);
30
+ const tables = checkTables(doc, index, config.tables?.column);
31
+ report.findings.push(...claims.findings, ...tables.findings, ...checkNames(doc, index, allow, gone));
32
+ report.claims.bound += claims.bound + tables.bound;
33
+ report.claims.passed += claims.passed + tables.passed;
34
+ report.claims.unbound += claims.unbound;
35
+ }
36
+ report.findings.push(...checkOwners(root, config, docFiles));
37
+ return report;
38
+ }
@@ -0,0 +1,34 @@
1
+ import type { CodeIndex } from './code.js';
2
+ import type { Doc } from './markdown.js';
3
+ import { type Quantity, type TimeUnit } from './numbers.js';
4
+ import type { Finding } from './types.js';
5
+ /**
6
+ * Bound claims: a number written next to a code name is a claim about that name.
7
+ * "kept 8 days from first seen (`LEDGER_DAYS`)", "a brake of `BRAKE_PER_DAY` (40)",
8
+ * "from 21:00 until 07:00 (`QUIET_FROM`, `QUIET_UNTIL`)". The number is held to the constant's value,
9
+ * in the unit its name gives (`_MS`, `_DAYS`, …). Anything unsure is left unbound, never failed.
10
+ */
11
+ /** A code name in backticks: LEDGER_DAYS, KEEP, STORY_RULE.days. */
12
+ export declare const CODE_NAME: RegExp;
13
+ /** A time unit, money, an hour of the day, or a size's scale in bytes (`_MB` → 1e6). */
14
+ type NameUnit = TimeUnit | 'money' | 'hour' | number | null;
15
+ /** The unit a name says its value is in: REST_AFTER_MS → ms, STORY_RULE.days → day, TODAY_HOUR → hour of day. */
16
+ export declare function nameUnit(name: string): NameUnit;
17
+ type Verdict = {
18
+ kind: 'equal';
19
+ } | {
20
+ kind: 'differs';
21
+ expected: string;
22
+ sure: boolean;
23
+ } | {
24
+ kind: 'incompatible';
25
+ };
26
+ /** Is the number a doc wrote the value the code holds? */
27
+ export declare function compare(value: number, unit: NameUnit, q: Quantity): Verdict;
28
+ export declare function checkClaims(doc: Doc, index: CodeIndex): {
29
+ findings: Finding[];
30
+ bound: number;
31
+ passed: number;
32
+ unbound: number;
33
+ };
34
+ export {};
package/dist/claims.js ADDED
@@ -0,0 +1,216 @@
1
+ import { MS, quantities } from './numbers.js';
2
+ import { resolve } from './resolve.js';
3
+ /**
4
+ * Bound claims: a number written next to a code name is a claim about that name.
5
+ * "kept 8 days from first seen (`LEDGER_DAYS`)", "a brake of `BRAKE_PER_DAY` (40)",
6
+ * "from 21:00 until 07:00 (`QUIET_FROM`, `QUIET_UNTIL`)". The number is held to the constant's value,
7
+ * in the unit its name gives (`_MS`, `_DAYS`, …). Anything unsure is left unbound, never failed.
8
+ */
9
+ /** A code name in backticks: LEDGER_DAYS, KEEP, STORY_RULE.days. */
10
+ export const CODE_NAME = /^[A-Z][A-Z0-9_]{2,}(?:\.[A-Za-z_]\w*)*$/;
11
+ /** The unit a name says its value is in: REST_AFTER_MS → ms, STORY_RULE.days → day, TODAY_HOUR → hour of day. */
12
+ export function nameUnit(name) {
13
+ const last = name.split(/[._]/).at(-1).toUpperCase();
14
+ if (/_PER_[A-Z]+$/i.test(name))
15
+ return null;
16
+ if (/^(MS|MILLIS|MILLISECONDS)$/.test(last))
17
+ return 'ms';
18
+ if (/^(S|SEC|SECS|SECONDS)$/.test(last))
19
+ return 's';
20
+ if (/^(MIN|MINS|MINUTES)$/.test(last))
21
+ return 'min';
22
+ if (/^(H|HRS|HOURS)$/.test(last))
23
+ return 'h';
24
+ if (/^(HOUR|FROM|UNTIL|TIME|AT)$/.test(last))
25
+ return 'hour';
26
+ if (last === 'DAYS')
27
+ return 'day';
28
+ if (last === 'WEEKS')
29
+ return 'week';
30
+ if (/^(USD|GBP|EUR)$/.test(last))
31
+ return 'money';
32
+ if (/^(BYTES|KB|MB|GB)$/.test(last))
33
+ return { BYTES: 1, KB: 1e3, MB: 1e6, GB: 1e9 }[last];
34
+ return null;
35
+ }
36
+ const TIME = new Set(['ms', 's', 'min', 'h', 'day', 'week']);
37
+ const near = (a, b) => Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
38
+ const plural = (n, unit) => {
39
+ const words = { ms: 'ms', s: 'second', min: 'minute', h: 'hour', day: 'day', week: 'week' };
40
+ const r = Math.round(n * 1e6) / 1e6;
41
+ return unit === 'ms' ? `${r} ms` : `${r} ${words[unit]}${r === 1 ? '' : 's'}`;
42
+ };
43
+ /** Is the number a doc wrote the value the code holds? */
44
+ export function compare(value, unit, q) {
45
+ const u = q.unit;
46
+ if (u === 'clock') {
47
+ if (unit !== 'hour')
48
+ return { kind: 'incompatible' };
49
+ return near(value, q.value) ? { kind: 'equal' } : { kind: 'differs', expected: `${String(Math.floor(value)).padStart(2, '0')}:${String(Math.round((value % 1) * 60)).padStart(2, '0')}`, sure: unit === 'hour' };
50
+ }
51
+ if (u === 'percent') {
52
+ if (unit !== null)
53
+ return { kind: 'incompatible' };
54
+ if (near(value, q.value / 100) || near(value, q.value))
55
+ return { kind: 'equal' };
56
+ return { kind: 'differs', expected: value <= 1 ? `${Math.round(value * 1e8) / 1e6}%` : `${value}%`, sure: true };
57
+ }
58
+ if (u === 'bytes') {
59
+ // A size: the name may say its scale (`MAX_BODY_MB`), or hold bytes or characters.
60
+ const scale = unit === null ? 1 : typeof unit === 'number' ? unit : undefined;
61
+ if (scale === undefined)
62
+ return { kind: 'incompatible' };
63
+ return near(value * scale, q.value) ? { kind: 'equal' } : { kind: 'differs', expected: `${(value * scale) / (q.value >= 1e9 ? 1e9 : q.value >= 1e6 ? 1e6 : 1e3)} ${q.value >= 1e9 ? 'GB' : q.value >= 1e6 ? 'MB' : 'KB'}`, sure: true };
64
+ }
65
+ if (typeof unit === 'number')
66
+ return { kind: 'incompatible' };
67
+ if (u === 'money') {
68
+ if (unit !== null && unit !== 'money')
69
+ return { kind: 'incompatible' };
70
+ return near(value, q.value) ? { kind: 'equal' } : { kind: 'differs', expected: String(value), sure: true };
71
+ }
72
+ if (u !== null && TIME.has(u)) {
73
+ const docUnit = u;
74
+ if (unit !== null && TIME.has(unit)) {
75
+ const said = q.value * MS[docUnit];
76
+ const holds = value * MS[unit];
77
+ return near(said, holds) ? { kind: 'equal' } : { kind: 'differs', expected: plural(holds / MS[docUnit], docUnit), sure: true };
78
+ }
79
+ if (unit !== null)
80
+ return { kind: 'incompatible' };
81
+ // No unit in the name: the value may be in the doc's unit, in ms, or in seconds.
82
+ if (near(value, q.value) || near(value, q.value * MS[docUnit]) || near(value, (q.value * MS[docUnit]) / 1000))
83
+ return { kind: 'equal' };
84
+ return { kind: 'differs', expected: plural(value, docUnit), sure: false };
85
+ }
86
+ // A bare number.
87
+ if (unit === 'money' || unit === 'hour')
88
+ return { kind: 'incompatible' };
89
+ if (unit !== null && TIME.has(unit))
90
+ return q.value === 0 ? (value === 0 ? { kind: 'equal' } : { kind: 'differs', expected: plural(value, unit), sure: true }) : { kind: 'incompatible' };
91
+ return near(value, q.value) ? { kind: 'equal' } : { kind: 'differs', expected: String(Math.round(value * 1e6) / 1e6), sure: true };
92
+ }
93
+ /** Code names side by side: "(`QUIET_FROM`, `QUIET_UNTIL`)" is one group of two. */
94
+ function groups(doc) {
95
+ const out = [];
96
+ for (const span of doc.spans) {
97
+ if (!CODE_NAME.test(span.code))
98
+ continue;
99
+ const last = out.at(-1);
100
+ const between = last ? doc.text.slice(last.end, span.start) : '';
101
+ if (last && /^\s*(?:,|and|&|\/)?\s*$/.test(between)) {
102
+ last.names.push({ name: span.code, start: span.start, end: span.end });
103
+ last.end = span.end;
104
+ }
105
+ else
106
+ out.push({ names: [{ name: span.code, start: span.start, end: span.end }], start: span.start, end: span.end });
107
+ }
108
+ return out;
109
+ }
110
+ /** Where the clause holding a group begins: the sentence, list item, table cell or previous group, at most 160 characters back. */
111
+ function clauseStart(doc, at, floor) {
112
+ const from = Math.max(floor, at - 160);
113
+ const before = doc.prose.slice(from, at);
114
+ let cut = 0;
115
+ for (const m of before.matchAll(/[.!?](?=\s)|;|\n\s*\n|\||\n\s*[-*+]\s/g))
116
+ cut = m.index + m[0].length;
117
+ return from + cut;
118
+ }
119
+ /** File paths a doc names close to a group, to settle a name the code defines twice. */
120
+ function hints(doc, start, end) {
121
+ const paths = (text) => [...text.matchAll(/[\w./-]+\.(?:ts|tsx|js|mjs|cjs|py)\b/g)].map((m) => m[0]);
122
+ return [paths(doc.text.slice(Math.max(0, start - 200), end + 200)), paths(doc.text)];
123
+ }
124
+ const where = (d) => `${d.file}:${d.line}`;
125
+ /** How far before an annotating name its number may be, in characters. */
126
+ const NEAR = 100;
127
+ /** A value a doc can state as a number: a number, or a clock time the code keeps as text ("08:00"). */
128
+ function numeric(value) {
129
+ if (typeof value === 'number')
130
+ return value;
131
+ const clock = typeof value === 'string' ? /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value) : null;
132
+ return clock ? Number(clock[1]) + Number(clock[2]) / 60 : undefined;
133
+ }
134
+ export function checkClaims(doc, index) {
135
+ const findings = [];
136
+ let bound = 0;
137
+ let passed = 0;
138
+ let unbound = 0;
139
+ let floor = 0;
140
+ for (const g of groups(doc)) {
141
+ const hint = hints(doc, g.start, g.end);
142
+ // The names in the group that stand for one number.
143
+ const targets = g.names
144
+ .map((n) => {
145
+ const resolved = resolve(index, n.name, hint);
146
+ const value = resolved.kind === 'value' ? numeric(resolved.value) : undefined;
147
+ const clockText = resolved.kind === 'value' && typeof resolved.value === 'string';
148
+ return { ...n, resolved, value, unit: clockText ? 'hour' : nameUnit(n.name) };
149
+ })
150
+ .filter((t) => t.value !== undefined);
151
+ const ambiguous = g.names.filter((n) => resolve(index, n.name, hint).kind === 'ambiguous');
152
+ for (const n of ambiguous) {
153
+ const r = resolve(index, n.name, hint);
154
+ if (r.kind === 'ambiguous')
155
+ findings.push({ check: 'claim', severity: 'info', file: doc.file, line: doc.line(n.start), message: `\`${n.name}\` has different values in ${r.where.map(where).join(' and ')}.`, fix: 'Name the file it means close by, so the claim can be checked.' });
156
+ }
157
+ if (targets.length === 0) {
158
+ floor = g.end;
159
+ continue;
160
+ }
161
+ // A number right after the group: "(`SEARCH_DAILY_USD`, $5)", "`BRAKE_PER_DAY` (40)", "(`JUDGEMENT_DAYS` 0)".
162
+ // A colon after the name starts a breakdown ("`PAGES_PER_SITE`: one pricing, two docs"), not the value.
163
+ const afterText = doc.prose.slice(g.end, g.end + 48);
164
+ const lead = /^[\s,=(]*/.exec(afterText)[0].length;
165
+ const after = quantities(afterText).filter((q) => q.start <= lead + 1).map((q) => ({ ...q, start: q.start + g.end, end: q.end + g.end }));
166
+ // Numbers in the clause before, only when the names annotate it: "kept 8 days from first seen (`LEDGER_DAYS`)".
167
+ // A name used in a sentence ("under `SEARCH_DAILY_USD`", "at most `READS_PER_TICK`") states nothing before it.
168
+ const annotates = /\(\s*$/.test(doc.prose.slice(Math.max(0, g.start - 8), g.start));
169
+ const from = Math.max(clauseStart(doc, g.start, floor), g.start - NEAR);
170
+ const before = annotates ? quantities(doc.prose.slice(from, g.start)).map((q) => ({ ...q, start: q.start + from, end: q.end + from })) : [];
171
+ const pairs = [];
172
+ if (targets.length === 1) {
173
+ const t = targets[0];
174
+ const fits = (q) => compare(t.value, t.unit, q).kind !== 'incompatible';
175
+ const a = after.find((q) => fits(q));
176
+ // A unit in the name lets us skip numbers that can't be about it; without one, only the nearest counts.
177
+ const b = t.unit !== null ? [...before].reverse().find((q) => fits(q)) : before.at(-1);
178
+ pairs.push({ t, q: a ?? b });
179
+ }
180
+ else {
181
+ // Several names, several numbers: in order, from the numbers just before (or just after) the group.
182
+ const pool = (after.length >= targets.length ? after.slice(0, targets.length) : before.slice(-targets.length));
183
+ targets.forEach((t, i) => pairs.push({ t, q: pool.length === targets.length ? pool[i] : undefined }));
184
+ }
185
+ for (const { t, q } of pairs) {
186
+ const { value } = t;
187
+ const def = t.resolved.where;
188
+ if (!q || q.approx) {
189
+ unbound += 1;
190
+ findings.push({ check: 'claim', severity: 'info', file: doc.file, line: doc.line(t.start), message: q ? `\`${t.name}\` follows "${q.text}", which the doc gives as approximate.` : `\`${t.name}\` has no number beside it.`, fix: `Write its value (${value}) beside it if the doc means to state it.` });
191
+ continue;
192
+ }
193
+ const verdict = compare(value, t.unit, q);
194
+ if (verdict.kind === 'incompatible') {
195
+ unbound += 1;
196
+ continue;
197
+ }
198
+ bound += 1;
199
+ if (verdict.kind === 'equal') {
200
+ passed += 1;
201
+ continue;
202
+ }
203
+ const said = doc.text.slice(q.start, q.end);
204
+ findings.push({
205
+ check: 'claim',
206
+ severity: verdict.sure ? 'error' : 'warning',
207
+ file: doc.file,
208
+ line: doc.line(q.start),
209
+ message: `The doc says "${said}" for \`${t.name}\`, but ${where(def)} makes it ${verdict.expected}${verdict.sure ? '' : ' (if the value is in the doc’s unit)'}.`,
210
+ fix: `Change "${said}" to "${verdict.expected}" in ${doc.file}, or change \`${t.name}\` in ${def.file}.`,
211
+ });
212
+ }
213
+ floor = g.end;
214
+ }
215
+ return { findings, bound, passed, unbound };
216
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, writeFileSync } from 'node:fs';
3
+ import { check } from './check.js';
4
+ import { loadConfig } from './config.js';
5
+ import { failed, format } from './report.js';
6
+ const HELP = `liarliar: docs that can't lie about the code.
7
+
8
+ liarliar check [--all] [--json] [--config <file>] check every claim, name, owner and generated text
9
+ liarliar write [--config <file>] write generated regions and files from the code
10
+ liarliar init write a starting liarliar.config.ts
11
+ `;
12
+ const STARTER = `import { defineConfig, envExample } from 'liarliar';
13
+
14
+ export default defineConfig({
15
+ // Markdown whose numbers and names are held to the code.
16
+ docs: ['README.md', 'docs/**/*.md'],
17
+ // Code whose constants and env defaults are the truth.
18
+ code: ['src/**/*.{ts,tsx,js,mjs}'],
19
+ // Other files whose names count as "still in the code".
20
+ words: ['**/*.sql', '*.json', '*.{yml,yaml,toml}'],
21
+ // Uncomment to make each source file's doc change with it:
22
+ // owners: { code: ['src/**/*.ts'], except: [] },
23
+ // Uncomment to write .env.example from the code:
24
+ // files: { '.env.example': envExample() },
25
+ });
26
+ `;
27
+ async function main(argv) {
28
+ const [command = 'check', ...rest] = argv;
29
+ const flag = (name) => rest.includes(name);
30
+ const value = (name) => {
31
+ const i = rest.indexOf(name);
32
+ return i >= 0 ? rest[i + 1] : undefined;
33
+ };
34
+ if (command === 'help' || flag('--help') || flag('-h')) {
35
+ process.stdout.write(HELP);
36
+ return 0;
37
+ }
38
+ if (command === 'init') {
39
+ if (existsSync('liarliar.config.ts')) {
40
+ process.stderr.write('liarliar.config.ts already exists.\n');
41
+ return 1;
42
+ }
43
+ writeFileSync('liarliar.config.ts', STARTER);
44
+ process.stdout.write('Wrote liarliar.config.ts. Run `liarliar check`.\n');
45
+ return 0;
46
+ }
47
+ if (command !== 'check' && command !== 'write') {
48
+ process.stderr.write(HELP);
49
+ return 2;
50
+ }
51
+ const config = await loadConfig(value('--config'));
52
+ const report = await check(config, { write: command === 'write' });
53
+ if (flag('--json'))
54
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
55
+ else
56
+ process.stdout.write(`${format(report, { all: flag('--all') })}\n`);
57
+ return failed(report) ? 1 : 0;
58
+ }
59
+ main(process.argv.slice(2)).then((code) => process.exit(code), (error) => {
60
+ process.stderr.write(`liarliar: ${error instanceof Error ? error.message : String(error)}\n`);
61
+ process.exit(2);
62
+ });
package/dist/code.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * What the code says: every top-level constant in TypeScript and JavaScript, evaluated without running
3
+ * anything, and every environment variable with the default the code falls back to.
4
+ */
5
+ export type Value = number | string | boolean | null | Value[] | {
6
+ [key: string]: Value;
7
+ };
8
+ export interface Definition {
9
+ name: string;
10
+ file: string;
11
+ line: number;
12
+ /** Exported from its module: when a name is defined twice, the exported one is the one docs mean. */
13
+ exported?: boolean;
14
+ /** undefined when the value can't be worked out from the source alone. */
15
+ value: Value | undefined;
16
+ }
17
+ export interface CodeIndex {
18
+ /** Constants by name; a name defined in several files has several entries. */
19
+ constants: Map<string, Definition[]>;
20
+ /** Environment variables by name, with each default the code gives it (undefined: read with no default). */
21
+ env: Map<string, Definition[]>;
22
+ /** Every identifier-like word in the code, for "is this name still anywhere". */
23
+ words: Set<string>;
24
+ }
25
+ export declare function indexCode(files: string[], root: string): CodeIndex;
26
+ /** Adds plain words from files that aren't TypeScript (SQL, YAML, JSON, TOML) to the index's word list. */
27
+ export declare function indexWords(index: CodeIndex, files: string[], root: string): void;
package/dist/code.js ADDED
@@ -0,0 +1,231 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import ts from 'typescript';
3
+ /** process.env.X, unresolved: the default after `??` or `||` is what counts. */
4
+ const ENV = Symbol('env');
5
+ const lineOf = (source, node) => source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
6
+ function parse(file, text) {
7
+ const kind = file.endsWith('x') ? ts.ScriptKind.TSX : file.endsWith('.ts') || file.endsWith('.mts') ? ts.ScriptKind.TS : ts.ScriptKind.JS;
8
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
9
+ const locals = new Map();
10
+ const exports = new Set();
11
+ const imports = new Map();
12
+ for (const statement of source.statements) {
13
+ if (ts.isVariableStatement(statement) && statement.declarationList.flags & ts.NodeFlags.Const) {
14
+ const exported = statement.modifiers?.some((mod) => mod.kind === ts.SyntaxKind.ExportKeyword) ?? false;
15
+ for (const d of statement.declarationList.declarations) {
16
+ if (!ts.isIdentifier(d.name) || !d.initializer)
17
+ continue;
18
+ locals.set(d.name.text, d.initializer);
19
+ if (exported)
20
+ exports.add(d.name.text);
21
+ }
22
+ }
23
+ if (ts.isImportDeclaration(statement) && statement.importClause?.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) {
24
+ for (const e of statement.importClause.namedBindings.elements)
25
+ imports.set(e.name.text, (e.propertyName ?? e.name).text);
26
+ }
27
+ }
28
+ return { file, source, locals, imports, exports };
29
+ }
30
+ /** The env variable an expression reads, through Number(), .trim(), ?.trim(), parseInt() and the like. */
31
+ function envRead(node) {
32
+ let n = node;
33
+ for (;;) {
34
+ if (ts.isParenthesizedExpression(n) || ts.isNonNullExpression(n) || ts.isAsExpression(n))
35
+ n = n.expression;
36
+ else if (ts.isCallExpression(n) && n.arguments.length >= 1 && ts.isIdentifier(n.expression) && /^(Number|parseInt|parseFloat|String|Boolean)$/.test(n.expression.text))
37
+ n = n.arguments[0];
38
+ else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && /^(trim|toLowerCase|toUpperCase)$/.test(n.expression.name.text))
39
+ n = n.expression.expression;
40
+ else
41
+ break;
42
+ }
43
+ if (ts.isPropertyAccessExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === 'env' && ts.isIdentifier(n.expression.expression) && n.expression.expression.text === 'process')
44
+ return n.name.text;
45
+ if (ts.isElementAccessExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === 'env' && ts.isStringLiteral(n.argumentExpression))
46
+ return n.argumentExpression.text;
47
+ return undefined;
48
+ }
49
+ const MATH = { round: Math.round, floor: Math.floor, ceil: Math.ceil, min: Math.min, max: Math.max, abs: Math.abs };
50
+ export function indexCode(files, root) {
51
+ const modules = files.map((file) => parse(file, readFileSync(`${root}/${file}`, 'utf8')));
52
+ const byName = new Map();
53
+ for (const m of modules)
54
+ for (const name of m.locals.keys())
55
+ byName.set(name, [...(byName.get(name) ?? []), m]);
56
+ const memo = new Map();
57
+ const busy = new Set();
58
+ /** A name as seen from a module: its own const, or what it imports, found by its original name wherever it is unique. */
59
+ function lookup(name, from) {
60
+ if (from.locals.has(name))
61
+ return constant(from, name);
62
+ const original = from.imports.get(name);
63
+ const homes = original ? byName.get(original) : undefined;
64
+ if (!original || !homes)
65
+ return undefined;
66
+ const values = homes.map((h) => constant(h, original));
67
+ const first = values[0];
68
+ return values.every((v) => JSON.stringify(v) === JSON.stringify(first)) ? first : undefined;
69
+ }
70
+ function constant(m, name) {
71
+ const key = `${m.file}#${name}`;
72
+ if (memo.has(key))
73
+ return memo.get(key);
74
+ if (busy.has(key))
75
+ return undefined;
76
+ busy.add(key);
77
+ const value = evaluate(m.locals.get(name), m);
78
+ busy.delete(key);
79
+ memo.set(key, value);
80
+ return value;
81
+ }
82
+ function evaluate(node, m) {
83
+ if (ts.isNumericLiteral(node))
84
+ return Number(node.text.replace(/_/g, ''));
85
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
86
+ return node.text;
87
+ if (node.kind === ts.SyntaxKind.TrueKeyword)
88
+ return true;
89
+ if (node.kind === ts.SyntaxKind.FalseKeyword)
90
+ return false;
91
+ if (node.kind === ts.SyntaxKind.NullKeyword)
92
+ return null;
93
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node) || ts.isTypeAssertionExpression(node))
94
+ return evaluate(node.expression, m);
95
+ if (envRead(node))
96
+ return ENV;
97
+ if (ts.isIdentifier(node))
98
+ return lookup(node.text, m);
99
+ if (ts.isPrefixUnaryExpression(node)) {
100
+ const v = evaluate(node.operand, m);
101
+ if (typeof v !== 'number')
102
+ return undefined;
103
+ return node.operator === ts.SyntaxKind.MinusToken ? -v : node.operator === ts.SyntaxKind.PlusToken ? v : undefined;
104
+ }
105
+ if (ts.isBinaryExpression(node)) {
106
+ const op = node.operatorToken.kind;
107
+ const left = evaluate(node.left, m);
108
+ if (op === ts.SyntaxKind.QuestionQuestionToken || op === ts.SyntaxKind.BarBarToken)
109
+ return left === ENV || left === undefined ? evaluate(node.right, m) : left;
110
+ const right = evaluate(node.right, m);
111
+ if (op === ts.SyntaxKind.PlusToken && (typeof left === 'string' || typeof right === 'string') && left !== ENV && right !== ENV && left !== undefined && right !== undefined)
112
+ return `${String(left)}${String(right)}`;
113
+ if (typeof left !== 'number' || typeof right !== 'number')
114
+ return undefined;
115
+ switch (op) {
116
+ case ts.SyntaxKind.PlusToken: return left + right;
117
+ case ts.SyntaxKind.MinusToken: return left - right;
118
+ case ts.SyntaxKind.AsteriskToken: return left * right;
119
+ case ts.SyntaxKind.SlashToken: return left / right;
120
+ case ts.SyntaxKind.PercentToken: return left % right;
121
+ case ts.SyntaxKind.AsteriskAsteriskToken: return left ** right;
122
+ default: return undefined;
123
+ }
124
+ }
125
+ if (ts.isObjectLiteralExpression(node)) {
126
+ const out = {};
127
+ for (const p of node.properties) {
128
+ const key = p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) || ts.isNumericLiteral(p.name)) ? p.name.text : undefined;
129
+ if (!key)
130
+ continue;
131
+ const v = ts.isPropertyAssignment(p) ? evaluate(p.initializer, m) : ts.isShorthandPropertyAssignment(p) ? lookup(key, m) : undefined;
132
+ if (v !== undefined && v !== ENV)
133
+ out[key] = v;
134
+ }
135
+ return out;
136
+ }
137
+ if (ts.isArrayLiteralExpression(node)) {
138
+ const out = [];
139
+ for (const e of node.elements) {
140
+ const v = evaluate(e, m);
141
+ if (v === undefined || v === ENV)
142
+ return undefined;
143
+ out.push(v);
144
+ }
145
+ return out;
146
+ }
147
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
148
+ const key = ts.isPropertyAccessExpression(node) ? node.name.text : ts.isStringLiteral(node.argumentExpression) || ts.isNumericLiteral(node.argumentExpression) ? node.argumentExpression.text : undefined;
149
+ const target = evaluate(node.expression, m);
150
+ if (key === 'length' && (typeof target === 'string' || Array.isArray(target)))
151
+ return target.length;
152
+ if (key === undefined || target === null || typeof target !== 'object')
153
+ return undefined;
154
+ return target[key];
155
+ }
156
+ if (ts.isCallExpression(node)) {
157
+ const callee = node.expression;
158
+ const args = node.arguments.map((a) => evaluate(a, m));
159
+ if (args.some((a) => a === ENV))
160
+ return ENV;
161
+ if (ts.isIdentifier(callee) && args.length >= 1) {
162
+ const [a] = args;
163
+ if (callee.text === 'Number' && (typeof a === 'string' || typeof a === 'number'))
164
+ return Number(a);
165
+ if (callee.text === 'parseInt' && typeof a === 'string')
166
+ return Number.parseInt(a, 10);
167
+ if (callee.text === 'parseFloat' && typeof a === 'string')
168
+ return Number.parseFloat(a);
169
+ if (callee.text === 'String' && a !== undefined)
170
+ return String(a);
171
+ }
172
+ if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)) {
173
+ const fn = MATH[callee.name.text];
174
+ if (callee.expression.text === 'Math' && fn && args.every((a) => typeof a === 'number'))
175
+ return fn(...args);
176
+ if (callee.expression.text === 'Object' && callee.name.text === 'freeze')
177
+ return args[0];
178
+ }
179
+ return undefined;
180
+ }
181
+ return undefined;
182
+ }
183
+ const constants = new Map();
184
+ const env = new Map();
185
+ const words = new Set();
186
+ const add = (map, d) => {
187
+ const known = map.get(d.name) ?? [];
188
+ // `process.env.X?.trim()` reads X once, though two expressions name it.
189
+ const twin = known.findIndex((k) => k.file === d.file && k.line === d.line);
190
+ if (twin >= 0) {
191
+ if (known[twin].value === undefined)
192
+ known[twin] = d;
193
+ return;
194
+ }
195
+ map.set(d.name, [...known, d]);
196
+ };
197
+ for (const m of modules) {
198
+ for (const [name, init] of m.locals) {
199
+ const v = constant(m, name);
200
+ add(constants, { name, file: m.file, line: lineOf(m.source, init), exported: m.exports.has(name), value: v === ENV ? undefined : v });
201
+ }
202
+ const visit = (node) => {
203
+ if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
204
+ for (const w of node.text.split(/[^\w$]+/))
205
+ if (w)
206
+ words.add(w);
207
+ if (ts.isExpression(node)) {
208
+ const name = envRead(node);
209
+ const parent = node.parent;
210
+ if (name && !(parent && ts.isExpression(parent) && envRead(parent) === name)) {
211
+ // Climb to the ?? or || this read falls back through, if any.
212
+ let outer = node;
213
+ while (outer.parent && (ts.isCallExpression(outer.parent) || ts.isParenthesizedExpression(outer.parent) || ts.isPropertyAccessExpression(outer.parent) || ts.isAsExpression(outer.parent)))
214
+ outer = outer.parent;
215
+ const fallback = outer.parent && ts.isBinaryExpression(outer.parent) && outer.parent.left === outer && [ts.SyntaxKind.QuestionQuestionToken, ts.SyntaxKind.BarBarToken].includes(outer.parent.operatorToken.kind) ? evaluate(outer.parent.right, m) : undefined;
216
+ add(env, { name, file: m.file, line: lineOf(m.source, node), value: fallback === ENV ? undefined : fallback });
217
+ }
218
+ }
219
+ ts.forEachChild(node, visit);
220
+ };
221
+ visit(m.source);
222
+ }
223
+ return { constants, env, words };
224
+ }
225
+ /** Adds plain words from files that aren't TypeScript (SQL, YAML, JSON, TOML) to the index's word list. */
226
+ export function indexWords(index, files, root) {
227
+ for (const file of files)
228
+ for (const w of readFileSync(`${root}/${file}`, 'utf8').split(/[^\w$]+/))
229
+ if (w)
230
+ index.words.add(w);
231
+ }
@@ -0,0 +1,4 @@
1
+ import type { Config } from './types.js';
2
+ export declare const CONFIG_FILES: string[];
3
+ /** Finds and loads the config from the working directory or a path; its folder is the root unless it says otherwise. */
4
+ export declare function loadConfig(path?: string): Promise<Config>;