fix(types): preserve complete nested types during post-processing
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s

Use the TypeScript parser instead of a regex that truncates nested generics and function types. Validate generated syntax and add a regression test. Include workspace aliases and PTY ambient declarations. The full type package build still reports six errors in third-party node-pty source; this commit does not claim to resolve that remaining issue.
This commit is contained in:
手瓜一十雪 committed 2026-10-06 17:51:21 +08:00
1 parent 9109b8cfe2
commit 4f1401da78
4 files changed
+77 -6

No files matched your search

@@ -0,0 +1,44 @@
import { afterEach, expect, test } from 'vitest';
import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
const fixtures: string[] = [];
afterEach(() => {
for (const fixture of fixtures.splice(0)) {
rmSync(fixture, { recursive: true, force: true });
}
});
test('type post-build replaces complete nested generic and import types', () => {
const fixture = mkdtempSync(path.join(packageRoot, 'napcat-types/post-build-test-'));
fixtures.push(fixture);
mkdirSync(path.join(fixture, 'scripts'));
mkdirSync(path.join(fixture, 'dist'));
const script = path.join(fixture, 'scripts/post-build.mjs');
copyFileSync(path.join(packageRoot, 'napcat-types/scripts/post-build.mjs'), script);
writeFileSync(path.join(fixture, 'dist/fixture.d.ts'), `
import { NapProtoDecodeStructType } from 'napcat-protobuf';
export declare class Example {
parse(): import('napcat-protobuf').NapProtoDecodeStructType<() => { nested: Map<string, Array<number>> }>;
encode(): NapProtoEncodeStructType<{ fn: () => Promise<Array<string>> }>;
validate: ValidateFunction<Map<string, Array<number>>>;
unrelated: Promise<Array<string>>;
}
export declare enum ExampleKind { First = 1 }
`);
execFileSync(process.execPath, [script], { encoding: 'utf8' });
const output = readFileSync(path.join(fixture, 'dist/fixture.ts'), 'utf8');
const parsed = ts.transpileModule(output, { reportDiagnostics: true, compilerOptions: { target: ts.ScriptTarget.Latest } });
expect(parsed.diagnostics).toHaveLength(0);
expect(output).toContain('parse(): any;');
expect(output).toContain('encode(): any;');
expect(output).toContain('validate: any;');
expect(output).toContain('unrelated: Promise<Array<string>>;');
expect(output).toContain('export enum ExampleKind');
expect(output).not.toContain("import('napcat-protobuf').any");
});
+3 -2
View File
@@ -19,6 +19,7 @@
"devDependencies": {
"napcat-core": "workspace:*",
"napcat-onebot": "workspace:*",
"tsc-alias": "^1.8.16"
"tsc-alias": "^1.8.16",
"typescript": "^5.3.0"
}
}
}
+21 -3
View File
@@ -1,6 +1,7 @@
import { readdir, readFile, writeFile, rename } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
const __dirname = fileURLToPath(new URL('../', import.meta.url));
const distDir = join(__dirname, 'dist');
@@ -41,9 +42,21 @@ function replaceExternalTypes (content) {
let result = content;
// 替换带泛型的类型(先处理复杂的)
result = result.replace(/NapProtoDecodeStructType<[^>]+>/g, 'any');
result = result.replace(/NapProtoEncodeStructType<[^>]+>/g, 'any');
result = result.replace(/ValidateFunction<[^>]+>/g, 'any');
const sourceFile = ts.createSourceFile('declaration.d.ts', result, ts.ScriptTarget.Latest, true);
const genericTypeNames = new Set(['NapProtoDecodeStructType', 'NapProtoEncodeStructType', 'ValidateFunction']);
const replacements = [];
const visit = (node) => {
const typeName = ts.isTypeReferenceNode(node) ? node.typeName : ts.isImportTypeNode(node) ? node.qualifier : undefined;
if (typeName && genericTypeNames.has(typeName.getText(sourceFile).split('.').at(-1))) {
replacements.push({ start: node.getStart(sourceFile), end: node.getEnd() });
return;
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
for (const replacement of replacements.reverse()) {
result = result.slice(0, replacement.start) + 'any' + result.slice(replacement.end);
}
// 替换 winston.Logger 等带命名空间的类型
result = result.replace(/winston\.Logger/g, 'any');
@@ -103,6 +116,11 @@ async function processFile (filePath) {
// 3. Replace "export declare enum" with "export enum"
content = content.replace(/export declare enum/g, 'export enum');
const parsed = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
if (parsed.parseDiagnostics.length > 0) {
throw new Error(`Invalid generated declaration ${filePath}: ${parsed.parseDiagnostics.map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')).join('\n')}`);
}
// Write back the modified content
await writeFile(filePath, content, 'utf-8');
+9 -1
View File
@@ -12,6 +12,12 @@
"napcat-core": [
"../../packages/napcat-core/index.ts"
],
"napcat-core/*": [
"../../packages/napcat-core/*"
],
"napcat-webui-backend/*": [
"../../packages/napcat-webui-backend/*"
],
"napcat-onebot": [
"../../packages/napcat-onebot/index.ts"
],
@@ -40,6 +46,8 @@
},
"include": [
"./index.ts",
"../napcat-pty/node-pty.d.ts",
"../napcat-pty/native.d.ts",
"../napcat-core/**/*.ts",
"../napcat-onebot/**/*.ts",
"../napcat-common/**/*.ts"
@@ -48,4 +56,4 @@
"node_modules",
"dist"
]
}
}