context-asyncify.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.QuickJSAsyncContext = void 0;
  4. const context_1 = require("./context");
  5. const debug_1 = require("./debug");
  6. const types_1 = require("./types");
  7. /**
  8. * Asyncified version of [[QuickJSContext]].
  9. *
  10. * *Asyncify* allows normally synchronous code to wait for asynchronous Promises
  11. * or callbacks. The asyncified version of QuickJSContext can wait for async
  12. * host functions as though they were synchronous.
  13. */
  14. class QuickJSAsyncContext extends context_1.QuickJSContext {
  15. /**
  16. * Asyncified version of [[evalCode]].
  17. */
  18. async evalCodeAsync(code, filename = "eval.js",
  19. /** See [[EvalFlags]] for number semantics */
  20. options) {
  21. const detectModule = (options === undefined ? 1 : 0);
  22. const flags = (0, types_1.evalOptionsToFlags)(options);
  23. let resultPtr = 0;
  24. try {
  25. resultPtr = await this.memory
  26. .newHeapCharPointer(code)
  27. .consume((charHandle) => this.ffi.QTS_Eval_MaybeAsync(this.ctx.value, charHandle.value, filename, detectModule, flags));
  28. }
  29. catch (error) {
  30. (0, debug_1.debugLog)("QTS_Eval_MaybeAsync threw", error);
  31. throw error;
  32. }
  33. const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
  34. if (errorPtr) {
  35. this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr);
  36. return { error: this.memory.heapValueHandle(errorPtr) };
  37. }
  38. return { value: this.memory.heapValueHandle(resultPtr) };
  39. }
  40. /**
  41. * Similar to [[newFunction]].
  42. * Convert an async host Javascript function into a synchronous QuickJS function value.
  43. *
  44. * Whenever QuickJS calls this function, the VM's stack will be unwound while
  45. * waiting the async function to complete, and then restored when the returned
  46. * promise resolves.
  47. *
  48. * Asyncified functions must never call other asyncified functions or
  49. * `import`, even indirectly, because the stack cannot be unwound twice.
  50. *
  51. * See [Emscripten's docs on Asyncify](https://emscripten.org/docs/porting/asyncify.html).
  52. */
  53. newAsyncifiedFunction(name, fn) {
  54. return this.newFunction(name, fn);
  55. }
  56. }
  57. exports.QuickJSAsyncContext = QuickJSAsyncContext;
  58. //# sourceMappingURL=context-asyncify.js.map