"use strict";const path=require("node:path"),OKDB=require(path.join(__dirname,"okdb.js"));let db=null,worker=null,stopping=!1;function send(e){try{"function"==typeof process.send&&process.send(e)}catch{}}function loadHandler(e,t){const o=require(e);if(t&&"default"!==t){const e=o?.[t];if("function"!=typeof e)throw new Error(`Spawned queue worker export not found or not a function: ${t}`);return e}if("function"==typeof o)return o;if("function"==typeof o?.default)return o.default;throw new Error("Spawned queue worker module must export a function or default function")}async function main(){const e=process.env.OKDB_QUEUE_DB_PATH,t=process.env.OKDB_QUEUE_ENV_NAME||"default",o=process.env.OKDB_QUEUE_TYPE,r=process.env.OKDB_QUEUE_MODULE,n=process.env.OKDB_QUEUE_EXPORT||"default",s=JSON.parse(process.env.OKDB_QUEUE_WORKER_OPTIONS||"{}");if(!e)throw new Error("Missing OKDB_QUEUE_DB_PATH");if(!o)throw new Error("Missing OKDB_QUEUE_TYPE");if(!r)throw new Error("Missing OKDB_QUEUE_MODULE");db=new OKDB(e,{runtimeDeclarations:!1}),await db.open();const c=db.env(t);if(!c?.queue)throw new Error(`Queue environment not available: ${t}`);const a=loadHandler(r,n);worker=c.queue.worker(o,a,s),process.on("message",async e=>{if(e&&"object"==typeof e&&"stop"===e.type&&!stopping){stopping=!0;try{await(worker?.stop?.()),await(db?.close?.())}catch{}process.exit(0)}}),process.on("SIGINT",async()=>{if(!stopping){stopping=!0;try{await(worker?.stop?.())}catch{}try{await(db?.close?.())}catch{}process.exit(0)}}),process.on("SIGTERM",async()=>{if(!stopping){stopping=!0;try{await(worker?.stop?.())}catch{}try{await(db?.close?.())}catch{}process.exit(0)}}),send({type:"ready",pid:process.pid,envName:t,queueType:o})}main().catch(async e=>{send({type:"error",error:{message:e?.message||String(e),stack:e?.stack||null,code:e?.code||null}});try{await(worker?.stop?.())}catch{}try{await(db?.close?.())}catch{}process.exit(1)});