/**
 * @license
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import{Comlink}from'comlinkjs';Comlink.transferHandlers.set('FUNCTION',{canHandle(a){return a instanceof Function},serialize(a){const{port1:b,port2:c}=new MessageChannel;return Comlink.expose(a,b),c},deserialize(a){return Comlink.proxy(a)}}),Comlink.transferHandlers.set('EVENT',{canHandle(a){return a instanceof Event},serialize(a){return{targetId:a&&a.target&&a.target.id,targetClassList:a&&a.target&&a.target.classList&&[...a.target.classList],detail:a&&a.detail,data:a&&a.data}},deserialize(a){return a}});export{Comlink}from'comlinkjs';export const asRemoteValue=Comlink.proxyValue;export let defaultWorkerSrc='document'in self?document.currentScript&&document.currentScript.src:'';export const defaultOpts={maxNumContainers:1,newWorkerFunc:async()=>new Worker(defaultWorkerSrc)};export class RoundRobinStrategy{constructor(a={}){this._nextIndex=0,this._options=Object.assign({},defaultOpts,a),this._containers=Array(this._options.maxNumContainers).fill(null)}async _initOrGetContainer(a){if(a>=this._containers.length)throw Error('No worker available');if(!this._containers[a]){const b=await this._options.newWorkerFunc(),c=Comlink.proxy(b);this._containers[a]={spawn:c.spawn.bind(spawn),terminate:b.terminate.bind(b)}}return this._containers[a]}async _getNextContainer(){const a=await this._initOrGetContainer(this._nextIndex);return this._nextIndex=(this._nextIndex+1)%this._options.maxNumContainers,a}async spawn(a,b=[],c={}){const d=await this._getNextContainer(c);return await d.spawn(a.toString(),b)}async terminate(){this._containers.filter((a)=>a).forEach((a)=>a.terminate()),this._containers.length=0}get terminated(){return 0>=this._containers.length}}export let defaultStrategy=new RoundRobinStrategy;export async function spawn(a,b=[],c={}){return defaultStrategy.spawn(a,b,c)}export function makeContainer(a=self){Comlink.expose({async spawn(a,b){const c=new Function(`return ${a};`)();return Comlink.proxyValue(new c(...b))}},a)}function isWorker(){const a=self.WorkerGlobalScope;return a&&self instanceof a}isWorker()&&makeContainer();