import { Worker } from "node:worker_threads";
const workerCode = `
const { createRequire } = require('node:module')
const _require = createRequire(process.cwd() + '/')
const { parentPort } = require('node:worker_threads')
const { Resvg } = _require('@resvg/resvg-js')

parentPort.on('message', ({ id, svg, options }) => {
  try {
    const resvg = new Resvg(svg, options)
    const png = resvg.render().asPng()
    // Always slice to create a standard ArrayBuffer \u2014 native addon buffers
    // use external memory that can't be transferred via postMessage
    const ab = png.buffer.slice(png.byteOffset, png.byteOffset + png.byteLength)
    parentPort.postMessage({ id, png: ab }, [ab])
  } catch (err) {
    parentPort.postMessage({ id, error: err?.message || String(err) })
  }
})
`;
let worker = null;
let requestId = 0;
const pending = /* @__PURE__ */ new Map();
function killWorker() {
  if (!worker)
    return;
  worker.terminate();
  worker = null;
  for (const [id, p] of pending) {
    clearTimeout(p.timer);
    pending.delete(id);
    p.reject(new Error("Resvg worker terminated"));
  }
}
const signalKey = Symbol.for("og-image:resvg-worker-cleanup");
if (!globalThis[signalKey]) {
  globalThis[signalKey] = true;
  process.on("exit", killWorker);
}
function createWorker() {
  const w = new Worker(workerCode, { eval: true });
  w.on("message", ({ id, png, error }) => {
    const p = pending.get(id);
    if (p) {
      clearTimeout(p.timer);
      pending.delete(id);
      if (error)
        p.reject(new Error(error));
      else
        p.resolve(Buffer.from(png));
    }
  });
  w.on("error", (err) => {
    for (const [id, p] of pending) {
      clearTimeout(p.timer);
      pending.delete(id);
      p.reject(err);
    }
    worker = null;
  });
  w.on("exit", (code) => {
    if (code !== 0) {
      for (const [id, p] of pending) {
        clearTimeout(p.timer);
        pending.delete(id);
        p.reject(new Error(`Resvg worker exited with code ${code}`));
      }
    }
    worker = null;
  });
  w.unref();
  return w;
}
function renderPng(svg, options) {
  return new Promise((resolve, reject) => {
    if (!worker)
      worker = createWorker();
    const id = ++requestId;
    const timer = setTimeout(() => {
      pending.delete(id);
      reject(new Error("resvg worker timed out \u2014 killing worker"));
      killWorker();
    }, 3e4);
    pending.set(id, { resolve, reject, timer });
    worker.postMessage({ id, svg, options });
  });
}
class ResvgWorkerProxy {
  svg;
  options;
  pngPromise = null;
  constructor(svg, options) {
    this.svg = svg;
    this.options = options;
  }
  render() {
    if (!this.pngPromise)
      this.pngPromise = renderPng(this.svg, this.options);
    return {
      asPng: () => this.pngPromise
    };
  }
}
export default {
  initWasmPromise: Promise.resolve(),
  Resvg: ResvgWorkerProxy
};
