@zgeoff/chex 0.5.0 → 0.6.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,97 @@
1
+ import { posix } from 'node:path';
2
+ import { findLastEntry } from './find-last-entry.ts';
3
+ import { joinRawPath } from './join-raw-path.ts';
4
+ import type { JSONCNode } from './parse-jsonc-tree.ts';
5
+ import { parseShellCommands } from './parse-shell-commands.ts';
6
+ import type { ConfigReference } from './types.ts';
7
+
8
+ // npm runs a script from its package.json's folder, so a relative path resolves there, or in the
9
+ // folder an earlier `cd` in the same script moved to.
10
+ export function collectScriptConfigPaths(path: string, root: JSONCNode): ConfigReference[] {
11
+ return collectScripts(root).flatMap((script) => {
12
+ const folders = { current: posix.dirname(path) };
13
+
14
+ return parseShellCommands(script).flatMap((words) => collectCommandPaths(words, folders));
15
+ });
16
+ }
17
+
18
+ function collectScripts(root: JSONCNode): string[] {
19
+ const scripts =
20
+ root.kind === 'object' ? findLastEntry(root.entries, 'scripts')?.value : undefined;
21
+
22
+ return scripts?.kind === 'object'
23
+ ? scripts.entries.flatMap((entry) => (entry.value.kind === 'literal' ? [entry.value.text] : []))
24
+ : [];
25
+ }
26
+
27
+ interface Folders {
28
+ current: string;
29
+ }
30
+
31
+ // Words that may stand before the program in a command: they run it, and add no `-c` of their own.
32
+ const launcherWords = new Set([
33
+ 'bun',
34
+ 'bunx',
35
+ 'command',
36
+ 'dlx',
37
+ 'env',
38
+ 'exec',
39
+ 'nohup',
40
+ 'npx',
41
+ 'pnpm',
42
+ 'run',
43
+ 'time',
44
+ 'x',
45
+ 'yarn',
46
+ ]);
47
+
48
+ function collectCommandPaths(words: readonly string[], folders: Folders): ConfigReference[] {
49
+ const start = words.findIndex((word) => !/^\w+=/u.test(word));
50
+ const first = words[start];
51
+
52
+ if (first === 'cd') {
53
+ const target = words[start + 1];
54
+
55
+ if (target !== undefined) {
56
+ folders.current = joinRawPath(folders.current, target);
57
+ }
58
+
59
+ return [];
60
+ }
61
+
62
+ const program = words.findIndex(
63
+ (word, index) => index >= start && posix.basename(word) === 'oxlint',
64
+ );
65
+
66
+ const isOxlintCommand =
67
+ program !== -1 &&
68
+ words
69
+ .slice(start, program)
70
+ .every((word) => launcherWords.has(posix.basename(word)) || word.startsWith('-'));
71
+
72
+ return isOxlintCommand
73
+ ? words.slice(program + 1).flatMap((word, index, rest) => {
74
+ const value = pickFlagValue(word, rest[index + 1]);
75
+
76
+ return value === null
77
+ ? []
78
+ : [
79
+ {
80
+ path: joinRawPath(folders.current, value),
81
+ isOptional: value.split('/').includes('node_modules'),
82
+ },
83
+ ];
84
+ })
85
+ : [];
86
+ }
87
+
88
+ // `-c file`, `-c=file`, `-cfile`, `--config file` and `--config=file`
89
+ function pickFlagValue(word: string, following: string | undefined): string | null {
90
+ if (word === '-c' || word === '--config') {
91
+ return following ?? null;
92
+ }
93
+
94
+ const match = /^(?:--config=|-c=?)(?<value>.+)$/u.exec(word);
95
+
96
+ return match?.groups?.['value'] ?? null;
97
+ }
@@ -0,0 +1,6 @@
1
+ import type { JSONCEntry } from './parse-jsonc-tree.ts';
2
+
3
+ // oxlint keeps the last of two equal keys in an object.
4
+ export function findLastEntry(entries: readonly JSONCEntry[], key: string): JSONCEntry | undefined {
5
+ return entries.findLast((entry) => entry.key === key);
6
+ }
@@ -0,0 +1,16 @@
1
+ // Joins an entry of a config or a script to the folder it resolves against, and keeps each `..`
2
+ // where it stands, since a link on the way changes what it means. An absolute entry stays absolute.
3
+ // A `.` or an empty segment goes, except at the end, where it still demands a folder.
4
+ export function joinRawPath(folder: string, entry: string): string {
5
+ if (entry.startsWith('/')) {
6
+ return entry;
7
+ }
8
+
9
+ const segments = entry
10
+ .split('/')
11
+ .filter(
12
+ (segment, index, all) => index === all.length - 1 || (segment !== '' && segment !== '.'),
13
+ );
14
+
15
+ return folder === '.' || folder === '' ? segments.join('/') : `${folder}/${segments.join('/')}`;
16
+ }
@@ -0,0 +1,3 @@
1
+ export class JSONCSyntaxError extends Error {
2
+ override name = 'JSONCSyntaxError';
3
+ }
@@ -0,0 +1,85 @@
1
+ import { JSONCSyntaxError } from './jsonc-syntax-error.ts';
2
+
3
+ export interface JSONCToken {
4
+ readonly kind: 'string' | 'other';
5
+
6
+ // A string's content, or the token's own text.
7
+ readonly text: string;
8
+
9
+ // The 1-based line the token starts on.
10
+ readonly line: number;
11
+ }
12
+
13
+ // Reads the tokens of a JSON file that holds comments and trailing commas, as oxlint accepts. The
14
+ // comments are dropped.
15
+ export function parseJSONCTokens(text: string): JSONCToken[] {
16
+ const tokens: JSONCToken[] = [];
17
+ let line = 1;
18
+ let index = 0;
19
+
20
+ const advance = (end: number): number => {
21
+ const start = line;
22
+
23
+ for (let at = index; at < end; at += 1) {
24
+ if (text.charAt(at) === '\n') {
25
+ line += 1;
26
+ }
27
+ }
28
+
29
+ index = end;
30
+
31
+ return start;
32
+ };
33
+
34
+ while (index < text.length) {
35
+ const character = text.charAt(index);
36
+ const next = text.charAt(index + 1);
37
+
38
+ if (/\s/u.test(character)) {
39
+ advance(index + 1);
40
+ } else if (character === '/' && (next === '/' || next === '*')) {
41
+ const close = next === '/' ? text.indexOf('\n', index) : text.indexOf('*/', index + 2);
42
+ const end = close === -1 ? text.length : close;
43
+ const after = next === '/' || close === -1 ? end : end + 2;
44
+
45
+ advance(after);
46
+ } else if (character === '"') {
47
+ const end = getStringEnd(text, index);
48
+ const body = parseString(text.slice(index, end));
49
+ const start = advance(end);
50
+
51
+ tokens.push({ kind: 'string', text: body, line: start });
52
+ } else {
53
+ const word = /^[\w.+-]+/u.exec(text.slice(index))?.[0] ?? character;
54
+ const start = advance(index + word.length);
55
+
56
+ tokens.push({ kind: 'other', text: word, line: start });
57
+ }
58
+ }
59
+
60
+ return tokens;
61
+ }
62
+
63
+ function getStringEnd(text: string, start: number): number {
64
+ for (let index = start + 1; index < text.length; index += 1) {
65
+ const character = text.charAt(index);
66
+
67
+ if (character === '\\') {
68
+ index += 1;
69
+ } else if (character === '"') {
70
+ return index + 1;
71
+ }
72
+ }
73
+
74
+ throw new JSONCSyntaxError('a string never closes');
75
+ }
76
+
77
+ function parseString(literal: string): string {
78
+ try {
79
+ return String(JSON.parse(literal));
80
+ } catch (error) {
81
+ const reason = error instanceof Error ? error.message : String(error);
82
+
83
+ throw new JSONCSyntaxError(reason, { cause: error });
84
+ }
85
+ }
@@ -0,0 +1,132 @@
1
+ import { JSONCSyntaxError } from './jsonc-syntax-error.ts';
2
+ import type { JSONCToken } from './parse-jsonc-tokens.ts';
3
+ import { parseJSONCTokens } from './parse-jsonc-tokens.ts';
4
+
5
+ export type JSONCNode =
6
+ | { readonly kind: 'object'; readonly entries: readonly JSONCEntry[] }
7
+ | { readonly kind: 'array'; readonly items: readonly JSONCNode[] }
8
+ | { readonly kind: 'literal'; readonly text: string; readonly line: number };
9
+
10
+ export type JSONCTreeResult =
11
+ | { readonly isValid: true; readonly root: JSONCNode }
12
+ | { readonly isValid: false; readonly reason: string };
13
+
14
+ // Reads a JSON file that holds comments and trailing commas into a tree that keeps each key's line,
15
+ // and refuses what oxlint refuses, such as `undefined` or a missing comma.
16
+ export function parseJSONCTree(text: string): JSONCTreeResult {
17
+ try {
18
+ const tokens = parseJSONCTokens(text);
19
+ const cursor = { index: 0 };
20
+ const root = parseNode(tokens, cursor);
21
+
22
+ if (cursor.index < tokens.length) {
23
+ throw new JSONCSyntaxError('unexpected text after the first value');
24
+ }
25
+
26
+ return { isValid: true, root };
27
+ } catch (error) {
28
+ if (error instanceof JSONCSyntaxError) {
29
+ return { isValid: false, reason: error.message };
30
+ }
31
+
32
+ throw error;
33
+ }
34
+ }
35
+
36
+ interface Cursor {
37
+ index: number;
38
+ }
39
+
40
+ const bareValuePattern = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)$/u;
41
+
42
+ function parseNode(tokens: readonly JSONCToken[], cursor: Cursor): JSONCNode {
43
+ const token = tokens[cursor.index];
44
+
45
+ if (token === undefined) {
46
+ throw new JSONCSyntaxError('the file ends inside a value');
47
+ }
48
+
49
+ cursor.index += 1;
50
+
51
+ if (token.kind === 'other' && token.text === '{') {
52
+ return { kind: 'object', entries: parseEntries(tokens, cursor) };
53
+ }
54
+
55
+ if (token.kind === 'other' && token.text === '[') {
56
+ return { kind: 'array', items: parseItems(tokens, cursor) };
57
+ }
58
+
59
+ if (token.kind === 'other' && !bareValuePattern.test(token.text)) {
60
+ throw new JSONCSyntaxError(`line ${token.line} holds \`${token.text}\`, which is no value`);
61
+ }
62
+
63
+ return { kind: 'literal', text: token.text, line: token.line };
64
+ }
65
+
66
+ export interface JSONCEntry {
67
+ readonly key: string;
68
+ readonly line: number;
69
+ readonly value: JSONCNode;
70
+ }
71
+
72
+ function parseEntries(tokens: readonly JSONCToken[], cursor: Cursor): JSONCEntry[] {
73
+ const entries: JSONCEntry[] = [];
74
+
75
+ for (;;) {
76
+ const key = tokens[cursor.index];
77
+
78
+ if (key === undefined) {
79
+ throw new JSONCSyntaxError('an object never closes');
80
+ }
81
+
82
+ cursor.index += 1;
83
+
84
+ if (key.kind === 'other' && key.text === '}') {
85
+ return entries;
86
+ }
87
+
88
+ if (key.kind !== 'string' || tokens[cursor.index]?.text !== ':') {
89
+ throw new JSONCSyntaxError(`line ${key.line} holds no key`);
90
+ }
91
+
92
+ cursor.index += 1;
93
+
94
+ entries.push({ key: key.text, line: key.line, value: parseNode(tokens, cursor) });
95
+
96
+ skipSeparator(tokens, cursor, '}');
97
+ }
98
+ }
99
+
100
+ // After a value, takes the comma that separates it from the next one, and leaves the closing token
101
+ // for the caller.
102
+ function skipSeparator(tokens: readonly JSONCToken[], cursor: Cursor, closer: string): void {
103
+ const next = tokens[cursor.index];
104
+
105
+ if (next?.kind === 'other' && next.text === ',') {
106
+ cursor.index += 1;
107
+ } else if (next !== undefined && !(next.kind === 'other' && next.text === closer)) {
108
+ throw new JSONCSyntaxError(`line ${next.line} holds no comma or \`${closer}\``);
109
+ }
110
+ }
111
+
112
+ function parseItems(tokens: readonly JSONCToken[], cursor: Cursor): JSONCNode[] {
113
+ const items: JSONCNode[] = [];
114
+
115
+ for (;;) {
116
+ const next = tokens[cursor.index];
117
+
118
+ if (next === undefined) {
119
+ throw new JSONCSyntaxError('an array never closes');
120
+ }
121
+
122
+ if (next.kind === 'other' && next.text === ']') {
123
+ cursor.index += 1;
124
+
125
+ return items;
126
+ }
127
+
128
+ items.push(parseNode(tokens, cursor));
129
+
130
+ skipSeparator(tokens, cursor, ']');
131
+ }
132
+ }
@@ -0,0 +1,57 @@
1
+ // Splits a shell script into its commands, each as its words with the quotes taken off. An unquoted
2
+ // `&&`, `||`, `;`, `|`, `&`, a parenthesis or a line break ends a command.
3
+ export function parseShellCommands(script: string): string[][] {
4
+ const commands: string[][] = [];
5
+ let words: string[] = [];
6
+ let word: string | null = null;
7
+ let quote: string | null = null;
8
+
9
+ const endWord = (): void => {
10
+ if (word !== null) {
11
+ words.push(word);
12
+
13
+ word = null;
14
+ }
15
+ };
16
+
17
+ const endCommand = (): void => {
18
+ endWord();
19
+
20
+ if (words.length > 0) {
21
+ commands.push(words);
22
+
23
+ words = [];
24
+ }
25
+ };
26
+
27
+ for (let index = 0; index < script.length; index += 1) {
28
+ const character = script.charAt(index);
29
+
30
+ if (quote !== null) {
31
+ if (character === quote) {
32
+ quote = null;
33
+ } else if (character === '\\' && quote === '"' && index + 1 < script.length) {
34
+ index += 1;
35
+ word = (word ?? '') + script.charAt(index);
36
+ } else {
37
+ word = (word ?? '') + character;
38
+ }
39
+ } else if (character === '"' || character === "'") {
40
+ quote = character;
41
+ word ??= '';
42
+ } else if (character === '\\' && index + 1 < script.length) {
43
+ index += 1;
44
+ word = (word ?? '') + script.charAt(index);
45
+ } else if (/\s/u.test(character) && character !== '\n') {
46
+ endWord();
47
+ } else if (/[\n;&|()]/u.test(character)) {
48
+ endCommand();
49
+ } else {
50
+ word = (word ?? '') + character;
51
+ }
52
+ }
53
+
54
+ endCommand();
55
+
56
+ return commands;
57
+ }
@@ -0,0 +1,19 @@
1
+ import type { TreeEntry } from './types.ts';
2
+
3
+ // git ls-tree -z prints "<mode> <type> <object>\t<path>" per entry; mode 120000 is a link. An entry
4
+ // that is no file and no link, such as a submodule, drops out.
5
+ export function parseTreeEntries(output: string): TreeEntry[] {
6
+ return output
7
+ .split('\0')
8
+ .filter((line) => line.includes('\t'))
9
+ .flatMap((line): TreeEntry[] => {
10
+ const tabIndex = line.indexOf('\t');
11
+ const path = line.slice(tabIndex + 1);
12
+
13
+ if (line.startsWith('120000 ')) {
14
+ return [{ path, isLink: true }];
15
+ }
16
+
17
+ return / blob /u.test(line.slice(0, tabIndex)) ? [{ path, isLink: false }] : [];
18
+ });
19
+ }
@@ -0,0 +1,59 @@
1
+ import type { TrackedTree } from './types.ts';
2
+
3
+ const maxLinkHops = 40;
4
+
5
+ // Follows each tracked link on the way, a linked folder in the middle too, as the operating system
6
+ // would. Returns the tracked file the path ends at, or null when the path ends at no file, leaves
7
+ // the repo, loops, is absolute, or treats a file as a folder.
8
+ export function resolveTrackedPath(path: string, tree: Readonly<TrackedTree>): string | null {
9
+ if (path.startsWith('/')) {
10
+ return null;
11
+ }
12
+
13
+ const done: string[] = [];
14
+ const pending = path.split('/');
15
+ let hops = 0;
16
+
17
+ while (pending.length > 0) {
18
+ const segment = pending.shift();
19
+
20
+ if (segment === undefined) {
21
+ continue;
22
+ }
23
+
24
+ if (segment === '' || segment === '.' || segment === '..') {
25
+ if (done.length > 0 && !tree.directories.has(done.join('/'))) {
26
+ return null;
27
+ }
28
+
29
+ if (segment === '..') {
30
+ if (done.length === 0) {
31
+ return null;
32
+ }
33
+
34
+ done.pop();
35
+ }
36
+
37
+ continue;
38
+ }
39
+
40
+ done.push(segment);
41
+
42
+ const target = tree.links.get(done.join('/'));
43
+
44
+ if (target !== undefined) {
45
+ hops += 1;
46
+
47
+ if (hops > maxLinkHops || target.startsWith('/')) {
48
+ return null;
49
+ }
50
+
51
+ done.pop();
52
+ pending.unshift(...target.split('/'));
53
+ }
54
+ }
55
+
56
+ const resolved = done.join('/');
57
+
58
+ return tree.files.has(resolved) ? resolved : null;
59
+ }
@@ -0,0 +1,75 @@
1
+ import type { RunProgram } from '../program/run-program.ts';
2
+ import { runProgram } from '../program/run-program.ts';
3
+ import { buildTrackedTree } from './build-tracked-tree.ts';
4
+ import { collectConfigReport } from './collect-config-report.ts';
5
+ import { parseTreeEntries } from './parse-tree-entries.ts';
6
+ import type { LintOverrideFinding } from './types.ts';
7
+
8
+ export interface LintOverridesCheckOptions {
9
+ readonly cwd: string;
10
+ readonly env: Readonly<Record<string, string | undefined>>;
11
+ readonly runProgram: RunProgram;
12
+ }
13
+
14
+ // The check reads the files as HEAD holds them, so a push checks what it sends. Each file is read
15
+ // once: the report names the files it still needs, and the loop reads them and asks again.
16
+ export function runLintOverridesCheck(
17
+ options: Readonly<LintOverridesCheckOptions>,
18
+ ): LintOverrideFinding[] {
19
+ const entries = parseTreeEntries(runGit(options, ['ls-tree', '-r', '-z', 'HEAD']));
20
+
21
+ const linkTargets = new Map(
22
+ entries
23
+ .filter((entry) => entry.isLink)
24
+ .map((entry) => [entry.path, runGit(options, ['show', `HEAD:${entry.path}`])]),
25
+ );
26
+
27
+ const tree = buildTrackedTree(entries, linkTargets);
28
+
29
+ const texts = new Map<string, string>();
30
+
31
+ for (;;) {
32
+ const report = collectConfigReport(tree, texts);
33
+
34
+ if (report.missing.length === 0) {
35
+ return report.findings;
36
+ }
37
+
38
+ for (const file of report.missing) {
39
+ texts.set(file, runGit(options, ['show', `HEAD:${file}`]));
40
+ }
41
+ }
42
+ }
43
+
44
+ function runGit(options: Readonly<LintOverridesCheckOptions>, args: readonly string[]): string {
45
+ const result = options.runProgram(['git', ...args], { cwd: options.cwd, env: options.env });
46
+
47
+ if (result.exitCode !== 0) {
48
+ throw new Error(`git ${args.join(' ')} failed: ${result.stderr.trim()}`);
49
+ }
50
+
51
+ return result.stdout;
52
+ }
53
+
54
+ // Returns the exit code: 0 when clean, 1 with a finding, and 2 when the check cannot run.
55
+ export function runLintOverridesCommand(): number {
56
+ try {
57
+ const findings = runLintOverridesCheck({ cwd: process.cwd(), env: process.env, runProgram });
58
+
59
+ for (const finding of findings) {
60
+ process.stdout.write(`${finding.path}: ${finding.message}\n`);
61
+ }
62
+
63
+ return findings.length === 0 ? 0 : 1;
64
+ } catch (error) {
65
+ process.stderr.write(
66
+ `lint-overrides: ${error instanceof Error ? error.message : String(error)}\n`,
67
+ );
68
+
69
+ return 2;
70
+ }
71
+ }
72
+
73
+ if (import.meta.main) {
74
+ process.exitCode = runLintOverridesCommand();
75
+ }
@@ -0,0 +1,11 @@
1
+ // The files of @zgeoff/std that hold a type assertion. The tools repo alone may switch off
2
+ // typescript/consistent-type-assertions for these. @zgeoff/oxlint-config holds the same list, and a
3
+ // test keeps the two equal.
4
+ export const stdHelperPaths: readonly string[] = [
5
+ 'packages/std/src/objects/merge-deep.ts',
6
+ 'packages/std/src/types/machine-types.ts',
7
+ 'packages/std/src/types/to-exact-optional.ts',
8
+ 'packages/std/src/types/to-readonly-deep.ts',
9
+ 'packages/std/src/types/to-rows.ts',
10
+ 'packages/std/src/types/to-tagged.ts',
11
+ ];
@@ -0,0 +1,30 @@
1
+ export interface TrackedTree {
2
+ // Each tracked link, with the target text it holds.
3
+ readonly links: ReadonlyMap<string, string>;
4
+
5
+ // Each tracked file that is no link.
6
+ readonly files: ReadonlySet<string>;
7
+
8
+ // Each folder that holds a tracked file or link, at any depth.
9
+ readonly directories: ReadonlySet<string>;
10
+ }
11
+
12
+ export interface TreeEntry {
13
+ readonly path: string;
14
+ readonly isLink: boolean;
15
+ }
16
+
17
+ export interface LintOverrideFinding {
18
+ // Relative to the repo root.
19
+ readonly path: string;
20
+
21
+ readonly message: string;
22
+ }
23
+
24
+ export interface ConfigReference {
25
+ // The path as written against the folder of the referring file, with each `..` kept in place.
26
+ readonly path: string;
27
+
28
+ // True for a reference that may name a package, and so may leave no tracked file.
29
+ readonly isOptional: boolean;
30
+ }