/* COPYRIGHT Esri - https://js.arcgis.com/5.1.0/LICENSE.txt */
import t from"../Error.js";import{handlesGroup as r}from"../handleUtils.js";import has from"../has.js";import{getOrCreateMapValue as o}from"../MapUtils.js";import{throwIfAborted as e}from"../promiseUtils.js";import n from"./Connection.js";import{register as s}from"./connectionRegistry.js";import i from"./RemoteClient.js";import a from"./WorkerOwner.js";function u(){const t=has("min-workers-pool-size")??2,r=has("max-workers-pool-size")??8,o=has("host-browser")&&void 0!==navigator.hardwareConcurrency?navigator.hardwareConcurrency-1:r;return Math.min(Math.max(t,o),r)}const l=[],c=new Map;let m=u(),h=0;function f(){m=u(),h=0,c.clear()}function y(){k()}async function p(t,r={},o){const e=new n,{registryTarget:i,...a}=r;return await e.open(t,a,o),i&&s(i,e),e}async function g(r,e={}){if("string"!=typeof r)throw new t("workers:undefined-module","modulePath is missing");let n=e.strategy||"distributed";has("host-webworker")&&!has("esri-workers")&&(n="local");const s=o(c,r,()=>new _(r));return"local"===n?x(s,e):d(s,e)}async function x({modulePath:t},r){let o=await i.loadWorker(t);o||(o=await import(/* @vite-ignore */ /* webpackIgnore: true */t)),e(r.signal);const n=r.client||o,s=i.connect(o,r.schedule);return await p([s],{...r,client:n})}async function d(t,o){await k(),e(o.signal);const n=[];return p(w(t,"dedicated"===o.strategy?1:o.maxNumWorkers&&o.maxNumWorkers>0?Math.min(o.maxNumWorkers,m):m,o.signal,n),o,()=>r(n).remove())}function*w(t,r,o,e){const n=new Set;for(let s=0;s<r;s++){const r=t.getNextProxyId(t=>!n.has(t));if(null==r)break;n.add(r),e.push(t.useProxy(r)),yield l[r].open(t.modulePath,{signal:o})}}function C(){U&&(P.abort(),U=null);for(let t=0;t<l.length;t++)l[t]&&l[t].terminate();l.length=0,f()}let P,U=null;async function k(){if(U)return U;P=new AbortController;const t=[];for(let r=0;r<m;r++){const o=a.create(r).then(t=>(l[r]=t,t));t.push(o)}return U=Promise.all(t),U}class _{constructor(t){this.modulePath=t,this._proxyUseCount=new Map}useProxy(t){return this._proxyUseCount.set(t,this._getProxyUseCount(t)+1),{remove:()=>this._unuseProxy(t)}}getNextProxyId(t){const r=Array.from(this._proxyUseCount.keys());let o;const e=h;h=(h+1)%m;for(let n=0;n<r.length;n++){const s=r[(e+n)%r.length];if(t(s)&&(r.length===m&&(o??=s),0===this._getProxyUseCount(s)))return s}if(null!=o)return o;for(let n=0;n<m;n++){const r=(n+e)%m;if(t(r)&&!this._proxyUseCount.has(r))return r}}_unuseProxy(t){this._proxyUseCount.set(t,Math.max(0,this._getProxyUseCount(t)-1))}_getProxyUseCount(t){return this._proxyUseCount.get(t)??0}}export{n as Connection,i as RemoteClient,y as initialize,g as open,p as openWithPorts,C as terminate};
