Skip to content

[feature request] async es module loader #191

Open

Description

@codehz

async module loader is useful for loading code from network, or requiring execute external process like esbuild/swc
since this fork is already support top level await, it can be (partially) implemented in pure js (aka add an fake source for async module which will await an unresolved promise) but I think it would be better if add an the module loader interface which can do this without the workaround

Activity

  1. added
    enhancement
    on Dec 9, 2023
  2. bnoordhuis commented on Dec 9, 2023

    @bnoordhuis
    Contributor

    It's easier to discuss details if you can give a quick sketch of what you think the C API should look like and how it would be used.

  3. saghul commented on Dec 9, 2023

    @saghul
    Contributor

    IIRC the main problem is the module loader must populate a JSModuleDef as it's called, you can't perform an async operation and call some API to complete it later.

  4. codehz commented on Dec 10, 2023

    @codehz
    Author

    quick sketch

    ref
    https://html.spec.whatwg.org/#hostloadimportedmodule
    https://tc39.es/ecma262/#sec-HostLoadImportedModule
    https://tc39.es/proposal-import-attributes/#importattribute-record

    HostLoadImportedModule(referrer, moduleRequest, loadState, payload)
    FinishLoadingImportedModule(referrer, moduleRequest, payload, result)

    typedef enum JSModuleLoadingResultEnum {
        JS_ASYNC_MODULE_SYNC,
        JS_ASYNC_MODULE_ASYNC
    } JSModuleLoadingResultEnum;
    
    // also reserve the import attribute struct for future extend
    // to support something like `import { main } from './foo.wasm' with { type: "webassembly" }`
    // or `import { xyz } 'xyz.ts' with { type: "typescript", compiler: "tsc" }`
    typedef struct JSImportAttribute {
        char *key; /* 0 if end */
        JSValue value;
    } JSImportAttribute;
    
    typedef struct JSModuleRequest {
        char *specifier;
        JSImportAttribute *attributes;
    } JSModuleRequest;
    
    typedef JSModuleLoadingResultEnum JSModuleLoaderFunc2(
        JSContext *ctx,
        const char *module_name,
        /* only be used in sync mode */ JSModuleDef** out_sync_module_def,
        void *opaque);
    
    // Changed the normalize function to allow serialize import attribute array into string
    typedef char *JSModuleNormalizeFunc2(JSContext *ctx,
        const char *referrer,
        const JSModuleRequest* request,
        void *opaque);
    
    void JS_SetModuleLoaderFunc2(JSRuntime *rt,
      JSModuleNormalizeFunc2 *module_normalize,
      JSModuleLoaderFunc2 *module_loader, void *opaque);
    
    // used when JSModuleLoaderFunc2 returns JS_ASYNC_MODULE_ASYNC
    void JS_FinishLoadingModule(JSRuntime *rt,
        const char *module_name,
        // null if failed
        JSModuleDef *module_def);
  5. bnoordhuis commented on Dec 10, 2023

    @bnoordhuis
    Contributor

    So the ask is to make the module loader interruptible? More specifically, that the JSModuleLoaderfunc callback can somehow signal that it will complete at a later time?

    I'm not saying 'no' outright but I expect it will be a big effort, with lots of edge cases that need dealing with, like should JS_Eval(JS_EVAL_TYPE_MODULE) return some kind of sentinel when it can't continue?


    Maybe an easier way forward is to have a special parse mode for modules that doesn't evaluate the module but returns its imports (and maybe exports?)

    Then you fetch and parse its imports in the same way (and those imports' imports, etc.) until you're done and evaluate everything.

  6. codehz commented on Dec 10, 2023

    @codehz
    Author

    btw, I found current implementation is actually cannot handle top-level-await in module... so no js workaround at first place....

    Maybe an easier way forward is to have a special parse mode for modules that doesn't evaluate the module but returns its imports (and maybe exports?)

    it sounds good, and I think it should be able to handle dynamic import too

  7. codehz commented on Dec 10, 2023

    @codehz
    Author

    Maybe an easier way forward is to have a special parse mode for modules that doesn't evaluate the module but returns its imports (and maybe exports?)

    ref: https://tc39.es/ecma262/#sec-source-text-module-records

    actually I think it is how most of existing js engine works, two pass for esm, resolve module is first pass (InitializeEnvironment() 1), eval is second part (ExecuteModule() 2)

    Footnotes

    1. https://tc39.es/ecma262/#sec-source-text-module-record-initialize-environment ↩

    2. https://tc39.es/ecma262/#sec-source-text-module-record-execute-module ↩

  8. codehz commented on Dec 10, 2023

    @codehz
    Author

    but I suggest to create a new api for module loading and eval. not just reuse JS_Eval, so we can avoid parse code twice...

    maybe a dedicated JS_LoadModule which only return module records (contains import and export information, and set unresolved module as null, let caller to filling the gap), and JS_EvalModule to execute the resolved module (I known the old JS_Eval has module mode, but the api is only accept js source code)

    a possible user code for sync module loading would be:

    // not JS_ModuleDef since it cannot be same structure
    JS_ModuleRecord *record = JS_LoadModuleRecord(rt, file);
    
    /* "link" the module */
    // use c++ ranged loop as pesudo code
    for (JS_ModuleImportInfo *it : record->imports) {
      JS_ModuleRecord *dependentModule = UserCode_ResolveImport(record->specifier, record->attributes);
      it->resolved = dependentModule;
    }
    
    JS_EvalModule(rt, record);
  9. bnoordhuis commented on Dec 10, 2023

    @bnoordhuis
    Contributor

    so we can avoid parse code twice

    That can't be avoided but the upside is it only needs to run the first pass of the three parse/code-gen passes. Maybe we can keep the pass 1 bytecode around, maybe not.

    it should be able to handle dynamic import too

    Only dynamic imports where the path is a static string. That's so restricting it probably isn't worth bothering with though.

  10. codehz commented on Dec 10, 2023

    @codehz
    Author

    Only dynamic imports where the path is a static string. That's so restricting it probably isn't worth bothering with though

    but dynamic import is already return a promise, I mean it is possible to change the behavior for dynamic import...

    static JSValue js_dynamic_import_job(JSContext *ctx,
                                         int argc, JSValueConst *argv)
    {
        JSValueConst *resolving_funcs = argv;
        JSValueConst basename_val = argv[2];
        JSValueConst specifier = argv[3];
        JSModuleDef *m;
        const char *basename = NULL, *filename;
        JSValue ret, err, ns;
    
        if (!JS_IsString(basename_val)) {
            JS_ThrowTypeError(ctx, "no function filename for import()");
            goto exception;
        }
        basename = JS_ToCString(ctx, basename_val);
        if (!basename)
            goto exception;
    
        filename = JS_ToCString(ctx, specifier);
        if (!filename)
            goto exception;
    
        m = JS_RunModule(ctx, basename, filename); // change that to be allow async
        JS_FreeCString(ctx, filename);
        if (!m)
            goto exception;
    
        /* return the module namespace */
        ns = js_get_module_ns(ctx, m);
        if (JS_IsException(ns))
            goto exception;
    
        if (!JS_IsUndefined(m->promise)) {
            JSValueConst args[] = {argv[0], argv[1], ns};
            JSValueConst funcs[2];
            funcs[0] = JS_NewCFunctionData(ctx, js_dynamic_import_resolve, 0, 0, 3, args);
            funcs[1] = JS_NewCFunctionData(ctx, js_dynamic_import_reject, 0, 0, 3, args);
            JS_FreeValue(ctx, js_promise_then(ctx, m->promise, 2, funcs));
    
            JS_FreeValue(ctx, (JSValue)funcs[0]);
            JS_FreeValue(ctx, (JSValue)funcs[1]);
            JS_FreeValue(ctx, ns);
            JS_FreeCString(ctx, basename);
    
            return JS_UNDEFINED;
        }
    
        ret = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED,
                       1, (JSValueConst *)&ns);
        JS_FreeValue(ctx, ret); /* XXX: what to do if exception ? */
        JS_FreeValue(ctx, ns);
        JS_FreeCString(ctx, basename);
        return JS_UNDEFINED;
     exception:
    
        err = JS_GetException(ctx);
        ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED,
                       1, (JSValueConst *)&err);
        JS_FreeValue(ctx, ret); /* XXX: what to do if exception ? */
        JS_FreeValue(ctx, err);
        JS_FreeCString(ctx, basename);
        return JS_UNDEFINED;
    }
  11. bnoordhuis commented on Dec 10, 2023

    @bnoordhuis
    Contributor

    I think you're confusing parsing and execution:

    • dynamic imports are done when bytecode is executed (and they have in fact their own opcode, OP_import)

    • my suggestion for non-dynamic imports is a static analysis pass; no bytecode executes

  12. codehz commented on Dec 10, 2023

    @codehz
    Author
    • my suggestion for non-dynamic imports is a static analysis pass; no bytecode executes

    ok, thats make sense (for static analysis pass), but my suggestion is also change the js_dynamic_import_job to allow async import too
    aka allow customize how js_dynamic_import is execute, current implementation is just call JS_RunModule(ctx, basename, filename); in js_dynamic_import_job, which will only works with sync module loading mode

  13. bnoordhuis commented on Dec 10, 2023

    @bnoordhuis
    Contributor

    Okay, but that's something of an orthogonal issue. It'd be best to open a new issue so it can be tracked separately.

  14. karlseguin commented on Oct 17, 2025

    @karlseguin
    Contributor

    moved my comment to #196

  15. bnoordhuis commented on Oct 17, 2025

    @bnoordhuis
    Contributor

    @karlseguin that's #196, this issue is about static imports.

  16. nakisen commented on Nov 20, 2026

    @nakisen

    Picking up @bnoordhuis's suggestion from earlier in this thread: a parse mode for modules that returns their imports without resolving them.

    #1860 made dynamic import() asynchronous, which is great. Static imports still go through the synchronous JSModuleLoaderFunc, though, and the header comment for JSDynamicImportFunc (step 6) says as much: the module a dynamic import fetches pulls in its own static graph through that loader. An embedder that fetches modules over a network, such as a development server that serves an application as hundreds of separate modules, therefore has to either block in the loader once per module or know a module's imports before it is linked. There is no way to get that today:

    • JS_EVAL_FLAG_COMPILE_ONLY still resolves. __JS_EvalInternal calls js_resolve_module() before it tests the flag (with the comment "Could add a flag to avoid resolution if necessary"), so the loader runs during a compile-only call. qjsc relies on that behaviour to walk the graph, so changing the existing flag isn't an option.
    • The requested specifiers live in JSModuleDef.req_module_entries, which is private.

    Proposed API

    /* With JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY: compile the module
       but do not resolve its imports; the module loader is not called. */
    #define JS_EVAL_FLAG_NO_RESOLVE (1 << 8)   /* or the next free bit */
    
    /* The import requests of a compiled module value, in source order.
       The name is the specifier as written, before normalization. */
    JS_EXTERN int     JS_GetModuleRequestCount(JSContext *ctx, JSValueConst module);
    JS_EXTERN JSAtom  JS_GetModuleRequestName(JSContext *ctx, JSValueConst module, int index);
    JS_EXTERN JSValue JS_GetModuleRequestAttributes(JSContext *ctx, JSValueConst module, int index);

    How it would be used

    1. Compile the entry module with JS_EVAL_FLAG_NO_RESOLVE and read its requests.
    2. Normalize each specifier, fetch the sources asynchronously (in parallel), and compile each one the same way under its normalized name. Repeat until the graph is complete.
    3. Call the existing JS_ResolveModule() on the entry module, then evaluate it.

    Step 3 needs no further change: js_host_resolve_imported_module() already looks a normalized name up in ctx->loaded_modules before it calls the loader, and every compiled module is in that list. The loader is then only reached for a module the embedder failed to fetch.

    The same functions would let a JSDynamicImportFunc fetch a dynamically imported module's whole static graph before it calls JS_LoadModule().

    If this shape looks acceptable, I'm happy to send a PR with tests (cycles, import attributes, a module that fails to compile half-way through the graph). Names and the choice between an eval flag and a new JSEvalOptions field are open to whatever you prefer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions