lukeed / tsm

TypeScript Module Loader
MIT License
1.18k stars 19 forks source link

Doesn't handle package.json `imports` field #45

Open deecewan opened 1 year ago

deecewan commented 1 year ago

the chalk uses imports in the package.json. these start with a #. I'm not sure of the full semantics of how this "should" work. It might be as simple as switching this:

- if (/^\w+\:?/.test(ident)) return fallback(ident, context, fallback);
+ if (/^(\w+\:?|#)/.test(ident)) return fallback(ident, context, fallback);

but that might be too naive to work in every case.

It seems to be because the check function calls fileURLToPath from url, which strips the # and following text, meaning that the check function ends up just checking if the parentURL exists.

I think the full solution to this would be to, if there's a # at the start of the import, call fallback and then process the result of fallback, as it might resolve to a typescript file. It might be enough to just ignore any # files and assume that the package exposing them is not using typescript?

Repro Steps

you'll see

file:///<folder>/imports-repro/node_modules/chalk/source/index.js#supports-color.mts:7
const { stdout: stdoutColor, stderr: stderrColor } = supportsColor;
                ^

TypeError: Cannot destructure property 'stdout' of 'supportsColor' as it is undefined.
    at file:///<folder>/imports-repro/node_modules/chalk/source/index.js#supports-color.mts:7:17
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:527:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)
marcomontalbano commented 7 months ago

I've the same issue with p-limit.

file:///<folder>/imports-repro/node_modules/p-limit/index.js#async_hooks.mts:2
import { AsyncResource } from "#async_hooks";
         ^^^^^^^^^^^^^
SyntaxError: The requested module '#async_hooks' does not provide an export named 'AsyncResource'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async ModuleJob.run (node:internal/modules/esm/module_job:190:5)