UNPKG

@metamask/ocap-kernel

Version:
67 lines 2.45 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeGCAndFinalize = makeGCAndFinalize; const kernel_utils_1 = require("@metamask/kernel-utils"); /** * Try to get a GC function for the current environment * * @param logger - The logger to use. * @returns A function that triggers GC and finalization when possible */ async function getGCFunction(logger) { if (typeof globalThis.gc === 'function') { return globalThis.gc; } // Check if we're in Node.js if (typeof globalThis === 'object' && Object.prototype.toString.call(globalThis.process) === '[object process]') { try { // Dynamic import of Node.js specific module so it's not included in browser builds const { engineGC } = await import("./gc-engine.cjs"); return engineGC; } catch (error) { logger?.debug('Failed to load Node.js GC implementation:', error); } } return undefined; } /** * Utility to create a function that performs garbage collection and finalization * in a cross-environment compatible way. * * @param logger - The logger to use. * @returns A function that triggers GC and finalization when possible */ function makeGCAndFinalize(logger) { // Cache the GC function promise const gcFunctionPromise = getGCFunction(logger); /** * Function to trigger garbage collection and finalization */ return async function gcAndFinalize() { try { const gcFunction = await gcFunctionPromise; if (gcFunction) { // First GC pass gcFunction(); // Allow finalization callbacks to run await (0, kernel_utils_1.delay)(0); // Second GC pass to clean up objects that might have become // unreachable during finalization gcFunction(); // Another tick to ensure finalization completes await (0, kernel_utils_1.delay)(0); } else { // No GC function available, log warning and cycle the event loop logger?.warn('Deterministic GC not available in this environment'); await (0, kernel_utils_1.delay)(0); } } catch (error) { logger?.warn('GC operation failed:', error); } }; } //# sourceMappingURL=gc-finalize.cjs.map