@6qat/tcp-connection 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +39 -2
- package/dist/tcp-connection.d.ts +33 -0
- package/dist/tcp-connection.test.d.ts +1 -0
- package/dist/tcp-stream.d.ts +2 -3
- package/package.json +11 -7
- package/dist/tcp-stream.js +0 -82
package/dist/index.js
CHANGED
|
@@ -1,2 +1,39 @@
|
|
|
1
|
-
// Export everything from tcp-stream
|
|
2
|
-
|
|
1
|
+
var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:(newValue)=>all[name]=()=>newValue})};var isFunction=(input)=>typeof input==="function",dual=function(arity,body){if(typeof arity==="function")return function(){if(arity(arguments))return body.apply(this,arguments);return(self)=>body(self,...arguments)};switch(arity){case 0:case 1:throw new RangeError(`Invalid arity ${arity}`);case 2:return function(a,b){if(arguments.length>=2)return body(a,b);return function(self){return body(self,a)}};case 3:return function(a,b,c){if(arguments.length>=3)return body(a,b,c);return function(self){return body(self,a,b)}};case 4:return function(a,b,c,d){if(arguments.length>=4)return body(a,b,c,d);return function(self){return body(self,a,b,c)}};case 5:return function(a,b,c,d,e){if(arguments.length>=5)return body(a,b,c,d,e);return function(self){return body(self,a,b,c,d)}};default:return function(){if(arguments.length>=arity)return body.apply(this,arguments);let args=arguments;return function(self){return body(self,...args)}}}};var identity=(a)=>a;var constant=(value)=>()=>value,constTrue=constant(!0),constFalse=constant(!1);var constUndefined=constant(void 0),constVoid=constUndefined;function pipe(a,ab,bc,cd,de,ef,fg,gh,hi){switch(arguments.length){case 1:return a;case 2:return ab(a);case 3:return bc(ab(a));case 4:return cd(bc(ab(a)));case 5:return de(cd(bc(ab(a))));case 6:return ef(de(cd(bc(ab(a)))));case 7:return fg(ef(de(cd(bc(ab(a))))));case 8:return gh(fg(ef(de(cd(bc(ab(a)))))));case 9:return hi(gh(fg(ef(de(cd(bc(ab(a))))))));default:{let ret=arguments[0];for(let i=1;i<arguments.length;i++)ret=arguments[i](ret);return ret}}}var make=(isEquivalent)=>(self,that)=>self===that||isEquivalent(self,that),isStrictEquivalent=(x,y)=>x===y,strict=()=>isStrictEquivalent;var number=strict();var mapInput=dual(2,(self,f)=>make((x,y)=>self(f(x),f(y)))),Date2=mapInput(number,(date)=>date.getTime());var array=(item)=>make((self,that)=>{if(self.length!==that.length)return!1;for(let i=0;i<self.length;i++)if(!item(self[i],that[i]))return!1;return!0});var let_=(map)=>dual(3,(self,name,f)=>map(self,(a)=>Object.assign({},a,{[name]:f(a)}))),bindTo=(map)=>dual(2,(self,name)=>map(self,(a)=>({[name]:a}))),bind=(map,flatMap)=>dual(3,(self,name,f)=>flatMap(self,(a)=>map(f(a),(b)=>Object.assign({},a,{[name]:b}))));var moduleVersion="3.14.18",getCurrentVersion=()=>moduleVersion;var globalStoreId=`effect/GlobalValue/globalStoreId/${getCurrentVersion()}`,globalStore,globalValue=(id,compute)=>{if(!globalStore)globalThis[globalStoreId]??=new Map,globalStore=globalThis[globalStoreId];if(!globalStore.has(id))globalStore.set(id,compute());return globalStore.get(id)};var isString=(input)=>typeof input==="string",isNumber=(input)=>typeof input==="number",isBoolean=(input)=>typeof input==="boolean",isBigInt=(input)=>typeof input==="bigint",isSymbol=(input)=>typeof input==="symbol";var isFunction2=isFunction,isUndefined=(input)=>input===void 0;var isNever=(_)=>!1;var isRecordOrArray=(input)=>typeof input==="object"&&input!==null,isObject=(input)=>isRecordOrArray(input)||isFunction2(input),hasProperty=dual(2,(self,property)=>isObject(self)&&(property in self)),isTagged=dual(2,(self,tag)=>hasProperty(self,"_tag")&&self._tag===tag),isNullable=(input)=>input===null||input===void 0,isNotNullable=(input)=>input!==null&&input!==void 0;var isDate=(input)=>input instanceof Date,isIterable=(input)=>hasProperty(input,Symbol.iterator),isRecord=(input)=>isRecordOrArray(input)&&!Array.isArray(input);var isPromiseLike=(input)=>hasProperty(input,"then")&&isFunction2(input.then);var getBugErrorMessage=(message)=>`BUG: ${message} - please report an issue at https://github.com/Effect-TS/effect/issues`;class SingleShotGen{self;called=!1;constructor(self){this.self=self}next(a){return this.called?{value:a,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(a){return{value:a,done:!0}}throw(e){throw e}[Symbol.iterator](){return new SingleShotGen(this.self)}}var defaultIncHi=335903614,defaultIncLo=4150755663,MUL_HI=1481765933,MUL_LO=1284865837,BIT_53=9007199254740992,BIT_27=134217728;class PCGRandom{_state;constructor(seedHi,seedLo,incHi,incLo){if(isNullable(seedLo)&&isNullable(seedHi))seedLo=Math.random()*4294967295>>>0,seedHi=0;else if(isNullable(seedLo))seedLo=seedHi,seedHi=0;if(isNullable(incLo)&&isNullable(incHi))incLo=this._state?this._state[3]:defaultIncLo,incHi=this._state?this._state[2]:defaultIncHi;else if(isNullable(incLo))incLo=incHi,incHi=0;return this._state=new Int32Array([0,0,incHi>>>0,((incLo||0)|1)>>>0]),this._next(),add64(this._state,this._state[0],this._state[1],seedHi>>>0,seedLo>>>0),this._next(),this}getState(){return[this._state[0],this._state[1],this._state[2],this._state[3]]}setState(state){this._state[0]=state[0],this._state[1]=state[1],this._state[2]=state[2],this._state[3]=state[3]|1}integer(max){return Math.round(this.number()*Number.MAX_SAFE_INTEGER)%max}number(){let hi=(this._next()&67108863)*1,lo=(this._next()&134217727)*1;return(hi*BIT_27+lo)/BIT_53}_next(){let oldHi=this._state[0]>>>0,oldLo=this._state[1]>>>0;mul64(this._state,oldHi,oldLo,MUL_HI,MUL_LO),add64(this._state,this._state[0],this._state[1],this._state[2],this._state[3]);let xsHi=oldHi>>>18,xsLo=(oldLo>>>18|oldHi<<14)>>>0;xsHi=(xsHi^oldHi)>>>0,xsLo=(xsLo^oldLo)>>>0;let xorshifted=(xsLo>>>27|xsHi<<5)>>>0,rot=oldHi>>>27,rot2=(-rot>>>0&31)>>>0;return(xorshifted>>>rot|xorshifted<<rot2)>>>0}}function mul64(out,aHi,aLo,bHi,bLo){let c1=(aLo>>>16)*(bLo&65535)>>>0,c0=(aLo&65535)*(bLo>>>16)>>>0,lo=(aLo&65535)*(bLo&65535)>>>0,hi=(aLo>>>16)*(bLo>>>16)+((c0>>>16)+(c1>>>16))>>>0;if(c0=c0<<16>>>0,lo=lo+c0>>>0,lo>>>0<c0>>>0)hi=hi+1>>>0;if(c1=c1<<16>>>0,lo=lo+c1>>>0,lo>>>0<c1>>>0)hi=hi+1>>>0;hi=hi+Math.imul(aLo,bHi)>>>0,hi=hi+Math.imul(aHi,bLo)>>>0,out[0]=hi,out[1]=lo}function add64(out,aHi,aLo,bHi,bLo){let hi=aHi+bHi>>>0,lo=aLo+bLo>>>0;if(lo>>>0<aLo>>>0)hi=hi+1|0;out[0]=hi,out[1]=lo}var YieldWrapTypeId=Symbol.for("effect/Utils/YieldWrap");class YieldWrap{#value;constructor(value){this.#value=value}[YieldWrapTypeId](){return this.#value}}function yieldWrapGet(self){if(typeof self==="object"&&self!==null&&YieldWrapTypeId in self)return self[YieldWrapTypeId]();throw new Error(getBugErrorMessage("yieldWrapGet"))}var structuralRegionState=globalValue("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0}));var standard={effect_internal_function:(body)=>{return body()}},forced={effect_internal_function:(body)=>{try{return body()}finally{}}},isNotOptimizedAway=standard.effect_internal_function(()=>new Error().stack)?.includes("effect_internal_function")===!0,internalCall=isNotOptimizedAway?standard.effect_internal_function:forced.effect_internal_function,genConstructor=function*(){}.constructor,isGeneratorFunction=(u)=>isObject(u)&&u.constructor===genConstructor;var randomHashCache=globalValue(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),symbol=Symbol.for("effect/Hash"),hash=(self)=>{if(structuralRegionState.enabled===!0)return 0;switch(typeof self){case"number":return number2(self);case"bigint":return string(self.toString(10));case"boolean":return string(String(self));case"symbol":return string(String(self));case"string":return string(self);case"undefined":return string("undefined");case"function":case"object":if(self===null)return string("null");else if(self instanceof Date)return hash(self.toISOString());else if(self instanceof URL)return hash(self.href);else if(isHash(self))return self[symbol]();else return random(self);default:throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},random=(self)=>{if(!randomHashCache.has(self))randomHashCache.set(self,number2(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return randomHashCache.get(self)},combine=(b)=>(self)=>self*53^b,optimize=(n)=>n&3221225471|n>>>1&1073741824,isHash=(u)=>hasProperty(u,symbol),number2=(n)=>{if(n!==n||n===1/0)return 0;let h=n|0;if(h!==n)h^=n*4294967295;while(n>4294967295)h^=n/=4294967295;return optimize(h)},string=(str)=>{let h=5381,i=str.length;while(i)h=h*33^str.charCodeAt(--i);return optimize(h)},structureKeys=(o,keys)=>{let h=12289;for(let i=0;i<keys.length;i++)h^=pipe(string(keys[i]),combine(hash(o[keys[i]])));return optimize(h)},structure=(o)=>structureKeys(o,Object.keys(o)),array2=(arr)=>{let h=6151;for(let i=0;i<arr.length;i++)h=pipe(h,combine(hash(arr[i])));return optimize(h)},cached=function(){if(arguments.length===1){let self2=arguments[0];return function(hash3){return Object.defineProperty(self2,symbol,{value(){return hash3},enumerable:!1}),hash3}}let self=arguments[0],hash2=arguments[1];return Object.defineProperty(self,symbol,{value(){return hash2},enumerable:!1}),hash2};var symbol2=Symbol.for("effect/Equal");function equals(){if(arguments.length===1)return(self)=>compareBoth(self,arguments[0]);return compareBoth(arguments[0],arguments[1])}function compareBoth(self,that){if(self===that)return!0;let selfType=typeof self;if(selfType!==typeof that)return!1;if(selfType==="object"||selfType==="function"){if(self!==null&&that!==null){if(isEqual(self)&&isEqual(that))if(hash(self)===hash(that)&&self[symbol2](that))return!0;else return structuralRegionState.enabled&&structuralRegionState.tester?structuralRegionState.tester(self,that):!1;else if(self instanceof Date&&that instanceof Date)return self.toISOString()===that.toISOString();else if(self instanceof URL&&that instanceof URL)return self.href===that.href}if(structuralRegionState.enabled){if(Array.isArray(self)&&Array.isArray(that))return self.length===that.length&&self.every((v,i)=>compareBoth(v,that[i]));if(Object.getPrototypeOf(self)===Object.prototype&&Object.getPrototypeOf(self)===Object.prototype){let keysSelf=Object.keys(self),keysThat=Object.keys(that);if(keysSelf.length===keysThat.length){for(let key of keysSelf)if(!((key in that)&&compareBoth(self[key],that[key])))return structuralRegionState.tester?structuralRegionState.tester(self,that):!1;return!0}}return structuralRegionState.tester?structuralRegionState.tester(self,that):!1}}return structuralRegionState.enabled&&structuralRegionState.tester?structuralRegionState.tester(self,that):!1}var isEqual=(u)=>hasProperty(u,symbol2),equivalence=()=>equals;var NodeInspectSymbol=Symbol.for("nodejs.util.inspect.custom"),toJSON=(x)=>{try{if(hasProperty(x,"toJSON")&&isFunction2(x.toJSON)&&x.toJSON.length===0)return x.toJSON();else if(Array.isArray(x))return x.map(toJSON)}catch(_){return{}}return redact(x)},format=(x)=>JSON.stringify(x,null,2),BaseProto={toJSON(){return toJSON(this)},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}};var toStringUnknown=(u,whitespace=2)=>{if(typeof u==="string")return u;try{return typeof u==="object"?stringifyCircular(u,whitespace):String(u)}catch(_){return String(u)}},stringifyCircular=(obj,whitespace)=>{let cache=[],retVal=JSON.stringify(obj,(_key,value)=>typeof value==="object"&&value!==null?cache.includes(value)?void 0:cache.push(value)&&(redactableState.fiberRefs!==void 0&&isRedactable(value)?value[symbolRedactable](redactableState.fiberRefs):value):value,whitespace);return cache=void 0,retVal},symbolRedactable=Symbol.for("effect/Inspectable/Redactable"),isRedactable=(u)=>typeof u==="object"&&u!==null&&(symbolRedactable in u),redactableState=globalValue("effect/Inspectable/redactableState",()=>({fiberRefs:void 0})),withRedactableContext=(context,f)=>{let prev=redactableState.fiberRefs;redactableState.fiberRefs=context;try{return f()}finally{redactableState.fiberRefs=prev}},redact=(u)=>{if(isRedactable(u)&&redactableState.fiberRefs!==void 0)return u[symbolRedactable](redactableState.fiberRefs);return u};var pipeArguments=(self,args)=>{switch(args.length){case 0:return self;case 1:return args[0](self);case 2:return args[1](args[0](self));case 3:return args[2](args[1](args[0](self)));case 4:return args[3](args[2](args[1](args[0](self))));case 5:return args[4](args[3](args[2](args[1](args[0](self)))));case 6:return args[5](args[4](args[3](args[2](args[1](args[0](self))))));case 7:return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));case 8:return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));case 9:return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));default:{let ret=self;for(let i=0,len=args.length;i<len;i++)ret=args[i](ret);return ret}}};var OP_ASYNC="Async",OP_COMMIT="Commit",OP_FAILURE="Failure",OP_ON_FAILURE="OnFailure",OP_ON_SUCCESS="OnSuccess",OP_ON_SUCCESS_AND_FAILURE="OnSuccessAndFailure",OP_SUCCESS="Success",OP_SYNC="Sync",OP_TAG="Tag",OP_UPDATE_RUNTIME_FLAGS="UpdateRuntimeFlags",OP_WHILE="While",OP_ITERATOR="Iterator",OP_WITH_RUNTIME="WithRuntime",OP_YIELD="Yield",OP_REVERT_FLAGS="RevertFlags";var EffectTypeId=Symbol.for("effect/Effect"),StreamTypeId=Symbol.for("effect/Stream"),SinkTypeId=Symbol.for("effect/Sink"),ChannelTypeId=Symbol.for("effect/Channel"),effectVariance={_R:(_)=>_,_E:(_)=>_,_A:(_)=>_,_V:getCurrentVersion()},sinkVariance={_A:(_)=>_,_In:(_)=>_,_L:(_)=>_,_E:(_)=>_,_R:(_)=>_},channelVariance={_Env:(_)=>_,_InErr:(_)=>_,_InElem:(_)=>_,_InDone:(_)=>_,_OutErr:(_)=>_,_OutElem:(_)=>_,_OutDone:(_)=>_},EffectPrototype={[EffectTypeId]:effectVariance,[StreamTypeId]:effectVariance,[SinkTypeId]:sinkVariance,[ChannelTypeId]:channelVariance,[symbol2](that){return this===that},[symbol](){return cached(this,random(this))},[Symbol.iterator](){return new SingleShotGen(new YieldWrap(this))},pipe(){return pipeArguments(this,arguments)}},StructuralPrototype={[symbol](){return cached(this,structure(this))},[symbol2](that){let selfKeys=Object.keys(this),thatKeys=Object.keys(that);if(selfKeys.length!==thatKeys.length)return!1;for(let key of selfKeys)if(!((key in that)&&equals(this[key],that[key])))return!1;return!0}},CommitPrototype={...EffectPrototype,_op:OP_COMMIT},StructuralCommitPrototype={...CommitPrototype,...StructuralPrototype},Base=function(){function Base2(){}return Base2.prototype=CommitPrototype,Base2}();var TypeId=Symbol.for("effect/Option"),CommonProto={...EffectPrototype,[TypeId]:{_A:(_)=>_},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}},SomeProto=Object.assign(Object.create(CommonProto),{_tag:"Some",_op:"Some",[symbol2](that){return isOption(that)&&isSome(that)&&equals(this.value,that.value)},[symbol](){return cached(this,combine(hash(this._tag))(hash(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:toJSON(this.value)}}}),NoneHash=hash("None"),NoneProto=Object.assign(Object.create(CommonProto),{_tag:"None",_op:"None",[symbol2](that){return isOption(that)&&isNone(that)},[symbol](){return NoneHash},toJSON(){return{_id:"Option",_tag:this._tag}}}),isOption=(input)=>hasProperty(input,TypeId),isNone=(fa)=>fa._tag==="None",isSome=(fa)=>fa._tag==="Some",none=Object.create(NoneProto),some=(value)=>{let a=Object.create(SomeProto);return a.value=value,a};var TypeId2=Symbol.for("effect/Either"),CommonProto2={...EffectPrototype,[TypeId2]:{_R:(_)=>_},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}},RightProto=Object.assign(Object.create(CommonProto2),{_tag:"Right",_op:"Right",[symbol2](that){return isEither(that)&&isRight(that)&&equals(this.right,that.right)},[symbol](){return combine(hash(this._tag))(hash(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:toJSON(this.right)}}}),LeftProto=Object.assign(Object.create(CommonProto2),{_tag:"Left",_op:"Left",[symbol2](that){return isEither(that)&&isLeft(that)&&equals(this.left,that.left)},[symbol](){return combine(hash(this._tag))(hash(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:toJSON(this.left)}}}),isEither=(input)=>hasProperty(input,TypeId2),isLeft=(ma)=>ma._tag==="Left",isRight=(ma)=>ma._tag==="Right",left=(left2)=>{let a=Object.create(LeftProto);return a.left=left2,a},right=(right2)=>{let a=Object.create(RightProto);return a.right=right2,a};var right2=right;var left2=left;var isEither2=isEither,isLeft2=isLeft,isRight2=isRight;var mapLeft=dual(2,(self,f)=>isLeft2(self)?left2(f(self.left)):right2(self.right)),map=dual(2,(self,f)=>isRight2(self)?right2(f(self.right)):left2(self.left)),match=dual(2,(self,{onLeft,onRight})=>isLeft2(self)?onLeft(self.left):onRight(self.right));var merge=match({onLeft:identity,onRight:identity});var getOrThrowWith=dual(2,(self,onLeft)=>{if(isRight2(self))return self.right;throw onLeft(self.left)}),getOrThrow=getOrThrowWith(()=>new Error("getOrThrow called on a Left"));var isNonEmptyArray=(self)=>self.length>0;var make2=(compare)=>(self,that)=>self===that?0:compare(self,that);var number3=make2((self,that)=>self<that?-1:1);var mapInput2=dual(2,(self,f)=>make2((b1,b2)=>self(f(b1),f(b2))));var all=(collection)=>{return make2((x,y)=>{let len=Math.min(x.length,y.length),collectionLength=0;for(let O of collection){if(collectionLength>=len)break;let o=O(x[collectionLength],y[collectionLength]);if(o!==0)return o;collectionLength++}return 0})};var tuple=(...elements)=>all(elements);var lessThan=(O)=>dual(2,(self,that)=>O(self,that)===-1),greaterThan=(O)=>dual(2,(self,that)=>O(self,that)===1);var min=(O)=>dual(2,(self,that)=>self===that||O(self,that)<1?self:that),max=(O)=>dual(2,(self,that)=>self===that||O(self,that)>-1?self:that),clamp=(O)=>dual(2,(self,options)=>min(O)(options.maximum,max(O)(options.minimum,self))),between=(O)=>dual(2,(self,options)=>!lessThan(O)(self,options.minimum)&&!greaterThan(O)(self,options.maximum));var none2=()=>none,some2=some;var isNone2=isNone,isSome2=isSome,match2=dual(2,(self,{onNone,onSome})=>isNone2(self)?onNone():onSome(self.value));var getOrElse=dual(2,(self,onNone)=>isNone2(self)?onNone():self.value),orElse=dual(2,(self,that)=>isNone2(self)?that():self),orElseSome=dual(2,(self,onNone)=>isNone2(self)?some2(onNone()):self);var fromNullable=(nullableValue)=>nullableValue==null?none2():some2(nullableValue);var getOrUndefined=getOrElse(constUndefined),liftThrowable=(f)=>(...a)=>{try{return some2(f(...a))}catch(e){return none2()}},getOrThrowWith2=dual(2,(self,onNone)=>{if(isSome2(self))return self.value;throw onNone()}),getOrThrow2=getOrThrowWith2(()=>new Error("getOrThrow called on a None")),map2=dual(2,(self,f)=>isNone2(self)?none2():some2(f(self.value)));var flatMap=dual(2,(self,f)=>isNone2(self)?none2():f(self.value));var flatMapNullable=dual(2,(self,f)=>isNone2(self)?none2():fromNullable(f(self.value)));var containsWith=(isEquivalent)=>dual(2,(self,a)=>isNone2(self)?!1:isEquivalent(self.value,a)),_equivalence=equivalence(),contains=containsWith(_equivalence),exists=dual(2,(self,refinement)=>isNone2(self)?!1:refinement(self.value));var mergeWith=(f)=>(o1,o2)=>{if(isNone2(o1))return o2;else if(isNone2(o2))return o1;return some2(f(o1.value,o2.value))};var make3=(...elements)=>elements;var unsafeHead=(self)=>{let result=self[Symbol.iterator]().next();if(result.done)throw new Error("unsafeHead: empty iterable");return result.value};var findFirst=dual(2,(self,f)=>{let i=0;for(let a of self){let o=f(a,i);if(isBoolean(o)){if(o)return some2(a)}else if(isSome2(o))return o;i++}return none2()});var constEmpty={[Symbol.iterator](){return constEmptyIterator}},constEmptyIterator={next(){return{done:!0,value:void 0}}},empty=()=>constEmpty;var allocate=(n)=>new Array(n),makeBy=dual(2,(n,f)=>{let max2=Math.max(1,Math.floor(n)),out=new Array(max2);for(let i=0;i<max2;i++)out[i]=f(i);return out});var fromIterable=(collection)=>Array.isArray(collection)?collection:Array.from(collection),ensure=(self)=>Array.isArray(self)?self:[self];var matchLeft=dual(2,(self,{onEmpty,onNonEmpty})=>isNonEmptyReadonlyArray(self)?onNonEmpty(headNonEmpty(self),tailNonEmpty(self)):onEmpty());var prepend=dual(2,(self,head)=>[head,...self]);var append=dual(2,(self,last)=>[...self,last]),appendAll=dual(2,(self,that)=>fromIterable(self).concat(fromIterable(that)));var isArray=Array.isArray,isEmptyArray=(self)=>self.length===0,isEmptyReadonlyArray=isEmptyArray,isNonEmptyArray2=isNonEmptyArray,isNonEmptyReadonlyArray=isNonEmptyArray;var isOutOfBounds=(i,as)=>i<0||i>=as.length,clamp2=(i,as)=>Math.floor(Math.min(Math.max(0,i),as.length)),get=dual(2,(self,index)=>{let i=Math.floor(index);return isOutOfBounds(i,self)?none2():some2(self[i])}),unsafeGet=dual(2,(self,index)=>{let i=Math.floor(index);if(isOutOfBounds(i,self))throw new Error(`Index ${i} out of bounds`);return self[i]});var head=get(0),headNonEmpty=unsafeGet(0),last=(self)=>isNonEmptyReadonlyArray(self)?some2(lastNonEmpty(self)):none2(),lastNonEmpty=(self)=>self[self.length-1];var tailNonEmpty=(self)=>self.slice(1);var spanIndex=(self,predicate)=>{let i=0;for(let a of self){if(!predicate(a,i))break;i++}return i},span=dual(2,(self,predicate)=>splitAt(self,spanIndex(self,predicate))),drop=dual(2,(self,n)=>{let input=fromIterable(self);return input.slice(clamp2(n,input),input.length)});var findFirst2=findFirst;var reverse=(self)=>Array.from(self).reverse(),sort=dual(2,(self,O)=>{let out=Array.from(self);return out.sort(O),out});var zip=dual(2,(self,that)=>zipWith(self,that,make3)),zipWith=dual(3,(self,that,f)=>{let as=fromIterable(self),bs=fromIterable(that);if(isNonEmptyReadonlyArray(as)&&isNonEmptyReadonlyArray(bs)){let out=[f(headNonEmpty(as),headNonEmpty(bs))],len=Math.min(as.length,bs.length);for(let i=1;i<len;i++)out[i]=f(as[i],bs[i]);return out}return[]});var _equivalence2=equivalence();var splitAt=dual(2,(self,n)=>{let input=Array.from(self),_n=Math.floor(n);if(isNonEmptyReadonlyArray(input)){if(_n>=1)return splitNonEmptyAt(input,_n);return[[],input]}return[input,[]]}),splitNonEmptyAt=dual(2,(self,n)=>{let _n=Math.max(1,Math.floor(n));return _n>=self.length?[copy(self),[]]:[prepend(self.slice(1,_n),headNonEmpty(self)),self.slice(_n)]});var copy=(self)=>self.slice();var unionWith=dual(3,(self,that,isEquivalent)=>{let a=fromIterable(self),b=fromIterable(that);if(isNonEmptyReadonlyArray(a)){if(isNonEmptyReadonlyArray(b))return dedupeWith(isEquivalent)(appendAll(a,b));return a}return b}),union=dual(2,(self,that)=>unionWith(self,that,_equivalence2));var empty2=()=>[],of=(a)=>[a],map3=dual(2,(self,f)=>self.map(f)),flatMap2=dual(2,(self,f)=>{if(isEmptyReadonlyArray(self))return[];let out=[];for(let i=0;i<self.length;i++){let inner=f(self[i],i);for(let j=0;j<inner.length;j++)out.push(inner[j])}return out}),flatten=flatMap2(identity),filterMap=dual(2,(self,f)=>{let as=fromIterable(self),out=[];for(let i=0;i<as.length;i++){let o=f(as[i],i);if(isSome2(o))out.push(o.value)}return out}),filterMapWhile=dual(2,(self,f)=>{let i=0,out=[];for(let a of self){let b=f(a,i);if(isSome2(b))out.push(b.value);else break;i++}return out}),partitionMap=dual(2,(self,f)=>{let left3=[],right3=[],as=fromIterable(self);for(let i=0;i<as.length;i++){let e=f(as[i],i);if(isLeft2(e))left3.push(e.left);else right3.push(e.right)}return[left3,right3]}),getSomes=filterMap(identity);var filter=dual(2,(self,predicate)=>{let as=fromIterable(self),out=[];for(let i=0;i<as.length;i++)if(predicate(as[i],i))out.push(as[i]);return out});var reduce=dual(3,(self,b,f)=>fromIterable(self).reduce((b2,a,i)=>f(b2,a,i),b)),reduceRight=dual(3,(self,b,f)=>fromIterable(self).reduceRight((b2,a,i)=>f(b2,a,i),b));var every=dual(2,(self,refinement)=>self.every(refinement));var unfold=(b,f)=>{let out=[],next=b,o;while(isSome2(o=f(next))){let[a,b2]=o.value;out.push(a),next=b2}return out};var getEquivalence=array;var dedupeWith=dual(2,(self,isEquivalent)=>{let input=fromIterable(self);if(isNonEmptyReadonlyArray(input)){let out=[headNonEmpty(input)],rest=tailNonEmpty(input);for(let r of rest)if(out.every((a)=>!isEquivalent(r,a)))out.push(r);return out}return[]}),dedupe=(self)=>dedupeWith(self,equivalence());var join=dual(2,(self,sep)=>fromIterable(self).join(sep)),mapAccum=dual(3,(self,s,f)=>{let i=0,s1=s,out=[];for(let a of self){let r=f(s1,a,i);s1=r[0],out.push(r[1]),i++}return[s1,out]});var getKeysForIndexSignature=(input,parameter)=>{switch(parameter._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(input);case"SymbolKeyword":return Object.getOwnPropertySymbols(input);case"Refinement":return getKeysForIndexSignature(input,parameter.from)}},ownKeys=(o)=>Object.keys(o).concat(Object.getOwnPropertySymbols(o)),memoizeThunk=(f)=>{let done=!1,a;return()=>{if(done)return a;return a=f(),done=!0,a}},formatDate=(date)=>{try{return date.toISOString()}catch(e){return String(date)}},formatUnknown=(u,checkCircular=!0)=>{if(Array.isArray(u))return`[${u.map((i)=>formatUnknown(i,checkCircular)).join(",")}]`;if(isDate(u))return formatDate(u);if(hasProperty(u,"toString")&&isFunction2(u.toString)&&u.toString!==Object.prototype.toString)return u.toString();if(isString(u))return JSON.stringify(u);if(isNumber(u)||u==null||isBoolean(u)||isSymbol(u))return String(u);if(isBigInt(u))return String(u)+"n";if(isIterable(u))return`${u.constructor.name}(${formatUnknown(Array.from(u),checkCircular)})`;try{if(checkCircular)JSON.stringify(u);let pojo=`{${ownKeys(u).map((k)=>`${isString(k)?JSON.stringify(k):String(k)}:${formatUnknown(u[k],!1)}`).join(",")}}`,name=u.constructor.name;return u.constructor!==Object.prototype.constructor?`${name}(${pojo})`:pojo}catch(e){return"<circular structure>"}},formatPropertyKey=(name)=>typeof name==="string"?JSON.stringify(name):String(name),isNonEmpty=(x)=>Array.isArray(x),isSingle=(x)=>!Array.isArray(x),formatPathKey=(key)=>`[${formatPropertyKey(key)}]`,formatPath=(path)=>isNonEmpty(path)?path.map(formatPathKey).join(""):formatPathKey(path);var getErrorMessage=(reason,details,path,ast)=>{let out=reason;if(path&&isNonEmptyReadonlyArray(path))out+=`
|
|
2
|
+
at path: ${formatPath(path)}`;if(details!==void 0)out+=`
|
|
3
|
+
details: ${details}`;if(ast)out+=`
|
|
4
|
+
schema (${ast._tag}): ${ast}`;return out};var getASTDuplicateIndexSignatureErrorMessage=(type)=>getErrorMessage("Duplicate index signature",`${type} index signature`),getASTIndexSignatureParameterErrorMessage=getErrorMessage("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),getASTRequiredElementFollowinAnOptionalElementErrorMessage=getErrorMessage("Invalid element","A required element cannot follow an optional element. ts(1257)");var getASTDuplicatePropertySignatureErrorMessage=(key)=>getErrorMessage("Duplicate property signature",`Duplicate key ${formatUnknown(key)}`);var DateFromSelfSchemaId=Symbol.for("effect/SchemaId/DateFromSelf");var Order=number3;var nextPow2=(n)=>{let nextPow=Math.ceil(Math.log(n)/Math.log(2));return Math.max(Math.pow(2,nextPow),2)};var escape=(string2)=>string2.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var BrandAnnotationId=Symbol.for("effect/annotation/Brand"),SchemaIdAnnotationId=Symbol.for("effect/annotation/SchemaId"),MessageAnnotationId=Symbol.for("effect/annotation/Message"),MissingMessageAnnotationId=Symbol.for("effect/annotation/MissingMessage"),IdentifierAnnotationId=Symbol.for("effect/annotation/Identifier"),TitleAnnotationId=Symbol.for("effect/annotation/Title"),AutoTitleAnnotationId=Symbol.for("effect/annotation/AutoTitle"),DescriptionAnnotationId=Symbol.for("effect/annotation/Description"),ExamplesAnnotationId=Symbol.for("effect/annotation/Examples"),DefaultAnnotationId=Symbol.for("effect/annotation/Default"),JSONSchemaAnnotationId=Symbol.for("effect/annotation/JSONSchema"),ArbitraryAnnotationId=Symbol.for("effect/annotation/Arbitrary"),PrettyAnnotationId=Symbol.for("effect/annotation/Pretty"),EquivalenceAnnotationId=Symbol.for("effect/annotation/Equivalence"),DocumentationAnnotationId=Symbol.for("effect/annotation/Documentation"),ConcurrencyAnnotationId=Symbol.for("effect/annotation/Concurrency"),BatchingAnnotationId=Symbol.for("effect/annotation/Batching"),ParseIssueTitleAnnotationId=Symbol.for("effect/annotation/ParseIssueTitle"),ParseOptionsAnnotationId=Symbol.for("effect/annotation/ParseOptions"),DecodingFallbackAnnotationId=Symbol.for("effect/annotation/DecodingFallback"),SurrogateAnnotationId=Symbol.for("effect/annotation/Surrogate"),StableFilterAnnotationId=Symbol.for("effect/annotation/StableFilter"),getAnnotation=dual(2,(annotated,key)=>Object.prototype.hasOwnProperty.call(annotated.annotations,key)?some2(annotated.annotations[key]):none2()),getBrandAnnotation=getAnnotation(BrandAnnotationId);var getMessageAnnotation=getAnnotation(MessageAnnotationId),getMissingMessageAnnotation=getAnnotation(MissingMessageAnnotationId),getTitleAnnotation=getAnnotation(TitleAnnotationId),getAutoTitleAnnotation=getAnnotation(AutoTitleAnnotationId),getIdentifierAnnotation=getAnnotation(IdentifierAnnotationId),getDescriptionAnnotation=getAnnotation(DescriptionAnnotationId);var getConcurrencyAnnotation=getAnnotation(ConcurrencyAnnotationId),getBatchingAnnotation=getAnnotation(BatchingAnnotationId),getParseIssueTitleAnnotation=getAnnotation(ParseIssueTitleAnnotationId),getParseOptionsAnnotation=getAnnotation(ParseOptionsAnnotationId),getDecodingFallbackAnnotation=getAnnotation(DecodingFallbackAnnotationId),getSurrogateAnnotation=getAnnotation(SurrogateAnnotationId),getStableFilterAnnotation=getAnnotation(StableFilterAnnotationId),hasStableFilter=(annotated)=>exists(getStableFilterAnnotation(annotated),(b)=>b===!0),JSONIdentifierAnnotationId=Symbol.for("effect/annotation/JSONIdentifier"),getJSONIdentifierAnnotation=getAnnotation(JSONIdentifierAnnotationId),getJSONIdentifier=(annotated)=>orElse(getJSONIdentifierAnnotation(annotated),()=>getIdentifierAnnotation(annotated));class Declaration{typeParameters;decodeUnknown;encodeUnknown;annotations;_tag="Declaration";constructor(typeParameters,decodeUnknown,encodeUnknown,annotations={}){this.typeParameters=typeParameters,this.decodeUnknown=decodeUnknown,this.encodeUnknown=encodeUnknown,this.annotations=annotations}toString(){return getOrElse(getExpected(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((ast)=>ast.toJSON()),annotations:toJSONAnnotations(this.annotations)}}}var createASTGuard=(tag)=>(ast)=>ast._tag===tag;class Literal{literal;annotations;_tag="Literal";constructor(literal,annotations={}){this.literal=literal,this.annotations=annotations}toString(){return getOrElse(getExpected(this),()=>formatUnknown(this.literal))}toJSON(){return{_tag:this._tag,literal:isBigInt(this.literal)?String(this.literal):this.literal,annotations:toJSONAnnotations(this.annotations)}}}var isLiteral=createASTGuard("Literal");class UniqueSymbol{symbol;annotations;_tag="UniqueSymbol";constructor(symbol3,annotations={}){this.symbol=symbol3,this.annotations=annotations}toString(){return getOrElse(getExpected(this),()=>formatUnknown(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:toJSONAnnotations(this.annotations)}}}class UndefinedKeyword{annotations;_tag="UndefinedKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var undefinedKeyword=new UndefinedKeyword({[TitleAnnotationId]:"undefined"});class VoidKeyword{annotations;_tag="VoidKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var voidKeyword=new VoidKeyword({[TitleAnnotationId]:"void"});class NeverKeyword{annotations;_tag="NeverKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var neverKeyword=new NeverKeyword({[TitleAnnotationId]:"never"});class UnknownKeyword{annotations;_tag="UnknownKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var unknownKeyword=new UnknownKeyword({[TitleAnnotationId]:"unknown"});class AnyKeyword{annotations;_tag="AnyKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var anyKeyword=new AnyKeyword({[TitleAnnotationId]:"any"});class StringKeyword{annotations;_tag="StringKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var stringKeyword=new StringKeyword({[TitleAnnotationId]:"string",[DescriptionAnnotationId]:"a string"}),isStringKeyword=createASTGuard("StringKeyword");class NumberKeyword{annotations;_tag="NumberKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var numberKeyword=new NumberKeyword({[TitleAnnotationId]:"number",[DescriptionAnnotationId]:"a number"});class BooleanKeyword{annotations;_tag="BooleanKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var booleanKeyword=new BooleanKeyword({[TitleAnnotationId]:"boolean",[DescriptionAnnotationId]:"a boolean"});class BigIntKeyword{annotations;_tag="BigIntKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var bigIntKeyword=new BigIntKeyword({[TitleAnnotationId]:"bigint",[DescriptionAnnotationId]:"a bigint"});class SymbolKeyword{annotations;_tag="SymbolKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var symbolKeyword=new SymbolKeyword({[TitleAnnotationId]:"symbol",[DescriptionAnnotationId]:"a symbol"}),isSymbolKeyword=createASTGuard("SymbolKeyword");class ObjectKeyword{annotations;_tag="ObjectKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var objectKeyword=new ObjectKeyword({[TitleAnnotationId]:"object",[DescriptionAnnotationId]:"an object in the TypeScript meaning, i.e. the `object` type"});class Type{type;annotations;constructor(type,annotations={}){this.type=type,this.annotations=annotations}toJSON(){return{type:this.type.toJSON(),annotations:toJSONAnnotations(this.annotations)}}toString(){return String(this.type)}}class OptionalType extends Type{isOptional;constructor(type,isOptional,annotations={}){super(type,annotations);this.isOptional=isOptional}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:toJSONAnnotations(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}}var getRestASTs=(rest)=>rest.map((annotatedAST)=>annotatedAST.type);class TupleType{elements;rest;isReadonly;annotations;_tag="TupleType";constructor(elements,rest,isReadonly,annotations={}){this.elements=elements,this.rest=rest,this.isReadonly=isReadonly,this.annotations=annotations;let hasOptionalElement=!1,hasIllegalRequiredElement=!1;for(let e of elements)if(e.isOptional)hasOptionalElement=!0;else if(hasOptionalElement){hasIllegalRequiredElement=!0;break}if(hasIllegalRequiredElement||hasOptionalElement&&rest.length>1)throw new Error(getASTRequiredElementFollowinAnOptionalElementErrorMessage)}toString(){return getOrElse(getExpected(this),()=>formatTuple(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((ast)=>ast.toJSON()),isReadonly:this.isReadonly,annotations:toJSONAnnotations(this.annotations)}}}var formatTuple=(ast)=>{let formattedElements=ast.elements.map(String).join(", ");return matchLeft(ast.rest,{onEmpty:()=>`readonly [${formattedElements}]`,onNonEmpty:(head2,tail)=>{let formattedHead=String(head2),wrappedHead=formattedHead.includes(" | ")?`(${formattedHead})`:formattedHead;if(tail.length>0){let formattedTail=tail.map(String).join(", ");if(ast.elements.length>0)return`readonly [${formattedElements}, ...${wrappedHead}[], ${formattedTail}]`;else return`readonly [...${wrappedHead}[], ${formattedTail}]`}else if(ast.elements.length>0)return`readonly [${formattedElements}, ...${wrappedHead}[]]`;else return`ReadonlyArray<${formattedHead}>`}})};class PropertySignature extends OptionalType{name;isReadonly;constructor(name,type,isOptional,isReadonly,annotations){super(type,isOptional,annotations);this.name=name,this.isReadonly=isReadonly}toString(){return(this.isReadonly?"readonly ":"")+String(this.name)+(this.isOptional?"?":"")+": "+this.type}toJSON(){return{name:String(this.name),type:this.type.toJSON(),isOptional:this.isOptional,isReadonly:this.isReadonly,annotations:toJSONAnnotations(this.annotations)}}}var isParameter=(ast)=>{switch(ast._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return isParameter(ast.from)}return!1};class IndexSignature{type;isReadonly;parameter;constructor(parameter,type,isReadonly){if(this.type=type,this.isReadonly=isReadonly,isParameter(parameter))this.parameter=parameter;else throw new Error(getASTIndexSignatureParameterErrorMessage)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class TypeLiteral{annotations;_tag="TypeLiteral";propertySignatures;indexSignatures;constructor(propertySignatures,indexSignatures,annotations={}){this.annotations=annotations;let keys={};for(let i=0;i<propertySignatures.length;i++){let name=propertySignatures[i].name;if(Object.prototype.hasOwnProperty.call(keys,name))throw new Error(getASTDuplicatePropertySignatureErrorMessage(name));keys[name]=null}let parameters={string:!1,symbol:!1};for(let i=0;i<indexSignatures.length;i++){let encodedParameter=getEncodedParameter(indexSignatures[i].parameter);if(isStringKeyword(encodedParameter)){if(parameters.string)throw new Error(getASTDuplicateIndexSignatureErrorMessage("string"));parameters.string=!0}else if(isSymbolKeyword(encodedParameter)){if(parameters.symbol)throw new Error(getASTDuplicateIndexSignatureErrorMessage("symbol"));parameters.symbol=!0}}this.propertySignatures=propertySignatures,this.indexSignatures=indexSignatures}toString(){return getOrElse(getExpected(this),()=>formatTypeLiteral(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((ps)=>ps.toJSON()),indexSignatures:this.indexSignatures.map((ps)=>ps.toJSON()),annotations:toJSONAnnotations(this.annotations)}}}var formatIndexSignatures=(iss)=>iss.map(String).join("; "),formatTypeLiteral=(ast)=>{if(ast.propertySignatures.length>0){let pss=ast.propertySignatures.map(String).join("; ");if(ast.indexSignatures.length>0)return`{ ${pss}; ${formatIndexSignatures(ast.indexSignatures)} }`;else return`{ ${pss} }`}else if(ast.indexSignatures.length>0)return`{ ${formatIndexSignatures(ast.indexSignatures)} }`;else return"{}"};var sortCandidates=sort(mapInput2(Order,(ast)=>{switch(ast._tag){case"AnyKeyword":return 0;case"UnknownKeyword":return 1;case"ObjectKeyword":return 2;case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":return 3}return 4})),literalMap={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"},flatten2=(candidates)=>flatMap2(candidates,(ast)=>isUnion(ast)?flatten2(ast.types):[ast]),unify=(candidates)=>{let cs=sortCandidates(candidates),out=[],uniques={},literals=[];for(let ast of cs)switch(ast._tag){case"NeverKeyword":break;case"AnyKeyword":return[anyKeyword];case"UnknownKeyword":return[unknownKeyword];case"ObjectKeyword":case"UndefinedKeyword":case"VoidKeyword":case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":{if(!uniques[ast._tag])uniques[ast._tag]=ast,out.push(ast);break}case"Literal":{let type=typeof ast.literal;switch(type){case"string":case"number":case"bigint":case"boolean":{let _tag=literalMap[type];if(!uniques[_tag]&&!literals.includes(ast.literal))literals.push(ast.literal),out.push(ast);break}case"object":{if(!literals.includes(ast.literal))literals.push(ast.literal),out.push(ast);break}}break}case"UniqueSymbol":{if(!uniques.SymbolKeyword&&!literals.includes(ast.symbol))literals.push(ast.symbol),out.push(ast);break}case"TupleType":{if(!uniques.ObjectKeyword)out.push(ast);break}case"TypeLiteral":{if(ast.propertySignatures.length===0&&ast.indexSignatures.length===0){if(!uniques["{}"])uniques["{}"]=ast,out.push(ast)}else if(!uniques.ObjectKeyword)out.push(ast);break}default:out.push(ast)}return out};class Union{types;annotations;static make=(types,annotations)=>{return isMembers(types)?new Union(types,annotations):types.length===1?types[0]:neverKeyword};static unify=(candidates,annotations)=>{return Union.make(unify(flatten2(candidates)),annotations)};_tag="Union";constructor(types,annotations={}){this.types=types,this.annotations=annotations}toString(){return getOrElse(getExpected(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((ast)=>ast.toJSON()),annotations:toJSONAnnotations(this.annotations)}}}var isMembers=(as)=>as.length>1,isUnion=createASTGuard("Union"),toJSONMemoMap=globalValue(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);class Suspend{f;annotations;_tag="Suspend";constructor(f,annotations={}){this.f=f,this.annotations=annotations,this.f=memoizeThunk(f)}toString(){return getExpected(this).pipe(orElse(()=>flatMap(liftThrowable(this.f)(),(ast)=>getExpected(ast))),getOrElse(()=>"<suspended schema>"))}toJSON(){let ast=this.f(),out=toJSONMemoMap.get(ast);if(out)return out;return toJSONMemoMap.set(ast,{_tag:this._tag}),out={_tag:this._tag,ast:ast.toJSON(),annotations:toJSONAnnotations(this.annotations)},toJSONMemoMap.set(ast,out),out}}class Refinement{from;filter;annotations;_tag="Refinement";constructor(from,filter2,annotations={}){this.from=from,this.filter=filter2,this.annotations=annotations}toString(){return getIdentifierAnnotation(this).pipe(getOrElse(()=>match2(getOrElseExpected(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(expected)=>isRefinement(this.from)?String(this.from)+" & "+expected:expected})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:toJSONAnnotations(this.annotations)}}}var isRefinement=createASTGuard("Refinement"),defaultParseOption={};var annotations=(ast,overrides)=>{let d=Object.getOwnPropertyDescriptors(ast),value={...ast.annotations,...overrides},surrogate=getSurrogateAnnotation(ast);if(isSome2(surrogate))value[SurrogateAnnotationId]=annotations(surrogate.value,overrides);return d.annotations.value=value,Object.create(Object.getPrototypeOf(ast),d)};var STRING_KEYWORD_PATTERN="[\\s\\S]*",NUMBER_KEYWORD_PATTERN="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",getTemplateLiteralSpanTypePattern=(type,capture)=>{switch(type._tag){case"Literal":return escape(String(type.literal));case"StringKeyword":return STRING_KEYWORD_PATTERN;case"NumberKeyword":return NUMBER_KEYWORD_PATTERN;case"TemplateLiteral":return getTemplateLiteralPattern(type,capture,!1);case"Union":return type.types.map((type2)=>getTemplateLiteralSpanTypePattern(type2,capture)).join("|")}},handleTemplateLiteralSpanTypeParens=(type,s,capture,top)=>{if(isUnion(type)){if(capture&&!top)return`(?:${s})`}else if(!capture||!top)return s;return`(${s})`},getTemplateLiteralPattern=(ast,capture,top)=>{let pattern="";if(ast.head!==""){let head2=escape(ast.head);pattern+=capture&&top?`(${head2})`:head2}for(let span2 of ast.spans){let spanPattern=getTemplateLiteralSpanTypePattern(span2.type,capture);if(pattern+=handleTemplateLiteralSpanTypeParens(span2.type,spanPattern,capture,top),span2.literal!==""){let literal=escape(span2.literal);pattern+=capture&&top?`(${literal})`:literal}}return pattern},getTemplateLiteralRegExp=(ast)=>new RegExp(`^${getTemplateLiteralPattern(ast,!1,!0)}$`);var pickAnnotations=(annotationIds)=>(annotated)=>{let out=void 0;for(let id of annotationIds)if(Object.prototype.hasOwnProperty.call(annotated.annotations,id)){if(out===void 0)out={};out[id]=annotated.annotations[id]}return out};var preserveTransformationAnnotations=pickAnnotations([ExamplesAnnotationId,DefaultAnnotationId,JSONSchemaAnnotationId,ArbitraryAnnotationId,PrettyAnnotationId,EquivalenceAnnotationId]),typeAST=(ast)=>{switch(ast._tag){case"Declaration":{let typeParameters=changeMap(ast.typeParameters,typeAST);return typeParameters===ast.typeParameters?ast:new Declaration(typeParameters,ast.decodeUnknown,ast.encodeUnknown,ast.annotations)}case"TupleType":{let elements=changeMap(ast.elements,(e)=>{let type=typeAST(e.type);return type===e.type?e:new OptionalType(type,e.isOptional)}),restASTs=getRestASTs(ast.rest),rest=changeMap(restASTs,typeAST);return elements===ast.elements&&rest===restASTs?ast:new TupleType(elements,rest.map((type)=>new Type(type)),ast.isReadonly,ast.annotations)}case"TypeLiteral":{let propertySignatures=changeMap(ast.propertySignatures,(p)=>{let type=typeAST(p.type);return type===p.type?p:new PropertySignature(p.name,type,p.isOptional,p.isReadonly)}),indexSignatures=changeMap(ast.indexSignatures,(is)=>{let type=typeAST(is.type);return type===is.type?is:new IndexSignature(is.parameter,type,is.isReadonly)});return propertySignatures===ast.propertySignatures&&indexSignatures===ast.indexSignatures?ast:new TypeLiteral(propertySignatures,indexSignatures,ast.annotations)}case"Union":{let types=changeMap(ast.types,typeAST);return types===ast.types?ast:Union.make(types,ast.annotations)}case"Suspend":return new Suspend(()=>typeAST(ast.f()),ast.annotations);case"Refinement":{let from=typeAST(ast.from);return from===ast.from?ast:new Refinement(from,ast.filter,ast.annotations)}case"Transformation":{let preserve=preserveTransformationAnnotations(ast);return typeAST(preserve!==void 0?annotations(ast.to,preserve):ast.to)}}return ast},createJSONIdentifierAnnotation=(annotated)=>match2(getJSONIdentifier(annotated),{onNone:()=>{return},onSome:(identifier)=>({[JSONIdentifierAnnotationId]:identifier})});function changeMap(as,f){let changed=!1,out=allocate(as.length);for(let i=0;i<as.length;i++){let a=as[i],fa=f(a);if(fa!==a)changed=!0;out[i]=fa}return changed?out:as}var getTransformationFrom=(ast)=>{switch(ast._tag){case"Transformation":return ast.from;case"Refinement":return getTransformationFrom(ast.from);case"Suspend":return getTransformationFrom(ast.f())}},encodedAST_=(ast,isBound)=>{switch(ast._tag){case"Declaration":{let typeParameters=changeMap(ast.typeParameters,(ast2)=>encodedAST_(ast2,isBound));return typeParameters===ast.typeParameters?ast:new Declaration(typeParameters,ast.decodeUnknown,ast.encodeUnknown,ast.annotations)}case"TupleType":{let elements=changeMap(ast.elements,(e)=>{let type=encodedAST_(e.type,isBound);return type===e.type?e:new OptionalType(type,e.isOptional)}),restASTs=getRestASTs(ast.rest),rest=changeMap(restASTs,(ast2)=>encodedAST_(ast2,isBound));return elements===ast.elements&&rest===restASTs?ast:new TupleType(elements,rest.map((ast2)=>new Type(ast2)),ast.isReadonly,createJSONIdentifierAnnotation(ast))}case"TypeLiteral":{let propertySignatures=changeMap(ast.propertySignatures,(ps)=>{let type=encodedAST_(ps.type,isBound);return type===ps.type?ps:new PropertySignature(ps.name,type,ps.isOptional,ps.isReadonly)}),indexSignatures=changeMap(ast.indexSignatures,(is)=>{let type=encodedAST_(is.type,isBound);return type===is.type?is:new IndexSignature(is.parameter,type,is.isReadonly)});return propertySignatures===ast.propertySignatures&&indexSignatures===ast.indexSignatures?ast:new TypeLiteral(propertySignatures,indexSignatures,createJSONIdentifierAnnotation(ast))}case"Union":{let types=changeMap(ast.types,(ast2)=>encodedAST_(ast2,isBound));return types===ast.types?ast:Union.make(types,createJSONIdentifierAnnotation(ast))}case"Suspend":return new Suspend(()=>encodedAST_(ast.f(),isBound),createJSONIdentifierAnnotation(ast));case"Refinement":{let from=encodedAST_(ast.from,isBound);if(isBound){if(from===ast.from)return ast;if(getTransformationFrom(ast.from)===void 0&&hasStableFilter(ast))return new Refinement(from,ast.filter,ast.annotations)}let identifier=createJSONIdentifierAnnotation(ast);return identifier?annotations(from,identifier):from}case"Transformation":{let identifier=createJSONIdentifierAnnotation(ast);return encodedAST_(identifier?annotations(ast.from,identifier):ast.from,isBound)}}return ast},encodedAST=(ast)=>encodedAST_(ast,!1);var toJSONAnnotations=(annotations2)=>{let out={};for(let k of Object.getOwnPropertySymbols(annotations2))out[String(k)]=annotations2[k];return out},getEncodedParameter=(ast)=>{switch(ast._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return ast;case"Refinement":return getEncodedParameter(ast.from)}};var formatKeyword=(ast)=>getOrElse(getExpected(ast),()=>ast._tag);function getBrands(ast){return match2(getBrandAnnotation(ast),{onNone:()=>"",onSome:(brands)=>brands.map((brand)=>` & Brand<${formatUnknown(brand)}>`).join("")})}var getOrElseExpected=(ast)=>getTitleAnnotation(ast).pipe(orElse(()=>getDescriptionAnnotation(ast)),orElse(()=>getAutoTitleAnnotation(ast)),map2((s)=>s+getBrands(ast))),getExpected=(ast)=>orElse(getIdentifierAnnotation(ast),()=>getOrElseExpected(ast));var TypeId3=Symbol.for("effect/BigDecimal"),BigDecimalProto={[TypeId3]:TypeId3,[symbol](){let normalized=normalize(this);return pipe(hash(normalized.value),combine(number2(normalized.scale)),cached(this))},[symbol2](that){return isBigDecimal(that)&&equals2(this,that)},toString(){return`BigDecimal(${format2(this)})`},toJSON(){return{_id:"BigDecimal",value:String(this.value),scale:this.scale}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},isBigDecimal=(u)=>hasProperty(u,TypeId3),make4=(value,scale)=>{let o=Object.create(BigDecimalProto);return o.value=value,o.scale=scale,o},unsafeMakeNormalized=(value,scale)=>{if(value!==bigint0&&value%bigint10===bigint0)throw new RangeError("Value must be normalized");let o=make4(value,scale);return o.normalized=o,o},bigint0=BigInt(0);var bigint10=BigInt(10),zero=unsafeMakeNormalized(bigint0,0),normalize=(self)=>{if(self.normalized===void 0)if(self.value===bigint0)self.normalized=zero;else{let digits=`${self.value}`,trail=0;for(let i=digits.length-1;i>=0;i--)if(digits[i]==="0")trail++;else break;if(trail===0)self.normalized=self;let value=BigInt(digits.substring(0,digits.length-trail)),scale=self.scale-trail;self.normalized=unsafeMakeNormalized(value,scale)}return self.normalized},scale=dual(2,(self,scale2)=>{if(scale2>self.scale)return make4(self.value*bigint10**BigInt(scale2-self.scale),scale2);if(scale2<self.scale)return make4(self.value/bigint10**BigInt(self.scale-scale2),scale2);return self});var abs=(n)=>n.value<bigint0?make4(-n.value,n.scale):n;var Equivalence=make((self,that)=>{if(self.scale>that.scale)return scale(that,self.scale).value===self.value;if(self.scale<that.scale)return scale(self,that.scale).value===that.value;return self.value===that.value}),equals2=dual(2,(self,that)=>Equivalence(self,that));var format2=(n)=>{let normalized=normalize(n);if(Math.abs(normalized.scale)>=16)return toExponential(normalized);let negative=normalized.value<bigint0,absolute=negative?`${normalized.value}`.substring(1):`${normalized.value}`,before,after;if(normalized.scale>=absolute.length)before="0",after="0".repeat(normalized.scale-absolute.length)+absolute;else{let location=absolute.length-normalized.scale;if(location>absolute.length){let zeros=location-absolute.length;before=`${absolute}${"0".repeat(zeros)}`,after=""}else after=absolute.slice(location),before=absolute.slice(0,location)}let complete=after===""?before:`${before}.${after}`;return negative?`-${complete}`:complete},toExponential=(n)=>{if(isZero(n))return"0e+0";let normalized=normalize(n),digits=`${abs(normalized).value}`,head2=digits.slice(0,1),tail=digits.slice(1),output=`${isNegative(normalized)?"-":""}${head2}`;if(tail!=="")output+=`.${tail}`;let exp=tail.length-normalized.scale;return`${output}e${exp>=0?"+":""}${exp}`};var isZero=(n)=>n.value===bigint0,isNegative=(n)=>n.value<bigint0;var not=(self)=>!self;var TagTypeId=Symbol.for("effect/Context/Tag"),ReferenceTypeId=Symbol.for("effect/Context/Reference"),STMSymbolKey="effect/STM",STMTypeId=Symbol.for(STMSymbolKey),TagProto={...EffectPrototype,_op:"Tag",[STMTypeId]:effectVariance,[TagTypeId]:{_Service:(_)=>_,_Identifier:(_)=>_},toString(){return format(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[NodeInspectSymbol](){return this.toJSON()},of(self){return self},context(self){return make5(this,self)}},ReferenceProto={...TagProto,[ReferenceTypeId]:ReferenceTypeId},makeGenericTag=(key)=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=new Error;Error.stackTraceLimit=limit;let tag=Object.create(TagProto);return Object.defineProperty(tag,"stack",{get(){return creationError.stack}}),tag.key=key,tag};var Reference=()=>(id,options)=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=new Error;Error.stackTraceLimit=limit;function ReferenceClass(){}return Object.setPrototypeOf(ReferenceClass,ReferenceProto),ReferenceClass.key=id,ReferenceClass.defaultValue=options.defaultValue,Object.defineProperty(ReferenceClass,"stack",{get(){return creationError.stack}}),ReferenceClass},TypeId4=Symbol.for("effect/Context"),ContextProto={[TypeId4]:{_Services:(_)=>_},[symbol2](that){if(isContext(that)){if(this.unsafeMap.size===that.unsafeMap.size){for(let k of this.unsafeMap.keys())if(!that.unsafeMap.has(k)||!equals(this.unsafeMap.get(k),that.unsafeMap.get(k)))return!1;return!0}}return!1},[symbol](){return cached(this,number2(this.unsafeMap.size))},pipe(){return pipeArguments(this,arguments)},toString(){return format(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()}},makeContext=(unsafeMap)=>{let context=Object.create(ContextProto);return context.unsafeMap=unsafeMap,context},serviceNotFoundError=(tag)=>{let error=new Error(`Service not found${tag.key?`: ${String(tag.key)}`:""}`);if(tag.stack){let lines=tag.stack.split(`
|
|
5
|
+
`);if(lines.length>2){let afterAt=lines[2].match(/at (.*)/);if(afterAt)error.message=error.message+` (defined at ${afterAt[1]})`}}if(error.stack){let lines=error.stack.split(`
|
|
6
|
+
`);lines.splice(1,3),error.stack=lines.join(`
|
|
7
|
+
`)}return error},isContext=(u)=>hasProperty(u,TypeId4),isTag=(u)=>hasProperty(u,TagTypeId),isReference=(u)=>hasProperty(u,ReferenceTypeId),_empty=makeContext(new Map),empty3=()=>_empty,make5=(tag,service)=>makeContext(new Map([[tag.key,service]])),add=dual(3,(self,tag,service)=>{let map4=new Map(self.unsafeMap);return map4.set(tag.key,service),makeContext(map4)}),defaultValueCache=globalValue("effect/Context/defaultValueCache",()=>new Map),getDefaultValue=(tag)=>{if(defaultValueCache.has(tag.key))return defaultValueCache.get(tag.key);let value=tag.defaultValue();return defaultValueCache.set(tag.key,value),value},unsafeGetReference=(self,tag)=>{return self.unsafeMap.has(tag.key)?self.unsafeMap.get(tag.key):getDefaultValue(tag)},unsafeGet2=dual(2,(self,tag)=>{if(!self.unsafeMap.has(tag.key)){if(ReferenceTypeId in tag)return getDefaultValue(tag);throw serviceNotFoundError(tag)}return self.unsafeMap.get(tag.key)}),get2=unsafeGet2;var getOption=dual(2,(self,tag)=>{if(!self.unsafeMap.has(tag.key))return isReference(tag)?some(getDefaultValue(tag)):none;return some(self.unsafeMap.get(tag.key))}),merge2=dual(2,(self,that)=>{let map4=new Map(self.unsafeMap);for(let[tag,s]of that.unsafeMap)map4.set(tag,s);return makeContext(map4)});var GenericTag=makeGenericTag;var isContext2=isContext,isTag2=isTag;var empty4=empty3,make6=make5,add2=add,get3=get2;var unsafeGet3=unsafeGet2,getOption2=getOption,merge3=merge2;var Reference2=Reference;var TypeId5=Symbol.for("effect/Chunk");function copy2(src,srcPos,dest,destPos,len){for(let i=srcPos;i<Math.min(src.length,srcPos+len);i++)dest[destPos+i-srcPos]=src[i];return dest}var emptyArray=[],getEquivalence2=(isEquivalent)=>make((self,that)=>self.length===that.length&&toReadonlyArray(self).every((value,i)=>isEquivalent(value,unsafeGet4(that,i)))),_equivalence3=getEquivalence2(equals),ChunkProto={[TypeId5]:{_A:(_)=>_},toString(){return format(this.toJSON())},toJSON(){return{_id:"Chunk",values:toReadonlyArray(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},[symbol2](that){return isChunk(that)&&_equivalence3(this,that)},[symbol](){return cached(this,array2(toReadonlyArray(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return emptyArray[Symbol.iterator]();default:return toReadonlyArray(this)[Symbol.iterator]()}},pipe(){return pipeArguments(this,arguments)}},makeChunk=(backing)=>{let chunk=Object.create(ChunkProto);switch(chunk.backing=backing,backing._tag){case"IEmpty":{chunk.length=0,chunk.depth=0,chunk.left=chunk,chunk.right=chunk;break}case"IConcat":{chunk.length=backing.left.length+backing.right.length,chunk.depth=1+Math.max(backing.left.depth,backing.right.depth),chunk.left=backing.left,chunk.right=backing.right;break}case"IArray":{chunk.length=backing.array.length,chunk.depth=0,chunk.left=_empty2,chunk.right=_empty2;break}case"ISingleton":{chunk.length=1,chunk.depth=0,chunk.left=_empty2,chunk.right=_empty2;break}case"ISlice":{chunk.length=backing.length,chunk.depth=backing.chunk.depth+1,chunk.left=_empty2,chunk.right=_empty2;break}}return chunk},isChunk=(u)=>hasProperty(u,TypeId5),_empty2=makeChunk({_tag:"IEmpty"}),empty5=()=>_empty2,make7=(...as)=>unsafeFromNonEmptyArray(as),of2=(a)=>makeChunk({_tag:"ISingleton",a}),fromIterable2=(self)=>isChunk(self)?self:unsafeFromArray(fromIterable(self)),copyToArray=(self,array4,initial)=>{switch(self.backing._tag){case"IArray":{copy2(self.backing.array,0,array4,initial,self.length);break}case"IConcat":{copyToArray(self.left,array4,initial),copyToArray(self.right,array4,initial+self.left.length);break}case"ISingleton":{array4[initial]=self.backing.a;break}case"ISlice":{let i=0,j=initial;while(i<self.length)array4[j]=unsafeGet4(self,i),i+=1,j+=1;break}}};var toReadonlyArray_=(self)=>{switch(self.backing._tag){case"IEmpty":return emptyArray;case"IArray":return self.backing.array;default:{let arr=new Array(self.length);return copyToArray(self,arr,0),self.backing={_tag:"IArray",array:arr},self.left=_empty2,self.right=_empty2,self.depth=0,arr}}},toReadonlyArray=toReadonlyArray_,reverseChunk=(self)=>{switch(self.backing._tag){case"IEmpty":case"ISingleton":return self;case"IArray":return makeChunk({_tag:"IArray",array:reverse(self.backing.array)});case"IConcat":return makeChunk({_tag:"IConcat",left:reverse2(self.backing.right),right:reverse2(self.backing.left)});case"ISlice":return unsafeFromArray(reverse(toReadonlyArray(self)))}},reverse2=reverseChunk,get4=dual(2,(self,index)=>index<0||index>=self.length?none2():some2(unsafeGet4(self,index))),unsafeFromArray=(self)=>self.length===0?empty5():self.length===1?of2(self[0]):makeChunk({_tag:"IArray",array:self}),unsafeFromNonEmptyArray=(self)=>unsafeFromArray(self),unsafeGet4=dual(2,(self,index)=>{switch(self.backing._tag){case"IEmpty":throw new Error("Index out of bounds");case"ISingleton":{if(index!==0)throw new Error("Index out of bounds");return self.backing.a}case"IArray":{if(index>=self.length||index<0)throw new Error("Index out of bounds");return self.backing.array[index]}case"IConcat":return index<self.left.length?unsafeGet4(self.left,index):unsafeGet4(self.right,index-self.left.length);case"ISlice":return unsafeGet4(self.backing.chunk,index+self.backing.offset)}}),append2=dual(2,(self,a)=>appendAll2(self,of2(a))),prepend2=dual(2,(self,elem)=>appendAll2(of2(elem),self)),take=dual(2,(self,n)=>{if(n<=0)return _empty2;else if(n>=self.length)return self;else switch(self.backing._tag){case"ISlice":return makeChunk({_tag:"ISlice",chunk:self.backing.chunk,length:n,offset:self.backing.offset});case"IConcat":{if(n>self.left.length)return makeChunk({_tag:"IConcat",left:self.left,right:take(self.right,n-self.left.length)});return take(self.left,n)}default:return makeChunk({_tag:"ISlice",chunk:self,offset:0,length:n})}}),drop2=dual(2,(self,n)=>{if(n<=0)return self;else if(n>=self.length)return _empty2;else switch(self.backing._tag){case"ISlice":return makeChunk({_tag:"ISlice",chunk:self.backing.chunk,offset:self.backing.offset+n,length:self.backing.length-n});case"IConcat":{if(n>self.left.length)return drop2(self.right,n-self.left.length);return makeChunk({_tag:"IConcat",left:drop2(self.left,n),right:self.right})}default:return makeChunk({_tag:"ISlice",chunk:self,offset:n,length:self.length-n})}});var dropWhile=dual(2,(self,predicate)=>{let arr=toReadonlyArray(self),len=arr.length,i=0;while(i<len&&predicate(arr[i]))i++;return drop2(self,i)});var appendAll2=dual(2,(self,that)=>{if(self.backing._tag==="IEmpty")return that;if(that.backing._tag==="IEmpty")return self;let diff=that.depth-self.depth;if(Math.abs(diff)<=1)return makeChunk({_tag:"IConcat",left:self,right:that});else if(diff<-1)if(self.left.depth>=self.right.depth){let nr=appendAll2(self.right,that);return makeChunk({_tag:"IConcat",left:self.left,right:nr})}else{let nrr=appendAll2(self.right.right,that);if(nrr.depth===self.depth-3){let nr=makeChunk({_tag:"IConcat",left:self.right.left,right:nrr});return makeChunk({_tag:"IConcat",left:self.left,right:nr})}else{let nl=makeChunk({_tag:"IConcat",left:self.left,right:self.right.left});return makeChunk({_tag:"IConcat",left:nl,right:nrr})}}else if(that.right.depth>=that.left.depth){let nl=appendAll2(self,that.left);return makeChunk({_tag:"IConcat",left:nl,right:that.right})}else{let nll=appendAll2(self,that.left.left);if(nll.depth===that.depth-3){let nl=makeChunk({_tag:"IConcat",left:nll,right:that.left.right});return makeChunk({_tag:"IConcat",left:nl,right:that.right})}else{let nr=makeChunk({_tag:"IConcat",left:that.left.right,right:that.right});return makeChunk({_tag:"IConcat",left:nll,right:nr})}}}),filterMap2=dual(2,(self,f)=>unsafeFromArray(filterMap(self,f))),filter3=dual(2,(self,predicate)=>unsafeFromArray(filter(self,predicate))),filterMapWhile2=dual(2,(self,f)=>unsafeFromArray(filterMapWhile(self,f)));var flatMap3=dual(2,(self,f)=>{if(self.backing._tag==="ISingleton")return f(self.backing.a,0);let out=_empty2,i=0;for(let k of self)out=appendAll2(out,f(k,i++));return out});var flatten3=flatMap3(identity);var isEmpty=(self)=>self.length===0,isNonEmpty2=(self)=>self.length>0,head2=get4(0),unsafeHead2=(self)=>unsafeGet4(self,0),headNonEmpty2=unsafeHead2,last2=(self)=>get4(self,self.length-1),unsafeLast=(self)=>unsafeGet4(self,self.length-1);var map4=dual(2,(self,f)=>self.backing._tag==="ISingleton"?of2(f(self.backing.a,0)):unsafeFromArray(pipe(toReadonlyArray(self),map3((a,i)=>f(a,i))))),mapAccum2=dual(3,(self,s,f)=>{let[s1,as]=mapAccum(self,s,f);return[s1,unsafeFromArray(as)]});var splitAt2=dual(2,(self,n)=>[take(self,n),drop2(self,n)]);var splitWhere=dual(2,(self,predicate)=>{let i=0;for(let a of toReadonlyArray(self))if(predicate(a))break;else i++;return splitAt2(self,i)});var tailNonEmpty2=(self)=>drop2(self,1),takeRight=dual(2,(self,n)=>drop2(self,self.length-n)),takeWhile=dual(2,(self,predicate)=>{let out=[];for(let a of toReadonlyArray(self))if(predicate(a))out.push(a);else break;return unsafeFromArray(out)});var zipWith2=dual(3,(self,that,f)=>unsafeFromArray(zipWith(self,that,f)));var makeBy2=dual(2,(n,f)=>fromIterable2(makeBy(n,f))),range=(start,end)=>start<=end?makeBy2(end-start+1,(i)=>start+i):of2(start);var findFirst3=findFirst2;var reduce3=reduce,reduceRight2=reduceRight;var exports_Duration={};__export(exports_Duration,{zero:()=>zero2,weeks:()=>weeks,unsafeToNanos:()=>unsafeToNanos,unsafeFormatIso:()=>unsafeFormatIso,unsafeDivide:()=>unsafeDivide,toWeeks:()=>toWeeks,toSeconds:()=>toSeconds,toNanos:()=>toNanos,toMinutes:()=>toMinutes,toMillis:()=>toMillis,toHrTime:()=>toHrTime,toHours:()=>toHours,toDays:()=>toDays,times:()=>times,sum:()=>sum,subtract:()=>subtract,seconds:()=>seconds,parts:()=>parts,nanos:()=>nanos,minutes:()=>minutes,min:()=>min2,millis:()=>millis,micros:()=>micros,max:()=>max2,matchWith:()=>matchWith,match:()=>match4,lessThanOrEqualTo:()=>lessThanOrEqualTo2,lessThan:()=>lessThan2,isZero:()=>isZero2,isFinite:()=>isFinite,isDuration:()=>isDuration,infinity:()=>infinity,hours:()=>hours,greaterThanOrEqualTo:()=>greaterThanOrEqualTo2,greaterThan:()=>greaterThan2,fromIso:()=>fromIso,formatIso:()=>formatIso,format:()=>format3,equals:()=>equals3,divide:()=>divide,decodeUnknown:()=>decodeUnknown,decode:()=>decode,days:()=>days,clamp:()=>clamp3,between:()=>between2,Order:()=>Order2,Equivalence:()=>Equivalence2});var TypeId6=Symbol.for("effect/Duration"),bigint02=BigInt(0),bigint24=BigInt(24),bigint60=BigInt(60),bigint1e3=BigInt(1000),bigint1e6=BigInt(1e6),bigint1e9=BigInt(1e9),DURATION_REGEX=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,decode=(input)=>{if(isDuration(input))return input;else if(isNumber(input))return millis(input);else if(isBigInt(input))return nanos(input);else if(Array.isArray(input)&&input.length===2&&input.every(isNumber)){if(input[0]===-1/0||input[1]===-1/0||Number.isNaN(input[0])||Number.isNaN(input[1]))return zero2;if(input[0]===1/0||input[1]===1/0)return infinity;return nanos(BigInt(Math.round(input[0]*1e9))+BigInt(Math.round(input[1])))}else if(isString(input)){let match4=DURATION_REGEX.exec(input);if(match4){let[_,valueStr,unit]=match4,value=Number(valueStr);switch(unit){case"nano":case"nanos":return nanos(BigInt(valueStr));case"micro":case"micros":return micros(BigInt(valueStr));case"milli":case"millis":return millis(value);case"second":case"seconds":return seconds(value);case"minute":case"minutes":return minutes(value);case"hour":case"hours":return hours(value);case"day":case"days":return days(value);case"week":case"weeks":return weeks(value)}}}throw new Error("Invalid DurationInput")},decodeUnknown=liftThrowable(decode),zeroValue={_tag:"Millis",millis:0},infinityValue={_tag:"Infinity"},DurationProto={[TypeId6]:TypeId6,[symbol](){return cached(this,structure(this.value))},[symbol2](that){return isDuration(that)&&equals3(this,that)},toString(){return`Duration(${format3(this)})`},toJSON(){switch(this.value._tag){case"Millis":return{_id:"Duration",_tag:"Millis",millis:this.value.millis};case"Nanos":return{_id:"Duration",_tag:"Nanos",hrtime:toHrTime(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},make8=(input)=>{let duration=Object.create(DurationProto);if(isNumber(input))if(isNaN(input)||input<=0)duration.value=zeroValue;else if(!Number.isFinite(input))duration.value=infinityValue;else if(!Number.isInteger(input))duration.value={_tag:"Nanos",nanos:BigInt(Math.round(input*1e6))};else duration.value={_tag:"Millis",millis:input};else if(input<=bigint02)duration.value=zeroValue;else duration.value={_tag:"Nanos",nanos:input};return duration},isDuration=(u)=>hasProperty(u,TypeId6),isFinite=(self)=>self.value._tag!=="Infinity",isZero2=(self)=>{switch(self.value._tag){case"Millis":return self.value.millis===0;case"Nanos":return self.value.nanos===bigint02;case"Infinity":return!1}},zero2=make8(0),infinity=make8(1/0),nanos=(nanos2)=>make8(nanos2),micros=(micros2)=>make8(micros2*bigint1e3),millis=(millis2)=>make8(millis2),seconds=(seconds2)=>make8(seconds2*1000),minutes=(minutes2)=>make8(minutes2*60000),hours=(hours2)=>make8(hours2*3600000),days=(days2)=>make8(days2*86400000),weeks=(weeks2)=>make8(weeks2*604800000),toMillis=(self)=>match4(self,{onMillis:(millis2)=>millis2,onNanos:(nanos2)=>Number(nanos2)/1e6}),toSeconds=(self)=>match4(self,{onMillis:(millis2)=>millis2/1000,onNanos:(nanos2)=>Number(nanos2)/1e9}),toMinutes=(self)=>match4(self,{onMillis:(millis2)=>millis2/60000,onNanos:(nanos2)=>Number(nanos2)/60000000000}),toHours=(self)=>match4(self,{onMillis:(millis2)=>millis2/3600000,onNanos:(nanos2)=>Number(nanos2)/3600000000000}),toDays=(self)=>match4(self,{onMillis:(millis2)=>millis2/86400000,onNanos:(nanos2)=>Number(nanos2)/86400000000000}),toWeeks=(self)=>match4(self,{onMillis:(millis2)=>millis2/604800000,onNanos:(nanos2)=>Number(nanos2)/604800000000000}),toNanos=(self)=>{let _self=decode(self);switch(_self.value._tag){case"Infinity":return none2();case"Nanos":return some2(_self.value.nanos);case"Millis":return some2(BigInt(Math.round(_self.value.millis*1e6)))}},unsafeToNanos=(self)=>{let _self=decode(self);switch(_self.value._tag){case"Infinity":throw new Error("Cannot convert infinite duration to nanos");case"Nanos":return _self.value.nanos;case"Millis":return BigInt(Math.round(_self.value.millis*1e6))}},toHrTime=(self)=>{let _self=decode(self);switch(_self.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(_self.value.nanos/bigint1e9),Number(_self.value.nanos%bigint1e9)];case"Millis":return[Math.floor(_self.value.millis/1000),Math.round(_self.value.millis%1000*1e6)]}},match4=dual(2,(self,options)=>{let _self=decode(self);switch(_self.value._tag){case"Nanos":return options.onNanos(_self.value.nanos);case"Infinity":return options.onMillis(1/0);case"Millis":return options.onMillis(_self.value.millis)}}),matchWith=dual(3,(self,that,options)=>{let _self=decode(self),_that=decode(that);if(_self.value._tag==="Infinity"||_that.value._tag==="Infinity")return options.onMillis(toMillis(_self),toMillis(_that));else if(_self.value._tag==="Nanos"||_that.value._tag==="Nanos"){let selfNanos=_self.value._tag==="Nanos"?_self.value.nanos:BigInt(Math.round(_self.value.millis*1e6)),thatNanos=_that.value._tag==="Nanos"?_that.value.nanos:BigInt(Math.round(_that.value.millis*1e6));return options.onNanos(selfNanos,thatNanos)}return options.onMillis(_self.value.millis,_that.value.millis)}),Order2=make2((self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2<that2?-1:self2>that2?1:0,onNanos:(self2,that2)=>self2<that2?-1:self2>that2?1:0})),between2=between(mapInput2(Order2,decode)),Equivalence2=(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2===that2,onNanos:(self2,that2)=>self2===that2}),_min=min(Order2),min2=dual(2,(self,that)=>_min(decode(self),decode(that))),_max=max(Order2),max2=dual(2,(self,that)=>_max(decode(self),decode(that))),_clamp=clamp(Order2),clamp3=dual(2,(self,options)=>_clamp(decode(self),{minimum:decode(options.minimum),maximum:decode(options.maximum)})),divide=dual(2,(self,by)=>match4(self,{onMillis:(millis2)=>{if(by===0||isNaN(by)||!Number.isFinite(by))return none2();return some2(make8(millis2/by))},onNanos:(nanos2)=>{if(isNaN(by)||by<=0||!Number.isFinite(by))return none2();try{return some2(make8(nanos2/BigInt(by)))}catch(e){return none2()}}})),unsafeDivide=dual(2,(self,by)=>match4(self,{onMillis:(millis2)=>make8(millis2/by),onNanos:(nanos2)=>{if(isNaN(by)||by<0||Object.is(by,-0))return zero2;else if(Object.is(by,0)||!Number.isFinite(by))return infinity;return make8(nanos2/BigInt(by))}})),times=dual(2,(self,times2)=>match4(self,{onMillis:(millis2)=>make8(millis2*times2),onNanos:(nanos2)=>make8(nanos2*BigInt(times2))})),subtract=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>make8(self2-that2),onNanos:(self2,that2)=>make8(self2-that2)})),sum=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>make8(self2+that2),onNanos:(self2,that2)=>make8(self2+that2)})),lessThan2=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2<that2,onNanos:(self2,that2)=>self2<that2})),lessThanOrEqualTo2=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2<=that2,onNanos:(self2,that2)=>self2<=that2})),greaterThan2=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2>that2,onNanos:(self2,that2)=>self2>that2})),greaterThanOrEqualTo2=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2>=that2,onNanos:(self2,that2)=>self2>=that2})),equals3=dual(2,(self,that)=>Equivalence2(decode(self),decode(that))),parts=(self)=>{let duration=decode(self);if(duration.value._tag==="Infinity")return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};let nanos2=unsafeToNanos(duration),ms=nanos2/bigint1e6,sec=ms/bigint1e3,min3=sec/bigint60,hr=min3/bigint60,days2=hr/bigint24;return{days:Number(days2),hours:Number(hr%bigint24),minutes:Number(min3%bigint60),seconds:Number(sec%bigint60),millis:Number(ms%bigint1e3),nanos:Number(nanos2%bigint1e6)}},format3=(self)=>{let duration=decode(self);if(duration.value._tag==="Infinity")return"Infinity";if(isZero2(duration))return"0";let fragments=parts(duration),pieces=[];if(fragments.days!==0)pieces.push(`${fragments.days}d`);if(fragments.hours!==0)pieces.push(`${fragments.hours}h`);if(fragments.minutes!==0)pieces.push(`${fragments.minutes}m`);if(fragments.seconds!==0)pieces.push(`${fragments.seconds}s`);if(fragments.millis!==0)pieces.push(`${fragments.millis}ms`);if(fragments.nanos!==0)pieces.push(`${fragments.nanos}ns`);return pieces.join(" ")},unsafeFormatIso=(self)=>{let duration=decode(self);if(!isFinite(duration))throw new RangeError("Cannot format infinite duration");let fragments=[],{days:days2,hours:hours2,millis:millis2,minutes:minutes2,nanos:nanos2,seconds:seconds2}=parts(duration),rest=days2;if(rest>=365){let years=Math.floor(rest/365);rest%=365,fragments.push(`${years}Y`)}if(rest>=30){let months=Math.floor(rest/30);rest%=30,fragments.push(`${months}M`)}if(rest>=7){let weeks2=Math.floor(rest/7);rest%=7,fragments.push(`${weeks2}W`)}if(rest>0)fragments.push(`${rest}D`);if(hours2!==0||minutes2!==0||seconds2!==0||millis2!==0||nanos2!==0){if(fragments.push("T"),hours2!==0)fragments.push(`${hours2}H`);if(minutes2!==0)fragments.push(`${minutes2}M`);if(seconds2!==0||millis2!==0||nanos2!==0){let total=BigInt(seconds2)*bigint1e9+BigInt(millis2)*bigint1e6+BigInt(nanos2),str=(Number(total)/1e9).toFixed(9).replace(/\.?0+$/,"");fragments.push(`${str}S`)}}return`P${fragments.join("")||"T0S"}`},formatIso=(self)=>{let duration=decode(self);return isFinite(duration)?some2(unsafeFormatIso(duration)):none2()},fromIso=(iso)=>{let result=DURATION_ISO_REGEX.exec(iso);if(result==null)return none2();let[years,months,weeks2,days2,hours2,mins,secs]=result.slice(1,8).map((_)=>_?Number(_):0),value=years*365*24*60*60+months*30*24*60*60+weeks2*7*24*60*60+days2*24*60*60+hours2*60*60+mins*60+secs;return some2(seconds(value))},DURATION_ISO_REGEX=/^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/;var SIZE=5,BUCKET_SIZE=Math.pow(2,5),MASK=BUCKET_SIZE-1,MAX_INDEX_NODE=BUCKET_SIZE/2,MIN_ARRAY_NODE=BUCKET_SIZE/4;function popcount(x){return x-=x>>1&1431655765,x=(x&858993459)+(x>>2&858993459),x=x+(x>>4)&252645135,x+=x>>8,x+=x>>16,x&127}function hashFragment(shift,h){return h>>>shift&MASK}function toBitmap(x){return 1<<x}function fromBitmap(bitmap,bit){return popcount(bitmap&bit-1)}var make9=(value,previous)=>({value,previous});function arrayUpdate(mutate,at,v,arr){let out=arr;if(!mutate){let len=arr.length;out=new Array(len);for(let i=0;i<len;++i)out[i]=arr[i]}return out[at]=v,out}function arraySpliceOut(mutate,at,arr){let newLen=arr.length-1,i=0,g=0,out=arr;if(mutate)i=g=at;else{out=new Array(newLen);while(i<at)out[g++]=arr[i++]}++i;while(i<=newLen)out[g++]=arr[i++];if(mutate)out.length=newLen;return out}function arraySpliceIn(mutate,at,v,arr){let len=arr.length;if(mutate){let i2=len;while(i2>=at)arr[i2--]=arr[i2];return arr[at]=v,arr}let i=0,g=0,out=new Array(len+1);while(i<at)out[g++]=arr[i++];out[at]=v;while(i<len)out[++g]=arr[i++];return out}class EmptyNode{_tag="EmptyNode";modify(edit,_shift,f,hash2,key,size){let v=f(none2());if(isNone2(v))return new EmptyNode;return++size.value,new LeafNode(edit,hash2,key,v)}}function isEmptyNode(a){return isTagged(a,"EmptyNode")}function isLeafNode(node){return isEmptyNode(node)||node._tag==="LeafNode"||node._tag==="CollisionNode"}function canEditNode(node,edit){return isEmptyNode(node)?!1:edit===node.edit}class LeafNode{edit;hash;key;value;_tag="LeafNode";constructor(edit,hash2,key,value){this.edit=edit,this.hash=hash2,this.key=key,this.value=value}modify(edit,shift,f,hash2,key,size){if(equals(key,this.key)){let v2=f(this.value);if(v2===this.value)return this;else if(isNone2(v2))return--size.value,new EmptyNode;if(canEditNode(this,edit))return this.value=v2,this;return new LeafNode(edit,hash2,key,v2)}let v=f(none2());if(isNone2(v))return this;return++size.value,mergeLeaves(edit,shift,this.hash,this,hash2,new LeafNode(edit,hash2,key,v))}}class CollisionNode{edit;hash;children;_tag="CollisionNode";constructor(edit,hash2,children){this.edit=edit,this.hash=hash2,this.children=children}modify(edit,shift,f,hash2,key,size){if(hash2===this.hash){let canEdit=canEditNode(this,edit),list=this.updateCollisionList(canEdit,edit,this.hash,this.children,f,key,size);if(list===this.children)return this;return list.length>1?new CollisionNode(edit,this.hash,list):list[0]}let v=f(none2());if(isNone2(v))return this;return++size.value,mergeLeaves(edit,shift,this.hash,this,hash2,new LeafNode(edit,hash2,key,v))}updateCollisionList(mutate,edit,hash2,list,f,key,size){let len=list.length;for(let i=0;i<len;++i){let child=list[i];if("key"in child&&equals(key,child.key)){let value=child.value,newValue2=f(value);if(newValue2===value)return list;if(isNone2(newValue2))return--size.value,arraySpliceOut(mutate,i,list);return arrayUpdate(mutate,i,new LeafNode(edit,hash2,key,newValue2),list)}}let newValue=f(none2());if(isNone2(newValue))return list;return++size.value,arrayUpdate(mutate,len,new LeafNode(edit,hash2,key,newValue),list)}}class IndexedNode{edit;mask;children;_tag="IndexedNode";constructor(edit,mask,children){this.edit=edit,this.mask=mask,this.children=children}modify(edit,shift,f,hash2,key,size){let mask=this.mask,children=this.children,frag=hashFragment(shift,hash2),bit=toBitmap(frag),indx=fromBitmap(mask,bit),exists2=mask&bit,canEdit=canEditNode(this,edit);if(!exists2){let _newChild=new EmptyNode().modify(edit,shift+SIZE,f,hash2,key,size);if(!_newChild)return this;return children.length>=MAX_INDEX_NODE?expand(edit,frag,_newChild,mask,children):new IndexedNode(edit,mask|bit,arraySpliceIn(canEdit,indx,_newChild,children))}let current=children[indx],child=current.modify(edit,shift+SIZE,f,hash2,key,size);if(current===child)return this;let bitmap=mask,newChildren;if(isEmptyNode(child)){if(bitmap&=~bit,!bitmap)return new EmptyNode;if(children.length<=2&&isLeafNode(children[indx^1]))return children[indx^1];newChildren=arraySpliceOut(canEdit,indx,children)}else newChildren=arrayUpdate(canEdit,indx,child,children);if(canEdit)return this.mask=bitmap,this.children=newChildren,this;return new IndexedNode(edit,bitmap,newChildren)}}class ArrayNode{edit;size;children;_tag="ArrayNode";constructor(edit,size,children){this.edit=edit,this.size=size,this.children=children}modify(edit,shift,f,hash2,key,size){let count=this.size,children=this.children,frag=hashFragment(shift,hash2),child=children[frag],newChild=(child||new EmptyNode).modify(edit,shift+SIZE,f,hash2,key,size);if(child===newChild)return this;let canEdit=canEditNode(this,edit),newChildren;if(isEmptyNode(child)&&!isEmptyNode(newChild))++count,newChildren=arrayUpdate(canEdit,frag,newChild,children);else if(!isEmptyNode(child)&&isEmptyNode(newChild)){if(--count,count<=MIN_ARRAY_NODE)return pack(edit,count,frag,children);newChildren=arrayUpdate(canEdit,frag,new EmptyNode,children)}else newChildren=arrayUpdate(canEdit,frag,newChild,children);if(canEdit)return this.size=count,this.children=newChildren,this;return new ArrayNode(edit,count,newChildren)}}function pack(edit,count,removed,elements){let children=new Array(count-1),g=0,bitmap=0;for(let i=0,len=elements.length;i<len;++i)if(i!==removed){let elem=elements[i];if(elem&&!isEmptyNode(elem))children[g++]=elem,bitmap|=1<<i}return new IndexedNode(edit,bitmap,children)}function expand(edit,frag,child,bitmap,subNodes){let arr=[],bit=bitmap,count=0;for(let i=0;bit;++i){if(bit&1)arr[i]=subNodes[count++];bit>>>=1}return arr[frag]=child,new ArrayNode(edit,count+1,arr)}function mergeLeavesInner(edit,shift,h1,n1,h2,n2){if(h1===h2)return new CollisionNode(edit,h1,[n2,n1]);let subH1=hashFragment(shift,h1),subH2=hashFragment(shift,h2);if(subH1===subH2)return(child)=>new IndexedNode(edit,toBitmap(subH1)|toBitmap(subH2),[child]);else{let children=subH1<subH2?[n1,n2]:[n2,n1];return new IndexedNode(edit,toBitmap(subH1)|toBitmap(subH2),children)}}function mergeLeaves(edit,shift,h1,n1,h2,n2){let stack=void 0,currentShift=shift;while(!0){let res=mergeLeavesInner(edit,currentShift,h1,n1,h2,n2);if(typeof res==="function")stack=make9(res,stack),currentShift=currentShift+SIZE;else{let final=res;while(stack!=null)final=stack.value(final),stack=stack.previous;return final}}}var HashMapSymbolKey="effect/HashMap",HashMapTypeId=Symbol.for(HashMapSymbolKey),HashMapProto={[HashMapTypeId]:HashMapTypeId,[Symbol.iterator](){return new HashMapIterator(this,(k,v)=>[k,v])},[symbol](){let hash2=hash(HashMapSymbolKey);for(let item of this)hash2^=pipe(hash(item[0]),combine(hash(item[1])));return cached(this,hash2)},[symbol2](that){if(isHashMap(that)){if(that._size!==this._size)return!1;for(let item of this){let elem=pipe(that,getHash(item[0],hash(item[0])));if(isNone2(elem))return!1;else if(!equals(item[1],elem.value))return!1}return!0}return!1},toString(){return format(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},makeImpl=(editable,edit,root,size)=>{let map5=Object.create(HashMapProto);return map5._editable=editable,map5._edit=edit,map5._root=root,map5._size=size,map5};class HashMapIterator{map;f;v;constructor(map5,f){this.map=map5,this.f=f,this.v=visitLazy(this.map._root,this.f,void 0)}next(){if(isNone2(this.v))return{done:!0,value:void 0};let v0=this.v.value;return this.v=applyCont(v0.cont),{done:!1,value:v0.value}}[Symbol.iterator](){return new HashMapIterator(this.map,this.f)}}var applyCont=(cont)=>cont?visitLazyChildren(cont[0],cont[1],cont[2],cont[3],cont[4]):none2(),visitLazy=(node,f,cont=void 0)=>{switch(node._tag){case"LeafNode":{if(isSome2(node.value))return some2({value:f(node.key,node.value.value),cont});return applyCont(cont)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let children=node.children;return visitLazyChildren(children.length,children,0,f,cont)}default:return applyCont(cont)}},visitLazyChildren=(len,children,i,f,cont)=>{while(i<len){let child=children[i++];if(child&&!isEmptyNode(child))return visitLazy(child,f,[len,children,i,f,cont])}return applyCont(cont)},_empty3=makeImpl(!1,0,new EmptyNode,0),empty6=()=>_empty3;var fromIterable3=(entries)=>{let map5=beginMutation(empty6());for(let entry of entries)set(map5,entry[0],entry[1]);return endMutation(map5)},isHashMap=(u)=>hasProperty(u,HashMapTypeId),isEmpty2=(self)=>self&&isEmptyNode(self._root),get5=dual(2,(self,key)=>getHash(self,key,hash(key))),getHash=dual(3,(self,key,hash2)=>{let node=self._root,shift=0;while(!0)switch(node._tag){case"LeafNode":return equals(key,node.key)?node.value:none2();case"CollisionNode":{if(hash2===node.hash){let children=node.children;for(let i=0,len=children.length;i<len;++i){let child=children[i];if("key"in child&&equals(key,child.key))return child.value}}return none2()}case"IndexedNode":{let frag=hashFragment(shift,hash2),bit=toBitmap(frag);if(node.mask&bit){node=node.children[fromBitmap(node.mask,bit)],shift+=SIZE;break}return none2()}case"ArrayNode":{if(node=node.children[hashFragment(shift,hash2)],node){shift+=SIZE;break}return none2()}default:return none2()}});var has=dual(2,(self,key)=>isSome2(getHash(self,key,hash(key))));var set=dual(3,(self,key,value)=>modifyAt(self,key,()=>some2(value))),setTree=dual(3,(self,newRoot,newSize)=>{if(self._editable)return self._root=newRoot,self._size=newSize,self;return newRoot===self._root?self:makeImpl(self._editable,self._edit,newRoot,newSize)}),keys=(self)=>new HashMapIterator(self,(key)=>key);var size=(self)=>self._size,beginMutation=(self)=>makeImpl(!0,self._edit+1,self._root,self._size),endMutation=(self)=>{return self._editable=!1,self},mutate=dual(2,(self,f)=>{let transient=beginMutation(self);return f(transient),endMutation(transient)}),modifyAt=dual(3,(self,key,f)=>modifyHash(self,key,hash(key),f)),modifyHash=dual(4,(self,key,hash2,f)=>{let size2={value:self._size},newRoot=self._root.modify(self._editable?self._edit:NaN,0,f,hash2,key,size2);return pipe(self,setTree(newRoot,size2.value))});var remove2=dual(2,(self,key)=>modifyAt(self,key,none2));var map5=dual(2,(self,f)=>reduce4(self,empty6(),(map6,value,key)=>set(map6,key,f(value,key))));var forEach=dual(2,(self,f)=>reduce4(self,void 0,(_,value,key)=>f(value,key))),reduce4=dual(3,(self,zero3,f)=>{let root=self._root;if(root._tag==="LeafNode")return isSome2(root.value)?f(zero3,root.value.value,root.key):zero3;if(root._tag==="EmptyNode")return zero3;let toVisit=[root.children],children;while(children=toVisit.pop())for(let i=0,len=children.length;i<len;){let child=children[i++];if(child&&!isEmptyNode(child))if(child._tag==="LeafNode"){if(isSome2(child.value))zero3=f(zero3,child.value.value,child.key)}else toVisit.push(child.children)}return zero3});var HashSetSymbolKey="effect/HashSet",HashSetTypeId=Symbol.for(HashSetSymbolKey),HashSetProto={[HashSetTypeId]:HashSetTypeId,[Symbol.iterator](){return keys(this._keyMap)},[symbol](){return cached(this,combine(hash(this._keyMap))(hash(HashSetSymbolKey)))},[symbol2](that){if(isHashSet(that))return size(this._keyMap)===size(that._keyMap)&&equals(this._keyMap,that._keyMap);return!1},toString(){return format(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},makeImpl2=(keyMap)=>{let set2=Object.create(HashSetProto);return set2._keyMap=keyMap,set2},isHashSet=(u)=>hasProperty(u,HashSetTypeId),_empty4=makeImpl2(empty6()),empty7=()=>_empty4,fromIterable4=(elements)=>{let set2=beginMutation2(empty7());for(let value of elements)add3(set2,value);return endMutation2(set2)},make10=(...elements)=>{let set2=beginMutation2(empty7());for(let value of elements)add3(set2,value);return endMutation2(set2)},has2=dual(2,(self,value)=>has(self._keyMap,value)),some3=dual(2,(self,f)=>{let found=!1;for(let value of self)if(found=f(value),found)break;return found}),every2=dual(2,(self,refinement)=>!some3(self,(a)=>!refinement(a)));var size2=(self)=>size(self._keyMap),beginMutation2=(self)=>makeImpl2(beginMutation(self._keyMap)),endMutation2=(self)=>{return self._keyMap._editable=!1,self},mutate2=dual(2,(self,f)=>{let transient=beginMutation2(self);return f(transient),endMutation2(transient)}),add3=dual(2,(self,value)=>self._keyMap._editable?(set(value,!0)(self._keyMap),self):makeImpl2(set(value,!0)(self._keyMap))),remove3=dual(2,(self,value)=>self._keyMap._editable?(remove2(value)(self._keyMap),self):makeImpl2(remove2(value)(self._keyMap))),difference2=dual(2,(self,that)=>mutate2(self,(set2)=>{for(let value of that)remove3(set2,value)}));var union2=dual(2,(self,that)=>mutate2(empty7(),(set2)=>{forEach2(self,(value)=>add3(set2,value));for(let value of that)add3(set2,value)}));var forEach2=dual(2,(self,f)=>forEach(self._keyMap,(_,k)=>f(k))),reduce5=dual(3,(self,zero3,f)=>reduce4(self._keyMap,zero3,(z,_,a)=>f(z,a)));var empty8=empty7,fromIterable5=fromIterable4,make11=make10,has3=has2;var every3=every2;var size3=size2;var add4=add3,remove4=remove3,difference3=difference2;var union3=union2;var forEach3=forEach2,reduce6=reduce5;var TypeId7=Symbol.for("effect/MutableRef"),MutableRefProto={[TypeId7]:TypeId7,toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableRef",current:toJSON(this.current)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},make12=(value)=>{let ref=Object.create(MutableRefProto);return ref.current=value,ref},compareAndSet=dual(3,(self,oldValue,newValue)=>{if(equals(oldValue,self.current))return self.current=newValue,!0;return!1});var get6=(self)=>self.current;var set2=dual(2,(self,value)=>{return self.current=value,self});var FiberIdSymbolKey="effect/FiberId",FiberIdTypeId=Symbol.for(FiberIdSymbolKey),OP_NONE="None",OP_RUNTIME="Runtime",OP_COMPOSITE="Composite",emptyHash=string(`${FiberIdSymbolKey}-${OP_NONE}`);class None{[FiberIdTypeId]=FiberIdTypeId;_tag=OP_NONE;id=-1;startTimeMillis=-1;[symbol](){return emptyHash}[symbol2](that){return isFiberId(that)&&that._tag===OP_NONE}toString(){return format(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[NodeInspectSymbol](){return this.toJSON()}}class Runtime{id;startTimeMillis;[FiberIdTypeId]=FiberIdTypeId;_tag=OP_RUNTIME;constructor(id,startTimeMillis){this.id=id,this.startTimeMillis=startTimeMillis}[symbol](){return cached(this,string(`${FiberIdSymbolKey}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[symbol2](that){return isFiberId(that)&&that._tag===OP_RUNTIME&&this.id===that.id&&this.startTimeMillis===that.startTimeMillis}toString(){return format(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[NodeInspectSymbol](){return this.toJSON()}}class Composite{left;right;[FiberIdTypeId]=FiberIdTypeId;_tag=OP_COMPOSITE;constructor(left3,right3){this.left=left3,this.right=right3}_hash;[symbol](){return pipe(string(`${FiberIdSymbolKey}-${this._tag}`),combine(hash(this.left)),combine(hash(this.right)),cached(this))}[symbol2](that){return isFiberId(that)&&that._tag===OP_COMPOSITE&&equals(this.left,that.left)&&equals(this.right,that.right)}toString(){return format(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,left:toJSON(this.left),right:toJSON(this.right)}}[NodeInspectSymbol](){return this.toJSON()}}var none3=new None;var isFiberId=(self)=>hasProperty(self,FiberIdTypeId),isNone3=(self)=>{return self._tag===OP_NONE||pipe(toSet(self),every3((id)=>isNone3(id)))};var combine2=dual(2,(self,that)=>{if(self._tag===OP_NONE)return that;if(that._tag===OP_NONE)return self;return new Composite(self,that)}),combineAll2=(fiberIds)=>{return pipe(fiberIds,reduce6(none3,(a,b)=>combine2(b)(a)))},getOrElse3=dual(2,(self,that)=>isNone3(self)?that:self),ids=(self)=>{switch(self._tag){case OP_NONE:return empty8();case OP_RUNTIME:return make11(self.id);case OP_COMPOSITE:return pipe(ids(self.left),union3(ids(self.right)))}},_fiberCounter=globalValue(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>make12(0));var threadName=(self)=>{return Array.from(ids(self)).map((n)=>`#${n}`).join(",")};var toSet=(self)=>{switch(self._tag){case OP_NONE:return empty8();case OP_RUNTIME:return make11(self);case OP_COMPOSITE:return pipe(toSet(self.left),union3(toSet(self.right)))}},unsafeMake=()=>{let id=get6(_fiberCounter);return pipe(_fiberCounter,set2(id+1)),new Runtime(id,Date.now())};var none4=none3;var combine3=combine2,combineAll3=combineAll2,getOrElse4=getOrElse3,ids2=ids;var threadName2=threadName;var unsafeMake2=unsafeMake;var empty9=empty6;var fromIterable6=fromIterable3,isEmpty3=isEmpty2,get7=get5;var set3=set,keys2=keys;var mutate3=mutate,modifyAt2=modifyAt;var map7=map5;var forEach4=forEach,reduce7=reduce4;var TypeId8=Symbol.for("effect/List"),toArray2=(self)=>fromIterable(self),getEquivalence3=(isEquivalent)=>mapInput(getEquivalence(isEquivalent),toArray2),_equivalence4=getEquivalence3(equals),ConsProto={[TypeId8]:TypeId8,_tag:"Cons",toString(){return format(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:toArray2(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},[symbol2](that){return isList(that)&&this._tag===that._tag&&_equivalence4(this,that)},[symbol](){return cached(this,array2(toArray2(this)))},[Symbol.iterator](){let done=!1,self=this;return{next(){if(done)return this.return();if(self._tag==="Nil")return done=!0,this.return();let value=self.head;return self=self.tail,{done,value}},return(value){if(!done)done=!0;return{done:!0,value}}}},pipe(){return pipeArguments(this,arguments)}},makeCons=(head3,tail)=>{let cons=Object.create(ConsProto);return cons.head=head3,cons.tail=tail,cons},NilHash=string("Nil"),NilProto={[TypeId8]:TypeId8,_tag:"Nil",toString(){return format(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[NodeInspectSymbol](){return this.toJSON()},[symbol](){return NilHash},[symbol2](that){return isList(that)&&this._tag===that._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return pipeArguments(this,arguments)}},_Nil=Object.create(NilProto),isList=(u)=>hasProperty(u,TypeId8),isNil=(self)=>self._tag==="Nil",isCons=(self)=>self._tag==="Cons";var nil=()=>_Nil,cons=(head3,tail)=>makeCons(head3,tail),empty10=nil,of3=(value)=>makeCons(value,_Nil);var appendAll3=dual(2,(self,that)=>prependAll(that,self)),prepend3=dual(2,(self,element)=>cons(element,self)),prependAll=dual(2,(self,prefix)=>{if(isNil(self))return prefix;else if(isNil(prefix))return self;else{let result=makeCons(prefix.head,self),curr=result,that=prefix.tail;while(!isNil(that)){let temp=makeCons(that.head,self);curr.tail=temp,curr=temp,that=that.tail}return result}});var reduce8=dual(3,(self,zero3,f)=>{let acc=zero3,these=self;while(!isNil(these))acc=f(acc,these.head),these=these.tail;return acc});var reverse3=(self)=>{let result=empty10(),these=self;while(!isNil(these))result=prepend3(result,these.head),these=these.tail;return result};var ArrayProto=Object.assign(Object.create(Array.prototype),{[symbol](){return cached(this,array2(this))},[symbol2](that){if(Array.isArray(that)&&this.length===that.length)return this.every((v,i)=>equals(v,that[i]));else return!1}}),Structural=function(){function Structural2(args){if(args)Object.assign(this,args)}return Structural2.prototype=StructuralPrototype,Structural2}(),struct=(as)=>Object.assign(Object.create(StructuralPrototype),as);var ChunkPatchTypeId=Symbol.for("effect/DifferChunkPatch");function variance(a){return a}var PatchProto={...Structural.prototype,[ChunkPatchTypeId]:{_Value:variance,_Patch:variance}};var ContextPatchTypeId=Symbol.for("effect/DifferContextPatch");function variance2(a){return a}var PatchProto2={...Structural.prototype,[ContextPatchTypeId]:{_Value:variance2,_Patch:variance2}},EmptyProto=Object.assign(Object.create(PatchProto2),{_tag:"Empty"}),_empty5=Object.create(EmptyProto),empty11=()=>_empty5,AndThenProto=Object.assign(Object.create(PatchProto2),{_tag:"AndThen"}),makeAndThen=(first,second)=>{let o=Object.create(AndThenProto);return o.first=first,o.second=second,o},AddServiceProto=Object.assign(Object.create(PatchProto2),{_tag:"AddService"}),makeAddService=(key,service)=>{let o=Object.create(AddServiceProto);return o.key=key,o.service=service,o},RemoveServiceProto=Object.assign(Object.create(PatchProto2),{_tag:"RemoveService"}),makeRemoveService=(key)=>{let o=Object.create(RemoveServiceProto);return o.key=key,o},UpdateServiceProto=Object.assign(Object.create(PatchProto2),{_tag:"UpdateService"}),makeUpdateService=(key,update)=>{let o=Object.create(UpdateServiceProto);return o.key=key,o.update=update,o},diff=(oldValue,newValue)=>{let missingServices=new Map(oldValue.unsafeMap),patch=empty11();for(let[tag,newService]of newValue.unsafeMap.entries())if(missingServices.has(tag)){let old=missingServices.get(tag);if(missingServices.delete(tag),!equals(old,newService))patch=combine4(makeUpdateService(tag,()=>newService))(patch)}else missingServices.delete(tag),patch=combine4(makeAddService(tag,newService))(patch);for(let[tag]of missingServices.entries())patch=combine4(makeRemoveService(tag))(patch);return patch},combine4=dual(2,(self,that)=>makeAndThen(self,that)),patch=dual(2,(self,context)=>{if(self._tag==="Empty")return context;let wasServiceUpdated=!1,patches=of2(self),updatedContext=new Map(context.unsafeMap);while(isNonEmpty2(patches)){let head3=headNonEmpty2(patches),tail=tailNonEmpty2(patches);switch(head3._tag){case"Empty":{patches=tail;break}case"AddService":{updatedContext.set(head3.key,head3.service),patches=tail;break}case"AndThen":{patches=prepend2(prepend2(tail,head3.second),head3.first);break}case"RemoveService":{updatedContext.delete(head3.key),patches=tail;break}case"UpdateService":{updatedContext.set(head3.key,head3.update(updatedContext.get(head3.key))),wasServiceUpdated=!0,patches=tail;break}}}if(!wasServiceUpdated)return makeContext(updatedContext);let map8=new Map;for(let[tag]of context.unsafeMap)if(updatedContext.has(tag))map8.set(tag,updatedContext.get(tag)),updatedContext.delete(tag);for(let[tag,s]of updatedContext)map8.set(tag,s);return makeContext(map8)});var HashMapPatchTypeId=Symbol.for("effect/DifferHashMapPatch");function variance3(a){return a}var PatchProto3={...Structural.prototype,[HashMapPatchTypeId]:{_Value:variance3,_Key:variance3,_Patch:variance3}};var HashSetPatchTypeId=Symbol.for("effect/DifferHashSetPatch");function variance4(a){return a}var PatchProto4={...Structural.prototype,[HashSetPatchTypeId]:{_Value:variance4,_Key:variance4,_Patch:variance4}},EmptyProto2=Object.assign(Object.create(PatchProto4),{_tag:"Empty"}),_empty6=Object.create(EmptyProto2),empty12=()=>_empty6,AndThenProto2=Object.assign(Object.create(PatchProto4),{_tag:"AndThen"}),makeAndThen2=(first,second)=>{let o=Object.create(AndThenProto2);return o.first=first,o.second=second,o},AddProto=Object.assign(Object.create(PatchProto4),{_tag:"Add"}),makeAdd=(value)=>{let o=Object.create(AddProto);return o.value=value,o},RemoveProto=Object.assign(Object.create(PatchProto4),{_tag:"Remove"}),makeRemove=(value)=>{let o=Object.create(RemoveProto);return o.value=value,o},diff2=(oldValue,newValue)=>{let[removed,patch2]=reduce6([oldValue,empty12()],([set4,patch3],value)=>{if(has3(value)(set4))return[remove4(value)(set4),patch3];return[set4,combine5(makeAdd(value))(patch3)]})(newValue);return reduce6(patch2,(patch3,value)=>combine5(makeRemove(value))(patch3))(removed)},combine5=dual(2,(self,that)=>makeAndThen2(self,that)),patch2=dual(2,(self,oldValue)=>{if(self._tag==="Empty")return oldValue;let set4=oldValue,patches=of2(self);while(isNonEmpty2(patches)){let head3=headNonEmpty2(patches),tail=tailNonEmpty2(patches);switch(head3._tag){case"Empty":{patches=tail;break}case"AndThen":{patches=prepend2(head3.first)(prepend2(head3.second)(tail));break}case"Add":{set4=add4(head3.value)(set4),patches=tail;break}case"Remove":set4=remove4(head3.value)(set4),patches=tail}}return set4});var OrPatchTypeId=Symbol.for("effect/DifferOrPatch");function variance5(a){return a}var PatchProto5={...Structural.prototype,[OrPatchTypeId]:{_Value:variance5,_Key:variance5,_Patch:variance5}};var ReadonlyArrayPatchTypeId=Symbol.for("effect/DifferReadonlyArrayPatch");function variance6(a){return a}var PatchProto6={...Structural.prototype,[ReadonlyArrayPatchTypeId]:{_Value:variance6,_Patch:variance6}},EmptyProto3=Object.assign(Object.create(PatchProto6),{_tag:"Empty"}),_empty7=Object.create(EmptyProto3),empty13=()=>_empty7,AndThenProto3=Object.assign(Object.create(PatchProto6),{_tag:"AndThen"}),makeAndThen3=(first,second)=>{let o=Object.create(AndThenProto3);return o.first=first,o.second=second,o},AppendProto=Object.assign(Object.create(PatchProto6),{_tag:"Append"}),makeAppend=(values3)=>{let o=Object.create(AppendProto);return o.values=values3,o},SliceProto=Object.assign(Object.create(PatchProto6),{_tag:"Slice"}),makeSlice=(from,until)=>{let o=Object.create(SliceProto);return o.from=from,o.until=until,o},UpdateProto=Object.assign(Object.create(PatchProto6),{_tag:"Update"}),makeUpdate=(index,patch3)=>{let o=Object.create(UpdateProto);return o.index=index,o.patch=patch3,o},diff3=(options)=>{let i=0,patch3=empty13();while(i<options.oldValue.length&&i<options.newValue.length){let oldElement=options.oldValue[i],newElement=options.newValue[i],valuePatch=options.differ.diff(oldElement,newElement);if(!equals(valuePatch,options.differ.empty))patch3=combine6(patch3,makeUpdate(i,valuePatch));i=i+1}if(i<options.oldValue.length)patch3=combine6(patch3,makeSlice(0,i));if(i<options.newValue.length)patch3=combine6(patch3,makeAppend(drop(i)(options.newValue)));return patch3},combine6=dual(2,(self,that)=>makeAndThen3(self,that)),patch3=dual(3,(self,oldValue,differ)=>{if(self._tag==="Empty")return oldValue;let readonlyArray=oldValue.slice(),patches=of(self);while(isNonEmptyArray2(patches)){let head3=headNonEmpty(patches),tail=tailNonEmpty(patches);switch(head3._tag){case"Empty":{patches=tail;break}case"AndThen":{tail.unshift(head3.first,head3.second),patches=tail;break}case"Append":{for(let value of head3.values)readonlyArray.push(value);patches=tail;break}case"Slice":{readonlyArray=readonlyArray.slice(head3.from,head3.until),patches=tail;break}case"Update":{readonlyArray[head3.index]=differ.patch(head3.patch,readonlyArray[head3.index]),patches=tail;break}}}return readonlyArray});var DifferTypeId=Symbol.for("effect/Differ"),DifferProto={[DifferTypeId]:{_P:identity,_V:identity},pipe(){return pipeArguments(this,arguments)}},make15=(params)=>{let differ=Object.create(DifferProto);return differ.empty=params.empty,differ.diff=params.diff,differ.combine=params.combine,differ.patch=params.patch,differ},environment=()=>make15({empty:empty11(),combine:(first,second)=>combine4(second)(first),diff:(oldValue,newValue)=>diff(oldValue,newValue),patch:(patch7,oldValue)=>patch(oldValue)(patch7)});var hashSet=()=>make15({empty:empty12(),combine:(first,second)=>combine5(second)(first),diff:(oldValue,newValue)=>diff2(oldValue,newValue),patch:(patch7,oldValue)=>patch2(oldValue)(patch7)});var readonlyArray=(differ)=>make15({empty:empty13(),combine:(first,second)=>combine6(first,second),diff:(oldValue,newValue)=>diff3({oldValue,newValue,differ}),patch:(patch7,oldValue)=>patch3(patch7,oldValue,differ)});var update=()=>updateWith((_,a)=>a),updateWith=(f)=>make15({empty:identity,combine:(first,second)=>{if(first===identity)return second;if(second===identity)return first;return(a)=>second(first(a))},diff:(oldValue,newValue)=>{if(equals(oldValue,newValue))return identity;return constant(newValue)},patch:(patch7,oldValue)=>f(oldValue,patch7(oldValue))});var BIT_MASK=255,BIT_SHIFT=8,active=(patch7)=>patch7&BIT_MASK,enabled=(patch7)=>patch7>>BIT_SHIFT&BIT_MASK,make16=(active2,enabled2)=>(active2&BIT_MASK)+((enabled2&active2&BIT_MASK)<<BIT_SHIFT),empty17=make16(0,0),enable=(flag)=>make16(flag,flag),disable=(flag)=>make16(flag,0);var exclude=dual(2,(self,flag)=>make16(active(self)&~flag,enabled(self)));var andThen=dual(2,(self,that)=>self|that);var invert=(n)=>~n>>>0&BIT_MASK;var None2=0,Interruption=1,OpSupervision=2,RuntimeMetrics=4,WindDown=16,CooperativeYielding=32;var cooperativeYielding=(self)=>isEnabled(self,CooperativeYielding);var enable2=dual(2,(self,flag)=>self|flag);var interruptible=(self)=>interruption(self)&&!windDown(self),interruption=(self)=>isEnabled(self,Interruption);var isEnabled=dual(2,(self,flag)=>(self&flag)!==0),make17=(...flags)=>flags.reduce((a,b)=>a|b,0),none5=make17(None2);var runtimeMetrics=(self)=>isEnabled(self,RuntimeMetrics);var windDown=(self)=>isEnabled(self,WindDown);var diff7=dual(2,(self,that)=>make16(self^that,that)),patch7=dual(2,(self,patch8)=>self&(invert(active(patch8))|enabled(patch8))|active(patch8)&enabled(patch8));var differ=make15({empty:empty17,diff:(oldValue,newValue)=>diff7(oldValue,newValue),combine:(first,second)=>andThen(second)(first),patch:(_patch,oldValue)=>patch7(oldValue,_patch)});var empty18=empty17;var enable3=enable,disable2=disable;var exclude2=exclude;var empty19={_tag:"Empty"},par=(self,that)=>({_tag:"Par",left:self,right:that}),seq=(self,that)=>({_tag:"Seq",left:self,right:that}),single=(dataSource,blockedRequest)=>({_tag:"Single",dataSource,blockedRequest});var flatten4=(self)=>{let current=of3(self),updated=empty10();while(!0){let[parallel,sequential]=reduce8(current,[parallelCollectionEmpty(),empty10()],([parallel2,sequential2],blockedRequest)=>{let[par2,seq2]=step(blockedRequest);return[parallelCollectionCombine(parallel2,par2),appendAll3(sequential2,seq2)]});if(updated=merge4(updated,parallel),isNil(sequential))return reverse3(updated);current=sequential}throw new Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},step=(requests)=>{let current=requests,parallel=parallelCollectionEmpty(),stack=empty10(),sequential=empty10();while(!0)switch(current._tag){case"Empty":{if(isNil(stack))return[parallel,sequential];current=stack.head,stack=stack.tail;break}case"Par":{stack=cons(current.right,stack),current=current.left;break}case"Seq":{let{left:left3,right:right3}=current;switch(left3._tag){case"Empty":{current=right3;break}case"Par":{let{left:l,right:r}=left3;current=par(seq(l,right3),seq(r,right3));break}case"Seq":{let{left:l,right:r}=left3;current=seq(l,seq(r,right3));break}case"Single":{current=left3,sequential=cons(right3,sequential);break}}break}case"Single":{if(parallel=parallelCollectionAdd(parallel,current),isNil(stack))return[parallel,sequential];current=stack.head,stack=stack.tail;break}}throw new Error("BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues")},merge4=(sequential,parallel)=>{if(isNil(sequential))return of3(parallelCollectionToSequentialCollection(parallel));if(parallelCollectionIsEmpty(parallel))return sequential;let seqHeadKeys=sequentialCollectionKeys(sequential.head),parKeys=parallelCollectionKeys(parallel);if(seqHeadKeys.length===1&&parKeys.length===1&&equals(seqHeadKeys[0],parKeys[0]))return cons(sequentialCollectionCombine(sequential.head,parallelCollectionToSequentialCollection(parallel)),sequential.tail);return cons(parallelCollectionToSequentialCollection(parallel),sequential)},EntryTypeId=Symbol.for("effect/RequestBlock/Entry");class EntryImpl{request;result;listeners;ownerId;state;[EntryTypeId]=blockedRequestVariance;constructor(request,result,listeners,ownerId,state){this.request=request,this.result=result,this.listeners=listeners,this.ownerId=ownerId,this.state=state}}var blockedRequestVariance={_R:(_)=>_};var makeEntry=(options)=>new EntryImpl(options.request,options.result,options.listeners,options.ownerId,options.state),RequestBlockParallelTypeId=Symbol.for("effect/RequestBlock/RequestBlockParallel"),parallelVariance={_R:(_)=>_};class ParallelImpl{map;[RequestBlockParallelTypeId]=parallelVariance;constructor(map8){this.map=map8}}var parallelCollectionEmpty=()=>new ParallelImpl(empty9());var parallelCollectionAdd=(self,blockedRequest)=>new ParallelImpl(modifyAt2(self.map,blockedRequest.dataSource,(_)=>orElseSome(map2(_,append2(blockedRequest.blockedRequest)),()=>of2(blockedRequest.blockedRequest)))),parallelCollectionCombine=(self,that)=>new ParallelImpl(reduce7(self.map,that.map,(map8,value,key)=>set3(map8,key,match2(get7(map8,key),{onNone:()=>value,onSome:(other)=>appendAll2(value,other)})))),parallelCollectionIsEmpty=(self)=>isEmpty3(self.map),parallelCollectionKeys=(self)=>Array.from(keys2(self.map)),parallelCollectionToSequentialCollection=(self)=>sequentialCollectionMake(map7(self.map,(x)=>of2(x))),SequentialCollectionTypeId=Symbol.for("effect/RequestBlock/RequestBlockSequential"),sequentialVariance={_R:(_)=>_};class SequentialImpl{map;[SequentialCollectionTypeId]=sequentialVariance;constructor(map8){this.map=map8}}var sequentialCollectionMake=(map8)=>new SequentialImpl(map8),sequentialCollectionCombine=(self,that)=>new SequentialImpl(reduce7(that.map,self.map,(map8,value,key)=>set3(map8,key,match2(get7(map8,key),{onNone:()=>empty5(),onSome:(a)=>appendAll2(a,value)}))));var sequentialCollectionKeys=(self)=>Array.from(keys2(self.map)),sequentialCollectionToChunk=(self)=>Array.from(self.map);var OP_DIE="Die",OP_EMPTY="Empty",OP_FAIL="Fail",OP_INTERRUPT="Interrupt",OP_PARALLEL="Parallel",OP_SEQUENTIAL="Sequential";var CauseSymbolKey="effect/Cause",CauseTypeId=Symbol.for(CauseSymbolKey),variance7={_E:(_)=>_},proto={[CauseTypeId]:variance7,[symbol](){return pipe(hash(CauseSymbolKey),combine(hash(flattenCause(this))),cached(this))},[symbol2](that){return isCause(that)&&causeEquals(this,that)},pipe(){return pipeArguments(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:toJSON(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:toJSON(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:toJSON(this.left),right:toJSON(this.right)}}},toString(){return pretty(this)},[NodeInspectSymbol](){return this.toJSON()}},empty20=(()=>{let o=Object.create(proto);return o._tag=OP_EMPTY,o})(),fail=(error)=>{let o=Object.create(proto);return o._tag=OP_FAIL,o.error=error,o},die=(defect)=>{let o=Object.create(proto);return o._tag=OP_DIE,o.defect=defect,o},interrupt=(fiberId)=>{let o=Object.create(proto);return o._tag=OP_INTERRUPT,o.fiberId=fiberId,o},parallel=(left3,right3)=>{let o=Object.create(proto);return o._tag=OP_PARALLEL,o.left=left3,o.right=right3,o},sequential=(left3,right3)=>{let o=Object.create(proto);return o._tag=OP_SEQUENTIAL,o.left=left3,o.right=right3,o},isCause=(u)=>hasProperty(u,CauseTypeId),isEmptyType=(self)=>self._tag===OP_EMPTY,isFailType=(self)=>self._tag===OP_FAIL,isDieType=(self)=>self._tag===OP_DIE;var isEmpty5=(self)=>{if(self._tag===OP_EMPTY)return!0;return reduce9(self,!0,(acc,cause)=>{switch(cause._tag){case OP_EMPTY:return some2(acc);case OP_DIE:case OP_FAIL:case OP_INTERRUPT:return some2(!1);default:return none2()}})};var isInterrupted=(self)=>isSome2(interruptOption(self)),isInterruptedOnly=(self)=>reduceWithContext(void 0,IsInterruptedOnlyCauseReducer)(self),failures=(self)=>reverse2(reduce9(self,empty5(),(list,cause)=>cause._tag===OP_FAIL?some2(pipe(list,prepend2(cause.error))):none2())),defects=(self)=>reverse2(reduce9(self,empty5(),(list,cause)=>cause._tag===OP_DIE?some2(pipe(list,prepend2(cause.defect))):none2())),interruptors=(self)=>reduce9(self,empty8(),(set4,cause)=>cause._tag===OP_INTERRUPT?some2(pipe(set4,add4(cause.fiberId))):none2()),failureOption=(self)=>find(self,(cause)=>cause._tag===OP_FAIL?some2(cause.error):none2()),failureOrCause=(self)=>{let option=failureOption(self);switch(option._tag){case"None":return right2(self);case"Some":return left2(option.value)}};var flipCauseOption=(self)=>match5(self,{onEmpty:some2(empty20),onFail:map2(fail),onDie:(defect)=>some2(die(defect)),onInterrupt:(fiberId)=>some2(interrupt(fiberId)),onSequential:mergeWith(sequential),onParallel:mergeWith(parallel)}),interruptOption=(self)=>find(self,(cause)=>cause._tag===OP_INTERRUPT?some2(cause.fiberId):none2()),keepDefects=(self)=>match5(self,{onEmpty:none2(),onFail:()=>none2(),onDie:(defect)=>some2(die(defect)),onInterrupt:()=>none2(),onSequential:mergeWith(sequential),onParallel:mergeWith(parallel)}),keepDefectsAndElectFailures=(self)=>match5(self,{onEmpty:none2(),onFail:(failure)=>some2(die(failure)),onDie:(defect)=>some2(die(defect)),onInterrupt:()=>none2(),onSequential:mergeWith(sequential),onParallel:mergeWith(parallel)});var stripFailures=(self)=>match5(self,{onEmpty:empty20,onFail:()=>empty20,onDie:die,onInterrupt:interrupt,onSequential:sequential,onParallel:parallel}),electFailures=(self)=>match5(self,{onEmpty:empty20,onFail:die,onDie:die,onInterrupt:interrupt,onSequential:sequential,onParallel:parallel});var map9=dual(2,(self,f)=>flatMap7(self,(e)=>fail(f(e)))),flatMap7=dual(2,(self,f)=>match5(self,{onEmpty:empty20,onFail:(error)=>f(error),onDie:(defect)=>die(defect),onInterrupt:(fiberId)=>interrupt(fiberId),onSequential:(left3,right3)=>sequential(left3,right3),onParallel:(left3,right3)=>parallel(left3,right3)})),flatten5=(self)=>flatMap7(self,identity);var causeEquals=(left3,right3)=>{let leftStack=of2(left3),rightStack=of2(right3);while(isNonEmpty2(leftStack)&&isNonEmpty2(rightStack)){let[leftParallel,leftSequential]=pipe(headNonEmpty2(leftStack),reduce9([empty8(),empty5()],([parallel2,sequential2],cause)=>{let[par2,seq2]=evaluateCause(cause);return some2([pipe(parallel2,union3(par2)),pipe(sequential2,appendAll2(seq2))])})),[rightParallel,rightSequential]=pipe(headNonEmpty2(rightStack),reduce9([empty8(),empty5()],([parallel2,sequential2],cause)=>{let[par2,seq2]=evaluateCause(cause);return some2([pipe(parallel2,union3(par2)),pipe(sequential2,appendAll2(seq2))])}));if(!equals(leftParallel,rightParallel))return!1;leftStack=leftSequential,rightStack=rightSequential}return!0},flattenCause=(cause)=>{return flattenCauseLoop(of2(cause),empty5())},flattenCauseLoop=(causes,flattened)=>{while(!0){let[parallel2,sequential2]=pipe(causes,reduce([empty8(),empty5()],([parallel3,sequential3],cause)=>{let[par2,seq2]=evaluateCause(cause);return[pipe(parallel3,union3(par2)),pipe(sequential3,appendAll2(seq2))]})),updated=size3(parallel2)>0?pipe(flattened,prepend2(parallel2)):flattened;if(isEmpty(sequential2))return reverse2(updated);causes=sequential2,flattened=updated}throw new Error(getBugErrorMessage("Cause.flattenCauseLoop"))},find=dual(2,(self,pf)=>{let stack=[self];while(stack.length>0){let item=stack.pop(),option=pf(item);switch(option._tag){case"None":{switch(item._tag){case OP_SEQUENTIAL:case OP_PARALLEL:{stack.push(item.right),stack.push(item.left);break}}break}case"Some":return option}}return none2()});var evaluateCause=(self)=>{let cause=self,stack=[],_parallel=empty8(),_sequential=empty5();while(cause!==void 0)switch(cause._tag){case OP_EMPTY:{if(stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_FAIL:{if(_parallel=add4(_parallel,make7(cause._tag,cause.error)),stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_DIE:{if(_parallel=add4(_parallel,make7(cause._tag,cause.defect)),stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_INTERRUPT:{if(_parallel=add4(_parallel,make7(cause._tag,cause.fiberId)),stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_SEQUENTIAL:{switch(cause.left._tag){case OP_EMPTY:{cause=cause.right;break}case OP_SEQUENTIAL:{cause=sequential(cause.left.left,sequential(cause.left.right,cause.right));break}case OP_PARALLEL:{cause=parallel(sequential(cause.left.left,cause.right),sequential(cause.left.right,cause.right));break}default:{_sequential=prepend2(_sequential,cause.right),cause=cause.left;break}}break}case OP_PARALLEL:{stack.push(cause.right),cause=cause.left;break}}throw new Error(getBugErrorMessage("Cause.evaluateCauseLoop"))};var IsInterruptedOnlyCauseReducer={emptyCase:constTrue,failCase:constFalse,dieCase:constFalse,interruptCase:constTrue,sequentialCase:(_,left3,right3)=>left3&&right3,parallelCase:(_,left3,right3)=>left3&&right3};var OP_SEQUENTIAL_CASE="SequentialCase",OP_PARALLEL_CASE="ParallelCase",match5=dual(2,(self,{onDie,onEmpty,onFail,onInterrupt,onParallel,onSequential})=>{return reduceWithContext(self,void 0,{emptyCase:()=>onEmpty,failCase:(_,error)=>onFail(error),dieCase:(_,defect)=>onDie(defect),interruptCase:(_,fiberId)=>onInterrupt(fiberId),sequentialCase:(_,left3,right3)=>onSequential(left3,right3),parallelCase:(_,left3,right3)=>onParallel(left3,right3)})}),reduce9=dual(3,(self,zero3,pf)=>{let accumulator=zero3,cause=self,causes=[];while(cause!==void 0){let option=pf(accumulator,cause);switch(accumulator=isSome2(option)?option.value:accumulator,cause._tag){case OP_SEQUENTIAL:{causes.push(cause.right),cause=cause.left;break}case OP_PARALLEL:{causes.push(cause.right),cause=cause.left;break}default:{cause=void 0;break}}if(cause===void 0&&causes.length>0)cause=causes.pop()}return accumulator}),reduceWithContext=dual(3,(self,context,reducer)=>{let input=[self],output=[];while(input.length>0){let cause=input.pop();switch(cause._tag){case OP_EMPTY:{output.push(right2(reducer.emptyCase(context)));break}case OP_FAIL:{output.push(right2(reducer.failCase(context,cause.error)));break}case OP_DIE:{output.push(right2(reducer.dieCase(context,cause.defect)));break}case OP_INTERRUPT:{output.push(right2(reducer.interruptCase(context,cause.fiberId)));break}case OP_SEQUENTIAL:{input.push(cause.right),input.push(cause.left),output.push(left2({_tag:OP_SEQUENTIAL_CASE}));break}case OP_PARALLEL:{input.push(cause.right),input.push(cause.left),output.push(left2({_tag:OP_PARALLEL_CASE}));break}}}let accumulator=[];while(output.length>0){let either2=output.pop();switch(either2._tag){case"Left":{switch(either2.left._tag){case OP_SEQUENTIAL_CASE:{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.sequentialCase(context,left3,right3);accumulator.push(value);break}case OP_PARALLEL_CASE:{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.parallelCase(context,left3,right3);accumulator.push(value);break}}break}case"Right":{accumulator.push(either2.right);break}}}if(accumulator.length===0)throw new Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return accumulator.pop()}),pretty=(cause,options)=>{if(isInterruptedOnly(cause))return"All fibers interrupted without errors.";return prettyErrors(cause).map(function(e){if(options?.renderErrorCause!==!0||e.cause===void 0)return e.stack;return`${e.stack} {
|
|
8
|
+
${renderErrorCause(e.cause," ")}
|
|
9
|
+
}`}).join(`
|
|
10
|
+
`)},renderErrorCause=(cause,prefix)=>{let lines=cause.stack.split(`
|
|
11
|
+
`),stack=`${prefix}[cause]: ${lines[0]}`;for(let i=1,len=lines.length;i<len;i++)stack+=`
|
|
12
|
+
${prefix}${lines[i]}`;if(cause.cause)stack+=` {
|
|
13
|
+
${renderErrorCause(cause.cause,`${prefix} `)}
|
|
14
|
+
${prefix}}`;return stack};class PrettyError extends globalThis.Error{span=void 0;constructor(originalError){let originalErrorIsObject=typeof originalError==="object"&&originalError!==null,prevLimit=Error.stackTraceLimit;Error.stackTraceLimit=1;super(prettyErrorMessage(originalError),originalErrorIsObject&&"cause"in originalError&&typeof originalError.cause!=="undefined"?{cause:new PrettyError(originalError.cause)}:void 0);if(this.message==="")this.message="An error has occurred";if(Error.stackTraceLimit=prevLimit,this.name=originalError instanceof Error?originalError.name:"Error",originalErrorIsObject){if(spanSymbol in originalError)this.span=originalError[spanSymbol];Object.keys(originalError).forEach((key)=>{if(!(key in this))this[key]=originalError[key]})}this.stack=prettyErrorStack(`${this.name}: ${this.message}`,originalError instanceof Error&&originalError.stack?originalError.stack:"",this.span)}}var prettyErrorMessage=(u)=>{if(typeof u==="string")return u;if(typeof u==="object"&&u!==null&&u instanceof Error)return u.message;try{if(hasProperty(u,"toString")&&isFunction2(u.toString)&&u.toString!==Object.prototype.toString&&u.toString!==globalThis.Array.prototype.toString)return u.toString()}catch{}return stringifyCircular(u)},locationRegex=/\((.*)\)/g,spanToTrace=globalValue("effect/Tracer/spanToTrace",()=>new WeakMap),prettyErrorStack=(message,stack,span2)=>{let out=[message],lines=stack.startsWith(message)?stack.slice(message.length).split(`
|
|
15
|
+
`):stack.split(`
|
|
16
|
+
`);for(let i=1;i<lines.length;i++){if(lines[i].includes(" at new BaseEffectError")||lines[i].includes(" at new YieldableError")){i++;continue}if(lines[i].includes("Generator.next"))break;if(lines[i].includes("effect_internal_function"))break;out.push(lines[i].replace(/at .*effect_instruction_i.*\((.*)\)/,"at $1").replace(/EffectPrimitive\.\w+/,"<anonymous>"))}if(span2){let current=span2,i=0;while(current&¤t._tag==="Span"&&i<10){let stackFn=spanToTrace.get(current);if(typeof stackFn==="function"){let stack2=stackFn();if(typeof stack2==="string"){let locationMatchAll=stack2.matchAll(locationRegex),match6=!1;for(let[,location]of locationMatchAll)match6=!0,out.push(` at ${current.name} (${location})`);if(!match6)out.push(` at ${current.name} (${stack2.replace(/^at /,"")})`)}else out.push(` at ${current.name}`)}else out.push(` at ${current.name}`);current=getOrUndefined(current.parent),i++}}return out.join(`
|
|
17
|
+
`)},spanSymbol=Symbol.for("effect/SpanAnnotation"),prettyErrors=(cause)=>reduceWithContext(cause,void 0,{emptyCase:()=>[],dieCase:(_,unknownError)=>{return[new PrettyError(unknownError)]},failCase:(_,error)=>{return[new PrettyError(error)]},interruptCase:()=>[],parallelCase:(_,l,r)=>[...l,...r],sequentialCase:(_,l,r)=>[...l,...r]});var OP_STATE_PENDING="Pending",OP_STATE_DONE="Done";var DeferredSymbolKey="effect/Deferred",DeferredTypeId=Symbol.for(DeferredSymbolKey),deferredVariance={_E:(_)=>_,_A:(_)=>_},pending=(joiners)=>{return{_tag:OP_STATE_PENDING,joiners}},done=(effect)=>{return{_tag:OP_STATE_DONE,effect}};class SingleShotGen2{self;called=!1;constructor(self){this.self=self}next(a){return this.called?{value:a,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(a){return{value:a,done:!0}}throw(e){throw e}[Symbol.iterator](){return new SingleShotGen2(this.self)}}var blocked=(blockedRequests,_continue)=>{let effect=new EffectPrimitive("Blocked");return effect.effect_instruction_i0=blockedRequests,effect.effect_instruction_i1=_continue,effect},runRequestBlock=(blockedRequests)=>{let effect=new EffectPrimitive("RunBlocked");return effect.effect_instruction_i0=blockedRequests,effect},EffectTypeId2=Symbol.for("effect/Effect");class RevertFlags{patch;op;_op=OP_REVERT_FLAGS;constructor(patch8,op){this.patch=patch8,this.op=op}}class EffectPrimitive{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[EffectTypeId2]=effectVariance;constructor(_op){this._op=_op}[symbol2](that){return this===that}[symbol](){return cached(this,random(this))}pipe(){return pipeArguments(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:toJSON(this.effect_instruction_i0),effect_instruction_i1:toJSON(this.effect_instruction_i1),effect_instruction_i2:toJSON(this.effect_instruction_i2)}}toString(){return format(this.toJSON())}[NodeInspectSymbol](){return this.toJSON()}[Symbol.iterator](){return new SingleShotGen2(new YieldWrap(this))}}class EffectPrimitiveFailure{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[EffectTypeId2]=effectVariance;constructor(_op){this._op=_op,this._tag=_op}[symbol2](that){return exitIsExit(that)&&that._op==="Failure"&&equals(this.effect_instruction_i0,that.effect_instruction_i0)}[symbol](){return pipe(string(this._tag),combine(hash(this.effect_instruction_i0)),cached(this))}get cause(){return this.effect_instruction_i0}pipe(){return pipeArguments(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return format(this.toJSON())}[NodeInspectSymbol](){return this.toJSON()}[Symbol.iterator](){return new SingleShotGen2(new YieldWrap(this))}}class EffectPrimitiveSuccess{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[EffectTypeId2]=effectVariance;constructor(_op){this._op=_op,this._tag=_op}[symbol2](that){return exitIsExit(that)&&that._op==="Success"&&equals(this.effect_instruction_i0,that.effect_instruction_i0)}[symbol](){return pipe(string(this._tag),combine(hash(this.effect_instruction_i0)),cached(this))}get value(){return this.effect_instruction_i0}pipe(){return pipeArguments(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:toJSON(this.value)}}toString(){return format(this.toJSON())}[NodeInspectSymbol](){return this.toJSON()}[Symbol.iterator](){return new SingleShotGen2(new YieldWrap(this))}}var isEffect=(u)=>hasProperty(u,EffectTypeId2),withFiberRuntime=(withRuntime)=>{let effect=new EffectPrimitive(OP_WITH_RUNTIME);return effect.effect_instruction_i0=withRuntime,effect},acquireUseRelease=dual(3,(acquire,use,release)=>uninterruptibleMask((restore)=>flatMap8(acquire,(a)=>flatMap8(exit(suspend(()=>restore(use(a)))),(exit)=>{return suspend(()=>release(a,exit)).pipe(matchCauseEffect({onFailure:(cause)=>{switch(exit._tag){case OP_FAILURE:return failCause(sequential(exit.effect_instruction_i0,cause));case OP_SUCCESS:return failCause(cause)}},onSuccess:()=>exit}))})))),as=dual(2,(self,value)=>flatMap8(self,()=>succeed(value))),asVoid=(self)=>as(self,void 0),custom=function(){let wrapper=new EffectPrimitive(OP_COMMIT);switch(arguments.length){case 2:{wrapper.effect_instruction_i0=arguments[0],wrapper.commit=arguments[1];break}case 3:{wrapper.effect_instruction_i0=arguments[0],wrapper.effect_instruction_i1=arguments[1],wrapper.commit=arguments[2];break}case 4:{wrapper.effect_instruction_i0=arguments[0],wrapper.effect_instruction_i1=arguments[1],wrapper.effect_instruction_i2=arguments[2],wrapper.commit=arguments[3];break}default:throw new Error(getBugErrorMessage("you're not supposed to end up here"))}return wrapper},unsafeAsync=(register,blockingOn=none4)=>{let effect=new EffectPrimitive(OP_ASYNC),cancelerRef=void 0;return effect.effect_instruction_i0=(resume)=>{cancelerRef=register(resume)},effect.effect_instruction_i1=blockingOn,onInterrupt(effect,(_)=>isEffect(cancelerRef)?cancelerRef:void_)},asyncInterrupt=(register,blockingOn=none4)=>suspend(()=>unsafeAsync(register,blockingOn)),async_=(resume,blockingOn=none4)=>{return custom(resume,function(){let backingResume=void 0,pendingEffect=void 0;function proxyResume(effect2){if(backingResume)backingResume(effect2);else if(pendingEffect===void 0)pendingEffect=effect2}let effect=new EffectPrimitive(OP_ASYNC);effect.effect_instruction_i0=(resume2)=>{if(backingResume=resume2,pendingEffect)resume2(pendingEffect)},effect.effect_instruction_i1=blockingOn;let cancelerRef=void 0,controllerRef=void 0;if(this.effect_instruction_i0.length!==1)controllerRef=new AbortController,cancelerRef=internalCall(()=>this.effect_instruction_i0(proxyResume,controllerRef.signal));else cancelerRef=internalCall(()=>this.effect_instruction_i0(proxyResume));return cancelerRef||controllerRef?onInterrupt(effect,(_)=>{if(controllerRef)controllerRef.abort();return cancelerRef??void_}):effect})};var catchAllCause=dual(2,(self,f)=>{let effect=new EffectPrimitive(OP_ON_FAILURE);return effect.effect_instruction_i0=self,effect.effect_instruction_i1=f,effect}),catchAll=dual(2,(self,f)=>matchEffect(self,{onFailure:f,onSuccess:succeed})),catchIf=dual(3,(self,predicate,f)=>catchAllCause(self,(cause)=>{let either2=failureOrCause(cause);switch(either2._tag){case"Left":return predicate(either2.left)?f(either2.left):failCause(cause);case"Right":return failCause(either2.right)}})),catchSome=dual(2,(self,pf)=>catchAllCause(self,(cause)=>{let either2=failureOrCause(cause);switch(either2._tag){case"Left":return pipe(pf(either2.left),getOrElse(()=>failCause(cause)));case"Right":return failCause(either2.right)}})),checkInterruptible=(f)=>withFiberRuntime((_,status)=>f(interruption(status.runtimeFlags))),originalSymbol=Symbol.for("effect/OriginalAnnotation");var capture=(obj,span2)=>{if(isSome2(span2))return new Proxy(obj,{has(target,p){return p===spanSymbol||p===originalSymbol||p in target},get(target,p){if(p===spanSymbol)return span2.value;if(p===originalSymbol)return obj;return target[p]}});return obj},die2=(defect)=>isObject(defect)&&!(spanSymbol in defect)?withFiberRuntime((fiber)=>failCause(die(capture(defect,currentSpanFromFiber(fiber))))):failCause(die(defect)),dieMessage=(message)=>failCauseSync(()=>die(new RuntimeException(message))),dieSync=(evaluate)=>flatMap8(sync(evaluate),die2),either2=(self)=>matchEffect(self,{onFailure:(e)=>succeed(left2(e)),onSuccess:(a)=>succeed(right2(a))}),exit=(self)=>matchCause(self,{onFailure:exitFailCause,onSuccess:exitSucceed}),fail2=(error)=>isObject(error)&&!(spanSymbol in error)?withFiberRuntime((fiber)=>failCause(fail(capture(error,currentSpanFromFiber(fiber))))):failCause(fail(error)),failSync=(evaluate)=>flatMap8(sync(evaluate),fail2),failCause=(cause)=>{let effect=new EffectPrimitiveFailure(OP_FAILURE);return effect.effect_instruction_i0=cause,effect},failCauseSync=(evaluate)=>flatMap8(sync(evaluate),failCause),fiberId=withFiberRuntime((state)=>succeed(state.id())),fiberIdWith=(f)=>withFiberRuntime((state)=>f(state.id())),flatMap8=dual(2,(self,f)=>{let effect=new EffectPrimitive(OP_ON_SUCCESS);return effect.effect_instruction_i0=self,effect.effect_instruction_i1=f,effect}),andThen2=dual(2,(self,f)=>flatMap8(self,(a)=>{let b=typeof f==="function"?f(a):f;if(isEffect(b))return b;else if(isPromiseLike(b))return unsafeAsync((resume)=>{b.then((a2)=>resume(succeed(a2)),(e)=>resume(fail2(new UnknownException(e,"An unknown error occurred in Effect.andThen"))))});return succeed(b)})),step2=(self)=>{let effect=new EffectPrimitive("OnStep");return effect.effect_instruction_i0=self,effect},flatten6=(self)=>flatMap8(self,identity),flip=(self)=>matchEffect(self,{onFailure:succeed,onSuccess:fail2}),matchCause=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>succeed(options.onFailure(cause)),onSuccess:(a)=>succeed(options.onSuccess(a))})),matchCauseEffect=dual(2,(self,options)=>{let effect=new EffectPrimitive(OP_ON_SUCCESS_AND_FAILURE);return effect.effect_instruction_i0=self,effect.effect_instruction_i1=options.onFailure,effect.effect_instruction_i2=options.onSuccess,effect}),matchEffect=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>{if(defects(cause).length>0)return failCause(electFailures(cause));let failures2=failures(cause);if(failures2.length>0)return options.onFailure(unsafeHead2(failures2));return failCause(cause)},onSuccess:options.onSuccess})),forEachSequential=dual(2,(self,f)=>suspend(()=>{let arr=fromIterable(self),ret=allocate(arr.length),i=0;return as(whileLoop({while:()=>i<arr.length,body:()=>f(arr[i],i),step:(b)=>{ret[i++]=b}}),ret)})),forEachSequentialDiscard=dual(2,(self,f)=>suspend(()=>{let arr=fromIterable(self),i=0;return whileLoop({while:()=>i<arr.length,body:()=>f(arr[i],i),step:()=>{i++}})})),if_=dual((args)=>typeof args[0]==="boolean"||isEffect(args[0]),(self,options)=>isEffect(self)?flatMap8(self,(b)=>b?options.onTrue():options.onFalse()):self?options.onTrue():options.onFalse()),interrupt2=flatMap8(fiberId,(fiberId2)=>interruptWith(fiberId2)),interruptWith=(fiberId2)=>failCause(interrupt(fiberId2)),interruptible2=(self)=>{let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=enable3(Interruption),effect.effect_instruction_i1=()=>self,effect},interruptibleMask=(f)=>custom(f,function(){let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=enable3(Interruption),effect.effect_instruction_i1=(oldFlags)=>interruption(oldFlags)?internalCall(()=>this.effect_instruction_i0(interruptible2)):internalCall(()=>this.effect_instruction_i0(uninterruptible)),effect}),intoDeferred=dual(2,(self,deferred)=>uninterruptibleMask((restore)=>flatMap8(exit(restore(self)),(exit2)=>deferredDone(deferred,exit2)))),map10=dual(2,(self,f)=>flatMap8(self,(a)=>sync(()=>f(a)))),mapBoth=dual(2,(self,options)=>matchEffect(self,{onFailure:(e)=>failSync(()=>options.onFailure(e)),onSuccess:(a)=>sync(()=>options.onSuccess(a))})),mapError=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(cause)=>{let either3=failureOrCause(cause);switch(either3._tag){case"Left":return failSync(()=>f(either3.left));case"Right":return failCause(either3.right)}},onSuccess:succeed})),onError=dual(2,(self,cleanup)=>onExit(self,(exit2)=>exitIsSuccess(exit2)?void_:cleanup(exit2.effect_instruction_i0))),onExit=dual(2,(self,cleanup)=>uninterruptibleMask((restore)=>matchCauseEffect(restore(self),{onFailure:(cause1)=>{let result=exitFailCause(cause1);return matchCauseEffect(cleanup(result),{onFailure:(cause2)=>exitFailCause(sequential(cause1,cause2)),onSuccess:()=>result})},onSuccess:(success)=>{let result=exitSucceed(success);return zipRight(cleanup(result),result)}}))),onInterrupt=dual(2,(self,cleanup)=>onExit(self,exitMatch({onFailure:(cause)=>isInterruptedOnly(cause)?asVoid(cleanup(interruptors(cause))):void_,onSuccess:()=>void_}))),orElse2=dual(2,(self,that)=>attemptOrElse(self,that,succeed)),orDie=(self)=>orDieWith(self,identity),orDieWith=dual(2,(self,f)=>matchEffect(self,{onFailure:(e)=>die2(f(e)),onSuccess:succeed})),partitionMap2=partitionMap,runtimeFlags=withFiberRuntime((_,status)=>succeed(status.runtimeFlags)),succeed=(value)=>{let effect=new EffectPrimitiveSuccess(OP_SUCCESS);return effect.effect_instruction_i0=value,effect},suspend=(evaluate)=>{let effect=new EffectPrimitive(OP_COMMIT);return effect.commit=evaluate,effect},sync=(thunk)=>{let effect=new EffectPrimitive(OP_SYNC);return effect.effect_instruction_i0=thunk,effect},tap=dual((args)=>args.length===3||args.length===2&&!(isObject(args[1])&&("onlyEffect"in args[1])),(self,f)=>flatMap8(self,(a)=>{let b=typeof f==="function"?f(a):f;if(isEffect(b))return as(b,a);else if(isPromiseLike(b))return unsafeAsync((resume)=>{b.then((_)=>resume(succeed(a)),(e)=>resume(fail2(new UnknownException(e,"An unknown error occurred in Effect.tap"))))});return succeed(a)})),transplant=(f)=>withFiberRuntime((state)=>{let scopeOverride=state.getFiberRef(currentForkScopeOverride),scope=pipe(scopeOverride,getOrElse(()=>state.scope()));return f(fiberRefLocally(currentForkScopeOverride,some2(scope)))}),attemptOrElse=dual(3,(self,that,onSuccess)=>matchCauseEffect(self,{onFailure:(cause)=>{if(defects(cause).length>0)return failCause(getOrThrow2(keepDefectsAndElectFailures(cause)));return that()},onSuccess})),uninterruptible=(self)=>{let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=disable2(Interruption),effect.effect_instruction_i1=()=>self,effect},uninterruptibleMask=(f)=>custom(f,function(){let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=disable2(Interruption),effect.effect_instruction_i1=(oldFlags)=>interruption(oldFlags)?internalCall(()=>this.effect_instruction_i0(interruptible2)):internalCall(()=>this.effect_instruction_i0(uninterruptible)),effect}),void_=succeed(void 0);var updateRuntimeFlags=(patch8)=>{let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=patch8,effect.effect_instruction_i1=void 0,effect},whenEffect=dual(2,(self,condition)=>flatMap8(condition,(b)=>{if(b)return pipe(self,map10(some2));return succeed(none2())})),whileLoop=(options)=>{let effect=new EffectPrimitive(OP_WHILE);return effect.effect_instruction_i0=options.while,effect.effect_instruction_i1=options.body,effect.effect_instruction_i2=options.step,effect},fromIterator=(iterator)=>suspend(()=>{let effect=new EffectPrimitive(OP_ITERATOR);return effect.effect_instruction_i0=iterator(),effect}),gen=function(){let f=arguments.length===1?arguments[0]:arguments[1].bind(arguments[0]);return fromIterator(()=>f(pipe))},fnUntraced=(body,...pipeables)=>Object.defineProperty(pipeables.length===0?function(...args){return fromIterator(()=>body.apply(this,args))}:function(...args){let effect=fromIterator(()=>body.apply(this,args));for(let x of pipeables)effect=x(effect,...args);return effect},"length",{value:body.length,configurable:!0}),withConcurrency=dual(2,(self,concurrency)=>fiberRefLocally(self,currentConcurrency,concurrency)),withRequestBatching=dual(2,(self,requestBatching)=>fiberRefLocally(self,currentRequestBatching,requestBatching)),withRuntimeFlags=dual(2,(self,update2)=>{let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=update2,effect.effect_instruction_i1=()=>self,effect}),withTracerEnabled=dual(2,(effect,enabled2)=>fiberRefLocally(effect,currentTracerEnabled,enabled2)),withTracerTiming=dual(2,(effect,enabled2)=>fiberRefLocally(effect,currentTracerTimingEnabled,enabled2)),yieldNow=(options)=>{let effect=new EffectPrimitive(OP_YIELD);return typeof options?.priority!=="undefined"?withSchedulingPriority(effect,options.priority):effect},zip2=dual(2,(self,that)=>flatMap8(self,(a)=>map10(that,(b)=>[a,b])));var zipLeft=dual(2,(self,that)=>flatMap8(self,(a)=>as(that,a))),zipRight=dual(2,(self,that)=>flatMap8(self,()=>that)),zipWith3=dual(3,(self,that,f)=>flatMap8(self,(a)=>map10(that,(b)=>f(a,b)))),never=asyncInterrupt(()=>{let interval=setInterval(()=>{},2147483647);return sync(()=>clearInterval(interval))}),interruptFiber=(self)=>flatMap8(fiberId,(fiberId2)=>pipe(self,interruptAsFiber(fiberId2))),interruptAsFiber=dual(2,(self,fiberId2)=>flatMap8(self.interruptAsFork(fiberId2),()=>self.await)),logLevelAll={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return pipeArguments(this,arguments)}},logLevelFatal={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return pipeArguments(this,arguments)}},logLevelError={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return pipeArguments(this,arguments)}},logLevelWarning={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return pipeArguments(this,arguments)}},logLevelInfo={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return pipeArguments(this,arguments)}},logLevelDebug={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return pipeArguments(this,arguments)}},logLevelTrace={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return pipeArguments(this,arguments)}},logLevelNone={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return pipeArguments(this,arguments)}};var FiberRefSymbolKey="effect/FiberRef",FiberRefTypeId=Symbol.for(FiberRefSymbolKey),fiberRefVariance={_A:(_)=>_},fiberRefGet=(self)=>withFiberRuntime((fiber)=>exitSucceed(fiber.getFiberRef(self)));var fiberRefGetWith=dual(2,(self,f)=>flatMap8(fiberRefGet(self),f)),fiberRefSet=dual(2,(self,value)=>fiberRefModify(self,()=>[void 0,value]));var fiberRefModify=dual(2,(self,f)=>withFiberRuntime((state)=>{let[b,a]=f(state.getFiberRef(self));return state.setFiberRef(self,a),succeed(b)}));var fiberRefLocally=dual(3,(use,self,value)=>acquireUseRelease(zipLeft(fiberRefGet(self),fiberRefSet(self,value)),()=>use,(oldValue)=>fiberRefSet(self,oldValue))),fiberRefLocallyWith=dual(3,(use,self,f)=>fiberRefGetWith(self,(a)=>fiberRefLocally(use,self,f(a)))),fiberRefUnsafeMake=(initial,options)=>fiberRefUnsafeMakePatch(initial,{differ:update(),fork:options?.fork??identity,join:options?.join}),fiberRefUnsafeMakeHashSet=(initial)=>{let differ2=hashSet();return fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:differ2.empty})},fiberRefUnsafeMakeReadonlyArray=(initial)=>{let differ2=readonlyArray(update());return fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:differ2.empty})},fiberRefUnsafeMakeContext=(initial)=>{let differ2=environment();return fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:differ2.empty})},fiberRefUnsafeMakePatch=(initial,options)=>{return{...CommitPrototype,[FiberRefTypeId]:fiberRefVariance,initial,commit(){return fiberRefGet(this)},diff:(oldValue,newValue)=>options.differ.diff(oldValue,newValue),combine:(first,second)=>options.differ.combine(first,second),patch:(patch8)=>(oldValue)=>options.differ.patch(patch8,oldValue),fork:options.fork,join:options.join??((_,n)=>n)}},fiberRefUnsafeMakeRuntimeFlags=(initial)=>fiberRefUnsafeMakePatch(initial,{differ,fork:differ.empty}),currentContext=globalValue(Symbol.for("effect/FiberRef/currentContext"),()=>fiberRefUnsafeMakeContext(empty4())),currentSchedulingPriority=globalValue(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>fiberRefUnsafeMake(0)),currentMaxOpsBeforeYield=globalValue(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>fiberRefUnsafeMake(2048)),currentLogAnnotations=globalValue(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>fiberRefUnsafeMake(empty9())),currentLogLevel=globalValue(Symbol.for("effect/FiberRef/currentLogLevel"),()=>fiberRefUnsafeMake(logLevelInfo)),currentLogSpan=globalValue(Symbol.for("effect/FiberRef/currentLogSpan"),()=>fiberRefUnsafeMake(empty10())),withSchedulingPriority=dual(2,(self,scheduler)=>fiberRefLocally(self,currentSchedulingPriority,scheduler)),withMaxOpsBeforeYield=dual(2,(self,scheduler)=>fiberRefLocally(self,currentMaxOpsBeforeYield,scheduler)),currentConcurrency=globalValue(Symbol.for("effect/FiberRef/currentConcurrency"),()=>fiberRefUnsafeMake("unbounded")),currentRequestBatching=globalValue(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>fiberRefUnsafeMake(!0)),currentUnhandledErrorLogLevel=globalValue(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>fiberRefUnsafeMake(some2(logLevelDebug))),withUnhandledErrorLogLevel=dual(2,(self,level)=>fiberRefLocally(self,currentUnhandledErrorLogLevel,level)),currentMetricLabels=globalValue(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>fiberRefUnsafeMakeReadonlyArray(empty2())),metricLabels=fiberRefGet(currentMetricLabels),currentForkScopeOverride=globalValue(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>fiberRefUnsafeMake(none2(),{fork:()=>none2(),join:(parent,_)=>parent})),currentInterruptedCause=globalValue(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>fiberRefUnsafeMake(empty20,{fork:()=>empty20,join:(parent,_)=>parent})),currentTracerEnabled=globalValue(Symbol.for("effect/FiberRef/currentTracerEnabled"),()=>fiberRefUnsafeMake(!0)),currentTracerTimingEnabled=globalValue(Symbol.for("effect/FiberRef/currentTracerTiming"),()=>fiberRefUnsafeMake(!0)),currentTracerSpanAnnotations=globalValue(Symbol.for("effect/FiberRef/currentTracerSpanAnnotations"),()=>fiberRefUnsafeMake(empty9())),currentTracerSpanLinks=globalValue(Symbol.for("effect/FiberRef/currentTracerSpanLinks"),()=>fiberRefUnsafeMake(empty5())),ScopeTypeId=Symbol.for("effect/Scope"),CloseableScopeTypeId=Symbol.for("effect/CloseableScope"),scopeAddFinalizer=(self,finalizer)=>self.addFinalizer(()=>asVoid(finalizer)),scopeAddFinalizerExit=(self,finalizer)=>self.addFinalizer(finalizer),scopeClose=(self,exit2)=>self.close(exit2),scopeFork=(self,strategy)=>self.fork(strategy),causeSquash=(self)=>{return causeSquashWith(identity)(self)},causeSquashWith=dual(2,(self,f)=>{let option=pipe(self,failureOption,map2(f));switch(option._tag){case"None":return pipe(defects(self),head2,match2({onNone:()=>{let interrupts=fromIterable(interruptors(self)).flatMap((fiberId2)=>fromIterable(ids2(fiberId2)).map((id)=>`#${id}`));return new InterruptedException(interrupts?`Interrupted by fibers: ${interrupts.join(", ")}`:void 0)},onSome:identity}));case"Some":return option.value}}),YieldableError=function(){class YieldableError2 extends globalThis.Error{commit(){return fail2(this)}toJSON(){let obj={...this};if(this.message)obj.message=this.message;if(this.cause)obj.cause=this.cause;return obj}[NodeInspectSymbol](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
|
|
18
|
+
${this.stack.split(`
|
|
19
|
+
`).slice(1).join(`
|
|
20
|
+
`)}`:this.toString();else if("Bun"in globalThis)return pretty(fail(this),{renderErrorCause:!0});return this}}return Object.assign(YieldableError2.prototype,StructuralCommitPrototype),YieldableError2}(),makeException=(proto2,tag)=>{class Base2 extends YieldableError{_tag=tag}return Object.assign(Base2.prototype,proto2),Base2.prototype.name=tag,Base2},RuntimeExceptionTypeId=Symbol.for("effect/Cause/errors/RuntimeException"),RuntimeException=makeException({[RuntimeExceptionTypeId]:RuntimeExceptionTypeId},"RuntimeException"),isRuntimeException=(u)=>hasProperty(u,RuntimeExceptionTypeId),InterruptedExceptionTypeId=Symbol.for("effect/Cause/errors/InterruptedException"),InterruptedException=makeException({[InterruptedExceptionTypeId]:InterruptedExceptionTypeId},"InterruptedException"),isInterruptedException=(u)=>hasProperty(u,InterruptedExceptionTypeId),IllegalArgumentExceptionTypeId=Symbol.for("effect/Cause/errors/IllegalArgument"),IllegalArgumentException=makeException({[IllegalArgumentExceptionTypeId]:IllegalArgumentExceptionTypeId},"IllegalArgumentException");var NoSuchElementExceptionTypeId=Symbol.for("effect/Cause/errors/NoSuchElement"),NoSuchElementException=makeException({[NoSuchElementExceptionTypeId]:NoSuchElementExceptionTypeId},"NoSuchElementException"),isNoSuchElementException=(u)=>hasProperty(u,NoSuchElementExceptionTypeId),InvalidPubSubCapacityExceptionTypeId=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),InvalidPubSubCapacityException=makeException({[InvalidPubSubCapacityExceptionTypeId]:InvalidPubSubCapacityExceptionTypeId},"InvalidPubSubCapacityException"),ExceededCapacityExceptionTypeId=Symbol.for("effect/Cause/errors/ExceededCapacityException"),ExceededCapacityException=makeException({[ExceededCapacityExceptionTypeId]:ExceededCapacityExceptionTypeId},"ExceededCapacityException");var TimeoutExceptionTypeId=Symbol.for("effect/Cause/errors/Timeout"),TimeoutException=makeException({[TimeoutExceptionTypeId]:TimeoutExceptionTypeId},"TimeoutException"),timeoutExceptionFromDuration=(duration)=>new TimeoutException(`Operation timed out after '${format3(duration)}'`);var UnknownExceptionTypeId=Symbol.for("effect/Cause/errors/UnknownException"),UnknownException=function(){class UnknownException2 extends YieldableError{_tag="UnknownException";error;constructor(cause,message){super(message??"An unknown error occurred",{cause});this.error=cause}}return Object.assign(UnknownException2.prototype,{[UnknownExceptionTypeId]:UnknownExceptionTypeId,name:"UnknownException"}),UnknownException2}();var exitIsExit=(u)=>isEffect(u)&&("_tag"in u)&&(u._tag==="Success"||u._tag==="Failure"),exitIsFailure=(self)=>self._tag==="Failure",exitIsSuccess=(self)=>self._tag==="Success";var exitAs=dual(2,(self,value)=>{switch(self._tag){case OP_FAILURE:return exitFailCause(self.effect_instruction_i0);case OP_SUCCESS:return exitSucceed(value)}}),exitAsVoid=(self)=>exitAs(self,void 0);var exitCollectAll=(exits,options)=>exitCollectAllInternal(exits,options?.parallel?parallel:sequential),exitDie=(defect)=>exitFailCause(die(defect));var exitFail=(error)=>exitFailCause(fail(error)),exitFailCause=(cause)=>{let effect=new EffectPrimitiveFailure(OP_FAILURE);return effect.effect_instruction_i0=cause,effect},exitFlatMap=dual(2,(self,f)=>{switch(self._tag){case OP_FAILURE:return exitFailCause(self.effect_instruction_i0);case OP_SUCCESS:return f(self.effect_instruction_i0)}});var exitFlatten=(self)=>pipe(self,exitFlatMap(identity)),exitForEachEffect=dual(2,(self,f)=>{switch(self._tag){case OP_FAILURE:return succeed(exitFailCause(self.effect_instruction_i0));case OP_SUCCESS:return exit(f(self.effect_instruction_i0))}});var exitInterrupt=(fiberId2)=>exitFailCause(interrupt(fiberId2)),exitMap=dual(2,(self,f)=>{switch(self._tag){case OP_FAILURE:return exitFailCause(self.effect_instruction_i0);case OP_SUCCESS:return exitSucceed(f(self.effect_instruction_i0))}}),exitMapBoth=dual(2,(self,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:return exitFailCause(pipe(self.effect_instruction_i0,map9(onFailure)));case OP_SUCCESS:return exitSucceed(onSuccess(self.effect_instruction_i0))}});var exitMatch=dual(2,(self,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:return onFailure(self.effect_instruction_i0);case OP_SUCCESS:return onSuccess(self.effect_instruction_i0)}}),exitMatchEffect=dual(2,(self,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:return onFailure(self.effect_instruction_i0);case OP_SUCCESS:return onSuccess(self.effect_instruction_i0)}}),exitSucceed=(value)=>{let effect=new EffectPrimitiveSuccess(OP_SUCCESS);return effect.effect_instruction_i0=value,effect},exitVoid=exitSucceed(void 0),exitZip=dual(2,(self,that)=>exitZipWith(self,that,{onSuccess:(a,a2)=>[a,a2],onFailure:sequential}));var exitZipRight=dual(2,(self,that)=>exitZipWith(self,that,{onSuccess:(_,a2)=>a2,onFailure:sequential}));var exitZipWith=dual(3,(self,that,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:switch(that._tag){case OP_SUCCESS:return exitFailCause(self.effect_instruction_i0);case OP_FAILURE:return exitFailCause(onFailure(self.effect_instruction_i0,that.effect_instruction_i0))}case OP_SUCCESS:switch(that._tag){case OP_SUCCESS:return exitSucceed(onSuccess(self.effect_instruction_i0,that.effect_instruction_i0));case OP_FAILURE:return exitFailCause(that.effect_instruction_i0)}}}),exitCollectAllInternal=(exits,combineCauses)=>{let list=fromIterable2(exits);if(!isNonEmpty2(list))return none2();return pipe(tailNonEmpty2(list),reduce(pipe(headNonEmpty2(list),exitMap(of2)),(accumulator,current)=>pipe(accumulator,exitZipWith(current,{onSuccess:(list2,value)=>pipe(list2,prepend2(value)),onFailure:combineCauses}))),exitMap(reverse2),exitMap((chunk)=>toReadonlyArray(chunk)),some2)},deferredUnsafeMake=(fiberId2)=>{return{...CommitPrototype,[DeferredTypeId]:deferredVariance,state:make12(pending([])),commit(){return deferredAwait(this)},blockingOn:fiberId2}},deferredMake=()=>flatMap8(fiberId,(id)=>deferredMakeAs(id)),deferredMakeAs=(fiberId2)=>sync(()=>deferredUnsafeMake(fiberId2)),deferredAwait=(self)=>asyncInterrupt((resume)=>{let state=get6(self.state);switch(state._tag){case OP_STATE_DONE:return resume(state.effect);case OP_STATE_PENDING:return state.joiners.push(resume),deferredInterruptJoiner(self,resume)}},self.blockingOn),deferredComplete=dual(2,(self,effect)=>intoDeferred(effect,self)),deferredCompleteWith=dual(2,(self,effect)=>sync(()=>{let state=get6(self.state);switch(state._tag){case OP_STATE_DONE:return!1;case OP_STATE_PENDING:{set2(self.state,done(effect));for(let i=0,len=state.joiners.length;i<len;i++)state.joiners[i](effect);return!0}}})),deferredDone=dual(2,(self,exit2)=>deferredCompleteWith(self,exit2)),deferredFail=dual(2,(self,error)=>deferredCompleteWith(self,fail2(error)));var deferredFailCause=dual(2,(self,cause)=>deferredCompleteWith(self,failCause(cause)));var deferredInterrupt=(self)=>flatMap8(fiberId,(fiberId2)=>deferredCompleteWith(self,interruptWith(fiberId2))),deferredInterruptWith=dual(2,(self,fiberId2)=>deferredCompleteWith(self,interruptWith(fiberId2))),deferredIsDone=(self)=>sync(()=>get6(self.state)._tag===OP_STATE_DONE),deferredPoll=(self)=>sync(()=>{let state=get6(self.state);switch(state._tag){case OP_STATE_DONE:return some2(state.effect);case OP_STATE_PENDING:return none2()}}),deferredSucceed=dual(2,(self,value)=>deferredCompleteWith(self,succeed(value)));var deferredUnsafeDone=(self,effect)=>{let state=get6(self.state);if(state._tag===OP_STATE_PENDING){set2(self.state,done(effect));for(let i=0,len=state.joiners.length;i<len;i++)state.joiners[i](effect)}},deferredInterruptJoiner=(self,joiner)=>sync(()=>{let state=get6(self.state);if(state._tag===OP_STATE_PENDING){let index=state.joiners.indexOf(joiner);if(index>=0)state.joiners.splice(index,1)}}),constContext=withFiberRuntime((fiber)=>exitSucceed(fiber.currentContext)),context=()=>constContext;var contextWithEffect=(f)=>flatMap8(context(),f),provideContext=dual(2,(self,context2)=>fiberRefLocally(currentContext,context2)(self)),provideSomeContext=dual(2,(self,context2)=>fiberRefLocallyWith(currentContext,(parent)=>merge3(parent,context2))(self)),mapInputContext=dual(2,(self,f)=>contextWithEffect((context2)=>provideContext(self,f(context2)))),filterEffectOrElse=dual(2,(self,options)=>flatMap8(self,(a)=>flatMap8(options.predicate(a),(pass)=>pass?succeed(a):options.orElse(a)))),filterEffectOrFail=dual(2,(self,options)=>filterEffectOrElse(self,{predicate:options.predicate,orElse:(a)=>fail2(options.orFailWith(a))})),currentSpanFromFiber=(fiber)=>{let span2=fiber.currentSpan;return span2!==void 0&&span2._tag==="Span"?some2(span2):none2()},NoopSpanProto={_tag:"Span",spanId:"noop",traceId:"noop",sampled:!1,status:{_tag:"Ended",startTime:BigInt(0),endTime:BigInt(0),exit:exitVoid},attributes:new Map,links:[],kind:"internal",attribute(){},event(){},end(){},addLinks(){}},noopSpan=(options)=>Object.assign(Object.create(NoopSpanProto),options);var make19=deferredMake;var _await=deferredAwait;var done2=deferredDone,fail3=deferredFail;var failCause2=deferredFailCause;var interrupt3=deferredInterrupt;var isDone=deferredIsDone,poll=deferredPoll,succeed2=deferredSucceed;var unsafeMake3=deferredUnsafeMake,unsafeDone=deferredUnsafeDone;var isExit=exitIsExit,isFailure=exitIsFailure,isSuccess=exitIsSuccess;var all2=exitCollectAll,die3=exitDie;var fail4=exitFail,failCause3=exitFailCause;var flatten7=exitFlatten,forEachEffect=exitForEachEffect;var interrupt4=exitInterrupt,map11=exitMap,mapBoth2=exitMapBoth;var match6=exitMatch;var succeed3=exitSucceed,void_2=exitVoid;var zip3=exitZip;var zipRight2=exitZipRight;var zipWith4=exitZipWith;var TypeId9=Symbol.for("effect/MutableHashMap"),MutableHashMapProto={[TypeId9]:TypeId9,[Symbol.iterator](){return new MutableHashMapIterator(this)},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};class MutableHashMapIterator{self;referentialIterator;bucketIterator;constructor(self){this.self=self,this.referentialIterator=self.referential[Symbol.iterator]()}next(){if(this.bucketIterator!==void 0)return this.bucketIterator.next();let result=this.referentialIterator.next();if(result.done)return this.bucketIterator=new BucketIterator(this.self.buckets.values()),this.next();return result}[Symbol.iterator](){return new MutableHashMapIterator(this.self)}}class BucketIterator{backing;constructor(backing){this.backing=backing}currentBucket;next(){if(this.currentBucket===void 0){let result2=this.backing.next();if(result2.done)return result2;this.currentBucket=result2.value[Symbol.iterator]()}let result=this.currentBucket.next();if(result.done)return this.currentBucket=void 0,this.next();return result}}var empty21=()=>{let self=Object.create(MutableHashMapProto);return self.referential=new Map,self.buckets=new Map,self.bucketsSize=0,self};var get8=dual(2,(self,key)=>{if(isEqual(key)===!1)return self.referential.has(key)?some2(self.referential.get(key)):none2();let hash2=key[symbol](),bucket=self.buckets.get(hash2);if(bucket===void 0)return none2();return getFromBucket(self,bucket,key)});var getFromBucket=(self,bucket,key,remove6=!1)=>{for(let i=0,len=bucket.length;i<len;i++)if(key[symbol2](bucket[i][0])){let value=bucket[i][1];if(remove6)bucket.splice(i,1),self.bucketsSize--;return some2(value)}return none2()},has4=dual(2,(self,key)=>isSome2(get8(self,key))),set4=dual(3,(self,key,value)=>{if(isEqual(key)===!1)return self.referential.set(key,value),self;let hash2=key[symbol](),bucket=self.buckets.get(hash2);if(bucket===void 0)return self.buckets.set(hash2,[[key,value]]),self.bucketsSize++,self;return removeFromBucket(self,bucket,key),bucket.push([key,value]),self.bucketsSize++,self}),removeFromBucket=(self,bucket,key)=>{for(let i=0,len=bucket.length;i<len;i++)if(key[symbol2](bucket[i][0])){bucket.splice(i,1),self.bucketsSize--;return}};var remove6=dual(2,(self,key)=>{if(isEqual(key)===!1)return self.referential.delete(key),self;let hash2=key[symbol](),bucket=self.buckets.get(hash2);if(bucket===void 0)return self;if(removeFromBucket(self,bucket,key),bucket.length===0)self.buckets.delete(hash2);return self});var size4=(self)=>{return self.referential.size+self.bucketsSize};var TypeId10=Symbol.for("effect/MutableList"),MutableListProto={[TypeId10]:TypeId10,[Symbol.iterator](){let done3=!1,head3=this.head;return{next(){if(done3)return this.return();if(head3==null)return done3=!0,this.return();let value=head3.value;return head3=head3.next,{done:done3,value}},return(value){if(!done3)done3=!0;return{done:!0,value}}}},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableList",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},makeNode=(value)=>({value,removed:!1,prev:void 0,next:void 0}),empty22=()=>{let list=Object.create(MutableListProto);return list.head=void 0,list.tail=void 0,list._length=0,list};var isEmpty6=(self)=>length(self)===0,length=(self)=>self._length;var append3=dual(2,(self,value)=>{let node=makeNode(value);if(self.head===void 0)self.head=node;if(self.tail===void 0)self.tail=node;else self.tail.next=node,node.prev=self.tail,self.tail=node;return self._length+=1,self}),shift=(self)=>{let head3=self.head;if(head3!==void 0)return remove7(self,head3),head3.value;return};var remove7=(self,node)=>{if(node.removed)return;if(node.removed=!0,node.prev!==void 0&&node.next!==void 0)node.prev.next=node.next,node.next.prev=node.prev;else if(node.prev!==void 0)self.tail=node.prev,node.prev.next=void 0;else if(node.next!==void 0)self.head=node.next,node.next.prev=void 0;else self.tail=void 0,self.head=void 0;if(self._length>0)self._length-=1};var TypeId11=Symbol.for("effect/MutableQueue"),EmptyMutableQueue=Symbol.for("effect/mutable/MutableQueue/Empty"),MutableQueueProto={[TypeId11]:TypeId11,[Symbol.iterator](){return Array.from(this.queue)[Symbol.iterator]()},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableQueue",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},make20=(capacity)=>{let queue=Object.create(MutableQueueProto);return queue.queue=empty22(),queue.capacity=capacity,queue},bounded=(capacity)=>make20(capacity),unbounded=()=>make20(void 0),length2=(self)=>length(self.queue),isEmpty7=(self)=>isEmpty6(self.queue);var capacity=(self)=>self.capacity===void 0?1/0:self.capacity,offer=dual(2,(self,value)=>{let queueLength=length(self.queue);if(self.capacity!==void 0&&queueLength===self.capacity)return!1;return append3(value)(self.queue),!0}),offerAll=dual(2,(self,values3)=>{let iterator=values3[Symbol.iterator](),next,remainder=empty5(),offering=!0;while(offering&&(next=iterator.next())&&!next.done)offering=offer(next.value)(self);while(next!=null&&!next.done)remainder=prepend2(next.value)(remainder),next=iterator.next();return reverse2(remainder)}),poll2=dual(2,(self,def)=>{if(isEmpty6(self.queue))return def;return shift(self.queue)}),pollUpTo=dual(2,(self,n)=>{let result=empty5(),count=0;while(count<n){let element=poll2(EmptyMutableQueue)(self);if(element===EmptyMutableQueue)break;result=prepend2(element)(result),count+=1}return reverse2(result)});var ClockSymbolKey="effect/Clock",ClockTypeId=Symbol.for(ClockSymbolKey),clockTag=GenericTag("effect/Clock"),MAX_TIMER_MILLIS=2147483647,globalClockScheduler={unsafeSchedule(task,duration){let millis2=toMillis(duration);if(millis2>MAX_TIMER_MILLIS)return constFalse;let completed=!1,handle=setTimeout(()=>{completed=!0,task()},millis2);return()=>{return clearTimeout(handle),!completed}}},performanceNowNanos=function(){let bigint1e62=BigInt(1e6);if(typeof performance==="undefined")return()=>BigInt(Date.now())*bigint1e62;let origin;return()=>{if(origin===void 0)origin=BigInt(Date.now())*bigint1e62-BigInt(Math.round(performance.now()*1e6));return origin+BigInt(Math.round(performance.now()*1e6))}}(),processOrPerformanceNow=function(){let processHrtime=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!processHrtime)return performanceNowNanos;let origin=performanceNowNanos()-processHrtime.bigint();return()=>origin+processHrtime.bigint()}();class ClockImpl{[ClockTypeId]=ClockTypeId;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return processOrPerformanceNow()}currentTimeMillis=sync(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=sync(()=>this.unsafeCurrentTimeNanos());scheduler(){return succeed(globalClockScheduler)}sleep(duration){return async_((resume)=>{let canceler=globalClockScheduler.unsafeSchedule(()=>resume(void_),duration);return asVoid(sync(canceler))})}}var make21=()=>new ClockImpl;var OP_AND="And",OP_OR="Or",OP_INVALID_DATA="InvalidData",OP_MISSING_DATA="MissingData",OP_SOURCE_UNAVAILABLE="SourceUnavailable",OP_UNSUPPORTED="Unsupported";var ConfigErrorSymbolKey="effect/ConfigError",ConfigErrorTypeId=Symbol.for(ConfigErrorSymbolKey),proto2={_tag:"ConfigError",[ConfigErrorTypeId]:ConfigErrorTypeId},And=(self,that)=>{let error=Object.create(proto2);return error._op=OP_AND,error.left=self,error.right=that,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`${this.left} and ${this.right}`}}),error},Or=(self,that)=>{let error=Object.create(proto2);return error._op=OP_OR,error.left=self,error.right=that,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`${this.left} or ${this.right}`}}),error},InvalidData=(path,message,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_INVALID_DATA,error.path=path,error.message=message,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Invalid data at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error},MissingData=(path,message,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_MISSING_DATA,error.path=path,error.message=message,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Missing data at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error},SourceUnavailable=(path,message,cause,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_SOURCE_UNAVAILABLE,error.path=path,error.message=message,error.cause=cause,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Source unavailable at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error},Unsupported=(path,message,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_UNSUPPORTED,error.path=path,error.message=message,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error};var prefixed=dual(2,(self,prefix)=>{switch(self._op){case OP_AND:return And(prefixed(self.left,prefix),prefixed(self.right,prefix));case OP_OR:return Or(prefixed(self.left,prefix),prefixed(self.right,prefix));case OP_INVALID_DATA:return InvalidData([...prefix,...self.path],self.message);case OP_MISSING_DATA:return MissingData([...prefix,...self.path],self.message);case OP_SOURCE_UNAVAILABLE:return SourceUnavailable([...prefix,...self.path],self.message,self.cause);case OP_UNSUPPORTED:return Unsupported([...prefix,...self.path],self.message)}});var empty23={_tag:"Empty"};var patch8=dual(2,(path,patch9)=>{let input=of3(patch9),output=path;while(isCons(input)){let patch10=input.head;switch(patch10._tag){case"Empty":{input=input.tail;break}case"AndThen":{input=cons(patch10.first,cons(patch10.second,input.tail));break}case"MapName":{output=map3(output,patch10.f),input=input.tail;break}case"Nested":{output=prepend(output,patch10.name),input=input.tail;break}case"Unnested":{if(pipe(head(output),contains(patch10.name)))output=tailNonEmpty(output),input=input.tail;else return left2(MissingData(output,`Expected ${patch10.name} to be in path in ConfigProvider#unnested`));break}}}return right2(output)});var OP_CONSTANT="Constant",OP_FAIL2="Fail",OP_FALLBACK="Fallback",OP_DESCRIBED="Described",OP_LAZY="Lazy",OP_MAP_OR_FAIL="MapOrFail",OP_NESTED="Nested",OP_PRIMITIVE="Primitive",OP_SEQUENCE="Sequence",OP_HASHMAP="HashMap",OP_ZIP_WITH="ZipWith";var concat=(l,r)=>[...l,...r],ConfigProviderSymbolKey="effect/ConfigProvider",ConfigProviderTypeId=Symbol.for(ConfigProviderSymbolKey),configProviderTag=GenericTag("effect/ConfigProvider"),FlatConfigProviderSymbolKey="effect/ConfigProviderFlat",FlatConfigProviderTypeId=Symbol.for(FlatConfigProviderSymbolKey),make23=(options)=>({[ConfigProviderTypeId]:ConfigProviderTypeId,pipe(){return pipeArguments(this,arguments)},...options}),makeFlat=(options)=>({[FlatConfigProviderTypeId]:FlatConfigProviderTypeId,patch:options.patch,load:(path,config,split=!0)=>options.load(path,config,split),enumerateChildren:options.enumerateChildren}),fromFlat=(flat)=>make23({load:(config)=>flatMap8(fromFlatLoop(flat,empty2(),config,!1),(chunk)=>match2(head(chunk),{onNone:()=>fail2(MissingData(empty2(),`Expected a single value having structure: ${config}`)),onSome:succeed})),flattened:flat}),fromEnv=(options)=>{let{pathDelim,seqDelim}=Object.assign({},{pathDelim:"_",seqDelim:","},options),makePathString=(path)=>pipe(path,join(pathDelim)),unmakePathString=(pathString)=>pathString.split(pathDelim),getEnv=()=>typeof process!=="undefined"&&("env"in process)&&typeof process.env==="object"?process.env:{};return fromFlat(makeFlat({load:(path,primitive,split=!0)=>{let pathString=makePathString(path),current=getEnv(),valueOpt=pathString in current?some2(current[pathString]):none2();return pipe(valueOpt,mapError(()=>MissingData(path,`Expected ${pathString} to exist in the process context`)),flatMap8((value)=>parsePrimitive(value,path,primitive,seqDelim,split)))},enumerateChildren:(path)=>sync(()=>{let current=getEnv(),filteredKeyPaths=Object.keys(current).map((value)=>unmakePathString(value.toUpperCase())).filter((keyPath)=>{for(let i=0;i<path.length;i++){let pathComponent=pipe(path,unsafeGet(i)),currentElement=keyPath[i];if(currentElement===void 0||pathComponent!==currentElement)return!1}return!0}).flatMap((keyPath)=>keyPath.slice(path.length,path.length+1));return fromIterable5(filteredKeyPaths)}),patch:empty23}))};var extend=(leftDef,rightDef,left3,right3)=>{let leftPad=unfold(left3.length,(index)=>index>=right3.length?none2():some2([leftDef(index),index+1])),rightPad=unfold(right3.length,(index)=>index>=left3.length?none2():some2([rightDef(index),index+1])),leftExtension=concat(left3,leftPad),rightExtension=concat(right3,rightPad);return[leftExtension,rightExtension]},appendConfigPath=(path,config)=>{let op=config;if(op._tag==="Nested"){let out=path.slice();while(op._tag==="Nested")out.push(op.name),op=op.config;return out}return path},fromFlatLoop=(flat,prefix,config,split)=>{let op=config;switch(op._tag){case OP_CONSTANT:return succeed(of(op.value));case OP_DESCRIBED:return suspend(()=>fromFlatLoop(flat,prefix,op.config,split));case OP_FAIL2:return fail2(MissingData(prefix,op.message));case OP_FALLBACK:return pipe(suspend(()=>fromFlatLoop(flat,prefix,op.first,split)),catchAll((error1)=>{if(op.condition(error1))return pipe(fromFlatLoop(flat,prefix,op.second,split),catchAll((error2)=>fail2(Or(error1,error2))));return fail2(error1)}));case OP_LAZY:return suspend(()=>fromFlatLoop(flat,prefix,op.config(),split));case OP_MAP_OR_FAIL:return suspend(()=>pipe(fromFlatLoop(flat,prefix,op.original,split),flatMap8(forEachSequential((a)=>pipe(op.mapOrFail(a),mapError(prefixed(appendConfigPath(prefix,op.original))))))));case OP_NESTED:return suspend(()=>fromFlatLoop(flat,concat(prefix,of(op.name)),op.config,split));case OP_PRIMITIVE:return pipe(patch8(prefix,flat.patch),flatMap8((prefix2)=>pipe(flat.load(prefix2,op,split),flatMap8((values3)=>{if(values3.length===0){let name=pipe(last(prefix2),getOrElse(()=>"<n/a>"));return fail2(MissingData([],`Expected ${op.description} with name ${name}`))}return succeed(values3)}))));case OP_SEQUENCE:return pipe(patch8(prefix,flat.patch),flatMap8((patchedPrefix)=>pipe(flat.enumerateChildren(patchedPrefix),flatMap8(indicesFrom),flatMap8((indices)=>{if(indices.length===0)return suspend(()=>map10(fromFlatLoop(flat,prefix,op.config,!0),of));return pipe(forEachSequential(indices,(index)=>fromFlatLoop(flat,append(prefix,`[${index}]`),op.config,!0)),map10((chunkChunk)=>{let flattened=flatten(chunkChunk);if(flattened.length===0)return of(empty2());return of(flattened)}))}))));case OP_HASHMAP:return suspend(()=>pipe(patch8(prefix,flat.patch),flatMap8((prefix2)=>pipe(flat.enumerateChildren(prefix2),flatMap8((keys3)=>{return pipe(keys3,forEachSequential((key)=>fromFlatLoop(flat,concat(prefix2,of(key)),op.valueConfig,split)),map10((matrix)=>{if(matrix.length===0)return of(empty9());return pipe(transpose(matrix),map3((values3)=>fromIterable6(zip(fromIterable(keys3),values3))))}))})))));case OP_ZIP_WITH:return suspend(()=>pipe(fromFlatLoop(flat,prefix,op.left,split),either2,flatMap8((left3)=>pipe(fromFlatLoop(flat,prefix,op.right,split),either2,flatMap8((right3)=>{if(isLeft2(left3)&&isLeft2(right3))return fail2(And(left3.left,right3.left));if(isLeft2(left3)&&isRight2(right3))return fail2(left3.left);if(isRight2(left3)&&isLeft2(right3))return fail2(right3.left);if(isRight2(left3)&&isRight2(right3)){let path=pipe(prefix,join(".")),fail5=fromFlatLoopFail(prefix,path),[lefts,rights]=extend(fail5,fail5,pipe(left3.right,map3(right2)),pipe(right3.right,map3(right2)));return pipe(lefts,zip(rights),forEachSequential(([left4,right4])=>pipe(zip2(left4,right4),map10(([left5,right5])=>op.zip(left5,right5)))))}throw new Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},fromFlatLoopFail=(prefix,path)=>(index)=>left2(MissingData(prefix,`The element at index ${index} in a sequence at path "${path}" was missing`));var splitPathString=(text,delim)=>{return text.split(new RegExp(`\\s*${escape(delim)}\\s*`))},parsePrimitive=(text,path,primitive,delimiter,split)=>{if(!split)return pipe(primitive.parse(text),mapBoth({onFailure:prefixed(path),onSuccess:of}));return pipe(splitPathString(text,delimiter),forEachSequential((char)=>primitive.parse(char.trim())),mapError(prefixed(path)))},transpose=(array4)=>{return Object.keys(array4[0]).map((column)=>array4.map((row)=>row[column]))},indicesFrom=(quotedIndices)=>pipe(forEachSequential(quotedIndices,parseQuotedIndex),mapBoth({onFailure:()=>empty2(),onSuccess:sort(Order)}),either2,map10(merge));var QUOTED_INDEX_REGEX=/^(\[(\d+)\])$/,parseQuotedIndex=(str)=>{let match7=str.match(QUOTED_INDEX_REGEX);if(match7!==null){let matchedIndex=match7[2];return pipe(matchedIndex!==void 0&&matchedIndex.length>0?some2(matchedIndex):none2(),flatMap(parseInteger))}return none2()};var parseInteger=(str)=>{let parsedIndex=Number.parseInt(str);return Number.isNaN(parsedIndex)?none2():some2(parsedIndex)};var TypeId12=Symbol.for("effect/Console"),consoleTag=GenericTag("effect/Console"),defaultConsole={[TypeId12]:TypeId12,assert(condition,...args){return sync(()=>{console.assert(condition,...args)})},clear:sync(()=>{console.clear()}),count(label){return sync(()=>{console.count(label)})},countReset(label){return sync(()=>{console.countReset(label)})},debug(...args){return sync(()=>{console.debug(...args)})},dir(item,options){return sync(()=>{console.dir(item,options)})},dirxml(...args){return sync(()=>{console.dirxml(...args)})},error(...args){return sync(()=>{console.error(...args)})},group(options){return options?.collapsed?sync(()=>console.groupCollapsed(options?.label)):sync(()=>console.group(options?.label))},groupEnd:sync(()=>{console.groupEnd()}),info(...args){return sync(()=>{console.info(...args)})},log(...args){return sync(()=>{console.log(...args)})},table(tabularData,properties){return sync(()=>{console.table(tabularData,properties)})},time(label){return sync(()=>console.time(label))},timeEnd(label){return sync(()=>console.timeEnd(label))},timeLog(label,...args){return sync(()=>{console.timeLog(label,...args)})},trace(...args){return sync(()=>{console.trace(...args)})},warn(...args){return sync(()=>{console.warn(...args)})},unsafe:console};var RandomSymbolKey="effect/Random",RandomTypeId=Symbol.for(RandomSymbolKey),randomTag=GenericTag("effect/Random");class RandomImpl{seed;[RandomTypeId]=RandomTypeId;PRNG;constructor(seed){this.seed=seed,this.PRNG=new PCGRandom(seed)}get next(){return sync(()=>this.PRNG.number())}get nextBoolean(){return map10(this.next,(n)=>n>0.5)}get nextInt(){return sync(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(min3,max3){return map10(this.next,(n)=>(max3-min3)*n+min3)}nextIntBetween(min3,max3){return sync(()=>this.PRNG.integer(max3-min3)+min3)}shuffle(elements){return shuffleWith(elements,(n)=>this.nextIntBetween(0,n))}}var shuffleWith=(elements,nextIntBounded)=>{return suspend(()=>pipe(sync(()=>Array.from(elements)),flatMap8((buffer)=>{let numbers=[];for(let i=buffer.length;i>=2;i=i-1)numbers.push(i);return pipe(numbers,forEachSequentialDiscard((n)=>pipe(nextIntBounded(n),map10((k)=>swap(buffer,n-1,k)))),as(fromIterable2(buffer)))})))},swap=(buffer,index1,index2)=>{let tmp=buffer[index1];return buffer[index1]=buffer[index2],buffer[index2]=tmp,buffer},make24=(seed)=>new RandomImpl(hash(seed));var TracerTypeId=Symbol.for("effect/Tracer"),make25=(options)=>({[TracerTypeId]:TracerTypeId,...options}),tracerTag=GenericTag("effect/Tracer"),spanTag=GenericTag("effect/ParentSpan"),randomHexString=function(){return function(length3){let result="";for(let i=0;i<length3;i++)result+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return result}}();class NativeSpan{name;parent;context;startTime;kind;_tag="Span";spanId;traceId="native";sampled=!0;status;attributes;events=[];links;constructor(name,parent,context2,links,startTime,kind){this.name=name,this.parent=parent,this.context=context2,this.startTime=startTime,this.kind=kind,this.status={_tag:"Started",startTime},this.attributes=new Map,this.traceId=parent._tag==="Some"?parent.value.traceId:randomHexString(32),this.spanId=randomHexString(16),this.links=Array.from(links)}end(endTime,exit2){this.status={_tag:"Ended",endTime,exit:exit2,startTime:this.status.startTime}}attribute(key,value){this.attributes.set(key,value)}event(name,startTime,attributes){this.events.push([name,startTime,attributes??{}])}addLinks(links){this.links.push(...links)}}var nativeTracer=make25({span:(name,parent,context2,links,startTime,kind)=>new NativeSpan(name,parent,context2,links,startTime,kind),context:(f)=>f()});var addSpanStackTrace=(options)=>{if(options?.captureStackTrace===!1)return options;else if(options?.captureStackTrace!==void 0&&typeof options.captureStackTrace!=="boolean")return options;let limit=Error.stackTraceLimit;Error.stackTraceLimit=3;let traceError=new Error;Error.stackTraceLimit=limit;let cache=!1;return{...options,captureStackTrace:()=>{if(cache!==!1)return cache;if(traceError.stack!==void 0){let stack=traceError.stack.split(`
|
|
21
|
+
`);if(stack[3]!==void 0)return cache=stack[3].trim(),cache}}}},DisablePropagation=Reference2()("effect/Tracer/DisablePropagation",{defaultValue:constFalse});var liveServices=pipe(empty4(),add2(clockTag,make21()),add2(consoleTag,defaultConsole),add2(randomTag,make24(Math.random())),add2(configProviderTag,fromEnv()),add2(tracerTag,nativeTracer)),currentServices=globalValue(Symbol.for("effect/DefaultServices/currentServices"),()=>fiberRefUnsafeMakeContext(liveServices)),sleep=(duration)=>{let decodedDuration=decode(duration);return clockWith((clock)=>clock.sleep(decodedDuration))},defaultServicesWith=(f)=>withFiberRuntime((fiber)=>f(fiber.currentDefaultServices)),clockWith=(f)=>defaultServicesWith((services)=>f(services.unsafeMap.get(clockTag.key))),currentTimeMillis=clockWith((clock)=>clock.currentTimeMillis),currentTimeNanos=clockWith((clock)=>clock.currentTimeNanos),withClock=dual(2,(effect,c)=>fiberRefLocallyWith(currentServices,add2(clockTag,c))(effect)),withConfigProvider=dual(2,(self,provider)=>fiberRefLocallyWith(currentServices,add2(configProviderTag,provider))(self)),configProviderWith=(f)=>defaultServicesWith((services)=>f(services.unsafeMap.get(configProviderTag.key))),config=(config2)=>configProviderWith((_)=>_.load(config2));var randomWith=(f)=>defaultServicesWith((services)=>f(services.unsafeMap.get(randomTag.key))),withRandom=dual(2,(effect,value)=>fiberRefLocallyWith(currentServices,add2(randomTag,value))(effect));var tracerWith=(f)=>defaultServicesWith((services)=>f(services.unsafeMap.get(tracerTag.key))),withTracer=dual(2,(effect,value)=>fiberRefLocallyWith(currentServices,add2(tracerTag,value))(effect));var sleep2=sleep,currentTimeMillis2=currentTimeMillis,currentTimeNanos2=currentTimeNanos,clockWith2=clockWith,Clock=clockTag;function unsafeMake4(fiberRefLocals){return new FiberRefsImpl(fiberRefLocals)}function empty24(){return unsafeMake4(new Map)}var FiberRefsSym=Symbol.for("effect/FiberRefs");class FiberRefsImpl{locals;[FiberRefsSym]=FiberRefsSym;constructor(locals){this.locals=locals}pipe(){return pipeArguments(this,arguments)}}var findAncestor=(_ref,_parentStack,_childStack,_childModified=!1)=>{let ref=_ref,parentStack=_parentStack,childStack=_childStack,childModified=_childModified,ret=void 0;while(ret===void 0)if(isNonEmptyReadonlyArray(parentStack)&&isNonEmptyReadonlyArray(childStack)){let parentFiberId=headNonEmpty(parentStack)[0],parentAncestors=tailNonEmpty(parentStack),childFiberId=headNonEmpty(childStack)[0],childRefValue=headNonEmpty(childStack)[1],childAncestors=tailNonEmpty(childStack);if(parentFiberId.startTimeMillis<childFiberId.startTimeMillis)childStack=childAncestors,childModified=!0;else if(parentFiberId.startTimeMillis>childFiberId.startTimeMillis)parentStack=parentAncestors;else if(parentFiberId.id<childFiberId.id)childStack=childAncestors,childModified=!0;else if(parentFiberId.id>childFiberId.id)parentStack=parentAncestors;else ret=[childRefValue,childModified]}else ret=[ref.initial,!0];return ret},joinAs=dual(3,(self,fiberId2,that)=>{let parentFiberRefs=new Map(self.locals);return that.locals.forEach((childStack,fiberRef)=>{let childValue=childStack[0][1];if(!childStack[0][0][symbol2](fiberId2)){if(!parentFiberRefs.has(fiberRef)){if(equals(childValue,fiberRef.initial))return;parentFiberRefs.set(fiberRef,[[fiberId2,fiberRef.join(fiberRef.initial,childValue)]]);return}let parentStack=parentFiberRefs.get(fiberRef),[ancestor,wasModified]=findAncestor(fiberRef,parentStack,childStack);if(wasModified){let patch9=fiberRef.diff(ancestor,childValue),oldValue=parentStack[0][1],newValue=fiberRef.join(oldValue,fiberRef.patch(patch9)(oldValue));if(!equals(oldValue,newValue)){let newStack,parentFiberId=parentStack[0][0];if(parentFiberId[symbol2](fiberId2))newStack=[[parentFiberId,newValue],...parentStack.slice(1)];else newStack=[[fiberId2,newValue],...parentStack];parentFiberRefs.set(fiberRef,newStack)}}}}),new FiberRefsImpl(parentFiberRefs)}),forkAs=dual(2,(self,childId)=>{let map12=new Map;return unsafeForkAs(self,map12,childId),new FiberRefsImpl(map12)}),unsafeForkAs=(self,map12,fiberId2)=>{self.locals.forEach((stack,fiberRef)=>{let oldValue=stack[0][1],newValue=fiberRef.patch(fiberRef.fork)(oldValue);if(equals(oldValue,newValue))map12.set(fiberRef,stack);else map12.set(fiberRef,[[fiberId2,newValue],...stack])})},fiberRefs=(self)=>fromIterable5(self.locals.keys()),setAll=(self)=>forEachSequentialDiscard(fiberRefs(self),(fiberRef)=>fiberRefSet(fiberRef,getOrDefault(self,fiberRef))),delete_=dual(2,(self,fiberRef)=>{let locals=new Map(self.locals);return locals.delete(fiberRef),new FiberRefsImpl(locals)}),get9=dual(2,(self,fiberRef)=>{if(!self.locals.has(fiberRef))return none2();return some2(headNonEmpty(self.locals.get(fiberRef))[1])}),getOrDefault=dual(2,(self,fiberRef)=>pipe(get9(self,fiberRef),getOrElse(()=>fiberRef.initial))),updateAs=dual(2,(self,{fiberId:fiberId2,fiberRef,value})=>{if(self.locals.size===0)return new FiberRefsImpl(new Map([[fiberRef,[[fiberId2,value]]]]));let locals=new Map(self.locals);return unsafeUpdateAs(locals,fiberId2,fiberRef,value),new FiberRefsImpl(locals)}),unsafeUpdateAs=(locals,fiberId2,fiberRef,value)=>{let oldStack=locals.get(fiberRef)??[],newStack;if(isNonEmptyReadonlyArray(oldStack)){let[currentId,currentValue]=headNonEmpty(oldStack);if(currentId[symbol2](fiberId2))if(equals(currentValue,value))return;else newStack=[[fiberId2,value],...oldStack.slice(1)];else newStack=[[fiberId2,value],...oldStack]}else newStack=[[fiberId2,value]];locals.set(fiberRef,newStack)},updateManyAs=dual(2,(self,{entries:entries2,forkAs:forkAs2})=>{if(self.locals.size===0)return new FiberRefsImpl(new Map(entries2));let locals=new Map(self.locals);if(forkAs2!==void 0)unsafeForkAs(self,locals,forkAs2);return entries2.forEach(([fiberRef,values3])=>{if(values3.length===1)unsafeUpdateAs(locals,values3[0][0],fiberRef,values3[0][1]);else values3.forEach(([fiberId2,value])=>{unsafeUpdateAs(locals,fiberId2,fiberRef,value)})}),new FiberRefsImpl(locals)});var get10=get9,getOrDefault2=getOrDefault,joinAs2=joinAs,setAll2=setAll;var updateManyAs2=updateManyAs;var empty25=empty24;var All=logLevelAll,Fatal=logLevelFatal,Error2=logLevelError,Warning=logLevelWarning,Info=logLevelInfo,Debug=logLevelDebug,Trace=logLevelTrace,None3=logLevelNone;var Order3=pipe(Order,mapInput2((level)=>level.ordinal));var greaterThan3=greaterThan(Order3);var fromLiteral=(literal)=>{switch(literal){case"All":return All;case"Debug":return Debug;case"Error":return Error2;case"Fatal":return Fatal;case"Info":return Info;case"Trace":return Trace;case"None":return None3;case"Warning":return Warning}};var make26=(label,startTime)=>({label,startTime}),formatLabel=(key)=>key.replace(/[\s="]/g,"_"),render=(now)=>(self)=>{return`${formatLabel(self.label)}=${now-self.startTime}ms`};var make27=make26;var exports_Ref={};__export(exports_Ref,{updateSomeAndGet:()=>updateSomeAndGet2,updateSome:()=>updateSome2,updateAndGet:()=>updateAndGet2,update:()=>update3,unsafeMake:()=>unsafeMake6,setAndGet:()=>setAndGet2,set:()=>set6,modifySome:()=>modifySome2,modify:()=>modify3,make:()=>make29,getAndUpdateSome:()=>getAndUpdateSome2,getAndUpdate:()=>getAndUpdate2,getAndSet:()=>getAndSet2,get:()=>get12,RefTypeId:()=>RefTypeId2});var EffectPrototype2=EffectPrototype,CommitPrototype2=CommitPrototype;var Base2=Base;class Class extends Base2{}var TypeId13=Symbol.for("effect/Readable");var Proto={[TypeId13]:TypeId13,pipe(){return pipeArguments(this,arguments)}};var RefTypeId=Symbol.for("effect/Ref"),refVariance={_A:(_)=>_};class RefImpl extends Class{ref;commit(){return this.get}[RefTypeId]=refVariance;[TypeId13]=TypeId13;constructor(ref){super();this.ref=ref,this.get=sync(()=>get6(this.ref))}get;modify(f){return sync(()=>{let current=get6(this.ref),[b,a]=f(current);if(current!==a)set2(a)(this.ref);return b})}}var unsafeMake5=(value)=>new RefImpl(make12(value)),make28=(value)=>sync(()=>unsafeMake5(value)),get11=(self)=>self.get,set5=dual(2,(self,value)=>self.modify(()=>[void 0,value])),getAndSet=dual(2,(self,value)=>self.modify((a)=>[a,value])),getAndUpdate=dual(2,(self,f)=>self.modify((a)=>[a,f(a)])),getAndUpdateSome=dual(2,(self,pf)=>self.modify((value)=>{let option=pf(value);switch(option._tag){case"None":return[value,value];case"Some":return[value,option.value]}})),setAndGet=dual(2,(self,value)=>self.modify(()=>[value,value])),modify2=dual(2,(self,f)=>self.modify(f)),modifySome=dual(3,(self,fallback,pf)=>self.modify((value)=>{let option=pf(value);switch(option._tag){case"None":return[fallback,value];case"Some":return option.value}})),update2=dual(2,(self,f)=>self.modify((a)=>[void 0,f(a)])),updateAndGet=dual(2,(self,f)=>self.modify((a)=>{let result=f(a);return[result,result]})),updateSome=dual(2,(self,f)=>self.modify((a)=>[void 0,match2(f(a),{onNone:()=>a,onSome:(b)=>b})])),updateSomeAndGet=dual(2,(self,pf)=>self.modify((value)=>{let option=pf(value);switch(option._tag){case"None":return[value,value];case"Some":return[option.value,option.value]}}));var RefTypeId2=RefTypeId,make29=make28,get12=get11,getAndSet2=getAndSet,getAndUpdate2=getAndUpdate,getAndUpdateSome2=getAndUpdateSome,modify3=modify2,modifySome2=modifySome,set6=set5,setAndGet2=setAndGet,update3=update2,updateAndGet2=updateAndGet,updateSome2=updateSome,updateSomeAndGet2=updateSomeAndGet,unsafeMake6=unsafeMake5;var tracerWith2=tracerWith;var OP_EMPTY2="Empty",OP_ADD="Add",OP_REMOVE="Remove",OP_UPDATE="Update",OP_AND_THEN="AndThen",empty26={_tag:OP_EMPTY2},diff8=(oldValue,newValue)=>{let missingLocals=new Map(oldValue.locals),patch9=empty26;for(let[fiberRef,pairs]of newValue.locals.entries()){let newValue2=headNonEmpty(pairs)[1],old=missingLocals.get(fiberRef);if(old!==void 0){let oldValue2=headNonEmpty(old)[1];if(!equals(oldValue2,newValue2))patch9=combine10({_tag:OP_UPDATE,fiberRef,patch:fiberRef.diff(oldValue2,newValue2)})(patch9)}else patch9=combine10({_tag:OP_ADD,fiberRef,value:newValue2})(patch9);missingLocals.delete(fiberRef)}for(let[fiberRef]of missingLocals.entries())patch9=combine10({_tag:OP_REMOVE,fiberRef})(patch9);return patch9},combine10=dual(2,(self,that)=>({_tag:OP_AND_THEN,first:self,second:that})),patch9=dual(3,(self,fiberId2,oldValue)=>{let fiberRefs2=oldValue,patches=of(self);while(isNonEmptyReadonlyArray(patches)){let head3=headNonEmpty(patches),tail=tailNonEmpty(patches);switch(head3._tag){case OP_EMPTY2:{patches=tail;break}case OP_ADD:{fiberRefs2=updateAs(fiberRefs2,{fiberId:fiberId2,fiberRef:head3.fiberRef,value:head3.value}),patches=tail;break}case OP_REMOVE:{fiberRefs2=delete_(fiberRefs2,head3.fiberRef),patches=tail;break}case OP_UPDATE:{let value=getOrDefault(fiberRefs2,head3.fiberRef);fiberRefs2=updateAs(fiberRefs2,{fiberId:fiberId2,fiberRef:head3.fiberRef,value:head3.fiberRef.patch(head3.patch)(value)}),patches=tail;break}case OP_AND_THEN:{patches=prepend(head3.first)(prepend(head3.second)(tail));break}}}return fiberRefs2});var MetricLabelSymbolKey="effect/MetricLabel",MetricLabelTypeId=Symbol.for(MetricLabelSymbolKey);class MetricLabelImpl{key;value;[MetricLabelTypeId]=MetricLabelTypeId;_hash;constructor(key,value){this.key=key,this.value=value,this._hash=string(MetricLabelSymbolKey+this.key+this.value)}[symbol](){return this._hash}[symbol2](that){return isMetricLabel(that)&&this.key===that.key&&this.value===that.value}pipe(){return pipeArguments(this,arguments)}}var make30=(key,value)=>{return new MetricLabelImpl(key,value)},isMetricLabel=(u)=>hasProperty(u,MetricLabelTypeId);var annotateLogs=dual((args)=>isEffect(args[0]),function(){let args=arguments;return fiberRefLocallyWith(args[0],currentLogAnnotations,typeof args[1]==="string"?set3(args[1],args[2]):(annotations2)=>Object.entries(args[1]).reduce((acc,[key,value])=>set3(acc,key,value),annotations2))}),asSome=(self)=>map10(self,some2),asSomeError=(self)=>mapError(self,some2),try_=(arg)=>{let evaluate,onFailure=void 0;if(typeof arg==="function")evaluate=arg;else evaluate=arg.try,onFailure=arg.catch;return suspend(()=>{try{return succeed(internalCall(evaluate))}catch(error){return fail2(onFailure?internalCall(()=>onFailure(error)):new UnknownException(error,"An unknown error occurred in Effect.try"))}})},_catch=dual(3,(self,tag,options)=>catchAll(self,(e)=>{if(hasProperty(e,tag)&&e[tag]===options.failure)return options.onFailure(e);return fail2(e)})),catchAllDefect=dual(2,(self,f)=>catchAllCause(self,(cause)=>{let option=find(cause,(_)=>isDieType(_)?some2(_):none2());switch(option._tag){case"None":return failCause(cause);case"Some":return f(option.value.defect)}})),catchSomeCause=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(cause)=>{let option=f(cause);switch(option._tag){case"None":return failCause(cause);case"Some":return option.value}},onSuccess:succeed})),catchSomeDefect=dual(2,(self,pf)=>catchAllCause(self,(cause)=>{let option=find(cause,(_)=>isDieType(_)?some2(_):none2());switch(option._tag){case"None":return failCause(cause);case"Some":{let optionEffect=pf(option.value.defect);return optionEffect._tag==="Some"?optionEffect.value:failCause(cause)}}})),catchTag=dual(3,(self,k,f)=>catchIf(self,isTagged(k),f)),catchTags=dual(2,(self,cases)=>{let keys3;return catchIf(self,(e)=>{return keys3??=Object.keys(cases),hasProperty(e,"_tag")&&isString(e._tag)&&keys3.includes(e._tag)},(e)=>cases[e._tag](e))}),cause=(self)=>matchCause(self,{onFailure:identity,onSuccess:()=>empty20}),clockWith3=clockWith2,clock=clockWith3(succeed),delay=dual(2,(self,duration)=>zipRight(sleep2(duration),self)),descriptorWith=(f)=>withFiberRuntime((state,status)=>f({id:state.id(),status,interruptors:interruptors(state.getFiberRef(currentInterruptedCause))})),allowInterrupt=descriptorWith((descriptor)=>size3(descriptor.interruptors)>0?interrupt2:void_),descriptor=descriptorWith(succeed),diffFiberRefs=(self)=>summarized(self,fiberRefs2,diff8),diffFiberRefsAndRuntimeFlags=(self)=>summarized(self,zip2(fiberRefs2,runtimeFlags),([refs,flags],[refsNew,flagsNew])=>[diff8(refs,refsNew),diff7(flags,flagsNew)]),Do=succeed({}),bind2=bind(map10,flatMap8),bindTo2=bindTo(map10),let_2=let_(map10),dropUntil=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],next,dropping=succeed(!1),i=0;while((next=iterator.next())&&!next.done){let a=next.value,index=i++;dropping=flatMap8(dropping,(bool)=>{if(bool)return builder.push(a),succeed(!0);return predicate(a,index)})}return map10(dropping,()=>builder)})),dropWhile2=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],next,dropping=succeed(!0),i=0;while((next=iterator.next())&&!next.done){let a=next.value,index=i++;dropping=flatMap8(dropping,(d)=>map10(d?predicate(a,index):succeed(!1),(b)=>{if(!b)builder.push(a);return b}))}return map10(dropping,()=>builder)})),contextWith=(f)=>map10(context(),f),eventually=(self)=>orElse2(self,()=>flatMap8(yieldNow(),()=>eventually(self))),filterMap4=dual(2,(elements,pf)=>map10(forEachSequential(elements,identity),filterMap(pf))),filterOrDie=dual(3,(self,predicate,orDieWith2)=>filterOrElse(self,predicate,(a)=>dieSync(()=>orDieWith2(a)))),filterOrDieMessage=dual(3,(self,predicate,message)=>filterOrElse(self,predicate,()=>dieMessage(message))),filterOrElse=dual(3,(self,predicate,orElse3)=>flatMap8(self,(a)=>predicate(a)?succeed(a):orElse3(a))),liftPredicate=dual(3,(self,predicate,orFailWith)=>suspend(()=>predicate(self)?succeed(self):fail2(orFailWith(self)))),filterOrFail=dual((args)=>isEffect(args[0]),(self,predicate,orFailWith)=>filterOrElse(self,predicate,(a)=>orFailWith===void 0?fail2(new NoSuchElementException):failSync(()=>orFailWith(a)))),findFirst5=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),next=iterator.next();if(!next.done)return findLoop(iterator,0,predicate,next.value);return succeed(none2())})),findLoop=(iterator,index,f,value)=>flatMap8(f(value,index),(result)=>{if(result)return succeed(some2(value));let next=iterator.next();if(!next.done)return findLoop(iterator,index+1,f,next.value);return succeed(none2())}),firstSuccessOf=(effects)=>suspend(()=>{let list=fromIterable2(effects);if(!isNonEmpty2(list))return dieSync(()=>new IllegalArgumentException("Received an empty collection of effects"));return pipe(tailNonEmpty2(list),reduce(headNonEmpty2(list),(left3,right3)=>orElse2(left3,()=>right3)))}),flipWith=dual(2,(self,f)=>flip(f(flip(self)))),match7=dual(2,(self,options)=>matchEffect(self,{onFailure:(e)=>succeed(options.onFailure(e)),onSuccess:(a)=>succeed(options.onSuccess(a))})),every5=dual(2,(elements,predicate)=>suspend(()=>forAllLoop(elements[Symbol.iterator](),0,predicate))),forAllLoop=(iterator,index,f)=>{let next=iterator.next();return next.done?succeed(!0):flatMap8(f(next.value,index),(b)=>b?forAllLoop(iterator,index+1,f):succeed(b))},forever=(self)=>{let loop=flatMap8(flatMap8(self,()=>yieldNow()),()=>loop);return loop},fiberRefs2=withFiberRuntime((state)=>succeed(state.getFiberRefs())),head3=(self)=>flatMap8(self,(as2)=>{let next=as2[Symbol.iterator]().next();if(next.done)return fail2(new NoSuchElementException);return succeed(next.value)}),ignore=(self)=>match7(self,{onFailure:constVoid,onSuccess:constVoid}),ignoreLogged=(self)=>matchCauseEffect(self,{onFailure:(cause2)=>logDebug(cause2,"An error was silently ignored because it is not anticipated to be useful"),onSuccess:()=>void_}),inheritFiberRefs=(childFiberRefs)=>updateFiberRefs((parentFiberId,parentFiberRefs)=>joinAs2(parentFiberRefs,parentFiberId,childFiberRefs)),isFailure2=(self)=>match7(self,{onFailure:constTrue,onSuccess:constFalse}),isSuccess2=(self)=>match7(self,{onFailure:constFalse,onSuccess:constTrue}),iterate=(initial,options)=>suspend(()=>{if(options.while(initial))return flatMap8(options.body(initial),(z2)=>iterate(z2,options));return succeed(initial)}),logWithLevel=(level)=>(...message)=>{let levelOption=fromNullable(level),cause2=void 0;for(let i=0,len=message.length;i<len;i++){let msg=message[i];if(isCause(msg)){if(cause2!==void 0)cause2=sequential(cause2,msg);else cause2=msg;message=[...message.slice(0,i),...message.slice(i+1)],i--}}if(cause2===void 0)cause2=empty20;return withFiberRuntime((fiberState)=>{return fiberState.log(message,cause2,levelOption),void_})},log=logWithLevel(),logTrace=logWithLevel(Trace),logDebug=logWithLevel(Debug),logInfo=logWithLevel(Info),logWarning=logWithLevel(Warning),logError=logWithLevel(Error2),logFatal=logWithLevel(Fatal),withLogSpan=dual(2,(effect,label)=>flatMap8(currentTimeMillis2,(now)=>fiberRefLocallyWith(effect,currentLogSpan,prepend3(make27(label,now))))),logAnnotations=fiberRefGet(currentLogAnnotations),loop=(initial,options)=>options.discard?loopDiscard(initial,options.while,options.step,options.body):map10(loopInternal(initial,options.while,options.step,options.body),fromIterable),loopInternal=(initial,cont,inc,body)=>suspend(()=>cont(initial)?flatMap8(body(initial),(a)=>map10(loopInternal(inc(initial),cont,inc,body),prepend3(a))):sync(()=>empty10())),loopDiscard=(initial,cont,inc,body)=>suspend(()=>cont(initial)?flatMap8(body(initial),()=>loopDiscard(inc(initial),cont,inc,body)):void_),mapAccum3=dual(3,(elements,initial,f)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],result=succeed(initial),next,i=0;while(!(next=iterator.next()).done){let index=i++,value=next.value;result=flatMap8(result,(state)=>map10(f(state,value,index),([z,b])=>{return builder.push(b),z}))}return map10(result,(z)=>[z,builder])})),mapErrorCause=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(c)=>failCauseSync(()=>f(c)),onSuccess:succeed})),memoize=(self)=>pipe(deferredMake(),flatMap8((deferred)=>pipe(diffFiberRefsAndRuntimeFlags(self),intoDeferred(deferred),once,map10((complete)=>zipRight(complete,pipe(deferredAwait(deferred),flatMap8(([patch10,a])=>as(zip2(patchFiberRefs(patch10[0]),updateRuntimeFlags(patch10[1])),a)))))))),merge5=(self)=>matchEffect(self,{onFailure:(e)=>succeed(e),onSuccess:succeed}),negate=(self)=>map10(self,(b)=>!b),none6=(self)=>flatMap8(self,(option)=>{switch(option._tag){case"None":return void_;case"Some":return fail2(new NoSuchElementException)}}),once=(self)=>map10(make29(!0),(ref)=>asVoid(whenEffect(self,getAndSet2(ref,!1)))),option=(self)=>matchEffect(self,{onFailure:()=>succeed(none2()),onSuccess:(a)=>succeed(some2(a))}),orElseFail=dual(2,(self,evaluate)=>orElse2(self,()=>failSync(evaluate))),orElseSucceed=dual(2,(self,evaluate)=>orElse2(self,()=>sync(evaluate))),parallelErrors=(self)=>matchCauseEffect(self,{onFailure:(cause2)=>{let errors=fromIterable(failures(cause2));return errors.length===0?failCause(cause2):fail2(errors)},onSuccess:succeed}),patchFiberRefs=(patch10)=>updateFiberRefs((fiberId2,fiberRefs3)=>pipe(patch10,patch9(fiberId2,fiberRefs3))),promise=(evaluate)=>evaluate.length>=1?async_((resolve,signal)=>{try{evaluate(signal).then((a)=>resolve(exitSucceed(a)),(e)=>resolve(exitDie(e)))}catch(e){resolve(exitDie(e))}}):async_((resolve)=>{try{evaluate().then((a)=>resolve(exitSucceed(a)),(e)=>resolve(exitDie(e)))}catch(e){resolve(exitDie(e))}}),provideService=dual(3,(self,tag,service)=>contextWithEffect((env)=>provideContext(self,add2(env,tag,service)))),provideServiceEffect=dual(3,(self,tag,effect)=>contextWithEffect((env)=>flatMap8(effect,(service)=>provideContext(self,pipe(env,add2(tag,service)))))),random2=randomWith(succeed),reduce11=dual(3,(elements,zero3,f)=>fromIterable(elements).reduce((acc,el,i)=>flatMap8(acc,(a)=>f(a,el,i)),succeed(zero3))),reduceRight3=dual(3,(elements,zero3,f)=>fromIterable(elements).reduceRight((acc,el,i)=>flatMap8(acc,(a)=>f(el,a,i)),succeed(zero3))),reduceWhile=dual(3,(elements,zero3,options)=>flatMap8(sync(()=>elements[Symbol.iterator]()),(iterator)=>reduceWhileLoop(iterator,0,zero3,options.while,options.body))),reduceWhileLoop=(iterator,index,state,predicate,f)=>{let next=iterator.next();if(!next.done&&predicate(state))return flatMap8(f(state,next.value,index),(nextState)=>reduceWhileLoop(iterator,index+1,nextState,predicate,f));return succeed(state)},repeatN=dual(2,(self,n)=>suspend(()=>repeatNLoop(self,n))),repeatNLoop=(self,n)=>flatMap8(self,(a)=>n<=0?succeed(a):zipRight(yieldNow(),repeatNLoop(self,n-1))),sandbox=(self)=>matchCauseEffect(self,{onFailure:fail2,onSuccess:succeed}),setFiberRefs=(fiberRefs3)=>suspend(()=>setAll2(fiberRefs3)),sleep3=sleep2,succeedNone=succeed(none2()),succeedSome=(value)=>succeed(some2(value)),summarized=dual(3,(self,summary,f)=>flatMap8(summary,(start)=>flatMap8(self,(value)=>map10(summary,(end)=>[f(start,end),value])))),tagMetrics=dual((args)=>isEffect(args[0]),function(){return labelMetrics(arguments[0],typeof arguments[1]==="string"?[make30(arguments[1],arguments[2])]:Object.entries(arguments[1]).map(([k,v])=>make30(k,v)))}),labelMetrics=dual(2,(self,labels)=>fiberRefLocallyWith(self,currentMetricLabels,(old)=>union(old,labels))),takeUntil=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],next,effect=succeed(!1),i=0;while((next=iterator.next())&&!next.done){let a=next.value,index=i++;effect=flatMap8(effect,(bool)=>{if(bool)return succeed(!0);return builder.push(a),predicate(a,index)})}return map10(effect,()=>builder)})),takeWhile2=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],next,taking=succeed(!0),i=0;while((next=iterator.next())&&!next.done){let a=next.value,index=i++;taking=flatMap8(taking,(taking2)=>pipe(taking2?predicate(a,index):succeed(!1),map10((bool)=>{if(bool)builder.push(a);return bool})))}return map10(taking,()=>builder)})),tapBoth=dual(2,(self,{onFailure,onSuccess})=>matchCauseEffect(self,{onFailure:(cause2)=>{let either3=failureOrCause(cause2);switch(either3._tag){case"Left":return zipRight(onFailure(either3.left),failCause(cause2));case"Right":return failCause(cause2)}},onSuccess:(a)=>as(onSuccess(a),a)})),tapDefect=dual(2,(self,f)=>catchAllCause(self,(cause2)=>match2(keepDefects(cause2),{onNone:()=>failCause(cause2),onSome:(a)=>zipRight(f(a),failCause(cause2))}))),tapError=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(cause2)=>{let either3=failureOrCause(cause2);switch(either3._tag){case"Left":return zipRight(f(either3.left),failCause(cause2));case"Right":return failCause(cause2)}},onSuccess:succeed})),tapErrorTag=dual(3,(self,k,f)=>tapError(self,(e)=>{if(isTagged(e,k))return f(e);return void_})),tapErrorCause=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(cause2)=>zipRight(f(cause2),failCause(cause2)),onSuccess:succeed})),timed=(self)=>timedWith(self,currentTimeNanos2),timedWith=dual(2,(self,nanos2)=>summarized(self,nanos2,(start,end)=>nanos(end-start))),tracerWith3=tracerWith2,tracer=tracerWith3(succeed),tryPromise=(arg)=>{let evaluate,catcher=void 0;if(typeof arg==="function")evaluate=arg;else evaluate=arg.try,catcher=arg.catch;let fail5=(e)=>catcher?failSync(()=>catcher(e)):fail2(new UnknownException(e,"An unknown error occurred in Effect.tryPromise"));if(evaluate.length>=1)return async_((resolve,signal)=>{try{evaluate(signal).then((a)=>resolve(exitSucceed(a)),(e)=>resolve(fail5(e)))}catch(e){resolve(fail5(e))}});return async_((resolve)=>{try{evaluate().then((a)=>resolve(exitSucceed(a)),(e)=>resolve(fail5(e)))}catch(e){resolve(fail5(e))}})},tryMap=dual(2,(self,options)=>flatMap8(self,(a)=>try_({try:()=>options.try(a),catch:options.catch}))),tryMapPromise=dual(2,(self,options)=>flatMap8(self,(a)=>tryPromise({try:options.try.length>=1?(signal)=>options.try(a,signal):()=>options.try(a),catch:options.catch}))),unless=dual(2,(self,condition)=>suspend(()=>condition()?succeedNone:asSome(self))),unlessEffect=dual(2,(self,condition)=>flatMap8(condition,(b)=>b?succeedNone:asSome(self))),unsandbox=(self)=>mapErrorCause(self,flatten5),updateFiberRefs=(f)=>withFiberRuntime((state)=>{return state.setFiberRefs(f(state.id(),state.getFiberRefs())),void_}),updateService=dual(3,(self,tag,f)=>mapInputContext(self,(context2)=>add2(context2,tag,f(unsafeGet3(context2,tag))))),when=dual(2,(self,condition)=>suspend(()=>condition()?map10(self,some2):succeed(none2()))),whenFiberRef=dual(3,(self,fiberRef,predicate)=>flatMap8(fiberRefGet(fiberRef),(s)=>predicate(s)?map10(self,(a)=>[s,some2(a)]):succeed([s,none2()]))),whenRef=dual(3,(self,ref,predicate)=>flatMap8(get12(ref),(s)=>predicate(s)?map10(self,(a)=>[s,some2(a)]):succeed([s,none2()]))),withMetric=dual(2,(self,metric)=>metric(self)),serviceFunctionEffect=(getService,f)=>(...args)=>flatMap8(getService,(a)=>f(a)(...args)),serviceFunction=(getService,f)=>(...args)=>map10(getService,(a)=>f(a)(...args)),serviceFunctions=(getService)=>new Proxy({},{get(_target,prop,_receiver){return(...args)=>flatMap8(getService,(s)=>s[prop](...args))}}),serviceConstants=(getService)=>new Proxy({},{get(_target,prop,_receiver){return flatMap8(getService,(s)=>isEffect(s[prop])?s[prop]:succeed(s[prop]))}}),serviceMembers=(getService)=>({functions:serviceFunctions(getService),constants:serviceConstants(getService)}),serviceOption=(tag)=>map10(context(),getOption2(tag)),serviceOptional=(tag)=>flatMap8(context(),getOption2(tag)),annotateCurrentSpan=function(){let args=arguments;return ignore(flatMap8(currentSpan,(span2)=>sync(()=>{if(typeof args[0]==="string")span2.attribute(args[0],args[1]);else for(let key in args[0])span2.attribute(key,args[0][key])})))},linkSpanCurrent=function(){let args=arguments,links=Array.isArray(args[0])?args[0]:[{_tag:"SpanLink",span:args[0],attributes:args[1]??{}}];return ignore(flatMap8(currentSpan,(span2)=>sync(()=>span2.addLinks(links))))},annotateSpans=dual((args)=>isEffect(args[0]),function(){let args=arguments;return fiberRefLocallyWith(args[0],currentTracerSpanAnnotations,typeof args[1]==="string"?set3(args[1],args[2]):(annotations2)=>Object.entries(args[1]).reduce((acc,[key,value])=>set3(acc,key,value),annotations2))}),currentParentSpan=serviceOptional(spanTag),currentSpan=flatMap8(context(),(context2)=>{let span2=context2.unsafeMap.get(spanTag.key);return span2!==void 0&&span2._tag==="Span"?succeed(span2):fail2(new NoSuchElementException)}),linkSpans=dual((args)=>isEffect(args[0]),(self,span2,attributes)=>fiberRefLocallyWith(self,currentTracerSpanLinks,append2({_tag:"SpanLink",span:span2,attributes:attributes??{}}))),bigint03=BigInt(0),filterDisablePropagation=flatMap((span2)=>get3(span2.context,DisablePropagation)?span2._tag==="Span"?filterDisablePropagation(span2.parent):none2():some2(span2)),unsafeMakeSpan=(fiber,name,options)=>{let disablePropagation=!fiber.getFiberRef(currentTracerEnabled)||options.context&&get3(options.context,DisablePropagation),context2=fiber.getFiberRef(currentContext),parent=options.parent?some2(options.parent):options.root?none2():filterDisablePropagation(getOption2(context2,spanTag)),span2;if(disablePropagation)span2=noopSpan({name,parent,context:add2(options.context??empty4(),DisablePropagation,!0)});else{let services=fiber.getFiberRef(currentServices),tracer2=get3(services,tracerTag),clock2=get3(services,Clock),timingEnabled=fiber.getFiberRef(currentTracerTimingEnabled),fiberRefs3=fiber.getFiberRefs(),annotationsFromEnv=get10(fiberRefs3,currentTracerSpanAnnotations),linksFromEnv=get10(fiberRefs3,currentTracerSpanLinks),links=linksFromEnv._tag==="Some"?options.links!==void 0?[...toReadonlyArray(linksFromEnv.value),...options.links??[]]:toReadonlyArray(linksFromEnv.value):options.links??empty2();if(span2=tracer2.span(name,parent,options.context??empty4(),links,timingEnabled?clock2.unsafeCurrentTimeNanos():bigint03,options.kind??"internal"),annotationsFromEnv._tag==="Some")forEach4(annotationsFromEnv.value,(value,key)=>span2.attribute(key,value));if(options.attributes!==void 0)Object.entries(options.attributes).forEach(([k,v])=>span2.attribute(k,v))}if(typeof options.captureStackTrace==="function")spanToTrace.set(span2,options.captureStackTrace);return span2},makeSpan=(name,options)=>{return options=addSpanStackTrace(options),withFiberRuntime((fiber)=>succeed(unsafeMakeSpan(fiber,name,options)))},spanAnnotations=fiberRefGet(currentTracerSpanAnnotations),spanLinks=fiberRefGet(currentTracerSpanLinks),endSpan=(span2,exit2,clock2,timingEnabled)=>sync(()=>{if(span2.status._tag==="Ended")return;if(exitIsFailure(exit2)&&spanToTrace.has(span2))span2.attribute("code.stacktrace",spanToTrace.get(span2)());span2.end(timingEnabled?clock2.unsafeCurrentTimeNanos():bigint03,exit2)}),useSpan=(name,...args)=>{let options=addSpanStackTrace(args.length===1?void 0:args[0]),evaluate=args[args.length-1];return withFiberRuntime((fiber)=>{let span2=unsafeMakeSpan(fiber,name,options),timingEnabled=fiber.getFiberRef(currentTracerTimingEnabled),clock2=get3(fiber.getFiberRef(currentServices),clockTag);return onExit(evaluate(span2),(exit2)=>endSpan(span2,exit2,clock2,timingEnabled))})},withParentSpan=dual(2,(self,span2)=>provideService(self,spanTag,span2)),withSpan=function(){let dataFirst=typeof arguments[0]!=="string",name=dataFirst?arguments[1]:arguments[0],options=addSpanStackTrace(dataFirst?arguments[2]:arguments[1]);if(dataFirst){let self=arguments[0];return useSpan(name,options,(span2)=>withParentSpan(self,span2))}return(self)=>useSpan(name,options,(span2)=>withParentSpan(self,span2))},functionWithSpan=(options)=>function(){let captureStackTrace=options.captureStackTrace??!1;if(options.captureStackTrace!==!1){let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let error=new Error;Error.stackTraceLimit=limit;let cache=!1;captureStackTrace=()=>{if(cache!==!1)return cache;if(error.stack)return cache=error.stack.trim().split(`
|
|
22
|
+
`).slice(2).join(`
|
|
23
|
+
`).trim(),cache}}return suspend(()=>{let opts=typeof options.options==="function"?options.options.apply(null,arguments):options.options;return withSpan(suspend(()=>internalCall(()=>options.body.apply(this,arguments))),opts.name,{...opts,captureStackTrace})})},fromNullable2=(value)=>value==null?fail2(new NoSuchElementException):succeed(value),optionFromOptional=(self)=>catchAll(map10(self,some2),(error)=>isNoSuchElementException(error)?succeedNone:fail2(error));var OP_SEQUENTIAL2="Sequential",OP_PARALLEL2="Parallel",OP_PARALLEL_N="ParallelN",sequential2={_tag:OP_SEQUENTIAL2},parallel2={_tag:OP_PARALLEL2},parallelN=(parallelism)=>({_tag:OP_PARALLEL_N,parallelism}),isSequential=(self)=>self._tag===OP_SEQUENTIAL2,isParallel=(self)=>self._tag===OP_PARALLEL2;var sequential3=sequential2,parallel3=parallel2,parallelN2=parallelN;var diff9=diff8;var patch10=patch9;var FiberStatusSymbolKey="effect/FiberStatus",FiberStatusTypeId=Symbol.for(FiberStatusSymbolKey),OP_DONE="Done",OP_RUNNING="Running",OP_SUSPENDED="Suspended",DoneHash=string(`${FiberStatusSymbolKey}-${OP_DONE}`);class Done{[FiberStatusTypeId]=FiberStatusTypeId;_tag=OP_DONE;[symbol](){return DoneHash}[symbol2](that){return isFiberStatus(that)&&that._tag===OP_DONE}}class Running{runtimeFlags;[FiberStatusTypeId]=FiberStatusTypeId;_tag=OP_RUNNING;constructor(runtimeFlags2){this.runtimeFlags=runtimeFlags2}[symbol](){return pipe(hash(FiberStatusSymbolKey),combine(hash(this._tag)),combine(hash(this.runtimeFlags)),cached(this))}[symbol2](that){return isFiberStatus(that)&&that._tag===OP_RUNNING&&this.runtimeFlags===that.runtimeFlags}}class Suspended{runtimeFlags;blockingOn;[FiberStatusTypeId]=FiberStatusTypeId;_tag=OP_SUSPENDED;constructor(runtimeFlags2,blockingOn){this.runtimeFlags=runtimeFlags2,this.blockingOn=blockingOn}[symbol](){return pipe(hash(FiberStatusSymbolKey),combine(hash(this._tag)),combine(hash(this.runtimeFlags)),combine(hash(this.blockingOn)),cached(this))}[symbol2](that){return isFiberStatus(that)&&that._tag===OP_SUSPENDED&&this.runtimeFlags===that.runtimeFlags&&equals(this.blockingOn,that.blockingOn)}}var done3=new Done,running=(runtimeFlags2)=>new Running(runtimeFlags2),suspended=(runtimeFlags2,blockingOn)=>new Suspended(runtimeFlags2,blockingOn),isFiberStatus=(u)=>hasProperty(u,FiberStatusTypeId),isDone2=(self)=>self._tag===OP_DONE,isRunning=(self)=>self._tag===OP_RUNNING,isSuspended=(self)=>self._tag===OP_SUSPENDED;var done4=done3,running2=running,suspended2=suspended;var isDone3=isDone2,isRunning2=isRunning,isSuspended2=isSuspended;var TypeId14=Symbol.for("effect/Micro"),MicroExitTypeId=Symbol.for("effect/Micro/MicroExit");var MicroCauseTypeId=Symbol.for("effect/Micro/MicroCause");var microCauseVariance={_E:identity};class MicroCauseImpl extends globalThis.Error{_tag;traces;[MicroCauseTypeId];constructor(_tag,originalError,traces){let causeName=`MicroCause.${_tag}`,name,message,stack;if(originalError instanceof globalThis.Error){name=`(${causeName}) ${originalError.name}`,message=originalError.message;let messageLines=message.split(`
|
|
24
|
+
`).length;stack=originalError.stack?`(${causeName}) ${originalError.stack.split(`
|
|
25
|
+
`).slice(0,messageLines+3).join(`
|
|
26
|
+
`)}`:`${name}: ${message}`}else name=causeName,message=toStringUnknown(originalError,0),stack=`${name}: ${message}`;if(traces.length>0)stack+=`
|
|
27
|
+
${traces.join(`
|
|
28
|
+
`)}`;super(message);this._tag=_tag,this.traces=traces,this[MicroCauseTypeId]=microCauseVariance,this.name=name,this.stack=stack}pipe(){return pipeArguments(this,arguments)}toString(){return this.stack}[NodeInspectSymbol](){return this.stack}}class Die extends MicroCauseImpl{defect;constructor(defect,traces=[]){super("Die",defect,traces);this.defect=defect}}var causeDie=(defect,traces=[])=>new Die(defect,traces);class Interrupt extends MicroCauseImpl{constructor(traces=[]){super("Interrupt","interrupted",traces)}}var causeInterrupt=(traces=[])=>new Interrupt(traces);var causeIsInterrupt=(self)=>self._tag==="Interrupt";var MicroFiberTypeId=Symbol.for("effect/Micro/MicroFiber"),fiberVariance={_A:identity,_E:identity};class MicroFiberImpl{context;interruptible;[MicroFiberTypeId];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(context2,interruptible3=!0){this.context=context2,this.interruptible=interruptible3,this[MicroFiberTypeId]=fiberVariance}getRef(ref){return unsafeGetReference(this.context,ref)}addObserver(cb){if(this._exit)return cb(this._exit),constVoid;return this._observers.push(cb),()=>{let index=this._observers.indexOf(cb);if(index>=0)this._observers.splice(index,1)}}_interrupted=!1;unsafeInterrupt(){if(this._exit)return;if(this._interrupted=!0,this.interruptible)this.evaluate(exitInterrupt2)}unsafePoll(){return this._exit}evaluate(effect){if(this._exit)return;else if(this._yielded!==void 0){let yielded=this._yielded;this._yielded=void 0,yielded()}let exit2=this.runLoop(effect);if(exit2===Yield)return;let interruptChildren=fiberMiddleware.interruptChildren&&fiberMiddleware.interruptChildren(this);if(interruptChildren!==void 0)return this.evaluate(flatMap9(interruptChildren,()=>exit2));this._exit=exit2;for(let i=0;i<this._observers.length;i++)this._observers[i](exit2);this._observers.length=0}runLoop(effect){let yielding=!1,current=effect;this.currentOpCount=0;try{while(!0){if(this.currentOpCount++,!yielding&&this.getRef(CurrentScheduler).shouldYield(this)){yielding=!0;let prev=current;current=flatMap9(yieldNow2,()=>prev)}if(current=current[evaluate](this),current===Yield){let yielded=this._yielded;if(MicroExitTypeId in yielded)return this._yielded=void 0,yielded;return Yield}}}catch(error){if(!hasProperty(current,evaluate))return exitDie2(`MicroFiber.runLoop: Not a valid effect: ${String(current)}`);return exitDie2(error)}}getCont(symbol3){while(!0){let op=this._stack.pop();if(!op)return;let cont=op[ensureCont]&&op[ensureCont](this);if(cont)return{[symbol3]:cont};if(op[symbol3])return op}}_yielded=void 0;yieldWith(value){return this._yielded=value,Yield}children(){return this._children??=new Set}}var fiberMiddleware=globalValue("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0}));var identifier=Symbol.for("effect/Micro/identifier"),args=Symbol.for("effect/Micro/args"),evaluate=Symbol.for("effect/Micro/evaluate"),successCont=Symbol.for("effect/Micro/successCont"),failureCont=Symbol.for("effect/Micro/failureCont"),ensureCont=Symbol.for("effect/Micro/ensureCont"),Yield=Symbol.for("effect/Micro/Yield"),microVariance={_A:identity,_E:identity,_R:identity},MicroProto={...EffectPrototype2,_op:"Micro",[TypeId14]:microVariance,pipe(){return pipeArguments(this,arguments)},[Symbol.iterator](){return new SingleShotGen(new YieldWrap(this))},toJSON(){return{_id:"Micro",op:this[identifier],...args in this?{args:this[args]}:void 0}},toString(){return format(this)},[NodeInspectSymbol](){return format(this)}};function defaultEvaluate(_fiber){return exitDie2("Micro.evaluate: Not implemented")}var makePrimitiveProto=(options)=>({...MicroProto,[identifier]:options.op,[evaluate]:options.eval??defaultEvaluate,[successCont]:options.contA,[failureCont]:options.contE,[ensureCont]:options.ensure}),makePrimitive=(options)=>{let Proto2=makePrimitiveProto(options);return function(){let self=Object.create(Proto2);return self[args]=options.single===!1?arguments:arguments[0],self}},makeExit=(options)=>{let Proto2={...makePrimitiveProto(options),[MicroExitTypeId]:MicroExitTypeId,_tag:options.op,get[options.prop](){return this[args]},toJSON(){return{_id:"MicroExit",_tag:options.op,[options.prop]:this[args]}},[symbol2](that){return isMicroExit(that)&&that._tag===options.op&&equals(this[args],that[args])},[symbol](){return cached(this,combine(string(options.op))(hash(this[args])))}};return function(value){let self=Object.create(Proto2);return self[args]=value,self[successCont]=void 0,self[failureCont]=void 0,self[ensureCont]=void 0,self}},succeed4=makeExit({op:"Success",prop:"value",eval(fiber){let cont=fiber.getCont(successCont);return cont?cont[successCont](this[args],fiber):fiber.yieldWith(this)}}),failCause4=makeExit({op:"Failure",prop:"cause",eval(fiber){let cont=fiber.getCont(failureCont);while(causeIsInterrupt(this[args])&&cont&&fiber.interruptible)cont=fiber.getCont(failureCont);return cont?cont[failureCont](this[args],fiber):fiber.yieldWith(this)}});var yieldNowWith=makePrimitive({op:"Yield",eval(fiber){let resumed=!1;return fiber.getRef(CurrentScheduler).scheduleTask(()=>{if(resumed)return;fiber.evaluate(exitVoid2)},this[args]??0),fiber.yieldWith(()=>{resumed=!0})}}),yieldNow2=yieldNowWith(0);var void_3=succeed4(void 0);var withMicroFiber=makePrimitive({op:"WithMicroFiber",eval(fiber){return this[args](fiber)}});var flatMap9=dual(2,(self,f)=>{let onSuccess=Object.create(OnSuccessProto);return onSuccess[args]=self,onSuccess[successCont]=f,onSuccess}),OnSuccessProto=makePrimitiveProto({op:"OnSuccess",eval(fiber){return fiber._stack.push(this),this[args]}});var isMicroExit=(u)=>hasProperty(u,MicroExitTypeId),exitSucceed2=succeed4,exitFailCause2=failCause4,exitInterrupt2=exitFailCause2(causeInterrupt());var exitDie2=(defect)=>exitFailCause2(causeDie(defect));var exitVoid2=exitSucceed2(void 0);var setImmediate="setImmediate"in globalThis?globalThis.setImmediate:(f)=>setTimeout(f,0);class MicroSchedulerDefault{tasks=[];running=!1;scheduleTask(task,_priority){if(this.tasks.push(task),!this.running)this.running=!0,setImmediate(this.afterScheduled)}afterScheduled=()=>{this.running=!1,this.runTasks()};runTasks(){let tasks=this.tasks;this.tasks=[];for(let i=0,len=tasks.length;i<len;i++)tasks[i]()}shouldYield(fiber){return fiber.currentOpCount>=fiber.getRef(MaxOpsBeforeYield)}flush(){while(this.tasks.length>0)this.runTasks()}}var updateContext=dual(2,(self,f)=>withMicroFiber((fiber)=>{let prev=fiber.context;return fiber.context=f(prev),onExit2(self,()=>{return fiber.context=prev,void_3})}));var provideContext2=dual(2,(self,provided)=>updateContext(self,merge3(provided)));class MaxOpsBeforeYield extends Reference2()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){}class CurrentScheduler extends Reference2()("effect/Micro/currentScheduler",{defaultValue:()=>new MicroSchedulerDefault}){}var matchCauseEffect2=dual(2,(self,options)=>{let primitive=Object.create(OnSuccessAndFailureProto);return primitive[args]=self,primitive[successCont]=options.onSuccess,primitive[failureCont]=options.onFailure,primitive}),OnSuccessAndFailureProto=makePrimitiveProto({op:"OnSuccessAndFailure",eval(fiber){return fiber._stack.push(this),this[args]}});var onExit2=dual(2,(self,f)=>uninterruptibleMask2((restore)=>matchCauseEffect2(restore(self),{onFailure:(cause2)=>flatMap9(f(exitFailCause2(cause2)),()=>failCause4(cause2)),onSuccess:(a)=>flatMap9(f(exitSucceed2(a)),()=>succeed4(a))})));var setInterruptible=makePrimitive({op:"SetInterruptible",ensure(fiber){if(fiber.interruptible=this[args],fiber._interrupted&&fiber.interruptible)return()=>exitInterrupt2}}),interruptible3=(self)=>withMicroFiber((fiber)=>{if(fiber.interruptible)return self;if(fiber.interruptible=!0,fiber._stack.push(setInterruptible(!1)),fiber._interrupted)return exitInterrupt2;return self}),uninterruptibleMask2=(f)=>withMicroFiber((fiber)=>{if(!fiber.interruptible)return f(identity);return fiber.interruptible=!1,fiber._stack.push(setInterruptible(!0)),f(interruptible3)});var runFork=(effect,options)=>{let fiber=new MicroFiberImpl(CurrentScheduler.context(options?.scheduler??new MicroSchedulerDefault));if(fiber.evaluate(effect),options?.signal)if(options.signal.aborted)fiber.unsafeInterrupt();else{let abort=()=>fiber.unsafeInterrupt();options.signal.addEventListener("abort",abort,{once:!0}),fiber.addObserver(()=>options.signal.removeEventListener("abort",abort))}return fiber};class PriorityBuckets{buckets=[];scheduleTask(task,priority){let length3=this.buckets.length,bucket=void 0,index=0;for(;index<length3;index++)if(this.buckets[index][0]<=priority)bucket=this.buckets[index];else break;if(bucket&&bucket[0]===priority)bucket[1].push(task);else if(index===length3)this.buckets.push([priority,[task]]);else this.buckets.splice(index,0,[priority,[task]])}}class MixedScheduler{maxNextTickBeforeTimer;running=!1;tasks=new PriorityBuckets;constructor(maxNextTickBeforeTimer){this.maxNextTickBeforeTimer=maxNextTickBeforeTimer}starveInternal(depth){let tasks=this.tasks.buckets;this.tasks.buckets=[];for(let[_,toRun]of tasks)for(let i=0;i<toRun.length;i++)toRun[i]();if(this.tasks.buckets.length===0)this.running=!1;else this.starve(depth)}starve(depth=0){if(depth>=this.maxNextTickBeforeTimer)setTimeout(()=>this.starveInternal(0),0);else Promise.resolve(void 0).then(()=>this.starveInternal(depth+1))}shouldYield(fiber){return fiber.currentOpCount>fiber.getFiberRef(currentMaxOpsBeforeYield)?fiber.getFiberRef(currentSchedulingPriority):!1}scheduleTask(task,priority){if(this.tasks.scheduleTask(task,priority),!this.running)this.running=!0,this.starve()}}var defaultScheduler=globalValue(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new MixedScheduler(2048));class SyncScheduler{tasks=new PriorityBuckets;deferred=!1;scheduleTask(task,priority){if(this.deferred)defaultScheduler.scheduleTask(task,priority);else this.tasks.scheduleTask(task,priority)}shouldYield(fiber){return fiber.currentOpCount>fiber.getFiberRef(currentMaxOpsBeforeYield)?fiber.getFiberRef(currentSchedulingPriority):!1}flush(){while(this.tasks.buckets.length>0){let tasks=this.tasks.buckets;this.tasks.buckets=[];for(let[_,toRun]of tasks)for(let i=0;i<toRun.length;i++)toRun[i]()}this.deferred=!0}}var currentScheduler=globalValue(Symbol.for("effect/FiberRef/currentScheduler"),()=>fiberRefUnsafeMake(defaultScheduler)),withScheduler=dual(2,(self,scheduler)=>fiberRefLocally(self,currentScheduler,scheduler));var currentRequestMap=globalValue(Symbol.for("effect/FiberRef/currentRequestMap"),()=>fiberRefUnsafeMake(new Map));var match9=(concurrency,sequential4,unbounded2,bounded2)=>{switch(concurrency){case void 0:return sequential4();case"unbounded":return unbounded2();case"inherit":return fiberRefGetWith(currentConcurrency,(concurrency2)=>concurrency2==="unbounded"?unbounded2():concurrency2>1?bounded2(concurrency2):sequential4());default:return concurrency>1?bounded2(concurrency):sequential4()}},matchSimple=(concurrency,sequential4,concurrent)=>{switch(concurrency){case void 0:return sequential4();case"unbounded":return concurrent();case"inherit":return fiberRefGetWith(currentConcurrency,(concurrency2)=>concurrency2==="unbounded"||concurrency2>1?concurrent():sequential4());default:return concurrency>1?concurrent():sequential4()}};var OP_INTERRUPT_SIGNAL="InterruptSignal",OP_STATEFUL="Stateful",OP_RESUME="Resume",OP_YIELD_NOW="YieldNow",interruptSignal=(cause2)=>({_tag:"InterruptSignal",cause:cause2}),stateful=(onFiber)=>({_tag:"Stateful",onFiber}),resume=(effect)=>({_tag:"Resume",effect}),yieldNow3=()=>({_tag:"YieldNow"});var FiberScopeSymbolKey="effect/FiberScope",FiberScopeTypeId=Symbol.for(FiberScopeSymbolKey);class Global{[FiberScopeTypeId]=FiberScopeTypeId;fiberId=none4;roots=new Set;add(_runtimeFlags,child){this.roots.add(child),child.addObserver(()=>{this.roots.delete(child)})}}class Local{fiberId;parent;[FiberScopeTypeId]=FiberScopeTypeId;constructor(fiberId2,parent){this.fiberId=fiberId2,this.parent=parent}add(_runtimeFlags,child){this.parent.tell(stateful((parentFiber)=>{parentFiber.addChild(child),child.addObserver(()=>{parentFiber.removeChild(child)})}))}}var unsafeMake7=(fiber)=>{return new Local(fiber.id(),fiber)},globalScope=globalValue(Symbol.for("effect/FiberScope/Global"),()=>new Global);var FiberSymbolKey="effect/Fiber",FiberTypeId=Symbol.for(FiberSymbolKey),fiberVariance2={_E:(_)=>_,_A:(_)=>_},fiberProto={[FiberTypeId]:fiberVariance2,pipe(){return pipeArguments(this,arguments)}},RuntimeFiberSymbolKey="effect/Fiber",RuntimeFiberTypeId=Symbol.for(RuntimeFiberSymbolKey),Order4=pipe(tuple(Order,Order),mapInput2((fiber)=>[fiber.id().startTimeMillis,fiber.id().id])),isFiber=(u)=>hasProperty(u,FiberTypeId),isRuntimeFiber=(self)=>(RuntimeFiberTypeId in self),_await2=(self)=>self.await,children=(self)=>self.children,done5=(exit2)=>{return{...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>none4,await:succeed(exit2),children:succeed([]),inheritAll:void_,poll:succeed(some2(exit2)),interruptAsFork:()=>void_}},dump=(self)=>map10(self.status,(status)=>({id:self.id(),status})),dumpAll=(fibers)=>forEachSequential(fibers,dump),fail5=(error)=>done5(fail4(error)),failCause5=(cause2)=>done5(failCause3(cause2)),fromEffect=(effect)=>map10(exit(effect),done5),id=(self)=>self.id(),inheritAll=(self)=>self.inheritAll,interrupted=(fiberId2)=>done5(interrupt4(fiberId2)),interruptAll=(fibers)=>flatMap8(fiberId,(fiberId2)=>pipe(fibers,interruptAllAs(fiberId2))),interruptAllAs=dual(2,(fibers,fiberId2)=>pipe(forEachSequentialDiscard(fibers,interruptAsFork(fiberId2)),zipRight(pipe(fibers,forEachSequentialDiscard(_await2))))),interruptAsFork=dual(2,(self,fiberId2)=>self.interruptAsFork(fiberId2)),join2=(self)=>zipLeft(flatten6(self.await),self.inheritAll),map12=dual(2,(self,f)=>mapEffect(self,(a)=>sync(()=>f(a)))),mapEffect=dual(2,(self,f)=>{return{...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>self.id(),await:flatMap8(self.await,forEachEffect(f)),children:self.children,inheritAll:self.inheritAll,poll:flatMap8(self.poll,(result)=>{switch(result._tag){case"None":return succeed(none2());case"Some":return pipe(forEachEffect(result.value,f),map10(some2))}}),interruptAsFork:(id2)=>self.interruptAsFork(id2)}}),mapFiber=dual(2,(self,f)=>map10(self.await,match6({onFailure:(cause2)=>failCause5(cause2),onSuccess:(a)=>f(a)}))),match10=dual(2,(self,{onFiber,onRuntimeFiber})=>{if(isRuntimeFiber(self))return onRuntimeFiber(self);return onFiber(self)}),_never={...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>none4,await:never,children:succeed([]),inheritAll:never,poll:succeed(none2()),interruptAsFork:()=>never},never2=_never,orElse3=dual(2,(self,that)=>({...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>getOrElse4(self.id(),that.id()),await:zipWith3(self.await,that.await,(exit1,exit2)=>isSuccess(exit1)?exit1:exit2),children:self.children,inheritAll:zipRight(that.inheritAll,self.inheritAll),poll:zipWith3(self.poll,that.poll,(option1,option2)=>{switch(option1._tag){case"None":return none2();case"Some":return isSuccess(option1.value)?option1:option2}}),interruptAsFork:(id2)=>pipe(interruptAsFiber(self,id2),zipRight(pipe(that,interruptAsFiber(id2))),asVoid)})),orElseEither=dual(2,(self,that)=>orElse3(map12(self,left2),map12(that,right2))),poll3=(self)=>self.poll,parseMs=(milliseconds)=>{let roundTowardsZero=milliseconds>0?Math.floor:Math.ceil;return{days:roundTowardsZero(milliseconds/86400000),hours:roundTowardsZero(milliseconds/3600000)%24,minutes:roundTowardsZero(milliseconds/60000)%60,seconds:roundTowardsZero(milliseconds/1000)%60,milliseconds:roundTowardsZero(milliseconds)%1000,microseconds:roundTowardsZero(milliseconds*1000)%1000,nanoseconds:roundTowardsZero(milliseconds*1e6)%1000}},renderStatus=(status)=>{if(isDone3(status))return"Done";if(isRunning2(status))return"Running";return`Suspended(${interruptible(status.runtimeFlags)?"interruptible":"uninterruptible"})`},pretty2=(self)=>flatMap8(currentTimeMillis2,(now)=>map10(dump(self),(dump2)=>{let time=now-dump2.id.startTimeMillis,{days:days2,hours:hours2,milliseconds,minutes:minutes2,seconds:seconds2}=parseMs(time),lifeMsg=(days2===0?"":`${days2}d`)+(days2===0&&hours2===0?"":`${hours2}h`)+(days2===0&&hours2===0&&minutes2===0?"":`${minutes2}m`)+(days2===0&&hours2===0&&minutes2===0&&seconds2===0?"":`${seconds2}s`)+`${milliseconds}ms`,waitMsg=isSuspended2(dump2.status)?(()=>{let ids3=ids2(dump2.status.blockingOn);return size3(ids3)>0?"waiting on "+Array.from(ids3).map((id2)=>`${id2}`).join(", "):""})():"",statusMsg=renderStatus(dump2.status);return`[Fiber](#${dump2.id.id}) (${lifeMsg}) ${waitMsg}
|
|
29
|
+
Status: ${statusMsg}`})),unsafeRoots=()=>Array.from(globalScope.roots),roots=sync(unsafeRoots),status=(self)=>self.status,succeed5=(value)=>done5(succeed3(value)),void_4=succeed5(void 0);var currentFiberURI="effect/FiberCurrent",getCurrentFiber=()=>fromNullable(globalThis[currentFiberURI]);var LoggerSymbolKey="effect/Logger",LoggerTypeId=Symbol.for(LoggerSymbolKey),loggerVariance={_Message:(_)=>_,_Output:(_)=>_},makeLogger=(log2)=>({[LoggerTypeId]:loggerVariance,log:log2,pipe(){return pipeArguments(this,arguments)}});var none7={[LoggerTypeId]:loggerVariance,log:constVoid,pipe(){return pipeArguments(this,arguments)}};var textOnly=/^[^\s"=]*$/,format4=(quoteValue,whitespace)=>({annotations:annotations2,cause:cause2,date,fiberId:fiberId2,logLevel,message,spans})=>{let formatValue=(value)=>value.match(textOnly)?value:quoteValue(value),format5=(label,value)=>`${formatLabel(label)}=${formatValue(value)}`,append4=(label,value)=>" "+format5(label,value),out=format5("timestamp",date.toISOString());out+=append4("level",logLevel.label),out+=append4("fiber",threadName(fiberId2));let messages=ensure(message);for(let i=0;i<messages.length;i++)out+=append4("message",toStringUnknown(messages[i],whitespace));if(!isEmptyType(cause2))out+=append4("cause",pretty(cause2,{renderErrorCause:!0}));for(let span2 of spans)out+=" "+render(date.getTime())(span2);for(let[label,value]of annotations2)out+=append4(label,toStringUnknown(value,whitespace));return out},escapeDoubleQuotes=(s)=>`"${s.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,stringLogger=makeLogger(format4(escapeDoubleQuotes)),logfmtLogger=makeLogger(format4(JSON.stringify,0));var colors={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},logLevelColors={None:[],All:[],Trace:[colors.gray],Debug:[colors.blue],Info:[colors.green],Warning:[colors.yellow],Error:[colors.red],Fatal:[colors.bgBrightRed,colors.black]};var hasProcessStdout=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,processStdoutIsTTY=hasProcessStdout&&process.stdout.isTTY===!0,hasProcessStdoutOrDeno=hasProcessStdout||"Deno"in globalThis;var MetricBoundariesSymbolKey="effect/MetricBoundaries",MetricBoundariesTypeId=Symbol.for(MetricBoundariesSymbolKey);class MetricBoundariesImpl{values;[MetricBoundariesTypeId]=MetricBoundariesTypeId;constructor(values3){this.values=values3,this._hash=pipe(string(MetricBoundariesSymbolKey),combine(array2(this.values)))}_hash;[symbol](){return this._hash}[symbol2](u){return isMetricBoundaries(u)&&equals(this.values,u.values)}pipe(){return pipeArguments(this,arguments)}}var isMetricBoundaries=(u)=>hasProperty(u,MetricBoundariesTypeId),fromIterable7=(iterable)=>{let values3=pipe(iterable,appendAll(of2(Number.POSITIVE_INFINITY)),dedupe);return new MetricBoundariesImpl(values3)};var exponential=(options)=>pipe(makeBy(options.count-1,(i)=>options.start*Math.pow(options.factor,i)),unsafeFromArray,fromIterable7);var MetricKeyTypeSymbolKey="effect/MetricKeyType",MetricKeyTypeTypeId=Symbol.for(MetricKeyTypeSymbolKey),CounterKeyTypeSymbolKey="effect/MetricKeyType/Counter",CounterKeyTypeTypeId=Symbol.for(CounterKeyTypeSymbolKey),FrequencyKeyTypeSymbolKey="effect/MetricKeyType/Frequency",FrequencyKeyTypeTypeId=Symbol.for(FrequencyKeyTypeSymbolKey),GaugeKeyTypeSymbolKey="effect/MetricKeyType/Gauge",GaugeKeyTypeTypeId=Symbol.for(GaugeKeyTypeSymbolKey),HistogramKeyTypeSymbolKey="effect/MetricKeyType/Histogram",HistogramKeyTypeTypeId=Symbol.for(HistogramKeyTypeSymbolKey),SummaryKeyTypeSymbolKey="effect/MetricKeyType/Summary",SummaryKeyTypeTypeId=Symbol.for(SummaryKeyTypeSymbolKey),metricKeyTypeVariance={_In:(_)=>_,_Out:(_)=>_};class CounterKeyType{incremental;bigint;[MetricKeyTypeTypeId]=metricKeyTypeVariance;[CounterKeyTypeTypeId]=CounterKeyTypeTypeId;constructor(incremental,bigint3){this.incremental=incremental,this.bigint=bigint3,this._hash=string(CounterKeyTypeSymbolKey)}_hash;[symbol](){return this._hash}[symbol2](that){return isCounterKey(that)}pipe(){return pipeArguments(this,arguments)}}class HistogramKeyType{boundaries;[MetricKeyTypeTypeId]=metricKeyTypeVariance;[HistogramKeyTypeTypeId]=HistogramKeyTypeTypeId;constructor(boundaries){this.boundaries=boundaries,this._hash=pipe(string(HistogramKeyTypeSymbolKey),combine(hash(this.boundaries)))}_hash;[symbol](){return this._hash}[symbol2](that){return isHistogramKey(that)&&equals(this.boundaries,that.boundaries)}pipe(){return pipeArguments(this,arguments)}}var counter=(options)=>new CounterKeyType(options?.incremental??!1,options?.bigint??!1);var histogram=(boundaries)=>{return new HistogramKeyType(boundaries)};var isCounterKey=(u)=>hasProperty(u,CounterKeyTypeTypeId),isFrequencyKey=(u)=>hasProperty(u,FrequencyKeyTypeTypeId),isGaugeKey=(u)=>hasProperty(u,GaugeKeyTypeTypeId),isHistogramKey=(u)=>hasProperty(u,HistogramKeyTypeTypeId),isSummaryKey=(u)=>hasProperty(u,SummaryKeyTypeTypeId);var MetricKeySymbolKey="effect/MetricKey",MetricKeyTypeId=Symbol.for(MetricKeySymbolKey),metricKeyVariance={_Type:(_)=>_},arrayEquivilence=getEquivalence(equals);class MetricKeyImpl{name;keyType;description;tags;[MetricKeyTypeId]=metricKeyVariance;constructor(name,keyType,description,tags=[]){this.name=name,this.keyType=keyType,this.description=description,this.tags=tags,this._hash=pipe(string(this.name+this.description),combine(hash(this.keyType)),combine(array2(this.tags)))}_hash;[symbol](){return this._hash}[symbol2](u){return isMetricKey(u)&&this.name===u.name&&equals(this.keyType,u.keyType)&&equals(this.description,u.description)&&arrayEquivilence(this.tags,u.tags)}pipe(){return pipeArguments(this,arguments)}}var isMetricKey=(u)=>hasProperty(u,MetricKeyTypeId),counter2=(name,options)=>new MetricKeyImpl(name,counter(options),fromNullable(options?.description));var histogram2=(name,boundaries,description)=>new MetricKeyImpl(name,histogram(boundaries),fromNullable(description));var taggedWithLabels=dual(2,(self,extraTags)=>extraTags.length===0?self:new MetricKeyImpl(self.name,self.keyType,self.description,union(self.tags,extraTags)));var MetricStateSymbolKey="effect/MetricState",MetricStateTypeId=Symbol.for(MetricStateSymbolKey),CounterStateSymbolKey="effect/MetricState/Counter",CounterStateTypeId=Symbol.for(CounterStateSymbolKey),FrequencyStateSymbolKey="effect/MetricState/Frequency",FrequencyStateTypeId=Symbol.for(FrequencyStateSymbolKey),GaugeStateSymbolKey="effect/MetricState/Gauge",GaugeStateTypeId=Symbol.for(GaugeStateSymbolKey),HistogramStateSymbolKey="effect/MetricState/Histogram",HistogramStateTypeId=Symbol.for(HistogramStateSymbolKey),SummaryStateSymbolKey="effect/MetricState/Summary",SummaryStateTypeId=Symbol.for(SummaryStateSymbolKey),metricStateVariance={_A:(_)=>_};class CounterState{count;[MetricStateTypeId]=metricStateVariance;[CounterStateTypeId]=CounterStateTypeId;constructor(count){this.count=count}[symbol](){return pipe(hash(CounterStateSymbolKey),combine(hash(this.count)),cached(this))}[symbol2](that){return isCounterState(that)&&this.count===that.count}pipe(){return pipeArguments(this,arguments)}}var arrayEquals=getEquivalence(equals);class FrequencyState{occurrences;[MetricStateTypeId]=metricStateVariance;[FrequencyStateTypeId]=FrequencyStateTypeId;constructor(occurrences){this.occurrences=occurrences}_hash;[symbol](){return pipe(string(FrequencyStateSymbolKey),combine(array2(fromIterable(this.occurrences.entries()))),cached(this))}[symbol2](that){return isFrequencyState(that)&&arrayEquals(fromIterable(this.occurrences.entries()),fromIterable(that.occurrences.entries()))}pipe(){return pipeArguments(this,arguments)}}class GaugeState{value;[MetricStateTypeId]=metricStateVariance;[GaugeStateTypeId]=GaugeStateTypeId;constructor(value){this.value=value}[symbol](){return pipe(hash(GaugeStateSymbolKey),combine(hash(this.value)),cached(this))}[symbol2](u){return isGaugeState(u)&&this.value===u.value}pipe(){return pipeArguments(this,arguments)}}class HistogramState{buckets;count;min;max;sum;[MetricStateTypeId]=metricStateVariance;[HistogramStateTypeId]=HistogramStateTypeId;constructor(buckets,count,min3,max3,sum2){this.buckets=buckets,this.count=count,this.min=min3,this.max=max3,this.sum=sum2}[symbol](){return pipe(hash(HistogramStateSymbolKey),combine(hash(this.buckets)),combine(hash(this.count)),combine(hash(this.min)),combine(hash(this.max)),combine(hash(this.sum)),cached(this))}[symbol2](that){return isHistogramState(that)&&equals(this.buckets,that.buckets)&&this.count===that.count&&this.min===that.min&&this.max===that.max&&this.sum===that.sum}pipe(){return pipeArguments(this,arguments)}}class SummaryState{error;quantiles;count;min;max;sum;[MetricStateTypeId]=metricStateVariance;[SummaryStateTypeId]=SummaryStateTypeId;constructor(error,quantiles,count,min3,max3,sum2){this.error=error,this.quantiles=quantiles,this.count=count,this.min=min3,this.max=max3,this.sum=sum2}[symbol](){return pipe(hash(SummaryStateSymbolKey),combine(hash(this.error)),combine(hash(this.quantiles)),combine(hash(this.count)),combine(hash(this.min)),combine(hash(this.max)),combine(hash(this.sum)),cached(this))}[symbol2](that){return isSummaryState(that)&&this.error===that.error&&equals(this.quantiles,that.quantiles)&&this.count===that.count&&this.min===that.min&&this.max===that.max&&this.sum===that.sum}pipe(){return pipeArguments(this,arguments)}}var counter3=(count)=>new CounterState(count),frequency2=(occurrences)=>{return new FrequencyState(occurrences)},gauge2=(count)=>new GaugeState(count),histogram3=(options)=>new HistogramState(options.buckets,options.count,options.min,options.max,options.sum),summary2=(options)=>new SummaryState(options.error,options.quantiles,options.count,options.min,options.max,options.sum);var isCounterState=(u)=>hasProperty(u,CounterStateTypeId),isFrequencyState=(u)=>hasProperty(u,FrequencyStateTypeId),isGaugeState=(u)=>hasProperty(u,GaugeStateTypeId),isHistogramState=(u)=>hasProperty(u,HistogramStateTypeId),isSummaryState=(u)=>hasProperty(u,SummaryStateTypeId);var MetricHookSymbolKey="effect/MetricHook",MetricHookTypeId=Symbol.for(MetricHookSymbolKey),metricHookVariance={_In:(_)=>_,_Out:(_)=>_},make31=(options)=>({[MetricHookTypeId]:metricHookVariance,pipe(){return pipeArguments(this,arguments)},...options});var bigint04=BigInt(0),counter4=(key)=>{let sum2=key.keyType.bigint?bigint04:0,canUpdate=key.keyType.incremental?key.keyType.bigint?(value)=>value>=bigint04:(value)=>value>=0:(_value)=>!0,update4=(value)=>{if(canUpdate(value))sum2=sum2+value};return make31({get:()=>counter3(sum2),update:update4,modify:update4})},frequency3=(key)=>{let values3=new Map;for(let word of key.keyType.preregisteredWords)values3.set(word,0);let update4=(word)=>{let slotCount=values3.get(word)??0;values3.set(word,slotCount+1)};return make31({get:()=>frequency2(values3),update:update4,modify:update4})},gauge3=(_key,startAt)=>{let value=startAt;return make31({get:()=>gauge2(value),update:(v)=>{value=v},modify:(v)=>{value=value+v}})},histogram4=(key)=>{let bounds=key.keyType.boundaries.values,size6=bounds.length,values3=new Uint32Array(size6+1),boundaries=new Float32Array(size6),count=0,sum2=0,min3=Number.MAX_VALUE,max3=Number.MIN_VALUE;pipe(bounds,sort(Order),map3((n,i)=>{boundaries[i]=n}));let update4=(value)=>{let from=0,to=size6;while(from!==to){let mid=Math.floor(from+(to-from)/2),boundary=boundaries[mid];if(value<=boundary)to=mid;else from=mid;if(to===from+1)if(value<=boundaries[from])to=from;else from=to}if(values3[from]=values3[from]+1,count=count+1,sum2=sum2+value,value<min3)min3=value;if(value>max3)max3=value},getBuckets=()=>{let builder=allocate(size6),cumulated=0;for(let i=0;i<size6;i++){let boundary=boundaries[i],value=values3[i];cumulated=cumulated+value,builder[i]=[boundary,cumulated]}return builder};return make31({get:()=>histogram3({buckets:getBuckets(),count,min:min3,max:max3,sum:sum2}),update:update4,modify:update4})},summary3=(key)=>{let{error,maxAge,maxSize,quantiles}=key.keyType,sortedQuantiles=pipe(quantiles,sort(Order)),values3=allocate(maxSize),head4=0,count=0,sum2=0,min3=Number.MAX_VALUE,max3=Number.MIN_VALUE,snapshot=(now)=>{let builder=[],i=0;while(i!==maxSize-1){let item=values3[i];if(item!=null){let[t,v]=item,age=millis(now-t);if(greaterThanOrEqualTo2(age,zero2)&&lessThanOrEqualTo2(age,maxAge))builder.push(v)}i=i+1}return calculateQuantiles(error,sortedQuantiles,sort(builder,Order))},observe=(value,timestamp)=>{if(maxSize>0){head4=head4+1;let target=head4%maxSize;values3[target]=[timestamp,value]}if(count=count+1,sum2=sum2+value,value<min3)min3=value;if(value>max3)max3=value};return make31({get:()=>summary2({error,quantiles:snapshot(Date.now()),count,min:min3,max:max3,sum:sum2}),update:([value,timestamp])=>observe(value,timestamp),modify:([value,timestamp])=>observe(value,timestamp)})},calculateQuantiles=(error,sortedQuantiles,sortedSamples)=>{let sampleCount=sortedSamples.length;if(!isNonEmptyReadonlyArray(sortedQuantiles))return empty2();let head4=sortedQuantiles[0],tail=sortedQuantiles.slice(1),resolvedHead=resolveQuantile(error,sampleCount,none2(),0,head4,sortedSamples),resolved=of(resolvedHead);return tail.forEach((quantile)=>{resolved.push(resolveQuantile(error,sampleCount,resolvedHead.value,resolvedHead.consumed,quantile,resolvedHead.rest))}),map3(resolved,(rq)=>[rq.quantile,rq.value])},resolveQuantile=(error,sampleCount,current,consumed,quantile,rest)=>{let error_1=error,sampleCount_1=sampleCount,current_1=current,consumed_1=consumed,quantile_1=quantile,rest_1=rest,error_2=error,sampleCount_2=sampleCount,current_2=current,consumed_2=consumed,quantile_2=quantile,rest_2=rest;while(!0){if(!isNonEmptyReadonlyArray(rest_1))return{quantile:quantile_1,value:none2(),consumed:consumed_1,rest:[]};if(quantile_1===1)return{quantile:quantile_1,value:some2(lastNonEmpty(rest_1)),consumed:consumed_1+rest_1.length,rest:[]};let headValue=headNonEmpty(rest_1),sameHead=span(rest_1,(n)=>n===headValue),desired=quantile_1*sampleCount_1,allowedError=error_1/2*desired,candConsumed=consumed_1+sameHead[0].length,candError=Math.abs(candConsumed-desired);if(candConsumed<desired-allowedError){error_2=error_1,sampleCount_2=sampleCount_1,current_2=head(rest_1),consumed_2=candConsumed,quantile_2=quantile_1,rest_2=sameHead[1],error_1=error_2,sampleCount_1=sampleCount_2,current_1=current_2,consumed_1=consumed_2,quantile_1=quantile_2,rest_1=rest_2;continue}if(candConsumed>desired+allowedError){let valueToReturn=isNone2(current_1)?some2(headValue):current_1;return{quantile:quantile_1,value:valueToReturn,consumed:consumed_1,rest:rest_1}}switch(current_1._tag){case"None":{error_2=error_1,sampleCount_2=sampleCount_1,current_2=head(rest_1),consumed_2=candConsumed,quantile_2=quantile_1,rest_2=sameHead[1],error_1=error_2,sampleCount_1=sampleCount_2,current_1=current_2,consumed_1=consumed_2,quantile_1=quantile_2,rest_1=rest_2;continue}case"Some":{let prevError=Math.abs(desired-current_1.value);if(candError<prevError){error_2=error_1,sampleCount_2=sampleCount_1,current_2=head(rest_1),consumed_2=candConsumed,quantile_2=quantile_1,rest_2=sameHead[1],error_1=error_2,sampleCount_1=sampleCount_2,current_1=current_2,consumed_1=consumed_2,quantile_1=quantile_2,rest_1=rest_2;continue}return{quantile:quantile_1,value:some2(current_1.value),consumed:consumed_1,rest:rest_1}}}}throw new Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var MetricPairSymbolKey="effect/MetricPair",MetricPairTypeId=Symbol.for(MetricPairSymbolKey),metricPairVariance={_Type:(_)=>_};var unsafeMake8=(metricKey,metricState)=>{return{[MetricPairTypeId]:metricPairVariance,metricKey,metricState,pipe(){return pipeArguments(this,arguments)}}};var MetricRegistrySymbolKey="effect/MetricRegistry",MetricRegistryTypeId=Symbol.for(MetricRegistrySymbolKey);class MetricRegistryImpl{[MetricRegistryTypeId]=MetricRegistryTypeId;map=empty21();snapshot(){let result=[];for(let[key,hook]of this.map)result.push(unsafeMake8(key,hook.get()));return result}get(key){let hook=pipe(this.map,get8(key),getOrUndefined);if(hook==null){if(isCounterKey(key.keyType))return this.getCounter(key);if(isGaugeKey(key.keyType))return this.getGauge(key);if(isFrequencyKey(key.keyType))return this.getFrequency(key);if(isHistogramKey(key.keyType))return this.getHistogram(key);if(isSummaryKey(key.keyType))return this.getSummary(key);throw new Error("BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/effect/issues")}else return hook}getCounter(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let counter5=counter4(key);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,counter5));value=counter5}return value}getFrequency(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let frequency4=frequency3(key);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,frequency4));value=frequency4}return value}getGauge(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let gauge4=gauge3(key,key.keyType.bigint?BigInt(0):0);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,gauge4));value=gauge4}return value}getHistogram(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let histogram5=histogram4(key);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,histogram5));value=histogram5}return value}getSummary(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let summary4=summary3(key);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,summary4));value=summary4}return value}}var make32=()=>{return new MetricRegistryImpl};var MetricSymbolKey="effect/Metric",MetricTypeId=Symbol.for(MetricSymbolKey),metricVariance={_Type:(_)=>_,_In:(_)=>_,_Out:(_)=>_},globalMetricRegistry=globalValue(Symbol.for("effect/Metric/globalMetricRegistry"),()=>make32()),make33=function(keyType,unsafeUpdate,unsafeValue,unsafeModify){let metric=Object.assign((effect)=>tap(effect,(a)=>update4(metric,a)),{[MetricTypeId]:metricVariance,keyType,unsafeUpdate,unsafeValue,unsafeModify,register(){return this.unsafeValue([]),this},pipe(){return pipeArguments(this,arguments)}});return metric};var counter5=(name,options)=>fromMetricKey(counter2(name,options));var fromMetricKey=(key)=>{let untaggedHook,hookCache=new WeakMap,hook=(extraTags)=>{if(extraTags.length===0){if(untaggedHook!==void 0)return untaggedHook;return untaggedHook=globalMetricRegistry.get(key),untaggedHook}let hook2=hookCache.get(extraTags);if(hook2!==void 0)return hook2;return hook2=globalMetricRegistry.get(taggedWithLabels(key,extraTags)),hookCache.set(extraTags,hook2),hook2};return make33(key.keyType,(input,extraTags)=>hook(extraTags).update(input),(extraTags)=>hook(extraTags).get(),(input,extraTags)=>hook(extraTags).modify(input))};var histogram5=(name,boundaries,description)=>fromMetricKey(histogram2(name,boundaries,description));var tagged=dual(3,(self,key,value)=>taggedWithLabels2(self,[make30(key,value)]));var taggedWithLabels2=dual(2,(self,extraTags)=>{return make33(self.keyType,(input,extraTags1)=>self.unsafeUpdate(input,union(extraTags,extraTags1)),(extraTags1)=>self.unsafeValue(union(extraTags,extraTags1)),(input,extraTags1)=>self.unsafeModify(input,union(extraTags,extraTags1)))});var update4=dual(2,(self,input)=>fiberRefGetWith(currentMetricLabels,(tags)=>sync(()=>self.unsafeUpdate(input,tags))));var RequestSymbolKey="effect/Request",RequestTypeId=Symbol.for(RequestSymbolKey),requestVariance={_E:(_)=>_,_A:(_)=>_},RequestPrototype={...StructuralPrototype,[RequestTypeId]:requestVariance},isRequest=(u)=>hasProperty(u,RequestTypeId);var complete=dual(2,(self,result)=>fiberRefGetWith(currentRequestMap,(map13)=>sync(()=>{if(map13.has(self)){let entry=map13.get(self);if(!entry.state.completed)entry.state.completed=!0,deferredUnsafeDone(entry.result,result)}})));class Listeners{count=0;observers=new Set;interrupted=!1;addObserver(f){this.observers.add(f)}removeObserver(f){this.observers.delete(f)}increment(){this.count++,this.observers.forEach((f)=>f(this.count))}decrement(){this.count--,this.observers.forEach((f)=>f(this.count))}}var Direction={Forward:0,Backward:1};class RedBlackTreeIterator{self;stack;direction;count=0;constructor(self,stack,direction){this.self=self,this.stack=stack,this.direction=direction}clone(){return new RedBlackTreeIterator(this.self,this.stack.slice(),this.direction)}reversed(){return new RedBlackTreeIterator(this.self,this.stack.slice(),this.direction===Direction.Forward?Direction.Backward:Direction.Forward)}next(){let entry=this.entry;if(this.count++,this.direction===Direction.Forward)this.moveNext();else this.movePrev();switch(entry._tag){case"None":return{done:!0,value:this.count};case"Some":return{done:!1,value:entry.value}}}get key(){if(this.stack.length>0)return some2(this.stack[this.stack.length-1].key);return none2()}get value(){if(this.stack.length>0)return some2(this.stack[this.stack.length-1].value);return none2()}get entry(){return map2(last(this.stack),(node)=>[node.key,node.value])}get index(){let idx=0,stack=this.stack;if(stack.length===0){let r=this.self._root;if(r!=null)return r.count;return 0}else if(stack[stack.length-1].left!=null)idx=stack[stack.length-1].left.count;for(let s=stack.length-2;s>=0;--s)if(stack[s+1]===stack[s].right){if(++idx,stack[s].left!=null)idx+=stack[s].left.count}return idx}moveNext(){let stack=this.stack;if(stack.length===0)return;let n=stack[stack.length-1];if(n.right!=null){n=n.right;while(n!=null)stack.push(n),n=n.left}else{stack.pop();while(stack.length>0&&stack[stack.length-1].right===n)n=stack[stack.length-1],stack.pop()}}get hasNext(){let stack=this.stack;if(stack.length===0)return!1;if(stack[stack.length-1].right!=null)return!0;for(let s=stack.length-1;s>0;--s)if(stack[s-1].left===stack[s])return!0;return!1}movePrev(){let stack=this.stack;if(stack.length===0)return;let n=stack[stack.length-1];if(n!=null&&n.left!=null){n=n.left;while(n!=null)stack.push(n),n=n.right}else{stack.pop();while(stack.length>0&&stack[stack.length-1].left===n)n=stack[stack.length-1],stack.pop()}}get hasPrev(){let stack=this.stack;if(stack.length===0)return!1;if(stack[stack.length-1].left!=null)return!0;for(let s=stack.length-1;s>0;--s)if(stack[s-1].right===stack[s])return!0;return!1}}var RedBlackTreeSymbolKey="effect/RedBlackTree",RedBlackTreeTypeId=Symbol.for(RedBlackTreeSymbolKey),redBlackTreeVariance={_Key:(_)=>_,_Value:(_)=>_},RedBlackTreeProto={[RedBlackTreeTypeId]:redBlackTreeVariance,[symbol](){let hash2=hash(RedBlackTreeSymbolKey);for(let item of this)hash2^=pipe(hash(item[0]),combine(hash(item[1])));return cached(this,hash2)},[symbol2](that){if(isRedBlackTree(that)){if((this._root?.count??0)!==(that._root?.count??0))return!1;let entries2=Array.from(that);return Array.from(this).every((itemSelf,i)=>{let itemThat=entries2[i];return equals(itemSelf[0],itemThat[0])&&equals(itemSelf[1],itemThat[1])})}return!1},[Symbol.iterator](){let stack=[],n=this._root;while(n!=null)stack.push(n),n=n.left;return new RedBlackTreeIterator(this,stack,Direction.Forward)},toString(){return format(this.toJSON())},toJSON(){return{_id:"RedBlackTree",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var isRedBlackTree=(u)=>hasProperty(u,RedBlackTreeTypeId);var keysForward=(self)=>keys3(self,Direction.Forward);var keys3=(self,direction)=>{let begin=self[Symbol.iterator](),count=0;return{[Symbol.iterator]:()=>keys3(self,direction),next:()=>{count++;let entry=begin.key;if(direction===Direction.Forward)begin.moveNext();else begin.movePrev();switch(entry._tag){case"None":return{done:!0,value:count};case"Some":return{done:!1,value:entry.value}}}}};var keys4=keysForward;var TypeId15=Symbol.for("effect/SortedSet"),SortedSetProto={[TypeId15]:{_A:(_)=>_},[symbol](){return pipe(hash(this.keyTree),combine(hash(TypeId15)),cached(this))},[symbol2](that){return isSortedSet(that)&&equals(this.keyTree,that.keyTree)},[Symbol.iterator](){return keys4(this.keyTree)},toString(){return format(this.toJSON())},toJSON(){return{_id:"SortedSet",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var isSortedSet=(u)=>hasProperty(u,TypeId15);var SupervisorSymbolKey="effect/Supervisor",SupervisorTypeId=Symbol.for(SupervisorSymbolKey),supervisorVariance={_T:(_)=>_};class ProxySupervisor{underlying;value0;[SupervisorTypeId]=supervisorVariance;constructor(underlying,value0){this.underlying=underlying,this.value0=value0}get value(){return this.value0}onStart(context2,effect,parent,fiber){this.underlying.onStart(context2,effect,parent,fiber)}onEnd(value,fiber){this.underlying.onEnd(value,fiber)}onEffect(fiber,effect){this.underlying.onEffect(fiber,effect)}onSuspend(fiber){this.underlying.onSuspend(fiber)}onResume(fiber){this.underlying.onResume(fiber)}map(f){return new ProxySupervisor(this,pipe(this.value,map10(f)))}zip(right3){return new Zip(this,right3)}}class Zip{left;right;_tag="Zip";[SupervisorTypeId]=supervisorVariance;constructor(left3,right3){this.left=left3,this.right=right3}get value(){return zip2(this.left.value,this.right.value)}onStart(context2,effect,parent,fiber){this.left.onStart(context2,effect,parent,fiber),this.right.onStart(context2,effect,parent,fiber)}onEnd(value,fiber){this.left.onEnd(value,fiber),this.right.onEnd(value,fiber)}onEffect(fiber,effect){this.left.onEffect(fiber,effect),this.right.onEffect(fiber,effect)}onSuspend(fiber){this.left.onSuspend(fiber),this.right.onSuspend(fiber)}onResume(fiber){this.left.onResume(fiber),this.right.onResume(fiber)}map(f){return new ProxySupervisor(this,pipe(this.value,map10(f)))}zip(right3){return new Zip(this,right3)}}var isZip=(self)=>hasProperty(self,SupervisorTypeId)&&isTagged(self,"Zip");class Track{[SupervisorTypeId]=supervisorVariance;fibers=new Set;get value(){return sync(()=>Array.from(this.fibers))}onStart(_context,_effect,_parent,fiber){this.fibers.add(fiber)}onEnd(_value,fiber){this.fibers.delete(fiber)}onEffect(_fiber,_effect){}onSuspend(_fiber){}onResume(_fiber){}map(f){return new ProxySupervisor(this,pipe(this.value,map10(f)))}zip(right3){return new Zip(this,right3)}onRun(execution,_fiber){return execution()}}class Const{effect;[SupervisorTypeId]=supervisorVariance;constructor(effect){this.effect=effect}get value(){return this.effect}onStart(_context,_effect,_parent,_fiber){}onEnd(_value,_fiber){}onEffect(_fiber,_effect){}onSuspend(_fiber){}onResume(_fiber){}map(f){return new ProxySupervisor(this,pipe(this.value,map10(f)))}zip(right3){return new Zip(this,right3)}onRun(execution,_fiber){return execution()}}var unsafeTrack=()=>{return new Track},track=sync(unsafeTrack),fromEffect2=(effect)=>{return new Const(effect)},none8=globalValue("effect/Supervisor/none",()=>fromEffect2(void_));var make35=make15;var OP_EMPTY3="Empty",OP_ADD_SUPERVISOR="AddSupervisor",OP_REMOVE_SUPERVISOR="RemoveSupervisor",OP_AND_THEN2="AndThen",empty29={_tag:OP_EMPTY3},combine11=(self,that)=>{return{_tag:OP_AND_THEN2,first:self,second:that}},patch11=(self,supervisor)=>{return patchLoop(supervisor,of2(self))},patchLoop=(_supervisor,_patches)=>{let supervisor=_supervisor,patches=_patches;while(isNonEmpty2(patches)){let head4=headNonEmpty2(patches);switch(head4._tag){case OP_EMPTY3:{patches=tailNonEmpty2(patches);break}case OP_ADD_SUPERVISOR:{supervisor=supervisor.zip(head4.supervisor),patches=tailNonEmpty2(patches);break}case OP_REMOVE_SUPERVISOR:{supervisor=removeSupervisor(supervisor,head4.supervisor),patches=tailNonEmpty2(patches);break}case OP_AND_THEN2:{patches=prepend2(head4.first)(prepend2(head4.second)(tailNonEmpty2(patches)));break}}}return supervisor},removeSupervisor=(self,that)=>{if(equals(self,that))return none8;else if(isZip(self))return removeSupervisor(self.left,that).zip(removeSupervisor(self.right,that));else return self},toSet2=(self)=>{if(equals(self,none8))return empty8();else if(isZip(self))return pipe(toSet2(self.left),union3(toSet2(self.right)));else return make11(self)},diff10=(oldValue,newValue)=>{if(equals(oldValue,newValue))return empty29;let oldSupervisors=toSet2(oldValue),newSupervisors=toSet2(newValue),added=pipe(newSupervisors,difference3(oldSupervisors),reduce6(empty29,(patch12,supervisor)=>combine11(patch12,{_tag:OP_ADD_SUPERVISOR,supervisor}))),removed=pipe(oldSupervisors,difference3(newSupervisors),reduce6(empty29,(patch12,supervisor)=>combine11(patch12,{_tag:OP_REMOVE_SUPERVISOR,supervisor})));return combine11(added,removed)},differ2=make35({empty:empty29,patch:patch11,combine:combine11,diff:diff10});var fiberStarted=counter5("effect_fiber_started",{incremental:!0}),fiberActive=counter5("effect_fiber_active"),fiberSuccesses=counter5("effect_fiber_successes",{incremental:!0}),fiberFailures=counter5("effect_fiber_failures",{incremental:!0}),fiberLifetimes=tagged(histogram5("effect_fiber_lifetimes",exponential({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),EvaluationSignalContinue="Continue",EvaluationSignalDone="Done",EvaluationSignalYieldNow="Yield",runtimeFiberVariance={_E:(_)=>_,_A:(_)=>_},absurd=(_)=>{throw new Error(`BUG: FiberRuntime - ${toStringUnknown(_)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},YieldedOp=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),yieldedOpChannel=globalValue("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),contOpSuccess={[OP_ON_SUCCESS]:(_,cont,value)=>{return internalCall(()=>cont.effect_instruction_i1(value))},["OnStep"]:(_,_cont,value)=>{return exitSucceed(exitSucceed(value))},[OP_ON_SUCCESS_AND_FAILURE]:(_,cont,value)=>{return internalCall(()=>cont.effect_instruction_i2(value))},[OP_REVERT_FLAGS]:(self,cont,value)=>{if(self.patchRuntimeFlags(self.currentRuntimeFlags,cont.patch),interruptible(self.currentRuntimeFlags)&&self.isInterrupted())return exitFailCause(self.getInterruptedCause());else return exitSucceed(value)},[OP_WHILE]:(self,cont,value)=>{if(internalCall(()=>cont.effect_instruction_i2(value)),internalCall(()=>cont.effect_instruction_i0()))return self.pushStack(cont),internalCall(()=>cont.effect_instruction_i1());else return void_},[OP_ITERATOR]:(self,cont,value)=>{let state=internalCall(()=>cont.effect_instruction_i0.next(value));if(state.done)return exitSucceed(state.value);return self.pushStack(cont),yieldWrapGet(state.value)}},drainQueueWhileRunningTable={[OP_INTERRUPT_SIGNAL]:(self,runtimeFlags2,cur,message)=>{return self.processNewInterruptSignal(message.cause),interruptible(runtimeFlags2)?exitFailCause(message.cause):cur},[OP_RESUME]:(_self,_runtimeFlags,_cur,_message)=>{throw new Error("It is illegal to have multiple concurrent run loops in a single fiber")},[OP_STATEFUL]:(self,runtimeFlags2,cur,message)=>{return message.onFiber(self,running2(runtimeFlags2)),cur},[OP_YIELD_NOW]:(_self,_runtimeFlags,cur,_message)=>{return flatMap8(yieldNow(),()=>cur)}},runBlockedRequests=(self)=>forEachSequentialDiscard(flatten4(self),(requestsByRequestResolver)=>forEachConcurrentDiscard(sequentialCollectionToChunk(requestsByRequestResolver),([dataSource,sequential4])=>{let map13=new Map,arr=[];for(let block of sequential4){arr.push(toReadonlyArray(block));for(let entry of block)map13.set(entry.request,entry)}let flat=arr.flat();return fiberRefLocally(invokeWithInterrupt(dataSource.runAll(arr),flat,()=>flat.forEach((entry)=>{entry.listeners.interrupted=!0})),currentRequestMap,map13)},!1,!1)),_version=getCurrentVersion();class FiberRuntime extends Class{[FiberTypeId]=fiberVariance2;[RuntimeFiberTypeId]=runtimeFiberVariance;_fiberRefs;_fiberId;_queue=new Array;_children=null;_observers=new Array;_running=!1;_stack=[];_asyncInterruptor=null;_asyncBlockingOn=null;_exitValue=null;_steps=[];_isYielding=!1;currentRuntimeFlags;currentOpCount=0;currentSupervisor;currentScheduler;currentTracer;currentSpan;currentContext;currentDefaultServices;constructor(fiberId2,fiberRefs0,runtimeFlags0){super();if(this.currentRuntimeFlags=runtimeFlags0,this._fiberId=fiberId2,this._fiberRefs=fiberRefs0,runtimeMetrics(runtimeFlags0)){let tags=this.getFiberRef(currentMetricLabels);fiberStarted.unsafeUpdate(1,tags),fiberActive.unsafeUpdate(1,tags)}this.refreshRefCache()}commit(){return join2(this)}id(){return this._fiberId}resume(effect){this.tell(resume(effect))}get status(){return this.ask((_,status2)=>status2)}get runtimeFlags(){return this.ask((state,status2)=>{if(isDone3(status2))return state.currentRuntimeFlags;return status2.runtimeFlags})}scope(){return unsafeMake7(this)}get children(){return this.ask((fiber)=>Array.from(fiber.getChildren()))}getChildren(){if(this._children===null)this._children=new Set;return this._children}getInterruptedCause(){return this.getFiberRef(currentInterruptedCause)}fiberRefs(){return this.ask((fiber)=>fiber.getFiberRefs())}ask(f){return suspend(()=>{let deferred=deferredUnsafeMake(this._fiberId);return this.tell(stateful((fiber,status2)=>{deferredUnsafeDone(deferred,sync(()=>f(fiber,status2)))})),deferredAwait(deferred)})}tell(message){if(this._queue.push(message),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return async_((resume2)=>{let cb=(exit2)=>resume2(succeed(exit2));return this.tell(stateful((fiber,_)=>{if(fiber._exitValue!==null)cb(this._exitValue);else fiber.addObserver(cb)})),sync(()=>this.tell(stateful((fiber,_)=>{fiber.removeObserver(cb)})))},this.id())}get inheritAll(){return withFiberRuntime((parentFiber,parentStatus)=>{let parentFiberId=parentFiber.id(),parentFiberRefs=parentFiber.getFiberRefs(),parentRuntimeFlags=parentStatus.runtimeFlags,childFiberRefs=this.getFiberRefs(),updatedFiberRefs=joinAs(parentFiberRefs,parentFiberId,childFiberRefs);parentFiber.setFiberRefs(updatedFiberRefs);let updatedRuntimeFlags=parentFiber.getFiberRef(currentRuntimeFlags),patch12=pipe(diff7(parentRuntimeFlags,updatedRuntimeFlags),exclude2(Interruption),exclude2(WindDown));return updateRuntimeFlags(patch12)})}get poll(){return sync(()=>fromNullable(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(fiberId2){return sync(()=>this.tell(interruptSignal(interrupt(fiberId2))))}unsafeInterruptAsFork(fiberId2){this.tell(interruptSignal(interrupt(fiberId2)))}addObserver(observer){if(this._exitValue!==null)observer(this._exitValue);else this._observers.push(observer)}removeObserver(observer){this._observers=this._observers.filter((o)=>o!==observer)}getFiberRefs(){return this.setFiberRef(currentRuntimeFlags,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(fiberRef){this._fiberRefs=delete_(this._fiberRefs,fiberRef)}getFiberRef(fiberRef){if(this._fiberRefs.locals.has(fiberRef))return this._fiberRefs.locals.get(fiberRef)[0][1];return fiberRef.initial}setFiberRef(fiberRef,value){this._fiberRefs=updateAs(this._fiberRefs,{fiberId:this._fiberId,fiberRef,value}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(currentServices),this.currentTracer=this.currentDefaultServices.unsafeMap.get(tracerTag.key),this.currentSupervisor=this.getFiberRef(currentSupervisor),this.currentScheduler=this.getFiberRef(currentScheduler),this.currentContext=this.getFiberRef(currentContext),this.currentSpan=this.currentContext.unsafeMap.get(spanTag.key)}setFiberRefs(fiberRefs3){this._fiberRefs=fiberRefs3,this.refreshRefCache()}addChild(child){this.getChildren().add(child)}removeChild(child){this.getChildren().delete(child)}transferChildren(scope){let children2=this._children;if(this._children=null,children2!==null&&children2.size>0){for(let child of children2)if(child._exitValue===null)scope.add(this.currentRuntimeFlags,child)}}drainQueueOnCurrentThread(){let recurse=!0;while(recurse){let evaluationSignal=EvaluationSignalContinue,prev=globalThis[currentFiberURI];globalThis[currentFiberURI]=this;try{while(evaluationSignal===EvaluationSignalContinue)evaluationSignal=this._queue.length===0?EvaluationSignalDone:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[currentFiberURI]=prev}if(this._queue.length>0&&!this._running)if(this._running=!0,evaluationSignal===EvaluationSignalYieldNow)this.drainQueueLaterOnExecutor(),recurse=!1;else recurse=!0;else recurse=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(currentSchedulingPriority))}drainQueueWhileRunning(runtimeFlags2,cur0){let cur=cur0;while(this._queue.length>0){let message=this._queue.splice(0,1)[0];cur=drainQueueWhileRunningTable[message._tag](this,runtimeFlags2,cur,message)}return cur}isInterrupted(){return!isEmpty5(this.getFiberRef(currentInterruptedCause))}addInterruptedCause(cause2){let oldSC=this.getFiberRef(currentInterruptedCause);this.setFiberRef(currentInterruptedCause,sequential(oldSC,cause2))}processNewInterruptSignal(cause2){this.addInterruptedCause(cause2),this.sendInterruptSignalToAllChildren()}sendInterruptSignalToAllChildren(){if(this._children===null||this._children.size===0)return!1;let told=!1;for(let child of this._children)child.tell(interruptSignal(interrupt(this.id()))),told=!0;return told}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let it=this._children.values();this._children=null;let isDone4=!1;return whileLoop({while:()=>!isDone4,body:()=>{let next=it.next();if(!next.done)return asVoid(next.value.await);else return sync(()=>{isDone4=!0})},step:()=>{}})}return null}reportExitValue(exit2){if(runtimeMetrics(this.currentRuntimeFlags)){let tags=this.getFiberRef(currentMetricLabels),startTimeMillis=this.id().startTimeMillis,endTimeMillis=Date.now();switch(fiberLifetimes.unsafeUpdate(endTimeMillis-startTimeMillis,tags),fiberActive.unsafeUpdate(-1,tags),exit2._tag){case OP_SUCCESS:{fiberSuccesses.unsafeUpdate(1,tags);break}case OP_FAILURE:{fiberFailures.unsafeUpdate(1,tags);break}}}if(exit2._tag==="Failure"){let level=this.getFiberRef(currentUnhandledErrorLogLevel);if(!isInterruptedOnly(exit2.cause)&&level._tag==="Some")this.log("Fiber terminated with an unhandled error",exit2.cause,level)}}setExitValue(exit2){this._exitValue=exit2,this.reportExitValue(exit2);for(let i=this._observers.length-1;i>=0;i--)this._observers[i](exit2);this._observers=[]}getLoggers(){return this.getFiberRef(currentLoggers)}log(message,cause2,overrideLogLevel){let logLevel=isSome2(overrideLogLevel)?overrideLogLevel.value:this.getFiberRef(currentLogLevel),minimumLogLevel=this.getFiberRef(currentMinimumLogLevel);if(greaterThan3(minimumLogLevel,logLevel))return;let spans=this.getFiberRef(currentLogSpan),annotations2=this.getFiberRef(currentLogAnnotations),loggers=this.getLoggers(),contextMap=this.getFiberRefs();if(size3(loggers)>0){let clockService=get3(this.getFiberRef(currentServices),clockTag),date=new Date(clockService.unsafeCurrentTimeMillis());withRedactableContext(contextMap,()=>{for(let logger of loggers)logger.log({fiberId:this.id(),logLevel,message,cause:cause2,context:contextMap,spans,annotations:annotations2,date})})}}evaluateMessageWhileSuspended(message){switch(message._tag){case OP_YIELD_NOW:return EvaluationSignalYieldNow;case OP_INTERRUPT_SIGNAL:{if(this.processNewInterruptSignal(message.cause),this._asyncInterruptor!==null)this._asyncInterruptor(exitFailCause(message.cause)),this._asyncInterruptor=null;return EvaluationSignalContinue}case OP_RESUME:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(message.effect),EvaluationSignalContinue;case OP_STATEFUL:return message.onFiber(this,this._exitValue!==null?done4:suspended2(this.currentRuntimeFlags,this._asyncBlockingOn)),EvaluationSignalContinue;default:return absurd(message)}}evaluateEffect(effect0){this.currentSupervisor.onResume(this);try{let effect=interruptible(this.currentRuntimeFlags)&&this.isInterrupted()?exitFailCause(this.getInterruptedCause()):effect0;while(effect!==null){let eff=effect,exit2=this.runLoop(eff);if(exit2===YieldedOp){let op=yieldedOpChannel.currentOp;if(yieldedOpChannel.currentOp=null,op._op===OP_YIELD)if(cooperativeYielding(this.currentRuntimeFlags))this.tell(yieldNow3()),this.tell(resume(exitVoid)),effect=null;else effect=exitVoid;else if(op._op===OP_ASYNC)effect=null}else{this.currentRuntimeFlags=pipe(this.currentRuntimeFlags,enable2(WindDown));let interruption2=this.interruptAllChildren();if(interruption2!==null)effect=flatMap8(interruption2,()=>exit2);else{if(this._queue.length===0)this.setExitValue(exit2);else this.tell(resume(exit2));effect=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(effect){if(!this._running){this._running=!0;let prev=globalThis[currentFiberURI];globalThis[currentFiberURI]=this;try{this.evaluateEffect(effect)}finally{if(this._running=!1,globalThis[currentFiberURI]=prev,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(resume(effect))}startFork(effect){this.tell(resume(effect))}patchRuntimeFlags(oldRuntimeFlags,patch12){let newRuntimeFlags=patch7(oldRuntimeFlags,patch12);return globalThis[currentFiberURI]=this,this.currentRuntimeFlags=newRuntimeFlags,newRuntimeFlags}initiateAsync(runtimeFlags2,asyncRegister){let alreadyCalled=!1,callback=(effect)=>{if(!alreadyCalled)alreadyCalled=!0,this.tell(resume(effect))};if(interruptible(runtimeFlags2))this._asyncInterruptor=callback;try{asyncRegister(callback)}catch(e){callback(failCause(die(e)))}}pushStack(cont){if(this._stack.push(cont),cont._op==="OnStep")this._steps.push({refs:this.getFiberRefs(),flags:this.currentRuntimeFlags})}popStack(){let item=this._stack.pop();if(item){if(item._op==="OnStep")this._steps.pop();return item}return}getNextSuccessCont(){let frame=this.popStack();while(frame){if(frame._op!==OP_ON_FAILURE)return frame;frame=this.popStack()}}getNextFailCont(){let frame=this.popStack();while(frame){if(frame._op!==OP_ON_SUCCESS&&frame._op!==OP_WHILE&&frame._op!==OP_ITERATOR)return frame;frame=this.popStack()}}[OP_TAG](op){return sync(()=>unsafeGet3(this.currentContext,op))}["Left"](op){return fail2(op.left)}["None"](_){return fail2(new NoSuchElementException)}["Right"](op){return exitSucceed(op.right)}["Some"](op){return exitSucceed(op.value)}["Micro"](op){return unsafeAsync((microResume)=>{let resume2=microResume,fiber=runFork(provideContext2(op,this.currentContext));return fiber.addObserver((exit2)=>{if(exit2._tag==="Success")return resume2(exitSucceed(exit2.value));switch(exit2.cause._tag){case"Interrupt":return resume2(exitFailCause(interrupt(none4)));case"Fail":return resume2(fail2(exit2.cause.error));case"Die":return resume2(die2(exit2.cause.defect))}}),unsafeAsync((abortResume)=>{resume2=(_)=>{abortResume(void_)},fiber.unsafeInterrupt()})})}[OP_SYNC](op){let value=internalCall(()=>op.effect_instruction_i0()),cont=this.getNextSuccessCont();if(cont!==void 0){if(!(cont._op in contOpSuccess))absurd(cont);return contOpSuccess[cont._op](this,cont,value)}else return yieldedOpChannel.currentOp=exitSucceed(value),YieldedOp}[OP_SUCCESS](op){let oldCur=op,cont=this.getNextSuccessCont();if(cont!==void 0){if(!(cont._op in contOpSuccess))absurd(cont);return contOpSuccess[cont._op](this,cont,oldCur.effect_instruction_i0)}else return yieldedOpChannel.currentOp=oldCur,YieldedOp}[OP_FAILURE](op){let cause2=op.effect_instruction_i0,cont=this.getNextFailCont();if(cont!==void 0)switch(cont._op){case OP_ON_FAILURE:case OP_ON_SUCCESS_AND_FAILURE:if(!(interruptible(this.currentRuntimeFlags)&&this.isInterrupted()))return internalCall(()=>cont.effect_instruction_i1(cause2));else return exitFailCause(stripFailures(cause2));case"OnStep":if(!(interruptible(this.currentRuntimeFlags)&&this.isInterrupted()))return exitSucceed(exitFailCause(cause2));else return exitFailCause(stripFailures(cause2));case OP_REVERT_FLAGS:if(this.patchRuntimeFlags(this.currentRuntimeFlags,cont.patch),interruptible(this.currentRuntimeFlags)&&this.isInterrupted())return exitFailCause(sequential(cause2,this.getInterruptedCause()));else return exitFailCause(cause2);default:absurd(cont)}else return yieldedOpChannel.currentOp=exitFailCause(cause2),YieldedOp}[OP_WITH_RUNTIME](op){return internalCall(()=>op.effect_instruction_i0(this,running2(this.currentRuntimeFlags)))}["Blocked"](op){let refs=this.getFiberRefs(),flags=this.currentRuntimeFlags;if(this._steps.length>0){let frames=[],snap=this._steps[this._steps.length-1],frame=this.popStack();while(frame&&frame._op!=="OnStep")frames.push(frame),frame=this.popStack();this.setFiberRefs(snap.refs),this.currentRuntimeFlags=snap.flags;let patchRefs=diff9(snap.refs,refs),patchFlags=diff7(snap.flags,flags);return exitSucceed(blocked(op.effect_instruction_i0,withFiberRuntime((newFiber)=>{while(frames.length>0)newFiber.pushStack(frames.pop());return newFiber.setFiberRefs(patch10(newFiber.id(),newFiber.getFiberRefs())(patchRefs)),newFiber.currentRuntimeFlags=patch7(patchFlags)(newFiber.currentRuntimeFlags),op.effect_instruction_i1})))}return uninterruptibleMask((restore)=>flatMap8(forkDaemon(runRequestBlock(op.effect_instruction_i0)),()=>restore(op.effect_instruction_i1)))}["RunBlocked"](op){return runBlockedRequests(op.effect_instruction_i0)}[OP_UPDATE_RUNTIME_FLAGS](op){let updateFlags=op.effect_instruction_i0,oldRuntimeFlags=this.currentRuntimeFlags,newRuntimeFlags=patch7(oldRuntimeFlags,updateFlags);if(interruptible(newRuntimeFlags)&&this.isInterrupted())return exitFailCause(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,updateFlags),op.effect_instruction_i1){let revertFlags=diff7(newRuntimeFlags,oldRuntimeFlags);return this.pushStack(new RevertFlags(revertFlags,op)),internalCall(()=>op.effect_instruction_i1(oldRuntimeFlags))}else return exitVoid}[OP_ON_SUCCESS](op){return this.pushStack(op),op.effect_instruction_i0}["OnStep"](op){return this.pushStack(op),op.effect_instruction_i0}[OP_ON_FAILURE](op){return this.pushStack(op),op.effect_instruction_i0}[OP_ON_SUCCESS_AND_FAILURE](op){return this.pushStack(op),op.effect_instruction_i0}[OP_ASYNC](op){return this._asyncBlockingOn=op.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,op.effect_instruction_i0),yieldedOpChannel.currentOp=op,YieldedOp}[OP_YIELD](op){return this._isYielding=!1,yieldedOpChannel.currentOp=op,YieldedOp}[OP_WHILE](op){let{effect_instruction_i0:check,effect_instruction_i1:body}=op;if(check())return this.pushStack(op),body();else return exitVoid}[OP_ITERATOR](op){return contOpSuccess[OP_ITERATOR](this,op,void 0)}[OP_COMMIT](op){return internalCall(()=>op.commit())}runLoop(effect0){let cur=effect0;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&OpSupervision)!==0)this.currentSupervisor.onEffect(this,cur);if(this._queue.length>0)cur=this.drainQueueWhileRunning(this.currentRuntimeFlags,cur);if(!this._isYielding){this.currentOpCount+=1;let shouldYield=this.currentScheduler.shouldYield(this);if(shouldYield!==!1){this._isYielding=!0,this.currentOpCount=0;let oldCur=cur;cur=flatMap8(yieldNow({priority:shouldYield}),()=>oldCur)}}try{if(cur=this.currentTracer.context(()=>{if(_version!==cur[EffectTypeId2]._V)return dieMessage(`Cannot execute an Effect versioned ${cur[EffectTypeId2]._V} with a Runtime of version ${getCurrentVersion()}`);return this[cur._op](cur)},this),cur===YieldedOp){let op=yieldedOpChannel.currentOp;if(op._op===OP_YIELD||op._op===OP_ASYNC)return YieldedOp;return yieldedOpChannel.currentOp=null,op._op===OP_SUCCESS||op._op===OP_FAILURE?op:exitFailCause(die(op))}}catch(e){if(cur!==YieldedOp&&!hasProperty(cur,"_op")||!(cur._op in this))cur=dieMessage(`Not a valid effect: ${toStringUnknown(cur)}`);else if(isInterruptedException(e))cur=exitFailCause(sequential(die(e),interrupt(none4)));else cur=die2(e)}}}run=()=>{this.drainQueueOnCurrentThread()}}var currentMinimumLogLevel=globalValue("effect/FiberRef/currentMinimumLogLevel",()=>fiberRefUnsafeMake(fromLiteral("Info"))),loggerWithConsoleLog=(self)=>makeLogger((opts)=>{let services=getOrDefault2(opts.context,currentServices);get3(services,consoleTag).unsafe.log(self.log(opts))});var defaultLogger=globalValue(Symbol.for("effect/Logger/defaultLogger"),()=>loggerWithConsoleLog(stringLogger));var tracerLogger=globalValue(Symbol.for("effect/Logger/tracerLogger"),()=>makeLogger(({annotations:annotations2,cause:cause2,context:context2,fiberId:fiberId2,logLevel,message})=>{let span2=getOption2(getOrDefault(context2,currentContext),spanTag);if(span2._tag==="None"||span2.value._tag==="ExternalSpan")return;let clockService=unsafeGet3(getOrDefault(context2,currentServices),clockTag),attributes={};for(let[key,value]of annotations2)attributes[key]=value;if(attributes["effect.fiberId"]=threadName2(fiberId2),attributes["effect.logLevel"]=logLevel.label,cause2!==null&&cause2._tag!=="Empty")attributes["effect.cause"]=pretty(cause2,{renderErrorCause:!0});span2.value.event(toStringUnknown(Array.isArray(message)?message[0]:message),clockService.unsafeCurrentTimeNanos(),attributes)}));var currentLoggers=globalValue(Symbol.for("effect/FiberRef/currentLoggers"),()=>fiberRefUnsafeMakeHashSet(make11(defaultLogger,tracerLogger)));var annotateLogsScoped=function(){if(typeof arguments[0]==="string")return fiberRefLocallyScopedWith(currentLogAnnotations,set3(arguments[0],arguments[1]));let entries2=Object.entries(arguments[0]);return fiberRefLocallyScopedWith(currentLogAnnotations,mutate3((annotations2)=>{for(let i=0;i<entries2.length;i++){let[key,value]=entries2[i];set3(annotations2,key,value)}return annotations2}))},whenLogLevel=dual(2,(effect,level)=>{let requiredLogLevel=typeof level==="string"?fromLiteral(level):level;return withFiberRuntime((fiberState)=>{let minimumLogLevel=fiberState.getFiberRef(currentMinimumLogLevel);if(greaterThan3(minimumLogLevel,requiredLogLevel))return succeed(none2());return map10(effect,some2)})}),acquireRelease=dual((args2)=>isEffect(args2[0]),(acquire,release)=>uninterruptible(tap(acquire,(a)=>addFinalizer((exit2)=>release(a,exit2))))),acquireReleaseInterruptible=dual((args2)=>isEffect(args2[0]),(acquire,release)=>ensuring(acquire,addFinalizer((exit2)=>release(exit2)))),addFinalizer=(finalizer)=>withFiberRuntime((runtime2)=>{let acquireRefs=runtime2.getFiberRefs(),acquireFlags=runtime2.currentRuntimeFlags;return flatMap8(scope,(scope)=>scopeAddFinalizerExit(scope,(exit2)=>withFiberRuntime((runtimeFinalizer)=>{let preRefs=runtimeFinalizer.getFiberRefs(),preFlags=runtimeFinalizer.currentRuntimeFlags,patchRefs=diff9(preRefs,acquireRefs),patchFlags=diff7(preFlags,acquireFlags),inverseRefs=diff9(acquireRefs,preRefs);return runtimeFinalizer.setFiberRefs(patch10(patchRefs,runtimeFinalizer.id(),acquireRefs)),ensuring(withRuntimeFlags(finalizer(exit2),patchFlags),sync(()=>{runtimeFinalizer.setFiberRefs(patch10(inverseRefs,runtimeFinalizer.id(),runtimeFinalizer.getFiberRefs()))}))})))}),daemonChildren=(self)=>{return fiberRefLocally(currentForkScopeOverride,some2(globalScope))(self)},_existsParFound=Symbol.for("effect/Effect/existsPar/found"),exists2=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,predicate,options)=>matchSimple(options?.concurrency,()=>suspend(()=>existsLoop(elements[Symbol.iterator](),0,predicate)),()=>matchEffect(forEach7(elements,(a,i)=>if_(predicate(a,i),{onTrue:()=>fail2(_existsParFound),onFalse:()=>void_}),options),{onFailure:(e)=>e===_existsParFound?succeed(!0):fail2(e),onSuccess:()=>succeed(!1)}))),existsLoop=(iterator,index,f)=>{let next=iterator.next();if(next.done)return succeed(!1);return pipe(flatMap8(f(next.value,index),(b)=>b?succeed(b):existsLoop(iterator,index+1,f)))},filter6=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,predicate,options)=>{let predicate_=options?.negate?(a,i)=>map10(predicate(a,i),not):predicate;return matchSimple(options?.concurrency,()=>suspend(()=>fromIterable(elements).reduceRight((effect,a,i)=>zipWith3(effect,suspend(()=>predicate_(a,i)),(list,b)=>b?[a,...list]:list),sync(()=>new Array))),()=>map10(forEach7(elements,(a,i)=>map10(predicate_(a,i),(b)=>b?some2(a):none2()),options),getSomes))}),allResolveInput=(input)=>{if(Array.isArray(input)||isIterable(input))return[input,none2()];let keys5=Object.keys(input),size8=keys5.length;return[keys5.map((k)=>input[k]),some2((values3)=>{let res={};for(let i=0;i<size8;i++)res[keys5[i]]=values3[i];return res})]},allValidate=(effects,reconcile,options)=>{let eitherEffects=[];for(let effect of effects)eitherEffects.push(either2(effect));return flatMap8(forEach7(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),(eithers)=>{let none9=none2(),size8=eithers.length,errors=new Array(size8),successes=new Array(size8),errored=!1;for(let i=0;i<size8;i++){let either3=eithers[i];if(either3._tag==="Left")errors[i]=some2(either3.left),errored=!0;else successes[i]=either3.right,errors[i]=none9}if(errored)return reconcile._tag==="Some"?fail2(reconcile.value(errors)):fail2(errors);else if(options?.discard)return void_;return reconcile._tag==="Some"?succeed(reconcile.value(successes)):succeed(successes)})},allEither=(effects,reconcile,options)=>{let eitherEffects=[];for(let effect of effects)eitherEffects.push(either2(effect));if(options?.discard)return forEach7(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,discard:!0,concurrentFinalizers:options?.concurrentFinalizers});return map10(forEach7(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),(eithers)=>reconcile._tag==="Some"?reconcile.value(eithers):eithers)},all4=(arg,options)=>{let[effects,reconcile]=allResolveInput(arg);if(options?.mode==="validate")return allValidate(effects,reconcile,options);else if(options?.mode==="either")return allEither(effects,reconcile,options);return options?.discard!==!0&&reconcile._tag==="Some"?map10(forEach7(effects,identity,options),reconcile.value):forEach7(effects,identity,options)},allWith=(options)=>(arg)=>all4(arg,options),allSuccesses=(elements,options)=>map10(all4(fromIterable(elements).map(exit),options),filterMap((exit2)=>exitIsSuccess(exit2)?some2(exit2.effect_instruction_i0):none2())),replicate=dual(2,(self,n)=>Array.from({length:n},()=>self)),replicateEffect=dual((args2)=>isEffect(args2[0]),(self,n,options)=>all4(replicate(self,n),options)),forEach7=dual((args2)=>isIterable(args2[0]),(self,f,options)=>withFiberRuntime((r)=>{let isRequestBatchingEnabled=options?.batching===!0||options?.batching==="inherit"&&r.getFiberRef(currentRequestBatching);if(options?.discard)return match9(options.concurrency,()=>finalizersMaskInternal(sequential3,options?.concurrentFinalizers)((restore)=>isRequestBatchingEnabled?forEachConcurrentDiscard(self,(a,i)=>restore(f(a,i)),!0,!1,1):forEachSequentialDiscard(self,(a,i)=>restore(f(a,i)))),()=>finalizersMaskInternal(parallel3,options?.concurrentFinalizers)((restore)=>forEachConcurrentDiscard(self,(a,i)=>restore(f(a,i)),isRequestBatchingEnabled,!1)),(n)=>finalizersMaskInternal(parallelN2(n),options?.concurrentFinalizers)((restore)=>forEachConcurrentDiscard(self,(a,i)=>restore(f(a,i)),isRequestBatchingEnabled,!1,n)));return match9(options?.concurrency,()=>finalizersMaskInternal(sequential3,options?.concurrentFinalizers)((restore)=>isRequestBatchingEnabled?forEachParN(self,1,(a,i)=>restore(f(a,i)),!0):forEachSequential(self,(a,i)=>restore(f(a,i)))),()=>finalizersMaskInternal(parallel3,options?.concurrentFinalizers)((restore)=>forEachParUnbounded(self,(a,i)=>restore(f(a,i)),isRequestBatchingEnabled)),(n)=>finalizersMaskInternal(parallelN2(n),options?.concurrentFinalizers)((restore)=>forEachParN(self,n,(a,i)=>restore(f(a,i)),isRequestBatchingEnabled)))})),forEachParUnbounded=(self,f,batching)=>suspend(()=>{let as2=fromIterable(self),array4=new Array(as2.length);return zipRight(forEachConcurrentDiscard(as2,(a,i)=>flatMap8(f(a,i),(b)=>sync(()=>array4[i]=b)),batching,!1),succeed(array4))}),forEachConcurrentDiscard=(self,f,batching,processAll,n)=>uninterruptibleMask((restore)=>transplant((graft)=>withFiberRuntime((parent)=>{let todos=Array.from(self).reverse(),target=todos.length;if(target===0)return void_;let counter6=0,interrupted2=!1,fibersCount=n?Math.min(todos.length,n):todos.length,fibers=new Set,results=new Array,interruptAll2=()=>fibers.forEach((fiber)=>{fiber.currentScheduler.scheduleTask(()=>{fiber.unsafeInterruptAsFork(parent.id())},0)}),startOrder=new Array,joinOrder=new Array,residual=new Array,collectExits=()=>{let exits=results.filter(({exit:exit2})=>exit2._tag==="Failure").sort((a,b)=>a.index<b.index?-1:a.index===b.index?0:1).map(({exit:exit2})=>exit2);if(exits.length===0)exits.push(exitVoid);return exits},runFiber=(eff,interruptImmediately=!1)=>{let runnable=uninterruptible(graft(eff)),fiber=unsafeForkUnstarted(runnable,parent,parent.currentRuntimeFlags,globalScope);return parent.currentScheduler.scheduleTask(()=>{if(interruptImmediately)fiber.unsafeInterruptAsFork(parent.id());fiber.resume(runnable)},0),fiber},onInterruptSignal=()=>{if(!processAll)target-=todos.length,todos=[];interrupted2=!0,interruptAll2()},stepOrExit=batching?step2:exit,processingFiber=runFiber(async_((resume2)=>{let pushResult=(res,index)=>{if(res._op==="Blocked")residual.push(res);else if(results.push({index,exit:res}),res._op==="Failure"&&!interrupted2)onInterruptSignal()},next=()=>{if(todos.length>0){let a=todos.pop(),index=counter6++,returnNextElement=()=>{let a2=todos.pop();return index=counter6++,flatMap8(yieldNow(),()=>flatMap8(stepOrExit(restore(f(a2,index))),onRes))},onRes=(res)=>{if(todos.length>0){if(pushResult(res,index),todos.length>0)return returnNextElement()}return succeed(res)},todo=flatMap8(stepOrExit(restore(f(a,index))),onRes),fiber=runFiber(todo);if(startOrder.push(fiber),fibers.add(fiber),interrupted2)fiber.currentScheduler.scheduleTask(()=>{fiber.unsafeInterruptAsFork(parent.id())},0);fiber.addObserver((wrapped)=>{let exit2;if(wrapped._op==="Failure")exit2=wrapped;else exit2=wrapped.effect_instruction_i0;if(joinOrder.push(fiber),fibers.delete(fiber),pushResult(exit2,index),results.length===target)resume2(succeed(getOrElse(exitCollectAll(collectExits(),{parallel:!0}),()=>exitVoid)));else if(residual.length+results.length===target){let exits=collectExits(),requests=residual.map((blocked2)=>blocked2.effect_instruction_i0).reduce(par);resume2(succeed(blocked(requests,forEachConcurrentDiscard([getOrElse(exitCollectAll(exits,{parallel:!0}),()=>exitVoid),...residual.map((blocked2)=>blocked2.effect_instruction_i1)],(i)=>i,batching,!0,n))))}else next()})}};for(let i=0;i<fibersCount;i++)next()}));return asVoid(onExit(flatten6(restore(join2(processingFiber))),exitMatch({onFailure:(cause2)=>{onInterruptSignal();let target2=residual.length+1,concurrency=Math.min(typeof n==="number"?n:residual.length,residual.length),toPop=Array.from(residual);return async_((cb)=>{let exits=[],count=0,index=0,check=(index2,hitNext)=>(exit2)=>{if(exits[index2]=exit2,count++,count===target2)cb(exitSucceed(exitFailCause(cause2)));if(toPop.length>0&&hitNext)next()},next=()=>{runFiber(toPop.pop(),!0).addObserver(check(index,!0)),index++};processingFiber.addObserver(check(index,!1)),index++;for(let i=0;i<concurrency;i++)next()})},onSuccess:()=>forEachSequential(joinOrder,(f2)=>f2.inheritAll)})))}))),forEachParN=(self,n,f,batching)=>suspend(()=>{let as2=fromIterable(self),array4=new Array(as2.length);return zipRight(forEachConcurrentDiscard(as2,(a,i)=>map10(f(a,i),(b)=>array4[i]=b),batching,!1,n),succeed(array4))}),fork=(self)=>withFiberRuntime((state,status2)=>succeed(unsafeFork(self,state,status2.runtimeFlags))),forkDaemon=(self)=>forkWithScopeOverride(self,globalScope),forkWithErrorHandler=dual(2,(self,handler)=>fork(onError(self,(cause2)=>{let either3=failureOrCause(cause2);switch(either3._tag){case"Left":return handler(either3.left);case"Right":return failCause(either3.right)}}))),unsafeFork=(effect,parentFiber,parentRuntimeFlags,overrideScope=null)=>{let childFiber=unsafeMakeChildFiber(effect,parentFiber,parentRuntimeFlags,overrideScope);return childFiber.resume(effect),childFiber},unsafeForkUnstarted=(effect,parentFiber,parentRuntimeFlags,overrideScope=null)=>{return unsafeMakeChildFiber(effect,parentFiber,parentRuntimeFlags,overrideScope)},unsafeMakeChildFiber=(effect,parentFiber,parentRuntimeFlags,overrideScope=null)=>{let childId=unsafeMake2(),parentFiberRefs=parentFiber.getFiberRefs(),childFiberRefs=forkAs(parentFiberRefs,childId),childFiber=new FiberRuntime(childId,childFiberRefs,parentRuntimeFlags),childContext=getOrDefault(childFiberRefs,currentContext),supervisor=childFiber.currentSupervisor;return supervisor.onStart(childContext,effect,some2(parentFiber),childFiber),childFiber.addObserver((exit2)=>supervisor.onEnd(exit2,childFiber)),(overrideScope!==null?overrideScope:pipe(parentFiber.getFiberRef(currentForkScopeOverride),getOrElse(()=>parentFiber.scope()))).add(parentRuntimeFlags,childFiber),childFiber},forkWithScopeOverride=(self,scopeOverride)=>withFiberRuntime((parentFiber,parentStatus)=>succeed(unsafeFork(self,parentFiber,parentStatus.runtimeFlags,scopeOverride))),mergeAll2=dual((args2)=>isFunction2(args2[2]),(elements,zero3,f,options)=>matchSimple(options?.concurrency,()=>fromIterable(elements).reduce((acc,a,i)=>zipWith3(acc,a,(acc2,a2)=>f(acc2,a2,i)),succeed(zero3)),()=>flatMap8(make29(zero3),(acc)=>flatMap8(forEach7(elements,(effect,i)=>flatMap8(effect,(a)=>update3(acc,(b)=>f(b,a,i))),options),()=>get12(acc))))),partition3=dual((args2)=>isIterable(args2[0]),(elements,f,options)=>pipe(forEach7(elements,(a,i)=>either2(f(a,i)),options),map10((chunk2)=>partitionMap2(chunk2,identity)))),validateAll=dual((args2)=>isIterable(args2[0]),(elements,f,options)=>flatMap8(partition3(elements,f,{concurrency:options?.concurrency,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),([es,bs])=>isNonEmptyArray2(es)?fail2(es):options?.discard?void_:succeed(bs))),raceAll=(all5)=>{let list=fromIterable2(all5);if(!isNonEmpty2(list))return dieSync(()=>new IllegalArgumentException("Received an empty collection of effects"));let self=headNonEmpty2(list),effects=tailNonEmpty2(list),inheritAll2=(res)=>pipe(inheritAll(res[1]),as(res[0]));return pipe(deferredMake(),flatMap8((done6)=>pipe(make29(effects.length),flatMap8((fails)=>uninterruptibleMask((restore)=>pipe(fork(interruptible2(self)),flatMap8((head4)=>pipe(effects,forEachSequential((effect)=>fork(interruptible2(effect))),map10((fibers)=>unsafeFromArray(fibers)),map10((tail)=>pipe(tail,prepend2(head4))),tap((fibers)=>pipe(fibers,reduce(void_,(effect,fiber)=>pipe(effect,zipRight(pipe(_await2(fiber),flatMap8(raceAllArbiter(fibers,fiber,done6,fails)),fork,asVoid)))))),flatMap8((fibers)=>pipe(restore(pipe(_await(done6),flatMap8(inheritAll2))),onInterrupt(()=>pipe(fibers,reduce(void_,(effect,fiber)=>pipe(effect,zipLeft(interruptFiber(fiber))))))))))))))))},raceAllArbiter=(fibers,winner,deferred,fails)=>(exit2)=>exitMatchEffect(exit2,{onFailure:(cause2)=>pipe(modify3(fails,(fails2)=>[fails2===0?pipe(deferredFailCause(deferred,cause2),asVoid):void_,fails2-1]),flatten6),onSuccess:(value)=>pipe(deferredSucceed(deferred,[value,winner]),flatMap8((set7)=>set7?pipe(fromIterable2(fibers),reduce(void_,(effect,fiber)=>fiber===winner?effect:pipe(effect,zipLeft(interruptFiber(fiber))))):void_))}),reduceEffect=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,zero3,f,options)=>matchSimple(options?.concurrency,()=>fromIterable(elements).reduce((acc,a,i)=>zipWith3(acc,a,(acc2,a2)=>f(acc2,a2,i)),zero3),()=>suspend(()=>pipe(mergeAll2([zero3,...elements],none2(),(acc,elem,i)=>{switch(acc._tag){case"None":return some2(elem);case"Some":return some2(f(acc.value,elem,i))}},options),map10((option2)=>{switch(option2._tag){case"None":throw new Error("BUG: Effect.reduceEffect - please report an issue at https://github.com/Effect-TS/effect/issues");case"Some":return option2.value}}))))),parallelFinalizers=(self)=>contextWithEffect((context2)=>match2(getOption2(context2,scopeTag),{onNone:()=>self,onSome:(scope)=>{switch(scope.strategy._tag){case"Parallel":return self;case"Sequential":case"ParallelN":return flatMap8(scopeFork(scope,parallel3),(inner)=>scopeExtend(self,inner))}}})),parallelNFinalizers=(parallelism)=>(self)=>contextWithEffect((context2)=>match2(getOption2(context2,scopeTag),{onNone:()=>self,onSome:(scope)=>{if(scope.strategy._tag==="ParallelN"&&scope.strategy.parallelism===parallelism)return self;return flatMap8(scopeFork(scope,parallelN2(parallelism)),(inner)=>scopeExtend(self,inner))}})),finalizersMask=(strategy)=>(self)=>finalizersMaskInternal(strategy,!0)(self),finalizersMaskInternal=(strategy,concurrentFinalizers)=>(self)=>contextWithEffect((context2)=>match2(getOption2(context2,scopeTag),{onNone:()=>self(identity),onSome:(scope)=>{if(concurrentFinalizers===!0){let patch12=strategy._tag==="Parallel"?parallelFinalizers:strategy._tag==="Sequential"?sequentialFinalizers:parallelNFinalizers(strategy.parallelism);switch(scope.strategy._tag){case"Parallel":return patch12(self(parallelFinalizers));case"Sequential":return patch12(self(sequentialFinalizers));case"ParallelN":return patch12(self(parallelNFinalizers(scope.strategy.parallelism)))}}else return self(identity)}})),scopeWith=(f)=>flatMap8(scopeTag,f),scopedWith=(f)=>flatMap8(scopeMake(),(scope)=>onExit(f(scope),(exit2)=>scope.close(exit2))),scopedEffect=(effect)=>flatMap8(scopeMake(),(scope)=>scopeUse(effect,scope)),sequentialFinalizers=(self)=>contextWithEffect((context2)=>match2(getOption2(context2,scopeTag),{onNone:()=>self,onSome:(scope)=>{switch(scope.strategy._tag){case"Sequential":return self;case"Parallel":case"ParallelN":return flatMap8(scopeFork(scope,sequential3),(inner)=>scopeExtend(self,inner))}}})),tagMetricsScoped=(key,value)=>labelMetricsScoped([make30(key,value)]),labelMetricsScoped=(labels)=>fiberRefLocallyScopedWith(currentMetricLabels,(old)=>union(old,labels)),using=dual(2,(self,use)=>scopedWith((scope)=>flatMap8(scopeExtend(self,scope),use))),validate=dual((args2)=>isEffect(args2[1]),(self,that,options)=>validateWith(self,that,(a,b)=>[a,b],options)),validateWith=dual((args2)=>isEffect(args2[1]),(self,that,f,options)=>flatten6(zipWithOptions(exit(self),exit(that),(ea,eb)=>exitZipWith(ea,eb,{onSuccess:f,onFailure:(ca,cb)=>options?.concurrent?parallel(ca,cb):sequential(ca,cb)}),options)));var validateFirst=dual((args2)=>isIterable(args2[0]),(elements,f,options)=>flip(forEach7(elements,(a,i)=>flip(f(a,i)),options))),withClockScoped=(c)=>fiberRefLocallyScopedWith(currentServices,add2(clockTag,c)),withRandomScoped=(value)=>fiberRefLocallyScopedWith(currentServices,add2(randomTag,value)),withConfigProviderScoped=(provider)=>fiberRefLocallyScopedWith(currentServices,add2(configProviderTag,provider)),withEarlyRelease=(self)=>scopeWith((parent)=>flatMap8(scopeFork(parent,sequential2),(child)=>pipe(self,scopeExtend(child),map10((value)=>[fiberIdWith((fiberId2)=>scopeClose(child,exitInterrupt(fiberId2))),value])))),zipOptions=dual((args2)=>isEffect(args2[1]),(self,that,options)=>zipWithOptions(self,that,(a,b)=>[a,b],options)),zipLeftOptions=dual((args2)=>isEffect(args2[1]),(self,that,options)=>{if(options?.concurrent!==!0&&(options?.batching===void 0||options.batching===!1))return zipLeft(self,that);return zipWithOptions(self,that,(a,_)=>a,options)}),zipRightOptions=dual((args2)=>isEffect(args2[1]),(self,that,options)=>{if(options?.concurrent!==!0&&(options?.batching===void 0||options.batching===!1))return zipRight(self,that);return zipWithOptions(self,that,(_,b)=>b,options)}),zipWithOptions=dual((args2)=>isEffect(args2[1]),(self,that,f,options)=>map10(all4([self,that],{concurrency:options?.concurrent?2:1,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),([a,a2])=>f(a,a2))),withRuntimeFlagsScoped=(update5)=>{if(update5===empty18)return void_;return pipe(runtimeFlags,flatMap8((runtimeFlags2)=>{let updatedRuntimeFlags=patch7(runtimeFlags2,update5),revertRuntimeFlags=diff7(updatedRuntimeFlags,runtimeFlags2);return pipe(updateRuntimeFlags(update5),zipRight(addFinalizer(()=>updateRuntimeFlags(revertRuntimeFlags))),asVoid)}),uninterruptible)},scopeTag=GenericTag("effect/Scope"),scope=scopeTag,scopeUnsafeAddFinalizer=(scope2,fin)=>{if(scope2.state._tag==="Open")scope2.state.finalizers.set({},fin)},ScopeImplProto={[ScopeTypeId]:ScopeTypeId,[CloseableScopeTypeId]:CloseableScopeTypeId,pipe(){return pipeArguments(this,arguments)},fork(strategy){return sync(()=>{let newScope=scopeUnsafeMake(strategy);if(this.state._tag==="Closed")return newScope.state=this.state,newScope;let key={},fin=(exit2)=>newScope.close(exit2);return this.state.finalizers.set(key,fin),scopeUnsafeAddFinalizer(newScope,(_)=>sync(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(key)})),newScope})},close(exit2){return suspend(()=>{if(this.state._tag==="Closed")return void_;let finalizers=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:exit2},finalizers.length===0)return void_;return isSequential(this.strategy)?pipe(forEachSequential(finalizers,(fin)=>exit(fin(exit2))),flatMap8((results)=>pipe(exitCollectAll(results),map2(exitAsVoid),getOrElse(()=>exitVoid)))):isParallel(this.strategy)?pipe(forEachParUnbounded(finalizers,(fin)=>exit(fin(exit2)),!1),flatMap8((results)=>pipe(exitCollectAll(results,{parallel:!0}),map2(exitAsVoid),getOrElse(()=>exitVoid)))):pipe(forEachParN(finalizers,this.strategy.parallelism,(fin)=>exit(fin(exit2)),!1),flatMap8((results)=>pipe(exitCollectAll(results,{parallel:!0}),map2(exitAsVoid),getOrElse(()=>exitVoid))))})},addFinalizer(fin){return suspend(()=>{if(this.state._tag==="Closed")return fin(this.state.exit);return this.state.finalizers.set({},fin),void_})}},scopeUnsafeMake=(strategy=sequential2)=>{let scope2=Object.create(ScopeImplProto);return scope2.strategy=strategy,scope2.state={_tag:"Open",finalizers:new Map},scope2},scopeMake=(strategy=sequential2)=>sync(()=>scopeUnsafeMake(strategy)),scopeExtend=dual(2,(effect,scope2)=>mapInputContext(effect,merge3(make6(scopeTag,scope2)))),scopeUse=dual(2,(effect,scope2)=>pipe(effect,scopeExtend(scope2),onExit((exit2)=>scope2.close(exit2)))),fiberRefUnsafeMakeSupervisor=(initial)=>fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:empty29}),fiberRefLocallyScoped=dual(2,(self,value)=>asVoid(acquireRelease(flatMap8(fiberRefGet(self),(oldValue)=>as(fiberRefSet(self,value),oldValue)),(oldValue)=>fiberRefSet(self,oldValue)))),fiberRefLocallyScopedWith=dual(2,(self,f)=>fiberRefGetWith(self,(a)=>fiberRefLocallyScoped(self,f(a))));var currentRuntimeFlags=fiberRefUnsafeMakeRuntimeFlags(none5),currentSupervisor=fiberRefUnsafeMakeSupervisor(none8),fiberAwaitAll=(fibers)=>forEach7(fibers,_await2),fiberAll=(fibers)=>{return{...CommitPrototype2,commit(){return join2(this)},[FiberTypeId]:fiberVariance2,id:()=>fromIterable(fibers).reduce((id2,fiber)=>combine3(id2,fiber.id()),none4),await:exit(forEachParUnbounded(fibers,(fiber)=>flatten6(fiber.await),!1)),children:map10(forEachParUnbounded(fibers,(fiber)=>fiber.children,!1),flatten),inheritAll:forEachSequentialDiscard(fibers,(fiber)=>fiber.inheritAll),poll:map10(forEachSequential(fibers,(fiber)=>fiber.poll),reduceRight(some2(exitSucceed(new Array)),(optionB,optionA)=>{switch(optionA._tag){case"None":return none2();case"Some":switch(optionB._tag){case"None":return none2();case"Some":return some2(exitZipWith(optionA.value,optionB.value,{onSuccess:(a,chunk2)=>[a,...chunk2],onFailure:parallel}))}}})),interruptAsFork:(fiberId2)=>forEachSequentialDiscard(fibers,(fiber)=>fiber.interruptAsFork(fiberId2))}},fiberInterruptFork=(self)=>asVoid(forkDaemon(interruptFiber(self))),fiberJoinAll=(fibers)=>join2(fiberAll(fibers)),fiberScoped=(self)=>acquireRelease(succeed(self),interruptFiber),raceWith=dual(3,(self,other,options)=>raceFibersWith(self,other,{onSelfWin:(winner,loser)=>flatMap8(winner.await,(exit2)=>{switch(exit2._tag){case OP_SUCCESS:return flatMap8(winner.inheritAll,()=>options.onSelfDone(exit2,loser));case OP_FAILURE:return options.onSelfDone(exit2,loser)}}),onOtherWin:(winner,loser)=>flatMap8(winner.await,(exit2)=>{switch(exit2._tag){case OP_SUCCESS:return flatMap8(winner.inheritAll,()=>options.onOtherDone(exit2,loser));case OP_FAILURE:return options.onOtherDone(exit2,loser)}})})),disconnect=(self)=>uninterruptibleMask((restore)=>fiberIdWith((fiberId2)=>flatMap8(forkDaemon(restore(self)),(fiber)=>pipe(restore(join2(fiber)),onInterrupt(()=>pipe(fiber,interruptAsFork(fiberId2))))))),race=dual(2,(self,that)=>fiberIdWith((parentFiberId)=>raceWith(self,that,{onSelfDone:(exit2,right3)=>exitMatchEffect(exit2,{onFailure:(cause2)=>pipe(join2(right3),mapErrorCause((cause22)=>parallel(cause2,cause22))),onSuccess:(value)=>pipe(right3,interruptAsFiber(parentFiberId),as(value))}),onOtherDone:(exit2,left3)=>exitMatchEffect(exit2,{onFailure:(cause2)=>pipe(join2(left3),mapErrorCause((cause22)=>parallel(cause22,cause2))),onSuccess:(value)=>pipe(left3,interruptAsFiber(parentFiberId),as(value))})}))),raceFibersWith=dual(3,(self,other,options)=>withFiberRuntime((parentFiber,parentStatus)=>{let parentRuntimeFlags=parentStatus.runtimeFlags,raceIndicator=make12(!0),leftFiber=unsafeMakeChildFiber(self,parentFiber,parentRuntimeFlags,options.selfScope),rightFiber=unsafeMakeChildFiber(other,parentFiber,parentRuntimeFlags,options.otherScope);return async_((cb)=>{leftFiber.addObserver(()=>completeRace(leftFiber,rightFiber,options.onSelfWin,raceIndicator,cb)),rightFiber.addObserver(()=>completeRace(rightFiber,leftFiber,options.onOtherWin,raceIndicator,cb)),leftFiber.startFork(self),rightFiber.startFork(other)},combine3(leftFiber.id(),rightFiber.id()))})),completeRace=(winner,loser,cont,ab,cb)=>{if(compareAndSet(!0,!1)(ab))cb(cont(winner,loser))},ensuring=dual(2,(self,finalizer)=>uninterruptibleMask((restore)=>matchCauseEffect(restore(self),{onFailure:(cause1)=>matchCauseEffect(finalizer,{onFailure:(cause2)=>failCause(sequential(cause1,cause2)),onSuccess:()=>failCause(cause1)}),onSuccess:(a)=>as(finalizer,a)}))),invokeWithInterrupt=(self,entries2,onInterrupt2)=>fiberIdWith((id2)=>flatMap8(flatMap8(forkDaemon(interruptible2(self)),(processing)=>async_((cb)=>{let counts=entries2.map((_)=>_.listeners.count),checkDone=()=>{if(counts.every((count)=>count===0)){if(entries2.every((_)=>{if(_.result.state.current._tag==="Pending")return!0;else if(_.result.state.current._tag==="Done"&&exitIsExit(_.result.state.current.effect)&&_.result.state.current.effect._tag==="Failure"&&isInterrupted(_.result.state.current.effect.cause))return!0;else return!1}))cleanup.forEach((f)=>f()),onInterrupt2?.(),cb(interruptFiber(processing))}};processing.addObserver((exit2)=>{cleanup.forEach((f)=>f()),cb(exit2)});let cleanup=entries2.map((r,i)=>{let observer=(count)=>{counts[i]=count,checkDone()};return r.listeners.addObserver(observer),()=>r.listeners.removeObserver(observer)});return checkDone(),sync(()=>{cleanup.forEach((f)=>f())})})),()=>suspend(()=>{let residual=entries2.flatMap((entry)=>{if(!entry.state.completed)return[entry];return[]});return forEachSequentialDiscard(residual,(entry)=>complete(entry.request,exitInterrupt(id2)))})));var makeSpanScoped=(name,options)=>{return options=addSpanStackTrace(options),uninterruptible(withFiberRuntime((fiber)=>{let scope2=unsafeGet3(fiber.getFiberRef(currentContext),scopeTag),span2=unsafeMakeSpan(fiber,name,options),timingEnabled=fiber.getFiberRef(currentTracerTimingEnabled),clock_=get3(fiber.getFiberRef(currentServices),clockTag);return as(scopeAddFinalizerExit(scope2,(exit2)=>endSpan(span2,exit2,clock_,timingEnabled)),span2)}))},withTracerScoped=(value)=>fiberRefLocallyScopedWith(currentServices,add2(tracerTag,value)),withSpanScoped=function(){let dataFirst=typeof arguments[0]!=="string",name=dataFirst?arguments[1]:arguments[0],options=addSpanStackTrace(dataFirst?arguments[2]:arguments[1]);if(dataFirst){let self=arguments[0];return flatMap8(makeSpanScoped(name,addSpanStackTrace(options)),(span2)=>provideService(self,spanTag,span2))}return(self)=>flatMap8(makeSpanScoped(name,addSpanStackTrace(options)),(span2)=>provideService(self,spanTag,span2))};var complete2=(key,exit2,entryStats,timeToLiveMillis)=>struct({_tag:"Complete",key,exit:exit2,entryStats,timeToLiveMillis}),pending2=(key,deferred)=>struct({_tag:"Pending",key,deferred}),refreshing=(deferred,complete3)=>struct({_tag:"Refreshing",deferred,complete:complete3}),MapKeyTypeId=Symbol.for("effect/Cache/MapKey");class MapKeyImpl{current;[MapKeyTypeId]=MapKeyTypeId;previous=void 0;next=void 0;constructor(current){this.current=current}[symbol](){return pipe(hash(this.current),combine(hash(this.previous)),combine(hash(this.next)),cached(this))}[symbol2](that){if(this===that)return!0;return isMapKey(that)&&equals(this.current,that.current)&&equals(this.previous,that.previous)&&equals(this.next,that.next)}}var makeMapKey=(current)=>new MapKeyImpl(current),isMapKey=(u)=>hasProperty(u,MapKeyTypeId);class KeySetImpl{head=void 0;tail=void 0;add(key){if(key!==this.tail)if(this.tail===void 0)this.head=key,this.tail=key;else{let{previous,next}=key;if(next!==void 0)if(key.next=void 0,previous!==void 0)previous.next=next,next.previous=previous;else this.head=next,this.head.previous=void 0;this.tail.next=key,key.previous=this.tail,this.tail=key}}remove(){let key=this.head;if(key!==void 0){let next=key.next;if(next!==void 0)key.next=void 0,this.head=next,this.head.previous=void 0;else this.head=void 0,this.tail=void 0}return key}}var makeKeySet=()=>new KeySetImpl,makeCacheState=(map13,keys5,accesses,updating,hits,misses)=>({map:map13,keys:keys5,accesses,updating,hits,misses}),initialCacheState=()=>makeCacheState(empty21(),makeKeySet(),unbounded(),make12(!1),0,0),CacheSymbolKey="effect/Cache",CacheTypeId=Symbol.for(CacheSymbolKey),cacheVariance={_Key:(_)=>_,_Error:(_)=>_,_Value:(_)=>_},ConsumerCacheSymbolKey="effect/ConsumerCache",ConsumerCacheTypeId=Symbol.for(ConsumerCacheSymbolKey),consumerCacheVariance={_Key:(_)=>_,_Error:(_)=>_,_Value:(_)=>_},makeCacheStats=(options)=>options,makeEntryStats=(loadedMillis)=>({loadedMillis});class CacheImpl{capacity;context;fiberId;lookup;timeToLive;[CacheTypeId]=cacheVariance;[ConsumerCacheTypeId]=consumerCacheVariance;cacheState;constructor(capacity2,context2,fiberId2,lookup,timeToLive){this.capacity=capacity2,this.context=context2,this.fiberId=fiberId2,this.lookup=lookup,this.timeToLive=timeToLive,this.cacheState=initialCacheState()}get(key){return map10(this.getEither(key),merge)}get cacheStats(){return sync(()=>makeCacheStats({hits:this.cacheState.hits,misses:this.cacheState.misses,size:size4(this.cacheState.map)}))}getOption(key){return suspend(()=>match2(get8(this.cacheState.map,key),{onNone:()=>{let mapKey=makeMapKey(key);return this.trackAccess(mapKey),this.trackMiss(),succeed(none2())},onSome:(value)=>this.resolveMapValue(value)}))}getOptionComplete(key){return suspend(()=>match2(get8(this.cacheState.map,key),{onNone:()=>{let mapKey=makeMapKey(key);return this.trackAccess(mapKey),this.trackMiss(),succeed(none2())},onSome:(value)=>this.resolveMapValue(value,!0)}))}contains(key){return sync(()=>has4(this.cacheState.map,key))}entryStats(key){return sync(()=>{let option2=get8(this.cacheState.map,key);if(isSome2(option2))switch(option2.value._tag){case"Complete":{let loaded=option2.value.entryStats.loadedMillis;return some2(makeEntryStats(loaded))}case"Pending":return none2();case"Refreshing":{let loaded=option2.value.complete.entryStats.loadedMillis;return some2(makeEntryStats(loaded))}}return none2()})}getEither(key){return suspend(()=>{let k=key,mapKey=void 0,deferred=void 0,value=getOrUndefined(get8(this.cacheState.map,k));if(value===void 0)if(deferred=unsafeMake3(this.fiberId),mapKey=makeMapKey(k),has4(this.cacheState.map,k))value=getOrUndefined(get8(this.cacheState.map,k));else set4(this.cacheState.map,k,pending2(mapKey,deferred));if(value===void 0)return this.trackAccess(mapKey),this.trackMiss(),map10(this.lookupValueOf(key,deferred),right2);else return flatMap8(this.resolveMapValue(value),match2({onNone:()=>this.getEither(key),onSome:(value2)=>succeed(left2(value2))}))})}invalidate(key){return sync(()=>{remove6(this.cacheState.map,key)})}invalidateWhen(key,when2){return sync(()=>{let value=get8(this.cacheState.map,key);if(isSome2(value)&&value.value._tag==="Complete"){if(value.value.exit._tag==="Success"){if(when2(value.value.exit.value))remove6(this.cacheState.map,key)}}})}get invalidateAll(){return sync(()=>{this.cacheState.map=empty21()})}refresh(key){return clockWith3((clock2)=>suspend(()=>{let k=key,deferred=unsafeMake3(this.fiberId),value=getOrUndefined(get8(this.cacheState.map,k));if(value===void 0)if(has4(this.cacheState.map,k))value=getOrUndefined(get8(this.cacheState.map,k));else set4(this.cacheState.map,k,pending2(makeMapKey(k),deferred));if(value===void 0)return asVoid(this.lookupValueOf(key,deferred));else switch(value._tag){case"Complete":{if(this.hasExpired(clock2,value.timeToLiveMillis)){let found=getOrUndefined(get8(this.cacheState.map,k));if(equals(found,value))remove6(this.cacheState.map,k);return asVoid(this.get(key))}return pipe(this.lookupValueOf(key,deferred),when(()=>{let current=getOrUndefined(get8(this.cacheState.map,k));if(equals(current,value)){let mapValue=refreshing(deferred,value);return set4(this.cacheState.map,k,mapValue),!0}return!1}),asVoid)}case"Pending":return _await(value.deferred);case"Refreshing":return _await(value.deferred)}}))}set(key,value){return clockWith3((clock2)=>sync(()=>{let now=clock2.unsafeCurrentTimeMillis(),k=key,lookupResult=succeed3(value),mapValue=complete2(makeMapKey(k),lookupResult,makeEntryStats(now),now+toMillis(decode(this.timeToLive(lookupResult))));set4(this.cacheState.map,k,mapValue)}))}get size(){return sync(()=>{return size4(this.cacheState.map)})}get values(){return sync(()=>{let values3=[];for(let entry of this.cacheState.map)if(entry[1]._tag==="Complete"&&entry[1].exit._tag==="Success")values3.push(entry[1].exit.value);return values3})}get entries(){return sync(()=>{let values3=[];for(let entry of this.cacheState.map)if(entry[1]._tag==="Complete"&&entry[1].exit._tag==="Success")values3.push([entry[0],entry[1].exit.value]);return values3})}get keys(){return sync(()=>{let keys5=[];for(let entry of this.cacheState.map)if(entry[1]._tag==="Complete"&&entry[1].exit._tag==="Success")keys5.push(entry[0]);return keys5})}resolveMapValue(value,ignorePending=!1){return clockWith3((clock2)=>{switch(value._tag){case"Complete":{if(this.trackAccess(value.key),this.hasExpired(clock2,value.timeToLiveMillis))return remove6(this.cacheState.map,value.key.current),succeed(none2());return this.trackHit(),map10(value.exit,some2)}case"Pending":{if(this.trackAccess(value.key),this.trackHit(),ignorePending)return succeed(none2());return map10(_await(value.deferred),some2)}case"Refreshing":{if(this.trackAccess(value.complete.key),this.trackHit(),this.hasExpired(clock2,value.complete.timeToLiveMillis)){if(ignorePending)return succeed(none2());return map10(_await(value.deferred),some2)}return map10(value.complete.exit,some2)}}})}trackHit(){this.cacheState.hits=this.cacheState.hits+1}trackMiss(){this.cacheState.misses=this.cacheState.misses+1}trackAccess(key){if(offer(this.cacheState.accesses,key),compareAndSet(this.cacheState.updating,!1,!0)){let loop2=!0;while(loop2){let key2=poll2(this.cacheState.accesses,EmptyMutableQueue);if(key2===EmptyMutableQueue)loop2=!1;else this.cacheState.keys.add(key2)}let size8=size4(this.cacheState.map);loop2=size8>this.capacity;while(loop2){let key2=this.cacheState.keys.remove();if(key2!==void 0){if(has4(this.cacheState.map,key2.current))remove6(this.cacheState.map,key2.current),size8=size8-1,loop2=size8>this.capacity}else loop2=!1}set2(this.cacheState.updating,!1)}}hasExpired(clock2,timeToLiveMillis){return clock2.unsafeCurrentTimeMillis()>timeToLiveMillis}lookupValueOf(input,deferred){return clockWith3((clock2)=>suspend(()=>{let key=input;return pipe(this.lookup(input),provideContext(this.context),exit,flatMap8((exit2)=>{let now=clock2.unsafeCurrentTimeMillis(),stats=makeEntryStats(now),value=complete2(makeMapKey(key),exit2,stats,now+toMillis(decode(this.timeToLive(exit2))));return set4(this.cacheState.map,key,value),zipRight(done2(deferred,exit2),exit2)}),onInterrupt(()=>zipRight(interrupt3(deferred),sync(()=>{remove6(this.cacheState.map,key)}))))}))}}var unsafeMakeWith=(capacity2,lookup,timeToLive)=>new CacheImpl(capacity2,empty4(),none3,lookup,(exit2)=>decode(timeToLive(exit2)));var fail6=fail,die4=die,interrupt5=interrupt;var isFailType2=isFailType,isDieType2=isDieType;var isInterrupted2=isInterrupted,isInterruptedOnly2=isInterruptedOnly;var interruptors2=interruptors;var failureOrCause2=failureOrCause,flipCauseOption2=flipCauseOption;var map13=map9;var squash=causeSquash;var IllegalArgumentException2=IllegalArgumentException;var NoSuchElementException2=NoSuchElementException;var RuntimeException2=RuntimeException,isRuntimeException2=isRuntimeException;var pretty3=pretty;var exports_Effect={};__export(exports_Effect,{zipWith:()=>zipWith8,zipRight:()=>zipRight4,zipLeft:()=>zipLeft3,zip:()=>zip6,yieldNow:()=>yieldNow4,withUnhandledErrorLogLevel:()=>withUnhandledErrorLogLevel2,withTracerTiming:()=>withTracerTiming2,withTracerScoped:()=>withTracerScoped2,withTracerEnabled:()=>withTracerEnabled2,withTracer:()=>withTracer2,withSpanScoped:()=>withSpanScoped2,withSpan:()=>withSpan2,withSchedulingPriority:()=>withSchedulingPriority2,withScheduler:()=>withScheduler2,withRuntimeFlagsPatchScoped:()=>withRuntimeFlagsPatchScoped,withRuntimeFlagsPatch:()=>withRuntimeFlagsPatch,withRequestCaching:()=>withRequestCaching2,withRequestCache:()=>withRequestCache2,withRequestBatching:()=>withRequestBatching2,withRandomScoped:()=>withRandomScoped2,withRandom:()=>withRandom2,withParentSpan:()=>withParentSpan2,withMetric:()=>withMetric2,withMaxOpsBeforeYield:()=>withMaxOpsBeforeYield2,withLogSpan:()=>withLogSpan2,withFiberRuntime:()=>withFiberRuntime2,withEarlyRelease:()=>withEarlyRelease2,withConsoleScoped:()=>withConsoleScoped2,withConsole:()=>withConsole2,withConfigProviderScoped:()=>withConfigProviderScoped2,withConfigProvider:()=>withConfigProvider2,withConcurrency:()=>withConcurrency2,withClockScoped:()=>withClockScoped2,withClock:()=>withClock2,whileLoop:()=>whileLoop2,whenRef:()=>whenRef2,whenLogLevel:()=>whenLogLevel2,whenFiberRef:()=>whenFiberRef2,whenEffect:()=>whenEffect2,when:()=>when2,void:()=>_void,validateWith:()=>validateWith2,validateFirst:()=>validateFirst2,validateAll:()=>validateAll2,validate:()=>validate2,using:()=>using2,useSpan:()=>useSpan2,updateService:()=>updateService2,updateFiberRefs:()=>updateFiberRefs2,unsandbox:()=>unsandbox2,unsafeMakeSemaphore:()=>unsafeMakeSemaphore2,unsafeMakeLatch:()=>unsafeMakeLatch2,unlessEffect:()=>unlessEffect2,unless:()=>unless2,uninterruptibleMask:()=>uninterruptibleMask3,uninterruptible:()=>uninterruptible2,tryPromise:()=>tryPromise2,tryMapPromise:()=>tryMapPromise2,tryMap:()=>tryMap2,try:()=>try_2,transposeOption:()=>transposeOption,transposeMapOption:()=>transposeMapOption,transplant:()=>transplant2,tracerWith:()=>tracerWith4,tracer:()=>tracer2,timeoutTo:()=>timeoutTo2,timeoutOption:()=>timeoutOption2,timeoutFailCause:()=>timeoutFailCause2,timeoutFail:()=>timeoutFail2,timeout:()=>timeout2,timedWith:()=>timedWith2,timed:()=>timed2,tapErrorTag:()=>tapErrorTag2,tapErrorCause:()=>tapErrorCause2,tapError:()=>tapError2,tapDefect:()=>tapDefect2,tapBoth:()=>tapBoth2,tap:()=>tap2,takeWhile:()=>takeWhile3,takeUntil:()=>takeUntil2,tagMetricsScoped:()=>tagMetricsScoped2,tagMetrics:()=>tagMetrics2,sync:()=>sync3,suspend:()=>suspend3,supervised:()=>supervised2,summarized:()=>summarized2,succeedSome:()=>succeedSome2,succeedNone:()=>succeedNone2,succeed:()=>succeed9,step:()=>step3,spanLinks:()=>spanLinks2,spanAnnotations:()=>spanAnnotations2,sleep:()=>sleep4,setFiberRefs:()=>setFiberRefs2,serviceOptional:()=>serviceOptional2,serviceOption:()=>serviceOption2,serviceMembers:()=>serviceMembers2,serviceFunctions:()=>serviceFunctions2,serviceFunctionEffect:()=>serviceFunctionEffect2,serviceFunction:()=>serviceFunction2,serviceConstants:()=>serviceConstants2,sequentialFinalizers:()=>sequentialFinalizers2,scopedWith:()=>scopedWith2,scoped:()=>scoped3,scopeWith:()=>scopeWith2,scope:()=>scope2,scheduleFrom:()=>scheduleFrom,scheduleForked:()=>scheduleForked2,schedule:()=>schedule,sandbox:()=>sandbox2,runtime:()=>runtime3,runSyncExit:()=>runSyncExit,runSync:()=>runSync,runRequestBlock:()=>runRequestBlock2,runPromiseExit:()=>runPromiseExit,runPromise:()=>runPromise,runFork:()=>runFork2,runCallback:()=>runCallback,retryOrElse:()=>retryOrElse,retry:()=>retry,request:()=>request,replicateEffect:()=>replicateEffect2,replicate:()=>replicate2,repeatOrElse:()=>repeatOrElse,repeatN:()=>repeatN2,repeat:()=>repeat,reduceWhile:()=>reduceWhile2,reduceRight:()=>reduceRight4,reduceEffect:()=>reduceEffect2,reduce:()=>reduce13,randomWith:()=>randomWith2,random:()=>random3,raceWith:()=>raceWith2,raceFirst:()=>raceFirst2,raceAll:()=>raceAll2,race:()=>race2,provideServiceEffect:()=>provideServiceEffect2,provideService:()=>provideService2,provide:()=>provide2,promise:()=>promise2,patchRuntimeFlags:()=>patchRuntimeFlags,patchFiberRefs:()=>patchFiberRefs2,partition:()=>partition4,parallelFinalizers:()=>parallelFinalizers2,parallelErrors:()=>parallelErrors2,orElseSucceed:()=>orElseSucceed2,orElseFail:()=>orElseFail2,orElse:()=>orElse5,orDieWith:()=>orDieWith2,orDie:()=>orDie2,optionFromOptional:()=>optionFromOptional2,option:()=>option2,once:()=>once2,onInterrupt:()=>onInterrupt2,onExit:()=>onExit3,onError:()=>onError2,none:()=>none9,never:()=>never4,negate:()=>negate2,metricLabels:()=>metricLabels2,mergeAll:()=>mergeAll4,merge:()=>merge7,matchEffect:()=>matchEffect2,matchCauseEffect:()=>matchCauseEffect3,matchCause:()=>matchCause2,match:()=>match13,mapInputContext:()=>mapInputContext2,mapErrorCause:()=>mapErrorCause2,mapError:()=>mapError2,mapBoth:()=>mapBoth3,mapAccum:()=>mapAccum4,map:()=>map16,makeSpanScoped:()=>makeSpanScoped2,makeSpan:()=>makeSpan2,makeSemaphore:()=>makeSemaphore2,makeLatch:()=>makeLatch2,loop:()=>loop2,logWithLevel:()=>logWithLevel2,logWarning:()=>logWarning2,logTrace:()=>logTrace2,logInfo:()=>logInfo2,logFatal:()=>logFatal2,logError:()=>logError2,logDebug:()=>logDebug2,logAnnotations:()=>logAnnotations2,log:()=>log2,locallyWith:()=>locallyWith,locallyScopedWith:()=>locallyScopedWith,locallyScoped:()=>locallyScoped,locally:()=>locally,linkSpans:()=>linkSpans2,linkSpanCurrent:()=>linkSpanCurrent2,liftPredicate:()=>liftPredicate2,let:()=>let_3,labelMetricsScoped:()=>labelMetricsScoped2,labelMetrics:()=>labelMetrics2,iterate:()=>iterate2,isSuccess:()=>isSuccess3,isFailure:()=>isFailure4,isEffect:()=>isEffect2,intoDeferred:()=>intoDeferred2,interruptibleMask:()=>interruptibleMask2,interruptible:()=>interruptible4,interruptWith:()=>interruptWith2,interrupt:()=>interrupt7,inheritFiberRefs:()=>inheritFiberRefs2,ignoreLogged:()=>ignoreLogged2,ignore:()=>ignore2,if:()=>if_2,head:()=>head4,getRuntimeFlags:()=>getRuntimeFlags,getFiberRefs:()=>getFiberRefs,gen:()=>gen2,functionWithSpan:()=>functionWithSpan2,fromNullable:()=>fromNullable3,fromFiberEffect:()=>fromFiberEffect2,fromFiber:()=>fromFiber2,forkWithErrorHandler:()=>forkWithErrorHandler2,forkScoped:()=>forkScoped2,forkIn:()=>forkIn2,forkDaemon:()=>forkDaemon2,forkAll:()=>forkAll2,fork:()=>fork3,forever:()=>forever3,forEach:()=>forEach8,fnUntraced:()=>fnUntraced2,fn:()=>fn,flipWith:()=>flipWith2,flip:()=>flip2,flatten:()=>flatten8,flatMap:()=>flatMap10,firstSuccessOf:()=>firstSuccessOf2,findFirst:()=>findFirst7,finalizersMask:()=>finalizersMask2,filterOrFail:()=>filterOrFail2,filterOrElse:()=>filterOrElse2,filterOrDieMessage:()=>filterOrDieMessage2,filterOrDie:()=>filterOrDie2,filterMap:()=>filterMap5,filterEffectOrFail:()=>filterEffectOrFail2,filterEffectOrElse:()=>filterEffectOrElse2,filter:()=>filter8,fiberIdWith:()=>fiberIdWith2,fiberId:()=>fiberId2,failSync:()=>failSync2,failCauseSync:()=>failCauseSync2,failCause:()=>failCause8,fail:()=>fail9,exit:()=>exit2,exists:()=>exists3,every:()=>every6,eventually:()=>eventually2,ensuringChildren:()=>ensuringChildren2,ensuringChild:()=>ensuringChild2,ensuring:()=>ensuring2,either:()=>either3,dropWhile:()=>dropWhile3,dropUntil:()=>dropUntil2,disconnect:()=>disconnect2,diffFiberRefs:()=>diffFiberRefs2,dieSync:()=>dieSync2,dieMessage:()=>dieMessage2,die:()=>die5,descriptorWith:()=>descriptorWith2,descriptor:()=>descriptor2,delay:()=>delay2,daemonChildren:()=>daemonChildren2,custom:()=>custom2,currentSpan:()=>currentSpan2,currentParentSpan:()=>currentParentSpan2,contextWithEffect:()=>contextWithEffect2,contextWith:()=>contextWith2,context:()=>context3,consoleWith:()=>consoleWith2,console:()=>console3,configProviderWith:()=>configProviderWith2,clockWith:()=>clockWith4,clock:()=>clock2,checkInterruptible:()=>checkInterruptible2,cause:()=>cause2,catchTags:()=>catchTags2,catchTag:()=>catchTag2,catchSomeDefect:()=>catchSomeDefect2,catchSomeCause:()=>catchSomeCause2,catchSome:()=>catchSome2,catchIf:()=>catchIf2,catchAllDefect:()=>catchAllDefect2,catchAllCause:()=>catchAllCause2,catchAll:()=>catchAll2,catch:()=>_catch2,cachedWithTTL:()=>cachedWithTTL,cachedInvalidateWithTTL:()=>cachedInvalidateWithTTL2,cachedFunction:()=>cachedFunction2,cached:()=>cached3,cacheRequestResult:()=>cacheRequestResult,blocked:()=>blocked2,bindTo:()=>bindTo3,bindAll:()=>bindAll2,bind:()=>bind3,awaitAllChildren:()=>awaitAllChildren2,asyncEffect:()=>asyncEffect2,async:()=>async,asVoid:()=>asVoid2,asSomeError:()=>asSomeError2,asSome:()=>asSome2,as:()=>as3,ap:()=>ap,annotateSpans:()=>annotateSpans2,annotateLogsScoped:()=>annotateLogsScoped2,annotateLogs:()=>annotateLogs2,annotateCurrentSpan:()=>annotateCurrentSpan2,andThen:()=>andThen4,allowInterrupt:()=>allowInterrupt2,allWith:()=>allWith2,allSuccesses:()=>allSuccesses2,all:()=>all7,addFinalizer:()=>addFinalizer3,acquireUseRelease:()=>acquireUseRelease2,acquireReleaseInterruptible:()=>acquireReleaseInterruptible2,acquireRelease:()=>acquireRelease2,Tag:()=>Tag2,Service:()=>Service,EffectTypeId:()=>EffectTypeId3,Do:()=>Do2});var IntervalSymbolKey="effect/ScheduleInterval",IntervalTypeId=Symbol.for(IntervalSymbolKey),empty30={[IntervalTypeId]:IntervalTypeId,startMillis:0,endMillis:0},make37=(startMillis,endMillis)=>{if(startMillis>endMillis)return empty30;return{[IntervalTypeId]:IntervalTypeId,startMillis,endMillis}},lessThan3=dual(2,(self,that)=>min3(self,that)===self),min3=dual(2,(self,that)=>{if(self.endMillis<=that.startMillis)return self;if(that.endMillis<=self.startMillis)return that;if(self.startMillis<that.startMillis)return self;if(that.startMillis<self.startMillis)return that;if(self.endMillis<=that.endMillis)return self;return that});var isEmpty8=(self)=>{return self.startMillis>=self.endMillis};var intersect=dual(2,(self,that)=>{let start=Math.max(self.startMillis,that.startMillis),end=Math.min(self.endMillis,that.endMillis);return make37(start,end)}),size9=(self)=>{return millis(self.endMillis-self.startMillis)};var after=(startMilliseconds)=>{return make37(startMilliseconds,Number.POSITIVE_INFINITY)};var make38=make37,empty31=empty30,lessThan4=lessThan3;var isEmpty9=isEmpty8;var intersect2=intersect,size10=size9;var after2=after;var IntervalsSymbolKey="effect/ScheduleIntervals",IntervalsTypeId=Symbol.for(IntervalsSymbolKey),make39=(intervals)=>{return{[IntervalsTypeId]:IntervalsTypeId,intervals}};var intersect3=dual(2,(self,that)=>intersectLoop(self.intervals,that.intervals,empty5())),intersectLoop=(_left,_right,_acc)=>{let left3=_left,right3=_right,acc=_acc;while(isNonEmpty2(left3)&&isNonEmpty2(right3)){let interval=pipe(headNonEmpty2(left3),intersect2(headNonEmpty2(right3))),intervals=isEmpty9(interval)?acc:pipe(acc,prepend2(interval));if(pipe(headNonEmpty2(left3),lessThan4(headNonEmpty2(right3))))left3=tailNonEmpty2(left3);else right3=tailNonEmpty2(right3);acc=intervals}return make39(reverse2(acc))},start=(self)=>{return pipe(self.intervals,head2,getOrElse(()=>empty31)).startMillis},end=(self)=>{return pipe(self.intervals,head2,getOrElse(()=>empty31)).endMillis},lessThan5=dual(2,(self,that)=>start(self)<start(that)),isNonEmpty4=(self)=>{return isNonEmpty2(self.intervals)};var make40=make39;var intersect4=intersect3,start2=start,end2=end,lessThan6=lessThan5,isNonEmpty5=isNonEmpty4;var OP_CONTINUE="Continue",OP_DONE2="Done",_continue=(intervals)=>{return{_tag:OP_CONTINUE,intervals}},continueWith=(interval)=>{return{_tag:OP_CONTINUE,intervals:make40(of2(interval))}},done6={_tag:OP_DONE2},isContinue=(self)=>{return self._tag===OP_CONTINUE},isDone4=(self)=>{return self._tag===OP_DONE2};var _continue2=_continue;var continueWith2=continueWith,done7=done6,isContinue2=isContinue,isDone5=isDone4;var addFinalizer2=scopeAddFinalizer,addFinalizerExit=scopeAddFinalizerExit,close=scopeClose,extend2=scopeExtend,fork2=scopeFork;var make41=scopeMake;var Error3=function(){let plainArgsSymbol=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends YieldableError{constructor(args2){super(args2?.message,args2?.cause?{cause:args2.cause}:void 0);if(args2)Object.assign(this,args2),Object.defineProperty(this,plainArgsSymbol,{value:args2,enumerable:!1})}toJSON(){return{...this[plainArgsSymbol],...this}}}}.BaseEffectError}(),TaggedError=(tag)=>{let O={BaseEffectError:class extends Error3{_tag=tag}};return O.BaseEffectError.prototype.name=tag,O.BaseEffectError};var TypeId16=Symbol.for("effect/DateTime"),TimeZoneTypeId=Symbol.for("effect/DateTime/TimeZone"),Proto2={[TypeId16]:TypeId16,pipe(){return pipeArguments(this,arguments)},[NodeInspectSymbol](){return this.toString()},toJSON(){return toDateUtc(this).toJSON()}},ProtoUtc={...Proto2,_tag:"Utc",[symbol](){return cached(this,number2(this.epochMillis))},[symbol2](that){return isDateTime(that)&&that._tag==="Utc"&&this.epochMillis===that.epochMillis},toString(){return`DateTime.Utc(${toDateUtc(this).toJSON()})`}},ProtoZoned={...Proto2,_tag:"Zoned",[symbol](){return pipe(number2(this.epochMillis),combine(hash(this.zone)),cached(this))},[symbol2](that){return isDateTime(that)&&that._tag==="Zoned"&&this.epochMillis===that.epochMillis&&equals(this.zone,that.zone)},toString(){return`DateTime.Zoned(${formatIsoZoned(this)})`}},ProtoTimeZone={[TimeZoneTypeId]:TimeZoneTypeId,[NodeInspectSymbol](){return this.toString()}},ProtoTimeZoneNamed={...ProtoTimeZone,_tag:"Named",[symbol](){return cached(this,string(`Named:${this.id}`))},[symbol2](that){return isTimeZone(that)&&that._tag==="Named"&&this.id===that.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:"TimeZone",_tag:"Named",id:this.id}}},ProtoTimeZoneOffset={...ProtoTimeZone,_tag:"Offset",[symbol](){return cached(this,string(`Offset:${this.offset}`))},[symbol2](that){return isTimeZone(that)&&that._tag==="Offset"&&this.offset===that.offset},toString(){return`TimeZone.Offset(${offsetToString(this.offset)})`},toJSON(){return{_id:"TimeZone",_tag:"Offset",offset:this.offset}}};var isDateTime=(u)=>hasProperty(u,TypeId16);var isTimeZone=(u)=>hasProperty(u,TimeZoneTypeId);var toDateUtc=(self)=>new Date(self.epochMillis),toDate=(self)=>{if(self._tag==="Utc")return new Date(self.epochMillis);else if(self.zone._tag==="Offset")return new Date(self.epochMillis+self.zone.offset);else if(self.adjustedEpochMillis!==void 0)return new Date(self.adjustedEpochMillis);let parts2=self.zone.format.formatToParts(self.epochMillis).filter((_)=>_.type!=="literal"),date=new Date(0);return date.setUTCFullYear(Number(parts2[2].value),Number(parts2[0].value)-1,Number(parts2[1].value)),date.setUTCHours(Number(parts2[3].value),Number(parts2[4].value),Number(parts2[5].value),Number(parts2[6].value)),self.adjustedEpochMillis=date.getTime(),date},zonedOffset=(self)=>{return toDate(self).getTime()-toEpochMillis(self)},offsetToString=(offset)=>{let abs2=Math.abs(offset),hours2=Math.floor(abs2/3600000),minutes2=Math.round(abs2%3600000/60000);if(minutes2===60)hours2+=1,minutes2=0;return`${offset<0?"-":"+"}${String(hours2).padStart(2,"0")}:${String(minutes2).padStart(2,"0")}`},zonedOffsetIso=(self)=>offsetToString(zonedOffset(self)),toEpochMillis=(self)=>self.epochMillis;var formatIsoOffset=(self)=>{let date=toDate(self);return self._tag==="Utc"?date.toISOString():`${date.toISOString().slice(0,-1)}${zonedOffsetIso(self)}`},formatIsoZoned=(self)=>self.zone._tag==="Offset"?formatIsoOffset(self):`${formatIsoOffset(self)}[${self.zone.id}]`;var TypeId17=Symbol.for("effect/Cron"),CronProto={[TypeId17]:TypeId17,[symbol2](that){return isCron(that)&&equals4(this,that)},[symbol](){return pipe(hash(this.tz),combine(array2(fromIterable(this.seconds))),combine(array2(fromIterable(this.minutes))),combine(array2(fromIterable(this.hours))),combine(array2(fromIterable(this.days))),combine(array2(fromIterable(this.months))),combine(array2(fromIterable(this.weekdays))),cached(this))},toString(){return format(this.toJSON())},toJSON(){return{_id:"Cron",tz:this.tz,seconds:fromIterable(this.seconds),minutes:fromIterable(this.minutes),hours:fromIterable(this.hours),days:fromIterable(this.days),months:fromIterable(this.months),weekdays:fromIterable(this.weekdays)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},isCron=(u)=>hasProperty(u,TypeId17);var Equivalence3=make((self,that)=>restrictionsEquals(self.seconds,that.seconds)&&restrictionsEquals(self.minutes,that.minutes)&&restrictionsEquals(self.hours,that.hours)&&restrictionsEquals(self.days,that.days)&&restrictionsEquals(self.months,that.months)&&restrictionsEquals(self.weekdays,that.weekdays)),restrictionsArrayEquals=array(number),restrictionsEquals=(self,that)=>restrictionsArrayEquals(fromIterable(self),fromIterable(that)),equals4=dual(2,(self,that)=>Equivalence3(self,that));var ScheduleSymbolKey="effect/Schedule",ScheduleTypeId=Symbol.for(ScheduleSymbolKey),isSchedule=(u)=>hasProperty(u,ScheduleTypeId),ScheduleDriverSymbolKey="effect/ScheduleDriver",ScheduleDriverTypeId=Symbol.for(ScheduleDriverSymbolKey),scheduleVariance={_Out:(_)=>_,_In:(_)=>_,_R:(_)=>_},scheduleDriverVariance={_Out:(_)=>_,_In:(_)=>_,_R:(_)=>_};class ScheduleImpl{initial;step;[ScheduleTypeId]=scheduleVariance;constructor(initial,step3){this.initial=initial,this.step=step3}pipe(){return pipeArguments(this,arguments)}}class ScheduleDriverImpl{schedule;ref;[ScheduleDriverTypeId]=scheduleDriverVariance;constructor(schedule,ref){this.schedule=schedule,this.ref=ref}get state(){return map10(get11(this.ref),(tuple3)=>tuple3[1])}get last(){return flatMap8(get11(this.ref),([element,_])=>{switch(element._tag){case"None":return failSync(()=>new NoSuchElementException);case"Some":return succeed(element.value)}})}get reset(){return set5(this.ref,[none2(),this.schedule.initial])}next(input){return pipe(map10(get11(this.ref),(tuple3)=>tuple3[1]),flatMap8((state)=>pipe(currentTimeMillis2,flatMap8((now)=>pipe(suspend(()=>this.schedule.step(now,input,state)),flatMap8(([state2,out,decision])=>{let setState=set5(this.ref,[some2(out),state2]);if(isDone5(decision))return zipRight(setState,fail2(none2()));let millis2=start2(decision.intervals)-now;if(millis2<=0)return as(setState,out);return pipe(setState,zipRight(sleep3(millis(millis2))),as(out))}))))))}}var makeWithState=(initial,step3)=>new ScheduleImpl(initial,step3),addDelay=dual(2,(self,f)=>addDelayEffect(self,(out)=>sync(()=>f(out)))),addDelayEffect=dual(2,(self,f)=>modifyDelayEffect(self,(out,duration)=>map10(f(out),(delay2)=>sum(duration,decode(delay2)))));var check=dual(2,(self,test)=>checkEffect(self,(input,out)=>sync(()=>test(input,out)))),checkEffect=dual(2,(self,test)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>{if(isDone5(decision))return succeed([state2,out,done7]);return map10(test(input,out),(cont)=>cont?[state2,out,decision]:[state2,out,done7])})));var driver=(self)=>pipe(make28([none2(),self.initial]),map10((ref)=>new ScheduleDriverImpl(self,ref)));var intersect5=dual(2,(self,that)=>intersectWith(self,that,intersect4)),intersectWith=dual(3,(self,that,f)=>makeWithState([self.initial,that.initial],(now,input,state)=>pipe(zipWith3(self.step(now,input,state[0]),that.step(now,input,state[1]),(a,b)=>[a,b]),flatMap8(([[lState,out,lDecision],[rState,out2,rDecision]])=>{if(isContinue2(lDecision)&&isContinue2(rDecision))return intersectWithLoop(self,that,input,lState,out,lDecision.intervals,rState,out2,rDecision.intervals,f);return succeed([[lState,rState],[out,out2],done7])})))),intersectWithLoop=(self,that,input,lState,out,lInterval,rState,out2,rInterval,f)=>{let combined=f(lInterval,rInterval);if(isNonEmpty5(combined))return succeed([[lState,rState],[out,out2],_continue2(combined)]);if(pipe(lInterval,lessThan6(rInterval)))return flatMap8(self.step(end2(lInterval),input,lState),([lState2,out3,decision])=>{if(isDone5(decision))return succeed([[lState2,rState],[out3,out2],done7]);return intersectWithLoop(self,that,input,lState2,out3,decision.intervals,rState,out2,rInterval,f)});return flatMap8(that.step(end2(rInterval),input,rState),([rState2,out22,decision])=>{if(isDone5(decision))return succeed([[lState,rState2],[out,out22],done7]);return intersectWithLoop(self,that,input,lState,out,lInterval,rState2,out22,decision.intervals,f)})};var map14=dual(2,(self,f)=>mapEffect2(self,(out)=>sync(()=>f(out)))),mapEffect2=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>map10(f(out),(out2)=>[state2,out2,decision]))));var modifyDelayEffect=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>{if(isDone5(decision))return succeed([state2,out,decision]);let intervals=decision.intervals,delay2=size10(make38(now,start2(intervals)));return map10(f(out,delay2),(durationInput)=>{let duration=decode(durationInput),oldStart=start2(intervals),newStart=now+toMillis(duration),delta=newStart-oldStart,newEnd=Math.max(0,end2(intervals)+delta),newInterval=make38(newStart,newEnd);return[state2,out,continueWith2(newInterval)]})})));var passthrough=(self)=>makeWithState(self.initial,(now,input,state)=>pipe(self.step(now,input,state),map10(([state2,_,decision])=>[state2,input,decision])));var recurs=(n)=>whileOutput(forever2,(out)=>out<n);var spaced=(duration)=>addDelay(forever2,()=>duration);var unfold2=(initial,f)=>makeWithState(initial,(now,_,state)=>sync(()=>[f(state),state,continueWith2(after2(now))]));var untilInputEffect=dual(2,(self,f)=>checkEffect(self,(input,_)=>negate(f(input))));var whileInputEffect=dual(2,(self,f)=>checkEffect(self,(input,_)=>f(input))),whileOutput=dual(2,(self,f)=>check(self,(_,out)=>f(out)));var ScheduleDefectTypeId=Symbol.for("effect/Schedule/ScheduleDefect");class ScheduleDefect{error;[ScheduleDefectTypeId];constructor(error){this.error=error,this[ScheduleDefectTypeId]=ScheduleDefectTypeId}}var isScheduleDefect=(u)=>hasProperty(u,ScheduleDefectTypeId),scheduleDefectWrap=(self)=>catchAll(self,(e)=>die2(new ScheduleDefect(e))),scheduleDefectRefail=(self)=>catchAllCause(self,(cause2)=>match2(find(cause2,(_)=>isDieType(_)&&isScheduleDefect(_.defect)?some2(_.defect):none2()),{onNone:()=>failCause(cause2),onSome:(error)=>fail2(error.error)})),repeat_Effect=dual(2,(self,schedule)=>repeatOrElse_Effect(self,schedule,(e,_)=>fail2(e))),repeat_combined=dual(2,(self,options)=>{if(isSchedule(options))return repeat_Effect(self,options);let base=options.schedule??passthrough(forever2),withWhile=options.while?whileInputEffect(base,(a)=>{let applied=options.while(a);if(typeof applied==="boolean")return succeed(applied);return scheduleDefectWrap(applied)}):base,withUntil=options.until?untilInputEffect(withWhile,(a)=>{let applied=options.until(a);if(typeof applied==="boolean")return succeed(applied);return scheduleDefectWrap(applied)}):withWhile,withTimes=options.times?intersect5(withUntil,recurs(options.times)).pipe(map14((intersectionPair)=>intersectionPair[0])):withUntil;return scheduleDefectRefail(repeat_Effect(self,withTimes))}),repeatOrElse_Effect=dual(3,(self,schedule,orElse4)=>flatMap8(driver(schedule),(driver2)=>matchEffect(self,{onFailure:(error)=>orElse4(error,none2()),onSuccess:(value)=>repeatOrElseEffectLoop(self,driver2,orElse4,value)}))),repeatOrElseEffectLoop=(self,driver2,orElse4,value)=>{return matchEffect(driver2.next(value),{onFailure:()=>orDie(driver2.last),onSuccess:(b)=>matchEffect(self,{onFailure:(error)=>orElse4(error,some2(b)),onSuccess:(value2)=>repeatOrElseEffectLoop(self,driver2,orElse4,value2)})})},retry_Effect=dual(2,(self,policy)=>retryOrElse_Effect(self,policy,(e,_)=>fail2(e))),retry_combined=dual(2,(self,options)=>{if(isSchedule(options))return retry_Effect(self,options);let base=options.schedule??forever2,withWhile=options.while?whileInputEffect(base,(e)=>{let applied=options.while(e);if(typeof applied==="boolean")return succeed(applied);return scheduleDefectWrap(applied)}):base,withUntil=options.until?untilInputEffect(withWhile,(e)=>{let applied=options.until(e);if(typeof applied==="boolean")return succeed(applied);return scheduleDefectWrap(applied)}):withWhile,withTimes=options.times?intersect5(withUntil,recurs(options.times)):withUntil;return scheduleDefectRefail(retry_Effect(self,withTimes))}),retryOrElse_Effect=dual(3,(self,policy,orElse4)=>flatMap8(driver(policy),(driver2)=>retryOrElse_EffectLoop(self,driver2,orElse4))),retryOrElse_EffectLoop=(self,driver2,orElse4)=>{return catchAll(self,(e)=>matchEffect(driver2.next(e),{onFailure:()=>pipe(driver2.last,orDie,flatMap8((out)=>orElse4(e,out))),onSuccess:()=>retryOrElse_EffectLoop(self,driver2,orElse4)}))},schedule_Effect=dual(2,(self,schedule)=>scheduleFrom_Effect(self,void 0,schedule)),scheduleFrom_Effect=dual(3,(self,initial,schedule)=>flatMap8(driver(schedule),(driver2)=>scheduleFrom_EffectLoop(self,initial,driver2))),scheduleFrom_EffectLoop=(self,initial,driver2)=>matchEffect(driver2.next(initial),{onFailure:()=>orDie(driver2.last),onSuccess:()=>flatMap8(self,(a)=>scheduleFrom_EffectLoop(self,a,driver2))});var forever2=unfold2(0,(n)=>n+1);class Semaphore{permits;waiters=new Set;taken=0;constructor(permits){this.permits=permits}get free(){return this.permits-this.taken}take=(n)=>asyncInterrupt((resume2)=>{if(this.free<n){let observer=()=>{if(this.free<n)return;this.waiters.delete(observer),this.taken+=n,resume2(succeed(n))};return this.waiters.add(observer),sync(()=>{this.waiters.delete(observer)})}return this.taken+=n,resume2(succeed(n))});updateTaken=(f)=>withFiberRuntime((fiber)=>{if(this.taken=f(this.taken),this.waiters.size>0)fiber.getFiberRef(currentScheduler).scheduleTask(()=>{let iter=this.waiters.values(),item=iter.next();while(item.done===!1&&this.free>0)item.value(),item=iter.next()},fiber.getFiberRef(currentSchedulingPriority));return succeed(this.free)});release=(n)=>this.updateTaken((taken)=>taken-n);releaseAll=this.updateTaken((_)=>0);withPermits=(n)=>(self)=>uninterruptibleMask((restore)=>flatMap8(restore(this.take(n)),(permits)=>ensuring(restore(self),this.release(permits))));withPermitsIfAvailable=(n)=>(self)=>uninterruptibleMask((restore)=>suspend(()=>{if(this.free<n)return succeedNone;return this.taken+=n,ensuring(restore(asSome(self)),this.release(n))}))}var unsafeMakeSemaphore=(permits)=>new Semaphore(permits),makeSemaphore=(permits)=>sync(()=>unsafeMakeSemaphore(permits));class Latch extends Class{isOpen;waiters=[];scheduled=!1;constructor(isOpen){super();this.isOpen=isOpen}commit(){return this.await}unsafeSchedule(fiber){if(this.scheduled||this.waiters.length===0)return void_;return this.scheduled=!0,fiber.currentScheduler.scheduleTask(this.flushWaiters,fiber.getFiberRef(currentSchedulingPriority)),void_}flushWaiters=()=>{this.scheduled=!1;let waiters=this.waiters;this.waiters=[];for(let i=0;i<waiters.length;i++)waiters[i](exitVoid)};open=withFiberRuntime((fiber)=>{if(this.isOpen)return void_;return this.isOpen=!0,this.unsafeSchedule(fiber)});unsafeOpen(){if(this.isOpen)return;this.isOpen=!0,this.flushWaiters()}release=withFiberRuntime((fiber)=>{if(this.isOpen)return void_;return this.unsafeSchedule(fiber)});await=asyncInterrupt((resume2)=>{if(this.isOpen)return resume2(void_);return this.waiters.push(resume2),sync(()=>{let index=this.waiters.indexOf(resume2);if(index!==-1)this.waiters.splice(index,1)})});unsafeClose(){this.isOpen=!1}close=sync(()=>{this.isOpen=!1});whenOpen=(self)=>{return zipRight(this.await,self)}}var unsafeMakeLatch=(open)=>new Latch(open??!1),makeLatch=(open)=>sync(()=>unsafeMakeLatch(open)),awaitAllChildren=(self)=>ensuringChildren(self,fiberAwaitAll),cached2=dual(2,(self,timeToLive)=>map10(cachedInvalidateWithTTL(self,timeToLive),(tuple3)=>tuple3[0])),cachedInvalidateWithTTL=dual(2,(self,timeToLive)=>{let duration=decode(timeToLive);return flatMap8(context(),(env)=>map10(makeSynchronized(none2()),(cache)=>[provideContext(getCachedValue(self,duration,cache),env),invalidateCache(cache)]))}),computeCachedValue=(self,timeToLive,start3)=>{let timeToLiveMillis=toMillis(decode(timeToLive));return pipe(deferredMake(),tap((deferred)=>intoDeferred(self,deferred)),map10((deferred)=>some2([start3+timeToLiveMillis,deferred])))},getCachedValue=(self,timeToLive,cache)=>uninterruptibleMask((restore)=>pipe(clockWith3((clock2)=>clock2.currentTimeMillis),flatMap8((time)=>updateSomeAndGetEffectSynchronized(cache,(option2)=>{switch(option2._tag){case"None":return some2(computeCachedValue(self,timeToLive,time));case"Some":{let[end3]=option2.value;return end3-time<=0?some2(computeCachedValue(self,timeToLive,time)):none2()}}})),flatMap8((option2)=>isNone2(option2)?dieMessage("BUG: Effect.cachedInvalidate - please report an issue at https://github.com/Effect-TS/effect/issues"):restore(deferredAwait(option2.value[1]))))),invalidateCache=(cache)=>set5(cache,none2()),ensuringChild=dual(2,(self,f)=>ensuringChildren(self,(children2)=>f(fiberAll(children2)))),ensuringChildren=dual(2,(self,children2)=>flatMap8(track,(supervisor)=>pipe(supervised(self,supervisor),ensuring(flatMap8(supervisor.value,children2))))),forkAll=dual((args2)=>isIterable(args2[0]),(effects,options)=>options?.discard?forEachSequentialDiscard(effects,fork):map10(forEachSequential(effects,fork),fiberAll)),forkIn=dual(2,(self,scope2)=>withFiberRuntime((parent,parentStatus)=>{let scopeImpl=scope2,fiber=unsafeFork(self,parent,parentStatus.runtimeFlags,globalScope);if(scopeImpl.state._tag==="Open"){let finalizer=()=>fiberIdWith((fiberId2)=>equals(fiberId2,fiber.id())?void_:asVoid(interruptFiber(fiber))),key={};scopeImpl.state.finalizers.set(key,finalizer),fiber.addObserver(()=>{if(scopeImpl.state._tag==="Closed")return;scopeImpl.state.finalizers.delete(key)})}else fiber.unsafeInterruptAsFork(parent.id());return succeed(fiber)})),forkScoped=(self)=>scopeWith((scope2)=>forkIn(self,scope2)),fromFiber=(fiber)=>join2(fiber),fromFiberEffect=(fiber)=>suspend(()=>flatMap8(fiber,join2)),memoKeySymbol=Symbol.for("effect/Effect/memoizeFunction.key");class Key{a;eq;[memoKeySymbol]=memoKeySymbol;constructor(a,eq){this.a=a,this.eq=eq}[symbol2](that){if(hasProperty(that,memoKeySymbol))if(this.eq)return this.eq(this.a,that.a);else return equals(this.a,that.a);return!1}[symbol](){return this.eq?0:cached(this,hash(this.a))}}var cachedFunction=(f,eq)=>{return pipe(sync(()=>empty21()),flatMap8(makeSynchronized),map10((ref)=>(a)=>pipe(ref.modifyEffect((map15)=>{let result=pipe(map15,get8(new Key(a,eq)));if(isNone2(result))return pipe(deferredMake(),tap((deferred)=>pipe(diffFiberRefs(f(a)),intoDeferred(deferred),fork)),map10((deferred)=>[deferred,pipe(map15,set4(new Key(a,eq),deferred))]));return succeed([result.value,map15])}),flatMap8(deferredAwait),flatMap8(([patch12,b])=>pipe(patchFiberRefs(patch12),as(b))))))},raceFirst=dual(2,(self,that)=>pipe(exit(self),race(exit(that)),(effect)=>flatten6(effect))),scheduleForked=dual(2,(self,schedule)=>pipe(self,schedule_Effect(schedule),forkScoped)),supervised=dual(2,(self,supervisor)=>{return fiberRefLocallyWith(currentSupervisor,(s)=>s.zip(supervisor))(self)}),timeout=dual(2,(self,duration)=>timeoutFail(self,{onTimeout:()=>timeoutExceptionFromDuration(duration),duration})),timeoutFail=dual(2,(self,{duration,onTimeout})=>flatten6(timeoutTo(self,{onTimeout:()=>failSync(onTimeout),onSuccess:succeed,duration}))),timeoutFailCause=dual(2,(self,{duration,onTimeout})=>flatten6(timeoutTo(self,{onTimeout:()=>failCauseSync(onTimeout),onSuccess:succeed,duration}))),timeoutOption=dual(2,(self,duration)=>timeoutTo(self,{duration,onSuccess:some2,onTimeout:none2})),timeoutTo=dual(2,(self,{duration,onSuccess,onTimeout})=>fiberIdWith((parentFiberId)=>uninterruptibleMask((restore)=>raceFibersWith(restore(self),interruptible2(sleep3(duration)),{onSelfWin:(winner,loser)=>flatMap8(winner.await,(exit2)=>{if(exit2._tag==="Success")return flatMap8(winner.inheritAll,()=>as(interruptAsFiber(loser,parentFiberId),onSuccess(exit2.value)));else return flatMap8(interruptAsFiber(loser,parentFiberId),()=>exitFailCause(exit2.cause))}),onOtherWin:(winner,loser)=>flatMap8(winner.await,(exit2)=>{if(exit2._tag==="Success")return flatMap8(winner.inheritAll,()=>as(interruptAsFiber(loser,parentFiberId),onTimeout()));else return flatMap8(interruptAsFiber(loser,parentFiberId),()=>exitFailCause(exit2.cause))}),otherScope:globalScope})))),SynchronizedSymbolKey="effect/Ref/SynchronizedRef",SynchronizedTypeId=Symbol.for(SynchronizedSymbolKey),synchronizedVariance={_A:(_)=>_};class SynchronizedImpl extends Class{ref;withLock;[SynchronizedTypeId]=synchronizedVariance;[RefTypeId]=refVariance;[TypeId13]=TypeId13;constructor(ref,withLock){super();this.ref=ref,this.withLock=withLock,this.get=get11(this.ref)}get;commit(){return this.get}modify(f){return this.modifyEffect((a)=>succeed(f(a)))}modifyEffect(f){return this.withLock(pipe(flatMap8(get11(this.ref),f),flatMap8(([b,a])=>as(set5(this.ref,a),b))))}}var makeSynchronized=(value)=>sync(()=>unsafeMakeSynchronized(value)),unsafeMakeSynchronized=(value)=>{let ref=unsafeMake5(value),sem=unsafeMakeSemaphore(1);return new SynchronizedImpl(ref,sem.withPermits(1))},updateSomeAndGetEffectSynchronized=dual(2,(self,pf)=>self.modifyEffect((value)=>{let result=pf(value);switch(result._tag){case"None":return succeed([value,value]);case"Some":return map10(result.value,(a)=>[a,a])}})),zipFiber=dual(2,(self,that)=>zipWithFiber(self,that,(a,b)=>[a,b])),zipLeftFiber=dual(2,(self,that)=>zipWithFiber(self,that,(a,_)=>a)),zipRightFiber=dual(2,(self,that)=>zipWithFiber(self,that,(_,b)=>b)),zipWithFiber=dual(3,(self,that,f)=>({...CommitPrototype2,commit(){return join2(this)},[FiberTypeId]:fiberVariance2,id:()=>pipe(self.id(),getOrElse4(that.id())),await:pipe(self.await,flatten6,zipWithOptions(flatten6(that.await),f,{concurrent:!0}),exit),children:self.children,inheritAll:zipRight(that.inheritAll,self.inheritAll),poll:zipWith3(self.poll,that.poll,(optionA,optionB)=>pipe(optionA,flatMap((exitA)=>pipe(optionB,map2((exitB)=>zipWith4(exitA,exitB,{onSuccess:f,onFailure:parallel})))))),interruptAsFork:(id2)=>zipRight(self.interruptAsFork(id2),that.interruptAsFork(id2)),pipe(){return pipeArguments(this,arguments)}})),bindAll=dual((args2)=>isEffect(args2[0]),(self,f,options)=>flatMap8(self,(a)=>all4(f(a),options).pipe(map10((record)=>Object.assign({},a,record)))));var TypeId18=Symbol.for("effect/ManagedRuntime");var OP_FRESH="Fresh",OP_FROM_EFFECT="FromEffect",OP_SCOPED="Scoped",OP_SUSPEND="Suspend",OP_PROVIDE="Provide",OP_PROVIDE_MERGE="ProvideMerge",OP_ZIP_WITH2="ZipWith";var exports_Fiber={};__export(exports_Fiber,{zipWith:()=>zipWith6,zipRight:()=>zipRight3,zipLeft:()=>zipLeft2,zip:()=>zip5,void:()=>void_5,unsafeRoots:()=>unsafeRoots2,succeed:()=>succeed6,status:()=>status2,scoped:()=>scoped,roots:()=>roots2,pretty:()=>pretty4,poll:()=>poll4,orElseEither:()=>orElseEither3,orElse:()=>orElse4,never:()=>never3,match:()=>match12,mapFiber:()=>mapFiber2,mapEffect:()=>mapEffect3,map:()=>map15,joinAll:()=>joinAll,join:()=>join3,isRuntimeFiber:()=>isRuntimeFiber2,isFiber:()=>isFiber2,interrupted:()=>interrupted2,interruptFork:()=>interruptFork,interruptAsFork:()=>interruptAsFork2,interruptAs:()=>interruptAs,interruptAllAs:()=>interruptAllAs2,interruptAll:()=>interruptAll2,interrupt:()=>interrupt6,inheritAll:()=>inheritAll2,id:()=>id2,getCurrentFiber:()=>getCurrentFiber2,fromEffect:()=>fromEffect3,failCause:()=>failCause6,fail:()=>fail7,dumpAll:()=>dumpAll2,dump:()=>dump2,done:()=>done8,children:()=>children2,awaitAll:()=>awaitAll,await:()=>_await3,all:()=>all6,RuntimeFiberTypeId:()=>RuntimeFiberTypeId2,Order:()=>Order5,FiberTypeId:()=>FiberTypeId2});var FiberTypeId2=FiberTypeId,RuntimeFiberTypeId2=RuntimeFiberTypeId,Order5=Order4,isFiber2=isFiber,isRuntimeFiber2=isRuntimeFiber,id2=id,_await3=_await2;var awaitAll=fiberAwaitAll,children2=children,all6=fiberAll,done8=done5,dump2=dump,dumpAll2=dumpAll,fail7=fail5,failCause6=failCause5,fromEffect3=fromEffect,getCurrentFiber2=getCurrentFiber,inheritAll2=inheritAll,interrupt6=interruptFiber,interrupted2=interrupted,interruptAs=interruptAsFiber,interruptAsFork2=interruptAsFork,interruptAll2=interruptAll,interruptAllAs2=interruptAllAs,interruptFork=fiberInterruptFork,join3=join2,joinAll=fiberJoinAll,map15=map12,mapEffect3=mapEffect,mapFiber2=mapFiber,match12=match10,never3=never2,orElse4=orElse3,orElseEither3=orElseEither,poll4=poll3,pretty4=pretty2,roots2=roots,unsafeRoots2=unsafeRoots,scoped=fiberScoped,status2=status,succeed6=succeed5,void_5=void_4;var zip5=zipFiber,zipLeft2=zipLeftFiber,zipRight3=zipRightFiber,zipWith6=zipWithFiber;var makeDual=(f)=>function(){if(arguments.length===1){let runtime2=arguments[0];return(effect,...args2)=>f(runtime2,effect,...args2)}return f.apply(this,arguments)},unsafeFork2=makeDual((runtime2,self,options)=>{let fiberId2=unsafeMake2(),fiberRefUpdates=[[currentContext,[[fiberId2,runtime2.context]]]];if(options?.scheduler)fiberRefUpdates.push([currentScheduler,[[fiberId2,options.scheduler]]]);let fiberRefs3=updateManyAs2(runtime2.fiberRefs,{entries:fiberRefUpdates,forkAs:fiberId2});if(options?.updateRefs)fiberRefs3=options.updateRefs(fiberRefs3,fiberId2);let fiberRuntime=new FiberRuntime(fiberId2,fiberRefs3,runtime2.runtimeFlags),effect=self;if(options?.scope)effect=flatMap8(fork2(options.scope,sequential2),(closeableScope)=>zipRight(scopeAddFinalizer(closeableScope,fiberIdWith((id3)=>equals(id3,fiberRuntime.id())?void_:interruptAsFiber(fiberRuntime,id3))),onExit(self,(exit2)=>close(closeableScope,exit2))));let supervisor=fiberRuntime.currentSupervisor;if(supervisor!==none8)supervisor.onStart(runtime2.context,effect,none2(),fiberRuntime),fiberRuntime.addObserver((exit2)=>supervisor.onEnd(exit2,fiberRuntime));if(globalScope.add(runtime2.runtimeFlags,fiberRuntime),options?.immediate===!1)fiberRuntime.resume(effect);else fiberRuntime.start(effect);return fiberRuntime}),unsafeRunCallback=makeDual((runtime2,effect,options={})=>{let fiberRuntime=unsafeFork2(runtime2,effect,options);if(options.onExit)fiberRuntime.addObserver((exit2)=>{options.onExit(exit2)});return(id3,cancelOptions)=>unsafeRunCallback(runtime2)(pipe(fiberRuntime,interruptAs(id3??none4)),{...cancelOptions,onExit:cancelOptions?.onExit?(exit2)=>cancelOptions.onExit(flatten7(exit2)):void 0})}),unsafeRunSync=makeDual((runtime2,effect)=>{let result=unsafeRunSyncExit(runtime2)(effect);if(result._tag==="Failure")throw fiberFailure(result.effect_instruction_i0);return result.effect_instruction_i0});class AsyncFiberExceptionImpl extends Error{fiber;_tag="AsyncFiberException";constructor(fiber){super(`Fiber #${fiber.id().id} cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work`);this.fiber=fiber,this.name=this._tag,this.stack=this.message}}var asyncFiberException=(fiber)=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=0;let error=new AsyncFiberExceptionImpl(fiber);return Error.stackTraceLimit=limit,error};var FiberFailureId=Symbol.for("effect/Runtime/FiberFailure"),FiberFailureCauseId=Symbol.for("effect/Runtime/FiberFailure/Cause");class FiberFailureImpl extends Error{[FiberFailureId];[FiberFailureCauseId];constructor(cause2){let head4=prettyErrors(cause2)[0];super(head4?.message||"An error has occurred");if(this[FiberFailureId]=FiberFailureId,this[FiberFailureCauseId]=cause2,this.name=head4?`(FiberFailure) ${head4.name}`:"FiberFailure",head4?.stack)this.stack=head4.stack}toJSON(){return{_id:"FiberFailure",cause:this[FiberFailureCauseId].toJSON()}}toString(){return"(FiberFailure) "+pretty(this[FiberFailureCauseId],{renderErrorCause:!0})}[NodeInspectSymbol](){return this.toString()}}var fiberFailure=(cause2)=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=0;let error=new FiberFailureImpl(cause2);return Error.stackTraceLimit=limit,error};var fastPath=(effect)=>{let op=effect;switch(op._op){case"Failure":case"Success":return op;case"Left":return exitFail(op.left);case"Right":return exitSucceed(op.right);case"Some":return exitSucceed(op.value);case"None":return exitFail(NoSuchElementException())}},unsafeRunSyncExit=makeDual((runtime2,effect)=>{let op=fastPath(effect);if(op)return op;let scheduler=new SyncScheduler,fiberRuntime=unsafeFork2(runtime2)(effect,{scheduler});scheduler.flush();let result=fiberRuntime.unsafePoll();if(result)return result;return exitDie(capture(asyncFiberException(fiberRuntime),currentSpanFromFiber(fiberRuntime)))}),unsafeRunPromise=makeDual((runtime2,effect,options)=>unsafeRunPromiseExit(runtime2,effect,options).then((result)=>{switch(result._tag){case OP_SUCCESS:return result.effect_instruction_i0;case OP_FAILURE:throw fiberFailure(result.effect_instruction_i0)}})),unsafeRunPromiseExit=makeDual((runtime2,effect,options)=>new Promise((resolve)=>{let op=fastPath(effect);if(op)resolve(op);let fiber=unsafeFork2(runtime2)(effect);if(fiber.addObserver((exit2)=>{resolve(exit2)}),options?.signal!==void 0)if(options.signal.aborted)fiber.unsafeInterruptAsFork(fiber.id());else options.signal.addEventListener("abort",()=>{fiber.unsafeInterruptAsFork(fiber.id())},{once:!0})}));class RuntimeImpl{context;runtimeFlags;fiberRefs;constructor(context2,runtimeFlags2,fiberRefs3){this.context=context2,this.runtimeFlags=runtimeFlags2,this.fiberRefs=fiberRefs3}pipe(){return pipeArguments(this,arguments)}}var make42=(options)=>new RuntimeImpl(options.context,options.runtimeFlags,options.fiberRefs),runtime2=()=>withFiberRuntime((state,status3)=>succeed(new RuntimeImpl(state.getFiberRef(currentContext),status3.runtimeFlags,state.getFiberRefs()))),defaultRuntimeFlags=make17(Interruption,CooperativeYielding,RuntimeMetrics),defaultRuntime=make42({context:empty4(),runtimeFlags:defaultRuntimeFlags,fiberRefs:empty25()});var unsafeRunEffect=unsafeRunCallback(defaultRuntime),unsafeForkEffect=unsafeFork2(defaultRuntime),unsafeRunPromiseEffect=unsafeRunPromise(defaultRuntime),unsafeRunPromiseExitEffect=unsafeRunPromiseExit(defaultRuntime),unsafeRunSyncEffect=unsafeRunSync(defaultRuntime),unsafeRunSyncExitEffect=unsafeRunSyncExit(defaultRuntime),asyncEffect=(register)=>suspend(()=>{let cleanup=void 0;return flatMap8(deferredMake(),(deferred)=>flatMap8(runtime2(),(runtime3)=>uninterruptibleMask((restore)=>zipRight(fork(restore(matchCauseEffect(register((cb)=>unsafeRunCallback(runtime3)(intoDeferred(cb,deferred))),{onFailure:(cause2)=>deferredFailCause(deferred,cause2),onSuccess:(cleanup_)=>{return cleanup=cleanup_,void_}}))),restore(onInterrupt(deferredAwait(deferred),()=>cleanup??void_))))))});var modifyEffect=dual(2,(self,f)=>self.modifyEffect(f));var LayerSymbolKey="effect/Layer",LayerTypeId=Symbol.for(LayerSymbolKey),layerVariance={_RIn:(_)=>_,_E:(_)=>_,_ROut:(_)=>_},proto3={[LayerTypeId]:layerVariance,pipe(){return pipeArguments(this,arguments)}},MemoMapTypeIdKey="effect/Layer/MemoMap",MemoMapTypeId=Symbol.for(MemoMapTypeIdKey),CurrentMemoMap=Reference2()("effect/Layer/CurrentMemoMap",{defaultValue:()=>unsafeMakeMemoMap()}),isLayer=(u)=>hasProperty(u,LayerTypeId),isFresh=(self)=>{return self._op_layer===OP_FRESH};class MemoMapImpl{ref;[MemoMapTypeId];constructor(ref){this.ref=ref,this[MemoMapTypeId]=MemoMapTypeId}getOrElseMemoize(layer,scope2){return pipe(modifyEffect(this.ref,(map16)=>{let inMap=map16.get(layer);if(inMap!==void 0){let[acquire,release]=inMap,cached3=pipe(acquire,flatMap8(([patch12,b])=>pipe(patchFiberRefs(patch12),as(b))),onExit(exitMatch({onFailure:()=>void_,onSuccess:()=>scopeAddFinalizerExit(scope2,release)})));return succeed([cached3,map16])}return pipe(make28(0),flatMap8((observers)=>pipe(deferredMake(),flatMap8((deferred)=>pipe(make28(()=>void_),map10((finalizerRef)=>{let resource=uninterruptibleMask((restore)=>pipe(scopeMake(),flatMap8((innerScope)=>pipe(restore(flatMap8(makeBuilder(layer,innerScope,!0),(f)=>diffFiberRefs(f(this)))),exit,flatMap8((exit2)=>{switch(exit2._tag){case OP_FAILURE:return pipe(deferredFailCause(deferred,exit2.effect_instruction_i0),zipRight(scopeClose(innerScope,exit2)),zipRight(failCause(exit2.effect_instruction_i0)));case OP_SUCCESS:return pipe(set5(finalizerRef,(exit3)=>pipe(scopeClose(innerScope,exit3),whenEffect(modify2(observers,(n)=>[n===1,n-1])),asVoid)),zipRight(update2(observers,(n)=>n+1)),zipRight(scopeAddFinalizerExit(scope2,(exit3)=>pipe(sync(()=>map16.delete(layer)),zipRight(get11(finalizerRef)),flatMap8((finalizer)=>finalizer(exit3))))),zipRight(deferredSucceed(deferred,exit2.effect_instruction_i0)),as(exit2.effect_instruction_i0[1]))}}))))),memoized=[pipe(deferredAwait(deferred),onExit(exitMatchEffect({onFailure:()=>void_,onSuccess:()=>update2(observers,(n)=>n+1)}))),(exit2)=>pipe(get11(finalizerRef),flatMap8((finalizer)=>finalizer(exit2)))];return[resource,isFresh(layer)?map16:map16.set(layer,memoized)]}))))))}),flatten6)}}var makeMemoMap=suspend(()=>map10(makeSynchronized(new Map),(ref)=>new MemoMapImpl(ref))),unsafeMakeMemoMap=()=>new MemoMapImpl(unsafeMakeSynchronized(new Map));var buildWithScope=dual(2,(self,scope2)=>flatMap8(makeMemoMap,(memoMap)=>buildWithMemoMap(self,memoMap,scope2))),buildWithMemoMap=dual(3,(self,memoMap,scope2)=>flatMap8(makeBuilder(self,scope2),(run)=>provideService(run(memoMap),CurrentMemoMap,memoMap))),makeBuilder=(self,scope2,inMemoMap=!1)=>{let op=self;switch(op._op_layer){case"Locally":return sync(()=>(memoMap)=>op.f(memoMap.getOrElseMemoize(op.self,scope2)));case"ExtendScope":return sync(()=>(memoMap)=>scopeWith((scope3)=>memoMap.getOrElseMemoize(op.layer,scope3)));case"Fold":return sync(()=>(memoMap)=>pipe(memoMap.getOrElseMemoize(op.layer,scope2),matchCauseEffect({onFailure:(cause2)=>memoMap.getOrElseMemoize(op.failureK(cause2),scope2),onSuccess:(value)=>memoMap.getOrElseMemoize(op.successK(value),scope2)})));case"Fresh":return sync(()=>(_)=>pipe(op.layer,buildWithScope(scope2)));case"FromEffect":return inMemoMap?sync(()=>(_)=>op.effect):sync(()=>(memoMap)=>memoMap.getOrElseMemoize(self,scope2));case"Provide":return sync(()=>(memoMap)=>pipe(memoMap.getOrElseMemoize(op.first,scope2),flatMap8((env)=>pipe(memoMap.getOrElseMemoize(op.second,scope2),provideContext(env)))));case"Scoped":return inMemoMap?sync(()=>(_)=>scopeExtend(op.effect,scope2)):sync(()=>(memoMap)=>memoMap.getOrElseMemoize(self,scope2));case"Suspend":return sync(()=>(memoMap)=>memoMap.getOrElseMemoize(op.evaluate(),scope2));case"ProvideMerge":return sync(()=>(memoMap)=>pipe(memoMap.getOrElseMemoize(op.first,scope2),zipWith3(memoMap.getOrElseMemoize(op.second,scope2),op.zipK)));case"ZipWith":return sync(()=>(memoMap)=>pipe(memoMap.getOrElseMemoize(op.first,scope2),zipWithOptions(memoMap.getOrElseMemoize(op.second,scope2),op.zipK,{concurrent:!0})))}};var context2=()=>fromEffectContext(context());var fromEffect4=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b;return fromEffectContext(map10(tagFirst?b:a,(service)=>make6(tag,service)))});function fromEffectContext(effect){let fromEffect5=Object.create(proto3);return fromEffect5._op_layer=OP_FROM_EFFECT,fromEffect5.effect=effect,fromEffect5}var merge6=dual(2,(self,that)=>zipWith7(self,that,(a,b)=>merge3(a,b))),mergeAll3=(...layers)=>{let final=layers[0];for(let i=1;i<layers.length;i++)final=merge6(final,layers[i]);return final};var scoped2=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b;return scopedContext(map10(tagFirst?b:a,(service)=>make6(tag,service)))});var scopedContext=(effect)=>{let scoped3=Object.create(proto3);return scoped3._op_layer=OP_SCOPED,scoped3.effect=effect,scoped3};var succeed7=dual(2,(a,b)=>{let tagFirst=isTag2(a);return fromEffectContext(succeed(make6(tagFirst?a:b,tagFirst?b:a)))});var suspend2=(evaluate2)=>{let suspend3=Object.create(proto3);return suspend3._op_layer=OP_SUSPEND,suspend3.evaluate=evaluate2,suspend3},sync2=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b,evaluate2=tagFirst?b:a;return fromEffectContext(sync(()=>make6(tag,evaluate2())))});var provide=dual(2,(self,that)=>suspend2(()=>{let provideTo=Object.create(proto3);return provideTo._op_layer=OP_PROVIDE,provideTo.first=Object.create(proto3,{_op_layer:{value:OP_PROVIDE_MERGE,enumerable:!0},first:{value:context2(),enumerable:!0},second:{value:Array.isArray(that)?mergeAll3(...that):that},zipK:{value:(a,b)=>pipe(a,merge3(b))}}),provideTo.second=self,provideTo}));var zipWith7=dual(3,(self,that,f)=>suspend2(()=>{let zipWith8=Object.create(proto3);return zipWith8._op_layer=OP_ZIP_WITH2,zipWith8.first=self,zipWith8.second=that,zipWith8.zipK=f,zipWith8}));var provideSomeLayer=dual(2,(self,layer)=>scopedWith((scope2)=>flatMap8(buildWithScope(layer,scope2),(context3)=>provideSomeContext(self,context3)))),provideSomeRuntime=dual(2,(self,rt)=>{let patchRefs=diff9(defaultRuntime.fiberRefs,rt.fiberRefs),patchFlags=diff7(defaultRuntime.runtimeFlags,rt.runtimeFlags);return uninterruptibleMask((restore)=>withFiberRuntime((fiber)=>{let oldContext=fiber.getFiberRef(currentContext),oldRefs=fiber.getFiberRefs(),newRefs=patch10(fiber.id(),oldRefs)(patchRefs),oldFlags=fiber.currentRuntimeFlags,newFlags=patch7(patchFlags)(oldFlags),rollbackRefs=diff9(newRefs,oldRefs),rollbackFlags=diff7(newFlags,oldFlags);return fiber.setFiberRefs(newRefs),fiber.currentRuntimeFlags=newFlags,ensuring(provideSomeContext(restore(self),merge3(oldContext,rt.context)),withFiberRuntime((fiber2)=>{return fiber2.setFiberRefs(patch10(fiber2.id(),fiber2.getFiberRefs())(rollbackRefs)),fiber2.currentRuntimeFlags=patch7(rollbackFlags)(fiber2.currentRuntimeFlags),void_}))}))}),effect_provide=dual(2,(self,source)=>{if(Array.isArray(source))return provideSomeLayer(self,mergeAll3(...source));else if(isLayer(source))return provideSomeLayer(self,source);else if(isContext2(source))return provideSomeContext(self,source);else if(TypeId18 in source)return flatMap8(source.runtimeEffect,(rt)=>provideSomeRuntime(self,rt));else return provideSomeRuntime(self,source)});var console2=map10(fiberRefGet(currentServices),get3(consoleTag)),consoleWith=(f)=>fiberRefGetWith(currentServices,(services)=>f(get3(services,consoleTag))),withConsole=dual(2,(effect,value)=>fiberRefLocallyWith(effect,currentServices,add2(consoleTag,value))),withConsoleScoped=(console3)=>fiberRefLocallyScopedWith(currentServices,add2(consoleTag,console3));var currentCache=globalValue(Symbol.for("effect/FiberRef/currentCache"),()=>fiberRefUnsafeMake(unsafeMakeWith(65536,()=>map10(deferredMake(),(handle)=>({listeners:new Listeners,handle})),()=>seconds(60)))),currentCacheEnabled=globalValue(Symbol.for("effect/FiberRef/currentCacheEnabled"),()=>fiberRefUnsafeMake(!1)),fromRequest=(request,dataSource)=>flatMap8(isEffect(dataSource)?dataSource:succeed(dataSource),(ds)=>fiberIdWith((id3)=>{let proxy=new Proxy(request,{});return fiberRefGetWith(currentCacheEnabled,(cacheEnabled)=>{if(cacheEnabled){let cached3=fiberRefGetWith(currentCache,(cache)=>flatMap8(cache.getEither(proxy),(orNew)=>{switch(orNew._tag){case"Left":{if(orNew.left.listeners.interrupted)return flatMap8(cache.invalidateWhen(proxy,(entry)=>entry.handle===orNew.left.handle),()=>cached3);return orNew.left.listeners.increment(),uninterruptibleMask((restore)=>flatMap8(exit(blocked(empty19,restore(deferredAwait(orNew.left.handle)))),(exit2)=>{return orNew.left.listeners.decrement(),exit2}))}case"Right":return orNew.right.listeners.increment(),uninterruptibleMask((restore)=>flatMap8(exit(blocked(single(ds,makeEntry({request:proxy,result:orNew.right.handle,listeners:orNew.right.listeners,ownerId:id3,state:{completed:!1}})),restore(deferredAwait(orNew.right.handle)))),()=>{return orNew.right.listeners.decrement(),deferredAwait(orNew.right.handle)}))}}));return cached3}let listeners=new Listeners;return listeners.increment(),flatMap8(deferredMake(),(ref)=>ensuring(blocked(single(ds,makeEntry({request:proxy,result:ref,listeners,ownerId:id3,state:{completed:!1}})),deferredAwait(ref)),sync(()=>listeners.decrement())))})})),cacheRequest=(request,result)=>{return fiberRefGetWith(currentCacheEnabled,(cacheEnabled)=>{if(cacheEnabled)return fiberRefGetWith(currentCache,(cache)=>flatMap8(cache.getEither(request),(orNew)=>{switch(orNew._tag){case"Left":return void_;case"Right":return deferredComplete(orNew.right.handle,result)}}));return void_})},withRequestCaching=dual(2,(self,strategy)=>fiberRefLocally(self,currentCacheEnabled,strategy)),withRequestCache=dual(2,(self,cache)=>fiberRefLocally(self,currentCache,cache));var isRequest2=isRequest;var EffectTypeId3=EffectTypeId2,isEffect2=isEffect,cachedWithTTL=cached2,cachedInvalidateWithTTL2=cachedInvalidateWithTTL,cached3=memoize,cachedFunction2=cachedFunction,once2=once,all7=all4,allWith2=allWith,allSuccesses2=allSuccesses,dropUntil2=dropUntil,dropWhile3=dropWhile2,takeUntil2=takeUntil,takeWhile3=takeWhile2,every6=every5,exists3=exists2,filter8=filter6,filterMap5=filterMap4,findFirst7=findFirst5,forEach8=forEach7,head4=head3,mergeAll4=mergeAll2,partition4=partition3,reduce13=reduce11,reduceWhile2=reduceWhile,reduceRight4=reduceRight3,reduceEffect2=reduceEffect,replicate2=replicate,replicateEffect2=replicateEffect,validateAll2=validateAll,validateFirst2=validateFirst,async=async_,asyncEffect2=asyncEffect,custom2=custom,withFiberRuntime2=withFiberRuntime,fail9=fail2,failSync2=failSync,failCause8=failCause,failCauseSync2=failCauseSync,die5=die2,dieMessage2=dieMessage,dieSync2=dieSync,gen2=gen,never4=never,none9=none6,promise2=promise,succeed9=succeed,succeedNone2=succeedNone,succeedSome2=succeedSome,suspend3=suspend,sync3=sync,_void=void_;var yieldNow4=yieldNow,_catch2=_catch;var catchAll2=catchAll,catchAllCause2=catchAllCause,catchAllDefect2=catchAllDefect,catchIf2=catchIf,catchSome2=catchSome,catchSomeCause2=catchSomeCause,catchSomeDefect2=catchSomeDefect,catchTag2=catchTag,catchTags2=catchTags,cause2=cause,eventually2=eventually,ignore2=ignore,ignoreLogged2=ignoreLogged,parallelErrors2=parallelErrors,sandbox2=sandbox,retry=retry_combined,retryOrElse=retryOrElse_Effect,try_2=try_;var tryMap2=tryMap,tryMapPromise2=tryMapPromise,tryPromise2=tryPromise,unsandbox2=unsandbox,allowInterrupt2=allowInterrupt,checkInterruptible2=checkInterruptible,disconnect2=disconnect,interrupt7=interrupt2,interruptWith2=interruptWith,interruptible4=interruptible2,interruptibleMask2=interruptibleMask,onInterrupt2=onInterrupt,uninterruptible2=uninterruptible,uninterruptibleMask3=uninterruptibleMask,liftPredicate2=liftPredicate,as3=as,asSome2=asSome,asSomeError2=asSomeError,asVoid2=asVoid,flip2=flip,flipWith2=flipWith,map16=map10,mapAccum4=mapAccum3,mapBoth3=mapBoth,mapError2=mapError,mapErrorCause2=mapErrorCause,merge7=merge5,negate2=negate,acquireRelease2=acquireRelease,acquireReleaseInterruptible2=acquireReleaseInterruptible,acquireUseRelease2=acquireUseRelease,addFinalizer3=addFinalizer,ensuring2=ensuring,onError2=onError,onExit3=onExit,parallelFinalizers2=parallelFinalizers,sequentialFinalizers2=sequentialFinalizers,finalizersMask2=finalizersMask,scope2=scope,scopeWith2=scopeWith,scopedWith2=scopedWith,scoped3=scopedEffect,using2=using,withEarlyRelease2=withEarlyRelease,awaitAllChildren2=awaitAllChildren,daemonChildren2=daemonChildren,descriptor2=descriptor,descriptorWith2=descriptorWith,diffFiberRefs2=diffFiberRefs,ensuringChild2=ensuringChild,ensuringChildren2=ensuringChildren,fiberId2=fiberId,fiberIdWith2=fiberIdWith,fork3=fork,forkDaemon2=forkDaemon,forkAll2=forkAll,forkIn2=forkIn,forkScoped2=forkScoped,forkWithErrorHandler2=forkWithErrorHandler,fromFiber2=fromFiber,fromFiberEffect2=fromFiberEffect,supervised2=supervised,transplant2=transplant,withConcurrency2=withConcurrency,withScheduler2=withScheduler,withSchedulingPriority2=withSchedulingPriority,withMaxOpsBeforeYield2=withMaxOpsBeforeYield,clock2=clock,clockWith4=clockWith3,withClockScoped2=withClockScoped,withClock2=withClock,console3=console2,consoleWith2=consoleWith,withConsoleScoped2=withConsoleScoped,withConsole2=withConsole,delay2=delay,sleep4=sleep3,timed2=timed,timedWith2=timedWith,timeout2=timeout,timeoutOption2=timeoutOption,timeoutFail2=timeoutFail,timeoutFailCause2=timeoutFailCause,timeoutTo2=timeoutTo,configProviderWith2=configProviderWith,withConfigProvider2=withConfigProvider,withConfigProviderScoped2=withConfigProviderScoped,context3=context,contextWith2=contextWith,contextWithEffect2=contextWithEffect,mapInputContext2=mapInputContext,provide2=effect_provide,provideService2=provideService,provideServiceEffect2=provideServiceEffect,serviceFunction2=serviceFunction,serviceFunctionEffect2=serviceFunctionEffect,serviceFunctions2=serviceFunctions,serviceConstants2=serviceConstants,serviceMembers2=serviceMembers,serviceOption2=serviceOption,serviceOptional2=serviceOptional,updateService2=updateService,Do2=Do,bind3=bind2,bindAll2=bindAll,bindTo3=bindTo2,let_3=let_2;var option2=option,either3=either2,exit2=exit,intoDeferred2=intoDeferred,if_2=if_;var filterOrDie2=filterOrDie,filterOrDieMessage2=filterOrDieMessage,filterOrElse2=filterOrElse,filterOrFail2=filterOrFail,filterEffectOrElse2=filterEffectOrElse,filterEffectOrFail2=filterEffectOrFail,unless2=unless,unlessEffect2=unlessEffect,when2=when,whenEffect2=whenEffect,whenFiberRef2=whenFiberRef,whenRef2=whenRef,flatMap10=flatMap8,andThen4=andThen2,flatten8=flatten6,race2=race,raceAll2=raceAll,raceFirst2=raceFirst,raceWith2=raceWith,summarized2=summarized,tap2=tap,tapBoth2=tapBoth,tapDefect2=tapDefect,tapError2=tapError,tapErrorTag2=tapErrorTag,tapErrorCause2=tapErrorCause,forever3=forever,iterate2=iterate,loop2=loop,repeat=repeat_combined,repeatN2=repeatN,repeatOrElse=repeatOrElse_Effect,schedule=schedule_Effect,scheduleForked2=scheduleForked,scheduleFrom=scheduleFrom_Effect,whileLoop2=whileLoop,getFiberRefs=fiberRefs2,inheritFiberRefs2=inheritFiberRefs,locally=fiberRefLocally,locallyWith=fiberRefLocallyWith,locallyScoped=fiberRefLocallyScoped,locallyScopedWith=fiberRefLocallyScopedWith,patchFiberRefs2=patchFiberRefs,setFiberRefs2=setFiberRefs,updateFiberRefs2=updateFiberRefs,isFailure4=isFailure2,isSuccess3=isSuccess2,match13=match7,matchCause2=matchCause,matchCauseEffect3=matchCauseEffect,matchEffect2=matchEffect,log2=log,logWithLevel2=(level,...message)=>logWithLevel(level)(...message),logTrace2=logTrace,logDebug2=logDebug,logInfo2=logInfo,logWarning2=logWarning,logError2=logError,logFatal2=logFatal,withLogSpan2=withLogSpan,annotateLogs2=annotateLogs,annotateLogsScoped2=annotateLogsScoped,logAnnotations2=logAnnotations,withUnhandledErrorLogLevel2=withUnhandledErrorLogLevel,whenLogLevel2=whenLogLevel,orDie2=orDie,orDieWith2=orDieWith,orElse5=orElse2,orElseFail2=orElseFail,orElseSucceed2=orElseSucceed,firstSuccessOf2=firstSuccessOf,random3=random2,randomWith2=randomWith,withRandom2=withRandom,withRandomScoped2=withRandomScoped,runtime3=runtime2,getRuntimeFlags=runtimeFlags,patchRuntimeFlags=updateRuntimeFlags,withRuntimeFlagsPatch=withRuntimeFlags,withRuntimeFlagsPatchScoped=withRuntimeFlagsScoped,tagMetrics2=tagMetrics,labelMetrics2=labelMetrics,tagMetricsScoped2=tagMetricsScoped,labelMetricsScoped2=labelMetricsScoped,metricLabels2=metricLabels,withMetric2=withMetric,unsafeMakeSemaphore2=unsafeMakeSemaphore,makeSemaphore2=makeSemaphore,unsafeMakeLatch2=unsafeMakeLatch,makeLatch2=makeLatch,runFork2=unsafeForkEffect,runCallback=unsafeRunEffect,runPromise=unsafeRunPromiseEffect,runPromiseExit=unsafeRunPromiseExitEffect,runSync=unsafeRunSyncEffect,runSyncExit=unsafeRunSyncExitEffect,validate2=validate,validateWith2=validateWith,zip6=zipOptions,zipLeft3=zipLeftOptions,zipRight4=zipRightOptions,zipWith8=zipWithOptions,ap=dual(2,(self,that)=>zipWith8(self,that,(f,a)=>f(a))),blocked2=blocked,runRequestBlock2=runRequestBlock,step3=step2,request=dual((args2)=>isRequest2(args2[0]),fromRequest),cacheRequestResult=cacheRequest,withRequestBatching2=withRequestBatching,withRequestCaching2=withRequestCaching,withRequestCache2=withRequestCache,tracer2=tracer,tracerWith4=tracerWith,withTracer2=withTracer,withTracerScoped2=withTracerScoped,withTracerEnabled2=withTracerEnabled,withTracerTiming2=withTracerTiming,annotateSpans2=annotateSpans,annotateCurrentSpan2=annotateCurrentSpan,currentSpan2=currentSpan,currentParentSpan2=currentParentSpan,spanAnnotations2=spanAnnotations,spanLinks2=spanLinks,linkSpans2=linkSpans,linkSpanCurrent2=linkSpanCurrent,makeSpan2=makeSpan,makeSpanScoped2=makeSpanScoped,useSpan2=useSpan,withSpan2=withSpan,functionWithSpan2=functionWithSpan,withSpanScoped2=withSpanScoped,withParentSpan2=withParentSpan,fromNullable3=fromNullable2,optionFromOptional2=optionFromOptional,transposeOption=(self)=>{return isNone(self)?succeedNone2:map16(self.value,some)},transposeMapOption=dual(2,(self,f)=>isNone(self)?succeedNone2:map16(f(self.value),some)),makeTagProxy=(TagClass)=>{let cache=new Map;return new Proxy(TagClass,{get(target,prop,receiver){if(prop in target)return Reflect.get(target,prop,receiver);if(cache.has(prop))return cache.get(prop);let fn=(...args2)=>andThen2(target,(s)=>{if(typeof s[prop]==="function")return cache.set(prop,(...args3)=>andThen2(target,(s2)=>s2[prop](...args3))),s[prop](...args2);return cache.set(prop,andThen2(target,(s2)=>s2[prop])),s[prop]}),cn=andThen2(target,(s)=>s[prop]);return Object.assign(fn,cn),Object.setPrototypeOf(fn,Object.getPrototypeOf(cn)),cache.set(prop,fn),fn}})},Tag2=(id3)=>()=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=new Error;Error.stackTraceLimit=limit;function TagClass(){}return Object.setPrototypeOf(TagClass,TagProto),TagClass.key=id3,Object.defineProperty(TagClass,"use",{get(){return(body)=>andThen2(this,body)}}),Object.defineProperty(TagClass,"stack",{get(){return creationError.stack}}),makeTagProxy(TagClass)},Service=function(){return function(){let[id3,maker]=arguments,proxy="accessors"in maker?maker.accessors:!1,limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=new Error;Error.stackTraceLimit=limit;let patchState="unchecked",TagClass=function(service){if(patchState==="unchecked"){let proto4=Object.getPrototypeOf(service);if(proto4===Object.prototype||proto4===null)patchState="plain";else{let selfProto=Object.getPrototypeOf(this);Object.setPrototypeOf(selfProto,proto4),patchState="patched"}}if(patchState==="plain")Object.assign(this,service);else if(patchState==="patched")return Object.setPrototypeOf(service,Object.getPrototypeOf(this)),service};TagClass.prototype._tag=id3,Object.defineProperty(TagClass,"make",{get(){return(service)=>new this(service)}}),Object.defineProperty(TagClass,"use",{get(){return(body)=>andThen2(this,body)}}),TagClass.key=id3,Object.assign(TagClass,TagProto),Object.defineProperty(TagClass,"stack",{get(){return creationError.stack}});let hasDeps="dependencies"in maker&&maker.dependencies.length>0,layerName=hasDeps?"DefaultWithoutDependencies":"Default",layerCache;if("effect"in maker)Object.defineProperty(TagClass,layerName,{get(){return layerCache??=fromEffect4(TagClass,map16(maker.effect,(_)=>new this(_)))}});else if("scoped"in maker)Object.defineProperty(TagClass,layerName,{get(){return layerCache??=scoped2(TagClass,map16(maker.scoped,(_)=>new this(_)))}});else if("sync"in maker)Object.defineProperty(TagClass,layerName,{get(){return layerCache??=sync2(TagClass,()=>new this(maker.sync()))}});else Object.defineProperty(TagClass,layerName,{get(){return layerCache??=succeed7(TagClass,new this(maker.succeed))}});if(hasDeps){let layerWithDepsCache;Object.defineProperty(TagClass,"Default",{get(){return layerWithDepsCache??=provide(this.DefaultWithoutDependencies,maker.dependencies)}})}return proxy===!0?makeTagProxy(TagClass):TagClass}},fn=function(nameOrBody,...pipeables){let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorDef=new Error;if(Error.stackTraceLimit=limit,typeof nameOrBody!=="string")return defineLength(nameOrBody.length,function(...args2){let limit2=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorCall=new Error;return Error.stackTraceLimit=limit2,fnApply({self:this,body:nameOrBody,args:args2,pipeables,spanName:"<anonymous>",spanOptions:{context:DisablePropagation.context(!0)},errorDef,errorCall})});let name=nameOrBody,options=pipeables[0];return(body,...pipeables2)=>defineLength(body.length,function(...args2){let limit2=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorCall=new Error;return Error.stackTraceLimit=limit2,fnApply({self:this,body,args:args2,pipeables:pipeables2,spanName:name,spanOptions:options,errorDef,errorCall})})};function defineLength(length3,fn2){return Object.defineProperty(fn2,"length",{value:length3,configurable:!0})}function fnApply(options){let effect,fnError=void 0;if(isGeneratorFunction(options.body))effect=fromIterator(()=>options.body.apply(options.self,options.args));else try{effect=options.body.apply(options.self,options.args)}catch(error){fnError=error,effect=die5(error)}if(options.pipeables.length>0)try{for(let x of options.pipeables)effect=x(effect,...options.args)}catch(error){effect=fnError?failCause8(sequential(die(fnError),die(error))):die5(error)}let cache=!1,captureStackTrace=()=>{if(cache!==!1)return cache;if(options.errorCall.stack){let stackDef=options.errorDef.stack.trim().split(`
|
|
30
|
+
`),stackCall=options.errorCall.stack.trim().split(`
|
|
31
|
+
`),endStack=stackDef.slice(2).join(`
|
|
32
|
+
`).trim();if(!endStack.includes("("))endStack=endStack.replace(/at (.*)/,"at ($1)");return cache=`${endStack}
|
|
33
|
+
${stackCall.slice(2).join(`
|
|
34
|
+
`).trim()}`,cache}},opts=options.spanOptions&&"captureStackTrace"in options.spanOptions?options.spanOptions:{captureStackTrace,...options.spanOptions};return withSpan2(effect,options.spanName,opts)}var fnUntraced2=fnUntraced;var get13=fiberRefGet;var getWith=fiberRefGetWith;var currentContext2=currentContext,currentSchedulingPriority2=currentSchedulingPriority;var currentScheduler2=currentScheduler;var currentTracerTimingEnabled2=currentTracerTimingEnabled;var buildWithScope2=buildWithScope;var context4=context2;var merge8=merge6;var EnqueueSymbolKey="effect/QueueEnqueue",EnqueueTypeId=Symbol.for(EnqueueSymbolKey),DequeueSymbolKey="effect/QueueDequeue",DequeueTypeId=Symbol.for(DequeueSymbolKey),QueueStrategySymbolKey="effect/QueueStrategy",QueueStrategyTypeId=Symbol.for(QueueStrategySymbolKey),BackingQueueSymbolKey="effect/BackingQueue",BackingQueueTypeId=Symbol.for(BackingQueueSymbolKey),queueStrategyVariance={_A:(_)=>_},backingQueueVariance={_A:(_)=>_},enqueueVariance={_In:(_)=>_},dequeueVariance={_Out:(_)=>_};class QueueImpl extends Class{queue;takers;shutdownHook;shutdownFlag;strategy;[EnqueueTypeId]=enqueueVariance;[DequeueTypeId]=dequeueVariance;constructor(queue,takers,shutdownHook,shutdownFlag,strategy){super();this.queue=queue,this.takers=takers,this.shutdownHook=shutdownHook,this.shutdownFlag=shutdownFlag,this.strategy=strategy}pipe(){return pipeArguments(this,arguments)}commit(){return this.take}capacity(){return this.queue.capacity()}get size(){return suspend(()=>catchAll(this.unsafeSize(),()=>interrupt2))}unsafeSize(){if(get6(this.shutdownFlag))return none2();return some2(this.queue.length()-length2(this.takers)+this.strategy.surplusSize())}get isEmpty(){return map10(this.size,(size11)=>size11<=0)}get isFull(){return map10(this.size,(size11)=>size11>=this.capacity())}get shutdown(){return uninterruptible(withFiberRuntime((state)=>{return pipe(this.shutdownFlag,set2(!0)),pipe(forEachConcurrentDiscard(unsafePollAll(this.takers),(d)=>deferredInterruptWith(d,state.id()),!1,!1),zipRight(this.strategy.shutdown),whenEffect(deferredSucceed(this.shutdownHook,void 0)),asVoid)}))}get isShutdown(){return sync(()=>get6(this.shutdownFlag))}get awaitShutdown(){return deferredAwait(this.shutdownHook)}isActive(){return!get6(this.shutdownFlag)}unsafeOffer(value){if(get6(this.shutdownFlag))return!1;let noRemaining;if(this.queue.length()===0){let taker=pipe(this.takers,poll2(EmptyMutableQueue));if(taker!==EmptyMutableQueue)unsafeCompleteDeferred(taker,value),noRemaining=!0;else noRemaining=!1}else noRemaining=!1;if(noRemaining)return!0;let succeeded=this.queue.offer(value);return unsafeCompleteTakers(this.strategy,this.queue,this.takers),succeeded}offer(value){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let noRemaining;if(this.queue.length()===0){let taker=pipe(this.takers,poll2(EmptyMutableQueue));if(taker!==EmptyMutableQueue)unsafeCompleteDeferred(taker,value),noRemaining=!0;else noRemaining=!1}else noRemaining=!1;if(noRemaining)return succeed(!0);let succeeded=this.queue.offer(value);return unsafeCompleteTakers(this.strategy,this.queue,this.takers),succeeded?succeed(!0):this.strategy.handleSurplus([value],this.queue,this.takers,this.shutdownFlag)})}offerAll(iterable){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let values3=fromIterable(iterable),pTakers=this.queue.length()===0?fromIterable(unsafePollN(this.takers,values3.length)):empty2,[forTakers,remaining]=pipe(values3,splitAt(pTakers.length));for(let i=0;i<pTakers.length;i++){let taker=pTakers[i],item=forTakers[i];unsafeCompleteDeferred(taker,item)}if(remaining.length===0)return succeed(!0);let surplus=this.queue.offerAll(remaining);return unsafeCompleteTakers(this.strategy,this.queue,this.takers),isEmpty(surplus)?succeed(!0):this.strategy.handleSurplus(surplus,this.queue,this.takers,this.shutdownFlag)})}get take(){return withFiberRuntime((state)=>{if(get6(this.shutdownFlag))return interrupt2;let item=this.queue.poll(EmptyMutableQueue);if(item!==EmptyMutableQueue)return this.strategy.unsafeOnQueueEmptySpace(this.queue,this.takers),succeed(item);else{let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return pipe(this.takers,offer(deferred)),unsafeCompleteTakers(this.strategy,this.queue,this.takers),get6(this.shutdownFlag)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>{return sync(()=>unsafeRemove(this.takers,deferred))}))}})}get takeAll(){return suspend(()=>{return get6(this.shutdownFlag)?interrupt2:sync(()=>{let values3=this.queue.pollUpTo(Number.POSITIVE_INFINITY);return this.strategy.unsafeOnQueueEmptySpace(this.queue,this.takers),fromIterable2(values3)})})}takeUpTo(max6){return suspend(()=>get6(this.shutdownFlag)?interrupt2:sync(()=>{let values3=this.queue.pollUpTo(max6);return this.strategy.unsafeOnQueueEmptySpace(this.queue,this.takers),fromIterable2(values3)}))}takeBetween(min4,max6){return suspend(()=>takeRemainderLoop(this,min4,max6,empty5()))}}var takeRemainderLoop=(self,min4,max6,acc)=>{if(max6<min4)return succeed(acc);return pipe(takeUpTo(self,max6),flatMap8((bs)=>{let remaining=min4-bs.length;if(remaining===1)return pipe(take2(self),map10((b)=>pipe(acc,appendAll2(bs),append2(b))));if(remaining>1)return pipe(take2(self),flatMap8((b)=>takeRemainderLoop(self,remaining-1,max6-bs.length-1,pipe(acc,appendAll2(bs),append2(b)))));return succeed(pipe(acc,appendAll2(bs)))}))},isQueue=(u)=>isEnqueue(u)&&isDequeue(u),isEnqueue=(u)=>hasProperty(u,EnqueueTypeId),isDequeue=(u)=>hasProperty(u,DequeueTypeId),bounded2=(requestedCapacity)=>pipe(sync(()=>bounded(requestedCapacity)),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),backPressureStrategy()))),dropping=(requestedCapacity)=>pipe(sync(()=>bounded(requestedCapacity)),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),droppingStrategy()))),sliding=(requestedCapacity)=>pipe(sync(()=>bounded(requestedCapacity)),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),slidingStrategy()))),unbounded2=()=>pipe(sync(()=>unbounded()),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),droppingStrategy()))),unsafeMake9=(queue,takers,shutdownHook,shutdownFlag,strategy)=>{return new QueueImpl(queue,takers,shutdownHook,shutdownFlag,strategy)},make43=(queue,strategy)=>pipe(deferredMake(),map10((deferred)=>unsafeMake9(queue,unbounded(),deferred,make12(!1),strategy)));class BackingQueueFromMutableQueue{mutable;[BackingQueueTypeId]=backingQueueVariance;constructor(mutable){this.mutable=mutable}poll(def){return poll2(this.mutable,def)}pollUpTo(limit){return pollUpTo(this.mutable,limit)}offerAll(elements){return offerAll(this.mutable,elements)}offer(element){return offer(this.mutable,element)}capacity(){return capacity(this.mutable)}length(){return length2(this.mutable)}}var backingQueueFromMutableQueue=(mutable)=>new BackingQueueFromMutableQueue(mutable),capacity2=(self)=>self.capacity(),size11=(self)=>self.size,isFull=(self)=>self.isFull,isEmpty10=(self)=>self.isEmpty,isShutdown=(self)=>self.isShutdown,awaitShutdown=(self)=>self.awaitShutdown,shutdown=(self)=>self.shutdown,offer2=dual(2,(self,value)=>self.offer(value)),unsafeOffer=dual(2,(self,value)=>self.unsafeOffer(value)),offerAll2=dual(2,(self,iterable)=>self.offerAll(iterable)),poll5=(self)=>map10(self.takeUpTo(1),head2),take2=(self)=>self.take,takeAll=(self)=>self.takeAll,takeUpTo=dual(2,(self,max6)=>self.takeUpTo(max6)),takeBetween=dual(3,(self,min4,max6)=>self.takeBetween(min4,max6)),takeN=dual(2,(self,n)=>self.takeBetween(n,n)),backPressureStrategy=()=>new BackPressureStrategy,droppingStrategy=()=>new DroppingStrategy,slidingStrategy=()=>new SlidingStrategy;class BackPressureStrategy{[QueueStrategyTypeId]=queueStrategyVariance;putters=unbounded();surplusSize(){return length2(this.putters)}onCompleteTakersWithEmptyQueue(takers){while(!isEmpty7(this.putters)&&!isEmpty7(takers)){let taker=poll2(takers,void 0),putter=poll2(this.putters,void 0);if(putter[2])unsafeCompleteDeferred(putter[1],!0);unsafeCompleteDeferred(taker,putter[0])}}get shutdown(){return pipe(fiberId,flatMap8((fiberId3)=>pipe(sync(()=>unsafePollAll(this.putters)),flatMap8((putters)=>forEachConcurrentDiscard(putters,([_,deferred,isLastItem])=>isLastItem?pipe(deferredInterruptWith(deferred,fiberId3),asVoid):void_,!1,!1)))))}handleSurplus(iterable,queue,takers,isShutdown2){return withFiberRuntime((state)=>{let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return this.unsafeOffer(iterable,deferred),this.unsafeOnQueueEmptySpace(queue,takers),unsafeCompleteTakers(this,queue,takers),get6(isShutdown2)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>sync(()=>this.unsafeRemove(deferred))))})}unsafeOnQueueEmptySpace(queue,takers){let keepPolling=!0;while(keepPolling&&(queue.capacity()===Number.POSITIVE_INFINITY||queue.length()<queue.capacity())){let putter=pipe(this.putters,poll2(EmptyMutableQueue));if(putter===EmptyMutableQueue)keepPolling=!1;else{let offered=queue.offer(putter[0]);if(offered&&putter[2])unsafeCompleteDeferred(putter[1],!0);else if(!offered)unsafeOfferAll(this.putters,pipe(unsafePollAll(this.putters),prepend2(putter)));unsafeCompleteTakers(this,queue,takers)}}}unsafeOffer(iterable,deferred){let stuff=fromIterable(iterable);for(let i=0;i<stuff.length;i++){let value=stuff[i];if(i===stuff.length-1)pipe(this.putters,offer([value,deferred,!0]));else pipe(this.putters,offer([value,deferred,!1]))}}unsafeRemove(deferred){unsafeOfferAll(this.putters,pipe(unsafePollAll(this.putters),filter3(([,_])=>_!==deferred)))}}class DroppingStrategy{[QueueStrategyTypeId]=queueStrategyVariance;surplusSize(){return 0}get shutdown(){return void_}onCompleteTakersWithEmptyQueue(){}handleSurplus(_iterable,_queue,_takers,_isShutdown){return succeed(!1)}unsafeOnQueueEmptySpace(_queue,_takers){}}class SlidingStrategy{[QueueStrategyTypeId]=queueStrategyVariance;surplusSize(){return 0}get shutdown(){return void_}onCompleteTakersWithEmptyQueue(){}handleSurplus(iterable,queue,takers,_isShutdown){return sync(()=>{return this.unsafeOffer(queue,iterable),unsafeCompleteTakers(this,queue,takers),!0})}unsafeOnQueueEmptySpace(_queue,_takers){}unsafeOffer(queue,iterable){let iterator=iterable[Symbol.iterator](),next4,offering=!0;while(!(next4=iterator.next()).done&&offering){if(queue.capacity()===0)return;queue.poll(EmptyMutableQueue),offering=queue.offer(next4.value)}}}var unsafeCompleteDeferred=(deferred,a)=>{return deferredUnsafeDone(deferred,succeed(a))},unsafeOfferAll=(queue,as4)=>{return pipe(queue,offerAll(as4))},unsafePollAll=(queue)=>{return pipe(queue,pollUpTo(Number.POSITIVE_INFINITY))},unsafePollN=(queue,max6)=>{return pipe(queue,pollUpTo(max6))},unsafeRemove=(queue,a)=>{unsafeOfferAll(queue,pipe(unsafePollAll(queue),filter3((b)=>a!==b)))},unsafeCompleteTakers=(strategy,queue,takers)=>{let keepPolling=!0;while(keepPolling&&queue.length()!==0){let taker=pipe(takers,poll2(EmptyMutableQueue));if(taker!==EmptyMutableQueue){let element=queue.poll(EmptyMutableQueue);if(element!==EmptyMutableQueue)unsafeCompleteDeferred(taker,element),strategy.unsafeOnQueueEmptySpace(queue,takers);else unsafeOfferAll(takers,pipe(unsafePollAll(takers),prepend2(taker)));keepPolling=!0}else keepPolling=!1}if(keepPolling&&queue.length()===0&&!isEmpty7(takers))strategy.onCompleteTakersWithEmptyQueue(takers)};var AbsentValue=Symbol.for("effect/PubSub/AbsentValue"),addSubscribers=(subscription,pollers)=>(subscribers)=>{if(!subscribers.has(subscription))subscribers.set(subscription,new Set);subscribers.get(subscription).add(pollers)},removeSubscribers=(subscription,pollers)=>(subscribers)=>{if(!subscribers.has(subscription))return;let set7=subscribers.get(subscription);if(set7.delete(pollers),set7.size===0)subscribers.delete(subscription)},bounded3=(capacity3)=>suspend(()=>{let pubsub=makeBoundedPubSub(capacity3);return makePubSub(pubsub,new BackPressureStrategy2)}),dropping2=(capacity3)=>suspend(()=>{let pubsub=makeBoundedPubSub(capacity3);return makePubSub(pubsub,new DroppingStrategy2)}),sliding2=(capacity3)=>suspend(()=>{let pubsub=makeBoundedPubSub(capacity3);return makePubSub(pubsub,new SlidingStrategy2)}),unbounded3=(options)=>suspend(()=>{let pubsub=makeUnboundedPubSub(options);return makePubSub(pubsub,new DroppingStrategy2)});var shutdown2=(self)=>self.shutdown;var subscribe=(self)=>self.subscribe,makeBoundedPubSub=(capacity3)=>{let options=typeof capacity3==="number"?{capacity:capacity3}:capacity3;ensureCapacity(options.capacity);let replayBuffer=options.replay&&options.replay>0?new ReplayBuffer(Math.ceil(options.replay)):void 0;if(options.capacity===1)return new BoundedPubSubSingle(replayBuffer);else if(nextPow2(options.capacity)===options.capacity)return new BoundedPubSubPow2(options.capacity,replayBuffer);else return new BoundedPubSubArb(options.capacity,replayBuffer)},makeUnboundedPubSub=(options)=>new UnboundedPubSub(options?.replay?new ReplayBuffer(options.replay):void 0),makeSubscription=(pubsub,subscribers,strategy)=>map10(deferredMake(),(deferred)=>unsafeMakeSubscription(pubsub,subscribers,pubsub.subscribe(),unbounded(),deferred,make12(!1),strategy)),unsafeMakeSubscription=(pubsub,subscribers,subscription,pollers,shutdownHook,shutdownFlag,strategy)=>new SubscriptionImpl(pubsub,subscribers,subscription,pollers,shutdownHook,shutdownFlag,strategy,pubsub.replayWindow());class BoundedPubSubArb{capacity;replayBuffer;array;publisherIndex=0;subscribers;subscriberCount=0;subscribersIndex=0;constructor(capacity3,replayBuffer){this.capacity=capacity3,this.replayBuffer=replayBuffer,this.array=Array.from({length:capacity3}),this.subscribers=Array.from({length:capacity3})}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}isEmpty(){return this.publisherIndex===this.subscribersIndex}isFull(){return this.publisherIndex===this.subscribersIndex+this.capacity}size(){return this.publisherIndex-this.subscribersIndex}publish(value){if(this.isFull())return!1;if(this.subscriberCount!==0){let index=this.publisherIndex%this.capacity;this.array[index]=value,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1}if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.subscriberCount===0){if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}let chunk2=fromIterable2(elements),n=chunk2.length,size12=this.publisherIndex-this.subscribersIndex,available=this.capacity-size12,forPubSub=Math.min(n,available);if(forPubSub===0)return chunk2;let iteratorIndex=0,publishAllIndex=this.publisherIndex+forPubSub;while(this.publisherIndex!==publishAllIndex){let a=unsafeGet4(chunk2,iteratorIndex++),index=this.publisherIndex%this.capacity;if(this.array[index]=a,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1,this.replayBuffer)this.replayBuffer.offer(a)}return drop2(chunk2,iteratorIndex)}slide(){if(this.subscribersIndex!==this.publisherIndex){let index=this.subscribersIndex%this.capacity;this.array[index]=AbsentValue,this.subscribers[index]=0,this.subscribersIndex+=1}if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.subscriberCount+=1,new BoundedPubSubArbSubscription(this,this.publisherIndex,!1)}}class BoundedPubSubArbSubscription{self;subscriberIndex;unsubscribed;constructor(self,subscriberIndex,unsubscribed){this.self=self,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){return this.unsubscribed||this.self.publisherIndex===this.subscriberIndex||this.self.publisherIndex===this.self.subscribersIndex}size(){if(this.unsubscribed)return 0;return this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(default_){if(this.unsubscribed)return default_;if(this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex),this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex%this.self.capacity,elem=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;return this.subscriberIndex+=1,elem}return default_}pollUpTo(n){if(this.unsubscribed)return empty5();this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);let size12=this.self.publisherIndex-this.subscriberIndex,toPoll=Math.min(n,size12);if(toPoll<=0)return empty5();let builder=[],pollUpToIndex=this.subscriberIndex+toPoll;while(this.subscriberIndex!==pollUpToIndex){let index=this.subscriberIndex%this.self.capacity,a=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;builder.push(a),this.subscriberIndex+=1}return fromIterable2(builder)}unsubscribe(){if(!this.unsubscribed){this.unsubscribed=!0,this.self.subscriberCount-=1,this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);while(this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex%this.self.capacity;if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;this.subscriberIndex+=1}}}}class BoundedPubSubPow2{capacity;replayBuffer;array;mask;publisherIndex=0;subscribers;subscriberCount=0;subscribersIndex=0;constructor(capacity3,replayBuffer){this.capacity=capacity3,this.replayBuffer=replayBuffer,this.array=Array.from({length:capacity3}),this.mask=capacity3-1,this.subscribers=Array.from({length:capacity3})}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}isEmpty(){return this.publisherIndex===this.subscribersIndex}isFull(){return this.publisherIndex===this.subscribersIndex+this.capacity}size(){return this.publisherIndex-this.subscribersIndex}publish(value){if(this.isFull())return!1;if(this.subscriberCount!==0){let index=this.publisherIndex&this.mask;this.array[index]=value,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1}if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.subscriberCount===0){if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}let chunk2=fromIterable2(elements),n=chunk2.length,size12=this.publisherIndex-this.subscribersIndex,available=this.capacity-size12,forPubSub=Math.min(n,available);if(forPubSub===0)return chunk2;let iteratorIndex=0,publishAllIndex=this.publisherIndex+forPubSub;while(this.publisherIndex!==publishAllIndex){let elem=unsafeGet4(chunk2,iteratorIndex++),index=this.publisherIndex&this.mask;if(this.array[index]=elem,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1,this.replayBuffer)this.replayBuffer.offer(elem)}return drop2(chunk2,iteratorIndex)}slide(){if(this.subscribersIndex!==this.publisherIndex){let index=this.subscribersIndex&this.mask;this.array[index]=AbsentValue,this.subscribers[index]=0,this.subscribersIndex+=1}if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.subscriberCount+=1,new BoundedPubSubPow2Subscription(this,this.publisherIndex,!1)}}class BoundedPubSubPow2Subscription{self;subscriberIndex;unsubscribed;constructor(self,subscriberIndex,unsubscribed){this.self=self,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){return this.unsubscribed||this.self.publisherIndex===this.subscriberIndex||this.self.publisherIndex===this.self.subscribersIndex}size(){if(this.unsubscribed)return 0;return this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(default_){if(this.unsubscribed)return default_;if(this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex),this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex&this.self.mask,elem=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;return this.subscriberIndex+=1,elem}return default_}pollUpTo(n){if(this.unsubscribed)return empty5();this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);let size12=this.self.publisherIndex-this.subscriberIndex,toPoll=Math.min(n,size12);if(toPoll<=0)return empty5();let builder=[],pollUpToIndex=this.subscriberIndex+toPoll;while(this.subscriberIndex!==pollUpToIndex){let index=this.subscriberIndex&this.self.mask,elem=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;builder.push(elem),this.subscriberIndex+=1}return fromIterable2(builder)}unsubscribe(){if(!this.unsubscribed){this.unsubscribed=!0,this.self.subscriberCount-=1,this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);while(this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex&this.self.mask;if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;this.subscriberIndex+=1}}}}class BoundedPubSubSingle{replayBuffer;publisherIndex=0;subscriberCount=0;subscribers=0;value=AbsentValue;capacity=1;constructor(replayBuffer){this.replayBuffer=replayBuffer}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}pipe(){return pipeArguments(this,arguments)}isEmpty(){return this.subscribers===0}isFull(){return!this.isEmpty()}size(){return this.isEmpty()?0:1}publish(value){if(this.isFull())return!1;if(this.subscriberCount!==0)this.value=value,this.subscribers=this.subscriberCount,this.publisherIndex+=1;if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.subscriberCount===0){if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}let chunk2=fromIterable2(elements);if(isEmpty(chunk2))return chunk2;if(this.publish(unsafeHead2(chunk2)))return drop2(chunk2,1);else return chunk2}slide(){if(this.isFull())this.subscribers=0,this.value=AbsentValue;if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.subscriberCount+=1,new BoundedPubSubSingleSubscription(this,this.publisherIndex,!1)}}class BoundedPubSubSingleSubscription{self;subscriberIndex;unsubscribed;constructor(self,subscriberIndex,unsubscribed){this.self=self,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){return this.unsubscribed||this.self.subscribers===0||this.subscriberIndex===this.self.publisherIndex}size(){return this.isEmpty()?0:1}poll(default_){if(this.isEmpty())return default_;let elem=this.self.value;if(this.self.subscribers-=1,this.self.subscribers===0)this.self.value=AbsentValue;return this.subscriberIndex+=1,elem}pollUpTo(n){if(this.isEmpty()||n<1)return empty5();let a=this.self.value;if(this.self.subscribers-=1,this.self.subscribers===0)this.self.value=AbsentValue;return this.subscriberIndex+=1,of2(a)}unsubscribe(){if(!this.unsubscribed){if(this.unsubscribed=!0,this.self.subscriberCount-=1,this.subscriberIndex!==this.self.publisherIndex){if(this.self.subscribers-=1,this.self.subscribers===0)this.self.value=AbsentValue}}}}class UnboundedPubSub{replayBuffer;publisherHead={value:AbsentValue,subscribers:0,next:null};publisherTail=this.publisherHead;publisherIndex=0;subscribersIndex=0;capacity=Number.MAX_SAFE_INTEGER;constructor(replayBuffer){this.replayBuffer=replayBuffer}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}isEmpty(){return this.publisherHead===this.publisherTail}isFull(){return!1}size(){return this.publisherIndex-this.subscribersIndex}publish(value){let subscribers=this.publisherTail.subscribers;if(subscribers!==0)this.publisherTail.next={value,subscribers,next:null},this.publisherTail=this.publisherTail.next,this.publisherIndex+=1;if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.publisherTail.subscribers!==0)for(let a of elements)this.publish(a);else if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}slide(){if(this.publisherHead!==this.publisherTail)this.publisherHead=this.publisherHead.next,this.publisherHead.value=AbsentValue,this.subscribersIndex+=1;if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.publisherTail.subscribers+=1,new UnboundedPubSubSubscription(this,this.publisherTail,this.publisherIndex,!1)}}class UnboundedPubSubSubscription{self;subscriberHead;subscriberIndex;unsubscribed;constructor(self,subscriberHead,subscriberIndex,unsubscribed){this.self=self,this.subscriberHead=subscriberHead,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){if(this.unsubscribed)return!0;let empty34=!0,loop3=!0;while(loop3)if(this.subscriberHead===this.self.publisherTail)loop3=!1;else if(this.subscriberHead.next.value!==AbsentValue)empty34=!1,loop3=!1;else this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1;return empty34}size(){if(this.unsubscribed)return 0;return this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(default_){if(this.unsubscribed)return default_;let loop3=!0,polled=default_;while(loop3)if(this.subscriberHead===this.self.publisherTail)loop3=!1;else{let elem=this.subscriberHead.next.value;if(elem!==AbsentValue){if(polled=elem,this.subscriberHead.subscribers-=1,this.subscriberHead.subscribers===0)this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=AbsentValue,this.self.subscribersIndex+=1;loop3=!1}this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1}return polled}pollUpTo(n){let builder=[],default_=AbsentValue,i=0;while(i!==n){let a=this.poll(default_);if(a===default_)i=n;else builder.push(a),i+=1}return fromIterable2(builder)}unsubscribe(){if(!this.unsubscribed){this.unsubscribed=!0,this.self.publisherTail.subscribers-=1;while(this.subscriberHead!==this.self.publisherTail){if(this.subscriberHead.next.value!==AbsentValue){if(this.subscriberHead.subscribers-=1,this.subscriberHead.subscribers===0)this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=AbsentValue,this.self.subscribersIndex+=1}this.subscriberHead=this.subscriberHead.next}}}}class SubscriptionImpl extends Class{pubsub;subscribers;subscription;pollers;shutdownHook;shutdownFlag;strategy;replayWindow;[DequeueTypeId]=dequeueVariance;constructor(pubsub,subscribers,subscription,pollers,shutdownHook,shutdownFlag,strategy,replayWindow){super();this.pubsub=pubsub,this.subscribers=subscribers,this.subscription=subscription,this.pollers=pollers,this.shutdownHook=shutdownHook,this.shutdownFlag=shutdownFlag,this.strategy=strategy,this.replayWindow=replayWindow}commit(){return this.take}pipe(){return pipeArguments(this,arguments)}capacity(){return this.pubsub.capacity}isActive(){return!get6(this.shutdownFlag)}get size(){return suspend(()=>get6(this.shutdownFlag)?interrupt2:succeed(this.subscription.size()+this.replayWindow.remaining))}unsafeSize(){if(get6(this.shutdownFlag))return none2();return some2(this.subscription.size()+this.replayWindow.remaining)}get isFull(){return suspend(()=>get6(this.shutdownFlag)?interrupt2:succeed(this.subscription.size()===this.capacity()))}get isEmpty(){return map10(this.size,(size12)=>size12===0)}get shutdown(){return uninterruptible(withFiberRuntime((state)=>{return set2(this.shutdownFlag,!0),pipe(forEachParUnbounded(unsafePollAllQueue(this.pollers),(d)=>deferredInterruptWith(d,state.id()),!1),zipRight(sync(()=>{this.subscribers.delete(this.subscription),this.subscription.unsubscribe(),this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers)})),whenEffect(deferredSucceed(this.shutdownHook,void 0)),asVoid)}))}get isShutdown(){return sync(()=>get6(this.shutdownFlag))}get awaitShutdown(){return deferredAwait(this.shutdownHook)}get take(){return withFiberRuntime((state)=>{if(get6(this.shutdownFlag))return interrupt2;if(this.replayWindow.remaining>0){let message2=this.replayWindow.take();return succeed(message2)}let message=isEmpty7(this.pollers)?this.subscription.poll(EmptyMutableQueue):EmptyMutableQueue;if(message===EmptyMutableQueue){let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return pipe(this.pollers,offer(deferred)),pipe(this.subscribers,addSubscribers(this.subscription,this.pollers)),this.strategy.unsafeCompletePollers(this.pubsub,this.subscribers,this.subscription,this.pollers),get6(this.shutdownFlag)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>sync(()=>unsafeRemove2(this.pollers,deferred))))}else return this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers),succeed(message)})}get takeAll(){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let as4=isEmpty7(this.pollers)?unsafePollAllSubscription(this.subscription):empty5();if(this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers),this.replayWindow.remaining>0)return succeed(appendAll2(this.replayWindow.takeAll(),as4));return succeed(as4)})}takeUpTo(max6){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let replay=void 0;if(this.replayWindow.remaining>=max6){let as5=this.replayWindow.takeN(max6);return succeed(as5)}else if(this.replayWindow.remaining>0)replay=this.replayWindow.takeAll(),max6=max6-replay.length;let as4=isEmpty7(this.pollers)?unsafePollN2(this.subscription,max6):empty5();return this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers),replay?succeed(appendAll2(replay,as4)):succeed(as4)})}takeBetween(min4,max6){return suspend(()=>takeRemainderLoop2(this,min4,max6,empty5()))}}var takeRemainderLoop2=(self,min4,max6,acc)=>{if(max6<min4)return succeed(acc);return pipe(self.takeUpTo(max6),flatMap8((bs)=>{let remaining=min4-bs.length;if(remaining===1)return pipe(self.take,map10((b)=>pipe(acc,appendAll2(bs),append2(b))));if(remaining>1)return pipe(self.take,flatMap8((b)=>takeRemainderLoop2(self,remaining-1,max6-bs.length-1,pipe(acc,appendAll2(bs),append2(b)))));return succeed(pipe(acc,appendAll2(bs)))}))};class PubSubImpl{pubsub;subscribers;scope;shutdownHook;shutdownFlag;strategy;[EnqueueTypeId]=enqueueVariance;[DequeueTypeId]=dequeueVariance;constructor(pubsub,subscribers,scope4,shutdownHook,shutdownFlag,strategy){this.pubsub=pubsub,this.subscribers=subscribers,this.scope=scope4,this.shutdownHook=shutdownHook,this.shutdownFlag=shutdownFlag,this.strategy=strategy}capacity(){return this.pubsub.capacity}get size(){return suspend(()=>get6(this.shutdownFlag)?interrupt2:sync(()=>this.pubsub.size()))}unsafeSize(){if(get6(this.shutdownFlag))return none2();return some2(this.pubsub.size())}get isFull(){return map10(this.size,(size12)=>size12===this.capacity())}get isEmpty(){return map10(this.size,(size12)=>size12===0)}get awaitShutdown(){return deferredAwait(this.shutdownHook)}get isShutdown(){return sync(()=>get6(this.shutdownFlag))}get shutdown(){return uninterruptible(withFiberRuntime((state)=>{return pipe(this.shutdownFlag,set2(!0)),pipe(this.scope.close(exitInterrupt(state.id())),zipRight(this.strategy.shutdown),whenEffect(deferredSucceed(this.shutdownHook,void 0)),asVoid)}))}publish(value){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;if(this.pubsub.publish(value))return this.strategy.unsafeCompleteSubscribers(this.pubsub,this.subscribers),succeed(!0);return this.strategy.handleSurplus(this.pubsub,this.subscribers,of2(value),this.shutdownFlag)})}isActive(){return!get6(this.shutdownFlag)}unsafeOffer(value){if(get6(this.shutdownFlag))return!1;if(this.pubsub.publish(value))return this.strategy.unsafeCompleteSubscribers(this.pubsub,this.subscribers),!0;return!1}publishAll(elements){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let surplus=unsafePublishAll(this.pubsub,elements);if(this.strategy.unsafeCompleteSubscribers(this.pubsub,this.subscribers),isEmpty(surplus))return succeed(!0);return this.strategy.handleSurplus(this.pubsub,this.subscribers,surplus,this.shutdownFlag)})}get subscribe(){let acquire=tap(all4([this.scope.fork(sequential2),makeSubscription(this.pubsub,this.subscribers,this.strategy)]),(tuple3)=>tuple3[0].addFinalizer(()=>tuple3[1].shutdown));return map10(acquireRelease(acquire,(tuple3,exit3)=>tuple3[0].close(exit3)),(tuple3)=>tuple3[1])}offer(value){return this.publish(value)}offerAll(elements){return this.publishAll(elements)}pipe(){return pipeArguments(this,arguments)}}var makePubSub=(pubsub,strategy)=>flatMap8(scopeMake(),(scope4)=>map10(deferredMake(),(deferred)=>unsafeMakePubSub(pubsub,new Map,scope4,deferred,make12(!1),strategy))),unsafeMakePubSub=(pubsub,subscribers,scope4,shutdownHook,shutdownFlag,strategy)=>new PubSubImpl(pubsub,subscribers,scope4,shutdownHook,shutdownFlag,strategy),ensureCapacity=(capacity3)=>{if(capacity3<=0)throw new InvalidPubSubCapacityException(`Cannot construct PubSub with capacity of ${capacity3}`)},unsafeCompleteDeferred2=(deferred,a)=>{deferredUnsafeDone(deferred,succeed(a))},unsafeOfferAll2=(queue,as4)=>{return pipe(queue,offerAll(as4))},unsafePollAllQueue=(queue)=>{return pipe(queue,pollUpTo(Number.POSITIVE_INFINITY))},unsafePollAllSubscription=(subscription)=>{return subscription.pollUpTo(Number.POSITIVE_INFINITY)},unsafePollN2=(subscription,max6)=>{return subscription.pollUpTo(max6)},unsafePublishAll=(pubsub,as4)=>{return pubsub.publishAll(as4)},unsafeRemove2=(queue,value)=>{unsafeOfferAll2(queue,pipe(unsafePollAllQueue(queue),filter3((elem)=>elem!==value)))};class BackPressureStrategy2{publishers=unbounded();get shutdown(){return flatMap8(fiberId,(fiberId3)=>flatMap8(sync(()=>unsafePollAllQueue(this.publishers)),(publishers)=>forEachConcurrentDiscard(publishers,([_,deferred,last4])=>last4?pipe(deferredInterruptWith(deferred,fiberId3),asVoid):void_,!1,!1)))}handleSurplus(pubsub,subscribers,elements,isShutdown2){return withFiberRuntime((state)=>{let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return this.unsafeOffer(elements,deferred),this.unsafeOnPubSubEmptySpace(pubsub,subscribers),this.unsafeCompleteSubscribers(pubsub,subscribers),get6(isShutdown2)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>sync(()=>this.unsafeRemove(deferred))))})}unsafeOnPubSubEmptySpace(pubsub,subscribers){let keepPolling=!0;while(keepPolling&&!pubsub.isFull()){let publisher=pipe(this.publishers,poll2(EmptyMutableQueue));if(publisher===EmptyMutableQueue)keepPolling=!1;else{let published=pubsub.publish(publisher[0]);if(published&&publisher[2])unsafeCompleteDeferred2(publisher[1],!0);else if(!published)unsafeOfferAll2(this.publishers,pipe(unsafePollAllQueue(this.publishers),prepend2(publisher)));this.unsafeCompleteSubscribers(pubsub,subscribers)}}}unsafeCompletePollers(pubsub,subscribers,subscription,pollers){return unsafeStrategyCompletePollers(this,pubsub,subscribers,subscription,pollers)}unsafeCompleteSubscribers(pubsub,subscribers){return unsafeStrategyCompleteSubscribers(this,pubsub,subscribers)}unsafeOffer(elements,deferred){let iterator=elements[Symbol.iterator](),next4=iterator.next();if(!next4.done)while(!0){let value=next4.value;if(next4=iterator.next(),next4.done){pipe(this.publishers,offer([value,deferred,!0]));break}pipe(this.publishers,offer([value,deferred,!1]))}}unsafeRemove(deferred){unsafeOfferAll2(this.publishers,pipe(unsafePollAllQueue(this.publishers),filter3(([_,a])=>a!==deferred)))}}class DroppingStrategy2{get shutdown(){return void_}handleSurplus(_pubsub,_subscribers,_elements,_isShutdown){return succeed(!1)}unsafeOnPubSubEmptySpace(_pubsub,_subscribers){}unsafeCompletePollers(pubsub,subscribers,subscription,pollers){return unsafeStrategyCompletePollers(this,pubsub,subscribers,subscription,pollers)}unsafeCompleteSubscribers(pubsub,subscribers){return unsafeStrategyCompleteSubscribers(this,pubsub,subscribers)}}class SlidingStrategy2{get shutdown(){return void_}handleSurplus(pubsub,subscribers,elements,_isShutdown){return sync(()=>{return this.unsafeSlidingPublish(pubsub,elements),this.unsafeCompleteSubscribers(pubsub,subscribers),!0})}unsafeOnPubSubEmptySpace(_pubsub,_subscribers){}unsafeCompletePollers(pubsub,subscribers,subscription,pollers){return unsafeStrategyCompletePollers(this,pubsub,subscribers,subscription,pollers)}unsafeCompleteSubscribers(pubsub,subscribers){return unsafeStrategyCompleteSubscribers(this,pubsub,subscribers)}unsafeSlidingPublish(pubsub,elements){let it=elements[Symbol.iterator](),next4=it.next();if(!next4.done&&pubsub.capacity>0){let a=next4.value,loop3=!0;while(loop3){pubsub.slide();let pub=pubsub.publish(a);if(pub&&(next4=it.next())&&!next4.done)a=next4.value;else if(pub)loop3=!1}}}}var unsafeStrategyCompletePollers=(strategy,pubsub,subscribers,subscription,pollers)=>{let keepPolling=!0;while(keepPolling&&!subscription.isEmpty()){let poller=pipe(pollers,poll2(EmptyMutableQueue));if(poller===EmptyMutableQueue)if(pipe(subscribers,removeSubscribers(subscription,pollers)),isEmpty7(pollers))keepPolling=!1;else pipe(subscribers,addSubscribers(subscription,pollers));else{let pollResult=subscription.poll(EmptyMutableQueue);if(pollResult===EmptyMutableQueue)unsafeOfferAll2(pollers,pipe(unsafePollAllQueue(pollers),prepend2(poller)));else unsafeCompleteDeferred2(poller,pollResult),strategy.unsafeOnPubSubEmptySpace(pubsub,subscribers)}}},unsafeStrategyCompleteSubscribers=(strategy,pubsub,subscribers)=>{for(let[subscription,pollersSet]of subscribers)for(let pollers of pollersSet)strategy.unsafeCompletePollers(pubsub,subscribers,subscription,pollers)};class ReplayBuffer{capacity;constructor(capacity3){this.capacity=capacity3}head={value:AbsentValue,next:null};tail=this.head;size=0;index=0;slide(){this.index++}offer(a){if(this.tail.value=a,this.tail.next={value:AbsentValue,next:null},this.tail=this.tail.next,this.size===this.capacity)this.head=this.head.next;else this.size+=1}offerAll(as4){for(let a of as4)this.offer(a)}}class ReplayWindowImpl{buffer;head;index;remaining;constructor(buffer){this.buffer=buffer,this.index=buffer.index,this.remaining=buffer.size,this.head=buffer.head}fastForward(){while(this.index<this.buffer.index)this.head=this.head.next,this.index++}take(){if(this.remaining===0)return;else if(this.index<this.buffer.index)this.fastForward();this.remaining--;let value=this.head.value;return this.head=this.head.next,value}takeN(n){if(this.remaining===0)return empty5();else if(this.index<this.buffer.index)this.fastForward();let len=Math.min(n,this.remaining),items=new Array(len);for(let i=0;i<len;i++){let value=this.head.value;this.head=this.head.next,items[i]=value}return this.remaining-=len,unsafeFromArray(items)}takeAll(){return this.takeN(this.remaining)}}var emptyReplayWindow={remaining:0,take:()=>{return},takeN:()=>empty5(),takeAll:()=>empty5()};var bounded4=bounded3,dropping3=dropping2,sliding3=sliding2,unbounded4=unbounded3;var shutdown3=shutdown2;var subscribe2=subscribe;var exports_Queue={};__export(exports_Queue,{unsafeOffer:()=>unsafeOffer2,unbounded:()=>unbounded5,takeUpTo:()=>takeUpTo2,takeN:()=>takeN2,takeBetween:()=>takeBetween2,takeAll:()=>takeAll2,take:()=>take3,slidingStrategy:()=>slidingStrategy2,sliding:()=>sliding4,size:()=>size13,shutdown:()=>shutdown4,poll:()=>poll6,offerAll:()=>offerAll3,offer:()=>offer3,make:()=>make44,isShutdown:()=>isShutdown3,isQueue:()=>isQueue2,isFull:()=>isFull3,isEnqueue:()=>isEnqueue2,isEmpty:()=>isEmpty12,isDequeue:()=>isDequeue2,droppingStrategy:()=>droppingStrategy2,dropping:()=>dropping4,capacity:()=>capacity4,bounded:()=>bounded5,backPressureStrategy:()=>backPressureStrategy2,awaitShutdown:()=>awaitShutdown3,QueueStrategyTypeId:()=>QueueStrategyTypeId2,EnqueueTypeId:()=>EnqueueTypeId2,DequeueTypeId:()=>DequeueTypeId2,BackingQueueTypeId:()=>BackingQueueTypeId2});var EnqueueTypeId2=EnqueueTypeId,DequeueTypeId2=DequeueTypeId,QueueStrategyTypeId2=QueueStrategyTypeId,BackingQueueTypeId2=BackingQueueTypeId,isQueue2=isQueue,isDequeue2=isDequeue,isEnqueue2=isEnqueue,backPressureStrategy2=backPressureStrategy,droppingStrategy2=droppingStrategy,slidingStrategy2=slidingStrategy,make44=make43,bounded5=bounded2,dropping4=dropping,sliding4=sliding,unbounded5=unbounded2,capacity4=capacity2,size13=size11,isEmpty12=isEmpty10,isFull3=isFull,isShutdown3=isShutdown,awaitShutdown3=awaitShutdown,shutdown4=shutdown,offer3=offer2,unsafeOffer2=unsafeOffer,offerAll3=offerAll2,poll6=poll5,take3=take2,takeAll2=takeAll,takeUpTo2=takeUpTo,takeBetween2=takeBetween,takeN2=takeN;var OP_CONTINUE2="Continue",OP_CLOSE="Close",OP_YIELD2="Yield";var ChildExecutorDecisionSymbolKey="effect/ChannelChildExecutorDecision",ChildExecutorDecisionTypeId=Symbol.for(ChildExecutorDecisionSymbolKey),proto4={[ChildExecutorDecisionTypeId]:ChildExecutorDecisionTypeId},Continue=(_)=>{let op=Object.create(proto4);return op._tag=OP_CONTINUE2,op};var OP_CONTINUATION_K="ContinuationK",OP_CONTINUATION_FINALIZER="ContinuationFinalizer";var ContinuationTypeId=Symbol.for("effect/ChannelContinuation"),continuationVariance={_Env:(_)=>_,_InErr:(_)=>_,_InElem:(_)=>_,_InDone:(_)=>_,_OutErr:(_)=>_,_OutDone:(_)=>_,_OutErr2:(_)=>_,_OutElem:(_)=>_,_OutDone2:(_)=>_};class ContinuationKImpl{onSuccess;onHalt;_tag=OP_CONTINUATION_K;[ContinuationTypeId]=continuationVariance;constructor(onSuccess,onHalt){this.onSuccess=onSuccess,this.onHalt=onHalt}onExit(exit3){return isFailure(exit3)?this.onHalt(exit3.cause):this.onSuccess(exit3.value)}}class ContinuationFinalizerImpl{finalizer;_tag=OP_CONTINUATION_FINALIZER;[ContinuationTypeId]=continuationVariance;constructor(finalizer){this.finalizer=finalizer}}var OP_PULL_AFTER_NEXT="PullAfterNext",OP_PULL_AFTER_ALL_ENQUEUED="PullAfterAllEnqueued";var UpstreamPullStrategySymbolKey="effect/ChannelUpstreamPullStrategy",UpstreamPullStrategyTypeId=Symbol.for(UpstreamPullStrategySymbolKey),upstreamPullStrategyVariance={_A:(_)=>_},proto5={[UpstreamPullStrategyTypeId]:upstreamPullStrategyVariance},PullAfterNext=(emitSeparator)=>{let op=Object.create(proto5);return op._tag=OP_PULL_AFTER_NEXT,op.emitSeparator=emitSeparator,op};var OP_BRACKET_OUT="BracketOut",OP_BRIDGE="Bridge",OP_CONCAT_ALL="ConcatAll",OP_EMIT="Emit",OP_ENSURING="Ensuring",OP_FAIL3="Fail",OP_FOLD2="Fold",OP_FROM_EFFECT2="FromEffect",OP_PIPE_TO="PipeTo",OP_PROVIDE2="Provide",OP_READ="Read",OP_SUCCEED="Succeed",OP_SUCCEED_NOW="SucceedNow",OP_SUSPEND2="Suspend";var ChannelSymbolKey="effect/Channel",ChannelTypeId2=Symbol.for(ChannelSymbolKey),channelVariance2={_Env:(_)=>_,_InErr:(_)=>_,_InElem:(_)=>_,_InDone:(_)=>_,_OutErr:(_)=>_,_OutElem:(_)=>_,_OutDone:(_)=>_},proto6={[ChannelTypeId2]:channelVariance2,pipe(){return pipeArguments(this,arguments)}},isChannel=(u)=>hasProperty(u,ChannelTypeId2)||isEffect2(u),acquireReleaseOut=dual(2,(self,release)=>{let op=Object.create(proto6);return op._tag=OP_BRACKET_OUT,op.acquire=()=>self,op.finalizer=release,op}),catchAllCause4=dual(2,(self,f)=>{let op=Object.create(proto6);return op._tag=OP_FOLD2,op.channel=self,op.k=new ContinuationKImpl(succeed10,f),op}),collectElements=(self)=>{return suspend4(()=>{let builder=[];return flatMap12(pipeTo(self,collectElementsReader(builder)),(value)=>sync4(()=>[fromIterable2(builder),value]))})},collectElementsReader=(builder)=>readWith({onInput:(outElem)=>flatMap12(sync4(()=>{builder.push(outElem)}),()=>collectElementsReader(builder)),onFailure:fail11,onDone:succeedNow});var concatAllWith=(channels,f,g)=>{let op=Object.create(proto6);return op._tag=OP_CONCAT_ALL,op.combineInners=f,op.combineAll=g,op.onPull=()=>PullAfterNext(none2()),op.onEmit=()=>Continue,op.value=()=>channels,op.k=identity,op},concatMapWith=dual(4,(self,f,g,h)=>{let op=Object.create(proto6);return op._tag=OP_CONCAT_ALL,op.combineInners=g,op.combineAll=h,op.onPull=()=>PullAfterNext(none2()),op.onEmit=()=>Continue,op.value=()=>self,op.k=f,op});var embedInput=dual(2,(self,input)=>{let op=Object.create(proto6);return op._tag=OP_BRIDGE,op.input=input,op.channel=self,op}),ensuringWith=dual(2,(self,finalizer)=>{let op=Object.create(proto6);return op._tag=OP_ENSURING,op.channel=self,op.finalizer=finalizer,op}),fail11=(error)=>failCause10(fail6(error));var failCause10=(cause3)=>failCauseSync4(()=>cause3),failCauseSync4=(evaluate2)=>{let op=Object.create(proto6);return op._tag=OP_FAIL3,op.error=evaluate2,op},flatMap12=dual(2,(self,f)=>{let op=Object.create(proto6);return op._tag=OP_FOLD2,op.channel=self,op.k=new ContinuationKImpl(f,failCause10),op}),foldCauseChannel=dual(2,(self,options)=>{let op=Object.create(proto6);return op._tag=OP_FOLD2,op.channel=self,op.k=new ContinuationKImpl(options.onSuccess,options.onFailure),op}),fromEffect5=(effect)=>{let op=Object.create(proto6);return op._tag=OP_FROM_EFFECT2,op.effect=()=>effect,op},pipeTo=dual(2,(self,that)=>{let op=Object.create(proto6);return op._tag=OP_PIPE_TO,op.left=()=>self,op.right=()=>that,op}),provideContext3=dual(2,(self,env)=>{let op=Object.create(proto6);return op._tag=OP_PROVIDE2,op.context=()=>env,op.inner=self,op});var readWith=(options)=>readWithCause({onInput:options.onInput,onFailure:(cause3)=>match(failureOrCause2(cause3),{onLeft:options.onFailure,onRight:failCause10}),onDone:options.onDone}),readWithCause=(options)=>{let op=Object.create(proto6);return op._tag=OP_READ,op.more=options.onInput,op.done=new ContinuationKImpl(options.onDone,options.onFailure),op},succeed10=(value)=>sync4(()=>value),succeedNow=(result)=>{let op=Object.create(proto6);return op._tag=OP_SUCCEED_NOW,op.terminal=result,op},suspend4=(evaluate2)=>{let op=Object.create(proto6);return op._tag=OP_SUSPEND2,op.channel=evaluate2,op},sync4=(evaluate2)=>{let op=Object.create(proto6);return op._tag=OP_SUCCEED,op.evaluate=evaluate2,op},void_6=succeedNow(void 0);var write=(out)=>{let op=Object.create(proto6);return op._tag=OP_EMIT,op.out=out,op};var OP_DONE3="Done",OP_EMIT2="Emit",OP_FROM_EFFECT3="FromEffect",OP_READ2="Read";var ChannelStateTypeId=Symbol.for("effect/ChannelState"),channelStateVariance={_E:(_)=>_,_R:(_)=>_},proto7={[ChannelStateTypeId]:channelStateVariance},Done2=()=>{let op=Object.create(proto7);return op._tag=OP_DONE3,op},Emit=()=>{let op=Object.create(proto7);return op._tag=OP_EMIT2,op},fromEffect6=(effect)=>{let op=Object.create(proto7);return op._tag=OP_FROM_EFFECT3,op.effect=effect,op},Read=(upstream,onEffect,onEmit,onDone)=>{let op=Object.create(proto7);return op._tag=OP_READ2,op.upstream=upstream,op.onEffect=onEffect,op.onEmit=onEmit,op.onDone=onDone,op};var isFromEffect=(self)=>self._tag===OP_FROM_EFFECT3;var effect=(self)=>isFromEffect(self)?self.effect:_void,effectOrUndefinedIgnored=(self)=>isFromEffect(self)?ignore2(self.effect):void 0;var OP_PULL_FROM_CHILD="PullFromChild",OP_PULL_FROM_UPSTREAM="PullFromUpstream",OP_DRAIN_CHILD_EXECUTORS="DrainChildExecutors",OP_EMIT3="Emit";class PullFromChild{childExecutor;parentSubexecutor;onEmit;_tag=OP_PULL_FROM_CHILD;constructor(childExecutor,parentSubexecutor,onEmit){this.childExecutor=childExecutor,this.parentSubexecutor=parentSubexecutor,this.onEmit=onEmit}close(exit3){let fin1=this.childExecutor.close(exit3),fin2=this.parentSubexecutor.close(exit3);if(fin1!==void 0&&fin2!==void 0)return zipWith8(exit2(fin1),exit2(fin2),(exit1,exit22)=>pipe(exit1,zipRight2(exit22)));else if(fin1!==void 0)return fin1;else if(fin2!==void 0)return fin2;else return}enqueuePullFromChild(_child){return this}}class PullFromUpstream{upstreamExecutor;createChild;lastDone;activeChildExecutors;combineChildResults;combineWithChildResult;onPull;onEmit;_tag=OP_PULL_FROM_UPSTREAM;constructor(upstreamExecutor,createChild,lastDone,activeChildExecutors,combineChildResults,combineWithChildResult,onPull,onEmit){this.upstreamExecutor=upstreamExecutor,this.createChild=createChild,this.lastDone=lastDone,this.activeChildExecutors=activeChildExecutors,this.combineChildResults=combineChildResults,this.combineWithChildResult=combineWithChildResult,this.onPull=onPull,this.onEmit=onEmit}close(exit3){let fin1=this.upstreamExecutor.close(exit3),result=[...this.activeChildExecutors.map((child)=>child!==void 0?child.childExecutor.close(exit3):void 0),fin1].reduce((acc,next4)=>{if(acc!==void 0&&next4!==void 0)return zipWith8(acc,exit2(next4),(exit1,exit22)=>zipRight2(exit1,exit22));else if(acc!==void 0)return acc;else if(next4!==void 0)return exit2(next4);else return},void 0);return result===void 0?result:result}enqueuePullFromChild(child){return new PullFromUpstream(this.upstreamExecutor,this.createChild,this.lastDone,[...this.activeChildExecutors,child],this.combineChildResults,this.combineWithChildResult,this.onPull,this.onEmit)}}class DrainChildExecutors{upstreamExecutor;lastDone;activeChildExecutors;upstreamDone;combineChildResults;combineWithChildResult;onPull;_tag=OP_DRAIN_CHILD_EXECUTORS;constructor(upstreamExecutor,lastDone,activeChildExecutors,upstreamDone,combineChildResults,combineWithChildResult,onPull){this.upstreamExecutor=upstreamExecutor,this.lastDone=lastDone,this.activeChildExecutors=activeChildExecutors,this.upstreamDone=upstreamDone,this.combineChildResults=combineChildResults,this.combineWithChildResult=combineWithChildResult,this.onPull=onPull}close(exit3){let fin1=this.upstreamExecutor.close(exit3),result=[...this.activeChildExecutors.map((child)=>child!==void 0?child.childExecutor.close(exit3):void 0),fin1].reduce((acc,next4)=>{if(acc!==void 0&&next4!==void 0)return zipWith8(acc,exit2(next4),(exit1,exit22)=>zipRight2(exit1,exit22));else if(acc!==void 0)return acc;else if(next4!==void 0)return exit2(next4);else return},void 0);return result===void 0?result:result}enqueuePullFromChild(child){return new DrainChildExecutors(this.upstreamExecutor,this.lastDone,[...this.activeChildExecutors,child],this.upstreamDone,this.combineChildResults,this.combineWithChildResult,this.onPull)}}class Emit2{value;next;_tag=OP_EMIT3;constructor(value,next4){this.value=value,this.next=next4}close(exit3){let result=this.next.close(exit3);return result===void 0?result:result}enqueuePullFromChild(_child){return this}}var OP_PULLED="Pulled",OP_NO_UPSTREAM="NoUpstream";var UpstreamPullRequestSymbolKey="effect/ChannelUpstreamPullRequest",UpstreamPullRequestTypeId=Symbol.for(UpstreamPullRequestSymbolKey),upstreamPullRequestVariance={_A:(_)=>_},proto8={[UpstreamPullRequestTypeId]:upstreamPullRequestVariance},Pulled=(value)=>{let op=Object.create(proto8);return op._tag=OP_PULLED,op.value=value,op},NoUpstream=(activeDownstreamCount)=>{let op=Object.create(proto8);return op._tag=OP_NO_UPSTREAM,op.activeDownstreamCount=activeDownstreamCount,op};class ChannelExecutor{_activeSubexecutor=void 0;_cancelled=void 0;_closeLastSubstream=void 0;_currentChannel;_done=void 0;_doneStack=[];_emitted=void 0;_executeCloseLastSubstream;_input=void 0;_inProgressFinalizer=void 0;_providedEnv;constructor(initialChannel,providedEnv,executeCloseLastSubstream){this._currentChannel=initialChannel,this._executeCloseLastSubstream=executeCloseLastSubstream,this._providedEnv=providedEnv}run(){let result=void 0;while(result===void 0)if(this._cancelled!==void 0)result=this.processCancellation();else if(this._activeSubexecutor!==void 0)result=this.runSubexecutor();else try{if(this._currentChannel===void 0)result=Done2();else{if(isEffect2(this._currentChannel))this._currentChannel=fromEffect5(this._currentChannel);switch(this._currentChannel._tag){case OP_BRACKET_OUT:{result=this.runBracketOut(this._currentChannel);break}case OP_BRIDGE:{let bridgeInput=this._currentChannel.input;if(this._currentChannel=this._currentChannel.channel,this._input!==void 0){let inputExecutor=this._input;this._input=void 0;let drainer=()=>flatMap10(bridgeInput.awaitRead(),()=>suspend3(()=>{let state=inputExecutor.run();switch(state._tag){case OP_DONE3:return match6(inputExecutor.getDone(),{onFailure:(cause3)=>bridgeInput.error(cause3),onSuccess:(value)=>bridgeInput.done(value)});case OP_EMIT2:return flatMap10(bridgeInput.emit(inputExecutor.getEmit()),()=>drainer());case OP_FROM_EFFECT3:return matchCauseEffect3(state.effect,{onFailure:(cause3)=>bridgeInput.error(cause3),onSuccess:()=>drainer()});case OP_READ2:return readUpstream(state,()=>drainer(),(cause3)=>bridgeInput.error(cause3))}}));result=fromEffect6(flatMap10(forkDaemon2(interruptible4(drainer())),(fiber)=>sync3(()=>this.addFinalizer((exit3)=>flatMap10(interrupt6(fiber),()=>suspend3(()=>{let effect2=this.restorePipe(exit3,inputExecutor);return effect2!==void 0?effect2:_void}))))))}break}case OP_CONCAT_ALL:{let executor=new ChannelExecutor(this._currentChannel.value(),this._providedEnv,(effect2)=>sync3(()=>{let prevLastClose=this._closeLastSubstream===void 0?_void:this._closeLastSubstream;this._closeLastSubstream=pipe(prevLastClose,zipRight4(effect2))}));executor._input=this._input;let channel=this._currentChannel;this._activeSubexecutor=new PullFromUpstream(executor,(value)=>channel.k(value),void 0,[],(x,y)=>channel.combineInners(x,y),(x,y)=>channel.combineAll(x,y),(request2)=>channel.onPull(request2),(value)=>channel.onEmit(value)),this._closeLastSubstream=void 0,this._currentChannel=void 0;break}case OP_EMIT:{this._emitted=this._currentChannel.out,this._currentChannel=this._activeSubexecutor!==void 0?void 0:void_6,result=Emit();break}case OP_ENSURING:{this.runEnsuring(this._currentChannel);break}case OP_FAIL3:{result=this.doneHalt(this._currentChannel.error());break}case OP_FOLD2:{this._doneStack.push(this._currentChannel.k),this._currentChannel=this._currentChannel.channel;break}case OP_FROM_EFFECT2:{let effect2=this._providedEnv===void 0?this._currentChannel.effect():pipe(this._currentChannel.effect(),provide2(this._providedEnv));result=fromEffect6(matchCauseEffect3(effect2,{onFailure:(cause3)=>{let state=this.doneHalt(cause3);return state!==void 0&&isFromEffect(state)?state.effect:_void},onSuccess:(value)=>{let state=this.doneSucceed(value);return state!==void 0&&isFromEffect(state)?state.effect:_void}}));break}case OP_PIPE_TO:{let previousInput=this._input,leftExec=new ChannelExecutor(this._currentChannel.left(),this._providedEnv,(effect2)=>this._executeCloseLastSubstream(effect2));leftExec._input=previousInput,this._input=leftExec,this.addFinalizer((exit3)=>{let effect2=this.restorePipe(exit3,previousInput);return effect2!==void 0?effect2:_void}),this._currentChannel=this._currentChannel.right();break}case OP_PROVIDE2:{let previousEnv=this._providedEnv;this._providedEnv=this._currentChannel.context(),this._currentChannel=this._currentChannel.inner,this.addFinalizer(()=>sync3(()=>{this._providedEnv=previousEnv}));break}case OP_READ:{let read=this._currentChannel;result=Read(this._input,identity,(emitted)=>{try{this._currentChannel=read.more(emitted)}catch(error){this._currentChannel=read.done.onExit(die3(error))}return},(exit3)=>{let onExit4=(exit4)=>{return read.done.onExit(exit4)};this._currentChannel=onExit4(exit3);return});break}case OP_SUCCEED:{result=this.doneSucceed(this._currentChannel.evaluate());break}case OP_SUCCEED_NOW:{result=this.doneSucceed(this._currentChannel.terminal);break}case OP_SUSPEND2:{this._currentChannel=this._currentChannel.channel();break}default:this._currentChannel._tag}}}catch(error){this._currentChannel=failCause10(die4(error))}return result}getDone(){return this._done}getEmit(){return this._emitted}cancelWith(exit3){this._cancelled=exit3}clearInProgressFinalizer(){this._inProgressFinalizer=void 0}storeInProgressFinalizer(finalizer){this._inProgressFinalizer=finalizer}popAllFinalizers(exit3){let finalizers=[],next4=this._doneStack.pop();while(next4){if(next4._tag==="ContinuationFinalizer")finalizers.push(next4.finalizer);next4=this._doneStack.pop()}let effect2=finalizers.length===0?_void:runFinalizers(finalizers,exit3);return this.storeInProgressFinalizer(effect2),effect2}popNextFinalizers(){let builder=[];while(this._doneStack.length!==0){let cont=this._doneStack[this._doneStack.length-1];if(cont._tag===OP_CONTINUATION_K)return builder;builder.push(cont),this._doneStack.pop()}return builder}restorePipe(exit3,prev){let currInput=this._input;if(this._input=prev,currInput!==void 0)return currInput.close(exit3);return _void}close(exit3){let runInProgressFinalizers=void 0,finalizer=this._inProgressFinalizer;if(finalizer!==void 0)runInProgressFinalizers=pipe(finalizer,ensuring2(sync3(()=>this.clearInProgressFinalizer())));let closeSelf=void 0,selfFinalizers=this.popAllFinalizers(exit3);if(selfFinalizers!==void 0)closeSelf=pipe(selfFinalizers,ensuring2(sync3(()=>this.clearInProgressFinalizer())));let closeSubexecutors=this._activeSubexecutor===void 0?void 0:this._activeSubexecutor.close(exit3);if(closeSubexecutors===void 0&&runInProgressFinalizers===void 0&&closeSelf===void 0)return;return pipe(exit2(ifNotNull(closeSubexecutors)),zip6(exit2(ifNotNull(runInProgressFinalizers))),zip6(exit2(ifNotNull(closeSelf))),map16(([[exit1,exit22],exit32])=>pipe(exit1,zipRight2(exit22),zipRight2(exit32))),uninterruptible2,flatMap10((exit4)=>suspend3(()=>exit4)))}doneSucceed(value){if(this._doneStack.length===0)return this._done=succeed3(value),this._currentChannel=void 0,Done2();let head5=this._doneStack[this._doneStack.length-1];if(head5._tag===OP_CONTINUATION_K){this._doneStack.pop(),this._currentChannel=head5.onSuccess(value);return}let finalizers=this.popNextFinalizers();if(this._doneStack.length===0)return this._doneStack=finalizers.reverse(),this._done=succeed3(value),this._currentChannel=void 0,Done2();let finalizerEffect=runFinalizers(finalizers.map((f)=>f.finalizer),succeed3(value));this.storeInProgressFinalizer(finalizerEffect);let effect2=pipe(finalizerEffect,ensuring2(sync3(()=>this.clearInProgressFinalizer())),uninterruptible2,flatMap10(()=>sync3(()=>this.doneSucceed(value))));return fromEffect6(effect2)}doneHalt(cause3){if(this._doneStack.length===0)return this._done=failCause3(cause3),this._currentChannel=void 0,Done2();let head5=this._doneStack[this._doneStack.length-1];if(head5._tag===OP_CONTINUATION_K){this._doneStack.pop();try{this._currentChannel=head5.onHalt(cause3)}catch(error){this._currentChannel=failCause10(die4(error))}return}let finalizers=this.popNextFinalizers();if(this._doneStack.length===0)return this._doneStack=finalizers.reverse(),this._done=failCause3(cause3),this._currentChannel=void 0,Done2();let finalizerEffect=runFinalizers(finalizers.map((f)=>f.finalizer),failCause3(cause3));this.storeInProgressFinalizer(finalizerEffect);let effect2=pipe(finalizerEffect,ensuring2(sync3(()=>this.clearInProgressFinalizer())),uninterruptible2,flatMap10(()=>sync3(()=>this.doneHalt(cause3))));return fromEffect6(effect2)}processCancellation(){return this._currentChannel=void 0,this._done=this._cancelled,this._cancelled=void 0,Done2()}runBracketOut(bracketOut){let effect2=uninterruptible2(matchCauseEffect3(this.provide(bracketOut.acquire()),{onFailure:(cause3)=>sync3(()=>{this._currentChannel=failCause10(cause3)}),onSuccess:(out)=>sync3(()=>{this.addFinalizer((exit3)=>this.provide(bracketOut.finalizer(out,exit3))),this._currentChannel=write(out)})}));return fromEffect6(effect2)}provide(effect2){if(this._providedEnv===void 0)return effect2;return pipe(effect2,provide2(this._providedEnv))}runEnsuring(ensuring3){this.addFinalizer(ensuring3.finalizer),this._currentChannel=ensuring3.channel}addFinalizer(f){this._doneStack.push(new ContinuationFinalizerImpl(f))}runSubexecutor(){let subexecutor=this._activeSubexecutor;switch(subexecutor._tag){case OP_PULL_FROM_CHILD:return this.pullFromChild(subexecutor.childExecutor,subexecutor.parentSubexecutor,subexecutor.onEmit,subexecutor);case OP_PULL_FROM_UPSTREAM:return this.pullFromUpstream(subexecutor);case OP_DRAIN_CHILD_EXECUTORS:return this.drainChildExecutors(subexecutor);case OP_EMIT3:return this._emitted=subexecutor.value,this._activeSubexecutor=subexecutor.next,Emit()}}replaceSubexecutor(nextSubExec){this._currentChannel=void 0,this._activeSubexecutor=nextSubExec}finishWithExit(exit3){let state=match6(exit3,{onFailure:(cause3)=>this.doneHalt(cause3),onSuccess:(value)=>this.doneSucceed(value)});return this._activeSubexecutor=void 0,state===void 0?_void:effect(state)}finishSubexecutorWithCloseEffect(subexecutorDone,...closeFuncs){this.addFinalizer(()=>pipe(closeFuncs,forEach8((closeFunc)=>pipe(sync3(()=>closeFunc(subexecutorDone)),flatMap10((closeEffect)=>closeEffect!==void 0?closeEffect:_void)),{discard:!0})));let state=pipe(subexecutorDone,match6({onFailure:(cause3)=>this.doneHalt(cause3),onSuccess:(value)=>this.doneSucceed(value)}));return this._activeSubexecutor=void 0,state}applyUpstreamPullStrategy(upstreamFinished,queue,strategy){switch(strategy._tag){case OP_PULL_AFTER_NEXT:{let shouldPrepend=!upstreamFinished||queue.some((subexecutor)=>subexecutor!==void 0);return[strategy.emitSeparator,shouldPrepend?[void 0,...queue]:queue]}case OP_PULL_AFTER_ALL_ENQUEUED:{let shouldEnqueue=!upstreamFinished||queue.some((subexecutor)=>subexecutor!==void 0);return[strategy.emitSeparator,shouldEnqueue?[...queue,void 0]:queue]}}}pullFromChild(childExecutor,parentSubexecutor,onEmitted,subexecutor){return Read(childExecutor,identity,(emitted)=>{let childExecutorDecision=onEmitted(emitted);switch(childExecutorDecision._tag){case OP_CONTINUE2:break;case OP_CLOSE:{this.finishWithDoneValue(childExecutor,parentSubexecutor,childExecutorDecision.value);break}case OP_YIELD2:{let modifiedParent=parentSubexecutor.enqueuePullFromChild(subexecutor);this.replaceSubexecutor(modifiedParent);break}}this._activeSubexecutor=new Emit2(emitted,this._activeSubexecutor);return},match6({onFailure:(cause3)=>{let state=this.handleSubexecutorFailure(childExecutor,parentSubexecutor,cause3);return state===void 0?void 0:effectOrUndefinedIgnored(state)},onSuccess:(doneValue)=>{this.finishWithDoneValue(childExecutor,parentSubexecutor,doneValue);return}}))}finishWithDoneValue(childExecutor,parentSubexecutor,doneValue){let subexecutor=parentSubexecutor;switch(subexecutor._tag){case OP_PULL_FROM_UPSTREAM:{let modifiedParent=new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone!==void 0?subexecutor.combineChildResults(subexecutor.lastDone,doneValue):doneValue,subexecutor.activeChildExecutors,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit);this._closeLastSubstream=childExecutor.close(succeed3(doneValue)),this.replaceSubexecutor(modifiedParent);break}case OP_DRAIN_CHILD_EXECUTORS:{let modifiedParent=new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone!==void 0?subexecutor.combineChildResults(subexecutor.lastDone,doneValue):doneValue,subexecutor.activeChildExecutors,subexecutor.upstreamDone,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull);this._closeLastSubstream=childExecutor.close(succeed3(doneValue)),this.replaceSubexecutor(modifiedParent);break}default:break}}handleSubexecutorFailure(childExecutor,parentSubexecutor,cause3){return this.finishSubexecutorWithCloseEffect(failCause3(cause3),(exit3)=>parentSubexecutor.close(exit3),(exit3)=>childExecutor.close(exit3))}pullFromUpstream(subexecutor){if(subexecutor.activeChildExecutors.length===0)return this.performPullFromUpstream(subexecutor);let activeChild=subexecutor.activeChildExecutors[0],parentSubexecutor=new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone,subexecutor.activeChildExecutors.slice(1),subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit);if(activeChild===void 0)return this.performPullFromUpstream(parentSubexecutor);this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor,parentSubexecutor,activeChild.onEmit));return}performPullFromUpstream(subexecutor){return Read(subexecutor.upstreamExecutor,(effect2)=>{let closeLastSubstream=this._closeLastSubstream===void 0?_void:this._closeLastSubstream;return this._closeLastSubstream=void 0,pipe(this._executeCloseLastSubstream(closeLastSubstream),zipRight4(effect2))},(emitted)=>{if(this._closeLastSubstream!==void 0){let closeLastSubstream=this._closeLastSubstream;return this._closeLastSubstream=void 0,pipe(this._executeCloseLastSubstream(closeLastSubstream),map16(()=>{let childExecutor2=new ChannelExecutor(subexecutor.createChild(emitted),this._providedEnv,this._executeCloseLastSubstream);childExecutor2._input=this._input;let[emitSeparator2,updatedChildExecutors2]=this.applyUpstreamPullStrategy(!1,subexecutor.activeChildExecutors,subexecutor.onPull(Pulled(emitted)));if(this._activeSubexecutor=new PullFromChild(childExecutor2,new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone,updatedChildExecutors2,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit),subexecutor.onEmit),isSome2(emitSeparator2))this._activeSubexecutor=new Emit2(emitSeparator2.value,this._activeSubexecutor);return}))}let childExecutor=new ChannelExecutor(subexecutor.createChild(emitted),this._providedEnv,this._executeCloseLastSubstream);childExecutor._input=this._input;let[emitSeparator,updatedChildExecutors]=this.applyUpstreamPullStrategy(!1,subexecutor.activeChildExecutors,subexecutor.onPull(Pulled(emitted)));if(this._activeSubexecutor=new PullFromChild(childExecutor,new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone,updatedChildExecutors,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit),subexecutor.onEmit),isSome2(emitSeparator))this._activeSubexecutor=new Emit2(emitSeparator.value,this._activeSubexecutor);return},(exit3)=>{if(subexecutor.activeChildExecutors.some((subexecutor2)=>subexecutor2!==void 0)){let drain=new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone,[void 0,...subexecutor.activeChildExecutors],subexecutor.upstreamExecutor.getDone(),subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull);if(this._closeLastSubstream!==void 0){let closeLastSubstream2=this._closeLastSubstream;return this._closeLastSubstream=void 0,pipe(this._executeCloseLastSubstream(closeLastSubstream2),map16(()=>this.replaceSubexecutor(drain)))}this.replaceSubexecutor(drain);return}let closeLastSubstream=this._closeLastSubstream,state=this.finishSubexecutorWithCloseEffect(pipe(exit3,map11((a)=>subexecutor.combineWithChildResult(subexecutor.lastDone,a))),()=>closeLastSubstream,(exit4)=>subexecutor.upstreamExecutor.close(exit4));return state===void 0?void 0:effectOrUndefinedIgnored(state)})}drainChildExecutors(subexecutor){if(subexecutor.activeChildExecutors.length===0){let lastClose=this._closeLastSubstream;if(lastClose!==void 0)this.addFinalizer(()=>succeed9(lastClose));return this.finishSubexecutorWithCloseEffect(subexecutor.upstreamDone,()=>lastClose,(exit3)=>subexecutor.upstreamExecutor.close(exit3))}let activeChild=subexecutor.activeChildExecutors[0],rest=subexecutor.activeChildExecutors.slice(1);if(activeChild===void 0){let[emitSeparator,remainingExecutors]=this.applyUpstreamPullStrategy(!0,rest,subexecutor.onPull(NoUpstream(rest.reduce((n,curr)=>curr!==void 0?n+1:n,0))));if(this.replaceSubexecutor(new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone,remainingExecutors,subexecutor.upstreamDone,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull)),isSome2(emitSeparator))return this._emitted=emitSeparator.value,Emit();return}let parentSubexecutor=new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone,rest,subexecutor.upstreamDone,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull);this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor,parentSubexecutor,activeChild.onEmit));return}}var ifNotNull=(effect2)=>effect2!==void 0?effect2:_void,runFinalizers=(finalizers,exit3)=>{return pipe(forEach8(finalizers,(fin)=>exit2(fin(exit3))),map16((exits)=>pipe(all2(exits),getOrElse(()=>void_2))),flatMap10((exit4)=>suspend3(()=>exit4)))},readUpstream=(r,onSuccess,onFailure)=>{let readStack=[r],read=()=>{let current=readStack.pop();if(current===void 0||current.upstream===void 0)return dieMessage2("Unexpected end of input for channel execution");let state=current.upstream.run();switch(state._tag){case OP_EMIT2:{let emitEffect=current.onEmit(current.upstream.getEmit());if(readStack.length===0){if(emitEffect===void 0)return suspend3(onSuccess);return pipe(emitEffect,matchCauseEffect3({onFailure,onSuccess}))}if(emitEffect===void 0)return suspend3(()=>read());return pipe(emitEffect,matchCauseEffect3({onFailure,onSuccess:()=>read()}))}case OP_DONE3:{let doneEffect=current.onDone(current.upstream.getDone());if(readStack.length===0){if(doneEffect===void 0)return suspend3(onSuccess);return pipe(doneEffect,matchCauseEffect3({onFailure,onSuccess}))}if(doneEffect===void 0)return suspend3(()=>read());return pipe(doneEffect,matchCauseEffect3({onFailure,onSuccess:()=>read()}))}case OP_FROM_EFFECT3:return readStack.push(current),pipe(current.onEffect(state.effect),catchAllCause2((cause3)=>suspend3(()=>{let doneEffect=current.onDone(failCause3(cause3));return doneEffect===void 0?_void:doneEffect})),matchCauseEffect3({onFailure,onSuccess:()=>read()}));case OP_READ2:return readStack.push(current),readStack.push(state),suspend3(()=>read())}};return read()},runIn=dual(2,(self,scope4)=>{let run=(channelDeferred,scopeDeferred,scope5)=>acquireUseRelease2(sync3(()=>new ChannelExecutor(self,void 0,identity)),(exec)=>suspend3(()=>runScopedInterpret(exec.run(),exec).pipe(intoDeferred2(channelDeferred),zipRight4(_await(channelDeferred)),zipLeft3(_await(scopeDeferred)))),(exec,exit3)=>{let finalize=exec.close(exit3);if(finalize===void 0)return _void;return tapErrorCause2(finalize,(cause3)=>addFinalizer2(scope5,failCause8(cause3)))});return uninterruptibleMask3((restore)=>all7([fork2(scope4,sequential3),make19(),make19()]).pipe(flatMap10(([child,channelDeferred,scopeDeferred])=>restore(run(channelDeferred,scopeDeferred,child)).pipe(forkIn2(scope4),flatMap10((fiber)=>scope4.addFinalizer((exit3)=>{let interruptors3=isFailure(exit3)?interruptors2(exit3.cause):void 0;return isDone(channelDeferred).pipe(flatMap10((isDone6)=>isDone6?succeed2(scopeDeferred,void 0).pipe(zipRight4(_await3(fiber)),zipRight4(inheritAll2(fiber))):succeed2(scopeDeferred,void 0).pipe(zipRight4(interruptors3&&size3(interruptors3)>0?interruptAs(fiber,combineAll3(interruptors3)):interrupt6(fiber)),zipRight4(inheritAll2(fiber)))))}).pipe(zipRight4(restore(_await(channelDeferred)))))))))}),runScopedInterpret=(channelState,exec)=>{let op=channelState;switch(op._tag){case OP_FROM_EFFECT3:return pipe(op.effect,flatMap10(()=>runScopedInterpret(exec.run(),exec)));case OP_EMIT2:return runScopedInterpret(exec.run(),exec);case OP_DONE3:return suspend3(()=>exec.getDone());case OP_READ2:return readUpstream(op,()=>runScopedInterpret(exec.run(),exec),failCause8)}};var OP_DONE4="Done",OP_AWAIT="Await";var MergeDecisionSymbolKey="effect/ChannelMergeDecision",MergeDecisionTypeId=Symbol.for(MergeDecisionSymbolKey),proto9={[MergeDecisionTypeId]:{_R:(_)=>_,_E0:(_)=>_,_Z0:(_)=>_,_E:(_)=>_,_Z:(_)=>_}},Done3=(effect2)=>{let op=Object.create(proto9);return op._tag=OP_DONE4,op.effect=effect2,op},Await=(f)=>{let op=Object.create(proto9);return op._tag=OP_AWAIT,op.f=f,op};var OP_BOTH_RUNNING="BothRunning",OP_LEFT_DONE="LeftDone",OP_RIGHT_DONE="RightDone";var MergeStateSymbolKey="effect/ChannelMergeState",MergeStateTypeId=Symbol.for(MergeStateSymbolKey),proto10={[MergeStateTypeId]:MergeStateTypeId},BothRunning=(left3,right3)=>{let op=Object.create(proto10);return op._tag=OP_BOTH_RUNNING,op.left=left3,op.right=right3,op},LeftDone=(f)=>{let op=Object.create(proto10);return op._tag=OP_LEFT_DONE,op.f=f,op},RightDone=(f)=>{let op=Object.create(proto10);return op._tag=OP_RIGHT_DONE,op.f=f,op};var OP_BACK_PRESSURE="BackPressure",OP_BUFFER_SLIDING="BufferSliding";var MergeStrategySymbolKey="effect/ChannelMergeStrategy",MergeStrategyTypeId=Symbol.for(MergeStrategySymbolKey),proto11={[MergeStrategyTypeId]:MergeStrategyTypeId},BackPressure=(_)=>{let op=Object.create(proto11);return op._tag=OP_BACK_PRESSURE,op},BufferSliding=(_)=>{let op=Object.create(proto11);return op._tag=OP_BUFFER_SLIDING,op};var match15=dual(2,(self,{onBackPressure,onBufferSliding})=>{switch(self._tag){case OP_BACK_PRESSURE:return onBackPressure();case OP_BUFFER_SLIDING:return onBufferSliding()}});var OP_STATE_EMPTY="Empty",OP_STATE_EMIT="Emit",OP_STATE_ERROR="Error",OP_STATE_DONE2="Done",stateEmpty=(notifyProducer)=>({_tag:OP_STATE_EMPTY,notifyProducer}),stateEmit=(notifyConsumers)=>({_tag:OP_STATE_EMIT,notifyConsumers}),stateError=(cause3)=>({_tag:OP_STATE_ERROR,cause:cause3}),stateDone=(done9)=>({_tag:OP_STATE_DONE2,done:done9});class SingleProducerAsyncInputImpl{ref;constructor(ref){this.ref=ref}awaitRead(){return flatten8(modify3(this.ref,(state)=>state._tag===OP_STATE_EMPTY?[_await(state.notifyProducer),state]:[_void,state]))}get close(){return fiberIdWith2((fiberId3)=>this.error(interrupt5(fiberId3)))}done(value){return flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[_await(state.notifyProducer),state];case OP_STATE_EMIT:return[forEach8(state.notifyConsumers,(deferred)=>succeed2(deferred,left2(value)),{discard:!0}),stateDone(value)];case OP_STATE_ERROR:return[interrupt7,state];case OP_STATE_DONE2:return[interrupt7,state]}}))}emit(element){return flatMap10(make19(),(deferred)=>flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[_await(state.notifyProducer),state];case OP_STATE_EMIT:{let notifyConsumer=state.notifyConsumers[0],notifyConsumers=state.notifyConsumers.slice(1);if(notifyConsumer!==void 0)return[succeed2(notifyConsumer,right2(element)),notifyConsumers.length===0?stateEmpty(deferred):stateEmit(notifyConsumers)];throw new Error("Bug: Channel.SingleProducerAsyncInput.emit - Queue was empty! please report an issue at https://github.com/Effect-TS/effect/issues")}case OP_STATE_ERROR:return[interrupt7,state];case OP_STATE_DONE2:return[interrupt7,state]}})))}error(cause3){return flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[_await(state.notifyProducer),state];case OP_STATE_EMIT:return[forEach8(state.notifyConsumers,(deferred)=>failCause2(deferred,cause3),{discard:!0}),stateError(cause3)];case OP_STATE_ERROR:return[interrupt7,state];case OP_STATE_DONE2:return[interrupt7,state]}}))}get take(){return this.takeWith((cause3)=>failCause3(map13(cause3,left2)),(elem)=>succeed3(elem),(done9)=>fail4(right2(done9)))}takeWith(onError3,onElement,onDone){return flatMap10(make19(),(deferred)=>flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[zipRight4(succeed2(state.notifyProducer,void 0),matchCause2(_await(deferred),{onFailure:onError3,onSuccess:match({onLeft:onDone,onRight:onElement})})),stateEmit([deferred])];case OP_STATE_EMIT:return[matchCause2(_await(deferred),{onFailure:onError3,onSuccess:match({onLeft:onDone,onRight:onElement})}),stateEmit([...state.notifyConsumers,deferred])];case OP_STATE_ERROR:return[succeed9(onError3(state.cause)),state];case OP_STATE_DONE2:return[succeed9(onDone(state.done)),state]}})))}}var make45=()=>pipe(make19(),flatMap10((deferred)=>make29(stateEmpty(deferred))),map16((ref)=>new SingleProducerAsyncInputImpl(ref)));var acquireUseRelease3=(acquire,use,release)=>flatMap12(fromEffect5(make29(()=>_void)),(ref)=>pipe(fromEffect5(uninterruptible2(tap2(acquire,(a)=>set6(ref,(exit3)=>release(a,exit3))))),flatMap12(use),ensuringWith((exit3)=>flatMap10(get12(ref),(f)=>f(exit3))))),as4=dual(2,(self,value)=>map18(self,()=>value));var catchAll4=dual(2,(self,f)=>catchAllCause4(self,(cause3)=>match(failureOrCause2(cause3),{onLeft:f,onRight:failCause10}))),concatMap=dual(2,(self,f)=>concatMapWith(self,f,()=>{return},()=>{return}));var drain=(self)=>{let drainer=readWithCause({onInput:()=>drainer,onFailure:failCause10,onDone:succeed10});return pipeTo(self,drainer)};var ensuring3=dual(2,(self,finalizer)=>ensuringWith(self,()=>finalizer));var flatten10=(self)=>flatMap12(self,identity),foldChannel=dual(2,(self,options)=>foldCauseChannel(self,{onFailure:(cause3)=>{let either4=failureOrCause2(cause3);switch(either4._tag){case"Left":return options.onFailure(either4.left);case"Right":return failCause10(either4.right)}},onSuccess:options.onSuccess}));var fromInput=(input)=>unwrap(input.takeWith(failCause10,(elem)=>flatMap12(write(elem),()=>fromInput(input)),succeed10));var fromQueue=(queue)=>suspend4(()=>fromQueueInternal(queue)),fromQueueInternal=(queue)=>pipe(fromEffect5(take3(queue)),flatMap12(match({onLeft:match6({onFailure:failCause10,onSuccess:succeedNow}),onRight:(elem)=>flatMap12(write(elem),()=>fromQueueInternal(queue))}))),identityChannel=()=>readWith({onInput:(input)=>flatMap12(write(input),()=>identityChannel()),onFailure:fail11,onDone:succeedNow}),interruptWhen=dual(2,(self,effect2)=>mergeWith2(self,{other:fromEffect5(effect2),onSelfDone:(selfDone)=>Done3(suspend3(()=>selfDone)),onOtherDone:(effectDone)=>Done3(suspend3(()=>effectDone))})),interruptWhenDeferred=dual(2,(self,deferred)=>interruptWhen(self,_await(deferred))),map18=dual(2,(self,f)=>flatMap12(self,(a)=>sync4(()=>f(a))));var mapError4=dual(2,(self,f)=>mapErrorCause3(self,map13(f))),mapErrorCause3=dual(2,(self,f)=>catchAllCause4(self,(cause3)=>failCause10(f(cause3)))),mapOut=dual(2,(self,f)=>{let reader=readWith({onInput:(outElem)=>flatMap12(write(f(outElem)),()=>reader),onFailure:fail11,onDone:succeedNow});return pipeTo(self,reader)}),mapOutEffect=dual(2,(self,f)=>{let reader=readWithCause({onInput:(outElem)=>pipe(fromEffect5(f(outElem)),flatMap12(write),flatMap12(()=>reader)),onFailure:failCause10,onDone:succeedNow});return pipeTo(self,reader)}),mapOutEffectPar=dual(3,(self,f,n)=>unwrapScopedWith((scope4)=>gen2(function*(){let input=yield*make45(),queueReader=fromInput(input),queue=yield*bounded5(n);yield*addFinalizer2(scope4,shutdown4(queue));let errorSignal=yield*make19(),withPermits=n===Number.POSITIVE_INFINITY?(_)=>identity:(yield*makeSemaphore2(n)).withPermits;yield*(yield*queueReader.pipe(pipeTo(self),toPullIn(scope4))).pipe(matchCauseEffect3({onFailure:(cause3)=>offer3(queue,failCause8(cause3)),onSuccess:match({onLeft:(outDone)=>zipRight4(interruptible4(withPermits(n)(_void)),asVoid2(offer3(queue,succeed9(left2(outDone))))),onRight:(outElem)=>gen2(function*(){let deferred=yield*make19(),latch=yield*make19();yield*offer3(queue,map16(_await(deferred),right2)),yield*succeed2(latch,void 0).pipe(zipRight4(uninterruptibleMask3((restore)=>exit2(restore(_await(errorSignal))).pipe(raceFirst2(exit2(restore(f(outElem)))),flatMap10(identity))).pipe(tapErrorCause2((cause3)=>failCause2(errorSignal,cause3)),intoDeferred2(deferred))),withPermits(1),forkIn2(scope4)),yield*_await(latch)})})}),forever3,interruptible4,forkIn2(scope4));let consumer=unwrap(matchCause2(flatten8(take3(queue)),{onFailure:failCause10,onSuccess:match({onLeft:succeedNow,onRight:(outElem)=>flatMap12(write(outElem),()=>consumer)})}));return embedInput(consumer,input)}))),mergeAll5=(options)=>{return(channels)=>mergeAllWith(options)(channels,constVoid)};var mergeAllWith=({bufferSize=16,concurrency,mergeStrategy=BackPressure()})=>(channels,f)=>unwrapScopedWith((scope4)=>gen2(function*(){let concurrencyN=concurrency==="unbounded"?Number.MAX_SAFE_INTEGER:concurrency,input=yield*make45(),queueReader=fromInput(input),queue=yield*bounded5(bufferSize);yield*addFinalizer2(scope4,shutdown4(queue));let cancelers=yield*unbounded5();yield*addFinalizer2(scope4,shutdown4(cancelers));let lastDone=yield*make29(none2()),errorSignal=yield*make19(),withPermits=(yield*makeSemaphore2(concurrencyN)).withPermits,pull=yield*toPullIn(pipeTo(queueReader,channels),scope4);function evaluatePull(pull2){return pull2.pipe(flatMap10(match({onLeft:(done9)=>succeed9(some2(done9)),onRight:(outElem)=>as3(offer3(queue,succeed9(right2(outElem))),none2())})),repeat({until:(_)=>isSome2(_)}),flatMap10((outDone)=>update3(lastDone,match2({onNone:()=>some2(outDone.value),onSome:(lastDone2)=>some2(f(lastDone2,outDone.value))}))),catchAllCause2((cause3)=>isInterrupted2(cause3)?failCause8(cause3):offer3(queue,failCause8(cause3)).pipe(zipRight4(succeed2(errorSignal,void 0)),asVoid2)))}yield*pull.pipe(matchCauseEffect3({onFailure:(cause3)=>offer3(queue,failCause8(cause3)).pipe(zipRight4(succeed9(!1))),onSuccess:match({onLeft:(outDone)=>raceWith2(interruptible4(_await(errorSignal)),interruptible4(withPermits(concurrencyN)(_void)),{onSelfDone:(_,permitAcquisition)=>as3(interrupt6(permitAcquisition),!1),onOtherDone:(_,failureAwait)=>zipRight4(interrupt6(failureAwait),get12(lastDone).pipe(flatMap10(match2({onNone:()=>offer3(queue,succeed9(left2(outDone))),onSome:(lastDone2)=>offer3(queue,succeed9(left2(f(lastDone2,outDone))))})),as3(!1)))}),onRight:(channel)=>match15(mergeStrategy,{onBackPressure:()=>gen2(function*(){let latch=yield*make19(),raceEffects=scopedWith2((scope5)=>toPullIn(pipeTo(queueReader,channel),scope5).pipe(flatMap10((pull2)=>race2(exit2(evaluatePull(pull2)),exit2(interruptible4(_await(errorSignal))))),flatMap10(identity)));return yield*succeed2(latch,void 0).pipe(zipRight4(raceEffects),withPermits(1),forkIn2(scope4)),yield*_await(latch),!(yield*isDone(errorSignal))}),onBufferSliding:()=>gen2(function*(){let canceler=yield*make19(),latch=yield*make19(),size14=yield*size13(cancelers);yield*take3(cancelers).pipe(flatMap10((canceler2)=>succeed2(canceler2,void 0)),when2(()=>size14>=concurrencyN)),yield*offer3(cancelers,canceler);let raceEffects=scopedWith2((scope5)=>toPullIn(pipeTo(queueReader,channel),scope5).pipe(flatMap10((pull2)=>exit2(evaluatePull(pull2)).pipe(race2(exit2(interruptible4(_await(errorSignal)))),race2(exit2(interruptible4(_await(canceler)))))),flatMap10(identity)));return yield*succeed2(latch,void 0).pipe(zipRight4(raceEffects),withPermits(1),forkIn2(scope4)),yield*_await(latch),!(yield*isDone(errorSignal))})})})}),repeat({while:(_)=>_}),forkIn2(scope4));let consumer=pipe(take3(queue),flatten8,matchCause2({onFailure:failCause10,onSuccess:match({onLeft:succeedNow,onRight:(outElem)=>flatMap12(write(outElem),()=>consumer)})}),unwrap);return embedInput(consumer,input)})),mergeMap=dual(3,(self,f,options)=>mergeAll5(options)(mapOut(self,f)));var mergeWith2=dual(2,(self,options)=>{function merge9(scope4){return gen2(function*(){let input=yield*make45(),queueReader=fromInput(input),pullL=yield*toPullIn(pipeTo(queueReader,self),scope4),pullR=yield*toPullIn(pipeTo(queueReader,options.other),scope4);function handleSide(exit3,fiber,pull){return(done9,both2,single2)=>{function onDecision(decision){let op=decision;if(op._tag===OP_DONE4)return succeed9(fromEffect5(zipRight4(interrupt6(fiber),op.effect)));return map16(_await3(fiber),match6({onFailure:(cause3)=>fromEffect5(op.f(failCause3(cause3))),onSuccess:match({onLeft:(done10)=>fromEffect5(op.f(succeed3(done10))),onRight:(elem)=>zipRight5(write(elem),go(single2(op.f)))})}))}return match6(exit3,{onFailure:(cause3)=>onDecision(done9(failCause3(cause3))),onSuccess:match({onLeft:(z)=>onDecision(done9(succeed3(z))),onRight:(elem)=>succeed9(flatMap12(write(elem),()=>flatMap12(fromEffect5(forkIn2(interruptible4(pull),scope4)),(leftFiber)=>go(both2(leftFiber,fiber)))))})})}}function go(state){switch(state._tag){case OP_BOTH_RUNNING:{let leftJoin=interruptible4(join3(state.left)),rightJoin=interruptible4(join3(state.right));return unwrap(raceWith2(leftJoin,rightJoin,{onSelfDone:(leftExit,rf)=>zipRight4(interrupt6(rf),handleSide(leftExit,state.right,pullL)(options.onSelfDone,BothRunning,(f)=>LeftDone(f))),onOtherDone:(rightExit,lf)=>zipRight4(interrupt6(lf),handleSide(rightExit,state.left,pullR)(options.onOtherDone,(left3,right3)=>BothRunning(right3,left3),(f)=>RightDone(f)))}))}case OP_LEFT_DONE:return unwrap(map16(exit2(pullR),match6({onFailure:(cause3)=>fromEffect5(state.f(failCause3(cause3))),onSuccess:match({onLeft:(done9)=>fromEffect5(state.f(succeed3(done9))),onRight:(elem)=>flatMap12(write(elem),()=>go(LeftDone(state.f)))})})));case OP_RIGHT_DONE:return unwrap(map16(exit2(pullL),match6({onFailure:(cause3)=>fromEffect5(state.f(failCause3(cause3))),onSuccess:match({onLeft:(done9)=>fromEffect5(state.f(succeed3(done9))),onRight:(elem)=>flatMap12(write(elem),()=>go(RightDone(state.f)))})})))}}return fromEffect5(withFiberRuntime2((parent)=>{let inherit=withFiberRuntime2((state)=>{return state.transferChildren(parent.scope()),_void}),leftFiber=interruptible4(pullL).pipe(ensuring2(inherit),forkIn2(scope4)),rightFiber=interruptible4(pullR).pipe(ensuring2(inherit),forkIn2(scope4));return zipWith8(leftFiber,rightFiber,(left3,right3)=>BothRunning(left3,right3))})).pipe(flatMap12(go),embedInput(input))})}return unwrapScopedWith(merge9)});var orDieWith3=dual(2,(self,f)=>catchAll4(self,(e)=>failCauseSync4(()=>die4(f(e))))),orElse7=dual(2,(self,that)=>catchAll4(self,that)),pipeToOrFail=dual(2,(self,that)=>suspend4(()=>{let channelException=void 0,reader=readWith({onInput:(outElem)=>flatMap12(write(outElem),()=>reader),onFailure:(outErr)=>{return channelException=ChannelException(outErr),failCause10(die4(channelException))},onDone:succeedNow}),writer=readWithCause({onInput:(outElem)=>pipe(write(outElem),flatMap12(()=>writer)),onFailure:(cause3)=>isDieType2(cause3)&&isChannelException(cause3.defect)&&equals(cause3.defect,channelException)?fail11(cause3.defect.error):failCause10(cause3),onDone:succeedNow});return pipeTo(pipeTo(pipeTo(self,reader),that),writer)}));var repeated=(self)=>flatMap12(self,()=>repeated(self)),run=(self)=>scopedWith2((scope4)=>runIn(self,scope4));var runDrain=(self)=>run(drain(self)),runScoped=(self)=>scopeWith2((scope4)=>runIn(self,scope4)),scoped4=(effect2)=>unwrap(uninterruptibleMask3((restore)=>map16(make41(),(scope4)=>acquireReleaseOut(tapErrorCause2(restore(extend2(effect2,scope4)),(cause3)=>close(scope4,failCause3(cause3))),(_,exit3)=>close(scope4,exit3))))),scopedWith3=(f)=>unwrapScoped2(map16(scope2,(scope4)=>flatMap12(fromEffect5(f(scope4)),write)));var splitLines=()=>suspend4(()=>{let stringBuilder="",midCRLF=!1,splitLinesChunk=(chunk2)=>{let chunkBuilder=[];return map4(chunk2,(str)=>{if(str.length!==0){let from=0,indexOfCR=str.indexOf("\r"),indexOfLF=str.indexOf(`
|
|
35
|
+
`);if(midCRLF){if(indexOfLF===0)chunkBuilder.push(stringBuilder),stringBuilder="",from=1,indexOfLF=str.indexOf(`
|
|
36
|
+
`,from);else stringBuilder=stringBuilder+"\r";midCRLF=!1}while(indexOfCR!==-1||indexOfLF!==-1)if(indexOfCR===-1||indexOfLF!==-1&&indexOfLF<indexOfCR){if(stringBuilder.length===0)chunkBuilder.push(str.substring(from,indexOfLF));else chunkBuilder.push(stringBuilder+str.substring(from,indexOfLF)),stringBuilder="";from=indexOfLF+1,indexOfLF=str.indexOf(`
|
|
37
|
+
`,from)}else if(str.length===indexOfCR+1)midCRLF=!0,indexOfCR=-1;else if(indexOfLF===indexOfCR+1){if(stringBuilder.length===0)chunkBuilder.push(str.substring(from,indexOfCR));else stringBuilder=stringBuilder+str.substring(from,indexOfCR),chunkBuilder.push(stringBuilder),stringBuilder="";from=indexOfCR+2,indexOfCR=str.indexOf("\r",from),indexOfLF=str.indexOf(`
|
|
38
|
+
`,from)}else indexOfCR=str.indexOf("\r",indexOfCR+1);if(midCRLF)stringBuilder=stringBuilder+str.substring(from,str.length-1);else stringBuilder=stringBuilder+str.substring(from,str.length)}}),unsafeFromArray(chunkBuilder)},loop3=readWithCause({onInput:(input)=>{let out=splitLinesChunk(input);return isEmpty(out)?loop3:flatMap12(write(out),()=>loop3)},onFailure:(cause3)=>stringBuilder.length===0?failCause10(cause3):flatMap12(write(of2(stringBuilder)),()=>failCause10(cause3)),onDone:(done9)=>stringBuilder.length===0?succeed10(done9):flatMap12(write(of2(stringBuilder)),()=>succeed10(done9))});return loop3}),toPubSub=(pubsub)=>toQueue(pubsub),toPull=(self)=>flatMap10(scope2,(scope4)=>toPullIn(self,scope4)),toPullIn=dual(2,(self,scope4)=>zip6(sync3(()=>new ChannelExecutor(self,void 0,identity)),runtime3()).pipe(tap2(([executor,runtime4])=>addFinalizerExit(scope4,(exit3)=>{let finalizer=executor.close(exit3);return finalizer!==void 0?provide2(finalizer,runtime4):_void})),uninterruptible2,map16(([executor])=>suspend3(()=>interpretToPull(executor.run(),executor))))),interpretToPull=(channelState,exec)=>{let state=channelState;switch(state._tag){case OP_DONE3:return match6(exec.getDone(),{onFailure:failCause8,onSuccess:(done9)=>succeed9(left2(done9))});case OP_EMIT2:return succeed9(right2(exec.getEmit()));case OP_FROM_EFFECT3:return pipe(state.effect,flatMap10(()=>interpretToPull(exec.run(),exec)));case OP_READ2:return readUpstream(state,()=>interpretToPull(exec.run(),exec),(cause3)=>failCause8(cause3))}},toQueue=(queue)=>suspend4(()=>toQueueInternal(queue)),toQueueInternal=(queue)=>{return readWithCause({onInput:(elem)=>flatMap12(fromEffect5(offer3(queue,right2(elem))),()=>toQueueInternal(queue)),onFailure:(cause3)=>fromEffect5(pipe(offer3(queue,left2(failCause3(cause3))))),onDone:(done9)=>fromEffect5(pipe(offer3(queue,left2(succeed3(done9)))))})},unwrap=(channel)=>flatten10(fromEffect5(channel)),unwrapScoped2=(self)=>concatAllWith(scoped4(self),(d,_)=>d,(d,_)=>d),unwrapScopedWith=(f)=>concatAllWith(scopedWith3(f),(d,_)=>d,(d,_)=>d);var withSpan4=function(){let dataFirst=typeof arguments[0]!=="string",name=dataFirst?arguments[1]:arguments[0],options=addSpanStackTrace(dataFirst?arguments[2]:arguments[1]),acquire=all7([makeSpan2(name,options),context3(),clock2,get13(currentTracerTimingEnabled2)]);if(dataFirst){let self=arguments[0];return acquireUseRelease3(acquire,([span3,context5])=>provideContext3(self,add2(context5,spanTag,span3)),([span3,,clock3,timingEnabled],exit3)=>endSpan(span3,exit3,clock3,timingEnabled))}return(self)=>acquireUseRelease3(acquire,([span3,context5])=>provideContext3(self,add2(context5,spanTag,span3)),([span3,,clock3,timingEnabled],exit3)=>endSpan(span3,exit3,clock3,timingEnabled))},writeAll=(...outs)=>writeChunk(fromIterable2(outs)),writeChunk=(outs)=>writeChunkWriter(0,outs.length,outs),writeChunkWriter=(idx,len,chunk2)=>{return idx===len?void_6:pipe(write(pipe(chunk2,unsafeGet4(idx))),flatMap12(()=>writeChunkWriter(idx+1,len,chunk2)))},zip7=dual((args2)=>isChannel(args2[1]),(self,that,options)=>options?.concurrent?mergeWith2(self,{other:that,onSelfDone:(exit1)=>Await((exit22)=>suspend3(()=>zip3(exit1,exit22))),onOtherDone:(exit22)=>Await((exit1)=>suspend3(()=>zip3(exit1,exit22)))}):flatMap12(self,(a)=>map18(that,(b)=>[a,b]))),zipLeft4=dual((args2)=>isChannel(args2[1]),(self,that,options)=>options?.concurrent?map18(zip7(self,that,{concurrent:!0}),(tuple3)=>tuple3[0]):flatMap12(self,(z)=>as4(that,z))),zipRight5=dual((args2)=>isChannel(args2[1]),(self,that,options)=>options?.concurrent?map18(zip7(self,that,{concurrent:!0}),(tuple3)=>tuple3[1]):flatMap12(self,()=>that)),ChannelExceptionTypeId=Symbol.for("effect/Channel/ChannelException"),ChannelException=(error)=>({_tag:"ChannelException",[ChannelExceptionTypeId]:ChannelExceptionTypeId,error}),isChannelException=(u)=>hasProperty(u,ChannelExceptionTypeId);var SinkTypeId2=Symbol.for("effect/Sink"),sinkVariance2={_A:(_)=>_,_In:(_)=>_,_L:(_)=>_,_E:(_)=>_,_R:(_)=>_};class SinkImpl{channel;[SinkTypeId2]=sinkVariance2;constructor(channel){this.channel=channel}pipe(){return pipeArguments(this,arguments)}}var isSink=(u)=>hasProperty(u,SinkTypeId2),suspend5=(evaluate2)=>new SinkImpl(suspend4(()=>toChannel(evaluate2())));var collectAll=()=>new SinkImpl(collectAllLoop(empty5())),collectAllLoop=(acc)=>readWithCause({onInput:(chunk2)=>collectAllLoop(pipe(acc,appendAll2(chunk2))),onFailure:failCause10,onDone:()=>succeed10(acc)}),collectAllN=(n)=>suspend5(()=>fromChannel(collectAllNLoop(n,empty5()))),collectAllNLoop=(n,acc)=>readWithCause({onInput:(chunk2)=>{let[collected,leftovers]=splitAt2(chunk2,n);if(collected.length<n)return collectAllNLoop(n-collected.length,appendAll2(acc,collected));if(isEmpty(leftovers))return succeed10(appendAll2(acc,collected));return flatMap12(write(leftovers),()=>succeed10(appendAll2(acc,collected)))},onFailure:failCause10,onDone:()=>succeed10(acc)});var collectLeftover=(self)=>new SinkImpl(pipe(collectElements(toChannel(self)),map18(([chunks,z])=>[z,flatten3(chunks)])));var drain2=new SinkImpl(drain(identityChannel()));var fail12=(e)=>new SinkImpl(fail11(e));var fold=(s,contFn,f)=>suspend5(()=>new SinkImpl(foldReader(s,contFn,f))),foldReader=(s,contFn,f)=>{if(!contFn(s))return succeedNow(s);return readWith({onInput:(input)=>{let[nextS,leftovers]=foldChunkSplit(s,input,contFn,f,0,input.length);if(isNonEmpty2(leftovers))return pipe(write(leftovers),as4(nextS));return foldReader(nextS,contFn,f)},onFailure:fail11,onDone:()=>succeedNow(s)})},foldChunkSplit=(s,chunk2,contFn,f,index,length3)=>{if(index===length3)return[s,empty5()];let s1=f(s,pipe(chunk2,unsafeGet4(index)));if(contFn(s1))return foldChunkSplit(s1,chunk2,contFn,f,index+1,length3);return[s1,pipe(chunk2,drop2(index+1))]},foldSink=dual(2,(self,options)=>{let newChannel=pipe(toChannel(self),collectElements,foldChannel({onFailure:(error)=>toChannel(options.onFailure(error)),onSuccess:([leftovers,z])=>suspend4(()=>{let leftoversRef={ref:pipe(leftovers,filter3(isNonEmpty2))},refReader=pipe(sync4(()=>{let ref=leftoversRef.ref;return leftoversRef.ref=empty5(),ref}),flatMap12((chunk2)=>writeChunk(chunk2))),passthrough3=identityChannel(),continuationSink=pipe(refReader,zipRight5(passthrough3),pipeTo(toChannel(options.onSuccess(z))));return flatMap12(collectElements(continuationSink),([newLeftovers,z1])=>pipe(succeed10(leftoversRef.ref),flatMap12(writeChunk),zipRight5(writeChunk(newLeftovers)),as4(z1)))})}));return new SinkImpl(newChannel)}),foldChunks=(s,contFn,f)=>suspend5(()=>new SinkImpl(foldChunksReader(s,contFn,f))),foldChunksReader=(s,contFn,f)=>{if(!contFn(s))return succeedNow(s);return readWith({onInput:(input)=>foldChunksReader(f(s,input),contFn,f),onFailure:fail11,onDone:()=>succeedNow(s)})};var foldEffect=(s,contFn,f)=>suspend5(()=>new SinkImpl(foldEffectReader(s,contFn,f))),foldEffectReader=(s,contFn,f)=>{if(!contFn(s))return succeedNow(s);return readWith({onInput:(input)=>pipe(fromEffect5(foldChunkSplitEffect(s,input,contFn,f)),flatMap12(([nextS,leftovers])=>pipe(leftovers,match2({onNone:()=>foldEffectReader(nextS,contFn,f),onSome:(leftover)=>pipe(write(leftover),as4(nextS))})))),onFailure:fail11,onDone:()=>succeedNow(s)})},foldChunkSplitEffect=(s,chunk2,contFn,f)=>foldChunkSplitEffectInternal(s,chunk2,0,chunk2.length,contFn,f),foldChunkSplitEffectInternal=(s,chunk2,index,length3,contFn,f)=>{if(index===length3)return succeed9([s,none2()]);return pipe(f(s,pipe(chunk2,unsafeGet4(index))),flatMap10((s1)=>contFn(s1)?foldChunkSplitEffectInternal(s1,chunk2,index+1,length3,contFn,f):succeed9([s1,some2(pipe(chunk2,drop2(index+1)))])))};var foldLeftChunks=(s,f)=>foldChunks(s,constTrue,f);var flatMap13=dual(2,(self,f)=>foldSink(self,{onFailure:fail12,onSuccess:f})),forEach9=(f)=>{let process2=readWithCause({onInput:(input)=>pipe(fromEffect5(forEach8(input,(v)=>f(v),{discard:!0})),flatMap12(()=>process2)),onFailure:failCause10,onDone:()=>void_6});return new SinkImpl(process2)},forEachChunk=(f)=>{let process2=readWithCause({onInput:(input)=>pipe(fromEffect5(f(input)),flatMap12(()=>process2)),onFailure:failCause10,onDone:()=>void_6});return new SinkImpl(process2)},forEachWhile=(f)=>{let process2=readWithCause({onInput:(input)=>forEachWhileReader(f,input,0,input.length,process2),onFailure:failCause10,onDone:()=>void_6});return new SinkImpl(process2)},forEachWhileReader=(f,input,index,length3,cont)=>{if(index===length3)return cont;return pipe(fromEffect5(f(pipe(input,unsafeGet4(index)))),flatMap12((bool)=>bool?forEachWhileReader(f,input,index+1,length3,cont):write(pipe(input,drop2(index)))),catchAll4((error)=>pipe(write(pipe(input,drop2(index))),zipRight5(fail11(error)))))};var fromChannel=(channel)=>new SinkImpl(channel),fromEffect7=(effect2)=>new SinkImpl(fromEffect5(effect2));var head5=()=>fold(none2(),isNone2,(option3,input)=>match2(option3,{onNone:()=>some2(input),onSome:()=>option3}));var last4=()=>foldLeftChunks(none2(),(s,input)=>orElse(last2(input),()=>s));var map19=dual(2,(self,f)=>{return new SinkImpl(pipe(toChannel(self),map18(f)))});var raceWith3=dual(2,(self,options)=>{function race3(scope4){return gen2(function*(){let pubsub=yield*bounded4(options?.capacity??16),subscription1=yield*extend2(subscribe2(pubsub),scope4),subscription2=yield*extend2(subscribe2(pubsub),scope4),reader=toPubSub(pubsub),writer=fromQueue(subscription1).pipe(pipeTo(toChannel(self)),zipLeft4(fromEffect5(shutdown4(subscription1))),mergeWith2({other:fromQueue(subscription2).pipe(pipeTo(toChannel(options.other)),zipLeft4(fromEffect5(shutdown4(subscription2)))),onSelfDone:options.onSelfDone,onOtherDone:options.onOtherDone})),racedChannel=mergeWith2(reader,{other:writer,onSelfDone:()=>Await(identity),onOtherDone:(exit3)=>Done3(exit3)});return new SinkImpl(racedChannel)})}return unwrapScopedWith2(race3)});var sum2=foldLeftChunks(0,(acc,chunk2)=>acc+reduce3(chunk2,0,(s,a)=>s+a));var toChannel=(self)=>isEffect2(self)?toChannel(fromEffect7(self)):self.channel;var unwrapScopedWith2=(f)=>new SinkImpl(unwrapScopedWith((scope4)=>f(scope4).pipe(map16((sink)=>toChannel(sink)))));var zipRight6=dual((args2)=>isSink(args2[1]),(self,that,options)=>zipWith9(self,that,(_,z2)=>z2,options)),zipWith9=dual((args2)=>isSink(args2[1]),(self,that,f,options)=>options?.concurrent?raceWith3(self,{other:that,onSelfDone:match6({onFailure:(cause3)=>Done3(failCause8(cause3)),onSuccess:(leftZ)=>Await(match6({onFailure:failCause8,onSuccess:(rightZ)=>succeed9(f(leftZ,rightZ))}))}),onOtherDone:match6({onFailure:(cause3)=>Done3(failCause8(cause3)),onSuccess:(rightZ)=>Await(match6({onFailure:failCause8,onSuccess:(leftZ)=>succeed9(f(leftZ,rightZ))}))})}):flatMap13(self,(z)=>map19(that,(z2)=>f(z,z2))));var count=foldLeftChunks(0,(acc,chunk2)=>acc+chunk2.length),mkString=suspend5(()=>{let strings=[];return pipe(foldLeftChunks(void 0,(_,elems)=>map4(elems,(elem)=>{strings.push(String(elem))})),map19(()=>strings.join("")))});var Done4=Done3,Await2=Await;var TypeId19=Symbol.for("effect/RcRef"),stateEmpty2={_tag:"Empty"},stateClosed={_tag:"Closed"},variance8={_A:identity,_E:identity};class RcRefImpl extends Class{acquire;context;scope;idleTimeToLive;[TypeId19]=variance8;[TypeId13]=TypeId13;state=stateEmpty2;semaphore=unsafeMakeSemaphore(1);constructor(acquire,context5,scope4,idleTimeToLive){super();this.acquire=acquire,this.context=context5,this.scope=scope4,this.idleTimeToLive=idleTimeToLive,this.get=get14(this)}get;commit(){return this.get}}var make46=(options)=>withFiberRuntime((fiber)=>{let context5=fiber.getFiberRef(currentContext),scope4=get3(context5,scopeTag),ref=new RcRefImpl(options.acquire,context5,scope4,options.idleTimeToLive?decode(options.idleTimeToLive):void 0);return as(scope4.addFinalizer(()=>ref.semaphore.withPermits(1)(suspend(()=>{let close2=ref.state._tag==="Acquired"?scopeClose(ref.state.scope,exitVoid):void_;return ref.state=stateClosed,close2}))),ref)}),get14=(self_)=>{let self=self_;return uninterruptibleMask((restore)=>suspend(()=>{switch(self.state._tag){case"Closed":return interrupt2;case"Acquired":return self.state.refCount++,self.state.fiber?as(interruptFiber(self.state.fiber),self.state):succeed(self.state);case"Empty":return scopeMake().pipe(bindTo2("scope"),bind2("value",({scope:scope4})=>restore(fiberRefLocally(self.acquire,currentContext,add2(self.context,scopeTag,scope4)))),map10(({scope:scope4,value})=>{let state={_tag:"Acquired",value,scope:scope4,fiber:void 0,refCount:1};return self.state=state,state}))}})).pipe(self.semaphore.withPermits(1),bindTo2("state"),bind2("scope",()=>scopeTag),tap(({scope:scope4,state})=>scope4.addFinalizer(()=>suspend(()=>{if(state.refCount--,state.refCount>0)return void_;if(self.idleTimeToLive===void 0)return self.state=stateEmpty2,scopeClose(state.scope,exitVoid);return sleep3(self.idleTimeToLive).pipe(interruptible2,zipRight(suspend(()=>{if(self.state._tag==="Acquired"&&self.state.refCount===0)return self.state=stateEmpty2,scopeClose(state.scope,exitVoid);return void_})),ensuring(sync(()=>{state.fiber=void 0})),forkIn(self.scope),tap((fiber)=>{state.fiber=fiber}),self.semaphore.withPermits(1))}))),map10(({state})=>state.value))};var make47=make46,get15=get14;var runFork3=unsafeFork2;var runPromiseExit2=unsafeRunPromiseExit,defaultRuntime2=defaultRuntime;var driver2=driver;var forever4=forever2;var spaced2=spaced;var OP_LEFT="Left",OP_RIGHT="Right",OP_BOTH="Both",OP_EITHER="Either";var Left={_tag:OP_LEFT},Right={_tag:OP_RIGHT},Both={_tag:OP_BOTH},Either={_tag:OP_EITHER},fromInput2=(input)=>{switch(input){case"left":return Left;case"right":return Right;case"both":return Both;case"either":return Either;default:return input}};var Both2=Both;class Versioned{value;constructor(value){this.value=value}}var make48=(ref,isNew)=>({ref,isNew,isChanged:!1,expected:ref.versioned,newValue:ref.versioned.value}),unsafeGet7=(self)=>{return self.newValue},unsafeSet=(self,value)=>{self.isChanged=!0,self.newValue=value},commit=(self)=>{self.ref.versioned=new Versioned(self.newValue)};var isInvalid=(self)=>{return self.ref.versioned!==self.expected},isChanged=(self)=>{return self.isChanged};var JournalAnalysisInvalid="Invalid",JournalAnalysisReadWrite="ReadWrite",JournalAnalysisReadOnly="ReadOnly",commitJournal=(journal)=>{for(let entry of journal)commit(entry[1])},analyzeJournal=(journal)=>{let val=JournalAnalysisReadOnly;for(let[,entry]of journal)if(val=isInvalid(entry)?JournalAnalysisInvalid:isChanged(entry)?JournalAnalysisReadWrite:val,val===JournalAnalysisInvalid)return val;return val};var collectTodos=(journal)=>{let allTodos=new Map;for(let[,entry]of journal){for(let todo of entry.ref.todos)allTodos.set(todo[0],todo[1]);entry.ref.todos=new Map}return allTodos},execTodos=(todos)=>{let todosSorted=Array.from(todos.entries()).sort((x,y)=>x[0]-y[0]);for(let[_,todo]of todosSorted)todo()},addTodo=(txnId,journal,todoEffect)=>{let added=!1;for(let[,entry]of journal)if(!entry.ref.todos.has(txnId))entry.ref.todos.set(txnId,todoEffect),added=!0;return added};var OP_WITH_STM_RUNTIME="WithSTMRuntime",OP_ON_FAILURE2="OnFailure",OP_ON_RETRY="OnRetry",OP_ON_SUCCESS2="OnSuccess",OP_PROVIDE3="Provide",OP_SYNC2="Sync",OP_SUCCEED2="Succeed",OP_RETRY="Retry",OP_FAIL4="Fail",OP_DIE2="Die",OP_INTERRUPT2="Interrupt";var OP_FAIL5="Fail",OP_DIE3="Die",OP_INTERRUPT3="Interrupt",OP_SUCCEED3="Succeed",OP_RETRY2="Retry";var OP_DONE5="Done",OP_SUSPEND3="Suspend";var OP_DONE6="Done",OP_INTERRUPTED="Interrupted",OP_RUNNING2="Running";var STMStateSymbolKey="effect/STM/State",STMStateTypeId=Symbol.for(STMStateSymbolKey),isSTMState=(u)=>hasProperty(u,STMStateTypeId),isRunning3=(self)=>{return self._tag===OP_RUNNING2},isDone6=(self)=>{return self._tag===OP_DONE6};var done9=(exit3)=>{return{[STMStateTypeId]:STMStateTypeId,_tag:OP_DONE6,exit:exit3,[symbol](){return pipe(hash(STMStateSymbolKey),combine(hash(OP_DONE6)),combine(hash(exit3)),cached(this))},[symbol2](that){return isSTMState(that)&&that._tag===OP_DONE6&&equals(exit3,that.exit)}}},interruptedHash=pipe(hash(STMStateSymbolKey),combine(hash(OP_INTERRUPTED)),combine(hash("interrupted"))),interrupted3={[STMStateTypeId]:STMStateTypeId,_tag:OP_INTERRUPTED,[symbol](){return interruptedHash},[symbol2](that){return isSTMState(that)&&that._tag===OP_INTERRUPTED}},runningHash=pipe(hash(STMStateSymbolKey),combine(hash(OP_RUNNING2)),combine(hash("running"))),running3={[STMStateTypeId]:STMStateTypeId,_tag:OP_RUNNING2,[symbol](){return runningHash},[symbol2](that){return isSTMState(that)&&that._tag===OP_RUNNING2}},fromTExit=(tExit)=>{switch(tExit._tag){case OP_FAIL5:return done9(fail4(tExit.error));case OP_DIE3:return done9(die3(tExit.defect));case OP_INTERRUPT3:return done9(interrupt4(tExit.fiberId));case OP_SUCCEED3:return done9(succeed3(tExit.value));case OP_RETRY2:throw new Error("BUG: STM.STMState.fromTExit - please report an issue at https://github.com/Effect-TS/effect/issues")}};var TExitSymbolKey="effect/TExit",TExitTypeId=Symbol.for(TExitSymbolKey),variance9={_A:(_)=>_,_E:(_)=>_},isExit2=(u)=>hasProperty(u,TExitTypeId);var isSuccess4=(self)=>{return self._tag===OP_SUCCEED3},isRetry=(self)=>{return self._tag===OP_RETRY2},fail13=(error)=>({[TExitTypeId]:variance9,_tag:OP_FAIL5,error,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_FAIL5)),combine(hash(error)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_FAIL5&&equals(error,that.error)}}),die7=(defect)=>({[TExitTypeId]:variance9,_tag:OP_DIE3,defect,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_DIE3)),combine(hash(defect)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_DIE3&&equals(defect,that.defect)}}),interrupt8=(fiberId3)=>({[TExitTypeId]:variance9,_tag:OP_INTERRUPT3,fiberId:fiberId3,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_INTERRUPT3)),combine(hash(fiberId3)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_INTERRUPT3&&equals(fiberId3,that.fiberId)}}),succeed12=(value)=>({[TExitTypeId]:variance9,_tag:OP_SUCCEED3,value,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_SUCCEED3)),combine(hash(value)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_SUCCEED3&&equals(value,that.value)}}),retryHash=pipe(hash(TExitSymbolKey),combine(hash(OP_RETRY2)),combine(hash("retry"))),retry3={[TExitTypeId]:variance9,_tag:OP_RETRY2,[symbol](){return retryHash},[symbol2](that){return isExit2(that)&&isRetry(that)}};var done10=(exit3)=>{return{_tag:OP_DONE5,exit:exit3}},suspend6=(journal)=>{return{_tag:OP_SUSPEND3,journal}};var txnCounter={ref:0},make49=()=>{let newId=txnCounter.ref+1;return txnCounter.ref=newId,newId};var STMSymbolKey2="effect/STM",STMTypeId2=Symbol.for(STMSymbolKey2),stmVariance={_R:(_)=>_,_E:(_)=>_,_A:(_)=>_};class STMPrimitive{effect_instruction_i0;_op=OP_COMMIT;effect_instruction_i1=void 0;effect_instruction_i2=void 0;[EffectTypeId3];[StreamTypeId];[SinkTypeId2];[ChannelTypeId2];get[STMTypeId2](){return stmVariance}constructor(effect_instruction_i0){this.effect_instruction_i0=effect_instruction_i0,this[EffectTypeId3]=effectVariance,this[StreamTypeId]=stmVariance,this[SinkTypeId2]=stmVariance,this[ChannelTypeId2]=stmVariance}[symbol2](that){return this===that}[symbol](){return cached(this,random(this))}[Symbol.iterator](){return new SingleShotGen2(new YieldWrap(this))}commit(){return unsafeAtomically(this,constVoid,constVoid)}pipe(){return pipeArguments(this,arguments)}}var unsafeAtomically=(self,onDone,onInterrupt3)=>withFiberRuntime((state)=>{let fiberId3=state.id(),env=state.getFiberRef(currentContext2),scheduler=state.getFiberRef(currentScheduler2),priority=state.getFiberRef(currentSchedulingPriority2),commitResult=tryCommitSync(fiberId3,self,env,scheduler,priority);switch(commitResult._tag){case OP_DONE5:return onDone(commitResult.exit),commitResult.exit;case OP_SUSPEND3:{let txnId=make49(),state2={value:running3},effect2=async((k)=>tryCommitAsync(fiberId3,self,txnId,state2,env,scheduler,priority,k));return uninterruptibleMask3((restore)=>pipe(restore(effect2),catchAllCause2((cause3)=>{let currentState=state2.value;if(isRunning3(currentState))state2.value=interrupted3;if(currentState=state2.value,isDone6(currentState))return onDone(currentState.exit),currentState.exit;return onInterrupt3(),failCause8(cause3)})))}}}),tryCommit=(fiberId3,stm,state,env,scheduler,priority)=>{let journal=new Map,tExit=new STMDriver(stm,journal,fiberId3,env).run(),analysis=analyzeJournal(journal);if(analysis===JournalAnalysisReadWrite)commitJournal(journal);else if(analysis===JournalAnalysisInvalid)throw new Error("BUG: STM.TryCommit.tryCommit - please report an issue at https://github.com/Effect-TS/effect/issues");switch(tExit._tag){case OP_SUCCEED3:return state.value=fromTExit(tExit),completeTodos(succeed3(tExit.value),journal,scheduler,priority);case OP_FAIL5:{state.value=fromTExit(tExit);let cause3=fail6(tExit.error);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_DIE3:{state.value=fromTExit(tExit);let cause3=die4(tExit.defect);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_INTERRUPT3:{state.value=fromTExit(tExit);let cause3=interrupt5(fiberId3);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_RETRY2:return suspend6(journal)}},tryCommitSync=(fiberId3,stm,env,scheduler,priority)=>{let journal=new Map,tExit=new STMDriver(stm,journal,fiberId3,env).run(),analysis=analyzeJournal(journal);if(analysis===JournalAnalysisReadWrite&&isSuccess4(tExit))commitJournal(journal);else if(analysis===JournalAnalysisInvalid)throw new Error("BUG: STM.TryCommit.tryCommitSync - please report an issue at https://github.com/Effect-TS/effect/issues");switch(tExit._tag){case OP_SUCCEED3:return completeTodos(succeed3(tExit.value),journal,scheduler,priority);case OP_FAIL5:{let cause3=fail6(tExit.error);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_DIE3:{let cause3=die4(tExit.defect);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_INTERRUPT3:{let cause3=interrupt5(fiberId3);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_RETRY2:return suspend6(journal)}},tryCommitAsync=(fiberId3,self,txnId,state,context5,scheduler,priority,k)=>{if(isRunning3(state.value)){let result=tryCommit(fiberId3,self,state,context5,scheduler,priority);switch(result._tag){case OP_DONE5:{completeTryCommit(result.exit,k);break}case OP_SUSPEND3:{addTodo(txnId,result.journal,()=>tryCommitAsync(fiberId3,self,txnId,state,context5,scheduler,priority,k));break}}}},completeTodos=(exit3,journal,scheduler,priority)=>{let todos=collectTodos(journal);if(todos.size>0)scheduler.scheduleTask(()=>execTodos(todos),priority);return done10(exit3)},completeTryCommit=(exit3,k)=>{k(exit3)};class STMDriver{self;journal;fiberId;contStack=[];env;constructor(self,journal,fiberId3,r0){this.self=self,this.journal=journal,this.fiberId=fiberId3,this.env=r0}getEnv(){return this.env}pushStack(cont){this.contStack.push(cont)}popStack(){return this.contStack.pop()}nextSuccess(){let current=this.popStack();while(current!==void 0&¤t.effect_instruction_i0!==OP_ON_SUCCESS2)current=this.popStack();return current}nextFailure(){let current=this.popStack();while(current!==void 0&¤t.effect_instruction_i0!==OP_ON_FAILURE2)current=this.popStack();return current}nextRetry(){let current=this.popStack();while(current!==void 0&¤t.effect_instruction_i0!==OP_ON_RETRY)current=this.popStack();return current}run(){let curr=this.self,exit3=void 0;while(exit3===void 0&&curr!==void 0)try{let current=curr;if(current)switch(current._op){case"Tag":{curr=effect2((_,__,env)=>unsafeGet3(env,current));break}case"Left":{curr=fail14(current.left);break}case"None":{curr=fail14(new NoSuchElementException2);break}case"Right":{curr=succeed13(current.right);break}case"Some":{curr=succeed13(current.value);break}case"Commit":{switch(current.effect_instruction_i0){case OP_DIE2:{exit3=die7(internalCall(()=>current.effect_instruction_i1()));break}case OP_FAIL4:{let cont=this.nextFailure();if(cont===void 0)exit3=fail13(internalCall(()=>current.effect_instruction_i1()));else curr=internalCall(()=>cont.effect_instruction_i2(internalCall(()=>current.effect_instruction_i1())));break}case OP_RETRY:{let cont=this.nextRetry();if(cont===void 0)exit3=retry3;else curr=internalCall(()=>cont.effect_instruction_i2());break}case OP_INTERRUPT2:{exit3=interrupt8(this.fiberId);break}case OP_WITH_STM_RUNTIME:{curr=internalCall(()=>current.effect_instruction_i1(this));break}case OP_ON_SUCCESS2:case OP_ON_FAILURE2:case OP_ON_RETRY:{this.pushStack(current),curr=current.effect_instruction_i1;break}case OP_PROVIDE3:{let env=this.env;this.env=internalCall(()=>current.effect_instruction_i2(env)),curr=pipe(current.effect_instruction_i1,ensuring5(sync6(()=>this.env=env)));break}case OP_SUCCEED2:{let value=current.effect_instruction_i1,cont=this.nextSuccess();if(cont===void 0)exit3=succeed12(value);else curr=internalCall(()=>cont.effect_instruction_i2(value));break}case OP_SYNC2:{let value=internalCall(()=>current.effect_instruction_i1()),cont=this.nextSuccess();if(cont===void 0)exit3=succeed12(value);else curr=internalCall(()=>cont.effect_instruction_i2(value));break}}break}}}catch(e){curr=die8(e)}return exit3}}var catchAll5=dual(2,(self,f)=>{let stm=new STMPrimitive(OP_ON_FAILURE2);return stm.effect_instruction_i1=self,stm.effect_instruction_i2=f,stm});var die8=(defect)=>dieSync4(()=>defect);var dieSync4=(evaluate2)=>{let stm=new STMPrimitive(OP_DIE2);return stm.effect_instruction_i1=evaluate2,stm},effect2=(f)=>withSTMRuntime((_)=>succeed13(f(_.journal,_.fiberId,_.getEnv()))),ensuring5=dual(2,(self,finalizer)=>matchSTM(self,{onFailure:(e)=>zipRight8(finalizer,fail14(e)),onSuccess:(a)=>zipRight8(finalizer,succeed13(a))})),fail14=(error)=>failSync5(()=>error),failSync5=(evaluate2)=>{let stm=new STMPrimitive(OP_FAIL4);return stm.effect_instruction_i1=evaluate2,stm},flatMap14=dual(2,(self,f)=>{let stm=new STMPrimitive(OP_ON_SUCCESS2);return stm.effect_instruction_i1=self,stm.effect_instruction_i2=f,stm}),matchSTM=dual(2,(self,{onFailure,onSuccess})=>pipe(self,map20(right2),catchAll5((e)=>pipe(onFailure(e),map20(left2))),flatMap14((either5)=>{switch(either5._tag){case"Left":return succeed13(either5.left);case"Right":return onSuccess(either5.right)}}))),withSTMRuntime=(f)=>{let stm=new STMPrimitive(OP_WITH_STM_RUNTIME);return stm.effect_instruction_i1=f,stm};var interruptAs2=(fiberId3)=>{let stm=new STMPrimitive(OP_INTERRUPT2);return stm.effect_instruction_i1=fiberId3,stm},map20=dual(2,(self,f)=>pipe(self,flatMap14((a)=>sync6(()=>f(a)))));var retry4=new STMPrimitive(OP_RETRY),succeed13=(value)=>{let stm=new STMPrimitive(OP_SUCCEED2);return stm.effect_instruction_i1=value,stm},sync6=(evaluate2)=>{let stm=new STMPrimitive(OP_SYNC2);return stm.effect_instruction_i1=evaluate2,stm};var zipRight8=dual(2,(self,that)=>pipe(self,flatMap14(()=>that))),zipWith11=dual(3,(self,that,f)=>pipe(self,flatMap14((a)=>pipe(that,map20((b)=>f(a,b))))));var OP_BACKPRESSURE_STRATEGY="BackPressure",OP_DROPPING_STRATEGY="Dropping",OP_SLIDING_STRATEGY="Sliding";var as6=dual(2,(self,value)=>pipe(self,map20(()=>value)));var flatten11=(self)=>flatMap14(self,identity);var forEach10=dual((args2)=>isIterable(args2[0]),(iterable,f,options)=>{if(options?.discard)return pipe(sync6(()=>iterable[Symbol.iterator]()),flatMap14((iterator)=>{let loop3=suspend7(()=>{let next4=iterator.next();if(next4.done)return void_7;return pipe(f(next4.value),flatMap14(()=>loop3))});return loop3}));return suspend7(()=>fromIterable(iterable).reduce((acc,curr)=>zipWith11(acc,f(curr),(array4,elem)=>{return array4.push(elem),array4}),succeed13([])))});var all8=(input,options)=>{if(Symbol.iterator in input)return forEach10(input,identity,options);else if(options?.discard)return forEach10(Object.values(input),identity,options);return map20(forEach10(Object.entries(input),([_,e])=>map20(e,(a)=>[_,a])),(values3)=>{let res={};for(let[k,v]of values3)res[k]=v;return res})};var suspend7=(evaluate2)=>flatten11(sync6(evaluate2)),tap4=dual(2,(self,f)=>flatMap14(self,(a)=>as6(f(a),a)));var void_7=succeed13(void 0);var TRefSymbolKey="effect/TRef",TRefTypeId=Symbol.for(TRefSymbolKey),tRefVariance={_A:(_)=>_};class TRefImpl{[TRefTypeId]=tRefVariance;todos;versioned;constructor(value){this.versioned=new Versioned(value),this.todos=new Map}modify(f){return effect2((journal)=>{let entry=getOrMakeEntry(this,journal),[retValue,newValue]=f(unsafeGet7(entry));return unsafeSet(entry,newValue),retValue})}pipe(){return pipeArguments(this,arguments)}}var make50=(value)=>effect2((journal)=>{let ref=new TRefImpl(value);return journal.set(ref,make48(ref,!0)),ref}),get16=(self)=>self.modify((a)=>[a,a]),set7=dual(2,(self,value)=>self.modify(()=>[void 0,value]));var getOrMakeEntry=(self,journal)=>{if(journal.has(self))return journal.get(self);let entry=make48(self,!1);return journal.set(self,entry),entry},unsafeGet8=dual(2,(self,journal)=>unsafeGet7(getOrMakeEntry(self,journal))),unsafeSet2=dual(3,(self,value,journal)=>{let entry=getOrMakeEntry(self,journal);unsafeSet(entry,value);return});var TEnqueueSymbolKey="effect/TQueue/TEnqueue",TEnqueueTypeId=Symbol.for(TEnqueueSymbolKey),TDequeueSymbolKey="effect/TQueue/TDequeue",TDequeueTypeId=Symbol.for(TDequeueSymbolKey);var tDequeueVariance={_Out:(_)=>_},tEnqueueVariance={_In:(_)=>_};class TQueueImpl{ref;requestedCapacity;strategy;[TDequeueTypeId]=tDequeueVariance;[TEnqueueTypeId]=tEnqueueVariance;constructor(ref,requestedCapacity,strategy){this.ref=ref,this.requestedCapacity=requestedCapacity,this.strategy=strategy}capacity(){return this.requestedCapacity}size=withSTMRuntime((runtime4)=>{let queue=unsafeGet8(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);return succeed13(queue.length)});isFull=map20(this.size,(size14)=>size14===this.requestedCapacity);isEmpty=map20(this.size,(size14)=>size14===0);shutdown=withSTMRuntime((runtime4)=>{return unsafeSet2(this.ref,void 0,runtime4.journal),void_7});isShutdown=effect2((journal)=>{return unsafeGet8(this.ref,journal)===void 0});awaitShutdown=flatMap14(this.isShutdown,(isShutdown4)=>isShutdown4?void_7:retry4);offer(value){return withSTMRuntime((runtime4)=>{let queue=pipe(this.ref,unsafeGet8(runtime4.journal));if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length<this.requestedCapacity)return queue.push(value),unsafeSet2(this.ref,queue,runtime4.journal),succeed13(!0);switch(this.strategy._tag){case OP_BACKPRESSURE_STRATEGY:return retry4;case OP_DROPPING_STRATEGY:return succeed13(!1);case OP_SLIDING_STRATEGY:{if(queue.length===0)return succeed13(!0);return queue.shift(),queue.push(value),unsafeSet2(this.ref,queue,runtime4.journal),succeed13(!0)}}})}offerAll(iterable){return withSTMRuntime((runtime4)=>{let as7=Array.from(iterable),queue=unsafeGet8(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length+as7.length<=this.requestedCapacity)return unsafeSet2(this.ref,[...queue,...as7],runtime4.journal),succeed13(!0);switch(this.strategy._tag){case OP_BACKPRESSURE_STRATEGY:return retry4;case OP_DROPPING_STRATEGY:{let forQueue=as7.slice(0,this.requestedCapacity-queue.length);return unsafeSet2(this.ref,[...queue,...forQueue],runtime4.journal),succeed13(!1)}case OP_SLIDING_STRATEGY:{let forQueue=as7.slice(0,this.requestedCapacity-queue.length),toDrop=queue.length+forQueue.length-this.requestedCapacity,newQueue=queue.slice(toDrop);return unsafeSet2(this.ref,[...newQueue,...forQueue],runtime4.journal),succeed13(!0)}}})}peek=withSTMRuntime((runtime4)=>{let queue=unsafeGet8(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length===0)return retry4;return succeed13(queue[0])});peekOption=withSTMRuntime((runtime4)=>{let queue=unsafeGet8(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);return succeed13(fromNullable(queue[0]))});take=withSTMRuntime((runtime4)=>{let queue=unsafeGet8(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length===0)return retry4;let dequeued=queue.shift();return unsafeSet2(this.ref,queue,runtime4.journal),succeed13(dequeued)});takeAll=withSTMRuntime((runtime4)=>{let queue=unsafeGet8(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);return unsafeSet2(this.ref,[],runtime4.journal),succeed13(queue)});takeUpTo(max6){return withSTMRuntime((runtime4)=>{let queue=unsafeGet8(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);let[toTake,remaining]=splitAt2(unsafeFromArray(queue),max6);return unsafeSet2(this.ref,Array.from(remaining),runtime4.journal),succeed13(Array.from(toTake))})}}var isShutdown4=(self)=>self.isShutdown;var shutdown5=(self)=>self.shutdown;var take4=(self)=>self.take;var TPubSubSymbolKey="effect/TPubSub",TPubSubTypeId=Symbol.for(TPubSubSymbolKey),AbsentValue2=Symbol.for("effect/TPubSub/AbsentValue"),makeNode2=(head6,subscribers,tail)=>({head:head6,subscribers,tail});class TPubSubImpl{pubsubSize;publisherHead;publisherTail;requestedCapacity;strategy;subscriberCount;subscribers;[TPubSubTypeId]={_A:(_)=>_};[TEnqueueTypeId]=tEnqueueVariance;constructor(pubsubSize,publisherHead,publisherTail,requestedCapacity,strategy,subscriberCount,subscribers){this.pubsubSize=pubsubSize,this.publisherHead=publisherHead,this.publisherTail=publisherTail,this.requestedCapacity=requestedCapacity,this.strategy=strategy,this.subscriberCount=subscriberCount,this.subscribers=subscribers}isShutdown=effect2((journal)=>{return unsafeGet8(this.publisherTail,journal)===void 0});awaitShutdown=flatMap14(this.isShutdown,(isShutdown5)=>isShutdown5?void_7:retry4);capacity(){return this.requestedCapacity}size=withSTMRuntime((runtime4)=>{if(unsafeGet8(this.publisherTail,runtime4.journal)===void 0)return interruptAs2(runtime4.fiberId);return succeed13(unsafeGet8(this.pubsubSize,runtime4.journal))});isEmpty=map20(this.size,(size14)=>size14===0);isFull=map20(this.size,(size14)=>size14===this.capacity());offer(value){return withSTMRuntime((runtime4)=>{let currentPublisherTail=unsafeGet8(this.publisherTail,runtime4.journal);if(currentPublisherTail===void 0)return interruptAs2(runtime4.fiberId);let currentSubscriberCount=unsafeGet8(this.subscriberCount,runtime4.journal);if(currentSubscriberCount===0)return succeed13(!0);let currentPubSubSize=unsafeGet8(this.pubsubSize,runtime4.journal);if(currentPubSubSize<this.requestedCapacity){let updatedPublisherTail=new TRefImpl(void 0),updatedNode=makeNode2(value,currentSubscriberCount,updatedPublisherTail);return unsafeSet2(currentPublisherTail,updatedNode,runtime4.journal),unsafeSet2(this.publisherTail,updatedPublisherTail,runtime4.journal),unsafeSet2(this.pubsubSize,currentPubSubSize+1,runtime4.journal),succeed13(!0)}switch(this.strategy._tag){case OP_BACKPRESSURE_STRATEGY:return retry4;case OP_DROPPING_STRATEGY:return succeed13(!1);case OP_SLIDING_STRATEGY:{if(this.requestedCapacity>0){let currentPublisherHead=unsafeGet8(this.publisherHead,runtime4.journal),loop3=!0;while(loop3){let node=unsafeGet8(currentPublisherHead,runtime4.journal);if(node===void 0)return retry4;let{head:head6,tail}=node;if(head6!==AbsentValue2){let updatedNode2=makeNode2(AbsentValue2,node.subscribers,node.tail);unsafeSet2(currentPublisherHead,updatedNode2,runtime4.journal),unsafeSet2(this.publisherHead,tail,runtime4.journal),loop3=!1}else currentPublisherHead=tail}}let updatedPublisherTail=new TRefImpl(void 0),updatedNode=makeNode2(value,currentSubscriberCount,updatedPublisherTail);return unsafeSet2(currentPublisherTail,updatedNode,runtime4.journal),unsafeSet2(this.publisherTail,updatedPublisherTail,runtime4.journal),succeed13(!0)}}})}offerAll(iterable){return map20(forEach10(iterable,(a)=>this.offer(a)),every(identity))}shutdown=effect2((journal)=>{if(unsafeGet8(this.publisherTail,journal)!==void 0){unsafeSet2(this.publisherTail,void 0,journal);let currentSubscribers=unsafeGet8(this.subscribers,journal);forEach3(currentSubscribers,(subscriber)=>{unsafeSet2(subscriber,void 0,journal)}),unsafeSet2(this.subscribers,empty8(),journal)}})}class TPubSubSubscriptionImpl{pubsubSize;publisherHead;requestedCapacity;subscriberHead;subscriberCount;subscribers;[TPubSubTypeId]=TPubSubTypeId;[TDequeueTypeId]=tDequeueVariance;constructor(pubsubSize,publisherHead,requestedCapacity,subscriberHead,subscriberCount,subscribers){this.pubsubSize=pubsubSize,this.publisherHead=publisherHead,this.requestedCapacity=requestedCapacity,this.subscriberHead=subscriberHead,this.subscriberCount=subscriberCount,this.subscribers=subscribers}isShutdown=effect2((journal)=>{return unsafeGet8(this.subscriberHead,journal)===void 0});awaitShutdown=flatMap14(this.isShutdown,(isShutdown5)=>isShutdown5?void_7:retry4);capacity(){return this.requestedCapacity}size=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet8(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let loop3=!0,size14=0;while(loop3){let node=unsafeGet8(currentSubscriberHead,runtime4.journal);if(node===void 0)loop3=!1;else{let{head:head6,tail}=node;if(head6!==AbsentValue2){if(size14=size14+1,size14>=Number.MAX_SAFE_INTEGER)loop3=!1}currentSubscriberHead=tail}}return succeed13(size14)});isEmpty=map20(this.size,(size14)=>size14===0);isFull=map20(this.size,(size14)=>size14===this.capacity());peek=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet8(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let value=AbsentValue2,loop3=!0;while(loop3){let node=unsafeGet8(currentSubscriberHead,runtime4.journal);if(node===void 0)return retry4;let{head:head6,tail}=node;if(head6!==AbsentValue2)value=head6,loop3=!1;else currentSubscriberHead=tail}return succeed13(value)});peekOption=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet8(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let value=none2(),loop3=!0;while(loop3){let node=unsafeGet8(currentSubscriberHead,runtime4.journal);if(node===void 0)value=none2(),loop3=!1;else{let{head:head6,tail}=node;if(head6!==AbsentValue2)value=some2(head6),loop3=!1;else currentSubscriberHead=tail}}return succeed13(value)});shutdown=effect2((journal)=>{let currentSubscriberHead=unsafeGet8(this.subscriberHead,journal);if(currentSubscriberHead!==void 0){unsafeSet2(this.subscriberHead,void 0,journal);let loop3=!0;while(loop3){let node=unsafeGet8(currentSubscriberHead,journal);if(node===void 0)loop3=!1;else{let{head:head6,tail}=node;if(head6!==AbsentValue2){let subscribers=node.subscribers;if(subscribers===1){let size14=unsafeGet8(this.pubsubSize,journal),updatedNode=makeNode2(AbsentValue2,0,tail);unsafeSet2(currentSubscriberHead,updatedNode,journal),unsafeSet2(this.publisherHead,tail,journal),unsafeSet2(this.pubsubSize,size14-1,journal)}else{let updatedNode=makeNode2(head6,subscribers-1,tail);unsafeSet2(currentSubscriberHead,updatedNode,journal)}}currentSubscriberHead=tail}}let currentSubscriberCount=unsafeGet8(this.subscriberCount,journal);unsafeSet2(this.subscriberCount,currentSubscriberCount-1,journal),unsafeSet2(this.subscribers,remove4(unsafeGet8(this.subscribers,journal),this.subscriberHead),journal)}});take=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet8(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let value=AbsentValue2,loop3=!0;while(loop3){let node=unsafeGet8(currentSubscriberHead,runtime4.journal);if(node===void 0)return retry4;let{head:head6,tail}=node;if(head6!==AbsentValue2){let subscribers=node.subscribers;if(subscribers===1){let size14=unsafeGet8(this.pubsubSize,runtime4.journal),updatedNode=makeNode2(AbsentValue2,0,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal),unsafeSet2(this.publisherHead,tail,runtime4.journal),unsafeSet2(this.pubsubSize,size14-1,runtime4.journal)}else{let updatedNode=makeNode2(head6,subscribers-1,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal)}unsafeSet2(this.subscriberHead,tail,runtime4.journal),value=head6,loop3=!1}else currentSubscriberHead=tail}return succeed13(value)});takeAll=this.takeUpTo(Number.POSITIVE_INFINITY);takeUpTo(max6){return withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet8(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let builder=[],n=0;while(n!==max6){let node=unsafeGet8(currentSubscriberHead,runtime4.journal);if(node===void 0)n=max6;else{let{head:head6,tail}=node;if(head6!==AbsentValue2){let subscribers=node.subscribers;if(subscribers===1){let size14=unsafeGet8(this.pubsubSize,runtime4.journal),updatedNode=makeNode2(AbsentValue2,0,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal),unsafeSet2(this.publisherHead,tail,runtime4.journal),unsafeSet2(this.pubsubSize,size14-1,runtime4.journal)}else{let updatedNode=makeNode2(head6,subscribers-1,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal)}builder.push(head6),n=n+1}currentSubscriberHead=tail}}return unsafeSet2(this.subscriberHead,currentSubscriberHead,runtime4.journal),succeed13(builder)})}}var makeSubscription2=(pubsubSize,publisherHead,publisherTail,requestedCapacity,subscriberCount,subscribers)=>pipe(get16(publisherTail),flatMap14((currentPublisherTail)=>pipe(all8([make50(currentPublisherTail),get16(subscriberCount),get16(subscribers)]),tap4(([_,currentSubscriberCount])=>pipe(subscriberCount,set7(currentSubscriberCount+1))),tap4(([subscriberHead,_,currentSubscribers])=>pipe(subscribers,set7(pipe(currentSubscribers,add4(subscriberHead))))),map20(([subscriberHead])=>new TPubSubSubscriptionImpl(pubsubSize,publisherHead,requestedCapacity,subscriberHead,subscriberCount,subscribers)))));var subscribe3=(self)=>makeSubscription2(self.pubsubSize,self.publisherHead,self.publisherTail,self.requestedCapacity,self.subscriberCount,self.subscribers),subscribeScoped=(self)=>acquireRelease2(subscribe3(self),(dequeue)=>shutdown5(dequeue));var subscribeScoped2=subscribeScoped;var isShutdown6=isShutdown4;var take5=take4;class RingBuffer{capacity;array;size=0;current=0;constructor(capacity7){this.capacity=capacity7,this.array=Array.from({length:capacity7},constUndefined)}head(){return fromNullable(this.array[this.current])}lastOrNull(){if(this.size===0)return;let index=this.current===0?this.array.length-1:this.current-1;return this.array[index]??void 0}put(value){this.array[this.current]=value,this.increment()}dropLast(){if(this.size>0)this.decrement(),this.array[this.current]=void 0}toChunk(){let begin=this.current-this.size,newArray=begin<0?[...this.array.slice(this.capacity+begin,this.capacity),...this.array.slice(0,this.current)]:this.array.slice(begin,this.current);return fromIterable2(newArray)}increment(){if(this.size<this.capacity)this.size+=1;this.current=(this.current+1)%this.capacity}decrement(){if(this.size-=1,this.current>0)this.current-=1;else this.current=this.capacity-1}}var OP_NOT_STARTED="NotStarted",OP_PREVIOUS="Previous",OP_CURRENT="Current",notStarted={_tag:"NotStarted"},previous=(fiber)=>({_tag:"Previous",fiber}),current=(fiber)=>({_tag:"Current",fiber});var make51=(emit)=>{return Object.assign(emit,{chunk(as7){return this(succeed9(as7))},die(defect){return this(die5(defect))},dieMessage(message){return this(dieMessage2(message))},done(exit3){return this(suspend3(()=>mapBoth2(exit3,{onFailure:some2,onSuccess:of2})))},end(){return this(fail9(none2()))},fail(e){return this(fail9(some2(e)))},fromEffect(effect3){return this(mapBoth3(effect3,{onFailure:some2,onSuccess:of2}))},fromEffectChunk(effect3){return this(pipe(effect3,mapError2(some2)))},halt(cause3){return this(failCause8(pipe(cause3,map13(some2))))},single(value){return this(succeed9(of2(value)))}})},makePush=(queue,scheduler)=>{let finished=!1,buffer=[],running4=!1;function array4(items){if(finished)return!1;if(items.length<=50000)buffer.push.apply(buffer,items);else for(let i=0;i<items.length;i++)buffer.push(items[0]);if(!running4)running4=!0,scheduler.scheduleTask(flush,0);return!0}function flush(){if(running4=!1,buffer.length>0)queue.unsafeOffer(buffer),buffer=[]}function done11(exit3){if(finished)return;if(finished=!0,exit3._tag==="Success")buffer.push(exit3.value);flush(),queue.unsafeOffer(exit3._tag==="Success"?void_2:exit3)}return{single(value){if(finished)return!1;if(buffer.push(value),!running4)running4=!0,scheduler.scheduleTask(flush,0);return!0},array:array4,chunk(chunk2){return array4(toReadonlyArray(chunk2))},done:done11,end(){if(finished)return;finished=!0,flush(),queue.unsafeOffer(void_2)},halt(cause3){return done11(failCause3(cause3))},fail(error){return done11(fail4(error))},die(defect){return done11(die3(defect))},dieMessage(message){return done11(die3(new Error(message)))}}};var HandoffTypeId=Symbol.for("effect/Stream/Handoff"),OP_HANDOFF_STATE_EMPTY="Empty",OP_HANDOFF_STATE_FULL="Full",handoffStateEmpty=(notifyConsumer)=>({_tag:OP_HANDOFF_STATE_EMPTY,notifyConsumer}),handoffStateFull=(value,notifyProducer)=>({_tag:OP_HANDOFF_STATE_FULL,value,notifyProducer}),handoffStateMatch=(onEmpty,onFull)=>{return(self)=>{switch(self._tag){case OP_HANDOFF_STATE_EMPTY:return onEmpty(self.notifyConsumer);case OP_HANDOFF_STATE_FULL:return onFull(self.value,self.notifyProducer)}}},handoffVariance={_A:(_)=>_},make52=()=>pipe(make19(),flatMap10((deferred)=>make29(handoffStateEmpty(deferred))),map16((ref)=>({[HandoffTypeId]:handoffVariance,ref}))),offer5=dual(2,(self,value)=>{return flatMap10(make19(),(deferred)=>flatten8(modify3(self.ref,(state)=>pipe(state,handoffStateMatch((notifyConsumer)=>[zipRight4(succeed2(notifyConsumer,void 0),_await(deferred)),handoffStateFull(value,deferred)],(_,notifyProducer)=>[flatMap10(_await(notifyProducer),()=>pipe(self,offer5(value))),state])))))}),take6=(self)=>flatMap10(make19(),(deferred)=>flatten8(modify3(self.ref,(state)=>pipe(state,handoffStateMatch((notifyConsumer)=>[flatMap10(_await(notifyConsumer),()=>take6(self)),state],(value,notifyProducer)=>[as3(succeed2(notifyProducer,void 0),value),handoffStateEmpty(deferred)])))));var OP_EMIT4="Emit",OP_HALT="Halt",OP_END="End",emit=(elements)=>({_tag:"Emit",elements}),halt=(cause3)=>({_tag:"Halt",cause:cause3}),end3=(reason)=>({_tag:"End",reason});var TakeSymbolKey="effect/Take",TakeTypeId=Symbol.for(TakeSymbolKey),takeVariance={_A:(_)=>_,_E:(_)=>_};class TakeImpl{exit;[TakeTypeId]=takeVariance;constructor(exit3){this.exit=exit3}pipe(){return pipeArguments(this,arguments)}}var chunk2=(chunk3)=>new TakeImpl(succeed3(chunk3));var done11=(self)=>suspend3(()=>self.exit),end4=new TakeImpl(fail4(none2()));var failCause11=(cause3)=>new TakeImpl(failCause3(pipe(cause3,map13(some2))));var fromPull=(pull)=>matchCause2(pull,{onFailure:(cause3)=>match2(flipCauseOption2(cause3),{onNone:()=>end4,onSome:failCause11}),onSuccess:chunk2});var match18=dual(2,(self,{onEnd,onFailure,onSuccess})=>match6(self.exit,{onFailure:(cause3)=>match2(flipCauseOption2(cause3),{onNone:onEnd,onSome:onFailure}),onSuccess}));var of5=(value)=>new TakeImpl(succeed3(of2(value)));var end5=()=>fail9(none2());var failCause12=(cause3)=>mapError2(failCause8(cause3),some2);var OP_SCHEDULE_END="ScheduleEnd",OP_UPSTREAM_END="UpstreamEnd",ScheduleEnd={_tag:"ScheduleEnd"},UpstreamEnd={_tag:"UpstreamEnd"};var OP_DRAIN_LEFT="DrainLeft",OP_DRAIN_RIGHT="DrainRight",OP_PULL_BOTH="PullBoth",OP_PULL_LEFT="PullLeft",OP_PULL_RIGHT="PullRight",DrainLeft={_tag:"DrainLeft"},DrainRight={_tag:"DrainRight"},PullBoth={_tag:"PullBoth"},PullLeft=(rightChunk)=>({_tag:"PullLeft",rightChunk}),PullRight=(leftChunk)=>({_tag:"PullRight",leftChunk});var OP_PULL_BOTH2="PullBoth",OP_PULL_LEFT2="PullLet",OP_PULL_RIGHT2="PullRight",PullBoth2={_tag:"PullBoth"},PullLeft2=(rightChunk)=>({_tag:"PullLet",rightChunk}),PullRight2=(leftChunk)=>({_tag:"PullRight",leftChunk});var StreamSymbolKey="effect/Stream",StreamTypeId2=Symbol.for(StreamSymbolKey),streamVariance={_R:(_)=>_,_E:(_)=>_,_A:(_)=>_};class StreamImpl{channel;[StreamTypeId2]=streamVariance;constructor(channel){this.channel=channel}pipe(){return pipeArguments(this,arguments)}}var isStream=(u)=>hasProperty(u,StreamTypeId2)||isEffect2(u),DefaultChunkSize=4096,accumulate=(self)=>chunks(accumulateChunks(self)),accumulateChunks=(self)=>{let accumulator=(s)=>readWith({onInput:(input)=>{let next4=appendAll2(s,input);return flatMap12(write(next4),()=>accumulator(next4))},onFailure:fail11,onDone:()=>void_6});return new StreamImpl(pipeTo(toChannel2(self),accumulator(empty5())))},acquireRelease3=(acquire,release)=>scoped5(acquireRelease2(acquire,release)),aggregate=dual(2,(self,sink)=>aggregateWithin(self,sink,forever4)),aggregateWithin=dual(3,(self,sink,schedule2)=>filterMap6(aggregateWithinEither(self,sink,schedule2),(_)=>match(_,{onLeft:none2,onRight:some2}))),aggregateWithinEither=dual(3,(self,sink,schedule2)=>{let layer=all7([make52(),make29(ScheduleEnd),make29(empty5()),driver2(schedule2),make29(!1),make29(!1)]);return fromEffect8(layer).pipe(flatMap15(([handoff,sinkEndReason,sinkLeftovers,scheduleDriver,consumed,endAfterEmit])=>{let handoffProducer=readWithCause({onInput:(input)=>flatMap12(fromEffect5(pipe(handoff,offer5(emit(input)),when2(()=>isNonEmpty2(input)))),()=>handoffProducer),onFailure:(cause3)=>fromEffect5(offer5(handoff,halt(cause3))),onDone:()=>fromEffect5(offer5(handoff,end3(UpstreamEnd)))}),handoffConsumer=pipe(getAndSet2(sinkLeftovers,empty5()),flatMap10((leftovers)=>{if(isNonEmpty2(leftovers))return pipe(set6(consumed,!0),zipRight4(succeed9(pipe(write(leftovers),flatMap12(()=>handoffConsumer)))));return pipe(take6(handoff),map16((signal)=>{switch(signal._tag){case OP_EMIT4:return pipe(fromEffect5(set6(consumed,!0)),zipRight5(write(signal.elements)),zipRight5(fromEffect5(get12(endAfterEmit))),flatMap12((bool)=>bool?void_6:handoffConsumer));case OP_HALT:return failCause10(signal.cause);case OP_END:{if(signal.reason._tag===OP_SCHEDULE_END)return pipe(get12(consumed),map16((bool)=>bool?fromEffect5(pipe(set6(sinkEndReason,ScheduleEnd),zipRight4(set6(endAfterEmit,!0)))):pipe(fromEffect5(pipe(set6(sinkEndReason,ScheduleEnd),zipRight4(set6(endAfterEmit,!0)))),flatMap12(()=>handoffConsumer))),unwrap);return pipe(set6(sinkEndReason,signal.reason),zipRight4(set6(endAfterEmit,!0)),fromEffect5)}}}))}),unwrap),timeout3=(lastB)=>scheduleDriver.next(lastB),scheduledAggregator=(sinkFiber,scheduleFiber,scope4)=>{let forkSink=pipe(set6(consumed,!1),zipRight4(set6(endAfterEmit,!1)),zipRight4(pipe(handoffConsumer,pipeToOrFail(toChannel(sink)),collectElements,run,forkIn2(scope4)))),handleSide=(leftovers,b,c)=>pipe(set6(sinkLeftovers,flatten3(leftovers)),zipRight4(map16(get12(sinkEndReason),(reason)=>{switch(reason._tag){case OP_SCHEDULE_END:return pipe(all7([get12(consumed),forkSink,pipe(timeout3(some2(b)),forkIn2(scope4))]),map16(([wasConsumed,sinkFiber2,scheduleFiber2])=>{let toWrite=pipe(c,match2({onNone:()=>of2(right2(b)),onSome:(c2)=>make7(right2(b),left2(c2))}));if(wasConsumed)return pipe(write(toWrite),flatMap12(()=>scheduledAggregator(sinkFiber2,scheduleFiber2,scope4)));return scheduledAggregator(sinkFiber2,scheduleFiber2,scope4)}),unwrap);case OP_UPSTREAM_END:return pipe(get12(consumed),map16((wasConsumed)=>wasConsumed?write(of2(right2(b))):void_6),unwrap)}})),unwrap);return unwrap(raceWith2(join3(sinkFiber),join3(scheduleFiber),{onSelfDone:(sinkExit,_)=>pipe(interrupt6(scheduleFiber),zipRight4(pipe(suspend3(()=>sinkExit),map16(([leftovers,b])=>handleSide(leftovers,b,none2()))))),onOtherDone:(scheduleExit,_)=>matchCauseEffect3(suspend3(()=>scheduleExit),{onFailure:(cause3)=>match(failureOrCause2(cause3),{onLeft:()=>pipe(handoff,offer5(end3(ScheduleEnd)),forkDaemon2,zipRight4(pipe(join3(sinkFiber),map16(([leftovers,b])=>handleSide(leftovers,b,none2()))))),onRight:(cause4)=>pipe(handoff,offer5(halt(cause4)),forkDaemon2,zipRight4(pipe(join3(sinkFiber),map16(([leftovers,b])=>handleSide(leftovers,b,none2())))))}),onSuccess:(c)=>pipe(handoff,offer5(end3(ScheduleEnd)),forkDaemon2,zipRight4(pipe(join3(sinkFiber),map16(([leftovers,b])=>handleSide(leftovers,b,some2(c))))))})}))};return unwrapScopedWith3((scope4)=>pipeTo(toChannel2(self),handoffProducer).pipe(run,forkIn2(scope4),zipRight4(pipeToOrFail(handoffConsumer,toChannel(sink)).pipe(collectElements,run,forkIn2(scope4),flatMap10((sinkFiber)=>timeout3(none2()).pipe(forkIn2(scope4),map16((scheduleFiber)=>new StreamImpl(scheduledAggregator(sinkFiber,scheduleFiber,scope4)))))))))}))}),as7=dual(2,(self,value)=>map21(self,()=>value)),queueFromBufferOptions=(bufferSize)=>{if(bufferSize==="unbounded")return unbounded5();else if(typeof bufferSize==="number"||bufferSize===void 0)return bounded5(bufferSize??16);switch(bufferSize.strategy){case"dropping":return dropping4(bufferSize.bufferSize??16);case"sliding":return sliding4(bufferSize.bufferSize??16);default:return bounded5(bufferSize.bufferSize??16)}},_async=(register,bufferSize)=>acquireRelease2(queueFromBufferOptions(bufferSize),(queue)=>shutdown4(queue)).pipe(flatMap10((output)=>runtime3().pipe(flatMap10((runtime4)=>sync3(()=>{let runPromiseExit3=runPromiseExit2(runtime4);return register(make51((resume2)=>fromPull(resume2).pipe(flatMap10((take7)=>offer3(output,take7)),asVoid2,runPromiseExit3).then((exit3)=>{if(isFailure(exit3)){if(!isInterrupted2(exit3.cause))throw squash(exit3.cause)}})))})),map16((value)=>{let loop3=take3(output).pipe(flatMap10((take7)=>done11(take7)),match13({onFailure:(maybeError)=>fromEffect5(shutdown4(output)).pipe(zipRight5(match2(maybeError,{onNone:()=>void_6,onSome:(error)=>fail11(error)}))),onSuccess:(chunk3)=>write(chunk3).pipe(flatMap12(()=>loop3))}),unwrap);return fromChannel2(loop3).pipe(ensuring6(value??_void))}))),unwrapScoped3),asyncEffect3=(register,bufferSize)=>pipe(acquireRelease2(queueFromBufferOptions(bufferSize),(queue)=>shutdown4(queue)),flatMap10((output)=>pipe(runtime3(),flatMap10((runtime4)=>pipe(register(make51((k)=>pipe(fromPull(k),flatMap10((take7)=>offer3(output,take7)),asVoid2,runPromiseExit2(runtime4)).then((exit3)=>{if(isFailure(exit3)){if(!isInterrupted2(exit3.cause))throw squash(exit3.cause)}}))),map16(()=>{let loop3=pipe(take3(output),flatMap10(done11),match13({onFailure:(maybeError)=>pipe(fromEffect5(shutdown4(output)),zipRight5(match2(maybeError,{onNone:()=>void_6,onSome:fail11}))),onSuccess:(chunk3)=>pipe(write(chunk3),flatMap12(()=>loop3))}),unwrap);return loop3}))))),unwrapScoped2,fromChannel2),queueFromBufferOptionsPush=(options)=>{if(options?.bufferSize==="unbounded"||options?.bufferSize===void 0&&options?.strategy===void 0)return unbounded5();switch(options?.strategy){case"sliding":return sliding4(options.bufferSize??16);default:return dropping4(options?.bufferSize??16)}},asyncPush=(register,options)=>acquireRelease2(queueFromBufferOptionsPush(options),shutdown4).pipe(tap2((queue)=>getWith(currentScheduler2,(scheduler)=>register(makePush(queue,scheduler)))),map16((queue)=>{let loop3=flatMap12(take3(queue),(item)=>isExit(item)?isSuccess(item)?void_6:failCause10(item.cause):zipRight5(write(unsafeFromArray(item)),loop3));return loop3}),unwrapScoped2,fromChannel2),asyncScoped=(register,bufferSize)=>pipe(acquireRelease2(queueFromBufferOptions(bufferSize),(queue)=>shutdown4(queue)),flatMap10((output)=>pipe(runtime3(),flatMap10((runtime4)=>pipe(register(make51((k)=>pipe(fromPull(k),flatMap10((take7)=>offer3(output,take7)),asVoid2,runPromiseExit2(runtime4)).then((exit3)=>{if(isFailure(exit3)){if(!isInterrupted2(exit3.cause))throw squash(exit3.cause)}}))),zipRight4(make29(!1)),flatMap10((ref)=>pipe(get12(ref),map16((isDone7)=>isDone7?end5():pipe(take3(output),flatMap10(done11),onError2(()=>pipe(set6(ref,!0),zipRight4(shutdown4(output)))))))))))),scoped5,flatMap15(repeatEffectChunkOption)),branchAfter=dual(3,(self,n,f)=>suspend8(()=>{let buffering=(acc)=>readWith({onInput:(input)=>{if(acc.length+input.length>=n){let[b1,b2]=pipe(input,splitAt2(n-acc.length));return running4(pipe(acc,appendAll2(b1)),b2)}return buffering(pipe(acc,appendAll2(input)))},onFailure:fail11,onDone:()=>running4(acc,empty5())}),running4=(prefix,leftover)=>pipeTo(zipRight5(write(leftover),identityChannel()),toChannel2(f(prefix)));return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(buffering(empty5()))))})),broadcast=dual(3,(self,n,maximumLag)=>pipe(self,broadcastedQueues(n,maximumLag),map16((tuple3)=>tuple3.map((queue)=>flattenTake(fromQueue2(queue,{shutdown:!0})))))),broadcastDynamic=dual(2,(self,maximumLag)=>map16(toPubSub2(self,maximumLag),(pubsub)=>flattenTake(fromPubSub(pubsub)))),share=dual(2,(self,options)=>map16(make47({acquire:broadcastDynamic(self,options),idleTimeToLive:options.idleTimeToLive}),(rcRef)=>unwrapScoped3(get15(rcRef)))),broadcastedQueues=dual(3,(self,n,maximumLag)=>flatMap10(pubsubFromOptions(maximumLag),(pubsub)=>pipe(all7(Array.from({length:n},()=>subscribe2(pubsub))),tap2(()=>forkScoped2(runIntoPubSubScoped(self,pubsub)))))),broadcastedQueuesDynamic=dual(2,(self,maximumLag)=>map16(toPubSub2(self,maximumLag),subscribe2)),buffer=dual(2,(self,options)=>{if(options.capacity==="unbounded")return bufferUnbounded(self);else if(options.strategy==="dropping")return bufferDropping(self,options.capacity);else if(options.strategy==="sliding")return bufferSliding(self,options.capacity);let queue=toQueueOfElements(self,options);return new StreamImpl(unwrapScoped2(map16(queue,(queue2)=>{let process2=pipe(fromEffect5(take3(queue2)),flatMap12(match6({onFailure:(cause3)=>pipe(flipCauseOption2(cause3),match2({onNone:()=>void_6,onSome:failCause10})),onSuccess:(value)=>flatMap12(write(of2(value)),()=>process2)})));return process2})))}),bufferChunks=dual(2,(self,options)=>{if(options.strategy==="dropping")return bufferChunksDropping(self,options.capacity);else if(options.strategy==="sliding")return bufferChunksSliding(self,options.capacity);let queue=toQueue2(self,options);return new StreamImpl(unwrapScoped2(map16(queue,(queue2)=>{let process2=pipe(fromEffect5(take3(queue2)),flatMap12(match18({onEnd:()=>void_6,onFailure:failCause10,onSuccess:(value)=>pipe(write(value),flatMap12(()=>process2))})));return process2})))}),bufferChunksDropping=dual(2,(self,capacity7)=>{let queue=acquireRelease2(dropping4(capacity7),(queue2)=>shutdown4(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(self)))}),bufferChunksSliding=dual(2,(self,capacity7)=>{let queue=acquireRelease2(sliding4(capacity7),(queue2)=>shutdown4(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(self)))}),bufferDropping=dual(2,(self,capacity7)=>{let queue=acquireRelease2(dropping4(capacity7),(queue2)=>shutdown4(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(rechunk(1)(self))))}),bufferSliding=dual(2,(self,capacity7)=>{let queue=acquireRelease2(sliding4(capacity7),(queue2)=>shutdown4(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(pipe(self,rechunk(1)))))}),bufferUnbounded=(self)=>{let queue=toQueue2(self,{strategy:"unbounded"});return new StreamImpl(unwrapScoped2(map16(queue,(queue2)=>{let process2=pipe(fromEffect5(take3(queue2)),flatMap12(match18({onEnd:()=>void_6,onFailure:failCause10,onSuccess:(value)=>flatMap12(write(value),()=>process2)})));return process2})))},bufferSignal=(scoped5,bufferChannel)=>{let producer=(queue,ref)=>{let terminate=(take7)=>pipe(get12(ref),tap2(_await),zipRight4(make19()),flatMap10((deferred)=>pipe(offer3(queue,[take7,deferred]),zipRight4(set6(ref,deferred)),zipRight4(_await(deferred)))),asVoid2,fromEffect5);return readWithCause({onInput:(input)=>pipe(make19(),flatMap10((deferred)=>pipe(offer3(queue,[chunk2(input),deferred]),flatMap10((added)=>pipe(set6(ref,deferred),when2(()=>added))))),asVoid2,fromEffect5,flatMap12(()=>producer(queue,ref))),onFailure:(error)=>terminate(failCause11(error)),onDone:()=>terminate(end4)})},consumer=(queue)=>{let process2=pipe(fromEffect5(take3(queue)),flatMap12(([take7,deferred])=>zipRight5(fromEffect5(succeed2(deferred,void 0)),match18(take7,{onEnd:()=>void_6,onFailure:failCause10,onSuccess:(value)=>pipe(write(value),flatMap12(()=>process2))}))));return process2};return unwrapScoped2(pipe(scoped5,flatMap10((queue)=>pipe(make19(),tap2((start3)=>succeed2(start3,void 0)),flatMap10((start3)=>pipe(make29(start3),flatMap10((ref)=>pipe(bufferChannel,pipeTo(producer(queue,ref)),runScoped,forkScoped2)),as3(consumer(queue))))))))},catchAll6=dual(2,(self,f)=>catchAllCause5(self,(cause3)=>match(failureOrCause2(cause3),{onLeft:f,onRight:failCause13}))),catchAllCause5=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),catchAllCause4((cause3)=>toChannel2(f(cause3)))))),catchSome3=dual(2,(self,pf)=>pipe(self,catchAll6((error)=>pipe(pf(error),getOrElse(()=>fail15(error)))))),catchSomeCause3=dual(2,(self,pf)=>pipe(self,catchAllCause5((cause3)=>pipe(pf(cause3),getOrElse(()=>failCause13(cause3)))))),catchTag3=dual(3,(self,k,f)=>catchAll6(self,(e)=>{if("_tag"in e&&e._tag===k)return f(e);return fail15(e)})),catchTags3=dual(2,(self,cases)=>catchAll6(self,(e)=>{let keys5=Object.keys(cases);if("_tag"in e&&keys5.includes(e._tag))return cases[e._tag](e);return fail15(e)})),changes=(self)=>pipe(self,changesWith((x,y)=>equals(y)(x))),changesWith=dual(2,(self,f)=>{let writer=(last5)=>readWithCause({onInput:(input)=>{let[newLast,newChunk]=reduce3(input,[last5,empty5()],([option3,outputs],output)=>{if(isSome2(option3)&&f(option3.value,output))return[some2(output),outputs];return[some2(output),pipe(outputs,append2(output))]});return flatMap12(write(newChunk),()=>writer(newLast))},onFailure:failCause10,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeTo(writer(none2()))))}),changesWithEffect=dual(2,(self,f)=>{let writer=(last5)=>readWithCause({onInput:(input)=>pipe(input,reduce13([last5,empty5()],([option3,outputs],output)=>{if(isSome2(option3))return pipe(f(option3.value,output),map16((bool)=>bool?[some2(output),outputs]:[some2(output),pipe(outputs,append2(output))]));return succeed9([some2(output),pipe(outputs,append2(output))])}),fromEffect5,flatMap12(([newLast,newChunk])=>pipe(write(newChunk),flatMap12(()=>writer(newLast))))),onFailure:failCause10,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeTo(writer(none2()))))}),chunks=(self)=>pipe(self,mapChunks(of2)),chunksWith=dual(2,(self,f)=>flattenChunks(f(chunks(self)))),unsome=(effect3)=>catchAll2(asSome2(effect3),(o)=>o._tag==="None"?succeedNone2:fail9(o.value)),combine12=dual(4,(self,that,s,f)=>{function producer(handoff,latch){return fromEffect5(take6(latch)).pipe(zipRight5(readWithCause({onInput:(input)=>flatMap12(fromEffect5(offer5(handoff,succeed3(input))),()=>producer(handoff,latch)),onFailure:(cause3)=>fromEffect5(offer5(handoff,failCause3(pipe(cause3,map13(some2))))),onDone:()=>flatMap12(fromEffect5(offer5(handoff,fail4(none2()))),()=>producer(handoff,latch))})))}return new StreamImpl(unwrapScopedWith((scope4)=>all7([make52(),make52(),make52(),make52()]).pipe(tap2(([left3,_,latchL])=>toChannel2(self).pipe(concatMap(writeChunk),pipeTo(producer(left3,latchL)),runIn(scope4),forkIn2(scope4))),tap2(([,right3,_,rightL])=>toChannel2(that).pipe(concatMap(writeChunk),pipeTo(producer(right3,rightL)),runIn(scope4),forkIn2(scope4))),map16(([left3,right3,latchL,latchR])=>{let pullLeft=offer5(latchL,void 0).pipe(zipRight4(take6(left3).pipe(flatMap10(identity)))),pullRight=offer5(latchR,void 0).pipe(zipRight4(take6(right3).pipe(flatMap10(identity))));return toChannel2(unfoldEffect(s,(s2)=>flatMap10(f(s2,pullLeft,pullRight),unsome)))}))))}),combineChunks=dual(4,(self,that,s,f)=>{let producer=(handoff,latch)=>zipRight5(fromEffect5(take6(latch)),readWithCause({onInput:(input)=>flatMap12(fromEffect5(pipe(handoff,offer5(chunk2(input)))),()=>producer(handoff,latch)),onFailure:(cause3)=>fromEffect5(offer5(handoff,failCause11(cause3))),onDone:()=>fromEffect5(offer5(handoff,end4))}));return new StreamImpl(unwrapScopedWith((scope4)=>all7([make52(),make52(),make52(),make52()]).pipe(tap2(([left3,_,latchL])=>pipeTo(toChannel2(self),producer(left3,latchL)).pipe(runIn(scope4),forkIn2(scope4))),tap2(([_,right3,__,latchR])=>pipeTo(toChannel2(that),producer(right3,latchR)).pipe(runIn(scope4),forkIn2(scope4))),map16(([left3,right3,latchL,latchR])=>{let pullLeft=offer5(latchL,void 0).pipe(zipRight4(take6(left3).pipe(flatMap10(done11)))),pullRight=offer5(latchR,void 0).pipe(zipRight4(take6(right3).pipe(flatMap10(done11))));return toChannel2(unfoldChunkEffect(s,(s2)=>flatMap10(f(s2,pullLeft,pullRight),unsome)))}))))}),concat2=dual(2,(self,that)=>new StreamImpl(pipe(toChannel2(self),zipRight5(toChannel2(that))))),concatAll2=(streams)=>suspend8(()=>pipe(streams,reduce3(empty34,(x,y)=>concat2(y)(x)))),cross=dual(2,(left3,right3)=>pipe(left3,crossWith(right3,(a,a2)=>[a,a2]))),crossLeft=dual(2,(left3,right3)=>pipe(left3,crossWith(right3,(a,_)=>a))),crossRight=dual(2,(left3,right3)=>flatMap15(left3,()=>right3)),crossWith=dual(3,(left3,right3,f)=>pipe(left3,flatMap15((a)=>pipe(right3,map21((b)=>f(a,b)))))),debounce=dual(2,(self,duration2)=>unwrapScopedWith3((scope4)=>gen2(function*(){let handoff=yield*make52();function enqueue(last5){return sleep2(duration2).pipe(as3(last5),forkIn2(scope4),map16((fiber)=>consumer(previous(fiber))))}let producer=readWithCause({onInput:(input)=>match2(last2(input),{onNone:()=>producer,onSome:(elem)=>fromEffect5(offer5(handoff,emit(of2(elem)))).pipe(flatMap12(()=>producer))}),onFailure:(cause3)=>fromEffect5(offer5(handoff,halt(cause3))),onDone:()=>fromEffect5(offer5(handoff,end3(UpstreamEnd)))});function consumer(state){switch(state._tag){case OP_NOT_STARTED:return unwrap(take6(handoff).pipe(map16((signal)=>{switch(signal._tag){case OP_EMIT4:return unwrap(enqueue(signal.elements));case OP_HALT:return failCause10(signal.cause);case OP_END:return void_6}})));case OP_PREVIOUS:return unwrap(take6(handoff).pipe(forkIn2(scope4),flatMap10((handoffFiber)=>raceWith2(join3(state.fiber),join3(handoffFiber),{onSelfDone:(leftExit,current2)=>match6(leftExit,{onFailure:(cause3)=>interrupt6(current2).pipe(as3(failCause10(cause3))),onSuccess:(chunk3)=>interrupt6(current2).pipe(zipRight4(succeed9(write(chunk3).pipe(flatMap12(()=>consumer(current(handoffFiber)))))))}),onOtherDone:(rightExit,previous2)=>match6(rightExit,{onFailure:(cause3)=>interrupt6(previous2).pipe(as3(failCause10(cause3))),onSuccess:(signal)=>{switch(signal._tag){case OP_EMIT4:return interrupt6(previous2).pipe(zipRight4(enqueue(signal.elements)));case OP_HALT:return interrupt6(previous2).pipe(as3(failCause10(signal.cause)));case OP_END:return join3(previous2).pipe(map16((chunk3)=>write(chunk3).pipe(zipRight5(void_6))))}}})}))));case OP_CURRENT:return unwrap(join3(state.fiber).pipe(map16((signal)=>{switch(signal._tag){case OP_EMIT4:return unwrap(enqueue(signal.elements));case OP_HALT:return failCause10(signal.cause);case OP_END:return void_6}})))}}return scopedWith4((scope5)=>pipeTo(toChannel2(self),producer).pipe(runIn(scope5),forkIn2(scope5))).pipe(crossRight(new StreamImpl(consumer(notStarted))))}))),die9=(defect)=>fromEffect8(die5(defect)),dieSync5=(evaluate2)=>fromEffect8(dieSync2(evaluate2)),dieMessage4=(message)=>fromEffect8(dieMessage2(message)),distributedWith=dual(2,(self,options)=>pipe(make19(),flatMap10((deferred)=>pipe(self,distributedWithDynamic({maximumLag:options.maximumLag,decide:(a)=>flatMap10(_await(deferred),(f)=>f(a))}),flatMap10((next4)=>pipe(all7(map4(range(0,options.size-1),(id3)=>map16(next4,([key,queue])=>[[key,id3],queue]))),map16(unsafeFromArray),flatMap10((entries2)=>{let[mappings,queues]=reduceRight2(entries2,[new Map,empty5()],([mappings2,queues2],[mapping,queue])=>[mappings2.set(mapping[0],mapping[1]),pipe(queues2,prepend2(queue))]);return pipe(succeed2(deferred,(a)=>map16(options.decide(a),(f)=>(key)=>pipe(f(mappings.get(key))))),as3(Array.from(queues)))}))))))),distributedWithDynamicId={ref:0},newDistributedWithDynamicId=()=>{let current2=distributedWithDynamicId.ref;return distributedWithDynamicId.ref=current2+1,current2},distributedWithDynamic=dual(2,(self,options)=>distributedWithDynamicCallback(self,options.maximumLag,options.decide,()=>_void)),distributedWithDynamicCallback=dual(4,(self,maximumLag,decide,done12)=>pipe(acquireRelease2(make29(new Map),(ref,_)=>pipe(get12(ref),flatMap10((queues)=>pipe(queues.values(),forEach8(shutdown4))))),flatMap10((queuesRef)=>gen2(function*(){let offer6=(a)=>pipe(decide(a),flatMap10((shouldProcess)=>pipe(get12(queuesRef),flatMap10((queues)=>pipe(queues.entries(),reduce13(empty5(),(acc,[id3,queue])=>{if(shouldProcess(id3))return pipe(offer3(queue,succeed3(a)),matchCauseEffect3({onFailure:(cause3)=>isInterrupted2(cause3)?succeed9(pipe(acc,prepend2(id3))):failCause8(cause3),onSuccess:()=>succeed9(acc)}));return succeed9(acc)}),flatMap10((ids3)=>{if(isNonEmpty2(ids3))return pipe(update3(queuesRef,(map21)=>{for(let id3 of ids3)map21.delete(id3);return map21}));return _void}))))),asVoid2),queuesLock=yield*makeSemaphore2(1),newQueue=yield*make29(pipe(bounded5(maximumLag),flatMap10((queue)=>{let id3=newDistributedWithDynamicId();return pipe(update3(queuesRef,(map21)=>map21.set(id3,queue)),as3([id3,queue]))}))),finalize=(endTake)=>queuesLock.withPermits(1)(pipe(set6(newQueue,pipe(bounded5(1),tap2((queue)=>offer3(queue,endTake)),flatMap10((queue)=>{let id3=newDistributedWithDynamicId();return pipe(update3(queuesRef,(map21)=>map21.set(id3,queue)),as3(make3(id3,queue)))}))),zipRight4(pipe(get12(queuesRef),flatMap10((map21)=>pipe(fromIterable2(map21.values()),forEach8((queue)=>pipe(offer3(queue,endTake),catchSomeCause2((cause3)=>isInterrupted2(cause3)?some2(_void):none2()))))))),zipRight4(done12(endTake)),asVoid2));return yield*pipe(self,runForEachScoped(offer6),matchCauseEffect3({onFailure:(cause3)=>finalize(failCause3(pipe(cause3,map13(some2)))),onSuccess:()=>finalize(fail4(none2()))}),forkScoped2),queuesLock.withPermits(1)(flatten8(get12(newQueue)))})))),drain3=(self)=>new StreamImpl(drain(toChannel2(self))),drainFork=dual(2,(self,that)=>fromEffect8(make19()).pipe(flatMap15((backgroundDied)=>scopedWith4((scope4)=>toChannel2(that).pipe(drain,runIn(scope4),catchAllCause2((cause3)=>failCause2(backgroundDied,cause3)),forkIn2(scope4))).pipe(crossRight(interruptWhenDeferred2(self,backgroundDied)))))),drop3=dual(2,(self,n)=>{let loop3=(r)=>readWith({onInput:(input)=>{let dropped=pipe(input,drop2(r)),leftover=Math.max(0,r-input.length);if(isEmpty(input)||leftover>0)return loop3(leftover);return pipe(write(dropped),zipRight5(identityChannel()))},onFailure:fail11,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3(n))))}),dropRight=dual(2,(self,n)=>{if(n<=0)return identityStream();return suspend8(()=>{let queue=new RingBuffer(n),reader=readWith({onInput:(input)=>{let outputs=pipe(input,filterMap2((elem)=>{let head6=queue.head();return queue.put(elem),head6}));return pipe(write(outputs),flatMap12(()=>reader))},onFailure:fail11,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(reader)))})}),dropUntil3=dual(2,(self,predicate)=>drop3(dropWhile4(self,(a)=>!predicate(a)),1)),dropUntilEffect=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>pipe(dropUntil2(input,predicate),map16(unsafeFromArray),map16((leftover)=>{if(isEmpty(leftover))return suspend4(()=>loop3);return pipe(write(leftover),zipRight5(identityChannel()))}),unwrap),onFailure:fail11,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),dropWhile4=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>{let output=dropWhile(input,predicate);if(isEmpty(output))return suspend4(()=>loop3);return zipRight5(write(output),identityChannel())},onFailure:fail11,onDone:succeedNow});return new StreamImpl(pipeToOrFail(toChannel2(self),loop3))}),dropWhileEffect=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>pipe(dropWhile3(input,predicate),map16(unsafeFromArray),map16((leftover)=>{if(isEmpty(leftover))return suspend4(()=>loop3);return zipRight5(write(leftover),identityChannel())}),unwrap),onFailure:fail11,onDone:()=>void_6});return new StreamImpl(pipeToOrFail(toChannel2(self),loop3))}),either5=(self)=>pipe(self,map21(right2),catchAll6((error)=>make53(left2(error)))),empty34=new StreamImpl(void_6),ensuring6=dual(2,(self,finalizer)=>new StreamImpl(pipe(toChannel2(self),ensuring3(finalizer)))),ensuringWith2=dual(2,(self,finalizer)=>new StreamImpl(ensuringWith(toChannel2(self),finalizer))),context5=()=>fromEffect8(context3()),contextWith3=(f)=>pipe(context5(),map21(f)),contextWithEffect3=(f)=>pipe(context5(),mapEffectSequential(f)),contextWithStream=(f)=>pipe(context5(),flatMap15(f)),execute=(effect3)=>drain3(fromEffect8(effect3)),fail15=(error)=>fromEffectOption(fail9(some2(error))),failSync6=(evaluate2)=>fromEffectOption(failSync2(()=>some2(evaluate2()))),failCause13=(cause3)=>fromEffect8(failCause8(cause3)),failCauseSync5=(evaluate2)=>fromEffect8(failCauseSync2(evaluate2)),filter9=dual(2,(self,predicate)=>mapChunks(self,filter3(predicate))),filterEffect=dual(2,(self,f)=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(input)=>loop3(input[Symbol.iterator]()),onFailure:failCause10,onDone:succeed10});else return pipe(f(next4.value),map16((bool)=>bool?pipe(write(of2(next4.value)),flatMap12(()=>loop3(iterator))):loop3(iterator)),unwrap)};return new StreamImpl(suspend4(()=>pipe(toChannel2(self),pipeTo(loop3(empty5()[Symbol.iterator]())))))}),filterMap6=dual(2,(self,pf)=>mapChunks(self,filterMap2(pf))),filterMapEffect=dual(2,(self,pf)=>suspend8(()=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(input)=>loop3(input[Symbol.iterator]()),onFailure:failCause10,onDone:succeed10});else return pipe(pf(next4.value),match2({onNone:()=>sync3(()=>loop3(iterator)),onSome:map16((a2)=>flatMap12(write(of2(a2)),()=>loop3(iterator)))}),unwrap)};return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3(empty5()[Symbol.iterator]()))))})),filterMapWhile3=dual(2,(self,pf)=>{let loop3=readWith({onInput:(input)=>{let mapped=filterMapWhile2(input,pf);if(mapped.length===input.length)return pipe(write(mapped),flatMap12(()=>loop3));return write(mapped)},onFailure:fail11,onDone:succeed10});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),filterMapWhileEffect=dual(2,(self,pf)=>suspend8(()=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(input)=>loop3(input[Symbol.iterator]()),onFailure:failCause10,onDone:succeed10});else return unwrap(match2(pf(next4.value),{onNone:()=>succeed9(void_6),onSome:map16((a2)=>flatMap12(write(of2(a2)),()=>loop3(iterator)))}))};return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3(empty5()[Symbol.iterator]()))))})),finalizer=(finalizer2)=>acquireRelease3(_void,()=>finalizer2),find2=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>match2(findFirst3(input,predicate),{onNone:()=>loop3,onSome:(n)=>write(of2(n))}),onFailure:fail11,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3)))}),findEffect=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>pipe(findFirst7(input,predicate),map16(match2({onNone:()=>loop3,onSome:(n)=>write(of2(n))})),unwrap),onFailure:fail11,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3)))}),flatMap15=dual((args2)=>isStream(args2[0]),(self,f,options)=>{let bufferSize=options?.bufferSize??16;if(options?.switch)return matchConcurrency(options?.concurrency,()=>flatMapParSwitchBuffer(self,1,bufferSize,f),(n)=>flatMapParSwitchBuffer(self,n,bufferSize,f));return matchConcurrency(options?.concurrency,()=>new StreamImpl(concatMap(toChannel2(self),(as8)=>pipe(as8,map4((a)=>toChannel2(f(a))),reduce3(void_6,(left3,right3)=>pipe(left3,zipRight5(right3)))))),(_)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mergeMap((out)=>toChannel2(f(out)),options))))}),matchConcurrency=(concurrency,sequential4,bounded8)=>{switch(concurrency){case void 0:return sequential4();case"unbounded":return bounded8(Number.MAX_SAFE_INTEGER);default:return concurrency>1?bounded8(concurrency):sequential4()}},flatMapParSwitchBuffer=dual(4,(self,n,bufferSize,f)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mergeMap((out)=>toChannel2(f(out)),{concurrency:n,mergeStrategy:BufferSliding(),bufferSize})))),flatten12=dual((args2)=>isStream(args2[0]),(self,options)=>flatMap15(self,identity,options)),flattenChunks=(self)=>{let flatten13=readWithCause({onInput:(chunks2)=>flatMap12(writeChunk(chunks2),()=>flatten13),onFailure:failCause10,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeTo(flatten13)))},flattenEffect=dual((args2)=>isStream(args2[0]),(self,options)=>options?.unordered?flatMap15(self,(a)=>fromEffect8(a),{concurrency:options.concurrency}):matchConcurrency(options?.concurrency,()=>mapEffectSequential(self,identity),(n)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mapOutEffectPar(identity,n),mapOut(of2))))),flattenExitOption=(self)=>{let processChunk=(chunk3,cont)=>{let[toEmit,rest]=pipe(chunk3,splitWhere((exit3)=>!isSuccess(exit3))),next4=pipe(head2(rest),match2({onNone:()=>cont,onSome:match6({onFailure:(cause3)=>match2(flipCauseOption2(cause3),{onNone:()=>void_6,onSome:failCause10}),onSuccess:()=>void_6})}));return pipe(write(pipe(toEmit,filterMap2((exit3)=>isSuccess(exit3)?some2(exit3.value):none2()))),flatMap12(()=>next4))},process2=readWithCause({onInput:(chunk3)=>processChunk(chunk3,process2),onFailure:(cause3)=>failCause10(cause3),onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeTo(process2)))},flattenIterables=(self)=>pipe(self,map21(fromIterable2),flattenChunks),flattenTake=(self)=>flattenChunks(flattenExitOption(pipe(self,map21((take7)=>take7.exit)))),forever5=(self)=>new StreamImpl(repeated(toChannel2(self))),fromAsyncIterable=(iterable,onError3)=>pipe(acquireRelease2(sync3(()=>iterable[Symbol.asyncIterator]()),(iterator)=>iterator.return?promise2(async()=>iterator.return()):_void),map16((iterator)=>repeatEffectOption(pipe(tryPromise2({try:async()=>iterator.next(),catch:(reason)=>some2(onError3(reason))}),flatMap10((result)=>result.done?fail9(none2()):succeed9(result.value))))),unwrapScoped3),fromChannel2=(channel)=>new StreamImpl(channel),toChannel2=(stream)=>{if("channel"in stream)return stream.channel;else if(isEffect2(stream))return toChannel2(fromEffect8(stream));else throw new TypeError("Expected a Stream.")},fromChunk=(chunk3)=>new StreamImpl(isEmpty(chunk3)?void_6:write(chunk3)),fromChunkPubSub=(pubsub,options)=>{if(options?.scoped){let effect3=map16(subscribe2(pubsub),fromChunkQueue);return options.shutdown?map16(effect3,ensuring6(shutdown3(pubsub))):effect3}let stream=flatMap15(scoped5(subscribe2(pubsub)),fromChunkQueue);return options?.shutdown?ensuring6(stream,shutdown3(pubsub)):stream},fromChunkQueue=(queue,options)=>pipe(take3(queue),catchAllCause2((cause3)=>pipe(isShutdown3(queue),flatMap10((isShutdown7)=>isShutdown7&&isInterrupted2(cause3)?end5():failCause12(cause3)))),repeatEffectChunkOption,options?.shutdown?ensuring6(shutdown4(queue)):identity),fromChunks=(...chunks2)=>pipe(fromIterable11(chunks2),flatMap15(fromChunk)),fromEffect8=(effect3)=>pipe(effect3,mapError2(some2),fromEffectOption),fromEffectOption=(effect3)=>new StreamImpl(unwrap(match13(effect3,{onFailure:match2({onNone:()=>void_6,onSome:fail11}),onSuccess:(a)=>write(of2(a))}))),fromPubSub=(pubsub,options)=>{let maxChunkSize=options?.maxChunkSize??DefaultChunkSize;if(options?.scoped){let effect3=map16(subscribe2(pubsub),(queue)=>fromQueue2(queue,{maxChunkSize,shutdown:!0}));return options.shutdown?map16(effect3,ensuring6(shutdown3(pubsub))):effect3}let stream=flatMap15(scoped5(subscribe2(pubsub)),(queue)=>fromQueue2(queue,{maxChunkSize}));return options?.shutdown?ensuring6(stream,shutdown3(pubsub)):stream},fromTPubSub=(pubsub)=>{return unwrapScoped3(map16(subscribeScoped2(pubsub),(queue)=>fromTQueue(queue)))},fromIterable11=(iterable)=>suspend8(()=>isChunk(iterable)?fromChunk(iterable):fromIteratorSucceed(iterable[Symbol.iterator]())),fromIterableEffect=(effect3)=>pipe(effect3,map16(fromIterable11),unwrap2),fromIteratorSucceed=(iterator,maxChunkSize=DefaultChunkSize)=>{return pipe(sync3(()=>{let builder=[],loop3=(iterator2)=>pipe(sync3(()=>{let next4=iterator2.next();if(maxChunkSize===1){if(next4.done)return void_6;return pipe(write(of2(next4.value)),flatMap12(()=>loop3(iterator2)))}builder=[];let count3=0;while(next4.done===!1){if(builder.push(next4.value),count3=count3+1,count3>=maxChunkSize)break;next4=iterator2.next()}if(count3>0)return pipe(write(unsafeFromArray(builder)),flatMap12(()=>loop3(iterator2)));return void_6}),unwrap);return new StreamImpl(loop3(iterator))}),unwrap2)},fromPull2=(effect3)=>pipe(effect3,map16(repeatEffectChunkOption),unwrapScoped3),fromQueue2=(queue,options)=>pipe(takeBetween2(queue,1,options?.maxChunkSize??DefaultChunkSize),catchAllCause2((cause3)=>pipe(isShutdown3(queue),flatMap10((isShutdown7)=>isShutdown7&&isInterrupted2(cause3)?end5():failCause12(cause3)))),repeatEffectChunkOption,options?.shutdown?ensuring6(shutdown4(queue)):identity),fromTQueue=(queue)=>pipe(take5(queue),map16(of2),catchAllCause2((cause3)=>pipe(isShutdown6(queue),flatMap10((isShutdown7)=>isShutdown7&&isInterrupted2(cause3)?end5():failCause12(cause3)))),repeatEffectChunkOption),fromSchedule=(schedule2)=>pipe(driver2(schedule2),map16((driver3)=>repeatEffectOption(driver3.next(void 0))),unwrap2),fromReadableStream=(...args2)=>{let evaluate2=args2.length===1?args2[0].evaluate:args2[0],onError3=args2.length===1?args2[0].onError:args2[1],releaseLockOnEnd=args2.length===1?args2[0].releaseLockOnEnd===!0:!1;return unwrapScoped3(map16(acquireRelease2(sync3(()=>evaluate2().getReader()),(reader)=>releaseLockOnEnd?sync3(()=>reader.releaseLock()):promise2(()=>reader.cancel())),(reader)=>repeatEffectOption(flatMap10(tryPromise2({try:()=>reader.read(),catch:(reason)=>some2(onError3(reason))}),({done:done12,value})=>done12?fail9(none2()):succeed9(value)))))},fromReadableStreamByob=(...args2)=>{let evaluate2=args2.length===1?args2[0].evaluate:args2[0],onError3=args2.length===1?args2[0].onError:args2[1],allocSize=(args2.length===1?args2[0].bufferSize:args2[2])??4096,releaseLockOnEnd=args2.length===1?args2[0].releaseLockOnEnd===!0:!1;return unwrapScoped3(map16(acquireRelease2(sync3(()=>evaluate2().getReader({mode:"byob"})),(reader)=>releaseLockOnEnd?sync3(()=>reader.releaseLock()):promise2(()=>reader.cancel())),(reader)=>catchAll6(forever5(readChunkStreamByobReader(reader,onError3,allocSize)),(error)=>error===EOF?empty34:fail15(error))))},EOF=Symbol.for("effect/Stream/EOF"),readChunkStreamByobReader=(reader,onError3,size16)=>{let buffer2=new ArrayBuffer(size16);return paginateEffect(0,(offset)=>flatMap10(tryPromise2({try:()=>reader.read(new Uint8Array(buffer2,offset,buffer2.byteLength-offset)),catch:(reason)=>onError3(reason)}),({done:done12,value})=>{if(done12)return fail9(EOF);let newOffset=offset+value.byteLength;return succeed9([value,newOffset>=buffer2.byteLength?none2():some2(newOffset)])}))},groupAdjacentBy=dual(2,(self,f)=>{let groupAdjacentByChunk=(state,chunk3)=>{if(isEmpty(chunk3))return[state,empty5()];let builder=[],from=0,until=0,key=void 0,previousChunk=empty5();switch(state._tag){case"Some":{let tuple3=state.value;key=tuple3[0];let loop3=!0;while(loop3&&until<chunk3.length){let input=unsafeGet4(chunk3,until),updatedKey=f(input);if(!equals(key,updatedKey)){let previousChunk2=tuple3[1],additionalChunk=unsafeFromArray(Array.from(chunk3).slice(from,until)),group=appendAll2(previousChunk2,additionalChunk);builder.push([key,group]),key=updatedKey,from=until,loop3=!1}until=until+1}if(loop3)previousChunk=tuple3[1];break}case"None":{key=f(unsafeGet4(chunk3,until)),until=until+1;break}}while(until<chunk3.length){let input=unsafeGet4(chunk3,until),updatedKey=f(input);if(!equals(key,updatedKey))builder.push([key,unsafeFromArray(Array.from(chunk3).slice(from,until))]),key=updatedKey,from=until;until=until+1}let nonEmptyChunk=appendAll2(previousChunk,unsafeFromArray(Array.from(chunk3).slice(from,until))),output=unsafeFromArray(builder);return[some2([key,nonEmptyChunk]),output]},groupAdjacent=(state)=>readWithCause({onInput:(input)=>{let[updatedState,output]=groupAdjacentByChunk(state,input);return isEmpty(output)?groupAdjacent(updatedState):flatMap12(write(output),()=>groupAdjacent(updatedState))},onFailure:(cause3)=>match2(state,{onNone:()=>failCause10(cause3),onSome:(output)=>flatMap12(write(of2(output)),()=>failCause10(cause3))}),onDone:(done12)=>match2(state,{onNone:()=>succeedNow(done12),onSome:(output)=>flatMap12(write(of2(output)),()=>succeedNow(done12))})});return new StreamImpl(pipeToOrFail(toChannel2(self),groupAdjacent(none2())))}),grouped=dual(2,(self,chunkSize)=>pipe(self,rechunk(chunkSize),chunks)),groupedWithin=dual(3,(self,chunkSize,duration2)=>aggregateWithin(self,collectAllN(chunkSize),spaced2(duration2))),haltWhen=dual(2,(self,effect3)=>{let writer=(fiber)=>pipe(poll4(fiber),map16(match2({onNone:()=>readWith({onInput:(input)=>flatMap12(write(input),()=>writer(fiber)),onFailure:fail11,onDone:()=>void_6}),onSome:match6({onFailure:failCause10,onSuccess:()=>void_6})})),unwrap);return new StreamImpl(unwrapScopedWith((scope4)=>effect3.pipe(forkIn2(scope4),map16((fiber)=>toChannel2(self).pipe(pipeTo(writer(fiber)))))))}),haltAfter=dual(2,(self,duration2)=>pipe(self,haltWhen(sleep2(duration2)))),haltWhenDeferred=dual(2,(self,deferred)=>{let writer=pipe(poll(deferred),map16(match2({onNone:()=>readWith({onInput:(input)=>pipe(write(input),flatMap12(()=>writer)),onFailure:fail11,onDone:()=>void_6}),onSome:(effect3)=>unwrap(match13(effect3,{onFailure:fail11,onSuccess:()=>void_6}))})),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeTo(writer)))}),identityStream=()=>new StreamImpl(identityChannel()),interleave=dual(2,(self,that)=>pipe(self,interleaveWith(that,forever5(make53(!0,!1))))),interleaveWith=dual(3,(self,that,decider)=>{let producer=(handoff)=>readWithCause({onInput:(value)=>flatMap12(fromEffect5(offer5(handoff,of5(value))),()=>producer(handoff)),onFailure:(cause3)=>fromEffect5(offer5(handoff,failCause11(cause3))),onDone:()=>fromEffect5(offer5(handoff,end4))});return new StreamImpl(unwrapScopedWith((scope4)=>pipe(make52(),zip6(make52()),tap2(([left3])=>toChannel2(self).pipe(concatMap(writeChunk),pipeTo(producer(left3)),runIn(scope4),forkIn2(scope4))),tap2(([_,right3])=>toChannel2(that).pipe(concatMap(writeChunk),pipeTo(producer(right3)),runIn(scope4),forkIn2(scope4))),map16(([left3,right3])=>{let process2=(leftDone,rightDone)=>readWithCause({onInput:(bool)=>{if(bool&&!leftDone)return pipe(fromEffect5(take6(left3)),flatMap12(match18({onEnd:()=>rightDone?void_6:process2(!0,rightDone),onFailure:failCause10,onSuccess:(chunk3)=>pipe(write(chunk3),flatMap12(()=>process2(leftDone,rightDone)))})));if(!bool&&!rightDone)return pipe(fromEffect5(take6(right3)),flatMap12(match18({onEnd:()=>leftDone?void_6:process2(leftDone,!0),onFailure:failCause10,onSuccess:(chunk3)=>pipe(write(chunk3),flatMap12(()=>process2(leftDone,rightDone)))})));return process2(leftDone,rightDone)},onFailure:failCause10,onDone:()=>void_6});return pipe(toChannel2(decider),concatMap(writeChunk),pipeTo(process2(!1,!1)))}))))}),intersperse=dual(2,(self,element)=>new StreamImpl(pipe(toChannel2(self),pipeToOrFail(suspend4(()=>{let writer=(isFirst)=>readWithCause({onInput:(chunk3)=>{let builder=[],flagResult=isFirst;for(let output of chunk3)if(flagResult)flagResult=!1,builder.push(output);else builder.push(element),builder.push(output);return pipe(write(unsafeFromArray(builder)),flatMap12(()=>writer(flagResult)))},onFailure:failCause10,onDone:()=>void_6});return writer(!0)}))))),intersperseAffixes=dual(2,(self,{end:end6,middle,start:start3})=>pipe(make53(start3),concat2(pipe(self,intersperse(middle))),concat2(make53(end6)))),interruptAfter=dual(2,(self,duration2)=>pipe(self,interruptWhen2(sleep2(duration2)))),interruptWhen2=dual(2,(self,effect3)=>new StreamImpl(pipe(toChannel2(self),interruptWhen(effect3)))),interruptWhenDeferred2=dual(2,(self,deferred)=>new StreamImpl(pipe(toChannel2(self),interruptWhenDeferred(deferred)))),iterate3=(value,next4)=>unfold3(value,(a)=>some2([a,next4(a)])),make53=(...as8)=>fromIterable11(as8),map21=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapOut(map4(f))))),mapAccum5=dual(3,(self,s,f)=>{let accumulator=(s2)=>readWith({onInput:(input)=>{let[nextS,chunk3]=mapAccum2(input,s2,f);return flatMap12(write(chunk3),()=>accumulator(nextS))},onFailure:fail11,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeTo(accumulator(s))))}),mapAccumEffect=dual(3,(self,s,f)=>suspend8(()=>{let accumulator=(s2)=>readWith({onInput:(input)=>pipe(suspend3(()=>{let outputs=[],emit2=(output)=>sync3(()=>{outputs.push(output)});return pipe(input,reduce13(s2,(s3,a)=>pipe(f(s3,a),flatMap10(([s4,a2])=>pipe(emit2(a2),as3(s4))))),match13({onFailure:(error)=>{if(outputs.length!==0)return zipRight5(write(unsafeFromArray(outputs)),fail11(error));return fail11(error)},onSuccess:(s3)=>flatMap12(write(unsafeFromArray(outputs)),()=>accumulator(s3))}))}),unwrap),onFailure:fail11,onDone:()=>void_6});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(accumulator(s))))})),mapBoth5=dual(2,(self,options)=>pipe(self,mapError5(options.onFailure),map21(options.onSuccess))),mapChunks=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapOut(f)))),mapChunksEffect=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapOutEffect(f)))),mapConcat=dual(2,(self,f)=>pipe(self,mapConcatChunk((a)=>fromIterable2(f(a))))),mapConcatChunk=dual(2,(self,f)=>pipe(self,mapChunks(flatMap3(f)))),mapConcatChunkEffect=dual(2,(self,f)=>pipe(self,mapEffectSequential(f),mapConcatChunk(identity))),mapConcatEffect=dual(2,(self,f)=>pipe(self,mapEffectSequential((a)=>pipe(f(a),map16(fromIterable2))),mapConcatChunk(identity))),mapEffectSequential=dual(2,(self,f)=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(elem)=>loop3(elem[Symbol.iterator]()),onFailure:failCause10,onDone:succeed10});else{let value=next4.value;return unwrap(map16(f(value),(a2)=>flatMap12(write(of2(a2)),()=>loop3(iterator))))}};return new StreamImpl(pipe(toChannel2(self),pipeTo(suspend4(()=>loop3(empty5()[Symbol.iterator]())))))}),mapEffectPar=dual(3,(self,n,f)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mapOutEffectPar(f,n),mapOut(of2)))),mapError5=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapError4(f)))),mapErrorCause4=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapErrorCause3(f)))),merge9=dual((args2)=>isStream(args2[1]),(self,that,options)=>mergeWith3(self,that,{onSelf:identity,onOther:identity,haltStrategy:options?.haltStrategy})),mergeAll6=dual((args2)=>(Symbol.iterator in args2[0]),(streams,options)=>flatten12(fromIterable11(streams),options)),mergeWithTag=dual(2,(streams,options)=>{let values3=Object.keys(streams).map((key)=>streams[key].pipe(map21((value)=>({_tag:key,value}))));return mergeAll6(values3,options)}),mergeEither=dual(2,(self,that)=>mergeWith3(self,that,{onSelf:left2,onOther:right2})),mergeLeft=dual(2,(left3,right3)=>pipe(left3,merge9(drain3(right3)))),mergeRight=dual(2,(left3,right3)=>pipe(drain3(left3),merge9(right3))),mergeWith3=dual(3,(self,other,options)=>{let strategy=options.haltStrategy?fromInput2(options.haltStrategy):Both2,handler=(terminate)=>(exit3)=>terminate||!isSuccess(exit3)?Done4(suspend3(()=>exit3)):Await2((exit4)=>suspend3(()=>exit4));return new StreamImpl(mergeWith2(toChannel2(map21(self,options.onSelf)),{other:toChannel2(map21(other,options.onOther)),onSelfDone:handler(strategy._tag==="Either"||strategy._tag==="Left"),onOtherDone:handler(strategy._tag==="Either"||strategy._tag==="Right")}))}),mkString2=(self)=>run3(self,mkString),never5=fromEffect8(never4),onEnd=dual(2,(self,effect3)=>concat2(self,drain3(fromEffect8(effect3)))),onError3=dual(2,(self,cleanup)=>pipe(self,catchAllCause5((cause3)=>fromEffect8(pipe(cleanup(cause3),zipRight4(failCause8(cause3))))))),onDone=dual(2,(self,cleanup)=>new StreamImpl(pipe(toChannel2(self),ensuringWith((exit3)=>isSuccess(exit3)?cleanup():_void)))),onStart=dual(2,(self,effect3)=>unwrap2(as3(effect3,self))),orDie4=(self)=>pipe(self,orDieWith4(identity)),orDieWith4=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),orDieWith3(f)))),orElse8=dual(2,(self,that)=>new StreamImpl(pipe(toChannel2(self),orElse7(()=>toChannel2(that()))))),orElseEither4=dual(2,(self,that)=>pipe(self,map21(left2),orElse8(()=>pipe(that(),map21(right2))))),orElseFail3=dual(2,(self,error)=>pipe(self,orElse8(()=>failSync6(error)))),orElseIfEmpty=dual(2,(self,element)=>pipe(self,orElseIfEmptyChunk(()=>of2(element())))),orElseIfEmptyChunk=dual(2,(self,chunk3)=>pipe(self,orElseIfEmptyStream(()=>new StreamImpl(write(chunk3()))))),orElseIfEmptyStream=dual(2,(self,stream)=>{let writer=readWith({onInput:(input)=>{if(isEmpty(input))return suspend4(()=>writer);return pipe(write(input),zipRight5(identityChannel()))},onFailure:fail11,onDone:()=>suspend4(()=>toChannel2(stream()))});return new StreamImpl(pipe(toChannel2(self),pipeTo(writer)))}),orElseSucceed3=dual(2,(self,value)=>pipe(self,orElse8(()=>sync7(value)))),paginate=(s,f)=>paginateChunk(s,(s2)=>{let page=f(s2);return[of2(page[0]),page[1]]}),paginateChunk=(s,f)=>{let loop3=(s2)=>{let page=f(s2);return match2(page[1],{onNone:()=>zipRight5(write(page[0]),void_6),onSome:(s3)=>flatMap12(write(page[0]),()=>loop3(s3))})};return new StreamImpl(suspend4(()=>loop3(s)))},paginateChunkEffect=(s,f)=>{let loop3=(s2)=>unwrap(map16(f(s2),([chunk3,option3])=>match2(option3,{onNone:()=>zipRight5(write(chunk3),void_6),onSome:(s3)=>flatMap12(write(chunk3),()=>loop3(s3))})));return new StreamImpl(suspend4(()=>loop3(s)))},paginateEffect=(s,f)=>paginateChunkEffect(s,(s2)=>pipe(f(s2),map16(([a,s3])=>[of2(a),s3]))),peel=dual(2,(self,sink)=>{return pipe(make19(),flatMap10((deferred)=>pipe(make52(),map16((handoff)=>{let consumer=foldSink(collectLeftover(sink),{onFailure:(error)=>zipRight6(fromEffect7(fail3(deferred,error)),fail12(error)),onSuccess:([z,leftovers])=>{let loop3=readWithCause({onInput:(elements)=>flatMap12(fromEffect5(offer5(handoff,{_tag:"Emit",elements})),()=>loop3),onFailure:(cause3)=>zipRight5(fromEffect5(offer5(handoff,{_tag:"Halt",cause:cause3})),failCause10(cause3)),onDone:(_)=>zipRight5(fromEffect5(offer5(handoff,{_tag:"End"})),void_6)});return fromChannel(pipe(fromEffect5(succeed2(deferred,z)),zipRight5(fromEffect5(pipe(handoff,offer5({_tag:"Emit",elements:leftovers})))),zipRight5(loop3)))}}),producer=pipe(take6(handoff),map16((signal)=>{switch(signal._tag){case"Emit":return pipe(write(signal.elements),flatMap12(()=>producer));case"Halt":return failCause10(signal.cause);case"End":return void_6}}),unwrap);return pipe(self,tapErrorCause4((cause3)=>failCause2(deferred,cause3)),run3(consumer),forkScoped2,zipRight4(_await(deferred)),map16((z)=>[z,new StreamImpl(producer)]))}))),flatten8)}),partition5=dual((args2)=>typeof args2[1]==="function",(self,predicate,options)=>partitionEither(self,(a)=>succeed9(predicate(a)?right2(a):left2(a)),options)),partitionEither=dual((args2)=>typeof args2[1]==="function",(self,predicate,options)=>pipe(mapEffectSequential(self,predicate),distributedWith({size:2,maximumLag:options?.bufferSize??16,decide:match({onLeft:()=>succeed9((n)=>n===0),onRight:()=>succeed9((n)=>n===1)})}),flatMap10(([queue1,queue2])=>succeed9([filterMap6(flattenExitOption(fromQueue2(queue1,{shutdown:!0})),(_)=>match(_,{onLeft:some2,onRight:none2})),filterMap6(flattenExitOption(fromQueue2(queue2,{shutdown:!0})),(_)=>match(_,{onLeft:none2,onRight:some2}))])))),pipeThrough=dual(2,(self,sink)=>new StreamImpl(pipe(toChannel2(self),pipeToOrFail(toChannel(sink))))),pipeThroughChannel=dual(2,(self,channel)=>new StreamImpl(pipeTo(toChannel2(self),channel))),pipeThroughChannelOrFail=dual(2,(self,chan)=>new StreamImpl(pipe(toChannel2(self),pipeToOrFail(chan)))),prepend4=dual(2,(self,values3)=>new StreamImpl(zipRight5(write(values3),toChannel2(self)))),provideContext5=dual(2,(self,context6)=>new StreamImpl(pipe(toChannel2(self),provideContext3(context6)))),provideLayer=dual(2,(self,layer)=>new StreamImpl(unwrapScopedWith((scope4)=>buildWithScope2(layer,scope4).pipe(map16((env)=>pipe(toChannel2(self),provideContext3(env))))))),provideService5=dual(3,(self,tag,resource)=>provideServiceEffect3(self,tag,succeed9(resource))),provideServiceEffect3=dual(3,(self,tag,effect3)=>provideServiceStream(self,tag,fromEffect8(effect3))),provideServiceStream=dual(3,(self,tag,stream)=>contextWithStream((env)=>flatMap15(stream,(service2)=>pipe(self,provideContext5(add2(env,tag,service2)))))),mapInputContext5=dual(2,(self,f)=>contextWithStream((env)=>pipe(self,provideContext5(f(env))))),provideSomeLayer2=dual(2,(self,layer)=>pipe(self,provideLayer(pipe(context4(),merge8(layer))))),range2=(min4,max6,chunkSize=DefaultChunkSize)=>suspend8(()=>{if(min4>max6)return empty34;let go=(min5,max7,chunkSize2)=>{let remaining=max7-min5+1;if(remaining>chunkSize2)return pipe(write(range(min5,min5+chunkSize2-1)),flatMap12(()=>go(min5+chunkSize2,max7,chunkSize2)));return write(range(min5,min5+remaining-1))};return new StreamImpl(go(min4,max6,chunkSize))}),race3=dual(2,(left3,right3)=>raceAll3(left3,right3)),raceAll3=(...streams)=>make19().pipe(map16((halt2)=>{let winner=null;return mergeAll6(streams.map((stream,index)=>stream.pipe(takeWhile4(()=>{if(winner===null)return winner=index,unsafeDone(halt2,void_2),!0;return winner===index}),interruptWhen2(_await(halt2).pipe(flatMap10(()=>winner===index?never4:_void))))),{concurrency:streams.length})}),unwrap2),rechunk=dual(2,(self,n)=>suspend8(()=>{let target=Math.max(n,1),process2=rechunkProcess(new StreamRechunker(target),target);return new StreamImpl(pipe(toChannel2(self),pipeTo(process2)))})),rechunkProcess=(rechunker,target)=>readWithCause({onInput:(chunk3)=>{if(chunk3.length===target&&rechunker.isEmpty())return flatMap12(write(chunk3),()=>rechunkProcess(rechunker,target));if(chunk3.length>0){let chunks2=[],result=void 0,index=0;while(index<chunk3.length){while(index<chunk3.length&&result===void 0)result=rechunker.write(pipe(chunk3,unsafeGet4(index))),index=index+1;if(result!==void 0)chunks2.push(result),result=void 0}return flatMap12(writeAll(...chunks2),()=>rechunkProcess(rechunker,target))}return suspend4(()=>rechunkProcess(rechunker,target))},onFailure:(cause3)=>zipRight5(rechunker.emitIfNotEmpty(),failCause10(cause3)),onDone:()=>rechunker.emitIfNotEmpty()});class StreamRechunker{n;builder=[];pos=0;constructor(n){this.n=n}isEmpty(){return this.pos===0}write(elem){if(this.builder.push(elem),this.pos+=1,this.pos===this.n){let result=unsafeFromArray(this.builder);return this.builder=[],this.pos=0,result}return}emitIfNotEmpty(){if(this.pos!==0)return write(unsafeFromArray(this.builder));return void_6}}var refineOrDie=dual(2,(self,pf)=>pipe(self,refineOrDieWith(pf,identity))),refineOrDieWith=dual(3,(self,pf,f)=>new StreamImpl(catchAll4(toChannel2(self),(error)=>match2(pf(error),{onNone:()=>failCause10(die4(f(error))),onSome:fail11})))),repeat2=dual(2,(self,schedule2)=>filterMap6(repeatEither(self,schedule2),(_)=>match(_,{onLeft:none2,onRight:some2}))),repeatEffect=(effect3)=>repeatEffectOption(pipe(effect3,mapError2(some2))),repeatEffectChunk=(effect3)=>repeatEffectChunkOption(pipe(effect3,mapError2(some2))),repeatEffectChunkOption=(effect3)=>unfoldChunkEffect(effect3,(effect4)=>pipe(map16(effect4,(chunk3)=>some2([chunk3,effect4])),catchAll2(match2({onNone:()=>succeed9(none2()),onSome:fail9})))),repeatEffectOption=(effect3)=>repeatEffectChunkOption(pipe(effect3,map16(of2))),repeatEither=dual(2,(self,schedule2)=>repeatWith(self,schedule2,{onElement:(a)=>right2(a),onSchedule:left2})),repeatElements=dual(2,(self,schedule2)=>filterMap6(repeatElementsWith(self,schedule2,{onElement:(a)=>some2(a),onSchedule:none2}),identity)),repeatElementsWith=dual(3,(self,schedule2,options)=>{let driver3=pipe(driver2(schedule2),map16((driver4)=>{let feed=(input)=>match2(head2(input),{onNone:()=>loop3,onSome:(a)=>zipRight5(write(of2(options.onElement(a))),step4(pipe(input,drop2(1)),a))}),step4=(input,a)=>{let advance=pipe(driver4.next(a),as3(pipe(write(of2(options.onElement(a))),flatMap12(()=>step4(input,a))))),reset=pipe(driver4.last,orDie2,flatMap10((b)=>pipe(driver4.reset,map16(()=>pipe(write(of2(options.onSchedule(b))),zipRight5(feed(input)))))));return pipe(advance,orElse5(()=>reset),unwrap)},loop3=readWith({onInput:feed,onFailure:fail11,onDone:()=>void_6});return loop3}),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeTo(driver3)))}),repeatValue=(value)=>new StreamImpl(repeated(write(of2(value)))),repeatWith=dual(3,(self,schedule2,options)=>{return pipe(driver2(schedule2),map16((driver3)=>{let scheduleOutput=pipe(driver3.last,orDie2,map16(options.onSchedule)),process2=pipe(self,map21(options.onElement),toChannel2),loop3=unwrap(match13(driver3.next(void 0),{onFailure:()=>void_6,onSuccess:()=>pipe(process2,zipRight5(pipe(scheduleOutput,map16((c)=>pipe(write(of2(c)),flatMap12(()=>loop3))),unwrap)))}));return new StreamImpl(pipe(process2,zipRight5(loop3)))}),unwrap2)}),repeatWithSchedule=(value,schedule2)=>repeatEffectWithSchedule(succeed9(value),schedule2),repeatEffectWithSchedule=(effect3,schedule2)=>flatMap15(fromEffect8(zip6(effect3,driver2(schedule2))),([a,driver3])=>concat2(succeed14(a),unfoldEffect(a,(s)=>matchEffect2(driver3.next(s),{onFailure:succeed9,onSuccess:()=>map16(effect3,(nextA)=>some2([nextA,nextA]))})))),retry5=dual(2,(self,schedule2)=>driver2(schedule2).pipe(map16((driver3)=>{let loop3=toChannel2(self).pipe(mapOutEffect((out)=>as3(driver3.reset,out)),catchAll4((error)=>driver3.next(error).pipe(match13({onFailure:()=>fail11(error),onSuccess:()=>loop3}),unwrap)));return loop3}),unwrap,fromChannel2)),run3=dual(2,(self,sink)=>toChannel2(self).pipe(pipeToOrFail(toChannel(sink)),runDrain)),runCollect=(self)=>run3(self,collectAll()),runCount=(self)=>run3(self,count),runDrain2=(self)=>run3(self,drain2),runFold=dual(3,(self,s,f)=>runFoldWhile(self,s,constTrue,f)),runFoldEffect=dual(3,(self,s,f)=>runFoldWhileEffect(self,s,constTrue,f)),runFoldScoped=dual(3,(self,s,f)=>pipe(self,runFoldWhileScoped(s,constTrue,f))),runFoldScopedEffect=dual(3,(self,s,f)=>pipe(self,runFoldWhileScopedEffect(s,constTrue,f))),runFoldWhile=dual(4,(self,s,cont,f)=>run3(self,fold(s,cont,f))),runFoldWhileEffect=dual(4,(self,s,cont,f)=>run3(self,foldEffect(s,cont,f))),runFoldWhileScoped=dual(4,(self,s,cont,f)=>pipe(self,runScoped2(fold(s,cont,f)))),runFoldWhileScopedEffect=dual(4,(self,s,cont,f)=>pipe(self,runScoped2(foldEffect(s,cont,f)))),runForEach=dual(2,(self,f)=>run3(self,forEach9(f))),runForEachChunk=dual(2,(self,f)=>run3(self,forEachChunk(f))),runForEachChunkScoped=dual(2,(self,f)=>pipe(self,runScoped2(forEachChunk(f)))),runForEachScoped=dual(2,(self,f)=>pipe(self,runScoped2(forEach9(f)))),runForEachWhile=dual(2,(self,f)=>run3(self,forEachWhile(f))),runForEachWhileScoped=dual(2,(self,f)=>pipe(self,runScoped2(forEachWhile(f)))),runHead=(self)=>run3(self,head5()),runIntoPubSub=dual(2,(self,pubsub)=>pipe(self,runIntoQueue(pubsub))),runIntoPubSubScoped=dual(2,(self,pubsub)=>pipe(self,runIntoQueueScoped(pubsub))),runIntoQueue=dual(2,(self,queue)=>pipe(self,runIntoQueueScoped(queue),scoped3)),runIntoQueueElementsScoped=dual(2,(self,queue)=>{let writer=readWithCause({onInput:(input)=>flatMap12(fromEffect5(offerAll3(queue,map4(input,succeed3))),()=>writer),onFailure:(cause3)=>fromEffect5(offer3(queue,failCause3(map13(cause3,some2)))),onDone:()=>fromEffect5(offer3(queue,fail4(none2())))});return pipe(pipeTo(toChannel2(self),writer),drain,runScoped,asVoid2)}),runIntoQueueScoped=dual(2,(self,queue)=>{let writer=readWithCause({onInput:(input)=>flatMap12(write(chunk2(input)),()=>writer),onFailure:(cause3)=>write(failCause11(cause3)),onDone:()=>write(end4)});return pipe(pipeTo(toChannel2(self),writer),mapOutEffect((take7)=>offer3(queue,take7)),drain,runScoped,asVoid2)}),runLast=(self)=>run3(self,last4()),runScoped2=dual(2,(self,sink)=>pipe(toChannel2(self),pipeToOrFail(toChannel(sink)),drain,runScoped)),runSum=(self)=>run3(self,sum2),scan=dual(3,(self,s,f)=>pipe(self,scanEffect(s,(s2,a)=>succeed9(f(s2,a))))),scanReduce=dual(2,(self,f)=>pipe(self,scanReduceEffect((a2,a)=>succeed9(f(a2,a))))),scanReduceEffect=dual(2,(self,f)=>pipe(self,mapAccumEffect(none2(),(option3,a)=>{switch(option3._tag){case"None":return succeed9([some2(a),a]);case"Some":return pipe(f(option3.value,a),map16((b)=>[some2(b),b]))}}))),schedule2=dual(2,(self,schedule3)=>filterMap6(scheduleWith(self,schedule3,{onElement:some2,onSchedule:none2}),identity)),scheduleWith=dual(3,(self,schedule3,options)=>{let loop3=(driver3,iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(chunk3)=>loop3(driver3,chunk3[Symbol.iterator]()),onFailure:failCause10,onDone:succeedNow});return unwrap(matchEffect2(driver3.next(next4.value),{onFailure:()=>pipe(driver3.last,orDie2,map16((b)=>pipe(write(make7(options.onElement(next4.value),options.onSchedule(b))),flatMap12(()=>loop3(driver3,iterator)))),zipLeft3(driver3.reset)),onSuccess:()=>succeed9(pipe(write(of2(options.onElement(next4.value))),flatMap12(()=>loop3(driver3,iterator))))}))};return new StreamImpl(pipe(fromEffect5(driver2(schedule3)),flatMap12((driver3)=>pipe(toChannel2(self),pipeTo(loop3(driver3,empty5()[Symbol.iterator]()))))))}),scanEffect=dual(3,(self,s,f)=>new StreamImpl(pipe(write(of2(s)),flatMap12(()=>toChannel2(pipe(self,mapAccumEffect(s,(s2,a)=>pipe(f(s2,a),map16((s3)=>[s3,s3]))))))))),scoped5=(effect3)=>new StreamImpl(ensuring3(scoped4(pipe(effect3,map16(of2))),_void)),scopedWith4=(f)=>new StreamImpl(scopedWith3((scope4)=>f(scope4).pipe(map16(of2)))),some5=(self)=>pipe(self,mapError5(some2),someOrFail(()=>none2())),someOrElse=dual(2,(self,fallback)=>pipe(self,map21(getOrElse(fallback)))),someOrFail=dual(2,(self,error)=>mapEffectSequential(self,match2({onNone:()=>failSync2(error),onSome:succeed9}))),sliding7=dual(2,(self,chunkSize)=>slidingSize(self,chunkSize,1)),slidingSize=dual(3,(self,chunkSize,stepSize)=>{if(chunkSize<=0||stepSize<=0)return die9(new IllegalArgumentException2("Invalid bounds - `chunkSize` and `stepSize` must be greater than zero"));return new StreamImpl(suspend4(()=>{let queue=new RingBuffer(chunkSize),emitOnStreamEnd=(queueSize,channelEnd)=>{if(queueSize<chunkSize){let items=queue.toChunk(),result2=isEmpty(items)?empty5():of2(items);return pipe(write(result2),flatMap12(()=>channelEnd))}let lastEmitIndex=queueSize-(queueSize-chunkSize)%stepSize;if(lastEmitIndex===queueSize)return channelEnd;let leftovers=queueSize-(lastEmitIndex-chunkSize+stepSize),lastItems=pipe(queue.toChunk(),takeRight(leftovers)),result=isEmpty(lastItems)?empty5():of2(lastItems);return pipe(write(result),flatMap12(()=>channelEnd))},reader=(queueSize)=>readWithCause({onInput:(input)=>flatMap12(write(filterMap2(input,(element,index)=>{queue.put(element);let currentIndex=queueSize+index+1;if(currentIndex<chunkSize||(currentIndex-chunkSize)%stepSize>0)return none2();return some2(queue.toChunk())})),()=>reader(queueSize+input.length)),onFailure:(cause3)=>emitOnStreamEnd(queueSize,failCause10(cause3)),onDone:()=>emitOnStreamEnd(queueSize,void_6)});return pipe(toChannel2(self),pipeTo(reader(0)))}))}),split=dual(2,(self,predicate)=>{let split2=(leftovers,input)=>{let[chunk3,remaining]=pipe(leftovers,appendAll2(input),splitWhere(predicate));if(isEmpty(chunk3)||isEmpty(remaining))return loop3(pipe(chunk3,appendAll2(pipe(remaining,drop2(1)))));return pipe(write(of2(chunk3)),flatMap12(()=>split2(empty5(),pipe(remaining,drop2(1)))))},loop3=(leftovers)=>readWith({onInput:(input)=>split2(leftovers,input),onFailure:fail11,onDone:()=>{if(isEmpty(leftovers))return void_6;if(isNone2(pipe(leftovers,findFirst3(predicate))))return zipRight5(write(of2(leftovers)),void_6);return zipRight5(split2(empty5(),leftovers),void_6)}});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3(empty5()))))}),splitOnChunk=dual(2,(self,delimiter)=>{let next4=(leftover,delimiterIndex)=>readWithCause({onInput:(inputChunk)=>{let buffer2,[carry,delimiterCursor]=pipe(inputChunk,reduce3([pipe(leftover,getOrElse(()=>empty5())),delimiterIndex],([carry2,delimiterCursor2],a)=>{let concatenated=pipe(carry2,append2(a));if(delimiterCursor2<delimiter.length&&equals(a,pipe(delimiter,unsafeGet4(delimiterCursor2)))){if(delimiterCursor2+1===delimiter.length){if(buffer2===void 0)buffer2=[];return buffer2.push(pipe(concatenated,take(concatenated.length-delimiter.length))),[empty5(),0]}return[concatenated,delimiterCursor2+1]}return[concatenated,equals(a,pipe(delimiter,unsafeGet4(0)))?1:0]})),output=buffer2===void 0?empty5():unsafeFromArray(buffer2);return flatMap12(write(output),()=>next4(isNonEmpty2(carry)?some2(carry):none2(),delimiterCursor))},onFailure:(cause3)=>match2(leftover,{onNone:()=>failCause10(cause3),onSome:(chunk3)=>zipRight5(write(of2(chunk3)),failCause10(cause3))}),onDone:(done12)=>match2(leftover,{onNone:()=>succeed10(done12),onSome:(chunk3)=>zipRight5(write(of2(chunk3)),succeed10(done12))})});return new StreamImpl(pipe(toChannel2(self),pipeTo(next4(none2(),0))))}),splitLines2=(self)=>pipeThroughChannel(self,splitLines()),succeed14=(value)=>fromChunk(of2(value)),sync7=(evaluate2)=>suspend8(()=>fromChunk(of2(evaluate2()))),suspend8=(stream)=>new StreamImpl(suspend4(()=>toChannel2(stream()))),take7=dual(2,(self,n)=>{if(!Number.isInteger(n))return die9(new IllegalArgumentException2(`${n} must be an integer`));let loop3=(n2)=>readWith({onInput:(input)=>{let taken=pipe(input,take(Math.min(n2,Number.POSITIVE_INFINITY))),leftover=Math.max(0,n2-taken.length);if(leftover>0)return pipe(write(taken),flatMap12(()=>loop3(leftover)));return write(taken)},onFailure:fail11,onDone:succeed10});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(0<n?loop3(n):void_6)))}),takeRight2=dual(2,(self,n)=>{if(n<=0)return empty34;return new StreamImpl(pipe(succeed9(new RingBuffer(n)),map16((queue)=>{let reader=readWith({onInput:(input)=>{for(let element of input)queue.put(element);return reader},onFailure:fail11,onDone:()=>pipe(write(queue.toChunk()),zipRight5(void_6))});return pipe(toChannel2(self),pipeTo(reader))}),unwrap))}),takeUntil3=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>{let taken=pipe(input,takeWhile((a)=>!predicate(a))),last5=pipe(input,drop2(taken.length),take(1));if(isEmpty(last5))return pipe(write(taken),flatMap12(()=>loop3));return write(pipe(taken,appendAll2(last5)))},onFailure:fail11,onDone:succeed10});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),takeUntilEffect=dual(2,(self,predicate)=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(elem)=>loop3(elem[Symbol.iterator]()),onFailure:failCause10,onDone:succeed10});return pipe(predicate(next4.value),map16((bool)=>bool?write(of2(next4.value)):pipe(write(of2(next4.value)),flatMap12(()=>loop3(iterator)))),unwrap)};return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3(empty5()[Symbol.iterator]()))))}),takeWhile4=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>{let taken=pipe(input,takeWhile(predicate));if(taken.length===input.length)return pipe(write(taken),flatMap12(()=>loop3));return write(taken)},onFailure:fail11,onDone:succeed10});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),tap5=dual(2,(self,f)=>mapEffectSequential(self,(a)=>as3(f(a),a))),tapBoth3=dual(2,(self,options)=>pipe(self,tapError4(options.onFailure),tap5(options.onSuccess))),tapError4=dual(2,(self,f)=>catchAll6(self,(error)=>fromEffect8(zipRight4(f(error),fail9(error))))),tapErrorCause4=dual(2,(self,f)=>{let loop3=readWithCause({onInput:(chunk3)=>flatMap12(write(chunk3),()=>loop3),onFailure:(cause3)=>fromEffect5(zipRight4(f(cause3),failCause8(cause3))),onDone:succeedNow});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3)))}),tapSink=dual(2,(self,sink)=>pipe(fromEffect8(all7([bounded5(1),make19()])),flatMap15(([queue,deferred])=>{let right3=flattenTake(fromQueue2(queue,{maxChunkSize:1})),loop3=readWithCause({onInput:(chunk3)=>pipe(fromEffect5(offer3(queue,chunk2(chunk3))),foldCauseChannel({onFailure:()=>flatMap12(write(chunk3),()=>identityChannel()),onSuccess:()=>flatMap12(write(chunk3),()=>loop3)})),onFailure:(cause3)=>pipe(fromEffect5(offer3(queue,failCause11(cause3))),foldCauseChannel({onFailure:()=>failCause10(cause3),onSuccess:()=>failCause10(cause3)})),onDone:()=>pipe(fromEffect5(offer3(queue,end4)),foldCauseChannel({onFailure:()=>void_6,onSuccess:()=>void_6}))});return pipe(new StreamImpl(pipe(pipeTo(toChannel2(self),loop3),ensuring3(zipRight4(forkDaemon2(offer3(queue,end4)),_await(deferred))))),merge9(execute(pipe(run3(right3,sink),ensuring2(zipRight4(shutdown4(queue),succeed2(deferred,void 0)))))))}))),throttle=dual(2,(self,options)=>throttleEffect(self,{...options,cost:(chunk3)=>succeed9(options.cost(chunk3))})),throttleEffect=dual(2,(self,options)=>{if(options.strategy==="enforce")return throttleEnforceEffect(self,options.cost,options.units,options.duration,options.burst??0);return throttleShapeEffect(self,options.cost,options.units,options.duration,options.burst??0)}),throttleEnforceEffect=(self,cost,units,duration2,burst)=>{let loop3=(tokens,timestampMillis)=>readWithCause({onInput:(input)=>pipe(cost(input),zip6(currentTimeMillis2),map16(([weight,currentTimeMillis3])=>{let cycles=(currentTimeMillis3-timestampMillis)/toMillis(duration2),sum3=tokens+cycles*units,max6=units+burst<0?Number.POSITIVE_INFINITY:units+burst,available=sum3<0?max6:Math.min(sum3,max6);if(weight<=available)return pipe(write(input),flatMap12(()=>loop3(available-weight,currentTimeMillis3)));return loop3(tokens,timestampMillis)}),unwrap),onFailure:failCause10,onDone:()=>void_6}),throttled=pipe(currentTimeMillis2,map16((currentTimeMillis3)=>loop3(units,currentTimeMillis3)),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(throttled)))},throttleShapeEffect=(self,costFn,units,duration2,burst)=>{let loop3=(tokens,timestampMillis)=>readWithCause({onInput:(input)=>pipe(costFn(input),zip6(currentTimeMillis2),map16(([weight,currentTimeMillis3])=>{let cycles=(currentTimeMillis3-timestampMillis)/toMillis(duration2),sum3=tokens+cycles*units,max6=units+burst<0?Number.POSITIVE_INFINITY:units+burst,remaining=(sum3<0?max6:Math.min(sum3,max6))-weight,waitCycles=remaining>=0?0:-remaining/units,delay3=millis(Math.max(0,waitCycles*toMillis(duration2)));if(greaterThan2(delay3,zero2))return pipe(fromEffect5(sleep2(delay3)),zipRight5(write(input)),flatMap12(()=>loop3(remaining,currentTimeMillis3)));return flatMap12(write(input),()=>loop3(remaining,currentTimeMillis3))}),unwrap),onFailure:failCause10,onDone:()=>void_6}),throttled=pipe(currentTimeMillis2,map16((currentTimeMillis3)=>loop3(units,currentTimeMillis3)),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(throttled)))},tick=(interval)=>repeatWithSchedule(void 0,spaced2(interval)),timeout3=dual(2,(self,duration2)=>pipe(toPull2(self),map16(timeoutFail2({onTimeout:()=>none2(),duration:duration2})),fromPull2)),timeoutFail3=dual(3,(self,error,duration2)=>pipe(self,timeoutTo3(duration2,failSync6(error)))),timeoutFailCause3=dual(3,(self,cause3,duration2)=>pipe(toPull2(self),map16(timeoutFailCause2({onTimeout:()=>map13(cause3(),some2),duration:duration2})),fromPull2)),timeoutTo3=dual(3,(self,duration2,that)=>{let StreamTimeout=new RuntimeException2("Stream Timeout");return pipe(self,timeoutFailCause3(()=>die4(StreamTimeout),duration2),catchSomeCause3((cause3)=>isDieType2(cause3)&&isRuntimeException2(cause3.defect)&&cause3.defect.message!==void 0&&cause3.defect.message==="Stream Timeout"?some2(that):none2()))}),pubsubFromOptions=(options)=>{if(typeof options==="number")return bounded4(options);else if(options.capacity==="unbounded")return unbounded4({replay:options.replay});switch(options.strategy){case"dropping":return dropping3(options);case"sliding":return sliding3(options);default:return bounded4(options)}},toPubSub2=dual(2,(self,capacity7)=>pipe(acquireRelease2(pubsubFromOptions(capacity7),(pubsub)=>shutdown3(pubsub)),tap2((pubsub)=>pipe(self,runIntoPubSubScoped(pubsub),forkScoped2)))),toPull2=(self)=>map16(toPull(toChannel2(self)),(pull)=>pipe(pull,mapError2(some2),flatMap10(match({onLeft:()=>fail9(none2()),onRight:succeed9})))),toQueue2=dual((args2)=>isStream(args2[0]),(self,options)=>tap2(acquireRelease2(options?.strategy==="unbounded"?unbounded5():options?.strategy==="dropping"?dropping4(options.capacity??2):options?.strategy==="sliding"?sliding4(options.capacity??2):bounded5(options?.capacity??2),(queue)=>shutdown4(queue)),(queue)=>forkScoped2(runIntoQueueScoped(self,queue)))),toQueueOfElements=dual((args2)=>isStream(args2[0]),(self,options)=>tap2(acquireRelease2(bounded5(options?.capacity??2),(queue)=>shutdown4(queue)),(queue)=>forkScoped2(runIntoQueueElementsScoped(self,queue)))),toReadableStream=dual((args2)=>isStream(args2[0]),(self,options)=>toReadableStreamRuntime(self,defaultRuntime2,options)),toReadableStreamEffect=dual((args2)=>isStream(args2[0]),(self,options)=>map16(runtime3(),(runtime4)=>toReadableStreamRuntime(self,runtime4,options))),toReadableStreamRuntime=dual((args2)=>isStream(args2[0]),(self,runtime4,options)=>{let runFork4=runFork3(runtime4),currentResolve=void 0,fiber=void 0,latch=unsafeMakeLatch2(!1);return new ReadableStream({start(controller){fiber=runFork4(runForEachChunk(self,(chunk3)=>latch.whenOpen(sync3(()=>{latch.unsafeClose();for(let item of chunk3)controller.enqueue(item);currentResolve(),currentResolve=void 0})))),fiber.addObserver((exit3)=>{if(exit3._tag==="Failure")controller.error(squash(exit3.cause));else controller.close()})},pull(){return new Promise((resolve)=>{currentResolve=resolve,runSync(latch.open)})},cancel(){if(!fiber)return;return runPromise(asVoid2(interrupt6(fiber)))}},options?.strategy)}),transduce=dual(2,(self,sink)=>{let newChannel=suspend4(()=>{let leftovers={ref:empty5()},upstreamDone={ref:!1},buffer2=suspend4(()=>{let leftover=leftovers.ref;if(isEmpty(leftover))return readWith({onInput:(input)=>pipe(write(input),flatMap12(()=>buffer2)),onFailure:fail11,onDone:succeedNow});return leftovers.ref=empty5(),pipe(writeChunk(leftover),flatMap12(()=>buffer2))}),concatAndGet=(chunk3)=>{let leftover=leftovers.ref,concatenated=appendAll2(leftover,filter3(chunk3,(chunk4)=>chunk4.length!==0));return leftovers.ref=concatenated,concatenated},upstreamMarker=readWith({onInput:(input)=>flatMap12(write(input),()=>upstreamMarker),onFailure:fail11,onDone:(done12)=>zipRight5(sync4(()=>{upstreamDone.ref=!0}),succeedNow(done12))}),transducer=pipe(sink,toChannel,collectElements,flatMap12(([leftover,z])=>pipe(succeed10([upstreamDone.ref,concatAndGet(leftover)]),flatMap12(([done12,newLeftovers])=>{let nextChannel=done12&&isEmpty(newLeftovers)?void_6:transducer;return pipe(write(of2(z)),flatMap12(()=>nextChannel))}))));return pipe(toChannel2(self),pipeTo(upstreamMarker),pipeTo(buffer2),pipeToOrFail(transducer))});return new StreamImpl(newChannel)}),unfold3=(s,f)=>unfoldChunk(s,(s2)=>pipe(f(s2),map2(([a,s3])=>[of2(a),s3]))),unfoldChunk=(s,f)=>{let loop3=(s2)=>match2(f(s2),{onNone:()=>void_6,onSome:([chunk3,s3])=>flatMap12(write(chunk3),()=>loop3(s3))});return new StreamImpl(suspend4(()=>loop3(s)))},unfoldChunkEffect=(s,f)=>suspend8(()=>{let loop3=(s2)=>unwrap(map16(f(s2),match2({onNone:()=>void_6,onSome:([chunk3,s3])=>flatMap12(write(chunk3),()=>loop3(s3))})));return new StreamImpl(loop3(s))}),unfoldEffect=(s,f)=>unfoldChunkEffect(s,(s2)=>pipe(f(s2),map16(map2(([a,s3])=>[of2(a),s3])))),void_8=succeed14(void 0);var unwrap2=(effect3)=>flatten12(fromEffect8(effect3)),unwrapScoped3=(effect3)=>flatten12(scoped5(effect3)),unwrapScopedWith3=(f)=>flatten12(scopedWith4((scope4)=>f(scope4))),updateService3=dual(3,(self,tag,f)=>pipe(self,mapInputContext5((context6)=>pipe(context6,add2(tag,f(pipe(context6,unsafeGet3(tag)))))))),when3=dual(2,(self,test)=>pipe(self,whenEffect3(sync3(test)))),whenCase=(evaluate2,pf)=>whenCaseEffect(pf)(sync3(evaluate2)),whenCaseEffect=dual(2,(self,pf)=>pipe(fromEffect8(self),flatMap15((a)=>pipe(pf(a),getOrElse(()=>empty34))))),whenEffect3=dual(2,(self,effect3)=>pipe(fromEffect8(effect3),flatMap15((bool)=>bool?self:empty34))),withSpan5=function(){let dataFirst=typeof arguments[0]!=="string",name=dataFirst?arguments[1]:arguments[0],options=addSpanStackTrace(dataFirst?arguments[2]:arguments[1]);if(dataFirst){let self=arguments[0];return new StreamImpl(withSpan4(toChannel2(self),name,options))}return(self)=>new StreamImpl(withSpan4(toChannel2(self),name,options))},zip8=dual(2,(self,that)=>pipe(self,zipWith12(that,(a,a2)=>[a,a2]))),zipFlatten=dual(2,(self,that)=>pipe(self,zipWith12(that,(a,a2)=>[...a,a2]))),zipAll=dual(2,(self,options)=>zipAllWith(self,{other:options.other,onSelf:(a)=>[a,options.defaultOther],onOther:(a2)=>[options.defaultSelf,a2],onBoth:(a,a2)=>[a,a2]})),zipAllLeft=dual(3,(self,other,defaultSelf)=>zipAllWith(self,{other,onSelf:identity,onOther:()=>defaultSelf,onBoth:(a)=>a})),zipAllRight=dual(3,(self,other,defaultRight)=>zipAllWith(self,{other,onSelf:()=>defaultRight,onOther:identity,onBoth:(_,a2)=>a2})),zipAllSortedByKey=dual(2,(self,options)=>zipAllSortedByKeyWith(self,{other:options.other,onSelf:(a)=>[a,options.defaultOther],onOther:(a2)=>[options.defaultSelf,a2],onBoth:(a,a2)=>[a,a2],order:options.order})),zipAllSortedByKeyLeft=dual(2,(self,options)=>zipAllSortedByKeyWith(self,{other:options.other,onSelf:identity,onOther:()=>options.defaultSelf,onBoth:(a)=>a,order:options.order})),zipAllSortedByKeyRight=dual(2,(self,options)=>zipAllSortedByKeyWith(self,{other:options.other,onSelf:()=>options.defaultOther,onOther:identity,onBoth:(_,a2)=>a2,order:options.order})),zipAllSortedByKeyWith=dual(2,(self,options)=>{let pull=(state,pullLeft,pullRight)=>{switch(state._tag){case OP_DRAIN_LEFT:return pipe(pullLeft,match13({onFailure:fail4,onSuccess:(leftChunk)=>succeed3([map4(leftChunk,([k,a])=>[k,options.onSelf(a)]),DrainLeft])}));case OP_DRAIN_RIGHT:return pipe(pullRight,match13({onFailure:fail4,onSuccess:(rightChunk)=>succeed3([map4(rightChunk,([k,a2])=>[k,options.onOther(a2)]),DrainRight])}));case OP_PULL_BOTH:return pipe(unsome(pullLeft),zip6(unsome(pullRight),{concurrent:!0}),matchEffect2({onFailure:(error)=>succeed9(fail4(some2(error))),onSuccess:([leftOption,rightOption])=>{if(isSome2(leftOption)&&isSome2(rightOption)){if(isEmpty(leftOption.value)&&isEmpty(rightOption.value))return pull(PullBoth,pullLeft,pullRight);if(isEmpty(leftOption.value))return pull(PullLeft(rightOption.value),pullLeft,pullRight);if(isEmpty(rightOption.value))return pull(PullRight(leftOption.value),pullLeft,pullRight);return succeed9(succeed3(merge10(leftOption.value,rightOption.value)))}if(isSome2(leftOption)&&isNone2(rightOption)){if(isEmpty(leftOption.value))return pull(DrainLeft,pullLeft,pullRight);return succeed9(succeed3([pipe(leftOption.value,map4(([k,a])=>[k,options.onSelf(a)])),DrainLeft]))}if(isNone2(leftOption)&&isSome2(rightOption)){if(isEmpty(rightOption.value))return pull(DrainRight,pullLeft,pullRight);return succeed9(succeed3([pipe(rightOption.value,map4(([k,a2])=>[k,options.onOther(a2)])),DrainRight]))}return succeed9(fail4(none2()))}}));case OP_PULL_LEFT:return matchEffect2(pullLeft,{onFailure:match2({onNone:()=>succeed9(succeed3([pipe(state.rightChunk,map4(([k,a2])=>[k,options.onOther(a2)])),DrainRight])),onSome:(error)=>succeed9(fail4(some2(error)))}),onSuccess:(leftChunk)=>isEmpty(leftChunk)?pull(PullLeft(state.rightChunk),pullLeft,pullRight):succeed9(succeed3(merge10(leftChunk,state.rightChunk)))});case OP_PULL_RIGHT:return matchEffect2(pullRight,{onFailure:match2({onNone:()=>succeed9(succeed3([map4(state.leftChunk,([k,a])=>[k,options.onSelf(a)]),DrainLeft])),onSome:(error)=>succeed9(fail4(some2(error)))}),onSuccess:(rightChunk)=>isEmpty(rightChunk)?pull(PullRight(state.leftChunk),pullLeft,pullRight):succeed9(succeed3(merge10(state.leftChunk,rightChunk)))})}},merge10=(leftChunk,rightChunk)=>{let hasNext=(chunk3,index)=>index<chunk3.length-1,builder=[],state=void 0,leftIndex=0,rightIndex=0,leftTuple=pipe(leftChunk,unsafeGet4(leftIndex)),rightTuple=pipe(rightChunk,unsafeGet4(rightIndex)),k1=leftTuple[0],a=leftTuple[1],k2=rightTuple[0],a2=rightTuple[1],loop3=!0;while(loop3){let compare=options.order(k1,k2);if(compare===0)if(builder.push([k1,options.onBoth(a,a2)]),hasNext(leftChunk,leftIndex)&&hasNext(rightChunk,rightIndex))leftIndex=leftIndex+1,rightIndex=rightIndex+1,leftTuple=pipe(leftChunk,unsafeGet4(leftIndex)),rightTuple=pipe(rightChunk,unsafeGet4(rightIndex)),k1=leftTuple[0],a=leftTuple[1],k2=rightTuple[0],a2=rightTuple[1];else if(hasNext(leftChunk,leftIndex))state=PullRight(pipe(leftChunk,drop2(leftIndex+1))),loop3=!1;else if(hasNext(rightChunk,rightIndex))state=PullLeft(pipe(rightChunk,drop2(rightIndex+1))),loop3=!1;else state=PullBoth,loop3=!1;else if(compare<0)if(builder.push([k1,options.onSelf(a)]),hasNext(leftChunk,leftIndex))leftIndex=leftIndex+1,leftTuple=pipe(leftChunk,unsafeGet4(leftIndex)),k1=leftTuple[0],a=leftTuple[1];else{let rightBuilder=[];rightBuilder.push(rightTuple);while(hasNext(rightChunk,rightIndex))rightIndex=rightIndex+1,rightTuple=pipe(rightChunk,unsafeGet4(rightIndex)),rightBuilder.push(rightTuple);state=PullLeft(unsafeFromArray(rightBuilder)),loop3=!1}else if(builder.push([k2,options.onOther(a2)]),hasNext(rightChunk,rightIndex))rightIndex=rightIndex+1,rightTuple=pipe(rightChunk,unsafeGet4(rightIndex)),k2=rightTuple[0],a2=rightTuple[1];else{let leftBuilder=[];leftBuilder.push(leftTuple);while(hasNext(leftChunk,leftIndex))leftIndex=leftIndex+1,leftTuple=pipe(leftChunk,unsafeGet4(leftIndex)),leftBuilder.push(leftTuple);state=PullRight(unsafeFromArray(leftBuilder)),loop3=!1}}return[unsafeFromArray(builder),state]};return combineChunks(self,options.other,PullBoth,pull)}),zipAllWith=dual(2,(self,options)=>{let pull=(state,pullLeft,pullRight)=>{switch(state._tag){case OP_DRAIN_LEFT:return matchEffect2(pullLeft,{onFailure:(error)=>succeed9(fail4(error)),onSuccess:(leftChunk)=>succeed9(succeed3([map4(leftChunk,options.onSelf),DrainLeft]))});case OP_DRAIN_RIGHT:return matchEffect2(pullRight,{onFailure:(error)=>succeed9(fail4(error)),onSuccess:(rightChunk)=>succeed9(succeed3([map4(rightChunk,options.onOther),DrainRight]))});case OP_PULL_BOTH:return pipe(unsome(pullLeft),zip6(unsome(pullRight),{concurrent:!0}),matchEffect2({onFailure:(error)=>succeed9(fail4(some2(error))),onSuccess:([leftOption,rightOption])=>{if(isSome2(leftOption)&&isSome2(rightOption)){if(isEmpty(leftOption.value)&&isEmpty(rightOption.value))return pull(PullBoth,pullLeft,pullRight);if(isEmpty(leftOption.value))return pull(PullLeft(rightOption.value),pullLeft,pullRight);if(isEmpty(rightOption.value))return pull(PullRight(leftOption.value),pullLeft,pullRight);return succeed9(succeed3(zip9(leftOption.value,rightOption.value,options.onBoth)))}if(isSome2(leftOption)&&isNone2(rightOption))return succeed9(succeed3([map4(leftOption.value,options.onSelf),DrainLeft]));if(isNone2(leftOption)&&isSome2(rightOption))return succeed9(succeed3([map4(rightOption.value,options.onOther),DrainRight]));return succeed9(fail4(none2()))}}));case OP_PULL_LEFT:return matchEffect2(pullLeft,{onFailure:match2({onNone:()=>succeed9(succeed3([map4(state.rightChunk,options.onOther),DrainRight])),onSome:(error)=>succeed9(fail4(some2(error)))}),onSuccess:(leftChunk)=>{if(isEmpty(leftChunk))return pull(PullLeft(state.rightChunk),pullLeft,pullRight);if(isEmpty(state.rightChunk))return pull(PullRight(leftChunk),pullLeft,pullRight);return succeed9(succeed3(zip9(leftChunk,state.rightChunk,options.onBoth)))}});case OP_PULL_RIGHT:return matchEffect2(pullRight,{onFailure:match2({onNone:()=>succeed9(succeed3([map4(state.leftChunk,options.onSelf),DrainLeft])),onSome:(error)=>succeed9(fail4(some2(error)))}),onSuccess:(rightChunk)=>{if(isEmpty(rightChunk))return pull(PullRight(state.leftChunk),pullLeft,pullRight);if(isEmpty(state.leftChunk))return pull(PullLeft(rightChunk),pullLeft,pullRight);return succeed9(succeed3(zip9(state.leftChunk,rightChunk,options.onBoth)))}})}},zip9=(leftChunk,rightChunk,f)=>{let[output,either6]=zipChunks(leftChunk,rightChunk,f);switch(either6._tag){case"Left":{if(isEmpty(either6.left))return[output,PullBoth];return[output,PullRight(either6.left)]}case"Right":{if(isEmpty(either6.right))return[output,PullBoth];return[output,PullLeft(either6.right)]}}};return combineChunks(self,options.other,PullBoth,pull)}),zipLatest=dual(2,(left3,right3)=>pipe(left3,zipLatestWith(right3,(a,a2)=>[a,a2]))),zipLatestAll=(...streams)=>{if(streams.length===0)return empty34;else if(streams.length===1)return map21(streams[0],(x)=>[x]);let[head6,...tail]=streams;return zipLatestWith(head6,zipLatestAll(...tail),(first2,second)=>[first2,...second])},zipLatestWith=dual(3,(left3,right3,f)=>{let pullNonEmpty=(pull)=>pipe(pull,flatMap10((chunk3)=>isEmpty(chunk3)?pullNonEmpty(pull):succeed9(chunk3)));return pipe(toPull2(left3),map16(pullNonEmpty),zip6(pipe(toPull2(right3),map16(pullNonEmpty))),flatMap10(([left4,right4])=>pipe(fromEffectOption(raceWith2(left4,right4,{onSelfDone:(leftDone,rightFiber)=>pipe(suspend3(()=>leftDone),zipWith8(join3(rightFiber),(l,r)=>[l,r,!0])),onOtherDone:(rightDone,leftFiber)=>pipe(suspend3(()=>rightDone),zipWith8(join3(leftFiber),(l,r)=>[r,l,!1]))})),flatMap15(([l,r,leftFirst])=>pipe(fromEffect8(make29([unsafeLast(l),unsafeLast(r)])),flatMap15((latest)=>pipe(fromChunk(leftFirst?pipe(r,map4((a2)=>f(unsafeLast(l),a2))):pipe(l,map4((a)=>f(a,unsafeLast(r))))),concat2(pipe(repeatEffectOption(left4),mergeEither(repeatEffectOption(right4)),mapEffectSequential(match({onLeft:(leftChunk)=>pipe(modify3(latest,([_,rightLatest])=>[pipe(leftChunk,map4((a)=>f(a,rightLatest))),[unsafeLast(leftChunk),rightLatest]])),onRight:(rightChunk)=>pipe(modify3(latest,([leftLatest,_])=>[pipe(rightChunk,map4((a2)=>f(leftLatest,a2))),[leftLatest,unsafeLast(rightChunk)]]))})),flatMap15(fromChunk))))))),toPull2)),fromPull2)}),zipLeft6=dual(2,(left3,right3)=>pipe(left3,zipWithChunks(right3,(left4,right4)=>{if(left4.length>right4.length)return[pipe(left4,take(right4.length)),left2(pipe(left4,take(right4.length)))];return[left4,right2(pipe(right4,drop2(left4.length)))]}))),zipRight9=dual(2,(left3,right3)=>pipe(left3,zipWithChunks(right3,(left4,right4)=>{if(left4.length>right4.length)return[right4,left2(pipe(left4,take(right4.length)))];return[pipe(right4,take(left4.length)),right2(pipe(right4,drop2(left4.length)))]}))),zipWith12=dual(3,(left3,right3,f)=>pipe(left3,zipWithChunks(right3,(leftChunk,rightChunk)=>zipChunks(leftChunk,rightChunk,f)))),zipWithChunks=dual(3,(self,that,f)=>{let pull=(state,pullLeft,pullRight)=>{switch(state._tag){case OP_PULL_BOTH2:return pipe(unsome(pullLeft),zip6(unsome(pullRight),{concurrent:!0}),matchEffect2({onFailure:(error)=>succeed9(fail4(some2(error))),onSuccess:([leftOption,rightOption])=>{if(isSome2(leftOption)&&isSome2(rightOption)){if(isEmpty(leftOption.value)&&isEmpty(rightOption.value))return pull(PullBoth2,pullLeft,pullRight);if(isEmpty(leftOption.value))return pull(PullLeft2(rightOption.value),pullLeft,pullRight);if(isEmpty(rightOption.value))return pull(PullRight2(leftOption.value),pullLeft,pullRight);return succeed9(succeed3(zip9(leftOption.value,rightOption.value)))}return succeed9(fail4(none2()))}}));case OP_PULL_LEFT2:return matchEffect2(pullLeft,{onFailure:(error)=>succeed9(fail4(error)),onSuccess:(leftChunk)=>{if(isEmpty(leftChunk))return pull(PullLeft2(state.rightChunk),pullLeft,pullRight);if(isEmpty(state.rightChunk))return pull(PullRight2(leftChunk),pullLeft,pullRight);return succeed9(succeed3(zip9(leftChunk,state.rightChunk)))}});case OP_PULL_RIGHT2:return matchEffect2(pullRight,{onFailure:(error)=>succeed9(fail4(error)),onSuccess:(rightChunk)=>{if(isEmpty(rightChunk))return pull(PullRight2(state.leftChunk),pullLeft,pullRight);if(isEmpty(state.leftChunk))return pull(PullLeft2(rightChunk),pullLeft,pullRight);return succeed9(succeed3(zip9(state.leftChunk,rightChunk)))}})}},zip9=(leftChunk,rightChunk)=>{let[output,either6]=f(leftChunk,rightChunk);switch(either6._tag){case"Left":{if(isEmpty(either6.left))return[output,PullBoth2];return[output,PullRight2(either6.left)]}case"Right":{if(isEmpty(either6.right))return[output,PullBoth2];return[output,PullLeft2(either6.right)]}}};return pipe(self,combineChunks(that,PullBoth2,pull))}),zipWithIndex=(self)=>pipe(self,mapAccum5(0,(index,a)=>[index+1,[a,index]])),zipWithNext=(self)=>{let process2=(last5)=>readWithCause({onInput:(input)=>{let[newLast,chunk3]=mapAccum2(input,last5,(prev,curr)=>[some2(curr),pipe(prev,map2((a)=>[a,curr]))]),output=filterMap2(chunk3,(option3)=>isSome2(option3)?some2([option3.value[0],some2(option3.value[1])]):none2());return flatMap12(write(output),()=>process2(newLast))},onFailure:failCause10,onDone:()=>match2(last5,{onNone:()=>void_6,onSome:(value)=>zipRight5(write(of2([value,none2()])),void_6)})});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(process2(none2()))))},zipWithPrevious=(self)=>pipe(self,mapAccum5(none2(),(prev,curr)=>[some2(curr),[prev,curr]])),zipWithPreviousAndNext=(self)=>pipe(zipWithNext(zipWithPrevious(self)),map21(([[prev,curr],next4])=>[prev,curr,pipe(next4,map2((tuple3)=>tuple3[1]))])),zipChunks=(left3,right3,f)=>{if(left3.length>right3.length)return[pipe(left3,take(right3.length),zipWith2(right3,f)),left2(pipe(left3,drop2(right3.length)))];return[pipe(left3,zipWith2(pipe(right3,take(left3.length)),f)),right2(pipe(right3,drop2(left3.length)))]},Do3=succeed14({}),bind4=dual((args2)=>typeof args2[0]!=="string",(self,tag,f,options)=>flatMap15(self,(k)=>map21(f(k),(a)=>({...k,[tag]:a})),options)),bindTo4=bindTo(map21),let_4=let_(map21);var decodeText=dual((args2)=>isStream(args2[0]),(self,encoding="utf-8")=>suspend8(()=>{let decoder=new TextDecoder(encoding);return map21(self,(s)=>decoder.decode(s))})),encodeText=(self)=>suspend8(()=>{let encoder=new TextEncoder;return map21(self,(s)=>encoder.encode(s))}),fromEventListener=(target,type,options)=>asyncPush((emit2)=>acquireRelease2(sync3(()=>target.addEventListener(type,emit2.single,options)),()=>sync3(()=>target.removeEventListener(type,emit2.single,options))),{bufferSize:typeof options==="object"?options.bufferSize:void 0});var RedactedSymbolKey="effect/Redacted",redactedRegistry=globalValue("effect/Redacted/redactedRegistry",()=>new WeakMap),RedactedTypeId=Symbol.for(RedactedSymbolKey),proto12={[RedactedTypeId]:{_A:(_)=>_},pipe(){return pipeArguments(this,arguments)},toString(){return"<redacted>"},toJSON(){return"<redacted>"},[NodeInspectSymbol](){return"<redacted>"},[symbol](){return pipe(hash(RedactedSymbolKey),combine(hash(redactedRegistry.get(this))),cached(this))},[symbol2](that){return isRedacted(that)&&equals(redactedRegistry.get(this),redactedRegistry.get(that))}},isRedacted=(u)=>hasProperty(u,RedactedTypeId);var SecretSymbolKey="effect/Secret",SecretTypeId=Symbol.for(SecretSymbolKey);var SecretProto={...proto12,[SecretTypeId]:SecretTypeId};var ConfigSymbolKey="effect/Config",ConfigTypeId=Symbol.for(ConfigSymbolKey),configVariance={_A:(_)=>_},proto13={...CommitPrototype,[ConfigTypeId]:configVariance,commit(){return config(this)}};var TypeId20=Symbol.for("effect/FiberHandle");var Proto3={[TypeId20]:TypeId20,toString(){return format(this.toJSON())},toJSON(){return{_id:"FiberHandle",state:this.state}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var TypeId21=Symbol.for("effect/FiberMap");var Proto4={[TypeId21]:TypeId21,[Symbol.iterator](){if(this.state._tag==="Closed")return empty();return this.state.backing[Symbol.iterator]()},toString(){return format(this.toJSON())},toJSON(){return{_id:"FiberMap",state:this.state}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var TypeId22=Symbol.for("effect/FiberSet");var Proto5={[TypeId22]:TypeId22,[Symbol.iterator](){if(this.state._tag==="Closed")return empty();return this.state.backing[Symbol.iterator]()},toString(){return format(this.toJSON())},toJSON(){return{_id:"FiberMap",state:this.state}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var GroupBySymbolKey="effect/GroupBy",GroupByTypeId=Symbol.for(GroupBySymbolKey),groupByVariance={_R:(_)=>_,_E:(_)=>_,_K:(_)=>_,_V:(_)=>_},isGroupBy=(u)=>hasProperty(u,GroupByTypeId),evaluate2=dual((args2)=>isGroupBy(args2[0]),(self,f,options)=>flatMap15(self.grouped,([key,queue])=>f(key,flattenTake(fromQueue2(queue,{shutdown:!0}))),{concurrency:"unbounded",bufferSize:options?.bufferSize??16}));var make57=(grouped2)=>({[GroupByTypeId]:groupByVariance,pipe(){return pipeArguments(this,arguments)},grouped:grouped2}),groupBy=dual((args2)=>isStream(args2[0]),(self,f,options)=>make57(unwrapScoped3(gen2(function*(){let decider=yield*make19(),output=yield*acquireRelease2(bounded5(options?.bufferSize??16),(queue)=>shutdown4(queue)),ref=yield*make29(new Map),add7=yield*pipe(mapEffectSequential(self,f),distributedWithDynamicCallback(options?.bufferSize??16,([key,value])=>flatMap10(_await(decider),(f2)=>f2(key,value)),(exit3)=>offer3(output,exit3)));return yield*succeed2(decider,(key,_)=>pipe(get12(ref),map16((map24)=>fromNullable(map24.get(key))),flatMap10(match2({onNone:()=>flatMap10(add7,([index,queue])=>zipRight4(update3(ref,(map24)=>map24.set(key,index)),pipe(offer3(output,succeed3([key,mapDequeue(queue,(exit3)=>new TakeImpl(pipe(exit3,map11((tuple3)=>of2(tuple3[1])))))])),as3((n)=>n===index)))),onSome:(index)=>succeed9((n)=>n===index)})))),flattenExitOption(fromQueue2(output,{shutdown:!0}))})))),mapEffectOptions=dual((args2)=>typeof args2[0]!=="function",(self,f,options)=>{if(options?.key)return evaluate2(groupByKey(self,options.key,{bufferSize:options.bufferSize}),(_,s)=>mapEffectSequential(s,f));return matchConcurrency(options?.concurrency,()=>mapEffectSequential(self,f),(n)=>options?.unordered?flatMap15(self,(a)=>fromEffect8(f(a)),{concurrency:n}):mapEffectPar(self,n,f))}),bindEffect=dual((args2)=>typeof args2[0]!=="string",(self,tag,f,options)=>mapEffectOptions(self,(k)=>map16(f(k),(a)=>({...k,[tag]:a})),options)),mapDequeue=(dequeue,f)=>new MapDequeue(dequeue,f);class MapDequeue extends Class{dequeue;f;[DequeueTypeId2]={_Out:(_)=>_};constructor(dequeue,f){super();this.dequeue=dequeue,this.f=f}capacity(){return capacity4(this.dequeue)}get size(){return size13(this.dequeue)}unsafeSize(){return this.dequeue.unsafeSize()}get awaitShutdown(){return awaitShutdown3(this.dequeue)}isActive(){return this.dequeue.isActive()}get isShutdown(){return isShutdown3(this.dequeue)}get shutdown(){return shutdown4(this.dequeue)}get isFull(){return isFull3(this.dequeue)}get isEmpty(){return isEmpty12(this.dequeue)}get take(){return pipe(take3(this.dequeue),map16((a)=>this.f(a)))}get takeAll(){return pipe(takeAll2(this.dequeue),map16(map4((a)=>this.f(a))))}takeUpTo(max7){return pipe(takeUpTo2(this.dequeue,max7),map16(map4((a)=>this.f(a))))}takeBetween(min5,max7){return pipe(takeBetween2(this.dequeue,min5,max7),map16(map4((a)=>this.f(a))))}takeN(n){return pipe(takeN2(this.dequeue,n),map16(map4((a)=>this.f(a))))}poll(){return pipe(poll6(this.dequeue),map16(map2((a)=>this.f(a))))}pipe(){return pipeArguments(this,arguments)}commit(){return this.take}}var groupByKey=dual((args2)=>typeof args2[0]!=="function",(self,f,options)=>{let loop3=(map24,outerQueue)=>readWithCause({onInput:(input)=>flatMap12(fromEffect5(forEach8(groupByIterable(input,f),([key,values3])=>{let innerQueue=map24.get(key);if(innerQueue===void 0)return pipe(bounded5(options?.bufferSize??16),flatMap10((innerQueue2)=>pipe(sync3(()=>{map24.set(key,innerQueue2)}),zipRight4(offer3(outerQueue,of5([key,innerQueue2]))),zipRight4(pipe(offer3(innerQueue2,chunk2(values3)),catchSomeCause2((cause3)=>isInterruptedOnly2(cause3)?some2(_void):none2()))))));return catchSomeCause2(offer3(innerQueue,chunk2(values3)),(cause3)=>isInterruptedOnly2(cause3)?some2(_void):none2())},{discard:!0})),()=>loop3(map24,outerQueue)),onFailure:(cause3)=>fromEffect5(offer3(outerQueue,failCause11(cause3))),onDone:()=>pipe(fromEffect5(pipe(forEach8(map24.entries(),([_,innerQueue])=>pipe(offer3(innerQueue,end4),catchSomeCause2((cause3)=>isInterruptedOnly2(cause3)?some2(_void):none2())),{discard:!0}),zipRight4(offer3(outerQueue,end4)))))});return make57(unwrapScopedWith3((scope4)=>gen2(function*(){let map24=new Map,queue=yield*unbounded5();return yield*addFinalizer2(scope4,shutdown4(queue)),yield*toChannel2(self).pipe(pipeTo(loop3(map24,queue)),drain,runIn(scope4),forkIn2(scope4),as3(flattenTake(fromQueue2(queue,{shutdown:!0}))))})))}),groupByIterable=dual(2,(iterable,f)=>{let builder=[],iterator=iterable[Symbol.iterator](),map24=new Map,next4;while((next4=iterator.next())&&!next4.done){let value=next4.value,key=f(value);if(map24.has(key))map24.get(key).push(value);else{let innerBuilder=[value];builder.push([key,innerBuilder]),map24.set(key,innerBuilder)}}return unsafeFromArray(builder.map((tuple3)=>[tuple3[0],unsafeFromArray(tuple3[1])]))});class Pointer{path;actual;issue;_tag="Pointer";constructor(path,actual,issue){this.path=path,this.actual=actual,this.issue=issue}}class Unexpected{actual;message;_tag="Unexpected";constructor(actual,message){this.actual=actual,this.message=message}}class Missing{ast;message;_tag="Missing";actual=void 0;constructor(ast,message){this.ast=ast,this.message=message}}class Composite2{ast;actual;issues;output;_tag="Composite";constructor(ast,actual,issues,output){this.ast=ast,this.actual=actual,this.issues=issues,this.output=output}}class Refinement2{ast;actual;kind;issue;_tag="Refinement";constructor(ast,actual,kind,issue){this.ast=ast,this.actual=actual,this.kind=kind,this.issue=issue}}class Transformation{ast;actual;kind;issue;_tag="Transformation";constructor(ast,actual,kind,issue){this.ast=ast,this.actual=actual,this.kind=kind,this.issue=issue}}class Type2{ast;actual;message;_tag="Type";constructor(ast,actual,message){this.ast=ast,this.actual=actual,this.message=message}}class Forbidden{ast;actual;message;_tag="Forbidden";constructor(ast,actual,message){this.ast=ast,this.actual=actual,this.message=message}}var ParseErrorTypeId=Symbol.for("effect/Schema/ParseErrorTypeId");class ParseError extends TaggedError("ParseError"){[ParseErrorTypeId]=ParseErrorTypeId;get message(){return this.toString()}toString(){return TreeFormatter.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[NodeInspectSymbol](){return this.toJSON()}}var parseError=(issue)=>new ParseError({issue}),succeed17=right2,fail17=left2;var isEither4=isEither2,flatMap16=dual(2,(self,f)=>{return isEither4(self)?match(self,{onLeft:left2,onRight:f}):flatMap10(self,f)}),map24=dual(2,(self,f)=>{return isEither4(self)?map(self,f):map16(self,f)}),mapError6=dual(2,(self,f)=>{return isEither4(self)?mapLeft(self,f):mapError2(self,f)});var orElse11=dual(2,(self,f)=>{return isEither4(self)?match(self,{onLeft:f,onRight:right2}):catchAll2(self,f)}),mergeInternalOptions=(options,overrideOptions)=>{if(overrideOptions===void 0||isNumber(overrideOptions))return options;if(options===void 0)return overrideOptions;return{...options,...overrideOptions}},getEither=(ast,isDecoding,options)=>{let parser=goMemo(ast,isDecoding);return(u,overrideOptions)=>parser(u,mergeInternalOptions(options,overrideOptions))},getSync=(ast,isDecoding,options)=>{let parser=getEither(ast,isDecoding,options);return(input,overrideOptions)=>getOrThrowWith(parser(input,overrideOptions),parseError)};var validateSync=(schema,options)=>getSync(typeAST(schema.ast),!0,options);var decodeMemoMap=globalValue(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),encodeMemoMap=globalValue(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap),goMemo=(ast,isDecoding)=>{let memoMap=isDecoding?decodeMemoMap:encodeMemoMap,memo=memoMap.get(ast);if(memo)return memo;let raw=go(ast,isDecoding),parseOptionsAnnotation=getParseOptionsAnnotation(ast),parserWithOptions=isSome2(parseOptionsAnnotation)?(i,options)=>raw(i,mergeInternalOptions(options,parseOptionsAnnotation.value)):raw,decodingFallbackAnnotation=getDecodingFallbackAnnotation(ast),parser=isDecoding&&isSome2(decodingFallbackAnnotation)?(i,options)=>handleForbidden(orElse11(parserWithOptions(i,options),decodingFallbackAnnotation.value),ast,i,options):parserWithOptions;return memoMap.set(ast,parser),parser},getConcurrency=(ast)=>getOrUndefined(getConcurrencyAnnotation(ast)),getBatching=(ast)=>getOrUndefined(getBatchingAnnotation(ast)),go=(ast,isDecoding)=>{switch(ast._tag){case"Refinement":if(isDecoding){let from=goMemo(ast.from,!0);return(i,options)=>{options=options??defaultParseOption;let allErrors=options?.errors==="all",result=flatMap16(orElse11(from(i,options),(ef)=>{let issue=new Refinement2(ast,i,"From",ef);if(allErrors&&hasStableFilter(ast)&&isComposite2(ef))return match2(ast.filter(i,options,ast),{onNone:()=>left2(issue),onSome:(ep)=>left2(new Composite2(ast,i,[issue,new Refinement2(ast,i,"Predicate",ep)]))});return left2(issue)}),(a)=>match2(ast.filter(a,options,ast),{onNone:()=>right2(a),onSome:(ep)=>left2(new Refinement2(ast,i,"Predicate",ep))}));return handleForbidden(result,ast,i,options)}}else{let from=goMemo(typeAST(ast),!0),to=goMemo(dropRightRefinement(ast.from),!1);return(i,options)=>handleForbidden(flatMap16(from(i,options),(a)=>to(a,options)),ast,i,options)}case"Transformation":{let transform2=getFinalTransformation(ast.transformation,isDecoding),from=isDecoding?goMemo(ast.from,!0):goMemo(ast.to,!1),to=isDecoding?goMemo(ast.to,!0):goMemo(ast.from,!1);return(i,options)=>handleForbidden(flatMap16(mapError6(from(i,options),(e)=>new Transformation(ast,i,isDecoding?"Encoded":"Type",e)),(a)=>flatMap16(mapError6(transform2(a,options??defaultParseOption,ast,i),(e)=>new Transformation(ast,i,"Transformation",e)),(i2)=>mapError6(to(i2,options),(e)=>new Transformation(ast,i,isDecoding?"Type":"Encoded",e)))),ast,i,options)}case"Declaration":{let parse2=isDecoding?ast.decodeUnknown(...ast.typeParameters):ast.encodeUnknown(...ast.typeParameters);return(i,options)=>handleForbidden(parse2(i,options??defaultParseOption,ast),ast,i,options)}case"Literal":return fromRefinement(ast,(u)=>u===ast.literal);case"UniqueSymbol":return fromRefinement(ast,(u)=>u===ast.symbol);case"UndefinedKeyword":return fromRefinement(ast,isUndefined);case"NeverKeyword":return fromRefinement(ast,isNever);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return right2;case"StringKeyword":return fromRefinement(ast,isString);case"NumberKeyword":return fromRefinement(ast,isNumber);case"BooleanKeyword":return fromRefinement(ast,isBoolean);case"BigIntKeyword":return fromRefinement(ast,isBigInt);case"SymbolKeyword":return fromRefinement(ast,isSymbol);case"ObjectKeyword":return fromRefinement(ast,isObject);case"Enums":return fromRefinement(ast,(u)=>ast.enums.some(([_,value])=>value===u));case"TemplateLiteral":{let regex=getTemplateLiteralRegExp(ast);return fromRefinement(ast,(u)=>isString(u)&®ex.test(u))}case"TupleType":{let elements=ast.elements.map((e)=>goMemo(e.type,isDecoding)),rest=ast.rest.map((annotatedAST)=>goMemo(annotatedAST.type,isDecoding)),requiredTypes=ast.elements.filter((e)=>!e.isOptional);if(ast.rest.length>0)requiredTypes=requiredTypes.concat(ast.rest.slice(1));let requiredLen=requiredTypes.length,expectedIndexes=ast.elements.length>0?ast.elements.map((_,i)=>i).join(" | "):"never",concurrency=getConcurrency(ast),batching=getBatching(ast);return(input,options)=>{if(!isArray(input))return left2(new Type2(ast,input));let allErrors=options?.errors==="all",es=[],stepKey=0,output=[],len=input.length;for(let i2=len;i2<=requiredLen-1;i2++){let e=new Pointer(i2,input,new Missing(requiredTypes[i2-len]));if(allErrors){es.push([stepKey++,e]);continue}else return left2(new Composite2(ast,input,e,output))}if(ast.rest.length===0)for(let i2=ast.elements.length;i2<=len-1;i2++){let e=new Pointer(i2,input,new Unexpected(input[i2],`is unexpected, expected: ${expectedIndexes}`));if(allErrors){es.push([stepKey++,e]);continue}else return left2(new Composite2(ast,input,e,output))}let i=0,queue=void 0;for(;i<elements.length;i++)if(len<i+1){if(ast.elements[i].isOptional)continue}else{let parser=elements[i],te=parser(input[i],options);if(isEither4(te)){if(isLeft2(te)){let e=new Pointer(i,input,te.left);if(allErrors){es.push([stepKey++,e]);continue}else return left2(new Composite2(ast,input,e,sortByIndex(output)))}output.push([stepKey++,te.right])}else{let nk=stepKey++,index=i;if(!queue)queue=[];queue.push(({es:es2,output:output2})=>flatMap10(either3(te),(t)=>{if(isLeft2(t)){let e=new Pointer(index,input,t.left);if(allErrors)return es2.push([nk,e]),_void;else return left2(new Composite2(ast,input,e,sortByIndex(output2)))}return output2.push([nk,t.right]),_void}))}}if(isNonEmptyReadonlyArray(rest)){let[head6,...tail]=rest;for(;i<len-tail.length;i++){let te=head6(input[i],options);if(isEither4(te))if(isLeft2(te)){let e=new Pointer(i,input,te.left);if(allErrors){es.push([stepKey++,e]);continue}else return left2(new Composite2(ast,input,e,sortByIndex(output)))}else output.push([stepKey++,te.right]);else{let nk=stepKey++,index=i;if(!queue)queue=[];queue.push(({es:es2,output:output2})=>flatMap10(either3(te),(t)=>{if(isLeft2(t)){let e=new Pointer(index,input,t.left);if(allErrors)return es2.push([nk,e]),_void;else return left2(new Composite2(ast,input,e,sortByIndex(output2)))}else return output2.push([nk,t.right]),_void}))}}for(let j=0;j<tail.length;j++)if(i+=j,len<i+1)continue;else{let te=tail[j](input[i],options);if(isEither4(te)){if(isLeft2(te)){let e=new Pointer(i,input,te.left);if(allErrors){es.push([stepKey++,e]);continue}else return left2(new Composite2(ast,input,e,sortByIndex(output)))}output.push([stepKey++,te.right])}else{let nk=stepKey++,index=i;if(!queue)queue=[];queue.push(({es:es2,output:output2})=>flatMap10(either3(te),(t)=>{if(isLeft2(t)){let e=new Pointer(index,input,t.left);if(allErrors)return es2.push([nk,e]),_void;else return left2(new Composite2(ast,input,e,sortByIndex(output2)))}return output2.push([nk,t.right]),_void}))}}}let computeResult=({es:es2,output:output2})=>isNonEmptyArray2(es2)?left2(new Composite2(ast,input,sortByIndex(es2),sortByIndex(output2))):right2(sortByIndex(output2));if(queue&&queue.length>0){let cqueue=queue;return suspend3(()=>{let state={es:copy(es),output:copy(output)};return flatMap10(forEach8(cqueue,(f)=>f(state),{concurrency,batching,discard:!0}),()=>computeResult(state))})}return computeResult({output,es})}}case"TypeLiteral":{if(ast.propertySignatures.length===0&&ast.indexSignatures.length===0)return fromRefinement(ast,isNotNullable);let propertySignatures=[],expectedKeysMap={},expectedKeys=[];for(let ps of ast.propertySignatures)propertySignatures.push([goMemo(ps.type,isDecoding),ps]),expectedKeysMap[ps.name]=null,expectedKeys.push(ps.name);let indexSignatures=ast.indexSignatures.map((is)=>[goMemo(is.parameter,isDecoding),goMemo(is.type,isDecoding),is.parameter]),expectedAST=Union.make(ast.indexSignatures.map((is)=>is.parameter).concat(expectedKeys.map((key)=>isSymbol(key)?new UniqueSymbol(key):new Literal(key)))),expected=goMemo(expectedAST,isDecoding),concurrency=getConcurrency(ast),batching=getBatching(ast);return(input,options)=>{if(!isRecord(input))return left2(new Type2(ast,input));let allErrors=options?.errors==="all",es=[],stepKey=0,onExcessPropertyError=options?.onExcessProperty==="error",onExcessPropertyPreserve=options?.onExcessProperty==="preserve",output={},inputKeys;if(onExcessPropertyError||onExcessPropertyPreserve){inputKeys=ownKeys(input);for(let key of inputKeys){let te=expected(key,options);if(isEither4(te)&&isLeft2(te))if(onExcessPropertyError){let e=new Pointer(key,input,new Unexpected(input[key],`is unexpected, expected: ${String(expectedAST)}`));if(allErrors){es.push([stepKey++,e]);continue}else return left2(new Composite2(ast,input,e,output))}else output[key]=input[key]}}let queue=void 0,isExact=options?.exact===!0;for(let i=0;i<propertySignatures.length;i++){let ps=propertySignatures[i][1],name=ps.name,hasKey=Object.prototype.hasOwnProperty.call(input,name);if(!hasKey){if(ps.isOptional)continue;else if(isExact){let e=new Pointer(name,input,new Missing(ps));if(allErrors){es.push([stepKey++,e]);continue}else return left2(new Composite2(ast,input,e,output))}}let parser=propertySignatures[i][0],te=parser(input[name],options);if(isEither4(te)){if(isLeft2(te)){let e=new Pointer(name,input,hasKey?te.left:new Missing(ps));if(allErrors){es.push([stepKey++,e]);continue}else return left2(new Composite2(ast,input,e,output))}output[name]=te.right}else{let nk=stepKey++,index=name;if(!queue)queue=[];queue.push(({es:es2,output:output2})=>flatMap10(either3(te),(t)=>{if(isLeft2(t)){let e=new Pointer(index,input,hasKey?t.left:new Missing(ps));if(allErrors)return es2.push([nk,e]),_void;else return left2(new Composite2(ast,input,e,output2))}return output2[index]=t.right,_void}))}}for(let i=0;i<indexSignatures.length;i++){let indexSignature=indexSignatures[i],parameter=indexSignature[0],type=indexSignature[1],keys5=getKeysForIndexSignature(input,indexSignature[2]);for(let key of keys5){let keu=parameter(key,options);if(isEither4(keu)&&isRight2(keu)){let vpr=type(input[key],options);if(isEither4(vpr)){if(isLeft2(vpr)){let e=new Pointer(key,input,vpr.left);if(allErrors){es.push([stepKey++,e]);continue}else return left2(new Composite2(ast,input,e,output))}else if(!Object.prototype.hasOwnProperty.call(expectedKeysMap,key))output[key]=vpr.right}else{let nk=stepKey++,index=key;if(!queue)queue=[];queue.push(({es:es2,output:output2})=>flatMap10(either3(vpr),(tv)=>{if(isLeft2(tv)){let e=new Pointer(index,input,tv.left);if(allErrors)return es2.push([nk,e]),_void;else return left2(new Composite2(ast,input,e,output2))}else{if(!Object.prototype.hasOwnProperty.call(expectedKeysMap,key))output2[key]=tv.right;return _void}}))}}}}let computeResult=({es:es2,output:output2})=>{if(isNonEmptyArray2(es2))return left2(new Composite2(ast,input,sortByIndex(es2),output2));if(options?.propertyOrder==="original"){let keys5=inputKeys||ownKeys(input);for(let name of expectedKeys)if(keys5.indexOf(name)===-1)keys5.push(name);let out={};for(let key of keys5)if(Object.prototype.hasOwnProperty.call(output2,key))out[key]=output2[key];return right2(out)}return right2(output2)};if(queue&&queue.length>0){let cqueue=queue;return suspend3(()=>{let state={es:copy(es),output:Object.assign({},output)};return flatMap10(forEach8(cqueue,(f)=>f(state),{concurrency,batching,discard:!0}),()=>computeResult(state))})}return computeResult({es,output})}}case"Union":{let searchTree=getSearchTree(ast.types,isDecoding),ownKeys2=ownKeys(searchTree.keys),ownKeysLen=ownKeys2.length,astTypesLen=ast.types.length,map25=new Map;for(let i=0;i<astTypesLen;i++)map25.set(ast.types[i],goMemo(ast.types[i],isDecoding));let concurrency=getConcurrency(ast)??1,batching=getBatching(ast);return(input,options)=>{let es=[],stepKey=0,candidates=[];if(ownKeysLen>0)if(isRecordOrArray(input))for(let i=0;i<ownKeysLen;i++){let name=ownKeys2[i],buckets=searchTree.keys[name].buckets;if(Object.prototype.hasOwnProperty.call(input,name)){let literal2=String(input[name]);if(Object.prototype.hasOwnProperty.call(buckets,literal2))candidates=candidates.concat(buckets[literal2]);else{let{candidates:candidates2,literals}=searchTree.keys[name],literalsUnion=Union.make(literals),errorAst=candidates2.length===astTypesLen?new TypeLiteral([new PropertySignature(name,literalsUnion,!1,!0)],[]):Union.make(candidates2);es.push([stepKey++,new Composite2(errorAst,input,new Pointer(name,input,new Type2(literalsUnion,input[name])))])}}else{let{candidates:candidates2,literals}=searchTree.keys[name],fakePropertySignature=new PropertySignature(name,Union.make(literals),!1,!0),errorAst=candidates2.length===astTypesLen?new TypeLiteral([fakePropertySignature],[]):Union.make(candidates2);es.push([stepKey++,new Composite2(errorAst,input,new Pointer(name,input,new Missing(fakePropertySignature)))])}}else{let errorAst=searchTree.candidates.length===astTypesLen?ast:Union.make(searchTree.candidates);es.push([stepKey++,new Type2(errorAst,input)])}if(searchTree.otherwise.length>0)candidates=candidates.concat(searchTree.otherwise);let queue=void 0;for(let i=0;i<candidates.length;i++){let candidate=candidates[i],pr=map25.get(candidate)(input,options);if(isEither4(pr)&&(!queue||queue.length===0))if(isRight2(pr))return pr;else es.push([stepKey++,pr.left]);else{let nk=stepKey++;if(!queue)queue=[];queue.push((state)=>suspend3(()=>{if("finalResult"in state)return _void;else return flatMap10(either3(pr),(t)=>{if(isRight2(t))state.finalResult=t;else state.es.push([nk,t.left]);return _void})}))}}let computeResult=(es2)=>isNonEmptyArray2(es2)?es2.length===1&&es2[0][1]._tag==="Type"?left2(es2[0][1]):left2(new Composite2(ast,input,sortByIndex(es2))):left2(new Type2(ast,input));if(queue&&queue.length>0){let cqueue=queue;return suspend3(()=>{let state={es:copy(es)};return flatMap10(forEach8(cqueue,(f)=>f(state),{concurrency,batching,discard:!0}),()=>{if("finalResult"in state)return state.finalResult;return computeResult(state.es)})})}return computeResult(es)}}case"Suspend":{let get17=memoizeThunk(()=>goMemo(annotations(ast.f(),ast.annotations),isDecoding));return(a,options)=>get17()(a,options)}}},fromRefinement=(ast,refinement)=>(u)=>refinement(u)?right2(u):left2(new Type2(ast,u)),getLiterals=(ast,isDecoding)=>{switch(ast._tag){case"Declaration":{let annotation=getSurrogateAnnotation(ast);if(isSome2(annotation))return getLiterals(annotation.value,isDecoding);break}case"TypeLiteral":{let out=[];for(let i=0;i<ast.propertySignatures.length;i++){let propertySignature=ast.propertySignatures[i],type=isDecoding?encodedAST(propertySignature.type):typeAST(propertySignature.type);if(isLiteral(type)&&!propertySignature.isOptional)out.push([propertySignature.name,type])}return out}case"TupleType":{let out=[];for(let i=0;i<ast.elements.length;i++){let element=ast.elements[i],type=isDecoding?encodedAST(element.type):typeAST(element.type);if(isLiteral(type)&&!element.isOptional)out.push([i,type])}return out}case"Refinement":return getLiterals(ast.from,isDecoding);case"Suspend":return getLiterals(ast.f(),isDecoding);case"Transformation":return getLiterals(isDecoding?ast.from:ast.to,isDecoding)}return[]},getSearchTree=(members,isDecoding)=>{let keys5={},otherwise=[],candidates=[];for(let i=0;i<members.length;i++){let member=members[i],tags=getLiterals(member,isDecoding);if(tags.length>0){candidates.push(member);for(let j=0;j<tags.length;j++){let[key,literal2]=tags[j],hash2=String(literal2.literal);keys5[key]=keys5[key]||{buckets:{},literals:[],candidates:[]};let buckets=keys5[key].buckets;if(Object.prototype.hasOwnProperty.call(buckets,hash2)){if(j<tags.length-1)continue;buckets[hash2].push(member),keys5[key].literals.push(literal2),keys5[key].candidates.push(member)}else{buckets[hash2]=[member],keys5[key].literals.push(literal2),keys5[key].candidates.push(member);break}}}else otherwise.push(member)}return{keys:keys5,otherwise,candidates}},dropRightRefinement=(ast)=>isRefinement(ast)?dropRightRefinement(ast.from):ast,handleForbidden=(effect4,ast,actual,options)=>{if(options?.isEffectAllowed===!0)return effect4;if(isEither4(effect4))return effect4;let scheduler=new SyncScheduler,fiber=runFork2(effect4,{scheduler});scheduler.flush();let exit3=fiber.unsafePoll();if(exit3){if(isSuccess(exit3))return right2(exit3.value);let cause3=exit3.cause;if(isFailType2(cause3))return left2(cause3.error);return left2(new Forbidden(ast,actual,pretty3(cause3)))}return left2(new Forbidden(ast,actual,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},compare=([a],[b])=>a>b?1:a<b?-1:0;function sortByIndex(es){return es.sort(compare).map((t)=>t[1])}var getFinalTransformation=(transformation,isDecoding)=>{switch(transformation._tag){case"FinalTransformation":return isDecoding?transformation.decode:transformation.encode;case"ComposeTransformation":return right2;case"TypeLiteralTransformation":return(input)=>{let out=right2(input);for(let pst of transformation.propertySignatureTransformations){let[from,to]=isDecoding?[pst.from,pst.to]:[pst.to,pst.from],transformation2=isDecoding?pst.decode:pst.encode;out=map24(out,(input2)=>{let o=transformation2(Object.prototype.hasOwnProperty.call(input2,from)?some2(input2[from]):none2());if(delete input2[from],isSome2(o))input2[to]=o.value;return input2})}return out}}},makeTree=(value,forest=[])=>({value,forest}),TreeFormatter={formatIssue:(issue)=>map24(formatTree(issue),drawTree),formatIssueSync:(issue)=>{let e=TreeFormatter.formatIssue(issue);return isEither4(e)?getOrThrow(e):runSync(e)},formatError:(error2)=>TreeFormatter.formatIssue(error2.issue),formatErrorSync:(error2)=>TreeFormatter.formatIssueSync(error2.issue)},drawTree=(tree)=>tree.value+draw(`
|
|
39
|
+
`,tree.forest),draw=(indentation,forest)=>{let r="",len=forest.length,tree;for(let i=0;i<len;i++){tree=forest[i];let isLast=i===len-1;r+=indentation+(isLast?"└":"├")+"─ "+tree.value,r+=draw(indentation+(len>1&&!isLast?"│ ":" "),tree.forest)}return r},formatTransformationKind=(kind)=>{switch(kind){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},formatRefinementKind=(kind)=>{switch(kind){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},getAnnotated=(issue)=>("ast"in issue)?some2(issue.ast):none2(),Either_void=right2(void 0),getCurrentMessage=(issue)=>getAnnotated(issue).pipe(flatMap(getMessageAnnotation),match2({onNone:()=>Either_void,onSome:(messageAnnotation)=>{let union9=messageAnnotation(issue);if(isString(union9))return right2({message:union9,override:!1});if(isEffect2(union9))return map16(union9,(message)=>({message,override:!1}));if(isString(union9.message))return right2({message:union9.message,override:union9.override});return map16(union9.message,(message)=>({message,override:union9.override}))}})),createParseIssueGuard=(tag)=>(issue)=>issue._tag===tag,isComposite2=createParseIssueGuard("Composite"),isRefinement2=createParseIssueGuard("Refinement"),isTransformation=createParseIssueGuard("Transformation"),getMessage=(issue)=>flatMap16(getCurrentMessage(issue),(currentMessage)=>{if(currentMessage!==void 0)return!currentMessage.override&&(isComposite2(issue)||isRefinement2(issue)&&issue.kind==="From"||isTransformation(issue)&&issue.kind!=="Transformation")?isTransformation(issue)||isRefinement2(issue)?getMessage(issue.issue):Either_void:right2(currentMessage.message);return Either_void}),getParseIssueTitleAnnotation2=(issue)=>getAnnotated(issue).pipe(flatMap(getParseIssueTitleAnnotation),flatMapNullable((annotation)=>annotation(issue)),getOrUndefined);function getRefinementExpected(ast){return getDescriptionAnnotation(ast).pipe(orElse(()=>getTitleAnnotation(ast)),orElse(()=>getAutoTitleAnnotation(ast)),orElse(()=>getIdentifierAnnotation(ast)),getOrElse(()=>`{ ${ast.from} | filter }`))}function getDefaultTypeMessage(issue){if(issue.message!==void 0)return issue.message;return`Expected ${isRefinement(issue.ast)?getRefinementExpected(issue.ast):String(issue.ast)}, actual ${formatUnknown(issue.actual)}`}var formatTypeMessage=(issue)=>map24(getMessage(issue),(message)=>message??getParseIssueTitleAnnotation2(issue)??getDefaultTypeMessage(issue)),getParseIssueTitle=(issue)=>getParseIssueTitleAnnotation2(issue)??String(issue.ast),formatForbiddenMessage=(issue)=>issue.message??"is forbidden",formatUnexpectedMessage=(issue)=>issue.message??"is unexpected",formatMissingMessage=(issue)=>{let missingMessageAnnotation=getMissingMessageAnnotation(issue.ast);if(isSome2(missingMessageAnnotation)){let annotation=missingMessageAnnotation.value();return isString(annotation)?right2(annotation):annotation}return right2(issue.message??"is missing")},formatTree=(issue)=>{switch(issue._tag){case"Type":return map24(formatTypeMessage(issue),makeTree);case"Forbidden":return right2(makeTree(getParseIssueTitle(issue),[makeTree(formatForbiddenMessage(issue))]));case"Unexpected":return right2(makeTree(formatUnexpectedMessage(issue)));case"Missing":return map24(formatMissingMessage(issue),makeTree);case"Transformation":return flatMap16(getMessage(issue),(message)=>{if(message!==void 0)return right2(makeTree(message));return map24(formatTree(issue.issue),(tree)=>makeTree(getParseIssueTitle(issue),[makeTree(formatTransformationKind(issue.kind),[tree])]))});case"Refinement":return flatMap16(getMessage(issue),(message)=>{if(message!==void 0)return right2(makeTree(message));return map24(formatTree(issue.issue),(tree)=>makeTree(getParseIssueTitle(issue),[makeTree(formatRefinementKind(issue.kind),[tree])]))});case"Pointer":return map24(formatTree(issue.issue),(tree)=>makeTree(formatPath(issue.path),[tree]));case"Composite":return flatMap16(getMessage(issue),(message)=>{if(message!==void 0)return right2(makeTree(message));let parseIssueTitle=getParseIssueTitle(issue);return isNonEmpty(issue.issues)?map24(forEach8(issue.issues,formatTree),(forest)=>makeTree(parseIssueTitle,forest)):map24(formatTree(issue.issues),(tree)=>makeTree(parseIssueTitle,[tree]))})}};var PoolTypeId=Symbol.for("effect/Pool"),poolVariance={_E:(_)=>_,_A:(_)=>_};class PoolImpl extends Class{scope;acquire;concurrency;minSize;maxSize;strategy;targetUtilization;[PoolTypeId];isShuttingDown=!1;semaphore;items=new Set;available=new Set;availableLatch=unsafeMakeLatch(!1);invalidated=new Set;waiters=0;constructor(scope4,acquire,concurrency,minSize,maxSize,strategy,targetUtilization){super();this.scope=scope4,this.acquire=acquire,this.concurrency=concurrency,this.minSize=minSize,this.maxSize=maxSize,this.strategy=strategy,this.targetUtilization=targetUtilization,this[PoolTypeId]=poolVariance,this.semaphore=unsafeMakeSemaphore(concurrency*maxSize)}allocate=acquireUseRelease(scopeMake(),(scope4)=>this.acquire.pipe(scopeExtend(scope4),exit,flatMap8((exit3)=>{let item={exit:exit3,finalizer:catchAllCause(scope4.close(exit3),reportUnhandledError),refCount:0,disableReclaim:!1};return this.items.add(item),this.available.add(item),as(exit3._tag==="Success"?this.strategy.onAcquire(item):zipRight(item.finalizer,this.strategy.onAcquire(item)),item)})),(scope4,exit3)=>exit3._tag==="Failure"?scope4.close(exit3):void_);get currentUsage(){let count4=this.waiters;for(let item of this.items)count4+=item.refCount;return count4}get targetSize(){if(this.isShuttingDown)return 0;let utilization=this.currentUsage/this.targetUtilization,target=Math.ceil(utilization/this.concurrency);return Math.min(Math.max(this.minSize,target),this.maxSize)}get activeSize(){return this.items.size-this.invalidated.size}resizeLoop=suspend(()=>{if(this.activeSize>=this.targetSize)return void_;let toAcquire=this.targetSize-this.activeSize;return this.strategy.reclaim(this).pipe(flatMap8(match2({onNone:()=>this.allocate,onSome:succeed})),replicateEffect(toAcquire,{concurrency:toAcquire}),zipLeft(this.availableLatch.open),flatMap8((items)=>items.some((_)=>_.exit._tag==="Failure")?void_:this.resizeLoop))});resizeSemaphore=unsafeMakeSemaphore(1);resize=this.resizeSemaphore.withPermits(1)(this.resizeLoop);getPoolItem=uninterruptibleMask((restore)=>restore(this.semaphore.take(1)).pipe(zipRight(scopeTag),flatMap8((scope4)=>suspend(()=>{if(this.waiters++,this.isShuttingDown)return interrupt2;else if(this.targetSize>this.activeSize){let self=this;return flatMap8(this.resizeSemaphore.withPermitsIfAvailable(1)(forkIn(interruptible2(this.resize),this.scope)),function loop(){if(self.isShuttingDown)return interrupt2;else if(self.available.size>0)return succeed(unsafeHead(self.available));return self.availableLatch.unsafeClose(),flatMap8(self.availableLatch.await,loop)})}return succeed(unsafeHead(this.available))}).pipe(ensuring(sync(()=>this.waiters--)),tap((item)=>{if(item.exit._tag==="Failure")return this.items.delete(item),this.invalidated.delete(item),this.available.delete(item),this.semaphore.release(1);if(item.refCount++,this.available.delete(item),item.refCount<this.concurrency)this.available.add(item);return scope4.addFinalizer(()=>zipRight(suspend(()=>{if(item.refCount--,this.invalidated.has(item))return this.invalidatePoolItem(item);return this.available.add(item),exitVoid}),this.semaphore.release(1)))}),onInterrupt(()=>this.semaphore.release(1))))));commit(){return this.get}get=flatMap8(suspend(()=>this.isShuttingDown?interrupt2:this.getPoolItem),(_)=>_.exit);invalidate(item){return suspend(()=>{if(this.isShuttingDown)return void_;for(let poolItem of this.items)if(poolItem.exit._tag==="Success"&&poolItem.exit.value===item)return poolItem.disableReclaim=!0,uninterruptible(this.invalidatePoolItem(poolItem));return void_})}invalidatePoolItem(poolItem){return suspend(()=>{if(!this.items.has(poolItem))return void_;else if(poolItem.refCount===0)return this.items.delete(poolItem),this.available.delete(poolItem),this.invalidated.delete(poolItem),zipRight(poolItem.finalizer,forkIn(interruptible2(this.resize),this.scope));return this.invalidated.add(poolItem),this.available.delete(poolItem),void_})}get shutdown(){return suspend(()=>{if(this.isShuttingDown)return void_;this.isShuttingDown=!0;let size16=this.items.size,semaphore=unsafeMakeSemaphore(size16);return forEachSequentialDiscard(this.items,(item)=>{if(item.refCount>0)return item.finalizer=zipLeft(item.finalizer,semaphore.release(1)),this.invalidated.add(item),semaphore.take(1);return this.items.delete(item),this.available.delete(item),this.invalidated.delete(item),item.finalizer}).pipe(zipRight(this.semaphore.releaseAll),zipRight(this.availableLatch.open),zipRight(semaphore.take(size16)))})}pipe(){return pipeArguments(this,arguments)}}var reportUnhandledError=(cause3)=>withFiberRuntime((fiber)=>{let unhandledLogLevel=fiber.getFiberRef(currentUnhandledErrorLogLevel);if(unhandledLogLevel._tag==="Some")fiber.log("Unhandled error in pool finalizer",cause3,unhandledLogLevel);return void_});var ManagedRuntimeProto={...CommitPrototype2,[TypeId18]:TypeId18,pipe(){return pipeArguments(this,arguments)},commit(){return this.runtimeEffect}};var TypeId25=Symbol.for("@effect/matcher/Matcher"),TypeMatcherProto={[TypeId25]:{_input:identity,_filters:identity,_remaining:identity,_result:identity,_return:identity},_tag:"TypeMatcher",add(_case){return makeTypeMatcher([...this.cases,_case])},pipe(){return pipeArguments(this,arguments)}};function makeTypeMatcher(cases){let matcher=Object.create(TypeMatcherProto);return matcher.cases=cases,matcher}var ValueMatcherProto={[TypeId25]:{_input:identity,_filters:identity,_result:identity,_return:identity},_tag:"ValueMatcher",add(_case){if(this.value._tag==="Right")return this;if(_case._tag==="When"&&_case.guard(this.provided)===!0)return makeValueMatcher(this.provided,right2(_case.evaluate(this.provided)));else if(_case._tag==="Not"&&_case.guard(this.provided)===!1)return makeValueMatcher(this.provided,right2(_case.evaluate(this.provided)));return this},pipe(){return pipeArguments(this,arguments)}};function makeValueMatcher(provided,value){let matcher=Object.create(ValueMatcherProto);return matcher.provided=provided,matcher.value=value,matcher}var TypeId26=Symbol.for("effect/MutableHashSet"),MutableHashSetProto={[TypeId26]:TypeId26,[Symbol.iterator](){return Array.from(this.keyMap).map(([_])=>_)[Symbol.iterator]()},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableHashSet",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var ScopedRefSymbolKey="effect/ScopedRef",ScopedRefTypeId=Symbol.for(ScopedRefSymbolKey),scopedRefVariance={_A:(_)=>_},proto14={...CommitPrototype,commit(){return get21(this)},[ScopedRefTypeId]:scopedRefVariance};var get21=(self)=>map10(get11(self.ref),(tuple3)=>tuple3[1]);var ResourceSymbolKey="effect/Resource",ResourceTypeId=Symbol.for(ResourceSymbolKey),resourceVariance={_E:(_)=>_,_A:(_)=>_},proto15={...CommitPrototype,commit(){return get23(this)},[ResourceTypeId]:resourceVariance};var get23=(self)=>flatMap8(get21(self.scopedRef),identity);var TypeId27=Symbol.for("effect/Schema");function make69(ast){return class SchemaClass{[TypeId27]=variance10;static ast=ast;static annotations(annotations2){return make69(mergeSchemaAnnotations(this.ast,annotations2))}static pipe(){return pipeArguments(this,arguments)}static toString(){return String(ast)}static Type;static Encoded;static Context;static[TypeId27]=variance10}}var variance10={_A:(_)=>_,_I:(_)=>_,_R:(_)=>_};var builtInAnnotations={schemaId:SchemaIdAnnotationId,message:MessageAnnotationId,missingMessage:MissingMessageAnnotationId,identifier:IdentifierAnnotationId,title:TitleAnnotationId,description:DescriptionAnnotationId,examples:ExamplesAnnotationId,default:DefaultAnnotationId,documentation:DocumentationAnnotationId,jsonSchema:JSONSchemaAnnotationId,arbitrary:ArbitraryAnnotationId,pretty:PrettyAnnotationId,equivalence:EquivalenceAnnotationId,concurrency:ConcurrencyAnnotationId,batching:BatchingAnnotationId,parseIssueTitle:ParseIssueTitleAnnotationId,parseOptions:ParseOptionsAnnotationId,decodingFallback:DecodingFallbackAnnotationId},toASTAnnotations=(annotations2)=>{if(!annotations2)return{};let out={...annotations2};for(let key in builtInAnnotations)if(key in annotations2){let id3=builtInAnnotations[key];out[id3]=annotations2[key],delete out[key]}return out},mergeSchemaAnnotations=(ast,annotations2)=>annotations(ast,toASTAnnotations(annotations2));var declareConstructor=(typeParameters,options,annotations2)=>makeDeclareClass(typeParameters,new Declaration(typeParameters.map((tp)=>tp.ast),(...typeParameters2)=>options.decode(...typeParameters2.map(make69)),(...typeParameters2)=>options.encode(...typeParameters2.map(make69)),toASTAnnotations(annotations2))),declarePrimitive=(is3,annotations2)=>{let decodeUnknown3=()=>(input,_,ast)=>is3(input)?succeed17(input):fail17(new Type2(ast,input));return makeDeclareClass([],new Declaration([],decodeUnknown3,decodeUnknown3,toASTAnnotations(annotations2)))};function makeDeclareClass(typeParameters,ast){return class DeclareClass extends make69(ast){static annotations(annotations2){return makeDeclareClass(this.typeParameters,mergeSchemaAnnotations(this.ast,annotations2))}static typeParameters=[...typeParameters]}}var declare=function(){if(Array.isArray(arguments[0])){let typeParameters=arguments[0],options=arguments[1],annotations3=arguments[2];return declareConstructor(typeParameters,options,annotations3)}let is3=arguments[0],annotations2=arguments[1];return declarePrimitive(is3,annotations2)};class String$ extends make69(stringKeyword){}var RefineSchemaId=Symbol.for("effect/SchemaId/Refine");function makeRefineClass(from,filter13,ast){return class RefineClass extends make69(ast){static annotations(annotations2){return makeRefineClass(this.from,this.filter,mergeSchemaAnnotations(this.ast,annotations2))}static[RefineSchemaId]=from;static from=from;static filter=filter13;static make=(a,options)=>{return getDisableValidationMakeOption(options)?a:validateSync(this)(a)}}}var fromFilterPredicateReturnTypeItem=(item,ast,input)=>{if(isBoolean(item))return item?none2():some2(new Type2(ast,input));if(isString(item))return some2(new Type2(ast,input,item));if(item!==void 0){if("_tag"in item)return some2(item);let issue=new Type2(ast,input,item.message);return some2(isNonEmptyReadonlyArray(item.path)?new Pointer(item.path,input,issue):issue)}return none2()},toFilterParseIssue=(out,ast,input)=>{if(isSingle(out))return fromFilterPredicateReturnTypeItem(out,ast,input);if(isNonEmptyReadonlyArray(out)){let issues=filterMap(out,(issue)=>fromFilterPredicateReturnTypeItem(issue,ast,input));if(isNonEmptyReadonlyArray(issues))return some2(issues.length===1?issues[0]:new Composite2(ast,input,issues))}return none2()};function filter13(predicate,annotations2){return(self)=>{function filter14(input,options,ast2){return toFilterParseIssue(predicate(input,options,ast2),ast2,input)}let ast=new Refinement(self.ast,filter14,toASTAnnotations(annotations2));return makeRefineClass(self,filter14,ast)}}var PatternSchemaId=Symbol.for("effect/SchemaId/Pattern"),pattern=(regex,annotations2)=>(self)=>{let source=regex.source;return self.pipe(filter13((a)=>{return regex.lastIndex=0,regex.test(a)},{schemaId:PatternSchemaId,[PatternSchemaId]:{regex},description:`a string matching the pattern ${source}`,jsonSchema:{pattern:source},...annotations2}))};var UUIDSchemaId=Symbol.for("effect/SchemaId/UUID"),uuidRegexp=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;class UUID extends String$.pipe(pattern(uuidRegexp,{schemaId:UUIDSchemaId,identifier:"UUID",jsonSchema:{format:"uuid",pattern:uuidRegexp.source},description:"a Universally Unique Identifier",arbitrary:()=>(fc)=>fc.uuid()})){}var DateFromSelfSchemaId2=DateFromSelfSchemaId;class DateFromSelf extends declare(isDate,{identifier:"DateFromSelf",schemaId:DateFromSelfSchemaId2,[DateFromSelfSchemaId2]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(date2)=>`new Date(${JSON.stringify(date2)})`,arbitrary:()=>(fc)=>fc.date({noInvalidDate:!1}),equivalence:()=>Date2}){}function getDisableValidationMakeOption(options){return isBoolean(options)?options:options?.disableValidation??!1}var TypeId28=Symbol.for("effect/SortedMap"),SortedMapProto={[TypeId28]:{_K:(_)=>_,_V:(_)=>_},[symbol](){return pipe(hash(this.tree),combine(hash("effect/SortedMap")),cached(this))},[symbol2](that){return isSortedMap(that)&&equals(this.tree,that.tree)},[Symbol.iterator](){return this.tree[Symbol.iterator]()},toString(){return format(this.toJSON())},toJSON(){return{_id:"SortedMap",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var isSortedMap=(u)=>hasProperty(u,TypeId28);var exports_Stream={};__export(exports_Stream,{zipWithPreviousAndNext:()=>zipWithPreviousAndNext2,zipWithPrevious:()=>zipWithPrevious2,zipWithNext:()=>zipWithNext2,zipWithIndex:()=>zipWithIndex2,zipWithChunks:()=>zipWithChunks2,zipWith:()=>zipWith14,zipRight:()=>zipRight11,zipLeft:()=>zipLeft10,zipLatestWith:()=>zipLatestWith2,zipLatestAll:()=>zipLatestAll2,zipLatest:()=>zipLatest2,zipFlatten:()=>zipFlatten2,zipAllWith:()=>zipAllWith2,zipAllSortedByKeyWith:()=>zipAllSortedByKeyWith2,zipAllSortedByKeyRight:()=>zipAllSortedByKeyRight2,zipAllSortedByKeyLeft:()=>zipAllSortedByKeyLeft2,zipAllSortedByKey:()=>zipAllSortedByKey2,zipAllRight:()=>zipAllRight2,zipAllLeft:()=>zipAllLeft2,zipAll:()=>zipAll2,zip:()=>zip15,withSpan:()=>withSpan6,whenEffect:()=>whenEffect4,whenCaseEffect:()=>whenCaseEffect2,whenCase:()=>whenCase2,when:()=>when6,void:()=>void_9,updateService:()=>updateService5,unwrapScopedWith:()=>unwrapScopedWith4,unwrapScoped:()=>unwrapScoped5,unwrap:()=>unwrap5,unfoldEffect:()=>unfoldEffect2,unfoldChunkEffect:()=>unfoldChunkEffect2,unfoldChunk:()=>unfoldChunk2,unfold:()=>unfold4,transduce:()=>transduce2,toReadableStreamRuntime:()=>toReadableStreamRuntime2,toReadableStreamEffect:()=>toReadableStreamEffect2,toReadableStream:()=>toReadableStream2,toQueueOfElements:()=>toQueueOfElements2,toQueue:()=>toQueue3,toPull:()=>toPull3,toPubSub:()=>toPubSub3,toChannel:()=>toChannel4,timeoutTo:()=>timeoutTo4,timeoutFailCause:()=>timeoutFailCause4,timeoutFail:()=>timeoutFail4,timeout:()=>timeout4,tick:()=>tick2,throttleEffect:()=>throttleEffect2,throttle:()=>throttle2,tapSink:()=>tapSink2,tapErrorCause:()=>tapErrorCause5,tapError:()=>tapError6,tapBoth:()=>tapBoth5,tap:()=>tap6,takeWhile:()=>takeWhile5,takeUntilEffect:()=>takeUntilEffect2,takeUntil:()=>takeUntil4,takeRight:()=>takeRight3,take:()=>take9,sync:()=>sync13,suspend:()=>suspend10,succeed:()=>succeed21,splitOnChunk:()=>splitOnChunk2,splitLines:()=>splitLines3,split:()=>split2,someOrFail:()=>someOrFail2,someOrElse:()=>someOrElse2,some:()=>some8,slidingSize:()=>slidingSize2,sliding:()=>sliding8,share:()=>share2,scopedWith:()=>scopedWith5,scoped:()=>scoped7,scheduleWith:()=>scheduleWith2,schedule:()=>schedule3,scanReduceEffect:()=>scanReduceEffect2,scanReduce:()=>scanReduce2,scanEffect:()=>scanEffect2,scan:()=>scan2,runSum:()=>runSum2,runScoped:()=>runScoped3,runLast:()=>runLast2,runIntoQueueScoped:()=>runIntoQueueScoped2,runIntoQueueElementsScoped:()=>runIntoQueueElementsScoped2,runIntoQueue:()=>runIntoQueue2,runIntoPubSubScoped:()=>runIntoPubSubScoped2,runIntoPubSub:()=>runIntoPubSub2,runHead:()=>runHead2,runForEachWhileScoped:()=>runForEachWhileScoped2,runForEachWhile:()=>runForEachWhile2,runForEachScoped:()=>runForEachScoped2,runForEachChunkScoped:()=>runForEachChunkScoped2,runForEachChunk:()=>runForEachChunk2,runForEach:()=>runForEach2,runFoldWhileScopedEffect:()=>runFoldWhileScopedEffect2,runFoldWhileScoped:()=>runFoldWhileScoped2,runFoldWhileEffect:()=>runFoldWhileEffect2,runFoldWhile:()=>runFoldWhile2,runFoldScopedEffect:()=>runFoldScopedEffect2,runFoldScoped:()=>runFoldScoped2,runFoldEffect:()=>runFoldEffect2,runFold:()=>runFold2,runDrain:()=>runDrain3,runCount:()=>runCount2,runCollect:()=>runCollect3,run:()=>run4,retry:()=>retry7,repeatWith:()=>repeatWith2,repeatValue:()=>repeatValue2,repeatElementsWith:()=>repeatElementsWith2,repeatElements:()=>repeatElements2,repeatEither:()=>repeatEither2,repeatEffectWithSchedule:()=>repeatEffectWithSchedule2,repeatEffectOption:()=>repeatEffectOption2,repeatEffectChunkOption:()=>repeatEffectChunkOption2,repeatEffectChunk:()=>repeatEffectChunk2,repeatEffect:()=>repeatEffect2,repeat:()=>repeat4,refineOrDieWith:()=>refineOrDieWith4,refineOrDie:()=>refineOrDie4,rechunk:()=>rechunk2,range:()=>range3,raceAll:()=>raceAll4,race:()=>race6,provideSomeLayer:()=>provideSomeLayer4,provideServiceStream:()=>provideServiceStream2,provideServiceEffect:()=>provideServiceEffect4,provideService:()=>provideService8,provideLayer:()=>provideLayer3,provideContext:()=>provideContext9,prepend:()=>prepend5,pipeThroughChannelOrFail:()=>pipeThroughChannelOrFail2,pipeThroughChannel:()=>pipeThroughChannel2,pipeThrough:()=>pipeThrough2,peel:()=>peel2,partitionEither:()=>partitionEither2,partition:()=>partition7,paginateEffect:()=>paginateEffect2,paginateChunkEffect:()=>paginateChunkEffect2,paginateChunk:()=>paginateChunk2,paginate:()=>paginate2,orElseSucceed:()=>orElseSucceed5,orElseIfEmptyStream:()=>orElseIfEmptyStream2,orElseIfEmptyChunk:()=>orElseIfEmptyChunk2,orElseIfEmpty:()=>orElseIfEmpty2,orElseFail:()=>orElseFail5,orElseEither:()=>orElseEither6,orElse:()=>orElse15,orDieWith:()=>orDieWith6,orDie:()=>orDie7,onStart:()=>onStart2,onError:()=>onError4,onEnd:()=>onEnd2,onDone:()=>onDone2,never:()=>never9,mkString:()=>mkString3,mergeWithTag:()=>mergeWithTag2,mergeWith:()=>mergeWith4,mergeRight:()=>mergeRight2,mergeLeft:()=>mergeLeft2,mergeEither:()=>mergeEither2,mergeAll:()=>mergeAll8,merge:()=>merge11,mapInputContext:()=>mapInputContext8,mapErrorCause:()=>mapErrorCause5,mapError:()=>mapError9,mapEffect:()=>mapEffect6,mapConcatEffect:()=>mapConcatEffect2,mapConcatChunkEffect:()=>mapConcatChunkEffect2,mapConcatChunk:()=>mapConcatChunk2,mapConcat:()=>mapConcat2,mapChunksEffect:()=>mapChunksEffect2,mapChunks:()=>mapChunks2,mapBoth:()=>mapBoth9,mapAccumEffect:()=>mapAccumEffect2,mapAccum:()=>mapAccum6,map:()=>map27,make:()=>make73,let:()=>let_6,iterate:()=>iterate5,intersperseAffixes:()=>intersperseAffixes2,intersperse:()=>intersperse2,interruptWhenDeferred:()=>interruptWhenDeferred3,interruptWhen:()=>interruptWhen3,interruptAfter:()=>interruptAfter2,interleaveWith:()=>interleaveWith2,interleave:()=>interleave2,identity:()=>identity3,haltWhenDeferred:()=>haltWhenDeferred2,haltWhen:()=>haltWhen2,haltAfter:()=>haltAfter2,groupedWithin:()=>groupedWithin2,grouped:()=>grouped2,groupByKey:()=>groupByKey2,groupBy:()=>groupBy2,groupAdjacentBy:()=>groupAdjacentBy2,fromTQueue:()=>fromTQueue2,fromTPubSub:()=>fromTPubSub2,fromSchedule:()=>fromSchedule2,fromReadableStreamByob:()=>fromReadableStreamByob2,fromReadableStream:()=>fromReadableStream2,fromQueue:()=>fromQueue4,fromPull:()=>fromPull3,fromPubSub:()=>fromPubSub4,fromIteratorSucceed:()=>fromIteratorSucceed2,fromIterableEffect:()=>fromIterableEffect2,fromIterable:()=>fromIterable16,fromEventListener:()=>fromEventListener2,fromEffectOption:()=>fromEffectOption2,fromEffect:()=>fromEffect10,fromChunks:()=>fromChunks2,fromChunkQueue:()=>fromChunkQueue2,fromChunkPubSub:()=>fromChunkPubSub2,fromChunk:()=>fromChunk2,fromChannel:()=>fromChannel3,fromAsyncIterable:()=>fromAsyncIterable2,forever:()=>forever6,flattenTake:()=>flattenTake2,flattenIterables:()=>flattenIterables2,flattenExitOption:()=>flattenExitOption2,flattenEffect:()=>flattenEffect2,flattenChunks:()=>flattenChunks2,flatten:()=>flatten13,flatMap:()=>flatMap17,findEffect:()=>findEffect3,find:()=>find3,finalizer:()=>finalizer2,filterMapWhileEffect:()=>filterMapWhileEffect2,filterMapWhile:()=>filterMapWhile4,filterMapEffect:()=>filterMapEffect2,filterMap:()=>filterMap7,filterEffect:()=>filterEffect2,filter:()=>filter14,failSync:()=>failSync8,failCauseSync:()=>failCauseSync7,failCause:()=>failCause15,fail:()=>fail18,execute:()=>execute2,ensuringWith:()=>ensuringWith4,ensuring:()=>ensuring8,encodeText:()=>encodeText2,empty:()=>empty36,either:()=>either8,dropWhileEffect:()=>dropWhileEffect3,dropWhile:()=>dropWhile6,dropUntilEffect:()=>dropUntilEffect3,dropUntil:()=>dropUntil5,dropRight:()=>dropRight2,drop:()=>drop5,drainFork:()=>drainFork2,drain:()=>drain4,distributedWithDynamic:()=>distributedWithDynamic2,distributedWith:()=>distributedWith2,dieSync:()=>dieSync7,dieMessage:()=>dieMessage6,die:()=>die11,decodeText:()=>decodeText2,debounce:()=>debounce2,crossWith:()=>crossWith2,crossRight:()=>crossRight2,crossLeft:()=>crossLeft2,cross:()=>cross2,contextWithStream:()=>contextWithStream2,contextWithEffect:()=>contextWithEffect6,contextWith:()=>contextWith7,context:()=>context9,concatAll:()=>concatAll3,concat:()=>concat3,combineChunks:()=>combineChunks2,combine:()=>combine13,chunksWith:()=>chunksWith2,chunks:()=>chunks2,changesWithEffect:()=>changesWithEffect2,changesWith:()=>changesWith2,changes:()=>changes2,catchTags:()=>catchTags5,catchTag:()=>catchTag5,catchSomeCause:()=>catchSomeCause4,catchSome:()=>catchSome5,catchAllCause:()=>catchAllCause6,catchAll:()=>catchAll7,bufferChunks:()=>bufferChunks2,buffer:()=>buffer3,broadcastedQueuesDynamic:()=>broadcastedQueuesDynamic2,broadcastedQueues:()=>broadcastedQueues2,broadcastDynamic:()=>broadcastDynamic2,broadcast:()=>broadcast2,branchAfter:()=>branchAfter2,bindTo:()=>bindTo6,bindEffect:()=>bindEffect2,bind:()=>bind6,asyncScoped:()=>asyncScoped2,asyncPush:()=>asyncPush2,asyncEffect:()=>asyncEffect4,async:()=>_async2,as:()=>as9,aggregateWithinEither:()=>aggregateWithinEither2,aggregateWithin:()=>aggregateWithin2,aggregate:()=>aggregate2,acquireRelease:()=>acquireRelease4,accumulateChunks:()=>accumulateChunks2,accumulate:()=>accumulate2,StreamTypeId:()=>StreamTypeId3,Do:()=>Do4,DefaultChunkSize:()=>DefaultChunkSize2});var StreamTypeId3=StreamTypeId2,DefaultChunkSize2=DefaultChunkSize,accumulate2=accumulate,accumulateChunks2=accumulateChunks,acquireRelease4=acquireRelease3,aggregate2=aggregate,aggregateWithin2=aggregateWithin,aggregateWithinEither2=aggregateWithinEither,as9=as7,_async2=_async;var asyncEffect4=asyncEffect3,asyncPush2=asyncPush,asyncScoped2=asyncScoped,branchAfter2=branchAfter,broadcast2=broadcast,share2=share,broadcastDynamic2=broadcastDynamic,broadcastedQueues2=broadcastedQueues,broadcastedQueuesDynamic2=broadcastedQueuesDynamic,buffer3=buffer,bufferChunks2=bufferChunks,catchAll7=catchAll6,catchAllCause6=catchAllCause5,catchSome5=catchSome3,catchTag5=catchTag3,catchTags5=catchTags3,catchSomeCause4=catchSomeCause3,changes2=changes,changesWith2=changesWith,changesWithEffect2=changesWithEffect,chunks2=chunks,chunksWith2=chunksWith,combine13=combine12,combineChunks2=combineChunks,concat3=concat2,concatAll3=concatAll2,cross2=cross,crossLeft2=crossLeft,crossRight2=crossRight,crossWith2=crossWith,debounce2=debounce,die11=die9,dieSync7=dieSync5,dieMessage6=dieMessage4,distributedWith2=distributedWith,distributedWithDynamic2=distributedWithDynamic,drain4=drain3,drainFork2=drainFork,drop5=drop3,dropRight2=dropRight,dropUntil5=dropUntil3,dropUntilEffect3=dropUntilEffect,dropWhile6=dropWhile4,dropWhileEffect3=dropWhileEffect,either8=either5,empty36=empty34,ensuring8=ensuring6,ensuringWith4=ensuringWith2,context9=context5,contextWith7=contextWith3,contextWithEffect6=contextWithEffect3,contextWithStream2=contextWithStream,execute2=execute,fail18=fail15,failSync8=failSync6,failCause15=failCause13,failCauseSync7=failCauseSync5,filter14=filter9,filterEffect2=filterEffect,filterMap7=filterMap6,filterMapEffect2=filterMapEffect,filterMapWhile4=filterMapWhile3,filterMapWhileEffect2=filterMapWhileEffect,finalizer2=finalizer,find3=find2,findEffect3=findEffect,flatMap17=flatMap15,flatten13=flatten12,flattenChunks2=flattenChunks,flattenEffect2=flattenEffect,flattenExitOption2=flattenExitOption,flattenIterables2=flattenIterables,flattenTake2=flattenTake,forever6=forever5,fromAsyncIterable2=fromAsyncIterable,fromChannel3=fromChannel2,toChannel4=toChannel2,fromChunk2=fromChunk,fromChunkPubSub2=fromChunkPubSub,fromChunkQueue2=fromChunkQueue,fromChunks2=fromChunks,fromEffect10=fromEffect8,fromEffectOption2=fromEffectOption,fromPubSub4=fromPubSub,fromTPubSub2=fromTPubSub,fromIterable16=fromIterable11,fromIterableEffect2=fromIterableEffect,fromIteratorSucceed2=fromIteratorSucceed,fromPull3=fromPull2,fromQueue4=fromQueue2,fromTQueue2=fromTQueue,fromReadableStream2=fromReadableStream,fromReadableStreamByob2=fromReadableStreamByob,fromSchedule2=fromSchedule,groupAdjacentBy2=groupAdjacentBy,groupBy2=groupBy,groupByKey2=groupByKey,grouped2=grouped,groupedWithin2=groupedWithin,haltAfter2=haltAfter,haltWhen2=haltWhen,haltWhenDeferred2=haltWhenDeferred,identity3=identityStream,interleave2=interleave,interleaveWith2=interleaveWith,intersperse2=intersperse,intersperseAffixes2=intersperseAffixes,interruptAfter2=interruptAfter,interruptWhen3=interruptWhen2,interruptWhenDeferred3=interruptWhenDeferred2,iterate5=iterate3,make73=make53,map27=map21,mapAccum6=mapAccum5,mapAccumEffect2=mapAccumEffect,mapBoth9=mapBoth5,mapChunks2=mapChunks,mapChunksEffect2=mapChunksEffect,mapConcat2=mapConcat,mapConcatChunk2=mapConcatChunk,mapConcatChunkEffect2=mapConcatChunkEffect,mapConcatEffect2=mapConcatEffect,mapEffect6=mapEffectOptions,mapError9=mapError5,mapErrorCause5=mapErrorCause4,merge11=merge9,mergeAll8=mergeAll6,mergeWithTag2=mergeWithTag,mergeWith4=mergeWith3,mergeEither2=mergeEither,mergeLeft2=mergeLeft,mergeRight2=mergeRight,mkString3=mkString2,never9=never5,onEnd2=onEnd,onError4=onError3,onDone2=onDone,onStart2=onStart,orDie7=orDie4,orDieWith6=orDieWith4,orElse15=orElse8,orElseEither6=orElseEither4,orElseFail5=orElseFail3,orElseIfEmpty2=orElseIfEmpty,orElseIfEmptyChunk2=orElseIfEmptyChunk,orElseIfEmptyStream2=orElseIfEmptyStream,orElseSucceed5=orElseSucceed3,paginate2=paginate,paginateChunk2=paginateChunk,paginateChunkEffect2=paginateChunkEffect,paginateEffect2=paginateEffect,partition7=partition5,partitionEither2=partitionEither,peel2=peel,pipeThrough2=pipeThrough,pipeThroughChannel2=pipeThroughChannel,pipeThroughChannelOrFail2=pipeThroughChannelOrFail,prepend5=prepend4,provideContext9=provideContext5,provideLayer3=provideLayer,provideService8=provideService5,provideServiceEffect4=provideServiceEffect3,provideServiceStream2=provideServiceStream,mapInputContext8=mapInputContext5,provideSomeLayer4=provideSomeLayer2,race6=race3,raceAll4=raceAll3,range3=range2,rechunk2=rechunk,refineOrDie4=refineOrDie,refineOrDieWith4=refineOrDieWith,repeat4=repeat2,repeatEffect2=repeatEffect,repeatEffectChunk2=repeatEffectChunk,repeatEffectChunkOption2=repeatEffectChunkOption,repeatEffectOption2=repeatEffectOption,repeatEffectWithSchedule2=repeatEffectWithSchedule,repeatEither2=repeatEither,repeatElements2=repeatElements,repeatElementsWith2=repeatElementsWith,repeatValue2=repeatValue,repeatWith2=repeatWith,retry7=retry5,run4=run3,runCollect3=runCollect,runCount2=runCount,runDrain3=runDrain2,runFold2=runFold,runFoldEffect2=runFoldEffect,runFoldScoped2=runFoldScoped,runFoldScopedEffect2=runFoldScopedEffect,runFoldWhile2=runFoldWhile,runFoldWhileEffect2=runFoldWhileEffect,runFoldWhileScoped2=runFoldWhileScoped,runFoldWhileScopedEffect2=runFoldWhileScopedEffect,runForEach2=runForEach,runForEachChunk2=runForEachChunk,runForEachChunkScoped2=runForEachChunkScoped,runForEachScoped2=runForEachScoped,runForEachWhile2=runForEachWhile,runForEachWhileScoped2=runForEachWhileScoped,runHead2=runHead,runIntoPubSub2=runIntoPubSub,runIntoPubSubScoped2=runIntoPubSubScoped,runIntoQueue2=runIntoQueue,runIntoQueueElementsScoped2=runIntoQueueElementsScoped,runIntoQueueScoped2=runIntoQueueScoped,runLast2=runLast,runScoped3=runScoped2,runSum2=runSum,scan2=scan,scanEffect2=scanEffect,scanReduce2=scanReduce,scanReduceEffect2=scanReduceEffect,schedule3=schedule2,scheduleWith2=scheduleWith,scoped7=scoped5,scopedWith5=scopedWith4,sliding8=sliding7,slidingSize2=slidingSize,some8=some5,someOrElse2=someOrElse,someOrFail2=someOrFail,split2=split,splitOnChunk2=splitOnChunk,splitLines3=splitLines2,succeed21=succeed14,sync13=sync7,suspend10=suspend8,take9=take7,takeRight3=takeRight2,takeUntil4=takeUntil3,takeUntilEffect2=takeUntilEffect,takeWhile5=takeWhile4,tap6=tap5,tapBoth5=tapBoth3,tapError6=tapError4,tapErrorCause5=tapErrorCause4,tapSink2=tapSink,throttle2=throttle,throttleEffect2=throttleEffect,tick2=tick,timeout4=timeout3,timeoutFail4=timeoutFail3,timeoutFailCause4=timeoutFailCause3,timeoutTo4=timeoutTo3,toPubSub3=toPubSub2,toPull3=toPull2,toQueue3=toQueue2,toQueueOfElements2=toQueueOfElements,toReadableStream2=toReadableStream,toReadableStreamEffect2=toReadableStreamEffect,toReadableStreamRuntime2=toReadableStreamRuntime,transduce2=transduce,unfold4=unfold3,unfoldChunk2=unfoldChunk,unfoldChunkEffect2=unfoldChunkEffect,unfoldEffect2=unfoldEffect,void_9=void_8;var unwrap5=unwrap2,unwrapScoped5=unwrapScoped3,unwrapScopedWith4=unwrapScopedWith3,updateService5=updateService3,when6=when3,whenCase2=whenCase,whenCaseEffect2=whenCaseEffect,whenEffect4=whenEffect3,withSpan6=withSpan5,zip15=zip8,zipFlatten2=zipFlatten,zipAll2=zipAll,zipAllLeft2=zipAllLeft,zipAllRight2=zipAllRight,zipAllSortedByKey2=zipAllSortedByKey,zipAllSortedByKeyLeft2=zipAllSortedByKeyLeft,zipAllSortedByKeyRight2=zipAllSortedByKeyRight,zipAllSortedByKeyWith2=zipAllSortedByKeyWith,zipAllWith2=zipAllWith,zipLatest2=zipLatest,zipLatestAll2=zipLatestAll,zipLatestWith2=zipLatestWith,zipLeft10=zipLeft6,zipRight11=zipRight9,zipWith14=zipWith12,zipWithChunks2=zipWithChunks,zipWithNext2=zipWithNext,zipWithPrevious2=zipWithPrevious,zipWithPreviousAndNext2=zipWithPreviousAndNext,zipWithIndex2=zipWithIndex,Do4=Do3,bind6=bind4,bindEffect2=bindEffect,bindTo6=bindTo4,let_6=let_4;var decodeText2=decodeText,encodeText2=encodeText,fromEventListener2=fromEventListener;var TypeId29=Symbol.for("effect/Subscribable");var Proto6={[TypeId13]:TypeId13,[TypeId29]:TypeId29,pipe(){return pipeArguments(this,arguments)}};var TrieSymbolKey="effect/Trie",TrieTypeId=Symbol.for(TrieSymbolKey),trieVariance={_Value:(_)=>_},TrieProto={[TrieTypeId]:trieVariance,[Symbol.iterator](){return new TrieIterator(this,(k,v)=>[k,v],()=>!0)},[symbol](){let hash2=hash(TrieSymbolKey);for(let item of this)hash2^=pipe(hash(item[0]),combine(hash(item[1])));return cached(this,hash2)},[symbol2](that){if(isTrie(that)){let entries2=Array.from(that);return Array.from(this).every((itemSelf,i)=>{let itemThat=entries2[i];return equals(itemSelf[0],itemThat[0])&&equals(itemSelf[1],itemThat[1])})}return!1},toString(){return format(this.toJSON())},toJSON(){return{_id:"Trie",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};class TrieIterator{trie;f;filter;stack=[];constructor(trie,f,filter16){this.trie=trie,this.f=f,this.filter=filter16;let root=trie._root!==void 0?trie._root:void 0;if(root!==void 0)this.stack.push([root,"",!1])}next(){while(this.stack.length>0){let[node,keyString,isAdded]=this.stack.pop();if(isAdded){let value6=node.value;if(value6!==void 0){let key=keyString+node.key;if(this.filter(key,value6))return{done:!1,value:this.f(key,value6)}}}else this.addToStack(node,keyString)}return{done:!0,value:void 0}}addToStack(node,keyString){if(node.right!==void 0)this.stack.push([node.right,keyString,!1]);if(node.mid!==void 0)this.stack.push([node.mid,keyString+node.key,!1]);if(this.stack.push([node,keyString,!0]),node.left!==void 0)this.stack.push([node.left,keyString,!1])}[Symbol.iterator](){return new TrieIterator(this.trie,this.f,this.filter)}}var isTrie=(u)=>hasProperty(u,TrieTypeId);var createTcpConnection=(options)=>{return exports_Effect.scoped(exports_Effect.gen(function*(){let incomingQueue=yield*exports_Queue.unbounded(),outgoingQueue=yield*exports_Queue.unbounded(),writeErrorCount=yield*exports_Ref.make(0),isClosing=yield*exports_Ref.make(!1),performShutdown=exports_Effect.gen(function*(){if(yield*exports_Ref.getAndSet(isClosing,!0))return;bunSocket.end(),yield*exports_Effect.sleep(exports_Duration.millis(10)),yield*exports_Fiber.interrupt(writerFiber),yield*exports_Effect.all([exports_Queue.shutdown(incomingQueue),exports_Queue.shutdown(outgoingQueue)])}),bunSocket=yield*exports_Effect.tryPromise(()=>Bun.connect({port:options.port,hostname:options.host,socket:{data(_socket,data){exports_Queue.unsafeOffer(incomingQueue,data)},error(_socket,_error){exports_Effect.runPromise(performShutdown)},close(_socket){exports_Effect.runPromise(performShutdown)}}})).pipe(exports_Effect.timeout(options.timeout??exports_Duration.millis(3000)),exports_Effect.flatMap((maybeSocket)=>maybeSocket?exports_Effect.succeed(maybeSocket):exports_Effect.fail(new Error("Connection timeout")))),writerFiber=yield*pipe(exports_Effect.iterate(void 0,{while:()=>!0,body:()=>pipe(exports_Queue.take(outgoingQueue),exports_Effect.flatMap((data)=>exports_Effect.try({try:()=>{if(bunSocket.write(data)!==data.length)throw new Error("Partial write");exports_Effect.runSync(exports_Ref.set(writeErrorCount,0))},catch:(error2)=>{let currentErrors=exports_Effect.runSync(exports_Ref.updateAndGet(writeErrorCount,(n)=>n+1));if(currentErrors>3)return exports_Effect.runSync(performShutdown),exports_Effect.fail(new Error(`Write failed after ${currentErrors} attempts: ${error2}`));return exports_Effect.sleep(exports_Duration.millis(100)).pipe(exports_Effect.flatMap(()=>exports_Queue.offer(outgoingQueue,data)))}})))}),exports_Effect.fork),close2=exports_Effect.gen(function*(){console.log("Closing connection"),yield*performShutdown});return{stream:exports_Stream.fromQueue(incomingQueue).pipe(exports_Stream.ensuring(close2)),send:(data)=>exports_Queue.offer(outgoingQueue,data),sendText:(data)=>exports_Queue.offer(outgoingQueue,new TextEncoder().encode(data)),close:close2}}))};export{createTcpConnection};
|