Class: Quickjs::VM

Inherits:
Object
  • Object
show all
Defined in:
lib/quickjs/runnable.rb,
ext/quickjsrb/quickjsrb.c

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Object



1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
# File 'ext/quickjsrb/quickjsrb.c', line 1020

static VALUE vm_m_initialize(int argc, VALUE *argv, VALUE r_self)
{
  VALUE r_opts;
  rb_scan_args(argc, argv, ":", &r_opts);
  if (NIL_P(r_opts))
    r_opts = rb_hash_new();

  VALUE r_memory_limit = rb_hash_aref(r_opts, ID2SYM(rb_intern("memory_limit")));
  if (NIL_P(r_memory_limit))
    r_memory_limit = UINT2NUM(1024 * 1024 * 128);
  VALUE r_max_stack_size = rb_hash_aref(r_opts, ID2SYM(rb_intern("max_stack_size")));
  if (NIL_P(r_max_stack_size))
    r_max_stack_size = UINT2NUM(1024 * 1024 * 4);
  VALUE r_features = rb_hash_aref(r_opts, ID2SYM(rb_intern("features")));
  if (NIL_P(r_features))
    r_features = rb_ary_new();
  VALUE r_timeout_msec = rb_hash_aref(r_opts, ID2SYM(rb_intern("timeout_msec")));
  if (NIL_P(r_timeout_msec))
    r_timeout_msec = UINT2NUM(100);

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  data->eval_time->limit_ms = (int64_t)NUM2UINT(r_timeout_msec);
  JS_SetContextOpaque(data->context, data);
  JSRuntime *runtime = JS_GetRuntime(data->context);

  JS_SetMemoryLimit(runtime, NUM2UINT(r_memory_limit));
  JS_SetMaxStackSize(runtime, NUM2UINT(r_max_stack_size));

  register_module_loader_funcs(data);
  JS_SetHostPromiseRejectionTracker(runtime, quickjsrb_promise_rejection_tracker, NULL);
  js_std_init_handlers(runtime);

  JSValue j_global = JS_GetGlobalObject(data->context);

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featureStdId))))
  {
    js_init_module_std(data->context, "std");
    const char *enableStd = "import * as std from 'std';\n"
                            "globalThis.std = std;\n";
    JSValue j_stdEval = JS_Eval(data->context, enableStd, strlen(enableStd), vmInternalFilename, JS_EVAL_TYPE_MODULE);
    JS_FreeValue(data->context, j_stdEval);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featureOsId))))
  {
    js_init_module_os(data->context, "os");
    const char *enableOs = "import * as os from 'os';\n"
                           "globalThis.os = os;\n";
    JSValue j_osEval = JS_Eval(data->context, enableOs, strlen(enableOs), vmInternalFilename, JS_EVAL_TYPE_MODULE);
    JS_FreeValue(data->context, j_osEval);
  }
  else if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featureTimeoutId))))
  {
    JS_SetPropertyStr(
        data->context, j_global, "setTimeout",
        JS_NewCFunction(data->context, js_quickjsrb_set_timeout, "setTimeout", 2));
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillIntlId))))
  {
    const char *defineIntl = "Object.defineProperty(globalThis, 'Intl', { value:{} });\n";
    JSValue j_defineIntl = JS_Eval(data->context, defineIntl, strlen(defineIntl), vmInternalFilename, JS_EVAL_TYPE_GLOBAL);
    JS_FreeValue(data->context, j_defineIntl);

    JSValue j_polyfillIntlResult = load_polyfill_bytecode(data->context, &qjsc_polyfill_intl_en_min, qjsc_polyfill_intl_en_min_size);
    JS_FreeValue(data->context, j_polyfillIntlResult);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillFileId))))
  {
    JSValue j_polyfillFileResult = load_polyfill_bytecode(data->context, &qjsc_polyfill_file_min, qjsc_polyfill_file_min_size);
    JS_FreeValue(data->context, j_polyfillFileResult);

    quickjsrb_init_file_proxy(data);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillEncodingId))))
  {
    JSValue j_polyfillEncodingResult = load_polyfill_bytecode(data->context, &qjsc_polyfill_encoding_min, qjsc_polyfill_encoding_min_size);
    JS_FreeValue(data->context, j_polyfillEncodingResult);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillUrlId))))
  {
    JSValue j_polyfillUrlResult = load_polyfill_bytecode(data->context, &qjsc_polyfill_url_min, qjsc_polyfill_url_min_size);
    JS_FreeValue(data->context, j_polyfillUrlResult);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillCryptoId))))
  {
    quickjsrb_init_crypto(data->context, j_global);
  }

  // Host callbacks (console, setTimeout, Ruby-bridged functions) are
  // registered below this point — after all polyfill loading above.
  // load_polyfill_bytecode releases the GVL; any code moved above this
  // line that touches Ruby APIs must re-acquire it first.
  JSValue j_console = JS_NewObject(data->context);
  JS_SetPropertyStr(
      data->context, j_console, "log",
      JS_NewCFunction(data->context, js_console_info, "log", 1));
  JS_SetPropertyStr(
      data->context, j_console, "debug",
      JS_NewCFunction(data->context, js_console_verbose, "debug", 1));
  JS_SetPropertyStr(
      data->context, j_console, "info",
      JS_NewCFunction(data->context, js_console_info, "info", 1));
  JS_SetPropertyStr(
      data->context, j_console, "warn",
      JS_NewCFunction(data->context, js_console_warn, "warn", 1));
  JS_SetPropertyStr(
      data->context, j_console, "error",
      JS_NewCFunction(data->context, js_console_error, "error", 1));

  JS_SetPropertyStr(data->context, j_global, "console", j_console);
  JS_FreeValue(data->context, j_global);

  return r_self;
}

