pkgjs / parseargs

Polyfill of `util.parseArgs()`
Apache License 2.0
122 stars 10 forks source link

parseArgs in runtimes where `global` is not defined #157

Closed kisaragi-hiu closed 1 month ago

kisaragi-hiu commented 1 month ago

This module is useful as a polyfill for older Node versions. But it could also be useful for other runtimes, such as gjs, that may not want to implement a Node compatibility layer but nevertheless would find a good argument parser helpful.

Right now this module appears to polyfill a bunch of Node internal functions by modifying global (such as in internal/primordials.js). This is fine, even preferrable, when it was to be included in Node, but as a standalone library this has two problems:

  1. This pollutes the global namespace, which is inappropriate in non-Node contexts. A hypothetical case is someone wanting to emulate command parsing in the browser and utilizing this library - which works, but their namespace is now polluted.
  2. This doesn't work in some runtimes. Some runtimes do not have global (generally they have globalThis though), so the modification of global means this library just doesn't work there, even though it could.

    My actual use case is that I'm making a command line program with gjs (to make use of GLib). parseArgs({args: ARGV, options: {...}}) would work wonders there, but the polyfilling behavior prevents it from working. (ARGV is gjs's equivelant to process.argv.slice(2))

    Runtimes that have some use and don't have global:

This can be fixed by either:

kisaragi-hiu commented 1 month ago

Since globalThis was added in Node 12 and this package requires Node 14+, and since internal/primordials.js even already depends on globalThis existing, internal/primordials.js could just be patched to always use globalThis. This wouldn't solve the namespace pollution, but it does make this library work on gjs.

shadowspawn commented 1 month ago

Right now this module appears to polyfill a bunch of Node internal functions...

Historical note: this was to make it easy for submitting parseArgs to Node.js, rather than a fully-functional polyfill of those internals.

ljharb commented 1 month ago

although a non-broken browser bundler must always transform global into window, it’s fine to change it to use globalThis for server runtimes, given our engines declaration.