{"name":"mlly","version":"1.8.1","license":"MIT","_id":"mlly@1.8.1","maintainers":[{"name":"pi0","email":"pyapar@gmail.com"}],"homepage":"https://github.com/unjs/mlly#readme","bugs":{"url":"https://github.com/unjs/mlly/issues"},"dist":{"shasum":"2ed89f4fbbbde26db9fcc86df5bfa3153cfacea1","tarball":"http://registry-npm.ywwl.com/mlly/download/mlly-1.8.1.tgz","fileCount":8,"integrity":"sha512-SnL6sNutTwRWWR/vcmCYHSADjiEesp5TGQQ0pXyLhW5IoeibRlF/CbSLailbB3CNqJUk9cVJ9dUDnbD7GrcHBQ==","signatures":[{"sig":"MEUCIDwlQQddvM7DA5Np2RvcYLQ46EbsI4QBmp2o1/2c1tQFAiEAxZLMSpXvg5oFylLQ63ZWu6XsGBAic4jYHuD2SjRDpUA=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":237167,"size":52428,"noattachment":false,"key":"/mlly/-/mlly-1.8.1.tgz"},"main":"./dist/index.cjs","pnpm":{"onlyBuiltDependencies":["esbuild"]},"type":"module","types":"./dist/index.d.ts","module":"./dist/index.mjs","exports":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.cjs"},"gitHead":"d80d4691900e5e3af85d52a1c62dc5db8647230b","scripts":{"dev":"vitest","lint":"eslint src test && prettier -c src test","test":"pnpm lint && pnpm test:types && vitest run","build":"unbuild","release":"pnpm test && pnpm build && changelogen --release && npm publish && git push --follow-tags","lint:fix":"eslint src test --fix && prettier -w src test","test:types":"tsc --noEmit"},"_npmUser":{"name":"pi0","email":"pyapar@gmail.com"},"repository":{"url":"git+https://github.com/unjs/mlly.git","type":"git"},"_npmVersion":"11.6.2","description":"Missing ECMAScript module utils for Node.js","directories":{},"sideEffects":false,"_nodeVersion":"24.13.0","dependencies":{"ufo":"^1.6.3","acorn":"^8.16.0","pathe":"^2.0.3","pkg-types":"^1.3.1"},"_hasShrinkwrap":false,"packageManager":"pnpm@10.20.0","devDependencies":{"jiti":"^2.6.1","eslint":"^10.0.2","vitest":"^4.0.18","std-env":"^3.10.0","unbuild":"^3.6.1","prettier":"^3.8.1","typescript":"^5.9.3","@types/node":"^25.3.3","changelogen":"^0.6.2","eslint-config-unjs":"^0.6.2","@vitest/coverage-v8":"^4.0.18","import-meta-resolve":"^4.2.0"},"_npmOperationalInternal":{"tmp":"tmp/mlly_1.8.1_1772659752509_0.16812774100439287","host":"s3://npm-registry-packages-npm-production"},"readme":"# mlly\n\n[![npm version][npm-version-src]][npm-version-href]\n[![npm downloads][npm-downloads-src]][npm-downloads-href]\n[![Codecov][codecov-src]][codecov-href]\n\n> Missing [ECMAScript module](https://nodejs.org/api/esm.html) utils for Node.js\n\nWhile ESM Modules are evolving in Node.js ecosystem, there are still\nmany required features that are still experimental or missing or needed to support ESM. This package tries to fill in the gap.\n\n## Usage\n\nInstall npm package:\n\n```sh\n# using yarn\nyarn add mlly\n\n# using npm\nnpm install mlly\n```\n\n**Note:** Node.js 14+ is recommended.\n\nImport utils:\n\n```js\n// ESM\nimport {} from \"mlly\";\n\n// CommonJS\nconst {} = require(\"mlly\");\n```\n\n## Resolving ESM modules\n\nSeveral utilities to make ESM resolution easier:\n\n- Respecting [ECMAScript Resolver algorithm](https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_resolver_algorithm)\n- Exposed from Node.js implementation\n- Windows paths normalized\n- Supporting custom `extensions` and `/index` resolution\n- Supporting custom `conditions`\n- Support resolving from multiple paths or urls\n\n### `resolve` / `resolveSync`\n\nResolve a module by respecting [ECMAScript Resolver algorithm](https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_resolver_algorithm)\n(using [wooorm/import-meta-resolve](https://github.com/wooorm/import-meta-resolve)).\n\nAdditionally supports resolving without extension and `/index` similar to CommonJS.\n\n```js\nimport { resolve, resolveSync } from \"mlly\";\n\n// file:///home/user/project/module.mjs\nconsole.log(await resolve(\"./module.mjs\", { url: import.meta.url }));\n```\n\n**Resolve options:**\n\n- `url`: URL or string to resolve from (default is `pwd()`)\n- `conditions`: Array of conditions used for resolution algorithm (default is `['node', 'import']`)\n- `extensions`: Array of additional extensions to check if import failed (default is `['.mjs', '.cjs', '.js', '.json']`)\n\n### `resolvePath` / `resolvePathSync`\n\nSimilar to `resolve` but returns a path instead of URL using `fileURLToPath`.\n\n```js\nimport { resolvePath, resolveSync } from \"mlly\";\n\n// /home/user/project/module.mjs\nconsole.log(await resolvePath(\"./module.mjs\", { url: import.meta.url }));\n```\n\n### `createResolve`\n\nCreate a `resolve` function with defaults.\n\n```js\nimport { createResolve } from \"mlly\";\n\nconst _resolve = createResolve({ url: import.meta.url });\n\n// file:///home/user/project/module.mjs\nconsole.log(await _resolve(\"./module.mjs\"));\n```\n\n**Example:** Ponyfill [import.meta.resolve](https://nodejs.org/api/esm.html#esm_import_meta_resolve_specifier_parent):\n\n```js\nimport { createResolve } from \"mlly\";\n\nimport.meta.resolve = createResolve({ url: import.meta.url });\n```\n\n### `resolveImports`\n\nResolve all static and dynamic imports with relative paths to full resolved path.\n\n```js\nimport { resolveImports } from \"mlly\";\n\n// import foo from 'file:///home/user/project/bar.mjs'\nconsole.log(\n  await resolveImports(`import foo from './bar.mjs'`, { url: import.meta.url }),\n);\n```\n\n## Syntax Analyzes\n\n### `isValidNodeImport`\n\nUsing 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!\n\nWhen result is `false`, we usually need a to create a CommonJS require context or add specific rules to the bundler to transform dependency.\n\n```js\nimport { isValidNodeImport } from \"mlly\";\n\n// If returns true, we are safe to use `import('some-lib')`\nawait isValidNodeImport(\"some-lib\", {});\n```\n\n**Algorithm:**\n\n- Check import protocol - If is `data:` return `true` (✅ valid) - If is not `node:`, `file:` or `data:`, return `false` (\n  ❌ invalid)\n- Resolve full path of import using Node.js [Resolution algorithm](https://nodejs.org/api/esm.html#resolution-algorithm)\n- Check full path extension\n  - If is `.mjs`, `.cjs`, `.node` or `.wasm`, return `true` (✅ valid)\n  - If is not `.js`, return `false` (❌ invalid)\n  - If is matching known mixed syntax (`.esm.js`, `.es.js`, etc) return `false` (\n    ❌ invalid)\n- Read closest `package.json` file to resolve path\n- If `type: 'module'` field is set, return `true` (✅ valid)\n- Read source code of resolved path\n- Try to detect CommonJS syntax usage\n  - If yes, return `true` (✅ valid)\n- Try to detect ESM syntax usage\n  - if yes, return `false` (\n    ❌ invalid)\n\n**Notes:**\n\n- There might be still edge cases algorithm cannot cover. It is designed with best-efforts.\n- This method also allows using dynamic import of CommonJS libraries considering\n  Node.js has [Interoperability with CommonJS](https://nodejs.org/api/esm.html#interoperability-with-commonjs).\n\n### `hasESMSyntax`\n\nDetect if code, has usage of ESM syntax (Static `import`, ESM `export` and `import.meta` usage)\n\n```js\nimport { hasESMSyntax } from \"mlly\";\n\nhasESMSyntax(\"export default foo = 123\"); // true\n```\n\n### `hasCJSSyntax`\n\nDetect if code, has usage of CommonJS syntax (`exports`, `module.exports`, `require` and `global` usage)\n\n```js\nimport { hasCJSSyntax } from \"mlly\";\n\nhasCJSSyntax(\"export default foo = 123\"); // false\n```\n\n### `detectSyntax`\n\nTests code against both CJS and ESM.\n\n`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.\n\n```js\nimport { detectSyntax } from \"mlly\";\n\n// { hasESM: true, hasCJS: true, isMixed: true }\ndetectSyntax('export default require(\"lodash\")');\n```\n\n## CommonJS Context\n\n### `createCommonJS`\n\nThis utility creates a compatible CommonJS context that is missing in ECMAScript modules.\n\n```js\nimport { createCommonJS } from \"mlly\";\n\nconst { __dirname, __filename, require } = createCommonJS(import.meta.url);\n```\n\nNote: `require` and `require.resolve` implementation are lazy functions. [`createRequire`](https://nodejs.org/api/module.html#module_module_createrequire_filename) will be called on first usage.\n\n## Import/Export Analyzes\n\nTools to quickly analyze ESM syntax and extract static `import`/`export`\n\n- Super fast Regex based implementation\n- Handle most edge cases\n- Find all static ESM imports\n- Find all dynamic ESM imports\n- Parse static import statement\n- Find all named, declared and default exports\n\n### `findStaticImports`\n\nFind all static ESM imports.\n\nExample:\n\n```js\nimport { findStaticImports } from \"mlly\";\n\nconsole.log(\n  findStaticImports(`\n// Empty line\nimport foo, { bar /* foo */ } from 'baz'\n`),\n);\n```\n\nOutputs:\n\n```js\n[\n  {\n    type: \"static\",\n    imports: \"foo, { bar /* foo */ } \",\n    specifier: \"baz\",\n    code: \"import foo, { bar /* foo */ } from 'baz'\",\n    start: 15,\n    end: 55,\n  },\n];\n```\n\n### `parseStaticImport`\n\nParse a dynamic ESM import statement previously matched by `findStaticImports`.\n\nExample:\n\n```js\nimport { findStaticImports, parseStaticImport } from \"mlly\";\n\nconst [match0] = findStaticImports(`import baz, { x, y as z } from 'baz'`);\nconsole.log(parseStaticImport(match0));\n```\n\nOutputs:\n\n```js\n{\n  type: 'static',\n  imports: 'baz, { x, y as z } ',\n  specifier: 'baz',\n  code: \"import baz, { x, y as z } from 'baz'\",\n  start: 0,\n  end: 36,\n  defaultImport: 'baz',\n  namespacedImport: undefined,\n  namedImports: { x: 'x', y: 'z' }\n}\n```\n\n### `findDynamicImports`\n\nFind all dynamic ESM imports.\n\nExample:\n\n```js\nimport { findDynamicImports } from \"mlly\";\n\nconsole.log(\n  findDynamicImports(`\nconst foo = await import('bar')\n`),\n);\n```\n\n### `findExports`\n\n```js\nimport { findExports } from \"mlly\";\n\nconsole.log(\n  findExports(`\nexport const foo = 'bar'\nexport { bar, baz }\nexport default something\n`),\n);\n```\n\nOutputs:\n\n```js\n[\n  {\n    type: \"declaration\",\n    declaration: \"const\",\n    name: \"foo\",\n    code: \"export const foo\",\n    start: 1,\n    end: 17,\n  },\n  {\n    type: \"named\",\n    exports: \" bar, baz \",\n    code: \"export { bar, baz }\",\n    start: 26,\n    end: 45,\n    names: [\"bar\", \"baz\"],\n  },\n  { type: \"default\", code: \"export default \", start: 46, end: 61 },\n];\n```\n\n### `findExportNames`\n\nSame as `findExports` but returns array of export names.\n\n```js\nimport { findExportNames } from \"mlly\";\n\n// [ \"foo\", \"bar\", \"baz\", \"default\" ]\nconsole.log(\n  findExportNames(`\nexport const foo = 'bar'\nexport { bar, baz }\nexport default something\n`),\n);\n```\n\n## `resolveModuleExportNames`\n\nResolves module and reads its contents to extract possible export names using static analyzes.\n\n```js\nimport { resolveModuleExportNames } from \"mlly\";\n\n// [\"basename\", \"dirname\", ... ]\nconsole.log(await resolveModuleExportNames(\"mlly\"));\n```\n\n## Evaluating Modules\n\nSet of utilities to evaluate ESM modules using `data:` imports\n\n- Automatic import rewrite to resolved path using static analyzes\n- Allow bypass ESM Cache\n- Stack-trace support\n- `.json` loader\n\n### `evalModule`\n\nTransform and evaluates module code using dynamic imports.\n\n```js\nimport { evalModule } from \"mlly\";\n\nawait evalModule(`console.log(\"Hello World!\")`);\n\nawait evalModule(\n  `\n  import { reverse } from './utils.mjs'\n  console.log(reverse('!emosewa si sj'))\n`,\n  { url: import.meta.url },\n);\n```\n\n**Options:**\n\n- all `resolve` options\n- `url`: File URL\n\n### `loadModule`\n\nDynamically loads a module by evaluating source code.\n\n```js\nimport { loadModule } from \"mlly\";\n\nawait loadModule(\"./hello.mjs\", { url: import.meta.url });\n```\n\nOptions are same as `evalModule`.\n\n### `transformModule`\n\n- Resolves all relative imports will be resolved\n- All usages of `import.meta.url` will be replaced with `url` or `from` option\n\n```js\nimport { transformModule } from \"mlly\";\nconsole.log(transformModule(`console.log(import.meta.url)`), {\n  url: \"test.mjs\",\n});\n```\n\nOptions are same as `evalModule`.\n\n## Other Utils\n\n### `fileURLToPath`\n\nSimilar to [url.fileURLToPath](https://nodejs.org/api/url.html#url_url_fileurltopath_url) but also converts windows backslash `\\` to unix slash `/` and handles if input is already a path.\n\n```js\nimport { fileURLToPath } from \"mlly\";\n\n// /foo/bar.js\nconsole.log(fileURLToPath(\"file:///foo/bar.js\"));\n\n// C:/path\nconsole.log(fileURLToPath(\"file:///C:/path/\"));\n```\n\n### `pathToFileURL`\n\nSimilar to [url.pathToFileURL](https://nodejs.org/api/url.html#urlpathtofileurlpath) but also handles `URL` input and returns a **string** with `file://` protocol.\n\n```js\nimport { pathToFileURL } from \"mlly\";\n\n// /foo/bar.js\nconsole.log(pathToFileURL(\"foo/bar.js\"));\n\n// C:/path\nconsole.log(pathToFileURL(\"C:\\\\path\"));\n```\n\n### `normalizeid`\n\nEnsures id has either of `node:`, `data:`, `http:`, `https:` or `file:` protocols.\n\n```js\nimport { normalizeid } from \"mlly\";\n\n// file:///foo/bar.js\nconsole.log(normalizeid(\"/foo/bar.js\"));\n```\n\n### `loadURL`\n\nRead source contents of a URL. (currently only file protocol supported)\n\n```js\nimport { resolve, loadURL } from \"mlly\";\n\nconst url = await resolve(\"./index.mjs\", { url: import.meta.url });\nconsole.log(await loadURL(url));\n```\n\n### `toDataURL`\n\nConvert code to [`data:`](https://nodejs.org/api/esm.html#esm_data_imports) URL using base64 encoding.\n\n```js\nimport { toDataURL } from \"mlly\";\n\nconsole.log(\n  toDataURL(`\n  // This is an example\n  console.log('Hello world')\n`),\n);\n```\n\n### `interopDefault`\n\nReturn the default export of a module at the top-level, alongside any other named exports.\n\n```js\n// Assuming the shape { default: { foo: 'bar' }, baz: 'qux' }\nimport myModule from \"my-module\";\n\n// Returns { foo: 'bar', baz: 'qux' }\nconsole.log(interopDefault(myModule));\n```\n\n**Options:**\n\n- `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)\n\n### `sanitizeURIComponent`\n\nReplace reserved characters from a segment of URI to make it compatible with [rfc2396](https://datatracker.ietf.org/doc/html/rfc2396).\n\n```js\nimport { sanitizeURIComponent } from \"mlly\";\n\n// foo_bar\nconsole.log(sanitizeURIComponent(`foo:bar`));\n```\n\n### `sanitizeFilePath`\n\nSanitize each path of a file name or path with `sanitizeURIComponent` for URI compatibility.\n\n```js\nimport { sanitizeFilePath } from \"mlly\";\n\n// C:/te_st/_...slug_.jsx'\nconsole.log(sanitizeFilePath(\"C:\\\\te#st\\\\[...slug].jsx\"));\n```\n\n### `parseNodeModulePath`\n\nParses an absolute file path in `node_modules` to three segments:\n\n- `dir`: Path to main directory of package\n- `name`: Package name\n- `subpath`: The optional package subpath\n\nIt returns an empty object (with partial keys) if parsing fails.\n\n```js\nimport { parseNodeModulePath } from \"mlly\";\n\n// dir: \"/src/a/node_modules/\"\n// name: \"lib\"\n// subpath: \"./dist/index.mjs\"\nconst { dir, name, subpath } = parseNodeModulePath(\n  \"/src/a/node_modules/lib/dist/index.mjs\",\n);\n```\n\n### `lookupNodeModuleSubpath`\n\nParses an absolute file path in `node_modules` and tries to reverse lookup (or guess) the original package exports subpath for it.\n\n```js\nimport { lookupNodeModuleSubpath } from \"mlly\";\n\n// subpath: \"./utils\"\nconst subpath = lookupNodeModuleSubpath(\n  \"/src/a/node_modules/lib/dist/utils.mjs\",\n);\n```\n\n## License\n\n[MIT](./LICENSE) - Made with 💛\n\n<!-- Badges -->\n\n[npm-version-src]: https://img.shields.io/npm/v/mlly?style=flat&colorA=18181B&colorB=F0DB4F\n[npm-version-href]: https://npmjs.com/package/mlly\n[npm-downloads-src]: https://img.shields.io/npm/dm/mlly?style=flat&colorA=18181B&colorB=F0DB4F\n[npm-downloads-href]: https://npmjs.com/package/mlly\n[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/mlly/main?style=flat&colorA=18181B&colorB=F0DB4F\n[codecov-href]: https://codecov.io/gh/unjs/mlly\n","publish_time":1772659752700,"_cnpm_publish_time":1772659752700,"dist-tags":{"latest":"1.8.2"}}