Skip to content

re-implement module.register() on top of module.registerHooks() #59666

@joyeecheung

Description

@joyeecheung

This was an idea discussed in the loaders group a few times in the past as well as in the last collaboration summit. Opening an issue to track it properly.

The high-level idea is something like this:

module.register = function(specifier, parentURL, options) {
  loader.hooksProxy.makeSyncRequest('register', specifier, parentURL, options);
  module.registerHooks({
    resolve(specifier, context, nextResolve) {
      const result = loader.hooksProxy.makeSyncRequest('resolve', specifier, context);
      return result.shortCircuit ? result : nextResolve(specifier, context);
    }
    load(url, context, nextLoad) {
      const result = loader.hooksProxy.makeSyncRequest('load', url, context);
      return result.shortCircuit ? result : nextLoad(url, context);
    }
  });
}

Then we will be able to:

  1. Eliminate the races in ESM cache handling when require(esm) needs the linking to be synchronous but import esm may populate an asynchronous linking job in the cache. There were multiple band-aids applied to work around this, like esm: link modules synchronously when no async loader hooks are used #59519 and module: handle cached linked async jobs in require(esm) #57187, but to fully eliminate the races, this would be necessary to finish Tracking Issue: Syncify the ESM Loader #55782
  2. Go back to using the authentic require() in imported CJS instead of re-inventing a separate require() and eliminate its quirks, which currently includes
  3. Potentially this means module.register can be a user-land helper that we can publish as a separate npm package and version independently.

Refs: #57327
Refs: #55808
Refs: #52697
Refs: #56241
Refs: #55782

cc @nodejs/loaders

Metadata

Metadata

Assignees

No one assigned

    Labels

    loadersIssues and PRs related to ES module loaders

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions