// Runs inside the modularized Emscripten factory closure. Native SDL teardown
// releases browser resources; this finalizer then severs JavaScript references
// that Emscripten otherwise keeps for the lifetime of the page.
Module["teDisposeRuntime"] = function () {
    if (Module["teRuntimeDisposed"]) return;
    Module["teRuntimeDisposed"] = true;

    try { MainLoop.pause(); } catch {}
    MainLoop.func = null;
    MainLoop.scheduler = null;
    MainLoop.queue.length = 0;
    MainLoop.preMainLoop.length = 0;
    MainLoop.postMainLoop.length = 0;
    try { JSEvents.removeAllEventListeners(); } catch {}
    try { FS.quit(); } catch {}
    FS.streams.length = 0;
    FS.nameTable = null;
    FS.root = null;

    Module["onMapComplete"] = undefined;
    Module["onSaveComplete"] = undefined;
    Module["canvas"] = undefined;
    Module["FS"] = undefined;
    Module["callMain"] = undefined;
    Module["ccall"] = undefined;
    for (const key of Object.keys(Module)) {
        if (key.startsWith("_TE_") || key === "_main") delete Module[key];
    }

    HEAP8 = undefined;
    HEAP16 = undefined;
    HEAPU8 = undefined;
    HEAPU16 = undefined;
    HEAP32 = undefined;
    HEAPU32 = undefined;
    HEAPF32 = undefined;
    HEAPF64 = undefined;
    HEAP64 = undefined;
    wasmExports = undefined;
    wasmMemory = undefined;
    memory = undefined;
};
