|
| 1 | +import { readFile } from "node:fs/promises"; |
| 2 | +import { pathToFileURL } from "node:url"; |
| 3 | + |
| 4 | +const SELECTED_METHODS = ["source", "name"]; |
| 5 | +const ROOT_URL = new URL("../../", import.meta.url); |
| 6 | +const GENERATED_DECLARATION_URL = new URL("target/napi-sourcemap.d.ts", ROOT_URL); |
| 7 | +const PUBLIC_DECLARATION_URL = new URL("packages/sourcemap/index.d.ts", ROOT_URL); |
| 8 | + |
| 9 | +const extractReturnType = (declaration, method) => { |
| 10 | + const signature = new RegExp( |
| 11 | + `^\\s*${method}\\s*\\(\\s*index\\s*:\\s*number\\s*\\)\\s*:\\s*([^;\\n]+)\\s*;?`, |
| 12 | + "m", |
| 13 | + ).exec(declaration); |
| 14 | + |
| 15 | + return signature?.[1].trim().replaceAll(/\s+/g, " ") ?? null; |
| 16 | +}; |
| 17 | + |
| 18 | +/** Compare selected generated and public NAPI method return types. */ |
| 19 | +export const findDeclarationMismatches = (generatedDeclaration, publicDeclaration) => { |
| 20 | + const mismatches = []; |
| 21 | + |
| 22 | + for (const method of SELECTED_METHODS) { |
| 23 | + const generatedReturnType = extractReturnType(generatedDeclaration, method); |
| 24 | + const publicReturnType = extractReturnType(publicDeclaration, method); |
| 25 | + |
| 26 | + if (generatedReturnType === publicReturnType && generatedReturnType !== null) { |
| 27 | + continue; |
| 28 | + } |
| 29 | + |
| 30 | + mismatches.push( |
| 31 | + `${method}: generated returns ${generatedReturnType ?? "no declaration"}, public declaration returns ${publicReturnType ?? "no declaration"}`, |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + return mismatches; |
| 36 | +}; |
| 37 | + |
| 38 | +const main = async () => { |
| 39 | + const [generatedDeclaration, publicDeclaration] = await Promise.all([ |
| 40 | + readFile(GENERATED_DECLARATION_URL, "utf8"), |
| 41 | + readFile(PUBLIC_DECLARATION_URL, "utf8"), |
| 42 | + ]); |
| 43 | + const mismatches = findDeclarationMismatches(generatedDeclaration, publicDeclaration); |
| 44 | + |
| 45 | + if (mismatches.length === 0) { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + throw new Error(`NAPI declaration drift detected:\n${mismatches.join("\n")}`); |
| 50 | +}; |
| 51 | + |
| 52 | +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { |
| 53 | + await main(); |
| 54 | +} |
0 commit comments