Instance Method Details

#call(*args) ⇒ Object



1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
# File 'ext/quickjsrb/quickjsrb.c', line 1444

static VALUE vm_m_callGlobalFunction(int argc, VALUE *argv, VALUE r_self)
{
  if (argc < 1)
    rb_raise(rb_eArgError, "wrong number of arguments (given 0, expected 1+)");

  VALUE r_name = argv[0];

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  check_disposed(data);
  check_oom_poisoned(data);

  JSValue j_this = JS_UNDEFINED;
  JSValue j_func;

  VALUE r_path;
  if (SYMBOL_P(r_name) || RB_TYPE_P(r_name, T_STRING))
  {
    VALUE r_name_str = rb_funcall(r_name, rb_intern("to_s"), 0);
    const char *name_str = StringValueCStr(r_name_str);
    size_t name_len = strlen(name_str);
    const char *last_bracket = strrchr(name_str, '[');
    const char *last_dot = strrchr(name_str, '.');

    if (last_bracket != NULL && last_bracket != name_str && name_str[name_len - 1] == ']')
    {
      // Bracket notation: 'a["key"]' or 'a.b["key"]' or 'a[0]'
      // Split into parent expression and the bracketed key
      VALUE r_parent = rb_str_new(name_str, last_bracket - name_str);
      const char *key_start = last_bracket + 1;
      size_t key_len = name_len - (key_start - name_str) - 1; // exclude ']'
      // Strip surrounding quotes for string keys: 'a["b"]' → key = b
      if (key_len >= 2 &&
          ((key_start[0] == '\'' && key_start[key_len - 1] == '\'') ||
           (key_start[0] == '"' && key_start[key_len - 1] == '"')))
      {
        key_start++;
        key_len -= 2;
      }
      VALUE r_key = rb_str_new(key_start, key_len);
      r_path = rb_ary_new3(2, r_parent, r_key);
    }
    else if (last_dot != NULL && last_dot != name_str)
    {
      // Dot notation: 'a.b.c' → ['a.b', 'c'] so the parent becomes `this`
      VALUE r_parent = rb_str_new(name_str, last_dot - name_str);
      VALUE r_key = rb_str_new2(last_dot + 1);
      r_path = rb_ary_new3(2, r_parent, r_key);
    }
    else
    {
      r_path = rb_ary_new3(1, r_name_str);
    }
  }
  else
  {
    rb_raise(rb_eTypeError, "function's name should be a Symbol or a String");
  }

  {
    long path_len = RARRAY_LEN(r_path);

    VALUE r_first = RARRAY_AREF(r_path, 0);
    if (!(SYMBOL_P(r_first) || RB_TYPE_P(r_first, T_STRING)))
      rb_raise(rb_eTypeError, "function path elements should be Symbols or Strings");

    VALUE r_first_str = rb_funcall(r_first, rb_intern("to_s"), 0);
    const char *first_seg = StringValueCStr(r_first_str);

    // JS_Eval accesses both global object properties and lexical (const/let) bindings
    JSValue j_cur = JS_Eval(data->context, first_seg, strlen(first_seg), vmInternalFilename, JS_EVAL_TYPE_GLOBAL);
    if (JS_IsException(j_cur))
      return to_rb_value(data->context, j_cur); // raises

    for (long i = 1; i < path_len; i++)
    {
      VALUE r_seg = RARRAY_AREF(r_path, i);
      if (!(SYMBOL_P(r_seg) || RB_TYPE_P(r_seg, T_STRING)))
      {
        JS_FreeValue(data->context, j_cur);
        JS_FreeValue(data->context, j_this);
        rb_raise(rb_eTypeError, "function path elements should be Symbols or Strings");
      }
      VALUE r_seg_str = rb_funcall(r_seg, rb_intern("to_s"), 0);
      const char *seg = StringValueCStr(r_seg_str);

      JSValue j_next = JS_GetPropertyStr(data->context, j_cur, seg);
      if (JS_IsException(j_next))
      {
        JS_FreeValue(data->context, j_cur);
        JS_FreeValue(data->context, j_this);
        return to_rb_value(data->context, j_next); // raises
      }

      JS_FreeValue(data->context, j_this);
      j_this = j_cur;
      j_cur = j_next;
    }

    j_func = j_cur;
  }

  if (!JS_IsFunction(data->context, j_func))
  {
    JS_FreeValue(data->context, j_func);
    JS_FreeValue(data->context, j_this);
    VALUE r_error_message = rb_str_new2("given path is not a function");
    rb_exc_raise(rb_funcall(QUICKJSRB_ERROR_FOR(QUICKJSRB_ROOT_RUNTIME_ERROR), rb_intern("new"), 2, r_error_message, Qnil));
    return Qnil;
  }

  int nargs = argc - 1;
  JSValue *j_args = NULL;
  if (nargs > 0)
  {
    j_args = (JSValue *)malloc(sizeof(JSValue) * nargs);
    for (int i = 0; i < nargs; i++)
      j_args[i] = to_js_value(data->context, argv[i + 1]);
  }

  clock_gettime(CLOCK_MONOTONIC, &data->eval_time->started_at);
  JS_SetInterruptHandler(JS_GetRuntime(data->context), interrupt_handler, data->eval_time);

  JSValue j_result = JS_Call(data->context, j_func, j_this, nargs, (JSValueConst *)j_args);

  JS_FreeValue(data->context, j_func);
  JS_FreeValue(data->context, j_this);
  if (j_args)
  {
    for (int i = 0; i < nargs; i++)
      JS_FreeValue(data->context, j_args[i]);
    free(j_args);
  }

  // js_std_await handles both async (promise) and sync results; frees j_result
  return to_rb_return_value(data->context, js_std_await(data->context, j_result));
}

