import { createDefaultNativeKdlModuleLoader } from "./nativeModule.js";
import { createKdlWorkerRuntime } from "./runtime.js";
import { dispatchKdlRpcRequest } from "./workerRpc.js";
import type { KdlRpcRequest } from "./rpc.js";

const runtime = createKdlWorkerRuntime(createDefaultNativeKdlModuleLoader());
const workerScope = globalThis as unknown as {
  onmessage: ((event: MessageEvent<KdlRpcRequest<unknown[]>>) => void) | null;
  postMessage: (message: unknown, transfer?: Transferable[]) => void;
};

workerScope.onmessage = (event) => {
  void dispatchKdlRpcRequest(runtime, event.data).then((response) => {
    workerScope.postMessage(response);
  });
};
