Skip to content

Commit 12f266e

Browse files
committed
Fix type-check errors in vscode-knip
1 parent aeabff7 commit 12f266e

6 files changed

Lines changed: 52 additions & 19 deletions

File tree

packages/mcp-server/src/tools.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ export function buildResults(results, options) {
4141
: { exists: false, locations: KNIP_CONFIG_LOCATIONS };
4242

4343
const reviewHint = isSuppressIssues ? UNCONFIGURED_HINT : options.configFilePath ? CONFIG_REVIEW_HINT : undefined;
44-
const files = isSuppressIssues ? null : Array.from(results.issues.files);
44+
const files = isSuppressIssues ? null : Object.keys(results.issues.files);
4545
const issues = isSuppressIssues
4646
? null
4747
: Object.fromEntries(Object.entries(results.issues).filter(([key]) => key !== 'files' && key !== '_files'));
@@ -74,7 +74,7 @@ export function readContent(filePath) {
7474
const content = readFileSync(join(docsDir, filePath), 'utf-8');
7575
return content.replace(/^---[\s\S]*?---\n/, '');
7676
} catch (error) {
77-
return `Error reading ${filePath}: ${error.message}`;
77+
return `Error reading ${filePath}: ${error instanceof Error ? error.message : String(error)}`;
7878
}
7979
}
8080