#compile(source, **opts) ⇒ Object



19
20
21
# File 'lib/quickjs/runnable.rb', line 19

def compile(source, **opts)
  Runnable.new(send(:_compile_to_bytecode, source, **opts))
end

#define_function(*args) ⇒ Object



1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
# File 'ext/quickjsrb/quickjsrb.c', line 1320

static VALUE vm_m_defineGlobalFunction(int argc, VALUE *argv, VALUE r_self)
{
  rb_need_block();

  VALUE r_name;
  VALUE r_flags;
  VALUE r_block;
  rb_scan_args(argc, argv, "10*&", &r_name, &r_flags, &r_block);

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  check_disposed(data);

  if (RB_TYPE_P(r_name, T_ARRAY))
  {
    long path_len = RARRAY_LEN(r_name);
    if (path_len < 1)
      rb_raise(rb_eArgError, "function's path array must not be empty");

    for (long i = 0; i < path_len; i++)
    {
      VALUE r_seg = RARRAY_AREF(r_name, i);
      if (!(SYMBOL_P(r_seg) || RB_TYPE_P(r_seg, T_STRING)))
        rb_raise(rb_eTypeError, "function's name should be a Symbol or a String");
    }

    // Build internal lookup key by joining path segments with "."
    // e.g. ["myLib", "hello"] -> :"myLib.hello"
    VALUE r_segs = rb_ary_new();
    for (long i = 0; i < path_len; i++)
      rb_ary_push(r_segs, rb_funcall(RARRAY_AREF(r_name, i), rb_intern("to_s"), 0));
    VALUE r_key_str = rb_funcall(r_segs, rb_intern("join"), 1, rb_str_new2("."));
    VALUE r_key_sym = rb_funcall(r_key_str, rb_intern("to_sym"), 0);
    rb_hash_aset(data->defined_functions, r_key_sym, r_block);

    VALUE r_func_seg_str = rb_funcall(RARRAY_AREF(r_name, path_len - 1), rb_intern("to_s"), 0);
    char *funcName = StringValueCStr(r_func_seg_str);

    JSValueConst ruby_data[2];
    ruby_data[0] = JS_NewInt64(data->context, (int64_t)SYM2ID(r_key_sym));
    ruby_data[1] = JS_NewBool(data->context, RTEST(rb_funcall(r_flags, rb_intern("include?"), 1, ID2SYM(rb_intern("async")))));

    // Resolve the parent object to attach the function to.
    // For a single-element array, parent is the global object.
    // For multi-element arrays, traverse path[0..n-2] using JS_Eval for the first
    // segment (so lexical const/let bindings are resolved, not just global properties)
    // and JS_GetPropertyStr for subsequent segments.
    JSValue j_parent;
    if (path_len == 1)
    {
      j_parent = JS_GetGlobalObject(data->context);
    }
    else
    {
      VALUE r_first_str = rb_funcall(RARRAY_AREF(r_name, 0), rb_intern("to_s"), 0);
      const char *first_seg = StringValueCStr(r_first_str);
      j_parent = JS_Eval(data->context, first_seg, strlen(first_seg), vmInternalFilename, JS_EVAL_TYPE_GLOBAL);

      if (JS_IsException(j_parent) || !JS_IsObject(j_parent))
      {
        JS_FreeValue(data->context, j_parent);
        JS_FreeValue(data->context, ruby_data[0]);
        JS_FreeValue(data->context, ruby_data[1]);
        rb_raise(rb_eArgError, "cannot define function: '%s' is not an object", first_seg);
      }

      for (long i = 1; i < path_len - 1; i++)
      {
        VALUE r_seg_str = rb_funcall(RARRAY_AREF(r_name, i), rb_intern("to_s"), 0);
        JSValue j_next = JS_GetPropertyStr(data->context, j_parent, StringValueCStr(r_seg_str));
        JS_FreeValue(data->context, j_parent);

        if (JS_IsException(j_next) || !JS_IsObject(j_next))
        {
          JS_FreeValue(data->context, j_next);
          JS_FreeValue(data->context, ruby_data[0]);
          JS_FreeValue(data->context, ruby_data[1]);
          rb_raise(rb_eArgError, "cannot define function: '%s' is not an object", StringValueCStr(r_seg_str));
        }
        j_parent = j_next;
      }
    }

    JS_SetPropertyStr(
        data->context, j_parent, funcName,
        JS_NewCFunctionData(data->context, js_quickjsrb_call_global, 1, 0, 2, ruby_data));
    JS_FreeValue(data->context, j_parent);
    JS_FreeValue(data->context, ruby_data[0]);
    JS_FreeValue(data->context, ruby_data[1]);

    VALUE r_result = rb_ary_new();
    for (long i = 0; i < path_len; i++)
      rb_ary_push(r_result, rb_funcall(RARRAY_AREF(r_name, i), rb_intern("to_sym"), 0));
    return r_result;
  }
  else if (SYMBOL_P(r_name) || RB_TYPE_P(r_name, T_STRING))
  {
    VALUE r_name_sym = rb_funcall(r_name, rb_intern("to_sym"), 0);

    rb_hash_aset(data->defined_functions, r_name_sym, r_block);
    VALUE r_name_str = rb_funcall(r_name, rb_intern("to_s"), 0);
    char *funcName = StringValueCStr(r_name_str);

    JSValueConst ruby_data[2];
    ruby_data[0] = JS_NewInt64(data->context, (int64_t)SYM2ID(r_name_sym));
    ruby_data[1] = JS_NewBool(data->context, RTEST(rb_funcall(r_flags, rb_intern("include?"), 1, ID2SYM(rb_intern("async")))));

    JSValue j_global = JS_GetGlobalObject(data->context);
    JS_SetPropertyStr(
        data->context, j_global, funcName,
        JS_NewCFunctionData(data->context, js_quickjsrb_call_global, 1, 0, 2, ruby_data));
    JS_FreeValue(data->context, j_global);
    JS_FreeValue(data->context, ruby_data[0]);
    JS_FreeValue(data->context, ruby_data[1]);

    return r_name_sym;
  }
  else
  {
    rb_raise(rb_eTypeError, "function's name should be a Symbol or a String");
  }
}

