import-in-the-middle 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.release-please-manifest.json +3 -0
  2. package/CHANGELOG.md +15 -0
  3. package/CODE_OF_CONDUCT.md +4 -0
  4. package/CONTRIBUTING.md +32 -4
  5. package/GOVERNANCE.md +28 -0
  6. package/LICENSE +198 -10
  7. package/NOTICE +33 -3
  8. package/README.md +33 -0
  9. package/hook.js +131 -29
  10. package/hook.mjs +2 -2
  11. package/index.d.ts +1 -1
  12. package/lib/get-esm-exports.js +2 -2
  13. package/lib/get-exports.js +76 -43
  14. package/package.json +6 -5
  15. package/release-please-config.json +10 -0
  16. package/test/check-exports/test.mjs +317 -0
  17. package/test/fixtures/duplicate-b.mjs +1 -1
  18. package/test/fixtures/duplicate-c.mjs +1 -0
  19. package/test/fixtures/duplicate-explicit.mjs +5 -0
  20. package/test/fixtures/index.js +1 -0
  21. package/test/fixtures/json-attributes.mjs +5 -0
  22. package/test/fixtures/re-export-cjs-built-in.js +1 -0
  23. package/test/fixtures/re-export-cjs.js +1 -0
  24. package/test/fixtures/require-root.js +1 -0
  25. package/test/generic-loader.mjs +2 -2
  26. package/test/get-esm-exports/v20-get-esm-exports.js +1 -1
  27. package/test/hook/duplicate-exports-explicit.mjs +13 -0
  28. package/test/hook/duplicate-exports.mjs +3 -3
  29. package/test/hook/re-export-cjs.mjs +19 -0
  30. package/test/hook/require-root-cjs.mjs +12 -0
  31. package/test/hook/v18.19-openai.mjs +6 -0
  32. package/test/hook/v20.10-static-import-attributes.mjs +17 -0
  33. package/test/other/v20.10-import-executable.mjs +8 -0
  34. package/test/register/v18.19-exclude.mjs +15 -0
  35. package/test/register/v18.19-include.mjs +16 -0
  36. package/test/typescript/ts-node.test.mts +10 -2
  37. package/test/other/import-executable.mjs +0 -19
  38. /package/test/{other → fixtures}/executable +0 -0
