Socket
Socket
Sign inDemoInstall

mlly

Package Overview
Dependencies
Maintainers
1
Versions
76
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mlly - npm Package Compare versions

Comparing version 0.5.2 to 0.5.3

2

dist/index.d.ts

@@ -78,3 +78,3 @@ interface ESMImport {

declare function resolvePath(id: string, opts?: ResolveOptions): Promise<any>;
declare function createResolve(defaults?: ResolveOptions): (id: any, url: any) => Promise<string>;
declare function createResolve(defaults?: ResolveOptions): (id: string, url?: ResolveOptions['url']) => Promise<string>;

@@ -81,0 +81,0 @@ interface EvaluateOptions extends ResolveOptions {

{
"name": "mlly",
"version": "0.5.2",
"version": "0.5.3",
"description": "Missing ECMAScript module utils for Node.js",

@@ -19,9 +19,2 @@ "repository": "unjs/mlly",

],
"scripts": {
"build": "unbuild",
"dev": "vitest",
"lint": "eslint --ext .ts src",
"release": "pnpm test && pnpm build && standard-version && pnpm publish && git push --follow-tags",
"test": "pnpm lint && vitest run"
},
"dependencies": {

@@ -41,3 +34,11 @@ "pathe": "^0.2.0",

},
"packageManager": "pnpm@6.32.3"
}
"packageManager": "pnpm@6.32.3",
"scripts": {
"build": "unbuild",
"dev": "vitest",
"lint": "eslint --ext .ts src",
"release": "pnpm test && pnpm build && standard-version && pnpm publish && git push --follow-tags",
"test": "pnpm lint && vitest run"
},
"readme": "# mlly\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\n many 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 recommand.\n\nImport utils:\n\n```js\n// ESM\nimport { } from 'mlly'\n\n// CommonJS\nconst { } = require('mlly')\n```\n\n\n\n## Resolving ESM modules\n\nSeveral utilities to make ESM resolution easier:\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`\n\nResolve a module by respecting [ECMAScript Resolver algorithm](https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_resolver_algorithm)\n(based on experimental Node.js implementation extracted from [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 } 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`\n\nSimilar to `resolve` but returns a path instead of URL using `fileURLToPath`.\n\n```js\nimport { resolvePath } 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(await resolveImports(`import foo from './bar.mjs'`, { url: import.meta.url }))\n```\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 resault 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\n - If is `data:` return `true` (✅ valid)\n - 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\nNode.js has [Interoperability with CommonJS](https://nodejs.org/api/esm.html#interoperability-with-commonjs).\n\n\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\n## Import/Export Analyzes\n\nTools to quikcly analyze ESM synax and extract static `import`/`export`\n - Super fast Regex based implementation\n - Handle most of 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\n### `findStaticImports`\n\nFind all static ESM imports.\n\nExample:\n\n```js\nimport { findStaticImports } from 'mlly'\n\nconsole.log(findStaticImports(`\n// Empty line\nimport foo, { bar /* foo */ } from 'baz'\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 previusly 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\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\n### `findDynamicImports`\n\nFind all dynamic ESM imports.\n\nExample:\n\n```js\nimport { findDynamicImports } from 'mlly'\n\nconsole.log(findDynamicImports(`\nconst foo = await import('bar')\n`))\n```\n\n### `findExports`\n\n**Note:** API Of this function might be broken in a breaking change for code matcher\n\n```js\nimport { findExports } from 'mlly'\n\nconsole.log(findExports(`\nexport const foo = 'bar'\nexport { bar, baz }\nexport default something\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## Evaluating Modules\n\nSet of utilities to evaluate ESM modules using `data:` imports\n - Allow evaluating modules using\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 import { reverse } from './utils.mjs'\n console.log(reverse('!emosewa si sj'))\n`, { url: import.meta.url })\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 { toDataURL } from 'mlly'\nconsole.log(transformModule(`console.log(import.meta.url)`), { url: 'test.mjs' })\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### `normalizeid`\n\nEnsures id has either of `node:`, `data:`, `http:`, `https:` or `file:` protocols.\n\n```js\nimport { ensureProtocol } 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(toDataURL(`\n // This is an example\n console.log('Hello world')\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### `sanitizeURIComponent`\n\nReplace reserved charachters 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## License\n\n[MIT](./LICENSE) - Made with ❤️\n"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc