import{IndexOptions}from"./type.js";import{create_object}from"./common.js";import{searchCache}from"./cache.js";import handler from"./worker/handler.js";import apply_async from"./async.js";import Encoder from"./encoder.js";let pid=0;export default function WorkerIndex(a={},b){function c(c){function g(a){a=a.data||a;const b=a.id,c=b&&f.resolver[b];c&&(c(a.msg),delete f.resolver[b])}return(this.worker=c,this.resolver=create_object(),!this.worker)?void 0:(e?this.worker.on("message",g):this.worker.onmessage=g,a.config)?new Promise(function(b){1e9<pid&&(pid=0),f.resolver[++pid]=function(){b(f)},f.worker.postMessage({id:pid,task:"init",factory:d,options:a})}):(this.priority=a.priority||4,this.encoder=b||null,this.worker.postMessage({task:"init",factory:d,options:a}),this)}if(!this||this.constructor!==WorkerIndex)return new WorkerIndex(a);let d="undefined"==typeof self?"undefined"==typeof window?null:window._factory:self._factory;d&&(d=d.toString());const e="undefined"==typeof window,f=this,g=create(d,e,a.worker);return g.then?g.then(function(a){return c.call(f,a)}):c.call(this,g)}register("add"),register("append"),register("search"),register("update"),register("remove"),register("clear"),register("export"),register("import"),WorkerIndex.prototype.searchCache=searchCache,apply_async(WorkerIndex.prototype);function register(a){WorkerIndex.prototype[a]=function(){const b=this,c=[].slice.call(arguments),d=c[c.length-1];let e;"function"==typeof d&&(e=d,c.pop());const f=new Promise(function(d){"export"===a&&"function"==typeof c[0]&&(c[0]=null),1e9<pid&&(pid=0),b.resolver[++pid]=d,b.worker.postMessage({task:a,id:pid,args:c})});return e?(f.then(e),this):f}}function create(a,b,c){return b?"undefined"==typeof module?import("worker_threads").then(function(worker){return new worker["Worker"](import.meta.dirname+"/../node/node.mjs")}):new(require("worker_threads")["Worker"])(__dirname+"/worker/node.js"):a?new window.Worker(URL.createObjectURL(new Blob(["onmessage="+handler.toString()],{type:"text/javascript"}))):new window.Worker("string"==typeof c?c:import.meta.url.replace("/worker.js","/worker/worker.js").replace("flexsearch.bundle.module.min.js","module/worker/worker.js").replace("flexsearch.bundle.module.min.mjs","module/worker/worker.js"),{type:"module"})}