@@ -0,0 +1,3 @@
1
+ {
2
+ ".": "1.9.0"
3
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## [1.9.0](https://github.com/nodejs/import-in-the-middle/compare/import-in-the-middle-v1.8.1...import-in-the-middle-v1.9.0) (2024-07-08)
4
+
5
+
6
+ ### Features
7
+
8
+ * Allow passing of `include` or `exclude` list via `module.register()` ([#124](https://github.com/nodejs/import-in-the-middle/issues/124)) ([381f48c](https://github.com/nodejs/import-in-the-middle/commit/381f48c07ff755e88495f688c75c4912926194c7))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * CJS `require('.')` resolution ([#108](https://github.com/nodejs/import-in-the-middle/issues/108)) ([29c77b5](https://github.com/nodejs/import-in-the-middle/commit/29c77b560aec0429154632c950923d12db36f79e))
14
+ * Include source url for parsing failures ([#109](https://github.com/nodejs/import-in-the-middle/issues/109)) ([49d69ba](https://github.com/nodejs/import-in-the-middle/commit/49d69ba9e785d4b6a1b38d7da1293cb744b6d7e3))
15
+ * Use `process.emitWarning` to log wrapping errors ([#114](https://github.com/nodejs/import-in-the-middle/issues/114)) ([a3778ac](https://github.com/nodejs/import-in-the-middle/commit/a3778acfbe2220ce5d521232b41da23b4383e1e3))
@@ -0,0 +1,4 @@
1
+ # Code of Conduct
2
+
3
+ The Code of Conduct, which applies to this project, can be found at
4
+ https://github.com/nodejs/admin/blob/HEAD/CODE_OF_CONDUCT.md
package/CONTRIBUTING.md CHANGED
@@ -1,6 +1,34 @@
1
- # Contributing to import-in-the-middle
1
+ # Contributing to `import-in-the-middle`
2
2
 
3
- First of all, thanks for contributing!
3
+ ## Code of Conduct
4
4
 
5
- * If you think you've found an issue, please open a Github issue.
6
- * To propose improvements, feel free to submit a PR.
5
+ Please read the
6
+ [Code of Conduct](https://github.com/nodejs/admin/blob/main/CODE_OF_CONDUCT.md)
7
+ which explains the minimum behavior expectations for `import-in-the-middle` contributors.
8
+
9
+ <a id="developers-certificate-of-origin"></a>
10
+ ## Developer's Certificate of Origin 1.1
11
+
12
+ By making a contribution to this project, I certify that:
13
+
14
+ * (a) The contribution was created in whole or in part by me and I
15
+ have the right to submit it under the open source license
16
+ indicated in the file; or
17
+
18
+ * (b) The contribution is based upon previous work that, to the best
19
+ of my knowledge, is covered under an appropriate open source
20
+ license and I have the right under that license to submit that
21
+ work with modifications, whether created in whole or in part
22
+ by me, under the same open source license (unless I am
23
+ permitted to submit under a different license), as indicated
24
+ in the file; or
25
+
26
+ * (c) The contribution was provided directly to me by some other
27
+ person who certified (a), (b) or (c) and I have not modified
28
+ it.
29
+
30
+ * (d) I understand and agree that this project and the contribution
31
+ are public and that a record of the contribution (including all
32
+ personal information I submit with it, including my sign-off) is
33
+ maintained indefinitely and may be redistributed consistent with
34
+ this project or the open source license(s) involved.
package/GOVERNANCE.md ADDED
@@ -0,0 +1,28 @@
1
+ # `import-in-the-middle` Project Governance
2
+
3
+ ## Collaborators
4
+
5
+ `import-in-the-middle` core collaborators maintain the
6
+ [nodejs/import-in-the-middle](https://github.com/nodejs/import-in-the-middle)
7
+ GitHub repository.
8
+ The GitHub team for `import-in-the-middle` core collaborators is
9
+ [@nodejs/import-in-the-middle-maintainers](https://github.com/orgs/nodejs/teams/import-in-the-middle-maintainers).
10
+ Collaborators have commit access to the
11
+ [nodejs/import-in-the-middle](https://github.com/nodejs/import-in-the-middle)
12
+ repository.
13
+
14
+ Both collaborators and non-collaborators may propose changes to the `import-in-the-middle`
15
+ source code. The mechanism to propose such a change is a GitHub pull request.
16
+ Collaborators review and merge (_land_) pull requests.
17
+
18
+ ## PR Approval
19
+
20
+ Two collaborators must approve a pull request before the pull request can land.
21
+ Approving a pull request indicates that the collaborator accepts responsibility
22
+ for the change. Approval must be from collaborators who are not authors of the
23
+ change and at least one approval must be from a collaborator outside the authors
24
+ direct team.
25
+
26
+ If a collaborator opposes a proposed change, then the change cannot land. Often,
27
+ discussions or further changes result in collaborators removing their
28
+ opposition.
package/LICENSE CHANGED
@@ -1,13 +1,201 @@
1
- Copyright 2021 Datadog, Inc.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
2
4
 
3
- Licensed under the Apache License, Version 2.0 (the "License");
4
- you may not use this file except in compliance with the License.
5
- You may obtain a copy of the License at
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
6
 
7
- http://www.apache.org/licenses/LICENSE-2.0
7
+ 1. Definitions.
8
8
 
9
- Unless required by applicable law or agreed to in writing, software
10
- distributed under the License is distributed on an "AS IS" BASIS,
11
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- See the License for the specific language governing permissions and
13
- limitations under the License.
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE CHANGED
@@ -1,4 +1,34 @@
1
- Datadog import-in-the-middle
2
- Copyright 2021 Datadog, Inc.
1
+ import-in-the-middle is licensed for use as follows:
3
2
 
4
- This product includes software developed at Datadog (https://www.datadoghq.com/).
3
+ Copyright 2024 Node.js contributors. All rights reserved.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ This license applies to parts of import-in-the-middle originating from the
18
+ https://github.com/DataDog/import-in-the-middle repository:
19
+
20
+ This product includes software developed at Datadog (https://www.datadoghq.com/).
21
+
22
+ Copyright 2021 Datadog, Inc.
23
+
24
+ Licensed under the Apache License, Version 2.0 (the "License");
25
+ you may not use this file except in compliance with the License.
26
+ You may obtain a copy of the License at
27
+
28
+ http://www.apache.org/licenses/LICENSE-2.0
29
+
30
+ Unless required by applicable law or agreed to in writing, software
31
+ distributed under the License is distributed on an "AS IS" BASIS,
32
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33
+ See the License for the specific language governing permissions and
34
+ limitations under the License.
package/README.md CHANGED
@@ -38,6 +38,39 @@ command-line option.
38
38
  --loader=import-in-the-middle/hook.mjs
39
39
  ```
40
40
 
41
+ It's also possible to register the loader hook programmatically via the Node
42
+ [`module.register()`](https://nodejs.org/api/module.html#moduleregisterspecifier-parenturl-options)
43
+ API. However, for this to be able to hook non-dynamic imports, it needs to be
44
+ loaded before your app code is evaluated via the `--import` command-line option.
45
+
46
+ `my-loader.mjs`
47
+ ```js
48
+ import * as module from 'module'
49
+
50
+ module.register('import-in-the-middle/hook.mjs', import.meta.url)
51
+ ```
52
+ ```shell
53
+ node --import=./my-loader.mjs ./my-code.mjs
54
+ ```
55
+
56
+ When registering the loader hook programmatically, it's possible to pass a list
57
+ of modules or file URLs to either exclude or specifically include which modules
58
+ are intercepted. This is useful if a module is not compatible with the loader
59
+ hook.
60
+ ```js
61
+ import * as module from 'module'
62
+
63
+ // Exclude intercepting a specific module by name
64
+ module.register('import-in-the-middle/hook.mjs', import.meta.url, {
65
+ data: { exclude: ['package-i-want-to-exclude'] }
66
+ })
67
+
68
+ // Only intercept a specific module by name
69
+ module.register('import-in-the-middle/hook.mjs', import.meta.url, {
70
+ data: { include: ['package-i-want-to-include'] }
71
+ })
72
+ ```
73
+
41
74
  ## Limitations
42
75
 
43
76
  * You cannot add new exports to a module. You can only modify existing ones.
package/hook.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2021 Datadog, Inc.
4
4
 
5
5
  const { URL } = require('url')
6
+ const { inspect } = require('util')
6
7
  const specifiers = new Map()
7
8
  const isWin = process.platform === 'win32'
8
9
 
@@ -115,6 +116,46 @@ function isBareSpecifier (specifier) {
115
116
  }
116
117
  }
117
118
 
119
+ function isBareSpecifierOrFileUrl (input) {
120
+ // Relative and absolute paths
121
+ if (
122
+ input.startsWith('.') ||
123
+ input.startsWith('/')) {
124
+ return false
125
+ }
126
+
127
+ try {
128
+ // eslint-disable-next-line no-new
129
+ const url = new URL(input)
130
+ return url.protocol === 'file:'
131
+ } catch (err) {
132
+ // Anything that fails parsing is a bare specifier
133
+ return true
134
+ }
135
+ }
136
+
137
+ function ensureArrayWithBareSpecifiersAndFileUrls (array, type) {
138
+ if (!Array.isArray(array)) {
139
+ return undefined
140
+ }
141
+
142
+ const invalid = array.filter(s => !isBareSpecifierOrFileUrl(s))
143
+
144
+ if (invalid.length) {
145
+ throw new Error(`'${type}' option only supports bare specifiers and file URLs. Invalid entries: ${inspect(invalid)}`)
146
+ }
147
+
148
+ return array
149
+ }
150
+
151
+ function emitWarning (err) {
152
+ // Unfortunately, process.emitWarning does not output the full error
153
+ // with error.cause like console.warn does so we need to inspect it when
154
+ // tracing warnings
155
+ const warnMessage = process.execArgv.includes('--trace-warnings') ? inspect(err) : err
156
+ process.emitWarning(warnMessage)
157
+ }
158
+
118
159
  /**
119
160
  * Processes a module's exports and builds a set of setter blocks.
120
161
  *
@@ -129,15 +170,32 @@ function isBareSpecifier (specifier) {
129
170
  */
130
171
  async function processModule ({ srcUrl, context, parentGetSource, parentResolve, excludeDefault }) {
131
172
  const exportNames = await getExports(srcUrl, context, parentGetSource)
132
- const duplicates = new Set()
173
+ const starExports = new Set()
133
174
  const setters = new Map()
134
175
 
135
- const addSetter = (name, setter) => {
136
- // When doing an `import *` duplicates become undefined, so do the same
176
+ const addSetter = (name, setter, isStarExport = false) => {
137
177
  if (setters.has(name)) {
138
- duplicates.add(name)
139
- setters.delete(name)
140
- } else if (!duplicates.has(name)) {
178
+ if (isStarExport) {
179
+ // If there's already a matching star export, delete it
180
+ if (starExports.has(name)) {
181
+ setters.delete(name)
182
+ }
183
+ // and return so this is excluded
184
+ return
185
+ }
186
+
187
+ // if we already have this export but it is from a * export, overwrite it
188
+ if (starExports.has(name)) {
189
+ starExports.delete(name)
190
+ setters.set(name, setter)
191
+ }
192
+ } else {
193
+ // Store export * exports so we know they can be overridden by explicit
194
+ // named exports
195
+ if (isStarExport) {
196
+ starExports.add(name)
197
+ }
198
+
141
199
  setters.set(name, setter)
142
200
  }
143
201
  }
@@ -161,10 +219,11 @@ async function processModule ({ srcUrl, context, parentGetSource, parentResolve,
161
219
  srcUrl: modUrl,
162
220
  context,
163
221
  parentGetSource,
222
+ parentResolve,
164
223
  excludeDefault: true
165
224
  })
166
225
  for (const [name, setter] of setters.entries()) {
167
- addSetter(name, setter)
226
+ addSetter(name, setter, true)
168
227
  }
169
228
  } else {
170
229
  addSetter(n, `
@@ -190,11 +249,19 @@ function addIitm (url) {
190
249
  function createHook (meta) {
191
250
  let cachedResolve
192
251
  const iitmURL = new URL('lib/register.js', meta.url).toString()
252
+ let includeModules, excludeModules
253
+
254
+ async function initialize (data) {
255
+ if (data) {
256
+ includeModules = ensureArrayWithBareSpecifiersAndFileUrls(data.include, 'include')
257
+ excludeModules = ensureArrayWithBareSpecifiersAndFileUrls(data.exclude, 'exclude')
258
+ }
259
+ }
193
260
 
194
261
  async function resolve (specifier, context, parentResolve) {
195
262
  cachedResolve = parentResolve
196
263
 
197
- // See github.com/DataDog/import-in-the-middle/pull/76.
264
+ // See github.com/nodejs/import-in-the-middle/pull/76.
198
265
  if (specifier === iitmURL) {
199
266
  return {
200
267
  url: specifier,
@@ -207,14 +274,27 @@ function createHook (meta) {
207
274
  if (isWin && parentURL.indexOf('file:node') === 0) {
208
275
  context.parentURL = ''
209
276
  }
210
- const url = await parentResolve(newSpecifier, context, parentResolve)
211
- if (parentURL === '' && !EXTENSION_RE.test(url.url)) {
212
- entrypoint = url.url
213
- return { url: url.url, format: 'commonjs' }
277
+ const result = await parentResolve(newSpecifier, context, parentResolve)
278
+ if (parentURL === '' && !EXTENSION_RE.test(result.url)) {
279
+ entrypoint = result.url
280
+ return { url: result.url, format: 'commonjs' }
281
+ }
282
+
283
+ // For included/excluded modules, we check the specifier to match libraries
284
+ // that are loaded with bare specifiers from node_modules.
285
+ //
286
+ // For non-bare specifier imports, we only support matching file URL strings
287
+ // because using relative paths would be very error prone!
288
+ if (includeModules && !includeModules.some(lib => lib === specifier || lib === result.url.url)) {
289
+ return result
290
+ }
291
+
292
+ if (excludeModules && excludeModules.some(lib => lib === specifier || lib === result.url.url)) {
293
+ return result
214
294
  }
215
295
 
216
296
  if (isIitm(parentURL, meta) || hasIitm(parentURL)) {
217
- return url
297
+ return result
218
298
  }
219
299
 
220
300
  // Node.js v21 renames importAssertions to importAttributes
@@ -222,38 +302,40 @@ function createHook (meta) {
222
302
  (context.importAssertions && context.importAssertions.type === 'json') ||
223
303
  (context.importAttributes && context.importAttributes.type === 'json')
224
304
  ) {
225
- return url
305
+ return result
226
306
  }
227
307
 
228
308
  // If the file is referencing itself, we need to skip adding the iitm search params
229
- if (url.url === parentURL) {
309
+ if (result.url === parentURL) {
230
310
  return {
231
- url: url.url,
311
+ url: result.url,
232
312
  shortCircuit: true,
233
- format: url.format
313
+ format: result.format
234
314
  }
235
315
  }
236
316
 
237
- specifiers.set(url.url, specifier)
317
+ specifiers.set(result.url, specifier)
238
318
 
239
319
  return {
240
- url: addIitm(url.url),
320
+ url: addIitm(result.url),
241
321
  shortCircuit: true,
242
- format: url.format
322
+ format: result.format
243
323
  }
244
324
  }
245
325
 
246
326
  async function getSource (url, context, parentGetSource) {
247
327
  if (hasIitm(url)) {
248
328
  const realUrl = deleteIitm(url)
249
- const setters = await processModule({
250
- srcUrl: realUrl,
251
- context,
252
- parentGetSource,
253
- parentResolve: cachedResolve
254
- })
255
- return {
256
- source: `
329
+
330
+ try {
331
+ const setters = await processModule({
332
+ srcUrl: realUrl,
333
+ context,
334
+ parentGetSource,
335
+ parentResolve: cachedResolve
336
+ })
337
+ return {
338
+ source: `
257
339
  import { register } from '${iitmURL}'
258
340
  import * as namespace from ${JSON.stringify(realUrl)}
259
341
 
@@ -268,6 +350,25 @@ ${Array.from(setters.values()).join('\n')}
268
350
 
269
351
  register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(realUrl))})
270
352
  `
353
+ }
354
+ } catch (cause) {
355
+ // If there are other ESM loader hooks registered as well as iitm,
356
+ // depending on the order they are registered, source might not be
357
+ // JavaScript.
358
+ //
359
+ // If we fail to parse a module for exports, we should fall back to the
360
+ // parent loader. These modules will not be wrapped with proxies and
361
+ // cannot be Hook'ed but at least this does not take down the entire app
362
+ // and block iitm from being used.
363
+ //
364
+ // We log the error because there might be bugs in iitm and without this
365
+ // it would be very tricky to debug
366
+ const err = new Error(`'import-in-the-middle' failed to wrap '${realUrl}'`)
367
+ err.cause = cause
368
+ emitWarning(err)
369
+
370
+ // Revert back to the non-iitm URL
371
+ url = realUrl
271
372
  }
272
373
  }
273
374
 
@@ -289,9 +390,10 @@ register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(rea
289
390
  }
290
391
 
291
392
  if (NODE_MAJOR >= 17 || (NODE_MAJOR === 16 && NODE_MINOR >= 12)) {
292
- return { load, resolve }
393
+ return { initialize, load, resolve }
293
394
  } else {
294
395
  return {
396
+ initialize,
295
397
  load,
296
398
  resolve,
297
399
  getSource,
package/hook.mjs CHANGED
@@ -4,6 +4,6 @@
4
4
 
5
5
  import { createHook } from './hook.js'
6
6
 
7
- const { load, resolve, getFormat, getSource } = createHook(import.meta)
7
+ const { initialize, load, resolve, getFormat, getSource } = createHook(import.meta)
8
8
 
9
- export { load, resolve, getFormat, getSource }
9
+ export { initialize, load, resolve, getFormat, getSource }
package/index.d.ts CHANGED
@@ -27,7 +27,7 @@ export type Options = {
27
27
  internals?: boolean
28
28
  }
29
29
 
30
- declare class Hook {
30
+ export declare class Hook {
31
31
  /**
32
32
  * Creates a hook to be run on any already loaded modules and any that will
33
33
  * be loaded in the future. It will be run once per loaded module. If