-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(utils): add resolve utilities to handle cross esm/cjs dynamic im…
…ports. Signed-off-by: Braden Mars <bradenmars@bradenmars.me>
- Loading branch information
Showing
4 changed files
with
45 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
export * from './get-temp-dir' | ||
export * from './create-file-checksum' | ||
export * from './download-git-dir' | ||
export * from './resolve' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import process from 'node:process' | ||
import jiti from 'jiti' | ||
import consola from 'consola' | ||
|
||
const createJiti = (rootDir: string = process.cwd()) => | ||
jiti(rootDir, {interopDefault: true, esmResolve: true}) | ||
|
||
export const requireFrom = <T>(id: string, rootDir?: string) => | ||
createJiti(rootDir)(id) as T | ||
export const resolveFrom = (id: string, rootDir?: string) => | ||
createJiti(rootDir).resolve(id) | ||
|
||
const tryCatchModule = <T extends (...args: any[]) => any>( | ||
func: T, | ||
fallback: T extends (...args: infer ArgT) => ReturnType<T> | ||
? (...args: ArgT) => ReturnType<T> | ||
: never, | ||
): (<RT>(...args: Parameters<T>) => RT) => { | ||
return (...args: Parameters<T>) => { | ||
try { | ||
return func(...args) as ReturnType<T> | ||
} catch (error: unknown) { | ||
if ( | ||
'code' in (error as {code: string}) && | ||
(error as {code: string}).code !== 'MODULE_NOT_FOUND' | ||
) { | ||
consola.error(`Failed to import:`, args, error) | ||
} | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | ||
return fallback(...args) | ||
} | ||
} | ||
} | ||
|
||
export const maybeRequireFrom = tryCatchModule(requireFrom, () => ({})) | ||
export const maybeResolveFrom = tryCatchModule(resolveFrom, (id: string) => id) |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.