@sanity/pkg-utils
Version:
Simple utilities for modern npm packages.
49 lines (48 loc) • 2 kB
JavaScript
import ts from "@typescript/typescript6";
function extractModuleBlocksFromTypes({
tsOutDir,
extractResult
}) {
const program = extractResult.compilerState.program, moduleBlocks = [], sourceFiles = [...program.getSourceFiles()].filter((sourceFile) => sourceFile.fileName.includes(tsOutDir));
for (const sourceFile of sourceFiles)
if (sourceFile.text.includes("declare module")) {
const parsedFile = ts.createSourceFile(
sourceFile.fileName,
sourceFile.text,
ts.ScriptTarget.Latest,
/* setParentNodes */
!0
);
moduleBlocks.push(...extractModuleBlocks(parsedFile));
}
return moduleBlocks;
}
function extractModuleBlocks(sourceFile) {
const text = sourceFile.text, moduleBlocks = [], statements = sourceFile.statements;
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (statement && ts.isModuleDeclaration(statement)) {
const fullStart = statement.getFullStart(), start = statement.getStart(sourceFile);
let end = statement.getEnd();
const lastTrailing = ts.getTrailingCommentRanges(text, end)?.at(-1);
if (lastTrailing)
end = lastTrailing.end;
else {
const nextStatementStart = statements[i + 1]?.getFullStart() ?? text.length, lastCommentAfter = ts.getLeadingCommentRanges(text, end)?.at(-1);
lastCommentAfter && lastCommentAfter.end <= nextStatementStart && (end = lastCommentAfter.end);
}
const leadingComments = ts.getLeadingCommentRanges(text, fullStart);
let blockStart = start;
if (leadingComments && leadingComments.length > 0) {
const lastComment = leadingComments.at(-1);
lastComment && text.slice(lastComment.pos, lastComment.end).startsWith("/**") && (blockStart = lastComment.pos);
}
moduleBlocks.push(text.slice(blockStart, end));
}
}
return moduleBlocks;
}
export {
extractModuleBlocksFromTypes
};
//# sourceMappingURL=extractModuleBlocks.js.map