glosslint 0.0.1 → 0.1.1

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.
@@ -1,275 +0,0 @@
1
- import { a as kindOf, c as termKey, n as createMatcher, o as capitalise, s as splitWords } from "./matcher-Xz4vspsE.mjs";
2
- // src/format.ts
3
- const CODES = [
4
- "GLOSSLINT_TERM",
5
- "GLOSSLINT_AVOID",
6
- "GLOSSLINT_CASE"
7
- ];
8
- const FIX_VERBS = {
9
- autofix: "Change to",
10
- suggestion: "Use",
11
- rename: "Rename to"
12
- };
13
- const paint = (on, code, text) => on ? `\u001B[${code}m${text}\u001B[0m` : text;
14
- function isCliFinding(finding) {
15
- return "file" in finding;
16
- }
17
- function termLine(term) {
18
- const description = term.description?.trim().replace(/\s+/g, " ");
19
- if (!description) return term.term;
20
- const lowered = /^\p{Lu}(?![\p{Lu}\p{N}])/u.test(description) ? description.charAt(0).toLowerCase() + description.slice(1) : description;
21
- return `${term.term}, ${lowered}`;
22
- }
23
- /** One finding in the nostics tree format: the headline, then why, fix, term and see. */
24
- function formatFinding(finding, options = {}) {
25
- const color = options.color ?? false;
26
- const where = isCliFinding(finding) ? `${finding.file}:${finding.line}:${finding.column}` : `offset ${finding.start}`;
27
- const headline = `${paint(color, "1;31", `[${finding.code}]`)} "${finding.text}" ${isCliFinding(finding) ? "in" : "at"} ${paint(color, "36", where)}`;
28
- const lines = [];
29
- if (finding.why) lines.push(["why", capitalise(finding.why.trim().replace(/\s+/g, " "))]);
30
- if (finding.fix) {
31
- const result = "result" in finding.fix ? `: "${String(finding.fix.result).trim()}"` : "";
32
- lines.push(["fix", `${FIX_VERBS[finding.fix.kind]} "${finding.fix.replace}"${result}`]);
33
- }
34
- lines.push(["term", termLine(finding.term)]);
35
- if (finding.see) lines.push(["see", finding.see]);
36
- return [headline, ...lines.map(([label, text], index) => {
37
- const branch = index === lines.length - 1 ? "╰▶" : "├▶";
38
- return `${paint(color, "2", branch)} ${paint(color, "1", `${label}:`)} ${text}`;
39
- })].join("\n");
40
- }
41
- function plural(count, word) {
42
- return `${count} ${word}${count === 1 ? "" : "s"}`;
43
- }
44
- /** Every finding in the tree format, followed by a summary line. */
45
- function formatFindings(findings, options = {}) {
46
- const blocks = findings.map((finding) => formatFinding(finding, options));
47
- const withFiles = new Set(findings.filter(isCliFinding).map((finding) => finding.file)).size;
48
- let summary;
49
- if (options.files !== void 0) summary = findings.length === 0 ? `No findings in ${plural(options.files, "file")}.` : `${plural(findings.length, "finding")} in ${withFiles} of ${plural(options.files, "file")}.`;
50
- else summary = findings.length === 0 ? "No findings." : `${plural(findings.length, "finding")}.`;
51
- return [...blocks, summary].join("\n\n");
52
- }
53
- /** The JSON the CLI prints: `{ findings, summary }`. */
54
- function toJson(findings, files) {
55
- const counts = Object.fromEntries(CODES.map((code) => [code, 0]));
56
- for (const finding of findings) counts[finding.code]++;
57
- return {
58
- findings,
59
- summary: {
60
- files,
61
- findings: findings.length,
62
- ...counts
63
- }
64
- };
65
- }
66
- // src/tools.ts
67
- /** Checks every term's examples: each `bad` one must be reported and each `good` one must not. */
68
- function testCorpus(corpus) {
69
- const matcher = createMatcher(corpus);
70
- const failures = [];
71
- for (const term of corpus.terms) {
72
- const key = termKey(term.term);
73
- const about = (finding) => termKey(finding.term.term) === key;
74
- for (const example of term.examples?.good ?? []) {
75
- const findings = matcher.check(example, kindOf({
76
- text: example,
77
- shown: true
78
- }));
79
- if (findings.some(about)) failures.push({
80
- term,
81
- example,
82
- expected: "none",
83
- findings
84
- });
85
- }
86
- for (const example of term.examples?.bad ?? []) {
87
- const findings = matcher.check(example, kindOf({
88
- text: example,
89
- shown: true
90
- }));
91
- if (!findings.some(about)) failures.push({
92
- term,
93
- example,
94
- expected: "finding",
95
- findings
96
- });
97
- }
98
- }
99
- return failures;
100
- }
101
- /** Whether a term says nothing but how it is spelled, so the Markdown glossary lists it on one line. */
102
- function isBare(term) {
103
- return !term.description && !term.nuance && !term.avoid?.length && !term.examples?.good?.length && !term.examples?.bad?.length && !term.links?.length && term.case !== "context" && !term.casing;
104
- }
105
- function sentence(text) {
106
- const trimmed = text.trim().replace(/\s+/g, " ");
107
- return /[.!?:]$/.test(trimmed) ? trimmed : `${trimmed}.`;
108
- }
109
- /** A reason written as an aside: "Racks are unpowered." reads "racks are unpowered". */
110
- function aside(text) {
111
- const trimmed = text.trim().replace(/\s+/g, " ").replace(/[.!]$/, "");
112
- return /^\p{Lu}(?![\p{Lu}\p{N}])/u.test(trimmed) ? trimmed.charAt(0).toLowerCase() + trimmed.slice(1) : trimmed;
113
- }
114
- const quoted = (items) => items.map((item) => `"${item}"`).join(", ");
115
- function avoidList(term) {
116
- if (!term.avoid?.length) return void 0;
117
- return `${term.avoid.map((avoid) => typeof avoid === "string" ? avoid : avoid.why ? `${avoid.word} (${aside(avoid.why)})` : avoid.word).join(", ")}.`;
118
- }
119
- function examplesLine(term) {
120
- const parts = [];
121
- const list = (label, items) => `${label}: ${quoted(items)}${/[.!?]$/.test(items.at(-1).trim()) ? "" : "."}`;
122
- if (term.examples?.good?.length) parts.push(list("Good", term.examples.good));
123
- if (term.examples?.bad?.length) parts.push(list("Bad", term.examples.bad));
124
- return parts.length > 0 ? parts.join(" ") : void 0;
125
- }
126
- /** How the term is written, beyond its spelling: abbreviations and casing. */
127
- function writingLines(term) {
128
- const lines = [];
129
- if (term.abbr?.length) lines.push(`Abbreviation${term.abbr.length > 1 ? "s" : ""}: ${term.abbr.join(", ")}.`);
130
- if (term.case === "exact") lines.push(`Always written "${term.term}".`);
131
- if (term.casing && term.case !== "exact" && term.case !== "spelling") {
132
- const names = {
133
- title: "Title Case",
134
- sentence: "sentence case",
135
- lower: "lowercase",
136
- upper: "ALL CAPS"
137
- };
138
- const styles = Object.entries(term.casing).map(([kind, style]) => `${style === "as-written" ? `"${term.term}"` : names[style]} in ${kind}s`);
139
- lines.push(`Written ${styles.join(", ")}.`);
140
- } else if (term.case === "context") lines.push("Title Case in labels, lowercase in sentences.");
141
- return lines;
142
- }
143
- function spellingName(term) {
144
- return term.abbr?.length ? `${term.term} (${term.abbr.join(", ")})` : term.term;
145
- }
146
- function markdownEntry(term) {
147
- const lines = [`## ${term.term}`];
148
- if (term.description) lines.push(sentence(term.description));
149
- const bullets = [term.nuance && sentence(term.nuance), ...writingLines(term)];
150
- const avoid = avoidList(term);
151
- if (avoid) bullets.push(`Don't write: ${avoid}`);
152
- bullets.push(examplesLine(term));
153
- if (term.links?.length) bullets.push(`See: ${term.links.map((link) => `[${link.title}](${link.url})`).join(", ")}.`);
154
- for (const bullet of bullets) if (bullet) lines.push(`- ${bullet}`);
155
- return lines.join("\n");
156
- }
157
- /**
158
- * The corpus as a Markdown glossary, for agents to read, or as JSON. The Markdown gives each term that
159
- * says more than its spelling a section, and lists the rest on one "Spelling" line.
160
- */
161
- function printCorpus(corpus, format) {
162
- if (format === "json") return `${JSON.stringify({
163
- terms: corpus.terms,
164
- allow: corpus.allow
165
- }, null, 2)}\n`;
166
- const sections = corpus.terms.filter((term) => !isBare(term)).map(markdownEntry);
167
- const bare = corpus.terms.filter(isBare);
168
- if (bare.length > 0) sections.push(`## Spelling\nWrite these as shown: ${bare.map(spellingName).join(", ")}.`);
169
- return `${sections.join("\n\n")}\n`;
170
- }
171
- function mentionPattern(term) {
172
- const words = splitWords(term.term).map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
173
- return new RegExp(`(?<![\\p{L}\\p{N}])${words.join("[\\s\\-‐‑_]*")}(?:e?s)?(?![\\p{L}\\p{N}])`, "iu");
174
- }
175
- /** Looks a key up as written, then as a plural ending in `s` or `es`. */
176
- function byKey(map, key) {
177
- return map.get(key) ?? (key.endsWith("s") ? map.get(key.slice(0, -1)) : void 0) ?? (key.endsWith("es") ? map.get(key.slice(0, -2)) : void 0);
178
- }
179
- const squash = (text) => text.trim().replace(/\s+/g, " ").toLowerCase();
180
- /** The terms a word or phrase is about: as a term, an abbreviation, a form or an avoid word, else the terms it mentions. */
181
- function explainMatches(corpus, query) {
182
- const key = termKey(query);
183
- if (key === "") return [];
184
- const terms = /* @__PURE__ */ new Map();
185
- const abbrs = /* @__PURE__ */ new Map();
186
- const forms = /* @__PURE__ */ new Map();
187
- const avoids = /* @__PURE__ */ new Map();
188
- for (const term of corpus.terms) terms.set(termKey(term.term), term);
189
- for (const term of corpus.terms) {
190
- for (const abbr of term.abbr ?? []) abbrs.set(termKey(abbr), term);
191
- for (const list of Object.values(term.forms ?? {})) for (const form of list) if (!forms.has(termKey(form))) forms.set(termKey(form), term);
192
- for (const avoid of term.avoid ?? []) {
193
- const { word, why } = typeof avoid === "string" ? {
194
- word: avoid,
195
- why: void 0
196
- } : avoid;
197
- const avoidKey = termKey(word);
198
- avoids.set(avoidKey, {
199
- term,
200
- word,
201
- ...why ? { why } : {}
202
- });
203
- }
204
- }
205
- const matches = [];
206
- const add = (term, note) => {
207
- if (matches.some((match) => match.term === term)) return;
208
- matches.push(note ? {
209
- term,
210
- note
211
- } : { term });
212
- };
213
- const asTerm = byKey(terms, key);
214
- if (asTerm) add(asTerm, key === termKey(asTerm.term) && squash(query) !== squash(asTerm.term) ? `"${query.trim()}" is spelled "${asTerm.term}".` : void 0);
215
- const asAbbr = byKey(abbrs, key);
216
- if (asAbbr) add(asAbbr, `"${query.trim()}" abbreviates ${asAbbr.term}.`);
217
- const asForm = byKey(forms, key);
218
- if (asForm) add(asForm, `"${query.trim()}" is a form of ${asForm.term}.`);
219
- const asAvoid = byKey(avoids, key);
220
- if (asAvoid) {
221
- const why = asAvoid.why ? ` ${sentence(capitalise(asAvoid.why))}` : "";
222
- add(asAvoid.term, `"${asAvoid.word}" is an avoid word for ${asAvoid.term.term}.${why}`);
223
- }
224
- if (matches.length > 0) return matches;
225
- for (const finding of createMatcher(corpus).check(query)) {
226
- const note = finding.code === "GLOSSLINT_AVOID" ? `"${finding.text}" is an avoid word for ${finding.term.term}.` : `"${finding.text}" is spelled "${finding.fix?.replace ?? finding.term.term}".`;
227
- add(finding.term, note);
228
- }
229
- if (matches.length > 0) return matches;
230
- for (const term of corpus.terms) if (mentionPattern(term).test(query)) add(term);
231
- return matches;
232
- }
233
- /** Terms with more than a spelling that this term's description or nuance mentions, or whose name contains it. */
234
- function related(corpus, term) {
235
- const text = [term.description, term.nuance].filter(Boolean).join(" ");
236
- const own = mentionPattern(term);
237
- return corpus.terms.filter((other) => other !== term && !isBare(other) && termKey(other.term) !== termKey(term.term) && (mentionPattern(other).test(text) || own.test(other.term)));
238
- }
239
- function explainEntry(corpus, match) {
240
- const { term } = match;
241
- const lines = [
242
- match.note,
243
- term.description && sentence(term.description),
244
- term.nuance && sentence(term.nuance),
245
- ...writingLines(term)
246
- ];
247
- const avoid = avoidList(term);
248
- if (avoid) lines.push(`Avoid: ${avoid}`);
249
- lines.push(examplesLine(term));
250
- for (const link of term.links ?? []) lines.push(`See: ${link.title} ${link.url}`);
251
- const near = related(corpus, term);
252
- if (near.length > 0) lines.push(`Related: ${near.map((other) => other.term).join(", ")}`);
253
- return [term.term, ...lines.filter(Boolean).map((line) => ` ${line}`)].join("\n");
254
- }
255
- /** What the corpus says about a word or phrase: the term it belongs to, its meaning and nuance. */
256
- function explain(corpus, query) {
257
- const matches = explainMatches(corpus, query);
258
- if (matches.length === 0) return `No term in the corpus matches "${query.trim()}".`;
259
- return matches.map((match) => explainEntry(corpus, match)).join("\n\n");
260
- }
261
- /** The corpus as x18n `glossary` entries, with only the fields x18n accepts. */
262
- function toX18nGlossary(corpus) {
263
- return corpus.terms.map((term) => {
264
- const note = [term.description, term.nuance].filter((part) => Boolean(part)).map(sentence).join(" ");
265
- const keep = term.case === "exact" && !term.translations;
266
- return {
267
- term: term.term,
268
- ...term.translations ? { translations: term.translations } : {},
269
- ...term.forms ? { forms: term.forms } : {},
270
- ...note ? { note } : {},
271
- ...keep ? { doNotTranslate: true } : {}
272
- };
273
- });
274
- }
275
- export { toX18nGlossary as a, toJson as c, testCorpus as i, explainMatches as n, formatFinding as o, printCorpus as r, formatFindings as s, explain as t };