@skathi-native/cli 0.0.0 → 0.1.0-beta.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,219 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { paint, type Paint } from "../cli/term";
4
+ import { ALL_CODES, codeInfo, RANGES } from "./codes";
5
+ import type { Highlight } from "./highlight";
6
+ import type { CheckReport, Diagnostic, TypingScore } from "./schema";
7
+
8
+ const MAX_NOTES = 5;
9
+ const MAX_LINE = 120;
10
+ const TABLE_AFTER = 10;
11
+ const TYPING_ROWS = 15;
12
+
13
+ const plain: Highlight = (code) => code;
14
+ const same = (text: string) => text;
15
+
16
+ /** `code` spans in cyan, the rest through `base`. */
17
+ const inline = (p: Paint, text: string, base: (text: string) => string = same) =>
18
+ text
19
+ .split(/(`[^`]+`)/)
20
+ .map((part) => (part.length > 1 && part.startsWith("`") ? p.cyan(part) : base(part)))
21
+ .join("");
22
+
23
+ const at = (p: Paint, file: string, line: number, character: number) =>
24
+ `${p.cyan(file)}${p.dim(`:${line + 1}:${character + 1}`)}`;
25
+
26
+ const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
27
+
28
+ export const packageLabel = (d: Pick<Diagnostic, "package">) =>
29
+ d.package ? `${d.package.name}@${d.package.version}` : "app";
30
+
31
+ function excerpt(text: string | null, d: Diagnostic, width: number, p: Paint, highlight: Highlight): string[] {
32
+ const { start, end } = d.range;
33
+ if (text === null || (start.line === 0 && start.character === 0 && end.line === 0 && end.character === 0)) return [];
34
+ const line = text.split(/\r?\n/)[start.line];
35
+ if (line === undefined) return [];
36
+ const last = end.line === start.line ? end.character : line.length;
37
+ let from = 0;
38
+ let to = line.length;
39
+ if (line.length > MAX_LINE) {
40
+ from = Math.max(0, start.character - 40);
41
+ to = Math.min(line.length, from + MAX_LINE);
42
+ }
43
+ const shown = `${from > 0 ? p.dim("…") : ""}${highlight(line.slice(from, to))}${to < line.length ? p.dim("…") : ""}`;
44
+ const pad = `${from > 0 ? " " : ""}${line.slice(from, start.character).replace(/[^\t]/g, " ")}`;
45
+ const marks = "^".repeat(Math.max(1, Math.min(last, to) - start.character));
46
+ const bar = p.blue(`${" ".repeat(width + 1)}|`);
47
+ return [
48
+ bar,
49
+ `${p.blue(`${String(start.line + 1).padStart(width)} |`)} ${shown}`,
50
+ `${bar} ${pad}${d.severity === "error" ? p.red(marks) : p.yellow(marks)}`,
51
+ bar,
52
+ ];
53
+ }
54
+
55
+ export function formatDiagnostic(
56
+ d: Diagnostic,
57
+ source: string | null,
58
+ color: boolean,
59
+ highlight: Highlight = plain,
60
+ ): string {
61
+ const p = paint(color);
62
+ const width = String(d.range.start.line + 1).length;
63
+ const head = d.severity === "error" ? p.red(`error[${d.code}]`) : p.yellow(`warning[${d.code}]`);
64
+ const pkg = d.package ? ` ${p.magenta(`(${packageLabel(d)})`)}` : "";
65
+ const lines = [
66
+ `${head}${p.bold(":")} ${inline(p, d.message, p.bold)}`,
67
+ `${" ".repeat(width)}${p.blue("-->")} ${at(p, d.file, d.range.start.line, d.range.start.character)}${pkg}`,
68
+ ...excerpt(source, d, width, p, highlight),
69
+ ];
70
+ const gutter = `${" ".repeat(width + 1)}${p.blue("=")}`;
71
+ const note = (text: string) => `${gutter} ${p.bold("note")}: ${text}`;
72
+ for (const r of d.related.slice(0, MAX_NOTES)) {
73
+ const place = at(p, r.file, r.range.start.line, r.range.start.character);
74
+ lines.push(note(`${inline(p, r.message)} ${p.dim("(")}${place}${p.dim(")")}`));
75
+ }
76
+ if (d.related.length > MAX_NOTES)
77
+ lines.push(note(p.dim(`and ${d.related.length - MAX_NOTES} more (--format json lists all)`)));
78
+ if (d.help) lines.push(`${gutter} ${p.green("help")}: ${inline(p, d.help)}`);
79
+ lines.push(`${gutter} ${p.dim(`see: sk explain ${d.code}`)}`);
80
+ return lines.join("\n");
81
+ }
82
+
83
+ type Cell = { text: string; paint?: (text: string) => string };
84
+
85
+ function table(rows: Cell[][], align: ("l" | "r")[]): string[] {
86
+ const widths = align.map((_, i) => Math.max(...rows.map((r) => r[i]!.text.length)));
87
+ return rows.map((r) =>
88
+ r
89
+ .map((cell, i) => {
90
+ const text = align[i] === "r" ? cell.text.padStart(widths[i]!) : cell.text.padEnd(widths[i]!);
91
+ return i === r.length - 1 && align[i] === "l"
92
+ ? (cell.paint ?? same)(text.trimEnd())
93
+ : (cell.paint ?? same)(text);
94
+ })
95
+ .join(" "),
96
+ );
97
+ }
98
+
99
+ function typingSection(scores: TypingScore[], untyped: Set<string>, p: Paint): string[] {
100
+ const label = (s: TypingScore) => (s.package ? `${s.package}@${s.version}` : "app");
101
+ const rows = scores
102
+ .filter((s) => s.declarations > 0)
103
+ .map((s) => ({ s, share: untyped.has(label(s)) ? 0 : (s.declarations - s.any) / s.declarations }))
104
+ .sort((a, b) => a.share - b.share || b.s.any - a.s.any || label(a.s).localeCompare(label(b.s)));
105
+ if (!rows.length) return [];
106
+ const grade = (share: number) => (share < 0.7 ? p.red : share < 0.9 ? p.yellow : p.green);
107
+ const body = rows.slice(0, TYPING_ROWS).map(({ s, share }): Cell[] => [
108
+ { text: ` ${label(s)}`, paint: s.package ? same : p.bold },
109
+ untyped.has(label(s))
110
+ ? { text: "untyped", paint: p.red }
111
+ : { text: `${Math.floor(share * 100)}% typed`, paint: grade(share) },
112
+ {
113
+ text: untyped.has(label(s)) ? "no declarations" : `${s.any} of ${s.declarations} use any`,
114
+ paint: p.dim,
115
+ },
116
+ ]);
117
+ const out = ["", p.bold("typing quality (worst first)"), ...table(body, ["l", "r", "l"])];
118
+ if (rows.length > TYPING_ROWS) out.push(p.dim(` … ${rows.length - TYPING_ROWS} more (--format json lists all)`));
119
+ return out;
120
+ }
121
+
122
+ export function formatPretty(report: CheckReport, options: { color: boolean; highlight?: Highlight }): string {
123
+ const p = paint(options.color);
124
+ const sources = new Map<string, string | null>();
125
+ const source = (file: string) => {
126
+ if (!sources.has(file)) {
127
+ let text: string | null;
128
+ try {
129
+ text = readFileSync(join(report.root, file), "utf8").replace(/^/, "");
130
+ } catch {
131
+ text = null;
132
+ }
133
+ sources.set(file, text);
134
+ }
135
+ return sources.get(file) ?? null;
136
+ };
137
+ const blocks = report.diagnostics.map((d) => formatDiagnostic(d, source(d.file), options.color, options.highlight));
138
+ const s = report.summary;
139
+ const counts = [plural(s.errors, "error"), plural(s.warnings, "warning")].join(", ");
140
+ const suppressed = s.suppressed ? ` (${s.suppressed} suppressed)` : "";
141
+ const totals = `${counts}${suppressed} in ${plural(s.files, "file")}, ${plural(s.packages, "package")}`;
142
+ const tail: string[] = [s.errors ? p.red(totals) : s.warnings ? p.yellow(totals) : p.green(totals)];
143
+ if (report.diagnostics.length > TABLE_AFTER) {
144
+ const byKey = new Map<string, { code: string; pkg: string; n: number; error: boolean }>();
145
+ for (const d of report.diagnostics) {
146
+ const key = `${d.code} ${packageLabel(d)}`;
147
+ const row = byKey.get(key) ?? { code: d.code, pkg: packageLabel(d), n: 0, error: d.severity === "error" };
148
+ row.n++;
149
+ byKey.set(key, row);
150
+ }
151
+ const rows = [...byKey.values()].sort(
152
+ (a, b) => a.code.localeCompare(b.code) || b.n - a.n || a.pkg.localeCompare(b.pkg),
153
+ );
154
+ tail.push(
155
+ "",
156
+ ...table(
157
+ [
158
+ [
159
+ { text: "code", paint: p.dim },
160
+ { text: "package", paint: p.dim },
161
+ { text: "count", paint: p.dim },
162
+ ],
163
+ ...rows.map((r): Cell[] => [
164
+ { text: r.code, paint: r.error ? p.red : p.yellow },
165
+ { text: r.pkg, paint: r.pkg === "app" ? p.bold : p.magenta },
166
+ { text: String(r.n), paint: p.bold },
167
+ ]),
168
+ ],
169
+ ["l", "l", "r"],
170
+ ),
171
+ );
172
+ }
173
+ const untyped = new Set(
174
+ report.diagnostics.filter((d) => d.code === "SK3001" && d.package).map((d) => packageLabel(d)),
175
+ );
176
+ tail.push(...typingSection(s.typing, untyped, p));
177
+ return [...blocks, tail.join("\n")].join("\n\n");
178
+ }
179
+
180
+ export function explain(code: string, options: { color?: boolean; highlight?: Highlight } = {}): string | null {
181
+ const info = (() => {
182
+ try {
183
+ return codeInfo(code.toUpperCase());
184
+ } catch {
185
+ return null;
186
+ }
187
+ })();
188
+ if (!info) return null;
189
+ const p = paint(options.color ?? false);
190
+ const highlight = options.highlight ?? plain;
191
+ const severity = info.severity === "error" ? p.red : p.yellow;
192
+ return [
193
+ `${severity(info.code)} ${p.dim(`(${info.severity})`)}${p.dim(":")} ${inline(p, info.title, p.bold)}`,
194
+ "",
195
+ inline(p, info.explanation),
196
+ "",
197
+ p.bold("Example:"),
198
+ ...info.example.split("\n").map((l) => ` ${highlight(l)}`),
199
+ "",
200
+ `${p.green("Fix:")} ${inline(p, info.fix)}`,
201
+ ].join("\n");
202
+ }
203
+
204
+ export function listCodes(color = false): string {
205
+ const p = paint(color);
206
+ const lines: string[] = [];
207
+ for (const range of RANGES) {
208
+ const codes = ALL_CODES.filter((c) => Number(c.code.slice(2)) >= range.from && Number(c.code.slice(2)) <= range.to);
209
+ if (!codes.length) continue;
210
+ lines.push(
211
+ p.bold(`SK${String(range.from).padStart(4, "0")}–SK${String(range.to).padStart(4, "0")}: ${range.what}`),
212
+ );
213
+ for (const c of codes) {
214
+ const severity = c.severity === "error" ? p.red : p.yellow;
215
+ lines.push(` ${severity(c.code)} ${p.dim(c.severity.padEnd(7))} ${inline(p, c.title)}`);
216
+ }
217
+ }
218
+ return lines.join("\n");
219
+ }
package/check/rules.ts ADDED
@@ -0,0 +1,307 @@
1
+ import type ts from "typescript";
2
+ import { Builtins, LOCKED, LOCKED_OBJECTS, OBJECTS, REPLACEABLE, memberPath } from "./builtins";
3
+ import { rangeOf, type Finding } from "./finding";
4
+ import type { TypeScript, Unit } from "./program";
5
+
6
+ const DEFINE_CALLS = new Set([
7
+ "Object.defineProperty",
8
+ "Object.defineProperties",
9
+ "Object.assign",
10
+ "Reflect.set",
11
+ "Reflect.defineProperty",
12
+ "Reflect.deleteProperty",
13
+ ]);
14
+ const PROTOTYPE_CALLS = new Set(["Object.setPrototypeOf", "Reflect.setPrototypeOf"]);
15
+ const TIMERS = new Set(["setTimeout", "setInterval", "setImmediate"]);
16
+
17
+ /** What changing `path` on its holder does under AOT: null when it is allowed. */
18
+ function change(holder: string, path: string): "locked" | "locked-object" | null {
19
+ if (LOCKED.has(path)) return "locked";
20
+ if (LOCKED_OBJECTS.has(holder) && !REPLACEABLE.has(path)) return "locked-object";
21
+ return null;
22
+ }
23
+
24
+ export class Rules {
25
+ constructor(
26
+ private readonly typescript: TypeScript,
27
+ private readonly checker: ts.TypeChecker,
28
+ private readonly builtins: Builtins,
29
+ ) {}
30
+
31
+ run(unit: Unit, file: ts.SourceFile, out: Finding[]): void {
32
+ const t = this.typescript;
33
+ const report = (code: string, message: string, start: number, end: number) =>
34
+ out.push({ code, message, file: unit.path, range: rangeOf(file, start, end), related: [] });
35
+ const at = (node: ts.Node) => [node.getStart(file), node.getEnd()] as const;
36
+
37
+ const visit = (node: ts.Node): void => {
38
+ if (t.isBinaryExpression(node) && this.isAssignment(node.operatorToken.kind)) {
39
+ this.assignment(node, (code, message) => report(code, message, ...at(node.left)));
40
+ } else if (t.isDeleteExpression(node)) {
41
+ this.deletion(node, (code, message) => report(code, message, ...at(node.expression)));
42
+ } else if (t.isCallExpression(node) || t.isNewExpression(node)) {
43
+ this.call(node, file, report);
44
+ } else if (t.isIdentifier(node) && node.text === "eval") {
45
+ this.evalReference(node, (message) => report("SK2001", message, ...at(node)));
46
+ } else if (t.isPropertyAccessExpression(node) && node.name.text === "eval") {
47
+ if (!t.isTypeOfExpression(node.parent) && this.builtins.path(node.expression) === "globalThis")
48
+ report("SK2001", "`eval` (through the global object) runs interpreted under AOT, without a JIT", ...at(node));
49
+ return visit(node.expression);
50
+ }
51
+ t.forEachChild(node, visit);
52
+ };
53
+ visit(file);
54
+ }
55
+
56
+ private isAssignment(kind: ts.SyntaxKind): boolean {
57
+ const k = this.typescript.SyntaxKind;
58
+ return kind >= k.FirstAssignment && kind <= k.LastAssignment;
59
+ }
60
+
61
+ private target(node: ts.Expression): { holder: string; name: string; path: string } | null {
62
+ const t = this.typescript;
63
+ if (!t.isPropertyAccessExpression(node) && !t.isElementAccessExpression(node)) return null;
64
+ const name = this.builtins.memberName(t.isPropertyAccessExpression(node) ? node.name : node.argumentExpression);
65
+ if (name === null) return null;
66
+ const holder = this.builtins.path(node.expression);
67
+ if (holder === null) return null;
68
+ return { holder, name, path: memberPath(holder, name) };
69
+ }
70
+
71
+ private assignment(node: ts.BinaryExpression, report: (code: string, message: string) => void): void {
72
+ const t = this.typescript;
73
+ const left = node.left;
74
+ if (t.isIdentifier(left)) {
75
+ if (
76
+ LOCKED.has(left.text) &&
77
+ !left.text.includes(".") &&
78
+ this.builtins.isGlobal(left) &&
79
+ !this.guarded(node, left.text, left.text)
80
+ )
81
+ report("SK1004", `the global \`${left.text}\` is assigned; AOT code cannot replace the language's globals`);
82
+ return;
83
+ }
84
+ const target = this.target(left);
85
+ if (!target) return;
86
+ if (target.name === "__proto__") {
87
+ if (OBJECTS.has(target.holder))
88
+ report(
89
+ "SK1003",
90
+ `\`${target.holder}.__proto__\` is assigned; AOT code cannot change what a built-in inherits from`,
91
+ );
92
+ return;
93
+ }
94
+ const kind = change(target.holder, target.path);
95
+ // `??=` and `||=` write only when the member is missing, which a built-in never is.
96
+ const k = t.SyntaxKind;
97
+ const fills =
98
+ node.operatorToken.kind === k.QuestionQuestionEqualsToken || node.operatorToken.kind === k.BarBarEqualsToken;
99
+ if (
100
+ !kind ||
101
+ (fills && kind === "locked") ||
102
+ this.restores(node.right, target.path) ||
103
+ this.guarded(node, target.path, target.name)
104
+ )
105
+ return;
106
+ if (target.holder === "globalThis")
107
+ report("SK1004", `\`globalThis.${target.name}\` is replaced; AOT code cannot replace the language's globals`);
108
+ else if (kind === "locked-object")
109
+ report("SK1001", `\`${target.path}\` is added; ${target.holder} takes no new members under AOT`);
110
+ else report("SK1001", `\`${target.path}\` is replaced; AOT code cannot change built-in methods`);
111
+ }
112
+
113
+ private deletion(node: ts.DeleteExpression, report: (code: string, message: string) => void): void {
114
+ const target = this.target(node.expression);
115
+ if (!target || !LOCKED.has(target.path) || this.guarded(node, target.path, target.name)) return;
116
+ if (target.holder === "globalThis")
117
+ report("SK1004", `\`globalThis.${target.name}\` is deleted; AOT code cannot remove the language's globals`);
118
+ else report("SK1001", `\`${target.path}\` is deleted; AOT code cannot change built-in methods`);
119
+ }
120
+
121
+ private call(
122
+ node: ts.CallExpression | ts.NewExpression,
123
+ file: ts.SourceFile,
124
+ report: (code: string, message: string, start: number, end: number) => void,
125
+ ): void {
126
+ const t = this.typescript;
127
+ const args: readonly ts.Expression[] = node.arguments ?? [];
128
+ if (t.isCallExpression(node) && node.expression.kind === t.SyntaxKind.ImportKeyword) {
129
+ const spec = args[0];
130
+ if (spec && !t.isStringLiteral(spec) && !t.isNoSubstitutionTemplateLiteral(spec))
131
+ report(
132
+ "SK2004",
133
+ "`import()` with a computed specifier; AOT loads only the modules the build could find",
134
+ spec.getStart(file),
135
+ spec.getEnd(),
136
+ );
137
+ return;
138
+ }
139
+ const callee = this.builtins.path(node.expression);
140
+ if (callee === null) return;
141
+ const span = (n: ts.Node) => [n.getStart(file), n.getEnd()] as const;
142
+ if (callee === "Function") {
143
+ const what = t.isNewExpression(node) ? "`new Function(…)`" : "`Function(…)`";
144
+ report(
145
+ "SK2002",
146
+ `${what} compiles a string at run time; under AOT it runs interpreted, without a JIT`,
147
+ node.getStart(file),
148
+ node.expression.getEnd(),
149
+ );
150
+ return;
151
+ }
152
+ if (TIMERS.has(callee)) {
153
+ const code = args[0];
154
+ if (code && this.isString(code))
155
+ report(
156
+ "SK2003",
157
+ `\`${callee}\` is given a string of code; Skathi timers take functions only, so it never runs`,
158
+ ...span(code),
159
+ );
160
+ return;
161
+ }
162
+ if (PROTOTYPE_CALLS.has(callee)) {
163
+ const target = args[0] && this.builtins.path(args[0]);
164
+ if (target && (OBJECTS.has(target) || target === "globalThis") && !this.guarded(node, target, ""))
165
+ report(
166
+ "SK1003",
167
+ `\`${callee}\` changes what \`${target}\` inherits from; AOT built-ins cannot be rewired`,
168
+ ...span(node),
169
+ );
170
+ return;
171
+ }
172
+ if (!DEFINE_CALLS.has(callee)) return;
173
+ const holder = args[0] && this.builtins.path(args[0]);
174
+ if (!holder || !(OBJECTS.has(holder) || holder === "globalThis")) return;
175
+ const members: { name: string; node: ts.Node }[] = [];
176
+ const fromObject = (arg: ts.Expression | undefined) => {
177
+ if (!arg || !t.isObjectLiteralExpression(arg)) return;
178
+ for (const property of arg.properties) {
179
+ if (!property.name) continue;
180
+ const name = this.builtins.memberName(property.name);
181
+ if (name !== null) members.push({ name, node: property.name });
182
+ }
183
+ };
184
+ if (callee === "Object.defineProperties") fromObject(args[1]);
185
+ else if (callee === "Object.assign") for (const arg of args.slice(1)) fromObject(arg);
186
+ else if (args[1]) {
187
+ const name = this.builtins.memberName(args[1]);
188
+ if (name !== null) members.push({ name, node: args[1] });
189
+ }
190
+ for (const member of members) {
191
+ const path = memberPath(holder, member.name);
192
+ const kind = change(holder, path);
193
+ if (!kind || this.guarded(node, path, member.name)) continue;
194
+ const shown = holder === "globalThis" ? `globalThis.${member.name}` : path;
195
+ const message = callee.startsWith("Reflect.")
196
+ ? `\`${callee}\` cannot change \`${shown}\` under AOT: it returns false and leaves the built-in as it was`
197
+ : kind === "locked-object"
198
+ ? `\`${callee}\` adds \`${shown}\`; ${holder} takes no new members under AOT`
199
+ : `\`${callee}\` redefines \`${shown}\`; built-ins are read-only under AOT`;
200
+ report("SK1002", message, ...span(member.node));
201
+ }
202
+ }
203
+
204
+ private evalReference(node: ts.Identifier, report: (message: string) => void): void {
205
+ const t = this.typescript;
206
+ const parent = node.parent;
207
+ if (t.isTypeOfExpression(parent)) return;
208
+ if (t.isPropertyAccessExpression(parent) && parent.name === node) return;
209
+ if (t.isQualifiedName(parent) && parent.right === node) return;
210
+ if (t.isPropertyAssignment(parent) && parent.name === node) return;
211
+ if (t.isMethodDeclaration(parent) || t.isPropertyDeclaration(parent) || t.isPropertySignature(parent)) return;
212
+ if (t.isBindingElement(parent) || t.isVariableDeclaration(parent) || t.isParameter(parent)) return;
213
+ if (t.isImportSpecifier(parent) || t.isExportSpecifier(parent)) return;
214
+ if (!this.builtins.isGlobal(node)) return;
215
+ const direct = t.isCallExpression(parent) && parent.expression === node;
216
+ report(
217
+ direct
218
+ ? "`eval` runs interpreted under AOT, without a JIT"
219
+ : "a reference to `eval` (an indirect eval) runs interpreted under AOT, without a JIT",
220
+ );
221
+ }
222
+
223
+ private isString(node: ts.Expression): boolean {
224
+ const t = this.typescript;
225
+ if (t.isStringLiteralLike(node) || t.isTemplateExpression(node)) return true;
226
+ try {
227
+ const type = this.checker.getTypeAtLocation(node);
228
+ return (type.flags & t.TypeFlags.StringLike) !== 0;
229
+ } catch {
230
+ return false;
231
+ }
232
+ }
233
+
234
+ /** `x = x` or `x = saved` where `saved` was read from `x`: putting the original back is allowed. */
235
+ private restores(value: ts.Expression, path: string): boolean {
236
+ const t = this.typescript;
237
+ let node = value;
238
+ while (t.isParenthesizedExpression(node)) node = node.expression;
239
+ if (
240
+ t.isBinaryExpression(node) &&
241
+ (node.operatorToken.kind === t.SyntaxKind.BarBarToken ||
242
+ node.operatorToken.kind === t.SyntaxKind.QuestionQuestionToken)
243
+ )
244
+ return this.restores(node.left, path);
245
+ if (this.builtins.path(node) === path) return true;
246
+ if (t.isIdentifier(node)) {
247
+ const declaration = this.checker.getSymbolAtLocation(node)?.valueDeclaration;
248
+ return (
249
+ !!declaration &&
250
+ t.isVariableDeclaration(declaration) &&
251
+ !!declaration.initializer &&
252
+ this.builtins.path(declaration.initializer) === path
253
+ );
254
+ }
255
+ return false;
256
+ }
257
+
258
+ /** A polyfill guard around the change: `if (!X.prototype.m)`, `"m" in X.prototype`, `X.m || (X.m = …)`. */
259
+ private guarded(node: ts.Node, path: string, name: string): boolean {
260
+ const t = this.typescript;
261
+ const mentions = (condition: ts.Node): boolean => {
262
+ let found = false;
263
+ const look = (n: ts.Node): void => {
264
+ if (found) return;
265
+ if (
266
+ (t.isPropertyAccessExpression(n) || t.isElementAccessExpression(n) || t.isIdentifier(n)) &&
267
+ this.builtins.path(n) === path
268
+ )
269
+ found = true;
270
+ else if (name && t.isStringLiteralLike(n) && n.text === name) found = true;
271
+ else t.forEachChild(n, look);
272
+ };
273
+ look(condition);
274
+ return found;
275
+ };
276
+ let child: ts.Node = node;
277
+ for (let parent = node.parent; parent; child = parent, parent = parent.parent) {
278
+ if (t.isFunctionLike(parent) || t.isClassLike(parent)) return false;
279
+ if (t.isIfStatement(parent) && child !== parent.expression && mentions(parent.expression)) return true;
280
+ if (t.isConditionalExpression(parent) && child !== parent.condition && mentions(parent.condition)) return true;
281
+ if (
282
+ t.isBinaryExpression(parent) &&
283
+ child === parent.right &&
284
+ [t.SyntaxKind.AmpersandAmpersandToken, t.SyntaxKind.BarBarToken, t.SyntaxKind.QuestionQuestionToken].includes(
285
+ parent.operatorToken.kind,
286
+ ) &&
287
+ mentions(parent.left)
288
+ )
289
+ return true;
290
+ if (t.isBlock(parent) || t.isSourceFile(parent) || t.isModuleBlock(parent) || t.isCaseClause(parent)) {
291
+ // An early exit before the change: `if (Array.prototype.at) return;`
292
+ for (const statement of parent.statements) {
293
+ if (statement === child) break;
294
+ if (t.isIfStatement(statement) && mentions(statement.expression) && this.exits(statement.thenStatement))
295
+ return true;
296
+ }
297
+ }
298
+ }
299
+ return false;
300
+ }
301
+
302
+ private exits(statement: ts.Statement): boolean {
303
+ const t = this.typescript;
304
+ if (t.isReturnStatement(statement) || t.isThrowStatement(statement)) return true;
305
+ return t.isBlock(statement) && statement.statements.some((s) => t.isReturnStatement(s) || t.isThrowStatement(s));
306
+ }
307
+ }
@@ -0,0 +1,69 @@
1
+ // The JSON `sk check --format json` prints: schema "skathi.check", version 1. Additive changes keep the
2
+ // version; a renamed or removed field bumps it.
3
+
4
+ export type Severity = "error" | "warning";
5
+
6
+ /** Zero-based, in UTF-16 code units (LSP positions). */
7
+ export interface Position {
8
+ line: number;
9
+ character: number;
10
+ }
11
+
12
+ export interface Range {
13
+ start: Position;
14
+ end: Position;
15
+ }
16
+
17
+ export interface PackageRef {
18
+ name: string;
19
+ version: string;
20
+ }
21
+
22
+ export interface Related {
23
+ /** Relative to `root`, with forward slashes. */
24
+ file: string;
25
+ range: Range;
26
+ message: string;
27
+ }
28
+
29
+ export interface Diagnostic {
30
+ code: string;
31
+ severity: Severity;
32
+ message: string;
33
+ /** Relative to `root`, with forward slashes. */
34
+ file: string;
35
+ /** The package `file` belongs to; null for the app's own code. */
36
+ package: PackageRef | null;
37
+ range: Range;
38
+ help: string | null;
39
+ related: Related[];
40
+ }
41
+
42
+ export interface TypingScore {
43
+ /** null for the app's own code. */
44
+ package: string | null;
45
+ version: string | null;
46
+ /** Exported declarations the app reaches (for the app: its own declarations). */
47
+ declarations: number;
48
+ /** How many of them reach the compiler as `any`. */
49
+ any: number;
50
+ }
51
+
52
+ export interface Summary {
53
+ errors: number;
54
+ warnings: number;
55
+ suppressed: number;
56
+ files: number;
57
+ packages: number;
58
+ typing: TypingScore[];
59
+ }
60
+
61
+ export interface CheckReport {
62
+ schema: "skathi.check";
63
+ version: 1;
64
+ tool: { name: "sk"; version: string };
65
+ /** The app directory, absolute, with forward slashes. */
66
+ root: string;
67
+ diagnostics: Diagnostic[];
68
+ summary: Summary;
69
+ }