@inflexa-ai/typecheck 0.5.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.
@@ -0,0 +1,48 @@
1
+ import { type Diagnostic, type Program } from 'typescript/unstable/sync';
2
+ import type { ProjectFiles } from './projects.ts';
3
+ /**
4
+ * The diagnostics of a program in the order and with the gates of `tsc`: the
5
+ * `GetDiagnosticsOfAnyProgram` and `EmitFilesAndReportErrors` path of
6
+ * typescript-go at `typescript/v7.0.2`. A syntax error hides the options, the
7
+ * global and the semantic diagnostics, and an option or a global error hides
8
+ * the semantic ones, as in `tsc`.
9
+ *
10
+ * The declaration diagnostics join in two ways, as in `tsc` under `noEmit`,
11
+ * which the virtual tsconfig of the command always sets. The gated path adds
12
+ * them when nothing else was found. Outside of an incremental or composite
13
+ * project, the emit of `tsc` also runs the declaration transform on each file
14
+ * and adds its diagnostics beside the others, unless `noEmitOnError` stopped
15
+ * the emit on an earlier error.
16
+ */
17
+ export declare function collectDiagnostics(program: Program): Diagnostic[];
18
+ /**
19
+ * A diagnostic of the program of a virtual tsconfig as `tsc` gives it for the
20
+ * real one. Each mention of the virtual file names the real file. A location
21
+ * in the virtual file moves to the real file: an offset after the inserted
22
+ * text moves back by its length, and a diagnostic on the inserted text has no
23
+ * location, as a diagnostic of an option of the command line of `tsc` has none.
24
+ */
25
+ export declare function withRealConfig(diagnostic: Diagnostic, { virtual, tsconfig, insertion }: ProjectFiles): Diagnostic;
26
+ /**
27
+ * `SortAndDeduplicateDiagnostics` of typescript-go. The API gives the text of
28
+ * a message and not its arguments, thus the text stands for the arguments:
29
+ * two diagnostics with one code and one location differ in their arguments
30
+ * exactly when their texts differ.
31
+ */
32
+ export declare function sortAndDeduplicate(diagnostics: readonly Diagnostic[]): Diagnostic[];
33
+ /** A line and a column, both from 1, of a position that counts UTF-16 units. */
34
+ export type Location = {
35
+ line: number;
36
+ column: number;
37
+ };
38
+ /** The location of a position, from the line starts of its text. */
39
+ export declare function locationOf(starts: readonly number[], position: number): Location;
40
+ /** The path of a file relative to the working folder, with `/` between the parts, as `tsc` prints it. */
41
+ export declare function displayPath(cwd: string, fileName: string): string;
42
+ /**
43
+ * A diagnostic as `tsc --pretty false` writes it (`WriteFormatDiagnostic`):
44
+ * the location, the category and the code, the text, and each chained message
45
+ * two spaces deeper than the one before. The related locations are left out,
46
+ * as in `tsc`.
47
+ */
48
+ export declare function formatDiagnostic(diagnostic: Diagnostic, cwd: string, linesOf: (fileName: string) => readonly number[]): string;
@@ -0,0 +1,143 @@
1
+ import path from 'node:path';
2
+ import { DiagnosticCategory } from 'typescript/unstable/sync';
3
+ export function collectDiagnostics(program) {
4
+ const options = program.getCompilerOptions();
5
+ const emitsDeclarations = options.declaration === true || options.composite === true;
6
+ let declarations;
7
+ const declarationDiagnostics = () => (declarations ??= program.getDeclarationDiagnostics());
8
+ const all = [...program.getConfigFileParsingDiagnostics()];
9
+ const configCount = all.length;
10
+ all.push(...program.getSyntacticDiagnostics());
11
+ if (all.length === configCount) {
12
+ all.push(...program.getProgramDiagnostics());
13
+ all.push(...program.getGlobalDiagnostics());
14
+ if (all.length === configCount) {
15
+ all.push(...program.getSemanticDiagnostics());
16
+ all.push(...program.getGlobalDiagnostics());
17
+ }
18
+ if (emitsDeclarations && all.length === configCount)
19
+ all.push(...declarationDiagnostics());
20
+ }
21
+ const incremental = options.incremental === true || options.composite === true;
22
+ if (emitsDeclarations && !incremental && !(options.noEmitOnError === true && all.length > 0))
23
+ all.push(...declarationDiagnostics());
24
+ return sortAndDeduplicate(all);
25
+ }
26
+ export function withRealConfig(diagnostic, { virtual, tsconfig, insertion }) {
27
+ const real = (offset) => (insertion !== undefined && offset >= insertion.at + insertion.length ? offset - insertion.length : offset);
28
+ const onInsertion = (offset) => insertion !== undefined && offset >= insertion.at && offset < insertion.at + insertion.length;
29
+ const rename = (message) => {
30
+ const inVirtual = message.fileName === virtual;
31
+ return {
32
+ ...message,
33
+ fileName: inVirtual ? (onInsertion(message.pos) ? undefined : tsconfig) : message.fileName,
34
+ pos: inVirtual ? real(message.pos) : message.pos,
35
+ end: inVirtual ? Math.max(real(message.pos), real(message.end)) : message.end,
36
+ text: message.text.replaceAll(virtual, tsconfig),
37
+ messageChain: message.messageChain?.map(rename),
38
+ relatedInformation: message.relatedInformation?.map(rename),
39
+ };
40
+ };
41
+ return rename(diagnostic);
42
+ }
43
+ export function sortAndDeduplicate(diagnostics) {
44
+ const sorted = diagnostics.toSorted(compareDiagnostics);
45
+ return sorted.filter((diagnostic, index) => index === 0 || !equalWithoutRelated(sorted[index - 1], diagnostic));
46
+ }
47
+ function compareStrings(a, b) {
48
+ if (a === b)
49
+ return 0;
50
+ return a < b ? -1 : 1;
51
+ }
52
+ function compareDiagnostics(a, b) {
53
+ return (compareStrings(a.fileName ?? '', b.fileName ?? '') ||
54
+ a.pos - b.pos ||
55
+ a.end - b.end ||
56
+ a.code - b.code ||
57
+ compareStrings(a.text, b.text) ||
58
+ compareChainSize(a.messageChain ?? [], b.messageChain ?? []) ||
59
+ compareChainContent(a.messageChain ?? [], b.messageChain ?? []) ||
60
+ compareRelated(a.relatedInformation ?? [], b.relatedInformation ?? []));
61
+ }
62
+ function compareChainSize(a, b) {
63
+ if (a.length !== b.length)
64
+ return b.length - a.length;
65
+ for (const [index, chain] of a.entries()) {
66
+ const size = compareChainSize(chain.messageChain ?? [], b[index].messageChain ?? []);
67
+ if (size !== 0)
68
+ return size;
69
+ }
70
+ return 0;
71
+ }
72
+ function compareChainContent(a, b) {
73
+ for (const [index, chain] of a.entries()) {
74
+ const content = compareStrings(chain.text, b[index].text) || compareChainContent(chain.messageChain ?? [], b[index].messageChain ?? []);
75
+ if (content !== 0)
76
+ return content;
77
+ }
78
+ return 0;
79
+ }
80
+ function compareRelated(a, b) {
81
+ if (a.length !== b.length)
82
+ return b.length - a.length;
83
+ for (const [index, related] of a.entries()) {
84
+ const order = compareDiagnostics(related, b[index]);
85
+ if (order !== 0)
86
+ return order;
87
+ }
88
+ return 0;
89
+ }
90
+ function equalChains(a, b) {
91
+ return (a.length === b.length &&
92
+ a.every((chain, index) => chain.code === b[index].code && chain.text === b[index].text && equalChains(chain.messageChain ?? [], b[index].messageChain ?? [])));
93
+ }
94
+ function equalWithoutRelated(a, b) {
95
+ return ((a.fileName ?? '') === (b.fileName ?? '') &&
96
+ a.pos === b.pos &&
97
+ a.end === b.end &&
98
+ a.code === b.code &&
99
+ a.text === b.text &&
100
+ equalChains(a.messageChain ?? [], b.messageChain ?? []));
101
+ }
102
+ function categoryName(category) {
103
+ switch (category) {
104
+ case DiagnosticCategory.Error:
105
+ return 'error';
106
+ case DiagnosticCategory.Warning:
107
+ return 'warning';
108
+ case DiagnosticCategory.Suggestion:
109
+ return 'suggestion';
110
+ case DiagnosticCategory.Message:
111
+ return 'message';
112
+ default: {
113
+ const unknown = category;
114
+ throw new Error(`Unknown diagnostic category ${String(unknown)}`);
115
+ }
116
+ }
117
+ }
118
+ function flattenChain(chain, level) {
119
+ return chain.map((message) => `\n${' '.repeat(level)}${message.text}${flattenChain(message.messageChain ?? [], level + 1)}`).join('');
120
+ }
121
+ export function locationOf(starts, position) {
122
+ let low = 0;
123
+ let high = starts.length - 1;
124
+ while (low < high) {
125
+ const middle = Math.ceil((low + high) / 2);
126
+ if (starts[middle] <= position)
127
+ low = middle;
128
+ else
129
+ high = middle - 1;
130
+ }
131
+ return { line: low + 1, column: position - starts[low] + 1 };
132
+ }
133
+ export function displayPath(cwd, fileName) {
134
+ return path.relative(cwd, fileName).split(path.sep).join('/');
135
+ }
136
+ export function formatDiagnostic(diagnostic, cwd, linesOf) {
137
+ let location = '';
138
+ if (diagnostic.fileName !== undefined) {
139
+ const { line, column } = locationOf(linesOf(diagnostic.fileName), diagnostic.pos);
140
+ location = `${displayPath(cwd, diagnostic.fileName)}(${String(line)},${String(column)}): `;
141
+ }
142
+ return `${location}${categoryName(diagnostic.category)} TS${String(diagnostic.code)}: ${diagnostic.text}${flattenChain(diagnostic.messageChain ?? [], 1)}\n`;
143
+ }
@@ -0,0 +1,14 @@
1
+ import { type SourceFile } from 'typescript/unstable/ast';
2
+ import type { RuleReport } from './engine.ts';
3
+ export declare const DIRECTIVE = "typecheck-disable-next-line";
4
+ /** The id of the problems of a directive, in the place of a rule id. */
5
+ export declare const DIRECTIVE_ID = "typecheck-disable";
6
+ /**
7
+ * The reports of a file after its `typecheck-disable-next-line` directives. A
8
+ * directive suppresses each report of a rule that it names on the line after
9
+ * the last line of its comment. A directive with no reason, with no rule, or
10
+ * with a rule that suppressed nothing gives a problem at the start of its
11
+ * comment, and a directive with no reason still suppresses, so one mistake
12
+ * gives one line.
13
+ */
14
+ export declare function applyDirectives(sourceFile: SourceFile, reports: readonly RuleReport[]): RuleReport[];
@@ -0,0 +1,111 @@
1
+ import { SyntaxKind } from 'typescript/unstable/ast';
2
+ export const DIRECTIVE = 'typecheck-disable-next-line';
3
+ export const DIRECTIVE_ID = 'typecheck-disable';
4
+ const LITERALS = new Set([
5
+ SyntaxKind.StringLiteral,
6
+ SyntaxKind.NoSubstitutionTemplateLiteral,
7
+ SyntaxKind.TemplateHead,
8
+ SyntaxKind.TemplateMiddle,
9
+ SyntaxKind.TemplateTail,
10
+ SyntaxKind.RegularExpressionLiteral,
11
+ SyntaxKind.JsxText,
12
+ ]);
13
+ function literalRanges(sourceFile) {
14
+ const ranges = [];
15
+ const visit = (node) => {
16
+ if (LITERALS.has(node.kind))
17
+ ranges.push({ start: node.getStart(sourceFile), end: node.end });
18
+ node.forEachChild(visit);
19
+ return undefined;
20
+ };
21
+ visit(sourceFile);
22
+ return ranges.sort((a, b) => a.start - b.start);
23
+ }
24
+ function commentsOf(sourceFile) {
25
+ const { text } = sourceFile;
26
+ const literals = literalRanges(sourceFile);
27
+ const comments = [];
28
+ let index = 0;
29
+ let next = 0;
30
+ while (index < text.length) {
31
+ while (next < literals.length && literals[next].end <= index)
32
+ next += 1;
33
+ const literal = literals.at(next);
34
+ if (literal !== undefined && literal.start <= index) {
35
+ index = literal.end;
36
+ continue;
37
+ }
38
+ const limit = literal?.start ?? text.length;
39
+ const slash = text.indexOf('/', index);
40
+ if (slash === -1 || slash >= limit) {
41
+ index = limit;
42
+ continue;
43
+ }
44
+ const kind = text[slash + 1];
45
+ if (kind === '/' || kind === '*') {
46
+ const close = kind === '/' ? text.indexOf('\n', slash) : text.indexOf('*/', slash + 2);
47
+ const end = close === -1 ? text.length : kind === '/' ? close : close + 2;
48
+ comments.push({ start: slash, end, text: text.slice(slash + 2, kind === '/' ? end : Math.max(slash + 2, end - 2)) });
49
+ index = end;
50
+ }
51
+ else {
52
+ index = slash + 1;
53
+ }
54
+ }
55
+ return comments;
56
+ }
57
+ function directiveOf(sourceFile, comment) {
58
+ const body = comment.text.trim();
59
+ if (!body.startsWith(DIRECTIVE))
60
+ return undefined;
61
+ const rest = body.slice(DIRECTIVE.length);
62
+ if (rest !== '' && !/^\s/.test(rest))
63
+ return undefined;
64
+ const separator = /\s--(?:\s|$)/.exec(rest);
65
+ const list = separator === null ? rest : rest.slice(0, separator.index);
66
+ const reason = separator === null ? '' : rest.slice(separator.index + separator[0].length).trim();
67
+ const ids = list
68
+ .split(',')
69
+ .map((id) => id.trim())
70
+ .filter((id) => id !== '');
71
+ const start = sourceFile.getLineAndCharacterOfPosition(comment.start);
72
+ const last = sourceFile.getLineAndCharacterOfPosition(comment.end - 1).line;
73
+ return { start: comment.start, line: start.line + 1, column: start.character + 1, target: last + 2, ids, reason, used: new Set() };
74
+ }
75
+ const MESSAGES = {
76
+ noReason: 'The directive gives no reason. Write the reason after ` -- `.',
77
+ noRule: `The directive names no rule. Name each rule that it disables, and the reason after \` -- \`.`,
78
+ unused: (id) => `\`${id}\` reports nothing on the next line, so the directive does not suppress it. Remove \`${id}\` from the directive.`,
79
+ };
80
+ export function applyDirectives(sourceFile, reports) {
81
+ if (!sourceFile.text.includes(DIRECTIVE))
82
+ return [...reports];
83
+ const directives = commentsOf(sourceFile).flatMap((comment) => directiveOf(sourceFile, comment) ?? []);
84
+ if (directives.length === 0)
85
+ return [...reports];
86
+ const kept = reports.filter((report) => {
87
+ const directive = directives.find(({ target, ids }) => target === report.line && ids.includes(report.id));
88
+ directive?.used.add(report.id);
89
+ return directive === undefined;
90
+ });
91
+ const problem = (directive, message) => ({
92
+ fileName: sourceFile.fileName,
93
+ pos: directive.start,
94
+ line: directive.line,
95
+ column: directive.column,
96
+ id: DIRECTIVE_ID,
97
+ messageId: DIRECTIVE_ID,
98
+ data: {},
99
+ message,
100
+ });
101
+ for (const directive of directives) {
102
+ if (directive.ids.length === 0)
103
+ kept.push(problem(directive, MESSAGES.noRule));
104
+ else if (directive.reason === '')
105
+ kept.push(problem(directive, MESSAGES.noReason));
106
+ for (const id of directive.ids)
107
+ if (!directive.used.has(id))
108
+ kept.push(problem(directive, MESSAGES.unused(id)));
109
+ }
110
+ return kept;
111
+ }
@@ -0,0 +1,21 @@
1
+ import type { SourceFile } from 'typescript/unstable/ast';
2
+ import type { Checker, Program } from 'typescript/unstable/sync';
3
+ import type { ActiveRule } from './config.ts';
4
+ import type { ReportData } from './rule.ts';
5
+ /** A report of a rule, at the start of its node in a file. */
6
+ export type RuleReport = {
7
+ fileName: string;
8
+ pos: number;
9
+ line: number;
10
+ column: number;
11
+ id: string;
12
+ messageId: string;
13
+ data: ReportData;
14
+ message: string;
15
+ };
16
+ /**
17
+ * Runs the rules that are on for a file in one walk of its AST: each rule
18
+ * gives its visitor once, and the walk calls the visitors of each node in the
19
+ * order of the rules.
20
+ */
21
+ export declare function runRules(sourceFile: SourceFile, program: Program, checker: Checker, rules: readonly ActiveRule[]): RuleReport[];
package/dist/engine.js ADDED
@@ -0,0 +1,42 @@
1
+ const PLACEHOLDER = /\{\{\s*(\w+)\s*\}\}/g;
2
+ function fill(template, data) {
3
+ return template.replaceAll(PLACEHOLDER, (placeholder, name) => (Object.hasOwn(data, name) ? String(data[name]) : placeholder));
4
+ }
5
+ export function runRules(sourceFile, program, checker, rules) {
6
+ const reports = [];
7
+ const handlers = new Map();
8
+ for (const { id, rule, options } of rules) {
9
+ const visitor = rule.create({
10
+ id,
11
+ options,
12
+ sourceFile,
13
+ program,
14
+ checker,
15
+ report({ node, messageId, data = {} }) {
16
+ if (!Object.hasOwn(rule.meta.messages, messageId))
17
+ throw new Error(`${id} reports the message id ${messageId}, which its meta.messages does not declare.`);
18
+ const template = rule.meta.messages[messageId];
19
+ const pos = node.getStart(sourceFile);
20
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(pos);
21
+ reports.push({ fileName: sourceFile.fileName, pos, line: line + 1, column: character + 1, id, messageId, data, message: fill(template, data) });
22
+ },
23
+ });
24
+ for (const [kind, handler] of Object.entries(visitor)) {
25
+ const list = handlers.get(Number(kind));
26
+ if (list === undefined)
27
+ handlers.set(Number(kind), [handler]);
28
+ else
29
+ list.push(handler);
30
+ }
31
+ }
32
+ if (handlers.size === 0)
33
+ return reports;
34
+ const visit = (node) => {
35
+ for (const handler of handlers.get(node.kind) ?? [])
36
+ handler(node);
37
+ node.forEachChild(visit);
38
+ return undefined;
39
+ };
40
+ visit(sourceFile);
41
+ return reports;
42
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * An input of the run that cannot load: a project, the configuration, a plugin
3
+ * or the options of a rule. The command prints the message and exits with 1.
4
+ */
5
+ export declare class TypecheckLoadError extends Error {
6
+ name: string;
7
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,3 @@
1
+ export class TypecheckLoadError extends Error {
2
+ name = 'TypecheckLoadError';
3
+ }
@@ -0,0 +1,24 @@
1
+ import { type CallExpression, type Node } from 'typescript/unstable/ast';
2
+ import type { Signature } from 'typescript/unstable/sync';
3
+ /**
4
+ * The name of the indirection a call reaches its target through, or `undefined`
5
+ * where it reaches one directly or reaches nothing that matters.
6
+ *
7
+ * A rule that reads what a call was given has to see the call. Through `call`,
8
+ * `apply` and `Reflect.apply` it sees an argument list or an array instead, so
9
+ * a correct call and the one the rule exists to report look alike. The
10
+ * indirection is thus the finding by itself, whatever the arguments are: app
11
+ * code has no need for it, and it is the shape an author reaches for to get
12
+ * past a rule.
13
+ *
14
+ * `bind` is the exception, and only where it carries a receiver alone. The
15
+ * compiler keeps the method's own signature on the value it returns, so the
16
+ * later call resolves to the method again and the arguments are read there. An
17
+ * argument bound beside the receiver is one that no later call shows, and that
18
+ * is the indirection again.
19
+ *
20
+ * `reachesTarget` says whether a value is one the calling rule cares about, and
21
+ * it is asked about a type rather than a name, so an unrelated `map.get.call(…)`
22
+ * stays silent. `signature` is the one that `call` resolved to.
23
+ */
24
+ export declare function indirectionOf(call: CallExpression, signature: Signature, reachesTarget: (node: Node) => boolean): string | undefined;
@@ -0,0 +1,45 @@
1
+ import { isElementAccessExpression, isFunctionDeclaration, isIdentifier, isInterfaceDeclaration, isMethodSignatureDeclaration, isModuleBlock, isModuleDeclaration, isPropertyAccessExpression, isSpreadElement, SyntaxKind, } from 'typescript/unstable/ast';
2
+ const FUNCTION_INTERFACES = new Set(['CallableFunction', 'Function']);
3
+ const REFLECTIVE_MEMBERS = new Set(['call', 'apply', 'bind']);
4
+ const DECLARATION_FILE = /\.d\.[cm]?ts$/i;
5
+ function libraryDeclaration(signature, kind) {
6
+ const handle = signature.declaration;
7
+ if (handle === undefined || handle.kind !== kind || !DECLARATION_FILE.test(handle.path))
8
+ return undefined;
9
+ const declaration = handle.resolve();
10
+ return declaration?.getSourceFile().isDeclarationFile === true ? declaration : undefined;
11
+ }
12
+ function reflectiveMemberOf(signature) {
13
+ const declaration = libraryDeclaration(signature, SyntaxKind.MethodSignature);
14
+ if (declaration === undefined || !isMethodSignatureDeclaration(declaration))
15
+ return undefined;
16
+ const owner = declaration.parent;
17
+ if (!isInterfaceDeclaration(owner) || !FUNCTION_INTERFACES.has(owner.name.text))
18
+ return undefined;
19
+ const { name } = declaration;
20
+ return isIdentifier(name) && REFLECTIVE_MEMBERS.has(name.text) ? name.text : undefined;
21
+ }
22
+ function isReflectApply(signature) {
23
+ const declaration = libraryDeclaration(signature, SyntaxKind.FunctionDeclaration);
24
+ if (declaration === undefined || !isFunctionDeclaration(declaration) || declaration.name?.text !== 'apply')
25
+ return false;
26
+ const body = declaration.parent;
27
+ if (!isModuleBlock(body) || !isModuleDeclaration(body.parent))
28
+ return false;
29
+ const namespace = body.parent.name;
30
+ return isIdentifier(namespace) && namespace.text === 'Reflect';
31
+ }
32
+ export function indirectionOf(call, signature, reachesTarget) {
33
+ const through = reflectiveMemberOf(signature);
34
+ if (through !== undefined) {
35
+ if (through === 'bind' && call.arguments.length < 2)
36
+ return undefined;
37
+ const callee = call.expression;
38
+ const receiver = isPropertyAccessExpression(callee) || isElementAccessExpression(callee) ? callee.expression : undefined;
39
+ return receiver !== undefined && reachesTarget(receiver) ? `Function.prototype.${through}` : undefined;
40
+ }
41
+ if (!isReflectApply(signature))
42
+ return undefined;
43
+ const target = call.arguments.at(0);
44
+ return target !== undefined && !isSpreadElement(target) && reachesTarget(target) ? 'Reflect.apply' : undefined;
45
+ }
@@ -0,0 +1,4 @@
1
+ export { type Override, type RuleSetting, type Severity, typecheck, type TypecheckConfig, type TypecheckOptions } from './config.ts';
2
+ export type { OptionValue, Plugin, Report, ReportData, RuleContext, RuleMeta, RuleModule, RuleOptions, Visitor } from './rule.ts';
3
+ export { stringArraysOnly } from './rule-options.ts';
4
+ export { rules } from './rules/index.ts';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { typecheck } from './config.js';
2
+ export { stringArraysOnly } from './rule-options.js';
3
+ export { rules } from './rules/index.js';
@@ -0,0 +1,46 @@
1
+ /** Where the virtual tsconfig adds text to the real one: the offset in the real text and the length of the added text. */
2
+ export type Insertion = {
3
+ at: number;
4
+ length: number;
5
+ };
6
+ /**
7
+ * A project of the run: the tsconfig that a person named, and the tsconfig
8
+ * that the command opens in its place, with the place of the text that it adds.
9
+ */
10
+ export type ProjectFiles = {
11
+ tsconfig: string;
12
+ virtual: string;
13
+ virtualText: string;
14
+ insertion: Insertion | undefined;
15
+ };
16
+ /**
17
+ * The tsconfig of a `-p` value: the file it names, or the `tsconfig.json` of
18
+ * the folder it names, as `tsc -p` reads it.
19
+ */
20
+ export declare function resolveProject(cwd: string, project: string): string;
21
+ /** The text of a file without the byte order mark, which TypeScript does not count in a position. */
22
+ export declare function withoutByteOrderMark(text: string): string;
23
+ /**
24
+ * The tsconfig that the command opens for a real one: the text of the real
25
+ * file with `"noEmit": true` as the last member of its root `compilerOptions`,
26
+ * in the same folder, so that `extends`, `include`, `references` and each path
27
+ * resolve as they do in the real file. `noEmit` from the command line of `tsc`
28
+ * changes the diagnostics of the options that depend on emit, and an option
29
+ * error of the real file keeps its place, because each offset before the
30
+ * insertion is the offset of the real file.
31
+ */
32
+ export declare function projectFiles(tsconfig: string): ProjectFiles;
33
+ /**
34
+ * The place and the text that add `noEmit` to a tsconfig: before the closing
35
+ * brace of the last root `compilerOptions`, or a `compilerOptions` member
36
+ * before the closing brace of the root object when the root has none or a
37
+ * `compilerOptions` that is not an object. The added member comes after the
38
+ * real one, thus the error of the real value keeps its place, and the options
39
+ * of `extends` get `noEmit` as under `tsc --noEmit`. `undefined` when the scan
40
+ * finds no root object, or a `compilerOptions` key with no value: the program
41
+ * then reports the errors of the real file at their places.
42
+ */
43
+ export declare function noEmitInsertion(text: string): {
44
+ at: number;
45
+ text: string;
46
+ } | undefined;
@@ -0,0 +1,105 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { TypecheckLoadError } from './errors.js';
4
+ const VIRTUAL_PREFIX = '.inflexa-typecheck.';
5
+ export function resolveProject(cwd, project) {
6
+ const target = path.resolve(cwd, project);
7
+ const stat = statSync(target, { throwIfNoEntry: false });
8
+ const tsconfig = stat?.isDirectory() ? path.join(target, 'tsconfig.json') : target;
9
+ if (!statSync(tsconfig, { throwIfNoEntry: false })?.isFile()) {
10
+ throw new TypecheckLoadError(`Cannot find the project ${project}: ${path.relative(cwd, tsconfig) || tsconfig} does not exist.`);
11
+ }
12
+ return tsconfig;
13
+ }
14
+ export function withoutByteOrderMark(text) {
15
+ return text.startsWith('\uFEFF') ? text.slice(1) : text;
16
+ }
17
+ export function projectFiles(tsconfig) {
18
+ const name = path.basename(tsconfig);
19
+ const text = withoutByteOrderMark(readFileSync(tsconfig, 'utf8'));
20
+ const virtual = path.join(path.dirname(tsconfig), `${VIRTUAL_PREFIX}${name}`);
21
+ const place = noEmitInsertion(text);
22
+ if (place === undefined)
23
+ return { tsconfig, virtual, virtualText: text, insertion: undefined };
24
+ return { tsconfig, virtual, virtualText: text.slice(0, place.at) + place.text + text.slice(place.at), insertion: { at: place.at, length: place.text.length } };
25
+ }
26
+ function tokensOf(text) {
27
+ const tokens = [];
28
+ let index = 0;
29
+ while (index < text.length) {
30
+ const char = text[index];
31
+ if (' \t\r\n'.includes(char)) {
32
+ index += 1;
33
+ }
34
+ else if (char === '/' && text[index + 1] === '/') {
35
+ const end = text.indexOf('\n', index);
36
+ index = end === -1 ? text.length : end;
37
+ }
38
+ else if (char === '/' && text[index + 1] === '*') {
39
+ const end = text.indexOf('*/', index + 2);
40
+ if (end === -1)
41
+ return undefined;
42
+ index = end + 2;
43
+ }
44
+ else if (char === '"') {
45
+ let end = index + 1;
46
+ while (end < text.length && text[end] !== '"')
47
+ end += text[end] === '\\' ? 2 : 1;
48
+ if (end >= text.length)
49
+ return undefined;
50
+ tokens.push({ kind: 'string', start: index, end: end + 1, char });
51
+ index = end + 1;
52
+ }
53
+ else {
54
+ const kind = char === '{' || char === '[' ? 'open' : char === '}' || char === ']' ? 'close' : char === ',' ? 'comma' : char === ':' ? 'colon' : 'other';
55
+ tokens.push({ kind, start: index, end: index + 1, char });
56
+ index += 1;
57
+ }
58
+ }
59
+ return tokens;
60
+ }
61
+ function closeOf(tokens, open) {
62
+ let depth = 0;
63
+ for (let index = open; index < tokens.length; index += 1) {
64
+ if (tokens[index].kind === 'open')
65
+ depth += 1;
66
+ else if (tokens[index].kind === 'close') {
67
+ depth -= 1;
68
+ if (depth === 0)
69
+ return index;
70
+ }
71
+ }
72
+ return undefined;
73
+ }
74
+ function memberBefore(tokens, close, member) {
75
+ const previous = tokens[close - 1].kind;
76
+ return previous === 'open' || previous === 'comma' ? member : `,${member}`;
77
+ }
78
+ export function noEmitInsertion(text) {
79
+ const tokens = tokensOf(text);
80
+ if (tokens === undefined || tokens.at(0)?.char !== '{')
81
+ return undefined;
82
+ const rootClose = closeOf(tokens, 0);
83
+ if (rootClose === undefined)
84
+ return undefined;
85
+ let options;
86
+ for (let index = 1; index < rootClose; index += 1) {
87
+ const token = tokens[index];
88
+ if (token.kind === 'string' && text.slice(token.start, token.end) === '"compilerOptions"' && tokens.at(index + 1)?.kind === 'colon')
89
+ options = index + 2;
90
+ if (token.kind === 'open')
91
+ index = closeOf(tokens, index) ?? rootClose;
92
+ }
93
+ const rootMember = () => ({ at: tokens[rootClose].start, text: memberBefore(tokens, rootClose, '"compilerOptions":{"noEmit":true}') });
94
+ if (options === undefined)
95
+ return rootMember();
96
+ const value = tokens[options];
97
+ if (options >= rootClose || value.kind === 'close' || value.kind === 'comma' || value.kind === 'colon')
98
+ return undefined;
99
+ if (value.char !== '{')
100
+ return rootMember();
101
+ const optionsClose = closeOf(tokens, options);
102
+ if (optionsClose === undefined)
103
+ return undefined;
104
+ return { at: tokens[optionsClose].start, text: memberBefore(tokens, optionsClose, '"noEmit":true') };
105
+ }
@@ -0,0 +1,7 @@
1
+ import type { RuleOptions } from './rule.ts';
2
+ /**
3
+ * The option check of a rule whose options are lists of strings: each element
4
+ * of each array option must be a string. The configuration already refuses a
5
+ * key that the defaults do not have and a value of another kind.
6
+ */
7
+ export declare function stringArraysOnly(options: RuleOptions): string | undefined;
@@ -0,0 +1,7 @@
1
+ export function stringArraysOnly(options) {
2
+ for (const [key, value] of Object.entries(options)) {
3
+ if (Array.isArray(value) && value.some((element) => typeof element !== 'string'))
4
+ return `each element of the option ${key} must be a string.`;
5
+ }
6
+ return undefined;
7
+ }