{"name":"npx-import","version":"1.1.2","description":"Runtime dependencies, installed as if by magic ✨","main":"lib/index.js","type":"module","scripts":{"build":"tsc","dev":"tsc --watch","go":"node --experimental-vm-modules test/go.js","test":"pnpm build && vitest","test:watch":"vitest --watch"},"keywords":[],"author":{"name":"Glen Maddern","email":"glenmaddern@gmail.com"},"license":"ISC","homepage":"https://github.com/geelen/npx-import","devDependencies":{"@types/node":"^18.6.3","@types/semver":"^7.3.10","@types/validate-npm-package-name":"^4.0.0","chalk":"^5.0.1","prettier":"^2.7.1","typescript":"^4.7.4","vitest":"^0.20.3"},"dependencies":{"execa":"^6.1.0","parse-package-name":"^1.0.0","semver":"^7.3.7","validate-npm-package-name":"^4.0.0"},"types":"./lib/index.d.ts","gitHead":"2b136829a4643f614b41ad254b05dcadfda6c310","_id":"npx-import@1.1.2","_nodeVersion":"18.3.0","_npmVersion":"8.15.0","dist":{"integrity":"sha512-W/DCVEA7FQSK8vyphTLmT7LtGsZ8RJ85kRtAqhYediFCls9asiAebiKC9Y4S45u5e711fvDArC8UkbmX8nTwyg==","shasum":"4d68f5e78ee1283ae96bd57d513e6198b8a4d25a","tarball":"http://registry-npm.ywwl.com/npx-import/download/npx-import-1.1.2.tgz","fileCount":18,"unpackedSize":61340,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCSCLHNpWgssYlrCNMEGMRkmHWioSw27oWwpDmuIgx5fgIgZBQvOIZLvA+ln++7h39g8JsbtIYewhhHR3CJ9GKWavc="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjHyl3ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmpOeg//TEVrXzdMbiSG3a+rOoTuCChGvSEeq8ZVaw/+hlpMxULd4YcR\r\nwNlijBcebXPKeu9hVGbueAnWjvzO0dao1bgvicrlmuvw0NVzqVPluDaDmVps\r\nLVH4cpaockhBmkNc//X3qHLwzPdaxh6P/wY3kmH5QtfIBZA+gV0vVhm6LOnu\r\nQPk09I4h4/oZu3nufaVo5VIGhMH2l5ekoH8be0uurpGDRfqEZO9Jyjenu3Fh\r\nXog/jIwJYHcQuxwkcdHWVFCEaVmVHyaBOZZ+fwD2LMsebOGz4aShoNbZmc8f\r\nJJ5AVhTABaBeUbWzldWWp9RepqIzm3mOlMdIhEysKISGUFsgVH+VAXz/Flf7\r\nc6mK0ApJrlzIV1SuCZeKCUyuwtIn38QM6r3CkhA3qIPIGu9vvH1R/albC/fZ\r\nTxgsn90kf5a1x2b83XVTa9q+yyJrZc6KCBbHhG71na3vv9Q07art/rm4oe+R\r\nGZwzpjmuuaBZarojR1JR8VMBC2m7lZIn7hih2jKSIpWvkmZYzvId9zz0/GhQ\r\n+YGIMO7bFKb+Pb8I+PYp7kd5+cmGTt14dLZlWA7UC2hUkrMLq+W5vhL8XTHT\r\nHzf0Hb4ElCJxO3sp0PkRbMz+n8XSyNrh9rbZD19t2yzZggs4EqNGqNrRUmOb\r\n2zvAEDcjOOSVgiWqMTBAlY/Ilmnr0EXcVWc=\r\n=aXqN\r\n-----END PGP SIGNATURE-----\r\n","size":15918,"noattachment":false,"key":"/npx-import/-/npx-import-1.1.2.tgz"},"_npmUser":{"name":"geelen","email":"glen@glenmaddern.com"},"directories":{},"maintainers":[{"name":"geelen","email":"glen@glenmaddern.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/npx-import_1.1.2_1662986615358_0.7177439178423959"},"_hasShrinkwrap":false,"readme":"# 🧙‍♂️ `npx-import` 🧙‍♀️\n\n### Runtime dependencies, installed _as if by magic_ ✨\n\n[![twitter](https://img.shields.io/badge/@glenmaddern-blue.svg?style=flat&logo=twitter&label=​)](https://twitter.com/glenmaddern)&nbsp; [![GitHub last commit](https://img.shields.io/github/last-commit/geelen/npx-import?logo=github&style=flat&label=​)](https://github.com/geelen/npx-import)&nbsp; [![npm](https://img.shields.io/npm/v/npx-import?label=​&logo=npm)](https://www.npmjs.com/package/npx-import) \n\n`npx-import` can be used as a drop-in replacement for [dynamic `import()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import):\n\n```ts\nimport { npxImport } from 'npx-import'\n\n// If big-dep isn't installed locally, npxImport will try\n// to download, install & load it, completely seamlessly.\nconst dependency = await npxImport('big-dep')\n```\n\nIt's exactly like [`npx`](https://docs.npmjs.com/cli/v8/commands/npx), but for `import()`! <sub><sub><sup>(hence the name)</sup></sub></sub>\n\nIs this a good idea? See [FAQ](#faq) below.\n\n## Usage\n\n`npx-import` is ideal for deferring installation for dependencies that are unexpectedly large, require native compilation, or not used very often (or some combination thereof), for example:\n\n```ts\n// Statically import small/common deps as normal\nimport textRenderer from 'tiny-text-renderer'\n\n// Use npxImport to defer\nimport { npxImport } from 'npx-import'\n\nexport async function writeToFile(report: Report, filename: string) {\n\n  if (filename.endsWith('.png')) {\n    console.log(`This is a PNG! We'll have to compile imagemagick!`)\n    const { default: magick } = await npxImport('imagemagick-utils@^1.1.0')\n    await magick.renderToPNG(report, filename)\n\n  } else if (filename.endsWith('.pdf')) {\n    console.log(`Argh, a PDF!? Go make a cuppa, this'll take a while...`)\n    const { default: pdfBoi } = await npxImport('chonk-pdf-boi@3.1.4')\n    await pdfBoi.generate(report, filename)\n\n  } else {\n    console.log(`Writing to ${filename}...`)\n    await textRenderer.write(report, filename)\n  }\n  console.log(`Done!`)\n}\n```\n\nWhen run, `npx-import` will log out some explanation, as well as instructions for installing the dependency locally & skipping this step in future:\n\n```\n❯ node ./index.js --filename=image.png\n\nThis is a PNG! We'll have to compile imagemagick!\n[NPXI] imagemagick-utils not available locally. Attempting to use npx to install temporarily.\n[NPXI] Installing... (npx -y -p imagemagick-utils@^1.1.0)\n[NPXI] Installed into /Users/glen/.npm/_npx/8cac855b1579fd07/node_modules.\n[NPXI] To skip this step in future, run: pnpm add -D imagemagick-utils@^1.1.0\nDone!\n```\n\nFor some types of dependencies, this is a much better UX than the alternatives:\n\n- You either add `imagemagick-utils` & `chonk-pdf-boi` as dependencies, slowing down initial install.\n- The first time a user tries to export a PNG/PDF, you error out with instructions to install the relevant package and retry.\n- You pause, prompt the user for confirmation, then try to detect which package manager they're using and auto-install the dependency for them.\n\nThe last of these generally works well but `npx-import` has slightly different properties:\n\n- The user doesn't need to be prompted—if the dependency can be sourced, installed & transparently included, the program doesn't need to be interrupted.\n- Your user's current project directory is never altered as a side-effect of running a program.\n\nMost importantly, though, **it's compatible with `npx`!** For example, `npx some-cli --help` can be super fast but `npx some-cli export --type=pdf` can transparently download the required dependencies during execution. It's super neat!\n\n## Installation\n\n```\nnpm install --save npx-import\npnpm add -P npx-import\nyarn add npx-import\n```\n\n## Typescript\n\nJust like `import()`, the return type default to `any`. But you can import the types of a devDependency without any consumers of your package needing to download it at installation time.\n\n```\npnpm add -D big-dep\n```\n\n```ts\nimport { npxImport } from 'npx-import'\ntype BigDepType = typeof import('big-dep')\n\nconst bigDep = await npxImport<BigDepType>('big-dep')\n```\n\n## API\n\n* Since package versions are no longer tracked in your `package.json`, we recommend being explicit:\n\n```ts\nconst lazyDep = await npxImport('left-pad@1.3.0')\n```\n\nAny package specifier that's valid in `package.json` will work here: e.g. `^1.0.0`, `~2.3.0`, `>4.0.0`, `@latest`, `@next`, etc.\n\nNote: there is a speed benefit from using exact versions. `npxImport(pkg-a@1.2.3)` will run `npx --prefer-offline` under the hood, making it faster after the first run (since it doesn't first check the NPM registry for newer versions).\n\n* You can also install multiple packages at once:\n\n```ts\nconst [depA, depB] = await npxImport(['dep-a@7.8.2', 'dep-b@7.8.2'])\n```\n\n`npx-import` also takes a third argument, which lets you customise, or silence, the log output. Each line that would normally be printed is passed to the logger function:\n\n```ts\nconst grayLog = (line: string) => console.log(chalk.gray(line))\nconst [depA, depB] = await npxImport(['dep-a@7.8.2', 'dep-b@7.8.2'], grayLog)\n```\n\n* Use `npxResolve` instead of `require.resolve` to get the path (local or temporary)\n\n```ts\nexport function getSQLiteNativeBindingLocation() {\n  return path.resolve(\n    path.dirname(npxResolve(\"better-sqlite3\")),\n    \"../build/Release/better_sqlite3.node\"\n  );\n}\n```\n\nNote, `npxResolve` requires that you'd previously called `npxImport` for the same package.\n\n## FAQ\n\n### 🤔 Isn't this, like, a heroically bad idea?\n\nNah it's good actually.\n\n### 🤨 No but seriously, isn't using `npx` a big security hole?\n\nInitially, `npx` didn't prompt before downloading and executing a package, which was _definitely_ a security risk. But that's been [fixed since version 7](https://github.com/npm/npx/issues/9#issuecomment-786940691). Now, if you're intending to write `npx prettier` to format your code and accidentally type `npx prettomghackmycomputerpls`, you'll get a helpful prompt:\n\n```\n❯ npx prettier@latest\nNeed to install the following packages:\n  prettomghackmycomputerpls@6.6.6\nOk to proceed? (y)\n```\n\nThis gives the user a chance to see their mistake and prevent being hacked to bits.\n\n### 😠 But hang on, you're never prompting the user to confirm!\n\nAh yes, that seems to go against the previous point. But `npx-import` isn't being triggered from a potentially clumsy human on a keyboard, it's running inside some source code you've (by definition) already authorised to run on your machine.\n\n`npx-import` is an alternative to publishing these as normal dependencies of your project and having your users download them at install time. `npm install` doesn't prompt the user to approve every transitive dependency of what's being installed/run, so `npx-import` doesn't either.\n\n### 🧐 What if the user has already installed the dependency somewhere?\n\nThen `npxImport` short-circuits, returning the local version without logging anything out. This is what the user is instructed to do to \"skip this step in future\". In other words, `npxImport()` first tries to call your native `import()`, and only does anything if that fails.\n\nNote that this also works for multiple dependencies, `npxImport(['pkg-a', 'pkg-b', 'pkg-c'])` will only fetch & install those that are missing.\n\n### 🤪 Doesn't this mean dependencies gets repeatedly downloaded & installed?\n\nNo! `npx` maintains a cache in the user's home directory. If a cached package is found, `npx` will (by default) hit NPM to check if there's any new versions for that specifier, and if not, return the cache. `npxImport` adds a small optimisation—if you specify an exact package version (e.g. `@7.8.2`), it'll run `npx --prefer-offline` to skip the NPM check.\n\nSo new packages are only downloaded & installed when:\n\n* It's the first time a particular package/version combo is seen (see next section)\n* No locked version was provided and there's a new version on NPM\n\n### 😵‍💫 What about multiple projects? Doesn't the cache mean projects can clobber/overwrite/conflict with each other?\n\nAs it turns out, no! While I wasn't paying attention, `npx` got really smart! To understand why, we need to look at how `npx` works:\n\nFor starters, `npx some-pkg` is a shorthand for `npx -p some-pkg <command>`, where `<command>` is whatever `bin` that `some-pkg` declares. Often, the `<command>` and the package name are the same (e.g. `npx prettier`), but it's the `bin` field inside the package that's really being used. Otherwise, scoped packages (like `npx @11ty/eleventy`) would never work. If there's no `bin` field declared (e.g. for `chokidar`, you need `npx chokidar-cli`), or if there's more than one (e.g. for `typescript`, you need `npx -p typescript tsc`), you have to use the expanded form.\n\nBut there's no requirement that `<command>` is a `bin` inside the package at all! It can be any command (at least for `npx`, `pnpm dlx` and `yarn dlx` have different restrictions), for example, we can inject a `node -e` command and start to learn about what's going on:\n\n```\n❯ npx -y -p is-odd node -e 'console.log(process.env.PATH.split(\":\"))' | grep .npm/_npx\n  '/Users/glen/.npm/_npx/e1b5bd0eb9f99fbc/node_modules/.bin',\n```\n\nUsing `process.env.PATH` and searching for `.npm/_npx` is, on OSX with NPX v8+, a reliable way to find out where `npx` is installing these temporary packages. Let's look inside:\n\n```\n❯ ll2 /Users/glen/.npm/_npx/e1b5bd0eb9f99fbc/\ndrwxr-xr-x    - glen  4 Aug 11:07  /Users/glen/.npm/_npx/e1b5bd0eb9f99fbc\ndrwxr-xr-x    - glen  4 Aug 11:07 ├──  node_modules\n.rw-r--r--  780 glen  4 Aug 11:07 │  ├──  .package-lock.json\ndrwxr-xr-x    - glen  4 Aug 11:07 │  ├──  is-number\ndrwxr-xr-x    - glen  4 Aug 11:07 │  └──  is-odd\n.rw-r--r-- 1.4k glen  4 Aug 11:07 ├──  package-lock.json\n.rw-r--r--   51 glen  4 Aug 11:07 └──  package.json\n\n❯ cat /Users/glen/.npm/_npx/e1b5bd0eb9f99fbc/package.json\n{\n  \"dependencies\": {\n    \"is-odd\": \"^3.0.1\"\n  }\n}\n```\n\nThat looks like a pretty normal project directory to me!\n\n> Aside, `ll2` is my super rad alias for `exa --icons -laTL 2`. See [exa](https://github.com/ogham/exa).\n\nNow, the crucial bit: **every time `npx` runs for some unique set of packages it creates a new directory**. That goes for installing multiple deps at once but also for different named/pinned versions/tags for individual packages:\n\n```\n❯ export LOG_NPX_DIR=\"node -e 'console.log(process.env.PATH.split(\\\":\\\").filter(p => p.match(/\\.npm\\/_npx/)))'\"\n\n❯ npx -y -p is-odd $LOG_NPX_DIR\n[ '/Users/glen/.npm/_npx/e1b5bd0eb9f99fbc/node_modules/.bin' ]\n\n❯ npx -y -p is-odd@latest $LOG_NPX_DIR\n[ '/Users/glen/.npm/_npx/ecc6e2260c717fec/node_modules/.bin' ]\n\n❯ npx -y -p is-odd@3.0.1 $LOG_NPX_DIR\n[ '/Users/glen/.npm/_npx/c41e9ab9d1d9c43f/node_modules/.bin' ]\n\n❯ npx -y -p is-odd@\\^3.0.1 $LOG_NPX_DIR\n[ '/Users/glen/.npm/_npx/e86896689f5aebbb/node_modules/.bin' ]\n```\n\nNote that **every one of these commands downloaded the same version of `is-odd`**, but because they were referenced using different identifiers, `_` vs `latest` vs `3.0.1` vs `>3.0.1`, `npx` played it safe and made a new temporary directory.\n\nFor multiple packages, the same rule applies, although order is not important:\n\n```\n❯ npx -y -p is-odd -p is-even $LOG_NPX_DIR\n[ '/Users/glen/.npm/_npx/f9af4fded130fd33/node_modules/.bin' ]\n\n❯ npx -y -p is-even -p is-odd $LOG_NPX_DIR\n[ '/Users/glen/.npm/_npx/f9af4fded130fd33/node_modules/.bin' ]\n\n❯ ll2 /Users/glen/.npm/_npx/f9af4fded130fd33\ndrwxr-xr-x    - glen  4 Aug 11:37  /Users/glen/.npm/_npx/f9af4fded130fd33\ndrwxr-xr-x    - glen  4 Aug 11:37 ├──  node_modules\n.rw-r--r-- 2.6k glen  4 Aug 11:37 │  ├──  .package-lock.json\ndrwxr-xr-x    - glen  4 Aug 11:37 │  ├──  is-buffer\ndrwxr-xr-x    - glen  4 Aug 11:37 │  ├──  is-even\ndrwxr-xr-x    - glen  4 Aug 11:37 │  ├──  is-number\ndrwxr-xr-x    - glen  4 Aug 11:37 │  ├──  is-odd\ndrwxr-xr-x    - glen  4 Aug 11:37 │  └──  kind-of\n.rw-r--r-- 4.8k glen  4 Aug 11:37 ├──  package-lock.json\n.rw-r--r--   76 glen  4 Aug 11:37 └──  package.json\n\n❯ cat /Users/glen/.npm/_npx/f9af4fded130fd33/package.json\n{\n  \"dependencies\": {\n    \"is-even\": \"^1.0.0\",\n    \"is-odd\": \"^3.0.1\"\n  }\n}\n```\n\nSo `npx` is doing exactly the same as an `npm install`, with a `package.json`, `package-lock.json`, `node_modules` etc. It's just dynamically creating directories based on some hash of its inputs. So the only way two projects can use the same package in the cache is if they _both_ ask for _exactly_ the same packages & versions. It's super clever!\n\n### 😐 But what about transitive deps? Won't you get duplication?\n\nSadly, yes. If both your package `main-pkg` and `util-a` depend on `util-b`, then calling `npxImport('util-a')` from within `main-pkg` will create a new directory with a second copy of `util-b`. If there are globals in that package, or if the version specifiers are slightly different, you could potentially have problems.\n\nIt's probably possible to [detect this in future](https://github.com/geelen/npx-import/issues/2) and warn/error out. But for now, I recommend using `npxImport` for mostly self-contained dependencies.\n\n### 🫤 What about version mismatch with local files?\n\nIf a user has `pkg-a` version `1.0.0` installed, but one of their packages calls `npxImport('pkg-a@^2.0.0')`, `npxImport` isn't smart enough ([yet](https://github.com/geelen/npx-import/issues/3)) to know that the local version of `pkg-a` doesn't match the version range specified (since it's using native `import()` under the hood). Without `npxImport`, the `npm install` step would have had a chance to bump the installed version of `pkg-a` to meet the requirements of _all_ packages being used, but we're bypassing that.\n\nThis will be fixed in a future version.\n\n### 🫠 What kind of packages would you use this for?\n\n- Anything with native extensions needing building (do that when you need it)\n- Packages with large downloads (e.g. puppeteer, sqlite-node)\n- CLI packages that want to make `npx my-cli --help` or `npx my-cli init` really fast and dependency-free, but also allow `npx my-cli <cmd>` to pull in arbitrary deps on-demand, without forcing the user to stop, create a local directory, and install dev dependencies.\n- Anything already making heavy use of `npx`. You're in the jungle, baby.\n\n---\n\nBuilt with <3 during a massive yak shave by Glen Maddern.\n","publish_time":1662986615525,"_cnpm_publish_time":1662986615525,"dist-tags":{"latest":"1.1.4","wip":"1.0.5-0"}}