shims broken when import order cannot be guaranteed
versions:
- node: v22.14.0
- @mux/mux-node: v11.0.0, v11.0.1, and v11.0.2
- dd-trace: 5.45.0
- import-in-the-middle: 1.13.1
Example code:
// test.mjs
import Mux from '@mux/mux-node';
This works with all versions of mux:
node test.mjs
This works with mux v10, but fails with mux v11:
node --import dd-trace/register.js test.mjs
file:///home/mike/work/rocky-api/node_modules/@mux/mux-node/_shims/registry.mjs:17
throw new Error(`you must \`import '@mux/mux-node/shims/${shims.kind}'\` before importing anything else from @mux/mux-node`);
^
Error: you must `import '@mux/mux-node/shims/node'` before importing anything else from @mux/mux-node
at Module.setShims (file:///home/mike/work/rocky-api/node_modules/@mux/mux-node/_shims/registry.mjs:17:15)
at init (file:///home/mike/work/rocky-api/node_modules/@mux/mux-node/_shims/index.mjs:7:26)
at file:///home/mike/work/rocky-api/node_modules/@mux/mux-node/core.mjs:17:1
at ModuleJob.run (node:internal/modules/esm/module_job:271:25)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:578:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:116:5)
Node.js v22.14.0
Adding import '@mux/mux-node/shims/node'; before the other import in test.mjs results in:
Error: can't `import '@mux/mux-node/shims/node'` after `import '@mux/mux-node/shims/node'`
EDIT: The root issue seems to come from the fact that the datadog custom module loader does not guarantee module import order. I have updated the issue title and expanded on this in the comment below.
Seems the same kind of issue also exists in v10. When calling video.assets.create():
TypeError getDefaultAgent is not a function
node_modules/@mux/mux-node/src/core.ts:283:62 Mux.buildRequest
node_modules/@mux/mux-node/src/core.ts:416:40 Mux.makeRequest
node:internal/process/task_queues:105:5 process.processTicksAndRejections
src/app/tasks/taskRunners/finalizeAudioAssetTaskRunner.ts:86:22 async Object.handler
src/app/tasks/taskMaster.ts:447:11 async <anonymous>
The shimming seems to rely on import side effects and import order, both of which are considered bad practice. Especially given Mux supports CJS and ESM which have varying rules regarding import and execution order (order was not guaranteed pre-ES2020). Though, I certainly understand the value and desire to have a simple import interface which auto-magically supports various environments and is globally configured.
Would is be possible to provide an import/shortcut to skip shimming and pollyfilling entirely? The dependency injection methods could be used instead, and it provides a solution for edge cases in which import order can not be guaranteed. Such as certain transpilers/bundlers which may reorder and my use case of a custom module loader.