"use strict";const{parentPort:parentPort,workerData:workerData}=require("worker_threads"),lmdb=require("lmdb"),mode=workerData.mode??"snapshot";async function runSnapshotMode(){const{envPath:e,type:t,batchSize:o,mapSize:r,compression:s}=workerData,n=lmdb.open(e,{readOnly:!0,maxDbs:128,mapSize:r??268435456,compression:s??!0}),a=n.openDB(`type:${t}:data`,{dupSort:!1,useVersions:!0}).getRange({snapshot:!0});let p=null;const i=()=>new Promise(e=>{p=e});parentPort.on("message",e=>{if("ack"===e.type&&p){const e=p;p=null,e()}});let c=[],l=0;for(const{key:e,value:t,version:r}of a)if(c.push({key:e,value:t,version:r}),c.length>=o){const e=c.length;parentPort.postMessage({type:"batch",entries:c,processed:l}),await i(),l+=e,c=[]}c.length>0&&(parentPort.postMessage({type:"batch",entries:c,processed:l}),await i(),l+=c.length),await n.close(),parentPort.postMessage({type:"done",total:l}),process.exit(0)}async function runLiveMode(){const{handlerModule:e,rootPath:t,envName:o,type:r}=workerData,s=new(require("../okdb"))(t,{admin:!1,mcp:!1,http:!1,timeMachine:!1,engines:!1,asyncProcessors:!1,compaction:"passive",_skipBootRuntime:!0});await s.open();const n=s.env(o),a=require(e.module);let p=a[e.export]??a.default??a;if(p&&"object"==typeof p&&"function"==typeof p.handle&&("function"==typeof p.init&&await p.init({env:n,type:r}),p=p.handle.bind(p)),"function"!=typeof p)throw new Error(`live worker: ${e.export} is not a function in ${e.module}`);await new Promise(e=>{parentPort.on("message",t=>{"flush"===t.type?Promise.resolve().then(()=>p(t.changes,{mode:"live",type:r,env:n})).then(()=>{parentPort.postMessage({type:"flush-done",lastClock:t.lastClock})}).catch(e=>{parentPort.postMessage({type:"error",error:e.message??String(e)})}):"stop"===t.type&&e()})}),await s.close(),process.exit(0)}"live"===mode?runLiveMode().catch(e=>{parentPort.postMessage({type:"error",error:e.message??String(e)}),process.exit(1)}):runSnapshotMode().catch(e=>{parentPort.postMessage({type:"error",error:e.message??String(e)}),process.exit(1)});