Skip to content

Commit

Permalink
simplify type acquisition
Browse files Browse the repository at this point in the history
  • Loading branch information
souporserious committed Nov 23, 2023
1 parent 10e0c24 commit 3797e06
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 57 deletions.
65 changes: 25 additions & 40 deletions mdxts/src/utils/get-type-declarations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import { rollup } from 'rollup'
import dts from 'rollup-plugin-dts'
import ts from 'typescript'

/* TODO: this is inefficient, the ata utility should only be instantiated once. */
async function fetchTypes(
name: string[]
name: string
): Promise<{ code: string; path: string }[]> {
const { setupTypeAcquisition } = await import('@typescript/ata')
let types: { code: string; path: string }[] = []
Expand All @@ -17,33 +16,20 @@ async function fetchTypes(
projectName: 'mdxts',
typescript: ts,
logger: console,
fetcher: async (input) => {
const { default: fetch } = await import('node-fetch')
return fetch(input as any) as any
},
delegate: {
receivedFile: (code: string, path: string) => {
types = [...types, { code, path }]
types.push({ code, path: path.replace('@types/', '') })
},
errorMessage(userFacingMessage, error) {
throw new Error(userFacingMessage, { cause: error })
},
finished: () => {
resolve(
types.map(({ code, path }) => ({
code,
path: path.replace('@types/', ''),
}))
)
resolve(types)
},
},
})

/*
* ATA expects a list of imports from a source file to fetch types for,
* so we simply provide a list of imports for each package.
*/
ata(name.map((name) => `import ${name} from "${name}"`).join('\n'))
ata(`import "${name}"`)
})
}

Expand Down Expand Up @@ -143,22 +129,16 @@ async function findTypesPath(
}
}

try {
const parentNodeModulesPath = await findParentNodeModulesPath(
process.cwd(),
`@types/${packageName}`
)

if (!parentNodeModulesPath) {
throw new Error(`mdxts: Could not find types path for "${packageName}"`)
}
const parentNodeModulesPath = await findParentNodeModulesPath(
process.cwd(),
`@types/${packageName}`
)

return path.resolve(parentNodeModulesPath, 'index.d.ts')
} catch (error) {
throw new Error(`mdxts: Could not find types path for "${packageName}"`, {
cause: error,
})
if (!parentNodeModulesPath) {
return null
}

return path.resolve(parentNodeModulesPath, 'index.d.ts')
}

/** Parses the root package name from a nested package name. */
Expand All @@ -182,15 +162,20 @@ export async function getTypeDeclarations(packageName: string) {
'package.json'
)
const packageJson = await getPackageJson(packageJsonPath)
const allDependencies = getAllDependencies(packageJson)
const typesPath = await findTypesPath(packageJson, packageName)

// use ATA when dealing with @types since rollup is not reliable
if (typesPath.includes('@types/')) {
const packageTypes = await fetchTypes([packageName])
// Use ATA when failing to find path or dealing with @types since rollup is not reliable
if (
typesPath === null ||
typesPath.includes('@types/') ||
packageName.includes('@types/')
) {
const packageTypes = await fetchTypes(packageName)
return packageTypes
}

const allDependencies = getAllDependencies(packageJson)

try {
const bundle = await rollup({
input: path.resolve('./node_modules/', packageName, typesPath),
Expand All @@ -211,9 +196,9 @@ export async function getTypeDeclarations(packageName: string) {
path: `/node_modules/${packageName}/index.d.ts`,
},
]
} catch (error) {
throw new Error(`mdxts: Could not bundle "${packageName}"`, {
cause: error,
})
} catch {
// Fallback to ATA if Rollup fails for any reason
const packageTypes = await fetchTypes(packageName)
return packageTypes
}
}
14 changes: 0 additions & 14 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion site/docs/01.getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const allDocs = loadModules(

Use the [[get]] helper from the modules loader to render MDX content:

```tsx filename="app/[...slug]/page.tsx"
```tsx filename="page.tsx"
import { notFound } from 'next/navigation'
import { allDocs } from './data'

Expand Down
2 changes: 0 additions & 2 deletions site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
"@types/mdx": "^2.0.10",
"@types/react": "^18.2.38",
"@types/react-dom": "^18.2.17",
"@types/prop-types": "^15.7.11",
"@types/scheduler": "^0.16.8",
"@types/webpack-env": "1.18.4",
"case-anything": "^2.1.13",
"esbuild": "^0.19.6",
Expand Down

1 comment on commit 3797e06

@vercel
Copy link

@vercel vercel bot commented on 3797e06 Nov 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.