module-test.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.TestQuickJSWASMModule = void 0;
  4. const errors_1 = require("./errors");
  5. const lifetime_1 = require("./lifetime");
  6. /**
  7. * A test wrapper of [[QuickJSWASMModule]] that keeps a reference to each
  8. * context or runtime created.
  9. *
  10. * Call [[disposeAll]] to reset these sets and calls `dispose` on any left alive
  11. * (which may throw an error).
  12. *
  13. * Call [[assertNoMemoryAllocated]] at the end of a test, when you expect that you've
  14. * freed all the memory you've ever allocated.
  15. */
  16. class TestQuickJSWASMModule {
  17. constructor(parent) {
  18. this.parent = parent;
  19. this.contexts = new Set();
  20. this.runtimes = new Set();
  21. }
  22. newRuntime(options) {
  23. const runtime = this.parent.newRuntime({
  24. ...options,
  25. ownedLifetimes: [
  26. new lifetime_1.Lifetime(undefined, undefined, () => this.runtimes.delete(runtime)),
  27. ...(options?.ownedLifetimes ?? []),
  28. ],
  29. });
  30. this.runtimes.add(runtime);
  31. return runtime;
  32. }
  33. newContext(options) {
  34. const context = this.parent.newContext({
  35. ...options,
  36. ownedLifetimes: [
  37. new lifetime_1.Lifetime(undefined, undefined, () => this.contexts.delete(context)),
  38. ...(options?.ownedLifetimes ?? []),
  39. ],
  40. });
  41. this.contexts.add(context);
  42. return context;
  43. }
  44. evalCode(code, options) {
  45. return this.parent.evalCode(code, options);
  46. }
  47. disposeAll() {
  48. const allDisposables = [...this.contexts, ...this.runtimes];
  49. this.runtimes.clear();
  50. this.contexts.clear();
  51. allDisposables.forEach((d) => {
  52. if (d.alive) {
  53. d.dispose();
  54. }
  55. });
  56. }
  57. assertNoMemoryAllocated() {
  58. const leaksDetected = this.getFFI().QTS_RecoverableLeakCheck();
  59. if (leaksDetected) {
  60. // Note: this is currently only available when building from source
  61. // with debug builds.
  62. throw new errors_1.QuickJSMemoryLeakDetected("Leak sanitizer detected un-freed memory");
  63. }
  64. if (this.contexts.size > 0) {
  65. throw new errors_1.QuickJSMemoryLeakDetected(`${this.contexts.size} contexts leaked`);
  66. }
  67. if (this.runtimes.size > 0) {
  68. throw new errors_1.QuickJSMemoryLeakDetected(`${this.runtimes.size} runtimes leaked`);
  69. }
  70. }
  71. /** @private */
  72. getFFI() {
  73. return this.parent.getFFI();
  74. }
  75. }
  76. exports.TestQuickJSWASMModule = TestQuickJSWASMModule;
  77. //# sourceMappingURL=module-test.js.map