Flow Youtube Chat

Youtubeのチャットをニコニコ風に画面上へ流す(再アップ) Make youtube chats move in danmaku-style.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(У мене вже є менеджер скриптів, дайте мені встановити його!)

Advertisement:

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

Advertisement:

// ==UserScript==
// @name Flow Youtube Chat
// @description Youtubeのチャットをニコニコ風に画面上へ流す(再アップ) Make youtube chats move in danmaku-style.
// @version 1.20.0
// @match https://www.youtube.com/*
// @grant GM.setValue
// @grant GM.getValue
// @grant GM.deleteValue
// @grant GM.listValues
// @grant GM.setClipboard
// @license AGPL-3.0-or-later
// @namespace FlowYoutubeChatScript
// @noframes
// @require https://cdn.jsdelivr.net/npm/[email protected]/dist/astring.min.js#sha384-gUzcAqLRIDJ1ScWzdnKkrjzXHpYpzOO/U8HDPAEKsDROSsZ8us+dl9/EZj1wS6ZS
// @require https://cdn.jsdelivr.net/npm/[email protected]/dist/iife/jsep.iife.min.js#sha384-u5pZyxJagBZ9DBtzv4AS5S2kA00SNUEfNhVZDLb3MDdLkZhRKfoFBA3aNHHMFRTl
// @require https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/index.js#sha384-U2/sw6xwqtADIYTsYPbCyG67dKIq7Ztmr7v0Gvoju4zGiLrlHO4Pe3L1SdVNYoW6
// @require https://cdn.jsdelivr.net/npm/[email protected]/libs/lz-string.min.js#sha384-0d+Gr7vM4Drod8E3hXKgciWJSWbjD/opKLLygI9ktiWbuvlDwQLzU46wJ9s5gsp7
// @run-at document-end
// ==/UserScript==

/*! For license information please see index.js.LICENSE.txt */
/* jshint esversion: 6 */

;(() => {
	var __webpack_modules__ = {
		371(module) {
			"use strict"
			module.exports = function equal(a, b) {
				if (a === b) return !0
				if (a && b && "object" == typeof a && "object" == typeof b) {
					if (a.constructor !== b.constructor) return !1
					var length, i, keys
					if (Array.isArray(a)) {
						if ((length = a.length) != b.length) return !1
						for (i = length; 0 != i--;) if (!equal(a[i], b[i])) return !1
						return !0
					}
					if (a.constructor === RegExp)
						return a.source === b.source && a.flags === b.flags
					if (a.valueOf !== Object.prototype.valueOf)
						return a.valueOf() === b.valueOf()
					if (a.toString !== Object.prototype.toString)
						return a.toString() === b.toString()
					if (
						(length = (keys = Object.keys(a)).length) !== Object.keys(b).length
					)
						return !1
					for (i = length; 0 != i--;)
						if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return !1
					for (i = length; 0 != i--;) {
						var key = keys[i]
						if (!equal(a[key], b[key])) return !1
					}
					return !0
				}
				return a != a && b != b
			}
		},
		742(module) {
			module.exports = (function (e) {
				var r = {}
				function t(n) {
					if (r[n]) return r[n].exports
					var a = (r[n] = { i: n, l: !1, exports: {} })
					return (e[n].call(a.exports, a, a.exports, t), (a.l = !0), a.exports)
				}
				return (
					(t.m = e),
					(t.c = r),
					(t.d = function (e, r, n) {
						t.o(e, r) || Object.defineProperty(e, r, { enumerable: !0, get: n })
					}),
					(t.r = function (e) {
						;("undefined" != typeof Symbol &&
							Symbol.toStringTag &&
							Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }),
							Object.defineProperty(e, "__esModule", { value: !0 }))
					}),
					(t.t = function (e, r) {
						if ((1 & r && (e = t(e)), 8 & r)) return e
						if (4 & r && "object" == typeof e && e && e.__esModule) return e
						var n = Object.create(null)
						if (
							(t.r(n),
							Object.defineProperty(n, "default", { enumerable: !0, value: e }),
							2 & r && "string" != typeof e)
						)
							for (var a in e)
								t.d(
									n,
									a,
									function (r) {
										return e[r]
									}.bind(null, a),
								)
						return n
					}),
					(t.n = function (e) {
						var r =
							e && e.__esModule
								? function () {
										return e.default
									}
								: function () {
										return e
									}
						return (t.d(r, "a", r), r)
					}),
					(t.o = function (e, r) {
						return Object.prototype.hasOwnProperty.call(e, r)
					}),
					(t.p = ""),
					t((t.s = 0))
				)
			})([
				function (e, r, t) {
					"use strict"
					;(t.r(r),
						t.d(r, "validateHTMLColorName", function () {
							return l
						}),
						t.d(r, "validateHTMLColorSpecialName", function () {
							return i
						}),
						t.d(r, "validateHTMLColorHex", function () {
							return u
						}),
						t.d(r, "validateHTMLColorRgb", function () {
							return g
						}),
						t.d(r, "validateHTMLColorHsl", function () {
							return y
						}),
						t.d(r, "validateHTMLColorHwb", function () {
							return L
						}),
						t.d(r, "validateHTMLColorLab", function () {
							return S
						}),
						t.d(r, "validateHTMLColorLch", function () {
							return m
						}),
						t.d(r, "validateHTMLColor", function () {
							return G
						}))
					const n = e => e && "string" == typeof e,
						a = [
							"AliceBlue",
							"AntiqueWhite",
							"Aqua",
							"Aquamarine",
							"Azure",
							"Beige",
							"Bisque",
							"Black",
							"BlanchedAlmond",
							"Blue",
							"BlueViolet",
							"Brown",
							"BurlyWood",
							"CadetBlue",
							"Chartreuse",
							"Chocolate",
							"Coral",
							"CornflowerBlue",
							"Cornsilk",
							"Crimson",
							"Cyan",
							"DarkBlue",
							"DarkCyan",
							"DarkGoldenrod",
							"DarkGray",
							"DarkGrey",
							"DarkGreen",
							"DarkKhaki",
							"DarkMagenta",
							"DarkOliveGreen",
							"DarkOrange",
							"DarkOrchid",
							"DarkRed",
							"DarkSalmon",
							"DarkSeaGreen",
							"DarkSlateBlue",
							"DarkSlateGray",
							"DarkSlateGrey",
							"DarkTurquoise",
							"DarkViolet",
							"DeepPink",
							"DeepSkyBlue",
							"DimGray",
							"DimGrey",
							"DodgerBlue",
							"FireBrick",
							"FloralWhite",
							"ForestGreen",
							"Fuchsia",
							"Gainsboro",
							"GhostWhite",
							"Gold",
							"Goldenrod",
							"Gray",
							"Grey",
							"Green",
							"GreenYellow",
							"HoneyDew",
							"HotPink",
							"IndianRed",
							"Indigo",
							"Ivory",
							"Khaki",
							"Lavender",
							"LavenderBlush",
							"LawnGreen",
							"LemonChiffon",
							"LightBlue",
							"LightCoral",
							"LightCyan",
							"LightGoldenrodYellow",
							"LightGray",
							"LightGrey",
							"LightGreen",
							"LightPink",
							"LightSalmon",
							"LightSalmon",
							"LightSeaGreen",
							"LightSkyBlue",
							"LightSlateGray",
							"LightSlateGrey",
							"LightSteelBlue",
							"LightYellow",
							"Lime",
							"LimeGreen",
							"Linen",
							"Magenta",
							"Maroon",
							"MediumAquamarine",
							"MediumBlue",
							"MediumOrchid",
							"MediumPurple",
							"MediumSeaGreen",
							"MediumSlateBlue",
							"MediumSlateBlue",
							"MediumSpringGreen",
							"MediumTurquoise",
							"MediumVioletRed",
							"MidnightBlue",
							"MintCream",
							"MistyRose",
							"Moccasin",
							"NavajoWhite",
							"Navy",
							"OldLace",
							"Olive",
							"OliveDrab",
							"Orange",
							"OrangeRed",
							"Orchid",
							"PaleGoldenrod",
							"PaleGreen",
							"PaleTurquoise",
							"PaleVioletRed",
							"PapayaWhip",
							"PeachPuff",
							"Peru",
							"Pink",
							"Plum",
							"PowderBlue",
							"Purple",
							"RebeccaPurple",
							"Red",
							"RosyBrown",
							"RoyalBlue",
							"SaddleBrown",
							"Salmon",
							"SandyBrown",
							"SeaGreen",
							"SeaShell",
							"Sienna",
							"Silver",
							"SkyBlue",
							"SlateBlue",
							"SlateGray",
							"SlateGrey",
							"Snow",
							"SpringGreen",
							"SteelBlue",
							"Tan",
							"Teal",
							"Thistle",
							"Tomato",
							"Turquoise",
							"Violet",
							"Wheat",
							"White",
							"WhiteSmoke",
							"Yellow",
							"YellowGreen",
						],
						o = ["currentColor", "inherit", "transparent"],
						l = e => {
							let r = !1
							return (
								n(e) &&
									a.map(
										t => (
											e.toLowerCase() === t.toLowerCase() && (r = !0),
											null
										),
									),
								r
							)
						},
						i = e => {
							let r = !1
							return (
								n(e) &&
									o.map(
										t => (
											e.toLowerCase() === t.toLowerCase() && (r = !0),
											null
										),
									),
								r
							)
						},
						u = e =>
							!!n(e) &&
							e &&
							/^#([\da-f]{3}){1,2}$|^#([\da-f]{4}){1,2}$/i.test(e),
						d = "(([\\d]{0,5})((\\.([\\d]{1,5}))?))",
						s = `(${d}%)`,
						c = "(([0-9]|[1-9][0-9]|100)%)",
						f = `(${c}|(0?((\\.([\\d]{1,5}))?))|1)`,
						h = `([\\s]{0,5})\\)?)(([\\s]{0,5})(\\/?)([\\s]{1,5})(((${c}))|(0?((\\.([\\d]{1,5}))?))|1))?([\\s]{0,5})\\)`,
						$ =
							"(-?(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-9][0-9]|3[0-5][0-9])((\\.([\\d]{1,5}))?)|360)(deg)?)",
						g = e => {
							if (n(e)) {
								const r = "([\\s]{0,5})([\\d]{1,5})%?([\\s]{0,5}),?",
									t = "((([\\s]{0,5}),?([\\s]{0,5}))|(([\\s]{1,5})))",
									n = new RegExp(
										`^(rgb)a?\\(${r}${t}${r}${t}${r}${t}((\\/?([\\s]{0,5})(0?\\.?([\\d]{1,5})%?([\\s]{0,5}))?|1|0))?\\)$`,
									)
								return e && n.test(e)
							}
							return !1
						},
						y = e => {
							if (n(e)) {
								const r = new RegExp(
									`^(hsl)a?\\((([\\s]{0,5})(${$}|(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-9][0-9]|3[0-9][0-9]|400)grad)|((([0-5])?\\.([\\d]{1,5})|6\\.([0-9]|1[0-9]|2[0-8])|[0-6])rad)|((0?((\\.([\\d]{1,5}))?)|1)turn))((([\\s]{0,5}),([\\s]{0,5}))|(([\\s]{1,5}))))(([\\s]{0,5})(0|${c})((([\\s]{0,5}),([\\s]{0,5}))|(([\\s]{1,5}))))(([\\s]{0,5})(0|${c})([\\s]{0,5})\\)?)(([\\s]{0,5})(\\/?|,?)([\\s]{0,5})(((${c}))|(0?((\\.([\\d]{1,5}))?))|1))?\\)$`,
								)
								return e && r.test(e)
							}
							return !1
						},
						L = e => {
							if (n(e)) {
								const r = new RegExp(
									`^(hwb\\(([\\s]{0,5})${$}([\\s]{1,5}))((0|${c})([\\s]{1,5}))((0|${c})${h}$`,
								)
								return e && r.test(e)
							}
							return !1
						},
						S = e => {
							if (n(e)) {
								const r =
										"(-?(([0-9]|[1-9][0-9]|1[0-5][0-9])((\\.([\\d]{1,5}))?)?|160))",
									t = new RegExp(
										`^(lab\\(([\\s]{0,5})${s}([\\s]{1,5})${r}([\\s]{1,5})${r}${h}$`,
									)
								return e && t.test(e)
							}
							return !1
						},
						m = e => {
							if (n(e)) {
								const o = new RegExp(
									`^lch\\((([\\s]{0,5})((([0-9]|[1-9][0-9])?((\\.([\\d]{1,5}))?)|100)(%)?)([\\s]{1,5})${"" + d}([\\s]{1,5})((${$})|(0|${f})|(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-9][0-9]|3[0-5][0-9])((\\.([\\d]{1,5}))?)|360))([\\s]{0,5})((\\/([\\s]{0,5})${f}))?)\\)$`,
								)
								return e && o.test(e)
							}
							return !1
						},
						G = e => !!((e && u(e)) || g(e) || y(e) || L(e) || S(e) || m(e))
					r.default = e =>
						!!(
							(e && u(e)) ||
							l(e) ||
							i(e) ||
							g(e) ||
							y(e) ||
							L(e) ||
							S(e) ||
							m(e)
						)
				},
			])
		},
	}
	const __webpack_module_cache__ = {}
	function __webpack_require__(moduleId) {
		const cachedModule = __webpack_module_cache__[moduleId]
		if (void 0 !== cachedModule) return cachedModule.exports
		const module = (__webpack_module_cache__[moduleId] = { exports: {} })
		__webpack_modules__[moduleId](module, module.exports, __webpack_require__)
		return module.exports
	}
	__webpack_require__.n = module => {
		const getter =
			module && module.__esModule ? () => module.default : () => module
		__webpack_require__.d(getter, { a: getter })
		return getter
	}
	__webpack_require__.d = (exports, definition) => {
		if (Array.isArray(definition))
			for (var i = 0; i < definition.length;) {
				var key = definition[i++],
					binding = definition[i++]
				__webpack_require__.o(exports, key)
					? 0 === binding && i++
					: 0 === binding
						? Object.defineProperty(exports, key, {
								enumerable: !0,
								value: definition[i++],
							})
						: Object.defineProperty(exports, key, {
								enumerable: !0,
								get: binding,
							})
			}
		else
			for (var key in definition)
				__webpack_require__.o(definition, key) &&
					!__webpack_require__.o(exports, key) &&
					Object.defineProperty(exports, key, {
						enumerable: !0,
						get: definition[key],
					})
	}
	__webpack_require__.o = (obj, prop) =>
		Object.prototype.hasOwnProperty.call(obj, prop)
	__webpack_require__.dn = x => {
		;(Object.getOwnPropertyDescriptor(x, "name") || {}).writable ||
			Object.defineProperty(x, "name", { value: "default", configurable: !0 })
	}
	;(() => {
		"use strict"
		const dual = function (arity, body) {
				if ("function" == typeof arity)
					return function () {
						return arity(arguments)
							? body.apply(this, arguments)
							: self => body(self, ...arguments)
					}
				switch (arity) {
					case 0:
					case 1:
						throw new RangeError(`Invalid arity ${arity}`)
					case 2:
						return function (a, b) {
							return arguments.length >= 2
								? body(a, b)
								: function (self) {
										return body(self, a)
									}
						}
					case 3:
						return function (a, b, c) {
							return arguments.length >= 3
								? body(a, b, c)
								: function (self) {
										return body(self, a, b)
									}
						}
					case 4:
						return function (a, b, c, d) {
							return arguments.length >= 4
								? body(a, b, c, d)
								: function (self) {
										return body(self, a, b, c)
									}
						}
					case 5:
						return function (a, b, c, d, e) {
							return arguments.length >= 5
								? body(a, b, c, d, e)
								: function (self) {
										return body(self, a, b, c, d)
									}
						}
					default:
						return function () {
							if (arguments.length >= arity) return body.apply(this, arguments)
							const args = arguments
							return function (self) {
								return body(self, ...args)
							}
						}
				}
			},
			apply =
				(...a) =>
				self =>
					self(...a),
			identity = a => a,
			constant = value => () => value,
			constTrue = constant(!0),
			constFalse = constant(!1),
			constUndefined = constant(void 0),
			constVoid = constUndefined,
			flip =
				f =>
				(...b) =>
				(...a) =>
					f(...a)(...b)
		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
				}
			}
		}
		let globalStore
		const globalValue = (id, compute) => {
				if (!globalStore) {
					globalThis["effect/GlobalValue"] ??= new Map()
					globalStore = globalThis["effect/GlobalValue"]
				}
				globalStore.has(id) || globalStore.set(id, compute())
				return globalStore.get(id)
			},
			isTruthy = input => !!input,
			isString = input => "string" == typeof input,
			isNumber = input => "number" == typeof input,
			isBoolean = input => "boolean" == typeof input,
			isBigInt = input => "bigint" == typeof input,
			isSymbol = input => "symbol" == typeof input,
			Predicate_isFunction = input => "function" == typeof input,
			isUndefined = input => void 0 === input,
			isNever = _ => !1,
			isRecordOrArray = input => "object" == typeof input && null !== input,
			isObject = input => isRecordOrArray(input) || Predicate_isFunction(input),
			hasProperty = dual(
				2,
				(self, property) => isObject(self) && property in self,
			),
			isTagged = dual(
				2,
				(self, tag) => hasProperty(self, "_tag") && self._tag === tag,
			),
			isNullable = input => null == input,
			isNotNullable = input => null != input,
			isIterable = input =>
				"string" == typeof input || hasProperty(input, Symbol.iterator),
			not = self => a => !self(a),
			getBugErrorMessage = message =>
				`BUG: ${message} - please report an issue at https://github.com/Effect-TS/effect/issues`
		Symbol.iterator
		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)
			}
		}
		class PCGRandom {
			_state
			constructor(seedHi, seedLo, incHi, incLo) {
				if (isNullable(seedLo) && isNullable(seedHi)) {
					seedLo = (4294967295 * Math.random()) >>> 0
					seedHi = 0
				} else if (isNullable(seedLo)) {
					seedLo = seedHi
					seedHi = 0
				}
				if (isNullable(incLo) && isNullable(incHi)) {
					incLo = this._state ? this._state[3] : 4150755663
					incHi = this._state ? this._state[2] : 335903614
				} else if (isNullable(incLo)) {
					incLo = incHi
					incHi = 0
				}
				this._state = new Int32Array([
					0,
					0,
					incHi >>> 0,
					(1 | (incLo || 0)) >>> 0,
				])
				this._next()
				add64(
					this._state,
					this._state[0],
					this._state[1],
					seedHi >>> 0,
					seedLo >>> 0,
				)
				this._next()
				return 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] = 1 | state[3]
			}
			integer(max) {
				return Math.round(this.number() * Number.MAX_SAFE_INTEGER) % max
			}
			number() {
				return (
					(1 * (67108863 & this._next()) * 134217728 +
						1 * (134217727 & this._next())) /
					9007199254740992
				)
			}
			_next() {
				const oldHi = this._state[0] >>> 0,
					oldLo = this._state[1] >>> 0
				!(function (out, aHi, aLo) {
					let c1 = (32557 * (aLo >>> 16)) >>> 0,
						c0 = (19605 * (65535 & aLo)) >>> 0,
						lo = (32557 * (65535 & aLo)) >>> 0,
						hi = (19605 * (aLo >>> 16) + ((c0 >>> 16) + (c1 >>> 16))) >>> 0
					c0 = (c0 << 16) >>> 0
					lo = (lo + c0) >>> 0
					lo >>> 0 < c0 >>> 0 && (hi = (hi + 1) >>> 0)
					c1 = (c1 << 16) >>> 0
					lo = (lo + c1) >>> 0
					lo >>> 0 < c1 >>> 0 && (hi = (hi + 1) >>> 0)
					hi = (hi + Math.imul(aLo, 1481765933)) >>> 0
					hi = (hi + Math.imul(aHi, 1284865837)) >>> 0
					out[0] = hi
					out[1] = lo
				})(this._state, oldHi, oldLo)
				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
				const xorshifted = ((xsLo >>> 27) | (xsHi << 5)) >>> 0,
					rot = oldHi >>> 27
				return (
					((xorshifted >>> rot) |
						(xorshifted << (((-rot >>> 0) & 31) >>> 0))) >>>
					0
				)
			}
		}
		function add64(out, aHi, aLo, bHi, bLo) {
			let hi = (aHi + bHi) >>> 0
			const lo = (aLo + bLo) >>> 0
			lo >>> 0 < aLo >>> 0 && (hi = (hi + 1) | 0)
			out[0] = hi
			out[1] = lo
		}
		const YieldWrapTypeId = Symbol.for("effect/Utils/YieldWrap")
		class YieldWrap {
			#value
			constructor(value) {
				this.#value = value
			}
			[YieldWrapTypeId]() {
				return this.#value
			}
		}
		function yieldWrapGet(self) {
			if ("object" == typeof self && null !== self && YieldWrapTypeId in self)
				return self[YieldWrapTypeId]()
			throw new Error(getBugErrorMessage("yieldWrapGet"))
		}
		const structuralRegionState = globalValue(
				"effect/Utils/isStructuralRegion",
				() => ({ enabled: !1, tester: void 0 }),
			),
			standard = { effect_internal_function: body => body() },
			internalCall =
				!0 ===
				standard
					.effect_internal_function(() => new Error().stack)
					?.includes("effect_internal_function")
					? standard.effect_internal_function
					: body => {
							try {
								return body()
							} finally {
							}
						},
			randomHashCache = globalValue(
				Symbol.for("effect/Hash/randomHashCache"),
				() => new WeakMap(),
			),
			symbol = Symbol.for("effect/Hash"),
			Hash_hash = self => {
				if (!0 === structuralRegionState.enabled) return 0
				switch (typeof self) {
					case "number":
						return number(self)
					case "bigint":
						return string(self.toString(10))
					case "boolean":
					case "symbol":
						return string(String(self))
					case "string":
						return string(self)
					case "undefined":
						return string("undefined")
					case "function":
					case "object":
						return null === self
							? string("null")
							: self instanceof Date
								? Number.isNaN(self.getTime())
									? string("Invalid Date")
									: Hash_hash(self.toISOString())
								: self instanceof URL
									? Hash_hash(self.href)
									: isHash(self)
										? self[symbol]()
										: 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 => {
				randomHashCache.has(self) ||
					randomHashCache.set(
						self,
						number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
					)
				return randomHashCache.get(self)
			},
			combine = b => self => (53 * self) ^ b,
			optimize = n => (3221225471 & n) | ((n >>> 1) & 1073741824),
			isHash = u => hasProperty(u, symbol),
			number = n => {
				if (n != n || n === 1 / 0) return 0
				let h = 0 | n
				h !== n && (h ^= 4294967295 * n)
				for (; n > 4294967295;) h ^= n /= 4294967295
				return optimize(h)
			},
			string = str => {
				let h = 5381,
					i = str.length
				for (; i;) h = (33 * h) ^ str.charCodeAt(--i)
				return optimize(h)
			},
			structure = o =>
				((o, keys) => {
					let h = 12289
					for (let i = 0; i < keys.length; i++)
						h ^= pipe(string(keys[i]), combine(Hash_hash(o[keys[i]])))
					return optimize(h)
				})(o, Object.keys(o)),
			array = arr => {
				let h = 6151
				for (let i = 0; i < arr.length; i++)
					h = pipe(h, combine(Hash_hash(arr[i])))
				return optimize(h)
			},
			cached = function () {
				if (1 === arguments.length) {
					const self = arguments[0]
					return function (hash) {
						Object.defineProperty(self, symbol, {
							value: () => hash,
							enumerable: !1,
						})
						return hash
					}
				}
				const self = arguments[0],
					hash = arguments[1]
				Object.defineProperty(self, symbol, {
					value: () => hash,
					enumerable: !1,
				})
				return hash
			},
			Equal_symbol = Symbol.for("effect/Equal")
		function equals() {
			return 1 === arguments.length
				? self => compareBoth(self, arguments[0])
				: compareBoth(arguments[0], arguments[1])
		}
		function compareBoth(self, that) {
			if (self === that) return !0
			const selfType = typeof self
			if (selfType !== typeof that) return !1
			if ("object" === selfType || "function" === selfType) {
				if (null !== self && null !== that) {
					if (isEqual(self) && isEqual(that))
						return (
							!(
								Hash_hash(self) !== Hash_hash(that) || !self[Equal_symbol](that)
							) ||
							(!(
								!structuralRegionState.enabled || !structuralRegionState.tester
							) &&
								structuralRegionState.tester(self, that))
						)
					if (self instanceof Date && that instanceof Date) {
						const t1 = self.getTime(),
							t2 = that.getTime()
						return t1 === t2 || (Number.isNaN(t1) && Number.isNaN(t2))
					}
					if (self instanceof URL && that instanceof URL)
						return self.href === that.href
				}
				if (structuralRegionState.enabled) {
					if (null === self || null === that) return !1
					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(that) === Object.prototype
					) {
						const keysSelf = Object.keys(self),
							keysThat = Object.keys(that)
						if (keysSelf.length === keysThat.length) {
							for (const key of keysSelf)
								if (!(key in that) || !compareBoth(self[key], that[key]))
									return (
										!!structuralRegionState.tester &&
										structuralRegionState.tester(self, that)
									)
							return !0
						}
					}
					return (
						!!structuralRegionState.tester &&
						structuralRegionState.tester(self, that)
					)
				}
			}
			return (
				!(!structuralRegionState.enabled || !structuralRegionState.tester) &&
				structuralRegionState.tester(self, that)
			)
		}
		const isEqual = u => hasProperty(u, Equal_symbol),
			equivalence = () => equals,
			NodeInspectSymbol = Symbol.for("nodejs.util.inspect.custom"),
			toJSON = x => {
				try {
					if (
						hasProperty(x, "toJSON") &&
						Predicate_isFunction(x.toJSON) &&
						0 === x.toJSON.length
					)
						return x.toJSON()
					if (Array.isArray(x)) return x.map(toJSON)
				} catch {
					return {}
				}
				return redact(x)
			}
		function formatPropertyKey(name) {
			return isString(name) ? JSON.stringify(name) : String(name)
		}
		function formatUnknown(input, options) {
			const space = options?.space ?? 0,
				seen = new WeakSet(),
				gap = space ? (isNumber(space) ? " ".repeat(space) : space) : "",
				ind = d => gap.repeat(d),
				wrap = (v, body) => {
					const ctor = v?.constructor
					return ctor && ctor !== Object.prototype.constructor && ctor.name
						? `${ctor.name}(${body})`
						: body
				}
			return (function go(v, d = 0) {
				if (Array.isArray(v)) {
					if (seen.has(v)) return "[Circular]"
					seen.add(v)
					if (!gap || v.length <= 1)
						return `[${v.map(x => go(x, d)).join(",")}]`
					const inner = v.map(x => go(x, d + 1)).join(",\n" + ind(d + 1))
					return `[\n${ind(d + 1)}${inner}\n${ind(d)}]`
				}
				if ((input => input instanceof Date)(v))
					return (function (date) {
						try {
							return date.toISOString()
						} catch {
							return "Invalid Date"
						}
					})(v)
				if (
					!options?.ignoreToString &&
					hasProperty(v, "toString") &&
					Predicate_isFunction(v.toString) &&
					v.toString !== Object.prototype.toString &&
					v.toString !== Array.prototype.toString
				) {
					const s = (function (input) {
						try {
							const s = input.toString()
							return "string" == typeof s ? s : String(s)
						} catch {
							return "[toString threw]"
						}
					})(v)
					return v instanceof Error && v.cause
						? `${s} (cause: ${go(v.cause, d)})`
						: s
				}
				if (isString(v)) return JSON.stringify(v)
				if (isNumber(v) || null == v || isBoolean(v) || isSymbol(v))
					return String(v)
				if (isBigInt(v)) return String(v) + "n"
				if (v instanceof Set || v instanceof Map) {
					if (seen.has(v)) return "[Circular]"
					seen.add(v)
					return `${v.constructor.name}(${go(Array.from(v), d)})`
				}
				if (isObject(v)) {
					if (seen.has(v)) return "[Circular]"
					seen.add(v)
					const keys = (o => {
						try {
							return Reflect.ownKeys(o)
						} catch {
							return ["[ownKeys threw]"]
						}
					})(v)
					if (!gap || keys.length <= 1) {
						const body = `{${keys.map(k => `${formatPropertyKey(k)}:${go(v[k], d)}`).join(",")}}`
						return wrap(v, body)
					}
					const body = `{\n${keys.map(k => `${ind(d + 1)}${formatPropertyKey(k)}: ${go(v[k], d + 1)}`).join(",\n")}\n${ind(d)}}`
					return wrap(v, body)
				}
				return String(v)
			})(input, 0)
		}
		const format = x => JSON.stringify(x, null, 2),
			toStringUnknown = (u, whitespace = 2) => {
				if ("string" == typeof u) return u
				try {
					return "object" == typeof u
						? stringifyCircular(u, whitespace)
						: String(u)
				} catch {
					return String(u)
				}
			},
			stringifyCircular = (obj, whitespace) => {
				let cache = []
				const retVal = JSON.stringify(
					obj,
					(_key, value) =>
						"object" == typeof value && null !== value
							? cache.includes(value)
								? void 0
								: cache.push(value) &&
									(void 0 !== redactableState.fiberRefs && isRedactable(value)
										? value[symbolRedactable](redactableState.fiberRefs)
										: value)
							: value,
					whitespace,
				)
				cache = void 0
				return retVal
			},
			symbolRedactable = Symbol.for("effect/Inspectable/Redactable"),
			isRedactable = u =>
				"object" == typeof u && null !== u && symbolRedactable in u,
			redactableState = globalValue(
				"effect/Inspectable/redactableState",
				() => ({ fiberRefs: void 0 }),
			),
			redact = u =>
				isRedactable(u) && void 0 !== redactableState.fiberRefs
					? u[symbolRedactable](redactableState.fiberRefs)
					: u,
			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
					}
				}
			},
			getCurrentVersion = () => "3.21.4",
			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(),
			},
			EffectPrototype = {
				[EffectTypeId]: effectVariance,
				[StreamTypeId]: effectVariance,
				[SinkTypeId]: {
					_A: _ => _,
					_In: _ => _,
					_L: _ => _,
					_E: _ => _,
					_R: _ => _,
				},
				[ChannelTypeId]: {
					_Env: _ => _,
					_InErr: _ => _,
					_InElem: _ => _,
					_InDone: _ => _,
					_OutErr: _ => _,
					_OutElem: _ => _,
					_OutDone: _ => _,
				},
				[Equal_symbol](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))
				},
				[Equal_symbol](that) {
					const selfKeys = Object.keys(this),
						thatKeys = Object.keys(that)
					if (selfKeys.length !== thatKeys.length) return !1
					for (const key of selfKeys)
						if (!(key in that) || !equals(this[key], that[key])) return !1
					return !0
				},
			},
			CommitPrototype = { ...EffectPrototype, _op: "Commit" },
			StructuralCommitPrototype = {
				...CommitPrototype,
				...StructuralPrototype,
			},
			effectable_Base = (function () {
				function Base() {}
				Base.prototype = CommitPrototype
				return Base
			})(),
			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",
				[Equal_symbol](that) {
					return (
						isOption(that) && isSome(that) && equals(this.value, that.value)
					)
				},
				[symbol]() {
					return cached(
						this,
						combine(Hash_hash(this._tag))(Hash_hash(this.value)),
					)
				},
				toJSON() {
					return { _id: "Option", _tag: this._tag, value: toJSON(this.value) }
				},
			}),
			NoneHash = Hash_hash("None"),
			NoneProto = Object.assign(Object.create(CommonProto), {
				_tag: "None",
				_op: "None",
				[Equal_symbol]: that => isOption(that) && isNone(that),
				[symbol]: () => NoneHash,
				toJSON() {
					return { _id: "Option", _tag: this._tag }
				},
			}),
			isOption = input => hasProperty(input, TypeId),
			isNone = fa => "None" === fa._tag,
			isSome = fa => "Some" === fa._tag,
			none = Object.create(NoneProto),
			option_some = value => {
				const a = Object.create(SomeProto)
				a.value = value
				return a
			},
			TagTypeId = Symbol.for("effect/Context/Tag"),
			ReferenceTypeId = Symbol.for("effect/Context/Reference"),
			STMTypeId = Symbol.for("effect/STM"),
			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 => self,
				context(self) {
					return make(this, self)
				},
			},
			ReferenceProto = { ...TagProto, [ReferenceTypeId]: ReferenceTypeId },
			context_TypeId = Symbol.for("effect/Context"),
			ContextProto = {
				[context_TypeId]: { _Services: _ => _ },
				[Equal_symbol](that) {
					if (isContext(that) && this.unsafeMap.size === that.unsafeMap.size) {
						for (const 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, number(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 => {
				const context = Object.create(ContextProto)
				context.unsafeMap = unsafeMap
				return context
			},
			isContext = u => hasProperty(u, context_TypeId),
			_empty = makeContext(new Map()),
			make = (tag, service) => makeContext(new Map([[tag.key, service]])),
			add = dual(3, (self, tag, service) => {
				const map = new Map(self.unsafeMap)
				map.set(tag.key, service)
				return makeContext(map)
			}),
			defaultValueCache = globalValue(
				"effect/Context/defaultValueCache",
				() => new Map(),
			),
			getDefaultValue = tag => {
				if (defaultValueCache.has(tag.key))
					return defaultValueCache.get(tag.key)
				const value = tag.defaultValue()
				defaultValueCache.set(tag.key, value)
				return value
			},
			unsafeGet = dual(2, (self, tag) => {
				if (!self.unsafeMap.has(tag.key)) {
					if (ReferenceTypeId in tag) return getDefaultValue(tag)
					throw (tag => {
						const error = new Error(
							"Service not found" + (tag.key ? `: ${String(tag.key)}` : ""),
						)
						if (tag.stack) {
							const lines = tag.stack.split("\n")
							if (lines.length > 2) {
								const afterAt = lines[2].match(/at (.*)/)
								afterAt &&
									(error.message =
										error.message + ` (defined at ${afterAt[1]})`)
							}
						}
						if (error.stack) {
							const lines = error.stack.split("\n")
							lines.splice(1, 3)
							error.stack = lines.join("\n")
						}
						return error
					})(tag)
				}
				return self.unsafeMap.get(tag.key)
			}),
			get = unsafeGet,
			getOption = dual(2, (self, tag) =>
				self.unsafeMap.has(tag.key)
					? option_some(self.unsafeMap.get(tag.key))
					: (u => hasProperty(u, ReferenceTypeId))(tag)
						? option_some(getDefaultValue(tag))
						: none,
			),
			merge = dual(2, (self, that) => {
				const map = new Map(self.unsafeMap)
				for (const [tag, s] of that.unsafeMap) map.set(tag, s)
				return makeContext(map)
			}),
			GenericTag = key => {
				const limit = Error.stackTraceLimit
				Error.stackTraceLimit = 2
				const creationError = new Error()
				Error.stackTraceLimit = limit
				const tag = Object.create(TagProto)
				Object.defineProperty(tag, "stack", { get: () => creationError.stack })
				tag.key = key
				return tag
			},
			Context_isContext = isContext,
			Context_empty = () => _empty,
			Context_make = make,
			Context_add = add,
			Context_get = get,
			Context_unsafeGet = unsafeGet,
			Context_getOption = getOption,
			Context_merge = merge,
			Context_Reference = () => (id, options) => {
				const limit = Error.stackTraceLimit
				Error.stackTraceLimit = 2
				const creationError = new Error()
				Error.stackTraceLimit = limit
				function ReferenceClass() {}
				Object.setPrototypeOf(ReferenceClass, ReferenceProto)
				ReferenceClass.key = id
				ReferenceClass.defaultValue = options.defaultValue
				Object.defineProperty(ReferenceClass, "stack", {
					get: () => creationError.stack,
				})
				return ReferenceClass
			},
			either_TypeId = Symbol.for("effect/Either"),
			either_CommonProto = {
				...EffectPrototype,
				[either_TypeId]: { _R: _ => _ },
				[NodeInspectSymbol]() {
					return this.toJSON()
				},
				toString() {
					return format(this.toJSON())
				},
			},
			RightProto = Object.assign(Object.create(either_CommonProto), {
				_tag: "Right",
				_op: "Right",
				[Equal_symbol](that) {
					return (
						isEither(that) && isRight(that) && equals(this.right, that.right)
					)
				},
				[symbol]() {
					return combine(Hash_hash(this._tag))(Hash_hash(this.right))
				},
				toJSON() {
					return { _id: "Either", _tag: this._tag, right: toJSON(this.right) }
				},
			}),
			LeftProto = Object.assign(Object.create(either_CommonProto), {
				_tag: "Left",
				_op: "Left",
				[Equal_symbol](that) {
					return isEither(that) && isLeft(that) && equals(this.left, that.left)
				},
				[symbol]() {
					return combine(Hash_hash(this._tag))(Hash_hash(this.left))
				},
				toJSON() {
					return { _id: "Either", _tag: this._tag, left: toJSON(this.left) }
				},
			}),
			isEither = input => hasProperty(input, either_TypeId),
			isLeft = ma => "Left" === ma._tag,
			isRight = ma => "Right" === ma._tag,
			Either_right = right => {
				const a = Object.create(RightProto)
				a.right = right
				return a
			},
			Either_left = left => {
				const a = Object.create(LeftProto)
				a.left = left
				return a
			},
			Either_isEither = isEither,
			Either_isLeft = isLeft,
			Either_isRight = isRight,
			mapLeft = dual(2, (self, f) =>
				Either_isLeft(self)
					? Either_left(f(self.left))
					: Either_right(self.right),
			),
			map = dual(2, (self, f) =>
				Either_isRight(self)
					? Either_right(f(self.right))
					: Either_left(self.left),
			),
			match = dual(2, (self, { onLeft, onRight }) =>
				Either_isLeft(self) ? onLeft(self.left) : onRight(self.right),
			),
			Either_merge = match({ onLeft: identity, onRight: identity }),
			getOrThrowWith = dual(2, (self, onLeft) => {
				if (Either_isRight(self)) return self.right
				throw onLeft(self.left)
			}),
			getOrThrow = getOrThrowWith(
				() => new Error("getOrThrow called on a Left"),
			),
			Equivalence_make = isEquivalent => (self, that) =>
				self === that || isEquivalent(self, that),
			isStrictEquivalent = (x, y) => x === y,
			strict = () => isStrictEquivalent,
			Equivalence_string = strict(),
			Equivalence_mapInput = dual(2, (self, f) =>
				Equivalence_make((x, y) => self(f(x), f(y))),
			),
			isNonEmptyArray = self => self.length > 0,
			Option_none = () => none,
			Option_some = option_some,
			Option_isNone = isNone,
			Option_isSome = isSome,
			Option_match = dual(2, (self, { onNone, onSome }) =>
				Option_isNone(self) ? onNone() : onSome(self.value),
			),
			Option_getOrElse = dual(2, (self, onNone) =>
				Option_isNone(self) ? onNone() : self.value,
			),
			Option_orElse = dual(2, (self, that) =>
				Option_isNone(self) ? that() : self,
			),
			orElseSome = dual(2, (self, onNone) =>
				Option_isNone(self) ? Option_some(onNone()) : self,
			),
			Option_fromNullable = nullableValue =>
				null == nullableValue ? Option_none() : Option_some(nullableValue),
			Option_getOrUndefined = Option_getOrElse(constUndefined),
			Option_getOrThrow = dual(2, (self, onNone) => {
				if (Option_isSome(self)) return self.value
				throw onNone()
			})(() => new Error("getOrThrow called on a None")),
			Option_map = dual(2, (self, f) =>
				Option_isNone(self) ? Option_none() : Option_some(f(self.value)),
			),
			Option_flatMap = dual(2, (self, f) =>
				Option_isNone(self) ? Option_none() : f(self.value),
			),
			flatMapNullable = dual(2, (self, f) =>
				Option_isNone(self)
					? Option_none()
					: Option_fromNullable(f(self.value)),
			),
			filterMap = Option_flatMap,
			filter = dual(2, (self, predicate) =>
				filterMap(self, b => (predicate(b) ? option_some(b) : none)),
			),
			Option_liftPredicate = dual(2, (b, predicate) =>
				predicate(b) ? Option_some(b) : Option_none(),
			),
			containsWith = isEquivalent =>
				dual(
					2,
					(self, a) => !Option_isNone(self) && isEquivalent(self.value, a),
				),
			contains = containsWith(equivalence()),
			exists = dual(
				2,
				(self, refinement) => !Option_isNone(self) && refinement(self.value),
			),
			mergeWith = f => (o1, o2) =>
				Option_isNone(o1)
					? o2
					: Option_isNone(o2)
						? o1
						: Option_some(f(o1.value, o2.value)),
			findFirst = dual(2, (self, f) => {
				let i = 0
				for (const a of self) {
					const o = f(a, i)
					if (isBoolean(o)) {
						if (o) return Option_some(a)
					} else if (Option_isSome(o)) return o
					i++
				}
				return Option_none()
			})
		Symbol.iterator
		const Order_make = compare => (self, that) =>
				self === that ? 0 : compare(self, that),
			Order_number = Order_make((self, that) => (self < that ? -1 : 1)),
			Order_boolean = Order_make((self, that) => (self < that ? -1 : 1)),
			Order_mapInput = dual(2, (self, f) =>
				Order_make((b1, b2) => self(f(b1), f(b2))),
			),
			greaterThan = O => dual(2, (self, that) => 1 === O(self, that)),
			greaterThanOrEqualTo = O => dual(2, (self, that) => -1 !== O(self, that)),
			clamp = O =>
				dual(2, (self, options) =>
					(O =>
						dual(2, (self, that) =>
							self === that || O(self, that) < 1 ? self : that,
						))(O)(
						options.maximum,
						(O =>
							dual(2, (self, that) =>
								self === that || O(self, that) > -1 ? self : that,
							))(O)(options.minimum, self),
					),
				)
		Object.fromEntries
		const Tuple_make = (...elements) => elements,
			getFirst = self => self[0],
			getSecond = self => self[1],
			Tuple_mapBoth = dual(2, (self, { onFirst, onSecond }) => [
				onFirst(self[0]),
				onSecond(self[1]),
			]),
			mapFirst = dual(2, (self, f) => [f(self[0]), self[1]]),
			mapSecond = dual(2, (self, f) => [self[0], f(self[1])]),
			allocate = n => new Array(n),
			Array_makeBy = dual(2, (n, f) => {
				const max = Math.max(1, Math.floor(n)),
					out = new Array(max)
				for (let i = 0; i < max; i++) out[i] = f(i)
				return out
			}),
			Array_fromIterable = collection =>
				Array.isArray(collection) ? collection : Array.from(collection),
			matchLeft = dual(2, (self, { onEmpty, onNonEmpty }) =>
				isNonEmptyReadonlyArray(self)
					? onNonEmpty(headNonEmpty(self), tailNonEmpty(self))
					: onEmpty(),
			),
			matchRight = dual(2, (self, { onEmpty, onNonEmpty }) =>
				isNonEmptyReadonlyArray(self)
					? onNonEmpty(initNonEmpty(self), lastNonEmpty(self))
					: onEmpty(),
			),
			Array_prepend = dual(2, (self, head) => [head, ...self]),
			Array_append = dual(2, (self, last) => [...self, last]),
			Array_appendAll = dual(2, (self, that) =>
				Array_fromIterable(self).concat(Array_fromIterable(that)),
			),
			isArray = Array.isArray,
			Array_isNonEmptyArray = isNonEmptyArray,
			isNonEmptyReadonlyArray = isNonEmptyArray,
			isOutOfBounds = (i, as) => i < 0 || i >= as.length,
			Array_clamp = (i, as) => Math.floor(Math.min(Math.max(0, i), as.length)),
			Array_get = dual(2, (self, index) => {
				const i = Math.floor(index)
				return isOutOfBounds(i, self) ? Option_none() : Option_some(self[i])
			}),
			Array_unsafeGet = dual(2, (self, index) => {
				const i = Math.floor(index)
				if (isOutOfBounds(i, self)) throw new Error(`Index ${i} out of bounds`)
				return self[i]
			}),
			Array_head = Array_get(0),
			headNonEmpty = Array_unsafeGet(0),
			lastNonEmpty = self => self[self.length - 1],
			tailNonEmpty = self => self.slice(1),
			initNonEmpty = self => self.slice(0, -1),
			Array_take = dual(2, (self, n) => {
				const input = Array_fromIterable(self)
				return input.slice(0, Array_clamp(n, input))
			}),
			span = dual(2, (self, predicate) =>
				splitAt(
					self,
					((self, predicate) => {
						let i = 0
						for (const a of self) {
							if (!predicate(a, i)) break
							i++
						}
						return i
					})(self, predicate),
				),
			),
			Array_drop = dual(2, (self, n) => {
				const input = Array_fromIterable(self)
				return input.slice(Array_clamp(n, input), input.length)
			}),
			findFirstIndex = dual(2, (self, predicate) => {
				let i = 0
				for (const a of self) {
					if (predicate(a, i)) return Option_some(i)
					i++
				}
				return Option_none()
			}),
			Array_findFirst = findFirst,
			Array_findLast = dual(2, (self, f) => {
				const input = Array_fromIterable(self)
				for (let i = input.length - 1; i >= 0; i--) {
					const a = input[i],
						o = f(a, i)
					if (isBoolean(o)) {
						if (o) return Option_some(a)
					} else if (Option_isSome(o)) return o
				}
				return Option_none()
			}),
			Array_replace = dual(3, (self, i, b) => Array_modify(self, i, () => b)),
			Array_modify = dual(3, (self, i, f) => {
				const out = Array.from(self)
				if (isOutOfBounds(i, out)) return out
				const b = f(out[i])
				out[i] = b
				return out
			}),
			Array_remove = dual(2, (self, i) => {
				const out = Array.from(self)
				if (isOutOfBounds(i, out)) return out
				out.splice(i, 1)
				return out
			}),
			Array_reverse = self => Array.from(self).reverse(),
			sort = dual(2, (self, O) => {
				const out = Array.from(self)
				out.sort(O)
				return out
			}),
			Array_zip = dual(2, (self, that) =>
				Array_zipWith(self, that, Tuple_make),
			),
			Array_zipWith = dual(3, (self, that, f) => {
				const as = Array_fromIterable(self),
					bs = Array_fromIterable(that)
				if (isNonEmptyReadonlyArray(as) && isNonEmptyReadonlyArray(bs)) {
					const 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 []
			}),
			Array_containsWith = isEquivalent =>
				dual(2, (self, a) => {
					for (const i of self) if (isEquivalent(a, i)) return !0
					return !1
				}),
			Array_equivalence = equivalence(),
			splitAt = dual(2, (self, n) => {
				const input = Array.from(self),
					_n = Math.floor(n)
				return isNonEmptyReadonlyArray(input)
					? _n >= 1
						? splitNonEmptyAt(input, _n)
						: [[], input]
					: [input, []]
			}),
			splitNonEmptyAt = dual(2, (self, n) => {
				const _n = Math.max(1, Math.floor(n))
				return _n >= self.length
					? [copy(self), []]
					: [
							Array_prepend(self.slice(1, _n), headNonEmpty(self)),
							self.slice(_n),
						]
			}),
			copy = self => self.slice(),
			unionWith = dual(3, (self, that, isEquivalent) => {
				const a = Array_fromIterable(self),
					b = Array_fromIterable(that)
				return isNonEmptyReadonlyArray(a)
					? isNonEmptyReadonlyArray(b)
						? dedupeWith(isEquivalent)(Array_appendAll(a, b))
						: a
					: b
			}),
			Array_union = dual(2, (self, that) =>
				unionWith(self, that, Array_equivalence),
			),
			Array_empty = () => [],
			Array_of = a => [a],
			Array_map = dual(2, (self, f) => self.map(f)),
			Array_flatMap = dual(2, (self, f) => {
				if ((self => 0 === self.length)(self)) return []
				const out = []
				for (let i = 0; i < self.length; i++) {
					const inner = f(self[i], i)
					for (let j = 0; j < inner.length; j++) out.push(inner[j])
				}
				return out
			}),
			Array_flatten = Array_flatMap(identity),
			Array_filterMap = dual(2, (self, f) => {
				const as = Array_fromIterable(self),
					out = []
				for (let i = 0; i < as.length; i++) {
					const o = f(as[i], i)
					Option_isSome(o) && out.push(o.value)
				}
				return out
			}),
			Array_getSomes = Array_filterMap(identity),
			Array_filter = dual(2, (self, predicate) => {
				const as = Array_fromIterable(self),
					out = []
				for (let i = 0; i < as.length; i++)
					predicate(as[i], i) && out.push(as[i])
				return out
			}),
			Array_reduce = dual(3, (self, b, f) =>
				Array_fromIterable(self).reduce((b, a, i) => f(b, a, i), b),
			),
			Array_some = dual(2, (self, predicate) => self.some(predicate)),
			Array_unfold = (b, f) => {
				const out = []
				let o,
					next = b
				for (; Option_isSome((o = f(next)));) {
					const [a, b] = o.value
					out.push(a)
					next = b
				}
				return out
			},
			Array_getEquivalence = item =>
				Equivalence_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
				}),
			dedupeWith = dual(2, (self, isEquivalent) => {
				const input = Array_fromIterable(self)
				if (isNonEmptyReadonlyArray(input)) {
					const out = [headNonEmpty(input)],
						rest = tailNonEmpty(input)
					for (const r of rest)
						out.every(a => !isEquivalent(r, a)) && out.push(r)
					return out
				}
				return []
			}),
			dedupe = self => dedupeWith(self, equivalence()),
			join = dual(2, (self, sep) => Array_fromIterable(self).join(sep)),
			mapAccum = dual(3, (self, s, f) => {
				let i = 0,
					s1 = s
				const out = []
				for (const a of self) {
					const r = f(s1, a, i)
					s1 = r[0]
					out.push(r[1])
					i++
				}
				return [s1, out]
			}),
			Chunk_TypeId = Symbol.for("effect/Chunk"),
			emptyArray = [],
			Chunk_getEquivalence = isEquivalent =>
				Equivalence_make(
					(self, that) =>
						self.length === that.length &&
						toReadonlyArray(self).every((value, i) =>
							isEquivalent(value, Chunk_unsafeGet(that, i)),
						),
				),
			Chunk_equivalence = Chunk_getEquivalence(equals),
			ChunkProto = {
				[Chunk_TypeId]: { _A: _ => _ },
				toString() {
					return format(this.toJSON())
				},
				toJSON() {
					return { _id: "Chunk", values: toReadonlyArray(this).map(toJSON) }
				},
				[NodeInspectSymbol]() {
					return this.toJSON()
				},
				[Equal_symbol](that) {
					return isChunk(that) && Chunk_equivalence(this, that)
				},
				[symbol]() {
					return cached(this, array(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 => {
				const chunk = Object.create(ChunkProto)
				chunk.backing = backing
				switch (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 = Chunk_empty
						chunk.right = Chunk_empty
						break
					case "ISingleton":
						chunk.length = 1
						chunk.depth = 0
						chunk.left = Chunk_empty
						chunk.right = Chunk_empty
						break
					case "ISlice":
						chunk.length = backing.length
						chunk.depth = backing.chunk.depth + 1
						chunk.left = Chunk_empty
						chunk.right = Chunk_empty
				}
				return chunk
			},
			isChunk = u => hasProperty(u, Chunk_TypeId),
			Chunk_empty = makeChunk({ _tag: "IEmpty" }),
			esm_Chunk_empty = () => Chunk_empty,
			Chunk_make = (...as) => unsafeFromNonEmptyArray(as),
			Chunk_of = a => makeChunk({ _tag: "ISingleton", a }),
			Chunk_fromIterable = self =>
				isChunk(self) ? self : unsafeFromArray(Array_fromIterable(self)),
			copyToArray = (self, array, initial) => {
				switch (self.backing._tag) {
					case "IArray":
						!(function (src, srcPos, dest, destPos, len) {
							for (let i = 0; i < Math.min(src.length, 0 + len); i++)
								dest[destPos + i - 0] = src[i]
						})(self.backing.array, 0, array, initial, self.length)
						break
					case "IConcat":
						copyToArray(self.left, array, initial)
						copyToArray(self.right, array, initial + self.left.length)
						break
					case "ISingleton":
						array[initial] = self.backing.a
						break
					case "ISlice": {
						let i = 0,
							j = initial
						for (; i < self.length;) {
							array[j] = Chunk_unsafeGet(self, i)
							i += 1
							j += 1
						}
						break
					}
				}
			},
			toReadonlyArray = self => {
				switch (self.backing._tag) {
					case "IEmpty":
						return emptyArray
					case "IArray":
						return self.backing.array
					default: {
						const arr = new Array(self.length)
						copyToArray(self, arr, 0)
						self.backing = { _tag: "IArray", array: arr }
						self.left = Chunk_empty
						self.right = Chunk_empty
						self.depth = 0
						return arr
					}
				}
			},
			Chunk_reverse = self => {
				switch (self.backing._tag) {
					case "IEmpty":
					case "ISingleton":
						return self
					case "IArray":
						return makeChunk({
							_tag: "IArray",
							array: Array_reverse(self.backing.array),
						})
					case "IConcat":
						return makeChunk({
							_tag: "IConcat",
							left: Chunk_reverse(self.backing.right),
							right: Chunk_reverse(self.backing.left),
						})
					case "ISlice":
						return unsafeFromArray(Array_reverse(toReadonlyArray(self)))
				}
			},
			Chunk_get = dual(2, (self, index) =>
				index < 0 || index >= self.length
					? Option_none()
					: Option_some(Chunk_unsafeGet(self, index)),
			),
			unsafeFromArray = self =>
				0 === self.length
					? esm_Chunk_empty()
					: 1 === self.length
						? Chunk_of(self[0])
						: makeChunk({ _tag: "IArray", array: self }),
			unsafeFromNonEmptyArray = self => unsafeFromArray(self),
			Chunk_unsafeGet = dual(2, (self, index) => {
				switch (self.backing._tag) {
					case "IEmpty":
						throw new Error("Index out of bounds")
					case "ISingleton":
						if (0 !== index) 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
							? Chunk_unsafeGet(self.left, index)
							: Chunk_unsafeGet(self.right, index - self.left.length)
					case "ISlice":
						return Chunk_unsafeGet(
							self.backing.chunk,
							index + self.backing.offset,
						)
				}
			}),
			Chunk_append = dual(2, (self, a) => Chunk_appendAll(self, Chunk_of(a))),
			Chunk_prepend = dual(2, (self, elem) =>
				Chunk_appendAll(Chunk_of(elem), self),
			),
			Chunk_take = dual(2, (self, n) => {
				if (n <= 0) return Chunk_empty
				if (n >= self.length) return self
				switch (self.backing._tag) {
					case "ISlice":
						return makeChunk({
							_tag: "ISlice",
							chunk: self.backing.chunk,
							length: n,
							offset: self.backing.offset,
						})
					case "IConcat":
						return n > self.left.length
							? makeChunk({
									_tag: "IConcat",
									left: self.left,
									right: Chunk_take(self.right, n - self.left.length),
								})
							: Chunk_take(self.left, n)
					default:
						return makeChunk({
							_tag: "ISlice",
							chunk: self,
							offset: 0,
							length: n,
						})
				}
			}),
			Chunk_drop = dual(2, (self, n) => {
				if (n <= 0) return self
				if (n >= self.length) return Chunk_empty
				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":
						return n > self.left.length
							? Chunk_drop(self.right, n - self.left.length)
							: makeChunk({
									_tag: "IConcat",
									left: Chunk_drop(self.left, n),
									right: self.right,
								})
					default:
						return makeChunk({
							_tag: "ISlice",
							chunk: self,
							offset: n,
							length: self.length - n,
						})
				}
			}),
			Chunk_appendAll = dual(2, (self, that) => {
				if ("IEmpty" === self.backing._tag) return that
				if ("IEmpty" === that.backing._tag) return self
				const diff = that.depth - self.depth
				if (Math.abs(diff) <= 1)
					return makeChunk({ _tag: "IConcat", left: self, right: that })
				if (diff < -1) {
					if (self.left.depth >= self.right.depth) {
						const nr = Chunk_appendAll(self.right, that)
						return makeChunk({ _tag: "IConcat", left: self.left, right: nr })
					}
					{
						const nrr = Chunk_appendAll(self.right.right, that)
						if (nrr.depth === self.depth - 3) {
							const nr = makeChunk({
								_tag: "IConcat",
								left: self.right.left,
								right: nrr,
							})
							return makeChunk({ _tag: "IConcat", left: self.left, right: nr })
						}
						{
							const nl = makeChunk({
								_tag: "IConcat",
								left: self.left,
								right: self.right.left,
							})
							return makeChunk({ _tag: "IConcat", left: nl, right: nrr })
						}
					}
				}
				if (that.right.depth >= that.left.depth) {
					const nl = Chunk_appendAll(self, that.left)
					return makeChunk({ _tag: "IConcat", left: nl, right: that.right })
				}
				{
					const nll = Chunk_appendAll(self, that.left.left)
					if (nll.depth === that.depth - 3) {
						const nl = makeChunk({
							_tag: "IConcat",
							left: nll,
							right: that.left.right,
						})
						return makeChunk({ _tag: "IConcat", left: nl, right: that.right })
					}
					{
						const nr = makeChunk({
							_tag: "IConcat",
							left: that.left.right,
							right: that.right,
						})
						return makeChunk({ _tag: "IConcat", left: nll, right: nr })
					}
				}
			}),
			Chunk_filterMap = dual(2, (self, f) =>
				unsafeFromArray(Array_filterMap(self, f)),
			),
			Chunk_filter = dual(2, (self, predicate) =>
				unsafeFromArray(Array_filter(self, predicate)),
			),
			Chunk_isEmpty = self => 0 === self.length,
			isNonEmpty = self => self.length > 0,
			Chunk_head = Chunk_get(0),
			Chunk_unsafeHead = self => Chunk_unsafeGet(self, 0),
			Chunk_headNonEmpty = Chunk_unsafeHead,
			Chunk_map = dual(2, (self, f) =>
				"ISingleton" === self.backing._tag
					? Chunk_of(f(self.backing.a, 0))
					: unsafeFromArray(
							pipe(
								toReadonlyArray(self),
								Array_map((a, i) => f(a, i)),
							),
						),
			),
			Chunk_mapAccum = dual(3, (self, s, f) => {
				const [s1, as] = mapAccum(self, s, f)
				return [s1, unsafeFromArray(as)]
			}),
			Chunk_splitAt = dual(2, (self, n) => [
				Chunk_take(self, n),
				Chunk_drop(self, n),
			]),
			Chunk_splitWhere = dual(2, (self, predicate) => {
				let i = 0
				for (const a of toReadonlyArray(self)) {
					if (predicate(a)) break
					i++
				}
				return Chunk_splitAt(self, i)
			}),
			Chunk_tailNonEmpty = self => Chunk_drop(self, 1),
			Chunk_reduce = Array_reduce,
			Duration_TypeId = Symbol.for("effect/Duration"),
			bigint0 = BigInt(0),
			bigint24 = BigInt(24),
			bigint60 = BigInt(60),
			bigint1e3 = BigInt(1e3),
			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
				if (isNumber(input)) return Duration_millis(input)
				if (isBigInt(input)) return Duration_nanos(input)
				if (Array.isArray(input) && 2 === input.length && input.every(isNumber))
					return input[0] === -1 / 0 ||
						input[1] === -1 / 0 ||
						Number.isNaN(input[0]) ||
						Number.isNaN(input[1])
						? zero
						: input[0] === 1 / 0 || input[1] === 1 / 0
							? infinity
							: Duration_nanos(
									BigInt(Math.round(1e9 * input[0])) +
										BigInt(Math.round(input[1])),
								)
				if (isString(input)) {
					const match = DURATION_REGEX.exec(input)
					if (match) {
						const [_, valueStr, unit] = match,
							value = Number(valueStr)
						switch (unit) {
							case "nano":
							case "nanos":
								return Duration_nanos(BigInt(valueStr))
							case "micro":
							case "micros":
								return micros(BigInt(valueStr))
							case "milli":
							case "millis":
								return Duration_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")
			},
			zeroValue = { _tag: "Millis", millis: 0 },
			infinityValue = { _tag: "Infinity" },
			DurationProto = {
				[Duration_TypeId]: Duration_TypeId,
				[symbol]() {
					return cached(this, structure(this.value))
				},
				[Equal_symbol](that) {
					return isDuration(that) && Duration_equals(this, that)
				},
				toString() {
					return `Duration(${Duration_format(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)
				},
			},
			Duration_make = input => {
				const duration = Object.create(DurationProto)
				isNumber(input)
					? isNaN(input) || input <= 0
						? (duration.value = zeroValue)
						: Number.isFinite(input)
							? Number.isInteger(input)
								? (duration.value = { _tag: "Millis", millis: input })
								: (duration.value = {
										_tag: "Nanos",
										nanos: BigInt(Math.round(1e6 * input)),
									})
							: (duration.value = infinityValue)
					: (duration.value =
							input <= bigint0 ? zeroValue : { _tag: "Nanos", nanos: input })
				return duration
			},
			isDuration = u => hasProperty(u, Duration_TypeId),
			zero = Duration_make(0),
			infinity = Duration_make(1 / 0),
			Duration_nanos = nanos => Duration_make(nanos),
			micros = micros => Duration_make(micros * bigint1e3),
			Duration_millis = millis => Duration_make(millis),
			seconds = seconds => Duration_make(1e3 * seconds),
			minutes = minutes => Duration_make(6e4 * minutes),
			hours = hours => Duration_make(36e5 * hours),
			days = days => Duration_make(864e5 * days),
			weeks = weeks => Duration_make(6048e5 * weeks),
			toMillis = self =>
				Duration_match(self, {
					onMillis: millis => millis,
					onNanos: nanos => Number(nanos) / 1e6,
				}),
			toHrTime = self => {
				const _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 / 1e3),
							Math.round((_self.value.millis % 1e3) * 1e6),
						]
				}
			},
			Duration_match = dual(2, (self, options) => {
				const _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) => {
				const _self = decode(self),
					_that = decode(that)
				if ("Infinity" === _self.value._tag || "Infinity" === _that.value._tag)
					return options.onMillis(toMillis(_self), toMillis(_that))
				if ("Nanos" === _self.value._tag || "Nanos" === _that.value._tag) {
					const selfNanos =
							"Nanos" === _self.value._tag
								? _self.value.nanos
								: BigInt(Math.round(1e6 * _self.value.millis)),
						thatNanos =
							"Nanos" === _that.value._tag
								? _that.value.nanos
								: BigInt(Math.round(1e6 * _that.value.millis))
					return options.onNanos(selfNanos, thatNanos)
				}
				return options.onMillis(_self.value.millis, _that.value.millis)
			}),
			Duration_lessThanOrEqualTo = dual(2, (self, that) =>
				matchWith(self, that, {
					onMillis: (self, that) => self <= that,
					onNanos: (self, that) => self <= that,
				}),
			),
			Duration_greaterThanOrEqualTo = dual(2, (self, that) =>
				matchWith(self, that, {
					onMillis: (self, that) => self >= that,
					onNanos: (self, that) => self >= that,
				}),
			),
			Duration_equals = dual(2, (self, that) =>
				((self, that) =>
					matchWith(self, that, {
						onMillis: (self, that) => self === that,
						onNanos: (self, that) => self === that,
					}))(decode(self), decode(that)),
			),
			Duration_format = self => {
				const duration = decode(self)
				if ("Infinity" === duration.value._tag) return "Infinity"
				if (
					(self => {
						switch (self.value._tag) {
							case "Millis":
								return 0 === self.value.millis
							case "Nanos":
								return self.value.nanos === bigint0
							case "Infinity":
								return !1
						}
					})(duration)
				)
					return "0"
				const fragments = (self => {
						const duration = decode(self)
						if ("Infinity" === duration.value._tag)
							return {
								days: 1 / 0,
								hours: 1 / 0,
								minutes: 1 / 0,
								seconds: 1 / 0,
								millis: 1 / 0,
								nanos: 1 / 0,
							}
						const nanos = (self => {
								const _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(1e6 * _self.value.millis))
								}
							})(duration),
							ms = nanos / bigint1e6,
							sec = ms / bigint1e3,
							min = sec / bigint60,
							hr = min / bigint60
						return {
							days: Number(hr / bigint24),
							hours: Number(hr % bigint24),
							minutes: Number(min % bigint60),
							seconds: Number(sec % bigint60),
							millis: Number(ms % bigint1e3),
							nanos: Number(nanos % bigint1e6),
						}
					})(duration),
					pieces = []
				0 !== fragments.days && pieces.push(`${fragments.days}d`)
				0 !== fragments.hours && pieces.push(`${fragments.hours}h`)
				0 !== fragments.minutes && pieces.push(`${fragments.minutes}m`)
				0 !== fragments.seconds && pieces.push(`${fragments.seconds}s`)
				0 !== fragments.millis && pieces.push(`${fragments.millis}ms`)
				0 !== fragments.nanos && pieces.push(`${fragments.nanos}ns`)
				return pieces.join(" ")
			},
			BUCKET_SIZE = Math.pow(2, 5),
			MASK = BUCKET_SIZE - 1,
			MAX_INDEX_NODE = BUCKET_SIZE / 2,
			MIN_ARRAY_NODE = BUCKET_SIZE / 4
		function hashFragment(shift, h) {
			return (h >>> shift) & MASK
		}
		function toBitmap(x) {
			return 1 << x
		}
		function fromBitmap(bitmap, bit) {
			return (function (x) {
				x =
					((x =
						(858993459 & (x -= (x >> 1) & 1431655765)) +
						((x >> 2) & 858993459)) +
						(x >> 4)) &
					252645135
				return 127 & ((x += x >> 8) + (x >> 16))
			})(bitmap & (bit - 1))
		}
		function arrayUpdate(mutate, at, v, arr) {
			let out = arr
			if (!mutate) {
				const len = arr.length
				out = new Array(len)
				for (let i = 0; i < len; ++i) out[i] = arr[i]
			}
			out[at] = v
			return out
		}
		function arraySpliceOut(mutate, at, arr) {
			const newLen = arr.length - 1
			let i = 0,
				g = 0,
				out = arr
			if (mutate) i = g = at
			else {
				out = new Array(newLen)
				for (; i < at;) out[g++] = arr[i++]
			}
			++i
			for (; i <= newLen;) out[g++] = arr[i++]
			mutate && (out.length = newLen)
			return out
		}
		class EmptyNode {
			_tag = "EmptyNode"
			modify(edit, _shift, f, hash, key, size) {
				const v = f(Option_none())
				if (Option_isNone(v)) return new EmptyNode()
				++size.value
				return new LeafNode(edit, hash, key, v)
			}
		}
		function isEmptyNode(a) {
			return isTagged(a, "EmptyNode")
		}
		function canEditNode(node, edit) {
			return !isEmptyNode(node) && edit === node.edit
		}
		class LeafNode {
			edit
			hash
			key
			value
			_tag = "LeafNode"
			constructor(edit, hash, key, value) {
				this.edit = edit
				this.hash = hash
				this.key = key
				this.value = value
			}
			modify(edit, shift, f, hash, key, size) {
				if (equals(key, this.key)) {
					const v = f(this.value)
					if (v === this.value) return this
					if (Option_isNone(v)) {
						--size.value
						return new EmptyNode()
					}
					if (canEditNode(this, edit)) {
						this.value = v
						return this
					}
					return new LeafNode(edit, hash, key, v)
				}
				const v = f(Option_none())
				if (Option_isNone(v)) return this
				++size.value
				return mergeLeaves(
					edit,
					shift,
					this.hash,
					this,
					hash,
					new LeafNode(edit, hash, key, v),
				)
			}
		}
		class CollisionNode {
			edit
			hash
			children
			_tag = "CollisionNode"
			constructor(edit, hash, children) {
				this.edit = edit
				this.hash = hash
				this.children = children
			}
			modify(edit, shift, f, hash, key, size) {
				if (hash === this.hash) {
					const canEdit = canEditNode(this, edit),
						list = this.updateCollisionList(
							canEdit,
							edit,
							this.hash,
							this.children,
							f,
							key,
							size,
						)
					return list === this.children
						? this
						: list.length > 1
							? new CollisionNode(edit, this.hash, list)
							: list[0]
				}
				const v = f(Option_none())
				if (Option_isNone(v)) return this
				++size.value
				return mergeLeaves(
					edit,
					shift,
					this.hash,
					this,
					hash,
					new LeafNode(edit, hash, key, v),
				)
			}
			updateCollisionList(mutate, edit, hash, list, f, key, size) {
				const len = list.length
				for (let i = 0; i < len; ++i) {
					const child = list[i]
					if ("key" in child && equals(key, child.key)) {
						const value = child.value,
							newValue = f(value)
						if (newValue === value) return list
						if (Option_isNone(newValue)) {
							--size.value
							return arraySpliceOut(mutate, i, list)
						}
						return arrayUpdate(
							mutate,
							i,
							new LeafNode(edit, hash, key, newValue),
							list,
						)
					}
				}
				const newValue = f(Option_none())
				if (Option_isNone(newValue)) return list
				++size.value
				return arrayUpdate(
					mutate,
					len,
					new LeafNode(edit, hash, 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, hash, key, size) {
				const mask = this.mask,
					children = this.children,
					frag = hashFragment(shift, hash),
					bit = toBitmap(frag),
					indx = fromBitmap(mask, bit),
					exists = mask & bit,
					canEdit = canEditNode(this, edit)
				if (!exists) {
					const _newChild = new EmptyNode().modify(
						edit,
						shift + 5,
						f,
						hash,
						key,
						size,
					)
					return _newChild
						? children.length >= MAX_INDEX_NODE
							? (function (edit, frag, child, bitmap, subNodes) {
									const arr = []
									let bit = bitmap,
										count = 0
									for (let i = 0; bit; ++i) {
										1 & bit && (arr[i] = subNodes[count++])
										bit >>>= 1
									}
									arr[frag] = child
									return new ArrayNode(edit, count + 1, arr)
								})(edit, frag, _newChild, mask, children)
							: new IndexedNode(
									edit,
									mask | bit,
									(function (mutate, at, v, arr) {
										const len = arr.length
										if (mutate) {
											let i = len
											for (; i >= at;) arr[i--] = arr[i]
											arr[at] = v
											return arr
										}
										let i = 0,
											g = 0
										const out = new Array(len + 1)
										for (; i < at;) out[g++] = arr[i++]
										out[at] = v
										for (; i < len;) out[++g] = arr[i++]
										return out
									})(canEdit, indx, _newChild, children),
								)
						: this
				}
				const current = children[indx],
					child = current.modify(edit, shift + 5, f, hash, key, size)
				if (current === child) return this
				let newChildren,
					bitmap = mask
				if (isEmptyNode(child)) {
					bitmap &= ~bit
					if (!bitmap) return new EmptyNode()
					if (
						children.length <= 2 &&
						(isEmptyNode((node = children[1 ^ indx])) ||
							"LeafNode" === node._tag ||
							"CollisionNode" === node._tag)
					)
						return children[1 ^ indx]
					newChildren = arraySpliceOut(canEdit, indx, children)
				} else newChildren = arrayUpdate(canEdit, indx, child, children)
				var node
				if (canEdit) {
					this.mask = bitmap
					this.children = newChildren
					return 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, hash, key, size) {
				let count = this.size
				const children = this.children,
					frag = hashFragment(shift, hash),
					child = children[frag],
					newChild = (child || new EmptyNode()).modify(
						edit,
						shift + 5,
						f,
						hash,
						key,
						size,
					)
				if (child === newChild) return this
				const canEdit = canEditNode(this, edit)
				let newChildren
				if (isEmptyNode(child) && !isEmptyNode(newChild)) {
					++count
					newChildren = arrayUpdate(canEdit, frag, newChild, children)
				} else if (!isEmptyNode(child) && isEmptyNode(newChild)) {
					--count
					if (count <= MIN_ARRAY_NODE)
						return (function (edit, count, removed, elements) {
							const children = new Array(count - 1)
							let g = 0,
								bitmap = 0
							for (let i = 0, len = elements.length; i < len; ++i)
								if (i !== removed) {
									const elem = elements[i]
									if (elem && !isEmptyNode(elem)) {
										children[g++] = elem
										bitmap |= 1 << i
									}
								}
							return new IndexedNode(edit, bitmap, children)
						})(edit, count, frag, children)
					newChildren = arrayUpdate(canEdit, frag, new EmptyNode(), children)
				} else newChildren = arrayUpdate(canEdit, frag, newChild, children)
				if (canEdit) {
					this.size = count
					this.children = newChildren
					return this
				}
				return new ArrayNode(edit, count, newChildren)
			}
		}
		function mergeLeavesInner(edit, shift, h1, n1, h2, n2) {
			if (h1 === h2) return new CollisionNode(edit, h1, [n2, n1])
			const subH1 = hashFragment(shift, h1),
				subH2 = hashFragment(shift, h2)
			if (subH1 === subH2)
				return child =>
					new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), [child])
			{
				const 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,
				currentShift = shift
			for (;;) {
				const res = mergeLeavesInner(edit, currentShift, h1, n1, h2, n2)
				if ("function" != typeof res) {
					let final = res
					for (; null != stack;) {
						final = stack.value(final)
						stack = stack.previous
					}
					return final
				}
				stack = { value: res, previous: stack }
				currentShift += 5
			}
		}
		const HashMapTypeId = Symbol.for("effect/HashMap"),
			HashMapProto = {
				[HashMapTypeId]: HashMapTypeId,
				[Symbol.iterator]() {
					return new HashMapIterator(this, (k, v) => [k, v])
				},
				[symbol]() {
					let hash = Hash_hash("effect/HashMap")
					for (const item of this)
						hash ^= pipe(Hash_hash(item[0]), combine(Hash_hash(item[1])))
					return cached(this, hash)
				},
				[Equal_symbol](that) {
					if (isHashMap(that)) {
						if (that._size !== this._size) return !1
						for (const item of this) {
							const elem = pipe(that, getHash(item[0], Hash_hash(item[0])))
							if (Option_isNone(elem)) return !1
							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) => {
				const map = Object.create(HashMapProto)
				map._editable = editable
				map._edit = edit
				map._root = root
				map._size = size
				return map
			}
		class HashMapIterator {
			map
			f
			v
			constructor(map, f) {
				this.map = map
				this.f = f
				this.v = visitLazy(this.map._root, this.f, void 0)
			}
			next() {
				if (Option_isNone(this.v)) return { done: !0, value: void 0 }
				const v0 = this.v.value
				this.v = applyCont(v0.cont)
				return { done: !1, value: v0.value }
			}
			[Symbol.iterator]() {
				return new HashMapIterator(this.map, this.f)
			}
		}
		const applyCont = cont =>
				cont
					? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4])
					: Option_none(),
			visitLazy = (node, f, cont = void 0) => {
				switch (node._tag) {
					case "LeafNode":
						return Option_isSome(node.value)
							? Option_some({ value: f(node.key, node.value.value), cont })
							: applyCont(cont)
					case "CollisionNode":
					case "ArrayNode":
					case "IndexedNode": {
						const children = node.children
						return visitLazyChildren(children.length, children, 0, f, cont)
					}
					default:
						return applyCont(cont)
				}
			},
			visitLazyChildren = (len, children, i, f, cont) => {
				for (; i < len;) {
					const child = children[i++]
					if (child && !isEmptyNode(child))
						return visitLazy(child, f, [len, children, i, f, cont])
				}
				return applyCont(cont)
			},
			hashMap_empty = makeImpl(!1, 0, new EmptyNode(), 0),
			internal_hashMap_empty = () => hashMap_empty,
			isHashMap = u => hasProperty(u, HashMapTypeId),
			hashMap_get = dual(2, (self, key) => getHash(self, key, Hash_hash(key))),
			getHash = dual(3, (self, key, hash) => {
				let node = self._root,
					shift = 0
				for (;;)
					switch (node._tag) {
						case "LeafNode":
							return equals(key, node.key) ? node.value : Option_none()
						case "CollisionNode":
							if (hash === node.hash) {
								const children = node.children
								for (let i = 0, len = children.length; i < len; ++i) {
									const child = children[i]
									if ("key" in child && equals(key, child.key))
										return child.value
								}
							}
							return Option_none()
						case "IndexedNode": {
							const bit = toBitmap(hashFragment(shift, hash))
							if (node.mask & bit) {
								node = node.children[fromBitmap(node.mask, bit)]
								shift += 5
								break
							}
							return Option_none()
						}
						case "ArrayNode":
							node = node.children[hashFragment(shift, hash)]
							if (node) {
								shift += 5
								break
							}
							return Option_none()
						default:
							return Option_none()
					}
			}),
			hashMap_has = dual(2, (self, key) =>
				Option_isSome(getHash(self, key, Hash_hash(key))),
			),
			hashMap_set = dual(3, (self, key, value) =>
				modifyAt(self, key, () => Option_some(value)),
			),
			setTree = dual(3, (self, newRoot, newSize) => {
				if (self._editable) {
					self._root = newRoot
					self._size = newSize
					return self
				}
				return newRoot === self._root
					? self
					: makeImpl(self._editable, self._edit, newRoot, newSize)
			}),
			hashMap_keys = self => new HashMapIterator(self, key => key),
			hashMap_size = self => self._size,
			beginMutation = self =>
				makeImpl(!0, self._edit + 1, self._root, self._size),
			modifyAt = dual(3, (self, key, f) =>
				modifyHash(self, key, Hash_hash(key), f),
			),
			modifyHash = dual(4, (self, key, hash, f) => {
				const size = { value: self._size },
					newRoot = self._root.modify(
						self._editable ? self._edit : NaN,
						0,
						f,
						hash,
						key,
						size,
					)
				return pipe(self, setTree(newRoot, size.value))
			}),
			hashMap_remove = dual(2, (self, key) => modifyAt(self, key, Option_none)),
			hashMap_map = dual(2, (self, f) =>
				hashMap_reduce(self, internal_hashMap_empty(), (map, value, key) =>
					hashMap_set(map, key, f(value, key)),
				),
			),
			hashMap_forEach = dual(2, (self, f) =>
				hashMap_reduce(self, void 0, (_, value, key) => f(value, key)),
			),
			hashMap_reduce = dual(3, (self, zero, f) => {
				const root = self._root
				if ("LeafNode" === root._tag)
					return Option_isSome(root.value)
						? f(zero, root.value.value, root.key)
						: zero
				if ("EmptyNode" === root._tag) return zero
				const toVisit = [root.children]
				let children
				for (; (children = toVisit.pop());)
					for (let i = 0, len = children.length; i < len;) {
						const child = children[i++]
						child &&
							!isEmptyNode(child) &&
							("LeafNode" === child._tag
								? Option_isSome(child.value) &&
									(zero = f(zero, child.value.value, child.key))
								: toVisit.push(child.children))
					}
				return zero
			}),
			HashSetTypeId = Symbol.for("effect/HashSet"),
			HashSetProto = {
				[HashSetTypeId]: HashSetTypeId,
				[Symbol.iterator]() {
					return hashMap_keys(this._keyMap)
				},
				[symbol]() {
					return cached(
						this,
						combine(Hash_hash(this._keyMap))(Hash_hash("effect/HashSet")),
					)
				},
				[Equal_symbol](that) {
					return (
						!!isHashSet(that) &&
						hashMap_size(this._keyMap) === hashMap_size(that._keyMap) &&
						equals(this._keyMap, that._keyMap)
					)
				},
				toString() {
					return format(this.toJSON())
				},
				toJSON() {
					return { _id: "HashSet", values: Array.from(this).map(toJSON) }
				},
				[NodeInspectSymbol]() {
					return this.toJSON()
				},
				pipe() {
					return pipeArguments(this, arguments)
				},
			},
			hashSet_makeImpl = keyMap => {
				const set = Object.create(HashSetProto)
				set._keyMap = keyMap
				return set
			},
			isHashSet = u => hasProperty(u, HashSetTypeId),
			hashSet_empty = hashSet_makeImpl(internal_hashMap_empty()),
			internal_hashSet_empty = () => hashSet_empty,
			hashSet_has = dual(2, (self, value) => hashMap_has(self._keyMap, value)),
			hashSet_beginMutation = self =>
				hashSet_makeImpl(beginMutation(self._keyMap)),
			hashSet_endMutation = self => {
				self._keyMap._editable = !1
				return self
			},
			hashSet_mutate = dual(2, (self, f) => {
				const transient = hashSet_beginMutation(self)
				f(transient)
				return hashSet_endMutation(transient)
			}),
			hashSet_add = dual(2, (self, value) =>
				self._keyMap._editable
					? (hashMap_set(value, !0)(self._keyMap), self)
					: hashSet_makeImpl(hashMap_set(value, !0)(self._keyMap)),
			),
			hashSet_remove = dual(2, (self, value) =>
				self._keyMap._editable
					? (hashMap_remove(value)(self._keyMap), self)
					: hashSet_makeImpl(hashMap_remove(value)(self._keyMap)),
			),
			hashSet_difference = dual(2, (self, that) =>
				hashSet_mutate(self, set => {
					for (const value of that) hashSet_remove(set, value)
				}),
			),
			hashSet_union = dual(2, (self, that) =>
				hashSet_mutate(internal_hashSet_empty(), set => {
					hashSet_forEach(self, value => hashSet_add(set, value))
					for (const value of that) hashSet_add(set, value)
				}),
			),
			hashSet_forEach = dual(2, (self, f) =>
				hashMap_forEach(self._keyMap, (_, k) => f(k)),
			),
			hashSet_reduce = dual(3, (self, zero, f) =>
				hashMap_reduce(self._keyMap, zero, (z, _, a) => f(z, a)),
			),
			HashSet_empty = internal_hashSet_empty,
			HashSet_make = (...elements) => {
				const set = hashSet_beginMutation(internal_hashSet_empty())
				for (const value of elements) hashSet_add(set, value)
				return hashSet_endMutation(set)
			},
			HashSet_has = hashSet_has,
			HashSet_size = self => hashMap_size(self._keyMap),
			HashSet_add = hashSet_add,
			HashSet_remove = hashSet_remove,
			HashSet_difference = hashSet_difference,
			HashSet_union = hashSet_union,
			HashSet_reduce = hashSet_reduce,
			MutableRef_TypeId = Symbol.for("effect/MutableRef"),
			MutableRefProto = {
				[MutableRef_TypeId]: MutableRef_TypeId,
				toString() {
					return format(this.toJSON())
				},
				toJSON() {
					return { _id: "MutableRef", current: toJSON(this.current) }
				},
				[NodeInspectSymbol]() {
					return this.toJSON()
				},
				pipe() {
					return pipeArguments(this, arguments)
				},
			},
			MutableRef_make = value => {
				const ref = Object.create(MutableRefProto)
				ref.current = value
				return ref
			},
			compareAndSet = dual(3, (self, oldValue, newValue) => {
				if (equals(oldValue, self.current)) {
					self.current = newValue
					return !0
				}
				return !1
			}),
			MutableRef_get = self => self.current,
			MutableRef_set = dual(2, (self, value) => {
				self.current = value
				return self
			}),
			FiberIdTypeId = Symbol.for("effect/FiberId"),
			emptyHash = string("effect/FiberId-None")
		class None {
			[FiberIdTypeId] = FiberIdTypeId
			_tag = "None"
			id = -1
			startTimeMillis = -1;
			[symbol]() {
				return emptyHash
			}
			[Equal_symbol](that) {
				return isFiberId(that) && "None" === that._tag
			}
			toString() {
				return format(this.toJSON())
			}
			toJSON() {
				return { _id: "FiberId", _tag: this._tag }
			}
			[NodeInspectSymbol]() {
				return this.toJSON()
			}
		}
		class Runtime {
			id
			startTimeMillis;
			[FiberIdTypeId] = FiberIdTypeId
			_tag = "Runtime"
			constructor(id, startTimeMillis) {
				this.id = id
				this.startTimeMillis = startTimeMillis
			}
			[symbol]() {
				return cached(
					this,
					string(
						`effect/FiberId-${this._tag}-${this.id}-${this.startTimeMillis}`,
					),
				)
			}
			[Equal_symbol](that) {
				return (
					isFiberId(that) &&
					"Runtime" === that._tag &&
					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 = "Composite"
			constructor(left, right) {
				this.left = left
				this.right = right
			}
			_hash;
			[symbol]() {
				return pipe(
					string(`effect/FiberId-${this._tag}`),
					combine(Hash_hash(this.left)),
					combine(Hash_hash(this.right)),
					cached(this),
				)
			}
			[Equal_symbol](that) {
				return (
					isFiberId(that) &&
					"Composite" === that._tag &&
					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()
			}
		}
		const fiberId_none = new None(),
			isFiberId = self => hasProperty(self, FiberIdTypeId),
			fiberId_combine = dual(2, (self, that) =>
				"None" === self._tag
					? that
					: "None" === that._tag
						? self
						: new Composite(self, that),
			),
			ids = self => {
				switch (self._tag) {
					case "None":
						return HashSet_empty()
					case "Runtime":
						return HashSet_make(self.id)
					case "Composite":
						return pipe(ids(self.left), HashSet_union(ids(self.right)))
				}
			},
			_fiberCounter = globalValue(
				Symbol.for("effect/Fiber/Id/_fiberCounter"),
				() => MutableRef_make(0),
			),
			threadName = self => {
				const identifiers = Array.from(ids(self))
					.map(n => `#${n}`)
					.join(",")
				return identifiers
			},
			FiberId_none = fiberId_none,
			FiberId_combine = fiberId_combine,
			FiberId_ids = ids,
			FiberId_threadName = threadName,
			FiberId_unsafeMake = () => {
				const id = MutableRef_get(_fiberCounter)
				pipe(_fiberCounter, MutableRef_set(id + 1))
				return new Runtime(id, Date.now())
			},
			HashMap_empty = internal_hashMap_empty,
			HashMap_get = hashMap_get,
			HashMap_set = hashMap_set,
			HashMap_keys = hashMap_keys,
			HashMap_modifyAt = modifyAt,
			HashMap_map = hashMap_map,
			HashMap_reduce = hashMap_reduce,
			List_TypeId = Symbol.for("effect/List"),
			List_toArray = self => Array_fromIterable(self),
			List_getEquivalence = isEquivalent =>
				Equivalence_mapInput(Array_getEquivalence(isEquivalent), List_toArray),
			List_equivalence = List_getEquivalence(equals),
			ConsProto = {
				[List_TypeId]: List_TypeId,
				_tag: "Cons",
				toString() {
					return format(this.toJSON())
				},
				toJSON() {
					return {
						_id: "List",
						_tag: "Cons",
						values: List_toArray(this).map(toJSON),
					}
				},
				[NodeInspectSymbol]() {
					return this.toJSON()
				},
				[Equal_symbol](that) {
					return (
						isList(that) &&
						this._tag === that._tag &&
						List_equivalence(this, that)
					)
				},
				[symbol]() {
					return cached(this, array(List_toArray(this)))
				},
				[Symbol.iterator]() {
					let done = !1,
						self = this
					return {
						next() {
							if (done) return this.return()
							if ("Nil" === self._tag) {
								done = !0
								return this.return()
							}
							const value = self.head
							self = self.tail
							return { done, value }
						},
						return(value) {
							done || (done = !0)
							return { done: !0, value }
						},
					}
				},
				pipe() {
					return pipeArguments(this, arguments)
				},
			},
			makeCons = (head, tail) => {
				const cons = Object.create(ConsProto)
				cons.head = head
				cons.tail = tail
				return cons
			},
			NilHash = string("Nil"),
			NilProto = {
				[List_TypeId]: List_TypeId,
				_tag: "Nil",
				toString() {
					return format(this.toJSON())
				},
				toJSON: () => ({ _id: "List", _tag: "Nil" }),
				[NodeInspectSymbol]() {
					return this.toJSON()
				},
				[symbol]: () => NilHash,
				[Equal_symbol](that) {
					return isList(that) && this._tag === that._tag
				},
				[Symbol.iterator]: () => ({
					next: () => ({ done: !0, value: void 0 }),
				}),
				pipe() {
					return pipeArguments(this, arguments)
				},
			},
			_Nil = Object.create(NilProto),
			isList = u => hasProperty(u, List_TypeId),
			isNil = self => "Nil" === self._tag,
			isCons = self => "Cons" === self._tag,
			cons = (head, tail) => makeCons(head, tail),
			List_empty = () => _Nil,
			List_of = value => makeCons(value, _Nil),
			List_appendAll = dual(2, (self, that) => List_prependAll(that, self)),
			List_prepend = dual(2, (self, element) => cons(element, self)),
			List_prependAll = dual(2, (self, prefix) => {
				if (isNil(self)) return prefix
				if (isNil(prefix)) return self
				{
					const result = makeCons(prefix.head, self)
					let curr = result,
						that = prefix.tail
					for (; !isNil(that);) {
						const temp = makeCons(that.head, self)
						curr.tail = temp
						curr = temp
						that = that.tail
					}
					return result
				}
			}),
			List_reduce = dual(3, (self, zero, f) => {
				let acc = zero,
					these = self
				for (; !isNil(these);) {
					acc = f(acc, these.head)
					these = these.tail
				}
				return acc
			}),
			List_reverse = self => {
				let result = List_empty(),
					these = self
				for (; !isNil(these);) {
					result = List_prepend(result, these.head)
					these = these.tail
				}
				return result
			},
			Structural =
				(Array.prototype,
				(function () {
					function Structural(args) {
						args && Object.assign(this, args)
					}
					Structural.prototype = StructuralPrototype
					return Structural
				})())
		Structural.prototype
		const ContextPatchTypeId = Symbol.for("effect/DifferContextPatch")
		function contextPatch_variance(a) {
			return a
		}
		const contextPatch_PatchProto = {
				...Structural.prototype,
				[ContextPatchTypeId]: {
					_Value: contextPatch_variance,
					_Patch: contextPatch_variance,
				},
			},
			contextPatch_EmptyProto = Object.assign(
				Object.create(contextPatch_PatchProto),
				{ _tag: "Empty" },
			),
			contextPatch_empty = Object.create(contextPatch_EmptyProto),
			differ_contextPatch_empty = () => contextPatch_empty,
			contextPatch_AndThenProto = Object.assign(
				Object.create(contextPatch_PatchProto),
				{ _tag: "AndThen" },
			),
			AddServiceProto = Object.assign(Object.create(contextPatch_PatchProto), {
				_tag: "AddService",
			}),
			makeAddService = (key, service) => {
				const o = Object.create(AddServiceProto)
				o.key = key
				o.service = service
				return o
			},
			RemoveServiceProto = Object.assign(
				Object.create(contextPatch_PatchProto),
				{ _tag: "RemoveService" },
			),
			makeRemoveService = key => {
				const o = Object.create(RemoveServiceProto)
				o.key = key
				return o
			},
			UpdateServiceProto = Object.assign(
				Object.create(contextPatch_PatchProto),
				{ _tag: "UpdateService" },
			),
			makeUpdateService = (key, update) => {
				const o = Object.create(UpdateServiceProto)
				o.key = key
				o.update = update
				return o
			},
			contextPatch_combine = dual(2, (self, that) =>
				((first, second) => {
					const o = Object.create(contextPatch_AndThenProto)
					o.first = first
					o.second = second
					return o
				})(self, that),
			),
			contextPatch_patch = dual(2, (self, context) => {
				if ("Empty" === self._tag) return context
				let wasServiceUpdated = !1,
					patches = Chunk_of(self)
				const updatedContext = new Map(context.unsafeMap)
				for (; isNonEmpty(patches);) {
					const head = Chunk_headNonEmpty(patches),
						tail = Chunk_tailNonEmpty(patches)
					switch (head._tag) {
						case "Empty":
							patches = tail
							break
						case "AddService":
							updatedContext.set(head.key, head.service)
							patches = tail
							break
						case "AndThen":
							patches = Chunk_prepend(
								Chunk_prepend(tail, head.second),
								head.first,
							)
							break
						case "RemoveService":
							updatedContext.delete(head.key)
							patches = tail
							break
						case "UpdateService":
							updatedContext.set(
								head.key,
								head.update(updatedContext.get(head.key)),
							)
							wasServiceUpdated = !0
							patches = tail
					}
				}
				if (!wasServiceUpdated) return makeContext(updatedContext)
				const map = new Map()
				for (const [tag] of context.unsafeMap)
					if (updatedContext.has(tag)) {
						map.set(tag, updatedContext.get(tag))
						updatedContext.delete(tag)
					}
				for (const [tag, s] of updatedContext) map.set(tag, s)
				return makeContext(map)
			})
		Structural.prototype
		const HashSetPatchTypeId = Symbol.for("effect/DifferHashSetPatch")
		function hashSetPatch_variance(a) {
			return a
		}
		const hashSetPatch_PatchProto = {
				...Structural.prototype,
				[HashSetPatchTypeId]: {
					_Value: hashSetPatch_variance,
					_Key: hashSetPatch_variance,
					_Patch: hashSetPatch_variance,
				},
			},
			hashSetPatch_EmptyProto = Object.assign(
				Object.create(hashSetPatch_PatchProto),
				{ _tag: "Empty" },
			),
			hashSetPatch_empty = Object.create(hashSetPatch_EmptyProto),
			differ_hashSetPatch_empty = () => hashSetPatch_empty,
			hashSetPatch_AndThenProto = Object.assign(
				Object.create(hashSetPatch_PatchProto),
				{ _tag: "AndThen" },
			),
			hashSetPatch_AddProto = Object.assign(
				Object.create(hashSetPatch_PatchProto),
				{ _tag: "Add" },
			),
			hashSetPatch_makeAdd = value => {
				const o = Object.create(hashSetPatch_AddProto)
				o.value = value
				return o
			},
			hashSetPatch_RemoveProto = Object.assign(
				Object.create(hashSetPatch_PatchProto),
				{ _tag: "Remove" },
			),
			hashSetPatch_combine = dual(2, (self, that) =>
				((first, second) => {
					const o = Object.create(hashSetPatch_AndThenProto)
					o.first = first
					o.second = second
					return o
				})(self, that),
			),
			hashSetPatch_patch = dual(2, (self, oldValue) => {
				if ("Empty" === self._tag) return oldValue
				let set = oldValue,
					patches = Chunk_of(self)
				for (; isNonEmpty(patches);) {
					const head = Chunk_headNonEmpty(patches),
						tail = Chunk_tailNonEmpty(patches)
					switch (head._tag) {
						case "Empty":
							patches = tail
							break
						case "AndThen":
							patches = Chunk_prepend(head.first)(
								Chunk_prepend(head.second)(tail),
							)
							break
						case "Add":
							set = HashSet_add(head.value)(set)
							patches = tail
							break
						case "Remove":
							set = HashSet_remove(head.value)(set)
							patches = tail
					}
				}
				return set
			})
		Structural.prototype
		const ReadonlyArrayPatchTypeId = Symbol.for(
			"effect/DifferReadonlyArrayPatch",
		)
		function readonlyArrayPatch_variance(a) {
			return a
		}
		const readonlyArrayPatch_PatchProto = {
				...Structural.prototype,
				[ReadonlyArrayPatchTypeId]: {
					_Value: readonlyArrayPatch_variance,
					_Patch: readonlyArrayPatch_variance,
				},
			},
			readonlyArrayPatch_EmptyProto = Object.assign(
				Object.create(readonlyArrayPatch_PatchProto),
				{ _tag: "Empty" },
			),
			readonlyArrayPatch_empty = Object.create(readonlyArrayPatch_EmptyProto),
			differ_readonlyArrayPatch_empty = () => readonlyArrayPatch_empty,
			readonlyArrayPatch_AndThenProto = Object.assign(
				Object.create(readonlyArrayPatch_PatchProto),
				{ _tag: "AndThen" },
			),
			readonlyArrayPatch_AppendProto = Object.assign(
				Object.create(readonlyArrayPatch_PatchProto),
				{ _tag: "Append" },
			),
			readonlyArrayPatch_SliceProto = Object.assign(
				Object.create(readonlyArrayPatch_PatchProto),
				{ _tag: "Slice" },
			),
			readonlyArrayPatch_UpdateProto = Object.assign(
				Object.create(readonlyArrayPatch_PatchProto),
				{ _tag: "Update" },
			),
			readonlyArrayPatch_makeUpdate = (index, patch) => {
				const o = Object.create(readonlyArrayPatch_UpdateProto)
				o.index = index
				o.patch = patch
				return o
			},
			readonlyArrayPatch_combine = dual(2, (self, that) =>
				((first, second) => {
					const o = Object.create(readonlyArrayPatch_AndThenProto)
					o.first = first
					o.second = second
					return o
				})(self, that),
			),
			readonlyArrayPatch_patch = dual(3, (self, oldValue, differ) => {
				if ("Empty" === self._tag) return oldValue
				let readonlyArray = oldValue.slice(),
					patches = Array_of(self)
				for (; Array_isNonEmptyArray(patches);) {
					const head = headNonEmpty(patches),
						tail = tailNonEmpty(patches)
					switch (head._tag) {
						case "Empty":
							patches = tail
							break
						case "AndThen":
							tail.unshift(head.first, head.second)
							patches = tail
							break
						case "Append":
							for (const value of head.values) readonlyArray.push(value)
							patches = tail
							break
						case "Slice":
							readonlyArray = readonlyArray.slice(head.from, head.until)
							patches = tail
							break
						case "Update":
							readonlyArray[head.index] = differ.patch(
								head.patch,
								readonlyArray[head.index],
							)
							patches = tail
					}
				}
				return readonlyArray
			}),
			DifferTypeId = Symbol.for("effect/Differ"),
			DifferProto = {
				[DifferTypeId]: { _P: identity, _V: identity },
				pipe() {
					return pipeArguments(this, arguments)
				},
			},
			differ_make = params => {
				const differ = Object.create(DifferProto)
				differ.empty = params.empty
				differ.diff = params.diff
				differ.combine = params.combine
				differ.patch = params.patch
				return differ
			},
			differ_update = () => updateWith((_, a) => a),
			updateWith = f =>
				differ_make({
					empty: identity,
					combine: (first, second) =>
						first === identity
							? second
							: second === identity
								? first
								: a => second(first(a)),
					diff: (oldValue, newValue) =>
						equals(oldValue, newValue) ? identity : constant(newValue),
					patch: (patch, oldValue) => f(oldValue, patch(oldValue)),
				}),
			active = patch => 255 & patch,
			enabled = patch => (patch >> 8) & 255,
			runtimeFlagsPatch_make = (active, enabled) =>
				(255 & active) + ((enabled & active & 255) << 8),
			runtimeFlagsPatch_empty = runtimeFlagsPatch_make(0, 0),
			exclude = dual(2, (self, flag) =>
				runtimeFlagsPatch_make(active(self) & ~flag, enabled(self)),
			),
			runtimeFlagsPatch_andThen = dual(2, (self, that) => self | that),
			cooperativeYielding = self => runtimeFlags_isEnabled(self, 32),
			runtimeFlags_disable = dual(2, (self, flag) => self & ~flag),
			runtimeFlags_enable = dual(2, (self, flag) => self | flag),
			interruptible = self => interruption(self) && !windDown(self),
			interruption = self => runtimeFlags_isEnabled(self, 1),
			runtimeFlags_isEnabled = dual(2, (self, flag) => !!(self & flag)),
			runtimeFlags_make = (...flags) => flags.reduce((a, b) => a | b, 0),
			runtimeFlags_none = runtimeFlags_make(0),
			runtimeMetrics = self => runtimeFlags_isEnabled(self, 4),
			windDown = self => runtimeFlags_isEnabled(self, 16),
			runtimeFlags_diff = dual(2, (self, that) =>
				runtimeFlagsPatch_make(self ^ that, that),
			),
			runtimeFlags_patch = dual(
				2,
				(self, patch) =>
					(self & ((n => (~n >>> 0) & 255)(active(patch)) | enabled(patch))) |
					(active(patch) & enabled(patch)),
			),
			differ = differ_make({
				empty: runtimeFlagsPatch_empty,
				diff: (oldValue, newValue) => runtimeFlags_diff(oldValue, newValue),
				combine: (first, second) => runtimeFlagsPatch_andThen(second)(first),
				patch: (_patch, oldValue) => runtimeFlags_patch(oldValue, _patch),
			}),
			RuntimeFlagsPatch_disable = flag => runtimeFlagsPatch_make(flag, 0),
			RuntimeFlagsPatch_exclude = exclude,
			CauseTypeId = Symbol.for("effect/Cause"),
			proto = {
				[CauseTypeId]: { _E: _ => _ },
				[symbol]() {
					return pipe(
						Hash_hash("effect/Cause"),
						combine(Hash_hash(flattenCause(this))),
						cached(this),
					)
				},
				[Equal_symbol](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()
				},
			},
			cause_empty = (() => {
				const o = Object.create(proto)
				o._tag = "Empty"
				return o
			})(),
			fail = error => {
				const o = Object.create(proto)
				o._tag = "Fail"
				o.error = error
				return o
			},
			die = defect => {
				const o = Object.create(proto)
				o._tag = "Die"
				o.defect = defect
				return o
			},
			interrupt = fiberId => {
				const o = Object.create(proto)
				o._tag = "Interrupt"
				o.fiberId = fiberId
				return o
			},
			parallel = (left, right) => {
				const o = Object.create(proto)
				o._tag = "Parallel"
				o.left = left
				o.right = right
				return o
			},
			sequential = (left, right) => {
				const o = Object.create(proto)
				o._tag = "Sequential"
				o.left = left
				o.right = right
				return o
			},
			isCause = u => hasProperty(u, CauseTypeId),
			isDieType = self => "Die" === self._tag,
			isInterrupted = self => Option_isSome(interruptOption(self)),
			isInterruptedOnly = self =>
				reduceWithContext(void 0, IsInterruptedOnlyCauseReducer)(self),
			cause_defects = self =>
				Chunk_reverse(
					cause_reduce(self, esm_Chunk_empty(), (list, cause) =>
						"Die" === cause._tag
							? Option_some(pipe(list, Chunk_prepend(cause.defect)))
							: Option_none(),
					),
				),
			interruptors = self =>
				cause_reduce(self, HashSet_empty(), (set, cause) =>
					"Interrupt" === cause._tag
						? Option_some(pipe(set, HashSet_add(cause.fiberId)))
						: Option_none(),
				),
			failureOption = self =>
				find(self, cause =>
					"Fail" === cause._tag ? Option_some(cause.error) : Option_none(),
				),
			failureOrCause = self => {
				const option = failureOption(self)
				switch (option._tag) {
					case "None":
						return Either_right(self)
					case "Some":
						return Either_left(option.value)
				}
			},
			interruptOption = self =>
				find(self, cause =>
					"Interrupt" === cause._tag
						? Option_some(cause.fiberId)
						: Option_none(),
				),
			stripFailures = self =>
				cause_match(self, {
					onEmpty: cause_empty,
					onFail: () => cause_empty,
					onDie: die,
					onInterrupt: interrupt,
					onSequential: sequential,
					onParallel: parallel,
				}),
			cause_map = dual(2, (self, f) => cause_flatMap(self, e => fail(f(e)))),
			cause_flatMap = dual(2, (self, f) =>
				cause_match(self, {
					onEmpty: cause_empty,
					onFail: error => f(error),
					onDie: defect => die(defect),
					onInterrupt: fiberId => interrupt(fiberId),
					onSequential: (left, right) => sequential(left, right),
					onParallel: (left, right) => parallel(left, right),
				}),
			),
			causeEquals = (left, right) => {
				let leftStack = Chunk_of(left),
					rightStack = Chunk_of(right)
				for (; isNonEmpty(leftStack) && isNonEmpty(rightStack);) {
					const [leftParallel, leftSequential] = pipe(
							Chunk_headNonEmpty(leftStack),
							cause_reduce(
								[HashSet_empty(), esm_Chunk_empty()],
								([parallel, sequential], cause) => {
									const [par, seq] = evaluateCause(cause)
									return Option_some([
										pipe(parallel, HashSet_union(par)),
										pipe(sequential, Chunk_appendAll(seq)),
									])
								},
							),
						),
						[rightParallel, rightSequential] = pipe(
							Chunk_headNonEmpty(rightStack),
							cause_reduce(
								[HashSet_empty(), esm_Chunk_empty()],
								([parallel, sequential], cause) => {
									const [par, seq] = evaluateCause(cause)
									return Option_some([
										pipe(parallel, HashSet_union(par)),
										pipe(sequential, Chunk_appendAll(seq)),
									])
								},
							),
						)
					if (!equals(leftParallel, rightParallel)) return !1
					leftStack = leftSequential
					rightStack = rightSequential
				}
				return !0
			},
			flattenCause = cause =>
				flattenCauseLoop(Chunk_of(cause), esm_Chunk_empty()),
			flattenCauseLoop = (causes, flattened) => {
				for (;;) {
					const [parallel, sequential] = pipe(
							causes,
							Array_reduce(
								[HashSet_empty(), esm_Chunk_empty()],
								([parallel, sequential], cause) => {
									const [par, seq] = evaluateCause(cause)
									return [
										pipe(parallel, HashSet_union(par)),
										pipe(sequential, Chunk_appendAll(seq)),
									]
								},
							),
						),
						updated =
							HashSet_size(parallel) > 0
								? pipe(flattened, Chunk_prepend(parallel))
								: flattened
					if (Chunk_isEmpty(sequential)) return Chunk_reverse(updated)
					causes = sequential
					flattened = updated
				}
				throw new Error(getBugErrorMessage("Cause.flattenCauseLoop"))
			},
			find = dual(2, (self, pf) => {
				const stack = [self]
				for (; stack.length > 0;) {
					const item = stack.pop(),
						option = pf(item)
					switch (option._tag) {
						case "None":
							switch (item._tag) {
								case "Sequential":
								case "Parallel":
									stack.push(item.right)
									stack.push(item.left)
							}
							break
						case "Some":
							return option
					}
				}
				return Option_none()
			}),
			evaluateCause = self => {
				let cause = self
				const stack = []
				let _parallel = HashSet_empty(),
					_sequential = esm_Chunk_empty()
				for (; void 0 !== cause;)
					switch (cause._tag) {
						case "Empty":
							if (0 === stack.length) return [_parallel, _sequential]
							cause = stack.pop()
							break
						case "Fail":
							_parallel = HashSet_add(
								_parallel,
								Chunk_make(cause._tag, cause.error),
							)
							if (0 === stack.length) return [_parallel, _sequential]
							cause = stack.pop()
							break
						case "Die":
							_parallel = HashSet_add(
								_parallel,
								Chunk_make(cause._tag, cause.defect),
							)
							if (0 === stack.length) return [_parallel, _sequential]
							cause = stack.pop()
							break
						case "Interrupt":
							_parallel = HashSet_add(
								_parallel,
								Chunk_make(cause._tag, cause.fiberId),
							)
							if (0 === stack.length) return [_parallel, _sequential]
							cause = stack.pop()
							break
						case "Sequential":
							switch (cause.left._tag) {
								case "Empty":
									cause = cause.right
									break
								case "Sequential":
									cause = sequential(
										cause.left.left,
										sequential(cause.left.right, cause.right),
									)
									break
								case "Parallel":
									cause = parallel(
										sequential(cause.left.left, cause.right),
										sequential(cause.left.right, cause.right),
									)
									break
								default:
									_sequential = Chunk_prepend(_sequential, cause.right)
									cause = cause.left
							}
							break
						case "Parallel":
							stack.push(cause.right)
							cause = cause.left
					}
				throw new Error(getBugErrorMessage("Cause.evaluateCauseLoop"))
			},
			IsInterruptedOnlyCauseReducer = {
				emptyCase: constTrue,
				failCase: constFalse,
				dieCase: constFalse,
				interruptCase: constTrue,
				sequentialCase: (_, left, right) => left && right,
				parallelCase: (_, left, right) => left && right,
			},
			cause_match = dual(
				2,
				(
					self,
					{ onDie, onEmpty, onFail, onInterrupt, onParallel, onSequential },
				) =>
					reduceWithContext(self, void 0, {
						emptyCase: () => onEmpty,
						failCase: (_, error) => onFail(error),
						dieCase: (_, defect) => onDie(defect),
						interruptCase: (_, fiberId) => onInterrupt(fiberId),
						sequentialCase: (_, left, right) => onSequential(left, right),
						parallelCase: (_, left, right) => onParallel(left, right),
					}),
			),
			cause_reduce = dual(3, (self, zero, pf) => {
				let accumulator = zero,
					cause = self
				const causes = []
				for (; void 0 !== cause;) {
					const option = pf(accumulator, cause)
					accumulator = Option_isSome(option) ? option.value : accumulator
					switch (cause._tag) {
						case "Sequential":
						case "Parallel":
							causes.push(cause.right)
							cause = cause.left
							break
						default:
							cause = void 0
					}
					void 0 === cause && causes.length > 0 && (cause = causes.pop())
				}
				return accumulator
			}),
			reduceWithContext = dual(3, (self, context, reducer) => {
				const input = [self],
					output = []
				for (; input.length > 0;) {
					const cause = input.pop()
					switch (cause._tag) {
						case "Empty":
							output.push(Either_right(reducer.emptyCase(context)))
							break
						case "Fail":
							output.push(Either_right(reducer.failCase(context, cause.error)))
							break
						case "Die":
							output.push(Either_right(reducer.dieCase(context, cause.defect)))
							break
						case "Interrupt":
							output.push(
								Either_right(reducer.interruptCase(context, cause.fiberId)),
							)
							break
						case "Sequential":
							input.push(cause.right)
							input.push(cause.left)
							output.push(Either_left({ _tag: "SequentialCase" }))
							break
						case "Parallel":
							input.push(cause.right)
							input.push(cause.left)
							output.push(Either_left({ _tag: "ParallelCase" }))
					}
				}
				const accumulator = []
				for (; output.length > 0;) {
					const either = output.pop()
					switch (either._tag) {
						case "Left":
							switch (either.left._tag) {
								case "SequentialCase": {
									const left = accumulator.pop(),
										right = accumulator.pop(),
										value = reducer.sequentialCase(context, left, right)
									accumulator.push(value)
									break
								}
								case "ParallelCase": {
									const left = accumulator.pop(),
										right = accumulator.pop(),
										value = reducer.parallelCase(context, left, right)
									accumulator.push(value)
									break
								}
							}
							break
						case "Right":
							accumulator.push(either.right)
					}
				}
				if (0 === accumulator.length)
					throw new Error(
						"BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues",
					)
				return accumulator.pop()
			}),
			pretty = (cause, options) =>
				isInterruptedOnly(cause)
					? "All fibers interrupted without errors."
					: prettyErrors(cause)
							.map(function (e) {
								return !0 !== options?.renderErrorCause || void 0 === e.cause
									? e.stack
									: `${e.stack} {\n${renderErrorCause(e.cause, "  ")}\n}`
							})
							.join("\n"),
			renderErrorCause = (cause, prefix) => {
				const lines = cause.stack.split("\n")
				let stack = `${prefix}[cause]: ${lines[0]}`
				for (let i = 1, len = lines.length; i < len; i++)
					stack += `\n${prefix}${lines[i]}`
				cause.cause &&
					(stack += ` {\n${renderErrorCause(cause.cause, `${prefix}  `)}\n${prefix}}`)
				return stack
			},
			makePrettyError = originalError => {
				const originalErrorIsObject =
						"object" == typeof originalError && null !== originalError,
					prevLimit = Error.stackTraceLimit
				Error.stackTraceLimit = 1
				const error = new Error(
					prettyErrorMessage(originalError),
					originalErrorIsObject &&
						"cause" in originalError &&
						void 0 !== originalError.cause
						? { cause: makePrettyError(originalError.cause) }
						: void 0,
				)
				Error.stackTraceLimit = prevLimit
				"" === error.message && (error.message = "An error has occurred")
				Error.stackTraceLimit = prevLimit
				error.name =
					originalError instanceof Error ? originalError.name : "Error"
				if (originalErrorIsObject) {
					spanSymbol in originalError &&
						(error.span = originalError[spanSymbol])
					Object.keys(originalError).forEach(key => {
						key in error || (error[key] = originalError[key])
					})
				}
				error.stack = prettyErrorStack(
					`${error.name}: ${error.message}`,
					originalError instanceof Error && originalError.stack
						? originalError.stack
						: "",
					error.span,
				)
				return error
			},
			prettyErrorMessage = u => {
				if ("string" == typeof u) return u
				if ("object" == typeof u && null !== u && u instanceof Error)
					return u.message
				try {
					if (
						hasProperty(u, "toString") &&
						Predicate_isFunction(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, span) => {
				const out = [message],
					lines = stack.startsWith(message)
						? stack.slice(message.length).split("\n")
						: stack.split("\n")
				for (let i = 1; i < lines.length; i++)
					if (
						lines[i].includes(" at new BaseEffectError") ||
						lines[i].includes(" at new YieldableError")
					)
						i++
					else {
						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 (span) {
					let current = span,
						i = 0
					for (; current && "Span" === current._tag && i < 10;) {
						const stackFn = spanToTrace.get(current)
						if ("function" == typeof stackFn) {
							const stack = stackFn()
							if ("string" == typeof stack) {
								const locationMatchAll = stack.matchAll(locationRegex)
								let match = !1
								for (const [, location] of locationMatchAll) {
									match = !0
									out.push(`    at ${current.name} (${location})`)
								}
								match ||
									out.push(
										`    at ${current.name} (${stack.replace(/^at /, "")})`,
									)
							} else out.push(`    at ${current.name}`)
						} else out.push(`    at ${current.name}`)
						current = Option_getOrUndefined(current.parent)
						i++
					}
				}
				return out.join("\n")
			},
			spanSymbol = Symbol.for("effect/SpanAnnotation"),
			prettyErrors = cause =>
				reduceWithContext(cause, void 0, {
					emptyCase: () => [],
					dieCase: (_, unknownError) => [makePrettyError(unknownError)],
					failCase: (_, error) => [makePrettyError(error)],
					interruptCase: () => [],
					parallelCase: (_, l, r) => [...l, ...r],
					sequentialCase: (_, l, r) => [...l, ...r],
				}),
			DeferredTypeId = Symbol.for("effect/Deferred"),
			deferredVariance = { _E: _ => _, _A: _ => _ },
			done = effect => ({ _tag: "Done", effect }),
			OP_FAILURE = "Failure",
			OP_ON_FAILURE = "OnFailure",
			OP_ON_SUCCESS = "OnSuccess",
			OP_ON_SUCCESS_AND_FAILURE = "OnSuccessAndFailure",
			OP_SUCCESS = "Success",
			OP_UPDATE_RUNTIME_FLAGS = "UpdateRuntimeFlags",
			OP_ITERATOR = "Iterator",
			OP_WITH_RUNTIME = "WithRuntime",
			OP_REVERT_FLAGS = "RevertFlags"
		class singleShotGen_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_SingleShotGen(this.self)
			}
		}
		const blocked = (blockedRequests, _continue) => {
				const effect = new EffectPrimitive("Blocked")
				effect.effect_instruction_i0 = blockedRequests
				effect.effect_instruction_i1 = _continue
				return effect
			},
			core_EffectTypeId = Symbol.for("effect/Effect")
		class RevertFlags {
			patch
			op
			_op = "RevertFlags"
			constructor(patch, op) {
				this.patch = patch
				this.op = op
			}
		}
		class EffectPrimitive {
			_op
			effect_instruction_i0 = void 0
			effect_instruction_i1 = void 0
			effect_instruction_i2 = void 0
			trace = void 0;
			[core_EffectTypeId] = effectVariance
			constructor(_op) {
				this._op = _op
			}
			[Equal_symbol](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 singleShotGen_SingleShotGen(new YieldWrap(this))
			}
		}
		class EffectPrimitiveFailure {
			_op
			effect_instruction_i0 = void 0
			effect_instruction_i1 = void 0
			effect_instruction_i2 = void 0
			trace = void 0;
			[core_EffectTypeId] = effectVariance
			constructor(_op) {
				this._op = _op
				this._tag = _op
			}
			[Equal_symbol](that) {
				return (
					exitIsExit(that) &&
					"Failure" === that._op &&
					equals(this.effect_instruction_i0, that.effect_instruction_i0)
				)
			}
			[symbol]() {
				return pipe(
					string(this._tag),
					combine(Hash_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 singleShotGen_SingleShotGen(new YieldWrap(this))
			}
		}
		class EffectPrimitiveSuccess {
			_op
			effect_instruction_i0 = void 0
			effect_instruction_i1 = void 0
			effect_instruction_i2 = void 0
			trace = void 0;
			[core_EffectTypeId] = effectVariance
			constructor(_op) {
				this._op = _op
				this._tag = _op
			}
			[Equal_symbol](that) {
				return (
					exitIsExit(that) &&
					"Success" === that._op &&
					equals(this.effect_instruction_i0, that.effect_instruction_i0)
				)
			}
			[symbol]() {
				return pipe(
					string(this._tag),
					combine(Hash_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 singleShotGen_SingleShotGen(new YieldWrap(this))
			}
		}
		const isEffect = u => hasProperty(u, core_EffectTypeId),
			withFiberRuntime = withRuntime => {
				const effect = new EffectPrimitive("WithRuntime")
				effect.effect_instruction_i0 = withRuntime
				return effect
			},
			acquireUseRelease = dual(3, (acquire, use, release) =>
				uninterruptibleMask(restore =>
					core_flatMap(acquire, a =>
						core_flatMap(core_exit(suspend(() => restore(use(a)))), exit =>
							suspend(() => release(a, exit)).pipe(
								matchCauseEffect({
									onFailure: cause => {
										switch (exit._tag) {
											case "Failure":
												return failCause(
													sequential(exit.effect_instruction_i0, cause),
												)
											case "Success":
												return failCause(cause)
										}
									},
									onSuccess: () => exit,
								}),
							),
						),
					),
				),
			),
			core_as = dual(2, (self, value) =>
				core_flatMap(self, () => succeed(value)),
			),
			core_asVoid = self => core_as(self, void 0),
			custom = function () {
				const wrapper = new EffectPrimitive("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 = FiberId_none) => {
				const effect = new EffectPrimitive("Async")
				let cancelerRef
				effect.effect_instruction_i0 = resume => {
					cancelerRef = register(resume)
				}
				effect.effect_instruction_i1 = blockingOn
				return onInterrupt(effect, _ =>
					isEffect(cancelerRef) ? cancelerRef : core_void_,
				)
			},
			asyncInterrupt = (register, blockingOn = FiberId_none) =>
				suspend(() => unsafeAsync(register, blockingOn)),
			async_ = (resume, blockingOn = FiberId_none) =>
				custom(resume, function () {
					let backingResume, pendingEffect
					function proxyResume(effect) {
						backingResume
							? backingResume(effect)
							: void 0 === pendingEffect && (pendingEffect = effect)
					}
					const effect = new EffectPrimitive("Async")
					effect.effect_instruction_i0 = resume => {
						backingResume = resume
						pendingEffect && resume(pendingEffect)
					}
					effect.effect_instruction_i1 = blockingOn
					let cancelerRef, controllerRef
					if (1 !== this.effect_instruction_i0.length) {
						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, _ => {
								controllerRef && controllerRef.abort()
								return cancelerRef ?? core_void_
							})
						: effect
				}),
			catchAllCause = dual(2, (self, f) => {
				const effect = new EffectPrimitive("OnFailure")
				effect.effect_instruction_i0 = self
				effect.effect_instruction_i1 = f
				return effect
			}),
			catchAll = dual(2, (self, f) =>
				matchEffect(self, { onFailure: f, onSuccess: succeed }),
			),
			originalSymbol = Symbol.for("effect/OriginalAnnotation"),
			capture = (obj, span) =>
				Option_isSome(span)
					? new Proxy(obj, {
							has: (target, p) =>
								p === spanSymbol || p === originalSymbol || p in target,
							get: (target, p) =>
								p === spanSymbol
									? span.value
									: p === originalSymbol
										? obj
										: target[p],
						})
					: obj,
			core_die = defect =>
				isObject(defect) && !(spanSymbol in defect)
					? withFiberRuntime(fiber =>
							failCause(die(capture(defect, currentSpanFromFiber(fiber)))),
						)
					: failCause(die(defect)),
			dieMessage = message =>
				failCauseSync(() => die(new RuntimeException(message))),
			core_either = self =>
				matchEffect(self, {
					onFailure: e => succeed(Either_left(e)),
					onSuccess: a => succeed(Either_right(a)),
				}),
			core_exit = self =>
				matchCause(self, { onFailure: exitFailCause, onSuccess: exitSucceed }),
			core_fail = error =>
				isObject(error) && !(spanSymbol in error)
					? withFiberRuntime(fiber =>
							failCause(fail(capture(error, currentSpanFromFiber(fiber)))),
						)
					: failCause(fail(error)),
			failSync = evaluate => core_flatMap(sync(evaluate), core_fail),
			failCause = cause => {
				const effect = new EffectPrimitiveFailure("Failure")
				effect.effect_instruction_i0 = cause
				return effect
			},
			failCauseSync = evaluate => core_flatMap(sync(evaluate), failCause),
			fiberId = withFiberRuntime(state => succeed(state.id())),
			fiberIdWith = f => withFiberRuntime(state => f(state.id())),
			core_flatMap = dual(2, (self, f) => {
				const effect = new EffectPrimitive("OnSuccess")
				effect.effect_instruction_i0 = self
				effect.effect_instruction_i1 = f
				return effect
			}),
			step = self => {
				const effect = new EffectPrimitive("OnStep")
				effect.effect_instruction_i0 = self
				return effect
			},
			core_flatten = self => core_flatMap(self, identity),
			matchCause = dual(2, (self, options) =>
				matchCauseEffect(self, {
					onFailure: cause => succeed(options.onFailure(cause)),
					onSuccess: a => succeed(options.onSuccess(a)),
				}),
			),
			matchCauseEffect = dual(2, (self, options) => {
				const effect = new EffectPrimitive("OnSuccessAndFailure")
				effect.effect_instruction_i0 = self
				effect.effect_instruction_i1 = options.onFailure
				effect.effect_instruction_i2 = options.onSuccess
				return effect
			}),
			matchEffect = dual(2, (self, options) =>
				matchCauseEffect(self, {
					onFailure: cause => {
						if (cause_defects(cause).length > 0)
							return failCause(
								(self =>
									cause_match(self, {
										onEmpty: cause_empty,
										onFail: die,
										onDie: die,
										onInterrupt: interrupt,
										onSequential: sequential,
										onParallel: parallel,
									}))(cause),
							)
						const failures = (self =>
							Chunk_reverse(
								cause_reduce(self, esm_Chunk_empty(), (list, cause) =>
									"Fail" === cause._tag
										? Option_some(pipe(list, Chunk_prepend(cause.error)))
										: Option_none(),
								),
							))(cause)
						return failures.length > 0
							? options.onFailure(Chunk_unsafeHead(failures))
							: failCause(cause)
					},
					onSuccess: options.onSuccess,
				}),
			),
			forEachSequential = dual(2, (self, f) =>
				suspend(() => {
					const arr = Array_fromIterable(self),
						ret = allocate(arr.length)
					let i = 0
					return core_as(
						whileLoop({
							while: () => i < arr.length,
							body: () => f(arr[i], i),
							step: b => {
								ret[i++] = b
							},
						}),
						ret,
					)
				}),
			),
			forEachSequentialDiscard = dual(2, (self, f) =>
				suspend(() => {
					const arr = Array_fromIterable(self)
					let i = 0
					return whileLoop({
						while: () => i < arr.length,
						body: () => f(arr[i], i),
						step: () => {
							i++
						},
					})
				}),
			),
			core_interrupt = core_flatMap(fiberId, fiberId => interruptWith(fiberId)),
			interruptWith = fiberId => failCause(interrupt(fiberId)),
			core_interruptible = self => {
				const effect = new EffectPrimitive("UpdateRuntimeFlags")
				effect.effect_instruction_i0 = runtimeFlagsPatch_make((flag = 1), flag)
				var flag
				effect.effect_instruction_i1 = () => self
				return effect
			},
			intoDeferred = dual(2, (self, deferred) =>
				uninterruptibleMask(restore =>
					core_flatMap(core_exit(restore(self)), exit =>
						deferredDone(deferred, exit),
					),
				),
			),
			core_map = dual(2, (self, f) =>
				core_flatMap(self, a => sync(() => f(a))),
			),
			core_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 => {
						const either = failureOrCause(cause)
						switch (either._tag) {
							case "Left":
								return failSync(() => f(either.left))
							case "Right":
								return failCause(either.right)
						}
					},
					onSuccess: succeed,
				}),
			),
			onExit = dual(2, (self, cleanup) =>
				uninterruptibleMask(restore =>
					matchCauseEffect(restore(self), {
						onFailure: cause1 => {
							const result = exitFailCause(cause1)
							return matchCauseEffect(cleanup(result), {
								onFailure: cause2 => exitFailCause(sequential(cause1, cause2)),
								onSuccess: () => result,
							})
						},
						onSuccess: success => {
							const result = exitSucceed(success)
							return core_zipRight(cleanup(result), result)
						},
					}),
				),
			),
			onInterrupt = dual(2, (self, cleanup) =>
				onExit(
					self,
					exitMatch({
						onFailure: cause =>
							isInterruptedOnly(cause)
								? core_asVoid(cleanup(interruptors(cause)))
								: core_void_,
						onSuccess: () => core_void_,
					}),
				),
			),
			core_orElse = dual(2, (self, that) => attemptOrElse(self, that, succeed)),
			orDie = self => orDieWith(self, identity),
			orDieWith = dual(2, (self, f) =>
				matchEffect(self, {
					onFailure: e => core_die(f(e)),
					onSuccess: succeed,
				}),
			),
			succeed = value => {
				const effect = new EffectPrimitiveSuccess("Success")
				effect.effect_instruction_i0 = value
				return effect
			},
			suspend = evaluate => {
				const effect = new EffectPrimitive("Commit")
				effect.commit = evaluate
				return effect
			},
			sync = thunk => {
				const effect = new EffectPrimitive("Sync")
				effect.effect_instruction_i0 = thunk
				return effect
			},
			core_tap = dual(
				args =>
					3 === args.length ||
					(2 === args.length &&
						!(isObject(args[1]) && "onlyEffect" in args[1])),
				(self, f) =>
					core_flatMap(self, a => {
						const b = "function" == typeof f ? f(a) : f
						return isEffect(b)
							? core_as(b, a)
							: hasProperty((input = b), "then") &&
								  Predicate_isFunction(input.then)
								? unsafeAsync(resume => {
										b.then(
											_ => resume(succeed(a)),
											e =>
												resume(
													core_fail(
														new UnknownException(
															e,
															"An unknown error occurred in Effect.tap",
														),
													),
												),
										)
									})
								: succeed(a)
						var input
					}),
			),
			attemptOrElse = dual(3, (self, that, onSuccess) =>
				matchCauseEffect(self, {
					onFailure: cause =>
						cause_defects(cause).length > 0
							? failCause(
									Option_getOrThrow(
										(self =>
											cause_match(self, {
												onEmpty: Option_none(),
												onFail: failure => Option_some(die(failure)),
												onDie: defect => Option_some(die(defect)),
												onInterrupt: () => Option_none(),
												onSequential: mergeWith(sequential),
												onParallel: mergeWith(parallel),
											}))(cause),
									),
								)
							: that(),
					onSuccess,
				}),
			),
			uninterruptible = self => {
				const effect = new EffectPrimitive("UpdateRuntimeFlags")
				effect.effect_instruction_i0 = RuntimeFlagsPatch_disable(1)
				effect.effect_instruction_i1 = () => self
				return effect
			},
			uninterruptibleMask = f =>
				custom(f, function () {
					const effect = new EffectPrimitive("UpdateRuntimeFlags")
					effect.effect_instruction_i0 = RuntimeFlagsPatch_disable(1)
					effect.effect_instruction_i1 = oldFlags =>
						interruption(oldFlags)
							? internalCall(() =>
									this.effect_instruction_i0(core_interruptible),
								)
							: internalCall(() => this.effect_instruction_i0(uninterruptible))
					return effect
				}),
			core_void_ = succeed(void 0),
			whenEffect = dual(2, (self, condition) =>
				core_flatMap(condition, b =>
					b ? pipe(self, core_map(Option_some)) : succeed(Option_none()),
				),
			),
			whileLoop = options => {
				const effect = new EffectPrimitive("While")
				effect.effect_instruction_i0 = options.while
				effect.effect_instruction_i1 = options.body
				effect.effect_instruction_i2 = options.step
				return effect
			},
			fromIterator = iterator =>
				suspend(() => {
					const effect = new EffectPrimitive("Iterator")
					effect.effect_instruction_i0 = iterator()
					return effect
				}),
			core_gen = function () {
				const f =
					1 === arguments.length
						? arguments[0]
						: arguments[1].bind(arguments[0])
				return fromIterator(() => f(pipe))
			},
			fnUntraced = (body, ...pipeables) =>
				Object.defineProperty(
					0 === pipeables.length
						? function (...args) {
								return fromIterator(() => body.apply(this, args))
							}
						: function (...args) {
								let effect = fromIterator(() => body.apply(this, args))
								for (const x of pipeables) effect = x(effect, ...args)
								return effect
							},
					"length",
					{ value: body.length, configurable: !0 },
				),
			withConcurrency = dual(2, (self, concurrency) =>
				fiberRefLocally(self, currentConcurrency, concurrency),
			),
			withRuntimeFlags = dual(2, (self, update) => {
				const effect = new EffectPrimitive("UpdateRuntimeFlags")
				effect.effect_instruction_i0 = update
				effect.effect_instruction_i1 = () => self
				return effect
			}),
			yieldNow = options => {
				const effect = new EffectPrimitive("Yield")
				return void 0 !== options?.priority
					? withSchedulingPriority(effect, options.priority)
					: effect
			},
			core_zip = dual(2, (self, that) =>
				core_flatMap(self, a => core_map(that, b => [a, b])),
			),
			core_zipLeft = dual(2, (self, that) =>
				core_flatMap(self, a => core_as(that, a)),
			),
			core_zipRight = dual(2, (self, that) => core_flatMap(self, () => that)),
			core_zipWith = dual(3, (self, that, f) =>
				core_flatMap(self, a => core_map(that, b => f(a, b))),
			),
			interruptFiber = self =>
				core_flatMap(fiberId, fiberId => pipe(self, interruptAsFiber(fiberId))),
			interruptAsFiber = dual(2, (self, fiberId) =>
				core_flatMap(self.interruptAsFork(fiberId), () => self.await),
			),
			logLevelFatal =
				(Number.MIN_SAFE_INTEGER,
				{
					_tag: "Fatal",
					syslog: 2,
					label: "FATAL",
					ordinal: 5e4,
					pipe() {
						return pipeArguments(this, arguments)
					},
				}),
			logLevelError = {
				_tag: "Error",
				syslog: 3,
				label: "ERROR",
				ordinal: 4e4,
				pipe() {
					return pipeArguments(this, arguments)
				},
			},
			logLevelWarning = {
				_tag: "Warning",
				syslog: 4,
				label: "WARN",
				ordinal: 3e4,
				pipe() {
					return pipeArguments(this, arguments)
				},
			},
			logLevelInfo = {
				_tag: "Info",
				syslog: 6,
				label: "INFO",
				ordinal: 2e4,
				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)
				},
			},
			FiberRefTypeId = (Number.MAX_SAFE_INTEGER, Symbol.for("effect/FiberRef")),
			fiberRefVariance = { _A: _ => _ },
			fiberRefGet = self =>
				withFiberRuntime(fiber => exitSucceed(fiber.getFiberRef(self))),
			fiberRefGetWith = dual(2, (self, f) =>
				core_flatMap(fiberRefGet(self), f),
			),
			fiberRefSet = dual(2, (self, value) =>
				fiberRefModify(self, () => [void 0, value]),
			),
			fiberRefModify = dual(2, (self, f) =>
				withFiberRuntime(state => {
					const [b, a] = f(state.getFiberRef(self))
					state.setFiberRef(self, a)
					return succeed(b)
				}),
			),
			fiberRefLocally = dual(3, (use, self, value) =>
				acquireUseRelease(
					core_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: differ_update(),
					fork: options?.fork ?? identity,
					join: options?.join,
				}),
			fiberRefUnsafeMakeContext = initial => {
				const differ = differ_make({
					empty: differ_contextPatch_empty(),
					combine: (first, second) => contextPatch_combine(second)(first),
					diff: (oldValue, newValue) =>
						((oldValue, newValue) => {
							const missingServices = new Map(oldValue.unsafeMap)
							let patch = differ_contextPatch_empty()
							for (const [tag, newService] of newValue.unsafeMap.entries())
								if (missingServices.has(tag)) {
									const old = missingServices.get(tag)
									missingServices.delete(tag)
									equals(old, newService) ||
										(patch = contextPatch_combine(
											makeUpdateService(tag, () => newService),
										)(patch))
								} else {
									missingServices.delete(tag)
									patch = contextPatch_combine(makeAddService(tag, newService))(
										patch,
									)
								}
							for (const [tag] of missingServices.entries())
								patch = contextPatch_combine(makeRemoveService(tag))(patch)
							return patch
						})(oldValue, newValue),
					patch: (patch, oldValue) => contextPatch_patch(oldValue)(patch),
				})
				return fiberRefUnsafeMakePatch(initial, { differ, fork: differ.empty })
			},
			fiberRefUnsafeMakePatch = (initial, options) => {
				const _fiberRef = {
					...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: patch => oldValue => options.differ.patch(patch, oldValue),
					fork: options.fork,
					join: options.join ?? ((_, n) => n),
				}
				return _fiberRef
			},
			fiberRefUnsafeMakeRuntimeFlags = initial =>
				fiberRefUnsafeMakePatch(initial, { differ, fork: differ.empty }),
			currentContext = globalValue(
				Symbol.for("effect/FiberRef/currentContext"),
				() => fiberRefUnsafeMakeContext(Context_empty()),
			),
			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(HashMap_empty()),
			),
			currentLogLevel = globalValue(
				Symbol.for("effect/FiberRef/currentLogLevel"),
				() => fiberRefUnsafeMake(logLevelInfo),
			),
			currentLogSpan = globalValue(
				Symbol.for("effect/FiberRef/currentLogSpan"),
				() => fiberRefUnsafeMake(List_empty()),
			),
			withSchedulingPriority = dual(2, (self, scheduler) =>
				fiberRefLocally(self, currentSchedulingPriority, 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(Option_some(logLevelDebug)),
			),
			currentVersionMismatchErrorLogLevel = globalValue(
				Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),
				() => fiberRefUnsafeMake(Option_some(logLevelWarning)),
			),
			currentMetricLabels = globalValue(
				Symbol.for("effect/FiberRef/currentMetricLabels"),
				() =>
					(() => {
						const differ = (differ =>
							differ_make({
								empty: differ_readonlyArrayPatch_empty(),
								combine: (first, second) =>
									readonlyArrayPatch_combine(first, second),
								diff: (oldValue, newValue) =>
									(options => {
										let i = 0,
											patch = differ_readonlyArrayPatch_empty()
										for (
											;
											i < options.oldValue.length &&
											i < options.newValue.length;
										) {
											const oldElement = options.oldValue[i],
												newElement = options.newValue[i],
												valuePatch = options.differ.diff(oldElement, newElement)
											equals(valuePatch, options.differ.empty) ||
												(patch = readonlyArrayPatch_combine(
													patch,
													readonlyArrayPatch_makeUpdate(i, valuePatch),
												))
											i += 1
										}
										i < options.oldValue.length &&
											(patch = readonlyArrayPatch_combine(
												patch,
												((from, until) => {
													const o = Object.create(readonlyArrayPatch_SliceProto)
													o.from = 0
													o.until = until
													return o
												})(0, i),
											))
										i < options.newValue.length &&
											(patch = readonlyArrayPatch_combine(
												patch,
												(values => {
													const o = Object.create(
														readonlyArrayPatch_AppendProto,
													)
													o.values = values
													return o
												})(Array_drop(i)(options.newValue)),
											))
										return patch
									})({ oldValue, newValue, differ }),
								patch: (patch, oldValue) =>
									readonlyArrayPatch_patch(patch, oldValue, differ),
							}))(differ_update())
						return fiberRefUnsafeMakePatch([], { differ, fork: differ.empty })
					})(),
			),
			currentForkScopeOverride = globalValue(
				Symbol.for("effect/FiberRef/currentForkScopeOverride"),
				() =>
					fiberRefUnsafeMake(Option_none(), {
						fork: () => Option_none(),
						join: (parent, _) => parent,
					}),
			),
			currentInterruptedCause = globalValue(
				Symbol.for("effect/FiberRef/currentInterruptedCause"),
				() =>
					fiberRefUnsafeMake(cause_empty, {
						fork: () => cause_empty,
						join: (parent, _) => parent,
					}),
			),
			ScopeTypeId = Symbol.for("effect/Scope"),
			CloseableScopeTypeId = Symbol.for("effect/CloseableScope"),
			scopeAddFinalizer = (self, finalizer) =>
				self.addFinalizer(() => core_asVoid(finalizer)),
			scopeAddFinalizerExit = (self, finalizer) => self.addFinalizer(finalizer),
			scopeClose = (self, exit) => self.close(exit),
			scopeFork = (self, strategy) => self.fork(strategy),
			causeSquashWith = dual(2, (self, f) => {
				const option = pipe(self, failureOption, Option_map(f))
				switch (option._tag) {
					case "None":
						return pipe(
							cause_defects(self),
							Chunk_head,
							Option_match({
								onNone: () => {
									const interrupts = Array_fromIterable(
										interruptors(self),
									).flatMap(fiberId =>
										Array_fromIterable(FiberId_ids(fiberId)).map(
											id => `#${id}`,
										),
									)
									return new InterruptedException(
										interrupts
											? `Interrupted by fibers: ${interrupts.join(", ")}`
											: void 0,
									)
								},
								onSome: identity,
							}),
						)
					case "Some":
						return option.value
				}
			}),
			YieldableError = (function () {
				class YieldableError extends globalThis.Error {
					commit() {
						return core_fail(this)
					}
					toJSON() {
						const obj = { ...this }
						this.message && (obj.message = this.message)
						this.cause && (obj.cause = this.cause)
						return obj
					}
					[NodeInspectSymbol]() {
						return this.toString !== globalThis.Error.prototype.toString
							? this.stack
								? `${this.toString()}\n${this.stack.split("\n").slice(1).join("\n")}`
								: this.toString()
							: "Bun" in globalThis
								? pretty(fail(this), { renderErrorCause: !0 })
								: this
					}
				}
				Object.assign(YieldableError.prototype, StructuralCommitPrototype)
				return YieldableError
			})(),
			makeException = (proto, tag) => {
				class Base extends YieldableError {
					_tag = tag
				}
				Object.assign(Base.prototype, proto)
				Base.prototype.name = tag
				return Base
			},
			RuntimeExceptionTypeId = Symbol.for(
				"effect/Cause/errors/RuntimeException",
			),
			RuntimeException = makeException(
				{ [RuntimeExceptionTypeId]: RuntimeExceptionTypeId },
				"RuntimeException",
			),
			InterruptedExceptionTypeId = Symbol.for(
				"effect/Cause/errors/InterruptedException",
			),
			InterruptedException = makeException(
				{ [InterruptedExceptionTypeId]: InterruptedExceptionTypeId },
				"InterruptedException",
			),
			isInterruptedException = u => hasProperty(u, InterruptedExceptionTypeId),
			NoSuchElementExceptionTypeId = Symbol.for(
				"effect/Cause/errors/NoSuchElement",
			),
			NoSuchElementException = makeException(
				{ [NoSuchElementExceptionTypeId]: NoSuchElementExceptionTypeId },
				"NoSuchElementException",
			),
			UnknownExceptionTypeId = Symbol.for(
				"effect/Cause/errors/UnknownException",
			),
			UnknownException = (function () {
				class UnknownException extends YieldableError {
					_tag = "UnknownException"
					error
					constructor(cause, message) {
						super(message ?? "An unknown error occurred", { cause })
						this.error = cause
					}
				}
				Object.assign(UnknownException.prototype, {
					[UnknownExceptionTypeId]: UnknownExceptionTypeId,
					name: "UnknownException",
				})
				return UnknownException
			})(),
			exitIsExit = u =>
				isEffect(u) &&
				"_tag" in u &&
				("Success" === u._tag || "Failure" === u._tag),
			exitIsSuccess = self => "Success" === self._tag,
			exitAs = dual(2, (self, value) => {
				switch (self._tag) {
					case "Failure":
						return exitFailCause(self.effect_instruction_i0)
					case "Success":
						return exitSucceed(value)
				}
			}),
			exitAsVoid = self => exitAs(self, void 0),
			exitCollectAll = (exits, options) =>
				exitCollectAllInternal(
					exits,
					options?.parallel ? parallel : sequential,
				),
			exitDie = defect => exitFailCause(die(defect)),
			exitFail = error => exitFailCause(fail(error)),
			exitFailCause = cause => {
				const effect = new EffectPrimitiveFailure("Failure")
				effect.effect_instruction_i0 = cause
				return effect
			},
			exitInterrupt = fiberId => exitFailCause(interrupt(fiberId)),
			exitMap = dual(2, (self, f) => {
				switch (self._tag) {
					case "Failure":
						return exitFailCause(self.effect_instruction_i0)
					case "Success":
						return exitSucceed(f(self.effect_instruction_i0))
				}
			}),
			exitMatch = dual(2, (self, { onFailure, onSuccess }) => {
				switch (self._tag) {
					case "Failure":
						return onFailure(self.effect_instruction_i0)
					case "Success":
						return onSuccess(self.effect_instruction_i0)
				}
			}),
			exitMatchEffect = dual(2, (self, { onFailure, onSuccess }) => {
				switch (self._tag) {
					case "Failure":
						return onFailure(self.effect_instruction_i0)
					case "Success":
						return onSuccess(self.effect_instruction_i0)
				}
			}),
			exitSucceed = value => {
				const effect = new EffectPrimitiveSuccess("Success")
				effect.effect_instruction_i0 = value
				return effect
			},
			exitVoid = exitSucceed(void 0),
			exitZip = dual(2, (self, that) =>
				exitZipWith(self, that, {
					onSuccess: (a, a2) => [a, a2],
					onFailure: sequential,
				}),
			),
			exitZipRight = dual(2, (self, that) =>
				exitZipWith(self, that, {
					onSuccess: (_, a2) => a2,
					onFailure: sequential,
				}),
			),
			exitZipWith = dual(3, (self, that, { onFailure, onSuccess }) => {
				switch (self._tag) {
					case "Failure":
						switch (that._tag) {
							case "Success":
								return exitFailCause(self.effect_instruction_i0)
							case "Failure":
								return exitFailCause(
									onFailure(
										self.effect_instruction_i0,
										that.effect_instruction_i0,
									),
								)
						}
					case "Success":
						switch (that._tag) {
							case "Success":
								return exitSucceed(
									onSuccess(
										self.effect_instruction_i0,
										that.effect_instruction_i0,
									),
								)
							case "Failure":
								return exitFailCause(that.effect_instruction_i0)
						}
				}
			}),
			exitCollectAllInternal = (exits, combineCauses) => {
				const list = Chunk_fromIterable(exits)
				return isNonEmpty(list)
					? pipe(
							Chunk_tailNonEmpty(list),
							Array_reduce(
								pipe(Chunk_headNonEmpty(list), exitMap(Chunk_of)),
								(accumulator, current) =>
									pipe(
										accumulator,
										exitZipWith(current, {
											onSuccess: (list, value) =>
												pipe(list, Chunk_prepend(value)),
											onFailure: combineCauses,
										}),
									),
							),
							exitMap(Chunk_reverse),
							exitMap(chunk => toReadonlyArray(chunk)),
							Option_some,
						)
					: Option_none()
			},
			deferredUnsafeMake = fiberId => {
				var joiners
				return {
					...CommitPrototype,
					[DeferredTypeId]: deferredVariance,
					state: MutableRef_make(
						((joiners = []), { _tag: "Pending", joiners }),
					),
					commit() {
						return deferredAwait(this)
					},
					blockingOn: fiberId,
				}
			},
			deferredMake = () => core_flatMap(fiberId, id => deferredMakeAs(id)),
			deferredMakeAs = fiberId => sync(() => deferredUnsafeMake(fiberId)),
			deferredAwait = self =>
				asyncInterrupt(resume => {
					const state = MutableRef_get(self.state)
					switch (state._tag) {
						case "Done":
							return resume(state.effect)
						case "Pending":
							state.joiners.push(resume)
							return deferredInterruptJoiner(self, resume)
					}
				}, self.blockingOn),
			deferredCompleteWith = dual(2, (self, effect) =>
				sync(() => {
					const state = MutableRef_get(self.state)
					switch (state._tag) {
						case "Done":
							return !1
						case "Pending":
							MutableRef_set(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, exit) => deferredCompleteWith(self, exit)),
			deferredFailCause = dual(2, (self, cause) =>
				deferredCompleteWith(self, failCause(cause)),
			),
			deferredInterruptWith = dual(2, (self, fiberId) =>
				deferredCompleteWith(self, interruptWith(fiberId)),
			),
			deferredSucceed = dual(2, (self, value) =>
				deferredCompleteWith(self, succeed(value)),
			),
			deferredUnsafeDone = (self, effect) => {
				const state = MutableRef_get(self.state)
				if ("Pending" === state._tag) {
					MutableRef_set(self.state, done(effect))
					for (let i = 0, len = state.joiners.length; i < len; i++)
						state.joiners[i](effect)
				}
			},
			deferredInterruptJoiner = (self, joiner) =>
				sync(() => {
					const state = MutableRef_get(self.state)
					if ("Pending" === state._tag) {
						const index = state.joiners.indexOf(joiner)
						index >= 0 && state.joiners.splice(index, 1)
					}
				}),
			constContext = withFiberRuntime(fiber =>
				exitSucceed(fiber.currentContext),
			),
			contextWithEffect = f => core_flatMap(constContext, f),
			provideContext = dual(2, (self, context) =>
				fiberRefLocally(currentContext, context)(self),
			),
			provideSomeContext = dual(2, (self, context) =>
				fiberRefLocallyWith(currentContext, parent =>
					Context_merge(parent, context),
				)(self),
			),
			mapInputContext = dual(2, (self, f) =>
				contextWithEffect(context => provideContext(self, f(context))),
			),
			currentSpanFromFiber = fiber => {
				const span = fiber.currentSpan
				return void 0 !== span && "Span" === span._tag
					? Option_some(span)
					: Option_none()
			},
			ClockTypeId = Symbol.for("effect/Clock"),
			clockTag = GenericTag("effect/Clock"),
			globalClockScheduler = {
				unsafeSchedule(task, duration) {
					const millis = toMillis(duration)
					if (millis > 2147483647) return constFalse
					let completed = !1
					const handle = setTimeout(() => {
						completed = !0
						task()
					}, millis)
					return () => {
						clearTimeout(handle)
						return !completed
					}
				},
			},
			performanceNowNanos = (function () {
				const bigint1e6 = BigInt(1e6)
				if (
					"undefined" == typeof performance ||
					"function" != typeof performance.now
				)
					return () => BigInt(Date.now()) * bigint1e6
				let origin
				return () => {
					void 0 === origin &&
						(origin =
							BigInt(Date.now()) * bigint1e6 -
							BigInt(Math.round(1e6 * performance.now())))
					return origin + BigInt(Math.round(1e6 * performance.now()))
				}
			})(),
			processOrPerformanceNow = (function () {
				const processHrtime =
					"object" == typeof process &&
					"hrtime" in process &&
					"function" == typeof process.hrtime.bigint
						? process.hrtime
						: void 0
				if (!processHrtime) return performanceNowNanos
				const 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 => {
					const canceler = globalClockScheduler.unsafeSchedule(
						() => resume(core_void_),
						duration,
					)
					return core_asVoid(sync(canceler))
				})
			}
		}
		const clock_make = () => new ClockImpl(),
			Number_Order = Order_number,
			Number_clamp = clamp(Number_Order),
			RegExp_escape = string => string.replace(/[/\\^$*+?.()|[\]{}]/g, "\\$&"),
			ConfigErrorTypeId = Symbol.for("effect/ConfigError"),
			configError_proto = {
				_tag: "ConfigError",
				[ConfigErrorTypeId]: ConfigErrorTypeId,
			},
			And = (self, that) => {
				const error = Object.create(configError_proto)
				error._op = "And"
				error.left = self
				error.right = that
				Object.defineProperty(error, "toString", {
					enumerable: !1,
					value() {
						return `${this.left} and ${this.right}`
					},
				})
				Object.defineProperty(error, "message", {
					enumerable: !1,
					get() {
						return this.toString()
					},
				})
				return error
			},
			Or = (self, that) => {
				const error = Object.create(configError_proto)
				error._op = "Or"
				error.left = self
				error.right = that
				Object.defineProperty(error, "toString", {
					enumerable: !1,
					value() {
						return `${this.left} or ${this.right}`
					},
				})
				Object.defineProperty(error, "message", {
					enumerable: !1,
					get() {
						return this.toString()
					},
				})
				return error
			},
			InvalidData = (path, message, options = { pathDelim: "." }) => {
				const error = Object.create(configError_proto)
				error._op = "InvalidData"
				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}")`
					},
				})
				return error
			},
			MissingData = (path, message, options = { pathDelim: "." }) => {
				const error = Object.create(configError_proto)
				error._op = "MissingData"
				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}")`
					},
				})
				return error
			},
			SourceUnavailable = (
				path,
				message,
				cause,
				options = { pathDelim: "." },
			) => {
				const error = Object.create(configError_proto)
				error._op = "SourceUnavailable"
				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}")`
					},
				})
				return error
			},
			Unsupported = (path, message, options = { pathDelim: "." }) => {
				const error = Object.create(configError_proto)
				error._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}")`
					},
				})
				return error
			},
			prefixed = dual(2, (self, prefix) => {
				switch (self._op) {
					case "And":
						return And(
							prefixed(self.left, prefix),
							prefixed(self.right, prefix),
						)
					case "Or":
						return Or(prefixed(self.left, prefix), prefixed(self.right, prefix))
					case "InvalidData":
						return InvalidData([...prefix, ...self.path], self.message)
					case "MissingData":
						return MissingData([...prefix, ...self.path], self.message)
					case "SourceUnavailable":
						return SourceUnavailable(
							[...prefix, ...self.path],
							self.message,
							self.cause,
						)
					case "Unsupported":
						return Unsupported([...prefix, ...self.path], self.message)
				}
			}),
			pathPatch_empty = { _tag: "Empty" },
			patch = dual(2, (path, patch) => {
				let input = List_of(patch),
					output = path
				for (; isCons(input);) {
					const patch = input.head
					switch (patch._tag) {
						case "Empty":
							input = input.tail
							break
						case "AndThen":
							input = cons(patch.first, cons(patch.second, input.tail))
							break
						case "MapName":
							output = Array_map(output, patch.f)
							input = input.tail
							break
						case "Nested":
							output = Array_prepend(output, patch.name)
							input = input.tail
							break
						case "Unnested":
							if (!pipe(Array_head(output), contains(patch.name)))
								return Either_left(
									MissingData(
										output,
										`Expected ${patch.name} to be in path in ConfigProvider#unnested`,
									),
								)
							output = tailNonEmpty(output)
							input = input.tail
					}
				}
				return Either_right(output)
			}),
			concat = (l, r) => [...l, ...r],
			ConfigProviderTypeId = Symbol.for("effect/ConfigProvider"),
			configProviderTag = GenericTag("effect/ConfigProvider"),
			FlatConfigProviderTypeId = Symbol.for("effect/ConfigProviderFlat"),
			configProvider_make = options => ({
				[ConfigProviderTypeId]: ConfigProviderTypeId,
				pipe() {
					return pipeArguments(this, arguments)
				},
				...options,
			}),
			fromEnv = options => {
				const { pathDelim, seqDelim } = Object.assign(
						{},
						{ pathDelim: "_", seqDelim: "," },
						options,
					),
					getEnv = () =>
						"undefined" != typeof process &&
						"env" in process &&
						"object" == typeof process.env
							? process.env
							: {}
				return (
					(flat = (options => ({
						[FlatConfigProviderTypeId]: FlatConfigProviderTypeId,
						patch: options.patch,
						load: (path, config, split = !0) =>
							options.load(path, config, split),
						enumerateChildren: options.enumerateChildren,
					}))({
						load: (path, primitive, split = !0) => {
							const pathString = (path => pipe(path, join(pathDelim)))(path),
								current = getEnv()
							return pipe(
								pathString in current
									? Option_some(current[pathString])
									: Option_none(),
								mapError(() =>
									MissingData(
										path,
										`Expected ${pathString} to exist in the process context`,
									),
								),
								core_flatMap(value =>
									parsePrimitive(value, path, primitive, seqDelim, split),
								),
							)
						},
						enumerateChildren: path =>
							sync(() => {
								const current = getEnv()
								return (elements => {
									const set = hashSet_beginMutation(internal_hashSet_empty())
									for (const value of elements) hashSet_add(set, value)
									return hashSet_endMutation(set)
								})(
									Object.keys(current)
										.map(value => value.toUpperCase().split(pathDelim))
										.filter(keyPath => {
											for (let i = 0; i < path.length; i++) {
												const pathComponent = pipe(path, Array_unsafeGet(i)),
													currentElement = keyPath[i]
												if (
													void 0 === currentElement ||
													pathComponent !== currentElement
												)
													return !1
											}
											return !0
										})
										.flatMap(keyPath =>
											keyPath.slice(path.length, path.length + 1),
										),
								)
							}),
						patch: pathPatch_empty,
					})),
					configProvider_make({
						load: config =>
							core_flatMap(fromFlatLoop(flat, [], config, !1), chunk =>
								Option_match(Array_head(chunk), {
									onNone: () =>
										core_fail(
											MissingData(
												[],
												`Expected a single value having structure: ${config}`,
											),
										),
									onSome: succeed,
								}),
							),
						flattened: flat,
					})
				)
				var flat
			},
			fromFlatLoop = (flat, prefix, config, split) => {
				const op = config
				switch (op._tag) {
					case "Constant":
						return succeed(Array_of(op.value))
					case "Described":
						return suspend(() => fromFlatLoop(flat, prefix, op.config, split))
					case "Fail":
						return core_fail(MissingData(prefix, op.message))
					case "Fallback":
						return pipe(
							suspend(() => fromFlatLoop(flat, prefix, op.first, split)),
							catchAll(error1 =>
								op.condition(error1)
									? pipe(
											fromFlatLoop(flat, prefix, op.second, split),
											catchAll(error2 => core_fail(Or(error1, error2))),
										)
									: core_fail(error1),
							),
						)
					case "Lazy":
						return suspend(() => fromFlatLoop(flat, prefix, op.config(), split))
					case "MapOrFail":
						return suspend(() =>
							pipe(
								fromFlatLoop(flat, prefix, op.original, split),
								core_flatMap(
									forEachSequential(a =>
										pipe(
											op.mapOrFail(a),
											mapError(
												prefixed(
													((path, config) => {
														let op = config
														if ("Nested" === op._tag) {
															const out = path.slice()
															for (; "Nested" === op._tag;) {
																out.push(op.name)
																op = op.config
															}
															return out
														}
														return path
													})(prefix, op.original),
												),
											),
										),
									),
								),
							),
						)
					case "Nested":
						return suspend(() =>
							fromFlatLoop(
								flat,
								concat(prefix, Array_of(op.name)),
								op.config,
								split,
							),
						)
					case "Primitive":
						return pipe(
							patch(prefix, flat.patch),
							core_flatMap(prefix =>
								pipe(
									flat.load(prefix, op, split),
									core_flatMap(values => {
										if (0 === values.length) {
											const name = pipe(
												(self =>
													isNonEmptyReadonlyArray(self)
														? Option_some(lastNonEmpty(self))
														: Option_none())(prefix),
												Option_getOrElse(() => "<n/a>"),
											)
											return core_fail(
												MissingData(
													[],
													`Expected ${op.description} with name ${name}`,
												),
											)
										}
										return succeed(values)
									}),
								),
							),
						)
					case "Sequence":
						return pipe(
							patch(prefix, flat.patch),
							core_flatMap(patchedPrefix =>
								pipe(
									flat.enumerateChildren(patchedPrefix),
									core_flatMap(indicesFrom),
									core_flatMap(indices =>
										0 === indices.length
											? suspend(() =>
													core_map(
														fromFlatLoop(flat, prefix, op.config, !0),
														Array_of,
													),
												)
											: pipe(
													forEachSequential(indices, index =>
														fromFlatLoop(
															flat,
															Array_append(prefix, `[${index}]`),
															op.config,
															!0,
														),
													),
													core_map(chunkChunk => {
														const flattened = Array_flatten(chunkChunk)
														return 0 === flattened.length
															? Array_of([])
															: Array_of(flattened)
													}),
												),
									),
								),
							),
						)
					case "HashMap":
						return suspend(() =>
							pipe(
								patch(prefix, flat.patch),
								core_flatMap(prefix =>
									pipe(
										flat.enumerateChildren(prefix),
										core_flatMap(keys =>
											pipe(
												keys,
												forEachSequential(key =>
													fromFlatLoop(
														flat,
														concat(prefix, Array_of(key)),
														op.valueConfig,
														split,
													),
												),
												core_map(matrix =>
													0 === matrix.length
														? Array_of(HashMap_empty())
														: pipe(
																transpose(matrix),
																Array_map(values =>
																	(entries => {
																		const map = beginMutation(
																			internal_hashMap_empty(),
																		)
																		for (const entry of entries)
																			hashMap_set(map, entry[0], entry[1])
																		return (self => {
																			self._editable = !1
																			return self
																		})(map)
																	})(
																		Array_zip(Array_fromIterable(keys), values),
																	),
																),
															),
												),
											),
										),
									),
								),
							),
						)
					case "ZipWith":
						return suspend(() =>
							pipe(
								fromFlatLoop(flat, prefix, op.left, split),
								core_either,
								core_flatMap(left =>
									pipe(
										fromFlatLoop(flat, prefix, op.right, split),
										core_either,
										core_flatMap(right => {
											if (Either_isLeft(left) && Either_isLeft(right))
												return core_fail(And(left.left, right.left))
											if (Either_isLeft(left) && Either_isRight(right))
												return core_fail(left.left)
											if (Either_isRight(left) && Either_isLeft(right))
												return core_fail(right.left)
											if (Either_isRight(left) && Either_isRight(right)) {
												const path = pipe(prefix, join(".")),
													fail = fromFlatLoopFail(prefix, path),
													[lefts, rights] = ((
														leftDef,
														rightDef,
														left,
														right,
													) => {
														const leftPad = Array_unfold(left.length, index =>
																index >= right.length
																	? Option_none()
																	: Option_some([leftDef(index), index + 1]),
															),
															rightPad = Array_unfold(right.length, index =>
																index >= left.length
																	? Option_none()
																	: Option_some([rightDef(index), index + 1]),
															)
														return [
															concat(left, leftPad),
															concat(right, rightPad),
														]
													})(
														fail,
														fail,
														pipe(left.right, Array_map(Either_right)),
														pipe(right.right, Array_map(Either_right)),
													)
												return pipe(
													lefts,
													Array_zip(rights),
													forEachSequential(([left, right]) =>
														pipe(
															core_zip(left, right),
															core_map(([left, right]) => op.zip(left, right)),
														),
													),
												)
											}
											throw new Error(
												"BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues",
											)
										}),
									),
								),
							),
						)
				}
			},
			fromFlatLoopFail = (prefix, path) => index =>
				Either_left(
					MissingData(
						prefix,
						`The element at index ${index} in a sequence at path "${path}" was missing`,
					),
				),
			parsePrimitive = (text, path, primitive, delimiter, split) =>
				split
					? pipe(
							((text, delim) =>
								text.split(new RegExp(`\\s*${RegExp_escape(delim)}\\s*`)))(
								text,
								delimiter,
							),
							forEachSequential(char => primitive.parse(char.trim())),
							mapError(prefixed(path)),
						)
					: pipe(
							primitive.parse(text),
							core_mapBoth({ onFailure: prefixed(path), onSuccess: Array_of }),
						),
			transpose = array =>
				Object.keys(array[0]).map(column => array.map(row => row[column])),
			indicesFrom = quotedIndices =>
				pipe(
					forEachSequential(quotedIndices, parseQuotedIndex),
					core_mapBoth({ onFailure: () => [], onSuccess: sort(Number_Order) }),
					core_either,
					core_map(Either_merge),
				),
			QUOTED_INDEX_REGEX = /^(\[(\d+)\])$/,
			parseQuotedIndex = str => {
				const match = str.match(QUOTED_INDEX_REGEX)
				if (null !== match) {
					const matchedIndex = match[2]
					return pipe(
						void 0 !== matchedIndex && matchedIndex.length > 0
							? Option_some(matchedIndex)
							: Option_none(),
						Option_flatMap(parseInteger),
					)
				}
				return Option_none()
			},
			parseInteger = str => {
				const parsedIndex = Number.parseInt(str)
				return Number.isNaN(parsedIndex)
					? Option_none()
					: Option_some(parsedIndex)
			},
			console_TypeId = Symbol.for("effect/Console"),
			consoleTag = GenericTag("effect/Console"),
			defaultConsole = {
				[console_TypeId]: console_TypeId,
				assert: (condition, ...args) =>
					sync(() => {
						console.assert(condition, ...args)
					}),
				clear: sync(() => {
					console.clear()
				}),
				count: label =>
					sync(() => {
						console.count(label)
					}),
				countReset: label =>
					sync(() => {
						console.countReset(label)
					}),
				debug: (...args) =>
					sync(() => {
						console.debug(...args)
					}),
				dir: (item, options) =>
					sync(() => {
						console.dir(item, options)
					}),
				dirxml: (...args) =>
					sync(() => {
						console.dirxml(...args)
					}),
				error: (...args) =>
					sync(() => {
						console.error(...args)
					}),
				group: options =>
					sync(
						options?.collapsed
							? () => console.groupCollapsed(options?.label)
							: () => console.group(options?.label),
					),
				groupEnd: sync(() => {
					console.groupEnd()
				}),
				info: (...args) =>
					sync(() => {
						console.info(...args)
					}),
				log: (...args) =>
					sync(() => {
						console.log(...args)
					}),
				table: (tabularData, properties) =>
					sync(() => {
						console.table(tabularData, properties)
					}),
				time: label => sync(() => console.time(label)),
				timeEnd: label => sync(() => console.timeEnd(label)),
				timeLog: (label, ...args) =>
					sync(() => {
						console.timeLog(label, ...args)
					}),
				trace: (...args) =>
					sync(() => {
						console.trace(...args)
					}),
				warn: (...args) =>
					sync(() => {
						console.warn(...args)
					}),
				unsafe: console,
			},
			RandomTypeId = Symbol.for("effect/Random"),
			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 core_map(this.next, n => n > 0.5)
			}
			get nextInt() {
				return sync(() => this.PRNG.integer(Number.MAX_SAFE_INTEGER))
			}
			nextRange(min, max) {
				return core_map(this.next, n => (max - min) * n + min)
			}
			nextIntBetween(min, max) {
				return sync(() => this.PRNG.integer(max - min) + min)
			}
			shuffle(elements) {
				return shuffleWith(elements, n => this.nextIntBetween(0, n))
			}
		}
		const shuffleWith = (elements, nextIntBounded) =>
				suspend(() =>
					pipe(
						sync(() => Array.from(elements)),
						core_flatMap(buffer => {
							const numbers = []
							for (let i = buffer.length; i >= 2; i -= 1) numbers.push(i)
							return pipe(
								numbers,
								forEachSequentialDiscard(n =>
									pipe(
										nextIntBounded(n),
										core_map(k => random_swap(buffer, n - 1, k)),
									),
								),
								core_as(Chunk_fromIterable(buffer)),
							)
						}),
					),
				),
			random_swap = (buffer, index1, index2) => {
				const tmp = buffer[index1]
				buffer[index1] = buffer[index2]
				buffer[index2] = tmp
				return buffer
			},
			random_make = seed => new RandomImpl(Hash_hash(seed)),
			TracerTypeId = Symbol.for("effect/Tracer"),
			tracer_make = options => ({ [TracerTypeId]: TracerTypeId, ...options }),
			tracerTag = GenericTag("effect/Tracer"),
			spanTag = GenericTag("effect/ParentSpan"),
			randomHexString = (function () {
				return function (length) {
					let result = ""
					for (let i = 0; i < length; i++)
						result += "abcdef0123456789".charAt(Math.floor(16 * Math.random()))
					return result
				}
			})()
		class NativeSpan {
			name
			parent
			context
			startTime
			kind
			_tag = "Span"
			spanId
			traceId = "native"
			sampled = !0
			status
			attributes
			events = []
			links
			constructor(name, parent, context, links, startTime, kind) {
				this.name = name
				this.parent = parent
				this.context = context
				this.startTime = startTime
				this.kind = kind
				this.status = { _tag: "Started", startTime }
				this.attributes = new Map()
				this.traceId =
					"Some" === parent._tag ? parent.value.traceId : randomHexString(32)
				this.spanId = randomHexString(16)
				this.links = Array.from(links)
			}
			end(endTime, exit) {
				this.status = {
					_tag: "Ended",
					endTime,
					exit,
					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)
			}
		}
		const nativeTracer = tracer_make({
				span: (name, parent, context, links, startTime, kind) =>
					new NativeSpan(name, parent, context, links, startTime, kind),
				context: f => f(),
			}),
			DisablePropagation = Context_Reference()(
				"effect/Tracer/DisablePropagation",
				{ defaultValue: constFalse },
			),
			liveServices = pipe(
				Context_empty(),
				Context_add(clockTag, clock_make()),
				Context_add(consoleTag, defaultConsole),
				Context_add(randomTag, random_make(Math.random())),
				Context_add(configProviderTag, fromEnv()),
				Context_add(tracerTag, nativeTracer),
			),
			currentServices = globalValue(
				Symbol.for("effect/DefaultServices/currentServices"),
				() => fiberRefUnsafeMakeContext(liveServices),
			),
			clockWith = f =>
				(f => withFiberRuntime(fiber => f(fiber.currentDefaultServices)))(
					services => f(services.unsafeMap.get(clockTag.key)),
				),
			currentTimeMillis = clockWith(clock => clock.currentTimeMillis),
			Boolean_Order = Order_boolean,
			Effectable_EffectPrototype = EffectPrototype,
			Effectable_Base = effectable_Base
		class Effectable_Class extends Effectable_Base {}
		const executionStrategy_sequential = { _tag: "Sequential" },
			executionStrategy_parallel = { _tag: "Parallel" },
			ExecutionStrategy_sequential = executionStrategy_sequential,
			ExecutionStrategy_parallel = executionStrategy_parallel,
			ExecutionStrategy_parallelN = parallelism => ({
				_tag: "ParallelN",
				parallelism,
			}),
			FiberRefsSym = Symbol.for("effect/FiberRefs")
		class FiberRefsImpl {
			locals;
			[FiberRefsSym] = FiberRefsSym
			constructor(locals) {
				this.locals = locals
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const joinAs = dual(3, (self, fiberId, that) => {
				const parentFiberRefs = new Map(self.locals)
				that.locals.forEach((childStack, fiberRef) => {
					const childValue = childStack[0][1]
					if (!childStack[0][0][Equal_symbol](fiberId)) {
						if (!parentFiberRefs.has(fiberRef)) {
							if (equals(childValue, fiberRef.initial)) return
							parentFiberRefs.set(fiberRef, [
								[fiberId, fiberRef.join(fiberRef.initial, childValue)],
							])
							return
						}
						const parentStack = parentFiberRefs.get(fiberRef),
							[ancestor, wasModified] = ((
								_ref,
								_parentStack,
								_childStack,
								_childModified = !1,
							) => {
								const ref = _ref
								let ret,
									parentStack = _parentStack,
									childStack = _childStack,
									childModified = _childModified
								for (; void 0 === ret;)
									if (
										isNonEmptyReadonlyArray(parentStack) &&
										isNonEmptyReadonlyArray(childStack)
									) {
										const 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
											parentFiberId.id > childFiberId.id
												? (parentStack = parentAncestors)
												: (ret = [childRefValue, childModified])
									} else ret = [ref.initial, !0]
								return ret
							})(fiberRef, parentStack, childStack)
						if (wasModified) {
							const patch = fiberRef.diff(ancestor, childValue),
								oldValue = parentStack[0][1],
								newValue = fiberRef.join(
									oldValue,
									fiberRef.patch(patch)(oldValue),
								)
							if (!equals(oldValue, newValue)) {
								let newStack
								const parentFiberId = parentStack[0][0]
								newStack = parentFiberId[Equal_symbol](fiberId)
									? [[parentFiberId, newValue], ...parentStack.slice(1)]
									: [[fiberId, newValue], ...parentStack]
								parentFiberRefs.set(fiberRef, newStack)
							}
						}
					}
				})
				return new FiberRefsImpl(parentFiberRefs)
			}),
			forkAs = dual(2, (self, childId) => {
				const map = new Map()
				unsafeForkAs(self, map, childId)
				return new FiberRefsImpl(map)
			}),
			unsafeForkAs = (self, map, fiberId) => {
				self.locals.forEach((stack, fiberRef) => {
					const oldValue = stack[0][1],
						newValue = fiberRef.patch(fiberRef.fork)(oldValue)
					equals(oldValue, newValue)
						? map.set(fiberRef, stack)
						: map.set(fiberRef, [[fiberId, newValue], ...stack])
				})
			},
			delete_ = dual(2, (self, fiberRef) => {
				const locals = new Map(self.locals)
				locals.delete(fiberRef)
				return new FiberRefsImpl(locals)
			}),
			fiberRefs_get = dual(2, (self, fiberRef) =>
				self.locals.has(fiberRef)
					? Option_some(headNonEmpty(self.locals.get(fiberRef))[1])
					: Option_none(),
			),
			getOrDefault = dual(2, (self, fiberRef) =>
				pipe(
					fiberRefs_get(self, fiberRef),
					Option_getOrElse(() => fiberRef.initial),
				),
			),
			updateAs = dual(2, (self, { fiberId, fiberRef, value }) => {
				if (0 === self.locals.size)
					return new FiberRefsImpl(new Map([[fiberRef, [[fiberId, value]]]]))
				const locals = new Map(self.locals)
				unsafeUpdateAs(locals, fiberId, fiberRef, value)
				return new FiberRefsImpl(locals)
			}),
			unsafeUpdateAs = (locals, fiberId, fiberRef, value) => {
				const oldStack = locals.get(fiberRef) ?? []
				let newStack
				if (isNonEmptyReadonlyArray(oldStack)) {
					const [currentId, currentValue] = headNonEmpty(oldStack)
					if (currentId[Equal_symbol](fiberId)) {
						if (equals(currentValue, value)) return
						newStack = [[fiberId, value], ...oldStack.slice(1)]
					} else newStack = [[fiberId, value], ...oldStack]
				} else newStack = [[fiberId, value]]
				locals.set(fiberRef, newStack)
			},
			updateManyAs = dual(2, (self, { entries, forkAs }) => {
				if (0 === self.locals.size) return new FiberRefsImpl(new Map(entries))
				const locals = new Map(self.locals)
				void 0 !== forkAs && unsafeForkAs(self, locals, forkAs)
				entries.forEach(([fiberRef, values]) => {
					1 === values.length
						? unsafeUpdateAs(locals, values[0][0], fiberRef, values[0][1])
						: values.forEach(([fiberId, value]) => {
								unsafeUpdateAs(locals, fiberId, fiberRef, value)
							})
				})
				return new FiberRefsImpl(locals)
			}),
			FiberRefs_getOrDefault = getOrDefault,
			FiberRefs_updateManyAs = updateManyAs,
			FiberRefs_empty = function () {
				return ((fiberRefLocals = new Map()), new FiberRefsImpl(fiberRefLocals))
				var fiberRefLocals
			},
			patch_empty = { _tag: "Empty" },
			patch_diff = (oldValue, newValue) => {
				const missingLocals = new Map(oldValue.locals)
				let patch = patch_empty
				for (const [fiberRef, pairs] of newValue.locals.entries()) {
					const newValue = headNonEmpty(pairs)[1],
						old = missingLocals.get(fiberRef)
					if (void 0 !== old) {
						const oldValue = headNonEmpty(old)[1]
						equals(oldValue, newValue) ||
							(patch = patch_combine({
								_tag: "Update",
								fiberRef,
								patch: fiberRef.diff(oldValue, newValue),
							})(patch))
					} else
						patch = patch_combine({ _tag: "Add", fiberRef, value: newValue })(
							patch,
						)
					missingLocals.delete(fiberRef)
				}
				for (const [fiberRef] of missingLocals.entries())
					patch = patch_combine({ _tag: "Remove", fiberRef })(patch)
				return patch
			},
			patch_combine = dual(2, (self, that) => ({
				_tag: "AndThen",
				first: self,
				second: that,
			})),
			patch_patch = dual(3, (self, fiberId, oldValue) => {
				let fiberRefs = oldValue,
					patches = Array_of(self)
				for (; isNonEmptyReadonlyArray(patches);) {
					const head = headNonEmpty(patches),
						tail = tailNonEmpty(patches)
					switch (head._tag) {
						case "Empty":
							patches = tail
							break
						case "Add":
							fiberRefs = updateAs(fiberRefs, {
								fiberId,
								fiberRef: head.fiberRef,
								value: head.value,
							})
							patches = tail
							break
						case "Remove":
							fiberRefs = delete_(fiberRefs, head.fiberRef)
							patches = tail
							break
						case "Update": {
							const value = getOrDefault(fiberRefs, head.fiberRef)
							fiberRefs = updateAs(fiberRefs, {
								fiberId,
								fiberRef: head.fiberRef,
								value: head.fiberRef.patch(head.patch)(value),
							})
							patches = tail
							break
						}
						case "AndThen":
							patches = Array_prepend(head.first)(
								Array_prepend(head.second)(tail),
							)
					}
				}
				return fiberRefs
			}),
			FiberRefsPatch_diff = patch_diff,
			FiberRefsPatch_patch = patch_patch,
			FiberStatusTypeId = Symbol.for("effect/FiberStatus"),
			DoneHash = string("effect/FiberStatus-Done")
		class Done {
			[FiberStatusTypeId] = FiberStatusTypeId
			_tag = "Done";
			[symbol]() {
				return DoneHash
			}
			[Equal_symbol](that) {
				return isFiberStatus(that) && "Done" === that._tag
			}
		}
		class Running {
			runtimeFlags;
			[FiberStatusTypeId] = FiberStatusTypeId
			_tag = "Running"
			constructor(runtimeFlags) {
				this.runtimeFlags = runtimeFlags
			}
			[symbol]() {
				return pipe(
					Hash_hash("effect/FiberStatus"),
					combine(Hash_hash(this._tag)),
					combine(Hash_hash(this.runtimeFlags)),
					cached(this),
				)
			}
			[Equal_symbol](that) {
				return (
					isFiberStatus(that) &&
					"Running" === that._tag &&
					this.runtimeFlags === that.runtimeFlags
				)
			}
		}
		class Suspended {
			runtimeFlags
			blockingOn;
			[FiberStatusTypeId] = FiberStatusTypeId
			_tag = "Suspended"
			constructor(runtimeFlags, blockingOn) {
				this.runtimeFlags = runtimeFlags
				this.blockingOn = blockingOn
			}
			[symbol]() {
				return pipe(
					Hash_hash("effect/FiberStatus"),
					combine(Hash_hash(this._tag)),
					combine(Hash_hash(this.runtimeFlags)),
					combine(Hash_hash(this.blockingOn)),
					cached(this),
				)
			}
			[Equal_symbol](that) {
				return (
					isFiberStatus(that) &&
					"Suspended" === that._tag &&
					this.runtimeFlags === that.runtimeFlags &&
					equals(this.blockingOn, that.blockingOn)
				)
			}
		}
		const isFiberStatus = u => hasProperty(u, FiberStatusTypeId),
			FiberStatus_done = new Done(),
			FiberStatus_running = runtimeFlags => new Running(runtimeFlags),
			Fatal = logLevelFatal,
			LogLevel_Error = logLevelError,
			Warning = logLevelWarning,
			Info = logLevelInfo,
			Debug = logLevelDebug,
			Trace = logLevelTrace,
			locally = dual(2, (use, self) =>
				fiberRefLocally(use, currentLogLevel, self),
			),
			LogLevel_Order = pipe(
				Number_Order,
				Order_mapInput(level => level.ordinal),
			),
			LogLevel_greaterThan = greaterThan(LogLevel_Order),
			greaterThanEqual = greaterThanOrEqualTo(LogLevel_Order),
			Micro_TypeId = Symbol.for("effect/Micro"),
			MicroExitTypeId = Symbol.for("effect/Micro/MicroExit"),
			MicroCauseTypeId = Symbol.for("effect/Micro/MicroCause"),
			microCauseVariance = { _E: identity }
		class MicroCauseImpl extends globalThis.Error {
			_tag
			traces;
			[MicroCauseTypeId]
			constructor(_tag, originalError, traces) {
				const causeName = `MicroCause.${_tag}`
				let name, message, stack
				if (originalError instanceof globalThis.Error) {
					name = `(${causeName}) ${originalError.name}`
					message = originalError.message
					const messageLines = message.split("\n").length
					stack = originalError.stack
						? `(${causeName}) ${originalError.stack
								.split("\n")
								.slice(0, messageLines + 3)
								.join("\n")}`
						: `${name}: ${message}`
				} else {
					name = causeName
					message = toStringUnknown(originalError, 0)
					stack = `${name}: ${message}`
				}
				traces.length > 0 && (stack += `\n    ${traces.join("\n    ")}`)
				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
			}
		}
		class Interrupt extends MicroCauseImpl {
			constructor(traces = []) {
				super("Interrupt", "interrupted", traces)
			}
		}
		const causeInterrupt = (traces = []) => new Interrupt(traces),
			causeIsInterrupt = self => "Interrupt" === self._tag,
			MicroFiberTypeId = Symbol.for("effect/Micro/MicroFiber"),
			fiberVariance = { _A: identity, _E: identity }
		class MicroFiberImpl {
			context
			interruptible;
			[MicroFiberTypeId]
			_stack = []
			_observers = []
			_exit
			_children
			currentOpCount = 0
			constructor(context, interruptible = !0) {
				this.context = context
				this.interruptible = interruptible
				this[MicroFiberTypeId] = fiberVariance
			}
			getRef(ref) {
				return ((self, tag) =>
					self.unsafeMap.has(tag.key)
						? self.unsafeMap.get(tag.key)
						: getDefaultValue(tag))(this.context, ref)
			}
			addObserver(cb) {
				if (this._exit) {
					cb(this._exit)
					return constVoid
				}
				this._observers.push(cb)
				return () => {
					const index = this._observers.indexOf(cb)
					index >= 0 && this._observers.splice(index, 1)
				}
			}
			_interrupted = !1
			unsafeInterrupt() {
				if (!this._exit) {
					this._interrupted = !0
					this.interruptible && this.evaluate(Micro_exitInterrupt)
				}
			}
			unsafePoll() {
				return this._exit
			}
			evaluate(effect) {
				if (this._exit) return
				if (void 0 !== this._yielded) {
					const yielded = this._yielded
					this._yielded = void 0
					yielded()
				}
				const exit = this.runLoop(effect)
				if (exit === Yield) return
				const interruptChildren =
					fiberMiddleware.interruptChildren &&
					fiberMiddleware.interruptChildren(this)
				if (void 0 !== interruptChildren)
					return this.evaluate(Micro_flatMap(interruptChildren, () => exit))
				this._exit = exit
				for (let i = 0; i < this._observers.length; i++)
					this._observers[i](exit)
				this._observers.length = 0
			}
			runLoop(effect) {
				let yielding = !1,
					current = effect
				this.currentOpCount = 0
				try {
					for (;;) {
						this.currentOpCount++
						if (!yielding && this.getRef(CurrentScheduler).shouldYield(this)) {
							yielding = !0
							const prev = current
							current = Micro_flatMap(Micro_yieldNow, () => prev)
						}
						current = current[evaluate](this)
						if (current === Yield) {
							const yielded = this._yielded
							if (MicroExitTypeId in yielded) {
								this._yielded = void 0
								return yielded
							}
							return Yield
						}
					}
				} catch (error) {
					return hasProperty(current, evaluate)
						? Micro_exitDie(error)
						: Micro_exitDie(
								`MicroFiber.runLoop: Not a valid effect: ${String(current)}`,
							)
				}
			}
			getCont(symbol) {
				for (;;) {
					const op = this._stack.pop()
					if (!op) return
					const cont = op[ensureCont] && op[ensureCont](this)
					if (cont) return { [symbol]: cont }
					if (op[symbol]) return op
				}
			}
			_yielded = void 0
			yieldWith(value) {
				this._yielded = value
				return Yield
			}
			children() {
				return (this._children ??= new Set())
			}
		}
		const fiberMiddleware = globalValue("effect/Micro/fiberMiddleware", () => ({
				interruptChildren: void 0,
			})),
			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 = {
				...Effectable_EffectPrototype,
				_op: "Micro",
				[Micro_TypeId]: 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 Micro_exitDie("Micro.evaluate: Not implemented")
		}
		const makePrimitiveProto = options => ({
				...MicroProto,
				[identifier]: options.op,
				[evaluate]: options.eval ?? defaultEvaluate,
				[successCont]: options.contA,
				[failureCont]: options.contE,
				[ensureCont]: options.ensure,
			}),
			makePrimitive = options => {
				const Proto = makePrimitiveProto(options)
				return function () {
					const self = Object.create(Proto)
					self[args] = !1 === options.single ? arguments : arguments[0]
					return self
				}
			},
			makeExit = options => {
				const Proto = {
					...makePrimitiveProto(options),
					[MicroExitTypeId]: MicroExitTypeId,
					_tag: options.op,
					get [options.prop]() {
						return this[args]
					},
					toJSON() {
						return {
							_id: "MicroExit",
							_tag: options.op,
							[options.prop]: this[args],
						}
					},
					[Equal_symbol](that) {
						return (
							isMicroExit(that) &&
							that._tag === options.op &&
							equals(this[args], that[args])
						)
					},
					[symbol]() {
						return cached(
							this,
							combine(string(options.op))(Hash_hash(this[args])),
						)
					},
				}
				return function (value) {
					const self = Object.create(Proto)
					self[args] = value
					self[successCont] = void 0
					self[failureCont] = void 0
					self[ensureCont] = void 0
					return self
				}
			},
			Micro_succeed = makeExit({
				op: "Success",
				prop: "value",
				eval(fiber) {
					const cont = fiber.getCont(successCont)
					return cont
						? cont[successCont](this[args], fiber)
						: fiber.yieldWith(this)
				},
			}),
			Micro_failCause = makeExit({
				op: "Failure",
				prop: "cause",
				eval(fiber) {
					let cont = fiber.getCont(failureCont)
					for (; causeIsInterrupt(this[args]) && cont && fiber.interruptible;)
						cont = fiber.getCont(failureCont)
					return cont
						? cont[failureCont](this[args], fiber)
						: fiber.yieldWith(this)
				},
			}),
			Micro_yieldNow = makePrimitive({
				op: "Yield",
				eval(fiber) {
					let resumed = !1
					fiber.getRef(CurrentScheduler).scheduleTask(() => {
						resumed || fiber.evaluate(Micro_exitVoid)
					}, this[args] ?? 0)
					return fiber.yieldWith(() => {
						resumed = !0
					})
				},
			})(0),
			Micro_void_ = Micro_succeed(void 0),
			withMicroFiber = makePrimitive({
				op: "WithMicroFiber",
				eval(fiber) {
					return this[args](fiber)
				},
			}),
			Micro_flatMap = dual(2, (self, f) => {
				const onSuccess = Object.create(OnSuccessProto)
				onSuccess[args] = self
				onSuccess[successCont] = f
				return onSuccess
			}),
			OnSuccessProto = makePrimitiveProto({
				op: "OnSuccess",
				eval(fiber) {
					fiber._stack.push(this)
					return this[args]
				},
			}),
			isMicroExit = u => hasProperty(u, MicroExitTypeId),
			Micro_exitSucceed = Micro_succeed,
			Micro_exitFailCause = Micro_failCause,
			Micro_exitInterrupt = Micro_exitFailCause(causeInterrupt()),
			Micro_exitDie = defect =>
				Micro_exitFailCause(
					((defect, traces = []) => new Die(defect, traces))(defect),
				),
			Micro_exitVoid = Micro_exitSucceed(void 0),
			setImmediate =
				"setImmediate" in globalThis
					? globalThis.setImmediate
					: f => setTimeout(f, 0)
		class MicroSchedulerDefault {
			tasks = []
			running = !1
			scheduleTask(task, _priority) {
				this.tasks.push(task)
				if (!this.running) {
					this.running = !0
					setImmediate(this.afterScheduled)
				}
			}
			afterScheduled = () => {
				this.running = !1
				this.runTasks()
			}
			runTasks() {
				const 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() {
				for (; this.tasks.length > 0;) this.runTasks()
			}
		}
		const updateContext = dual(2, (self, f) =>
				withMicroFiber(fiber => {
					const prev = fiber.context
					fiber.context = f(prev)
					return Micro_onExit(self, () => {
						fiber.context = prev
						return Micro_void_
					})
				}),
			),
			Micro_provideContext = dual(2, (self, provided) =>
				updateContext(self, Context_merge(provided)),
			)
		class MaxOpsBeforeYield extends Context_Reference()(
			"effect/Micro/currentMaxOpsBeforeYield",
			{ defaultValue: () => 2048 },
		) {}
		class CurrentScheduler extends Context_Reference()(
			"effect/Micro/currentScheduler",
			{ defaultValue: () => new MicroSchedulerDefault() },
		) {}
		const Micro_matchCauseEffect = dual(2, (self, options) => {
				const primitive = Object.create(OnSuccessAndFailureProto)
				primitive[args] = self
				primitive[successCont] = options.onSuccess
				primitive[failureCont] = options.onFailure
				return primitive
			}),
			OnSuccessAndFailureProto = makePrimitiveProto({
				op: "OnSuccessAndFailure",
				eval(fiber) {
					fiber._stack.push(this)
					return this[args]
				},
			}),
			Micro_onExit = dual(2, (self, f) =>
				Micro_uninterruptibleMask(restore =>
					Micro_matchCauseEffect(restore(self), {
						onFailure: cause =>
							Micro_flatMap(f(Micro_exitFailCause(cause)), () =>
								Micro_failCause(cause),
							),
						onSuccess: a =>
							Micro_flatMap(f(Micro_exitSucceed(a)), () => Micro_succeed(a)),
					}),
				),
			),
			setInterruptible = makePrimitive({
				op: "SetInterruptible",
				ensure(fiber) {
					fiber.interruptible = this[args]
					if (fiber._interrupted && fiber.interruptible)
						return () => Micro_exitInterrupt
				},
			}),
			Micro_interruptible = self =>
				withMicroFiber(fiber => {
					if (fiber.interruptible) return self
					fiber.interruptible = !0
					fiber._stack.push(setInterruptible(!1))
					return fiber._interrupted ? Micro_exitInterrupt : self
				}),
			Micro_uninterruptibleMask = f =>
				withMicroFiber(fiber => {
					if (!fiber.interruptible) return f(identity)
					fiber.interruptible = !1
					fiber._stack.push(setInterruptible(!0))
					return f(Micro_interruptible)
				}),
			Readable_TypeId = Symbol.for("effect/Readable"),
			RefTypeId = Symbol.for("effect/Ref"),
			refVariance = { _A: _ => _ }
		class RefImpl extends Effectable_Class {
			ref
			commit() {
				return this.get
			}
			[RefTypeId] = refVariance;
			[Readable_TypeId] = Readable_TypeId
			constructor(ref) {
				super()
				this.ref = ref
				this.get = sync(() => MutableRef_get(this.ref))
			}
			get;
			modify(f) {
				return sync(() => {
					const current = MutableRef_get(this.ref),
						[b, a] = f(current)
					current !== a && MutableRef_set(a)(this.ref)
					return b
				})
			}
		}
		const ref_unsafeMake = value => new RefImpl(MutableRef_make(value)),
			ref_make = value => sync(() => ref_unsafeMake(value)),
			ref_get = self => self.get,
			ref_set = dual(2, (self, value) => self.modify(() => [void 0, value])),
			ref_modify = dual(2, (self, f) => self.modify(f)),
			ref_update = dual(2, (self, f) => self.modify(a => [void 0, f(a)])),
			Ref_RefTypeId = RefTypeId,
			Ref_make = ref_make,
			Ref_get = ref_get,
			Ref_modify = ref_modify,
			Ref_set = ref_set,
			Ref_update = ref_update
		class SchedulerRunner {
			scheduleDrain
			running = !1
			tasks = new PriorityBuckets()
			constructor(scheduleDrain) {
				this.scheduleDrain = scheduleDrain
			}
			starveInternal = depth => {
				const tasks = this.tasks.buckets
				this.tasks.buckets = []
				for (const [_, toRun] of tasks)
					for (let i = 0; i < toRun.length; i++) toRun[i]()
				0 === this.tasks.buckets.length
					? (this.running = !1)
					: this.starve(depth)
			}
			starve(depth = 0) {
				this.scheduleDrain(depth, this.starveInternal)
			}
			scheduleTask(task, priority) {
				this.tasks.scheduleTask(task, priority)
				if (!this.running) {
					this.running = !0
					this.starve()
				}
			}
			static cached(scheduleDrain) {
				const fallback = new SchedulerRunner(scheduleDrain),
					runners = new WeakMap()
				return fiber => {
					if (void 0 === fiber) return fallback
					let runner = runners.get(fiber)
					if (void 0 === runner) {
						runner = new SchedulerRunner(scheduleDrain)
						runners.set(fiber, runner)
					}
					return runner
				}
			}
		}
		class PriorityBuckets {
			buckets = []
			scheduleTask(task, priority) {
				const length = this.buckets.length
				let bucket,
					index = 0
				for (; index < length && this.buckets[index][0] <= priority; index++)
					bucket = this.buckets[index]
				bucket && bucket[0] === priority
					? bucket[1].push(task)
					: index === length
						? this.buckets.push([priority, [task]])
						: this.buckets.splice(index, 0, [priority, [task]])
			}
		}
		class MixedScheduler {
			maxNextTickBeforeTimer
			getRunner = SchedulerRunner.cached((depth, drain) => {
				depth >= this.maxNextTickBeforeTimer
					? setTimeout(() => drain(0), 0)
					: Promise.resolve(void 0).then(() => drain(depth + 1))
			})
			constructor(maxNextTickBeforeTimer) {
				this.maxNextTickBeforeTimer = maxNextTickBeforeTimer
			}
			shouldYield(fiber) {
				return (
					fiber.currentOpCount > fiber.getFiberRef(currentMaxOpsBeforeYield) &&
					fiber.getFiberRef(currentSchedulingPriority)
				)
			}
			scheduleTask(task, priority, fiber) {
				this.getRunner(fiber).scheduleTask(task, priority)
			}
		}
		const defaultScheduler = globalValue(
			Symbol.for("effect/Scheduler/defaultScheduler"),
			() => new MixedScheduler(2048),
		)
		class SyncScheduler {
			tasks = new PriorityBuckets()
			deferred = !1
			scheduleTask(task, priority, fiber) {
				this.deferred
					? defaultScheduler.scheduleTask(task, priority, fiber)
					: this.tasks.scheduleTask(task, priority)
			}
			shouldYield(fiber) {
				return (
					fiber.currentOpCount > fiber.getFiberRef(currentMaxOpsBeforeYield) &&
					fiber.getFiberRef(currentSchedulingPriority)
				)
			}
			flush() {
				for (; this.tasks.buckets.length > 0;) {
					const tasks = this.tasks.buckets
					this.tasks.buckets = []
					for (const [_, toRun] of tasks)
						for (let i = 0; i < toRun.length; i++) toRun[i]()
				}
				this.deferred = !0
			}
		}
		const currentScheduler = globalValue(
				Symbol.for("effect/FiberRef/currentScheduler"),
				() => fiberRefUnsafeMake(defaultScheduler),
			),
			par = (self, that) => ({ _tag: "Par", left: self, right: that }),
			seq = (self, that) => ({ _tag: "Seq", left: self, right: that }),
			blockedRequests_step = requests => {
				let current = requests,
					parallel = parallelCollectionEmpty(),
					stack = List_empty(),
					sequential = List_empty()
				for (;;)
					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": {
							const left = current.left,
								right = current.right
							switch (left._tag) {
								case "Empty":
									current = right
									break
								case "Par": {
									const l = left.left,
										r = left.right
									current = par(seq(l, right), seq(r, right))
									break
								}
								case "Seq": {
									const l = left.left,
										r = left.right
									current = seq(l, seq(r, right))
									break
								}
								case "Single":
									current = left
									sequential = cons(right, sequential)
							}
							break
						}
						case "Single":
							parallel = parallelCollectionAdd(parallel, current)
							if (isNil(stack)) return [parallel, sequential]
							current = stack.head
							stack = stack.tail
					}
				throw new Error(
					"BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues",
				)
			},
			blockedRequests_merge = (sequential, parallel) => {
				if (isNil(sequential))
					return List_of(parallelCollectionToSequentialCollection(parallel))
				if (parallelCollectionIsEmpty(parallel)) return sequential
				const seqHeadKeys = sequentialCollectionKeys(sequential.head),
					parKeys = parallelCollectionKeys(parallel)
				return 1 === seqHeadKeys.length &&
					1 === parKeys.length &&
					equals(seqHeadKeys[0], parKeys[0])
					? cons(
							sequentialCollectionCombine(
								sequential.head,
								parallelCollectionToSequentialCollection(parallel),
							),
							sequential.tail,
						)
					: cons(parallelCollectionToSequentialCollection(parallel), sequential)
			},
			RequestBlockParallelTypeId = Symbol.for(
				"effect/RequestBlock/RequestBlockParallel",
			),
			parallelVariance = { _R: _ => _ }
		class ParallelImpl {
			map;
			[RequestBlockParallelTypeId] = parallelVariance
			constructor(map) {
				this.map = map
			}
		}
		const parallelCollectionEmpty = () => new ParallelImpl(HashMap_empty()),
			parallelCollectionAdd = (self, blockedRequest) =>
				new ParallelImpl(
					HashMap_modifyAt(self.map, blockedRequest.dataSource, _ =>
						orElseSome(
							Option_map(_, Chunk_append(blockedRequest.blockedRequest)),
							() => Chunk_of(blockedRequest.blockedRequest),
						),
					),
				),
			parallelCollectionCombine = (self, that) =>
				new ParallelImpl(
					HashMap_reduce(self.map, that.map, (map, value, key) =>
						HashMap_set(
							map,
							key,
							Option_match(HashMap_get(map, key), {
								onNone: () => value,
								onSome: other => Chunk_appendAll(value, other),
							}),
						),
					),
				),
			parallelCollectionIsEmpty = self =>
				(self => self && isEmptyNode(self._root))(self.map),
			parallelCollectionKeys = self => Array.from(HashMap_keys(self.map)),
			parallelCollectionToSequentialCollection = self =>
				sequentialCollectionMake(HashMap_map(self.map, x => Chunk_of(x))),
			SequentialCollectionTypeId = Symbol.for(
				"effect/RequestBlock/RequestBlockSequential",
			),
			sequentialVariance = { _R: _ => _ }
		class SequentialImpl {
			map;
			[SequentialCollectionTypeId] = sequentialVariance
			constructor(map) {
				this.map = map
			}
		}
		const sequentialCollectionMake = map => new SequentialImpl(map),
			sequentialCollectionCombine = (self, that) =>
				new SequentialImpl(
					HashMap_reduce(that.map, self.map, (map, value, key) =>
						HashMap_set(
							map,
							key,
							Option_match(HashMap_get(map, key), {
								onNone: () => esm_Chunk_empty(),
								onSome: a => Chunk_appendAll(a, value),
							}),
						),
					),
				),
			sequentialCollectionKeys = self => Array.from(HashMap_keys(self.map)),
			currentRequestMap = globalValue(
				Symbol.for("effect/FiberRef/currentRequestMap"),
				() => fiberRefUnsafeMake(new Map()),
			),
			concurrency_match = (concurrency, sequential, unbounded, bounded) => {
				switch (concurrency) {
					case void 0:
						return sequential()
					case "unbounded":
						return unbounded()
					case "inherit":
						return fiberRefGetWith(currentConcurrency, concurrency =>
							"unbounded" === concurrency
								? unbounded()
								: concurrency > 1
									? bounded(concurrency)
									: sequential(),
						)
					default:
						return concurrency > 1 ? bounded(concurrency) : sequential()
				}
			},
			Clock_currentTimeMillis = currentTimeMillis,
			formatLabel = key => key.replace(/[\s="]/g, "_"),
			logSpan_render = now => self =>
				`${formatLabel(self.label)}=${now - self.startTime}ms`,
			MetricLabelTypeId = Symbol.for("effect/MetricLabel")
		class MetricLabelImpl {
			key
			value;
			[MetricLabelTypeId] = MetricLabelTypeId
			_hash
			constructor(key, value) {
				this.key = key
				this.value = value
				this._hash = string("effect/MetricLabel" + this.key + this.value)
			}
			[symbol]() {
				return this._hash
			}
			[Equal_symbol](that) {
				return (
					isMetricLabel(that) &&
					this.key === that.key &&
					this.value === that.value
				)
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const label_make = (key, value) => new MetricLabelImpl(key, value),
			isMetricLabel = u => hasProperty(u, MetricLabelTypeId),
			annotateLogs = dual(
				args => isEffect(args[0]),
				function () {
					const args = arguments
					return fiberRefLocallyWith(
						args[0],
						currentLogAnnotations,
						"string" == typeof args[1]
							? HashMap_set(args[1], args[2])
							: annotations =>
									Object.entries(args[1]).reduce(
										(acc, [key, value]) => HashMap_set(acc, key, value),
										annotations,
									),
					)
				},
			),
			catchSomeCause = dual(2, (self, f) =>
				matchCauseEffect(self, {
					onFailure: cause => {
						const option = f(cause)
						switch (option._tag) {
							case "None":
								return failCause(cause)
							case "Some":
								return option.value
						}
					},
					onSuccess: succeed,
				}),
			),
			filterOrElse = dual(3, (self, predicate, orElse) =>
				core_flatMap(self, a => (predicate(a) ? succeed(a) : orElse(a))),
			),
			core_effect_filterOrFail = dual(
				args => isEffect(args[0]),
				(self, predicate, orFailWith) =>
					filterOrElse(self, predicate, a =>
						void 0 === orFailWith
							? core_fail(new NoSuchElementException())
							: failSync(() => orFailWith(a)),
					),
			),
			core_effect_match = dual(2, (self, options) =>
				matchEffect(self, {
					onFailure: e => succeed(options.onFailure(e)),
					onSuccess: a => succeed(options.onSuccess(a)),
				}),
			),
			core_effect_fiberRefs = withFiberRuntime(state =>
				succeed(state.getFiberRefs()),
			),
			logWithLevel =
				level =>
				(...message) => {
					const levelOption = Option_fromNullable(level)
					let cause
					for (let i = 0, len = message.length; i < len; i++) {
						const msg = message[i]
						if (isCause(msg)) {
							cause = void 0 !== cause ? sequential(cause, msg) : msg
							message = [...message.slice(0, i), ...message.slice(i + 1)]
							i--
						}
					}
					void 0 === cause && (cause = cause_empty)
					return withFiberRuntime(fiberState => {
						fiberState.log(message, cause, levelOption)
						return core_void_
					})
				},
			log = logWithLevel(),
			logDebug = logWithLevel(Debug),
			logInfo = logWithLevel(Info),
			logWarning = logWithLevel(Warning),
			logError = logWithLevel(LogLevel_Error),
			core_effect_mapErrorCause = dual(2, (self, f) =>
				matchCauseEffect(self, {
					onFailure: c => failCauseSync(() => f(c)),
					onSuccess: succeed,
				}),
			),
			core_effect_orElseSucceed = dual(2, (self, evaluate) =>
				core_orElse(self, () => sync(evaluate)),
			),
			core_effect_provideService = dual(3, (self, tag, service) =>
				contextWithEffect(env =>
					provideContext(self, Context_add(env, tag, service)),
				),
			),
			core_effect_provideServiceEffect = dual(3, (self, tag, effect) =>
				contextWithEffect(env =>
					core_flatMap(effect, service =>
						provideContext(self, pipe(env, Context_add(tag, service))),
					),
				),
			),
			core_effect_sleep = duration => {
				const decodedDuration = decode(duration)
				return clockWith(clock => clock.sleep(decodedDuration))
			},
			core_effect_succeedNone = succeed(Option_none()),
			summarized = dual(3, (self, summary, f) =>
				core_flatMap(summary, start =>
					core_flatMap(self, value =>
						core_map(summary, end => [f(start, end), value]),
					),
				),
			),
			core_effect_tapErrorCause = dual(2, (self, f) =>
				matchCauseEffect(self, {
					onFailure: cause => core_zipRight(f(cause), failCause(cause)),
					onSuccess: succeed,
				}),
			),
			core_effect_when = dual(2, (self, condition) =>
				suspend(() =>
					condition() ? core_map(self, Option_some) : succeed(Option_none()),
				),
			),
			filterDisablePropagation = Option_flatMap(span =>
				Context_get(span.context, DisablePropagation)
					? "Span" === span._tag
						? filterDisablePropagation(span.parent)
						: Option_none()
					: Option_some(span),
			),
			isExit = exitIsExit,
			Exit_isFailure = self => "Failure" === self._tag,
			Exit_isSuccess = exitIsSuccess,
			Exit_all = exitCollectAll,
			Exit_die = exitDie,
			Exit_fail = exitFail,
			Exit_failCause = exitFailCause,
			Exit_map = exitMap,
			Exit_match = exitMatch,
			Exit_succeed = exitSucceed,
			Exit_void_ = exitVoid,
			Exit_zip = exitZip,
			Exit_zipRight = exitZipRight,
			OP_INTERRUPT_SIGNAL = "InterruptSignal",
			OP_STATEFUL = "Stateful",
			OP_YIELD_NOW = "YieldNow",
			interruptSignal = cause => ({ _tag: "InterruptSignal", cause }),
			stateful = onFiber => ({ _tag: "Stateful", onFiber }),
			resume = effect => ({ _tag: "Resume", effect }),
			FiberScopeTypeId = Symbol.for("effect/FiberScope")
		class Global {
			[FiberScopeTypeId] = FiberScopeTypeId
			fiberId = FiberId_none
			roots = new Set()
			add(_runtimeFlags, child) {
				this.roots.add(child)
				child.addObserver(() => {
					this.roots.delete(child)
				})
			}
		}
		class Local {
			fiberId
			parent;
			[FiberScopeTypeId] = FiberScopeTypeId
			constructor(fiberId, parent) {
				this.fiberId = fiberId
				this.parent = parent
			}
			add(_runtimeFlags, child) {
				this.parent.tell(
					stateful(parentFiber => {
						parentFiber.addChild(child)
						child.addObserver(() => {
							parentFiber.removeChild(child)
						})
					}),
				)
			}
		}
		const globalScope = globalValue(
				Symbol.for("effect/FiberScope/Global"),
				() => new Global(),
			),
			FiberTypeId = Symbol.for("effect/Fiber"),
			fiber_fiberVariance = { _E: _ => _, _A: _ => _ },
			RuntimeFiberTypeId = Symbol.for("effect/Fiber"),
			fiber_join = self =>
				core_zipLeft(core_flatten(self.await), self.inheritAll),
			currentFiberURI = "effect/FiberCurrent",
			LoggerTypeId = Symbol.for("effect/Logger"),
			loggerVariance = { _Message: _ => _, _Output: _ => _ },
			makeLogger = log => ({
				[LoggerTypeId]: loggerVariance,
				log,
				pipe() {
					return pipeArguments(this, arguments)
				},
			}),
			logger_zip = dual(2, (self, that) =>
				makeLogger(options => [self.log(options), that.log(options)]),
			),
			textOnly = /^[^\s"=]*$/,
			logger_format =
				(quoteValue, whitespace) =>
				({ annotations, cause, date, fiberId, logLevel, message, spans }) => {
					const format = (label, value) =>
							`${formatLabel(label)}=${(value => (value.match(textOnly) ? value : quoteValue(value)))(value)}`,
						append = (label, value) => " " + format(label, value)
					let out = format("timestamp", date.toISOString())
					out += append("level", logLevel.label)
					out += append("fiber", threadName(fiberId))
					const messages = (self => (Array.isArray(self) ? self : [self]))(
						message,
					)
					for (let i = 0; i < messages.length; i++)
						out += append("message", toStringUnknown(messages[i], whitespace))
					;(self => "Empty" === self._tag)(cause) ||
						(out += append("cause", pretty(cause, { renderErrorCause: !0 })))
					for (const span of spans)
						out += " " + logSpan_render(date.getTime())(span)
					for (const [label, value] of annotations)
						out += append(label, toStringUnknown(value, whitespace))
					return out
				},
			escapeDoubleQuotes = s => `"${s.replace(/\\([\s\S])|(")/g, "\\$1$2")}"`,
			stringLogger = makeLogger(logger_format(escapeDoubleQuotes)),
			hasProcessStdout =
				(JSON.stringify,
				"object" == typeof process &&
					null !== process &&
					"object" == typeof process.stdout &&
					null !== process.stdout)
		;(hasProcessStdout && process.stdout.isTTY, hasProcessStdout || globalThis)
		const MetricKeyTypeTypeId = Symbol.for("effect/MetricKeyType"),
			CounterKeyTypeTypeId = Symbol.for("effect/MetricKeyType/Counter"),
			FrequencyKeyTypeTypeId = Symbol.for("effect/MetricKeyType/Frequency"),
			GaugeKeyTypeTypeId = Symbol.for("effect/MetricKeyType/Gauge"),
			HistogramKeyTypeTypeId = Symbol.for("effect/MetricKeyType/Histogram"),
			SummaryKeyTypeTypeId = Symbol.for("effect/MetricKeyType/Summary"),
			metricKeyTypeVariance = { _In: _ => _, _Out: _ => _ }
		class CounterKeyType {
			incremental
			bigint;
			[MetricKeyTypeTypeId] = metricKeyTypeVariance;
			[CounterKeyTypeTypeId] = CounterKeyTypeTypeId
			constructor(incremental, bigint) {
				this.incremental = incremental
				this.bigint = bigint
				this._hash = string("effect/MetricKeyType/Counter")
			}
			_hash;
			[symbol]() {
				return this._hash
			}
			[Equal_symbol](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("effect/MetricKeyType/Histogram"),
					combine(Hash_hash(this.boundaries)),
				)
			}
			_hash;
			[symbol]() {
				return this._hash
			}
			[Equal_symbol](that) {
				return isHistogramKey(that) && equals(this.boundaries, that.boundaries)
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const isCounterKey = u => hasProperty(u, CounterKeyTypeTypeId),
			isHistogramKey = u => hasProperty(u, HistogramKeyTypeTypeId),
			MetricKeyTypeId = Symbol.for("effect/MetricKey"),
			metricKeyVariance = { _Type: _ => _ },
			arrayEquivilence = Array_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_hash(this.keyType)),
					combine(array(this.tags)),
				)
			}
			_hash;
			[symbol]() {
				return this._hash
			}
			[Equal_symbol](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)
			}
		}
		const isMetricKey = u => hasProperty(u, MetricKeyTypeId),
			taggedWithLabels = dual(2, (self, extraTags) =>
				0 === extraTags.length
					? self
					: new MetricKeyImpl(
							self.name,
							self.keyType,
							self.description,
							Array_union(self.tags, extraTags),
						),
			),
			MutableHashMap_TypeId = Symbol.for("effect/MutableHashMap"),
			MutableHashMapProto = {
				[MutableHashMap_TypeId]: MutableHashMap_TypeId,
				[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 (void 0 !== this.bucketIterator) return this.bucketIterator.next()
				const result = this.referentialIterator.next()
				if (result.done) {
					this.bucketIterator = new BucketIterator(this.self.buckets.values())
					return this.next()
				}
				return result
			}
			[Symbol.iterator]() {
				return new MutableHashMapIterator(this.self)
			}
		}
		class BucketIterator {
			backing
			constructor(backing) {
				this.backing = backing
			}
			currentBucket
			next() {
				if (void 0 === this.currentBucket) {
					const result = this.backing.next()
					if (result.done) return result
					this.currentBucket = result.value[Symbol.iterator]()
				}
				const result = this.currentBucket.next()
				if (result.done) {
					this.currentBucket = void 0
					return this.next()
				}
				return result
			}
		}
		const MutableHashMap_empty = () => {
				const self = Object.create(MutableHashMapProto)
				self.referential = new Map()
				self.buckets = new Map()
				self.bucketsSize = 0
				return self
			},
			MutableHashMap_get = dual(2, (self, key) => {
				if (!1 === isEqual(key))
					return self.referential.has(key)
						? Option_some(self.referential.get(key))
						: Option_none()
				const hash = key[symbol](),
					bucket = self.buckets.get(hash)
				return void 0 === bucket
					? Option_none()
					: getFromBucket(self, bucket, key)
			}),
			getFromBucket = (self, bucket, key, remove = !1) => {
				for (let i = 0, len = bucket.length; i < len; i++)
					if (key[Equal_symbol](bucket[i][0])) {
						const value = bucket[i][1]
						if (remove) {
							bucket.splice(i, 1)
							self.bucketsSize--
						}
						return Option_some(value)
					}
				return Option_none()
			},
			MutableHashMap_has = dual(2, (self, key) =>
				Option_isSome(MutableHashMap_get(self, key)),
			),
			MutableHashMap_set = dual(3, (self, key, value) => {
				if (!1 === isEqual(key)) {
					self.referential.set(key, value)
					return self
				}
				const hash = key[symbol](),
					bucket = self.buckets.get(hash)
				if (void 0 === bucket) {
					self.buckets.set(hash, [[key, value]])
					self.bucketsSize++
					return self
				}
				removeFromBucket(self, bucket, key)
				bucket.push([key, value])
				self.bucketsSize++
				return self
			}),
			removeFromBucket = (self, bucket, key) => {
				for (let i = 0, len = bucket.length; i < len; i++)
					if (key[Equal_symbol](bucket[i][0])) {
						bucket.splice(i, 1)
						self.bucketsSize--
						return
					}
			},
			MetricStateTypeId = Symbol.for("effect/MetricState"),
			CounterStateTypeId = Symbol.for("effect/MetricState/Counter"),
			FrequencyStateTypeId = Symbol.for("effect/MetricState/Frequency"),
			GaugeStateTypeId = Symbol.for("effect/MetricState/Gauge"),
			HistogramStateTypeId = Symbol.for("effect/MetricState/Histogram"),
			SummaryStateTypeId = Symbol.for("effect/MetricState/Summary"),
			metricStateVariance = { _A: _ => _ }
		class CounterState {
			count;
			[MetricStateTypeId] = metricStateVariance;
			[CounterStateTypeId] = CounterStateTypeId
			constructor(count) {
				this.count = count
			}
			[symbol]() {
				return pipe(
					Hash_hash("effect/MetricState/Counter"),
					combine(Hash_hash(this.count)),
					cached(this),
				)
			}
			[Equal_symbol](that) {
				return isCounterState(that) && this.count === that.count
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const arrayEquals = Array_getEquivalence(equals)
		class FrequencyState {
			occurrences;
			[MetricStateTypeId] = metricStateVariance;
			[FrequencyStateTypeId] = FrequencyStateTypeId
			constructor(occurrences) {
				this.occurrences = occurrences
			}
			_hash;
			[symbol]() {
				return pipe(
					string("effect/MetricState/Frequency"),
					combine(array(Array_fromIterable(this.occurrences.entries()))),
					cached(this),
				)
			}
			[Equal_symbol](that) {
				return (
					isFrequencyState(that) &&
					arrayEquals(
						Array_fromIterable(this.occurrences.entries()),
						Array_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_hash("effect/MetricState/Gauge"),
					combine(Hash_hash(this.value)),
					cached(this),
				)
			}
			[Equal_symbol](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, min, max, sum) {
				this.buckets = buckets
				this.count = count
				this.min = min
				this.max = max
				this.sum = sum
			}
			[symbol]() {
				return pipe(
					Hash_hash("effect/MetricState/Histogram"),
					combine(Hash_hash(this.buckets)),
					combine(Hash_hash(this.count)),
					combine(Hash_hash(this.min)),
					combine(Hash_hash(this.max)),
					combine(Hash_hash(this.sum)),
					cached(this),
				)
			}
			[Equal_symbol](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, min, max, sum) {
				this.error = error
				this.quantiles = quantiles
				this.count = count
				this.min = min
				this.max = max
				this.sum = sum
			}
			[symbol]() {
				return pipe(
					Hash_hash("effect/MetricState/Summary"),
					combine(Hash_hash(this.error)),
					combine(Hash_hash(this.quantiles)),
					combine(Hash_hash(this.count)),
					combine(Hash_hash(this.min)),
					combine(Hash_hash(this.max)),
					combine(Hash_hash(this.sum)),
					cached(this),
				)
			}
			[Equal_symbol](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)
			}
		}
		const 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),
			MetricHookTypeId = Symbol.for("effect/MetricHook"),
			metricHookVariance = { _In: _ => _, _Out: _ => _ },
			hook_make = options => ({
				[MetricHookTypeId]: metricHookVariance,
				pipe() {
					return pipeArguments(this, arguments)
				},
				...options,
			}),
			hook_bigint0 = BigInt(0),
			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
				for (;;) {
					if (!isNonEmptyReadonlyArray(rest_1))
						return {
							quantile: quantile_1,
							value: Option_none(),
							consumed: consumed_1,
							rest: [],
						}
					if (1 === quantile_1)
						return {
							quantile: quantile_1,
							value: Option_some(lastNonEmpty(rest_1)),
							consumed: consumed_1 + rest_1.length,
							rest: [],
						}
					const 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 = Array_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
					} else {
						if (candConsumed > desired + allowedError)
							return {
								quantile: quantile_1,
								value: Option_isNone(current_1)
									? Option_some(headValue)
									: current_1,
								consumed: consumed_1,
								rest: rest_1,
							}
						switch (current_1._tag) {
							case "None":
								error_2 = error_1
								sampleCount_2 = sampleCount_1
								current_2 = Array_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":
								if (candError < Math.abs(desired - current_1.value)) {
									error_2 = error_1
									sampleCount_2 = sampleCount_1
									current_2 = Array_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: Option_some(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",
				)
			},
			MetricPairTypeId = Symbol.for("effect/MetricPair"),
			metricPairVariance = { _Type: _ => _ },
			pair_unsafeMake = (metricKey, metricState) => ({
				[MetricPairTypeId]: metricPairVariance,
				metricKey,
				metricState,
				pipe() {
					return pipeArguments(this, arguments)
				},
			}),
			MetricRegistryTypeId = Symbol.for("effect/MetricRegistry")
		class MetricRegistryImpl {
			[MetricRegistryTypeId] = MetricRegistryTypeId
			map = MutableHashMap_empty()
			snapshot() {
				const result = []
				for (const [key, hook] of this.map)
					result.push(pair_unsafeMake(key, hook.get()))
				return result
			}
			get(key) {
				const hook = pipe(
					this.map,
					MutableHashMap_get(key),
					Option_getOrUndefined,
				)
				if (null == hook) {
					if (isCounterKey(key.keyType)) return this.getCounter(key)
					if ((u => hasProperty(u, GaugeKeyTypeTypeId))(key.keyType))
						return this.getGauge(key)
					if ((u => hasProperty(u, FrequencyKeyTypeTypeId))(key.keyType))
						return this.getFrequency(key)
					if (isHistogramKey(key.keyType)) return this.getHistogram(key)
					if ((u => hasProperty(u, SummaryKeyTypeTypeId))(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",
					)
				}
				return hook
			}
			getCounter(key) {
				let value = pipe(
					this.map,
					MutableHashMap_get(key),
					Option_getOrUndefined,
				)
				if (null == value) {
					const counter = (key => {
						let sum = key.keyType.bigint ? hook_bigint0 : 0
						const canUpdate = key.keyType.incremental
								? key.keyType.bigint
									? value => value >= hook_bigint0
									: value => value >= 0
								: _value => !0,
							update = value => {
								canUpdate(value) && (sum += value)
							}
						return hook_make({
							get: () => new CounterState(sum),
							update,
							modify: update,
						})
					})(key)
					pipe(this.map, MutableHashMap_has(key)) ||
						pipe(this.map, MutableHashMap_set(key, counter))
					value = counter
				}
				return value
			}
			getFrequency(key) {
				let value = pipe(
					this.map,
					MutableHashMap_get(key),
					Option_getOrUndefined,
				)
				if (null == value) {
					const frequency = (key => {
						const values = new Map()
						for (const word of key.keyType.preregisteredWords)
							values.set(word, 0)
						const update = word => {
							const slotCount = values.get(word) ?? 0
							values.set(word, slotCount + 1)
						}
						return hook_make({
							get: () => new FrequencyState(values),
							update,
							modify: update,
						})
					})(key)
					pipe(this.map, MutableHashMap_has(key)) ||
						pipe(this.map, MutableHashMap_set(key, frequency))
					value = frequency
				}
				return value
			}
			getGauge(key) {
				let value = pipe(
					this.map,
					MutableHashMap_get(key),
					Option_getOrUndefined,
				)
				if (null == value) {
					const gauge = ((_key, startAt) => {
						let value = startAt
						return hook_make({
							get: () => new GaugeState(value),
							update: v => {
								value = v
							},
							modify: v => {
								value += v
							},
						})
					})(0, key.keyType.bigint ? BigInt(0) : 0)
					pipe(this.map, MutableHashMap_has(key)) ||
						pipe(this.map, MutableHashMap_set(key, gauge))
					value = gauge
				}
				return value
			}
			getHistogram(key) {
				let value = pipe(
					this.map,
					MutableHashMap_get(key),
					Option_getOrUndefined,
				)
				if (null == value) {
					const histogram = (key => {
						const bounds = key.keyType.boundaries.values,
							size = bounds.length,
							values = new Uint32Array(size + 1),
							boundaries = new Float64Array(size)
						let count = 0,
							sum = 0,
							min = Number.MAX_VALUE,
							max = Number.MIN_VALUE
						pipe(
							bounds,
							sort(Number_Order),
							Array_map((n, i) => {
								boundaries[i] = n
							}),
						)
						const update = value => {
								let from = 0,
									to = size
								for (; from !== to;) {
									const mid = Math.floor(from + (to - from) / 2)
									value <= boundaries[mid] ? (to = mid) : (from = mid)
									to === from + 1 &&
										(value <= boundaries[from] ? (to = from) : (from = to))
								}
								values[from] = values[from] + 1
								count += 1
								sum += value
								value < min && (min = value)
								value > max && (max = value)
							},
							getBuckets = () => {
								const builder = allocate(size)
								let cumulated = 0
								for (let i = 0; i < size; i++) {
									const boundary = boundaries[i]
									cumulated += values[i]
									builder[i] = [boundary, cumulated]
								}
								return builder
							}
						return hook_make({
							get: () => {
								return (
									(options = { buckets: getBuckets(), count, min, max, sum }),
									new HistogramState(
										options.buckets,
										options.count,
										options.min,
										options.max,
										options.sum,
									)
								)
								var options
							},
							update,
							modify: update,
						})
					})(key)
					pipe(this.map, MutableHashMap_has(key)) ||
						pipe(this.map, MutableHashMap_set(key, histogram))
					value = histogram
				}
				return value
			}
			getSummary(key) {
				let value = pipe(
					this.map,
					MutableHashMap_get(key),
					Option_getOrUndefined,
				)
				if (null == value) {
					const summary = (key => {
						const { error, maxAge, maxSize, quantiles } = key.keyType,
							sortedQuantiles = pipe(quantiles, sort(Number_Order)),
							values = allocate(maxSize)
						let head = 0,
							count = 0,
							sum = 0,
							min = 0,
							max = 0
						const snapshot = now => {
								const builder = []
								let i = 0
								for (; i !== maxSize - 1;) {
									const item = values[i]
									if (null != item) {
										const [t, v] = item,
											age = Duration_millis(now - t)
										Duration_greaterThanOrEqualTo(age, zero) &&
											Duration_lessThanOrEqualTo(age, maxAge) &&
											builder.push(v)
									}
									i += 1
								}
								return ((error, sortedQuantiles, sortedSamples) => {
									const sampleCount = sortedSamples.length
									if (!isNonEmptyReadonlyArray(sortedQuantiles)) return []
									const head = sortedQuantiles[0],
										tail = sortedQuantiles.slice(1),
										resolvedHead = resolveQuantile(
											error,
											sampleCount,
											Option_none(),
											0,
											head,
											sortedSamples,
										),
										resolved = Array_of(resolvedHead)
									tail.forEach(quantile => {
										resolved.push(
											resolveQuantile(
												error,
												sampleCount,
												resolvedHead.value,
												resolvedHead.consumed,
												quantile,
												resolvedHead.rest,
											),
										)
									})
									return Array_map(resolved, rq => [rq.quantile, rq.value])
								})(error, sortedQuantiles, sort(builder, Number_Order))
							},
							observe = (value, timestamp) => {
								if (maxSize > 0) {
									head += 1
									values[head % maxSize] = [timestamp, value]
								}
								min = 0 === count ? value : Math.min(min, value)
								max = 0 === count ? value : Math.max(max, value)
								count += 1
								sum += value
							}
						return hook_make({
							get: () => {
								return (
									(options = {
										error,
										quantiles: snapshot(Date.now()),
										count,
										min,
										max,
										sum,
									}),
									new SummaryState(
										options.error,
										options.quantiles,
										options.count,
										options.min,
										options.max,
										options.sum,
									)
								)
								var options
							},
							update: ([value, timestamp]) => observe(value, timestamp),
							modify: ([value, timestamp]) => observe(value, timestamp),
						})
					})(key)
					pipe(this.map, MutableHashMap_has(key)) ||
						pipe(this.map, MutableHashMap_set(key, summary))
					value = summary
				}
				return value
			}
		}
		const MetricTypeId = Symbol.for("effect/Metric"),
			metricVariance = { _Type: _ => _, _In: _ => _, _Out: _ => _ },
			globalMetricRegistry = globalValue(
				Symbol.for("effect/Metric/globalMetricRegistry"),
				() => new MetricRegistryImpl(),
			),
			metric_make = function (
				keyType,
				unsafeUpdate,
				unsafeValue,
				unsafeModify,
			) {
				const metric = Object.assign(
					effect => core_tap(effect, a => metric_update(metric, a)),
					{
						[MetricTypeId]: metricVariance,
						keyType,
						unsafeUpdate,
						unsafeValue,
						unsafeModify,
						register() {
							this.unsafeValue([])
							return this
						},
						pipe() {
							return pipeArguments(this, arguments)
						},
					},
				)
				return metric
			},
			metric_counter = (name, options) =>
				fromMetricKey(
					((name, options) =>
						new MetricKeyImpl(
							name,
							(options =>
								new CounterKeyType(
									options?.incremental ?? !1,
									options?.bigint ?? !1,
								))(options),
							Option_fromNullable(options?.description),
						))(name, options),
				),
			fromMetricKey = key => {
				let untaggedHook
				const hookCache = new WeakMap(),
					hook = extraTags => {
						if (0 === extraTags.length) {
							if (void 0 !== untaggedHook) return untaggedHook
							untaggedHook = globalMetricRegistry.get(key)
							return untaggedHook
						}
						let hook = hookCache.get(extraTags)
						if (void 0 !== hook) return hook
						hook = globalMetricRegistry.get(taggedWithLabels(key, extraTags))
						hookCache.set(extraTags, hook)
						return hook
					}
				return metric_make(
					key.keyType,
					(input, extraTags) => hook(extraTags).update(input),
					extraTags => hook(extraTags).get(),
					(input, extraTags) => hook(extraTags).modify(input),
				)
			},
			metric_histogram = (name, boundaries, description) =>
				fromMetricKey(
					((name, boundaries, description) =>
						new MetricKeyImpl(
							name,
							(boundaries => new HistogramKeyType(boundaries))(boundaries),
							Option_fromNullable(description),
						))(name, boundaries, description),
				),
			metric_tagged = dual(3, (self, key, value) =>
				metric_taggedWithLabels(self, [label_make(key, value)]),
			),
			metric_taggedWithLabels = dual(2, (self, extraTags) =>
				metric_make(
					self.keyType,
					(input, extraTags1) =>
						self.unsafeUpdate(input, Array_union(extraTags, extraTags1)),
					extraTags1 => self.unsafeValue(Array_union(extraTags, extraTags1)),
					(input, extraTags1) =>
						self.unsafeModify(input, Array_union(extraTags, extraTags1)),
				),
			),
			metric_update = dual(2, (self, input) =>
				fiberRefGetWith(currentMetricLabels, tags =>
					sync(() => self.unsafeUpdate(input, tags)),
				),
			),
			MetricBoundariesTypeId = Symbol.for("effect/MetricBoundaries")
		class MetricBoundariesImpl {
			values;
			[MetricBoundariesTypeId] = MetricBoundariesTypeId
			constructor(values) {
				this.values = values
				this._hash = pipe(
					string("effect/MetricBoundaries"),
					combine(array(this.values)),
				)
			}
			_hash;
			[symbol]() {
				return this._hash
			}
			[Equal_symbol](u) {
				return isMetricBoundaries(u) && equals(this.values, u.values)
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const isMetricBoundaries = u => hasProperty(u, MetricBoundariesTypeId),
			boundaries_fromIterable = iterable => {
				const values = pipe(
					iterable,
					Array_appendAll(Chunk_of(Number.POSITIVE_INFINITY)),
					dedupe,
				)
				return new MetricBoundariesImpl(values)
			},
			exponential = options =>
				pipe(
					Array_makeBy(
						options.count - 1,
						i => options.start * Math.pow(options.factor, i),
					),
					unsafeFromArray,
					boundaries_fromIterable,
				),
			complete = dual(2, (self, result) =>
				fiberRefGetWith(currentRequestMap, map =>
					sync(() => {
						if (map.has(self)) {
							const entry = map.get(self)
							if (!entry.state.completed) {
								entry.state.completed = !0
								deferredUnsafeDone(entry.result, result)
							}
						}
					}),
				),
			),
			SupervisorTypeId = Symbol.for("effect/Supervisor"),
			supervisorVariance = { _T: _ => _ }
		class ProxySupervisor {
			underlying
			value0;
			[SupervisorTypeId] = supervisorVariance
			constructor(underlying, value0) {
				this.underlying = underlying
				this.value0 = value0
			}
			get value() {
				return this.value0
			}
			onStart(context, effect, parent, fiber) {
				this.underlying.onStart(context, 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, core_map(f)))
			}
			zip(right) {
				return new Zip(this, right)
			}
		}
		class Zip {
			left
			right
			_tag = "Zip";
			[SupervisorTypeId] = supervisorVariance
			constructor(left, right) {
				this.left = left
				this.right = right
			}
			get value() {
				return core_zip(this.left.value, this.right.value)
			}
			onStart(context, effect, parent, fiber) {
				this.left.onStart(context, effect, parent, fiber)
				this.right.onStart(context, 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, core_map(f)))
			}
			zip(right) {
				return new Zip(this, right)
			}
		}
		const isZip = self =>
			hasProperty(self, SupervisorTypeId) && isTagged(self, "Zip")
		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, core_map(f)))
			}
			zip(right) {
				return new Zip(this, right)
			}
			onRun(execution, _fiber) {
				return execution()
			}
		}
		const supervisor_none = globalValue(
				"effect/Supervisor/none",
				() => new Const(core_void_),
			),
			supervisor_patch_empty = { _tag: "Empty" },
			supervisor_patch_combine = (self, that) => ({
				_tag: "AndThen",
				first: self,
				second: that,
			}),
			removeSupervisor = (self, that) =>
				equals(self, that)
					? supervisor_none
					: isZip(self)
						? removeSupervisor(self.left, that).zip(
								removeSupervisor(self.right, that),
							)
						: self,
			patch_toSet = self =>
				equals(self, supervisor_none)
					? HashSet_empty()
					: isZip(self)
						? pipe(
								patch_toSet(self.left),
								HashSet_union(patch_toSet(self.right)),
							)
						: HashSet_make(self),
			patch_differ = differ_make({
				empty: supervisor_patch_empty,
				patch: (self, supervisor) =>
					((_supervisor, _patches) => {
						let supervisor = _supervisor,
							patches = _patches
						for (; isNonEmpty(patches);) {
							const head = Chunk_headNonEmpty(patches)
							switch (head._tag) {
								case "Empty":
									patches = Chunk_tailNonEmpty(patches)
									break
								case "AddSupervisor":
									supervisor = supervisor.zip(head.supervisor)
									patches = Chunk_tailNonEmpty(patches)
									break
								case "RemoveSupervisor":
									supervisor = removeSupervisor(supervisor, head.supervisor)
									patches = Chunk_tailNonEmpty(patches)
									break
								case "AndThen":
									patches = Chunk_prepend(head.first)(
										Chunk_prepend(head.second)(Chunk_tailNonEmpty(patches)),
									)
							}
						}
						return supervisor
					})(supervisor, Chunk_of(self)),
				combine: supervisor_patch_combine,
				diff: (oldValue, newValue) => {
					if (equals(oldValue, newValue)) return supervisor_patch_empty
					const oldSupervisors = patch_toSet(oldValue),
						newSupervisors = patch_toSet(newValue),
						added = pipe(
							newSupervisors,
							HashSet_difference(oldSupervisors),
							HashSet_reduce(supervisor_patch_empty, (patch, supervisor) =>
								supervisor_patch_combine(patch, {
									_tag: "AddSupervisor",
									supervisor,
								}),
							),
						),
						removed = pipe(
							oldSupervisors,
							HashSet_difference(newSupervisors),
							HashSet_reduce(supervisor_patch_empty, (patch, supervisor) =>
								supervisor_patch_combine(patch, {
									_tag: "RemoveSupervisor",
									supervisor,
								}),
							),
						)
					return supervisor_patch_combine(added, removed)
				},
			}),
			fiberStarted = metric_counter("effect_fiber_started", {
				incremental: !0,
			}),
			fiberActive = metric_counter("effect_fiber_active"),
			fiberSuccesses = metric_counter("effect_fiber_successes", {
				incremental: !0,
			}),
			fiberFailures = metric_counter("effect_fiber_failures", {
				incremental: !0,
			}),
			fiberLifetimes = metric_tagged(
				metric_histogram(
					"effect_fiber_lifetimes",
					exponential({ start: 0.5, factor: 2, count: 35 }),
				),
				"time_unit",
				"milliseconds",
			),
			runtimeFiberVariance = { _E: _ => _, _A: _ => _ },
			fiberRuntime_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) =>
					internalCall(() => cont.effect_instruction_i1(value)),
				OnStep: (_, _cont, value) => exitSucceed(exitSucceed(value)),
				[OP_ON_SUCCESS_AND_FAILURE]: (_, cont, value) =>
					internalCall(() => cont.effect_instruction_i2(value)),
				[OP_REVERT_FLAGS]: (self, cont, value) => {
					self.patchRuntimeFlags(self.currentRuntimeFlags, cont.patch)
					return interruptible(self.currentRuntimeFlags) && self.isInterrupted()
						? exitFailCause(self.getInterruptedCause())
						: exitSucceed(value)
				},
				While: (self, cont, value) => {
					internalCall(() => cont.effect_instruction_i2(value))
					if (internalCall(() => cont.effect_instruction_i0())) {
						self.pushStack(cont)
						return internalCall(() => cont.effect_instruction_i1())
					}
					return core_void_
				},
				[OP_ITERATOR]: (self, cont, value) => {
					for (;;) {
						const state = internalCall(() =>
							cont.effect_instruction_i0.next(value),
						)
						if (state.done) return exitSucceed(state.value)
						const primitive = yieldWrapGet(state.value)
						if (!exitIsExit(primitive)) {
							self.pushStack(cont)
							return primitive
						}
						if ("Failure" === primitive._tag) return primitive
						value = primitive.value
					}
				},
			},
			drainQueueWhileRunningTable = {
				[OP_INTERRUPT_SIGNAL]: (self, runtimeFlags, cur, message) => {
					self.processNewInterruptSignal(message.cause)
					return interruptible(runtimeFlags)
						? exitFailCause(message.cause)
						: cur
				},
				Resume: (_self, _runtimeFlags, _cur, _message) => {
					throw new Error(
						"It is illegal to have multiple concurrent run loops in a single fiber",
					)
				},
				[OP_STATEFUL]: (self, runtimeFlags, cur, message) => {
					message.onFiber(self, FiberStatus_running(runtimeFlags))
					return cur
				},
				[OP_YIELD_NOW]: (_self, _runtimeFlags, cur, _message) =>
					core_flatMap(yieldNow(), () => cur),
			},
			_version = getCurrentVersion()
		class FiberRuntime extends Effectable_Class {
			[FiberTypeId] = fiber_fiberVariance;
			[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(fiberId, fiberRefs0, runtimeFlags0) {
				super()
				this.currentRuntimeFlags = runtimeFlags0
				this._fiberId = fiberId
				this._fiberRefs = fiberRefs0
				if (runtimeMetrics(runtimeFlags0)) {
					const tags = this.getFiberRef(currentMetricLabels)
					fiberStarted.unsafeUpdate(1, tags)
					fiberActive.unsafeUpdate(1, tags)
				}
				this.refreshRefCache()
			}
			commit() {
				return fiber_join(this)
			}
			id() {
				return this._fiberId
			}
			resume(effect) {
				this.tell(resume(effect))
			}
			get status() {
				return this.ask((_, status) => status)
			}
			get runtimeFlags() {
				return this.ask((state, status) =>
					(self => "Done" === self._tag)(status)
						? state.currentRuntimeFlags
						: status.runtimeFlags,
				)
			}
			scope() {
				return new Local((fiber = this).id(), fiber)
				var fiber
			}
			get children() {
				return this.ask(fiber => Array.from(fiber.getChildren()))
			}
			getChildren() {
				null === this._children && (this._children = new Set())
				return this._children
			}
			getInterruptedCause() {
				return this.getFiberRef(currentInterruptedCause)
			}
			fiberRefs() {
				return this.ask(fiber => fiber.getFiberRefs())
			}
			ask(f) {
				return suspend(() => {
					const deferred = deferredUnsafeMake(this._fiberId)
					this.tell(
						stateful((fiber, status) => {
							deferredUnsafeDone(
								deferred,
								sync(() => f(fiber, status)),
							)
						}),
					)
					return deferredAwait(deferred)
				})
			}
			tell(message) {
				this._queue.push(message)
				if (!this._running) {
					this._running = !0
					this.drainQueueLaterOnExecutor()
				}
			}
			get await() {
				return async_(resume => {
					const cb = exit => resume(succeed(exit))
					if (null === this._exitValue) {
						this.tell(
							stateful((fiber, _) => {
								null !== fiber._exitValue
									? cb(this._exitValue)
									: fiber.addObserver(cb)
							}),
						)
						return sync(() =>
							this.tell(
								stateful((fiber, _) => {
									fiber.removeObserver(cb)
								}),
							),
						)
					}
					cb(this._exitValue)
				}, this.id())
			}
			get inheritAll() {
				return withFiberRuntime((parentFiber, parentStatus) => {
					const parentFiberId = parentFiber.id(),
						parentFiberRefs = parentFiber.getFiberRefs(),
						parentRuntimeFlags = parentStatus.runtimeFlags,
						childFiberRefs = this.getFiberRefs(),
						updatedFiberRefs = joinAs(
							parentFiberRefs,
							parentFiberId,
							childFiberRefs,
						)
					parentFiber.setFiberRefs(updatedFiberRefs)
					const updatedRuntimeFlags =
						parentFiber.getFiberRef(currentRuntimeFlags)
					return (patch => {
						const effect = new EffectPrimitive("UpdateRuntimeFlags")
						effect.effect_instruction_i0 = patch
						effect.effect_instruction_i1 = void 0
						return effect
					})(
						pipe(
							runtimeFlags_diff(parentRuntimeFlags, updatedRuntimeFlags),
							RuntimeFlagsPatch_exclude(1),
							RuntimeFlagsPatch_exclude(16),
						),
					)
				})
			}
			get poll() {
				return sync(() => Option_fromNullable(this._exitValue))
			}
			unsafePoll() {
				return this._exitValue
			}
			interruptAsFork(fiberId) {
				return sync(() => this.tell(interruptSignal(interrupt(fiberId))))
			}
			unsafeInterruptAsFork(fiberId) {
				this.tell(interruptSignal(interrupt(fiberId)))
			}
			addObserver(observer) {
				null !== this._exitValue
					? observer(this._exitValue)
					: this._observers.push(observer)
			}
			removeObserver(observer) {
				this._observers = this._observers.filter(o => o !== observer)
			}
			getFiberRefs() {
				this.setFiberRef(currentRuntimeFlags, this.currentRuntimeFlags)
				return this._fiberRefs
			}
			unsafeDeleteFiberRef(fiberRef) {
				this._fiberRefs = delete_(this._fiberRefs, fiberRef)
			}
			getFiberRef(fiberRef) {
				return this._fiberRefs.locals.has(fiberRef)
					? this._fiberRefs.locals.get(fiberRef)[0][1]
					: 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(fiberRefs) {
				this._fiberRefs = fiberRefs
				this.refreshRefCache()
			}
			addChild(child) {
				this.getChildren().add(child)
			}
			removeChild(child) {
				this.getChildren().delete(child)
			}
			transferChildren(scope) {
				const children = this._children
				this._children = null
				if (null !== children && children.size > 0)
					for (const child of children)
						null === child._exitValue &&
							scope.add(this.currentRuntimeFlags, child)
			}
			drainQueueOnCurrentThread() {
				let recurse = !0
				for (; recurse;) {
					let evaluationSignal = "Continue"
					const prev = globalThis[currentFiberURI]
					globalThis[currentFiberURI] = this
					try {
						for (; "Continue" === evaluationSignal;)
							evaluationSignal =
								0 === this._queue.length
									? "Done"
									: this.evaluateMessageWhileSuspended(
											this._queue.splice(0, 1)[0],
										)
					} finally {
						this._running = !1
						globalThis[currentFiberURI] = prev
					}
					if (this._queue.length > 0 && !this._running) {
						this._running = !0
						if ("Yield" === evaluationSignal) {
							this.drainQueueLaterOnExecutor()
							recurse = !1
						} else recurse = !0
					} else recurse = !1
				}
			}
			drainQueueLaterOnExecutor() {
				this.currentScheduler.scheduleTask(
					this.run,
					this.getFiberRef(currentSchedulingPriority),
					this,
				)
			}
			drainQueueWhileRunning(runtimeFlags, cur0) {
				let cur = cur0
				for (; this._queue.length > 0;) {
					const message = this._queue.splice(0, 1)[0]
					cur = drainQueueWhileRunningTable[message._tag](
						this,
						runtimeFlags,
						cur,
						message,
					)
				}
				return cur
			}
			isInterrupted() {
				return !(self =>
					"Empty" === self._tag ||
					cause_reduce(self, !0, (acc, cause) => {
						switch (cause._tag) {
							case "Empty":
								return Option_some(acc)
							case "Die":
							case "Fail":
							case "Interrupt":
								return Option_some(!1)
							default:
								return Option_none()
						}
					}))(this.getFiberRef(currentInterruptedCause))
			}
			addInterruptedCause(cause) {
				const oldSC = this.getFiberRef(currentInterruptedCause)
				this.setFiberRef(currentInterruptedCause, sequential(oldSC, cause))
			}
			processNewInterruptSignal(cause) {
				this.addInterruptedCause(cause)
				this.sendInterruptSignalToAllChildren()
			}
			sendInterruptSignalToAllChildren() {
				if (null === this._children || 0 === this._children.size) return !1
				let told = !1
				for (const child of this._children) {
					child.tell(interruptSignal(interrupt(this.id())))
					told = !0
				}
				return told
			}
			interruptAllChildren() {
				if (this.sendInterruptSignalToAllChildren()) {
					const it = this._children.values()
					this._children = null
					let isDone = !1
					return whileLoop({
						while: () => !isDone,
						body: () => {
							const next = it.next()
							return next.done
								? sync(() => {
										isDone = !0
									})
								: core_asVoid(next.value.await)
						},
						step: () => {},
					})
				}
				return null
			}
			reportExitValue(exit) {
				if (runtimeMetrics(this.currentRuntimeFlags)) {
					const tags = this.getFiberRef(currentMetricLabels),
						startTimeMillis = this.id().startTimeMillis,
						endTimeMillis = Date.now()
					fiberLifetimes.unsafeUpdate(endTimeMillis - startTimeMillis, tags)
					fiberActive.unsafeUpdate(-1, tags)
					switch (exit._tag) {
						case "Success":
							fiberSuccesses.unsafeUpdate(1, tags)
							break
						case "Failure":
							fiberFailures.unsafeUpdate(1, tags)
					}
				}
				if ("Failure" === exit._tag) {
					const level = this.getFiberRef(currentUnhandledErrorLogLevel)
					isInterruptedOnly(exit.cause) ||
						"Some" !== level._tag ||
						this.log(
							"Fiber terminated with an unhandled error",
							exit.cause,
							level,
						)
				}
			}
			setExitValue(exit) {
				this._exitValue = exit
				this.reportExitValue(exit)
				for (let i = this._observers.length - 1; i >= 0; i--)
					this._observers[i](exit)
				this._observers = []
			}
			getLoggers() {
				return this.getFiberRef(currentLoggers)
			}
			log(message, cause, overrideLogLevel) {
				const logLevel = Option_isSome(overrideLogLevel)
						? overrideLogLevel.value
						: this.getFiberRef(currentLogLevel),
					minimumLogLevel = this.getFiberRef(currentMinimumLogLevel)
				if (LogLevel_greaterThan(minimumLogLevel, logLevel)) return
				const spans = this.getFiberRef(currentLogSpan),
					annotations = this.getFiberRef(currentLogAnnotations),
					loggers = this.getLoggers(),
					contextMap = this.getFiberRefs()
				if (HashSet_size(loggers) > 0) {
					const clockService = Context_get(
							this.getFiberRef(currentServices),
							clockTag,
						),
						date = new Date(clockService.unsafeCurrentTimeMillis())
					;((context, f) => {
						const prev = redactableState.fiberRefs
						redactableState.fiberRefs = context
						try {
							return f()
						} finally {
							redactableState.fiberRefs = prev
						}
					})(contextMap, () => {
						for (const logger of loggers)
							logger.log({
								fiberId: this.id(),
								logLevel,
								message,
								cause,
								context: contextMap,
								spans,
								annotations,
								date,
							})
					})
				}
			}
			evaluateMessageWhileSuspended(message) {
				switch (message._tag) {
					case "YieldNow":
						return "Yield"
					case "InterruptSignal":
						this.processNewInterruptSignal(message.cause)
						if (null !== this._asyncInterruptor) {
							this._asyncInterruptor(exitFailCause(message.cause))
							this._asyncInterruptor = null
						}
						return "Continue"
					case "Resume":
						this._asyncInterruptor = null
						this._asyncBlockingOn = null
						this.evaluateEffect(message.effect)
						return "Continue"
					case "Stateful":
						message.onFiber(
							this,
							null !== this._exitValue
								? FiberStatus_done
								: ((runtimeFlags = this.currentRuntimeFlags),
									(blockingOn = this._asyncBlockingOn),
									new Suspended(runtimeFlags, blockingOn)),
						)
						return "Continue"
					default:
						return fiberRuntime_absurd(message)
				}
				var runtimeFlags, blockingOn
			}
			evaluateEffect(effect0) {
				this.currentSupervisor.onResume(this)
				try {
					let effect =
						interruptible(this.currentRuntimeFlags) && this.isInterrupted()
							? exitFailCause(this.getInterruptedCause())
							: effect0
					for (; null !== effect;) {
						const eff = effect,
							exit = this.runLoop(eff)
						if (exit === YieldedOp) {
							const op = yieldedOpChannel.currentOp
							yieldedOpChannel.currentOp = null
							if ("Yield" === op._op)
								if (cooperativeYielding(this.currentRuntimeFlags)) {
									this.tell({ _tag: "YieldNow" })
									this.tell(resume(exitVoid))
									effect = null
								} else effect = exitVoid
							else "Async" === op._op && (effect = null)
						} else {
							this.currentRuntimeFlags = pipe(
								this.currentRuntimeFlags,
								runtimeFlags_enable(16),
							)
							const interruption = this.interruptAllChildren()
							if (null !== interruption)
								effect = core_flatMap(interruption, () => exit)
							else {
								0 === this._queue.length
									? this.setExitValue(exit)
									: this.tell(resume(exit))
								effect = null
							}
						}
					}
				} finally {
					this.currentSupervisor.onSuspend(this)
				}
			}
			start(effect) {
				if (this._running) this.tell(resume(effect))
				else {
					this._running = !0
					const prev = globalThis[currentFiberURI]
					globalThis[currentFiberURI] = this
					try {
						this.evaluateEffect(effect)
					} finally {
						this._running = !1
						globalThis[currentFiberURI] = prev
						this._queue.length > 0 && this.drainQueueLaterOnExecutor()
					}
				}
			}
			startFork(effect) {
				this.tell(resume(effect))
			}
			patchRuntimeFlags(oldRuntimeFlags, patch) {
				const newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, patch)
				globalThis[currentFiberURI] = this
				this.currentRuntimeFlags = newRuntimeFlags
				return newRuntimeFlags
			}
			initiateAsync(runtimeFlags, asyncRegister) {
				let alreadyCalled = !1
				const callback = effect => {
					if (!alreadyCalled) {
						alreadyCalled = !0
						this.tell(resume(effect))
					}
				}
				interruptible(runtimeFlags) && (this._asyncInterruptor = callback)
				try {
					asyncRegister(callback)
				} catch (e) {
					callback(failCause(die(e)))
				}
			}
			pushStack(cont) {
				this._stack.push(cont)
				"OnStep" === cont._op &&
					this._steps.push({
						refs: this.getFiberRefs(),
						flags: this.currentRuntimeFlags,
					})
			}
			popStack() {
				const item = this._stack.pop()
				if (item) {
					"OnStep" === item._op && this._steps.pop()
					return item
				}
			}
			getNextSuccessCont() {
				let frame = this.popStack()
				for (; frame;) {
					if ("OnFailure" !== frame._op) return frame
					frame = this.popStack()
				}
			}
			getNextFailCont() {
				let frame = this.popStack()
				for (; frame;) {
					if (
						"OnSuccess" !== frame._op &&
						"While" !== frame._op &&
						"Iterator" !== frame._op
					)
						return frame
					frame = this.popStack()
				}
			}
			Tag(op) {
				return sync(() => Context_unsafeGet(this.currentContext, op))
			}
			Left(op) {
				return core_fail(op.left)
			}
			None(_) {
				return core_fail(new NoSuchElementException())
			}
			Right(op) {
				return exitSucceed(op.right)
			}
			Some(op) {
				return exitSucceed(op.value)
			}
			Micro(op) {
				return unsafeAsync(microResume => {
					let resume = microResume
					const fiber = (effect => {
						const fiber = new MicroFiberImpl(
							CurrentScheduler.context(new MicroSchedulerDefault()),
						)
						fiber.evaluate(effect)
						undefined
						return fiber
					})(Micro_provideContext(op, this.currentContext))
					fiber.addObserver(exit => {
						if ("Success" === exit._tag) return resume(exitSucceed(exit.value))
						switch (exit.cause._tag) {
							case "Interrupt":
								return resume(exitFailCause(interrupt(FiberId_none)))
							case "Fail":
								return resume(core_fail(exit.cause.error))
							case "Die":
								return resume(core_die(exit.cause.defect))
						}
					})
					return unsafeAsync(abortResume => {
						resume = _ => {
							abortResume(core_void_)
						}
						fiber.unsafeInterrupt()
					})
				})
			}
			Sync(op) {
				const value = internalCall(() => op.effect_instruction_i0()),
					cont = this.getNextSuccessCont()
				if (void 0 !== cont) {
					cont._op in contOpSuccess || fiberRuntime_absurd(cont)
					return contOpSuccess[cont._op](this, cont, value)
				}
				yieldedOpChannel.currentOp = exitSucceed(value)
				return YieldedOp
			}
			[OP_SUCCESS](op) {
				const oldCur = op,
					cont = this.getNextSuccessCont()
				if (void 0 !== cont) {
					cont._op in contOpSuccess || fiberRuntime_absurd(cont)
					return contOpSuccess[cont._op](
						this,
						cont,
						oldCur.effect_instruction_i0,
					)
				}
				yieldedOpChannel.currentOp = oldCur
				return YieldedOp
			}
			[OP_FAILURE](op) {
				const cause = op.effect_instruction_i0,
					cont = this.getNextFailCont()
				if (void 0 === cont) {
					yieldedOpChannel.currentOp = exitFailCause(cause)
					return YieldedOp
				}
				switch (cont._op) {
					case "OnFailure":
					case "OnSuccessAndFailure":
						return interruptible(this.currentRuntimeFlags) &&
							this.isInterrupted()
							? exitFailCause(stripFailures(cause))
							: internalCall(() => cont.effect_instruction_i1(cause))
					case "OnStep":
						return interruptible(this.currentRuntimeFlags) &&
							this.isInterrupted()
							? exitFailCause(stripFailures(cause))
							: exitSucceed(exitFailCause(cause))
					case "RevertFlags":
						this.patchRuntimeFlags(this.currentRuntimeFlags, cont.patch)
						return interruptible(this.currentRuntimeFlags) &&
							this.isInterrupted()
							? exitFailCause(sequential(cause, this.getInterruptedCause()))
							: exitFailCause(cause)
					default:
						fiberRuntime_absurd(cont)
				}
			}
			[OP_WITH_RUNTIME](op) {
				return internalCall(() =>
					op.effect_instruction_i0(
						this,
						FiberStatus_running(this.currentRuntimeFlags),
					),
				)
			}
			Blocked(op) {
				const refs = this.getFiberRefs(),
					flags = this.currentRuntimeFlags
				if (this._steps.length > 0) {
					const frames = [],
						snap = this._steps[this._steps.length - 1]
					let frame = this.popStack()
					for (; frame && "OnStep" !== frame._op;) {
						frames.push(frame)
						frame = this.popStack()
					}
					this.setFiberRefs(snap.refs)
					this.currentRuntimeFlags = snap.flags
					const patchRefs = FiberRefsPatch_diff(snap.refs, refs),
						patchFlags = runtimeFlags_diff(snap.flags, flags)
					return exitSucceed(
						blocked(
							op.effect_instruction_i0,
							withFiberRuntime(newFiber => {
								for (; frames.length > 0;) newFiber.pushStack(frames.pop())
								newFiber.setFiberRefs(
									FiberRefsPatch_patch(
										newFiber.id(),
										newFiber.getFiberRefs(),
									)(patchRefs),
								)
								newFiber.currentRuntimeFlags = runtimeFlags_patch(patchFlags)(
									newFiber.currentRuntimeFlags,
								)
								return op.effect_instruction_i1
							}),
						),
					)
				}
				return uninterruptibleMask(restore =>
					core_flatMap(
						fiberRuntime_forkDaemon(
							(blockedRequests => {
								const effect = new EffectPrimitive("RunBlocked")
								effect.effect_instruction_i0 = blockedRequests
								return effect
							})(op.effect_instruction_i0),
						),
						() => restore(op.effect_instruction_i1),
					),
				)
			}
			RunBlocked(op) {
				return (self =>
					forEachSequentialDiscard(
						(self => {
							let current = List_of(self),
								updated = List_empty()
							for (;;) {
								const [parallel, sequential] = List_reduce(
									current,
									[parallelCollectionEmpty(), List_empty()],
									([parallel, sequential], blockedRequest) => {
										const [par, seq] = blockedRequests_step(blockedRequest)
										return [
											parallelCollectionCombine(parallel, par),
											List_appendAll(sequential, seq),
										]
									},
								)
								updated = blockedRequests_merge(updated, parallel)
								if (isNil(sequential)) return List_reverse(updated)
								current = sequential
							}
							throw new Error(
								"BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues",
							)
						})(self),
						requestsByRequestResolver =>
							forEachConcurrentDiscard(
								(self => Array.from(self.map))(requestsByRequestResolver),
								([dataSource, sequential]) => {
									const map = new Map(),
										arr = []
									for (const block of sequential) {
										arr.push(toReadonlyArray(block))
										for (const entry of block) map.set(entry.request, entry)
									}
									const flat = arr.flat()
									return fiberRefLocally(
										invokeWithInterrupt(dataSource.runAll(arr), flat, () =>
											flat.forEach(entry => {
												entry.listeners.interrupted = !0
											}),
										),
										currentRequestMap,
										map,
									)
								},
								!1,
								!1,
							),
					))(op.effect_instruction_i0)
			}
			[OP_UPDATE_RUNTIME_FLAGS](op) {
				const updateFlags = op.effect_instruction_i0,
					oldRuntimeFlags = this.currentRuntimeFlags,
					newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, updateFlags)
				if (interruptible(newRuntimeFlags) && this.isInterrupted())
					return exitFailCause(this.getInterruptedCause())
				this.patchRuntimeFlags(this.currentRuntimeFlags, updateFlags)
				if (op.effect_instruction_i1) {
					const revertFlags = runtimeFlags_diff(
						newRuntimeFlags,
						oldRuntimeFlags,
					)
					this.pushStack(new RevertFlags(revertFlags, op))
					return internalCall(() => op.effect_instruction_i1(oldRuntimeFlags))
				}
				return exitVoid
			}
			[OP_ON_SUCCESS](op) {
				this.pushStack(op)
				return op.effect_instruction_i0
			}
			OnStep(op) {
				this.pushStack(op)
				return op.effect_instruction_i0
			}
			[OP_ON_FAILURE](op) {
				this.pushStack(op)
				return op.effect_instruction_i0
			}
			[OP_ON_SUCCESS_AND_FAILURE](op) {
				this.pushStack(op)
				return op.effect_instruction_i0
			}
			Async(op) {
				this._asyncBlockingOn = op.effect_instruction_i1
				this.initiateAsync(this.currentRuntimeFlags, op.effect_instruction_i0)
				yieldedOpChannel.currentOp = op
				return YieldedOp
			}
			Yield(op) {
				this._isYielding = !1
				yieldedOpChannel.currentOp = op
				return YieldedOp
			}
			While(op) {
				const check = op.effect_instruction_i0,
					body = op.effect_instruction_i1
				if (check()) {
					this.pushStack(op)
					return body()
				}
				return exitVoid
			}
			[OP_ITERATOR](op) {
				return contOpSuccess.Iterator(this, op, void 0)
			}
			Commit(op) {
				return internalCall(() => op.commit())
			}
			runLoop(effect0) {
				let cur = effect0
				this.currentOpCount = 0
				for (;;) {
					2 & this.currentRuntimeFlags &&
						this.currentSupervisor.onEffect(this, cur)
					this._queue.length > 0 &&
						(cur = this.drainQueueWhileRunning(this.currentRuntimeFlags, cur))
					if (!this._isYielding) {
						this.currentOpCount += 1
						const shouldYield = this.currentScheduler.shouldYield(this)
						if (!1 !== shouldYield) {
							this._isYielding = !0
							this.currentOpCount = 0
							const oldCur = cur
							cur = core_flatMap(
								yieldNow({ priority: shouldYield }),
								() => oldCur,
							)
						}
					}
					try {
						cur = this.currentTracer.context(() => {
							if (_version !== cur[core_EffectTypeId]._V) {
								const level = this.getFiberRef(
									currentVersionMismatchErrorLogLevel,
								)
								if ("Some" === level._tag) {
									const effectVersion = cur[core_EffectTypeId]._V
									this.log(
										`Executing an Effect versioned ${effectVersion} with a Runtime of version 3.21.4, you may want to dedupe the effect dependencies, you can use the language service plugin to detect this at compile time: https://github.com/Effect-TS/language-service`,
										cause_empty,
										level,
									)
								}
							}
							return this[cur._op](cur)
						}, this)
						if (cur === YieldedOp) {
							const op = yieldedOpChannel.currentOp
							if ("Yield" === op._op || "Async" === op._op) return YieldedOp
							yieldedOpChannel.currentOp = null
							return "Success" === op._op || "Failure" === op._op
								? op
								: exitFailCause(die(op))
						}
					} catch (e) {
						cur =
							(cur !== YieldedOp && !hasProperty(cur, "_op")) ||
							!(cur._op in this)
								? dieMessage(`Not a valid effect: ${toStringUnknown(cur)}`)
								: isInterruptedException(e)
									? exitFailCause(sequential(die(e), interrupt(FiberId_none)))
									: core_die(e)
					}
				}
			}
			run = () => {
				this.drainQueueOnCurrentThread()
			}
		}
		const currentMinimumLogLevel = globalValue(
				"effect/FiberRef/currentMinimumLogLevel",
				() => fiberRefUnsafeMake(Info),
			),
			defaultLogger = globalValue(
				Symbol.for("effect/Logger/defaultLogger"),
				() =>
					(self =>
						makeLogger(opts => {
							const services = FiberRefs_getOrDefault(
								opts.context,
								currentServices,
							)
							Context_get(services, consoleTag).unsafe.log(self.log(opts))
						}))(stringLogger),
			),
			tracerLogger = globalValue(Symbol.for("effect/Logger/tracerLogger"), () =>
				makeLogger(
					({ annotations, cause, context, fiberId, logLevel, message }) => {
						const span = filterDisablePropagation(
							Context_getOption(getOrDefault(context, currentContext), spanTag),
						)
						if ("None" === span._tag || "ExternalSpan" === span.value._tag)
							return
						const clockService = Context_unsafeGet(
								getOrDefault(context, currentServices),
								clockTag,
							),
							attributes = {}
						for (const [key, value] of annotations) attributes[key] = value
						attributes["effect.fiberId"] = FiberId_threadName(fiberId)
						attributes["effect.logLevel"] = logLevel.label
						null !== cause &&
							"Empty" !== cause._tag &&
							(attributes["effect.cause"] = pretty(cause, {
								renderErrorCause: !0,
							}))
						span.value.event(
							toStringUnknown(
								Array.isArray(message) && 1 === message.length
									? message[0]
									: message,
							),
							clockService.unsafeCurrentTimeNanos(),
							attributes,
						)
					},
				),
			),
			currentLoggers = globalValue(
				Symbol.for("effect/FiberRef/currentLoggers"),
				() =>
					(initial => {
						const differ = differ_make({
							empty: differ_hashSetPatch_empty(),
							combine: (first, second) => hashSetPatch_combine(second)(first),
							diff: (oldValue, newValue) =>
								((oldValue, newValue) => {
									const [removed, patch] = HashSet_reduce(
										[oldValue, differ_hashSetPatch_empty()],
										([set, patch], value) =>
											HashSet_has(value)(set)
												? [HashSet_remove(value)(set), patch]
												: [
														set,
														hashSetPatch_combine(hashSetPatch_makeAdd(value))(
															patch,
														),
													],
									)(newValue)
									return HashSet_reduce(patch, (patch, value) =>
										hashSetPatch_combine(
											(value => {
												const o = Object.create(hashSetPatch_RemoveProto)
												o.value = value
												return o
											})(value),
										)(patch),
									)(removed)
								})(oldValue, newValue),
							patch: (patch, oldValue) => hashSetPatch_patch(oldValue)(patch),
						})
						return fiberRefUnsafeMakePatch(initial, {
							differ,
							fork: differ.empty,
						})
					})(HashSet_make(defaultLogger, tracerLogger)),
			),
			fiberRuntime_acquireRelease = dual(
				args => isEffect(args[0]),
				(acquire, release) =>
					uninterruptible(
						core_tap(acquire, a =>
							fiberRuntime_addFinalizer(exit => release(a, exit)),
						),
					),
			),
			fiberRuntime_addFinalizer = finalizer =>
				withFiberRuntime(runtime => {
					const acquireRefs = runtime.getFiberRefs(),
						acquireFlags = runtimeFlags_disable(runtime.currentRuntimeFlags, 1)
					return core_flatMap(fiberRuntime_scope, scope =>
						scopeAddFinalizerExit(scope, exit =>
							withFiberRuntime(runtimeFinalizer => {
								const preRefs = runtimeFinalizer.getFiberRefs(),
									preFlags = runtimeFinalizer.currentRuntimeFlags,
									patchRefs = FiberRefsPatch_diff(preRefs, acquireRefs),
									patchFlags = runtimeFlags_diff(preFlags, acquireFlags),
									inverseRefs = FiberRefsPatch_diff(acquireRefs, preRefs)
								runtimeFinalizer.setFiberRefs(
									FiberRefsPatch_patch(
										patchRefs,
										runtimeFinalizer.id(),
										acquireRefs,
									),
								)
								return fiberRuntime_ensuring(
									withRuntimeFlags(finalizer(exit), patchFlags),
									sync(() => {
										runtimeFinalizer.setFiberRefs(
											FiberRefsPatch_patch(
												inverseRefs,
												runtimeFinalizer.id(),
												runtimeFinalizer.getFiberRefs(),
											),
										)
									}),
								)
							}),
						),
					)
				}),
			fiberRuntime_all = (arg, options) => {
				const [effects, reconcile] = (input => {
					if (Array.isArray(input) || isIterable(input))
						return [input, Option_none()]
					const keys = Object.keys(input),
						size = keys.length
					return [
						keys.map(k => input[k]),
						Option_some(values => {
							const res = {}
							for (let i = 0; i < size; i++) res[keys[i]] = values[i]
							return res
						}),
					]
				})(arg)
				return "validate" === options?.mode
					? ((effects, reconcile, options) => {
							const eitherEffects = []
							for (const effect of effects)
								eitherEffects.push(core_either(effect))
							return core_flatMap(
								fiberRuntime_forEach(eitherEffects, identity, {
									concurrency: options?.concurrency,
									batching: options?.batching,
									concurrentFinalizers: options?.concurrentFinalizers,
								}),
								eithers => {
									const none = Option_none(),
										size = eithers.length,
										errors = new Array(size),
										successes = new Array(size)
									let errored = !1
									for (let i = 0; i < size; i++) {
										const either = eithers[i]
										if ("Left" === either._tag) {
											errors[i] = Option_some(either.left)
											errored = !0
										} else {
											successes[i] = either.right
											errors[i] = none
										}
									}
									return errored
										? "Some" === reconcile._tag
											? core_fail(reconcile.value(errors))
											: core_fail(errors)
										: options?.discard
											? core_void_
											: "Some" === reconcile._tag
												? succeed(reconcile.value(successes))
												: succeed(successes)
								},
							)
						})(effects, reconcile, options)
					: "either" === options?.mode
						? ((effects, reconcile, options) => {
								const eitherEffects = []
								for (const effect of effects)
									eitherEffects.push(core_either(effect))
								return options?.discard
									? fiberRuntime_forEach(eitherEffects, identity, {
											concurrency: options?.concurrency,
											batching: options?.batching,
											discard: !0,
											concurrentFinalizers: options?.concurrentFinalizers,
										})
									: core_map(
											fiberRuntime_forEach(eitherEffects, identity, {
												concurrency: options?.concurrency,
												batching: options?.batching,
												concurrentFinalizers: options?.concurrentFinalizers,
											}),
											eithers =>
												"Some" === reconcile._tag
													? reconcile.value(eithers)
													: eithers,
										)
							})(effects, reconcile, options)
						: !0 !== options?.discard && "Some" === reconcile._tag
							? core_map(
									fiberRuntime_forEach(effects, identity, options),
									reconcile.value,
								)
							: fiberRuntime_forEach(effects, identity, options)
			},
			fiberRuntime_forEach = dual(
				args => isIterable(args[0]),
				(self, f, options) =>
					withFiberRuntime(r => {
						const isRequestBatchingEnabled =
							!0 === options?.batching ||
							("inherit" === options?.batching &&
								r.getFiberRef(currentRequestBatching))
						return options?.discard
							? concurrency_match(
									options.concurrency,
									() =>
										finalizersMaskInternal(
											ExecutionStrategy_sequential,
											options?.concurrentFinalizers,
										)(restore =>
											isRequestBatchingEnabled
												? forEachConcurrentDiscard(
														self,
														(a, i) => restore(f(a, i)),
														!0,
														!1,
														1,
													)
												: forEachSequentialDiscard(self, (a, i) =>
														restore(f(a, i)),
													),
										),
									() =>
										finalizersMaskInternal(
											ExecutionStrategy_parallel,
											options?.concurrentFinalizers,
										)(restore =>
											forEachConcurrentDiscard(
												self,
												(a, i) => restore(f(a, i)),
												isRequestBatchingEnabled,
												!1,
											),
										),
									n =>
										finalizersMaskInternal(
											ExecutionStrategy_parallelN(n),
											options?.concurrentFinalizers,
										)(restore =>
											forEachConcurrentDiscard(
												self,
												(a, i) => restore(f(a, i)),
												isRequestBatchingEnabled,
												!1,
												n,
											),
										),
								)
							: concurrency_match(
									options?.concurrency,
									() =>
										finalizersMaskInternal(
											ExecutionStrategy_sequential,
											options?.concurrentFinalizers,
										)(restore =>
											isRequestBatchingEnabled
												? forEachParN(self, 1, (a, i) => restore(f(a, i)), !0)
												: forEachSequential(self, (a, i) => restore(f(a, i))),
										),
									() =>
										finalizersMaskInternal(
											ExecutionStrategy_parallel,
											options?.concurrentFinalizers,
										)(restore =>
											forEachParUnbounded(
												self,
												(a, i) => restore(f(a, i)),
												isRequestBatchingEnabled,
											),
										),
									n =>
										finalizersMaskInternal(
											ExecutionStrategy_parallelN(n),
											options?.concurrentFinalizers,
										)(restore =>
											forEachParN(
												self,
												n,
												(a, i) => restore(f(a, i)),
												isRequestBatchingEnabled,
											),
										),
								)
					}),
			),
			forEachParUnbounded = (self, f, batching) =>
				suspend(() => {
					const as = Array_fromIterable(self),
						array = new Array(as.length)
					return core_zipRight(
						forEachConcurrentDiscard(
							as,
							(a, i) => core_flatMap(f(a, i), b => sync(() => (array[i] = b))),
							batching,
							!1,
						),
						succeed(array),
					)
				}),
			forEachConcurrentDiscard = (self, f, batching, processAll, n) =>
				uninterruptibleMask(restore =>
					(f =>
						withFiberRuntime(state => {
							const scope = pipe(
								state.getFiberRef(currentForkScopeOverride),
								Option_getOrElse(() => state.scope()),
							)
							return f(
								fiberRefLocally(currentForkScopeOverride, Option_some(scope)),
							)
						}))(graft =>
						withFiberRuntime(parent => {
							let todos = Array.from(self).reverse(),
								target = todos.length
							if (0 === target) return core_void_
							let counter = 0,
								interrupted = !1
							const fibersCount = n ? Math.min(todos.length, n) : todos.length,
								fibers = new Set(),
								results = new Array(),
								startOrder = new Array(),
								joinOrder = new Array(),
								residual = new Array(),
								collectExits = () => {
									const exits = results
										.filter(({ exit }) => "Failure" === exit._tag)
										.sort((a, b) =>
											a.index < b.index ? -1 : a.index === b.index ? 0 : 1,
										)
										.map(({ exit }) => exit)
									0 === exits.length && exits.push(exitVoid)
									return exits
								},
								runFiber = (eff, interruptImmediately = !1) => {
									const runnable = uninterruptible(graft(eff)),
										fiber = unsafeForkUnstarted(
											runnable,
											parent,
											parent.currentRuntimeFlags,
											globalScope,
										)
									parent.currentScheduler.scheduleTask(
										() => {
											interruptImmediately &&
												fiber.unsafeInterruptAsFork(parent.id())
											fiber.resume(runnable)
										},
										0,
										fiber,
									)
									return fiber
								},
								onInterruptSignal = () => {
									if (!processAll) {
										target -= todos.length
										todos = []
									}
									interrupted = !0
									fibers.forEach(fiber => {
										fiber.currentScheduler.scheduleTask(
											() => {
												fiber.unsafeInterruptAsFork(parent.id())
											},
											0,
											fiber,
										)
									})
								},
								stepOrExit = batching ? step : core_exit,
								processingFiber = runFiber(
									async_(resume => {
										const pushResult = (res, index) => {
												if ("Blocked" === res._op) residual.push(res)
												else {
													results.push({ index, exit: res })
													"Failure" !== res._op ||
														interrupted ||
														onInterruptSignal()
												}
											},
											next = () => {
												if (todos.length > 0) {
													const a = todos.pop()
													let index = counter++
													const returnNextElement = () => {
															const a = todos.pop()
															index = counter++
															return core_flatMap(yieldNow(), () =>
																core_flatMap(
																	stepOrExit(restore(f(a, index))),
																	onRes,
																),
															)
														},
														onRes = res => {
															if (todos.length > 0) {
																pushResult(res, index)
																if (todos.length > 0) return returnNextElement()
															}
															return succeed(res)
														},
														todo = core_flatMap(
															stepOrExit(restore(f(a, index))),
															onRes,
														),
														fiber = runFiber(todo)
													startOrder.push(fiber)
													fibers.add(fiber)
													interrupted &&
														fiber.currentScheduler.scheduleTask(
															() => {
																fiber.unsafeInterruptAsFork(parent.id())
															},
															0,
															fiber,
														)
													fiber.addObserver(wrapped => {
														let exit
														exit =
															"Failure" === wrapped._op
																? wrapped
																: wrapped.effect_instruction_i0
														joinOrder.push(fiber)
														fibers.delete(fiber)
														pushResult(exit, index)
														if (results.length === target)
															resume(
																succeed(
																	Option_getOrElse(
																		exitCollectAll(collectExits(), {
																			parallel: !0,
																		}),
																		() => exitVoid,
																	),
																),
															)
														else if (
															residual.length + results.length ===
															target
														) {
															const exits = collectExits(),
																requests = residual
																	.map(blocked => blocked.effect_instruction_i0)
																	.reduce(par)
															resume(
																succeed(
																	blocked(
																		requests,
																		forEachConcurrentDiscard(
																			[
																				Option_getOrElse(
																					exitCollectAll(exits, {
																						parallel: !0,
																					}),
																					() => exitVoid,
																				),
																				...residual.map(
																					blocked =>
																						blocked.effect_instruction_i1,
																				),
																			],
																			i => i,
																			batching,
																			!0,
																			n,
																		),
																	),
																),
															)
														} else next()
													})
												}
											}
										for (let i = 0; i < fibersCount; i++) next()
									}),
								)
							return core_asVoid(
								onExit(
									core_flatten(restore(fiber_join(processingFiber))),
									exitMatch({
										onFailure: cause => {
											onInterruptSignal()
											const target = residual.length + 1,
												concurrency = Math.min(
													"number" == typeof n ? n : residual.length,
													residual.length,
												),
												toPop = Array.from(residual)
											return async_(cb => {
												const exits = []
												let count = 0,
													index = 0
												const check = (index, hitNext) => exit => {
														exits[index] = exit
														count++
														count === target &&
															cb(exitSucceed(exitFailCause(cause)))
														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, f => f.inheritAll),
									}),
								),
							)
						}),
					),
				),
			forEachParN = (self, n, f, batching) =>
				suspend(() => {
					const as = Array_fromIterable(self),
						array = new Array(as.length)
					return core_zipRight(
						forEachConcurrentDiscard(
							as,
							(a, i) => core_map(f(a, i), b => (array[i] = b)),
							batching,
							!1,
							n,
						),
						succeed(array),
					)
				}),
			fiberRuntime_forkDaemon = self =>
				forkWithScopeOverride(self, globalScope),
			fiberRuntime_unsafeFork = (
				effect,
				parentFiber,
				parentRuntimeFlags,
				overrideScope = null,
			) => {
				const childFiber = unsafeMakeChildFiber(
					effect,
					parentFiber,
					parentRuntimeFlags,
					overrideScope,
				)
				childFiber.resume(effect)
				return childFiber
			},
			unsafeForkUnstarted = (
				effect,
				parentFiber,
				parentRuntimeFlags,
				overrideScope = null,
			) =>
				unsafeMakeChildFiber(
					effect,
					parentFiber,
					parentRuntimeFlags,
					overrideScope,
				),
			unsafeMakeChildFiber = (
				effect,
				parentFiber,
				parentRuntimeFlags,
				overrideScope = null,
			) => {
				const childId = FiberId_unsafeMake(),
					parentFiberRefs = parentFiber.getFiberRefs(),
					childFiberRefs = forkAs(parentFiberRefs, childId),
					childFiber = new FiberRuntime(
						childId,
						childFiberRefs,
						parentRuntimeFlags,
					),
					childContext = getOrDefault(childFiberRefs, currentContext),
					supervisor = childFiber.currentSupervisor
				supervisor.onStart(
					childContext,
					effect,
					Option_some(parentFiber),
					childFiber,
				)
				childFiber.addObserver(exit => supervisor.onEnd(exit, childFiber))
				;(null !== overrideScope
					? overrideScope
					: pipe(
							parentFiber.getFiberRef(currentForkScopeOverride),
							Option_getOrElse(() => parentFiber.scope()),
						)
				).add(parentRuntimeFlags, childFiber)
				return childFiber
			},
			forkWithScopeOverride = (self, scopeOverride) =>
				withFiberRuntime((parentFiber, parentStatus) =>
					succeed(
						fiberRuntime_unsafeFork(
							self,
							parentFiber,
							parentStatus.runtimeFlags,
							scopeOverride,
						),
					),
				),
			parallelFinalizers = self =>
				contextWithEffect(context =>
					Option_match(Context_getOption(context, scopeTag), {
						onNone: () => self,
						onSome: scope => {
							switch (scope.strategy._tag) {
								case "Parallel":
									return self
								case "Sequential":
								case "ParallelN":
									return core_flatMap(
										scopeFork(scope, ExecutionStrategy_parallel),
										inner => scopeExtend(self, inner),
									)
							}
						},
					}),
				),
			parallelNFinalizers = parallelism => self =>
				contextWithEffect(context =>
					Option_match(Context_getOption(context, scopeTag), {
						onNone: () => self,
						onSome: scope =>
							"ParallelN" === scope.strategy._tag &&
							scope.strategy.parallelism === parallelism
								? self
								: core_flatMap(
										scopeFork(scope, ExecutionStrategy_parallelN(parallelism)),
										inner => scopeExtend(self, inner),
									),
					}),
				),
			finalizersMaskInternal = (strategy, concurrentFinalizers) => self =>
				contextWithEffect(context =>
					Option_match(Context_getOption(context, scopeTag), {
						onNone: () => self(identity),
						onSome: scope => {
							if (!0 !== concurrentFinalizers) return self(identity)
							{
								const patch =
									"Parallel" === strategy._tag
										? parallelFinalizers
										: "Sequential" === strategy._tag
											? sequentialFinalizers
											: parallelNFinalizers(strategy.parallelism)
								switch (scope.strategy._tag) {
									case "Parallel":
										return patch(self(parallelFinalizers))
									case "Sequential":
										return patch(self(sequentialFinalizers))
									case "ParallelN":
										return patch(
											self(parallelNFinalizers(scope.strategy.parallelism)),
										)
								}
							}
						},
					}),
				),
			scopeWith = f => core_flatMap(scopeTag, f),
			scopedWith = f =>
				core_flatMap(fiberRuntime_scopeMake(), scope =>
					onExit(f(scope), exit => scope.close(exit)),
				),
			sequentialFinalizers = self =>
				contextWithEffect(context =>
					Option_match(Context_getOption(context, scopeTag), {
						onNone: () => self,
						onSome: scope => {
							switch (scope.strategy._tag) {
								case "Sequential":
									return self
								case "Parallel":
								case "ParallelN":
									return core_flatMap(
										scopeFork(scope, ExecutionStrategy_sequential),
										inner => scopeExtend(self, inner),
									)
							}
						},
					}),
				),
			zipOptions = dual(
				args => isEffect(args[1]),
				(self, that, options) =>
					zipWithOptions(self, that, (a, b) => [a, b], options),
			),
			zipLeftOptions = dual(
				args => isEffect(args[1]),
				(self, that, options) =>
					!0 === options?.concurrent ||
					(void 0 !== options?.batching && !1 !== options.batching)
						? zipWithOptions(self, that, (a, _) => a, options)
						: core_zipLeft(self, that),
			),
			zipRightOptions = dual(
				args => isEffect(args[1]),
				(self, that, options) =>
					!0 === options?.concurrent ||
					(void 0 !== options?.batching && !1 !== options.batching)
						? zipWithOptions(self, that, (_, b) => b, options)
						: core_zipRight(self, that),
			),
			zipWithOptions = dual(
				args => isEffect(args[1]),
				(self, that, f, options) =>
					core_map(
						fiberRuntime_all([self, that], {
							concurrency: options?.concurrent ? 2 : 1,
							batching: options?.batching,
							concurrentFinalizers: options?.concurrentFinalizers,
						}),
						([a, a2]) => f(a, a2),
					),
			),
			scopeTag = GenericTag("effect/Scope"),
			fiberRuntime_scope = scopeTag,
			ScopeImplProto = {
				[ScopeTypeId]: ScopeTypeId,
				[CloseableScopeTypeId]: CloseableScopeTypeId,
				pipe() {
					return pipeArguments(this, arguments)
				},
				fork(strategy) {
					return sync(() => {
						const newScope = fiberRuntime_scopeUnsafeMake(strategy)
						if ("Closed" === this.state._tag) {
							newScope.state = this.state
							return newScope
						}
						const key = {}
						this.state.finalizers.set(key, exit => newScope.close(exit))
						;((fin = _ =>
							sync(() => {
								"Open" === this.state._tag && this.state.finalizers.delete(key)
							})),
							"Open" === (scope = newScope).state._tag &&
								scope.state.finalizers.set({}, fin))
						var scope, fin
						return newScope
					})
				},
				close(exit) {
					return suspend(() => {
						if ("Closed" === this.state._tag) return core_void_
						const finalizers = Array.from(
							this.state.finalizers.values(),
						).reverse()
						this.state = { _tag: "Closed", exit }
						return 0 === finalizers.length
							? core_void_
							: (() => "Sequential" === this.strategy._tag)()
								? pipe(
										forEachSequential(finalizers, fin => core_exit(fin(exit))),
										core_flatMap(results =>
											pipe(
												exitCollectAll(results),
												Option_map(exitAsVoid),
												Option_getOrElse(() => exitVoid),
											),
										),
									)
								: (() => "Parallel" === this.strategy._tag)()
									? pipe(
											forEachParUnbounded(
												finalizers,
												fin => core_exit(fin(exit)),
												!1,
											),
											core_flatMap(results =>
												pipe(
													exitCollectAll(results, { parallel: !0 }),
													Option_map(exitAsVoid),
													Option_getOrElse(() => exitVoid),
												),
											),
										)
									: pipe(
											forEachParN(
												finalizers,
												this.strategy.parallelism,
												fin => core_exit(fin(exit)),
												!1,
											),
											core_flatMap(results =>
												pipe(
													exitCollectAll(results, { parallel: !0 }),
													Option_map(exitAsVoid),
													Option_getOrElse(() => exitVoid),
												),
											),
										)
					})
				},
				addFinalizer(fin) {
					return suspend(() => {
						if ("Closed" === this.state._tag) return fin(this.state.exit)
						this.state.finalizers.set({}, fin)
						return core_void_
					})
				},
			},
			fiberRuntime_scopeUnsafeMake = (
				strategy = executionStrategy_sequential,
			) => {
				const scope = Object.create(ScopeImplProto)
				scope.strategy = strategy
				scope.state = { _tag: "Open", finalizers: new Map() }
				return scope
			},
			fiberRuntime_scopeMake = (strategy = executionStrategy_sequential) =>
				sync(() => fiberRuntime_scopeUnsafeMake(strategy)),
			scopeExtend = dual(2, (effect, scope) =>
				mapInputContext(effect, Context_merge(Context_make(scopeTag, scope))),
			),
			fiberRefUnsafeMakeSupervisor = initial =>
				fiberRefUnsafeMakePatch(initial, {
					differ: patch_differ,
					fork: supervisor_patch_empty,
				}),
			fiberRefLocallyScoped = dual(2, (self, value) =>
				core_asVoid(
					fiberRuntime_acquireRelease(
						core_flatMap(fiberRefGet(self), oldValue =>
							core_as(fiberRefSet(self, value), oldValue),
						),
						oldValue => fiberRefSet(self, oldValue),
					),
				),
			),
			fiberRefLocallyScopedWith = dual(2, (self, f) =>
				fiberRefGetWith(self, a => fiberRefLocallyScoped(self, f(a))),
			),
			currentRuntimeFlags = fiberRefUnsafeMakeRuntimeFlags(runtimeFlags_none),
			currentSupervisor = fiberRefUnsafeMakeSupervisor(supervisor_none),
			raceWith = dual(3, (self, other, options) =>
				raceFibersWith(self, other, {
					onSelfWin: (winner, loser) =>
						core_flatMap(winner.await, exit => {
							switch (exit._tag) {
								case "Success":
									return core_flatMap(winner.inheritAll, () =>
										options.onSelfDone(exit, loser),
									)
								case "Failure":
									return options.onSelfDone(exit, loser)
							}
						}),
					onOtherWin: (winner, loser) =>
						core_flatMap(winner.await, exit => {
							switch (exit._tag) {
								case "Success":
									return core_flatMap(winner.inheritAll, () =>
										options.onOtherDone(exit, loser),
									)
								case "Failure":
									return options.onOtherDone(exit, loser)
							}
						}),
				}),
			),
			fiberRuntime_race = dual(2, (self, that) =>
				fiberIdWith(parentFiberId =>
					raceWith(self, that, {
						onSelfDone: (exit, right) =>
							exitMatchEffect(exit, {
								onFailure: cause =>
									pipe(
										fiber_join(right),
										core_effect_mapErrorCause(cause2 =>
											parallel(cause, cause2),
										),
									),
								onSuccess: value =>
									pipe(right, interruptAsFiber(parentFiberId), core_as(value)),
							}),
						onOtherDone: (exit, left) =>
							exitMatchEffect(exit, {
								onFailure: cause =>
									pipe(
										fiber_join(left),
										core_effect_mapErrorCause(cause2 =>
											parallel(cause2, cause),
										),
									),
								onSuccess: value =>
									pipe(left, interruptAsFiber(parentFiberId), core_as(value)),
							}),
					}),
				),
			),
			raceFibersWith = dual(3, (self, other, options) =>
				withFiberRuntime((parentFiber, parentStatus) => {
					const parentRuntimeFlags = parentStatus.runtimeFlags,
						raceIndicator = MutableRef_make(!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)
						},
						FiberId_combine(leftFiber.id(), rightFiber.id()),
					)
				}),
			),
			completeRace = (winner, loser, cont, ab, cb) => {
				compareAndSet(!0, !1)(ab) && cb(cont(winner, loser))
			},
			fiberRuntime_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 => core_as(finalizer, a),
					}),
				),
			),
			invokeWithInterrupt = (self, entries, onInterrupt) =>
				fiberIdWith(id =>
					fiberRuntime_ensuring(
						core_flatMap(
							fiberRuntime_forkDaemon(core_interruptible(self)),
							processing =>
								async_(cb => {
									const counts = entries.map(_ => _.listeners.count),
										checkDone = () => {
											if (
												counts.every(count => 0 === count) &&
												entries.every(
													_ =>
														"Pending" === _.result.state.current._tag ||
														!(
															"Done" !== _.result.state.current._tag ||
															!exitIsExit(_.result.state.current.effect) ||
															"Failure" !==
																_.result.state.current.effect._tag ||
															!isInterrupted(
																_.result.state.current.effect.cause,
															)
														),
												)
											) {
												cleanup.forEach(f => f())
												onInterrupt?.()
												cb(interruptFiber(processing))
											}
										}
									processing.addObserver(exit => {
										cleanup.forEach(f => f())
										cb(exit)
									})
									const cleanup = entries.map((r, i) => {
										const observer = count => {
											counts[i] = count
											checkDone()
										}
										r.listeners.addObserver(observer)
										return () => r.listeners.removeObserver(observer)
									})
									checkDone()
									return sync(() => {
										cleanup.forEach(f => f())
									})
								}),
						),
						suspend(() => {
							const residual = entries.flatMap(entry =>
								entry.state.completed ? [] : [entry],
							)
							return forEachSequentialDiscard(residual, entry =>
								complete(entry.request, exitInterrupt(id)),
							)
						}),
					),
				),
			Cause_fail = fail,
			Cause_die = die,
			Cause_interrupt = interrupt,
			Cause_isDieType = isDieType,
			Cause_isInterrupted = isInterrupted,
			Cause_isInterruptedOnly = isInterruptedOnly,
			Cause_interruptors = interruptors,
			Cause_failureOrCause = failureOrCause,
			Cause_map = cause_map,
			squash = self => causeSquashWith(identity)(self),
			Cause_NoSuchElementException = NoSuchElementException,
			Cause_pretty = pretty,
			IntervalTypeId = Symbol.for("effect/ScheduleInterval"),
			interval_empty = {
				[IntervalTypeId]: IntervalTypeId,
				startMillis: 0,
				endMillis: 0,
			},
			interval_make = (startMillis, endMillis) =>
				startMillis > endMillis
					? interval_empty
					: { [IntervalTypeId]: IntervalTypeId, startMillis, endMillis },
			interval_lessThan = dual(
				2,
				(self, that) => interval_min(self, that) === self,
			),
			interval_min = dual(2, (self, that) =>
				self.endMillis <= that.startMillis
					? self
					: that.endMillis <= self.startMillis
						? that
						: self.startMillis < that.startMillis
							? self
							: that.startMillis < self.startMillis
								? that
								: self.endMillis <= that.endMillis
									? self
									: that,
			),
			intersect = dual(2, (self, that) => {
				const start = Math.max(self.startMillis, that.startMillis),
					end = Math.min(self.endMillis, that.endMillis)
				return interval_make(start, end)
			}),
			ScheduleInterval_empty = interval_empty,
			ScheduleInterval_lessThan = interval_lessThan,
			ScheduleInterval_isEmpty = self => self.startMillis >= self.endMillis,
			ScheduleInterval_intersect = intersect,
			ScheduleInterval_after = startMilliseconds =>
				interval_make(startMilliseconds, Number.POSITIVE_INFINITY),
			IntervalsTypeId = Symbol.for("effect/ScheduleIntervals"),
			intervals_make = intervals => ({
				[IntervalsTypeId]: IntervalsTypeId,
				intervals,
			}),
			intervals_intersect = dual(2, (self, that) =>
				intersectLoop(self.intervals, that.intervals, esm_Chunk_empty()),
			),
			intersectLoop = (_left, _right, _acc) => {
				let left = _left,
					right = _right,
					acc = _acc
				for (; isNonEmpty(left) && isNonEmpty(right);) {
					const interval = pipe(
							Chunk_headNonEmpty(left),
							ScheduleInterval_intersect(Chunk_headNonEmpty(right)),
						),
						intervals = ScheduleInterval_isEmpty(interval)
							? acc
							: pipe(acc, Chunk_prepend(interval))
					pipe(
						Chunk_headNonEmpty(left),
						ScheduleInterval_lessThan(Chunk_headNonEmpty(right)),
					)
						? (left = Chunk_tailNonEmpty(left))
						: (right = Chunk_tailNonEmpty(right))
					acc = intervals
				}
				return intervals_make(Chunk_reverse(acc))
			},
			start = self =>
				pipe(
					self.intervals,
					Chunk_head,
					Option_getOrElse(() => ScheduleInterval_empty),
				).startMillis,
			intervals_lessThan = dual(2, (self, that) => start(self) < start(that)),
			ScheduleIntervals_make = intervals_make,
			ScheduleIntervals_intersect = intervals_intersect,
			ScheduleIntervals_start = start,
			ScheduleIntervals_end = self =>
				pipe(
					self.intervals,
					Chunk_head,
					Option_getOrElse(() => ScheduleInterval_empty),
				).endMillis,
			ScheduleIntervals_lessThan = intervals_lessThan,
			ScheduleDecision_continueWith = interval => ({
				_tag: "Continue",
				intervals: ScheduleIntervals_make(Chunk_of(interval)),
			}),
			ScheduleDecision_done = { _tag: "Done" },
			ScheduleDecision_isContinue = self => "Continue" === self._tag,
			ScheduleDecision_isDone = self => "Done" === self._tag,
			Scope_addFinalizer = scopeAddFinalizer,
			addFinalizerExit = scopeAddFinalizerExit,
			Scope_close = scopeClose,
			Scope_extend = scopeExtend,
			Scope_fork = scopeFork,
			Scope_make = fiberRuntime_scopeMake
		class Semaphore {
			permits
			waiters = new Set()
			taken = 0
			constructor(permits) {
				this.permits = permits
			}
			get free() {
				return this.permits - this.taken
			}
			take = n =>
				asyncInterrupt(resume => {
					if (this.free < n) {
						const observer = () => {
							if (!(this.free < n)) {
								this.waiters.delete(observer)
								resume(
									suspend(() => {
										if (this.free < n) return this.take(n)
										this.taken += n
										return succeed(n)
									}),
								)
							}
						}
						this.waiters.add(observer)
						return sync(() => {
							this.waiters.delete(observer)
						})
					}
					resume(
						suspend(() => {
							if (this.free < n) return this.take(n)
							this.taken += n
							return succeed(n)
						}),
					)
				})
			updateTakenUnsafe(fiber, f) {
				this.taken = f(this.taken)
				this.waiters.size > 0 &&
					fiber.getFiberRef(currentScheduler).scheduleTask(
						() => {
							const iter = this.waiters.values()
							let item = iter.next()
							for (; !1 === item.done && this.free > 0;) {
								item.value()
								item = iter.next()
							}
						},
						fiber.getFiberRef(currentSchedulingPriority),
						fiber,
					)
				return succeed(this.free)
			}
			updateTaken(f) {
				return withFiberRuntime(fiber => this.updateTakenUnsafe(fiber, f))
			}
			resize = permits =>
				core_asVoid(
					withFiberRuntime(fiber => {
						this.permits = permits
						return this.free < 0
							? core_void_
							: this.updateTakenUnsafe(fiber, taken => taken)
					}),
				)
			release = n => this.updateTaken(taken => taken - n)
			releaseAll = this.updateTaken(_ => 0)
			withPermits = n => self =>
				uninterruptibleMask(restore =>
					core_flatMap(restore(this.take(n)), permits =>
						fiberRuntime_ensuring(restore(self), this.release(permits)),
					),
				)
			withPermitsIfAvailable = n => self =>
				uninterruptibleMask(restore =>
					suspend(() => {
						if (this.free < n) return core_effect_succeedNone
						this.taken += n
						return fiberRuntime_ensuring(
							restore((self => core_map(self, Option_some))(self)),
							this.release(n),
						)
					}),
				)
		}
		const unsafeMakeSemaphore = permits => new Semaphore(permits),
			circular_forkIn = dual(2, (self, scope) =>
				withFiberRuntime((parent, parentStatus) => {
					const scopeImpl = scope,
						fiber = fiberRuntime_unsafeFork(
							self,
							parent,
							parentStatus.runtimeFlags,
							globalScope,
						)
					if ("Open" === scopeImpl.state._tag) {
						const finalizer = () =>
								fiberIdWith(fiberId =>
									equals(fiberId, fiber.id())
										? core_void_
										: core_asVoid(interruptFiber(fiber)),
								),
							key = {}
						scopeImpl.state.finalizers.set(key, finalizer)
						fiber.addObserver(() => {
							"Closed" !== scopeImpl.state._tag &&
								scopeImpl.state.finalizers.delete(key)
						})
					} else fiber.unsafeInterruptAsFork(parent.id())
					return succeed(fiber)
				}),
			),
			circular_raceFirst = dual(2, (self, that) =>
				pipe(core_exit(self), fiberRuntime_race(core_exit(that)), effect =>
					core_flatten(effect),
				),
			),
			SynchronizedTypeId = Symbol.for("effect/Ref/SynchronizedRef"),
			synchronizedVariance = { _A: _ => _ }
		class SynchronizedImpl extends Effectable_Class {
			ref
			withLock;
			[SynchronizedTypeId] = synchronizedVariance;
			[RefTypeId] = refVariance;
			[Readable_TypeId] = Readable_TypeId
			constructor(ref, withLock) {
				super()
				this.ref = ref
				this.withLock = withLock
				this.get = ref_get(this.ref)
			}
			get;
			commit() {
				return this.get
			}
			modify(f) {
				return this.modifyEffect(a => succeed(f(a)))
			}
			modifyEffect(f) {
				return this.withLock(
					pipe(
						core_flatMap(ref_get(this.ref), f),
						core_flatMap(([b, a]) => core_as(ref_set(this.ref, a), b)),
					),
				)
			}
		}
		const makeSynchronized = value => sync(() => unsafeMakeSynchronized(value)),
			unsafeMakeSynchronized = value => {
				const ref = ref_unsafeMake(value),
					sem = unsafeMakeSemaphore(1)
				return new SynchronizedImpl(ref, sem.withPermits(1))
			},
			circular_TypeId = Symbol.for("effect/ManagedRuntime"),
			Fiber_await = self => self.await,
			Fiber_inheritAll = self => self.inheritAll,
			Fiber_interrupt = interruptFiber,
			interruptAs = interruptAsFiber,
			Fiber_join = fiber_join,
			makeDual = f =>
				function () {
					if (1 === arguments.length) {
						const runtime = arguments[0]
						return (effect, ...args) => f(runtime, effect, ...args)
					}
					return f.apply(this, arguments)
				},
			runtime_unsafeFork = makeDual((runtime, self, options) => {
				const fiberId = FiberId_unsafeMake(),
					fiberRefUpdates = [[currentContext, [[fiberId, runtime.context]]]]
				options?.scheduler &&
					fiberRefUpdates.push([
						currentScheduler,
						[[fiberId, options.scheduler]],
					])
				let fiberRefs = FiberRefs_updateManyAs(runtime.fiberRefs, {
					entries: fiberRefUpdates,
					forkAs: fiberId,
				})
				options?.updateRefs &&
					(fiberRefs = options.updateRefs(fiberRefs, fiberId))
				const fiberRuntime = new FiberRuntime(
					fiberId,
					fiberRefs,
					runtime.runtimeFlags,
				)
				let effect = self
				options?.scope &&
					(effect = core_flatMap(
						Scope_fork(options.scope, executionStrategy_sequential),
						closeableScope =>
							core_zipRight(
								scopeAddFinalizer(
									closeableScope,
									fiberIdWith(id =>
										equals(id, fiberRuntime.id())
											? core_void_
											: interruptAsFiber(fiberRuntime, id),
									),
								),
								onExit(self, exit => Scope_close(closeableScope, exit)),
							),
					))
				const supervisor = fiberRuntime.currentSupervisor
				if (supervisor !== supervisor_none) {
					supervisor.onStart(
						runtime.context,
						effect,
						Option_none(),
						fiberRuntime,
					)
					fiberRuntime.addObserver(exit => supervisor.onEnd(exit, fiberRuntime))
				}
				globalScope.add(runtime.runtimeFlags, fiberRuntime)
				!1 === options?.immediate
					? fiberRuntime.resume(effect)
					: fiberRuntime.start(effect)
				return fiberRuntime
			}),
			unsafeRunSync = makeDual((runtime, effect) => {
				const result = unsafeRunSyncExit(runtime)(effect)
				if ("Failure" === result._tag)
					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
			}
		}
		const FiberFailureId = Symbol.for("effect/Runtime/FiberFailure"),
			FiberFailureCauseId = Symbol.for("effect/Runtime/FiberFailure/Cause")
		class FiberFailureImpl extends Error {
			[FiberFailureId];
			[FiberFailureCauseId]
			constructor(cause) {
				const head = prettyErrors(cause)[0]
				super(head?.message || "An error has occurred")
				this[FiberFailureId] = FiberFailureId
				this[FiberFailureCauseId] = cause
				this.name = head ? `(FiberFailure) ${head.name}` : "FiberFailure"
				head?.stack && (this.stack = head.stack)
			}
			toJSON() {
				return {
					_id: "FiberFailure",
					cause: this[FiberFailureCauseId].toJSON(),
				}
			}
			toString() {
				return (
					"(FiberFailure) " +
					pretty(this[FiberFailureCauseId], { renderErrorCause: !0 })
				)
			}
			[NodeInspectSymbol]() {
				return this.toString()
			}
		}
		const fiberFailure = cause => {
				const limit = Error.stackTraceLimit
				Error.stackTraceLimit = 0
				const error = new FiberFailureImpl(cause)
				Error.stackTraceLimit = limit
				return error
			},
			fastPath = effect => {
				const 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(new NoSuchElementException())
				}
			},
			unsafeRunSyncExit = makeDual((runtime, effect) => {
				const op = fastPath(effect)
				if (op) return op
				const scheduler = new SyncScheduler(),
					fiberRuntime = runtime_unsafeFork(runtime)(effect, { scheduler })
				scheduler.flush()
				return (
					fiberRuntime.unsafePoll() ||
					exitDie(
						capture(
							(fiber => {
								const limit = Error.stackTraceLimit
								Error.stackTraceLimit = 0
								const error = new AsyncFiberExceptionImpl(fiber)
								Error.stackTraceLimit = limit
								return error
							})(fiberRuntime),
							currentSpanFromFiber(fiberRuntime),
						),
					)
				)
			}),
			unsafeRunPromise = makeDual((runtime, effect, options) =>
				unsafeRunPromiseExit(runtime, effect, options).then(result => {
					switch (result._tag) {
						case "Success":
							return result.effect_instruction_i0
						case "Failure":
							throw fiberFailure(result.effect_instruction_i0)
					}
				}),
			),
			unsafeRunPromiseExit = makeDual(
				(runtime, effect, options) =>
					new Promise(resolve => {
						const op = fastPath(effect)
						op && resolve(op)
						const fiber = runtime_unsafeFork(runtime)(effect)
						fiber.addObserver(exit => {
							resolve(exit)
						})
						void 0 !== options?.signal &&
							(options.signal.aborted
								? fiber.unsafeInterruptAsFork(fiber.id())
								: options.signal.addEventListener(
										"abort",
										() => {
											fiber.unsafeInterruptAsFork(fiber.id())
										},
										{ once: !0 },
									))
					}),
			)
		class RuntimeImpl {
			context
			runtimeFlags
			fiberRefs
			constructor(context, runtimeFlags, fiberRefs) {
				this.context = context
				this.runtimeFlags = runtimeFlags
				this.fiberRefs = fiberRefs
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const runtime_make = options =>
				new RuntimeImpl(
					options.context,
					options.runtimeFlags,
					options.fiberRefs,
				),
			defaultRuntimeFlags = runtimeFlags_make(1, 32, 4),
			defaultRuntime = runtime_make({
				context: Context_empty(),
				runtimeFlags: defaultRuntimeFlags,
				fiberRefs: FiberRefs_empty(),
			}),
			unsafeForkEffect = runtime_unsafeFork(defaultRuntime),
			unsafeRunPromiseEffect = unsafeRunPromise(defaultRuntime),
			unsafeRunSyncEffect = unsafeRunSync(defaultRuntime),
			modifyEffect = dual(2, (self, f) => self.modifyEffect(f)),
			LayerTypeId = Symbol.for("effect/Layer"),
			layer_proto = {
				[LayerTypeId]: { _RIn: _ => _, _E: _ => _, _ROut: _ => _ },
				pipe() {
					return pipeArguments(this, arguments)
				},
			},
			MemoMapTypeId = Symbol.for("effect/Layer/MemoMap"),
			CurrentMemoMap = Context_Reference()("effect/Layer/CurrentMemoMap", {
				defaultValue: () => unsafeMakeMemoMap(),
			}),
			isFresh = self => "Fresh" === self._op_layer
		class MemoMapImpl {
			ref;
			[MemoMapTypeId]
			constructor(ref) {
				this.ref = ref
				this[MemoMapTypeId] = MemoMapTypeId
			}
			getOrElseMemoize(layer, scope) {
				return pipe(
					modifyEffect(this.ref, map => {
						const inMap = map.get(layer)
						if (void 0 !== inMap) {
							const [acquire, release] = inMap,
								cached = pipe(
									acquire,
									core_flatMap(([patch, b]) =>
										pipe(
											(patch =>
												(f =>
													withFiberRuntime(state => {
														state.setFiberRefs(
															f(state.id(), state.getFiberRefs()),
														)
														return core_void_
													}))((fiberId, fiberRefs) =>
													pipe(patch, patch_patch(fiberId, fiberRefs)),
												))(patch),
											core_as(b),
										),
									),
									onExit(
										exitMatch({
											onFailure: () => core_void_,
											onSuccess: () => scopeAddFinalizerExit(scope, release),
										}),
									),
								)
							return succeed([cached, map])
						}
						return pipe(
							ref_make(0),
							core_flatMap(observers =>
								pipe(
									deferredMake(),
									core_flatMap(deferred =>
										pipe(
											ref_make(() => core_void_),
											core_map(finalizerRef => {
												const resource = uninterruptibleMask(restore =>
														pipe(
															fiberRuntime_scopeMake(),
															core_flatMap(innerScope =>
																pipe(
																	restore(
																		core_flatMap(
																			makeBuilder(layer, innerScope, !0),
																			f =>
																				(self =>
																					summarized(
																						self,
																						core_effect_fiberRefs,
																						patch_diff,
																					))(f(this)),
																		),
																	),
																	core_exit,
																	core_flatMap(exit => {
																		switch (exit._tag) {
																			case "Failure":
																				return pipe(
																					deferredFailCause(
																						deferred,
																						exit.effect_instruction_i0,
																					),
																					core_zipRight(
																						scopeClose(innerScope, exit),
																					),
																					core_zipRight(
																						failCause(
																							exit.effect_instruction_i0,
																						),
																					),
																				)
																			case "Success":
																				return pipe(
																					ref_set(finalizerRef, exit =>
																						pipe(
																							scopeClose(innerScope, exit),
																							whenEffect(
																								ref_modify(observers, n => [
																									1 === n,
																									n - 1,
																								]),
																							),
																							core_asVoid,
																						),
																					),
																					core_zipRight(
																						ref_update(observers, n => n + 1),
																					),
																					core_zipRight(
																						scopeAddFinalizerExit(scope, exit =>
																							pipe(
																								sync(() => map.delete(layer)),
																								core_zipRight(
																									ref_get(finalizerRef),
																								),
																								core_flatMap(finalizer =>
																									finalizer(exit),
																								),
																							),
																						),
																					),
																					core_zipRight(
																						deferredSucceed(
																							deferred,
																							exit.effect_instruction_i0,
																						),
																					),
																					core_as(
																						exit.effect_instruction_i0[1],
																					),
																				)
																		}
																	}),
																),
															),
														),
													),
													memoized = [
														pipe(
															deferredAwait(deferred),
															onExit(
																exitMatchEffect({
																	onFailure: () => core_void_,
																	onSuccess: () =>
																		ref_update(observers, n => n + 1),
																}),
															),
														),
														exit =>
															pipe(
																ref_get(finalizerRef),
																core_flatMap(finalizer => finalizer(exit)),
															),
													]
												return [
													resource,
													isFresh(layer) ? map : map.set(layer, memoized),
												]
											}),
										),
									),
								),
							),
						)
					}),
					core_flatten,
				)
			}
		}
		const makeMemoMap = suspend(() =>
				core_map(makeSynchronized(new Map()), ref => new MemoMapImpl(ref)),
			),
			unsafeMakeMemoMap = () =>
				new MemoMapImpl(unsafeMakeSynchronized(new Map())),
			buildWithScope = dual(2, (self, scope) =>
				core_flatMap(makeMemoMap, memoMap =>
					buildWithMemoMap(self, memoMap, scope),
				),
			),
			buildWithMemoMap = dual(3, (self, memoMap, scope) =>
				core_flatMap(makeBuilder(self, scope), run =>
					core_effect_provideService(run(memoMap), CurrentMemoMap, memoMap),
				),
			),
			makeBuilder = (self, scope, inMemoMap = !1) => {
				const op = self
				switch (op._op_layer) {
					case "Locally":
						return sync(
							() => memoMap => op.f(memoMap.getOrElseMemoize(op.self, scope)),
						)
					case "ExtendScope":
						return sync(
							() => memoMap =>
								scopeWith(scope => memoMap.getOrElseMemoize(op.layer, scope)),
						)
					case "Fold":
						return sync(
							() => memoMap =>
								pipe(
									memoMap.getOrElseMemoize(op.layer, scope),
									matchCauseEffect({
										onFailure: cause =>
											memoMap.getOrElseMemoize(op.failureK(cause), scope),
										onSuccess: value =>
											memoMap.getOrElseMemoize(op.successK(value), scope),
									}),
								),
						)
					case "Fresh":
						return sync(() => _ => pipe(op.layer, buildWithScope(scope)))
					case "FromEffect":
						return sync(
							inMemoMap
								? () => _ => op.effect
								: () => memoMap => memoMap.getOrElseMemoize(self, scope),
						)
					case "Provide":
						return sync(
							() => memoMap =>
								pipe(
									memoMap.getOrElseMemoize(op.first, scope),
									core_flatMap(env =>
										pipe(
											memoMap.getOrElseMemoize(op.second, scope),
											provideContext(env),
										),
									),
								),
						)
					case "Scoped":
						return sync(
							inMemoMap
								? () => _ => scopeExtend(op.effect, scope)
								: () => memoMap => memoMap.getOrElseMemoize(self, scope),
						)
					case "Suspend":
						return sync(
							() => memoMap => memoMap.getOrElseMemoize(op.evaluate(), scope),
						)
					case "ProvideMerge":
						return sync(
							() => memoMap =>
								pipe(
									memoMap.getOrElseMemoize(op.first, scope),
									core_zipWith(
										memoMap.getOrElseMemoize(op.second, scope),
										op.zipK,
									),
								),
						)
					case "ZipWith":
						return core_gen(function* () {
							const parallelScope = yield* scopeFork(
									scope,
									executionStrategy_parallel,
								),
								firstScope = yield* scopeFork(
									parallelScope,
									executionStrategy_sequential,
								),
								secondScope = yield* scopeFork(
									parallelScope,
									executionStrategy_sequential,
								)
							return memoMap =>
								pipe(
									memoMap.getOrElseMemoize(op.first, firstScope),
									zipWithOptions(
										memoMap.getOrElseMemoize(op.second, secondScope),
										op.zipK,
										{ concurrent: !0 },
									),
								)
						})
					case "MergeAll": {
						const layers = op.layers
						return core_map(
							scopeFork(scope, executionStrategy_parallel),
							parallelScope => memoMap => {
								const contexts = new Array(layers.length)
								return core_map(
									forEachConcurrentDiscard(
										layers,
										fnUntraced(function* (layer, i) {
											const scope = yield* scopeFork(
													parallelScope,
													executionStrategy_sequential,
												),
												context = yield* memoMap.getOrElseMemoize(layer, scope)
											contexts[i] = context
										}),
										!1,
										!1,
									),
									() =>
										((...ctxs) => {
											const map = new Map()
											for (let i = 0; i < ctxs.length; i++)
												ctxs[i].unsafeMap.forEach((value, key) => {
													map.set(key, value)
												})
											return makeContext(map)
										})(...contexts),
								)
							},
						)
					}
				}
			},
			layer_fail = error => layer_failCause(Cause_fail(error)),
			layer_failCause = cause =>
				(function (effect) {
					const fromEffect = Object.create(layer_proto)
					fromEffect._op_layer = "FromEffect"
					fromEffect.effect = effect
					return fromEffect
				})(failCause(cause)),
			layer_flatMap = dual(2, (self, f) =>
				layer_match(self, { onFailure: layer_fail, onSuccess: f }),
			),
			layer_matchCause = dual(2, (self, { onFailure, onSuccess }) => {
				const fold = Object.create(layer_proto)
				fold._op_layer = "Fold"
				fold.layer = self
				fold.failureK = onFailure
				fold.successK = onSuccess
				return fold
			}),
			layer_match = dual(2, (self, { onFailure, onSuccess }) =>
				layer_matchCause(self, {
					onFailure: cause => {
						const failureOrCause = Cause_failureOrCause(cause)
						switch (failureOrCause._tag) {
							case "Left":
								return onFailure(failureOrCause.left)
							case "Right":
								return layer_failCause(failureOrCause.right)
						}
					},
					onSuccess,
				}),
			),
			scopedDiscard = effect =>
				scopedContext(pipe(effect, core_as(Context_empty()))),
			scopedContext = effect => {
				const scoped = Object.create(layer_proto)
				scoped._op_layer = "Scoped"
				scoped.effect = effect
				return scoped
			},
			provideSomeLayer = dual(2, (self, layer) =>
				scopedWith(scope =>
					core_flatMap(buildWithScope(layer, scope), context =>
						provideSomeContext(self, context),
					),
				),
			),
			provideSomeRuntime = dual(2, (self, rt) => {
				const patchRefs = FiberRefsPatch_diff(
						defaultRuntime.fiberRefs,
						rt.fiberRefs,
					),
					patchFlags = runtimeFlags_diff(
						defaultRuntime.runtimeFlags,
						rt.runtimeFlags,
					)
				return uninterruptibleMask(restore =>
					withFiberRuntime(fiber => {
						const oldContext = fiber.getFiberRef(currentContext),
							oldRefs = fiber.getFiberRefs(),
							newRefs = FiberRefsPatch_patch(fiber.id(), oldRefs)(patchRefs),
							oldFlags = fiber.currentRuntimeFlags,
							newFlags = runtimeFlags_patch(patchFlags)(oldFlags),
							rollbackRefs = FiberRefsPatch_diff(newRefs, oldRefs),
							rollbackFlags = runtimeFlags_diff(newFlags, oldFlags)
						fiber.setFiberRefs(newRefs)
						fiber.currentRuntimeFlags = newFlags
						return fiberRuntime_ensuring(
							provideSomeContext(
								restore(self),
								Context_merge(oldContext, rt.context),
							),
							withFiberRuntime(fiber => {
								fiber.setFiberRefs(
									FiberRefsPatch_patch(
										fiber.id(),
										fiber.getFiberRefs(),
									)(rollbackRefs),
								)
								fiber.currentRuntimeFlags = runtimeFlags_patch(rollbackFlags)(
									fiber.currentRuntimeFlags,
								)
								return core_void_
							}),
						)
					}),
				)
			}),
			effect_provide = dual(2, (self, source) =>
				Array.isArray(source)
					? provideSomeLayer(
							self,
							((...layers) => {
								const mergeAll = Object.create(layer_proto)
								mergeAll._op_layer = "MergeAll"
								mergeAll.layers = layers
								return mergeAll
							})(...source),
						)
					: (u => hasProperty(u, LayerTypeId))(source)
						? provideSomeLayer(self, source)
						: Context_isContext(source)
							? provideSomeContext(self, source)
							: circular_TypeId in source
								? core_flatMap(source.runtimeEffect, rt =>
										provideSomeRuntime(self, rt),
									)
								: provideSomeRuntime(self, source),
			),
			consoleWith = f =>
				fiberRefGetWith(currentServices, services =>
					f(Context_get(services, consoleTag)),
				),
			Data_Error = (function () {
				const plainArgsSymbol = Symbol.for("effect/Data/Error/plainArgs")
				return class extends YieldableError {
					constructor(args) {
						super(args?.message, args?.cause ? { cause: args.cause } : void 0)
						if (args) {
							Object.assign(this, args)
							Object.defineProperty(this, plainArgsSymbol, {
								value: args,
								enumerable: !1,
							})
						}
					}
					toJSON() {
						return { ...this[plainArgsSymbol], ...this }
					}
				}
			})(),
			Data_TaggedError = tag => {
				const O = {
					BaseEffectError: class extends Data_Error {
						_tag = tag
					},
				}
				O.BaseEffectError.prototype.name = tag
				return O.BaseEffectError
			},
			String_Equivalence = Equivalence_string,
			String_isEmpty = self => 0 === self.length,
			String_isNonEmpty = self => self.length > 0,
			String_split = dual(2, (self, separator) => {
				const out = self.split(separator)
				return isNonEmptyArray(out) ? out : [self]
			})
		Symbol.iterator
		const ScheduleTypeId = Symbol.for("effect/Schedule"),
			ScheduleDriverTypeId = Symbol.for("effect/ScheduleDriver"),
			defaultIterationMetadata = {
				start: 0,
				now: 0,
				input: void 0,
				output: void 0,
				elapsed: zero,
				elapsedSincePrevious: zero,
				recurrence: 0,
			},
			CurrentIterationMetadata = Context_Reference()(
				"effect/Schedule/CurrentIterationMetadata",
				{ defaultValue: () => defaultIterationMetadata },
			),
			scheduleVariance = { _Out: _ => _, _In: _ => _, _R: _ => _ },
			scheduleDriverVariance = { _Out: _ => _, _In: _ => _, _R: _ => _ }
		class ScheduleImpl {
			initial
			step;
			[ScheduleTypeId] = scheduleVariance
			constructor(initial, step) {
				this.initial = initial
				this.step = step
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const updateInfo = (iterationMetaRef, now, input, output) =>
			ref_update(iterationMetaRef, prev =>
				0 === prev.recurrence
					? {
							now,
							input,
							output,
							recurrence: prev.recurrence + 1,
							elapsed: zero,
							elapsedSincePrevious: zero,
							start: now,
						}
					: {
							now,
							input,
							output,
							recurrence: prev.recurrence + 1,
							elapsed: Duration_millis(now - prev.start),
							elapsedSincePrevious: Duration_millis(now - prev.now),
							start: prev.start,
						},
			)
		class ScheduleDriverImpl {
			schedule
			ref;
			[ScheduleDriverTypeId] = scheduleDriverVariance
			constructor(schedule, ref) {
				this.schedule = schedule
				this.ref = ref
			}
			get state() {
				return core_map(ref_get(this.ref), tuple => tuple[1])
			}
			get last() {
				return core_flatMap(ref_get(this.ref), ([element, _]) => {
					switch (element._tag) {
						case "None":
							return failSync(() => new NoSuchElementException())
						case "Some":
							return succeed(element.value)
					}
				})
			}
			iterationMeta = ref_unsafeMake(defaultIterationMetadata)
			get reset() {
				return ref_set(this.ref, [Option_none(), this.schedule.initial]).pipe(
					core_zipLeft(ref_set(this.iterationMeta, defaultIterationMetadata)),
				)
			}
			next(input) {
				return pipe(
					core_map(ref_get(this.ref), tuple => tuple[1]),
					core_flatMap(state =>
						pipe(
							Clock_currentTimeMillis,
							core_flatMap(now =>
								pipe(
									suspend(() => this.schedule.step(now, input, state)),
									core_flatMap(([state, out, decision]) => {
										const setState = ref_set(this.ref, [
											Option_some(out),
											state,
										])
										if (ScheduleDecision_isDone(decision))
											return setState.pipe(
												core_zipRight(core_fail(Option_none())),
											)
										const millis =
											ScheduleIntervals_start(decision.intervals) - now
										if (millis <= 0)
											return setState.pipe(
												core_zipRight(
													updateInfo(this.iterationMeta, now, input, out),
												),
												core_as(out),
											)
										const duration = Duration_millis(millis)
										return pipe(
											setState,
											core_zipRight(
												updateInfo(this.iterationMeta, now, input, out),
											),
											core_zipRight(core_effect_sleep(duration)),
											core_as(out),
										)
									}),
								),
							),
						),
					),
				)
			}
		}
		const makeWithState = (initial, step) => new ScheduleImpl(initial, step),
			check = dual(2, (self, test) =>
				checkEffect(self, (input, out) => sync(() => test(input, out))),
			),
			checkEffect = dual(2, (self, test) =>
				makeWithState(self.initial, (now, input, state) =>
					core_flatMap(
						self.step(now, input, state),
						([state, out, decision]) =>
							ScheduleDecision_isDone(decision)
								? succeed([state, out, ScheduleDecision_done])
								: core_map(test(input, out), cont =>
										cont
											? [state, out, decision]
											: [state, out, ScheduleDecision_done],
									),
					),
				),
			),
			driver = self =>
				pipe(
					ref_make([Option_none(), self.initial]),
					core_map(ref => new ScheduleDriverImpl(self, ref)),
				),
			schedule_intersect = dual(2, (self, that) =>
				intersectWith(self, that, ScheduleIntervals_intersect),
			),
			intersectWith = dual(3, (self, that, f) =>
				makeWithState([self.initial, that.initial], (now, input, state) =>
					pipe(
						core_zipWith(
							self.step(now, input, state[0]),
							that.step(now, input, state[1]),
							(a, b) => [a, b],
						),
						core_flatMap(
							([[lState, out, lDecision], [rState, out2, rDecision]]) =>
								ScheduleDecision_isContinue(lDecision) &&
								ScheduleDecision_isContinue(rDecision)
									? intersectWithLoop(
											self,
											that,
											input,
											lState,
											out,
											lDecision.intervals,
											rState,
											out2,
											rDecision.intervals,
											f,
										)
									: succeed([
											[lState, rState],
											[out, out2],
											ScheduleDecision_done,
										]),
						),
					),
				),
			),
			intersectWithLoop = (
				self,
				that,
				input,
				lState,
				out,
				lInterval,
				rState,
				out2,
				rInterval,
				f,
			) => {
				const combined = f(lInterval, rInterval)
				return (self => isNonEmpty(self.intervals))(combined)
					? succeed([
							[lState, rState],
							[out, out2],
							((intervals = combined), { _tag: "Continue", intervals }),
						])
					: pipe(lInterval, ScheduleIntervals_lessThan(rInterval))
						? core_flatMap(
								self.step(ScheduleIntervals_end(lInterval), input, lState),
								([lState, out, decision]) =>
									ScheduleDecision_isDone(decision)
										? succeed([
												[lState, rState],
												[out, out2],
												ScheduleDecision_done,
											])
										: intersectWithLoop(
												self,
												that,
												input,
												lState,
												out,
												decision.intervals,
												rState,
												out2,
												rInterval,
												f,
											),
							)
						: core_flatMap(
								that.step(ScheduleIntervals_end(rInterval), input, rState),
								([rState, out2, decision]) =>
									ScheduleDecision_isDone(decision)
										? succeed([
												[lState, rState],
												[out, out2],
												ScheduleDecision_done,
											])
										: intersectWithLoop(
												self,
												that,
												input,
												lState,
												out,
												lInterval,
												rState,
												out2,
												decision.intervals,
												f,
											),
							)
				var intervals
			},
			schedule_map = dual(2, (self, f) =>
				schedule_mapEffect(self, out => sync(() => f(out))),
			),
			schedule_mapEffect = dual(2, (self, f) =>
				makeWithState(self.initial, (now, input, state) =>
					core_flatMap(self.step(now, input, state), ([state, out, decision]) =>
						core_map(f(out), out2 => [state, out2, decision]),
					),
				),
			),
			schedule_unfold = (initial, f) =>
				makeWithState(initial, (now, _, state) =>
					sync(() => [
						f(state),
						state,
						ScheduleDecision_continueWith(ScheduleInterval_after(now)),
					]),
				),
			untilInputEffect = dual(2, (self, f) =>
				checkEffect(self, (input, _) =>
					(self => core_map(self, b => !b))(f(input)),
				),
			),
			whileInputEffect = dual(2, (self, f) =>
				checkEffect(self, (input, _) => f(input)),
			),
			whileOutput = dual(2, (self, f) => check(self, (_, out) => f(out))),
			ScheduleDefectTypeId = Symbol.for("effect/Schedule/ScheduleDefect")
		class ScheduleDefect {
			error;
			[ScheduleDefectTypeId]
			constructor(error) {
				this.error = error
				this[ScheduleDefectTypeId] = ScheduleDefectTypeId
			}
		}
		const scheduleDefectWrap = self =>
				catchAll(self, e => core_die(new ScheduleDefect(e))),
			repeat_Effect = dual(2, (self, schedule) =>
				repeatOrElse_Effect(self, schedule, (e, _) => core_fail(e)),
			),
			repeat_combined = dual(2, (self, options) => {
				if ((u => hasProperty(u, ScheduleTypeId))(options))
					return repeat_Effect(self, options)
				const base =
						options.schedule ??
						(self =>
							makeWithState(self.initial, (now, input, state) =>
								pipe(
									self.step(now, input, state),
									core_map(([state, _, decision]) => [state, input, decision]),
								),
							))(schedule_forever),
					withWhile = options.while
						? whileInputEffect(base, a => {
								const applied = options.while(a)
								return "boolean" == typeof applied
									? succeed(applied)
									: scheduleDefectWrap(applied)
							})
						: base,
					withUntil = options.until
						? untilInputEffect(withWhile, a => {
								const applied = options.until(a)
								return "boolean" == typeof applied
									? succeed(applied)
									: scheduleDefectWrap(applied)
							})
						: withWhile,
					withTimes = options.times
						? schedule_intersect(
								withUntil,
								(n => whileOutput(schedule_forever, out => out < n))(
									options.times,
								),
							).pipe(schedule_map(intersectionPair => intersectionPair[0]))
						: withUntil
				return (
					(effect = repeat_Effect(self, withTimes)),
					catchAllCause(effect, cause =>
						failCause(
							(cause =>
								Option_match(
									find(cause, _ =>
										isDieType(_) &&
										(u => hasProperty(u, ScheduleDefectTypeId))(_.defect)
											? Option_some(_.defect)
											: Option_none(),
									),
									{ onNone: () => cause, onSome: error => fail(error.error) },
								))(cause),
						),
					)
				)
				var effect
			}),
			repeatOrElse_Effect = dual(3, (self, schedule, orElse) =>
				core_flatMap(driver(schedule), driver =>
					matchEffect(self, {
						onFailure: error => orElse(error, Option_none()),
						onSuccess: value =>
							repeatOrElseEffectLoop(
								core_effect_provideServiceEffect(
									self,
									CurrentIterationMetadata,
									ref_get(driver.iterationMeta),
								),
								driver,
								(error, option) =>
									core_effect_provideServiceEffect(
										orElse(error, option),
										CurrentIterationMetadata,
										ref_get(driver.iterationMeta),
									),
								value,
							),
					}),
				),
			),
			repeatOrElseEffectLoop = (self, driver, orElse, value) =>
				matchEffect(driver.next(value), {
					onFailure: () => orDie(driver.last),
					onSuccess: b =>
						matchEffect(self, {
							onFailure: error => orElse(error, Option_some(b)),
							onSuccess: value =>
								repeatOrElseEffectLoop(self, driver, orElse, value),
						}),
				}),
			schedule_Effect = dual(2, (self, schedule) =>
				scheduleFrom_Effect(self, void 0, schedule),
			),
			scheduleFrom_Effect = dual(3, (self, initial, schedule) =>
				core_flatMap(driver(schedule), driver =>
					scheduleFrom_EffectLoop(
						core_effect_provideServiceEffect(
							self,
							CurrentIterationMetadata,
							ref_get(driver.iterationMeta),
						),
						initial,
						driver,
					),
				),
			),
			scheduleFrom_EffectLoop = (self, initial, driver) =>
				matchEffect(driver.next(initial), {
					onFailure: () => orDie(driver.last),
					onSuccess: () =>
						core_flatMap(self, a => scheduleFrom_EffectLoop(self, a, driver)),
				}),
			schedule_forever = schedule_unfold(0, n => n + 1),
			Deferred_make = deferredMake,
			Deferred_await = deferredAwait,
			Deferred_failCause = deferredFailCause,
			Deferred_isDone = self =>
				sync(() => "Done" === MutableRef_get(self.state)._tag),
			Deferred_succeed = deferredSucceed,
			MutableList_TypeId = Symbol.for("effect/MutableList"),
			MutableListProto = {
				[MutableList_TypeId]: MutableList_TypeId,
				[Symbol.iterator]() {
					let done = !1,
						head = this.head
					return {
						next() {
							if (done) return this.return()
							if (null == head) {
								done = !0
								return this.return()
							}
							const value = head.value
							head = head.next
							return { done, value }
						},
						return(value) {
							done || (done = !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)
				},
			},
			MutableList_isEmpty = self => 0 === MutableList_length(self),
			MutableList_length = self => self._length,
			MutableList_append = dual(2, (self, value) => {
				const node = (value => ({
					value,
					removed: !1,
					prev: void 0,
					next: void 0,
				}))(value)
				void 0 === self.head && (self.head = node)
				if (void 0 === self.tail) self.tail = node
				else {
					self.tail.next = node
					node.prev = self.tail
					self.tail = node
				}
				self._length += 1
				return self
			}),
			MutableQueue_TypeId = Symbol.for("effect/MutableQueue"),
			EmptyMutableQueue = Symbol.for("effect/mutable/MutableQueue/Empty"),
			MutableQueueProto = {
				[MutableQueue_TypeId]: MutableQueue_TypeId,
				[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)
				},
			},
			MutableQueue_make = capacity => {
				const queue = Object.create(MutableQueueProto)
				queue.queue = (() => {
					const list = Object.create(MutableListProto)
					list.head = void 0
					list.tail = void 0
					list._length = 0
					return list
				})()
				queue.capacity = capacity
				return queue
			},
			bounded = capacity => MutableQueue_make(capacity),
			unbounded = () => MutableQueue_make(void 0),
			MutableQueue_length = self => MutableList_length(self.queue),
			MutableQueue_isEmpty = self => MutableList_isEmpty(self.queue),
			offer = dual(2, (self, value) => {
				const queueLength = MutableList_length(self.queue)
				if (void 0 !== self.capacity && queueLength === self.capacity) return !1
				MutableList_append(value)(self.queue)
				return !0
			}),
			offerAll = dual(2, (self, values) => {
				const iterator = values[Symbol.iterator]()
				let next,
					remainder = esm_Chunk_empty(),
					offering = !0
				for (; offering && (next = iterator.next()) && !next.done;)
					offering = offer(next.value)(self)
				for (; null != next && !next.done;) {
					remainder = Chunk_prepend(next.value)(remainder)
					next = iterator.next()
				}
				return Chunk_reverse(remainder)
			}),
			MutableQueue_poll = dual(2, (self, def) =>
				MutableList_isEmpty(self.queue)
					? def
					: (self => {
							const head = self.head
							if (void 0 !== head) {
								;((self, node) => {
									if (!node.removed) {
										node.removed = !0
										if (void 0 !== node.prev && void 0 !== node.next) {
											node.prev.next = node.next
											node.next.prev = node.prev
										} else if (void 0 !== node.prev) {
											self.tail = node.prev
											node.prev.next = void 0
										} else if (void 0 !== node.next) {
											self.head = node.next
											node.next.prev = void 0
										} else {
											self.tail = void 0
											self.head = void 0
										}
										self._length > 0 && (self._length -= 1)
									}
								})(self, head)
								return head.value
							}
						})(self.queue),
			),
			pollUpTo = dual(2, (self, n) => {
				let result = esm_Chunk_empty(),
					count = 0
				for (; count < n;) {
					const element = MutableQueue_poll(EmptyMutableQueue)(self)
					if (element === EmptyMutableQueue) break
					result = Chunk_prepend(element)(result)
					count += 1
				}
				return Chunk_reverse(result)
			}),
			Effect_isEffect = isEffect,
			Effect_all = fiberRuntime_all,
			Effect_allSuccesses = (elements, options) =>
				core_map(
					fiberRuntime_all(
						Array_fromIterable(elements).map(core_exit),
						options,
					),
					Array_filterMap(exit =>
						exitIsSuccess(exit)
							? Option_some(exit.effect_instruction_i0)
							: Option_none(),
					),
				),
			Effect_forEach = fiberRuntime_forEach,
			Effect_withFiberRuntime = withFiberRuntime,
			Effect_fail = core_fail,
			Effect_failCause = failCause,
			Effect_dieMessage = dieMessage,
			Effect_gen = core_gen,
			Effect_promise = evaluate =>
				evaluate.length >= 1
					? async_((resolve, signal) => {
							try {
								evaluate(signal).then(
									a => resolve(succeed(a)),
									e => resolve(core_die(e)),
								)
							} catch (e) {
								resolve(core_die(e))
							}
						})
					: async_(resolve => {
							try {
								evaluate().then(
									a => resolve(succeed(a)),
									e => resolve(core_die(e)),
								)
							} catch (e) {
								resolve(core_die(e))
							}
						}),
			Effect_succeed = succeed,
			Effect_suspend = suspend,
			Effect_sync = sync,
			_void = core_void_,
			Effect_catchAll = catchAll,
			Effect_catchAllCause = catchAllCause,
			Effect_catchSomeCause = catchSomeCause,
			Effect_ignore = self =>
				core_effect_match(self, { onFailure: constVoid, onSuccess: constVoid }),
			Effect_interrupt = core_interrupt,
			Effect_interruptible = core_interruptible,
			Effect_uninterruptible = uninterruptible,
			Effect_uninterruptibleMask = uninterruptibleMask,
			Effect_as = core_as,
			Effect_asVoid = core_asVoid,
			Effect_map = core_map,
			Effect_mapError = mapError,
			Effect_acquireRelease = fiberRuntime_acquireRelease,
			Effect_acquireUseRelease = acquireUseRelease,
			Effect_ensuring = fiberRuntime_ensuring,
			Effect_scope = fiberRuntime_scope,
			Effect_scopedWith = scopedWith,
			Effect_fiberIdWith = fiberIdWith,
			Effect_forkDaemon = fiberRuntime_forkDaemon,
			Effect_forkIn = circular_forkIn,
			Effect_withConcurrency = withConcurrency,
			Effect_sleep = core_effect_sleep,
			Effect_provide = effect_provide,
			Effect_option = self =>
				matchEffect(self, {
					onFailure: () => succeed(Option_none()),
					onSuccess: a => succeed(Option_some(a)),
				}),
			Effect_either = core_either,
			Effect_exit = core_exit,
			Effect_intoDeferred = intoDeferred,
			Effect_filterOrElse = filterOrElse,
			Effect_filterOrFail = core_effect_filterOrFail,
			Effect_when = core_effect_when,
			Effect_flatMap = core_flatMap,
			Effect_flatten = core_flatten,
			Effect_race = fiberRuntime_race,
			Effect_raceFirst = circular_raceFirst,
			Effect_raceWith = raceWith,
			Effect_tap = core_tap,
			Effect_tapErrorCause = core_effect_tapErrorCause,
			Effect_forever = self => {
				const loop = core_flatMap(
					core_flatMap(self, () => yieldNow()),
					() => loop,
				)
				return loop
			},
			Effect_repeat = repeat_combined,
			schedule = schedule_Effect,
			Effect_locally = fiberRefLocally,
			Effect_isSuccess = self =>
				core_effect_match(self, {
					onFailure: constFalse,
					onSuccess: constTrue,
				}),
			Effect_match = core_effect_match,
			Effect_matchCause = matchCause,
			Effect_matchCauseEffect = matchCauseEffect,
			Effect_matchEffect = matchEffect,
			Effect_log = log,
			Effect_logDebug = logDebug,
			Effect_logInfo = logInfo,
			Effect_logWarning = logWarning,
			Effect_logError = logError,
			Effect_annotateLogs = annotateLogs,
			Effect_orElse = core_orElse,
			Effect_orElseSucceed = core_effect_orElseSucceed,
			Effect_runtime = () =>
				withFiberRuntime((state, status) =>
					succeed(
						new RuntimeImpl(
							state.getFiberRef(currentContext),
							status.runtimeFlags,
							state.getFiberRefs(),
						),
					),
				),
			Effect_makeSemaphore = permits =>
				sync(() => unsafeMakeSemaphore(permits)),
			Effect_runFork = unsafeForkEffect,
			Effect_runPromise = unsafeRunPromiseEffect,
			Effect_runSync = unsafeRunSyncEffect,
			Effect_zip = zipOptions,
			Effect_zipLeft = zipLeftOptions,
			Effect_zipRight = zipRightOptions,
			Effect_zipWith = zipWithOptions,
			Effect_fromNullable = value =>
				null == value ? core_fail(new NoSuchElementException()) : succeed(value)
		var EMPTY_OBJ = {},
			EMPTY_ARR = [],
			hyperapp_id = a => a,
			hyperapp_map = EMPTY_ARR.map,
			hyperapp_isArray = Array.isArray,
			enqueue =
				"undefined" != typeof requestAnimationFrame
					? requestAnimationFrame
					: setTimeout,
			createClass = obj => {
				var out = ""
				if ("string" == typeof obj) return obj
				if (hyperapp_isArray(obj))
					for (var tmp, k = 0; k < obj.length; k++)
						(tmp = createClass(obj[k])) && (out += (out && " ") + tmp)
				else for (var k in obj) obj[k] && (out += (out && " ") + k)
				return out
			},
			shouldRestart = (a, b) => {
				for (var k in { ...a, ...b })
					if ("function" == typeof (hyperapp_isArray(a[k]) ? a[k][0] : a[k]))
						b[k] = a[k]
					else if (a[k] !== b[k]) return !0
			},
			getKey = vdom => (null == vdom ? vdom : vdom.key),
			patchProperty = (node, key, oldValue, newValue, listener, isSvg) => {
				if ("style" === key)
					for (var k in { ...oldValue, ...newValue }) {
						oldValue =
							null == newValue || null == newValue[k] ? "" : newValue[k]
						"-" === k[0]
							? node[key].setProperty(k, oldValue)
							: (node[key][k] = oldValue)
					}
				else
					"o" === key[0] && "n" === key[1]
						? ((node.events || (node.events = {}))[(key = key.slice(2))] =
								newValue)
							? oldValue || node.addEventListener(key, listener)
							: node.removeEventListener(key, listener)
						: !isSvg && "list" !== key && "form" !== key && key in node
							? (node[key] = newValue ?? "")
							: null == newValue || !1 === newValue
								? node.removeAttribute(key)
								: node.setAttribute(key, newValue)
			},
			createNode = (vdom, listener, isSvg) => {
				var props = vdom.props,
					node =
						3 === vdom.type
							? document.createTextNode(vdom.tag)
							: (isSvg = isSvg || "svg" === vdom.tag)
								? document.createElementNS(
										"http://www.w3.org/2000/svg",
										vdom.tag,
										props.is && props,
									)
								: document.createElement(vdom.tag, props.is && props)
				for (var k in props)
					patchProperty(node, k, null, props[k], listener, isSvg)
				for (var i = 0; i < vdom.children.length; i++)
					node.appendChild(
						createNode(
							(vdom.children[i] = maybeVNode(vdom.children[i])),
							listener,
							isSvg,
						),
					)
				return (vdom.node = node)
			},
			hyperapp_patch = (parent, node, oldVNode, newVNode, listener, isSvg) => {
				if (oldVNode === newVNode);
				else if (null != oldVNode && 3 === oldVNode.type && 3 === newVNode.type)
					oldVNode.tag !== newVNode.tag && (node.nodeValue = newVNode.tag)
				else if (null == oldVNode || oldVNode.tag !== newVNode.tag) {
					node = parent.insertBefore(
						createNode((newVNode = maybeVNode(newVNode)), listener, isSvg),
						node,
					)
					null != oldVNode && parent.removeChild(oldVNode.node)
				} else {
					var tmpVKid,
						oldVKid,
						oldKey,
						newKey,
						oldProps = oldVNode.props,
						newProps = newVNode.props,
						oldVKids = oldVNode.children,
						newVKids = newVNode.children,
						oldHead = 0,
						newHead = 0,
						oldTail = oldVKids.length - 1,
						newTail = newVKids.length - 1
					isSvg = isSvg || "svg" === newVNode.tag
					for (var i in { ...oldProps, ...newProps })
						("value" === i || "selected" === i || "checked" === i
							? node[i]
							: oldProps[i]) !== newProps[i] &&
							patchProperty(node, i, oldProps[i], newProps[i], listener, isSvg)
					for (
						;
						newHead <= newTail &&
						oldHead <= oldTail &&
						null != (oldKey = getKey(oldVKids[oldHead])) &&
						oldKey === getKey(newVKids[newHead]);
					)
						hyperapp_patch(
							node,
							oldVKids[oldHead].node,
							oldVKids[oldHead],
							(newVKids[newHead] = maybeVNode(
								newVKids[newHead++],
								oldVKids[oldHead++],
							)),
							listener,
							isSvg,
						)
					for (
						;
						newHead <= newTail &&
						oldHead <= oldTail &&
						null != (oldKey = getKey(oldVKids[oldTail])) &&
						oldKey === getKey(newVKids[newTail]);
					)
						hyperapp_patch(
							node,
							oldVKids[oldTail].node,
							oldVKids[oldTail],
							(newVKids[newTail] = maybeVNode(
								newVKids[newTail--],
								oldVKids[oldTail--],
							)),
							listener,
							isSvg,
						)
					if (oldHead > oldTail)
						for (; newHead <= newTail;)
							node.insertBefore(
								createNode(
									(newVKids[newHead] = maybeVNode(newVKids[newHead++])),
									listener,
									isSvg,
								),
								(oldVKid = oldVKids[oldHead]) && oldVKid.node,
							)
					else if (newHead > newTail)
						for (; oldHead <= oldTail;)
							node.removeChild(oldVKids[oldHead++].node)
					else {
						var keyed = {},
							newKeyed = {}
						for (i = oldHead; i <= oldTail; i++)
							null != (oldKey = oldVKids[i].key) &&
								(keyed[oldKey] = oldVKids[i])
						for (; newHead <= newTail;) {
							oldKey = getKey((oldVKid = oldVKids[oldHead]))
							newKey = getKey(
								(newVKids[newHead] = maybeVNode(newVKids[newHead], oldVKid)),
							)
							if (
								newKeyed[oldKey] ||
								(null != newKey && newKey === getKey(oldVKids[oldHead + 1]))
							) {
								null == oldKey && node.removeChild(oldVKid.node)
								oldHead++
							} else if (null == newKey || 1 === oldVNode.type) {
								if (null == oldKey) {
									hyperapp_patch(
										node,
										oldVKid && oldVKid.node,
										oldVKid,
										newVKids[newHead],
										listener,
										isSvg,
									)
									newHead++
								}
								oldHead++
							} else {
								if (oldKey === newKey) {
									hyperapp_patch(
										node,
										oldVKid.node,
										oldVKid,
										newVKids[newHead],
										listener,
										isSvg,
									)
									newKeyed[newKey] = !0
									oldHead++
								} else if (null != (tmpVKid = keyed[newKey])) {
									hyperapp_patch(
										node,
										node.insertBefore(tmpVKid.node, oldVKid && oldVKid.node),
										tmpVKid,
										newVKids[newHead],
										listener,
										isSvg,
									)
									newKeyed[newKey] = !0
								} else
									hyperapp_patch(
										node,
										oldVKid && oldVKid.node,
										null,
										newVKids[newHead],
										listener,
										isSvg,
									)
								newHead++
							}
						}
						for (; oldHead <= oldTail;)
							null == getKey((oldVKid = oldVKids[oldHead++])) &&
								node.removeChild(oldVKid.node)
						for (var i in keyed)
							null == newKeyed[i] && node.removeChild(keyed[i].node)
					}
				}
				return (newVNode.node = node)
			},
			maybeVNode = (newVNode, oldVNode) =>
				!0 !== newVNode && !1 !== newVNode && newVNode
					? "function" == typeof newVNode.tag
						? ((!oldVNode ||
								null == oldVNode.memo ||
								((a, b) => {
									for (var k in a) if (a[k] !== b[k]) return !0
									for (var k in b) if (a[k] !== b[k]) return !0
								})(oldVNode.memo, newVNode.memo)) &&
								((oldVNode = newVNode.tag(newVNode.memo)).memo = newVNode.memo),
							oldVNode)
						: newVNode
					: hyperapp_text(""),
			recycleNode = node =>
				3 === node.nodeType
					? hyperapp_text(node.nodeValue, node)
					: createVNode(
							node.nodeName.toLowerCase(),
							EMPTY_OBJ,
							hyperapp_map.call(node.childNodes, recycleNode),
							1,
							node,
						),
			createVNode = (tag, { key, ...props }, children, type, node) => ({
				tag,
				props,
				key,
				children,
				type,
				node,
			}),
			hyperapp_text = (value, node) =>
				createVNode(value, EMPTY_OBJ, EMPTY_ARR, 3, node),
			h = (tag, { class: c, ...props }, children = EMPTY_ARR) =>
				createVNode(
					tag,
					{ ...props, ...(c ? { class: createClass(c) } : EMPTY_OBJ) },
					hyperapp_isArray(children) ? children : [children],
				),
			app = ({
				node,
				view,
				subscriptions,
				dispatch = hyperapp_id,
				init = EMPTY_OBJ,
			}) => {
				var state,
					busy,
					vdom = node && recycleNode(node),
					subs = [],
					update = newState => {
						if (state !== newState) {
							null == (state = newState) &&
								(dispatch = subscriptions = render = hyperapp_id)
							subscriptions &&
								(subs = ((oldSubs, newSubs = EMPTY_ARR, dispatch) => {
									for (
										var oldSub, newSub, subs = [], i = 0;
										i < oldSubs.length || i < newSubs.length;
										i++
									) {
										oldSub = oldSubs[i]
										newSub = newSubs[i]
										subs.push(
											newSub && !0 !== newSub
												? !oldSub ||
													newSub[0] !== oldSub[0] ||
													shouldRestart(newSub[1], oldSub[1])
													? [
															newSub[0],
															newSub[1],
															(oldSub && oldSub[2](),
															newSub[0](dispatch, newSub[1])),
														]
													: oldSub
												: oldSub && oldSub[2](),
										)
									}
									return subs
								})(subs, subscriptions(state), dispatch))
							view && !busy && enqueue(render, (busy = !0))
						}
					},
					render = () =>
						(node = hyperapp_patch(
							node.parentNode,
							node,
							vdom,
							(vdom = view(state)),
							listener,
							(busy = !1),
						)),
					listener = function (event) {
						dispatch(this.events[event.type], event)
					}
				return (
					(dispatch = dispatch((action, props) =>
						"function" == typeof action
							? dispatch(action(state, props))
							: hyperapp_isArray(action)
								? "function" == typeof action[0]
									? dispatch(action[0], action[1])
									: action
											.slice(1)
											.map(
												fx => fx && !0 !== fx && (fx[0] || fx)(dispatch, fx[1]),
												update(action[0]),
											)
								: update(action),
					))(init),
					dispatch
				)
			}
		const wrapApp = (comp, init) =>
			pipe(
				Effect_sync(() => document.createElement(comp.tag)),
				Effect_flatMap(node =>
					Effect_sync(() => ({
						node,
						dispatch: app({ init, view: comp.view, node }),
					})),
				),
			)
		__webpack_require__.dn(wrapApp)
		;(Promise.resolve(!1), Promise.resolve(!0))
		var PROMISE_RESOLVED_VOID = Promise.resolve()
		function util_sleep(time, resolveWith) {
			time || (time = 0)
			return new Promise(function (res) {
				return setTimeout(function () {
					return res(resolveWith)
				}, time)
			})
		}
		function randomToken() {
			return Math.random().toString(36).substring(2)
		}
		var lastMs = 0
		function microSeconds() {
			var ret = 1e3 * Date.now()
			ret <= lastMs && (ret = lastMs + 1)
			lastMs = ret
			return ret
		}
		var NativeMethod = {
			create: function (channelName) {
				var state = {
					time: microSeconds(),
					messagesCallback: null,
					bc: new BroadcastChannel(channelName),
					subFns: [],
				}
				state.bc.onmessage = function (msgEvent) {
					state.messagesCallback && state.messagesCallback(msgEvent.data)
				}
				return state
			},
			close: function (channelState) {
				channelState.bc.close()
				channelState.subFns = []
			},
			onMessage: function (channelState, fn) {
				channelState.messagesCallback = fn
			},
			postMessage: function (channelState, messageJson) {
				try {
					channelState.bc.postMessage(messageJson, !1)
					return PROMISE_RESOLVED_VOID
				} catch (err) {
					return Promise.reject(err)
				}
			},
			canBeUsed: function () {
				if (
					"undefined" != typeof globalThis &&
					globalThis.Deno &&
					globalThis.Deno.args
				)
					return !0
				if (
					("undefined" == typeof window && "undefined" == typeof self) ||
					"function" != typeof BroadcastChannel
				)
					return !1
				if (BroadcastChannel._pubkey)
					throw new Error(
						"BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill",
					)
				return !0
			},
			type: "native",
			averageResponseTime: function () {
				return 150
			},
			microSeconds,
		}
		class ObliviousSet {
			ttl
			map = new Map()
			_to = !1
			constructor(ttl) {
				this.ttl = ttl
			}
			has(value) {
				const valueTime = this.map.get(value)
				if (void 0 === valueTime) return !1
				if (valueTime < src_now() - this.ttl) {
					this.map.delete(value)
					return !1
				}
				return !0
			}
			add(value) {
				this.map.delete(value)
				this.map.set(value, src_now())
				if (!this._to) {
					this._to = !0
					setTimeout(() => {
						this._to = !1
						!(function (obliviousSet) {
							const olderThen = src_now() - obliviousSet.ttl,
								iterator = obliviousSet.map[Symbol.iterator]()
							for (;;) {
								const next = iterator.next().value
								if (!next) break
								const value = next[0]
								if (!(next[1] < olderThen)) break
								obliviousSet.map.delete(value)
							}
						})(this)
					}, 0)
				}
			}
			clear() {
				this.map.clear()
			}
		}
		function src_now() {
			return Date.now()
		}
		function fillOptionsWithDefaults() {
			var originalOptions =
					arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
				options = JSON.parse(JSON.stringify(originalOptions))
			void 0 === options.webWorkerSupport && (options.webWorkerSupport = !0)
			options.idb || (options.idb = {})
			options.idb.ttl || (options.idb.ttl = 45e3)
			options.idb.fallbackInterval || (options.idb.fallbackInterval = 150)
			originalOptions.idb &&
				"function" == typeof originalOptions.idb.onclose &&
				(options.idb.onclose = originalOptions.idb.onclose)
			options.localstorage || (options.localstorage = {})
			options.localstorage.removeTimeout ||
				(options.localstorage.removeTimeout = 6e4)
			originalOptions.methods && (options.methods = originalOptions.methods)
			options.node || (options.node = {})
			options.node.ttl || (options.node.ttl = 12e4)
			options.node.maxParallelWrites || (options.node.maxParallelWrites = 2048)
			void 0 === options.node.useFastPath && (options.node.useFastPath = !0)
			return options
		}
		var TRANSACTION_SETTINGS = { durability: "relaxed" }
		function getIdb() {
			if ("undefined" != typeof indexedDB) return indexedDB
			if ("undefined" != typeof window) {
				if (void 0 !== window.mozIndexedDB) return window.mozIndexedDB
				if (void 0 !== window.webkitIndexedDB) return window.webkitIndexedDB
				if (void 0 !== window.msIndexedDB) return window.msIndexedDB
			}
			return !1
		}
		function commitIndexedDBTransaction(tx) {
			tx.commit && tx.commit()
		}
		function _readLoop(state) {
			state.closed ||
				readNewMessages(state)
					.then(function () {
						return util_sleep(state.options.idb.fallbackInterval)
					})
					.then(function () {
						return _readLoop(state)
					})
		}
		function readNewMessages(state) {
			return state.closed
				? PROMISE_RESOLVED_VOID
				: state.messagesCallback
					? (function (db, lastCursorId) {
							var tx = db.transaction(
									"messages",
									"readonly",
									TRANSACTION_SETTINGS,
								),
								objectStore = tx.objectStore("messages"),
								ret = [],
								keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
							if (objectStore.getAll) {
								var getAllRequest = objectStore.getAll(keyRangeValue)
								return new Promise(function (res, rej) {
									getAllRequest.onerror = function (err) {
										return rej(err)
									}
									getAllRequest.onsuccess = function (e) {
										res(e.target.result)
									}
								})
							}
							return new Promise(function (res, rej) {
								var openCursorRequest = (function () {
									try {
										keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
										return objectStore.openCursor(keyRangeValue)
									} catch (e) {
										return objectStore.openCursor()
									}
								})()
								openCursorRequest.onerror = function (err) {
									return rej(err)
								}
								openCursorRequest.onsuccess = function (ev) {
									var cursor = ev.target.result
									if (cursor)
										if (cursor.value.id < lastCursorId + 1)
											cursor.continue(lastCursorId + 1)
										else {
											ret.push(cursor.value)
											cursor.continue()
										}
									else {
										commitIndexedDBTransaction(tx)
										res(ret)
									}
								}
							})
						})(state.db, state.lastCursorId).then(function (newerMessages) {
							var useMessages = newerMessages
								.filter(function (msgObj) {
									return !!msgObj
								})
								.map(function (msgObj) {
									msgObj.id > state.lastCursorId &&
										(state.lastCursorId = msgObj.id)
									return msgObj
								})
								.filter(function (msgObj) {
									return (function (msgObj, state) {
										return !(
											msgObj.uuid === state.uuid ||
											state.eMIs.has(msgObj.id) ||
											msgObj.data.time < state.messagesCallbackTime
										)
									})(msgObj, state)
								})
								.sort(function (msgObjA, msgObjB) {
									return msgObjA.time - msgObjB.time
								})
							useMessages.forEach(function (msgObj) {
								if (state.messagesCallback) {
									state.eMIs.add(msgObj.id)
									state.messagesCallback(msgObj.data)
								}
							})
							return PROMISE_RESOLVED_VOID
						})
					: PROMISE_RESOLVED_VOID
		}
		var IndexedDBMethod = {
			create: function (channelName, options) {
				options = fillOptionsWithDefaults(options)
				return (function (channelName) {
					var dbName = "pubkey.broadcast-channel-0-" + channelName,
						openRequest = getIdb().open(dbName)
					openRequest.onupgradeneeded = function (ev) {
						ev.target.result.createObjectStore("messages", {
							keyPath: "id",
							autoIncrement: !0,
						})
					}
					return new Promise(function (res, rej) {
						openRequest.onerror = function (ev) {
							return rej(ev)
						}
						openRequest.onsuccess = function () {
							res(openRequest.result)
						}
					})
				})(channelName).then(function (db) {
					var state = {
						closed: !1,
						lastCursorId: 0,
						channelName,
						options,
						uuid: randomToken(),
						eMIs: new ObliviousSet(2 * options.idb.ttl),
						writeBlockPromise: PROMISE_RESOLVED_VOID,
						messagesCallback: null,
						readQueuePromises: [],
						db,
					}
					db.onclose = function () {
						state.closed = !0
						options.idb.onclose && options.idb.onclose()
					}
					_readLoop(state)
					return state
				})
			},
			close: function (channelState) {
				channelState.closed = !0
				channelState.db.close()
			},
			onMessage: function (channelState, fn, time) {
				channelState.messagesCallbackTime = time
				channelState.messagesCallback = fn
				readNewMessages(channelState)
			},
			postMessage: function (channelState, messageJson) {
				channelState.writeBlockPromise = channelState.writeBlockPromise
					.then(function () {
						return (function (db, readerUuid, messageJson) {
							var writeObject = {
									uuid: readerUuid,
									time: Date.now(),
									data: messageJson,
								},
								tx = db.transaction(
									["messages"],
									"readwrite",
									TRANSACTION_SETTINGS,
								)
							return new Promise(function (res, rej) {
								tx.oncomplete = function () {
									return res()
								}
								tx.onerror = function (ev) {
									return rej(ev)
								}
								tx.objectStore("messages").add(writeObject)
								commitIndexedDBTransaction(tx)
							})
						})(channelState.db, channelState.uuid, messageJson)
					})
					.then(function () {
						0 === Math.floor(11 * Math.random() + 0) &&
							(function (channelState) {
								return ((db = channelState.db),
								(ttl = channelState.options.idb.ttl),
								(olderThen = Date.now() - ttl),
								(tx = db.transaction(
									"messages",
									"readonly",
									TRANSACTION_SETTINGS,
								)),
								(objectStore = tx.objectStore("messages")),
								(ret = []),
								new Promise(function (res) {
									objectStore.openCursor().onsuccess = function (ev) {
										var cursor = ev.target.result
										if (cursor) {
											var msgObk = cursor.value
											if (msgObk.time < olderThen) {
												ret.push(msgObk)
												cursor.continue()
											} else {
												commitIndexedDBTransaction(tx)
												res(ret)
											}
										} else res(ret)
									}
								})).then(function (tooOld) {
									return (function (channelState, ids) {
										if (channelState.closed) return Promise.resolve([])
										var objectStore = channelState.db
											.transaction(
												"messages",
												"readwrite",
												TRANSACTION_SETTINGS,
											)
											.objectStore("messages")
										return Promise.all(
											ids.map(function (id) {
												var deleteRequest = objectStore.delete(id)
												return new Promise(function (res) {
													deleteRequest.onsuccess = function () {
														return res()
													}
												})
											}),
										)
									})(
										channelState,
										tooOld.map(function (msg) {
											return msg.id
										}),
									)
								})
								var db, ttl, olderThen, tx, objectStore, ret
							})(channelState)
					})
				return channelState.writeBlockPromise
			},
			canBeUsed: function () {
				return !!getIdb()
			},
			type: "idb",
			averageResponseTime: function (options) {
				return 2 * options.idb.fallbackInterval
			},
			microSeconds,
		}
		function getLocalStorage() {
			var localStorage
			if ("undefined" == typeof window) return null
			try {
				localStorage = window.localStorage
				localStorage =
					window["ie8-eventlistener/storage"] || window.localStorage
			} catch (e) {}
			return localStorage
		}
		function storageKey(channelName) {
			return "pubkey.broadcastChannel-" + channelName
		}
		function localstorage_canBeUsed() {
			var ls = getLocalStorage()
			if (!ls) return !1
			try {
				var key = "__broadcastchannel_check"
				ls.setItem(key, "works")
				ls.removeItem(key)
			} catch (e) {
				return !1
			}
			return !0
		}
		var LocalstorageMethod = {
				create: function (channelName, options) {
					options = fillOptionsWithDefaults(options)
					if (!localstorage_canBeUsed())
						throw new Error("BroadcastChannel: localstorage cannot be used")
					var uuid = randomToken(),
						eMIs = new ObliviousSet(options.localstorage.removeTimeout),
						state = { channelName, uuid, eMIs }
					state.listener = (function (channelName) {
						var key = storageKey(channelName),
							listener = function (ev) {
								ev.key === key &&
									(function (msgObj) {
										if (
											state.messagesCallback &&
											msgObj.uuid !== uuid &&
											msgObj.token &&
											!eMIs.has(msgObj.token) &&
											!(
												msgObj.data.time &&
												msgObj.data.time < state.messagesCallbackTime
											)
										) {
											eMIs.add(msgObj.token)
											state.messagesCallback(msgObj.data)
										}
									})(JSON.parse(ev.newValue))
							}
						window.addEventListener("storage", listener)
						return listener
					})(channelName)
					return state
				},
				close: function (channelState) {
					;((listener = channelState.listener),
						window.removeEventListener("storage", listener))
					var listener
				},
				onMessage: function (channelState, fn, time) {
					channelState.messagesCallbackTime = time
					channelState.messagesCallback = fn
				},
				postMessage: function (channelState, messageJson) {
					return new Promise(function (res) {
						util_sleep().then(function () {
							var key = storageKey(channelState.channelName),
								writeObj = {
									token: randomToken(),
									time: Date.now(),
									data: messageJson,
									uuid: channelState.uuid,
								},
								value = JSON.stringify(writeObj)
							getLocalStorage().setItem(key, value)
							var ev = document.createEvent("Event")
							ev.initEvent("storage", !0, !0)
							ev.key = key
							ev.newValue = value
							window.dispatchEvent(ev)
							res()
						})
					})
				},
				canBeUsed: localstorage_canBeUsed,
				type: "localstorage",
				averageResponseTime: function () {
					var userAgent = navigator.userAgent.toLowerCase()
					return userAgent.includes("safari") && !userAgent.includes("chrome")
						? 240
						: 120
				},
				microSeconds,
			},
			simulate_microSeconds = microSeconds,
			SIMULATE_CHANNELS = new Set(),
			SimulateMethod = {
				create: function (channelName) {
					var state = {
						time: simulate_microSeconds(),
						name: channelName,
						messagesCallback: null,
					}
					SIMULATE_CHANNELS.add(state)
					return state
				},
				close: function (channelState) {
					SIMULATE_CHANNELS.delete(channelState)
				},
				onMessage: function (channelState, fn) {
					channelState.messagesCallback = fn
				},
				postMessage: function (channelState, messageJson) {
					return new Promise(function (res) {
						return setTimeout(function () {
							Array.from(SIMULATE_CHANNELS).forEach(function (channel) {
								channel.name === channelState.name &&
									channel !== channelState &&
									channel.messagesCallback &&
									channel.time < messageJson.time &&
									channel.messagesCallback(messageJson)
							})
							res()
						}, 5)
					})
				},
				canBeUsed: function () {
					return !0
				},
				type: "simulate",
				averageResponseTime: function () {
					return 5
				},
				microSeconds: simulate_microSeconds,
			},
			METHODS = [NativeMethod, IndexedDBMethod, LocalstorageMethod],
			OPEN_BROADCAST_CHANNELS = new Set(),
			lastId = 0,
			broadcast_channel_BroadcastChannel = function (name, options) {
				this.id = lastId++
				OPEN_BROADCAST_CHANNELS.add(this)
				this.name = name
				this.options = fillOptionsWithDefaults(options)
				this.method = (function (options) {
					var chooseMethods = []
						.concat(options.methods, METHODS)
						.filter(Boolean)
					if (options.type) {
						if ("simulate" === options.type) return SimulateMethod
						var ret = chooseMethods.find(function (m) {
							return m.type === options.type
						})
						if (ret) return ret
						throw new Error("method-type " + options.type + " not found")
					}
					options.webWorkerSupport ||
						(chooseMethods = chooseMethods.filter(function (m) {
							return "idb" !== m.type
						}))
					var useMethod = chooseMethods.find(function (method) {
						return method.canBeUsed()
					})
					if (useMethod) return useMethod
					throw new Error(
						"No usable method found in " +
							JSON.stringify(
								METHODS.map(function (m) {
									return m.type
								}),
							),
					)
				})(this.options)
				this._iL = !1
				this._onML = null
				this._addEL = { message: [], internal: [] }
				this._uMP = new Set()
				this._befC = []
				this._prepP = null
				!(function (channel) {
					var obj,
						maybePromise = channel.method.create(channel.name, channel.options)
					if ((obj = maybePromise) && "function" == typeof obj.then) {
						channel._prepP = maybePromise
						maybePromise.then(function (s) {
							channel._state = s
						})
					} else channel._state = maybePromise
				})(this)
			}
		broadcast_channel_BroadcastChannel._pubkey = !0
		broadcast_channel_BroadcastChannel.prototype = {
			postMessage: function (msg) {
				if (this.closed)
					throw new Error(
						"BroadcastChannel.postMessage(): Cannot post message after channel has closed " +
							JSON.stringify(msg),
					)
				return _post(this, "message", msg)
			},
			postInternal: function (msg) {
				return _post(this, "internal", msg)
			},
			set onmessage(fn) {
				var listenObj = { time: this.method.microSeconds(), fn }
				_removeListenerObject(this, "message", this._onML)
				if (fn && "function" == typeof fn) {
					this._onML = listenObj
					_addListenerObject(this, "message", listenObj)
				} else this._onML = null
			},
			addEventListener: function (type, fn) {
				_addListenerObject(this, type, { time: this.method.microSeconds(), fn })
			},
			removeEventListener: function (type, fn) {
				_removeListenerObject(
					this,
					type,
					this._addEL[type].find(function (obj) {
						return obj.fn === fn
					}),
				)
			},
			close: function () {
				var _this = this
				if (!this.closed) {
					OPEN_BROADCAST_CHANNELS.delete(this)
					this.closed = !0
					var awaitPrepare = this._prepP ? this._prepP : PROMISE_RESOLVED_VOID
					this._onML = null
					this._addEL.message = []
					return awaitPrepare
						.then(function () {
							return Promise.all(Array.from(_this._uMP))
						})
						.then(function () {
							return Promise.all(
								_this._befC.map(function (fn) {
									return fn()
								}),
							)
						})
						.then(function () {
							return _this.method.close(_this._state)
						})
				}
			},
			get type() {
				return this.method.type
			},
			get isClosed() {
				return this.closed
			},
		}
		function _post(broadcastChannel, type, msg) {
			var msgObj = {
				time: broadcastChannel.method.microSeconds(),
				type,
				data: msg,
			}
			return (
				broadcastChannel._prepP
					? broadcastChannel._prepP
					: PROMISE_RESOLVED_VOID
			).then(function () {
				var sendPromise = broadcastChannel.method.postMessage(
					broadcastChannel._state,
					msgObj,
				)
				broadcastChannel._uMP.add(sendPromise)
				sendPromise.catch().then(function () {
					return broadcastChannel._uMP.delete(sendPromise)
				})
				return sendPromise
			})
		}
		function _hasMessageListeners(channel) {
			return (
				channel._addEL.message.length > 0 || channel._addEL.internal.length > 0
			)
		}
		function _addListenerObject(channel, type, obj) {
			channel._addEL[type].push(obj)
			!(function (channel) {
				if (!channel._iL && _hasMessageListeners(channel)) {
					var listenerFn = function (msgObj) {
							channel._addEL[msgObj.type].forEach(function (listenerObject) {
								msgObj.time >= listenerObject.time &&
									listenerObject.fn(msgObj.data)
							})
						},
						time = channel.method.microSeconds()
					if (channel._prepP)
						channel._prepP.then(function () {
							channel._iL = !0
							channel.method.onMessage(channel._state, listenerFn, time)
						})
					else {
						channel._iL = !0
						channel.method.onMessage(channel._state, listenerFn, time)
					}
				}
			})(channel)
		}
		function _removeListenerObject(channel, type, obj) {
			channel._addEL[type] = channel._addEL[type].filter(function (o) {
				return o !== obj
			})
			!(function (channel) {
				if (channel._iL && !_hasMessageListeners(channel)) {
					channel._iL = !1
					var time = channel.method.microSeconds()
					channel.method.onMessage(channel._state, null, time)
				}
			})(channel)
		}
		const SynchronizedRefTypeId = SynchronizedTypeId,
			SynchronizedRef_make = makeSynchronized,
			SynchronizedRef_get = ref_get,
			SynchronizedRef_set = ref_set,
			SynchronizedRef_update = ref_update,
			Schedule_driver = driver,
			Schedule_fixed = intervalInput => {
				const interval = decode(intervalInput),
					intervalMillis = toMillis(interval)
				return makeWithState([Option_none(), 0], (now, _, [option, n]) =>
					sync(() => {
						switch (option._tag) {
							case "None":
								return [
									[Option_some([now, now + intervalMillis]), n + 1],
									n,
									ScheduleDecision_continueWith(
										ScheduleInterval_after(now + intervalMillis),
									),
								]
							case "Some": {
								const [startMillis, lastRun] = option.value,
									runningBehind = now > lastRun + intervalMillis,
									boundary = equals(interval, zero)
										? interval
										: Duration_millis(
												intervalMillis - ((now - startMillis) % intervalMillis),
											),
									sleepTime = equals(boundary, zero) ? interval : boundary,
									nextRun = runningBehind ? now : now + toMillis(sleepTime)
								return [
									[Option_some([startMillis, nextRun]), n + 1],
									n,
									ScheduleDecision_continueWith(
										ScheduleInterval_after(nextRun),
									),
								]
							}
						}
					}),
				)
			},
			EnqueueTypeId = Symbol.for("effect/QueueEnqueue"),
			DequeueTypeId = Symbol.for("effect/QueueDequeue"),
			QueueStrategyTypeId = Symbol.for("effect/QueueStrategy"),
			BackingQueueTypeId = Symbol.for("effect/BackingQueue"),
			queueStrategyVariance = { _A: _ => _ },
			backingQueueVariance = { _A: _ => _ },
			enqueueVariance = { _In: _ => _ },
			dequeueVariance = { _Out: _ => _ }
		class QueueImpl extends Effectable_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(), () => core_interrupt))
			}
			unsafeSize() {
				return MutableRef_get(this.shutdownFlag)
					? Option_none()
					: Option_some(
							this.queue.length() -
								MutableQueue_length(this.takers) +
								this.strategy.surplusSize(),
						)
			}
			get isEmpty() {
				return core_map(this.size, size => size <= 0)
			}
			get isFull() {
				return core_map(this.size, size => size >= this.capacity())
			}
			get shutdown() {
				return uninterruptible(
					withFiberRuntime(state => {
						pipe(this.shutdownFlag, MutableRef_set(!0))
						return pipe(
							forEachConcurrentDiscard(
								unsafePollAll(this.takers),
								d => deferredInterruptWith(d, state.id()),
								!1,
								!1,
							),
							core_zipRight(this.strategy.shutdown),
							whenEffect(deferredSucceed(this.shutdownHook, void 0)),
							core_asVoid,
						)
					}),
				)
			}
			get isShutdown() {
				return sync(() => MutableRef_get(this.shutdownFlag))
			}
			get awaitShutdown() {
				return deferredAwait(this.shutdownHook)
			}
			isActive() {
				return !MutableRef_get(this.shutdownFlag)
			}
			unsafeOffer(value) {
				if (MutableRef_get(this.shutdownFlag)) return !1
				let noRemaining
				if (0 === this.queue.length()) {
					const taker = pipe(this.takers, MutableQueue_poll(EmptyMutableQueue))
					if (taker !== EmptyMutableQueue) {
						unsafeCompleteDeferred(taker, value)
						noRemaining = !0
					} else noRemaining = !1
				} else noRemaining = !1
				if (noRemaining) return !0
				const succeeded = this.queue.offer(value)
				unsafeCompleteTakers(this.strategy, this.queue, this.takers)
				return succeeded
			}
			offer(value) {
				return suspend(() => {
					if (MutableRef_get(this.shutdownFlag)) return core_interrupt
					let noRemaining
					if (0 === this.queue.length()) {
						const taker = pipe(
							this.takers,
							MutableQueue_poll(EmptyMutableQueue),
						)
						if (taker !== EmptyMutableQueue) {
							unsafeCompleteDeferred(taker, value)
							noRemaining = !0
						} else noRemaining = !1
					} else noRemaining = !1
					if (noRemaining) return succeed(!0)
					const succeeded = this.queue.offer(value)
					unsafeCompleteTakers(this.strategy, this.queue, this.takers)
					return succeeded
						? succeed(!0)
						: this.strategy.handleSurplus(
								[value],
								this.queue,
								this.takers,
								this.shutdownFlag,
							)
				})
			}
			offerAll(iterable) {
				return suspend(() => {
					if (MutableRef_get(this.shutdownFlag)) return core_interrupt
					const values = Array_fromIterable(iterable),
						pTakers =
							0 === this.queue.length()
								? Array_fromIterable(unsafePollN(this.takers, values.length))
								: Array_empty,
						[forTakers, remaining] = pipe(values, splitAt(pTakers.length))
					for (let i = 0; i < pTakers.length; i++) {
						const taker = pTakers[i],
							item = forTakers[i]
						unsafeCompleteDeferred(taker, item)
					}
					if (0 === remaining.length) return succeed(!0)
					const surplus = this.queue.offerAll(remaining)
					unsafeCompleteTakers(this.strategy, this.queue, this.takers)
					return Chunk_isEmpty(surplus)
						? succeed(!0)
						: this.strategy.handleSurplus(
								surplus,
								this.queue,
								this.takers,
								this.shutdownFlag,
							)
				})
			}
			get take() {
				return withFiberRuntime(state => {
					if (MutableRef_get(this.shutdownFlag)) return core_interrupt
					const item = this.queue.poll(EmptyMutableQueue)
					if (item !== EmptyMutableQueue) {
						this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers)
						return succeed(item)
					}
					{
						const deferred = deferredUnsafeMake(state.id())
						return pipe(
							suspend(() => {
								pipe(this.takers, offer(deferred))
								unsafeCompleteTakers(this.strategy, this.queue, this.takers)
								return MutableRef_get(this.shutdownFlag)
									? core_interrupt
									: deferredAwait(deferred)
							}),
							onInterrupt(() =>
								sync(() => unsafeRemove(this.takers, deferred)),
							),
						)
					}
				})
			}
			get takeAll() {
				return suspend(() =>
					MutableRef_get(this.shutdownFlag)
						? core_interrupt
						: sync(() => {
								const values = this.queue.pollUpTo(Number.POSITIVE_INFINITY)
								this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers)
								return Chunk_fromIterable(values)
							}),
				)
			}
			takeUpTo(max) {
				return suspend(() =>
					MutableRef_get(this.shutdownFlag)
						? core_interrupt
						: sync(() => {
								const values = this.queue.pollUpTo(max)
								this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers)
								return Chunk_fromIterable(values)
							}),
				)
			}
			takeBetween(min, max) {
				return suspend(() =>
					takeRemainderLoop(this, min, max, esm_Chunk_empty()),
				)
			}
		}
		const takeRemainderLoop = (self, min, max, acc) =>
				max < min
					? succeed(acc)
					: pipe(
							takeUpTo(self, max),
							core_flatMap(bs => {
								const remaining = min - bs.length
								return 1 === remaining
									? pipe(
											queue_take(self),
											core_map(b =>
												pipe(acc, Chunk_appendAll(bs), Chunk_append(b)),
											),
										)
									: remaining > 1
										? pipe(
												queue_take(self),
												core_flatMap(b =>
													takeRemainderLoop(
														self,
														remaining - 1,
														max - bs.length - 1,
														pipe(acc, Chunk_appendAll(bs), Chunk_append(b)),
													),
												),
											)
										: succeed(pipe(acc, Chunk_appendAll(bs)))
							}),
						),
			queue_make = (queue, strategy) =>
				pipe(
					deferredMake(),
					core_map(deferred =>
						((queue, takers, shutdownHook, shutdownFlag, strategy) =>
							new QueueImpl(
								queue,
								takers,
								shutdownHook,
								shutdownFlag,
								strategy,
							))(queue, unbounded(), deferred, MutableRef_make(!1), strategy),
					),
				)
		class BackingQueueFromMutableQueue {
			mutable;
			[BackingQueueTypeId] = backingQueueVariance
			constructor(mutable) {
				this.mutable = mutable
			}
			poll(def) {
				return MutableQueue_poll(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 (self => (void 0 === self.capacity ? 1 / 0 : self.capacity))(
					this.mutable,
				)
			}
			length() {
				return MutableQueue_length(this.mutable)
			}
		}
		const backingQueueFromMutableQueue = mutable =>
				new BackingQueueFromMutableQueue(mutable),
			queue_offer = dual(2, (self, value) => self.offer(value)),
			unsafeOffer = dual(2, (self, value) => self.unsafeOffer(value)),
			queue_take = self => self.take,
			takeUpTo = dual(2, (self, max) => self.takeUpTo(max)),
			takeBetween = dual(3, (self, min, max) => self.takeBetween(min, max)),
			droppingStrategy = () => new DroppingStrategy()
		class BackPressureStrategy {
			[QueueStrategyTypeId] = queueStrategyVariance
			putters = unbounded()
			surplusSize() {
				return MutableQueue_length(this.putters)
			}
			onCompleteTakersWithEmptyQueue(takers) {
				for (
					;
					!MutableQueue_isEmpty(this.putters) && !MutableQueue_isEmpty(takers);
				) {
					const taker = MutableQueue_poll(takers, void 0),
						putter = MutableQueue_poll(this.putters, void 0)
					putter[2] && unsafeCompleteDeferred(putter[1], !0)
					unsafeCompleteDeferred(taker, putter[0])
				}
			}
			get shutdown() {
				return pipe(
					fiberId,
					core_flatMap(fiberId =>
						pipe(
							sync(() => unsafePollAll(this.putters)),
							core_flatMap(putters =>
								forEachConcurrentDiscard(
									putters,
									([_, deferred, isLastItem]) =>
										isLastItem
											? pipe(
													deferredInterruptWith(deferred, fiberId),
													core_asVoid,
												)
											: core_void_,
									!1,
									!1,
								),
							),
						),
					),
				)
			}
			handleSurplus(iterable, queue, takers, isShutdown) {
				return withFiberRuntime(state => {
					const deferred = deferredUnsafeMake(state.id())
					return pipe(
						suspend(() => {
							this.unsafeOffer(iterable, deferred)
							this.unsafeOnQueueEmptySpace(queue, takers)
							unsafeCompleteTakers(this, queue, takers)
							return MutableRef_get(isShutdown)
								? core_interrupt
								: deferredAwait(deferred)
						}),
						onInterrupt(() => sync(() => this.unsafeRemove(deferred))),
					)
				})
			}
			unsafeOnQueueEmptySpace(queue, takers) {
				let keepPolling = !0
				for (
					;
					keepPolling &&
					(queue.capacity() === Number.POSITIVE_INFINITY ||
						queue.length() < queue.capacity());
				) {
					const putter = pipe(
						this.putters,
						MutableQueue_poll(EmptyMutableQueue),
					)
					if (putter === EmptyMutableQueue) keepPolling = !1
					else {
						const offered = queue.offer(putter[0])
						offered && putter[2]
							? unsafeCompleteDeferred(putter[1], !0)
							: offered ||
								unsafeOfferAll(
									this.putters,
									pipe(unsafePollAll(this.putters), Chunk_prepend(putter)),
								)
						unsafeCompleteTakers(this, queue, takers)
					}
				}
			}
			unsafeOffer(iterable, deferred) {
				const stuff = Array_fromIterable(iterable)
				for (let i = 0; i < stuff.length; i++) {
					const value = stuff[i]
					i === stuff.length - 1
						? pipe(this.putters, offer([value, deferred, !0]))
						: pipe(this.putters, offer([value, deferred, !1]))
				}
			}
			unsafeRemove(deferred) {
				unsafeOfferAll(
					this.putters,
					pipe(
						unsafePollAll(this.putters),
						Chunk_filter(([, _]) => _ !== deferred),
					),
				)
			}
		}
		class DroppingStrategy {
			[QueueStrategyTypeId] = queueStrategyVariance
			surplusSize() {
				return 0
			}
			get shutdown() {
				return core_void_
			}
			onCompleteTakersWithEmptyQueue() {}
			handleSurplus(_iterable, _queue, _takers, _isShutdown) {
				return succeed(!1)
			}
			unsafeOnQueueEmptySpace(_queue, _takers) {}
		}
		class SlidingStrategy {
			[QueueStrategyTypeId] = queueStrategyVariance
			surplusSize() {
				return 0
			}
			get shutdown() {
				return core_void_
			}
			onCompleteTakersWithEmptyQueue() {}
			handleSurplus(iterable, queue, takers, _isShutdown) {
				return sync(() => {
					this.unsafeOffer(queue, iterable)
					unsafeCompleteTakers(this, queue, takers)
					return !0
				})
			}
			unsafeOnQueueEmptySpace(_queue, _takers) {}
			unsafeOffer(queue, iterable) {
				const iterator = iterable[Symbol.iterator]()
				let next,
					offering = !0
				for (; !(next = iterator.next()).done && offering;) {
					if (0 === queue.capacity()) return
					queue.poll(EmptyMutableQueue)
					offering = queue.offer(next.value)
				}
			}
		}
		const unsafeCompleteDeferred = (deferred, a) =>
				deferredUnsafeDone(deferred, succeed(a)),
			unsafeOfferAll = (queue, as) => pipe(queue, offerAll(as)),
			unsafePollAll = queue => pipe(queue, pollUpTo(Number.POSITIVE_INFINITY)),
			unsafePollN = (queue, max) => pipe(queue, pollUpTo(max)),
			unsafeRemove = (queue, a) => {
				unsafeOfferAll(
					queue,
					pipe(
						unsafePollAll(queue),
						Chunk_filter(b => a !== b),
					),
				)
			},
			unsafeCompleteTakers = (strategy, queue, takers) => {
				let keepPolling = !0
				for (; keepPolling && 0 !== queue.length();) {
					const taker = pipe(takers, MutableQueue_poll(EmptyMutableQueue))
					if (taker !== EmptyMutableQueue) {
						const element = queue.poll(EmptyMutableQueue)
						if (element !== EmptyMutableQueue) {
							unsafeCompleteDeferred(taker, element)
							strategy.unsafeOnQueueEmptySpace(queue, takers)
						} else
							unsafeOfferAll(
								takers,
								pipe(unsafePollAll(takers), Chunk_prepend(taker)),
							)
						keepPolling = !0
					} else keepPolling = !1
				}
				keepPolling &&
					0 === queue.length() &&
					!MutableQueue_isEmpty(takers) &&
					strategy.onCompleteTakersWithEmptyQueue(takers)
			},
			Queue_bounded = requestedCapacity =>
				pipe(
					sync(() => bounded(requestedCapacity)),
					core_flatMap(queue =>
						queue_make(
							backingQueueFromMutableQueue(queue),
							new BackPressureStrategy(),
						),
					),
				),
			Queue_unbounded = () =>
				pipe(
					sync(() => unbounded()),
					core_flatMap(queue =>
						queue_make(backingQueueFromMutableQueue(queue), droppingStrategy()),
					),
				),
			Queue_shutdown = self => self.shutdown,
			Queue_offer = queue_offer,
			Queue_unsafeOffer = unsafeOffer,
			Queue_take = queue_take,
			Queue_takeBetween = takeBetween,
			FiberRef_unsafeMake = fiberRefUnsafeMake,
			getWith = fiberRefGetWith,
			FiberRef_currentScheduler = currentScheduler,
			ChildExecutorDecisionTypeId = Symbol.for(
				"effect/ChannelChildExecutorDecision",
			),
			childExecutorDecision_proto = {
				[ChildExecutorDecisionTypeId]: ChildExecutorDecisionTypeId,
			},
			Continue = _ => {
				const op = Object.create(childExecutorDecision_proto)
				op._tag = "Continue"
				return op
			},
			ContinuationTypeId = Symbol.for("effect/ChannelContinuation"),
			continuationVariance = {
				_Env: _ => _,
				_InErr: _ => _,
				_InElem: _ => _,
				_InDone: _ => _,
				_OutErr: _ => _,
				_OutDone: _ => _,
				_OutErr2: _ => _,
				_OutElem: _ => _,
				_OutDone2: _ => _,
			}
		class ContinuationKImpl {
			onSuccess
			onHalt
			_tag = "ContinuationK";
			[ContinuationTypeId] = continuationVariance
			constructor(onSuccess, onHalt) {
				this.onSuccess = onSuccess
				this.onHalt = onHalt
			}
			onExit(exit) {
				return Exit_isFailure(exit)
					? this.onHalt(exit.cause)
					: this.onSuccess(exit.value)
			}
		}
		class ContinuationFinalizerImpl {
			finalizer
			_tag = "ContinuationFinalizer";
			[ContinuationTypeId] = continuationVariance
			constructor(finalizer) {
				this.finalizer = finalizer
			}
		}
		const UpstreamPullStrategyTypeId = Symbol.for(
				"effect/ChannelUpstreamPullStrategy",
			),
			upstreamPullStrategy_proto = {
				[UpstreamPullStrategyTypeId]: { _A: _ => _ },
			},
			PullAfterNext = emitSeparator => {
				const op = Object.create(upstreamPullStrategy_proto)
				op._tag = "PullAfterNext"
				op.emitSeparator = emitSeparator
				return op
			},
			core_stream_ChannelTypeId = Symbol.for("effect/Channel"),
			core_stream_proto = {
				[core_stream_ChannelTypeId]: {
					_Env: _ => _,
					_InErr: _ => _,
					_InElem: _ => _,
					_InDone: _ => _,
					_OutErr: _ => _,
					_OutElem: _ => _,
					_OutDone: _ => _,
				},
				pipe() {
					return pipeArguments(this, arguments)
				},
			},
			isChannel = u =>
				hasProperty(u, core_stream_ChannelTypeId) || Effect_isEffect(u),
			acquireReleaseOut = dual(2, (self, release) => {
				const op = Object.create(core_stream_proto)
				op._tag = "BracketOut"
				op.acquire = () => self
				op.finalizer = release
				return op
			}),
			core_stream_catchAllCause = dual(2, (self, f) => {
				const op = Object.create(core_stream_proto)
				op._tag = "Fold"
				op.channel = self
				op.k = new ContinuationKImpl(core_stream_succeed, f)
				return op
			}),
			concatAllWith = (channels, f, g) => {
				const op = Object.create(core_stream_proto)
				op._tag = "ConcatAll"
				op.combineInners = f
				op.combineAll = g
				op.onPull = () => PullAfterNext(Option_none())
				op.onEmit = () => Continue
				op.value = () => channels
				op.k = identity
				return op
			},
			concatMapWith = dual(4, (self, f, g, h) => {
				const op = Object.create(core_stream_proto)
				op._tag = "ConcatAll"
				op.combineInners = g
				op.combineAll = h
				op.onPull = () => PullAfterNext(Option_none())
				op.onEmit = () => Continue
				op.value = () => self
				op.k = f
				return op
			}),
			embedInput = dual(2, (self, input) => {
				const op = Object.create(core_stream_proto)
				op._tag = "Bridge"
				op.input = input
				op.channel = self
				return op
			}),
			ensuringWith = dual(2, (self, finalizer) => {
				const op = Object.create(core_stream_proto)
				op._tag = "Ensuring"
				op.channel = self
				op.finalizer = finalizer
				return op
			}),
			core_stream_fail = error => core_stream_failCause(Cause_fail(error)),
			core_stream_failCause = cause => core_stream_failCauseSync(() => cause),
			core_stream_failCauseSync = evaluate => {
				const op = Object.create(core_stream_proto)
				op._tag = "Fail"
				op.error = evaluate
				return op
			},
			core_stream_flatMap = dual(2, (self, f) => {
				const op = Object.create(core_stream_proto)
				op._tag = "Fold"
				op.channel = self
				op.k = new ContinuationKImpl(f, core_stream_failCause)
				return op
			}),
			core_stream_fromEffect = effect => {
				const op = Object.create(core_stream_proto)
				op._tag = "FromEffect"
				op.effect = () => effect
				return op
			},
			pipeTo = dual(2, (self, that) => {
				const op = Object.create(core_stream_proto)
				op._tag = "PipeTo"
				op.left = () => self
				op.right = () => that
				return op
			}),
			readWith = options =>
				readWithCause({
					onInput: options.onInput,
					onFailure: cause =>
						match(Cause_failureOrCause(cause), {
							onLeft: options.onFailure,
							onRight: core_stream_failCause,
						}),
					onDone: options.onDone,
				}),
			readWithCause = options => {
				const op = Object.create(core_stream_proto)
				op._tag = "Read"
				op.more = options.onInput
				op.done = new ContinuationKImpl(options.onDone, options.onFailure)
				return op
			},
			core_stream_succeed = value => core_stream_sync(() => value),
			succeedNow = result => {
				const op = Object.create(core_stream_proto)
				op._tag = "SucceedNow"
				op.terminal = result
				return op
			},
			core_stream_suspend = evaluate => {
				const op = Object.create(core_stream_proto)
				op._tag = "Suspend"
				op.channel = evaluate
				return op
			},
			core_stream_sync = evaluate => {
				const op = Object.create(core_stream_proto)
				op._tag = "Succeed"
				op.evaluate = evaluate
				return op
			},
			core_stream_void_ = succeedNow(void 0),
			write = out => {
				const op = Object.create(core_stream_proto)
				op._tag = "Emit"
				op.out = out
				return op
			},
			ChannelStateTypeId = Symbol.for("effect/ChannelState"),
			channelState_proto = { [ChannelStateTypeId]: { _E: _ => _, _R: _ => _ } },
			channelState_Done = () => {
				const op = Object.create(channelState_proto)
				op._tag = "Done"
				return op
			},
			Emit = () => {
				const op = Object.create(channelState_proto)
				op._tag = "Emit"
				return op
			},
			channelState_fromEffect = effect => {
				const op = Object.create(channelState_proto)
				op._tag = "FromEffect"
				op.effect = effect
				return op
			},
			Read = (upstream, onEffect, onEmit, onDone) => {
				const op = Object.create(channelState_proto)
				op._tag = "Read"
				op.upstream = upstream
				op.onEffect = onEffect
				op.onEmit = onEmit
				op.onDone = onDone
				return op
			},
			isFromEffect = self => "FromEffect" === self._tag,
			effectOrUndefinedIgnored = self =>
				isFromEffect(self) ? Effect_ignore(self.effect) : void 0
		class PullFromChild {
			childExecutor
			parentSubexecutor
			onEmit
			_tag = "PullFromChild"
			constructor(childExecutor, parentSubexecutor, onEmit) {
				this.childExecutor = childExecutor
				this.parentSubexecutor = parentSubexecutor
				this.onEmit = onEmit
			}
			close(exit) {
				const fin1 = this.childExecutor.close(exit),
					fin2 = this.parentSubexecutor.close(exit)
				return void 0 !== fin1 && void 0 !== fin2
					? Effect_zipWith(
							Effect_exit(fin1),
							Effect_exit(fin2),
							(exit1, exit2) => pipe(exit1, Exit_zipRight(exit2)),
						)
					: void 0 !== fin1
						? fin1
						: void 0 !== fin2
							? fin2
							: void 0
			}
			enqueuePullFromChild(_child) {
				return this
			}
		}
		class PullFromUpstream {
			upstreamExecutor
			createChild
			lastDone
			activeChildExecutors
			combineChildResults
			combineWithChildResult
			onPull
			onEmit
			_tag = "PullFromUpstream"
			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(exit) {
				const fin1 = this.upstreamExecutor.close(exit)
				return [
					...this.activeChildExecutors.map(child =>
						void 0 !== child ? child.childExecutor.close(exit) : void 0,
					),
					fin1,
				].reduce(
					(acc, next) =>
						void 0 !== acc && void 0 !== next
							? Effect_zipWith(acc, Effect_exit(next), (exit1, exit2) =>
									Exit_zipRight(exit1, exit2),
								)
							: void 0 !== acc
								? acc
								: void 0 !== next
									? Effect_exit(next)
									: void 0,
					void 0,
				)
			}
			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 = "DrainChildExecutors"
			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(exit) {
				const fin1 = this.upstreamExecutor.close(exit)
				return [
					...this.activeChildExecutors.map(child =>
						void 0 !== child ? child.childExecutor.close(exit) : void 0,
					),
					fin1,
				].reduce(
					(acc, next) =>
						void 0 !== acc && void 0 !== next
							? Effect_zipWith(acc, Effect_exit(next), (exit1, exit2) =>
									Exit_zipRight(exit1, exit2),
								)
							: void 0 !== acc
								? acc
								: void 0 !== next
									? Effect_exit(next)
									: void 0,
					void 0,
				)
			}
			enqueuePullFromChild(child) {
				return new DrainChildExecutors(
					this.upstreamExecutor,
					this.lastDone,
					[...this.activeChildExecutors, child],
					this.upstreamDone,
					this.combineChildResults,
					this.combineWithChildResult,
					this.onPull,
				)
			}
		}
		class subexecutor_Emit {
			value
			next
			_tag = "Emit"
			constructor(value, next) {
				this.value = value
				this.next = next
			}
			close(exit) {
				return this.next.close(exit)
			}
			enqueuePullFromChild(_child) {
				return this
			}
		}
		const UpstreamPullRequestTypeId = Symbol.for(
				"effect/ChannelUpstreamPullRequest",
			),
			upstreamPullRequest_proto = {
				[UpstreamPullRequestTypeId]: { _A: _ => _ },
			},
			Pulled = value => {
				const op = Object.create(upstreamPullRequest_proto)
				op._tag = "Pulled"
				op.value = value
				return 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
				for (; void 0 === result;)
					if (void 0 !== this._cancelled) result = this.processCancellation()
					else if (void 0 !== this._activeSubexecutor)
						result = this.runSubexecutor()
					else
						try {
							if (void 0 === this._currentChannel) result = channelState_Done()
							else {
								Effect_isEffect(this._currentChannel) &&
									(this._currentChannel = core_stream_fromEffect(
										this._currentChannel,
									))
								switch (this._currentChannel._tag) {
									case "BracketOut":
										result = this.runBracketOut(this._currentChannel)
										break
									case "Bridge": {
										const bridgeInput = this._currentChannel.input
										this._currentChannel = this._currentChannel.channel
										if (void 0 !== this._input) {
											const inputExecutor = this._input
											this._input = void 0
											const drainer = () =>
												Effect_flatMap(bridgeInput.awaitRead(), () =>
													Effect_suspend(() => {
														const state = inputExecutor.run()
														switch (state._tag) {
															case "Done":
																return Exit_match(inputExecutor.getDone(), {
																	onFailure: cause => bridgeInput.error(cause),
																	onSuccess: value => bridgeInput.done(value),
																})
															case "Emit":
																return Effect_flatMap(
																	bridgeInput.emit(inputExecutor.getEmit()),
																	() => drainer(),
																)
															case "FromEffect":
																return Effect_matchCauseEffect(state.effect, {
																	onFailure: cause => bridgeInput.error(cause),
																	onSuccess: () => drainer(),
																})
															case "Read":
																return readUpstream(
																	state,
																	() => drainer(),
																	cause => bridgeInput.error(cause),
																)
														}
													}),
												)
											result = channelState_fromEffect(
												Effect_flatMap(
													Effect_forkDaemon(Effect_interruptible(drainer())),
													fiber =>
														Effect_sync(() =>
															this.addFinalizer(exit =>
																Effect_flatMap(Fiber_interrupt(fiber), () =>
																	Effect_suspend(() => {
																		const effect = this.restorePipe(
																			exit,
																			inputExecutor,
																		)
																		return void 0 !== effect ? effect : _void
																	}),
																),
															),
														),
												),
											)
										}
										break
									}
									case "ConcatAll": {
										const executor = new ChannelExecutor(
											this._currentChannel.value(),
											this._providedEnv,
											effect =>
												Effect_sync(() => {
													const prevLastClose =
														void 0 === this._closeLastSubstream
															? _void
															: this._closeLastSubstream
													this._closeLastSubstream = pipe(
														prevLastClose,
														Effect_zipRight(effect),
													)
												}),
										)
										executor._input = this._input
										const 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),
											request => channel.onPull(request),
											value => channel.onEmit(value),
										)
										this._closeLastSubstream = void 0
										this._currentChannel = void 0
										break
									}
									case "Emit":
										this._emitted = this._currentChannel.out
										this._currentChannel =
											void 0 !== this._activeSubexecutor
												? void 0
												: core_stream_void_
										result = Emit()
										break
									case "Ensuring":
										this.runEnsuring(this._currentChannel)
										break
									case "Fail":
										result = this.doneHalt(this._currentChannel.error())
										break
									case "Fold":
										this._doneStack.push(this._currentChannel.k)
										this._currentChannel = this._currentChannel.channel
										break
									case "FromEffect": {
										const effect =
											void 0 === this._providedEnv
												? this._currentChannel.effect()
												: pipe(
														this._currentChannel.effect(),
														Effect_provide(this._providedEnv),
													)
										result = channelState_fromEffect(
											Effect_matchCauseEffect(effect, {
												onFailure: cause => {
													const state = this.doneHalt(cause)
													return void 0 !== state && isFromEffect(state)
														? state.effect
														: _void
												},
												onSuccess: value => {
													const state = this.doneSucceed(value)
													return void 0 !== state && isFromEffect(state)
														? state.effect
														: _void
												},
											}),
										)
										break
									}
									case "PipeTo": {
										const previousInput = this._input,
											leftExec = new ChannelExecutor(
												this._currentChannel.left(),
												this._providedEnv,
												effect => this._executeCloseLastSubstream(effect),
											)
										leftExec._input = previousInput
										this._input = leftExec
										this.addFinalizer(exit => {
											const effect = this.restorePipe(exit, previousInput)
											return void 0 !== effect ? effect : _void
										})
										this._currentChannel = this._currentChannel.right()
										break
									}
									case "Provide": {
										const previousEnv = this._providedEnv
										this._providedEnv = this._currentChannel.context()
										this._currentChannel = this._currentChannel.inner
										this.addFinalizer(() =>
											Effect_sync(() => {
												this._providedEnv = previousEnv
											}),
										)
										break
									}
									case "Read": {
										const read = this._currentChannel
										result = Read(
											this._input,
											identity,
											emitted => {
												try {
													this._currentChannel = read.more(emitted)
												} catch (error) {
													this._currentChannel = read.done.onExit(
														Exit_die(error),
													)
												}
											},
											exit => {
												this._currentChannel = (exit => read.done.onExit(exit))(
													exit,
												)
											},
										)
										break
									}
									case "Succeed":
										result = this.doneSucceed(this._currentChannel.evaluate())
										break
									case "SucceedNow":
										result = this.doneSucceed(this._currentChannel.terminal)
										break
									case "Suspend":
										this._currentChannel = this._currentChannel.channel()
								}
							}
						} catch (error) {
							this._currentChannel = core_stream_failCause(Cause_die(error))
						}
				return result
			}
			getDone() {
				return this._done
			}
			getEmit() {
				return this._emitted
			}
			cancelWith(exit) {
				this._cancelled = exit
			}
			clearInProgressFinalizer() {
				this._inProgressFinalizer = void 0
			}
			storeInProgressFinalizer(finalizer) {
				this._inProgressFinalizer = finalizer
			}
			popAllFinalizers(exit) {
				const finalizers = []
				let next = this._doneStack.pop()
				for (; next;) {
					"ContinuationFinalizer" === next._tag &&
						finalizers.push(next.finalizer)
					next = this._doneStack.pop()
				}
				const effect =
					0 === finalizers.length ? _void : runFinalizers(finalizers, exit)
				this.storeInProgressFinalizer(effect)
				return effect
			}
			popNextFinalizers() {
				const builder = []
				for (; 0 !== this._doneStack.length;) {
					const cont = this._doneStack[this._doneStack.length - 1]
					if ("ContinuationK" === cont._tag) return builder
					builder.push(cont)
					this._doneStack.pop()
				}
				return builder
			}
			restorePipe(exit, prev) {
				const currInput = this._input
				this._input = prev
				return void 0 !== currInput ? currInput.close(exit) : _void
			}
			close(exit) {
				let runInProgressFinalizers
				const finalizer = this._inProgressFinalizer
				void 0 !== finalizer &&
					(runInProgressFinalizers = pipe(
						finalizer,
						Effect_ensuring(Effect_sync(() => this.clearInProgressFinalizer())),
					))
				let closeSelf
				const selfFinalizers = this.popAllFinalizers(exit)
				void 0 !== selfFinalizers &&
					(closeSelf = pipe(
						selfFinalizers,
						Effect_ensuring(Effect_sync(() => this.clearInProgressFinalizer())),
					))
				const closeSubexecutors =
					void 0 === this._activeSubexecutor
						? void 0
						: this._activeSubexecutor.close(exit)
				if (
					void 0 !== closeSubexecutors ||
					void 0 !== runInProgressFinalizers ||
					void 0 !== closeSelf
				)
					return pipe(
						Effect_exit(ifNotNull(closeSubexecutors)),
						Effect_zip(Effect_exit(ifNotNull(runInProgressFinalizers))),
						Effect_zip(Effect_exit(ifNotNull(closeSelf))),
						Effect_map(([[exit1, exit2], exit3]) =>
							pipe(exit1, Exit_zipRight(exit2), Exit_zipRight(exit3)),
						),
						Effect_uninterruptible,
						Effect_flatMap(exit => Effect_suspend(() => exit)),
					)
			}
			doneSucceed(value) {
				if (0 === this._doneStack.length) {
					this._done = Exit_succeed(value)
					this._currentChannel = void 0
					return channelState_Done()
				}
				const head = this._doneStack[this._doneStack.length - 1]
				if ("ContinuationK" === head._tag) {
					this._doneStack.pop()
					this._currentChannel = head.onSuccess(value)
					return
				}
				const finalizers = this.popNextFinalizers()
				if (0 === this._doneStack.length) {
					this._doneStack = finalizers.reverse()
					this._done = Exit_succeed(value)
					this._currentChannel = void 0
					return channelState_Done()
				}
				const finalizerEffect = runFinalizers(
					finalizers.map(f => f.finalizer),
					Exit_succeed(value),
				)
				this.storeInProgressFinalizer(finalizerEffect)
				const effect = pipe(
					finalizerEffect,
					Effect_ensuring(Effect_sync(() => this.clearInProgressFinalizer())),
					Effect_uninterruptible,
					Effect_flatMap(() => Effect_sync(() => this.doneSucceed(value))),
				)
				return channelState_fromEffect(effect)
			}
			doneHalt(cause) {
				if (0 === this._doneStack.length) {
					this._done = Exit_failCause(cause)
					this._currentChannel = void 0
					return channelState_Done()
				}
				const head = this._doneStack[this._doneStack.length - 1]
				if ("ContinuationK" === head._tag) {
					this._doneStack.pop()
					try {
						this._currentChannel = head.onHalt(cause)
					} catch (error) {
						this._currentChannel = core_stream_failCause(Cause_die(error))
					}
					return
				}
				const finalizers = this.popNextFinalizers()
				if (0 === this._doneStack.length) {
					this._doneStack = finalizers.reverse()
					this._done = Exit_failCause(cause)
					this._currentChannel = void 0
					return channelState_Done()
				}
				const finalizerEffect = runFinalizers(
					finalizers.map(f => f.finalizer),
					Exit_failCause(cause),
				)
				this.storeInProgressFinalizer(finalizerEffect)
				const effect = pipe(
					finalizerEffect,
					Effect_ensuring(Effect_sync(() => this.clearInProgressFinalizer())),
					Effect_uninterruptible,
					Effect_flatMap(() => Effect_sync(() => this.doneHalt(cause))),
				)
				return channelState_fromEffect(effect)
			}
			processCancellation() {
				this._currentChannel = void 0
				this._done = this._cancelled
				this._cancelled = void 0
				return channelState_Done()
			}
			runBracketOut(bracketOut) {
				const effect = Effect_uninterruptible(
					Effect_matchCauseEffect(this.provide(bracketOut.acquire()), {
						onFailure: cause =>
							Effect_sync(() => {
								this._currentChannel = core_stream_failCause(cause)
							}),
						onSuccess: out =>
							Effect_sync(() => {
								this.addFinalizer(exit =>
									this.provide(bracketOut.finalizer(out, exit)),
								)
								this._currentChannel = write(out)
							}),
					}),
				)
				return channelState_fromEffect(effect)
			}
			provide(effect) {
				return void 0 === this._providedEnv
					? effect
					: pipe(effect, Effect_provide(this._providedEnv))
			}
			runEnsuring(ensuring) {
				this.addFinalizer(ensuring.finalizer)
				this._currentChannel = ensuring.channel
			}
			addFinalizer(f) {
				this._doneStack.push(new ContinuationFinalizerImpl(f))
			}
			runSubexecutor() {
				const subexecutor = this._activeSubexecutor
				switch (subexecutor._tag) {
					case "PullFromChild":
						return this.pullFromChild(
							subexecutor.childExecutor,
							subexecutor.parentSubexecutor,
							subexecutor.onEmit,
							subexecutor,
						)
					case "PullFromUpstream":
						return this.pullFromUpstream(subexecutor)
					case "DrainChildExecutors":
						return this.drainChildExecutors(subexecutor)
					case "Emit":
						this._emitted = subexecutor.value
						this._activeSubexecutor = subexecutor.next
						return Emit()
				}
			}
			replaceSubexecutor(nextSubExec) {
				this._currentChannel = void 0
				this._activeSubexecutor = nextSubExec
			}
			finishWithExit(exit) {
				const state = Exit_match(exit, {
					onFailure: cause => this.doneHalt(cause),
					onSuccess: value => this.doneSucceed(value),
				})
				this._activeSubexecutor = void 0
				return void 0 === state
					? _void
					: (self => (isFromEffect(self) ? self.effect : _void))(state)
			}
			finishSubexecutorWithCloseEffect(subexecutorDone, ...closeFuncs) {
				this.addFinalizer(() =>
					pipe(
						closeFuncs,
						Effect_forEach(
							closeFunc =>
								pipe(
									Effect_sync(() => closeFunc(subexecutorDone)),
									Effect_flatMap(closeEffect =>
										void 0 !== closeEffect ? closeEffect : _void,
									),
								),
							{ discard: !0 },
						),
					),
				)
				const state = pipe(
					subexecutorDone,
					Exit_match({
						onFailure: cause => this.doneHalt(cause),
						onSuccess: value => this.doneSucceed(value),
					}),
				)
				this._activeSubexecutor = void 0
				return state
			}
			applyUpstreamPullStrategy(upstreamFinished, queue, strategy) {
				switch (strategy._tag) {
					case "PullAfterNext": {
						const shouldPrepend =
							!upstreamFinished ||
							queue.some(subexecutor => void 0 !== subexecutor)
						return [
							strategy.emitSeparator,
							shouldPrepend ? [void 0, ...queue] : queue,
						]
					}
					case "PullAfterAllEnqueued": {
						const shouldEnqueue =
							!upstreamFinished ||
							queue.some(subexecutor => void 0 !== subexecutor)
						return [
							strategy.emitSeparator,
							shouldEnqueue ? [...queue, void 0] : queue,
						]
					}
				}
			}
			pullFromChild(childExecutor, parentSubexecutor, onEmitted, subexecutor) {
				return Read(
					childExecutor,
					identity,
					emitted => {
						const childExecutorDecision = onEmitted(emitted)
						switch (childExecutorDecision._tag) {
							case "Continue":
								break
							case "Close":
								this.finishWithDoneValue(
									childExecutor,
									parentSubexecutor,
									childExecutorDecision.value,
								)
								break
							case "Yield": {
								const modifiedParent =
									parentSubexecutor.enqueuePullFromChild(subexecutor)
								this.replaceSubexecutor(modifiedParent)
								break
							}
						}
						this._activeSubexecutor = new subexecutor_Emit(
							emitted,
							this._activeSubexecutor,
						)
					},
					Exit_match({
						onFailure: cause => {
							const state = this.handleSubexecutorFailure(
								childExecutor,
								parentSubexecutor,
								cause,
							)
							return void 0 === state ? void 0 : effectOrUndefinedIgnored(state)
						},
						onSuccess: doneValue => {
							this.finishWithDoneValue(
								childExecutor,
								parentSubexecutor,
								doneValue,
							)
						},
					}),
				)
			}
			finishWithDoneValue(childExecutor, parentSubexecutor, doneValue) {
				const subexecutor = parentSubexecutor
				switch (subexecutor._tag) {
					case "PullFromUpstream": {
						const modifiedParent = new PullFromUpstream(
							subexecutor.upstreamExecutor,
							subexecutor.createChild,
							void 0 !== subexecutor.lastDone
								? subexecutor.combineChildResults(
										subexecutor.lastDone,
										doneValue,
									)
								: doneValue,
							subexecutor.activeChildExecutors,
							subexecutor.combineChildResults,
							subexecutor.combineWithChildResult,
							subexecutor.onPull,
							subexecutor.onEmit,
						)
						this._closeLastSubstream = childExecutor.close(
							Exit_succeed(doneValue),
						)
						this.replaceSubexecutor(modifiedParent)
						break
					}
					case "DrainChildExecutors": {
						const modifiedParent = new DrainChildExecutors(
							subexecutor.upstreamExecutor,
							void 0 !== subexecutor.lastDone
								? subexecutor.combineChildResults(
										subexecutor.lastDone,
										doneValue,
									)
								: doneValue,
							subexecutor.activeChildExecutors,
							subexecutor.upstreamDone,
							subexecutor.combineChildResults,
							subexecutor.combineWithChildResult,
							subexecutor.onPull,
						)
						this._closeLastSubstream = childExecutor.close(
							Exit_succeed(doneValue),
						)
						this.replaceSubexecutor(modifiedParent)
						break
					}
				}
			}
			handleSubexecutorFailure(childExecutor, parentSubexecutor, cause) {
				return this.finishSubexecutorWithCloseEffect(
					Exit_failCause(cause),
					exit => parentSubexecutor.close(exit),
					exit => childExecutor.close(exit),
				)
			}
			pullFromUpstream(subexecutor) {
				if (0 === subexecutor.activeChildExecutors.length)
					return this.performPullFromUpstream(subexecutor)
				const 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 (void 0 === activeChild)
					return this.performPullFromUpstream(parentSubexecutor)
				this.replaceSubexecutor(
					new PullFromChild(
						activeChild.childExecutor,
						parentSubexecutor,
						activeChild.onEmit,
					),
				)
			}
			performPullFromUpstream(subexecutor) {
				return Read(
					subexecutor.upstreamExecutor,
					effect => {
						const closeLastSubstream =
							void 0 === this._closeLastSubstream
								? _void
								: this._closeLastSubstream
						this._closeLastSubstream = void 0
						return pipe(
							this._executeCloseLastSubstream(closeLastSubstream),
							Effect_zipRight(effect),
						)
					},
					emitted => {
						if (void 0 !== this._closeLastSubstream) {
							const closeLastSubstream = this._closeLastSubstream
							this._closeLastSubstream = void 0
							return pipe(
								this._executeCloseLastSubstream(closeLastSubstream),
								Effect_map(() => {
									const childExecutor = new ChannelExecutor(
										subexecutor.createChild(emitted),
										this._providedEnv,
										this._executeCloseLastSubstream,
									)
									childExecutor._input = this._input
									const [emitSeparator, updatedChildExecutors] =
										this.applyUpstreamPullStrategy(
											!1,
											subexecutor.activeChildExecutors,
											subexecutor.onPull(Pulled(emitted)),
										)
									this._activeSubexecutor = new PullFromChild(
										childExecutor,
										new PullFromUpstream(
											subexecutor.upstreamExecutor,
											subexecutor.createChild,
											subexecutor.lastDone,
											updatedChildExecutors,
											subexecutor.combineChildResults,
											subexecutor.combineWithChildResult,
											subexecutor.onPull,
											subexecutor.onEmit,
										),
										subexecutor.onEmit,
									)
									Option_isSome(emitSeparator) &&
										(this._activeSubexecutor = new subexecutor_Emit(
											emitSeparator.value,
											this._activeSubexecutor,
										))
								}),
							)
						}
						const childExecutor = new ChannelExecutor(
							subexecutor.createChild(emitted),
							this._providedEnv,
							this._executeCloseLastSubstream,
						)
						childExecutor._input = this._input
						const [emitSeparator, updatedChildExecutors] =
							this.applyUpstreamPullStrategy(
								!1,
								subexecutor.activeChildExecutors,
								subexecutor.onPull(Pulled(emitted)),
							)
						this._activeSubexecutor = new PullFromChild(
							childExecutor,
							new PullFromUpstream(
								subexecutor.upstreamExecutor,
								subexecutor.createChild,
								subexecutor.lastDone,
								updatedChildExecutors,
								subexecutor.combineChildResults,
								subexecutor.combineWithChildResult,
								subexecutor.onPull,
								subexecutor.onEmit,
							),
							subexecutor.onEmit,
						)
						Option_isSome(emitSeparator) &&
							(this._activeSubexecutor = new subexecutor_Emit(
								emitSeparator.value,
								this._activeSubexecutor,
							))
					},
					exit => {
						if (
							subexecutor.activeChildExecutors.some(
								subexecutor => void 0 !== subexecutor,
							)
						) {
							const drain = new DrainChildExecutors(
								subexecutor.upstreamExecutor,
								subexecutor.lastDone,
								[void 0, ...subexecutor.activeChildExecutors],
								subexecutor.upstreamExecutor.getDone(),
								subexecutor.combineChildResults,
								subexecutor.combineWithChildResult,
								subexecutor.onPull,
							)
							if (void 0 !== this._closeLastSubstream) {
								const closeLastSubstream = this._closeLastSubstream
								this._closeLastSubstream = void 0
								return pipe(
									this._executeCloseLastSubstream(closeLastSubstream),
									Effect_map(() => this.replaceSubexecutor(drain)),
								)
							}
							this.replaceSubexecutor(drain)
							return
						}
						const closeLastSubstream = this._closeLastSubstream,
							state = this.finishSubexecutorWithCloseEffect(
								pipe(
									exit,
									Exit_map(a =>
										subexecutor.combineWithChildResult(subexecutor.lastDone, a),
									),
								),
								() => closeLastSubstream,
								exit => subexecutor.upstreamExecutor.close(exit),
							)
						return void 0 === state ? void 0 : effectOrUndefinedIgnored(state)
					},
				)
			}
			drainChildExecutors(subexecutor) {
				if (0 === subexecutor.activeChildExecutors.length) {
					const lastClose = this._closeLastSubstream
					void 0 !== lastClose &&
						this.addFinalizer(() => Effect_succeed(lastClose))
					return this.finishSubexecutorWithCloseEffect(
						subexecutor.upstreamDone,
						() => lastClose,
						exit => subexecutor.upstreamExecutor.close(exit),
					)
				}
				const activeChild = subexecutor.activeChildExecutors[0],
					rest = subexecutor.activeChildExecutors.slice(1)
				if (void 0 === activeChild) {
					const [emitSeparator, remainingExecutors] =
						this.applyUpstreamPullStrategy(
							!0,
							rest,
							subexecutor.onPull(
								(activeDownstreamCount => {
									const op = Object.create(upstreamPullRequest_proto)
									op._tag = "NoUpstream"
									op.activeDownstreamCount = activeDownstreamCount
									return op
								})(rest.reduce((n, curr) => (void 0 !== curr ? n + 1 : n), 0)),
							),
						)
					this.replaceSubexecutor(
						new DrainChildExecutors(
							subexecutor.upstreamExecutor,
							subexecutor.lastDone,
							remainingExecutors,
							subexecutor.upstreamDone,
							subexecutor.combineChildResults,
							subexecutor.combineWithChildResult,
							subexecutor.onPull,
						),
					)
					if (Option_isSome(emitSeparator)) {
						this._emitted = emitSeparator.value
						return Emit()
					}
					return
				}
				const 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,
					),
				)
			}
		}
		const ifNotNull = effect => (void 0 !== effect ? effect : _void),
			runFinalizers = (finalizers, exit) =>
				pipe(
					Effect_forEach(finalizers, fin => Effect_exit(fin(exit))),
					Effect_map(exits =>
						pipe(
							Exit_all(exits),
							Option_getOrElse(() => Exit_void_),
						),
					),
					Effect_flatMap(exit => Effect_suspend(() => exit)),
				),
			readUpstream = (r, onSuccess, onFailure) => {
				const readStack = [r],
					read = () => {
						const current = readStack.pop()
						if (void 0 === current || void 0 === current.upstream)
							return Effect_dieMessage(
								"Unexpected end of input for channel execution",
							)
						const state = current.upstream.run()
						switch (state._tag) {
							case "Emit": {
								const emitEffect = current.onEmit(current.upstream.getEmit())
								return 0 === readStack.length
									? void 0 === emitEffect
										? Effect_suspend(onSuccess)
										: pipe(
												emitEffect,
												Effect_matchCauseEffect({ onFailure, onSuccess }),
											)
									: void 0 === emitEffect
										? Effect_suspend(() => read())
										: pipe(
												emitEffect,
												Effect_matchCauseEffect({
													onFailure,
													onSuccess: () => read(),
												}),
											)
							}
							case "Done": {
								const doneEffect = current.onDone(current.upstream.getDone())
								return 0 === readStack.length
									? void 0 === doneEffect
										? Effect_suspend(onSuccess)
										: pipe(
												doneEffect,
												Effect_matchCauseEffect({ onFailure, onSuccess }),
											)
									: void 0 === doneEffect
										? Effect_suspend(() => read())
										: pipe(
												doneEffect,
												Effect_matchCauseEffect({
													onFailure,
													onSuccess: () => read(),
												}),
											)
							}
							case "FromEffect":
								readStack.push(current)
								return pipe(
									current.onEffect(state.effect),
									Effect_catchAllCause(cause =>
										Effect_suspend(() => {
											const doneEffect = current.onDone(Exit_failCause(cause))
											return void 0 === doneEffect ? _void : doneEffect
										}),
									),
									Effect_matchCauseEffect({
										onFailure,
										onSuccess: () => read(),
									}),
								)
							case "Read":
								readStack.push(current)
								readStack.push(state)
								return Effect_suspend(() => read())
						}
					}
				return read()
			},
			runIn = dual(2, (self, scope) =>
				Effect_uninterruptibleMask(restore =>
					Effect_all([
						Scope_fork(scope, ExecutionStrategy_sequential),
						Deferred_make(),
						Deferred_make(),
					]).pipe(
						Effect_flatMap(([child, channelDeferred, scopeDeferred]) =>
							restore(
								((channelDeferred, scopeDeferred, scope) =>
									Effect_acquireUseRelease(
										Effect_sync(
											() => new ChannelExecutor(self, void 0, identity),
										),
										exec =>
											Effect_suspend(() =>
												runScopedInterpret(exec.run(), exec).pipe(
													Effect_intoDeferred(channelDeferred),
													Effect_zipRight(Deferred_await(channelDeferred)),
													Effect_zipLeft(Deferred_await(scopeDeferred)),
												),
											),
										(exec, exit) => {
											const finalize = exec.close(exit)
											return void 0 === finalize
												? _void
												: Effect_tapErrorCause(finalize, cause =>
														Scope_addFinalizer(scope, Effect_failCause(cause)),
													)
										},
									))(channelDeferred, scopeDeferred, child),
							).pipe(
								Effect_forkIn(scope),
								Effect_flatMap(fiber =>
									scope
										.addFinalizer(exit => {
											const interruptors = Exit_isFailure(exit)
												? Cause_interruptors(exit.cause)
												: void 0
											return Deferred_isDone(channelDeferred).pipe(
												Effect_flatMap(isDone =>
													isDone
														? Deferred_succeed(scopeDeferred, void 0).pipe(
																Effect_zipRight(Fiber_await(fiber)),
																Effect_zipRight(Fiber_inheritAll(fiber)),
															)
														: Deferred_succeed(scopeDeferred, void 0).pipe(
																Effect_zipRight(
																	interruptors && HashSet_size(interruptors) > 0
																		? interruptAs(
																				fiber,
																				pipe(
																					interruptors,
																					HashSet_reduce(fiberId_none, (a, b) =>
																						fiberId_combine(b)(a),
																					),
																				),
																			)
																		: Fiber_interrupt(fiber),
																),
																Effect_zipRight(Fiber_inheritAll(fiber)),
															),
												),
											)
										})
										.pipe(
											Effect_zipRight(restore(Deferred_await(channelDeferred))),
										),
								),
							),
						),
					),
				),
			),
			runScopedInterpret = (channelState, exec) => {
				const op = channelState
				switch (op._tag) {
					case "FromEffect":
						return pipe(
							op.effect,
							Effect_flatMap(() => runScopedInterpret(exec.run(), exec)),
						)
					case "Emit":
						return runScopedInterpret(exec.run(), exec)
					case "Done":
						return Effect_suspend(() => exec.getDone())
					case "Read":
						return readUpstream(
							op,
							() => runScopedInterpret(exec.run(), exec),
							Effect_failCause,
						)
				}
			},
			MergeDecisionTypeId = Symbol.for("effect/ChannelMergeDecision"),
			mergeDecision_proto = {
				[MergeDecisionTypeId]: {
					_R: _ => _,
					_E0: _ => _,
					_Z0: _ => _,
					_E: _ => _,
					_Z: _ => _,
				},
			},
			Await = f => {
				const op = Object.create(mergeDecision_proto)
				op._tag = "Await"
				op.f = f
				return op
			},
			MergeStateTypeId = Symbol.for("effect/ChannelMergeState"),
			mergeState_proto = { [MergeStateTypeId]: MergeStateTypeId },
			BothRunning = (left, right) => {
				const op = Object.create(mergeState_proto)
				op._tag = "BothRunning"
				op.left = left
				op.right = right
				return op
			},
			LeftDone = f => {
				const op = Object.create(mergeState_proto)
				op._tag = "LeftDone"
				op.f = f
				return op
			},
			RightDone = f => {
				const op = Object.create(mergeState_proto)
				op._tag = "RightDone"
				op.f = f
				return op
			},
			MergeStrategyTypeId = Symbol.for("effect/ChannelMergeStrategy"),
			mergeStrategy_proto = { [MergeStrategyTypeId]: MergeStrategyTypeId },
			BackPressure = _ => {
				const op = Object.create(mergeStrategy_proto)
				op._tag = "BackPressure"
				return op
			},
			BufferSliding = _ => {
				const op = Object.create(mergeStrategy_proto)
				op._tag = "BufferSliding"
				return op
			},
			mergeStrategy_match = dual(
				2,
				(self, { onBackPressure, onBufferSliding }) => {
					switch (self._tag) {
						case "BackPressure":
							return onBackPressure()
						case "BufferSliding":
							return onBufferSliding()
					}
				},
			),
			stateEmpty = notifyProducer => ({ _tag: "Empty", notifyProducer }),
			stateEmit = notifyConsumers => ({ _tag: "Emit", notifyConsumers }),
			stateError = cause => ({ _tag: "Error", cause }),
			stateDone = done => ({ _tag: "Done", done })
		class SingleProducerAsyncInputImpl {
			ref
			constructor(ref) {
				this.ref = ref
			}
			awaitRead() {
				return Effect_flatten(
					Ref_modify(this.ref, state =>
						"Empty" === state._tag
							? [Deferred_await(state.notifyProducer), state]
							: [_void, state],
					),
				)
			}
			get close() {
				return Effect_fiberIdWith(fiberId =>
					this.error(Cause_interrupt(fiberId)),
				)
			}
			done(value) {
				return Effect_flatten(
					Ref_modify(this.ref, state => {
						switch (state._tag) {
							case "Empty":
								return [Deferred_await(state.notifyProducer), state]
							case "Emit":
								return [
									Effect_forEach(
										state.notifyConsumers,
										deferred => Deferred_succeed(deferred, Either_left(value)),
										{ discard: !0 },
									),
									stateDone(value),
								]
							case "Error":
							case "Done":
								return [Effect_interrupt, state]
						}
					}),
				)
			}
			emit(element) {
				return Effect_flatMap(Deferred_make(), deferred =>
					Effect_flatten(
						Ref_modify(this.ref, state => {
							switch (state._tag) {
								case "Empty":
									return [Deferred_await(state.notifyProducer), state]
								case "Emit": {
									const notifyConsumer = state.notifyConsumers[0],
										notifyConsumers = state.notifyConsumers.slice(1)
									if (void 0 !== notifyConsumer)
										return [
											Deferred_succeed(notifyConsumer, Either_right(element)),
											0 === notifyConsumers.length
												? 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 "Error":
								case "Done":
									return [Effect_interrupt, state]
							}
						}),
					),
				)
			}
			error(cause) {
				return Effect_flatten(
					Ref_modify(this.ref, state => {
						switch (state._tag) {
							case "Empty":
								return [Deferred_await(state.notifyProducer), state]
							case "Emit":
								return [
									Effect_forEach(
										state.notifyConsumers,
										deferred => Deferred_failCause(deferred, cause),
										{ discard: !0 },
									),
									stateError(cause),
								]
							case "Error":
							case "Done":
								return [Effect_interrupt, state]
						}
					}),
				)
			}
			get take() {
				return this.takeWith(
					cause => Exit_failCause(Cause_map(cause, Either_left)),
					elem => Exit_succeed(elem),
					done => Exit_fail(Either_right(done)),
				)
			}
			takeWith(onError, onElement, onDone) {
				return Effect_flatMap(Deferred_make(), deferred =>
					Effect_flatten(
						Ref_modify(this.ref, state => {
							switch (state._tag) {
								case "Empty":
									return [
										Effect_zipRight(
											Deferred_succeed(state.notifyProducer, void 0),
											Effect_matchCause(Deferred_await(deferred), {
												onFailure: onError,
												onSuccess: match({
													onLeft: onDone,
													onRight: onElement,
												}),
											}),
										),
										stateEmit([deferred]),
									]
								case "Emit":
									return [
										Effect_matchCause(Deferred_await(deferred), {
											onFailure: onError,
											onSuccess: match({ onLeft: onDone, onRight: onElement }),
										}),
										stateEmit([...state.notifyConsumers, deferred]),
									]
								case "Error":
									return [Effect_succeed(onError(state.cause)), state]
								case "Done":
									return [Effect_succeed(onDone(state.done)), state]
							}
						}),
					),
				)
			}
		}
		const singleProducerAsyncInput_make = () =>
				pipe(
					Deferred_make(),
					Effect_flatMap(deferred => Ref_make(stateEmpty(deferred))),
					Effect_map(ref => new SingleProducerAsyncInputImpl(ref)),
				),
			concatMap = dual(2, (self, f) =>
				concatMapWith(
					self,
					f,
					() => {},
					() => {},
				),
			),
			drain = self => {
				const drainer = readWithCause({
					onInput: () => drainer,
					onFailure: core_stream_failCause,
					onDone: core_stream_succeed,
				})
				return pipeTo(self, drainer)
			},
			channel_ensuring = dual(2, (self, finalizer) =>
				ensuringWith(self, () => finalizer),
			),
			fromInput = input =>
				channel_unwrap(
					input.takeWith(
						core_stream_failCause,
						elem => core_stream_flatMap(write(elem), () => fromInput(input)),
						core_stream_succeed,
					),
				),
			identityChannel = () =>
				readWith({
					onInput: input =>
						core_stream_flatMap(write(input), () => identityChannel()),
					onFailure: core_stream_fail,
					onDone: succeedNow,
				}),
			channel_map = dual(2, (self, f) =>
				core_stream_flatMap(self, a => core_stream_sync(() => f(a))),
			),
			mapOut = dual(2, (self, f) => {
				const reader = readWith({
					onInput: outElem =>
						core_stream_flatMap(write(f(outElem)), () => reader),
					onFailure: core_stream_fail,
					onDone: succeedNow,
				})
				return pipeTo(self, reader)
			}),
			mapOutEffectPar = dual(3, (self, f, n) =>
				unwrapScopedWith(scope =>
					Effect_gen(function* () {
						const input = yield* singleProducerAsyncInput_make(),
							queueReader = fromInput(input),
							queue = yield* Queue_bounded(n)
						yield* Scope_addFinalizer(scope, Queue_shutdown(queue))
						const errorSignal = yield* Deferred_make(),
							withPermits =
								n === Number.POSITIVE_INFINITY
									? _ => identity
									: (yield* Effect_makeSemaphore(n)).withPermits,
							pull = yield* queueReader.pipe(pipeTo(self), toPullIn(scope))
						yield* pull.pipe(
							Effect_matchCauseEffect({
								onFailure: cause => Queue_offer(queue, Effect_failCause(cause)),
								onSuccess: match({
									onLeft: outDone =>
										Effect_zipRight(
											Effect_interruptible(withPermits(n)(_void)),
											Effect_asVoid(
												Queue_offer(
													queue,
													Effect_succeed(Either_left(outDone)),
												),
											),
										),
									onRight: outElem =>
										Effect_gen(function* () {
											const deferred = yield* Deferred_make(),
												latch = yield* Deferred_make()
											yield* Queue_offer(
												queue,
												Effect_map(Deferred_await(deferred), Either_right),
											)
											yield* Deferred_succeed(latch, void 0).pipe(
												Effect_zipRight(
													Effect_uninterruptibleMask(restore =>
														Effect_exit(
															restore(Deferred_await(errorSignal)),
														).pipe(
															Effect_raceFirst(
																Effect_exit(restore(f(outElem))),
															),
															Effect_flatMap(identity),
														),
													).pipe(
														Effect_tapErrorCause(cause =>
															Deferred_failCause(errorSignal, cause),
														),
														Effect_intoDeferred(deferred),
													),
												),
												withPermits(1),
												Effect_forkIn(scope),
											)
											yield* Deferred_await(latch)
										}),
								}),
							}),
							Effect_forever,
							Effect_interruptible,
							Effect_forkIn(scope),
						)
						const consumer = channel_unwrap(
							Effect_matchCause(Effect_flatten(Queue_take(queue)), {
								onFailure: core_stream_failCause,
								onSuccess: match({
									onLeft: succeedNow,
									onRight: outElem =>
										core_stream_flatMap(write(outElem), () => consumer),
								}),
							}),
						)
						return embedInput(consumer, input)
					}),
				),
			),
			mergeMap = dual(3, (self, f, options) =>
				(
					options => channels =>
						(
							({
								bufferSize = 16,
								concurrency,
								mergeStrategy = BackPressure(),
							}) =>
							(channels, f) =>
								unwrapScopedWith(scope =>
									Effect_gen(function* () {
										const concurrencyN =
												"unbounded" === concurrency
													? Number.MAX_SAFE_INTEGER
													: concurrency,
											input = yield* singleProducerAsyncInput_make(),
											queueReader = fromInput(input),
											queue = yield* Queue_bounded(bufferSize)
										yield* Scope_addFinalizer(scope, Queue_shutdown(queue))
										const cancelers = yield* Queue_unbounded()
										yield* Scope_addFinalizer(scope, Queue_shutdown(cancelers))
										const lastDone = yield* Ref_make(Option_none()),
											errorSignal = yield* Deferred_make(),
											withPermits = (yield* Effect_makeSemaphore(concurrencyN))
												.withPermits,
											pull = yield* toPullIn(
												pipeTo(queueReader, channels),
												scope,
											)
										function evaluatePull(pull) {
											return pull.pipe(
												Effect_flatMap(
													match({
														onLeft: done => Effect_succeed(Option_some(done)),
														onRight: outElem =>
															Effect_as(
																Queue_offer(
																	queue,
																	Effect_succeed(Either_right(outElem)),
																),
																Option_none(),
															),
													}),
												),
												Effect_repeat({ until: _ => Option_isSome(_) }),
												Effect_flatMap(outDone =>
													Ref_update(
														lastDone,
														Option_match({
															onNone: () => Option_some(outDone.value),
															onSome: lastDone =>
																Option_some(f(lastDone, outDone.value)),
														}),
													),
												),
												Effect_catchAllCause(cause =>
													Cause_isInterrupted(cause)
														? Effect_failCause(cause)
														: Queue_offer(queue, Effect_failCause(cause)).pipe(
																Effect_zipRight(
																	Deferred_succeed(errorSignal, void 0),
																),
																Effect_asVoid,
															),
												),
											)
										}
										yield* pull.pipe(
											Effect_matchCauseEffect({
												onFailure: cause =>
													Queue_offer(queue, Effect_failCause(cause)).pipe(
														Effect_zipRight(Effect_succeed(!1)),
													),
												onSuccess: match({
													onLeft: outDone =>
														Effect_raceWith(
															Effect_interruptible(Deferred_await(errorSignal)),
															Effect_interruptible(
																withPermits(concurrencyN)(_void),
															),
															{
																onSelfDone: (_, permitAcquisition) =>
																	Effect_as(
																		Fiber_interrupt(permitAcquisition),
																		!1,
																	),
																onOtherDone: (_, failureAwait) =>
																	Effect_zipRight(
																		Fiber_interrupt(failureAwait),
																		Ref_get(lastDone).pipe(
																			Effect_flatMap(
																				Option_match({
																					onNone: () =>
																						Queue_offer(
																							queue,
																							Effect_succeed(
																								Either_left(outDone),
																							),
																						),
																					onSome: lastDone =>
																						Queue_offer(
																							queue,
																							Effect_succeed(
																								Either_left(
																									f(lastDone, outDone),
																								),
																							),
																						),
																				}),
																			),
																			Effect_as(!1),
																		),
																	),
															},
														),
													onRight: channel =>
														mergeStrategy_match(mergeStrategy, {
															onBackPressure: () =>
																Effect_gen(function* () {
																	const latch = yield* Deferred_make(),
																		raceEffects = Effect_scopedWith(scope =>
																			toPullIn(
																				pipeTo(queueReader, channel),
																				scope,
																			).pipe(
																				Effect_flatMap(pull =>
																					Effect_race(
																						Effect_exit(evaluatePull(pull)),
																						Effect_exit(
																							Effect_interruptible(
																								Deferred_await(errorSignal),
																							),
																						),
																					),
																				),
																				Effect_flatMap(identity),
																			),
																		)
																	yield* Deferred_succeed(latch, void 0).pipe(
																		Effect_zipRight(raceEffects),
																		withPermits(1),
																		Effect_forkIn(scope),
																	)
																	yield* Deferred_await(latch)
																	return !(yield* Deferred_isDone(errorSignal))
																}),
															onBufferSliding: () =>
																Effect_gen(function* () {
																	const canceler = yield* Deferred_make(),
																		latch = yield* Deferred_make(),
																		size = yield* (self => self.size)(cancelers)
																	yield* Queue_take(cancelers).pipe(
																		Effect_flatMap(canceler =>
																			Deferred_succeed(canceler, void 0),
																		),
																		Effect_when(() => size >= concurrencyN),
																	)
																	yield* Queue_offer(cancelers, canceler)
																	const raceEffects = Effect_scopedWith(scope =>
																		toPullIn(
																			pipeTo(queueReader, channel),
																			scope,
																		).pipe(
																			Effect_flatMap(pull =>
																				Effect_exit(evaluatePull(pull)).pipe(
																					Effect_race(
																						Effect_exit(
																							Effect_interruptible(
																								Deferred_await(errorSignal),
																							),
																						),
																					),
																					Effect_race(
																						Effect_exit(
																							Effect_interruptible(
																								Deferred_await(canceler),
																							),
																						),
																					),
																				),
																			),
																			Effect_flatMap(identity),
																		),
																	)
																	yield* Deferred_succeed(latch, void 0).pipe(
																		Effect_zipRight(raceEffects),
																		withPermits(1),
																		Effect_forkIn(scope),
																	)
																	yield* Deferred_await(latch)
																	return !(yield* Deferred_isDone(errorSignal))
																}),
														}),
												}),
											}),
											Effect_repeat({ while: _ => _ }),
											Effect_forkIn(scope),
										)
										const consumer = pipe(
											Queue_take(queue),
											Effect_flatten,
											Effect_matchCause({
												onFailure: core_stream_failCause,
												onSuccess: match({
													onLeft: succeedNow,
													onRight: outElem =>
														core_stream_flatMap(write(outElem), () => consumer),
												}),
											}),
											channel_unwrap,
										)
										return embedInput(consumer, input)
									}),
								)
						)(options)(channels, constVoid)
				)(options)(mapOut(self, f)),
			),
			channel_mergeWith = dual(2, (self, options) =>
				unwrapScopedWith(function (scope) {
					return Effect_gen(function* () {
						const input = yield* singleProducerAsyncInput_make(),
							queueReader = fromInput(input),
							pullL = yield* toPullIn(pipeTo(queueReader, self), scope),
							pullR = yield* toPullIn(pipeTo(queueReader, options.other), scope)
						function handleSide(exit, fiber, pull) {
							return (done, both, single) => {
								function onDecision(decision) {
									const op = decision
									return "Done" === op._tag
										? Effect_succeed(
												core_stream_fromEffect(
													Effect_zipRight(Fiber_interrupt(fiber), op.effect),
												),
											)
										: Effect_map(
												Fiber_await(fiber),
												Exit_match({
													onFailure: cause =>
														core_stream_fromEffect(op.f(Exit_failCause(cause))),
													onSuccess: match({
														onLeft: done =>
															core_stream_fromEffect(op.f(Exit_succeed(done))),
														onRight: elem =>
															channel_zipRight(write(elem), go(single(op.f))),
													}),
												}),
											)
								}
								return Exit_match(exit, {
									onFailure: cause => onDecision(done(Exit_failCause(cause))),
									onSuccess: match({
										onLeft: z => onDecision(done(Exit_succeed(z))),
										onRight: elem =>
											Effect_succeed(
												core_stream_flatMap(write(elem), () =>
													core_stream_flatMap(
														core_stream_fromEffect(
															Effect_forkIn(Effect_interruptible(pull), scope),
														),
														leftFiber => go(both(leftFiber, fiber)),
													),
												),
											),
									}),
								})
							}
						}
						function go(state) {
							switch (state._tag) {
								case "BothRunning": {
									const leftJoin = Effect_interruptible(Fiber_join(state.left)),
										rightJoin = Effect_interruptible(Fiber_join(state.right))
									return channel_unwrap(
										Effect_raceWith(leftJoin, rightJoin, {
											onSelfDone: (leftExit, rf) =>
												Effect_zipRight(
													Fiber_interrupt(rf),
													handleSide(leftExit, state.right, pullL)(
														options.onSelfDone,
														BothRunning,
														f => LeftDone(f),
													),
												),
											onOtherDone: (rightExit, lf) =>
												Effect_zipRight(
													Fiber_interrupt(lf),
													handleSide(rightExit, state.left, pullR)(
														options.onOtherDone,
														(left, right) => BothRunning(right, left),
														f => RightDone(f),
													),
												),
										}),
									)
								}
								case "LeftDone":
									return channel_unwrap(
										Effect_map(
											Effect_exit(pullR),
											Exit_match({
												onFailure: cause =>
													core_stream_fromEffect(
														state.f(Exit_failCause(cause)),
													),
												onSuccess: match({
													onLeft: done =>
														core_stream_fromEffect(state.f(Exit_succeed(done))),
													onRight: elem =>
														core_stream_flatMap(write(elem), () =>
															go(LeftDone(state.f)),
														),
												}),
											}),
										),
									)
								case "RightDone":
									return channel_unwrap(
										Effect_map(
											Effect_exit(pullL),
											Exit_match({
												onFailure: cause =>
													core_stream_fromEffect(
														state.f(Exit_failCause(cause)),
													),
												onSuccess: match({
													onLeft: done =>
														core_stream_fromEffect(state.f(Exit_succeed(done))),
													onRight: elem =>
														core_stream_flatMap(write(elem), () =>
															go(RightDone(state.f)),
														),
												}),
											}),
										),
									)
							}
						}
						return core_stream_fromEffect(
							Effect_withFiberRuntime(parent => {
								const inherit = Effect_withFiberRuntime(state => {
										state.transferChildren(parent.scope())
										return _void
									}),
									leftFiber = Effect_interruptible(pullL).pipe(
										Effect_ensuring(inherit),
										Effect_forkIn(scope),
									),
									rightFiber = Effect_interruptible(pullR).pipe(
										Effect_ensuring(inherit),
										Effect_forkIn(scope),
									)
								return Effect_zipWith(leftFiber, rightFiber, (left, right) =>
									BothRunning(left, right),
								)
							}),
						).pipe(core_stream_flatMap(go), embedInput(input))
					})
				}),
			),
			pipeToOrFail = dual(2, (self, that) =>
				core_stream_suspend(() => {
					let channelException
					const reader = readWith({
							onInput: outElem =>
								core_stream_flatMap(write(outElem), () => reader),
							onFailure: outErr => {
								channelException = ChannelException(outErr)
								return core_stream_failCause(Cause_die(channelException))
							},
							onDone: succeedNow,
						}),
						writer = readWithCause({
							onInput: outElem =>
								pipe(
									write(outElem),
									core_stream_flatMap(() => writer),
								),
							onFailure: cause =>
								Cause_isDieType(cause) &&
								isChannelException(cause.defect) &&
								equals(cause.defect, channelException)
									? core_stream_fail(cause.defect.error)
									: core_stream_failCause(cause),
							onDone: succeedNow,
						})
					return pipeTo(pipeTo(pipeTo(self, reader), that), writer)
				}),
			),
			runDrain = self =>
				(self => Effect_scopedWith(scope => runIn(self, scope)))(drain(self)),
			channel_scoped = effect =>
				channel_unwrap(
					Effect_uninterruptibleMask(restore =>
						Effect_map(Scope_make(), scope =>
							acquireReleaseOut(
								Effect_tapErrorCause(
									restore(Scope_extend(effect, scope)),
									cause => Scope_close(scope, Exit_failCause(cause)),
								),
								(_, exit) => Scope_close(scope, exit),
							),
						),
					),
				),
			channel_scopedWith = f =>
				channel_unwrapScoped(
					Effect_map(Effect_scope, scope =>
						core_stream_flatMap(core_stream_fromEffect(f(scope)), write),
					),
				),
			toPullIn = dual(2, (self, scope) =>
				Effect_zip(
					Effect_sync(() => new ChannelExecutor(self, void 0, identity)),
					Effect_runtime(),
				).pipe(
					Effect_tap(([executor, runtime]) =>
						addFinalizerExit(scope, exit => {
							const finalizer = executor.close(exit)
							return void 0 !== finalizer
								? Effect_provide(finalizer, runtime)
								: _void
						}),
					),
					Effect_uninterruptible,
					Effect_map(([executor]) =>
						Effect_suspend(() => interpretToPull(executor.run(), executor)),
					),
				),
			),
			interpretToPull = (channelState, exec) => {
				const state = channelState
				switch (state._tag) {
					case "Done":
						return Exit_match(exec.getDone(), {
							onFailure: Effect_failCause,
							onSuccess: done => Effect_succeed(Either_left(done)),
						})
					case "Emit":
						return Effect_succeed(Either_right(exec.getEmit()))
					case "FromEffect":
						return pipe(
							state.effect,
							Effect_flatMap(() => interpretToPull(exec.run(), exec)),
						)
					case "Read":
						return readUpstream(
							state,
							() => interpretToPull(exec.run(), exec),
							cause => Effect_failCause(cause),
						)
				}
			},
			channel_unwrap = channel =>
				(self => core_stream_flatMap(self, identity))(
					core_stream_fromEffect(channel),
				),
			channel_unwrapScoped = self =>
				concatAllWith(
					channel_scoped(self),
					(d, _) => d,
					(d, _) => d,
				),
			unwrapScopedWith = f =>
				concatAllWith(
					channel_scopedWith(f),
					(d, _) => d,
					(d, _) => d,
				),
			writeChunk = outs => writeChunkWriter(0, outs.length, outs),
			writeChunkWriter = (idx, len, chunk) =>
				idx === len
					? core_stream_void_
					: pipe(
							write(pipe(chunk, Chunk_unsafeGet(idx))),
							core_stream_flatMap(() => writeChunkWriter(idx + 1, len, chunk)),
						),
			channel_zip = dual(
				args => isChannel(args[1]),
				(self, that, options) =>
					options?.concurrent
						? channel_mergeWith(self, {
								other: that,
								onSelfDone: exit1 =>
									Await(exit2 => Effect_suspend(() => Exit_zip(exit1, exit2))),
								onOtherDone: exit2 =>
									Await(exit1 => Effect_suspend(() => Exit_zip(exit1, exit2))),
							})
						: core_stream_flatMap(self, a => channel_map(that, b => [a, b])),
			),
			channel_zipRight = dual(
				args => isChannel(args[1]),
				(self, that, options) =>
					options?.concurrent
						? channel_map(
								channel_zip(self, that, { concurrent: !0 }),
								tuple => tuple[1],
							)
						: core_stream_flatMap(self, () => that),
			),
			ChannelExceptionTypeId = Symbol.for("effect/Channel/ChannelException"),
			ChannelException = error => ({
				_tag: "ChannelException",
				[ChannelExceptionTypeId]: ChannelExceptionTypeId,
				error,
			}),
			isChannelException = u => hasProperty(u, ChannelExceptionTypeId),
			withMinimumLogLevel = dual(2, (self, level) =>
				fiberRefLocally(currentMinimumLogLevel, level)(self),
			),
			replaceLogger = dual(2, (self, that) =>
				layer_flatMap(
					scopedDiscard(
						fiberRefLocallyScopedWith(currentLoggers, HashSet_remove(self)),
					),
					() =>
						scopedDiscard(
							fiberRefLocallyScopedWith(currentLoggers, HashSet_add(that)),
						),
				),
			),
			MergeDecision_Await = Await,
			AbsentValue = Symbol.for("effect/PubSub/AbsentValue"),
			addSubscribers = (subscription, pollers) => subscribers => {
				subscribers.has(subscription) ||
					subscribers.set(subscription, new Set())
				subscribers.get(subscription).add(pollers)
			},
			removeSubscribers = (subscription, pollers) => subscribers => {
				if (!subscribers.has(subscription)) return
				const set = subscribers.get(subscription)
				set.delete(pollers)
				0 === set.size && subscribers.delete(subscription)
			},
			publish = dual(2, (self, value) => self.publish(value))
		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) {
				const subscribers = this.publisherTail.subscribers
				if (0 !== subscribers) {
					this.publisherTail.next = { value, subscribers, next: null }
					this.publisherTail = this.publisherTail.next
					this.publisherIndex += 1
				}
				this.replayBuffer && this.replayBuffer.offer(value)
				return !0
			}
			publishAll(elements) {
				if (0 !== this.publisherTail.subscribers)
					for (const a of elements) this.publish(a)
				else this.replayBuffer && this.replayBuffer.offerAll(elements)
				return esm_Chunk_empty()
			}
			slide() {
				if (this.publisherHead !== this.publisherTail) {
					this.publisherHead = this.publisherHead.next
					this.publisherHead.value = AbsentValue
					this.subscribersIndex += 1
				}
				this.replayBuffer && this.replayBuffer.slide()
			}
			subscribe() {
				this.publisherTail.subscribers += 1
				return 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 empty = !0,
					loop = !0
				for (; loop;)
					if (this.subscriberHead === this.self.publisherTail) loop = !1
					else if (this.subscriberHead.next.value !== AbsentValue) {
						empty = !1
						loop = !1
					} else {
						this.subscriberHead = this.subscriberHead.next
						this.subscriberIndex += 1
					}
				return empty
			}
			size() {
				return this.unsubscribed
					? 0
					: this.self.publisherIndex -
							Math.max(this.subscriberIndex, this.self.subscribersIndex)
			}
			poll(default_) {
				if (this.unsubscribed) return default_
				let loop = !0,
					polled = default_
				for (; loop;)
					if (this.subscriberHead === this.self.publisherTail) loop = !1
					else {
						const elem = this.subscriberHead.next.value
						if (elem !== AbsentValue) {
							polled = elem
							this.subscriberHead.subscribers -= 1
							if (0 === this.subscriberHead.subscribers) {
								this.self.publisherHead = this.self.publisherHead.next
								this.self.publisherHead.value = AbsentValue
								this.self.subscribersIndex += 1
							}
							loop = !1
						}
						this.subscriberHead = this.subscriberHead.next
						this.subscriberIndex += 1
					}
				return polled
			}
			pollUpTo(n) {
				const builder = [],
					default_ = AbsentValue
				let i = 0
				for (; i !== n;) {
					const a = this.poll(default_)
					if (a === default_) i = n
					else {
						builder.push(a)
						i += 1
					}
				}
				return Chunk_fromIterable(builder)
			}
			unsubscribe() {
				if (!this.unsubscribed) {
					this.unsubscribed = !0
					this.self.publisherTail.subscribers -= 1
					for (; this.subscriberHead !== this.self.publisherTail;) {
						if (this.subscriberHead.next.value !== AbsentValue) {
							this.subscriberHead.subscribers -= 1
							if (0 === this.subscriberHead.subscribers) {
								this.self.publisherHead = this.self.publisherHead.next
								this.self.publisherHead.value = AbsentValue
								this.self.subscribersIndex += 1
							}
						}
						this.subscriberHead = this.subscriberHead.next
					}
				}
			}
		}
		class SubscriptionImpl extends Effectable_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 !MutableRef_get(this.shutdownFlag)
			}
			get size() {
				return suspend(() =>
					MutableRef_get(this.shutdownFlag)
						? core_interrupt
						: succeed(this.subscription.size() + this.replayWindow.remaining),
				)
			}
			unsafeSize() {
				return MutableRef_get(this.shutdownFlag)
					? Option_none()
					: Option_some(this.subscription.size() + this.replayWindow.remaining)
			}
			get isFull() {
				return suspend(() =>
					MutableRef_get(this.shutdownFlag)
						? core_interrupt
						: succeed(this.subscription.size() === this.capacity()),
				)
			}
			get isEmpty() {
				return core_map(this.size, size => 0 === size)
			}
			get shutdown() {
				return uninterruptible(
					withFiberRuntime(state => {
						MutableRef_set(this.shutdownFlag, !0)
						return pipe(
							forEachParUnbounded(
								unsafePollAllQueue(this.pollers),
								d => deferredInterruptWith(d, state.id()),
								!1,
							),
							core_zipRight(
								sync(() => {
									this.subscribers.delete(this.subscription)
									this.subscription.unsubscribe()
									this.strategy.unsafeOnPubSubEmptySpace(
										this.pubsub,
										this.subscribers,
									)
								}),
							),
							whenEffect(deferredSucceed(this.shutdownHook, void 0)),
							core_asVoid,
						)
					}),
				)
			}
			get isShutdown() {
				return sync(() => MutableRef_get(this.shutdownFlag))
			}
			get awaitShutdown() {
				return deferredAwait(this.shutdownHook)
			}
			get take() {
				return withFiberRuntime(state => {
					if (MutableRef_get(this.shutdownFlag)) return core_interrupt
					if (this.replayWindow.remaining > 0) {
						const message = this.replayWindow.take()
						return succeed(message)
					}
					const message = MutableQueue_isEmpty(this.pollers)
						? this.subscription.poll(EmptyMutableQueue)
						: EmptyMutableQueue
					if (message === EmptyMutableQueue) {
						const deferred = deferredUnsafeMake(state.id())
						return pipe(
							suspend(() => {
								pipe(this.pollers, offer(deferred))
								pipe(
									this.subscribers,
									addSubscribers(this.subscription, this.pollers),
								)
								this.strategy.unsafeCompletePollers(
									this.pubsub,
									this.subscribers,
									this.subscription,
									this.pollers,
								)
								return MutableRef_get(this.shutdownFlag)
									? core_interrupt
									: deferredAwait(deferred)
							}),
							onInterrupt(() =>
								sync(() => pubsub_unsafeRemove(this.pollers, deferred)),
							),
						)
					}
					this.strategy.unsafeOnPubSubEmptySpace(this.pubsub, this.subscribers)
					return succeed(message)
				})
			}
			get takeAll() {
				return suspend(() => {
					if (MutableRef_get(this.shutdownFlag)) return core_interrupt
					const as = MutableQueue_isEmpty(this.pollers)
						? unsafePollAllSubscription(this.subscription)
						: esm_Chunk_empty()
					this.strategy.unsafeOnPubSubEmptySpace(this.pubsub, this.subscribers)
					return this.replayWindow.remaining > 0
						? succeed(Chunk_appendAll(this.replayWindow.takeAll(), as))
						: succeed(as)
				})
			}
			takeUpTo(max) {
				return suspend(() => {
					if (MutableRef_get(this.shutdownFlag)) return core_interrupt
					let replay
					if (this.replayWindow.remaining >= max) {
						const as = this.replayWindow.takeN(max)
						return succeed(as)
					}
					if (this.replayWindow.remaining > 0) {
						replay = this.replayWindow.takeAll()
						max -= replay.length
					}
					const as = MutableQueue_isEmpty(this.pollers)
						? pubsub_unsafePollN(this.subscription, max)
						: esm_Chunk_empty()
					this.strategy.unsafeOnPubSubEmptySpace(this.pubsub, this.subscribers)
					return succeed(replay ? Chunk_appendAll(replay, as) : as)
				})
			}
			takeBetween(min, max) {
				return suspend(() =>
					pubsub_takeRemainderLoop(this, min, max, esm_Chunk_empty()),
				)
			}
		}
		const pubsub_takeRemainderLoop = (self, min, max, acc) =>
			max < min
				? succeed(acc)
				: pipe(
						self.takeUpTo(max),
						core_flatMap(bs => {
							const remaining = min - bs.length
							return 1 === remaining
								? pipe(
										self.take,
										core_map(b =>
											pipe(acc, Chunk_appendAll(bs), Chunk_append(b)),
										),
									)
								: remaining > 1
									? pipe(
											self.take,
											core_flatMap(b =>
												pubsub_takeRemainderLoop(
													self,
													remaining - 1,
													max - bs.length - 1,
													pipe(acc, Chunk_appendAll(bs), Chunk_append(b)),
												),
											),
										)
									: succeed(pipe(acc, Chunk_appendAll(bs)))
						}),
					)
		class PubSubImpl {
			pubsub
			subscribers
			scope
			shutdownHook
			shutdownFlag
			strategy;
			[EnqueueTypeId] = enqueueVariance;
			[DequeueTypeId] = dequeueVariance
			constructor(
				pubsub,
				subscribers,
				scope,
				shutdownHook,
				shutdownFlag,
				strategy,
			) {
				this.pubsub = pubsub
				this.subscribers = subscribers
				this.scope = scope
				this.shutdownHook = shutdownHook
				this.shutdownFlag = shutdownFlag
				this.strategy = strategy
			}
			capacity() {
				return this.pubsub.capacity
			}
			get size() {
				return suspend(() =>
					MutableRef_get(this.shutdownFlag)
						? core_interrupt
						: sync(() => this.pubsub.size()),
				)
			}
			unsafeSize() {
				return MutableRef_get(this.shutdownFlag)
					? Option_none()
					: Option_some(this.pubsub.size())
			}
			get isFull() {
				return core_map(this.size, size => size === this.capacity())
			}
			get isEmpty() {
				return core_map(this.size, size => 0 === size)
			}
			get awaitShutdown() {
				return deferredAwait(this.shutdownHook)
			}
			get isShutdown() {
				return sync(() => MutableRef_get(this.shutdownFlag))
			}
			get shutdown() {
				return uninterruptible(
					withFiberRuntime(state => {
						pipe(this.shutdownFlag, MutableRef_set(!0))
						return pipe(
							this.scope.close(exitInterrupt(state.id())),
							core_zipRight(this.strategy.shutdown),
							whenEffect(deferredSucceed(this.shutdownHook, void 0)),
							core_asVoid,
						)
					}),
				)
			}
			publish(value) {
				return suspend(() => {
					if (MutableRef_get(this.shutdownFlag)) return core_interrupt
					if (this.pubsub.publish(value)) {
						this.strategy.unsafeCompleteSubscribers(
							this.pubsub,
							this.subscribers,
						)
						return succeed(!0)
					}
					return this.strategy.handleSurplus(
						this.pubsub,
						this.subscribers,
						Chunk_of(value),
						this.shutdownFlag,
					)
				})
			}
			isActive() {
				return !MutableRef_get(this.shutdownFlag)
			}
			unsafeOffer(value) {
				if (MutableRef_get(this.shutdownFlag)) return !1
				if (this.pubsub.publish(value)) {
					this.strategy.unsafeCompleteSubscribers(this.pubsub, this.subscribers)
					return !0
				}
				return !1
			}
			publishAll(elements) {
				return suspend(() => {
					if (MutableRef_get(this.shutdownFlag)) return core_interrupt
					const surplus = unsafePublishAll(this.pubsub, elements)
					this.strategy.unsafeCompleteSubscribers(this.pubsub, this.subscribers)
					return Chunk_isEmpty(surplus)
						? succeed(!0)
						: this.strategy.handleSurplus(
								this.pubsub,
								this.subscribers,
								surplus,
								this.shutdownFlag,
							)
				})
			}
			get subscribe() {
				const acquire = core_tap(
					fiberRuntime_all([
						this.scope.fork(executionStrategy_sequential),
						((pubsub = this.pubsub),
						(subscribers = this.subscribers),
						(strategy = this.strategy),
						core_map(deferredMake(), deferred =>
							((
								pubsub,
								subscribers,
								subscription,
								pollers,
								shutdownHook,
								shutdownFlag,
								strategy,
							) =>
								new SubscriptionImpl(
									pubsub,
									subscribers,
									subscription,
									pollers,
									shutdownHook,
									shutdownFlag,
									strategy,
									pubsub.replayWindow(),
								))(
								pubsub,
								subscribers,
								pubsub.subscribe(),
								unbounded(),
								deferred,
								MutableRef_make(!1),
								strategy,
							),
						)),
					]),
					tuple => tuple[0].addFinalizer(() => tuple[1].shutdown),
				)
				var pubsub, subscribers, strategy
				return core_map(
					fiberRuntime_acquireRelease(acquire, (tuple, exit) =>
						tuple[0].close(exit),
					),
					tuple => tuple[1],
				)
			}
			offer(value) {
				return this.publish(value)
			}
			offerAll(elements) {
				return this.publishAll(elements)
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const pubsub_unsafeCompleteDeferred = (deferred, a) => {
				deferredUnsafeDone(deferred, succeed(a))
			},
			pubsub_unsafeOfferAll = (queue, as) => pipe(queue, offerAll(as)),
			unsafePollAllQueue = queue =>
				pipe(queue, pollUpTo(Number.POSITIVE_INFINITY)),
			unsafePollAllSubscription = subscription =>
				subscription.pollUpTo(Number.POSITIVE_INFINITY),
			pubsub_unsafePollN = (subscription, max) => subscription.pollUpTo(max),
			unsafePublishAll = (pubsub, as) => pubsub.publishAll(as),
			pubsub_unsafeRemove = (queue, value) => {
				pubsub_unsafeOfferAll(
					queue,
					pipe(
						unsafePollAllQueue(queue),
						Chunk_filter(elem => elem !== value),
					),
				)
			}
		class pubsub_DroppingStrategy {
			get shutdown() {
				return core_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)
			}
		}
		const unsafeStrategyCompletePollers = (
				strategy,
				pubsub,
				subscribers,
				subscription,
				pollers,
			) => {
				let keepPolling = !0
				for (; keepPolling && !subscription.isEmpty();) {
					const poller = pipe(pollers, MutableQueue_poll(EmptyMutableQueue))
					if (poller === EmptyMutableQueue) {
						pipe(subscribers, removeSubscribers(subscription, pollers))
						MutableQueue_isEmpty(pollers)
							? (keepPolling = !1)
							: pipe(subscribers, addSubscribers(subscription, pollers))
					} else {
						const pollResult = subscription.poll(EmptyMutableQueue)
						if (pollResult === EmptyMutableQueue)
							pubsub_unsafeOfferAll(
								pollers,
								pipe(unsafePollAllQueue(pollers), Chunk_prepend(poller)),
							)
						else {
							pubsub_unsafeCompleteDeferred(poller, pollResult)
							strategy.unsafeOnPubSubEmptySpace(pubsub, subscribers)
						}
					}
				}
			},
			unsafeStrategyCompleteSubscribers = (strategy, pubsub, subscribers) => {
				for (const [subscription, pollersSet] of subscribers)
					for (const pollers of pollersSet)
						strategy.unsafeCompletePollers(
							pubsub,
							subscribers,
							subscription,
							pollers,
						)
			}
		class ReplayBuffer {
			capacity
			constructor(capacity) {
				this.capacity = capacity
			}
			head = { value: AbsentValue, next: null }
			tail = this.head
			size = 0
			index = 0
			slide() {
				this.index++
			}
			offer(a) {
				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)
					: (this.size += 1)
			}
			offerAll(as) {
				for (const a of as) 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() {
				for (; this.index < this.buffer.index;) {
					this.head = this.head.next
					this.index++
				}
			}
			take() {
				if (0 === this.remaining) return
				this.index < this.buffer.index && this.fastForward()
				this.remaining--
				const value = this.head.value
				this.head = this.head.next
				return value
			}
			takeN(n) {
				if (0 === this.remaining) return esm_Chunk_empty()
				this.index < this.buffer.index && this.fastForward()
				const len = Math.min(n, this.remaining),
					items = new Array(len)
				for (let i = 0; i < len; i++) {
					const value = this.head.value
					this.head = this.head.next
					items[i] = value
				}
				this.remaining -= len
				return unsafeFromArray(items)
			}
			takeAll() {
				return this.takeN(this.remaining)
			}
		}
		const emptyReplayWindow = {
				remaining: 0,
				take: () => {},
				takeN: () => esm_Chunk_empty(),
				takeAll: () => esm_Chunk_empty(),
			},
			PubSub_unbounded = options =>
				suspend(() => {
					const pubsub = (options =>
						new UnboundedPubSub(
							options?.replay ? new ReplayBuffer(options.replay) : void 0,
						))(options)
					return ((pubsub, strategy) =>
						core_flatMap(fiberRuntime_scopeMake(), scope =>
							core_map(deferredMake(), deferred =>
								((
									pubsub,
									subscribers,
									scope,
									shutdownHook,
									shutdownFlag,
									strategy,
								) =>
									new PubSubImpl(
										pubsub,
										subscribers,
										scope,
										shutdownHook,
										shutdownFlag,
										strategy,
									))(
									pubsub,
									new Map(),
									scope,
									deferred,
									MutableRef_make(!1),
									strategy,
								),
							),
						))(pubsub, new pubsub_DroppingStrategy())
				}),
			PubSub_shutdown = self => self.shutdown,
			PubSub_publish = publish,
			PubSub_subscribe = self => self.subscribe,
			Runtime_runSync = unsafeRunSync,
			Left = { _tag: "Left" },
			Right = { _tag: "Right" },
			Both = { _tag: "Both" },
			haltStrategy_Either = { _tag: "Either" },
			StreamHaltStrategy_Both = Both,
			sink_SinkTypeId = Symbol.for("effect/Sink"),
			sink_sinkVariance = {
				_A: _ => _,
				_In: _ => _,
				_L: _ => _,
				_E: _ => _,
				_R: _ => _,
			}
		class SinkImpl {
			channel;
			[sink_SinkTypeId] = sink_sinkVariance
			constructor(channel) {
				this.channel = channel
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const sink_drain = new SinkImpl(drain(identityChannel())),
			toChannel = self =>
				Effect_isEffect(self)
					? toChannel(new SinkImpl(core_stream_fromEffect(self)))
					: self.channel
		Symbol.iterator
		const TakeTypeId = Symbol.for("effect/Take"),
			takeVariance = { _A: _ => _, _E: _ => _ }
		class TakeImpl {
			exit;
			[TakeTypeId] = takeVariance
			constructor(exit) {
				this.exit = exit
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const take_chunk = chunk => new TakeImpl(Exit_succeed(chunk)),
			take_end = new TakeImpl(Exit_fail(Option_none())),
			take_failCause = cause =>
				new TakeImpl(Exit_failCause(pipe(cause, Cause_map(Option_some)))),
			take_of = value => new TakeImpl(Exit_succeed(Chunk_of(value))),
			stream_StreamTypeId = Symbol.for("effect/Stream"),
			streamVariance = { _R: _ => _, _E: _ => _, _A: _ => _ }
		class StreamImpl {
			channel;
			[stream_StreamTypeId] = streamVariance
			constructor(channel) {
				this.channel = channel
			}
			pipe() {
				return pipeArguments(this, arguments)
			}
		}
		const isStream = u =>
				hasProperty(u, stream_StreamTypeId) || Effect_isEffect(u),
			asyncPush = (register, options) =>
				Effect_acquireRelease(
					(options => {
						return "unbounded" === options?.bufferSize ||
							(void 0 === options?.bufferSize && void 0 === options?.strategy)
							? Queue_unbounded()
							: "sliding" === options?.strategy
								? (requestedCapacity =>
										pipe(
											sync(() => bounded(requestedCapacity)),
											core_flatMap(queue =>
												queue_make(
													backingQueueFromMutableQueue(queue),
													new SlidingStrategy(),
												),
											),
										))(options.bufferSize ?? 16)
								: ((requestedCapacity = options?.bufferSize ?? 16),
									pipe(
										sync(() => bounded(requestedCapacity)),
										core_flatMap(queue =>
											queue_make(
												backingQueueFromMutableQueue(queue),
												droppingStrategy(),
											),
										),
									))
						var requestedCapacity
					})(options),
					Queue_shutdown,
				).pipe(
					Effect_tap(queue =>
						getWith(FiberRef_currentScheduler, scheduler =>
							register(
								((queue, scheduler) => {
									let finished = !1,
										buffer = [],
										running = !1
									function array(items) {
										if (finished) return !1
										if (items.length <= 5e4) buffer.push.apply(buffer, items)
										else
											for (let i = 0; i < items.length; i++)
												buffer.push(items[0])
										if (!running) {
											running = !0
											scheduler.scheduleTask(flush, 0)
										}
										return !0
									}
									function flush() {
										running = !1
										if (buffer.length > 0) {
											queue.unsafeOffer(buffer)
											buffer = []
										}
									}
									function done(exit) {
										if (!finished) {
											finished = !0
											"Success" === exit._tag && buffer.push(exit.value)
											flush()
											queue.unsafeOffer(
												"Success" === exit._tag ? Exit_void_ : exit,
											)
										}
									}
									return {
										single(value) {
											if (finished) return !1
											buffer.push(value)
											if (!running) {
												running = !0
												scheduler.scheduleTask(flush, 0)
											}
											return !0
										},
										array,
										chunk: chunk => array(toReadonlyArray(chunk)),
										done,
										end() {
											if (!finished) {
												finished = !0
												flush()
												queue.unsafeOffer(Exit_void_)
											}
										},
										halt: cause => done(Exit_failCause(cause)),
										fail: error => done(Exit_fail(error)),
										die: defect => done(Exit_die(defect)),
										dieMessage: message => done(Exit_die(new Error(message))),
									}
								})(queue, scheduler),
							),
						),
					),
					Effect_map(queue => {
						const loop = core_stream_flatMap(Queue_take(queue), item =>
							isExit(item)
								? Exit_isSuccess(item)
									? core_stream_void_
									: core_stream_failCause(item.cause)
								: channel_zipRight(write(unsafeFromArray(item)), loop),
						)
						return loop
					}),
					channel_unwrapScoped,
					stream_fromChannel,
				),
			stream_catchAllCause = dual(
				2,
				(self, f) =>
					new StreamImpl(
						pipe(
							stream_toChannel(self),
							core_stream_catchAllCause(cause => stream_toChannel(f(cause))),
						),
					),
			),
			changesWith = dual(2, (self, f) => {
				const writer = last =>
					readWithCause({
						onInput: input => {
							const [newLast, newChunk] = Chunk_reduce(
								input,
								[last, esm_Chunk_empty()],
								([option, outputs], output) =>
									Option_isSome(option) && f(option.value, output)
										? [Option_some(output), outputs]
										: [
												Option_some(output),
												pipe(outputs, Chunk_append(output)),
											],
							)
							return Chunk_isEmpty(newChunk)
								? writer(newLast)
								: core_stream_flatMap(write(newChunk), () => writer(newLast))
						},
						onFailure: core_stream_failCause,
						onDone: () => core_stream_void_,
					})
				return new StreamImpl(
					pipe(stream_toChannel(self), pipeTo(writer(Option_none()))),
				)
			}),
			stream_concat = dual(
				2,
				(self, that) =>
					new StreamImpl(
						pipe(
							stream_toChannel(self),
							channel_zipRight(stream_toChannel(that)),
						),
					),
			),
			stream_drop = dual(2, (self, n) => {
				const loop = r =>
					readWith({
						onInput: input => {
							const dropped = pipe(input, Chunk_drop(r)),
								leftover = Math.max(0, r - input.length)
							return Chunk_isEmpty(input) || leftover > 0
								? loop(leftover)
								: pipe(write(dropped), channel_zipRight(identityChannel()))
						},
						onFailure: core_stream_fail,
						onDone: () => core_stream_void_,
					})
				return new StreamImpl(
					pipe(stream_toChannel(self), pipeToOrFail(loop(n))),
				)
			}),
			stream_empty = new StreamImpl(core_stream_void_),
			stream_ensuring = dual(
				2,
				(self, finalizer) =>
					new StreamImpl(
						pipe(stream_toChannel(self), channel_ensuring(finalizer)),
					),
			),
			stream_filter = dual(2, (self, predicate) =>
				mapChunks(self, Chunk_filter(predicate)),
			),
			stream_filterMap = dual(2, (self, pf) =>
				mapChunks(self, Chunk_filterMap(pf)),
			),
			stream_flatMap = dual(
				args => isStream(args[0]),
				(self, f, options) => {
					const bufferSize = options?.bufferSize ?? 16
					return options?.switch
						? matchConcurrency(
								options?.concurrency,
								() => flatMapParSwitchBuffer(self, 1, bufferSize, f),
								n => flatMapParSwitchBuffer(self, n, bufferSize, f),
							)
						: matchConcurrency(
								options?.concurrency,
								() =>
									new StreamImpl(
										concatMap(stream_toChannel(self), as =>
											pipe(
												as,
												Chunk_map(a => stream_toChannel(f(a))),
												Chunk_reduce(core_stream_void_, (left, right) =>
													pipe(left, channel_zipRight(right)),
												),
											),
										),
									),
								_ =>
									new StreamImpl(
										pipe(
											stream_toChannel(self),
											concatMap(writeChunk),
											mergeMap(out => stream_toChannel(f(out)), options),
										),
									),
							)
				},
			),
			matchConcurrency = (concurrency, sequential, bounded) => {
				switch (concurrency) {
					case void 0:
						return sequential()
					case "unbounded":
						return bounded(Number.MAX_SAFE_INTEGER)
					default:
						return concurrency > 1 ? bounded(concurrency) : sequential()
				}
			},
			flatMapParSwitchBuffer = dual(
				4,
				(self, n, bufferSize, f) =>
					new StreamImpl(
						pipe(
							stream_toChannel(self),
							concatMap(writeChunk),
							mergeMap(out => stream_toChannel(f(out)), {
								concurrency: n,
								mergeStrategy: BufferSliding(),
								bufferSize,
							}),
						),
					),
			),
			stream_flatten = dual(
				args => isStream(args[0]),
				(self, options) => stream_flatMap(self, identity, options),
			),
			flattenTake = self =>
				(self => {
					const flatten = readWithCause({
						onInput: chunks =>
							core_stream_flatMap(writeChunk(chunks), () => flatten),
						onFailure: core_stream_failCause,
						onDone: () => core_stream_void_,
					})
					return new StreamImpl(pipe(stream_toChannel(self), pipeTo(flatten)))
				})(
					(self => {
						const process = readWithCause({
							onInput: chunk =>
								((chunk, cont) => {
									const [toEmit, rest] = pipe(
											chunk,
											Chunk_splitWhere(exit => !Exit_isSuccess(exit)),
										),
										next = pipe(
											Chunk_head(rest),
											Option_match({
												onNone: () => cont,
												onSome: Exit_match({
													onFailure: cause =>
														Option_match(
															(self =>
																cause_match(self, {
																	onEmpty: Option_some(cause_empty),
																	onFail: Option_map(fail),
																	onDie: defect => Option_some(die(defect)),
																	onInterrupt: fiberId =>
																		Option_some(interrupt(fiberId)),
																	onSequential: mergeWith(sequential),
																	onParallel: mergeWith(parallel),
																}))(cause),
															{
																onNone: () => core_stream_void_,
																onSome: core_stream_failCause,
															},
														),
													onSuccess: () => core_stream_void_,
												}),
											}),
										)
									return pipe(
										write(
											pipe(
												toEmit,
												Chunk_filterMap(exit =>
													Exit_isSuccess(exit)
														? Option_some(exit.value)
														: Option_none(),
												),
											),
										),
										core_stream_flatMap(() => next),
									)
								})(chunk, process),
							onFailure: cause => core_stream_failCause(cause),
							onDone: () => core_stream_void_,
						})
						return new StreamImpl(pipe(stream_toChannel(self), pipeTo(process)))
					})(
						pipe(
							self,
							stream_map(take => take.exit),
						),
					),
				),
			stream_fromChannel = channel => new StreamImpl(channel),
			stream_toChannel = stream => {
				if ("channel" in stream) return stream.channel
				if (Effect_isEffect(stream))
					return stream_toChannel(stream_fromEffect(stream))
				throw new TypeError("Expected a Stream.")
			},
			fromChunk = chunk =>
				new StreamImpl(Chunk_isEmpty(chunk) ? core_stream_void_ : write(chunk)),
			stream_fromEffect = effect =>
				pipe(effect, Effect_mapError(Option_some), fromEffectOption),
			fromEffectOption = effect =>
				new StreamImpl(
					channel_unwrap(
						Effect_match(effect, {
							onFailure: Option_match({
								onNone: () => core_stream_void_,
								onSome: core_stream_fail,
							}),
							onSuccess: a => write(Chunk_of(a)),
						}),
					),
				),
			stream_fromPubSub = (pubsub, options) => {
				const maxChunkSize = options?.maxChunkSize ?? 4096
				if (options?.scoped) {
					const effect = Effect_map(PubSub_subscribe(pubsub), queue =>
						stream_fromQueue(queue, { maxChunkSize, shutdown: !0 }),
					)
					return options.shutdown
						? Effect_map(effect, stream_ensuring(PubSub_shutdown(pubsub)))
						: effect
				}
				const stream = stream_flatMap(
					stream_scoped(PubSub_subscribe(pubsub)),
					queue => stream_fromQueue(queue, { maxChunkSize }),
				)
				return options?.shutdown
					? stream_ensuring(stream, PubSub_shutdown(pubsub))
					: stream
			},
			stream_fromIterable = iterable =>
				stream_suspend(() =>
					isChunk(iterable)
						? fromChunk(iterable)
						: fromIteratorSucceed(iterable[Symbol.iterator]()),
				),
			fromIteratorSucceed = (iterator, maxChunkSize = 4096) =>
				pipe(
					Effect_sync(() => {
						let builder = []
						const loop = iterator =>
							pipe(
								Effect_sync(() => {
									let next = iterator.next()
									if (1 === maxChunkSize)
										return next.done
											? core_stream_void_
											: pipe(
													write(Chunk_of(next.value)),
													core_stream_flatMap(() => loop(iterator)),
												)
									builder = []
									let count = 0
									for (; !1 === next.done;) {
										builder.push(next.value)
										count += 1
										if (count >= maxChunkSize) break
										next = iterator.next()
									}
									return count > 0
										? pipe(
												write(unsafeFromArray(builder)),
												core_stream_flatMap(() => loop(iterator)),
											)
										: core_stream_void_
								}),
								channel_unwrap,
							)
						return new StreamImpl(loop(iterator))
					}),
					stream_unwrap,
				),
			stream_fromQueue = (queue, options) =>
				pipe(
					Queue_takeBetween(queue, 1, options?.maxChunkSize ?? 4096),
					Effect_catchAllCause(cause =>
						pipe(
							(self => self.isShutdown)(queue),
							Effect_flatMap(isShutdown =>
								isShutdown && Cause_isInterrupted(cause)
									? Effect_fail(Option_none())
									: (cause =>
											Effect_mapError(Effect_failCause(cause), Option_some))(
											cause,
										),
							),
						),
					),
					repeatEffectChunkOption,
					options?.shutdown ? stream_ensuring(Queue_shutdown(queue)) : identity,
				),
			stream_make = (...as) => stream_fromIterable(as),
			stream_map = dual(
				2,
				(self, f) =>
					new StreamImpl(pipe(stream_toChannel(self), mapOut(Chunk_map(f)))),
			),
			stream_mapAccum = dual(3, (self, s, f) => {
				const accumulator = s =>
					readWith({
						onInput: input => {
							const [nextS, chunk] = Chunk_mapAccum(input, s, f)
							return core_stream_flatMap(write(chunk), () => accumulator(nextS))
						},
						onFailure: core_stream_fail,
						onDone: () => core_stream_void_,
					})
				return new StreamImpl(
					pipe(stream_toChannel(self), pipeTo(accumulator(s))),
				)
			}),
			mapChunks = dual(
				2,
				(self, f) => new StreamImpl(pipe(stream_toChannel(self), mapOut(f))),
			),
			mapEffectSequential = dual(2, (self, f) => {
				const loop = iterator => {
					const next = iterator.next()
					if (next.done)
						return readWithCause({
							onInput: elem => loop(elem[Symbol.iterator]()),
							onFailure: core_stream_failCause,
							onDone: core_stream_succeed,
						})
					{
						const value = next.value
						return channel_unwrap(
							Effect_map(f(value), a2 =>
								core_stream_flatMap(write(Chunk_of(a2)), () => loop(iterator)),
							),
						)
					}
				}
				return new StreamImpl(
					pipe(
						stream_toChannel(self),
						pipeTo(
							core_stream_suspend(() =>
								loop(esm_Chunk_empty()[Symbol.iterator]()),
							),
						),
					),
				)
			}),
			mapEffectPar = dual(
				3,
				(self, n, f) =>
					new StreamImpl(
						pipe(
							stream_toChannel(self),
							concatMap(writeChunk),
							mapOutEffectPar(f, n),
							mapOut(Chunk_of),
						),
					),
			),
			stream_merge = dual(
				args => isStream(args[1]),
				(self, that, options) =>
					stream_mergeWith(self, that, {
						onSelf: identity,
						onOther: identity,
						haltStrategy: options?.haltStrategy,
					}),
			),
			stream_mergeAll = dual(
				args => Symbol.iterator in args[0],
				(streams, options) =>
					stream_flatten(stream_fromIterable(streams), options),
			),
			stream_mergeWith = dual(3, (self, other, options) => {
				const strategy = options.haltStrategy
						? (input => {
								switch (input) {
									case "left":
										return Left
									case "right":
										return Right
									case "both":
										return Both
									case "either":
										return haltStrategy_Either
									default:
										return input
								}
							})(options.haltStrategy)
						: StreamHaltStrategy_Both,
					handler = terminate => exit =>
						terminate || !Exit_isSuccess(exit)
							? (effect => {
									const op = Object.create(mergeDecision_proto)
									op._tag = "Done"
									op.effect = effect
									return op
								})(Effect_suspend(() => exit))
							: MergeDecision_Await(exit => Effect_suspend(() => exit))
				return new StreamImpl(
					channel_mergeWith(
						stream_toChannel(stream_map(self, options.onSelf)),
						{
							other: stream_toChannel(stream_map(other, options.onOther)),
							onSelfDone: handler(
								"Either" === strategy._tag || "Left" === strategy._tag,
							),
							onOtherDone: handler(
								"Either" === strategy._tag || "Right" === strategy._tag,
							),
						},
					),
				)
			}),
			repeatEffectChunkOption = effect =>
				unfoldChunkEffect(effect, effect =>
					pipe(
						Effect_map(effect, chunk => Option_some([chunk, effect])),
						Effect_catchAll(
							Option_match({
								onNone: () => Effect_succeed(Option_none()),
								onSome: Effect_fail,
							}),
						),
					),
				),
			stream_run = dual(2, (self, sink) =>
				stream_toChannel(self).pipe(pipeToOrFail(toChannel(sink)), runDrain),
			),
			runForEach = dual(2, (self, f) =>
				stream_run(
					self,
					(f => {
						const process = readWithCause({
							onInput: input =>
								pipe(
									core_stream_fromEffect(
										Effect_forEach(input, v => f(v), { discard: !0 }),
									),
									core_stream_flatMap(() => process),
								),
							onFailure: core_stream_failCause,
							onDone: () => core_stream_void_,
						})
						return new SinkImpl(process)
					})(f),
				),
			),
			stream_scoped = effect =>
				new StreamImpl(
					channel_ensuring(
						channel_scoped(pipe(effect, Effect_map(Chunk_of))),
						_void,
					),
				),
			stream_suspend = stream =>
				new StreamImpl(core_stream_suspend(() => stream_toChannel(stream()))),
			stream_tap = dual(2, (self, f) =>
				mapEffectSequential(self, a => Effect_as(f(a), a)),
			),
			unfoldChunkEffect = (s, f) =>
				stream_suspend(() => {
					const loop = s =>
						channel_unwrap(
							Effect_map(
								f(s),
								Option_match({
									onNone: () => core_stream_void_,
									onSome: ([chunk, s]) =>
										core_stream_flatMap(write(chunk), () => loop(s)),
								}),
							),
						)
					return new StreamImpl(loop(s))
				}),
			stream_unwrap = effect => stream_flatten(stream_fromEffect(effect)),
			stream_unwrapScoped = effect => stream_flatten(stream_scoped(effect)),
			GroupByTypeId = Symbol.for("effect/GroupBy"),
			groupByVariance = { _R: _ => _, _E: _ => _, _K: _ => _, _V: _ => _ },
			groupBy_evaluate = dual(
				args => (u => hasProperty(u, GroupByTypeId))(args[0]),
				(self, f, options) =>
					stream_flatMap(
						self.grouped,
						([key, queue]) =>
							f(key, flattenTake(stream_fromQueue(queue, { shutdown: !0 }))),
						{ concurrency: "unbounded", bufferSize: options?.bufferSize ?? 16 },
					),
			),
			groupBy_make = grouped => ({
				[GroupByTypeId]: groupByVariance,
				pipe() {
					return pipeArguments(this, arguments)
				},
				grouped,
			}),
			mapEffectOptions = dual(
				args => "function" != typeof args[0],
				(self, f, options) =>
					options?.key
						? groupBy_evaluate(
								groupByKey(self, options.key, {
									bufferSize: options.bufferSize,
								}),
								(_, s) => mapEffectSequential(s, f),
							)
						: matchConcurrency(
								options?.concurrency,
								() => mapEffectSequential(self, f),
								n =>
									options?.unordered
										? stream_flatMap(self, a => stream_fromEffect(f(a)), {
												concurrency: n,
											})
										: mapEffectPar(self, n, f),
							),
			),
			groupByKey = dual(
				args => "function" != typeof args[0],
				(self, f, options) => {
					const loop = (map, outerQueue) =>
						readWithCause({
							onInput: input =>
								core_stream_flatMap(
									core_stream_fromEffect(
										Effect_forEach(
											groupByIterable(input, f),
											([key, values]) => {
												const innerQueue = map.get(key)
												return void 0 === innerQueue
													? pipe(
															Queue_bounded(options?.bufferSize ?? 16),
															Effect_flatMap(innerQueue =>
																pipe(
																	Effect_sync(() => {
																		map.set(key, innerQueue)
																	}),
																	Effect_zipRight(
																		Queue_offer(
																			outerQueue,
																			take_of([key, innerQueue]),
																		),
																	),
																	Effect_zipRight(
																		pipe(
																			Queue_offer(
																				innerQueue,
																				take_chunk(values),
																			),
																			Effect_catchSomeCause(cause =>
																				Cause_isInterruptedOnly(cause)
																					? Option_some(_void)
																					: Option_none(),
																			),
																		),
																	),
																),
															),
														)
													: Effect_catchSomeCause(
															Queue_offer(innerQueue, take_chunk(values)),
															cause =>
																Cause_isInterruptedOnly(cause)
																	? Option_some(_void)
																	: Option_none(),
														)
											},
											{ discard: !0 },
										),
									),
									() => loop(map, outerQueue),
								),
							onFailure: cause =>
								core_stream_fromEffect(
									Queue_offer(outerQueue, take_failCause(cause)),
								),
							onDone: () =>
								core_stream_fromEffect(
									pipe(
										Effect_forEach(
											map.entries(),
											([_, innerQueue]) =>
												pipe(
													Queue_offer(innerQueue, take_end),
													Effect_catchSomeCause(cause =>
														Cause_isInterruptedOnly(cause)
															? Option_some(_void)
															: Option_none(),
													),
												),
											{ discard: !0 },
										),
										Effect_zipRight(Queue_offer(outerQueue, take_end)),
									),
								),
						})
					return groupBy_make(
						(f =>
							stream_flatten(
								(f =>
									new StreamImpl(
										channel_scopedWith(scope =>
											f(scope).pipe(Effect_map(Chunk_of)),
										),
									))(scope => f(scope)),
							))(scope =>
							Effect_gen(function* () {
								const map = new Map(),
									queue = yield* Queue_unbounded()
								yield* Scope_addFinalizer(scope, Queue_shutdown(queue))
								return yield* stream_toChannel(self).pipe(
									pipeTo(loop(map, queue)),
									drain,
									runIn(scope),
									Effect_forkIn(scope),
									Effect_as(
										flattenTake(stream_fromQueue(queue, { shutdown: !0 })),
									),
								)
							}),
						),
					)
				},
			),
			groupByIterable = dual(2, (iterable, f) => {
				const builder = [],
					iterator = iterable[Symbol.iterator](),
					map = new Map()
				let next
				for (; (next = iterator.next()) && !next.done;) {
					const value = next.value,
						key = f(value)
					if (map.has(key)) map.get(key).push(value)
					else {
						const innerBuilder = [value]
						builder.push([key, innerBuilder])
						map.set(key, innerBuilder)
					}
				}
				return unsafeFromArray(
					builder.map(tuple => [tuple[0], unsafeFromArray(tuple[1])]),
				)
			}),
			Stream_catchAllCause = stream_catchAllCause,
			Stream_changes = self =>
				pipe(
					self,
					changesWith((x, y) => equals(y)(x)),
				),
			Stream_concat = stream_concat,
			Stream_drop = stream_drop,
			Stream_empty = stream_empty,
			Stream_filter = stream_filter,
			Stream_filterMap = stream_filterMap,
			Stream_flatMap = stream_flatMap,
			Stream_flattenTake = flattenTake,
			Stream_fromPubSub = stream_fromPubSub,
			Stream_fromQueue = stream_fromQueue,
			Stream_make = stream_make,
			Stream_map = stream_map,
			Stream_mapEffect = mapEffectOptions,
			Stream_merge = stream_merge,
			Stream_mergeAll = stream_mergeAll,
			Stream_runForEach = runForEach,
			Stream_succeed = value => fromChunk(Chunk_of(value)),
			Stream_tap = stream_tap,
			Stream_unwrap = stream_unwrap,
			Stream_unwrapScoped = stream_unwrapScoped,
			Stream_zipWithPrevious = self =>
				pipe(
					self,
					stream_mapAccum(Option_none(), (prev, curr) => [
						Option_some(curr),
						[prev, curr],
					]),
				),
			Stream_fromEventListener = (target, type, options) =>
				asyncPush(
					emit =>
						Effect_acquireRelease(
							Effect_sync(() =>
								target.addEventListener(type, emit.single, options),
							),
							() =>
								Effect_sync(() =>
									target.removeEventListener(type, emit.single, options),
								),
						),
					{
						bufferSize:
							"object" == typeof options ? options.bufferSize : void 0,
					},
				),
			Struct_entries = obj => Object.entries(obj),
			mapObject = f => o =>
				pipe(Struct_entries(o), Array_map(f), Object.fromEntries)
		__webpack_require__.dn(mapObject)
		const makeGetter = c =>
				pipe(
					c,
					mapObject(([x]) => [x, Effect_sync(() => c[x])]),
				),
			Subscribable_TypeId = Symbol.for("effect/Subscribable"),
			SubscriptionRefTypeId = Symbol.for("effect/SubscriptionRef"),
			subscriptionRefVariance = { _A: _ => _ }
		class SubscriptionRefImpl extends Effectable_Class {
			ref
			pubsub
			semaphore;
			[Readable_TypeId] = Readable_TypeId;
			[Subscribable_TypeId] = Subscribable_TypeId;
			[Ref_RefTypeId] = refVariance;
			[SynchronizedRefTypeId] = synchronizedVariance;
			[SubscriptionRefTypeId] = subscriptionRefVariance
			constructor(ref, pubsub, semaphore) {
				super()
				this.ref = ref
				this.pubsub = pubsub
				this.semaphore = semaphore
				this.get = Ref_get(this.ref)
			}
			commit() {
				return this.get
			}
			get;
			get changes() {
				return pipe(
					Ref_get(this.ref),
					Effect_flatMap(a =>
						Effect_map(stream_fromPubSub(this.pubsub, { scoped: !0 }), s =>
							stream_concat(stream_make(a), s),
						),
					),
					this.semaphore.withPermits(1),
					stream_unwrapScoped,
				)
			}
			modify(f) {
				return this.modifyEffect(a => Effect_succeed(f(a)))
			}
			modifyEffect(f) {
				return pipe(
					Ref_get(this.ref),
					Effect_flatMap(f),
					Effect_flatMap(([b, a]) =>
						pipe(
							Ref_set(this.ref, a),
							Effect_as(b),
							Effect_zipLeft(PubSub_publish(this.pubsub, a)),
						),
					),
					this.semaphore.withPermits(1),
				)
			}
		}
		const SubscriptionRef_make = value =>
				pipe(
					Effect_all([
						PubSub_unbounded(),
						Ref_make(value),
						Effect_makeSemaphore(1),
					]),
					Effect_map(
						([pubsub, ref, semaphore]) =>
							new SubscriptionRefImpl(ref, pubsub, semaphore),
					),
				),
			SubscriptionRef_set = dual(2, (self, value) =>
				pipe(
					Ref_set(self.ref, value),
					Effect_zipLeft(PubSub_publish(self.pubsub, value)),
					self.semaphore.withPermits(1),
				),
			),
			makePageState = mapObject(([k, v]) => [
				k,
				{ ele: Option_none(), read: v },
			]),
			richTypes = { Date: !0, RegExp: !0, String: !0, Number: !0 }
		function dist_diff(obj, newObj, options = { cyclesFix: !0 }, _stack = []) {
			let diffs = []
			const isObjArray = Array.isArray(obj)
			for (const key in obj) {
				const objKey = obj[key],
					path = isObjArray ? +key : key
				if (!(key in newObj)) {
					diffs.push({ type: "REMOVE", path: [path], oldValue: obj[key] })
					continue
				}
				const newObjKey = newObj[key],
					areCompatibleObjects =
						"object" == typeof objKey &&
						"object" == typeof newObjKey &&
						Array.isArray(objKey) === Array.isArray(newObjKey)
				!(objKey && newObjKey && areCompatibleObjects) ||
				richTypes[Object.getPrototypeOf(objKey)?.constructor?.name] ||
				(options.cyclesFix && _stack.includes(objKey))
					? objKey === newObjKey ||
						(Number.isNaN(objKey) && Number.isNaN(newObjKey)) ||
						(areCompatibleObjects &&
							(isNaN(objKey)
								? objKey + "" == newObjKey + ""
								: +objKey == +newObjKey)) ||
						diffs.push({
							path: [path],
							type: "CHANGE",
							value: newObjKey,
							oldValue: objKey,
						})
					: diffs.push.apply(
							diffs,
							dist_diff(
								objKey,
								newObjKey,
								options,
								options.cyclesFix ? _stack.concat([objKey]) : [],
							).map(difference => {
								difference.path.unshift(path)
								return difference
							}),
						)
			}
			const isNewObjArray = Array.isArray(newObj)
			for (const key in newObj)
				key in obj ||
					diffs.push({
						type: "CREATE",
						path: [isNewObjArray ? +key : key],
						value: newObj[key],
					})
			return diffs
		}
		const configDiff = (oldValue, value) =>
			"object" == typeof oldValue &&
			null !== oldValue &&
			"object" == typeof value &&
			null !== value
				? dist_diff(oldValue, value)
				: [{ type: "CHANGE", path: [], oldValue, value }]
		__webpack_require__.dn(configDiff)
		const external_astring_namespaceObject = astring,
			external_jsep_namespaceObject = jsep
		var external_jsep_default = __webpack_require__.n(
			external_jsep_namespaceObject,
		)
		const fycKey = key => `FYC_${key}`
		__webpack_require__.dn(fycKey)
		const indirectConfig = (key, defaultValue, toConfig, toGm) =>
			pipe({ gmKey: key, defaultValue, toGm }, ctx => ({
				...ctx,
				getValue: pipe(
					Effect_promise(() => GM.getValue(key)),
					Effect_map(x => (void 0 !== x ? toConfig(x) : defaultValue)),
				),
			}))
		__webpack_require__.dn(indirectConfig)
		const languages = ["FYC_EN", "FYC_JA", "FYC_ZH_CN"],
			simpleConfig = (key, defaultValue) => ({
				gmKey: key,
				getValue: Effect_promise(async () => GM.getValue(key, defaultValue)),
				defaultValue,
				toGm: identity,
			})
		__webpack_require__.dn(simpleConfig)
		const stringsArgs = [
				[],
				x =>
					pipe(String_split(x, /\r\n|\n/), Array_filter(not(String_isEmpty))),
				join("\n"),
			],
			sc = (k, d) => simpleConfig(fycKey(k), d),
			ic = (k, d, c, g) => indirectConfig(fycKey(k), d, c, g),
			defaultGMConfig = pipe(
				{
					lang: ic(
						"LANG",
						"FYC_EN",
						x => (languages.includes(x) ? x : "FYC_EN"),
						x => x,
					),
					font: sc("FONT", "MS PGothic"),
					chatOpacity: sc("OPACITY", 0.8),
					color: sc("COLOR", "#ffffff"),
					ownerColor: sc("COLOR_OWNER", "#ffd600"),
					moderatorColor: sc("COLOR_MODERATOR", "#c564ff"),
					memberColor: sc("COLOR_MEMBER", "#9fffff"),
					fontSize: sc("SIZE", 1),
					fontWeight: sc("WEIGHT", 730),
					shadowFontWeight: sc("WEIGHT_SHADOW", 1),
					maxChatCount: sc("LIMIT", 40),
					flowSpeed: sc("SPEED", 18),
					maxChatLength: sc("MAX", 100),
					laneCount: sc("LANE_DIV", 12),
					bannedWords: ic("NG_WORDS", ...stringsArgs),
					bannedWordRegexes: ic("NG_REG_WORDS", ...stringsArgs),
					bannedUsers: ic("NG_USERS", ...stringsArgs),
					createChats: sc("TOGGLE_CREATE_COMMENTS", !0),
					noOverlap: sc("NO_OVERLAP", !0),
					createBanButton: sc("NG_BUTTON", !0),
					simplifyChatField: sc("SIMPLE_CHAT_FIELD", !1),
					displayModName: sc("DISPLAY_MODERATOR_NAME", !0),
					displaySuperChatAuthor: sc("DISPLAY_SUPER_CHAT_AUTHOR", !0),
					textOnly: sc("TEXT_ONLY", !1),
					timingFunction: sc("TIMING_FUNCTION", "linear"),
					displayChats: sc("DISPLAY_COMMENTS", !0),
					minSpacing: sc("MIN_SPACING", 0.5),
					fieldScale: sc("FIELD_SCALE", 1),
					flowY1: sc("flowY1", 0),
					flowY2: sc("flowY2", 1),
					flowX1: sc("flowX1", 0),
					flowX2: sc("flowX2", 1),
					shadowColor: sc("shadowColor", "#000000"),
					logEvents: sc("logEvents", !0),
				},
				x => ({
					...x,
					filterExp: ic(
						"filterExp",
						external_jsep_default()(
							`\n  or([\n  A.some(\n    flip(flow([inText, A.some]))(${JSON.stringify(x.bannedWords.defaultValue)})\n  )(A.getSomes([\n    messageText,\n    paymentInfo\n  ])),\n  A.some(\n    flip(flow([matchedByText, A.some]))(${JSON.stringify(x.bannedWordRegexes.defaultValue)})\n  )(A.getSomes([\n    messageText,\n    paymentInfo\n  ])),\n  O.exists(\n    flip(flow([eqText, A.some]))(${JSON.stringify(x.bannedUsers.defaultValue)})\n  )(authorID)\n  ])\n        `,
						),
						external_jsep_default(),
						external_astring_namespaceObject.generate,
					),
				}),
			),
			src_defaultGMConfig = defaultGMConfig,
			configKeys = Object.keys(src_defaultGMConfig),
			removeOldChats = flowChats => maxChatCount =>
				pipe(
					SynchronizedRef_get(flowChats),
					Effect_map(
						sort(
							Order_mapInput(x => Either_isRight(x.animationState))(
								Boolean_Order,
							),
						),
					),
					Effect_map(x => splitAt(x, x.length - maxChatCount)),
					Effect_flatMap(([oldChats, newChats]) =>
						pipe(
							oldChats,
							Effect_forEach(x =>
								pipe(
									Effect_logDebug("RemoveChat"),
									Effect_zipRight(
										Effect_sync(() => {
											x.element.remove()
										}),
									),
								),
							),
							Effect_map(() => newChats),
						),
					),
					Effect_tap(x => Effect_logDebug(`length after clear: ${x.length}`)),
					Effect_flatMap(x => SynchronizedRef_set(flowChats, x)),
				)
		__webpack_require__.dn(removeOldChats)
		const t = globalThis,
			s = t.trustedTypes,
			e = s ? s.createPolicy("lit-html", { createHTML: t => t }) : void 0,
			o = `lit$${Math.random().toFixed(9).slice(2)}$`,
			n = "?" + o,
			r = `<${n}>`,
			l = document,
			c = () => l.createComment(""),
			a = t => null === t || ("object" != typeof t && "function" != typeof t),
			u = Array.isArray,
			f = "[ \t\n\f\r]",
			v = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,
			_ = /-->/g,
			m = />/g,
			p = RegExp(
				`>|${f}(?:([^\\s"'>=/]+)(${f}*=${f}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,
				"g",
			),
			g = /'/g,
			$ = /"/g,
			y = /^(?:script|style|textarea|title)$/i,
			x =
				t =>
				(i, ...s) => ({ _$litType$: t, strings: i, values: s }),
			b = x(1),
			lit_html_E = (x(2), x(3), Symbol.for("lit-noChange")),
			A = Symbol.for("lit-nothing"),
			C = new WeakMap(),
			P = l.createTreeWalker(l, 129)
		function V(t, i) {
			if (!u(t) || !t.hasOwnProperty("raw"))
				throw Error("invalid template strings array")
			return void 0 !== e ? e.createHTML(i) : i
		}
		const N = (t, i) => {
			const s = t.length - 1,
				e = []
			let n,
				l = 2 === i ? "<svg>" : 3 === i ? "<math>" : "",
				c = v
			for (let i = 0; i < s; i++) {
				const s = t[i]
				let a,
					u,
					d = -1,
					f = 0
				for (
					;
					f < s.length && ((c.lastIndex = f), (u = c.exec(s)), null !== u);
				)
					((f = c.lastIndex),
						c === v
							? "!--" === u[1]
								? (c = _)
								: void 0 !== u[1]
									? (c = m)
									: void 0 !== u[2]
										? (y.test(u[2]) && (n = RegExp("</" + u[2], "g")), (c = p))
										: void 0 !== u[3] && (c = p)
							: c === p
								? ">" === u[0]
									? ((c = n ?? v), (d = -1))
									: void 0 === u[1]
										? (d = -2)
										: ((d = c.lastIndex - u[2].length),
											(a = u[1]),
											(c = void 0 === u[3] ? p : '"' === u[3] ? $ : g))
								: c === $ || c === g
									? (c = p)
									: c === _ || c === m
										? (c = v)
										: ((c = p), (n = void 0)))
				const x = c === p && t[i + 1].startsWith("/>") ? " " : ""
				l +=
					c === v
						? s + r
						: d >= 0
							? (e.push(a), s.slice(0, d) + "$lit$" + s.slice(d) + o + x)
							: s + o + (-2 === d ? i : x)
			}
			return [
				V(
					t,
					l + (t[s] || "<?>") + (2 === i ? "</svg>" : 3 === i ? "</math>" : ""),
				),
				e,
			]
		}
		class S {
			constructor({ strings: t, _$litType$: i }, e) {
				let r
				this.parts = []
				let l = 0,
					a = 0
				const u = t.length - 1,
					d = this.parts,
					[f, v] = N(t, i)
				if (
					((this.el = S.createElement(f, e)),
					(P.currentNode = this.el.content),
					2 === i || 3 === i)
				) {
					const t = this.el.content.firstChild
					t.replaceWith(...t.childNodes)
				}
				for (; null !== (r = P.nextNode()) && d.length < u;) {
					if (1 === r.nodeType) {
						if (r.hasAttributes())
							for (const t of r.getAttributeNames())
								if (t.endsWith("$lit$")) {
									const i = v[a++],
										s = r.getAttribute(t).split(o),
										e = /([.?@])?(.*)/.exec(i)
									;(d.push({
										type: 1,
										index: l,
										name: e[2],
										strings: s,
										ctor:
											"." === e[1]
												? I
												: "?" === e[1]
													? L
													: "@" === e[1]
														? z
														: H,
									}),
										r.removeAttribute(t))
								} else
									t.startsWith(o) &&
										(d.push({ type: 6, index: l }), r.removeAttribute(t))
						if (y.test(r.tagName)) {
							const t = r.textContent.split(o),
								i = t.length - 1
							if (i > 0) {
								r.textContent = s ? s.emptyScript : ""
								for (let s = 0; s < i; s++)
									(r.append(t[s], c()),
										P.nextNode(),
										d.push({ type: 2, index: ++l }))
								r.append(t[i], c())
							}
						}
					} else if (8 === r.nodeType)
						if (r.data === n) d.push({ type: 2, index: l })
						else {
							let t = -1
							for (; -1 !== (t = r.data.indexOf(o, t + 1));)
								(d.push({ type: 7, index: l }), (t += o.length - 1))
						}
					l++
				}
			}
			static createElement(t, i) {
				const s = l.createElement("template")
				return ((s.innerHTML = t), s)
			}
		}
		function M(t, i, s = t, e) {
			if (i === lit_html_E) return i
			let h = void 0 !== e ? s._$Co?.[e] : s._$Cl
			const o = a(i) ? void 0 : i._$litDirective$
			return (
				h?.constructor !== o &&
					(h?._$AO?.(!1),
					void 0 === o ? (h = void 0) : ((h = new o(t)), h._$AT(t, s, e)),
					void 0 !== e ? ((s._$Co ??= [])[e] = h) : (s._$Cl = h)),
				void 0 !== h && (i = M(t, h._$AS(t, i.values), h, e)),
				i
			)
		}
		class R {
			constructor(t, i) {
				;((this._$AV = []),
					(this._$AN = void 0),
					(this._$AD = t),
					(this._$AM = i))
			}
			get parentNode() {
				return this._$AM.parentNode
			}
			get _$AU() {
				return this._$AM._$AU
			}
			u(t) {
				const {
						el: { content: i },
						parts: s,
					} = this._$AD,
					e = (t?.creationScope ?? l).importNode(i, !0)
				P.currentNode = e
				let h = P.nextNode(),
					o = 0,
					n = 0,
					r = s[0]
				for (; void 0 !== r;) {
					if (o === r.index) {
						let i
						;(2 === r.type
							? (i = new k(h, h.nextSibling, this, t))
							: 1 === r.type
								? (i = new r.ctor(h, r.name, r.strings, this, t))
								: 6 === r.type && (i = new Z(h, this, t)),
							this._$AV.push(i),
							(r = s[++n]))
					}
					o !== r?.index && ((h = P.nextNode()), o++)
				}
				return ((P.currentNode = l), e)
			}
			p(t) {
				let i = 0
				for (const s of this._$AV)
					(void 0 !== s &&
						(void 0 !== s.strings
							? (s._$AI(t, s, i), (i += s.strings.length - 2))
							: s._$AI(t[i])),
						i++)
			}
		}
		class k {
			get _$AU() {
				return this._$AM?._$AU ?? this._$Cv
			}
			constructor(t, i, s, e) {
				;((this.type = 2),
					(this._$AH = A),
					(this._$AN = void 0),
					(this._$AA = t),
					(this._$AB = i),
					(this._$AM = s),
					(this.options = e),
					(this._$Cv = e?.isConnected ?? !0))
			}
			get parentNode() {
				let t = this._$AA.parentNode
				const i = this._$AM
				return (void 0 !== i && 11 === t?.nodeType && (t = i.parentNode), t)
			}
			get startNode() {
				return this._$AA
			}
			get endNode() {
				return this._$AB
			}
			_$AI(t, i = this) {
				;((t = M(this, t, i)),
					a(t)
						? t === A || null == t || "" === t
							? (this._$AH !== A && this._$AR(), (this._$AH = A))
							: t !== this._$AH && t !== lit_html_E && this._(t)
						: void 0 !== t._$litType$
							? this.$(t)
							: void 0 !== t.nodeType
								? this.T(t)
								: (t => u(t) || "function" == typeof t?.[Symbol.iterator])(t)
									? this.k(t)
									: this._(t))
			}
			O(t) {
				return this._$AA.parentNode.insertBefore(t, this._$AB)
			}
			T(t) {
				this._$AH !== t && (this._$AR(), (this._$AH = this.O(t)))
			}
			_(t) {
				;(this._$AH !== A && a(this._$AH)
					? (this._$AA.nextSibling.data = t)
					: this.T(l.createTextNode(t)),
					(this._$AH = t))
			}
			$(t) {
				const { values: i, _$litType$: s } = t,
					e =
						"number" == typeof s
							? this._$AC(t)
							: (void 0 === s.el &&
									(s.el = S.createElement(V(s.h, s.h[0]), this.options)),
								s)
				if (this._$AH?._$AD === e) this._$AH.p(i)
				else {
					const t = new R(e, this),
						s = t.u(this.options)
					;(t.p(i), this.T(s), (this._$AH = t))
				}
			}
			_$AC(t) {
				let i = C.get(t.strings)
				return (void 0 === i && C.set(t.strings, (i = new S(t))), i)
			}
			k(t) {
				u(this._$AH) || ((this._$AH = []), this._$AR())
				const i = this._$AH
				let s,
					e = 0
				for (const h of t)
					(e === i.length
						? i.push((s = new k(this.O(c()), this.O(c()), this, this.options)))
						: (s = i[e]),
						s._$AI(h),
						e++)
				e < i.length && (this._$AR(s && s._$AB.nextSibling, e), (i.length = e))
			}
			_$AR(t = this._$AA.nextSibling, s) {
				for (this._$AP?.(!1, !0, s); t !== this._$AB;) {
					const s = t.nextSibling
					;(t.remove(), (t = s))
				}
			}
			setConnected(t) {
				void 0 === this._$AM && ((this._$Cv = t), this._$AP?.(t))
			}
		}
		class H {
			get tagName() {
				return this.element.tagName
			}
			get _$AU() {
				return this._$AM._$AU
			}
			constructor(t, i, s, e, h) {
				;((this.type = 1),
					(this._$AH = A),
					(this._$AN = void 0),
					(this.element = t),
					(this.name = i),
					(this._$AM = e),
					(this.options = h),
					s.length > 2 || "" !== s[0] || "" !== s[1]
						? ((this._$AH = Array(s.length - 1).fill(new String())),
							(this.strings = s))
						: (this._$AH = A))
			}
			_$AI(t, i = this, s, e) {
				const h = this.strings
				let o = !1
				if (void 0 === h)
					((t = M(this, t, i, 0)),
						(o = !a(t) || (t !== this._$AH && t !== lit_html_E)),
						o && (this._$AH = t))
				else {
					const e = t
					let n, r
					for (t = h[0], n = 0; n < h.length - 1; n++)
						((r = M(this, e[s + n], i, n)),
							r === lit_html_E && (r = this._$AH[n]),
							(o ||= !a(r) || r !== this._$AH[n]),
							r === A ? (t = A) : t !== A && (t += (r ?? "") + h[n + 1]),
							(this._$AH[n] = r))
				}
				o && !e && this.j(t)
			}
			j(t) {
				t === A
					? this.element.removeAttribute(this.name)
					: this.element.setAttribute(this.name, t ?? "")
			}
		}
		class I extends H {
			constructor() {
				;(super(...arguments), (this.type = 3))
			}
			j(t) {
				this.element[this.name] = t === A ? void 0 : t
			}
		}
		class L extends H {
			constructor() {
				;(super(...arguments), (this.type = 4))
			}
			j(t) {
				this.element.toggleAttribute(this.name, !!t && t !== A)
			}
		}
		class z extends H {
			constructor(t, i, s, e, h) {
				;(super(t, i, s, e, h), (this.type = 5))
			}
			_$AI(t, i = this) {
				if ((t = M(this, t, i, 0) ?? A) === lit_html_E) return
				const s = this._$AH,
					e =
						(t === A && s !== A) ||
						t.capture !== s.capture ||
						t.once !== s.once ||
						t.passive !== s.passive,
					h = t !== A && (s === A || e)
				;(e && this.element.removeEventListener(this.name, this, s),
					h && this.element.addEventListener(this.name, this, t),
					(this._$AH = t))
			}
			handleEvent(t) {
				"function" == typeof this._$AH
					? this._$AH.call(this.options?.host ?? this.element, t)
					: this._$AH.handleEvent(t)
			}
		}
		class Z {
			constructor(t, i, s) {
				;((this.element = t),
					(this.type = 6),
					(this._$AN = void 0),
					(this._$AM = i),
					(this.options = s))
			}
			get _$AU() {
				return this._$AM._$AU
			}
			_$AI(t) {
				M(this, t)
			}
		}
		const B = t.litHtmlPolyfillSupport
		;(B?.(S, k), (t.litHtmlVersions ??= []).push("3.3.3"))
		class directive_i {
			constructor(t) {}
			get _$AU() {
				return this._$AM._$AU
			}
			_$AT(t, e, i) {
				;((this._$Ct = t), (this._$AM = e), (this._$Ci = i))
			}
			_$AS(t, e) {
				return this.update(t, e)
			}
			update(t, e) {
				return this.render(...e)
			}
		}
		const style_map_o = (
				t =>
				(...e) => ({ _$litDirective$: t, values: e })
			)(
				class extends directive_i {
					constructor(t) {
						if (
							(super(t),
							1 !== t.type || "style" !== t.name || t.strings?.length > 2)
						)
							throw Error(
								"The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.",
							)
					}
					render(t) {
						return Object.keys(t).reduce((e, r) => {
							const s = t[r]
							return null == s
								? e
								: e +
										`${(r = r.includes("-") ? r : r.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g, "-$&").toLowerCase())}:${s};`
						}, "")
					}
					update(e, [r]) {
						const { style: s } = e.element
						if (void 0 === this.ft)
							return ((this.ft = new Set(Object.keys(r))), this.render(r))
						for (const t of this.ft)
							null == r[t] &&
								(this.ft.delete(t),
								t.includes("-") ? s.removeProperty(t) : (s[t] = null))
						for (const t in r) {
							const e = r[t]
							if (null != e) {
								this.ft.add(t)
								const r = "string" == typeof e && e.endsWith(" !important")
								t.includes("-") || r
									? s.setProperty(
											t,
											r ? e.slice(0, -11) : e,
											r ? "important" : "",
										)
									: (s[t] = e)
							}
						}
						return lit_html_E
					}
				},
			),
			getChatFontSize = ({ config: { value: config }, playerRect }) =>
				SynchronizedRef_get(playerRect).pipe(
					Effect_map(
						rect =>
							Math.round(
								((Math.max(config.fontSize - 0.2, 0.01) * rect.height) /
									config.laneCount) *
									(config.flowY2 - config.flowY1) *
									100,
							) / 100,
					),
				)
		__webpack_require__.dn(getChatFontSize)
		const textShadow = shadowColor => offset =>
			pipe(
				offset,
				x => `${x}px`,
				x => (a, b) => `${a}${x} ${b}${x} ${shadowColor}99`,
				x => join(", ")([x("-", "-"), x("", "-"), x("-", ""), x("", "")]),
			)
		__webpack_require__.dn(textShadow)
		const textStyle = { fontFamily: "inherit" },
			chatNode = (chat, mainState) =>
				pipe(
					Effect_gen(function* () {
						return {
							data: chat.data,
							config: mainState.config.value,
							fontSize: yield* getChatFontSize(mainState),
						}
					}),
					Effect_map(
						({ data, config, fontSize }) =>
							b`<span style=${style_map_o({ fontSize: `${fontSize}px`, visibility: config.displayChats ? "visible" : "hidden", color: "owner" === data.authorType ? config.ownerColor : "moderator" === data.authorType ? config.moderatorColor : "member" === data.authorType ? config.memberColor : config.color, fontWeight: config.fontWeight.toString(), fontFamily: config.font, opacity: config.chatOpacity.toString(), textShadow: textShadow(config.shadowColor)(config.shadowFontWeight) })}>${pipe(
								[
									pipe(
										data.authorName,
										filter(
											() =>
												("moderator" === data.authorType &&
													config.displayModName) ||
												(Option_isSome(data.paymentInfo) &&
													config.displaySuperChatAuthor),
										),
										Option_map(
											text =>
												b`<span style=${style_map_o({ ...Option_match(data.textColor, { onNone: () => {}, onSome: x => ({ color: x }) }), fontSize: "0.84em", ...textStyle })}>${text}: </span>`,
										),
									),
									pipe(
										data.messageElement,
										Option_map(x =>
											((message, config) => {
												const eleWin =
														message.ownerDocument.defaultView ?? window,
													{ maxChatLength } = config
												return pipe(
													Array.from(message.childNodes),
													Array_reduce(
														{ vnodes: [], length: 0 },
														({ vnodes, length }, node) => {
															return length >= maxChatLength
																? { vnodes, length }
																: !config.textOnly &&
																	  node instanceof eleWin.HTMLImageElement
																	? {
																			vnodes: [
																				...vnodes,
																				b`<img style=${style_map_o({ height: "1em", width: "1em", verticalAlign: "text-top" })} src=${node.src.replace(/=w\d+-h\d+-c-k-nd$/, "")} alt=${node.alt}>`,
																			],
																			length: length + 1,
																		}
																	: pipe(
																			node.textContent ?? "",
																			((end = maxChatLength),
																			self => self.slice(0, end)),
																			x =>
																				node instanceof eleWin.HTMLAnchorElement
																					? {
																							vnodes: [
																								...vnodes,
																								b`<span style=${style_map_o({ fontSize: "0.84em", textDecoration: "underline", ...textStyle })}>${x}</span>`,
																							],
																							length: length + x.length,
																						}
																					: {
																							vnodes: [...vnodes, b`${x}`],
																							length: length + x.length,
																						},
																		)
															var end
														},
													),
												)
											})(x, config),
										),
										Option_map(
											text =>
												b`<span style=${style_map_o({ ...Option_match(data.textColor, { onNone: () => {}, onSome: x => ({ color: x }) }), ...textStyle })}>${text.vnodes}</span>`,
										),
									),
									pipe(
										data.paymentInfo,
										Option_map(
											text =>
												b`<span style=${style_map_o({ ...Option_match(data.paidColor, { onNone: () => {}, onSome: x => ({ color: x }) }), fontSize: "0.84em", ...textStyle })}><strong style=${style_map_o(textStyle)}></strong> ${text.trim()}</span>`,
										),
									),
								],
								Array_getSomes,
							)}</span>`,
					),
				)
		__webpack_require__.dn(chatNode)
		const renderChat = chat => mainState =>
			chatNode(chat, mainState).pipe(
				Effect_flatMap(node =>
					Effect_sync(() =>
						((t, i) => {
							const e = i
							let h = e._$litPart$
							if (void 0 === h) {
								const t = null
								e._$litPart$ = h = new k(i.insertBefore(c(), t), t, void 0, {})
							}
							return (h._$AI(t), h)
						})(node, chat.element),
					),
				),
			)
		__webpack_require__.dn(renderChat)
		const scaleChatField = live => scale =>
			pipe(
				live.chatField.ele,
				Effect_flatMap(field =>
					pipe(
						[
							pipe(
								Option_fromNullable(field.parentElement),
								Option_map(x =>
									Effect_sync(() =>
										Object.assign(x.style, {
											transformOrigin:
												(scale >= 1 ? "top" : "bottom") + " left",
											transform: `scale(${scale})`,
											width: 100 / scale + "%",
											height: 100 / scale + "%",
										}),
									),
								),
							),
							pipe(
								live.chatScroller.ele,
								Option_map(scroller =>
									Effect_sync(() => {
										scroller.scrollTop = scroller.scrollHeight
									}),
								),
							),
						],
						Array_getSomes,
						Effect_all,
					),
				),
				Effect_ignore,
			)
		__webpack_require__.dn(scaleChatField)
		const external_window_hash_it_namespaceObject = window["hash-it"],
			{ getOwnPropertyNames, getOwnPropertySymbols } = Object,
			{ hasOwnProperty: es_hasOwnProperty } = Object.prototype
		function combineComparators(comparatorA, comparatorB) {
			return function (a, b, state) {
				return comparatorA(a, b, state) && comparatorB(a, b, state)
			}
		}
		function createIsCircular(areItemsEqual) {
			return function (a, b, state) {
				if (!a || !b || "object" != typeof a || "object" != typeof b)
					return areItemsEqual(a, b, state)
				const { cache } = state,
					cachedA = cache.get(a),
					cachedB = cache.get(b)
				if (cachedA && cachedB) return cachedA === b && cachedB === a
				cache.set(a, b)
				cache.set(b, a)
				const result = areItemsEqual(a, b, state)
				cache.delete(a)
				cache.delete(b)
				return result
			}
		}
		function getStrictProperties(object) {
			return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object))
		}
		const hasOwn =
			Object.hasOwn ||
			((object, property) => es_hasOwnProperty.call(object, property))
		function sameValueZeroEqual(a, b) {
			return a === b || (!a && !b && a != a && b != b)
		}
		const { getOwnPropertyDescriptor, keys: es_keys } = Object
		function areArrayBuffersEqual(a, b) {
			return (
				a.byteLength === b.byteLength &&
				areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b))
			)
		}
		function areArraysEqual(a, b, state) {
			let index = a.length
			if (b.length !== index) return !1
			for (; index-- > 0;)
				if (!state.equals(a[index], b[index], index, index, a, b, state))
					return !1
			return !0
		}
		function areDataViewsEqual(a, b) {
			return (
				a.byteLength === b.byteLength &&
				areTypedArraysEqual(
					new Uint8Array(a.buffer, a.byteOffset, a.byteLength),
					new Uint8Array(b.buffer, b.byteOffset, b.byteLength),
				)
			)
		}
		function areDatesEqual(a, b) {
			return sameValueZeroEqual(a.getTime(), b.getTime())
		}
		function areErrorsEqual(a, b) {
			return (
				a.name === b.name &&
				a.message === b.message &&
				a.cause === b.cause &&
				a.stack === b.stack
			)
		}
		function areFunctionsEqual(a, b) {
			return a === b
		}
		function areMapsEqual(a, b, state) {
			const size = a.size
			if (size !== b.size) return !1
			if (!size) return !0
			const matchedIndices = new Array(size),
				aIterable = a.entries()
			let aResult,
				bResult,
				index = 0
			for (; (aResult = aIterable.next()) && !aResult.done;) {
				const bIterable = b.entries()
				let hasMatch = !1,
					matchIndex = 0
				for (; (bResult = bIterable.next()) && !bResult.done;) {
					if (matchedIndices[matchIndex]) {
						matchIndex++
						continue
					}
					const aEntry = aResult.value,
						bEntry = bResult.value
					if (
						state.equals(
							aEntry[0],
							bEntry[0],
							index,
							matchIndex,
							a,
							b,
							state,
						) &&
						state.equals(
							aEntry[1],
							bEntry[1],
							aEntry[0],
							bEntry[0],
							a,
							b,
							state,
						)
					) {
						hasMatch = matchedIndices[matchIndex] = !0
						break
					}
					matchIndex++
				}
				if (!hasMatch) return !1
				index++
			}
			return !0
		}
		const areNumbersEqual = sameValueZeroEqual
		function areObjectsEqual(a, b, state) {
			const properties = es_keys(a)
			let index = properties.length
			if (es_keys(b).length !== index) return !1
			for (; index-- > 0;)
				if (!isPropertyEqual(a, b, state, properties[index])) return !1
			return !0
		}
		function areObjectsEqualStrict(a, b, state) {
			const properties = getStrictProperties(a)
			let property,
				descriptorA,
				descriptorB,
				index = properties.length
			if (getStrictProperties(b).length !== index) return !1
			for (; index-- > 0;) {
				property = properties[index]
				if (!isPropertyEqual(a, b, state, property)) return !1
				descriptorA = getOwnPropertyDescriptor(a, property)
				descriptorB = getOwnPropertyDescriptor(b, property)
				if (
					(descriptorA || descriptorB) &&
					(!descriptorA ||
						!descriptorB ||
						descriptorA.configurable !== descriptorB.configurable ||
						descriptorA.enumerable !== descriptorB.enumerable ||
						descriptorA.writable !== descriptorB.writable)
				)
					return !1
			}
			return !0
		}
		function arePrimitiveWrappersEqual(a, b) {
			return sameValueZeroEqual(a.valueOf(), b.valueOf())
		}
		function areRegExpsEqual(a, b) {
			return a.source === b.source && a.flags === b.flags
		}
		function areSetsEqual(a, b, state) {
			const size = a.size
			if (size !== b.size) return !1
			if (!size) return !0
			const matchedIndices = new Array(size),
				aIterable = a.values()
			let aResult, bResult
			for (; (aResult = aIterable.next()) && !aResult.done;) {
				const bIterable = b.values()
				let hasMatch = !1,
					matchIndex = 0
				for (; (bResult = bIterable.next()) && !bResult.done;) {
					if (
						!matchedIndices[matchIndex] &&
						state.equals(
							aResult.value,
							bResult.value,
							aResult.value,
							bResult.value,
							a,
							b,
							state,
						)
					) {
						hasMatch = matchedIndices[matchIndex] = !0
						break
					}
					matchIndex++
				}
				if (!hasMatch) return !1
			}
			return !0
		}
		function areTypedArraysEqual(a, b) {
			let index = a.byteLength
			if (b.byteLength !== index || a.byteOffset !== b.byteOffset) return !1
			for (; index-- > 0;) if (a[index] !== b[index]) return !1
			return !0
		}
		function areUrlsEqual(a, b) {
			return (
				a.hostname === b.hostname &&
				a.pathname === b.pathname &&
				a.protocol === b.protocol &&
				a.port === b.port &&
				a.hash === b.hash &&
				a.username === b.username &&
				a.password === b.password
			)
		}
		function isPropertyEqual(a, b, state, property) {
			return (
				!(
					("_owner" !== property && "__o" !== property && "__v" !== property) ||
					(!a.$$typeof && !b.$$typeof)
				) ||
				(hasOwn(b, property) &&
					state.equals(
						a[property],
						b[property],
						property,
						property,
						a,
						b,
						state,
					))
			)
		}
		const TYPED_ARRAY_TAGS = {
				"[object Int8Array]": !0,
				"[object Uint8Array]": !0,
				"[object Uint8ClampedArray]": !0,
				"[object Int16Array]": !0,
				"[object Uint16Array]": !0,
				"[object Int32Array]": !0,
				"[object Uint32Array]": !0,
				"[object Float16Array]": !0,
				"[object Float32Array]": !0,
				"[object Float64Array]": !0,
				"[object BigInt64Array]": !0,
				"[object BigUint64Array]": !0,
			},
			es_toString = Object.prototype.toString,
			deepEqual = createCustomEqual(),
			shallowEqual =
				(createCustomEqual({ strict: !0 }),
				createCustomEqual({ circular: !0 }),
				createCustomEqual({ circular: !0, strict: !0 }),
				createCustomEqual({
					createInternalComparator: () => sameValueZeroEqual,
				}))
		;(createCustomEqual({
			strict: !0,
			createInternalComparator: () => sameValueZeroEqual,
		}),
			createCustomEqual({
				circular: !0,
				createInternalComparator: () => sameValueZeroEqual,
			}),
			createCustomEqual({
				circular: !0,
				createInternalComparator: () => sameValueZeroEqual,
				strict: !0,
			}))
		function createCustomEqual(options = {}) {
			const {
					circular = !1,
					createInternalComparator: createCustomInternalComparator,
					createState,
					strict = !1,
				} = options,
				config = (function ({ circular, createCustomConfig, strict }) {
					let config = {
						areArrayBuffersEqual,
						areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual,
						areDataViewsEqual,
						areDatesEqual,
						areErrorsEqual,
						areFunctionsEqual,
						areMapsEqual: strict
							? combineComparators(areMapsEqual, areObjectsEqualStrict)
							: areMapsEqual,
						areNumbersEqual,
						areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual,
						arePrimitiveWrappersEqual,
						areRegExpsEqual,
						areSetsEqual: strict
							? combineComparators(areSetsEqual, areObjectsEqualStrict)
							: areSetsEqual,
						areTypedArraysEqual: strict
							? combineComparators(areTypedArraysEqual, areObjectsEqualStrict)
							: areTypedArraysEqual,
						areUrlsEqual,
						unknownTagComparators: void 0,
					}
					createCustomConfig &&
						(config = Object.assign({}, config, createCustomConfig(config)))
					if (circular) {
						const areArraysEqual = createIsCircular(config.areArraysEqual),
							areMapsEqual = createIsCircular(config.areMapsEqual),
							areObjectsEqual = createIsCircular(config.areObjectsEqual),
							areSetsEqual = createIsCircular(config.areSetsEqual)
						config = Object.assign({}, config, {
							areArraysEqual,
							areMapsEqual,
							areObjectsEqual,
							areSetsEqual,
						})
					}
					return config
				})(options),
				comparator = (function ({
					areArrayBuffersEqual,
					areArraysEqual,
					areDataViewsEqual,
					areDatesEqual,
					areErrorsEqual,
					areFunctionsEqual,
					areMapsEqual,
					areNumbersEqual,
					areObjectsEqual,
					arePrimitiveWrappersEqual,
					areRegExpsEqual,
					areSetsEqual,
					areTypedArraysEqual,
					areUrlsEqual,
					unknownTagComparators,
				}) {
					return function (a, b, state) {
						if (a === b) return !0
						if (null == a || null == b) return !1
						const type = typeof a
						if (type !== typeof b) return !1
						if ("object" !== type)
							return "number" === type
								? areNumbersEqual(a, b, state)
								: "function" === type && areFunctionsEqual(a, b, state)
						const constructor = a.constructor
						if (constructor !== b.constructor) return !1
						if (constructor === Object) return areObjectsEqual(a, b, state)
						if (Array.isArray(a)) return areArraysEqual(a, b, state)
						if (constructor === Date) return areDatesEqual(a, b, state)
						if (constructor === RegExp) return areRegExpsEqual(a, b, state)
						if (constructor === Map) return areMapsEqual(a, b, state)
						if (constructor === Set) return areSetsEqual(a, b, state)
						const tag = es_toString.call(a)
						if ("[object Date]" === tag) return areDatesEqual(a, b, state)
						if ("[object RegExp]" === tag) return areRegExpsEqual(a, b, state)
						if ("[object Map]" === tag) return areMapsEqual(a, b, state)
						if ("[object Set]" === tag) return areSetsEqual(a, b, state)
						if ("[object Object]" === tag)
							return (
								"function" != typeof a.then &&
								"function" != typeof b.then &&
								areObjectsEqual(a, b, state)
							)
						if ("[object URL]" === tag) return areUrlsEqual(a, b, state)
						if ("[object Error]" === tag) return areErrorsEqual(a, b, state)
						if ("[object Arguments]" === tag)
							return areObjectsEqual(a, b, state)
						if (TYPED_ARRAY_TAGS[tag]) return areTypedArraysEqual(a, b, state)
						if ("[object ArrayBuffer]" === tag)
							return areArrayBuffersEqual(a, b, state)
						if ("[object DataView]" === tag)
							return areDataViewsEqual(a, b, state)
						if (
							"[object Boolean]" === tag ||
							"[object Number]" === tag ||
							"[object String]" === tag
						)
							return arePrimitiveWrappersEqual(a, b, state)
						if (unknownTagComparators) {
							let unknownTagComparator = unknownTagComparators[tag]
							if (!unknownTagComparator) {
								const shortTag =
									null != (value = a) ? value[Symbol.toStringTag] : void 0
								shortTag &&
									(unknownTagComparator = unknownTagComparators[shortTag])
							}
							if (unknownTagComparator) return unknownTagComparator(a, b, state)
						}
						var value
						return !1
					}
				})(config),
				equals = createCustomInternalComparator
					? createCustomInternalComparator(comparator)
					: (function (compare) {
							return function (
								a,
								b,
								_indexOrKeyA,
								_indexOrKeyB,
								_parentA,
								_parentB,
								state,
							) {
								return compare(a, b, state)
							}
						})(comparator)
			return (function ({ circular, comparator, createState, equals, strict }) {
				if (createState)
					return function (a, b) {
						const { cache = circular ? new WeakMap() : void 0, meta } =
							createState()
						return comparator(a, b, { cache, equals, meta, strict })
					}
				if (circular)
					return function (a, b) {
						return comparator(a, b, {
							cache: new WeakMap(),
							equals,
							meta: void 0,
							strict,
						})
					}
				const state = { cache: void 0, equals, meta: void 0, strict }
				return function (a, b) {
					return comparator(a, b, state)
				}
			})({ circular, comparator, createState, equals, strict })
		}
		var DEFAULT_OPTIONS = {}
		function stringify(value, _a) {
			var _b = void 0 === _a ? DEFAULT_OPTIONS : _a,
				indent = _b.indent,
				replacer = _b.replacer,
				circularReplacer = _b.circularReplacer,
				stable = _b.stable,
				stabilizer = _b.stabilizer,
				cache = [],
				keys = [],
				getStableSorter =
					stable && stabilizer
						? function (object) {
								var options = {
									get: function (key) {
										return object[key]
									},
								}
								return function (a, b) {
									return stabilizer(
										{ key: a, value: object[a] },
										{ key: b, value: object[b] },
										options,
									)
								}
							}
						: void 0
			return JSON.stringify(
				value,
				function (key, rawValue) {
					var value = rawValue
					if ("object" == typeof value && null !== value) {
						if (cache.length) {
							var thisCutoff = cache.indexOf(this) + 1
							if (0 === thisCutoff) cache[cache.length] = this
							else {
								cache.splice(thisCutoff)
								keys.splice(thisCutoff)
							}
							keys[keys.length] = key
							var valueCutoff = cache.indexOf(value) + 1
							if (valueCutoff > 0) {
								var referenceKey = keys.slice(0, valueCutoff).join(".") || "."
								return circularReplacer
									? circularReplacer.call(this, key, value, referenceKey)
									: "[ref=" + referenceKey + "]"
							}
						} else {
							cache[0] = value
							keys[0] = key
						}
						stable &&
							!Array.isArray(value) &&
							(value = Object.keys(value)
								.sort(null == getStableSorter ? void 0 : getStableSorter(value))
								.reduce(function (sorted, key) {
									sorted[key] = value[key]
									return sorted
								}, {}))
					}
					return replacer ? replacer.call(this, key, value) : value
				},
				indent,
			)
		}
		class CacheEventEmitter {
			constructor(cache) {
				this.l = {}
				this.c = cache
			}
			a(type, listener) {
				const listeners = this.l[type]
				listeners
					? listeners.has(listener) || listeners.add(listener)
					: (this.l[type] = new Set([listener]))
			}
			n(type, node, reason) {
				const listeners = this.l[type]
				listeners &&
					listeners.forEach(listener => {
						listener({
							cache: this.c,
							key: node.k,
							reason,
							value: node.v,
							type,
						})
					})
			}
			r(type, listener) {
				const listeners = this.l[type]
				if (listeners) {
					listeners.delete(listener)
					listeners.size || (this.l[type] = void 0)
				}
			}
		}
		function getMaxArgsTransformKey(maxArgs) {
			return 1 === maxArgs
				? args => (maxArgs >= args.length ? args : [args[0]])
				: 2 === maxArgs
					? args => (maxArgs >= args.length ? args : [args[0], args[1]])
					: args => {
							if (maxArgs >= args.length) return args
							const clone = new Array(maxArgs)
							for (let index = 0; index < maxArgs; ++index)
								clone[index] = args[index]
							return clone
						}
		}
		function replacer(_key, value) {
			const type = typeof value
			return "function" === type || "symbol" === type ? value.toString() : value
		}
		function transformKeySerialized(args) {
			return [stringify(args, { replacer })]
		}
		function isSerializedKeyEqual(prevKey, nextKey) {
			return prevKey[0] === nextKey[0]
		}
		function isNumericValueValid(value) {
			return "number" == typeof value && value >= 0 && Number.isFinite(value)
		}
		class Cache {
			constructor(options) {
				this.c = 0
				const { async, maxSize } = options
				this.e = (function ({ isKeyEqual, isKeyItemEqual, serialize }) {
					if ("function" == typeof isKeyEqual) return isKeyEqual
					if (serialize) return isSerializedKeyEqual
					const isItemEqual =
						"function" == typeof isKeyItemEqual
							? isKeyItemEqual
							: "deep" === isKeyItemEqual
								? deepEqual
								: "shallow" === isKeyItemEqual
									? shallowEqual
									: Object.is
					return function (prevKey, nextKey) {
						const length = nextKey.length
						if (prevKey.length !== length) return !1
						if (1 === length) return isItemEqual(prevKey[0], nextKey[0], 0)
						for (let index = 0; index < length; ++index)
							if (!isItemEqual(prevKey[index], nextKey[index], index)) return !1
						return !0
					}
				})(options)
				this.k = (function (options) {
					const { maxArgs, serialize, transformKey } = options,
						transformers = [
							serialize
								? "function" == typeof serialize
									? serialize
									: transformKeySerialized
								: void 0,
							isNumericValueValid(maxArgs)
								? getMaxArgsTransformKey(maxArgs)
								: void 0,
							"function" == typeof transformKey ? transformKey : void 0,
						].filter(Boolean)
					return transformers.length
						? transformers.reduce(
								(f, g) =>
									(...args) =>
										f(g(...args)),
							)
						: void 0
				})(options)
				this.p = "boolean" == typeof async && async
				this.s = isNumericValueValid(maxSize) ? maxSize : 1
			}
			get size() {
				return this.c
			}
			get snapshot() {
				const entries = [],
					keys = [],
					values = []
				let node = this.h,
					size = 0
				for (; null != node;) {
					keys.push(node.k)
					values.push(node.v)
					entries.push([node.k, node.v])
					++size
					node = node.n
				}
				return { entries, keys, size, values }
			}
			clear(reason = "explicit clear") {
				if (!this.h) return
				const emitter = this.o
				let nodes
				if (emitter) {
					nodes = []
					let node = this.h
					for (; null != node;) {
						nodes.push(node)
						node = node.n
					}
				}
				this.h = this.t = void 0
				this.c = 0
				if (emitter && nodes)
					for (let index = 0; index < nodes.length; ++index)
						emitter.n("delete", nodes[index], reason)
			}
			delete(args, reason = "explicit delete") {
				const node = this.g(this.k ? this.k(args) : args)
				if (node) {
					this.d(node, reason)
					return !0
				}
				return !1
			}
			get(args, reason = "explicit get") {
				const node = this.g(this.k ? this.k(args) : args)
				if (node) {
					node !== this.h
						? this.u(node, reason, !0)
						: this.o && this.o.n("hit", node, reason)
					return node.v
				}
			}
			has(args) {
				return !!this.g(this.k ? this.k(args) : args)
			}
			off(type, listener) {
				this.o && this.o.r(type, listener)
			}
			on(type, listener) {
				this.o || (this.o = new CacheEventEmitter(this))
				this.o.a(type, listener)
			}
			set(key, value, reason = "explicit set") {
				const normalizedKey = this.k ? this.k(key) : key
				let node = this.g(normalizedKey)
				if (node) {
					const prevValue = node.v
					node.v = value
					this.p && value !== prevValue && (node.v = this.w(node))
					node !== this.h && this.u(node, reason, !1)
				} else node = this.n(normalizedKey, value)
			}
			d(node, reason) {
				const next = node.n,
					prev = node.p
				next ? (next.p = prev) : (this.t = prev)
				prev ? (prev.n = next) : (this.h = next)
				--this.c
				node.r = !0
				this.o && this.o.n("delete", node, reason)
			}
			g(key) {
				let node = this.h
				if (node && !node.r) {
					if (this.e(node.k, key)) return node
					if (this.h !== this.t) {
						node = node.n
						for (; node;) {
							if (node.r) return
							if (this.e(node.k, key)) return node
							node = node.n
						}
					}
				}
			}
			n(key, value, reason) {
				const prevHead = this.h,
					prevTail = this.t,
					node = { k: key, n: prevHead, p: void 0, v: value }
				this.p && (node.v = this.w(node))
				this.h = node
				prevHead ? (prevHead.p = node) : (this.t = node)
				++this.c > this.s && prevTail && this.d(prevTail, "evicted")
				this.o && this.o.n("add", node, reason)
				return node
			}
			u(node, reason, hit) {
				const next = node.n,
					prev = node.p
				next && (next.p = prev)
				prev && (prev.n = next)
				this.h && (this.h.p = node)
				node.n = this.h
				node.p = void 0
				this.h = node
				node === this.t && (this.t = prev)
				if (this.o) {
					hit && this.o.n("hit", node, reason)
					this.o.n("update", node, reason)
				}
			}
			w(node) {
				const { v: value } = node
				return null == value || "function" != typeof value.then
					? value
					: value.then(
							value => {
								!node.r && this.o && this.o.n("update", node, "resolved")
								return value
							},
							error => {
								!node.r && this.d(node, "rejected")
								throw error
							},
						)
			}
		}
		class ExpirationManager {
			constructor(cache, expires) {
				this.e = new Map()
				this.c = cache
				if ("object" == typeof expires) {
					this.t = expires.after
					this.p = expires.shouldPersist
					this.r = expires.shouldRemove
					this.u = !!expires.update
				} else {
					this.t = expires
					this.u = !1
				}
				this.c.on("add", ({ key, value }) => {
					this.a(key, value) && this.s(key, value)
				})
				if (this.u) {
					this.c.on("hit", ({ key, value }) => {
						this.a(key, value) && this.s(key, value)
					})
					if (this.c.p) {
						const onResolved = ({ key, reason, value }) => {
							if ("resolved" === reason && this.a(key, value)) {
								this.s(key, value)
								this.c.off("update", onResolved)
							}
						}
						this.c.on("update", onResolved)
					}
				}
				this.c.on("delete", ({ key }) => {
					this.e.has(key) && this.d(key)
				})
			}
			get size() {
				return this.e.size
			}
			a(key, value) {
				var _a
				return !(
					!this.c.g(key) ||
					(null === (_a = this.p) || void 0 === _a
						? void 0
						: _a.call(this, key, value, this.c))
				)
			}
			d(key) {
				const expiration = this.e.get(key)
				if (expiration) {
					clearTimeout(expiration)
					this.e.delete(key)
				}
			}
			s(key, value) {
				this.e.has(key) && this.d(key)
				const cache = this.c,
					time =
						"function" == typeof this.t ? this.t(key, value, cache) : this.t
				if (!isNumericValueValid(time))
					throw new TypeError(
						`The expiration time must be a finite, non-negative number; received ${time}`,
					)
				const timeout = setTimeout(() => {
					this.d(key)
					const node = cache.g(key)
					if (node)
						if ("function" != typeof this.r || this.r(key, node.v, time, cache))
							cache.d(node, "expired")
						else {
							node !== cache.h
								? cache.u(node, "expiration reset", !1)
								: cache.o && cache.o.n("update", node, "expiration reset")
							this.s(key, node.v)
						}
				}, time)
				"function" == typeof timeout.unref && timeout.unref()
				this.e.set(key, timeout)
			}
		}
		const nameToProfile = new Map()
		class StatsManager {
			constructor(cache, statsName) {
				this.p = { c: 0, h: 0 }
				this.c = cache
				this.n = statsName
				nameToProfile.set(statsName, this)
			}
			m() {
				const { c: calls, h: hits } = this.p,
					usage = calls ? `${((hits / calls) * 100).toFixed(4)}%` : "0.0000%"
				return { calls, hits, name: this.n, usage }
			}
			r() {
				this.p = { c: 0, h: 0 }
			}
			s() {
				const onAdd = () => {
						++this.p.c
					},
					onHit = () => {
						++this.p.c
						++this.p.h
					}
				this.d = () => {
					this.c.off("add", onAdd)
					this.c.off("hit", onHit)
					this.d = void 0
					this.p.c = this.p.h = 0
				}
				this.c.on("add", onAdd)
				this.c.on("hit", onHit)
			}
		}
		const es_memoize = function memoize(fn, options = {}) {
				if (
					(function (fn) {
						return "function" == typeof fn && fn.isMemoized
					})(fn)
				)
					return memoize(fn.fn, Object.assign({}, fn.options, options))
				if ("function" != typeof fn)
					throw new TypeError(
						"Expected first parameter to be function; received " + typeof fn,
					)
				const cache = new Cache(options),
					memoized = (function (fn, cache, forceUpdate) {
						const memoized = function (...args) {
							const key = cache.k ? cache.k(args) : args
							let node = cache.g(key)
							node
								? node !== cache.h
									? cache.u(node, void 0, !0)
									: cache.o && cache.o.n("hit", node)
								: (node = cache.n(key, fn.apply(this, args)))
							return node.v
						}
						return forceUpdate
							? function (...args) {
									if (!forceUpdate(args) || !cache.has(args))
										return memoized.apply(this, args)
									const value = fn.apply(this, args)
									cache.set(args, value, "forced")
									return value
								}
							: memoized
					})(fn, cache, options.forceUpdate),
					{ expires, statsName } = options
				memoized.cache = cache
				memoized.expirationManager =
					null != expires ? new ExpirationManager(cache, expires) : null
				memoized.fn = fn
				memoized.isMemoized = !0
				memoized.options = options
				memoized.statsManager =
					null != statsName ? new StatsManager(cache, statsName) : null
				return memoized
			},
			getFlowChatProgress = animationState =>
				animationState.pipe(
					match({ onLeft: Option_none, onRight: Option_some }),
					flatMapNullable(x => x.currentTime),
					Option_map(x => ("number" == typeof x ? x : x.to("ms").value)),
					Option_map(x => x / 6400),
					Option_getOrElse(() => 0),
				)
		__webpack_require__.dn(getFlowChatProgress)
		const getFlowChatRect = (chat, config, playerRect) =>
			pipe(
				config,
				x =>
					playerRect.width * x.flowX2 -
					(chat.width + playerRect.width * (x.flowX2 - x.flowX1)) *
						getFlowChatProgress(chat.animationState),
				x => new DOMRectReadOnly(x, chat.y, chat.width, chat.height),
			)
		__webpack_require__.dn(getFlowChatRect)
		const getChatLane =
			(flowChat, chatIndex, progress) =>
			({ config: { value: config }, flowChats, playerRect }) =>
				Effect_gen(function* () {
					const rect = yield* SynchronizedRef_get(playerRect),
						flowWidth = rect.width * (config.flowX2 - config.flowX1),
						{
							width: chatWidth,
							height: chatHeight,
							x: chatX,
						} = getFlowChatRect(flowChat, config, rect),
						movingChats = pipe(
							yield* SynchronizedRef_get(flowChats),
							chats =>
								Array_take(
									chats,
									Option_getOrElse(chatIndex, () => chats.length),
								),
							Array_filter(
								chat => Either_isRight(chat.animationState) && chat.width > 0,
							),
							sort(Order_mapInput(x => x.lane)(Number_Order)),
						),
						tooCloseTo = es_memoize(
							x => {
								const { width: otherWidth, x: otherX } = getFlowChatRect(
										x,
										config,
										rect,
									),
									gap =
										(chatHeight * otherWidth * chatWidth) ** 0.333 *
										config.minSpacing
								return (
									(flowWidth - otherX) / (flowWidth + otherWidth) - progress <
										(chatWidth + gap) / (flowWidth + chatWidth) ||
									otherX + otherWidth + gap > chatX
								)
							},
							{ maxSize: 1e3 },
						),
						occupyInfo = pipe(
							movingChats,
							Array_map(x => ({ tooClose: () => tooCloseTo(x), lane: x.lane })),
							Array_append({ tooClose: () => !0, lane: config.laneCount }),
						),
						index = pipe(
							occupyInfo,
							findFirstIndex(x => x.lane >= flowChat.lane),
							Option_getOrElse(() => -1),
						),
						nextOccupiedLaneAbove = pipe(
							occupyInfo,
							Array_take(index),
							Array_findLast(x => x.tooClose()),
							Option_map(x => x.lane),
							Option_getOrElse(() => -1),
						),
						nextOccupiedLaneBelow = pipe(
							occupyInfo,
							Array_drop(index),
							Array_findFirst(x => x.tooClose()),
							Option_map(x => x.lane),
							Option_getOrElse(() => config.laneCount),
						),
						formerLaneInterval = Math.min(
							flowChat.lane - nextOccupiedLaneAbove,
							nextOccupiedLaneBelow - flowChat.lane,
							1,
						)
					return pipe(
						occupyInfo,
						Array_reduce(
							{ maxInterval: 0, maxIntervalLane: 0, lastLane: -1 },
							({ maxInterval, maxIntervalLane, lastLane }, info) =>
								maxInterval > 0.999 || !info.tooClose()
									? { maxInterval, maxIntervalLane, lastLane }
									: (() => {
											const nextLane = info.lane,
												interLane = Number_clamp({
													minimum: 0,
													maximum: config.laneCount - 1,
												})((lastLane + nextLane) / 2),
												newInterval = Math.min(
													interLane - lastLane,
													nextLane - interLane,
													1,
												)
											return {
												lastLane: nextLane,
												...(newInterval - maxInterval > 0.001
													? {
															maxInterval: newInterval,
															maxIntervalLane: Math.max(
																lastLane + newInterval,
																0,
															),
														}
													: { maxInterval, maxIntervalLane }),
											}
										})(),
						),
						x => ({
							lane:
								Math.abs(formerLaneInterval - x.maxInterval) < 0.001
									? flowChat.lane
									: x.maxIntervalLane,
							interval: x.maxInterval,
						}),
					)
				})
		__webpack_require__.dn(getChatLane)
		const intervalTooSmall = interval => config =>
			config.noOverlap && interval < 0.999
		__webpack_require__.dn(intervalTooSmall)
		const setChatPlayState = chat => mainState =>
			pipe(
				chat.animationState,
				Effect_tap(x =>
					SynchronizedRef_get(mainState.chatPlaying).pipe(
						Effect_flatMap(playing =>
							Effect_sync(playing ? () => x.play() : () => x.pause()),
						),
					),
				),
				Effect_flatMap(x =>
					Effect_sync(() => {
						x.playbackRate = mainState.config.value.flowSpeed / 15
					}),
				),
				Effect_ignore,
			)
		__webpack_require__.dn(setChatPlayState)
		const getLaneY = (lane, { config: { value: config }, playerRect }) =>
			SynchronizedRef_get(playerRect).pipe(
				Effect_map(
					rect =>
						rect.height *
						((lane / config.laneCount + 0.005) *
							(config.flowY2 - config.flowY1) +
							config.flowY1),
				),
			)
		__webpack_require__.dn(getLaneY)
		const setNewChatAnimation = chat => lane => progress => mainState =>
			pipe(
				getLaneY(lane, mainState),
				Effect_map(y => ({ ...chat, lane, y })),
				Effect_tap(newChat =>
					pipe(
						newChat.animationState,
						match({
							onLeft: () => _void,
							onRight: x => Effect_sync(() => x.cancel()),
						}),
					),
				),
				Effect_flatMap(newChat =>
					SynchronizedRef_get(mainState.playerRect).pipe(
						Effect_map(rect => [
							[
								rect.width *
									(mainState.config.value.flowX2 -
										mainState.config.value.flowX1),
								newChat.y,
							],
							[-newChat.width, newChat.y],
						]),
						Effect_map(
							pipe(
								x => `${x}px`,
								x => Array_map(Tuple_mapBoth({ onFirst: x, onSecond: x })),
							),
						),
						Effect_map(
							Array_map(([x, y]) => ({ transform: `translate(${x}, ${y})` })),
						),
						Effect_flatMap(x =>
							Effect_sync(() =>
								newChat.element.animate(x, {
									duration: 6400,
									easing: mainState.config.value.timingFunction,
								}),
							),
						),
						Effect_flatMap(animation =>
							Effect_sync(() => {
								const newNewChat = {
									...newChat,
									animationState: Either_right(animation),
								}
								Object.assign(animation, {
									onfinish: () =>
										Object.assign(newNewChat, {
											animationState: Either_left("Ended"),
										}),
									currentTime: 6400 * progress,
								})
								return newNewChat
							}),
						),
					),
				),
			)
		__webpack_require__.dn(setNewChatAnimation)
		const getWidth = es_memoize(
				ele => ele?.getBoundingClientRect().width ?? 0,
				{
					maxSize: 2e3,
					transformKey: Array_map(external_window_hash_it_namespaceObject.hash),
				},
			),
			setChatAnimation = chat => mainState =>
				pipe(
					getChatFontSize(mainState),
					Effect_tap(height =>
						Effect_gen(function* () {
							chat.element.style.transform = `translate(${(yield* SynchronizedRef_get(mainState.playerRect)).width * (mainState.config.value.flowX2 - mainState.config.value.flowX1)}px, -${2 * height}px)`
						}),
					),
					Effect_filterOrFail(() =>
						match(chat.animationState, {
							onLeft: x => "NotStarted" === x,
							onRight: () => !0,
						}),
					),
					Effect_flatMap(height =>
						Effect_gen(function* () {
							return {
								newChat: {
									...chat,
									width: getWidth(chat.element.firstElementChild),
									height,
								},
								oldChatIndex: pipe(
									yield* SynchronizedRef_get(mainState.flowChats),
									findFirstIndex(x => x === chat),
								),
								progress: getFlowChatProgress(chat.animationState),
							}
						}),
					),
					Effect_flatMap(ctx =>
						getChatLane(
							ctx.newChat,
							ctx.oldChatIndex,
							ctx.progress,
						)(mainState).pipe(
							Effect_flatMap(({ lane, interval }) =>
								intervalTooSmall(interval)(mainState.config.value)
									? ctx.newChat.animationState.pipe(
											Effect_tap(x => Effect_sync(() => x.finish())),
											Effect_map(() => ({
												...ctx.newChat,
												animationState: Either_left("Ended"),
											})),
											Effect_orElse(() => Effect_succeed(ctx.newChat)),
										)
									: setNewChatAnimation(ctx.newChat)(lane)(ctx.progress)(
											mainState,
										),
							),
							Effect_map(x => ({ oldChatIndex: ctx.oldChatIndex, newChat: x })),
						),
					),
					Effect_tap(x => setChatPlayState(x.newChat)(mainState)),
					Effect_flatMap(x =>
						Option_match(x.oldChatIndex, {
							onNone: () => Effect_succeed({ newChat: x.newChat }),
							onSome: index =>
								pipe(
									SynchronizedRef_update(
										mainState.flowChats,
										Array_replace(index, x.newChat),
									),
									Effect_zipRight(
										Effect_fail(new Cause_NoSuchElementException()),
									),
								),
						}),
					),
				)
		__webpack_require__.dn(setChatAnimation)
		const Take_end = take_end,
			Take_failCause = take_failCause,
			Take_of = take_of,
			throttleLatest = durationInput => self => {
				const duration = decode(durationInput)
				return Stream_unwrapScoped(
					Effect_gen(function* () {
						const output = yield* Queue_unbounded(),
							gate = yield* Effect_makeSemaphore(1),
							window = yield* Ref_make({ open: !1 }),
							windowTrain = Effect_gen(function* () {
								for (;;) {
									yield* Effect_sleep(duration)
									if (
										!(yield* gate.withPermits(1)(
											Effect_gen(function* () {
												const state = yield* Ref_get(window)
												if (!state.open || Option_isNone(state.pending)) {
													yield* Ref_set(window, { open: !1 })
													return !1
												}
												yield* Queue_offer(output, Take_of(state.pending.value))
												yield* Ref_set(window, {
													open: !0,
													pending: Option_none(),
												})
												return !0
											}),
										))
									)
										return
								}
							}),
							consume = pipe(
								self,
								Stream_runForEach(element =>
									pipe(
										(element =>
											gate.withPermits(1)(
												Effect_gen(function* () {
													if ((yield* Ref_get(window)).open) {
														yield* Ref_set(window, {
															open: !0,
															pending: Option_some(element),
														})
														return !1
													}
													yield* Queue_offer(output, Take_of(element))
													yield* Ref_set(window, {
														open: !0,
														pending: Option_none(),
													})
													return !0
												}),
											))(element),
										Effect_flatMap(opened =>
											opened
												? (self =>
														withFiberRuntime((state, status) =>
															succeed(
																fiberRuntime_unsafeFork(
																	self,
																	state,
																	status.runtimeFlags,
																),
															),
														))(windowTrain)
												: _void,
										),
										Effect_asVoid,
									),
								),
								Effect_matchCauseEffect({
									onFailure: cause =>
										Queue_offer(output, Take_failCause(cause)),
									onSuccess: () =>
										Effect_gen(function* () {
											const state = yield* gate.withPermits(1)(Ref_get(window))
											state.open &&
												Option_isSome(state.pending) &&
												(yield* Queue_offer(
													output,
													Take_of(state.pending.value),
												))
											yield* Queue_offer(output, Take_end)
										}),
								}),
							)
						yield* (self => scopeWith(scope => circular_forkIn(self, scope)))(
							consume,
						)
						return Stream_flattenTake(Stream_fromQueue(output))
					}),
				)
			}
		__webpack_require__.dn(throttleLatest)
		const configStream = (provideLog, mainState, refs, chatScreen, live) => {
			const changed = key => Stream_drop(refs[key].changes, 1)
			return Stream_merge(
				pipe(
					refs.fieldScale.changes,
					Stream_mapEffect(x => provideLog(scaleChatField(live)(x))),
				),
				pipe(
					Stream_mergeAll(
						[
							pipe(
								Stream_mergeAll(
									[
										changed("displayModName"),
										changed("displaySuperChatAuthor"),
										changed("font"),
										changed("fontSize"),
										changed("fontWeight"),
										changed("laneCount"),
										changed("minSpacing"),
										changed("flowY1"),
										changed("flowY2"),
										pipe(
											refs.flowX1.changes,
											Stream_tap(x =>
												provideLog(
													Effect_sync(() =>
														Object.assign(chatScreen.style, {
															left: 100 * x + "%",
															width:
																100 * (mainState.config.value.flowX2 - x) + "%",
														}),
													),
												),
											),
										),
										pipe(
											changed("flowX2"),
											Stream_tap(x =>
												provideLog(
													Effect_sync(() =>
														Object.assign(chatScreen.style, {
															left: 100 * mainState.config.value.flowX1 + "%",
															width:
																100 * (x - mainState.config.value.flowX1) + "%",
														}),
													),
												),
											),
										),
										changed("textOnly"),
									],
									{ concurrency: "unbounded" },
								),
								Stream_map(() => ({ render: !0, setAnimation: !0 })),
							),
							pipe(
								Stream_mergeAll(
									[
										changed("color"),
										changed("ownerColor"),
										changed("moderatorColor"),
										changed("memberColor"),
										changed("shadowColor"),
										changed("chatOpacity"),
										changed("shadowFontWeight"),
										changed("displayChats"),
									],
									{ concurrency: "unbounded" },
								),
								Stream_map(() => ({ render: !0 })),
							),
							pipe(
								changed("flowSpeed"),
								Stream_map(() => ({ setPlayState: !0 })),
							),
							pipe(
								Stream_mergeAll(
									[
										pipe(
											changed("maxChatCount"),
											Stream_tap(x =>
												provideLog(removeOldChats(mainState.flowChats)(x)),
											),
										),
										changed("noOverlap"),
										changed("timingFunction"),
									],
									{ concurrency: "unbounded" },
								),
								Stream_map(() => ({ setAnimation: !0 })),
							),
						],
						{ concurrency: "unbounded" },
					),
					throttleLatest("180 millis"),
					Stream_map(x => ({
						render: !1,
						setAnimation: !1,
						setPlayState: !1,
						...x,
					})),
					Stream_mapEffect(c =>
						provideLog(
							pipe(
								SynchronizedRef_get(mainState.flowChats),
								Effect_map(Array_filter(x => Either_isRight(x.animationState))),
								Effect_flatMap(
									Effect_forEach(chat =>
										pipe(
											Effect_allSuccesses([
												c.render
													? Effect_succeed(renderChat(chat))
													: Effect_fail(new Cause_NoSuchElementException()),
												c.setAnimation
													? Effect_succeed(state =>
															Effect_ignore(setChatAnimation(chat)(state)),
														)
													: c.setPlayState
														? Effect_succeed(setChatPlayState(chat))
														: Effect_fail(new Cause_NoSuchElementException()),
											]),
											Effect_flatMap(Effect_forEach(apply(mainState))),
										),
									),
								),
							),
						),
					),
				),
			)
		}
		__webpack_require__.dn(configStream)
		const src_listeningBroadcastConfigKeys = [
				"lang",
				"bannedWords",
				"bannedWordRegexes",
				"bannedUsers",
				"filterExp",
				"simplifyChatField",
				"createBanButton",
				"fieldScale",
			],
			chatApp = pipe(
				Effect_sync(() => document.querySelector("#chatframe")),
				Effect_flatMap(nullableFrame =>
					pipe(
						Option_fromNullable(nullableFrame),
						filter(frame =>
							pipe(
								frame.contentDocument?.readyState,
								x => "loading" === x || "complete" === x,
							),
						),
						flatMapNullable(x => x.contentDocument),
						Option_orElse(() => Option_some(document)),
						flatMapNullable(x => x.querySelector("yt-live-chat-app")),
					),
				),
			),
			livePageYt = {
				toggleChatBtnParent: pipe(
					Effect_sync(() =>
						Array.from(document.querySelectorAll(".ytp-right-controls")),
					),
					Effect_flatMap(Array_findFirst(x => null !== x.offsetParent)),
				),
				settingsToggleNextElement: pipe(
					Effect_sync(() => document.querySelector("#menu-container")),
					Effect_flatMap(Effect_fromNullable),
					Effect_filterOrFail(x => null !== x.offsetParent),
					Effect_flatMap(x =>
						Effect_fromNullable(
							x.querySelector(".dropdown-trigger.ytd-menu-renderer"),
						),
					),
					Effect_orElse(() =>
						Effect_fromNullable(
							document.querySelector(
								"#top-row .dropdown-trigger.ytd-menu-renderer",
							),
						),
					),
					Effect_filterOrFail(x => null !== x.parentElement?.offsetParent),
				),
				settingsContainer: pipe(
					Effect_sync(() => document.body),
					Effect_flatMap(Option_fromNullable),
				),
				player: pipe(
					Effect_sync(() => document.querySelector("#movie_player")),
					Effect_flatMap(Option_fromNullable),
				),
				video: pipe(
					Effect_sync(() =>
						document.querySelector("video.video-stream.html5-main-video"),
					),
					Effect_flatMap(Option_fromNullable),
				),
				chatField: pipe(
					chatApp,
					Effect_flatMap(app =>
						pipe(
							app.querySelector("#items.yt-live-chat-item-list-renderer"),
							Option_fromNullable,
						),
					),
				),
				chatTicker: pipe(
					chatApp,
					Effect_flatMap(app =>
						pipe(
							app.querySelector("#items.yt-live-chat-ticker-renderer"),
							Option_fromNullable,
						),
					),
				),
				chatScroller: pipe(
					chatApp,
					Effect_flatMap(app =>
						pipe(
							app.querySelector(
								"#item-scroller.yt-live-chat-item-list-renderer",
							),
							Option_fromNullable,
						),
					),
				),
				offlineSlate: pipe(
					Effect_sync(() => document.querySelector(".ytp-offline-slate")),
					Effect_flatMap(Option_fromNullable),
				),
			},
			logMeta = FiberRef_unsafeMake(Option_none()),
			logWithMeta = level => message => data =>
				pipe(
					Effect_log(message),
					Effect_locally(logMeta, Option_some(data)),
					x => locally(level)(x),
				)
		__webpack_require__.dn(logWithMeta)
		const mainCss = pipe(
				Effect_sync(() => document.createElement("style")),
				Effect_tap(x =>
					Effect_sync(() => {
						x.textContent =
							".fyc_chat {\n  line-height: 1;\n  z-index: 30;\n  position: absolute;\n  user-select: none;\n  white-space: nowrap;\n  will-change: transform;\n}\n.fyc_button {\n  display: inline-block;\n  border-style: none;\n  z-index: 4;\n  font-weight: 500;\n  color: var(--yt-spec-text-secondary);\n}"
					}),
				),
			),
			emptyElement = document.createElement("span"),
			addFlowChat = (data, chatScrn, mainState) =>
				Effect_gen(function* () {
					const chatFontSize = yield* getChatFontSize(mainState)
					;(yield* pipe(
						Effect_succeed({
							data,
							element: emptyElement,
							lane: -1,
							animationState: Either_left("NotStarted"),
							width: 2,
							height: chatFontSize,
							y: 0,
						}),
						Effect_flatMap(x => getChatLane(x, Option_none(), 0)(mainState)),
						Effect_map(
							({ interval }) =>
								!intervalTooSmall(interval)(mainState.config.value),
						),
					)) &&
						(yield* pipe(
							SynchronizedRef_get(mainState.flowChats),
							Effect_flatMap(chats =>
								findFirstIndex(
									chats,
									chat =>
										match(chat.animationState, {
											onLeft: x => "Ended" === x,
											onRight: () => !1,
										}) || chats.length >= mainState.config.value.maxChatCount,
								),
							),
							Effect_matchEffect({
								onFailure: () =>
									pipe(
										Effect_sync(() => document.createElement("span")),
										Effect_tap(element =>
											Effect_sync(() => chatScrn.append(element)),
										),
										Effect_tap(element =>
											Effect_sync(() => element.classList.add("fyc_chat")),
										),
										Effect_zipLeft(Effect_logDebug("Flow chat element added")),
									),
								onSuccess: index =>
									pipe(
										Effect_gen(function* () {
											const chat = pipe(
												yield* SynchronizedRef_get(mainState.flowChats),
												Array_unsafeGet(index),
											)
											yield* SynchronizedRef_update(
												mainState.flowChats,
												Array_remove(index),
											)
											yield* chat.animationState.pipe(
												Effect_tap(animation =>
													Effect_sync(() => animation.cancel()),
												),
												Effect_ignore,
											)
											return chat.element
										}),
									),
							}),
							Effect_map(element => ({
								data,
								element,
								lane: -1,
								animationState: Either_left("NotStarted"),
								width: 2,
								height: chatFontSize,
								y: 0,
							})),
							Effect_flatMap(flowChat =>
								pipe(
									Effect_succeed(mainState),
									Effect_tap(renderChat(flowChat)),
									Effect_flatMap(setChatAnimation(flowChat)),
									Effect_matchEffect({
										onFailure: () =>
											pipe(
												Effect_sync(() => flowChat.element.remove()),
												Effect_zipLeft(
													Effect_logDebug("Flow chat element removed"),
												),
											),
										onSuccess: x =>
											SynchronizedRef_update(
												mainState.flowChats,
												Array_append(x.newChat),
											),
									}),
								),
							),
						))
				})
		__webpack_require__.dn(addFlowChat)
		const appendChatMessage = flip(chat =>
				Effect_flatMap(x =>
					Effect_sync(() => chat.querySelector("#content #message")?.append(x)),
				),
			),
			template = Effect_runPromise(
				pipe(
					Effect_succeed(document.createElement("button")),
					Effect_tap(x =>
						Effect_sync(() =>
							x.classList.add("style-scope", "yt-icon-button", "fyc_button"),
						),
					),
					Effect_tap(x =>
						Effect_sync(() =>
							Object.assign(x.style, {
								padding: "0px",
								width: "20px",
								height: "20px",
								fill: "#fff",
							}),
						),
					),
					Effect_tap(x =>
						Effect_sync(() =>
							x.setAttribute("aria-label", "NGに入れる(Ban this user)"),
						),
					),
					Effect_tap(x =>
						Effect_sync(() => {
							const svg = document.createElementNS(
								"http://www.w3.org/2000/svg",
								"svg",
							)
							svg.setAttribute("class", "style-scope yt-icon")
							Object.assign(svg.style, {
								width: "100%",
								height: "75%",
								fill: "var(--yt-spec-text-secondary)",
							})
							svg.setAttribute("viewBox", "0 0 512 512")
							const path = document.createElementNS(
								"http://www.w3.org/2000/svg",
								"path",
							)
							path.setAttribute(
								"d",
								"M440 78A256 256 0 1 0 73 435 256 256 0 0 0 440 78zm-99 35L113 341C37 179 212 44 341 113zM177 405l228-228c76 162-99 297-228 228z",
							)
							path.setAttribute("fill-rule", "evenodd")
							svg.appendChild(path)
							x.appendChild(svg)
						}),
					),
				),
			),
			banButton = id => getConfig => setConfig => chat =>
				pipe(
					getConfig.bannedUsers,
					Effect_filterOrFail(x => !x.includes(id)),
					Effect_map(x =>
						pipe(dedupeWith(x, String_Equivalence), Array_append(id)),
					),
					Effect_flatMap(x => pipe(setConfig.bannedUsers(x))),
					Effect_ignore,
					Effect_zipRight(
						Effect_sync(() => {
							chat.style.display = "none"
						}),
					),
					onclick =>
						pipe(
							Effect_promise(() => template),
							Effect_map(x => x.cloneNode(!0)),
							Effect_tap(x =>
								Effect_sync(() => {
									x.onclick = () => Effect_runPromise(onclick)
								}),
							),
						),
				)
		__webpack_require__.dn(banButton)
		const forbiddenProperties = new Set([
				"__proto__",
				"constructor",
				"prototype",
			]),
			unaryOperations = {
				"!": x => !isTruthy(x),
				"-": x => -Number(x),
				"+": x => Number(x),
			},
			binaryOperations = {
				"==": (l, r) => l == r,
				"!=": (l, r) => l != r,
				"===": (l, r) => l === r,
				"!==": (l, r) => l !== r,
				"<": (l, r) => l < r,
				">": (l, r) => l > r,
				"<=": (l, r) => l <= r,
				">=": (l, r) => l >= r,
				"+": (l, r) => l + r,
				"-": (l, r) => l - r,
				"*": (l, r) => l * r,
				"/": (l, r) => l / r,
				"%": (l, r) => l % r,
			},
			evaluateExpression = context => expression => {
				const evaluate = evaluateExpression(context),
					exp = expression
				switch (exp.type) {
					case "Literal":
						return exp.value
					case "Identifier":
						if (!Object.hasOwn(context, exp.name))
							throw new Error(
								`Unknown identifier in filter expression: ${exp.name}`,
							)
						return context[exp.name]
					case "ArrayExpression":
						return exp.elements.map(x => (null === x ? void 0 : evaluate(x)))
					case "MemberExpression": {
						const property = exp.computed
							? evaluate(exp.property)
							: exp.property.name
						return ((object, property) => {
							if (null == object)
								throw new Error(
									"Cannot read a property of null/undefined in a filter expression",
								)
							const key =
								"string" == typeof property
									? property
									: "number" == typeof property
										? String(property)
										: void 0
							if (void 0 === key)
								throw new Error(
									"Filter expression property names must be strings or numbers",
								)
							if (forbiddenProperties.has(key))
								throw new Error(
									`Property "${key}" is not allowed in filter expressions`,
								)
							const record = object
							return Object.hasOwn(record, key) ? record[key] : void 0
						})(evaluate(exp.object), property)
					}
					case "CallExpression": {
						const fn = evaluate(exp.callee)
						if ("function" != typeof fn)
							throw new Error("Filter expression tried to call a non-function")
						return fn(...exp.arguments.map(evaluate))
					}
					case "UnaryExpression": {
						const operation = unaryOperations[exp.operator]
						if (void 0 === operation)
							throw new Error(`Unsupported unary operator: ${exp.operator}`)
						return operation(evaluate(exp.argument))
					}
					case "BinaryExpression": {
						const left = evaluate(exp.left)
						if ("||" === exp.operator)
							return isTruthy(left) ? left : evaluate(exp.right)
						if ("&&" === exp.operator)
							return isTruthy(left) ? evaluate(exp.right) : left
						const operation = binaryOperations[exp.operator]
						if (void 0 === operation)
							throw new Error(`Unsupported binary operator: ${exp.operator}`)
						return operation(left, evaluate(exp.right))
					}
					case "ConditionalExpression":
						return isTruthy(evaluate(exp.test))
							? evaluate(exp.consequent)
							: evaluate(exp.alternate)
					case "Compound":
					case "SequenceExpression":
						return ("Compound" === exp.type ? exp.body : exp.expressions)
							.map(evaluate)
							.at(-1)
					default:
						throw new Error(`Unsupported expression type: ${expression.type}`)
				}
			},
			filter_evaluateExpression = evaluateExpression,
			fromSemigroup = (S, empty) => ({
				combine: S.combine,
				combineMany: S.combineMany,
				empty,
				combineAll: collection => S.combineMany(empty, collection),
			}),
			Semigroup_make = (
				combine,
				combineMany = (self, collection) =>
					(function (b, f) {
						return function (iterable) {
							if (Array.isArray(iterable)) return iterable.reduce(f, b)
							let result = b
							for (const n of iterable) result = f(result, n)
							return result
						}
					})(
						self,
						combine,
					)(collection),
			) => ({ combine, combineMany }),
			SemigroupEvery = Semigroup_make(
				(self, that) => self && that,
				(self, collection) => {
					if (!1 === self) return !1
					for (const b of collection) if (!1 === b) return !1
					return !0
				},
			),
			SemigroupSome = Semigroup_make(
				(self, that) => self || that,
				(self, collection) => {
					if (!0 === self) return !0
					for (const b of collection) if (!0 === b) return !0
					return !1
				},
			),
			MonoidEvery = fromSemigroup(SemigroupEvery, !0),
			MonoidSome = fromSemigroup(SemigroupSome, !1),
			filterOperators = {
				flip,
				flow: fns => x => pipe(x, ...fns),
				and: MonoidEvery.combineAll,
				or: MonoidSome.combineAll,
				A: { some: Array_some, getSomes: Array_getSomes },
				O: { exists },
				inText: text => x => {
					return ((searchString = x),
					self => self.includes(searchString, void 0))(text)
					var searchString
				},
				eqText: text => x => text === x,
				matchedByText: text => x => isTruthy(text.match(RegExp(x, "u"))),
			},
			filter_filterOperators = filterOperators,
			filterContext = data => ({
				...filter_filterOperators,
				authorName: data.authorName,
				message: data.message,
				messageText: data.messageText,
				paymentInfo: data.paymentInfo,
				authorID: data.authorID,
			})
		__webpack_require__.dn(filterContext)
		const checkBannedWords = (data, config) =>
			pipe(
				Effect_succeed(data),
				Effect_filterOrFail(x =>
					Boolean(
						filter_evaluateExpression(filterContext(x))(config.filterExp),
					),
				),
				Effect_map(x => [x.message, x.paymentInfo]),
				Effect_flatMap(Effect_forEach(Effect_orElse(() => Effect_succeed("")))),
				Effect_map(JSON.stringify),
				Effect_flatMap(x => Effect_logDebug(`Filtered: ${x}`)),
				Effect_isSuccess,
			)
		__webpack_require__.dn(checkBannedWords)
		const parseChat = chat => {
			const chatType = chat.querySelector(
					".yt-live-chat-ticker-paid-message-item-renderer",
				)
					? "ticker"
					: chat.querySelector(".yt-live-chat-membership-item-renderer")
						? "membership"
						: chat.querySelector(
									".yt-live-chat-viewer-engagement-message-renderer",
							  )
							? "engagement"
							: "normal",
				paymentInfo = pipe(
					"ticker" === chatType || null !== chat.querySelector("#card"),
					isPaid =>
						Option_fromNullable(
							isPaid
								? chat.querySelector(
										join(", ")([
											"#purchase-amount",
											"#purchase-amount-chip",
											"#content>#text",
										]),
									)?.textContent
								: void 0,
						),
				),
				messageElement = Option_fromNullable(chat.querySelector("#message")),
				isPaidNormal =
					Option_isSome(paymentInfo) &&
					isTruthy(chat.querySelector(".yt-live-chat-paid-message-renderer")),
				isPaidSticker =
					Option_isSome(paymentInfo) &&
					!isPaidNormal &&
					isTruthy(chat.querySelector(".yt-live-chat-paid-sticker-renderer")),
				visibleBackgroundColor = element =>
					pipe(
						window
							.getComputedStyle(element)
							.getPropertyValue("background-color"),
						Option_liftPredicate(
							x => "transparent" !== x && "rgba(0, 0, 0, 0)" !== x,
						),
					)
			return {
				chatType,
				authorType: chat.querySelector(".owner")
					? "owner"
					: chat.querySelector(".moderator")
						? "moderator"
						: chat.querySelector(".member")
							? "member"
							: "normal",
				authorID: pipe(
					chat
						.querySelector(join(" ")(["#author-photo", "img"]))
						?.src.match(/ggpht\.com\/(ytc\/)?(.*)=/),
					authorPhotoMatches => Option_fromNullable(authorPhotoMatches?.at(-1)),
				),
				authorName: Option_fromNullable(
					chat.querySelector("#author-name")?.textContent,
				),
				timestamp: Option_fromNullable(
					chat.querySelector("#timestamp")?.textContent,
				),
				messageElement,
				message: pipe(
					messageElement,
					Option_map(x => x.innerHTML),
				),
				messageText: pipe(
					messageElement,
					Option_map(x => x.textContent ?? ""),
				),
				paymentInfo,
				textColor: isPaidNormal
					? pipe(
							Option_fromNullable(chat.querySelector("#header")),
							Option_flatMap(visibleBackgroundColor),
							Option_orElse(() =>
								pipe(
									Option_fromNullable(chat.querySelector("#card")),
									Option_flatMap(visibleBackgroundColor),
								),
							),
							Option_orElse(() =>
								pipe(
									Option_fromNullable(chat.querySelector("#content")),
									Option_flatMap(visibleBackgroundColor),
								),
							),
						)
					: isPaidSticker
						? Option_some(
								window
									.getComputedStyle(chat)
									.getPropertyValue(
										"--yt-live-chat-paid-sticker-chip-background-color",
									),
							)
						: Option_none(),
				paidColor: isPaidNormal
					? pipe(
							Option_fromNullable(chat.querySelector("#content")),
							Option_flatMap(visibleBackgroundColor),
							Option_orElse(() =>
								pipe(
									Option_fromNullable(chat.querySelector("#card")),
									Option_flatMap(visibleBackgroundColor),
								),
							),
							Option_orElse(() =>
								pipe(
									Option_fromNullable(chat.querySelector("#header")),
									Option_flatMap(visibleBackgroundColor),
								),
							),
						)
					: isPaidSticker
						? Option_some(
								window
									.getComputedStyle(chat)
									.getPropertyValue(
										"--yt-live-chat-paid-sticker-background-color",
									),
							)
						: Option_none(),
			}
		}
		__webpack_require__.dn(parseChat)
		const setChatFieldSimplifyStyle = chat =>
			Effect_gen(function* () {
				chat.querySelector(".style-scope.yt-live-chat-paid-message-renderer") ||
					(yield* pipe(
						[
							"#author-photo",
							"yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer",
						],
						Array_map(x => Option_fromNullable(chat.querySelector(x))),
						Array_getSomes,
						Array_map(x =>
							Effect_sync(() => {
								x.style.display = "none"
							}),
						),
						Array_append(
							Effect_sync(() => {
								chat.style.borderBottom =
									"1px solid var(--yt-spec-text-secondary)"
							}),
						),
						Effect_all,
					))
			})
		__webpack_require__.dn(setChatFieldSimplifyStyle)
		const strictOptionEquivalence =
				((isEquivalent = strict()),
				Equivalence_make((x, y) =>
					Option_isNone(x)
						? Option_isNone(y)
						: !Option_isNone(y) && isEquivalent(x.value, y.value),
				)),
			onChatFieldMutate = (chatScrn, mainState) => records =>
				pipe(
					Effect_succeed(records),
					Effect_map(Array_flatMap(e => Array.from(e.addedNodes))),
					Effect_map(Array_filter(x => x.children.length > 0)),
					Effect_map(Array_reverse),
					Effect_flatMap(
						Effect_forEach(chat =>
							Effect_gen(function* () {
								yield* Effect_logDebug("Chat detected")
								const data = parseChat(chat)
								;(yield* checkBannedWords(data, mainState.config.value))
									? (chat.style.display = "none")
									: yield* Effect_all(
											[
												pipe(
													addFlowChat(data, chatScrn, mainState),
													Effect_when(
														pipe(
															yield* SynchronizedRef_get(mainState.flowChats),
															flowChats => () =>
																mainState.config.value.createChats &&
																"normal" === data.chatType &&
																!Array_some(
																	flowChats,
																	x =>
																		Either_isRight(x.animationState) &&
																		strictOptionEquivalence(
																			x.data.authorID,
																			data.authorID,
																		) &&
																		strictOptionEquivalence(
																			x.data.messageText,
																			data.messageText,
																		) &&
																		strictOptionEquivalence(
																			x.data.timestamp,
																			data.timestamp,
																		),
																),
														),
													),
												),
												data.authorID.pipe(
													filter(
														() =>
															mainState.config.value.createBanButton &&
															!chat.children.namedItem("card"),
													),
													Effect_flatMap(x =>
														appendChatMessage(
															banButton(x)(mainState.config.getConfig)(
																mainState.config.setConfig,
															)(chat),
														)(chat),
													),
													Effect_zipLeft(Effect_logDebug("Ban button added")),
												),
												pipe(
													setChatFieldSimplifyStyle(chat),
													Effect_when(
														() => mainState.config.value.simplifyChatField,
													),
													Effect_zipLeft(Effect_logDebug("Chat simplified")),
												),
											],
											{ mode: "either" },
										)
							}),
						),
					),
				)
		var isEquivalent
		__webpack_require__.dn(onChatFieldMutate)
		const onPlayerResize = (rect, mainState) =>
			pipe(
				Effect_succeed(rect),
				Effect_tap(x =>
					Effect_logDebug(
						`Resize [${x.width.toFixed(1)}, ${x.height.toFixed(1)}]`,
					),
				),
				Effect_flatMap(r => SynchronizedRef_set(mainState.playerRect, r)),
				Effect_zipRight(SynchronizedRef_get(mainState.flowChats)),
				Effect_flatMap(
					Effect_forEach(x =>
						Effect_all([
							renderChat(x)(mainState),
							Effect_ignore(setChatAnimation(x)(mainState)),
						]),
					),
				),
			)
		__webpack_require__.dn(onPlayerResize)
		const observePair = con =>
			Effect_gen(function* () {
				const pubsub = yield* PubSub_unbounded(),
					runtime = yield* Effect_runtime(),
					runPublish = Runtime_runSync(runtime)
				return {
					stream: Stream_fromPubSub(pubsub),
					observer: new con(a => {
						runPublish(PubSub_publish(pubsub, a))
					}),
				}
			})
		__webpack_require__.dn(observePair)
		const toggleEvents = [
				["playing", !0],
				["waiting", !1],
				["pause", !1],
			],
			videoToggleStream = video =>
				Stream_mergeAll(
					Array_map(toggleEvents, ([type, playing]) =>
						Stream_map(Stream_fromEventListener(video, type), () => playing),
					),
					{ concurrency: "unbounded" },
				)
		__webpack_require__.dn(videoToggleStream)
		const updateSettingsRect =
			toggleSettingsElement => nextSettingsRect => last =>
				pipe(
					Effect_succeed(toggleSettingsElement),
					Effect_filterOrFail(x => null !== x.offsetParent),
					Effect_map(x => x.getBoundingClientRect()),
					Effect_map(
						x =>
							new DOMRectReadOnly(
								Math.max(0, x.right + window.scrollX - 660),
								Math.max(0, x.y + window.scrollY - 395),
								660,
								Math.min(x.y + window.scrollY, 395),
							),
					),
					Effect_orElseSucceed(() => new DOMRectReadOnly(-660, -395, 660, 395)),
					Effect_filterOrFail(
						x =>
							x.x !== last.x ||
							x.y !== last.y ||
							x.width !== last.width ||
							x.height !== last.height,
					),
					Effect_tap(nextSettingsRect),
					Effect_ignore,
				)
		__webpack_require__.dn(updateSettingsRect)
		const allStream = provideLog => ctx =>
			Effect_gen(function* () {
				const live = makePageState(livePageYt),
					css = yield* mainCss,
					documentMutationPair = yield* observePair(MutationObserver),
					chatMutationPair = yield* observePair(MutationObserver),
					playerResizePair = yield* observePair(ResizeObserver),
					bodyResizePair = yield* observePair(ResizeObserver),
					liveElementKeys = Object.keys(live),
					settingsRect = yield* SubscriptionRef_make(
						new DOMRectReadOnly(0, 0, 660, 395),
					),
					tapUpdateSettingsRect = stream =>
						Stream_tap(stream, () =>
							provideLog(
								pipe(
									(self => Ref_get(self.ref))(settingsRect),
									Effect_flatMap(
										updateSettingsRect(ctx.apps.toggleSettingsPanelApp.node)(
											rect => SubscriptionRef_set(settingsRect, rect),
										),
									),
								),
							),
						),
					config$ = configStream(
						provideLog,
						ctx.mainState,
						ctx.configRefs,
						ctx.chatScreen,
						live,
					),
					pollChanged = provideLog(
						pipe(
							Effect_succeed(liveElementKeys),
							Effect_flatMap(
								Effect_forEach(key =>
									live[key].read.pipe(
										Effect_option,
										Effect_flatMap(
											Option_liftPredicate(
												newEle =>
													!strictOptionEquivalence(live[key].ele, newEle),
											),
										),
										Effect_tap(x =>
											Effect_sync(() => {
												live[key].ele = x
											}),
										),
										Effect_map(Option_isSome),
										Effect_map(x => `${key} ${x ? "found" : "lost"}`),
										Effect_flatMap(Effect_logDebug),
										Effect_isSuccess,
									),
								),
							),
							Effect_map(Array_some(identity)),
						),
					),
					setup = provideLog(
						Effect_suspend(() =>
							pipe(
								Effect_logDebug("Loading..."),
								Effect_zipRight(
									Effect_sync(() => {
										;[
											documentMutationPair,
											chatMutationPair,
											playerResizePair,
											bodyResizePair,
										].forEach(pair => {
											pair.observer.disconnect()
										})
										documentMutationPair.observer.observe(document, {
											childList: !0,
											subtree: !0,
										})
										document.head.append(css)
									}),
								),
								Effect_zipRight(
									Effect_allSuccesses([
										...Array_map(
											[live.chatField.ele, live.chatTicker.ele],
											Effect_flatMap(x =>
												Effect_sync(() =>
													chatMutationPair.observer.observe(x, {
														childList: !0,
													}),
												),
											),
										),
										live.player.ele.pipe(
											Effect_flatMap(element =>
												pipe(
													Effect_succeed(element),
													Effect_tap(x =>
														Effect_sync(() =>
															playerResizePair.observer.observe(x),
														),
													),
													Effect_flatMap(x =>
														Effect_sync(() => x.prepend(ctx.chatScreen)),
													),
												),
											),
										),
										live.toggleChatBtnParent.ele.pipe(
											Effect_flatMap(x =>
												Effect_sync(() =>
													x.prepend(ctx.apps.toggleChatButtonApp.node),
												),
											),
										),
										live.settingsToggleNextElement.ele.pipe(
											Effect_flatMap(x =>
												Effect_sync(() =>
													x.before(ctx.apps.toggleSettingsPanelApp.node),
												),
											),
											Effect_orElse(() =>
												live.toggleChatBtnParent.ele.pipe(
													Effect_flatMap(() =>
														Effect_sync(() =>
															ctx.apps.toggleChatButtonApp.node.before(
																ctx.apps.toggleSettingsPanelApp.node,
															),
														),
													),
												),
											),
										),
										live.settingsContainer.ele.pipe(
											Effect_flatMap(x =>
												Effect_sync(() => x.append(ctx.apps.settingsApp.node)),
											),
										),
										pipe(
											document.body,
											Effect_fromNullable,
											Effect_flatMap(x =>
												Effect_sync(() => bodyResizePair.observer.observe(x)),
											),
										),
										live.video.ele.pipe(
											Effect_filterOrElse(
												x => !x.paused,
												() => live.offlineSlate.ele,
											),
											Effect_isSuccess,
											Effect_flatMap(x =>
												SynchronizedRef_set(ctx.mainState.chatPlaying, x),
											),
										),
									]),
								),
							),
						),
					),
					main = pipe(
						Stream_fromQueue(ctx.reinitQueue),
						Stream_mapEffect(() =>
							pipe(
								Effect_sleep("100 millis"),
								Effect_zipRight(provideLog(Effect_logInfo("Init"))),
							),
						),
						Stream_flatMap(
							() =>
								pipe(
									(schedule =>
										pipe(
											Schedule_driver(schedule),
											Effect_map(driver => {
												return (
													(effect = driver.next(void 0)),
													repeatEffectChunkOption(
														pipe(effect, Effect_map(Chunk_of)),
													)
												)
												var effect
											}),
											stream_unwrap,
										))(Schedule_fixed("700 millis")),
									tapUpdateSettingsRect,
									Stream_mapEffect(() => pollChanged),
									Stream_filter(identity),
									s => Stream_concat(Stream_make(!0), s),
									Stream_tap(() => setup),
									Stream_flatMap(
										() =>
											Stream_mergeAll(
												[
													pipe(
														Stream_fromEventListener(ctx.channel, "message"),
														Stream_mapEffect(([key, val]) =>
															provideLog(
																pipe(
																	src_listeningBroadcastConfigKeys.includes(
																		key,
																	),
																	x =>
																		x
																			? ctx.setChangedConfig[key](val)
																			: Effect_sync(() => {}),
																),
															),
														),
													),
													...pipe(
														configKeys,
														Array_map(key =>
															pipe(
																ctx.configRefs[key].changes,
																Stream_zipWithPrevious,
																Stream_filterMap(([previous, next]) =>
																	Option_map(previous, x =>
																		configDiff(x, next),
																	),
																),
																Stream_mapEffect(x =>
																	provideLog(
																		Effect_logDebug(
																			`Config ${key}: ${JSON.stringify(x, void 0, 2)}`,
																		),
																	),
																),
															),
														),
													),
													config$,
													live.video.ele.pipe(
														Option_match({
															onNone: () => Stream_empty,
															onSome: element =>
																pipe(
																	videoToggleStream(element),
																	Stream_map(
																		playing =>
																			playing ||
																			Option_isSome(live.offlineSlate.ele),
																	),
																	Stream_mapEffect(chatPlaying =>
																		provideLog(
																			pipe(
																				SynchronizedRef_set(
																					ctx.mainState.chatPlaying,
																					chatPlaying,
																				),
																				Effect_zipRight(
																					pipe(
																						SynchronizedRef_get(
																							ctx.mainState.flowChats,
																						),
																						Effect_map(
																							Array_map(setChatPlayState),
																						),
																						Effect_flatMap(
																							Effect_forEach(
																								apply(ctx.mainState),
																							),
																						),
																					),
																				),
																			),
																		),
																	),
																),
														}),
													),
													pipe(
														chatMutationPair.stream,
														Stream_mapEffect(records =>
															provideLog(
																onChatFieldMutate(
																	ctx.chatScreen,
																	ctx.mainState,
																)(records),
															),
														),
													),
													pipe(
														documentMutationPair.stream,
														Stream_map(() => window.location.href),
														Stream_changes,
														Stream_drop(1),
														tapUpdateSettingsRect,
														Stream_mapEffect(x =>
															provideLog(
																Effect_all([
																	Effect_logDebug(`URL Changed: ${x}`),
																	removeOldChats(ctx.mainState.flowChats)(0),
																]),
															),
														),
														Stream_mapEffect(() =>
															pipe(
																Effect_sleep("1700 millis"),
																Effect_zipRight(ctx.reinitialize),
															),
														),
													),
													pipe(
														playerResizePair.stream,
														throttleLatest("500 millis"),
														s => Stream_concat(Stream_succeed([]), s),
														Stream_mapEffect(() =>
															provideLog(
																live.player.ele.pipe(
																	Option_map(x => x.getBoundingClientRect()),
																	Option_match({
																		onNone: () => _void,
																		onSome: x =>
																			onPlayerResize(x, ctx.mainState),
																	}),
																),
															),
														),
													),
													pipe(
														bodyResizePair.stream,
														throttleLatest("300 millis"),
														s => Stream_concat(Stream_succeed([]), s),
														tapUpdateSettingsRect,
													),
													pipe(
														settingsRect.changes,
														Stream_mapEffect(panelRect =>
															ctx.updateSettingState(s => ({
																...s,
																panelRect,
															})),
														),
													),
												],
												{ concurrency: "unbounded" },
											),
										{ switch: !0 },
									),
								),
							{ switch: !0 },
						),
					),
					resilient = self =>
						pipe(
							self,
							Stream_catchAllCause(cause =>
								Stream_unwrap(
									pipe(
										provideLog(
											logWithMeta(LogLevel_Error)(
												`Errored: ${Cause_pretty(cause)}`,
											)(squash(cause)),
										),
										Effect_zipRight(Effect_sleep("5 seconds")),
										Effect_zipRight(ctx.reinitialize),
										Effect_as(resilient(self)),
									),
								),
							),
						)
				return resilient(main)
			})
		__webpack_require__.dn(allStream)
		var fast_deep_equal = __webpack_require__(371),
			fast_deep_equal_default = __webpack_require__.n(fast_deep_equal)
		const setterFromKeysAndMap = keys => f =>
			pipe(
				keys,
				Array_map(x => [x, f(x)]),
				Object.fromEntries,
			)
		__webpack_require__.dn(setterFromKeysAndMap)
		const configWriteFunnel = ({
			configValue,
			configRefs,
			configKeys,
			dispatchToSettings,
			broadcastAndPersist,
			defaultFilterExp,
		}) => {
			const writeBase = key => val =>
					pipe(
						Effect_sync(() => {
							Object.assign(configValue, { [key]: val })
						}),
						Effect_zipRight(SubscriptionRef_set(configRefs[key], val)),
					),
				setterFromMap = setterFromKeysAndMap(configKeys),
				setConfigPlain = setterFromMap(
					key => val =>
						pipe(
							writeBase(key)(val),
							Effect_zipRight(
								(
									key => val =>
										pipe(
											dispatchToSettings(key)(val),
											Effect_zipRight(
												pipe(
													["bannedWords", "bannedUsers", "bannedWordRegexes"],
													Array_containsWith(String_Equivalence)(key),
													x =>
														x
															? Effect_suspend(() =>
																	(val =>
																		pipe(
																			Effect_sync(() => configValue.filterExp),
																			Effect_filterOrFail(
																				x => !fast_deep_equal_default()(x, val),
																			),
																			Effect_flatMap(() =>
																				pipe(
																					writeBase("filterExp")(val),
																					Effect_zipRight(
																						dispatchToSettings("filterExp")(
																							val,
																						),
																					),
																				),
																			),
																			Effect_zipRight(
																				broadcastAndPersist("filterExp")(val),
																			),
																			Effect_ignore,
																		))(defaultFilterExp()),
																)
															: _void,
												),
											),
										)
								)(key)(val),
							),
						),
				),
				changedConfigMap = key => val =>
					pipe(
						Effect_sync(() => configValue[key]),
						Effect_filterOrFail(x => !fast_deep_equal_default()(x, val)),
						Effect_flatMap(() => setConfigPlain[key](val)),
					)
			return {
				setConfigPlain,
				setChangedConfig: setterFromMap(
					key => val => changedConfigMap(key)(val).pipe(Effect_ignore),
				),
				setConfig: setterFromMap(
					key => val =>
						changedConfigMap(key)(val).pipe(
							Effect_zipRight(broadcastAndPersist(key)(val)),
							Effect_ignore,
						),
				),
			}
		}
		__webpack_require__.dn(configWriteFunnel)
		const defaultFilter = config =>
			external_jsep_default()(
				`\nor([\nA.some(\n  flip(flow([inText, A.some]))(${JSON.stringify(config.bannedWords)})\n)(A.getSomes([\n  messageText,\n  paymentInfo\n])),\nA.some(\n  flip(flow([matchedByText, A.some]))(${JSON.stringify(config.bannedWordRegexes)})\n)(A.getSomes([\n  messageText,\n  paymentInfo\n])),\nO.exists(\n  flip(flow([eqText, A.some]))(${JSON.stringify(config.bannedUsers)})\n)(authorID)\n])\n`,
			)
		__webpack_require__.dn(defaultFilter)
		const makeChatScreen = pipe(
				Effect_sync(() => document.createElement("div")),
				Effect_tap(x =>
					Effect_sync(() =>
						Object.assign(x.style, {
							pointerEvents: "none",
							zIndex: "30",
							position: "absolute",
							overflow: "hidden",
							height: "100%",
							width: "100%",
						}),
					),
				),
			),
			Editable_of = x => [x, Option_none()],
			fromValueText = v => t => [v, Option_some([t, Option_none()])],
			Editable_value = getFirst,
			Editable_text = x => pipe(getSecond(x), Option_map(getFirst)),
			Editable_error = x => pipe(getSecond(x), Option_flatMap(getSecond)),
			setValue = v => pipe(constant(v), x => mapFirst(x)),
			setText = x =>
				mapSecond(snd =>
					snd.pipe(
						Option_map(mapFirst(constant(x))),
						Option_orElse(constant(Option_some([x, Option_none()]))),
					),
				),
			hasError = x => Option_isSome(Editable_error(x)),
			exceptions = ["timingFunction", "lang"],
			isEditable = k => v =>
				("number" == typeof v ||
					"string" == typeof v ||
					(Array.isArray(v) && ("string" == typeof v[0] || 0 === v.length))) &&
				!Array_some(x => x === k)(exceptions)
		__webpack_require__.dn(isEditable)
		const setSettingFromConfig = key => value => state => ({
			...state,
			[key]: isEditable(key)(value)
				? setValue(value)(state[key])
				: "filterExp" === key
					? void 0
					: value,
		})
		__webpack_require__.dn(setSettingFromConfig)
		const RefinedConstructorsTypeId = Symbol.for("effect/Brand/Refined"),
			nominal = () =>
				Object.assign(args => args, {
					[RefinedConstructorsTypeId]: RefinedConstructorsTypeId,
					option: args => Option_some(args),
					either: args => Either_right(args),
					is: _args => !0,
				}),
			external_LZString_namespaceObject = LZString,
			makeCompressedLogBlock = nominal(),
			makeLog = nominal(),
			decompressBlock = x =>
				pipe(
					(0, external_LZString_namespaceObject.decompressFromUTF16)(x),
					JSON.parse,
				),
			importLog = s =>
				makeLog(
					pipe(
						"<" === s[0] ? s.slice(5, -6) : s,
						x => JSON.parse(x),
						log => ({
							nextId: log.nextId,
							...pipe(
								log.blocks,
								Array_map(
									external_LZString_namespaceObject.decompressFromEncodedURIComponent,
								),
								matchRight({
									onEmpty: () => ({ compressedBlocks: [], lastBlock: [] }),
									onNonEmpty: (init, last) => ({
										compressedBlocks: Array_map(init, x =>
											pipe(
												(0, external_LZString_namespaceObject.compressToUTF16)(
													x,
												),
												makeCompressedLogBlock,
											),
										),
										lastBlock: JSON.parse(last),
									}),
								}),
							),
						}),
					),
				),
			settingStateInit = config =>
				pipe(
					config,
					mapObject(([k, v]) => [
						k,
						isEditable(k)(v) ? Editable_of(v) : "filterExp" === k ? void 0 : v,
					]),
					x => ({
						...x,
						showPanel: !1,
						mainTab: 0,
						logTab: 0,
						timingStepCount: Editable_of(
							parseInt(
								config.timingFunction.match(/^steps\((\d+),.+/)?.[1] ?? "150",
								10,
							),
						),
						eventLog: makeLog({
							nextId: 0,
							compressedBlocks: [],
							lastBlock: [],
						}),
						panelRect: new DOMRectReadOnly(0, 0, 660, 395),
					}),
				)
		__webpack_require__.dn(settingStateInit)
		const makeComponent = x => tag => ({ tag, view: x(tag) }),
			node_option = (value, label, selected) =>
				h("option", { value, selected }, hyperapp_text(label))
		__webpack_require__.dn(node_option)
		const tabContainer = style => ontabSelect => labels => tabs => mainTab =>
			h("div", { style: style.container }, [
				h(
					"div",
					{},
					pipe(
						labels,
						Array_map((x, i) =>
							h(
								"span",
								{
									style: {
										...style.label,
										...(mainTab === i ? style.labelFocus : {}),
										display: "inline-block",
									},
									onpointerdown: [ontabSelect, i],
								},
								hyperapp_text(x),
							),
						),
					),
				),
				h(
					"div",
					{
						style: { ...style.tab, overflow: "auto", boxSizing: "border-box" },
					},
					pipe(
						tabs,
						Array_get(mainTab),
						Option_match({ onNone: () => {}, onSome: x => x() }),
					),
				),
			])
		__webpack_require__.dn(tabContainer)
		const defaultText = {
				setting: ["Settings", "設定", "设置"],
				font: ["Font", "フォント", "字体"],
				color: ["Color(Normal)", "色(通常)", "颜色(正常)"],
				ownerColor: ["Color(Owner)", "色(オーナー)", "颜色(主人)"],
				moderatorColor: [
					"Color(Moderator)",
					"色(モデレーター)",
					"颜色(管理员)",
				],
				memberColor: ["Color(Member)", "色(メンバー)", "颜色(成员)"],
				feedback: ["Feedback", "バグ報告と要望", "反馈"],
				eventLog: ["Event log", "イベントログ", "事件日志"],
				giveFeedback: [
					"Give your feedbacks here(Please attach the event log for bug reports)",
					"バグ報告、要望はこちら(バグの場合は、イベントログを添付してください)",
					"在此处提供您的反馈(如报告错误,请附上事件日志)",
				],
				chatOpacity: ["Opacity", "不透明度", "不透明度"],
				fontSize: ["Size", "サイズ", "字体大小"],
				fontWeight: ["Weight", "太さ", "字体粗细"],
				shadowFontWeight: ["Shadow Weight", "影の太さ", "阴影粗细"],
				flowSpeed: ["Speed", "速度", "弹幕速度"],
				maxChatCount: ["Max number of chats", "最大表示数", "最大聊天数量"],
				maxChatLength: ["Max number of characters", "最大文字数", "最大字符数"],
				laneCount: ["Number of rows", "行数", "行数"],
				bannedWords: ["Banned Words", "NGワード", "屏蔽词"],
				bannedWordRegexes: [
					"Banned Words(Regex)",
					"NGワード(正規表現)",
					"屏蔽词(正则表达式)",
				],
				bannedUsers: ["Banned Users", "NGユーザー", "屏蔽用户"],
				simplifyChatField: ["Simplify", "簡略化する", "简化聊天栏"],
				createBanButton: [
					"Show ban button",
					"NGボタンを表示する",
					"显示屏蔽按钮",
				],
				displayModName: [
					"Show moderator's name",
					"モデレーターの名前を表示する",
					"显示管理员姓名",
				],
				displaySuperChatAuthor: [
					"Show super chat author",
					"スパチャの作成者を表示する",
					"显示超级留言作者",
				],
				createChats: ["Create flowing chats", "チャットを流す", "创建弹幕"],
				textOnly: [
					"Text only(ignore emojis)",
					"文字のみ(絵文字を無視する)",
					"仅文本(忽略表情符号)",
				],
				error: ["Error", "エラー", "错误"],
				video: ["Video", "画面", "视频"],
				chatField: ["Chat Window", "チャット欄", "聊天窗口"],
				useStepTiming: [
					"Move chat in steps",
					"チャットを段階的に動かす",
					"按步骤移动弹幕",
				],
				timingStepCount: ["└Step Count", "└段階数", "└步骤数"],
				chatFilter: ["Chat Filter", "チャットフィルター", "聊天过滤器"],
				flowChat: ["Flow Chat", "チャット流れ", "聊天弹幕"],
				clearFlowChats: [
					"Clear Flowing Chats",
					"流れるチャットをクリアする",
					"清除弹幕",
				],
				flowNewChatIf: [
					"A new chat will appear if all of the followings are met:",
					"新しいチャットは以下のすべてを満たす場合に流れます:",
					"如果满足以下所有条件,新弹幕会出现:",
				],
				noOverlap: [
					"└Chats won't overlap",
					"└他のチャットと重ならない",
					"└弹幕不会重叠",
				],
				minSpacing: [
					"Min spacing between chats",
					"チャットの最小間隔",
					"弹幕间的最小间距",
				],
				fieldScale: ["Scale", "拡大率", "缩放比例"],
				copy: ["Copy", "コピーする", "复制"],
				showChats: ["Show chats", "チャットを表示する", "显示弹幕"],
				hideChats: ["Hide chats", "チャットを非表示にする", "隐藏弹幕"],
				flowY1: ["Flow area top edge", "流れ範囲の上端", "显示区域上边缘"],
				flowY2: ["Flow area bottom edge", "流れ範囲の下端", "显示区域下边缘"],
				flowX1: ["Flow area left edge", "流れ範囲の左端", "显示区域左边缘"],
				flowX2: ["Flow area right edge", "流れ範囲の右端", "显示区域右边缘"],
				shadowColor: ["Shadow Color", "影の色", "阴影颜色"],
				invalidColor: ["Invalid color", "無効な色", "无效颜色"],
				inputNonNumberic: [
					"Input isn't a number",
					"入力値が数字でない",
					"输入值非数字",
				],
				invalidSetting: ["Invalid setting", "無効な設定値", "无效的设置值"],
				logEvents: [
					"Enable event logging",
					"イベントログを有効にする",
					"启用事件日志",
				],
				importLog: [
					"Import event log",
					"イベントログを取り込む",
					"导入事件日志",
				],
			},
			getText = key => state =>
				pipe(
					languages,
					findFirstIndex(x => x === state.lang),
					Option_map(x => Array_unsafeGet(defaultText[key], x)),
					Option_getOrElse(() => "Error"),
				)
		__webpack_require__.dn(getText)
		const languageLabels = ["English(US)", "日本語", "简体中文"],
			panelBoxStyle = width => ({
				flex: `0 0 ${width}px`,
				width: `${width}px`,
				margin: "2px",
			})
		__webpack_require__.dn(panelBoxStyle)
		const checkboxRow = (label, checked, onchange) =>
			h(
				"div",
				{},
				h("label", {}, [
					hyperapp_text(label),
					h("input", { type: "checkbox", checked, onchange }),
				]),
			)
		__webpack_require__.dn(checkboxRow)
		const checkboxNode = (getText, getState, updateBool) => label => c => s =>
			checkboxRow(getText(label)(s), getState(label)(s), updateBool(label)(c))
		__webpack_require__.dn(checkboxNode)
		const computed = {
				useStepTiming: s => isTruthy(s.timingFunction.match(/^steps\(.+/)),
			},
			getState = k => (k in computed ? computed[k] : s => s[k])
		__webpack_require__.dn(getState)
		const 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)
				}
			},
			memoizeThunk = f => {
				let a,
					done = !1
				return () => {
					if (done) return a
					a = f()
					done = !0
					return a
				}
			},
			util_isNonEmpty = x => Array.isArray(x),
			formatPathKey = key => `[${formatPropertyKey(key)}]`,
			formatPath = path =>
				util_isNonEmpty(path)
					? path.map(formatPathKey).join("")
					: formatPathKey(path),
			getErrorMessage = (reason, details, path, ast) => {
				let out = reason
				path &&
					isNonEmptyReadonlyArray(path) &&
					(out += `\nat path: ${formatPath(path)}`)
				void 0 !== details && (out += `\ndetails: ${details}`)
				ast && (out += `\nschema (${ast._tag}): ${ast}`)
				return out
			},
			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)",
				),
			TypeConstructorAnnotationId = Symbol.for(
				"effect/annotation/TypeConstructor",
			),
			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)
					? Option_some(annotated.annotations[key])
					: Option_none(),
			),
			getBrandAnnotation = getAnnotation(BrandAnnotationId),
			getMessageAnnotation = getAnnotation(MessageAnnotationId),
			getMissingMessageAnnotation = getAnnotation(MissingMessageAnnotationId),
			getTitleAnnotation = getAnnotation(TitleAnnotationId),
			getAutoTitleAnnotation = getAnnotation(AutoTitleAnnotationId),
			getIdentifierAnnotation = getAnnotation(IdentifierAnnotationId),
			getDescriptionAnnotation = getAnnotation(DescriptionAnnotationId),
			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 => !0 === b),
			JSONIdentifierAnnotationId = Symbol.for(
				"effect/annotation/JSONIdentifier",
			),
			getJSONIdentifierAnnotation = getAnnotation(JSONIdentifierAnnotationId)
		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 Option_getOrElse(getExpected(this), () => "<declaration schema>")
			}
			toJSON() {
				return {
					_tag: this._tag,
					typeParameters: this.typeParameters.map(ast => ast.toJSON()),
					annotations: toJSONAnnotations(this.annotations),
				}
			}
		}
		const createASTGuard = tag => ast => ast._tag === tag
		class Literal {
			literal
			annotations
			_tag = "Literal"
			constructor(literal, annotations = {}) {
				this.literal = literal
				this.annotations = annotations
			}
			toString() {
				return Option_getOrElse(getExpected(this), () =>
					formatUnknown(this.literal),
				)
			}
			toJSON() {
				return {
					_tag: this._tag,
					literal: isBigInt(this.literal) ? String(this.literal) : this.literal,
					annotations: toJSONAnnotations(this.annotations),
				}
			}
		}
		const isLiteral = createASTGuard("Literal")
		class UniqueSymbol {
			symbol
			annotations
			_tag = "UniqueSymbol"
			constructor(symbol, annotations = {}) {
				this.symbol = symbol
				this.annotations = annotations
			}
			toString() {
				return Option_getOrElse(getExpected(this), () =>
					formatUnknown(this.symbol),
				)
			}
			toJSON() {
				return {
					_tag: this._tag,
					symbol: String(this.symbol),
					annotations: toJSONAnnotations(this.annotations),
				}
			}
		}
		class NeverKeyword {
			annotations
			_tag = "NeverKeyword"
			constructor(annotations = {}) {
				this.annotations = annotations
			}
			toString() {
				return formatKeyword(this)
			}
			toJSON() {
				return {
					_tag: this._tag,
					annotations: toJSONAnnotations(this.annotations),
				}
			}
		}
		const 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),
				}
			}
		}
		const 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),
				}
			}
		}
		const anyKeyword = new AnyKeyword({ [TitleAnnotationId]: "any" }),
			isStringKeyword = createASTGuard("StringKeyword"),
			isSymbolKeyword = createASTGuard("SymbolKeyword")
		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 ? "?" : "")
			}
		}
		const 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 (const 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 Option_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),
				}
			}
		}
		const formatTuple = ast => {
			const formattedElements = ast.elements.map(String).join(", ")
			return matchLeft(ast.rest, {
				onEmpty: () => `readonly [${formattedElements}]`,
				onNonEmpty: (head, tail) => {
					const formattedHead = String(head),
						wrappedHead = formattedHead.includes(" | ")
							? `(${formattedHead})`
							: formattedHead
					if (tail.length > 0) {
						const formattedTail = tail.map(String).join(", ")
						return ast.elements.length > 0
							? `readonly [${formattedElements}, ...${wrappedHead}[], ${formattedTail}]`
							: `readonly [...${wrappedHead}[], ${formattedTail}]`
					}
					return ast.elements.length > 0
						? `readonly [${formattedElements}, ...${wrappedHead}[]]`
						: `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),
				}
			}
		}
		const 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) {
				this.type = type
				this.isReadonly = isReadonly
				if (!isParameter(parameter))
					throw new Error(getASTIndexSignatureParameterErrorMessage)
				this.parameter = parameter
			}
			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
				const keys = {}
				for (let i = 0; i < propertySignatures.length; i++) {
					const name = propertySignatures[i].name
					if (Object.prototype.hasOwnProperty.call(keys, name))
						throw new Error(
							getErrorMessage(
								"Duplicate property signature",
								`Duplicate key ${formatUnknown(name)}`,
							),
						)
					keys[name] = null
				}
				const parameters = { string: !1, symbol: !1 }
				for (let i = 0; i < indexSignatures.length; i++) {
					const 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 Option_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),
				}
			}
		}
		const formatIndexSignatures = iss => iss.map(String).join("; "),
			formatTypeLiteral = ast => {
				if (ast.propertySignatures.length > 0) {
					const pss = ast.propertySignatures.map(String).join("; ")
					return ast.indexSignatures.length > 0
						? `{ ${pss}; ${formatIndexSignatures(ast.indexSignatures)} }`
						: `{ ${pss} }`
				}
				return ast.indexSignatures.length > 0
					? `{ ${formatIndexSignatures(ast.indexSignatures)} }`
					: "{}"
			},
			sortCandidates = sort(
				Order_mapInput(Number_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",
			},
			SchemaAST_flatten = candidates =>
				Array_flatMap(candidates, ast =>
					isUnion(ast) ? SchemaAST_flatten(ast.types) : [ast],
				)
		class Union {
			types
			annotations
			static make = (types, annotations) =>
				isMembers(types)
					? new Union(types, annotations)
					: 1 === types.length
						? types[0]
						: neverKeyword
			static unify = (candidates, annotations) =>
				Union.make(
					(candidates => {
						const cs = sortCandidates(candidates),
							out = [],
							uniques = {},
							literals = []
						for (const 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": {
									const type = typeof ast.literal
									switch (type) {
										case "string":
										case "number":
										case "bigint":
										case "boolean":
											if (
												!uniques[literalMap[type]] &&
												!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
								}
								case "UniqueSymbol":
									if (
										!uniques.SymbolKeyword &&
										!literals.includes(ast.symbol)
									) {
										literals.push(ast.symbol)
										out.push(ast)
									}
									break
								case "TupleType":
									uniques.ObjectKeyword || out.push(ast)
									break
								case "TypeLiteral":
									if (
										0 === ast.propertySignatures.length &&
										0 === ast.indexSignatures.length
									) {
										if (!uniques["{}"]) {
											uniques["{}"] = ast
											out.push(ast)
										}
									} else uniques.ObjectKeyword || out.push(ast)
									break
								default:
									out.push(ast)
							}
						return out
					})(SchemaAST_flatten(candidates)),
					annotations,
				)
			_tag = "Union"
			constructor(types, annotations = {}) {
				this.types = types
				this.annotations = annotations
			}
			toString() {
				return Option_getOrElse(getExpected(this), () =>
					this.types.map(String).join(" | "),
				)
			}
			toJSON() {
				return {
					_tag: this._tag,
					types: this.types.map(ast => ast.toJSON()),
					annotations: toJSONAnnotations(this.annotations),
				}
			}
		}
		const 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(
					Option_orElse(() =>
						Option_flatMap(
							(
								f =>
								(...a) => {
									try {
										return Option_some(f(...a))
									} catch {
										return Option_none()
									}
								}
							)(this.f)(),
							ast => getExpected(ast),
						),
					),
					Option_getOrElse(() => "<suspended schema>"),
				)
			}
			toJSON() {
				const ast = this.f()
				let out = toJSONMemoMap.get(ast)
				if (out) return out
				toJSONMemoMap.set(ast, { _tag: this._tag })
				out = {
					_tag: this._tag,
					ast: ast.toJSON(),
					annotations: toJSONAnnotations(this.annotations),
				}
				toJSONMemoMap.set(ast, out)
				return out
			}
		}
		class Refinement {
			from
			filter
			annotations
			_tag = "Refinement"
			constructor(from, filter, annotations = {}) {
				this.from = from
				this.filter = filter
				this.annotations = annotations
			}
			toString() {
				return getIdentifierAnnotation(this).pipe(
					Option_getOrElse(() =>
						Option_match(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),
				}
			}
		}
		const isRefinement = createASTGuard("Refinement"),
			defaultParseOption = {},
			SchemaAST_annotations = (ast, overrides) => {
				const d = Object.getOwnPropertyDescriptors(ast),
					base = { ...ast.annotations }
				delete base[IdentifierAnnotationId]
				const value = { ...base, ...overrides },
					surrogate = getSurrogateAnnotation(ast)
				Option_isSome(surrogate) &&
					(value[SurrogateAnnotationId] = SchemaAST_annotations(
						surrogate.value,
						overrides,
					))
				d.annotations.value = value
				return Object.create(Object.getPrototypeOf(ast), d)
			},
			getTemplateLiteralSpanTypePattern = (type, capture) => {
				switch (type._tag) {
					case "Literal":
						return RegExp_escape(String(type.literal))
					case "StringKeyword":
						return "[\\s\\S]*?"
					case "NumberKeyword":
						return "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?"
					case "TemplateLiteral":
						return getTemplateLiteralPattern(type, capture, !1)
					case "Union":
						return type.types
							.map(type => getTemplateLiteralSpanTypePattern(type, 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) {
					const head = RegExp_escape(ast.head)
					pattern += capture && top ? `(${head})` : head
				}
				for (const span of ast.spans) {
					const spanPattern = getTemplateLiteralSpanTypePattern(
						span.type,
						capture,
					)
					pattern += handleTemplateLiteralSpanTypeParens(
						span.type,
						spanPattern,
						capture,
						top,
					)
					if ("" !== span.literal) {
						const literal = RegExp_escape(span.literal)
						pattern += capture && top ? `(${literal})` : literal
					}
				}
				return pattern
			},
			preserveTransformationAnnotations = (annotationIds => annotated => {
				let out
				for (const id of annotationIds)
					if (Object.prototype.hasOwnProperty.call(annotated.annotations, id)) {
						void 0 === out && (out = {})
						out[id] = annotated.annotations[id]
					}
				return out
			})([
				ExamplesAnnotationId,
				DefaultAnnotationId,
				JSONSchemaAnnotationId,
				ArbitraryAnnotationId,
				PrettyAnnotationId,
				EquivalenceAnnotationId,
			]),
			typeAST = ast => {
				switch (ast._tag) {
					case "Declaration": {
						const typeParameters = changeMap(ast.typeParameters, typeAST)
						return typeParameters === ast.typeParameters
							? ast
							: new Declaration(
									typeParameters,
									ast.decodeUnknown,
									ast.encodeUnknown,
									ast.annotations,
								)
					}
					case "TupleType": {
						const elements = changeMap(ast.elements, e => {
								const 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": {
						const propertySignatures = changeMap(ast.propertySignatures, p => {
								const type = typeAST(p.type)
								return type === p.type
									? p
									: new PropertySignature(
											p.name,
											type,
											p.isOptional,
											p.isReadonly,
										)
							}),
							indexSignatures = changeMap(ast.indexSignatures, is => {
								const 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": {
						const 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": {
						const from = typeAST(ast.from)
						return from === ast.from
							? ast
							: new Refinement(from, ast.filter, ast.annotations)
					}
					case "Transformation": {
						const preserve = preserveTransformationAnnotations(ast)
						return typeAST(
							void 0 !== preserve
								? SchemaAST_annotations(ast.to, preserve)
								: ast.to,
						)
					}
				}
				return ast
			}
		function changeMap(as, f) {
			let changed = !1
			const out = allocate(as.length)
			for (let i = 0; i < as.length; i++) {
				const a = as[i],
					fa = f(a)
				fa !== a && (changed = !0)
				out[i] = fa
			}
			return changed ? out : as
		}
		const 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": {
						const typeParameters = changeMap(ast.typeParameters, ast =>
							encodedAST_(ast, isBound),
						)
						return typeParameters === ast.typeParameters
							? ast
							: new Declaration(
									typeParameters,
									ast.decodeUnknown,
									ast.encodeUnknown,
								)
					}
					case "TupleType": {
						const elements = changeMap(ast.elements, e => {
								const type = encodedAST_(e.type, isBound)
								return type === e.type
									? e
									: new OptionalType(type, e.isOptional)
							}),
							restASTs = getRestASTs(ast.rest),
							rest = changeMap(restASTs, ast => encodedAST_(ast, isBound))
						return elements === ast.elements && rest === restASTs
							? ast
							: new TupleType(
									elements,
									rest.map(ast => new Type(ast)),
									ast.isReadonly,
								)
					}
					case "TypeLiteral": {
						const propertySignatures = changeMap(ast.propertySignatures, ps => {
								const type = encodedAST_(ps.type, isBound)
								return type === ps.type
									? ps
									: new PropertySignature(
											ps.name,
											type,
											ps.isOptional,
											ps.isReadonly,
										)
							}),
							indexSignatures = changeMap(ast.indexSignatures, is => {
								const 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)
					}
					case "Union": {
						const types = changeMap(ast.types, ast => encodedAST_(ast, isBound))
						return types === ast.types ? ast : Union.make(types)
					}
					case "Suspend": {
						let borrowedAnnotations
						const identifier = Option_orElse(
							getJSONIdentifierAnnotation((annotated = ast)),
							() => getIdentifierAnnotation(annotated),
						)
						if (Option_isSome(identifier)) {
							const suffix = isBound ? "Bound" : ""
							borrowedAnnotations = {
								[JSONIdentifierAnnotationId]: `${identifier.value}Encoded${suffix}`,
							}
						}
						return new Suspend(
							() => encodedAST_(ast.f(), isBound),
							borrowedAnnotations,
						)
					}
					case "Refinement": {
						const from = encodedAST_(ast.from, isBound)
						return isBound
							? from === ast.from
								? ast
								: void 0 === getTransformationFrom(ast.from) &&
									  hasStableFilter(ast)
									? new Refinement(from, ast.filter, ast.annotations)
									: from
							: from
					}
					case "Transformation":
						return encodedAST_(ast.from, isBound)
				}
				var annotated
				return ast
			},
			encodedAST = ast => encodedAST_(ast, !1),
			toJSONAnnotations = annotations => {
				const out = {}
				for (const k of Object.getOwnPropertySymbols(annotations))
					out[String(k)] = annotations[k]
				return out
			},
			getEncodedParameter = ast => {
				switch (ast._tag) {
					case "StringKeyword":
					case "SymbolKeyword":
					case "TemplateLiteral":
						return ast
					case "Refinement":
						return getEncodedParameter(ast.from)
				}
			},
			formatKeyword = ast => Option_getOrElse(getExpected(ast), () => ast._tag),
			getOrElseExpected = ast =>
				getTitleAnnotation(ast).pipe(
					Option_orElse(() => getDescriptionAnnotation(ast)),
					Option_orElse(() => getAutoTitleAnnotation(ast)),
					Option_map(
						s =>
							s +
							(function (ast) {
								return Option_match(getBrandAnnotation(ast), {
									onNone: () => "",
									onSome: brands =>
										brands
											.map(brand => ` & Brand<${formatUnknown(brand)}>`)
											.join(""),
								})
							})(ast),
					),
				),
			getExpected = ast =>
				Option_orElse(getIdentifierAnnotation(ast), () =>
					getOrElseExpected(ast),
				)
		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 ParseResult_Composite {
			ast
			actual
			issues
			output
			_tag = "Composite"
			constructor(ast, actual, issues, output) {
				this.ast = ast
				this.actual = actual
				this.issues = issues
				this.output = output
			}
		}
		class ParseResult_Refinement {
			ast
			actual
			kind
			issue
			_tag = "Refinement"
			constructor(ast, actual, kind, issue) {
				this.ast = ast
				this.actual = actual
				this.kind = kind
				this.issue = issue
			}
		}
		class ParseResult_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 ParseResult_Type {
			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
			}
		}
		const ParseResult_ParseErrorTypeId = Symbol.for(
			"effect/Schema/ParseErrorTypeId",
		)
		class ParseResult_ParseError extends Data_TaggedError("ParseError") {
			[ParseResult_ParseErrorTypeId] = ParseResult_ParseErrorTypeId
			get message() {
				return this.toString()
			}
			toString() {
				return TreeFormatter.formatIssueSync(this.issue)
			}
			toJSON() {
				return { _id: "ParseError", message: this.toString() }
			}
			[NodeInspectSymbol]() {
				return this.toJSON()
			}
		}
		const parseError = issue => new ParseResult_ParseError({ issue }),
			ParseResult_succeed = Either_right,
			ParseResult_fail = Either_left,
			ParseResult_isEither = Either_isEither,
			ParseResult_flatMap = dual(2, (self, f) =>
				ParseResult_isEither(self)
					? match(self, { onLeft: Either_left, onRight: f })
					: Effect_flatMap(self, f),
			),
			ParseResult_map = dual(2, (self, f) =>
				ParseResult_isEither(self) ? map(self, f) : Effect_map(self, f),
			),
			ParseResult_mapError = dual(2, (self, f) =>
				ParseResult_isEither(self)
					? mapLeft(self, f)
					: Effect_mapError(self, f),
			),
			ParseResult_orElse = dual(2, (self, f) =>
				ParseResult_isEither(self)
					? match(self, { onLeft: f, onRight: Either_right })
					: Effect_catchAll(self, f),
			),
			mergeInternalOptions = (options, overrideOptions) =>
				void 0 === overrideOptions || isNumber(overrideOptions)
					? options
					: void 0 === options
						? overrideOptions
						: { ...options, ...overrideOptions },
			decodeUnknownSync = (schema, options) =>
				((ast, isDecoding, options) => {
					const parser = ((ast, isDecoding, options) => {
						const parser = goMemo(ast, isDecoding)
						return (u, overrideOptions) =>
							parser(u, mergeInternalOptions(options, overrideOptions))
					})(ast, isDecoding, options)
					return (input, overrideOptions) =>
						getOrThrowWith(parser(input, overrideOptions), parseError)
				})(schema.ast, !0, options),
			decodeMemoMap = globalValue(
				Symbol.for("effect/ParseResult/decodeMemoMap"),
				() => new WeakMap(),
			),
			encodeMemoMap = globalValue(
				Symbol.for("effect/ParseResult/encodeMemoMap"),
				() => new WeakMap(),
			),
			goMemo = (ast, isDecoding) => {
				const memoMap = isDecoding ? decodeMemoMap : encodeMemoMap,
					memo = memoMap.get(ast)
				if (memo) return memo
				const raw = go(ast, isDecoding),
					parseOptionsAnnotation = getParseOptionsAnnotation(ast),
					parserWithOptions = Option_isSome(parseOptionsAnnotation)
						? (i, options) =>
								raw(
									i,
									mergeInternalOptions(options, parseOptionsAnnotation.value),
								)
						: raw,
					decodingFallbackAnnotation = getDecodingFallbackAnnotation(ast),
					parser =
						isDecoding && Option_isSome(decodingFallbackAnnotation)
							? (i, options) =>
									handleForbidden(
										ParseResult_orElse(
											parserWithOptions(i, options),
											decodingFallbackAnnotation.value,
										),
										ast,
										i,
										options,
									)
							: parserWithOptions
				memoMap.set(ast, parser)
				return parser
			},
			getConcurrency = ast =>
				Option_getOrUndefined(getConcurrencyAnnotation(ast)),
			getBatching = ast => Option_getOrUndefined(getBatchingAnnotation(ast)),
			go = (ast, isDecoding) => {
				switch (ast._tag) {
					case "Refinement":
						if (isDecoding) {
							const from = goMemo(ast.from, !0)
							return (i, options) => {
								options = options ?? defaultParseOption
								const allErrors = "all" === options?.errors,
									result = ParseResult_flatMap(
										ParseResult_orElse(from(i, options), ef => {
											const issue = new ParseResult_Refinement(
												ast,
												i,
												"From",
												ef,
											)
											return allErrors &&
												hasStableFilter(ast) &&
												ParseResult_isComposite(ef)
												? Option_match(ast.filter(i, options, ast), {
														onNone: () => Either_left(issue),
														onSome: ep =>
															Either_left(
																new ParseResult_Composite(ast, i, [
																	issue,
																	new ParseResult_Refinement(
																		ast,
																		i,
																		"Predicate",
																		ep,
																	),
																]),
															),
													})
												: Either_left(issue)
										}),
										a =>
											Option_match(ast.filter(a, options, ast), {
												onNone: () => Either_right(a),
												onSome: ep =>
													Either_left(
														new ParseResult_Refinement(ast, i, "Predicate", ep),
													),
											}),
									)
								return handleForbidden(result, ast, i, options)
							}
						}
						{
							const from = goMemo(typeAST(ast), !0),
								to = goMemo(dropRightRefinement(ast.from), !1)
							return (i, options) =>
								handleForbidden(
									ParseResult_flatMap(from(i, options), a => to(a, options)),
									ast,
									i,
									options,
								)
						}
					case "Transformation": {
						const transform = 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(
								ParseResult_flatMap(
									ParseResult_mapError(
										from(i, options),
										e =>
											new ParseResult_Transformation(
												ast,
												i,
												isDecoding ? "Encoded" : "Type",
												e,
											),
									),
									a =>
										ParseResult_flatMap(
											ParseResult_mapError(
												transform(a, options ?? defaultParseOption, ast, i),
												e =>
													new ParseResult_Transformation(
														ast,
														i,
														"Transformation",
														e,
													),
											),
											i2 =>
												ParseResult_mapError(
													to(i2, options),
													e =>
														new ParseResult_Transformation(
															ast,
															i,
															isDecoding ? "Type" : "Encoded",
															e,
														),
												),
										),
								),
								ast,
								i,
								options,
							)
					}
					case "Declaration": {
						const parse = isDecoding
							? ast.decodeUnknown(...ast.typeParameters)
							: ast.encodeUnknown(...ast.typeParameters)
						return (i, options) =>
							handleForbidden(
								parse(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 Either_right
					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": {
						const regex = (ast =>
							new RegExp(`^${getTemplateLiteralPattern(ast, !1, !0)}$`))(ast)
						return fromRefinement(ast, u => isString(u) && regex.test(u))
					}
					case "TupleType": {
						const elements = ast.elements.map(e => goMemo(e.type, isDecoding)),
							rest = ast.rest.map(annotatedAST =>
								goMemo(annotatedAST.type, isDecoding),
							)
						let requiredTypes = ast.elements.filter(e => !e.isOptional)
						ast.rest.length > 0 &&
							(requiredTypes = requiredTypes.concat(ast.rest.slice(1)))
						const 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 Either_left(new ParseResult_Type(ast, input))
							const allErrors = "all" === options?.errors,
								es = []
							let stepKey = 0
							const output = [],
								len = input.length
							for (let i = len; i <= requiredLen - 1; i++) {
								const e = new Pointer(
									i,
									input,
									new Missing(requiredTypes[i - len]),
								)
								if (!allErrors)
									return Either_left(
										new ParseResult_Composite(ast, input, e, output),
									)
								es.push([stepKey++, e])
							}
							if (0 === ast.rest.length)
								for (let i = ast.elements.length; i <= len - 1; i++) {
									const e = new Pointer(
										i,
										input,
										new Unexpected(
											input[i],
											`is unexpected, expected: ${expectedIndexes}`,
										),
									)
									if (!allErrors)
										return Either_left(
											new ParseResult_Composite(ast, input, e, output),
										)
									es.push([stepKey++, e])
								}
							let queue,
								i = 0
							for (; i < elements.length; i++)
								if (len < i + 1) {
									if (ast.elements[i].isOptional) continue
								} else {
									const te = (0, elements[i])(input[i], options)
									if (ParseResult_isEither(te)) {
										if (Either_isLeft(te)) {
											const e = new Pointer(i, input, te.left)
											if (allErrors) {
												es.push([stepKey++, e])
												continue
											}
											return Either_left(
												new ParseResult_Composite(
													ast,
													input,
													e,
													sortByIndex(output),
												),
											)
										}
										output.push([stepKey++, te.right])
									} else {
										const nk = stepKey++,
											index = i
										queue || (queue = [])
										queue.push(({ es, output }) =>
											Effect_flatMap(Effect_either(te), t => {
												if (Either_isLeft(t)) {
													const e = new Pointer(index, input, t.left)
													if (allErrors) {
														es.push([nk, e])
														return _void
													}
													return Either_left(
														new ParseResult_Composite(
															ast,
															input,
															e,
															sortByIndex(output),
														),
													)
												}
												output.push([nk, t.right])
												return _void
											}),
										)
									}
								}
							if (isNonEmptyReadonlyArray(rest)) {
								const [head, ...tail] = rest
								for (; i < len - tail.length; i++) {
									const te = head(input[i], options)
									if (ParseResult_isEither(te)) {
										if (Either_isLeft(te)) {
											const e = new Pointer(i, input, te.left)
											if (allErrors) {
												es.push([stepKey++, e])
												continue
											}
											return Either_left(
												new ParseResult_Composite(
													ast,
													input,
													e,
													sortByIndex(output),
												),
											)
										}
										output.push([stepKey++, te.right])
									} else {
										const nk = stepKey++,
											index = i
										queue || (queue = [])
										queue.push(({ es, output }) =>
											Effect_flatMap(Effect_either(te), t => {
												if (Either_isLeft(t)) {
													const e = new Pointer(index, input, t.left)
													if (allErrors) {
														es.push([nk, e])
														return _void
													}
													return Either_left(
														new ParseResult_Composite(
															ast,
															input,
															e,
															sortByIndex(output),
														),
													)
												}
												output.push([nk, t.right])
												return _void
											}),
										)
									}
								}
								for (let j = 0; j < tail.length; j++) {
									const index = i + j
									if (!(len < index + 1)) {
										const te = tail[j](input[index], options)
										if (ParseResult_isEither(te)) {
											if (Either_isLeft(te)) {
												const e = new Pointer(index, input, te.left)
												if (allErrors) {
													es.push([stepKey++, e])
													continue
												}
												return Either_left(
													new ParseResult_Composite(
														ast,
														input,
														e,
														sortByIndex(output),
													),
												)
											}
											output.push([stepKey++, te.right])
										} else {
											const nk = stepKey++
											queue || (queue = [])
											queue.push(({ es, output }) =>
												Effect_flatMap(Effect_either(te), t => {
													if (Either_isLeft(t)) {
														const e = new Pointer(index, input, t.left)
														if (allErrors) {
															es.push([nk, e])
															return _void
														}
														return Either_left(
															new ParseResult_Composite(
																ast,
																input,
																e,
																sortByIndex(output),
															),
														)
													}
													output.push([nk, t.right])
													return _void
												}),
											)
										}
									}
								}
							}
							const computeResult = ({ es, output }) =>
								Array_isNonEmptyArray(es)
									? Either_left(
											new ParseResult_Composite(
												ast,
												input,
												sortByIndex(es),
												sortByIndex(output),
											),
										)
									: Either_right(sortByIndex(output))
							if (queue && queue.length > 0) {
								const cqueue = queue
								return Effect_suspend(() => {
									const state = { es: copy(es), output: copy(output) }
									return Effect_flatMap(
										Effect_forEach(cqueue, f => f(state), {
											concurrency,
											batching,
											discard: !0,
										}),
										() => computeResult(state),
									)
								})
							}
							return computeResult({ output, es })
						}
					}
					case "TypeLiteral": {
						if (
							0 === ast.propertySignatures.length &&
							0 === ast.indexSignatures.length
						)
							return fromRefinement(ast, isNotNullable)
						const propertySignatures = [],
							expectedKeysMap = {},
							expectedKeys = []
						for (const ps of ast.propertySignatures) {
							propertySignatures.push([goMemo(ps.type, isDecoding), ps])
							expectedKeysMap[ps.name] = null
							expectedKeys.push(ps.name)
						}
						const 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 (
								!(input => isRecordOrArray(input) && !Array.isArray(input))(
									input,
								)
							)
								return Either_left(new ParseResult_Type(ast, input))
							const allErrors = "all" === options?.errors,
								es = []
							let stepKey = 0
							const onExcessPropertyError =
									"error" === options?.onExcessProperty,
								output = {}
							let inputKeys, queue
							if (
								onExcessPropertyError ||
								"preserve" === options?.onExcessProperty
							) {
								inputKeys = Reflect.ownKeys(input)
								for (const key of inputKeys) {
									const te = expected(key, options)
									if (ParseResult_isEither(te) && Either_isLeft(te)) {
										if (onExcessPropertyError) {
											const e = new Pointer(
												key,
												input,
												new Unexpected(
													input[key],
													`is unexpected, expected: ${String(expectedAST)}`,
												),
											)
											if (allErrors) {
												es.push([stepKey++, e])
												continue
											}
											return Either_left(
												new ParseResult_Composite(ast, input, e, output),
											)
										}
										output[key] = input[key]
									}
								}
							}
							const isExact = !0 === options?.exact
							for (let i = 0; i < propertySignatures.length; i++) {
								const ps = propertySignatures[i][1],
									name = ps.name,
									hasKey = Object.prototype.hasOwnProperty.call(input, name)
								if (!hasKey) {
									if (ps.isOptional) continue
									if (isExact) {
										const e = new Pointer(name, input, new Missing(ps))
										if (allErrors) {
											es.push([stepKey++, e])
											continue
										}
										return Either_left(
											new ParseResult_Composite(ast, input, e, output),
										)
									}
								}
								const te = (0, propertySignatures[i][0])(input[name], options)
								if (ParseResult_isEither(te)) {
									if (Either_isLeft(te)) {
										const e = new Pointer(
											name,
											input,
											hasKey ? te.left : new Missing(ps),
										)
										if (allErrors) {
											es.push([stepKey++, e])
											continue
										}
										return Either_left(
											new ParseResult_Composite(ast, input, e, output),
										)
									}
									output[name] = te.right
								} else {
									const nk = stepKey++,
										index = name
									queue || (queue = [])
									queue.push(({ es, output }) =>
										Effect_flatMap(Effect_either(te), t => {
											if (Either_isLeft(t)) {
												const e = new Pointer(
													index,
													input,
													hasKey ? t.left : new Missing(ps),
												)
												if (allErrors) {
													es.push([nk, e])
													return _void
												}
												return Either_left(
													new ParseResult_Composite(ast, input, e, output),
												)
											}
											output[index] = t.right
											return _void
										}),
									)
								}
							}
							for (let i = 0; i < indexSignatures.length; i++) {
								const indexSignature = indexSignatures[i],
									parameter = indexSignature[0],
									type = indexSignature[1],
									keys = getKeysForIndexSignature(input, indexSignature[2])
								for (const key of keys) {
									const keu = parameter(key, options)
									if (ParseResult_isEither(keu) && Either_isRight(keu)) {
										const vpr = type(input[key], options)
										if (ParseResult_isEither(vpr)) {
											if (Either_isLeft(vpr)) {
												const e = new Pointer(key, input, vpr.left)
												if (allErrors) {
													es.push([stepKey++, e])
													continue
												}
												return Either_left(
													new ParseResult_Composite(ast, input, e, output),
												)
											}
											Object.prototype.hasOwnProperty.call(
												expectedKeysMap,
												key,
											) || (output[key] = vpr.right)
										} else {
											const nk = stepKey++,
												index = key
											queue || (queue = [])
											queue.push(({ es, output }) =>
												Effect_flatMap(Effect_either(vpr), tv => {
													if (Either_isLeft(tv)) {
														const e = new Pointer(index, input, tv.left)
														if (allErrors) {
															es.push([nk, e])
															return _void
														}
														return Either_left(
															new ParseResult_Composite(ast, input, e, output),
														)
													}
													Object.prototype.hasOwnProperty.call(
														expectedKeysMap,
														key,
													) || (output[key] = tv.right)
													return _void
												}),
											)
										}
									}
								}
							}
							const computeResult = ({ es, output }) => {
								if (Array_isNonEmptyArray(es))
									return Either_left(
										new ParseResult_Composite(
											ast,
											input,
											sortByIndex(es),
											output,
										),
									)
								if ("original" === options?.propertyOrder) {
									const keys = inputKeys || Reflect.ownKeys(input)
									for (const name of expectedKeys)
										-1 === keys.indexOf(name) && keys.push(name)
									const out = {}
									for (const key of keys)
										Object.prototype.hasOwnProperty.call(output, key) &&
											(out[key] = output[key])
									return Either_right(out)
								}
								return Either_right(output)
							}
							if (queue && queue.length > 0) {
								const cqueue = queue
								return Effect_suspend(() => {
									const state = {
										es: copy(es),
										output: Object.assign({}, output),
									}
									return Effect_flatMap(
										Effect_forEach(cqueue, f => f(state), {
											concurrency,
											batching,
											discard: !0,
										}),
										() => computeResult(state),
									)
								})
							}
							return computeResult({ es, output })
						}
					}
					case "Union": {
						const searchTree = getSearchTree(ast.types, isDecoding),
							ownKeys = Reflect.ownKeys(searchTree.keys),
							ownKeysLen = ownKeys.length,
							astTypesLen = ast.types.length,
							map = new Map()
						for (let i = 0; i < astTypesLen; i++)
							map.set(ast.types[i], goMemo(ast.types[i], isDecoding))
						const concurrency = getConcurrency(ast) ?? 1,
							batching = getBatching(ast)
						return (input, options) => {
							const es = []
							let queue,
								stepKey = 0,
								candidates = []
							if (ownKeysLen > 0)
								if (isRecordOrArray(input))
									for (let i = 0; i < ownKeysLen; i++) {
										const name = ownKeys[i],
											buckets = searchTree.keys[name].buckets
										if (Object.prototype.hasOwnProperty.call(input, name)) {
											const literal = String(input[name])
											if (
												Object.prototype.hasOwnProperty.call(buckets, literal)
											)
												candidates = candidates.concat(buckets[literal])
											else {
												const { candidates, literals } = searchTree.keys[name],
													literalsUnion = Union.make(literals),
													errorAst =
														candidates.length === astTypesLen
															? new TypeLiteral(
																	[
																		new PropertySignature(
																			name,
																			literalsUnion,
																			!1,
																			!0,
																		),
																	],
																	[],
																)
															: Union.make(candidates)
												es.push([
													stepKey++,
													new ParseResult_Composite(
														errorAst,
														input,
														new Pointer(
															name,
															input,
															new ParseResult_Type(literalsUnion, input[name]),
														),
													),
												])
											}
										} else {
											const { candidates, literals } = searchTree.keys[name],
												fakePropertySignature = new PropertySignature(
													name,
													Union.make(literals),
													!1,
													!0,
												),
												errorAst =
													candidates.length === astTypesLen
														? new TypeLiteral([fakePropertySignature], [])
														: Union.make(candidates)
											es.push([
												stepKey++,
												new ParseResult_Composite(
													errorAst,
													input,
													new Pointer(
														name,
														input,
														new Missing(fakePropertySignature),
													),
												),
											])
										}
									}
								else {
									const errorAst =
										searchTree.candidates.length === astTypesLen
											? ast
											: Union.make(searchTree.candidates)
									es.push([stepKey++, new ParseResult_Type(errorAst, input)])
								}
							searchTree.otherwise.length > 0 &&
								(candidates = candidates.concat(searchTree.otherwise))
							for (let i = 0; i < candidates.length; i++) {
								const candidate = candidates[i],
									pr = map.get(candidate)(input, options)
								if (
									!ParseResult_isEither(pr) ||
									(queue && 0 !== queue.length)
								) {
									const nk = stepKey++
									queue || (queue = [])
									queue.push(state =>
										Effect_suspend(() =>
											"finalResult" in state
												? _void
												: Effect_flatMap(Effect_either(pr), t => {
														Either_isRight(t)
															? (state.finalResult = t)
															: state.es.push([nk, t.left])
														return _void
													}),
										),
									)
								} else {
									if (Either_isRight(pr)) return pr
									es.push([stepKey++, pr.left])
								}
							}
							const computeResult = es =>
								Array_isNonEmptyArray(es)
									? 1 === es.length && "Type" === es[0][1]._tag
										? Either_left(es[0][1])
										: Either_left(
												new ParseResult_Composite(ast, input, sortByIndex(es)),
											)
									: Either_left(new ParseResult_Type(ast, input))
							if (queue && queue.length > 0) {
								const cqueue = queue
								return Effect_suspend(() => {
									const state = { es: copy(es) }
									return Effect_flatMap(
										Effect_forEach(cqueue, f => f(state), {
											concurrency,
											batching,
											discard: !0,
										}),
										() =>
											"finalResult" in state
												? state.finalResult
												: computeResult(state.es),
									)
								})
							}
							return computeResult(es)
						}
					}
					case "Suspend": {
						const get = memoizeThunk(() => goMemo(ast.f(), isDecoding))
						return (a, options) => get()(a, options)
					}
				}
			},
			fromRefinement = (ast, refinement) => u =>
				refinement(u)
					? Either_right(u)
					: Either_left(new ParseResult_Type(ast, u)),
			getLiterals = (ast, isDecoding) => {
				switch (ast._tag) {
					case "Declaration": {
						const annotation = getSurrogateAnnotation(ast)
						if (Option_isSome(annotation))
							return getLiterals(annotation.value, isDecoding)
						break
					}
					case "TypeLiteral": {
						const out = []
						for (let i = 0; i < ast.propertySignatures.length; i++) {
							const propertySignature = ast.propertySignatures[i],
								type = isDecoding
									? encodedAST(propertySignature.type)
									: typeAST(propertySignature.type)
							isLiteral(type) &&
								!propertySignature.isOptional &&
								out.push([propertySignature.name, type])
						}
						return out
					}
					case "TupleType": {
						const out = []
						for (let i = 0; i < ast.elements.length; i++) {
							const element = ast.elements[i],
								type = isDecoding
									? encodedAST(element.type)
									: typeAST(element.type)
							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) => {
				const keys = {},
					otherwise = [],
					candidates = []
				for (let i = 0; i < members.length; i++) {
					const member = members[i],
						tags = getLiterals(member, isDecoding)
					if (tags.length > 0) {
						candidates.push(member)
						for (let j = 0; j < tags.length; j++) {
							const [key, literal] = tags[j],
								hash = String(literal.literal)
							keys[key] = keys[key] || {
								buckets: {},
								literals: [],
								candidates: [],
							}
							const buckets = keys[key].buckets
							if (!Object.prototype.hasOwnProperty.call(buckets, hash)) {
								buckets[hash] = [member]
								keys[key].literals.push(literal)
								keys[key].candidates.push(member)
								break
							}
							if (!(j < tags.length - 1)) {
								buckets[hash].push(member)
								keys[key].literals.push(literal)
								keys[key].candidates.push(member)
							}
						}
					} else otherwise.push(member)
				}
				return { keys, otherwise, candidates }
			},
			dropRightRefinement = ast =>
				isRefinement(ast) ? dropRightRefinement(ast.from) : ast,
			handleForbidden = (effect, ast, actual, options) => {
				if (!0 === options?.isEffectAllowed) return effect
				if (ParseResult_isEither(effect)) return effect
				const scheduler = new SyncScheduler(),
					fiber = Effect_runFork(effect, { scheduler })
				scheduler.flush()
				const exit = fiber.unsafePoll()
				if (exit) {
					if (Exit_isSuccess(exit)) return Either_right(exit.value)
					const cause = exit.cause
					return (self => "Fail" === self._tag)(cause)
						? Either_left(cause.error)
						: Either_left(new Forbidden(ast, actual, Cause_pretty(cause)))
				}
				return Either_left(
					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])
		}
		const getFinalTransformation = (transformation, isDecoding) => {
				switch (transformation._tag) {
					case "FinalTransformation":
						return isDecoding ? transformation.decode : transformation.encode
					case "ComposeTransformation":
						return Either_right
					case "TypeLiteralTransformation":
						return input => {
							let out = Either_right(input)
							for (const pst of transformation.propertySignatureTransformations) {
								const [from, to] = isDecoding
										? [pst.from, pst.to]
										: [pst.to, pst.from],
									transformation = isDecoding ? pst.decode : pst.encode,
									f = input => {
										const o = transformation(
											Object.prototype.hasOwnProperty.call(input, from)
												? Option_some(input[from])
												: Option_none(),
										)
										delete input[from]
										Option_isSome(o) && (input[to] = o.value)
										return input
									}
								out = ParseResult_map(out, f)
							}
							return out
						}
				}
			},
			makeTree = (value, forest = []) => ({ value, forest }),
			TreeFormatter = {
				formatIssue: issue => ParseResult_map(formatTree(issue), drawTree),
				formatIssueSync: issue => {
					const e = TreeFormatter.formatIssue(issue)
					return ParseResult_isEither(e) ? getOrThrow(e) : Effect_runSync(e)
				},
				formatError: error => TreeFormatter.formatIssue(error.issue),
				formatErrorSync: error => TreeFormatter.formatIssueSync(error.issue),
			},
			drawTree = tree => tree.value + draw("\n", tree.forest),
			draw = (indentation, forest) => {
				let r = ""
				const len = forest.length
				let tree
				for (let i = 0; i < len; i++) {
					tree = forest[i]
					const 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 ? Option_some(issue.ast) : Option_none(),
			Either_void = Either_right(void 0),
			createParseIssueGuard = tag => issue => issue._tag === tag,
			ParseResult_isComposite = createParseIssueGuard("Composite"),
			ParseResult_isRefinement = createParseIssueGuard("Refinement"),
			ParseResult_isTransformation = createParseIssueGuard("Transformation"),
			getMessage = issue =>
				ParseResult_flatMap(
					(issue =>
						getAnnotated(issue).pipe(
							Option_flatMap(getMessageAnnotation),
							Option_match({
								onNone: () => Either_void,
								onSome: messageAnnotation => {
									const union = messageAnnotation(issue)
									return isString(union)
										? Either_right({ message: union, override: !1 })
										: Effect_isEffect(union)
											? Effect_map(union, message => ({
													message,
													override: !1,
												}))
											: isString(union.message)
												? Either_right({
														message: union.message,
														override: union.override,
													})
												: Effect_map(union.message, message => ({
														message,
														override: union.override,
													}))
								},
							}),
						))(issue),
					currentMessage =>
						void 0 !== currentMessage
							? !currentMessage.override &&
								(ParseResult_isComposite(issue) ||
									(ParseResult_isRefinement(issue) && "From" === issue.kind) ||
									(ParseResult_isTransformation(issue) &&
										"Transformation" !== issue.kind))
								? ParseResult_isTransformation(issue) ||
									ParseResult_isRefinement(issue)
									? getMessage(issue.issue)
									: Either_void
								: Either_right(currentMessage.message)
							: Either_void,
				),
			ParseResult_getParseIssueTitleAnnotation = issue =>
				getAnnotated(issue).pipe(
					Option_flatMap(getParseIssueTitleAnnotation),
					flatMapNullable(annotation => annotation(issue)),
					Option_getOrUndefined,
				),
			getParseIssueTitle = issue =>
				ParseResult_getParseIssueTitleAnnotation(issue) ?? String(issue.ast),
			formatForbiddenMessage = issue => issue.message ?? "is forbidden",
			formatTree = issue => {
				switch (issue._tag) {
					case "Type":
						return ParseResult_map(
							(issue =>
								ParseResult_map(
									getMessage(issue),
									message =>
										message ??
										ParseResult_getParseIssueTitleAnnotation(issue) ??
										(function (issue) {
											return void 0 !== issue.message
												? issue.message
												: `Expected ${
														isRefinement(issue.ast)
															? ((ast = issue.ast),
																getDescriptionAnnotation(ast).pipe(
																	Option_orElse(() => getTitleAnnotation(ast)),
																	Option_orElse(() =>
																		getAutoTitleAnnotation(ast),
																	),
																	Option_orElse(() =>
																		getIdentifierAnnotation(ast),
																	),
																	Option_getOrElse(
																		() => `{ ${ast.from} | filter }`,
																	),
																))
															: String(issue.ast)
													}, actual ${formatUnknown(issue.actual)}`
											var ast
										})(issue),
								))(issue),
							makeTree,
						)
					case "Forbidden":
						return Either_right(
							makeTree(getParseIssueTitle(issue), [
								makeTree(formatForbiddenMessage(issue)),
							]),
						)
					case "Unexpected":
						return Either_right(
							makeTree((issue => issue.message ?? "is unexpected")(issue)),
						)
					case "Missing":
						return ParseResult_map(
							(issue => {
								const missingMessageAnnotation = getMissingMessageAnnotation(
									issue.ast,
								)
								if (Option_isSome(missingMessageAnnotation)) {
									const annotation = missingMessageAnnotation.value()
									return isString(annotation)
										? Either_right(annotation)
										: annotation
								}
								return Either_right(issue.message ?? "is missing")
							})(issue),
							makeTree,
						)
					case "Transformation":
						return ParseResult_flatMap(getMessage(issue), message =>
							void 0 !== message
								? Either_right(makeTree(message))
								: ParseResult_map(formatTree(issue.issue), tree =>
										makeTree(getParseIssueTitle(issue), [
											makeTree(formatTransformationKind(issue.kind), [tree]),
										]),
									),
						)
					case "Refinement":
						return ParseResult_flatMap(getMessage(issue), message =>
							void 0 !== message
								? Either_right(makeTree(message))
								: ParseResult_map(formatTree(issue.issue), tree =>
										makeTree(getParseIssueTitle(issue), [
											makeTree(formatRefinementKind(issue.kind), [tree]),
										]),
									),
						)
					case "Pointer":
						return ParseResult_map(formatTree(issue.issue), tree =>
							makeTree(formatPath(issue.path), [tree]),
						)
					case "Composite":
						return ParseResult_flatMap(getMessage(issue), message => {
							if (void 0 !== message) return Either_right(makeTree(message))
							const parseIssueTitle = getParseIssueTitle(issue)
							return util_isNonEmpty(issue.issues)
								? ParseResult_map(
										Effect_forEach(issue.issues, formatTree),
										forest => makeTree(parseIssueTitle, forest),
									)
								: ParseResult_map(formatTree(issue.issues), tree =>
										makeTree(parseIssueTitle, [tree]),
									)
						})
				}
			},
			Schema_TypeId = Symbol.for("effect/Schema")
		function Schema_make(ast) {
			return class {
				[Schema_TypeId] = Schema_variance
				static ast = ast
				static annotations(annotations) {
					return Schema_make(mergeSchemaAnnotations(this.ast, annotations))
				}
				static pipe() {
					return pipeArguments(this, arguments)
				}
				static toString() {
					return String(ast)
				}
				static Type
				static Encoded
				static Context
				static [Schema_TypeId] = Schema_variance
			}
		}
		const Schema_variance = { _A: _ => _, _I: _ => _, _R: _ => _ },
			builtInAnnotations = {
				typeConstructor: TypeConstructorAnnotationId,
				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 = annotations => {
				if (!annotations) return {}
				const out = { ...annotations }
				for (const key in builtInAnnotations)
					if (key in annotations) {
						out[builtInAnnotations[key]] = annotations[key]
						delete out[key]
					}
				return out
			},
			mergeSchemaAnnotations = (ast, annotations) =>
				SchemaAST_annotations(ast, toASTAnnotations(annotations))
		function makeDeclareClass(typeParameters, ast) {
			return class extends Schema_make(ast) {
				static annotations(annotations) {
					return makeDeclareClass(
						this.typeParameters,
						mergeSchemaAnnotations(this.ast, annotations),
					)
				}
				static typeParameters = [...typeParameters]
			}
		}
		const InstanceOfSchemaId = Symbol.for("effect/SchemaId/InstanceOf"),
			instanceOf = (constructor, annotations) =>
				(function () {
					return Array.isArray(arguments[0])
						? ((options = arguments[1]),
							(annotations = arguments[2]),
							makeDeclareClass(
								(typeParameters = arguments[0]),
								new Declaration(
									typeParameters.map(tp => tp.ast),
									(...typeParameters) =>
										options.decode(...typeParameters.map(Schema_make)),
									(...typeParameters) =>
										options.encode(...typeParameters.map(Schema_make)),
									toASTAnnotations(annotations),
								),
							))
						: ((is, annotations) => {
								const decodeUnknown = () => (input, _, ast) =>
									is(input)
										? ParseResult_succeed(input)
										: ParseResult_fail(new ParseResult_Type(ast, input))
								return makeDeclareClass(
									[],
									new Declaration(
										[],
										decodeUnknown,
										decodeUnknown,
										toASTAnnotations(annotations),
									),
								)
							})(arguments[0], arguments[1])
					var typeParameters, options, annotations
				})(u => u instanceof constructor, {
					title: constructor.name,
					description: `an instance of ${constructor.name}`,
					pretty: () => String,
					schemaId: InstanceOfSchemaId,
					[InstanceOfSchemaId]: { constructor },
					...annotations,
				}),
			getChecked = e =>
				decodeUnknownSync(instanceOf(HTMLInputElement))(e.currentTarget).checked
		__webpack_require__.dn(getChecked)
		const configEffect = (k, v) => c => () =>
			Effect_runPromise(c.provideLog(c.setConfig[k](v)))
		__webpack_require__.dn(configEffect)
		const stepTiming = stepCount => `steps(${stepCount}, jump-end)`
		__webpack_require__.dn(stepTiming)
		const setComputed = {
				useStepTiming: v => c => s =>
					pipe(
						v ? stepTiming(Editable_value(s.timingStepCount)) : "linear",
						timingFunction => [
							{ ...s, timingFunction },
							configEffect("timingFunction", timingFunction)(c),
						],
					),
			},
			settingUI_setComputed = setComputed,
			setRange = keyA => keyB => bFn => vA => commander => s =>
				pipe(
					Editable_value(vA),
					a => ({ a, b: bFn(a)(Editable_value(s[keyB])) }),
					({ a, b }) =>
						pipe(
							[configEffect(keyA, a), configEffect(keyB, b)],
							xs => c =>
								pipe(
									xs,
									Array_map(x => x(c)),
									effects => [
										{ ...s, [keyA]: vA, [keyB]: setValue(b)(s[keyB]) },
										...effects,
									],
								),
						)(commander),
				)
		__webpack_require__.dn(setRange)
		const setState = {
				flowY1: setRange("flowY1")("flowY2")(a => b => Math.max(b, a + 0.05)),
				flowY2: setRange("flowY2")("flowY1")(a => b => Math.min(b, a - 0.05)),
				flowX1: setRange("flowX1")("flowX2")(a => b => Math.max(b, a + 0.05)),
				flowX2: setRange("flowX2")("flowX1")(a => b => Math.min(b, a - 0.05)),
				timingStepCount: v => c => s =>
					pipe(stepTiming(Editable_value(v)), timingFunction => [
						{ ...s, timingStepCount: v, timingFunction },
						configEffect("timingFunction", timingFunction)(c),
					]),
			},
			settingUI_setState = setState,
			updateAt = k => v =>
				pipe(
					k in settingUI_setComputed
						? settingUI_setComputed[k](v)
						: k in settingUI_setState
							? settingUI_setState[k](v)
							: c => s => [
									{ ...s, [k]: v },
									...(k in c.setConfig && "filterExp" !== k
										? [
												configEffect(
													k,
													Array.isArray(v) &&
														2 === v.length &&
														isEditable(k)(v[0])
														? Editable_value(v)
														: v,
												)(c),
											]
										: []),
								],
				)
		__webpack_require__.dn(updateAt)
		const updateBool = (
				updateAt => key =>
					flip((s, e) => pipe(getChecked(e), updateAt(key), flip, apply(s)))
			)(updateAt),
			settingUI_checkboxNode = checkboxNode(getText, getState, updateBool),
			mapSettingNodes = f => xs => c => s =>
				pipe(
					xs,
					Array_map(x => x(c)(s)),
					f,
				)
		__webpack_require__.dn(mapSettingNodes)
		const errorText = subject => edit =>
			pipe(
				edit,
				Editable_error,
				Option_map(x => `${subject}${"" === x ? "" : ": "}${x}`),
				Option_getOrElse(constant("")),
			)
		__webpack_require__.dn(errorText)
		const rangeRow = (config, action) => value =>
			h("div", {}, [
				h("input", {
					style: { width: "150px", verticalAlign: "middle" },
					type: "range",
					...config,
					value: Editable_value(value).toString(),
					oninput: action.onchange ?? identity,
				}),
				h("input", {
					style: {
						width: "30px",
						backgroundColor: "transparent",
						color: "inherit",
						borderWidth: "1px",
						verticalAlign: "middle",
						borderColor: hasError(value) ? "#f55" : null,
					},
					inputmode: "decimal",
					value: pipe(
						value,
						Editable_text,
						Option_getOrElse(
							constant(
								Editable_value(value)
									.toFixed(4)
									.replace(/\.?0+$/, ""),
							),
						),
					),
					...action,
				}),
			])
		__webpack_require__.dn(rangeRow)
		const settingRow = (label, error, content) =>
			h("div", {}, [
				h("span", {}, hyperapp_text(label)),
				h(
					"span",
					{
						style: { color: "#f55", marginLeft: "5px", whiteSpace: "pre-wrap" },
					},
					hyperapp_text(error),
				),
				h("div", {}, content),
			])
		__webpack_require__.dn(settingRow)
		const numericNode =
			setter =>
			(editAction, getText, getState) =>
			(label, min, max, step) =>
			c =>
			s =>
				settingRow(
					getText(label)(s),
					errorText(getText("inputNonNumberic")(s))(getState(label)(s)),
					[
						rangeRow(
							{ min, max, step },
							editAction(label, setter)(c),
						)(getState(label)(s)),
					],
				)
		__webpack_require__.dn(numericNode)
		const numberNode = numericNode(
				editing => value => state =>
					pipe(
						value,
						Number.parseFloat,
						editing
							? x =>
									Number.isNaN(x) || "." === value.at(-1)
										? pipe(state, setText(value))
										: fromValueText(x)(value)
							: x =>
									Number.isNaN(x)
										? pipe(
												state,
												mapSecond(
													constant(Option_some([value, Option_some("")])),
												),
											)
										: Editable_of(x),
					),
			),
			getValue = e => {
				const target = e.currentTarget ?? e.__target
				if (
					target instanceof HTMLSelectElement ||
					target instanceof HTMLTextAreaElement ||
					target instanceof HTMLInputElement
				)
					return target.value
				throw Error("Event target type isn't acceptable.")
			}
		__webpack_require__.dn(getValue)
		const updateInput = (
				(getState, updateAt) => key => setter => c => (s, e) =>
					pipe(getValue(e), setter, apply(getState(key)(s)), updateAt(key), x =>
						x(c)(s),
					)
			)(getState, updateAt),
			editAction = (updateInput => (key, setter) => c => ({
				oninput: updateInput(key)(setter(!0))(c),
				onchange: updateInput(key)(setter(!1))(c),
			}))(updateInput),
			settingUI_numberNode = numberNode(editAction, getText, getState),
			chatFieldPanel = pipe(
				[
					pipe(
						[
							settingUI_numberNode("fieldScale", 0.7, 1.5, 0.05),
							settingUI_checkboxNode("simplifyChatField"),
							settingUI_checkboxNode("createBanButton"),
						],
						mapSettingNodes(x => h("div", { style: panelBoxStyle(644) }, x)),
					),
				],
				mapSettingNodes(identity),
			),
			settingUI_chatFieldPanel = chatFieldPanel,
			action = {
				copy: () => s =>
					Effect_map(
						Effect_promise(async () =>
							GM.setClipboard(
								(x =>
									`<pre>${JSON.stringify({ nextId: x.nextId, blocks: pipe(x.compressedBlocks, Array_map(external_LZString_namespaceObject.decompressFromUTF16), Array_append(JSON.stringify(x.lastBlock)), Array_map(external_LZString_namespaceObject.compressToEncodedURIComponent)) })}</pre>`)(
									s.eventLog,
								),
							),
						),
						() => s,
					),
				clearFlowChats: c => s => Effect_map(c.act.clearFlowChats, () => s),
				importLog: () => s =>
					pipe(
						Effect_sync(() => prompt(getText("importLog")(s))),
						Effect_flatMap(Effect_fromNullable),
						Effect_map(x => ({ ...s, eventLog: importLog(x) })),
						Effect_orElseSucceed(() => s),
					),
			},
			buttonNode = label => c => state =>
				h(
					"button",
					{
						type: "button",
						onclick: s => [
							s,
							d =>
								Effect_runPromise(
									c.provideLog(
										pipe(
											action[label](c)(s),
											Effect_flatMap(newS => Effect_sync(() => d(newS))),
										),
									),
								),
						],
					},
					hyperapp_text(getText(label)(state)),
				)
		__webpack_require__.dn(buttonNode)
		const feedbackPanel = c => s =>
			pipe(
				getState("eventLog")(s).compressedBlocks.length + 1,
				logPageCount => [
					pipe(
						[settingUI_checkboxNode("logEvents"), buttonNode("importLog")],
						mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x)),
					)(c)(s),
					h("div", { style: panelBoxStyle(428) }, [
						h(
							"a",
							{
								style: { color: "#f0f" },
								href: "https://greasyfork.org/en/scripts/411442-flow-youtube-chat/feedback",
								target: "_blank",
							},
							hyperapp_text(getText("giveFeedback")(s)),
						),
						h("div", {}, [
							h("span", {}, hyperapp_text(getText("eventLog")(s))),
							buttonNode("copy")(c)(s),
							tabContainer({
								container: {},
								label: { padding: "4px", width: "2em", textAlign: "center" },
								labelFocus: { background: "#666" },
								tab: {
									height: "251px",
									display: "flex",
									flexDirection: "column",
									padding: "6px",
								},
							})((_, n) => updateAt("logTab")(n)(c))(
								pipe(Array_makeBy(logPageCount, x => `${x}`)),
							)(
								pipe(getState("eventLog")(s), l =>
									Array_makeBy(
										logPageCount,
										i => () =>
											pipe(
												Array_get(l.compressedBlocks, i),
												Option_map(decompressBlock),
												Option_getOrElse(() => l.lastBlock),
												Array_map((x, j) =>
													h("div", { style: { display: "flex" } }, [
														h(
															"div",
															{
																style: { userSelect: "none", flex: "0 0 2em" },
															},
															hyperapp_text(x.id),
														),
														h(
															"div",
															{
																style: {
																	background: j % 2 == 0 ? "#fff" : "#ddd",
																	color: "#000",
																	flex: "auto",
																	wordBreak: "break-all",
																	whiteSpace: "break-spaces",
																	padding: "0 2px",
																},
															},
															hyperapp_text(`[${x.level}] ${x.text}`),
														),
													]),
												),
											),
									),
								),
							)(getState("logTab")(s)),
						]),
					]),
				],
			)
		__webpack_require__.dn(feedbackPanel)
		const textAreaRow = (rows, action) => value =>
			h("textarea", {
				rows,
				style: {
					resize: "none",
					boxSizing: "border-box",
					width: "100%",
					borderColor: hasError(value) ? "#f55" : null,
				},
				value: pipe(
					value,
					Editable_text,
					Option_getOrElse(pipe(Editable_value(value), join("\n"), constant)),
				),
				...action,
			})
		__webpack_require__.dn(textAreaRow)
		const textAreaNode =
			setter => (editAction, getText, getState) => (label, rows) => c => s =>
				settingRow(
					getText(label)(s),
					errorText(getText("invalidSetting")(s))(getState(label)(s)),
					[textAreaRow(rows, editAction(label, setter)(c))(getState(label)(s))],
				)
		__webpack_require__.dn(textAreaNode)
		const settingUI_plainTextAreaNode = textAreaNode(
				editing => value =>
					pipe(
						value,
						String_split(/\r\n|\n/),
						Array_filter(not(String_isEmpty)),
						regexes => ({
							regexes,
							errors: pipe(
								regexes,
								Array_map((x, i) => {
									try {
										RegExp(x, "u")
										return Option_none()
									} catch (e) {
										return Option_some(`${e} in regex number ${i}`)
									}
								}),
								Array_getSomes,
								Array_reduce("", (b, a) => `${b}\n${a}`),
								Option_liftPredicate(String_isNonEmpty),
							),
						}),
						ctx =>
							editing
								? setText(value)
								: pipe(
										ctx.errors,
										Option_map(x =>
											mapSecond(() => Option_some([value, Option_some(x)])),
										),
										Option_getOrElse(() => () => Editable_of(ctx.regexes)),
									),
					),
			)(editAction, getText, getState),
			settingUI_regexTextAreaNode = textAreaNode(
				editing => value =>
					pipe(
						value,
						String_split(/\r\n|\n/),
						Array_filter(not(String_isEmpty)),
						x =>
							constant(
								editing
									? [x, Option_some([value, Option_none()])]
									: Editable_of(x),
							),
					),
			)(editAction, getText, getState),
			filterPanelOld = c => s => [
				h(
					"div",
					{ style: panelBoxStyle(212) },
					settingUI_plainTextAreaNode("bannedWords", 18)(c)(s),
				),
				h(
					"div",
					{ style: panelBoxStyle(212) },
					settingUI_regexTextAreaNode("bannedWordRegexes", 18)(c)(s),
				),
				h(
					"div",
					{ style: panelBoxStyle(212) },
					settingUI_plainTextAreaNode("bannedUsers", 18)(c)(s),
				),
			]
		__webpack_require__.dn(filterPanelOld)
		const colorPicker = action => color =>
			h("input", {
				style: { width: "36px", verticalAlign: "middle" },
				type: "color",
				value: color,
				oninput: action.onchange ?? identity,
			})
		__webpack_require__.dn(colorPicker)
		const textInput = action => value =>
			h("input", {
				style: {
					verticalAlign: "middle",
					width: "5.5em",
					borderColor: hasError(value) ? "#f55" : null,
				},
				maxlength: 20,
				value: pipe(
					value,
					Editable_text,
					Option_getOrElse(constant(Editable_value(value))),
				),
				...action,
			})
		__webpack_require__.dn(textInput)
		var lib = __webpack_require__(742),
			lib_default = __webpack_require__.n(lib)
		const setter_setEditColor = editing => value =>
				editing
					? lib_default()(value)
						? constant(fromValueText(value)(value))
						: setText(value)
					: lib_default()(value)
						? constant(Editable_of(value))
						: mapSecond(constant(Option_some([value, Option_some("")]))),
			colorNode = (editAction, getText, getState) => label => c => s =>
				settingRow(
					getText(label)(s),
					errorText(getText("invalidColor")(s))(getState(label)(s)),
					pipe(editAction(label, setter_setEditColor)(c), x => [
						colorPicker(x)(Editable_value(getState(label)(s))),
						textInput(x)(getState(label)(s)),
					]),
				)
		__webpack_require__.dn(colorNode)
		const settingUI_colorNode = colorNode(editAction, getText, getState),
			settingUI_intNode = numericNode(
				editing => value => state =>
					pipe(
						value,
						Number.parseInt,
						editing
							? x =>
									Number.isNaN(x) || "." === value.at(-1)
										? pipe(state, setText(value))
										: fromValueText(x)(value)
							: x =>
									Number.isNaN(x)
										? pipe(
												state,
												mapSecond(
													constant(Option_some([value, Option_some("")])),
												),
											)
										: Editable_of(x),
					),
			)(editAction, getText, getState),
			setter_setEditString = editing => x =>
				constant(editing ? fromValueText(x)(x) : Editable_of(x)),
			fonts = currentFont => [
				["", "Default", "デフォルト", "Default"],
				["arial", "Arial", "Arial", "Arial"],
				["arial black", "Arial Black", "Arial Black", "Arial Black"],
				["arial narrow", "Arial Narrow", "Arial Narrow", "Arial Narrow"],
				["Century", "Century", "Century", "Century"],
				["Comic Sans MS", "Comic Sans MS", "Comic Sans MS", "Comic Sans MS"],
				["Courier", "Courier", "Courier", "Courier"],
				["cursive", "cursive", "cursive", "cursive"],
				["fantasy", "fantasy", "fantasy", "fantasy"],
				["Impact", "Impact", "Impact", "Impact"],
				["Meiryo", "Meiryo", "メイリオ", "Meiryo"],
				["Meiryo UI", "Meiryo UI", "メイリオ UI", "Meiryo UI"],
				["monospace", "monospace", "monospace", "monospace"],
				[
					"Monotype Corsiva",
					"Monotype Corsiva",
					"Monotype Corsiva",
					"Monotype Corsiva",
				],
				["MS PGothic", "MS PGothic", "MS Pゴシック", "MS PGothic"],
				["MS Gothic", "MS Gothic", "MS ゴシック", "MS Gothic"],
				["MS Sans Serif", "MS Sans Serif", "MS Sans Serif", "MS Sans Serif"],
				["MS Serif", "MS Serif", "MS Serif", "MS Serif"],
				["MS UI Gothic", "MS UI Gothic", "MS UI Gothic", "MS UI Gothic"],
				["sans-serif", "Sans-serif", "Sans-serif", "Sans-serif"],
				["serif", "Serif", "Serif", "Serif"],
				[
					"Times New Roman",
					"Times New Roman",
					"Times New Roman",
					"Times New Roman",
				],
				["Yu Gothic", "Yu Gothic", "遊ゴシック", "Yu Gothic"],
				["YuGothic", "YuGothic", "游ゴシック体", "YuGothic"],
				[currentFont, "Custom", "カスタム", "自定义"],
			]
		__webpack_require__.dn(fonts)
		const settingUI_textRowStyle = { width: "70%", boxSizing: "border-box" },
			selectFontNode = c => s =>
				pipe(Editable_value(s.font), font =>
					settingRow(getText("font")(s), "", [
						h(
							"select",
							{
								style: settingUI_textRowStyle,
								onchange: updateInput("font")(setter_setEditString(!1))(c),
							},
							pipe(
								fonts(font),
								findFirstIndex(x => x[0] === font),
								Option_getOrElse(() => 0),
								index =>
									pipe(
										fonts(font),
										Array_map((f, i) =>
											node_option(
												f[0],
												pipe(
													languages,
													findFirstIndex(x => x === s.lang),
													Option_map(x => Array_unsafeGet(x + 1)(f)),
													Option_getOrElse(() => "Error"),
												),
												i === index,
											),
										),
									),
							),
						),
						h("input", {
							style: settingUI_textRowStyle,
							maxlength: 20,
							value: font,
							...editAction("font", setter_setEditString),
						}),
					]),
				)
		__webpack_require__.dn(selectFontNode)
		const stepTimingNode = c => s =>
			h("div", {}, [
				settingUI_checkboxNode("useStepTiming")(c)(s),
				h(
					"div",
					{ style: { opacity: getState("useStepTiming")(s) ? null : "0.5" } },
					settingUI_intNode("timingStepCount", 1, 400, 1)(c)(s),
				),
			])
		__webpack_require__.dn(stepTimingNode)
		const colorTextOutput = textStyle => color =>
			h("span", { style: { ...textStyle, color } }, hyperapp_text("Aa1あア亜"))
		__webpack_require__.dn(colorTextOutput)
		const textColorNode =
			(editAction, getText, getState, getExampleTextStyle) => label => c => s =>
				settingRow(
					getText(label)(s),
					errorText(getText("invalidColor")(s))(getState(label)(s)),
					pipe(
						{
							a: editAction(label, setter_setEditColor)(c),
							v: Editable_value(getState(label)(s)),
						},
						({ a, v }) => [
							colorPicker(a)(v),
							textInput(a)(getState(label)(s)),
							colorTextOutput(getExampleTextStyle(s))(v),
						],
					),
				)
		__webpack_require__.dn(textColorNode)
		const getExampleTextStyle = s => ({
			fontFamily: Editable_value(s.font),
			fontWeight: Editable_value(s.fontWeight).toString(),
			textShadow: textShadow(Editable_value(s.shadowColor))(
				Editable_value(s.shadowFontWeight),
			),
		})
		__webpack_require__.dn(getExampleTextStyle)
		const settingUI_textColorNode = textColorNode(
				editAction,
				getText,
				getState,
				getExampleTextStyle,
			),
			flowChatPanel = pipe(
				[
					pipe(
						[
							selectFontNode,
							settingUI_textColorNode("color"),
							settingUI_textColorNode("ownerColor"),
							settingUI_textColorNode("moderatorColor"),
							settingUI_textColorNode("memberColor"),
							settingUI_colorNode("shadowColor"),
						],
						mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x)),
					),
					pipe(
						[
							settingUI_numberNode("chatOpacity", 0, 1, 0.05),
							settingUI_numberNode("fontSize", 0.3, 2, 0.05),
							settingUI_numberNode("fontWeight", 10, 1e3, 10),
							settingUI_numberNode("shadowFontWeight", 0, 3, 0.1),
							settingUI_numberNode("flowSpeed", 1, 50, 1),
							settingUI_intNode("maxChatCount", 5, 200, 5),
							settingUI_intNode("maxChatLength", 5, 200, 5),
							settingUI_intNode("laneCount", 1, 25, 1),
						],
						mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x)),
					),
					pipe(
						[
							settingUI_numberNode("flowY1", 0, 0.95, 0.01),
							settingUI_numberNode("flowY2", 0.05, 1, 0.01),
							settingUI_numberNode("flowX1", 0, 0.95, 0.01),
							settingUI_numberNode("flowX2", 0.05, 1, 0.01),
							settingUI_numberNode("minSpacing", 0, 2.5, 0.1),
							stepTimingNode,
							settingUI_checkboxNode("createChats"),
							settingUI_checkboxNode("displayModName"),
							settingUI_checkboxNode("displaySuperChatAuthor"),
							settingUI_checkboxNode("textOnly"),
							() => s => hyperapp_text(getText("flowNewChatIf")(s)),
							settingUI_checkboxNode("noOverlap"),
							buttonNode("clearFlowChats"),
						],
						mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x)),
					),
				],
				mapSettingNodes(identity),
			),
			settingUI_flowChatPanel = flowChatPanel,
			settingsPanel = c => state => {
				return state.showPanel
					? h(
							"div",
							{
								class: "fyc_panel",
								style: {
									backgroundColor: "rgba(30,30,30,0.9)",
									position: "absolute",
									zIndex: "66666",
									color: "#fff",
									fontSize: "14px",
									overflow: "auto",
									left: `${state.panelRect.x}px`,
									top: `${state.panelRect.y}px`,
									width: `${state.panelRect.width}px`,
									height: `${state.panelRect.height}px`,
									border: "solid 1px #666",
									fontFamily: "MS PGothic",
									lineHeight: "1.2",
									colorScheme: "dark",
								},
							},
							[
								h(
									"div",
									{
										style: { position: "absolute", inset: "3px 3px auto auto" },
									},
									[
										hyperapp_text("🌐"),
										h(
											"select",
											{
												onchange: updateInput("lang")(
													((allowedStrings = languages),
													value => state =>
														pipe(
															value,
															Option_liftPredicate(x =>
																Array_containsWith(String_Equivalence)(
																	allowedStrings,
																	x,
																),
															),
															Option_getOrElse(() => state),
														)),
												)(c),
											},
											pipe(
												languages,
												Array_zip(languageLabels),
												Array_map(([lang, label]) =>
													node_option(lang, label, lang === state.lang),
												),
											),
										),
									],
								),
								tabContainer({
									container: {},
									label: { padding: "6px" },
									labelFocus: { background: "#666" },
									tab: { height: "364px", display: "flex", padding: "6px" },
								})((s, n) => updateAt("mainTab")(n)(c)(s))(
									pipe(
										["flowChat", "chatFilter", "chatField", "feedback"],
										Array_map(getText),
										Array_map(apply(state)),
									),
								)(
									pipe(
										[
											settingUI_flowChatPanel,
											filterPanelOld,
											settingUI_chatFieldPanel,
											feedbackPanel,
										],
										Array_map(apply(c)),
										Array_map(constant),
										Array_map(flip),
										Array_map(apply(state)),
									),
								)(getState("mainTab")(state)),
							],
						)
					: h("div", {})
				var allowedStrings
			}
		__webpack_require__.dn(settingsPanel)
		const settingsComponent = command =>
			pipe(settingsPanel(command), panel =>
				makeComponent(
					tag => s => h(tag, { style: { display: "contents" } }, panel(s)),
				)("span"),
			)
		__webpack_require__.dn(settingsComponent)
		const makeRefs = o =>
			pipe(
				Struct_entries(o),
				Effect_forEach(([k, v]) =>
					pipe(
						SubscriptionRef_make(v),
						Effect_map(ref => [k, ref]),
					),
				),
				Effect_map(Object.fromEntries),
			)
		__webpack_require__.dn(makeRefs)
		const toggleChatButton = setConfig =>
			pipe(
				"button",
				makeComponent(
					tag => state =>
						pipe(
							getText(state.displayChats ? "hideChats" : "showChats")(state),
							label =>
								h(
									tag,
									{
										class: "ytp-button",
										style: {
											background: "none",
											border: "none",
											cursor: "pointer",
											float: "left",
											fontSize: "1em",
											height: "100%",
											outline: "none",
											overflow: "visible",
											padding: "0 0 0em",
											position: "relative",
											width: "48px",
											display: "flex",
											alignItems: "center",
										},
										type: "button",
										"aria-label": label,
										title: label,
										onclick: s =>
											pipe(!s.displayChats, displayChats => [
												{ ...s, displayChats },
												() =>
													Effect_runPromise(
														setConfig.displayChats(displayChats),
													),
											]),
									},
									[
										h(
											"svg",
											{ style: { width: "36px" }, viewBox: "0 0 36 36" },
											[
												h("path", {
													class: "chat-button-path",
													d: "m11 12h17q1 0 1 1v9q0 1-1 1h-1v2l-4-2h-12q-1 0-1-1v-9q0-1 1-1z",
													fill: "#fff",
													"fill-opacity": state.displayChats ? "1" : "0",
													stroke: "#fff",
													"stroke-width": "2",
												}),
											],
										),
									],
								),
						),
				),
			)
		__webpack_require__.dn(toggleChatButton)
		const toggleSettingsPanelComponent = updateState =>
			pipe(
				(
					updateState => (x, e) =>
						pipe({ ...x, showPanel: !x.showPanel }, newState => [
							newState,
							x.showPanel
								? () =>
										decodeUnknownSync(instanceOf(HTMLElement))(
											e.currentTarget,
										).blur()
								: () => {},
							() =>
								Effect_runPromise(
									updateState(oldState => ({ ...oldState, ...newState })),
								),
						])
				)(updateState),
				toggle => state =>
					h(
						"button",
						{
							class: "fyc_button",
							style: {
								background: "rgba(0,0,0,0)",
								marginLeft: "10px",
								whiteSpace: "nowrap",
							},
							onclick: toggle,
						},
						[
							h(
								"svg",
								{
									preserveAspectRatio: "xMidYMid meet",
									viewBox: "0 0 640 640",
									width: "15",
									height: "15",
									style: { position: "relative", top: "1px" },
								},
								[
									h(
										"defs",
										{},
										h("path", {
											id: "d1TbzTC1zI",
											d: "M135 58c25 14 67 30 82 35-7 49 16 109-15 149-50 71-19 184 64 213 74 31 165-18 183-95-3-38 23-62 58-36l120 55c-39 10-106 35-72 85 40 38 1 71-29 98-29 53-70-17-109-5-46 22-25 109-96 85h-55c-24-31-21-103-80-84-32 32-70 31-93-9l-35-36c4-40 57-96-6-120-45 5-58-32-52-68 2-19-4-41 3-59 35-15 100-22 77-79-48-43 1-84 35-115 5-6 12-12 20-14zM577 2c52 3 72 62 62 106-5 51 19 117-27 155-18 24 8 49 11 74-39-8-98-46-146-60-55-1-111 2-167-2-52-15-57-76-52-121S242 52 282 18c38-30 88-11 132-16h163z",
										}),
									),
									h("use", {
										href: "#d1TbzTC1zI",
										opacity: "1",
										fill: "var(--iron-icon-fill-color, currentcolor)",
										"fill-opacity": "1",
									}),
								],
							),
							h(
								"span",
								{
									style: {
										position: "relative",
										top: "-2px",
										marginLeft: "8px,",
									},
								},
								hyperapp_text(getText("setting")(state)),
							),
						],
					),
				button =>
					makeComponent(
						tag => s =>
							h(
								tag,
								{
									style: { float: "left", display: "flex", minHeight: "100%" },
								},
								button(s),
							),
					)("span"),
			)
		__webpack_require__.dn(toggleSettingsPanelComponent)
		const initialize = ({ settingUpdateApps, provideLog }) =>
			provideLog(
				pipe(
					Effect_gen(function* () {
						const updateSettingState = dispatchable =>
								provideLog(
									pipe(
										Ref_get(settingUpdateApps),
										Effect_flatMap(
											Effect_forEach(x => Effect_sync(() => x(dispatchable))),
										),
									),
								),
							channel = new broadcast_channel_BroadcastChannel(
								"fyc-0615654655528523",
							),
							configValue = yield* ((config = src_defaultGMConfig),
							pipe(
								Struct_entries(config),
								Effect_forEach(([k, c]) =>
									c.getValue.pipe(Effect_map(x => [k, x])),
								),
								Effect_map(Object.fromEntries),
							)),
							configRefs = yield* makeRefs(configValue),
							{ setConfigPlain, setChangedConfig, setConfig } =
								configWriteFunnel({
									configValue,
									configRefs,
									configKeys,
									dispatchToSettings: key => val =>
										updateSettingState(setSettingFromConfig(key)(val)),
									broadcastAndPersist: key => val =>
										pipe(
											Effect_promise(() => channel.postMessage([key, val])),
											Effect_zipRight(
												Effect_promise(() =>
													pipe(src_defaultGMConfig[key], x =>
														GM.setValue(x.gmKey, x.toGm(val)),
													),
												),
											),
										),
									defaultFilterExp: () => defaultFilter(configValue),
								})
						var config
						yield* setConfigPlain.filterExp(defaultFilter(configValue))
						return {
							updateSettingState,
							channel,
							configValue,
							configRefs,
							setChangedConfig,
							mainState: {
								chatPlaying: yield* SynchronizedRef_make(!0),
								playerRect: yield* SynchronizedRef_make(
									new DOMRectReadOnly(0, 0, 600, 400),
								),
								flowChats: yield* SynchronizedRef_make([]),
								config: {
									value: configValue,
									getConfig: makeGetter(configValue),
									setConfig,
								},
							},
						}
					}),
					Effect_flatMap(ctx =>
						Effect_gen(function* () {
							const stateInit = settingStateInit(ctx.mainState.config.value)
							return {
								...ctx,
								apps: {
									toggleChatButtonApp: yield* wrapApp(
										toggleChatButton(ctx.mainState.config.setConfig),
										stateInit,
									),
									settingsApp: yield* wrapApp(
										settingsComponent({
											setConfig: ctx.mainState.config.setConfig,
											act: {
												clearFlowChats: removeOldChats(ctx.mainState.flowChats)(
													0,
												),
											},
											provideLog,
										}),
										stateInit,
									),
									toggleSettingsPanelApp: yield* wrapApp(
										toggleSettingsPanelComponent(ctx.updateSettingState),
										stateInit,
									),
								},
							}
						}),
					),
					Effect_tap(ctx =>
						Ref_set(
							settingUpdateApps,
							Array_map(
								[
									ctx.apps.settingsApp,
									ctx.apps.toggleSettingsPanelApp,
									ctx.apps.toggleChatButtonApp,
								],
								x => x.dispatch,
							),
						),
					),
					Effect_tap(ctx =>
						pipe(
							Effect_succeed([
								"Version: 1.20.0",
								`User Agent: ${window.navigator.userAgent}`,
								`GMConfig: ${JSON.stringify(ctx.mainState.config, void 0, "\t")}`,
							]),
							Effect_flatMap(Effect_forEach(x => Effect_logDebug(x))),
						),
					),
					Effect_zipLeft(
						pipe(
							Effect_logDebug("10s..."),
							schedule(Schedule_fixed(seconds(10))),
							Effect_forkDaemon,
						),
					),
					Effect_flatMap(ctx =>
						Effect_gen(function* () {
							const reinitQueue = yield* Queue_unbounded(),
								reinitialize = provideLog(
									Effect_sync(() => {
										requestAnimationFrame(() => {
											Queue_unsafeOffer(reinitQueue, void 0)
										})
									}),
								),
								stream = yield* allStream(provideLog)({
									...ctx,
									reinitQueue,
									reinitialize,
									chatScreen: yield* makeChatScreen,
								})
							yield* pipe(
								(self => stream_run(self, sink_drain))(stream),
								Effect_zipRight(Effect_logWarning("Stream complete")),
								Effect_catchAllCause(cause =>
									logWithMeta(LogLevel_Error)(
										`Stream Errored: ${Cause_pretty(cause)}`,
									)(squash(cause)),
								),
								Effect_forkDaemon,
							)
							yield* reinitialize
						}),
					),
				),
			)
		__webpack_require__.dn(initialize)
		const Logger_make = makeLogger,
			Logger_replace = replaceLogger,
			Logger_withMinimumLogLevel = withMinimumLogLevel,
			Logger_zip = logger_zip,
			Logger_defaultLogger = defaultLogger
		var LogAnnotationKeys
		!(function (LogAnnotationKeys) {
			LogAnnotationKeys.name = "name"
		})(LogAnnotationKeys || (LogAnnotationKeys = {}))
		const src_LogAnnotationKeys = LogAnnotationKeys,
			maxEventLogBlockCount = Math.floor(50),
			preserveEventLogBlockCount = Math.floor(0.2 * maxEventLogBlockCount),
			appendEventLog = (text, level) => x => {
				return pipe(
					x.compressedBlocks.length === maxEventLogBlockCount
						? ((i = Math.floor(preserveEventLogBlockCount)),
							log =>
								i > log.compressedBlocks.length
									? log
									: makeLog({
											nextId: log.nextId,
											...(i === log.compressedBlocks.length
												? {
														lastBlock: [],
														compressedBlocks: log.compressedBlocks,
													}
												: {
														lastBlock: log.lastBlock,
														compressedBlocks: Array_remove(
															log.compressedBlocks,
															i,
														),
													}),
										}))(x)
						: x,
					(
						(text, level) => log =>
							makeLog({
								nextId: log.nextId + 1,
								...pipe(
									log.lastBlock,
									Array_append({ id: log.nextId, text, level }),
									x =>
										200 === x.length
											? {
													compressedBlocks: Array_append(
														log.compressedBlocks,
														makeCompressedLogBlock(
															(0,
															external_LZString_namespaceObject.compressToUTF16)(
																JSON.stringify(x),
															),
														),
													),
													lastBlock: [],
												}
											: {
													compressedBlocks: log.compressedBlocks,
													lastBlock: x,
												},
								),
							})
					)(text, level),
				)
				var i
			}
		__webpack_require__.dn(appendEventLog)
		const updateSettingState = apps => dispatchable =>
			pipe(
				apps,
				Effect_forEach(x => Effect_sync(() => x(dispatchable))),
			)
		__webpack_require__.dn(updateSettingState)
		const eventLogger = apps =>
			Logger_make(({ logLevel, message }) =>
				Effect_runPromise(
					pipe(
						Ref_get(apps),
						Effect_flatMap(x =>
							updateSettingState(x)(s =>
								s.logEvents
									? {
											...s,
											eventLog: appendEventLog(
												String(message),
												logLevel.label,
											)(s.eventLog),
										}
									: s,
							),
						),
					),
				),
			)
		__webpack_require__.dn(eventLogger)
		const Console_debug = (...args) => consoleWith(_ => _.debug(...args)),
			Console_error = (...args) => consoleWith(_ => _.error(...args)),
			Console_info = (...args) => consoleWith(_ => _.info(...args)),
			Console_log = (...args) => consoleWith(_ => _.log(...args)),
			Console_trace = (...args) => consoleWith(_ => _.trace(...args)),
			Console_warn = (...args) => consoleWith(_ => _.warn(...args)),
			getConsoleLog = x =>
				x === Trace
					? Console_trace
					: x === Debug
						? Console_debug
						: x === Info
							? Console_info
							: x === Warning
								? Console_warn
								: x === LogLevel_Error || x === Fatal
									? Console_error
									: Console_log,
			metaLogger = Logger_make(({ logLevel, message, context, annotations }) =>
				Effect_runPromise(
					pipe(
						() =>
							`${pipe(annotations, HashMap_get(src_LogAnnotationKeys.name), Option_match({ onNone: () => "", onSome: x => `[${x}] ` }))}${message}`,
						getStr =>
							pipe(
								FiberRefs_getOrDefault(context, logMeta),
								Option_match({
									onNone: () =>
										greaterThanEqual(Warning)(logLevel)
											? getConsoleLog(logLevel)(getStr())
											: _void,
									onSome: meta =>
										Effect_sync(() =>
											getConsoleLog(logLevel)(`${getStr()}: `, meta),
										),
								}),
							),
					),
				),
			),
			provideLog = settingUpdateApps => effect =>
				pipe(
					Effect_succeed(
						Logger_replace(
							Logger_defaultLogger,
							Logger_zip(metaLogger)(eventLogger(settingUpdateApps)),
						),
					),
					Effect_flatMap(logLayer =>
						pipe(
							effect,
							Effect_tapErrorCause(x => Effect_logError(Cause_pretty(x))),
							Effect_provide(logLayer),
						),
					),
					Effect_annotateLogs(src_LogAnnotationKeys.name, "FYC"),
					Logger_withMinimumLogLevel(Debug),
				)
		__webpack_require__.dn(provideLog)
		Effect_runPromise(
			pipe(
				Effect_gen(function* () {
					const settingUpdateApps = yield* Ref_make([])
					yield* initialize({
						settingUpdateApps,
						provideLog: provideLog(settingUpdateApps),
					})
				}),
				Effect_withConcurrency(30),
			),
		)
	})()
})()