Skip to content

Commit

Permalink
bugfix: replaces import assertion with createRequire construct (#12)
Browse files Browse the repository at this point in the history
because node 19 json prints a scary message when you use a json import assertion
  • Loading branch information
sverweij committed Apr 2, 2023
1 parent a7fc0a5 commit 8068ced
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions src/try-import.mts
@@ -1,13 +1,14 @@
import path from "path/posix";
import { createRequire } from "module";
import { coerce, satisfies } from "semver";
// import extractRootModuleName from "./extract-root-module-name.js";

const LOCAL_MODULE_RE = /^[.]{1,2}($|\/.*)/g;
const ABSOLUTE_MODULE_RE = /^\/.*/g;

const PACKAGE_RE = "[^/]+";
const SCOPED_PACKAGE_RE = "@[^/]+(/[^/]+)";
const ROOT_MODULE_RE = new RegExp(`^(${SCOPED_PACKAGE_RE}|${PACKAGE_RE})`, "g");
const require = createRequire(import.meta.url);

/**
* returns the module name that likely contains the package.json
Expand All @@ -25,15 +26,28 @@ function extractRootModuleName(pModuleName: string): string | undefined {
}
}

async function getVersion(pModuleName: string): Promise<string> {
const lManifest = await import(
function getVersion(pModuleName: string): string {
// // The 'proper' way to do this would be with a dynamic import with an
// // import assertion. Because it's 'experimental' since node 16 and prints
// // an ugly warning on stderr since node 19 we'll be using the require
// // hack below in stead.
// const lManifest = await import(
// // @ts-expect-error TS2345 extractRootModuleName can return either a string or
// // undefined. If undefined this function will throw. Which is _fine_, even
// // _expected_ in the context it's currently used
// path.join(extractRootModuleName(pModuleName), "package.json"),
// { assert: { type: "json" } }
// );
// // changes the return type to Promise<string>
// return lManifest.default.version;
const lManifest = require(path.join(
// @ts-expect-error TS2345 extractRootModuleName can return either a string or
// undefined. If undefined this function will throw. Which is _fine_, even
// _expected_ in the context it's currently used
path.join(extractRootModuleName(pModuleName), "package.json"),
{ assert: { type: "json" } }
);
return lManifest.default.version;
extractRootModuleName(pModuleName),
"package.json"
));
return lManifest.version;
}

export default async function tryImport(
Expand All @@ -47,7 +61,7 @@ export default async function tryImport(
lReturnValue = lModule.default;

if (pSemanticVersion) {
const lVersion = await getVersion(pModuleName);
const lVersion = getVersion(pModuleName);
const lCoerced = coerce(lVersion);
if (
lVersion &&
Expand Down

0 comments on commit 8068ced

Please sign in to comment.