diff --git a/packages/napcat-test/typePostBuild.test.ts b/packages/napcat-test/typePostBuild.test.ts new file mode 100644 index 000000000..dbf02511e --- /dev/null +++ b/packages/napcat-test/typePostBuild.test.ts @@ -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> }>; + encode(): NapProtoEncodeStructType<{ fn: () => Promise> }>; + validate: ValidateFunction>>; + unrelated: Promise>; +} +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>;'); + expect(output).toContain('export enum ExampleKind'); + expect(output).not.toContain("import('napcat-protobuf').any"); +}); diff --git a/packages/napcat-types/package.json b/packages/napcat-types/package.json index 5e6cf2975..0be9ee4ab 100644 --- a/packages/napcat-types/package.json +++ b/packages/napcat-types/package.json @@ -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" } -} \ No newline at end of file +} diff --git a/packages/napcat-types/scripts/post-build.mjs b/packages/napcat-types/scripts/post-build.mjs index 52af6f3be..0d901b0c8 100644 --- a/packages/napcat-types/scripts/post-build.mjs +++ b/packages/napcat-types/scripts/post-build.mjs @@ -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'); diff --git a/packages/napcat-types/tsconfig.json b/packages/napcat-types/tsconfig.json index aea42d9fe..c32a88cfd 100644 --- a/packages/napcat-types/tsconfig.json +++ b/packages/napcat-types/tsconfig.json @@ -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" ] -} \ No newline at end of file +}