#dispose!Object



36
# File 'ext/quickjsrb/quickjsrb.c', line 36

static VALUE vm_m_dispose(VALUE r_self);

#disposed?Boolean

Returns:

  • (Boolean)


37
# File 'ext/quickjsrb/quickjsrb.c', line 37

static VALUE vm_m_disposed(VALUE r_self);

#drain_jobs!Object



38
# File 'ext/quickjsrb/quickjsrb.c', line 38

static VALUE vm_m_drainJobs(VALUE r_self);

#eval_code(*args) ⇒ Object



1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
# File 'ext/quickjsrb/quickjsrb.c', line 1209

static VALUE vm_m_evalCode(int argc, VALUE *argv, VALUE r_self)
{
  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  check_disposed(data);
  check_oom_poisoned(data);

  VALUE r_code, r_opts;
  rb_scan_args(argc, argv, "1:", &r_code, &r_opts);
  const char *filename = parse_code_and_filename(r_code, r_opts);

  bool async_mode = true;
  if (!NIL_P(r_opts))
  {
    VALUE r_async = rb_hash_aref(r_opts, ID2SYM(rb_intern("async")));
    if (r_async == Qfalse)
      async_mode = false;
  }

  arm_eval_timer(data);

  StringValue(r_code);

  if (!async_mode)
  {
    JSValue j_codeResult = JS_Eval(data->context, RSTRING_PTR(r_code), RSTRING_LEN(r_code), filename, JS_EVAL_TYPE_GLOBAL);
    return to_rb_return_value(data->context, j_codeResult);
  }

  JSValue j_codeResult = JS_Eval(data->context, RSTRING_PTR(r_code), RSTRING_LEN(r_code), filename, JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_ASYNC);
  JSValue j_awaitedResult = js_std_await(data->context, j_codeResult); // This frees j_codeResult
  // JS_EVAL_FLAG_ASYNC wraps the result in {value, done} — extract the actual value
  // Free j_awaitedResult before to_rb_return_value because it may raise (longjmp), which would skip cleanup
  JSValue j_returnedValue = JS_GetPropertyStr(data->context, j_awaitedResult, "value");
  JS_FreeValue(data->context, j_awaitedResult);
  return to_rb_return_value(data->context, j_returnedValue);
}

