added JSON modules and import attributes

This commit is contained in:
Fabrice Bellard
2025-05-20 18:27:23 +02:00
parent 838124580b
commit f10ef299a6
10 changed files with 424 additions and 100 deletions

View File

@@ -836,13 +836,21 @@ static char *load_file(const char *filename, size_t *lenp)
return buf;
}
static int json_module_init_test(JSContext *ctx, JSModuleDef *m)
{
JSValue val;
val = JS_GetModulePrivateValue(ctx, m);
JS_SetModuleExport(ctx, m, "default", val);
return 0;
}
static JSModuleDef *js_module_loader_test(JSContext *ctx,
const char *module_name, void *opaque)
const char *module_name, void *opaque,
JSValueConst attributes)
{
size_t buf_len;
uint8_t *buf;
JSModuleDef *m;
JSValue func_val;
char *filename, *slash, path[1024];
// interpret import("bar.js") from path/to/foo.js as
@@ -864,15 +872,33 @@ static JSModuleDef *js_module_loader_test(JSContext *ctx,
return NULL;
}
/* compile the module */
func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,
JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
js_free(ctx, buf);
if (JS_IsException(func_val))
return NULL;
/* the module is already referenced, so we must free it */
m = JS_VALUE_GET_PTR(func_val);
JS_FreeValue(ctx, func_val);
if (js_module_test_json(ctx, attributes)) {
/* compile as JSON */
JSValue val;
val = JS_ParseJSON(ctx, (char *)buf, buf_len, module_name);
js_free(ctx, buf);
if (JS_IsException(val))
return NULL;
m = JS_NewCModule(ctx, module_name, json_module_init_test);
if (!m) {
JS_FreeValue(ctx, val);
return NULL;
}
/* only export the "default" symbol which will contain the JSON object */
JS_AddModuleExport(ctx, m, "default");
JS_SetModulePrivateValue(ctx, m, val);
} else {
JSValue func_val;
/* compile the module */
func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,
JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
js_free(ctx, buf);
if (JS_IsException(func_val))
return NULL;
/* the module is already referenced, so we must free it */
m = JS_VALUE_GET_PTR(func_val);
JS_FreeValue(ctx, func_val);
}
return m;
}
@@ -1587,7 +1613,7 @@ int run_test_buf(const char *filename, const char *harness, namelist_t *ip,
JS_SetCanBlock(rt, can_block);
/* loader for ES6 modules */
JS_SetModuleLoaderFunc(rt, NULL, js_module_loader_test, (void *)filename);
JS_SetModuleLoaderFunc2(rt, NULL, js_module_loader_test, NULL, (void *)filename);
add_helpers(ctx);
@@ -1888,7 +1914,7 @@ int run_test262_harness_test(const char *filename, BOOL is_module)
JS_SetCanBlock(rt, can_block);
/* loader for ES6 modules */
JS_SetModuleLoaderFunc(rt, NULL, js_module_loader_test, (void *)filename);
JS_SetModuleLoaderFunc2(rt, NULL, js_module_loader_test, NULL, (void *)filename);
add_helpers(ctx);