@@ -90,7 +90,9 @@ export function getDocs(topic) {
9090

9191
/** @param {string} topic */
9292
function findDocPage(topic) {
93-
if (CURATED_RESOURCES[topic]) return readContent(CURATED_RESOURCES[topic].path);
93+
/** @type {Record<string, { name: string; description: string; path: string }>} */
94+
const resources = CURATED_RESOURCES;
95+
if (resources[topic]) return readContent(resources[topic].path);
9496

9597
for (const ext of ['.md', '.mdx']) {
9698
const filePath = join(docsDir, `${topic}${ext}`);

packages/vscode-knip/scripts/publish.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ const root = join(dirname(fileURLToPath(import.meta.url)), '..');
3030
const dist = join(root, 'dist');
3131
const nm = join(dist, 'node_modules');
3232

33+
/** @type {Record<string, string>} */
3334
const targets = {
3435
'darwin-arm64': 'darwin-arm64',
3536
'darwin-x64': 'darwin-x64',
@@ -49,6 +50,12 @@ const vsixFiles = [];
4950

5051
rmSync(dist, { recursive: true, force: true });
5152

53+
/**
54+
* @param {string} input
55+
* @param {string} output
56+
* @param {(string | RegExp)[]} [external]
57+
* @param {Record<string, string>} [paths]
58+
*/
5259
const bundle = async (input, output, external = ext, paths) => {
5360
const build = await rolldown({ input: join(root, input), external, platform: 'node' });
5461
await build.write({ format: 'cjs', minify: true, file: join(dist, output), paths });
@@ -71,6 +78,7 @@ await bundle('src/index.js', 'extension.js', [...extSession, '@knip/language-ser
7178
const knipNm = join(dirname(fileURLToPath(import.meta.resolve('knip'))), '..', 'node_modules');
7279

7380
const knipRequire = createRequire(join(knipNm, '..', 'package.json'));
81+
/** @param {string} pkgName */
7482
const bindingVersion = pkgName =>
7583
JSON.parse(readFileSync(knipRequire.resolve(`${pkgName}/package.json`), 'utf8')).version;
7684
const oxcParserVersion = bindingVersion('oxc-parser');
@@ -99,6 +107,12 @@ const selectedTargets = args.target
99107
? Object.entries(targets)
100108
: [[currentTarget, targets[currentTarget]]];
101109

110+
/**
111+
* @param {string} scope
112+
* @param {string} name
113+
* @param {string} binding
114+
* @param {string} version
115+
*/
102116
const packNativeBinding = (scope, name, binding, version) => {
103117
rmSync(join(nm, scope), { recursive: true, force: true });
104118
mkdirSync(join(nm, `${scope}/binding-${binding}`), { recursive: true });

packages/vscode-knip/src/index.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,10 @@ export class Extension {
262262
* @returns {string} Package manager name ('pnpm', 'yarn', or 'npm')
263263
* @throws {Error} If no package manager can be detected
264264
*/
265+
/**
266+
* @param {string} startDir
267+
* @returns {'npm' | 'pnpm' | 'yarn'}
268+
*/
265269
#detectPackageManager(startDir) {
266270
let dir = startDir;
267271
const root = path.parse(dir).root;
@@ -298,7 +302,7 @@ export class Extension {
298302
try {
299303
await client.sendRequest(REQUEST_START);
300304
} catch (error) {
301-
vscode.window.showErrorMessage((error?.message || error).toString());
305+
vscode.window.showErrorMessage(error instanceof Error ? error.message : String(error));
302306
}
303307
}
304308
});
@@ -310,7 +314,7 @@ export class Extension {
310314
this.#packageJsonCache = undefined;
311315
await client.sendRequest(REQUEST_RESTART);
312316
} catch (error) {
313-
vscode.window.showErrorMessage((error?.message || error).toString());
317+
vscode.window.showErrorMessage(error instanceof Error ? error.message : String(error));
314318
}
315319
});
316320

@@ -679,7 +683,7 @@ export class Extension {
679683
});
680684

681685
const showReferences = vscode.commands.registerCommand('knip.showReferences', (uri, position, importLocations) => {
682-
const locations = importLocations.map(location => {
686+
const locations = importLocations.map(/** @param {{ filePath: string; line?: number; col?: number }} location */ location => {
683687
const pos = new vscode.Position(location.line ? location.line - 1 : 0, location.col ? location.col - 1 : 0);
684688
return new vscode.Location(vscode.Uri.file(location.filePath), pos);
685689
});
@@ -688,10 +692,12 @@ export class Extension {
688692
});
689693

690694
const expandAll = vscode.commands.registerCommand('knip.expandAll', () => {
695+
/** @param {import('./tree-view-base.js').BaseTreeViewProvider | undefined} provider */
691696
const expand = async provider => {
692697
const treeViewLocal = provider?.treeView;
693698
if (!treeViewLocal) return;
694699

700+
/** @param {import('./tree-view-base.js').TreeViewItem} element */
695701
const expandNode = async element => {
696702
try {
697703
await treeViewLocal.reveal(element, { expand: true, focus: false, select: false });

packages/vscode-knip/src/tree-view-base.js

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import * as vscode from 'vscode';
1010
*
1111
* @typedef {vscode.TreeItem & {
1212
* _parent?: TreeViewItem;
13-
* _children?: TreeViewItem[];
13+
* _children?: Array<TreeViewItem | Node>;
1414
* _reveal?: { identifier: string; line: number; col: number; };
1515
* }} TreeViewItem
1616
*
@@ -156,8 +156,10 @@ export class BaseTreeViewProvider {
156156
getChildren(element) {
157157
if (element) {
158158
if (!element._children) return [];
159-
if (element._children[0] instanceof vscode.TreeItem) return element._children;
160-
return (element._children ?? []).map(child => this.createTreeViewItems(Object.assign(child, { lazy: true })));
159+
if (element._children[0] instanceof vscode.TreeItem) return /** @type {TreeViewItem[]} */ (element._children);
160+
return (element._children ?? []).map(child =>
161+
this.createTreeViewItems(/** @type {Node} */ (Object.assign(child, { lazy: true })))
162+
);
161163
}
162164

163165
if (!this.currentUri) {
@@ -215,7 +217,7 @@ export class BaseTreeViewProvider {
215217
* importCol?: number;
216218
* icon?: string;
217219
* lazy?: boolean
218-
* children?: Node[];
220+
* children?: Array<TreeViewItem | Node>;
219221
* }} Node;
220222
* @param {Node} options
221223
* @returns {TreeViewItem}
@@ -258,9 +260,16 @@ export class BaseTreeViewProvider {
258260
};
259261
}
260262

261-
const children = options.children?.[0]?.filePath
262-
? options.children.toSorted((a, b) => (a.filePath && b.filePath ? a.filePath.localeCompare(b.filePath) : 0))
263-
: (options.children ?? []);
263+
const childList = options.children ?? [];
264+
const firstChild = childList[0];
265+
const children =
266+
firstChild && 'filePath' in firstChild && firstChild.filePath
267+
? childList.toSorted((a, b) => {
268+
const af = 'filePath' in a ? a.filePath : undefined;
269+
const bf = 'filePath' in b ? b.filePath : undefined;
270+
return af && bf ? af.localeCompare(bf) : 0;
271+
})
272+
: childList;
264273

265274
const node = this.createTreeViewItem({
266275
label: filePath ? (options.icon ?? '→') : (options.label ?? ''),
@@ -272,10 +281,12 @@ export class BaseTreeViewProvider {
272281

273282
if (!options.lazy) {
274283
for (let i = 0; i < children.length; i++) {
275-
if (children[i] instanceof vscode.TreeItem) continue;
276-
children[i].tooltip = children[i].tooltip ?? options.tooltipChildren;
277-
children[i] = this.createTreeViewItems(children[i]);
278-
children[i]._parent = node;
284+
const child = children[i];
285+
if (child instanceof vscode.TreeItem) continue;
286+
child.tooltip = child.tooltip ?? options.tooltipChildren;
287+
const built = this.createTreeViewItems(child);
288+
built._parent = node;
289+
children[i] = built;
279290
}
280291
}
281292

packages/vscode-knip/src/tree-view-exports.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ export class ExportsTreeViewProvider extends BaseTreeViewProvider {
9797
}
9898
const nodes = [];
9999

100-
const stringFields = ['main', 'module', 'browser', 'types', 'typings'];
100+
const stringFields = /** @type {const} */ (['main', 'module', 'browser', 'types', 'typings']);
101101
for (const field of stringFields) {
102102
if (typeof manifest[field] === 'string') {
103103
nodes.push(this.createTreeViewItems({ label: field, children: [{ filePath: manifest[field] }] }));

packages/vscode-knip/test/index.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export async function run() {
1616
console.log(`✓ ${name}`);
1717
results.passed++;
1818
} catch (err) {
19-
console.error(`✗ ${name}:`, err.message);
19+
console.error(`✗ ${name}:`, err instanceof Error ? err.message : String(err));
2020
results.failed++;
2121
}
2222
}

0 commit comments

Comments
 (0)