#gc!Object



34
# File 'ext/quickjsrb/quickjsrb.c', line 34

static VALUE vm_m_runGC(VALUE r_self);

#import(*args) ⇒ Object



1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
# File 'ext/quickjsrb/quickjsrb.c', line 1618

static VALUE vm_m_import(int argc, VALUE *argv, VALUE r_self)
{
  VALUE r_import_string, r_opts;
  rb_scan_args(argc, argv, "10:", &r_import_string, &r_opts);
  if (NIL_P(r_opts))
    r_opts = rb_hash_new();
  VALUE r_from = rb_hash_aref(r_opts, ID2SYM(rb_intern("from")));
  VALUE r_filename = rb_hash_aref(r_opts, ID2SYM(rb_intern("filename")));
  if (NIL_P(r_from) && NIL_P(r_filename))
  {
    VALUE r_error_message = rb_str_new2("missing import source");
    rb_exc_raise(rb_funcall(QUICKJSRB_ERROR_FOR(QUICKJSRB_ROOT_RUNTIME_ERROR), rb_intern("new"), 2, r_error_message, Qnil));
    return Qnil;
  }
  if (!NIL_P(r_from) && !NIL_P(r_filename))
    rb_raise(rb_eArgError, "pass either from: (inline source) or filename: (loader-resolved), not both");
  VALUE r_custom_exposure = rb_hash_aref(r_opts, ID2SYM(rb_intern("code_to_expose")));

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  check_disposed(data);

  char *filename;
  VALUE r_seeded_key = Qnil;
  if (!NIL_P(r_filename))
  {
    filename = StringValueCStr(r_filename);
  }
  else
  {
    filename = random_string();
    char *source = StringValueCStr(r_from);
    JSValue module = JS_Eval(data->context, source, strlen(source), filename, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
    if (JS_IsException(module))
    {
      JS_FreeValue(data->context, module);
      return to_rb_value(data->context, module);
    }
    js_module_set_import_meta(data->context, module, TRUE, FALSE);
    // The bridge module below will `import` this filename; without a
    // resolution-cache seed, our normalize hook would ask the user's
    // module_loader for it (and fail), even though QuickJS already has
    // the module loaded from the JS_Eval just above. Each `from:` call
    // mints a fresh random filename, so we also delete the entry once
    // the bridge eval finishes — otherwise the cache grows unboundedly.
    if (!NIL_P(data->module_loader))
    {
      VALUE r_filename_str = rb_str_new_cstr(filename);
      r_seeded_key = rb_ary_new3(2, r_filename_str, rb_str_new2(vmInternalFilename));
      rb_hash_aset(data->module_resolution_cache, r_seeded_key, r_filename_str);
    }
    JS_FreeValue(data->context, module);
  }

  VALUE r_import_settings = rb_funcall(
      rb_const_get(rb_cClass, rb_intern("Quickjs")),
      rb_intern("_build_import"),
      1,
      r_import_string);
  VALUE r_import_name = rb_ary_entry(r_import_settings, 0);
  char *import_name = StringValueCStr(r_import_name);
  VALUE r_default_exposure = rb_ary_entry(r_import_settings, 1);
  char *globalize;
  if (RTEST(r_custom_exposure))
  {
    globalize = StringValueCStr(r_custom_exposure);
  }
  else
  {
    globalize = StringValueCStr(r_default_exposure);
  }

  const char *importAndGlobalizeModule = "import %s from '%s';\n"
                                         "%s\n";
  int length = snprintf(NULL, 0, importAndGlobalizeModule, import_name, filename, globalize);
  char *result = (char *)malloc(length + 1);
  snprintf(result, length + 1, importAndGlobalizeModule, import_name, filename, globalize);

  JSValue j_codeResult = JS_Eval(data->context, result, strlen(result), vmInternalFilename, JS_EVAL_TYPE_MODULE);
  free(result);
  if (JS_IsException(j_codeResult))
    return to_rb_value(data->context, j_codeResult);

  // Module eval returns a Promise. Awaiting it surfaces top-level throws,
  // rejected dynamic imports, and rejected top-level awaits as Ruby
  // exceptions instead of silently dropping them.
  JSValue j_awaited = js_std_await(data->context, j_codeResult);
  if (JS_IsException(j_awaited))
    return to_rb_value(data->context, j_awaited);
  JS_FreeValue(data->context, j_awaited);

  if (!NIL_P(r_seeded_key))
    rb_hash_delete(data->module_resolution_cache, r_seeded_key);

  return Qtrue;
}

#memory_poisoned?Boolean

Returns:

  • (Boolean)


35
# File 'ext/quickjsrb/quickjsrb.c', line 35

static VALUE vm_m_memoryPoisoned(VALUE r_self);

#memory_usageObject



33
# File 'ext/quickjsrb/quickjsrb.c', line 33

static VALUE vm_m_memoryUsage(VALUE r_self);

#module_loaderObject



1600
1601
1602
1603
1604
1605
# File 'ext/quickjsrb/quickjsrb.c', line 1600

static VALUE vm_m_get_module_loader(VALUE r_self)
{
  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);
  return data->module_loader;
}

