glosslint 0.0.0 → 0.0.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.
@@ -0,0 +1,275 @@
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 };
@@ -0,0 +1,190 @@
1
+ /** A word or phrase to avoid, with the reason a finding prints. */
2
+ interface Avoid {
3
+ /** The word or phrase to avoid, matched in any case unless it has two capitals in a row. */
4
+ word: string;
5
+ /** Why to avoid it, printed as the finding's `why`. */
6
+ why?: string;
7
+ }
8
+ /** A link printed as a finding's `see`. */
9
+ interface Link {
10
+ /** The link's text, such as the title of the page. */
11
+ title: string;
12
+ /** Where the term is explained. */
13
+ url: string;
14
+ }
15
+ /** How a term's capitals are checked. */
16
+ type CaseMode = "exact" | "spelling" | "context";
17
+ /**
18
+ * How a `context` term is written in one kind of text: `title` (Title Case), `sentence` (lowercase, with a capital at
19
+ * the start of a sentence), `lower`, `upper` (ALL CAPS) or `as-written` (the term exactly as the corpus writes it).
20
+ */
21
+ type CaseStyle = "title" | "sentence" | "lower" | "upper" | "as-written";
22
+ /** The kinds of text whose casing a corpus or a term can set. */
23
+ type CasingKind = "label" | "header" | "sentence";
24
+ /** The case style per kind of text. A header takes the label's style unless it sets its own. */
25
+ type Casing = Partial<Record<CasingKind, CaseStyle>>;
26
+ /** One term of the corpus: the words to use, what they mean, and the words to avoid. */
27
+ interface Term {
28
+ /** The term as it should be written, such as `Dock` or `eBike`. */
29
+ term: string;
30
+ /** What the concept is, in one sentence. Printed in every finding about the term. */
31
+ description?: string;
32
+ /** How it differs from near terms and when not to use it. Printed in findings for avoid words. */
33
+ nuance?: string;
34
+ /** Abbreviations of the term, always checked as `exact`, such as `DP` for `Day Pass`. */
35
+ abbr?: string[];
36
+ /** Words to avoid in favour of this term, each a word or `{ word, why }`. */
37
+ avoid?: (string | Avoid)[];
38
+ /** Strings `glosslint test` expects to pass (`good`) or to be reported (`bad`). */
39
+ examples?: {
40
+ good?: string[];
41
+ bad?: string[];
42
+ };
43
+ /** Pages that explain the term; the first is printed as the finding's `see`. */
44
+ links?: Link[];
45
+ /** `exact`: one form everywhere. `spelling` (default): word splits and hyphens only, in any case. `context`: Title Case in labels, lowercase in sentences. */
46
+ case?: CaseMode;
47
+ /** This term's case style per kind of text, over the corpus's `casing`. Setting it makes the term `context` unless `case` says otherwise. */
48
+ casing?: Casing;
49
+ /** Whole-word casings that always pass, as case-police skips `github` and `GITHUB`. */
50
+ skip?: ("lower" | "upper")[];
51
+ /** Other forms per locale, such as inflections, passed to x18n's glossary as they are. */
52
+ forms?: Record<string, string[]>;
53
+ /** The term's translation per locale, passed to x18n's glossary as it is. */
54
+ translations?: Record<string, string>;
55
+ }
56
+ /** What `defineCorpus` takes: presets and other corpora to extend, your own terms, and allowed phrases. */
57
+ interface CorpusInput {
58
+ /** Corpora to merge first, such as presets. Later ones win per term, and `terms` win over all of them. */
59
+ extends?: Corpus[];
60
+ /** Your own terms, which win over every term from `extends` with the same words. */
61
+ terms?: Term[];
62
+ /** Phrases that are never reported, such as `roof rack`. A finding inside one is dropped. */
63
+ allow?: string[];
64
+ /** The case style of `context` terms per kind of text. Default: `title` in labels and headers, `sentence` in sentences. */
65
+ casing?: Casing;
66
+ /**
67
+ * Also write a label or header that holds a `context` term wholly in its style, when that style is
68
+ * `title` or `upper`, so "Day pass price" becomes "Day Pass Price". Off by default: only the term is checked.
69
+ */
70
+ wholeLabel?: boolean;
71
+ }
72
+ /** A validated, flattened corpus, as `defineCorpus` returns it. */
73
+ interface Corpus {
74
+ /** Marks the object as the output of `defineCorpus`. */
75
+ readonly kind: "glosslint.corpus";
76
+ /** Every term after merging, one per key. */
77
+ readonly terms: readonly Term[];
78
+ /** Every allowed phrase, from `extends` first. */
79
+ readonly allow: readonly string[];
80
+ /** The case style per kind of text, from `extends` first, then the corpus's own. */
81
+ readonly casing?: Readonly<Casing>;
82
+ /** Whether labels and headers holding a `context` term follow their style as a whole. */
83
+ readonly wholeLabel?: boolean;
84
+ }
85
+ /** What a string is, which decides how `context` terms are cased and which checks run. */
86
+ type TextKind = "label" | "header" | "sentence" | "comment" | "identifier" | "unknown";
87
+ /** A string an adapter is about to check, as the `kindOf` option sees it. */
88
+ interface KindSite {
89
+ /** The string. */
90
+ text: string;
91
+ /** The key, attribute, variable, slot or element tag the string belongs to, such as `headerName` or `h2`. */
92
+ name?: string;
93
+ /** The file the string is in, when the adapter knows it. */
94
+ file?: string;
95
+ /** Whether a person reads the string as it stands, as template text and locale messages are, so its shape may place it. */
96
+ shown?: boolean;
97
+ }
98
+ /** Decides the kind of a string an adapter checks, or returns `undefined` to leave it to glosslint's `kindOf`. */
99
+ type KindOf = (site: KindSite) => TextKind | undefined;
100
+ /** What a finding may do: `autofix` applies alone, `suggestion` needs a person to pick it, `rename` touches every caller. */
101
+ type FixKind = "autofix" | "suggestion" | "rename";
102
+ /** The code of a finding: a different spelling of a term, an avoid word, or wrong capitals. */
103
+ type FindingCode = "GLOSSLINT_TERM" | "GLOSSLINT_AVOID" | "GLOSSLINT_CASE";
104
+ /** A replacement for the reported text. */
105
+ interface Fix {
106
+ /** Whether the fix applies alone, needs a person, or renames a symbol. */
107
+ kind: FixKind;
108
+ /** The text that replaces `text`, between `start` and `end`. */
109
+ replace: string;
110
+ }
111
+ /** One problem the matcher found in a string. */
112
+ interface Finding {
113
+ /** Which kind of problem it is. */
114
+ code: FindingCode;
115
+ /** Offset of the reported text's first character in the checked string. */
116
+ start: number;
117
+ /** Offset just past the reported text's last character. */
118
+ end: number;
119
+ /** The reported text, as written. */
120
+ text: string;
121
+ /** The one-line headline, such as `Use "dock" instead of "rack".` */
122
+ message: string;
123
+ /** Why it is reported: the avoid word's reason, or the term's nuance. */
124
+ why?: string;
125
+ /** The replacement, when there is one. */
126
+ fix?: Fix;
127
+ /** The corpus term the finding is about. */
128
+ term: Term;
129
+ /** The first of the term's links. */
130
+ see?: string;
131
+ }
132
+ /** The parts of a term that a CLI finding carries. */
133
+ type TermSummary = Pick<Term, "term" | "description" | "nuance">;
134
+ /** A finding as the CLI prints it, in a file. */
135
+ interface CliFinding extends Omit<Finding, "fix" | "term"> {
136
+ /** The file's path, relative to the current folder. */
137
+ file: string;
138
+ /** 1-based line of `start`. */
139
+ line: number;
140
+ /** 1-based column of `start`. */
141
+ column: number;
142
+ /** The replacement, with `result`, the line as it reads once fixed. */
143
+ fix?: Fix & {
144
+ result: string;
145
+ };
146
+ /** The term's name, description and nuance. */
147
+ term: TermSummary;
148
+ }
149
+ /** What `glosslint check --format json` prints. */
150
+ interface CliReport {
151
+ /** Every finding, in file order. */
152
+ findings: CliFinding[];
153
+ /** How many files were read and how many findings each code has. */
154
+ summary: {
155
+ files: number;
156
+ findings: number;
157
+ } & Record<FindingCode, number>;
158
+ }
159
+ /** A corpus compiled for matching, from `createMatcher`. */
160
+ interface Matcher {
161
+ /** The corpus the matcher was built from. */
162
+ readonly corpus: Corpus;
163
+ /** Finds every problem in `text`, read as `kind` (default `unknown`). */
164
+ check(text: string, kind?: TextKind): Finding[];
165
+ }
166
+ /** An example of a term that did not behave as `examples` says. */
167
+ interface CorpusTestFailure {
168
+ /** The term whose example failed. */
169
+ term: Term;
170
+ /** The example string. */
171
+ example: string;
172
+ /** `finding` for a `bad` example that passed, `none` for a `good` example that was reported. */
173
+ expected: "finding" | "none";
174
+ /** What the matcher reported for the example. */
175
+ findings: Finding[];
176
+ }
177
+ /** One entry of x18n's `glossary`, the fields x18n accepts. */
178
+ interface X18nGlossaryEntry {
179
+ /** The term in the source locale. */
180
+ term: string;
181
+ /** The translation per locale. */
182
+ translations?: Record<string, string>;
183
+ /** Other forms per locale. */
184
+ forms?: Record<string, string[]>;
185
+ /** The description and nuance, for translators. */
186
+ note?: string;
187
+ /** Whether every locale keeps the term as it is, as for brands. */
188
+ doNotTranslate?: boolean;
189
+ }
190
+ export { X18nGlossaryEntry as S, Link as _, CasingKind as a, TermSummary as b, Corpus as c, Finding as d, FindingCode as f, KindSite as g, KindOf as h, Casing as i, CorpusInput as l, FixKind as m, CaseMode as n, CliFinding as o, Fix as p, CaseStyle as r, CliReport as s, Avoid as t, CorpusTestFailure as u, Matcher as v, TextKind as x, Term as y };
@@ -0,0 +1,23 @@
1
+ import { c as Corpus, h as KindOf } from "./types-CBQGgzID.mjs";
2
+ import { Plugin } from "@x18n/core";
3
+ /** Options of the x18n plugin. */
4
+ export interface GlosslintX18nOptions {
5
+ /** The corpus, usually `import corpus from './glosslint.config.ts'`. */
6
+ corpus: Corpus;
7
+ /** The locale whose messages are checked. Default: the project's source locale. */
8
+ sourceLocale?: string;
9
+ /**
10
+ * Decides whether a message or hard string is a label, header or sentence before glosslint's own
11
+ * `kindOf`. Return `undefined` to leave it to glosslint.
12
+ */
13
+ kindOf?: KindOf;
14
+ }
15
+ declare module "@x18n/core" {
16
+ interface CheckIds {
17
+ "glosslint-term": true;
18
+ "glosslint-avoid": true;
19
+ "glosslint-case": true;
20
+ }
21
+ }
22
+ /** An x18n plugin that checks source-locale messages and hard strings against the corpus. */
23
+ export default function glosslint(options: GlosslintX18nOptions): Plugin;
package/dist/x18n.mjs ADDED
@@ -0,0 +1,156 @@
1
+ import { i as classify, n as createMatcher, r as caseModeOf } from "./matcher-Xz4vspsE.mjs";
2
+ // src/x18n.ts
3
+ const CHECKS = [
4
+ {
5
+ id: "glosslint-term",
6
+ code: "GLOSSLINT_TERM",
7
+ defaultSeverity: "error",
8
+ description: "A corpus term written with other words, splits or hyphens."
9
+ },
10
+ {
11
+ id: "glosslint-avoid",
12
+ code: "GLOSSLINT_AVOID",
13
+ defaultSeverity: "warning",
14
+ description: "A word the corpus says to avoid, with the term to use instead."
15
+ },
16
+ {
17
+ id: "glosslint-case",
18
+ code: "GLOSSLINT_CASE",
19
+ defaultSeverity: "error",
20
+ description: "A corpus term written with the wrong capitals."
21
+ }
22
+ ];
23
+ /**
24
+ * Where `value` starts inside `range` of the file: at the range's start when the file holds it as is, one past it when
25
+ * the range only adds quotes. Undefined when escapes or template arguments make offsets differ.
26
+ */
27
+ function valueStart(text, range, value) {
28
+ const raw = text?.slice(range.start, range.end);
29
+ if (raw === value) return range.start;
30
+ if (raw?.length === value.length + 2 && raw.slice(1, -1) === value) return range.start + 1;
31
+ }
32
+ function locate(path, range, start, finding) {
33
+ if (path === void 0 || range === void 0) return void 0;
34
+ return {
35
+ path,
36
+ range: start === void 0 ? range : {
37
+ start: start + finding.start,
38
+ end: start + finding.end
39
+ }
40
+ };
41
+ }
42
+ /** Applies the autofixes right to left, skipping one that overlaps a fix already applied. */
43
+ function applyFixes(value, findings) {
44
+ let out = value;
45
+ let limit = value.length;
46
+ for (const finding of [...findings].sort((a, b) => b.start - a.start)) {
47
+ if (!finding.fix || finding.end > limit) continue;
48
+ out = out.slice(0, finding.start) + finding.fix.replace + out.slice(finding.end);
49
+ limit = finding.start;
50
+ }
51
+ return out;
52
+ }
53
+ /**
54
+ * The fixes of a message finding. x18n's `--fix` keeps the first `set` of a key, so when a message has several
55
+ * autofixes, each finding's safe fix applies all of them, and a quick fix without a level applies only its own.
56
+ * A fix left out of `autofixes`, because only the message's shape placed it, gets only the quick fix.
57
+ */
58
+ function messageFixes(message, value, finding, autofixes) {
59
+ if (finding.fix?.kind !== "autofix") return [];
60
+ const set = (findings) => [{
61
+ type: "set",
62
+ key: message.key,
63
+ locale: message.locale,
64
+ value: applyFixes(value, findings)
65
+ }];
66
+ const own = `Change "${finding.text}" to "${finding.fix.replace}"`;
67
+ if (!autofixes.includes(finding)) return [{
68
+ title: own,
69
+ ops: set([finding])
70
+ }];
71
+ if (autofixes.length === 1) return [{
72
+ title: own,
73
+ level: "safe",
74
+ ops: set(autofixes)
75
+ }];
76
+ return [{
77
+ title: `Fix ${autofixes.length} terms in "${message.key}"`,
78
+ level: "safe",
79
+ ops: set(autofixes)
80
+ }, {
81
+ title: own,
82
+ ops: set([finding])
83
+ }];
84
+ }
85
+ /** An x18n plugin that checks source-locale messages and hard strings against the corpus. */
86
+ function glosslint(options) {
87
+ const matcher = createMatcher(options.corpus);
88
+ function* collect(ctx) {
89
+ const locale = options.sourceLocale ?? ctx.sourceLocale;
90
+ const paths = new Map(ctx.resources.map((resource) => [resource.id, resource.path]));
91
+ for (const message of ctx.messages(locale)) {
92
+ const value = message.value;
93
+ if (typeof value !== "string") continue;
94
+ const path = paths.get(message.resource);
95
+ const { kind, guessed } = classify({
96
+ name: message.key,
97
+ text: value,
98
+ shown: true,
99
+ ...path ? { file: path } : {}
100
+ }, options.kindOf);
101
+ const findings = matcher.check(value, kind);
102
+ if (findings.length === 0) continue;
103
+ const range = message.range?.value;
104
+ const start = path !== void 0 && range ? valueStart(ctx.text(path), range, value) : void 0;
105
+ const safe = (finding) => finding.fix?.kind === "autofix" && !(guessed && caseModeOf(finding.term) === "context");
106
+ const autofixes = findings.filter(safe);
107
+ for (const finding of findings) yield {
108
+ code: finding.code,
109
+ diagnostic: {
110
+ key: message.key,
111
+ locale: message.locale,
112
+ message: finding.message,
113
+ location: locate(path, range, start, finding),
114
+ fixes: messageFixes(message, value, finding, autofixes)
115
+ }
116
+ };
117
+ }
118
+ for (const hard of ctx.hardStrings()) {
119
+ const { kind } = classify({
120
+ text: hard.text,
121
+ file: hard.path,
122
+ shown: hard.attribute === void 0,
123
+ ...hard.attribute !== void 0 ? { name: hard.attribute } : {}
124
+ }, options.kindOf);
125
+ const findings = matcher.check(hard.text, kind);
126
+ if (findings.length === 0) continue;
127
+ const start = valueStart(ctx.text(hard.path), hard.range, hard.text);
128
+ for (const finding of findings) yield {
129
+ code: finding.code,
130
+ diagnostic: {
131
+ message: finding.message,
132
+ location: locate(hard.path, hard.range, start, finding)
133
+ }
134
+ };
135
+ }
136
+ }
137
+ let cache;
138
+ const items = (ctx) => {
139
+ if (cache?.source !== ctx.messages) cache = {
140
+ source: ctx.messages,
141
+ items: [...collect(ctx)]
142
+ };
143
+ return cache.items;
144
+ };
145
+ return {
146
+ name: "glosslint",
147
+ checks: CHECKS.map(({ code, ...check }) => ({
148
+ ...check,
149
+ docs: "https://github.com/onmax/glosslint#readme",
150
+ *run(ctx) {
151
+ for (const item of items(ctx)) if (item.code === code) yield item.diagnostic;
152
+ }
153
+ }))
154
+ };
155
+ }
156
+ export { glosslint as default };