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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # liarliar
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Docs that can't lie about the code, even with ten agents editing it.
4
+
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;