|
3 | 3 | #endif
|
4 | 4 | #include <assert.h>
|
5 | 5 | #include <stdlib.h>
|
| 6 | +#include <string.h> |
6 | 7 | #include "quickjs.h"
|
7 | 8 |
|
8 | 9 | #define MAX_TIME 10
|
@@ -180,12 +181,66 @@ static void is_array(void)
|
180 | 181 | JS_FreeRuntime(rt);
|
181 | 182 | }
|
182 | 183 |
|
| 184 | +static int loader_calls; |
| 185 | + |
| 186 | +static JSModuleDef *loader(JSContext *ctx, const char *name, void *opaque) |
| 187 | +{ |
| 188 | + loader_calls++; |
| 189 | + assert(!strcmp(name, "b")); |
| 190 | + static const char code[] = "export function f(x){}"; |
| 191 | + JSValue ret = JS_Eval(ctx, code, strlen(code), "b", |
| 192 | + JS_EVAL_TYPE_MODULE|JS_EVAL_FLAG_COMPILE_ONLY); |
| 193 | + assert(!JS_IsException(ret)); |
| 194 | + JSModuleDef *m = JS_VALUE_GET_PTR(ret); |
| 195 | + assert(m); |
| 196 | + JS_FreeValue(ctx, ret); |
| 197 | + return m; |
| 198 | +} |
| 199 | + |
| 200 | +static void module_serde(void) |
| 201 | +{ |
| 202 | + JSRuntime *rt = JS_NewRuntime(); |
| 203 | + JS_SetDumpFlags(rt, JS_DUMP_MODULE_RESOLVE); |
| 204 | + JS_SetModuleLoaderFunc(rt, NULL, loader, NULL); |
| 205 | + JSContext *ctx = JS_NewContext(rt); |
| 206 | + static const char code[] = "import {f} from 'b'; f()"; |
| 207 | + assert(loader_calls == 0); |
| 208 | + JSValue mod = JS_Eval(ctx, code, strlen(code), "a", |
| 209 | + JS_EVAL_TYPE_MODULE|JS_EVAL_FLAG_COMPILE_ONLY); |
| 210 | + assert(loader_calls == 1); |
| 211 | + assert(!JS_IsException(mod)); |
| 212 | + assert(JS_IsModule(mod)); |
| 213 | + size_t len = 0; |
| 214 | + uint8_t *buf = JS_WriteObject(ctx, &len, mod, |
| 215 | + JS_WRITE_OBJ_BYTECODE|JS_WRITE_OBJ_REFERENCE); |
| 216 | + assert(buf); |
| 217 | + assert(len > 0); |
| 218 | + JS_FreeValue(ctx, mod); |
| 219 | + assert(loader_calls == 1); |
| 220 | + mod = JS_ReadObject(ctx, buf, len, JS_READ_OBJ_BYTECODE); |
| 221 | + free(buf); |
| 222 | + assert(loader_calls == 1); // 'b' is returned from cache |
| 223 | + assert(!JS_IsException(mod)); |
| 224 | + JSValue ret = JS_EvalFunction(ctx, mod); |
| 225 | + assert(!JS_IsException(ret)); |
| 226 | + assert(JS_IsPromise(ret)); |
| 227 | + JSValue result = JS_PromiseResult(ctx, ret); |
| 228 | + assert(!JS_IsException(result)); |
| 229 | + assert(JS_IsUndefined(result)); |
| 230 | + JS_FreeValue(ctx, result); |
| 231 | + JS_FreeValue(ctx, ret); |
| 232 | + JS_FreeValue(ctx, mod); |
| 233 | + JS_FreeContext(ctx); |
| 234 | + JS_FreeRuntime(rt); |
| 235 | +} |
| 236 | + |
183 | 237 | int main(void)
|
184 | 238 | {
|
185 | 239 | sync_call();
|
186 | 240 | async_call();
|
187 | 241 | async_call_stack_overflow();
|
188 | 242 | raw_context_global_var();
|
189 | 243 | is_array();
|
| 244 | + module_serde(); |
190 | 245 | return 0;
|
191 | 246 | }
|
0 commit comments