Gathering detailed insights and metrics for mlly
Gathering detailed insights and metrics for mlly
Gathering detailed insights and metrics for mlly
Gathering detailed insights and metrics for mlly
npm install mlly
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
473 Stars
420 Commits
35 Forks
7 Watching
5 Branches
42 Contributors
Updated on 27 Nov 2024
TypeScript (97.16%)
JavaScript (2.84%)
Cumulative downloads
Total Downloads
Last day
-0.9%
1,336,378
Compared to previous day
Last week
3.3%
6,919,193
Compared to previous week
Last month
10.3%
28,767,539
Compared to previous month
Last year
190.3%
277,152,053
Compared to previous year
Missing ECMAScript module utils for Node.js
While ESM Modules are evolving in Node.js ecosystem, there are still many required features that are still experimental or missing or needed to support ESM. This package tries to fill in the gap.
Install npm package:
1# using yarn 2yarn add mlly 3 4# using npm 5npm install mlly
Note: Node.js 14+ is recommended.
Import utils:
1// ESM 2import {} from "mlly"; 3 4// CommonJS 5const {} = require("mlly");
Several utilities to make ESM resolution easier:
extensions
and /index
resolutionconditions
resolve
/ resolveSync
Resolve a module by respecting ECMAScript Resolver algorithm (using wooorm/import-meta-resolve).
Additionally supports resolving without extension and /index
similar to CommonJS.
1import { resolve, resolveSync } from "mlly"; 2 3// file:///home/user/project/module.mjs 4console.log(await resolve("./module.mjs", { url: import.meta.url }));
Resolve options:
url
: URL or string to resolve from (default is pwd()
)conditions
: Array of conditions used for resolution algorithm (default is ['node', 'import']
)extensions
: Array of additional extensions to check if import failed (default is ['.mjs', '.cjs', '.js', '.json']
)resolvePath
/ resolvePathSync
Similar to resolve
but returns a path instead of URL using fileURLToPath
.
1import { resolvePath, resolveSync } from "mlly"; 2 3// /home/user/project/module.mjs 4console.log(await resolvePath("./module.mjs", { url: import.meta.url }));
createResolve
Create a resolve
function with defaults.
1import { createResolve } from "mlly"; 2 3const _resolve = createResolve({ url: import.meta.url }); 4 5// file:///home/user/project/module.mjs 6console.log(await _resolve("./module.mjs"));
Example: Ponyfill import.meta.resolve:
1import { createResolve } from "mlly";
2
3import.meta.resolve = createResolve({ url: import.meta.url });
resolveImports
Resolve all static and dynamic imports with relative paths to full resolved path.
1import { resolveImports } from "mlly"; 2 3// import foo from 'file:///home/user/project/bar.mjs' 4console.log( 5 await resolveImports(`import foo from './bar.mjs'`, { url: import.meta.url }), 6);
isValidNodeImport
Using various syntax detection and heuristics, this method can determine if import is a valid import or not to be imported using dynamic import()
before hitting an error!
When result is false
, we usually need a to create a CommonJS require context or add specific rules to the bundler to transform dependency.
1import { isValidNodeImport } from "mlly"; 2 3// If returns true, we are safe to use `import('some-lib')` 4await isValidNodeImport("some-lib", {});
Algorithm:
data:
return true
(✅ valid) - If is not node:
, file:
or data:
, return false
(
❌ invalid).mjs
, .cjs
, .node
or .wasm
, return true
(✅ valid).js
, return false
(❌ invalid).esm.js
, .es.js
, etc) return false
(
❌ invalid)package.json
file to resolve pathtype: 'module'
field is set, return true
(✅ valid)true
(✅ valid)false
(
❌ invalid)Notes:
hasESMSyntax
Detect if code, has usage of ESM syntax (Static import
, ESM export
and import.meta
usage)
1import { hasESMSyntax } from "mlly"; 2 3hasESMSyntax("export default foo = 123"); // true
hasCJSSyntax
Detect if code, has usage of CommonJS syntax (exports
, module.exports
, require
and global
usage)
1import { hasCJSSyntax } from "mlly"; 2 3hasCJSSyntax("export default foo = 123"); // false
detectSyntax
Tests code against both CJS and ESM.
isMixed
indicates if both are detected! This is a common case with legacy packages exporting semi-compatible ESM syntax meant to be used by bundlers.
1import { detectSyntax } from "mlly"; 2 3// { hasESM: true, hasCJS: true, isMixed: true } 4detectSyntax('export default require("lodash")');
createCommonJS
This utility creates a compatible CommonJS context that is missing in ECMAScript modules.
1import { createCommonJS } from "mlly"; 2 3const { __dirname, __filename, require } = createCommonJS(import.meta.url);
Note: require
and require.resolve
implementation are lazy functions. createRequire
will be called on first usage.
Tools to quickly analyze ESM syntax and extract static import
/export
findStaticImports
Find all static ESM imports.
Example:
1import { findStaticImports } from "mlly"; 2 3console.log( 4 findStaticImports(` 5// Empty line 6import foo, { bar /* foo */ } from 'baz' 7`), 8);
Outputs:
1[ 2 { 3 type: "static", 4 imports: "foo, { bar /* foo */ } ", 5 specifier: "baz", 6 code: "import foo, { bar /* foo */ } from 'baz'", 7 start: 15, 8 end: 55, 9 }, 10];
parseStaticImport
Parse a dynamic ESM import statement previously matched by findStaticImports
.
Example:
1import { findStaticImports, parseStaticImport } from "mlly";
2
3const [match0] = findStaticImports(`import baz, { x, y as z } from 'baz'`);
4console.log(parseStaticImport(match0));
Outputs:
1{ 2 type: 'static', 3 imports: 'baz, { x, y as z } ', 4 specifier: 'baz', 5 code: "import baz, { x, y as z } from 'baz'", 6 start: 0, 7 end: 36, 8 defaultImport: 'baz', 9 namespacedImport: undefined, 10 namedImports: { x: 'x', y: 'z' } 11}
findDynamicImports
Find all dynamic ESM imports.
Example:
1import { findDynamicImports } from "mlly"; 2 3console.log( 4 findDynamicImports(` 5const foo = await import('bar') 6`), 7);
findExports
1import { findExports } from "mlly";
2
3console.log(
4 findExports(`
5export const foo = 'bar'
6export { bar, baz }
7export default something
8`),
9);
Outputs:
1[ 2 { 3 type: "declaration", 4 declaration: "const", 5 name: "foo", 6 code: "export const foo", 7 start: 1, 8 end: 17, 9 }, 10 { 11 type: "named", 12 exports: " bar, baz ", 13 code: "export { bar, baz }", 14 start: 26, 15 end: 45, 16 names: ["bar", "baz"], 17 }, 18 { type: "default", code: "export default ", start: 46, end: 61 }, 19];
findExportNames
Same as findExports
but returns array of export names.
1import { findExportNames } from "mlly"; 2 3// [ "foo", "bar", "baz", "default" ] 4console.log( 5 findExportNames(` 6export const foo = 'bar' 7export { bar, baz } 8export default something 9`), 10);
resolveModuleExportNames
Resolves module and reads its contents to extract possible export names using static analyzes.
1import { resolveModuleExportNames } from "mlly"; 2 3// ["basename", "dirname", ... ] 4console.log(await resolveModuleExportNames("mlly"));
Set of utilities to evaluate ESM modules using data:
imports
.json
loaderevalModule
Transform and evaluates module code using dynamic imports.
1import { evalModule } from "mlly";
2
3await evalModule(`console.log("Hello World!")`);
4
5await evalModule(
6 `
7 import { reverse } from './utils.mjs'
8 console.log(reverse('!emosewa si sj'))
9`,
10 { url: import.meta.url },
11);
Options:
resolve
optionsurl
: File URLloadModule
Dynamically loads a module by evaluating source code.
1import { loadModule } from "mlly";
2
3await loadModule("./hello.mjs", { url: import.meta.url });
Options are same as evalModule
.
transformModule
import.meta.url
will be replaced with url
or from
option1import { transformModule } from "mlly";
2console.log(transformModule(`console.log(import.meta.url)`), {
3 url: "test.mjs",
4});
Options are same as evalModule
.
fileURLToPath
Similar to url.fileURLToPath but also converts windows backslash \
to unix slash /
and handles if input is already a path.
1import { fileURLToPath } from "mlly"; 2 3// /foo/bar.js 4console.log(fileURLToPath("file:///foo/bar.js")); 5 6// C:/path 7console.log(fileURLToPath("file:///C:/path/"));
pathToFileURL
Similar to url.pathToFileURL but also handles URL
input and returns a string with file://
protocol.
1import { pathToFileURL } from "mlly"; 2 3// /foo/bar.js 4console.log(pathToFileURL("foo/bar.js")); 5 6// C:/path 7console.log(pathToFileURL("C:\\path"));
normalizeid
Ensures id has either of node:
, data:
, http:
, https:
or file:
protocols.
1import { ensureProtocol } from "mlly"; 2 3// file:///foo/bar.js 4console.log(normalizeid("/foo/bar.js"));
loadURL
Read source contents of a URL. (currently only file protocol supported)
1import { resolve, loadURL } from "mlly"; 2 3const url = await resolve("./index.mjs", { url: import.meta.url }); 4console.log(await loadURL(url));
toDataURL
Convert code to data:
URL using base64 encoding.
1import { toDataURL } from "mlly";
2
3console.log(
4 toDataURL(`
5 // This is an example
6 console.log('Hello world')
7`),
8);
interopDefault
Return the default export of a module at the top-level, alongside any other named exports.
1// Assuming the shape { default: { foo: 'bar' }, baz: 'qux' } 2import myModule from "my-module"; 3 4// Returns { foo: 'bar', baz: 'qux' } 5console.log(interopDefault(myModule));
Options:
preferNamespace
: In case that default
value exists but is not extendable (when is string for example), return input as-is (default is false
, meaning default
's value is prefered even if cannot be extended)sanitizeURIComponent
Replace reserved characters from a segment of URI to make it compatible with rfc2396.
1import { sanitizeURIComponent } from "mlly"; 2 3// foo_bar 4console.log(sanitizeURIComponent(`foo:bar`));
sanitizeFilePath
Sanitize each path of a file name or path with sanitizeURIComponent
for URI compatibility.
1import { sanitizeFilePath } from "mlly"; 2 3// C:/te_st/_...slug_.jsx' 4console.log(sanitizeFilePath("C:\\te#st\\[...slug].jsx"));
parseNodeModulePath
Parses an absolute file path in node_modules
to three segments:
dir
: Path to main directory of packagename
: Package namesubpath
: The optional package subpathIt returns an empty object (with partial keys) if parsing fails.
1import { parseNodeModulePath } from "mlly"; 2 3// dir: "/src/a/node_modules/" 4// name: "lib" 5// subpath: "./dist/index.mjs" 6const { dir, name, subpath } = parseNodeModulePath( 7 "/src/a/node_modules/lib/dist/index.mjs", 8);
lookupNodeModuleSubpath
Parses an absolute file path in node_modules
and tries to reverse lookup (or guess) the original package exports subpath for it.
1import { lookupNodeModuleSubpath } from "mlly"; 2 3// subpath: "./utils" 4const subpath = lookupNodeModuleSubpath( 5 "/src/a/node_modules/lib/dist/utils.mjs", 6);
MIT - Made with 💛
No vulnerabilities found.
Reason
15 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
1 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 5
Details
Reason
Found 2/30 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More@flex-development/mlly
ECMAScript module utilities
unkit
UnJS standard library
detect-imports
> [!NOTE] > This is a slimmed down version of [unjs/mlly](https://github.com/unjs/mlly/), only detecting static and type imports and without other utilities (enabling this package to be bundled for the browser). All credit goes to the amazing UnJS team!