liarliar 0.0.0-stage → 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/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>;
package/dist/config.js ADDED
@@ -0,0 +1,33 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { createJiti } from 'jiti';
4
+ export const CONFIG_FILES = ['liarliar.config.ts', 'liarliar.config.mts', 'liarliar.config.js', 'liarliar.config.mjs'];
5
+ /** The tsconfig "paths" as jiti aliases, so a config can import the project's own code by "@/lib/x". */
6
+ function aliases(root) {
7
+ const file = join(root, 'tsconfig.json');
8
+ if (!existsSync(file))
9
+ return {};
10
+ try {
11
+ // tsconfig allows comments and trailing commas.
12
+ const json = JSON.parse(readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\/|(?<![:"])\/\/.*$/gm, '').replace(/,(\s*[}\]])/g, '$1'));
13
+ const base = join(root, json.compilerOptions?.baseUrl ?? '.');
14
+ const out = {};
15
+ for (const [from, [to]] of Object.entries(json.compilerOptions?.paths ?? {}))
16
+ if (to)
17
+ out[from.replace(/\/\*$/, '')] = join(base, to.replace(/\/\*$/, ''));
18
+ return out;
19
+ }
20
+ catch {
21
+ return {};
22
+ }
23
+ }
24
+ /** Finds and loads the config from the working directory or a path; its folder is the root unless it says otherwise. */
25
+ export async function loadConfig(path) {
26
+ const file = path ? resolve(path) : CONFIG_FILES.map((f) => resolve(f)).find((f) => existsSync(f));
27
+ if (!file || !existsSync(file))
28
+ throw new Error(`No liarliar config found (looked for ${CONFIG_FILES.join(', ')}). Run \`liarliar init\` to write one.`);
29
+ const root = dirname(file);
30
+ const jiti = createJiti(import.meta.url, { alias: aliases(root), interopDefault: true });
31
+ const config = (await jiti.import(file, { default: true }));
32
+ return { ...config, root: config.root ? resolve(root, config.root) : root };
33
+ }
@@ -0,0 +1,3 @@
1
+ /** Files under root matching any of the globs and none of the ignores, as sorted paths relative to root. */
2
+ export declare function list(root: string, globs: string[], ignore?: string[]): string[];
3
+ export declare const matches: (file: string, globs: string[]) => boolean;
package/dist/files.js ADDED
@@ -0,0 +1,13 @@
1
+ import { globSync } from 'node:fs';
2
+ import { matchesGlob } from 'node:path';
3
+ /** Files under root matching any of the globs and none of the ignores, as sorted paths relative to root. */
4
+ export function list(root, globs, ignore = []) {
5
+ const skip = ['**/node_modules/**', ...ignore];
6
+ const found = new Set();
7
+ for (const g of globs)
8
+ for (const f of globSync(g, { cwd: root }))
9
+ if (!skip.some((s) => matchesGlob(f, s)))
10
+ found.add(f.split('\\').join('/'));
11
+ return [...found].sort();
12
+ }
13
+ export const matches = (file, globs) => globs.some((g) => matchesGlob(file, g));
@@ -0,0 +1,12 @@
1
+ import type { Config, Context, Finding } from './types.js';
2
+ export declare function checkGenerated(context: Context, config: Config, docFiles: string[], write: boolean): Promise<Finding[]>;
3
+ /**
4
+ * A generator for .env.example: every environment variable the code reads, one per line, no values.
5
+ * `extra` names variables a library reads for you; `exclude` those the platform sets.
6
+ */
7
+ export declare function envExample(options?: {
8
+ header?: string;
9
+ extra?: string[];
10
+ exclude?: string[];
11
+ from?: string[];
12
+ }): ({ index }: Context) => string;
@@ -0,0 +1,63 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { matches } from './files.js';
3
+ /**
4
+ * Text written from the code, so it can't drift: a region inside a doc
5
+ * (<!-- liarliar:generate NAME --> … <!-- liarliar:end -->) or a whole file.
6
+ * `liarliar check` fails when the text and the code disagree; `liarliar write` writes it again.
7
+ */
8
+ const REGION = /(<!--\s*liarliar:generate\s+([\w-]+)\s*-->\n)([\s\S]*?)(<!--\s*liarliar:end\s*-->)/g;
9
+ const withNewline = (s) => (s.endsWith('\n') ? s : `${s}\n`);
10
+ export async function checkGenerated(context, config, docFiles, write) {
11
+ const findings = [];
12
+ const { root } = context;
13
+ for (const file of docFiles) {
14
+ const text = readFileSync(`${root}/${file}`, 'utf8');
15
+ const parts = [];
16
+ for (const m of text.matchAll(REGION)) {
17
+ const name = m[2];
18
+ const generator = config.generate?.[name];
19
+ const line = text.slice(0, m.index).split('\n').length;
20
+ if (!generator) {
21
+ findings.push({ check: 'generated', severity: 'error', file, line, message: `No generator called "${name}".`, fix: `Add generate["${name}"] to the liarliar config, or fix the region's name.` });
22
+ continue;
23
+ }
24
+ const next = withNewline(await generator(context));
25
+ if (next === m[3])
26
+ continue;
27
+ const start = m.index + m[1].length;
28
+ parts.push({ start, end: start + m[3].length, next, name });
29
+ if (!write)
30
+ findings.push({ check: 'generated', severity: 'error', file, line, message: `The "${name}" region no longer matches the code.`, fix: 'Run `liarliar write` and commit the result.' });
31
+ }
32
+ if (write && parts.length) {
33
+ let out = text;
34
+ for (const p of [...parts].reverse())
35
+ out = out.slice(0, p.start) + p.next + out.slice(p.end);
36
+ writeFileSync(`${root}/${file}`, out);
37
+ }
38
+ }
39
+ for (const [file, generator] of Object.entries(config.files ?? {})) {
40
+ const next = withNewline(await generator(context));
41
+ const now = existsSync(`${root}/${file}`) ? readFileSync(`${root}/${file}`, 'utf8') : undefined;
42
+ if (now === next)
43
+ continue;
44
+ if (write)
45
+ writeFileSync(`${root}/${file}`, next);
46
+ else
47
+ findings.push({ check: 'generated', severity: 'error', file, line: 1, message: now === undefined ? `${file} is missing.` : `${file} no longer matches the code.`, fix: 'Run `liarliar write` and commit the result.' });
48
+ }
49
+ return findings;
50
+ }
51
+ /**
52
+ * A generator for .env.example: every environment variable the code reads, one per line, no values.
53
+ * `extra` names variables a library reads for you; `exclude` those the platform sets.
54
+ */
55
+ export function envExample(options = {}) {
56
+ const exclude = new Set(['NODE_ENV', ...(options.exclude ?? [])]);
57
+ return ({ index }) => {
58
+ // `from` limits it to variables read in those files (the app's own code, say, not its scripts).
59
+ const read = [...index.env.entries()].filter(([, defs]) => !options.from || defs.some((d) => matches(d.file, options.from))).map(([name]) => name);
60
+ const names = [...new Set([...read, ...(options.extra ?? [])])].filter((n) => !exclude.has(n)).sort();
61
+ return `${options.header ? withNewline(options.header) : ''}${names.map((n) => `${n}=`).join('\n')}\n`;
62
+ };
63
+ }
@@ -0,0 +1,9 @@
1
+ export { check } from './check.js';
2
+ export { loadConfig } from './config.js';
3
+ export { envExample } from './generated.js';
4
+ export { format, failed } from './report.js';
5
+ export type { Config, Context, Finding, Generator, Report } from './types.js';
6
+ export type { CodeIndex, Definition, Value } from './code.js';
7
+ import type { Config } from './types.js';
8
+ /** Types a config file: `export default defineConfig({ docs: [...], code: [...] })`. */
9
+ export declare const defineConfig: (config: Config) => Config;
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { check } from './check.js';
2
+ export { loadConfig } from './config.js';
3
+ export { envExample } from './generated.js';
4
+ export { format, failed } from './report.js';
5
+ /** Types a config file: `export default defineConfig({ docs: [...], code: [...] })`. */
6
+ export const defineConfig = (config) => config;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A Markdown file as liarliar reads it: the text, a copy with everything that isn't prose blanked out
3
+ * (code, comments, link targets, dates) so numbers in it aren't mistaken for claims, and the inline-code
4
+ * spans, which is where code names live.
5
+ */
6
+ export interface Doc {
7
+ file: string;
8
+ text: string;
9
+ /** Same length as text, newlines kept; code, comments, URLs and dates are spaces. */
10
+ prose: string;
11
+ /** Inline code spans: their content and where they sit in text. */
12
+ spans: {
13
+ code: string;
14
+ start: number;
15
+ end: number;
16
+ }[];
17
+ line: (offset: number) => number;
18
+ }
19
+ export declare function readDoc(file: string, root: string): Doc;
20
+ export declare function parseDoc(file: string, text: string): Doc;
@@ -0,0 +1,44 @@
1
+ import { readFileSync } from 'node:fs';
2
+ const blank = (s) => s.replace(/[^\n]/g, ' ');
3
+ const MONTHS = 'Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?';
4
+ const DATES = new RegExp(String.raw `\b\d{4}-\d{2}-\d{2}(?:[T ][\d:.]+Z?)?\b|\b\d{1,2}\s+(?:${MONTHS})\b(?:\s+\d{4})?|\b(?:${MONTHS})\s+\d{1,2}\b(?:,?\s+\d{4})?|\b20[12]\d\b(?!\s*(?:ms|s|min|minutes?|hours?|days?|%|characters?|rows?|items?))`, 'g');
5
+ export function readDoc(file, root) {
6
+ return parseDoc(file, readFileSync(`${root}/${file}`, 'utf8'));
7
+ }
8
+ export function parseDoc(file, text) {
9
+ let prose = text;
10
+ const keep = (pattern) => {
11
+ prose = prose.replace(pattern, (m) => blank(m));
12
+ };
13
+ // Fenced blocks (``` or ~~~), then HTML comments, before inline code so fences aren't read as spans.
14
+ keep(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm);
15
+ keep(/<!--[\s\S]*?-->/g);
16
+ const spans = [];
17
+ prose = prose.replace(/(`+)([^`\n]+?)\1/g, (m, _ticks, code, offset) => {
18
+ spans.push({ code: code.trim(), start: offset, end: offset + m.length });
19
+ return blank(m);
20
+ });
21
+ keep(/\]\([^)\s]*\)/g); // link targets
22
+ keep(/https?:\/\/\S+/g);
23
+ keep(DATES);
24
+ keep(/^\s*\d+\.(?=\s)/gm); // numbered list markers
25
+ keep(/\b[\w-]+\/[\w./-]+/g); // paths: src/lib/x.ts, docs/a.md
26
+ keep(/\b[vV]?\d+\.\d+\.\d+\b/g); // versions
27
+ const starts = [0];
28
+ for (let i = 0; i < text.length; i++)
29
+ if (text[i] === '\n')
30
+ starts.push(i + 1);
31
+ const line = (offset) => {
32
+ let lo = 0;
33
+ let hi = starts.length - 1;
34
+ while (lo < hi) {
35
+ const mid = (lo + hi + 1) >> 1;
36
+ if (starts[mid] <= offset)
37
+ lo = mid;
38
+ else
39
+ hi = mid - 1;
40
+ }
41
+ return lo + 1;
42
+ };
43
+ return { file, text, prose, spans, line };
44
+ }
@@ -0,0 +1,10 @@
1
+ import type { CodeIndex } from './code.js';
2
+ import type { Doc } from './markdown.js';
3
+ import type { Finding } from './types.js';
4
+ /**
5
+ * Names a doc gives in backticks that the code no longer has: `MATCH_WINDOW` after the code dropped it.
6
+ * A name counts when it is SCREAMING_CASE with an underscore (a constant or an env variable). A doc may name
7
+ * a dropped one if it says so close by ("removed", "renamed", "was", …).
8
+ */
9
+ export declare const DEFAULT_GONE: RegExp;
10
+ export declare function checkNames(doc: Doc, index: CodeIndex, allow: Set<string>, gone: RegExp): Finding[];
package/dist/names.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Names a doc gives in backticks that the code no longer has: `MATCH_WINDOW` after the code dropped it.
3
+ * A name counts when it is SCREAMING_CASE with an underscore (a constant or an env variable). A doc may name
4
+ * a dropped one if it says so close by ("removed", "renamed", "was", …).
5
+ */
6
+ export const DEFAULT_GONE = /\b(deleted|removed|killed|retired|gone|dropped|deprecated|not built|was renamed|renamed|replaced|used to|no longer|formerly)\b/i;
7
+ /** The sentence holding a span: from the last sentence end before it to the next after it. */
8
+ function sentence(text, start, end) {
9
+ const before = text.slice(Math.max(0, start - 400), start);
10
+ const cut = Math.max(...[...before.matchAll(/[.!?](?=\s)|\n\s*\n/g)].map((m) => m.index + m[0].length), 0);
11
+ const after = text.slice(end, end + 400);
12
+ const stop = /[.!?](?=\s|$)|\n\s*\n/.exec(after);
13
+ return before.slice(cut) + text.slice(start, end) + after.slice(0, stop ? stop.index : after.length);
14
+ }
15
+ export function checkNames(doc, index, allow, gone) {
16
+ const findings = [];
17
+ const seen = new Set();
18
+ for (const span of doc.spans) {
19
+ const m = /^([A-Z][A-Z0-9]*_[A-Z0-9_]+)(?:\.[\w.]+)?$/.exec(span.code);
20
+ if (!m)
21
+ continue;
22
+ const name = m[1];
23
+ if (seen.has(name) || allow.has(name) || index.words.has(name))
24
+ continue;
25
+ if (gone.test(sentence(doc.text, span.start, span.end)))
26
+ continue;
27
+ seen.add(name);
28
+ findings.push({
29
+ check: 'name',
30
+ severity: 'error',
31
+ file: doc.file,
32
+ line: doc.line(span.start),
33
+ message: `\`${name}\` is not in the code any more.`,
34
+ fix: `Rename it in ${doc.file} as the code did, or say close by that it was removed; if a platform sets it, add it to names.allow.`,
35
+ });
36
+ }
37
+ return findings;
38
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Numbers as people write them in prose: "15", "1,000", "0.05", "fifteen", "six weeks",
3
+ * "$5", "£250k", "$10M", "70%", "21:00", "8 million", "a 15-minute window", "within an hour".
4
+ */
5
+ export type TimeUnit = 'ms' | 's' | 'min' | 'h' | 'day' | 'week';
6
+ export type Unit = TimeUnit | 'percent' | 'money' | 'clock' | 'bytes' | null;
7
+ export interface Quantity {
8
+ value: number;
9
+ unit: Unit;
10
+ /** "about 960", "~5", "roughly a day": stated loosely, so never held to the code. */
11
+ approx: boolean;
12
+ /** Offsets in the text the quantity was read from. */
13
+ start: number;
14
+ end: number;
15
+ text: string;
16
+ }
17
+ export declare const MS: Record<TimeUnit, number>;
18
+ /** Sizes in bytes (or characters, which is how code usually counts a body). */
19
+ export declare const BYTES: Record<string, number>;
20
+ export declare function timeUnit(word: string): TimeUnit | null;
21
+ /** Every quantity in a stretch of text, in order. Masked spans (code, dates) should already be blanked out. */
22
+ export declare function quantities(text: string): Quantity[];
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Numbers as people write them in prose: "15", "1,000", "0.05", "fifteen", "six weeks",
3
+ * "$5", "£250k", "$10M", "70%", "21:00", "8 million", "a 15-minute window", "within an hour".
4
+ */
5
+ export const MS = { ms: 1, s: 1000, min: 60_000, h: 3_600_000, day: 86_400_000, week: 604_800_000 };
6
+ const WORDS = {
7
+ zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
8
+ eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18,
9
+ nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, ninety: 90, hundred: 100, twice: 2,
10
+ };
11
+ const SCALE = { thousand: 1e3, million: 1e6, billion: 1e9 };
12
+ const SUFFIX = { k: 1e3, m: 1e6, bn: 1e9, b: 1e9 };
13
+ /** Sizes in bytes (or characters, which is how code usually counts a body). */
14
+ export const BYTES = { KB: 1e3, kB: 1e3, MB: 1e6, GB: 1e9, KiB: 1024, MiB: 1024 ** 2, GiB: 1024 ** 3 };
15
+ const TIME_WORDS = [
16
+ [/^(?:ms|milliseconds?)$/i, 'ms'],
17
+ [/^(?:s|secs?|seconds?)$/i, 's'],
18
+ [/^(?:mins?|minutes?)$/i, 'min'],
19
+ [/^(?:h|hrs?|hours?)$/i, 'h'],
20
+ [/^days?$/i, 'day'],
21
+ [/^weeks?$/i, 'week'],
22
+ ];
23
+ export function timeUnit(word) {
24
+ for (const [pattern, unit] of TIME_WORDS)
25
+ if (pattern.test(word))
26
+ return unit;
27
+ return null;
28
+ }
29
+ const APPROX = /(?:\babout|\baround|\broughly|\bsome|\bnearly|\balmost|~|≈|\bapprox\.?|\bapproximately)\s*$/i;
30
+ const NEGATED = /(?:\bnot|\bnever|\brather than|\binstead of|\bno longer)\s*$/i;
31
+ const WORD_NUMBER = Object.keys(WORDS).join('|');
32
+ const UNIT_WORD = 'ms|milliseconds?|secs?|seconds?|mins?|minutes?|hrs?|hours?|days?|weeks?|s|h';
33
+ /** One pattern for every way a quantity is written. Order matters: clock times and money before bare numbers. */
34
+ const QUANTITY = new RegExp([
35
+ String.raw `\b(?<ch>[01]?\d|2[0-3]):(?<cm>[0-5]\d)\b`,
36
+ String.raw `(?<cur>[$£€])\s?(?<amt>\d[\d,]*(?:\.\d+)?)(?:(?<msfx>k|K|M|bn|B)\b|\s+(?<mscale>thousand|million|billion)\b)?`,
37
+ String.raw `(?:(?<![\w.$£€])(?<num>\d[\d,_]*(?:\.\d+)?)(?<nsfx>k|M|bn)?\b|\b(?<word>${WORD_NUMBER})\b)(?:\s+(?<scale>thousand|million|billion)\b)?(?:\s*(?<pct>%)|\s?(?<size>KB|kB|MB|GB|KiB|MiB|GiB)\b|[\s-]+(?<unit>${UNIT_WORD})\b)?`,
38
+ String.raw `(?<=\b(?:within|after|for|in|than|over|under|past|about|every|once|per)\s+)\b(?:an?)\s+(?<aunit>ms|millisecond|sec|second|min|minute|hour|day|week)\b`,
39
+ ].join('|'), 'gi');
40
+ /** Every quantity in a stretch of text, in order. Masked spans (code, dates) should already be blanked out. */
41
+ export function quantities(text) {
42
+ const found = [];
43
+ for (const m of text.matchAll(QUANTITY)) {
44
+ const g = m.groups;
45
+ const start = m.index;
46
+ const end = start + m[0].length;
47
+ const approx = APPROX.test(text.slice(Math.max(0, start - 16), start));
48
+ // "At 08:30, not 08:00": a number ruled out is no claim.
49
+ if (NEGATED.test(text.slice(Math.max(0, start - 16), start)))
50
+ continue;
51
+ const push = (value, unit) => {
52
+ if (Number.isFinite(value))
53
+ found.push({ value, unit, approx, start, end, text: m[0] });
54
+ };
55
+ if (g.ch !== undefined)
56
+ push(Number(g.ch) + Number(g.cm) / 60, 'clock');
57
+ else if (g.amt !== undefined) {
58
+ const scale = g.msfx ? SUFFIX[g.msfx.toLowerCase()] : g.mscale ? SCALE[g.mscale.toLowerCase()] : 1;
59
+ push(Number(g.amt.replace(/,/g, '')) * scale, 'money');
60
+ }
61
+ else if (g.num !== undefined || g.word !== undefined) {
62
+ const unit = g.pct ? 'percent' : g.size ? 'bytes' : g.unit ? timeUnit(g.unit) : null;
63
+ // "one" is mostly a pronoun ("one whose notes…"); it counts only with a unit or a scale.
64
+ if (g.word?.toLowerCase() === 'one' && unit === null && !g.scale)
65
+ continue;
66
+ let value = g.num !== undefined ? Number(g.num.replace(/[,_]/g, '')) : WORDS[g.word.toLowerCase()];
67
+ if (g.nsfx)
68
+ value *= SUFFIX[g.nsfx.toLowerCase()];
69
+ if (g.scale)
70
+ value *= SCALE[g.scale.toLowerCase()];
71
+ if (g.size)
72
+ value *= BYTES[g.size];
73
+ push(value, unit);
74
+ }
75
+ else if (g.aunit !== undefined)
76
+ push(1, timeUnit(g.aunit));
77
+ }
78
+ return found;
79
+ }
@@ -0,0 +1,8 @@
1
+ import type { Config, Finding } from './types.js';
2
+ /** The ways a doc names a file: its path, any tail of it two parts or longer, its bare name unless generic, and any aliases. */
3
+ export declare function namesOf(file: string, aliases?: (file: string) => string[]): string[];
4
+ export declare function docsOf(file: string, root: string, docs: {
5
+ path: string;
6
+ text: string;
7
+ }[], aliases?: (file: string) => string[]): string[];
8
+ export declare function checkOwners(root: string, config: Config, docFiles: string[]): Finding[];