export class ManagedWasm {
#registry;
#module;
constructor(module) {
this.#module = module;
if (typeof FinalizationRegistry !== 'undefined') {
this.#registry = new FinalizationRegistry((ptr) => {
if (ptr !== 0 && typeof this.#module.free_array === 'function') {
try {
this.#module.free_array(ptr);
} catch (_err) {
}
}
});
} else {
this.#registry = null;
}
}
static async init(wasmUrl) {
const wasmModule = await import(wasmUrl);
if (typeof wasmModule.default === 'function') {
await wasmModule.default();
}
return new ManagedWasm(wasmModule);
}
createArray(size) {
const token = { ptr: 0 };
const handle = {
size,
free() {
if (token.ptr !== 0) {
token.ptr = 0;
}
},
};
if (this.#registry !== null) {
this.#registry.register(handle, token.ptr, handle);
}
return handle;
}
unregister(handle) {
if (this.#registry !== null) {
this.#registry.unregister(handle);
}
}
}
export function isFinalizationRegistrySupported() {
return typeof FinalizationRegistry !== 'undefined';
}
export function createFinalizationPolyfill(callback) {
const entries = new Map();
let nextId = 0;
return {
register(_target, value, token) {
const id = nextId++;
entries.set(id, { value, token });
},
unregister(token) {
for (const [id, entry] of entries) {
if (entry.token === token) {
entries.delete(id);
}
}
},
};
}