"use strict";var m=Object.defineProperty;var k=(r,t,e)=>t in r?m(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var g=(r,t,e)=>(k(r,typeof t!="symbol"?t+"":t,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("worker_threads"),o="TSWM";class d extends I.Worker{constructor(e,n,i){super(e,n);g(this,"listeners",{});g(this,"callbackIncreaseId",0);g(this,"callbackWaitingMap",{});g(this,"logger");this.logger=i??console,this._bindMessage()}send(e,...n){const i=this.callbackIncreaseId;return this.postMessage({from:o,type:"message",name:e,payload:n,cbId:i}),this.callbackIncreaseId++,new Promise(c=>{this.callbackWaitingMap[i]=c})}handle(e,n){if(this.listeners[e])throw new Error(`Message handler ${String(e)} already existed!`);this.listeners[e]=n}_bindMessage(){this.on("message",this._handleReceivingMessage.bind(this))}async _handleReceivingMessage(e){if(!(!e||!e.from||e.from!==o)){if(e.type==="message"){if(this.listeners[e.name]){const n=await this.listeners[e.name](...e.payload);this.postMessage({from:o,type:"callback",name:"",payload:n,cbId:e.cbId})}else throw new Error(`Unknown message ${e.name}, try to bind ${e.name} as handle first.`);return}e.type==="callback"&&this.callbackWaitingMap&&this.callbackWaitingMap[e.cbId]&&(this.callbackWaitingMap[e.cbId](e.payload),delete this.callbackWaitingMap[e.cbId]),e.type==="logger"&&this.logger[e.name](...e.payload)}}}function u(r){const e=!r?{postMessage(...s){return console.log("postMessage",s),Promise.resolve()},on(...s){console.log("on",s)}}:r,n={};let i=0;const c={};function f(s,...a){const b=i;return e.postMessage({from:o,type:"message",name:s,payload:a,cbId:b}),i++,new Promise(M=>{c[b]=M})}function h(s,a){if(n[s])throw new Error(`Message handler ${String(s)} already existed!`);n[s]=a}e.on("message",async s=>{if(!(!s||!s.from||s.from!==o)){if(s.type==="message"){if(n[s.name]){const a=await n[s.name](...s.payload);e.postMessage({from:o,type:"callback",name:"",payload:a,cbId:s.cbId})}else throw new Error(`Unknown message ${s.name}, try to bind ${s.name} as handle first.`);return}s.type==="callback"&&c&&c[s.cbId]&&(c[s.cbId](s.payload),delete c[s.cbId])}});function l(s){return function(...a){e.postMessage({from:o,type:"logger",name:s,payload:a})}}return e.send=f,e.handle=h,e.error=l("error"),e.warn=l("warn"),e.info=l("info"),e.log=l("log"),e}exports.TypeSafeWorkerMessagesInMain=d;exports.TypeSafeWorkerMessagesInWorker=u;