#module_loader=(r_loader) ⇒ Object



1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
# File 'ext/quickjsrb/quickjsrb.c', line 1583

static VALUE vm_m_set_module_loader(VALUE r_self, VALUE r_loader)
{
  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  if (!NIL_P(r_loader) && !rb_obj_is_kind_of(r_loader, rb_cProc))
    rb_raise(rb_eTypeError, "module_loader must be a Proc or nil");

  data->module_loader = r_loader;
  // Stale entries from the previous loader's policy would survive the
  // swap and silently shadow the new behavior.
  rb_hash_clear(data->module_resolution_cache);
  rb_hash_clear(data->module_source_cache);
  register_module_loader_funcs(data);
  return r_loader;
}

#on_logObject



894
895
896
897
898
899
900
901
902
903
904
# File 'ext/quickjsrb/quickjsrb.c', line 894

static VALUE vm_m_on_log(VALUE r_self)
{
  rb_need_block();

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  data->log_listener = rb_block_proc();

  return Qnil;
}

#on_unhandled_rejectionObject



1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
# File 'ext/quickjsrb/quickjsrb.c', line 1607

static VALUE vm_m_on_unhandled_rejection(VALUE r_self)
{
  rb_need_block();

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  data->on_unhandled_rejection = rb_block_proc();
  return Qnil;
}