@skathi-native/cli 0.0.0-stage → 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.
package/check/index.ts ADDED
@@ -0,0 +1,308 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { join, relative, resolve, sep } from "node:path";
4
+ import { loadAppConfig } from "../cli/config";
5
+ import { quietProgress, type Progress } from "../cli/term";
6
+ import { Builtins } from "./builtins";
7
+ import { codeInfo, REGISTRY } from "./codes";
8
+ import { parseCheckConfig, Suppressions } from "./config";
9
+ import { rangeOf, ZERO_RANGE, type Finding } from "./finding";
10
+ import { buildGraph, GraphFailure, type ModuleGraph } from "./graph";
11
+ import { Packages } from "./packages";
12
+ import { buildProgram, readUnits, type TypeScript } from "./program";
13
+ import { Rules } from "./rules";
14
+ import type { CheckReport, Diagnostic } from "./schema";
15
+ import { Typing } from "./typing";
16
+
17
+ export type { CheckReport, Diagnostic } from "./schema";
18
+ export { explain, formatPretty, listCodes } from "./report";
19
+
20
+ const PROD_TS = join(import.meta.dir, "..", "prod.ts");
21
+
22
+ /** Packages the SDK provides and answers for under AOT; an app cannot swap or retype them. */
23
+ const PLATFORM = new Set([
24
+ "vue",
25
+ "@vue/runtime-core",
26
+ "@vue/runtime-dom",
27
+ "@vue/reactivity",
28
+ "@vue/shared",
29
+ "@skathi-native/runtime",
30
+ ]);
31
+
32
+ export class CheckSetupError extends Error {}
33
+
34
+ export interface CheckOptions {
35
+ target: string;
36
+ configPath?: string | undefined;
37
+ /** Check node_modules too (default); false: the app's own code only. */
38
+ deps?: boolean;
39
+ toolVersion: string;
40
+ progress?: Progress | undefined;
41
+ }
42
+
43
+ export interface AnalyzeInput {
44
+ typescript: TypeScript;
45
+ root: string;
46
+ entry: string;
47
+ modules: string[];
48
+ aliases?: Record<string, string>;
49
+ declarations?: string[];
50
+ allow?: Map<string, string[]>;
51
+ deps?: boolean;
52
+ toolVersion: string;
53
+ /** Findings made before the analysis (configuration problems). */
54
+ findings?: Finding[];
55
+ progress?: Progress | undefined;
56
+ }
57
+
58
+ export function loadTypeScript(appRoot: string): TypeScript {
59
+ for (const base of [join(import.meta.dir, "..", "package.json"), join(appRoot, "package.json")]) {
60
+ try {
61
+ return createRequire(base)("typescript") as TypeScript;
62
+ } catch {}
63
+ }
64
+ throw new CheckSetupError("sk check needs the typescript package: add it to the app (bun add -d typescript)");
65
+ }
66
+
67
+ const posix = (path: string) => path.split(sep).join("/");
68
+
69
+ export async function runCheck(options: CheckOptions): Promise<CheckReport> {
70
+ const progress = options.progress ?? quietProgress;
71
+ const config = loadAppConfig(options.target, { configPath: options.configPath });
72
+ const configFile = config.configPath ?? join(config.appRoot, "sk.config.json");
73
+ const checkConfig = parseCheckConfig(config.raw.check);
74
+ const configText = checkConfig.problems.length ? readFileSync(configFile, "utf8").replace(/^/, "") : "";
75
+ const findings: Finding[] = checkConfig.problems.map(({ message, key }) => {
76
+ const at = configText.indexOf(JSON.stringify(key));
77
+ const before = configText.slice(0, Math.max(0, at)).split("\n");
78
+ const line = before.length - 1;
79
+ const character = before[line]!.length;
80
+ return {
81
+ code: "SK0003",
82
+ message: `sk.config.json ${message}`,
83
+ file: configFile,
84
+ range:
85
+ at < 0
86
+ ? ZERO_RANGE
87
+ : { start: { line, character }, end: { line, character: character + JSON.stringify(key).length } },
88
+ related: [],
89
+ };
90
+ });
91
+ const typescript = loadTypeScript(config.appRoot);
92
+ const base = { typescript, root: config.appRoot, entry: config.entry, toolVersion: options.toolVersion, progress };
93
+ if (findings.length) return analyze({ ...base, modules: [], findings });
94
+
95
+ progress.step("module graph");
96
+ let graph: ModuleGraph;
97
+ try {
98
+ graph = await buildGraph({
99
+ prodTs: PROD_TS,
100
+ entry: config.entry,
101
+ appRoot: config.appRoot,
102
+ configPath: config.configPath,
103
+ });
104
+ } catch (e) {
105
+ if (!(e instanceof GraphFailure)) throw e;
106
+ findings.push({
107
+ code: "SK0004",
108
+ message: `the production build fails: ${e.message.split(/\r?\n/).find((l) => l.trim()) ?? e.message}`,
109
+ file: config.entry,
110
+ range: ZERO_RANGE,
111
+ help: e.message.includes("\n") ? e.message : undefined,
112
+ related: [],
113
+ });
114
+ return analyze({ ...base, modules: [], findings });
115
+ }
116
+ if (graph.errors.length) {
117
+ for (const error of graph.errors) {
118
+ const line = Math.max(0, (error.line ?? 1) - 1);
119
+ const character = Math.max(0, error.column ?? 0);
120
+ findings.push({
121
+ code: "SK0004",
122
+ message: error.specifier
123
+ ? `\`${error.specifier}\` does not resolve, so the bundle cannot be built: ${error.message}`
124
+ : `the production build fails: ${error.message}`,
125
+ file: error.file ?? config.entry,
126
+ range: { start: { line, character }, end: { line, character } },
127
+ related: [],
128
+ });
129
+ }
130
+ return analyze({ ...base, modules: [], findings });
131
+ }
132
+ progress.detail(`${graph.modules.length} files`);
133
+ return analyze({
134
+ ...base,
135
+ modules: graph.modules,
136
+ aliases: graph.aliases,
137
+ declarations: graph.declarations,
138
+ allow: checkConfig.allow,
139
+ deps: options.deps ?? true,
140
+ });
141
+ }
142
+
143
+ export function analyze(input: AnalyzeInput): CheckReport {
144
+ const { typescript } = input;
145
+ const progress = input.progress ?? quietProgress;
146
+ const deps = input.deps ?? true;
147
+ const root = resolve(input.root);
148
+ const packages = new Packages(root);
149
+ const findings: Finding[] = [...(input.findings ?? [])];
150
+ const { units, unreadable } = readUnits(input.modules, packages);
151
+ for (const u of unreadable)
152
+ findings.push({
153
+ code: "SK0001",
154
+ message: `cannot read this file: ${u.message}`,
155
+ file: u.path,
156
+ range: ZERO_RANGE,
157
+ related: [],
158
+ });
159
+
160
+ const analysed = deps ? units : units.filter((u) => !u.owner);
161
+ if (units.length) {
162
+ progress.step("TypeScript program", units.length);
163
+ const built = buildProgram({
164
+ typescript,
165
+ appRoot: root,
166
+ entry: input.entry,
167
+ units,
168
+ aliases: input.aliases ?? {},
169
+ declarations: input.declarations ?? [],
170
+ onFile: () => progress.tick(),
171
+ });
172
+ if (built.configNote) progress.warn(built.configNote);
173
+ const { program, checker } = built;
174
+ const rules = new Rules(typescript, checker, new Builtins(typescript, program, checker));
175
+ progress.step("AOT rules", units.length);
176
+ for (const unit of units) {
177
+ progress.tick();
178
+ const file = unit.sourceFile ?? program.getSourceFile(unit.programPath);
179
+ if (!file) {
180
+ findings.push({
181
+ code: "SK0001",
182
+ message: "the TypeScript program could not load this file",
183
+ file: unit.path,
184
+ range: ZERO_RANGE,
185
+ related: [],
186
+ });
187
+ continue;
188
+ }
189
+ unit.sourceFile = file;
190
+ const syntax = program.getSyntacticDiagnostics(file);
191
+ const first = syntax[0];
192
+ if (first) {
193
+ const start = first.start ?? 0;
194
+ findings.push({
195
+ code: "SK0002",
196
+ message: `this file does not parse, so it was not checked: ${typescript.flattenDiagnosticMessageText(first.messageText, " ")}`,
197
+ file: unit.path,
198
+ range: rangeOf(file, start, start + (first.length ?? 0)),
199
+ related: [],
200
+ });
201
+ delete unit.sourceFile;
202
+ continue;
203
+ }
204
+ if (deps || !unit.owner) rules.run(unit, file, findings);
205
+ }
206
+ progress.step("typing quality");
207
+ const typing = new Typing(
208
+ typescript,
209
+ program,
210
+ checker,
211
+ packages,
212
+ units.filter((u) => u.sourceFile),
213
+ );
214
+ const typingFindings: Finding[] = [];
215
+ if (deps) typing.untypedPackages(typingFindings);
216
+ typing.imports(typingFindings);
217
+ typing.appCode(typingFindings);
218
+ findings.push(...(deps ? typingFindings : typingFindings.filter((f) => !packages.ownerOf(f.file))));
219
+ return report(
220
+ input,
221
+ root,
222
+ packages,
223
+ findings,
224
+ analysed.length + unreadable.length,
225
+ deps ? typing.results() : typing.results().filter((s) => !s.owner),
226
+ );
227
+ }
228
+ return report(input, root, packages, findings, unreadable.length, []);
229
+ }
230
+
231
+ function report(
232
+ input: AnalyzeInput,
233
+ root: string,
234
+ packages: Packages,
235
+ findings: Finding[],
236
+ files: number,
237
+ scores: ReturnType<Typing["results"]>,
238
+ ): CheckReport {
239
+ const rel = (file: string) => posix(relative(root, file));
240
+ const suppress = new Suppressions(input.allow ?? new Map());
241
+ const diagnostics: Diagnostic[] = [];
242
+ const owners = new Set<string>();
243
+ let suppressed = 0;
244
+ for (const f of findings) {
245
+ const info = codeInfo(f.code);
246
+ const owner = packages.ownerOf(f.file);
247
+ if (owner && PLATFORM.has(owner.name)) continue;
248
+ const file = rel(f.file);
249
+ if (!info.fatal && suppress.matches(f.code, file, owner?.name ?? null)) {
250
+ suppressed++;
251
+ continue;
252
+ }
253
+ diagnostics.push({
254
+ code: f.code,
255
+ severity: info.severity,
256
+ message: f.message,
257
+ file,
258
+ package: owner ? { name: owner.name, version: owner.version } : null,
259
+ range: f.range,
260
+ help: f.help ?? info.fix,
261
+ related: f.related.map((r) => ({ file: rel(r.file), range: r.range, message: r.message })),
262
+ });
263
+ }
264
+ for (const u of input.modules) {
265
+ const owner = packages.ownerOf(u);
266
+ if (owner && !PLATFORM.has(owner.name) && (input.deps ?? true)) owners.add(`${owner.name}@${owner.version}`);
267
+ }
268
+ diagnostics.sort(
269
+ (a, b) =>
270
+ (a.file < b.file ? -1 : a.file > b.file ? 1 : 0) ||
271
+ a.range.start.line - b.range.start.line ||
272
+ a.range.start.character - b.range.start.character ||
273
+ a.code.localeCompare(b.code),
274
+ );
275
+ const typing = scores
276
+ .filter((s) => !(s.owner && PLATFORM.has(s.owner.name)))
277
+ .map((s) => ({
278
+ package: s.owner?.name ?? null,
279
+ version: s.owner?.version ?? null,
280
+ declarations: s.declarations,
281
+ any: s.any,
282
+ }))
283
+ .sort(
284
+ (a, b) => (a.package ?? "").localeCompare(b.package ?? "") || (a.version ?? "").localeCompare(b.version ?? ""),
285
+ );
286
+ return {
287
+ schema: "skathi.check",
288
+ version: 1,
289
+ tool: { name: "sk", version: input.toolVersion },
290
+ root: posix(root),
291
+ diagnostics,
292
+ summary: {
293
+ errors: diagnostics.filter((d) => d.severity === "error").length,
294
+ warnings: diagnostics.filter((d) => d.severity === "warning").length,
295
+ suppressed,
296
+ files,
297
+ packages: owners.size,
298
+ typing,
299
+ },
300
+ };
301
+ }
302
+
303
+ export function exitCode(report: CheckReport, denyWarnings: boolean): number {
304
+ if (report.diagnostics.some((d) => REGISTRY.get(d.code)?.fatal)) return 2;
305
+ if (report.summary.errors) return 1;
306
+ if (denyWarnings && report.summary.warnings) return 1;
307
+ return 0;
308
+ }
@@ -0,0 +1,54 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
3
+
4
+ export interface PackageInfo {
5
+ name: string;
6
+ version: string;
7
+ dir: string;
8
+ json: Record<string, unknown>;
9
+ }
10
+
11
+ const inside = (root: string, path: string) => {
12
+ const rel = relative(root, path);
13
+ return !rel.startsWith("..") && !isAbsolute(rel);
14
+ };
15
+
16
+ /** Attributes a file to the nearest package.json with a name, or to the app (null). */
17
+ export class Packages {
18
+ private readonly dirs = new Map<string, PackageInfo | null>();
19
+
20
+ constructor(readonly appRoot: string) {}
21
+
22
+ ownerOf(file: string): PackageInfo | null {
23
+ if (inside(this.appRoot, file) && !relative(this.appRoot, file).split(sep).includes("node_modules")) return null;
24
+ return this.lookup(dirname(file));
25
+ }
26
+
27
+ private lookup(dir: string): PackageInfo | null {
28
+ const known = this.dirs.get(dir);
29
+ if (known !== undefined) return known;
30
+ let found: PackageInfo | null = null;
31
+ const path = join(dir, "package.json");
32
+ if (dir !== this.appRoot && existsSync(path)) {
33
+ try {
34
+ const json = JSON.parse(readFileSync(path, "utf8")) as unknown;
35
+ if (json && typeof json === "object" && !Array.isArray(json)) {
36
+ const record = json as Record<string, unknown>;
37
+ if (typeof record.name === "string" && record.name)
38
+ found = {
39
+ name: record.name,
40
+ version: typeof record.version === "string" ? record.version : "0.0.0",
41
+ dir,
42
+ json: record,
43
+ };
44
+ }
45
+ } catch {}
46
+ }
47
+ if (!found && dir !== this.appRoot) {
48
+ const parent = dirname(dir);
49
+ found = parent === dir ? null : this.lookup(parent);
50
+ }
51
+ this.dirs.set(dir, found);
52
+ return found;
53
+ }
54
+ }
@@ -0,0 +1,209 @@
1
+ import { parse as parseSfc } from "@vue/compiler-sfc";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import type ts from "typescript";
5
+ import type { PackageInfo, Packages } from "./packages";
6
+
7
+ export type TypeScript = typeof ts;
8
+
9
+ /** One file of the bundle as the analysis sees it. */
10
+ export interface Unit {
11
+ /** The file on disk (.vue for a single-file component). */
12
+ path: string;
13
+ /** Its name in the TypeScript program: `<path>.ts`/`.js` for a .vue file. */
14
+ programPath: string;
15
+ /** The text positions refer to; for a .vue file everything but its scripts is blanked. */
16
+ text: string;
17
+ /** TypeScript rather than JavaScript. */
18
+ typed: boolean;
19
+ owner: PackageInfo | null;
20
+ sourceFile?: ts.SourceFile;
21
+ }
22
+
23
+ export interface Unreadable {
24
+ path: string;
25
+ owner: PackageInfo | null;
26
+ message: string;
27
+ }
28
+
29
+ const TS_FILE = /\.[cm]?tsx?$/i;
30
+
31
+ /** The scripts of an SFC at their own offsets, everything else replaced by spaces. */
32
+ export function vueScripts(source: string, path: string): { text: string; typed: boolean } | null {
33
+ const { descriptor } = parseSfc(source, { filename: path });
34
+ const blocks = [descriptor.script, descriptor.scriptSetup].filter((b) => b !== null && !b.src);
35
+ if (!blocks.length) return null;
36
+ const chars = source.replace(/[^\r\n]/g, " ").split("");
37
+ for (const block of blocks) {
38
+ const start = block!.loc.start.offset;
39
+ for (let i = 0; i < block!.content.length; i++) chars[start + i] = block!.content[i]!;
40
+ }
41
+ return { text: chars.join(""), typed: blocks.some((b) => /^tsx?$/.test(b!.lang ?? "")) };
42
+ }
43
+
44
+ export function readUnits(
45
+ modules: string[],
46
+ packages: Packages,
47
+ ): { units: Unit[]; unreadable: Unreadable[]; skipped: number } {
48
+ const units: Unit[] = [];
49
+ const unreadable: Unreadable[] = [];
50
+ let skipped = 0;
51
+ for (const path of modules) {
52
+ const owner = packages.ownerOf(path);
53
+ let source: string;
54
+ try {
55
+ source = readFileSync(path, "utf8").replace(/^/, "");
56
+ } catch (e) {
57
+ unreadable.push({ path, owner, message: (e as Error).message });
58
+ continue;
59
+ }
60
+ if (/\.vue$/i.test(path)) {
61
+ let scripts: ReturnType<typeof vueScripts>;
62
+ try {
63
+ scripts = vueScripts(source, path);
64
+ } catch (e) {
65
+ unreadable.push({ path, owner, message: (e as Error).message });
66
+ continue;
67
+ }
68
+ if (!scripts) {
69
+ skipped++;
70
+ continue;
71
+ }
72
+ units.push({
73
+ path,
74
+ programPath: `${path}.${scripts.typed ? "ts" : "js"}`,
75
+ text: scripts.text,
76
+ typed: scripts.typed,
77
+ owner,
78
+ });
79
+ } else {
80
+ units.push({ path, programPath: path, text: source, typed: TS_FILE.test(path), owner });
81
+ }
82
+ }
83
+ return { units, unreadable, skipped };
84
+ }
85
+
86
+ export interface ProgramInput {
87
+ typescript: TypeScript;
88
+ appRoot: string;
89
+ entry: string;
90
+ units: Unit[];
91
+ aliases: Record<string, string>;
92
+ declarations: string[];
93
+ onFile?: (() => void) | undefined;
94
+ }
95
+
96
+ export interface BuiltProgram {
97
+ program: ts.Program;
98
+ checker: ts.TypeChecker;
99
+ configNote: string | null;
100
+ }
101
+
102
+ function compilerOptions(
103
+ typescript: TypeScript,
104
+ appRoot: string,
105
+ entry: string,
106
+ ): { options: ts.CompilerOptions; roots: string[]; note: string | null } {
107
+ const fallback: ts.CompilerOptions = {
108
+ target: typescript.ScriptTarget.ESNext,
109
+ module: typescript.ModuleKind.ESNext,
110
+ moduleResolution: typescript.ModuleResolutionKind.Bundler,
111
+ };
112
+ const configPath = typescript.findConfigFile(appRoot, typescript.sys.fileExists);
113
+ if (!configPath) return { options: fallback, roots: [], note: null };
114
+ try {
115
+ const projects: ts.ParsedCommandLine[] = [];
116
+ const visited = new Set<string>();
117
+ const visit = (path: string) => {
118
+ if (visited.has(resolve(path))) return;
119
+ visited.add(resolve(path));
120
+ const config = typescript.readConfigFile(path, typescript.sys.readFile);
121
+ if (config.error) throw new Error(typescript.flattenDiagnosticMessageText(config.error.messageText, "\n"));
122
+ const parsed = typescript.parseJsonConfigFileContent(config.config, typescript.sys, dirname(path));
123
+ projects.push(parsed);
124
+ for (const reference of parsed.projectReferences ?? []) visit(typescript.resolveProjectReferencePath(reference));
125
+ };
126
+ visit(configPath);
127
+ const key = (p: string) => resolve(p).toLowerCase();
128
+ const selected = projects.find((p) => p.fileNames.some((f) => key(f) === key(entry))) ?? projects[0]!;
129
+ return {
130
+ options: selected.options,
131
+ roots: selected.fileNames.filter((f) => TS_FILE.test(f)),
132
+ note: null,
133
+ };
134
+ } catch (e) {
135
+ return { options: fallback, roots: [], note: `${configPath}: ${(e as Error).message}; checked with defaults` };
136
+ }
137
+ }
138
+
139
+ export function buildProgram(input: ProgramInput): BuiltProgram {
140
+ const { typescript, units, aliases } = input;
141
+ const { options: base, roots, note } = compilerOptions(typescript, input.appRoot, input.entry);
142
+ const options: ts.CompilerOptions = {
143
+ ...base,
144
+ noEmit: true,
145
+ allowJs: true,
146
+ checkJs: false,
147
+ skipLibCheck: true,
148
+ declaration: false,
149
+ composite: false,
150
+ incremental: false,
151
+ maxNodeModuleJsDepth: 0,
152
+ };
153
+ const caseless = !typescript.sys.useCaseSensitiveFileNames;
154
+ const key = (p: string) => (caseless ? resolve(p).toLowerCase() : resolve(p));
155
+ const own = new Map(units.map((u) => [key(u.programPath), u]));
156
+ const host = typescript.createCompilerHost(options, true);
157
+ const readFile = host.readFile.bind(host);
158
+ const fileExists = host.fileExists.bind(host);
159
+ const getSourceFile = host.getSourceFile.bind(host);
160
+ host.readFile = (path) => own.get(key(path))?.text ?? readFile(path);
161
+ host.fileExists = (path) => own.has(key(path)) || fileExists(path);
162
+ host.getSourceFile = (path, language, onError, create) => {
163
+ const unit = own.get(key(path));
164
+ if (!unit) return getSourceFile(path, language, onError, create);
165
+ input.onFile?.();
166
+ unit.sourceFile = typescript.createSourceFile(
167
+ path,
168
+ unit.text,
169
+ language,
170
+ true,
171
+ unit.typed ? typescript.ScriptKind.TS : /\.jsx$/i.test(path) ? typescript.ScriptKind.JSX : undefined,
172
+ );
173
+ return unit.sourceFile;
174
+ };
175
+ host.resolveModuleNames = (names, importer) =>
176
+ names.map((specifier) => {
177
+ // The bundle's aliases win over node_modules, as they do in the build.
178
+ const alias = aliases[specifier];
179
+ if (alias) {
180
+ if (TS_FILE.test(alias)) return { resolvedFileName: alias, extension: typescript.Extension.Ts };
181
+ // A built .mjs stands in for a package: take that package's own declarations.
182
+ return (
183
+ typescript.resolveModuleName(specifier, alias, options, host).resolvedModule ?? {
184
+ resolvedFileName: alias,
185
+ extension: typescript.Extension.Js,
186
+ }
187
+ );
188
+ }
189
+ const found = typescript.resolveModuleName(specifier, importer, options, host).resolvedModule;
190
+ if (found) return found;
191
+ if (/\.vue$/i.test(specifier) && specifier.startsWith(".")) {
192
+ for (const ext of ["ts", "js"] as const) {
193
+ const path = resolve(dirname(importer), `${specifier}.${ext}`);
194
+ if (own.has(key(path)))
195
+ return {
196
+ resolvedFileName: path,
197
+ extension: ext === "ts" ? typescript.Extension.Ts : typescript.Extension.Js,
198
+ };
199
+ }
200
+ }
201
+ return undefined;
202
+ });
203
+ const program = typescript.createProgram({
204
+ rootNames: [...new Set([...units.map((u) => u.programPath), ...input.declarations, ...roots])],
205
+ options,
206
+ host,
207
+ });
208
+ return { program, checker: program.getTypeChecker(), configNote: note };
209
+ }