{"name":"import-in-the-middle","version":"1.13.2","keywords":["import","ritm","iitm","loader","hook","hooks"],"author":{"name":"Bryan English","email":"bryan.english@datadoghq.com"},"license":"Apache-2.0","_id":"import-in-the-middle@1.13.2","maintainers":[{"name":"datadog","email":"robot-npm-frontend@datadoghq.com"},{"name":"nodejs-foundation","email":"build@iojs.org"}],"homepage":"https://github.com/nodejs/import-in-the-middle#readme","bugs":{"url":"https://github.com/nodejs/import-in-the-middle/issues"},"dist":{"shasum":"b8d873708ab121996da6842fa7740ac5cd437f9e","tarball":"http://registry-npm.ywwl.com/import-in-the-middle/download/import-in-the-middle-1.13.2.tgz","fileCount":149,"integrity":"sha512-Yjp9X7s2eHSXvZYQ0aye6UvwYPrVB5C2k47fuXjFKnYinAByaDZjh4t9MT2wEga9775n6WaIqyHnQhBxYtX2mg==","signatures":[{"sig":"MEQCIFJIqmJGcRL6ss5Y9dtZrXZzLxYdaq/H8PimILk0oijFAiBul3q75AgBKNJtQFfDAAeu/Dk4z6UNiaMLdRc8tjb3oQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":118528,"size":35507,"noattachment":false,"key":"/import-in-the-middle/-/import-in-the-middle-1.13.2.tgz"},"main":"index.js","types":"./index.d.ts","gitHead":"38f815b5cd1d5f9e881fc7c6f82f20e90a43d21c","imhotap":{"runner":"node","test-env":"NODE_OPTIONS=--no-warnings --require ./test/version-check.js --experimental-loader ./test/generic-loader.mjs"},"scripts":{"lint":"eslint .","test":"c8 --reporter lcov --check-coverage --lines 50 imhotap --files test/{hook,low-level,other,get-esm-exports,register}/*","test:ts":"c8 --reporter lcov imhotap --files test/typescript/*.test.mts","coverage":"c8 --reporter html imhotap --files test/{hook,low-level,other,get-esm-exports}/* && echo '\nNow open coverage/index.html\n'","lint:fix":"eslint . --fix","test:e2e":"node test/check-exports/test.mjs"},"_npmUser":{"name":"nodejs-foundation","email":"build@iojs.org"},"repository":{"url":"git+ssh://git@github.com/nodejs/import-in-the-middle.git","type":"git"},"_npmVersion":"10.9.2","description":"Intercept imports in Node.js","directories":{},"_nodeVersion":"22.15.0","dependencies":{"acorn":"^8.14.0","cjs-module-lexer":"^1.2.2","acorn-import-attributes":"^1.9.5","module-details-from-path":"^1.0.3"},"_hasShrinkwrap":false,"devDependencies":{"c8":"^7.8.0","got":"^14.3.0","vue":"^3.4.31","eslint":"^8.55.0","openai":"4.47.2","imhotap":"^2.1.0","ts-node":"^10.9.1","date-fns":"^3.6.0","typescript":"^4.7.4","@babel/core":"^7.23.7","@types/node":"^18.0.6","@node-rs/crc32":"^1.10.3","eslint-plugin-n":"^16.4.0","eslint-plugin-node":"^11.1.0","@babel/eslint-parser":"^7.23.3","eslint-plugin-import":"^2.29.0","eslint-plugin-promise":"^6.1.1","eslint-config-standard":"^17.1.0","@react-email/components":"^0.0.19","@babel/plugin-syntax-import-assertions":"^7.23.3"},"_npmOperationalInternal":{"tmp":"tmp/import-in-the-middle_1.13.2_1747128122389_0.5604658734459791","host":"s3://npm-registry-packages-npm-production"},"readme":"# import-in-the-middle\n\n**`import-in-the-middle`** is a module loading interceptor inspired by\n[`require-in-the-middle`](https://npm.im/require-in-the-middle), but\nspecifically for ESM modules. In fact, it can even modify modules after loading\ntime.\n\n## Usage\n\nThe API for\n`require-in-the-middle` is followed as closely as possible as the default\nexport. There are lower-level `addHook` and `removeHook` exports available which\ndon't do any filtering of modules, and present the full file URL as a parameter\nto the hook. See the Typescript definition file for detailed API docs.\n\nYou can modify anything exported from any given ESM or CJS module that's\nimported in ESM files, regardless of whether they're imported statically or\ndynamically.\n\n```js\nimport { Hook } from 'import-in-the-middle'\nimport { foo } from 'package-i-want-to-modify'\n\nconsole.log(foo) // whatever that module exported\n\nHook(['package-i-want-to-modify'], (exported, name, baseDir) => {\n  // `exported` is effectively `import * as exported from ${url}`\n  exported.foo += 1\n})\n\nconsole.log(foo) // 1 more than whatever that module exported\n```\n\nThis requires the use of an ESM loader hook, which can be added with the following\ncommand-line option.\n\n```shell\nnode --loader=import-in-the-middle/hook.mjs my-app.mjs\n```\n\nSince `--loader` has been deprecated you can also register the loader hook programmatically via the Node\n[`module.register()`](https://nodejs.org/api/module.html#moduleregisterspecifier-parenturl-options)\nAPI. However, for this to be able to hook non-dynamic imports, it needs to be\nregistered before your app code is evaluated via the `--import` command-line option.\n\n`my-loader.mjs`\n\n```js\nimport * as module from 'module'\n\nmodule.register('import-in-the-middle/hook.mjs', import.meta.url)\n```\n\n```shell\nnode --import=./my-loader.mjs ./my-code.mjs\n```\n\nWhen registering the loader hook programmatically, it's possible to pass a list\nof modules, file URLs or regular expressions to either `exclude` or specifically\n`include` which modules are intercepted. This is useful if a module is not\ncompatible with the loader hook.\n\n> **Note:** This feature is incompatible with the `{internals: true}` Hook option\n\n```js\nimport * as module from 'module'\n\n// Exclude intercepting a specific module by name\nmodule.register('import-in-the-middle/hook.mjs', import.meta.url, {\n  data: { exclude: ['package-i-want-to-exclude'] }\n})\n\n// Only intercept a specific module by name\nmodule.register('import-in-the-middle/hook.mjs', import.meta.url, {\n  data: { include: ['package-i-want-to-include'] }\n})\n```\n\n### Only Intercepting Hooked modules\n\n> **Note:** This feature is experimental and is incompatible with the `{internals: true}` Hook option\n\nIf you are `Hook`'ing all modules before they are imported, for example in a\nmodule loaded via the Node.js `--import` CLI argument, you can configure the\nloader to intercept only modules that were specifically hooked.\n\n`instrument.mjs`\n\n```js\nimport { register } from 'module'\nimport { Hook, createAddHookMessageChannel } from 'import-in-the-middle'\n\nconst { registerOptions, waitForAllMessagesAcknowledged } = createAddHookMessageChannel()\n\nregister('import-in-the-middle/hook.mjs', import.meta.url, registerOptions)\n\nHook(['fs'], (exported, name, baseDir) => {\n  // Instrument the fs module\n})\n\n// Ensure that the loader has acknowledged all the modules\n// before we allow execution to continue\nawait waitForAllMessagesAcknowledged()\n```\n\n`my-app.mjs`\n\n```js\nimport * as fs from 'fs'\n// fs will be instrumented!\nfs.readFileSync('file.txt')\n```\n\n```shell\nnode --import=./instrument.mjs ./my-app.mjs\n```\n\n## Synchronous loader hooks\n\nOn Node.js versions that support\n[`module.registerHooks()`](https://nodejs.org/api/module.html#moduleregisterhooksoptions)\nthe loader can run *synchronously*, on the application thread, instead of on the\nseparate thread that `module.register()` uses. Running in-thread removes the\nmessage channel: `Hook()` registrations are visible to the loader directly, so\nthe `createAddHookMessageChannel` / `waitForAllMessagesAcknowledged` step shown\nabove is unnecessary.\n\n`module.registerHooks()` was added in 22.15.0 / 24.0.0, but its synchronous load\nhook rejected the nullish CommonJS `source` the loader returns for `require()`s\npulled into the ESM graph until [nodejs/node#59929][]. The fix shipped in\n**22.22.3, 24.11.1, 25.1.0 and 26.0.0**; earlier versions ship\n`module.registerHooks()` but cannot run the synchronous loader. Use\n`supportsSyncHooks()` to branch on this rather than a hand-written version check:\n\n```js\nimport { register, supportsSyncHooks } from 'import-in-the-middle/register-hooks.mjs'\n\nif (supportsSyncHooks()) {\n  register({ include: ['package-i-want-to-include'] })\n} else {\n  // Fall back to the asynchronous loader, e.g. module.register('import-in-the-middle/hook.mjs').\n}\n```\n\n[nodejs/node#59929]: https://github.com/nodejs/node/pull/59929\n\n`instrument.mjs`\n\n```js\nimport { register } from 'import-in-the-middle/register-hooks.mjs'\nimport { Hook } from 'import-in-the-middle'\n\nregister({ include: ['package-i-want-to-include'] })\n\nHook(['package-i-want-to-include'], (exported, name, baseDir) => {\n  // Instrument the module\n})\n```\n\n```shell\nnode --import=./instrument.mjs ./my-app.mjs\n```\n\n`register()` accepts the same `include` / `exclude` options as the asynchronous\nloader and throws on a Node.js version where `supportsSyncHooks()` is `false`.\n\n### Custom matching with `shouldInclude`\n\nInstead of `include` / `exclude` lists, you can pass a `shouldInclude(url, specifier)`\npredicate to decide which modules are intercepted. It is called for every resolved\nmodule with the resolved URL and the import specifier; return a truthy value to\nintercept the module. When a predicate is provided it takes over the decision and\nthe `include` / `exclude` options are ignored.\n\nThis is useful when matching doesn't map cleanly onto bare specifiers, file URLs and\nregular expressions — for example a matcher built from your own configuration, or a\ndecision that depends on more than the specifier.\n\n```js\nimport { register } from 'import-in-the-middle/register-hooks.mjs'\n\nregister({\n  shouldInclude (url, specifier) {\n    return specifier === 'package-i-want-to-include' ||\n      url.includes('/node_modules/some-scope/')\n  }\n})\n```\n\nThe predicate receives only the URL and the specifier, never a resolved file path.\nBecause `module.register()` transfers its `data` to the loader thread by structured\nclone — which cannot carry a function — `shouldInclude` is supported for synchronous\nregistration (`register-hooks.mjs`, shown above) and for predicates constructed on\nthe loader thread; it is not accepted through the `data` option of the asynchronous\n`module.register('import-in-the-middle/hook.mjs', ...)`.\n\n### Opting out of CJS source stripping\n\nOn Node 22+, when a CJS module is loaded through the ESM translator and another\nloader hook provides its source (instead of leaving it `null` for Node to read\nnatively), `require()` calls inside that CJS module for packages using the\n`\"module-sync\"` exports condition fail with `ERR_VM_MODULE_LINK_FAILURE`. To work\naround this Node bug, `import-in-the-middle` strips hook-provided source for\nCJS modules in the synchronous require chain, forcing Node to use its native CJS\nloader which handles this correctly.\n\nIf you rely on a downstream loader hook seeing (and acting on) the source of\nCJS modules in the require chain, you can opt out of this workaround by passing\n`disableCjsSourceStripping: true` in the hook config. The workaround remains\nenabled by default.\n\n```js\nimport { register } from 'import-in-the-middle/register-hooks.mjs'\n\nregister({\n  include: ['package-i-want-to-include'],\n  disableCjsSourceStripping: true\n})\n```\n\nThis option is accepted by both synchronous (`register-hooks.mjs`) and\nasynchronous (`module.register('import-in-the-middle/hook.mjs', ...)`) registration.\n\n## TypeScript modules\n\nOn Node.js versions that strip TypeScript types natively (those exposing\n[`module.stripTypeScriptTypes()`](https://nodejs.org/api/module.html#modulestriptypescripttypescode-options),\n>= 22.13.0 / >= 23.9.0 / >= 24.0.0), `import-in-the-middle` intercepts `.ts`,\n`.mts` and `.cts` modules just like their JavaScript counterparts. The types are\nstripped before the module's exports are read, so type-only exports\n(`export type`, `export interface`) are not present on the intercepted\nnamespace; value exports are.\n\n```ts\n// math.mts\nexport type Op = '+' | '-'\nexport function add (a: number, b: number): number {\n  return a + b\n}\n```\n\n```js\nHook(['./math.mts'], (exported) => {\n  // `exported.add` is interceptable; the `Op` type is not part of the namespace\n})\n```\n\nOn Node.js versions where type stripping is not enabled by default, run with\n`--experimental-strip-types`. Older versions that predate\n`module.stripTypeScriptTypes()` leave TypeScript modules untouched.\n\n## Limitations\n\n* You cannot add new exports to a module. You can only modify existing ones.\n* While bindings to module exports end up being \"re-bound\" when modified in a\n  hook, dynamically imported modules cannot be altered after they're loaded.\n* Modules loaded via `require` are not affected at all.\n* A module's set of export *names* is assumed to be stable for the lifetime of\n  the process. `import-in-the-middle` reads a module's source once to lex its\n  exports and reuses that export set on later loads of the same URL. An upstream\n  loader that returns a *different set of exports* for the same URL across calls\n  — a stateful codegen loader, or one that varies its output by `context` — is\n  not supported and will be instrumented with the export set from its first\n  load. Idempotent transforms (type stripping, AST instrumentation, minifiers)\n  are unaffected, and the actual module still executes the source its real load\n  returns; only the interceptable export *names* are memoized.\n","publish_time":1747128122575,"_cnpm_publish_time":1747128122575,"dist-tags":{"latest":"3.6.0"}}