Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

commonjs-declarations.mjs

50 lines1.6 KB

1import ts from 'typescript'
2​
3// @tanstack/vite-config adds extensions to extensionless declaration imports,
4// but leaves explicit .js specifiers unchanged in its .d.cts output. Use its
5// pre-write hook to fix only module specifiers; string-literal types and
6// package imports must keep their meaning. The hook runs before .d.ts renaming.
7/**
8 * @param {string} filePath
9 * @param {string} content
10 * @returns {string}
11 */
12export function commonJsDeclarations(filePath, content) {
13 if (!/[/\\]dist[/\\]cjs[/\\]/.test(filePath)) return content
14​
15 const source = ts.createSourceFile(
16 filePath,
17 content,
18 ts.ScriptTarget.Latest,
19 true,
20 )
21 const result = ts.transform(source, [
22 (context) => {
23 /** @type {ts.Visitor} */
24 const visit = (node) => {
25 if (
26 ts.isStringLiteral(node) &&
27 /^\.\.?\/.+\.js$/.test(node.text) &&
28 (ts.isImportDeclaration(node.parent) ||
29 ts.isExportDeclaration(node.parent) ||
30 ts.isExternalModuleReference(node.parent) ||
31 ts.isModuleDeclaration(node.parent) ||
32 (ts.isLiteralTypeNode(node.parent) &&
33 ts.isImportTypeNode(node.parent.parent) &&
34 node.parent.parent.argument === node.parent))
35 ) {
36 return ts.factory.createStringLiteral(`${node.text.slice(0, -3)}.cjs`)
37 }
38 return ts.visitEachChild(node, visit, context)
39 }
40 return (file) => ts.visitEachChild(file, visit, context)
41 },
42 ])
43 try {
44 return ts
45 .createPrinter()
46 .printFile(/** @type {ts.SourceFile} */ (result.transformed[0]))
47 } finally {
48 result.dispose()
49 }