Flow Youtube Chat

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

目前為 2023-04-04 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Flow Youtube Chat
  3. // @description Youtubeのチャットをニコニコ風に画面上へ流す(再アップ) Make youtube chats move in danmaku-style.
  4. // @version 1.16.0
  5. // @match https://www.youtube.com/*
  6. // @grant GM.setValue
  7. // @grant GM.getValue
  8. // @grant GM.deleteValue
  9. // @grant GM.listValues
  10. // @grant GM.setClipboard
  11. // @license AGPL-3.0-or-later
  12. // @namespace FlowYoutubeChatScript
  13. // @noframes
  14. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11.7.3/dist/sweetalert2.all.min.js#sha384-/Wx1NuqlgALfa1Do1U6Mer7quEDHOo8REf/0izoIrV8Y3Z/gtEHQc01STCEMM1LZ
  15. // @require https://unpkg.com/loglevel@1.8.0/dist/loglevel.min.js#sha384-xnEzWQtTztbu/yV2BtSvqqZGP52iLXbnb4NJ59OYT0ZDo1fGaKCR6QBxjyRuNFJ8
  16. // @require https://unpkg.com/rxjs@7.5.6/dist/bundles/rxjs.umd.min.js#sha384-loWwI45AmzSZ93ze6KW4+6eZVsQT8PriLOVCZGZstdycw5uylV3xKkHLQh53ui6b
  17. // @require https://unpkg.com/mithril@2.2.2/mithril.min.js#sha384-60kek02kUAH+DNSgj7HCtrpcirTroG3uWnDpsdvoAl2Z9Xe3GdpXDSy4ouNMHoBZ
  18. // @require https://cdn.jsdelivr.net/npm/check-types@11.1.2/src/check-types.min.js#sha384-KGnImnhVjA5llfqKEbjBiY+1Mp6oa+NvW/TEY1XTPAKWNgrAwa3Qvn//MXL07wBM
  19. // @require https://cdn.jsdelivr.net/npm/deep-diff@1.0.2/index.min.js#sha384-Q/uiWfFlwn9XjOpL49VpFKn01EkScmaC3hh1prAn7S++WoZgXRrrjQvZ7cI7C7Zn
  20. // @require https://cdn.jsdelivr.net/npm/astring@1.8.3/dist/astring.min.js#sha384-5Ucbdr4B4nO60a/3Lv4z9adjzcDkpVPH19acFTr320dXMe+cKE5y5zV+gycjJO8N
  21. // @require https://cdn.jsdelivr.net/npm/jsep@1.3.6/dist/iife/jsep.iife.min.js#sha384-6PGvkKayYZDccXp2sQ43aTf44oUNudO3L940VBGQYHfhg3YZEgSEbuannHJk7NBe
  22. // @require https://cdn.jsdelivr.net/npm/hash-it@5.0.2/dist/hash-it.min.js#sha384-biRMep0zr/5fw/hIdnBIb56UHRgiIyhAagZrngd9dSxxQ9aDFMP0hbYR8PEj5lVu
  23. // @require https://cdn.jsdelivr.net/npm/micro-memoize@4.0.14/dist/micro-memoize.min.js#sha384-W1hqD6GTNQ97ZqDR18GhfU1G9qcDLs4sL7BPYND2ncvGNNiLUmUp37Ph+hzm+OPt
  24. // @require https://cdn.jsdelivr.net/npm/lz-string@1.5.0/libs/lz-string.min.js#sha384-0d+Gr7vM4Drod8E3hXKgciWJSWbjD/opKLLygI9ktiWbuvlDwQLzU46wJ9s5gsp7
  25. // @run-at document-end
  26. // ==/UserScript==
  27.  
  28. /* jshint esversion: 6 */
  29.  
  30. ;(() => {
  31. var __webpack_modules__ = {
  32. 661: module => {
  33. module.exports = !1
  34. },
  35. 204: module => {
  36. "use strict"
  37. module.exports = function equal(a, b) {
  38. if (a === b) return !0
  39. if (a && b && "object" == typeof a && "object" == typeof b) {
  40. if (a.constructor !== b.constructor) return !1
  41. var length, i, keys
  42. if (Array.isArray(a)) {
  43. if ((length = a.length) != b.length) return !1
  44. for (i = length; 0 != i--; ) if (!equal(a[i], b[i])) return !1
  45. return !0
  46. }
  47. if (a.constructor === RegExp)
  48. return a.source === b.source && a.flags === b.flags
  49. if (a.valueOf !== Object.prototype.valueOf)
  50. return a.valueOf() === b.valueOf()
  51. if (a.toString !== Object.prototype.toString)
  52. return a.toString() === b.toString()
  53. if (
  54. (length = (keys = Object.keys(a)).length) !==
  55. Object.keys(b).length
  56. )
  57. return !1
  58. for (i = length; 0 != i--; )
  59. if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return !1
  60. for (i = length; 0 != i--; ) {
  61. var key = keys[i]
  62. if (!equal(a[key], b[key])) return !1
  63. }
  64. return !0
  65. }
  66. return a != a && b != b
  67. }
  68. },
  69. 52: (__unused_webpack_module, exports) => {
  70. "use strict"
  71. exports.Xd = exports.hu = exports.tE = void 0
  72. const expectedToBe = type => `expected to be ${type}`
  73. exports.tE = (condition, message) => {
  74. if (!condition) throw new TypeError(message)
  75. }
  76. let baseAssert = exports.tE
  77. exports.hu = (condition, message) => baseAssert(condition, message)
  78. exports.Xd = function (
  79. input,
  80. message = expectedToBe("neither null nor undefined")
  81. ) {
  82. ;(0, exports.hu)(null != input, message)
  83. }
  84. },
  85. 694: module => {
  86. module.exports = (function (e) {
  87. var r = {}
  88. function t(n) {
  89. if (r[n]) return r[n].exports
  90. var a = (r[n] = { i: n, l: !1, exports: {} })
  91. return e[n].call(a.exports, a, a.exports, t), (a.l = !0), a.exports
  92. }
  93. return (
  94. (t.m = e),
  95. (t.c = r),
  96. (t.d = function (e, r, n) {
  97. t.o(e, r) ||
  98. Object.defineProperty(e, r, { enumerable: !0, get: n })
  99. }),
  100. (t.r = function (e) {
  101. "undefined" != typeof Symbol &&
  102. Symbol.toStringTag &&
  103. Object.defineProperty(e, Symbol.toStringTag, {
  104. value: "Module",
  105. }),
  106. Object.defineProperty(e, "__esModule", { value: !0 })
  107. }),
  108. (t.t = function (e, r) {
  109. if ((1 & r && (e = t(e)), 8 & r)) return e
  110. if (4 & r && "object" == typeof e && e && e.__esModule) return e
  111. var n = Object.create(null)
  112. if (
  113. (t.r(n),
  114. Object.defineProperty(n, "default", {
  115. enumerable: !0,
  116. value: e,
  117. }),
  118. 2 & r && "string" != typeof e)
  119. )
  120. for (var a in e)
  121. t.d(
  122. n,
  123. a,
  124. function (r) {
  125. return e[r]
  126. }.bind(null, a)
  127. )
  128. return n
  129. }),
  130. (t.n = function (e) {
  131. var r =
  132. e && e.__esModule
  133. ? function () {
  134. return e.default
  135. }
  136. : function () {
  137. return e
  138. }
  139. return t.d(r, "a", r), r
  140. }),
  141. (t.o = function (e, r) {
  142. return Object.prototype.hasOwnProperty.call(e, r)
  143. }),
  144. (t.p = ""),
  145. t((t.s = 0))
  146. )
  147. })([
  148. function (e, r, t) {
  149. "use strict"
  150. t.r(r),
  151. t.d(r, "validateHTMLColorName", function () {
  152. return l
  153. }),
  154. t.d(r, "validateHTMLColorSpecialName", function () {
  155. return i
  156. }),
  157. t.d(r, "validateHTMLColorHex", function () {
  158. return u
  159. }),
  160. t.d(r, "validateHTMLColorRgb", function () {
  161. return g
  162. }),
  163. t.d(r, "validateHTMLColorHsl", function () {
  164. return y
  165. }),
  166. t.d(r, "validateHTMLColorHwb", function () {
  167. return L
  168. }),
  169. t.d(r, "validateHTMLColorLab", function () {
  170. return S
  171. }),
  172. t.d(r, "validateHTMLColorLch", function () {
  173. return m
  174. }),
  175. t.d(r, "validateHTMLColor", function () {
  176. return G
  177. })
  178. const n = e => e && "string" == typeof e,
  179. a = [
  180. "AliceBlue",
  181. "AntiqueWhite",
  182. "Aqua",
  183. "Aquamarine",
  184. "Azure",
  185. "Beige",
  186. "Bisque",
  187. "Black",
  188. "BlanchedAlmond",
  189. "Blue",
  190. "BlueViolet",
  191. "Brown",
  192. "BurlyWood",
  193. "CadetBlue",
  194. "Chartreuse",
  195. "Chocolate",
  196. "Coral",
  197. "CornflowerBlue",
  198. "Cornsilk",
  199. "Crimson",
  200. "Cyan",
  201. "DarkBlue",
  202. "DarkCyan",
  203. "DarkGoldenrod",
  204. "DarkGray",
  205. "DarkGrey",
  206. "DarkGreen",
  207. "DarkKhaki",
  208. "DarkMagenta",
  209. "DarkOliveGreen",
  210. "DarkOrange",
  211. "DarkOrchid",
  212. "DarkRed",
  213. "DarkSalmon",
  214. "DarkSeaGreen",
  215. "DarkSlateBlue",
  216. "DarkSlateGray",
  217. "DarkSlateGrey",
  218. "DarkTurquoise",
  219. "DarkViolet",
  220. "DeepPink",
  221. "DeepSkyBlue",
  222. "DimGray",
  223. "DimGrey",
  224. "DodgerBlue",
  225. "FireBrick",
  226. "FloralWhite",
  227. "ForestGreen",
  228. "Fuchsia",
  229. "Gainsboro",
  230. "GhostWhite",
  231. "Gold",
  232. "Goldenrod",
  233. "Gray",
  234. "Grey",
  235. "Green",
  236. "GreenYellow",
  237. "HoneyDew",
  238. "HotPink",
  239. "IndianRed",
  240. "Indigo",
  241. "Ivory",
  242. "Khaki",
  243. "Lavender",
  244. "LavenderBlush",
  245. "LawnGreen",
  246. "LemonChiffon",
  247. "LightBlue",
  248. "LightCoral",
  249. "LightCyan",
  250. "LightGoldenrodYellow",
  251. "LightGray",
  252. "LightGrey",
  253. "LightGreen",
  254. "LightPink",
  255. "LightSalmon",
  256. "LightSalmon",
  257. "LightSeaGreen",
  258. "LightSkyBlue",
  259. "LightSlateGray",
  260. "LightSlateGrey",
  261. "LightSteelBlue",
  262. "LightYellow",
  263. "Lime",
  264. "LimeGreen",
  265. "Linen",
  266. "Magenta",
  267. "Maroon",
  268. "MediumAquamarine",
  269. "MediumBlue",
  270. "MediumOrchid",
  271. "MediumPurple",
  272. "MediumSeaGreen",
  273. "MediumSlateBlue",
  274. "MediumSlateBlue",
  275. "MediumSpringGreen",
  276. "MediumTurquoise",
  277. "MediumVioletRed",
  278. "MidnightBlue",
  279. "MintCream",
  280. "MistyRose",
  281. "Moccasin",
  282. "NavajoWhite",
  283. "Navy",
  284. "OldLace",
  285. "Olive",
  286. "OliveDrab",
  287. "Orange",
  288. "OrangeRed",
  289. "Orchid",
  290. "PaleGoldenrod",
  291. "PaleGreen",
  292. "PaleTurquoise",
  293. "PaleVioletRed",
  294. "PapayaWhip",
  295. "PeachPuff",
  296. "Peru",
  297. "Pink",
  298. "Plum",
  299. "PowderBlue",
  300. "Purple",
  301. "RebeccaPurple",
  302. "Red",
  303. "RosyBrown",
  304. "RoyalBlue",
  305. "SaddleBrown",
  306. "Salmon",
  307. "SandyBrown",
  308. "SeaGreen",
  309. "SeaShell",
  310. "Sienna",
  311. "Silver",
  312. "SkyBlue",
  313. "SlateBlue",
  314. "SlateGray",
  315. "SlateGrey",
  316. "Snow",
  317. "SpringGreen",
  318. "SteelBlue",
  319. "Tan",
  320. "Teal",
  321. "Thistle",
  322. "Tomato",
  323. "Turquoise",
  324. "Violet",
  325. "Wheat",
  326. "White",
  327. "WhiteSmoke",
  328. "Yellow",
  329. "YellowGreen",
  330. ],
  331. o = ["currentColor", "inherit", "transparent"],
  332. l = e => {
  333. let r = !1
  334. return (
  335. n(e) &&
  336. a.map(
  337. t => (
  338. e.toLowerCase() === t.toLowerCase() && (r = !0), null
  339. )
  340. ),
  341. r
  342. )
  343. },
  344. i = e => {
  345. let r = !1
  346. return (
  347. n(e) &&
  348. o.map(
  349. t => (
  350. e.toLowerCase() === t.toLowerCase() && (r = !0), null
  351. )
  352. ),
  353. r
  354. )
  355. },
  356. u = e => {
  357. if (n(e)) {
  358. const r = /^#([\da-f]{3}){1,2}$|^#([\da-f]{4}){1,2}$/i
  359. return e && r.test(e)
  360. }
  361. return !1
  362. },
  363. d = "(([\\d]{0,5})((\\.([\\d]{1,5}))?))",
  364. s = `(${d}%)`,
  365. c = "(([0-9]|[1-9][0-9]|100)%)",
  366. f = `(${c}|(0?((\\.([\\d]{1,5}))?))|1)`,
  367. h = `([\\s]{0,5})\\)?)(([\\s]{0,5})(\\/?)([\\s]{1,5})(((${c}))|(0?((\\.([\\d]{1,5}))?))|1))?([\\s]{0,5})\\)`,
  368. $ =
  369. "(-?(([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)?)",
  370. g = e => {
  371. if (n(e)) {
  372. const r = "([\\s]{0,5})([\\d]{1,5})%?([\\s]{0,5}),?",
  373. t = "((([\\s]{0,5}),?([\\s]{0,5}))|(([\\s]{1,5})))",
  374. n = new RegExp(
  375. `^(rgb)a?\\(${r}${t}${r}${t}${r}${t}((\\/?([\\s]{0,5})(0?\\.?([\\d]{1,5})%?([\\s]{0,5}))?|1|0))?\\)$`
  376. )
  377. return e && n.test(e)
  378. }
  379. return !1
  380. },
  381. y = e => {
  382. if (n(e)) {
  383. const r = new RegExp(
  384. `^(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))?\\)$`
  385. )
  386. return e && r.test(e)
  387. }
  388. return !1
  389. },
  390. L = e => {
  391. if (n(e)) {
  392. const r = new RegExp(
  393. `^(hwb\\(([\\s]{0,5})${$}([\\s]{1,5}))((0|${c})([\\s]{1,5}))((0|${c})${h}$`
  394. )
  395. return e && r.test(e)
  396. }
  397. return !1
  398. },
  399. S = e => {
  400. if (n(e)) {
  401. const r =
  402. "(-?(([0-9]|[1-9][0-9]|1[0-5][0-9])((\\.([\\d]{1,5}))?)?|160))",
  403. t = new RegExp(
  404. `^(lab\\(([\\s]{0,5})${s}([\\s]{1,5})${r}([\\s]{1,5})${r}${h}$`
  405. )
  406. return e && t.test(e)
  407. }
  408. return !1
  409. },
  410. m = e => {
  411. if (n(e)) {
  412. const o = new RegExp(
  413. `^lch\\((([\\s]{0,5})((([0-9]|[1-9][0-9])?((\\.([\\d]{1,5}))?)|100)(%)?)([\\s]{1,5})${
  414. "" + d
  415. }([\\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}))?)\\)$`
  416. )
  417. return e && o.test(e)
  418. }
  419. return !1
  420. },
  421. G = e => !!((e && u(e)) || g(e) || y(e) || L(e) || S(e) || m(e))
  422. r.default = e =>
  423. !!(
  424. (e && u(e)) ||
  425. l(e) ||
  426. i(e) ||
  427. g(e) ||
  428. y(e) ||
  429. L(e) ||
  430. S(e) ||
  431. m(e)
  432. )
  433. },
  434. ])
  435. },
  436. 938: () => {},
  437. },
  438. __webpack_module_cache__ = {}
  439. function __webpack_require__(moduleId) {
  440. var cachedModule = __webpack_module_cache__[moduleId]
  441. if (void 0 !== cachedModule) return cachedModule.exports
  442. var module = (__webpack_module_cache__[moduleId] = { exports: {} })
  443. __webpack_modules__[moduleId](module, module.exports, __webpack_require__)
  444. return module.exports
  445. }
  446. __webpack_require__.n = module => {
  447. var getter =
  448. module && module.__esModule ? () => module.default : () => module
  449. __webpack_require__.d(getter, { a: getter })
  450. return getter
  451. }
  452. __webpack_require__.d = (exports, definition) => {
  453. for (var key in definition)
  454. __webpack_require__.o(definition, key) &&
  455. !__webpack_require__.o(exports, key) &&
  456. Object.defineProperty(exports, key, {
  457. enumerable: !0,
  458. get: definition[key],
  459. })
  460. }
  461. __webpack_require__.o = (obj, prop) =>
  462. Object.prototype.hasOwnProperty.call(obj, prop)
  463. ;(() => {
  464. "use strict"
  465. const Function_dual = (arity, body) => {
  466. const isDataFirst =
  467. "number" == typeof arity ? args => args.length >= arity : arity
  468. return function () {
  469. return isDataFirst(arguments)
  470. ? body.apply(this, arguments)
  471. : self => body(self, ...arguments)
  472. }
  473. },
  474. apply = a => self => self(a),
  475. Function_identity = a => a,
  476. constant = value => () => value,
  477. Function_constTrue = constant(!0),
  478. Function_constFalse = constant(!1),
  479. Function_constUndefined = constant(void 0),
  480. Function_constVoid = Function_constUndefined,
  481. flip =
  482. f =>
  483. (...b) =>
  484. (...a) =>
  485. f(...a)(...b)
  486. function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) {
  487. switch (arguments.length) {
  488. case 1:
  489. return ab
  490. case 2:
  491. return function () {
  492. return bc(ab.apply(this, arguments))
  493. }
  494. case 3:
  495. return function () {
  496. return cd(bc(ab.apply(this, arguments)))
  497. }
  498. case 4:
  499. return function () {
  500. return de(cd(bc(ab.apply(this, arguments))))
  501. }
  502. case 5:
  503. return function () {
  504. return ef(de(cd(bc(ab.apply(this, arguments)))))
  505. }
  506. case 6:
  507. return function () {
  508. return fg(ef(de(cd(bc(ab.apply(this, arguments))))))
  509. }
  510. case 7:
  511. return function () {
  512. return gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))
  513. }
  514. case 8:
  515. return function () {
  516. return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))))
  517. }
  518. case 9:
  519. return function () {
  520. return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))))
  521. }
  522. }
  523. }
  524. function pipe(a, ab, bc, cd, de, ef, fg, gh, hi) {
  525. switch (arguments.length) {
  526. case 1:
  527. return a
  528. case 2:
  529. return ab(a)
  530. case 3:
  531. return bc(ab(a))
  532. case 4:
  533. return cd(bc(ab(a)))
  534. case 5:
  535. return de(cd(bc(ab(a))))
  536. case 6:
  537. return ef(de(cd(bc(ab(a)))))
  538. case 7:
  539. return fg(ef(de(cd(bc(ab(a))))))
  540. case 8:
  541. return gh(fg(ef(de(cd(bc(ab(a)))))))
  542. case 9:
  543. return hi(gh(fg(ef(de(cd(bc(ab(a))))))))
  544. default: {
  545. let ret = arguments[0]
  546. for (let i = 1; i < arguments.length; i++) ret = arguments[i](ret)
  547. return ret
  548. }
  549. }
  550. }
  551. const imap = map => Function_dual(3, (self, to, _) => map(self, to)),
  552. let_ = F =>
  553. Function_dual(3, (self, name, f) =>
  554. F.map(self, a => Object.assign({}, a, { [name]: f(a) }))
  555. ),
  556. letDiscard = F =>
  557. Function_dual(3, (self, name, b) =>
  558. F.map(self, a => Object.assign({}, a, { [name]: b }))
  559. ),
  560. globalStoreId = Symbol.for("@effect/data/Global/globalStoreId")
  561. globalStoreId in globalThis || (globalThis[globalStoreId] = new Map())
  562. const globalStore = globalThis[globalStoreId],
  563. globalValue = (id, compute) => {
  564. globalStore.has(id) || globalStore.set(id, compute())
  565. return globalStore.get(id)
  566. }
  567. function isNothing(value) {
  568. return null == value
  569. }
  570. class PCGRandom {
  571. constructor(seedHi, seedLo, incHi, incLo) {
  572. if (isNothing(seedLo) && isNothing(seedHi)) {
  573. seedLo = (4294967295 * Math.random()) >>> 0
  574. seedHi = 0
  575. } else if (isNothing(seedLo)) {
  576. seedLo = seedHi
  577. seedHi = 0
  578. }
  579. if (isNothing(incLo) && isNothing(incHi)) {
  580. incLo = this._state ? this._state[3] : 4150755663
  581. incHi = this._state ? this._state[2] : 335903614
  582. } else if (isNothing(incLo)) {
  583. incLo = incHi
  584. incHi = 0
  585. }
  586. this._state = new Int32Array([
  587. 0,
  588. 0,
  589. incHi >>> 0,
  590. (1 | (incLo || 0)) >>> 0,
  591. ])
  592. this._next()
  593. add64(
  594. this._state,
  595. this._state[0],
  596. this._state[1],
  597. seedHi >>> 0,
  598. seedLo >>> 0
  599. )
  600. this._next()
  601. return this
  602. }
  603. getState() {
  604. return [this._state[0], this._state[1], this._state[2], this._state[3]]
  605. }
  606. setState(state) {
  607. this._state[0] = state[0]
  608. this._state[1] = state[1]
  609. this._state[2] = state[2]
  610. this._state[3] = 1 | state[3]
  611. }
  612. integer(max) {
  613. if (!max) return this._next()
  614. if (0 == ((max >>>= 0) & (max - 1))) return this._next() & (max - 1)
  615. let num = 0
  616. const skew = (-max >>> 0) % max >>> 0
  617. for (num = this._next(); num < skew; num = this._next());
  618. return num % max
  619. }
  620. number() {
  621. return (
  622. (1 * (67108863 & this._next()) * 134217728 +
  623. 1 * (134217727 & this._next())) /
  624. 9007199254740992
  625. )
  626. }
  627. _next() {
  628. const oldHi = this._state[0] >>> 0,
  629. oldLo = this._state[1] >>> 0
  630. !(function (out, aHi, aLo, bHi, bLo) {
  631. let c1 = (32557 * (aLo >>> 16)) >>> 0,
  632. c0 = (19605 * (65535 & aLo)) >>> 0,
  633. lo = (32557 * (65535 & aLo)) >>> 0,
  634. hi = (19605 * (aLo >>> 16) + ((c0 >>> 16) + (c1 >>> 16))) >>> 0
  635. c0 = (c0 << 16) >>> 0
  636. lo = (lo + c0) >>> 0
  637. lo >>> 0 < c0 >>> 0 && (hi = (hi + 1) >>> 0)
  638. c1 = (c1 << 16) >>> 0
  639. lo = (lo + c1) >>> 0
  640. lo >>> 0 < c1 >>> 0 && (hi = (hi + 1) >>> 0)
  641. hi = (hi + Math.imul(aLo, 1481765933)) >>> 0
  642. hi = (hi + Math.imul(aHi, bLo)) >>> 0
  643. out[0] = hi
  644. out[1] = lo
  645. })(this._state, oldHi, oldLo, 0, 1284865837)
  646. add64(
  647. this._state,
  648. this._state[0],
  649. this._state[1],
  650. this._state[2],
  651. this._state[3]
  652. )
  653. let xsHi = oldHi >>> 18,
  654. xsLo = ((oldLo >>> 18) | (oldHi << 14)) >>> 0
  655. xsHi = (xsHi ^ oldHi) >>> 0
  656. xsLo = (xsLo ^ oldLo) >>> 0
  657. const xorshifted = ((xsLo >>> 27) | (xsHi << 5)) >>> 0,
  658. rot = oldHi >>> 27
  659. return (
  660. ((xorshifted >>> rot) |
  661. (xorshifted << (((-rot >>> 0) & 31) >>> 0))) >>>
  662. 0
  663. )
  664. }
  665. }
  666. function add64(out, aHi, aLo, bHi, bLo) {
  667. let hi = (aHi + bHi) >>> 0
  668. const lo = (aLo + bLo) >>> 0
  669. lo >>> 0 < aLo >>> 0 && (hi = (hi + 1) | 0)
  670. out[0] = hi
  671. out[1] = lo
  672. }
  673. const randomHashCache = globalValue(
  674. Symbol.for("@effect/data/Hash/randomHashCache"),
  675. () => new WeakMap()
  676. ),
  677. pcgr = globalValue(
  678. Symbol.for("@effect/data/Hash/pcgr"),
  679. () => new PCGRandom()
  680. ),
  681. symbol = Symbol.for("@effect/data/Hash"),
  682. Hash_hash = self => {
  683. switch (typeof self) {
  684. case "number":
  685. return number(self)
  686. case "bigint":
  687. return string(self.toString(10))
  688. case "boolean":
  689. case "symbol":
  690. return string(String(self))
  691. case "string":
  692. return string(self)
  693. case "undefined":
  694. return string("undefined")
  695. case "function":
  696. case "object":
  697. return null === self
  698. ? string("null")
  699. : isHash(self)
  700. ? self[symbol]()
  701. : random(self)
  702. default:
  703. throw new Error("Bug in Equal.hashGeneric")
  704. }
  705. },
  706. random = self => {
  707. randomHashCache.has(self) ||
  708. randomHashCache.set(
  709. self,
  710. number(pcgr.integer(Number.MAX_SAFE_INTEGER))
  711. )
  712. return randomHashCache.get(self)
  713. },
  714. combine = b => self => (53 * self) ^ b,
  715. optimize = n => (3221225471 & n) | ((n >>> 1) & 1073741824),
  716. isHash = u => "object" == typeof u && null !== u && symbol in u,
  717. number = n => {
  718. if (n != n || n === 1 / 0) return 0
  719. let h = 0 | n
  720. h !== n && (h ^= 4294967295 * n)
  721. for (; n > 4294967295; ) h ^= n /= 4294967295
  722. return optimize(n)
  723. },
  724. string = str => {
  725. let h = 5381,
  726. i = str.length
  727. for (; i; ) h = (33 * h) ^ str.charCodeAt(--i)
  728. return optimize(h)
  729. },
  730. array = arr => {
  731. let h = 6151
  732. for (let i = 0; i < arr.length; i++) h = combine(Hash_hash(arr[i]))(h)
  733. return optimize(h)
  734. },
  735. Equal_symbol = Symbol.for("@effect/data/Equal")
  736. function equals() {
  737. return 1 === arguments.length
  738. ? self => compareBoth(self, arguments[0])
  739. : compareBoth(arguments[0], arguments[1])
  740. }
  741. function compareBoth(self, that) {
  742. if (self === that) return !0
  743. const selfType = typeof self
  744. return (
  745. selfType === typeof that &&
  746. !(
  747. ("object" !== selfType && "function" !== selfType) ||
  748. null === self ||
  749. null === that ||
  750. !isEqual(self) ||
  751. !isEqual(that)
  752. ) &&
  753. Hash_hash(self) === Hash_hash(that) &&
  754. self[Equal_symbol](that)
  755. )
  756. }
  757. const isEqual = u => "object" == typeof u && null !== u && Equal_symbol in u
  758. var _a
  759. const runtimeDebug = globalValue(
  760. Symbol.for("@effect/data/Debug/runtimeDebug"),
  761. () => ({
  762. reportUnhandled: !0,
  763. minumumLogLevel: "Info",
  764. traceStackLimit: 5,
  765. tracingEnabled: !0,
  766. parseStack: error => {
  767. const stack = error.stack
  768. if (stack) {
  769. const lines = stack.split("\n")
  770. let starts = 0
  771. for (let i = 0; i < lines.length; i++)
  772. lines[i].startsWith("Error") && (starts = i)
  773. const frames = []
  774. for (let i = starts + 1; i < lines.length; i++)
  775. if (lines[i].includes("at")) {
  776. const blocks = lines[i]
  777. .split(" ")
  778. .filter(i => i.length > 0 && "at" !== i),
  779. name =
  780. 2 !== blocks.length || blocks[0].includes("<anonymous>")
  781. ? void 0
  782. : blocks[0],
  783. matchFrame = (
  784. 2 === blocks.length ? blocks[1] : blocks[0]
  785. )?.match(/\(?(.*):(\d+):(\d+)/)
  786. matchFrame
  787. ? frames.push({
  788. name,
  789. fileName: matchFrame[1],
  790. line: Number.parseInt(matchFrame[2]),
  791. column: Number.parseInt(matchFrame[3]),
  792. })
  793. : frames.push(void 0)
  794. } else frames.push(void 0)
  795. return frames
  796. }
  797. return []
  798. },
  799. filterStackFrame: _ =>
  800. null != _ && !_.fileName.match(/\/internal_effect_untraced/),
  801. })
  802. ),
  803. sourceLocationProto = Object.setPrototypeOf(
  804. {
  805. toFrame() {
  806. if ("parsed" in this) return this.parsed
  807. const stack = runtimeDebug.parseStack(this)
  808. stack && stack.length >= 2 && stack[0] && stack[1]
  809. ? (this.parsed = {
  810. ...stack[this.depth - 1],
  811. name: stack[this.depth - 2]?.name,
  812. })
  813. : (this.parsed = void 0)
  814. return this.parsed
  815. },
  816. },
  817. Error.prototype
  818. ),
  819. sourceLocation = error => {
  820. error.depth = Error.stackTraceLimit
  821. Object.setPrototypeOf(error, sourceLocationProto)
  822. return error
  823. },
  824. bodyWithTrace = body => {
  825. if (!runtimeDebug.tracingEnabled) return body(void 0, restoreOff)
  826. runtimeDebug.tracingEnabled = !1
  827. try {
  828. const limit = Error.stackTraceLimit
  829. Error.stackTraceLimit = 3
  830. const source = sourceLocation(new Error())
  831. Error.stackTraceLimit = limit
  832. return body(source, restoreOn)
  833. } finally {
  834. runtimeDebug.tracingEnabled = !0
  835. }
  836. },
  837. methodWithTrace = body =>
  838. function () {
  839. if (!runtimeDebug.tracingEnabled)
  840. return body(void 0, restoreOff).apply(this, arguments)
  841. runtimeDebug.tracingEnabled = !1
  842. try {
  843. const limit = Error.stackTraceLimit
  844. Error.stackTraceLimit = 2
  845. const error = sourceLocation(new Error())
  846. Error.stackTraceLimit = limit
  847. return body(error, restoreOn).apply(this, arguments)
  848. } finally {
  849. runtimeDebug.tracingEnabled = !0
  850. }
  851. },
  852. dualWithTrace = (dfLen, body) => {
  853. const isDataFirst =
  854. "number" == typeof dfLen ? args => args.length === dfLen : dfLen
  855. return function () {
  856. if (!runtimeDebug.tracingEnabled) {
  857. const f = body(void 0, restoreOff)
  858. return isDataFirst(arguments)
  859. ? untraced(() => f.apply(this, arguments))
  860. : self => untraced(() => f(self, ...arguments))
  861. }
  862. runtimeDebug.tracingEnabled = !1
  863. try {
  864. const limit = Error.stackTraceLimit
  865. Error.stackTraceLimit = 2
  866. const source = sourceLocation(new Error())
  867. Error.stackTraceLimit = limit
  868. const f = body(source, restoreOn)
  869. return isDataFirst(arguments)
  870. ? untraced(() => f.apply(this, arguments))
  871. : self => untraced(() => f(self, ...arguments))
  872. } finally {
  873. runtimeDebug.tracingEnabled = !0
  874. }
  875. }
  876. },
  877. untraced = body => {
  878. if (!runtimeDebug.tracingEnabled) return body(restoreOff)
  879. runtimeDebug.tracingEnabled = !1
  880. try {
  881. return body(restoreOn)
  882. } finally {
  883. runtimeDebug.tracingEnabled = !0
  884. }
  885. },
  886. untracedDual = (dfLen, body) =>
  887. function () {
  888. if (!runtimeDebug.tracingEnabled) {
  889. const f = body(restoreOff)
  890. return arguments.length === dfLen
  891. ? untraced(() => f.apply(this, arguments))
  892. : self => untraced(() => f(self, ...arguments))
  893. }
  894. runtimeDebug.tracingEnabled = !1
  895. try {
  896. const f = body(restoreOn)
  897. return arguments.length === dfLen
  898. ? untraced(() => f.apply(this, arguments))
  899. : self => untraced(() => f(self, ...arguments))
  900. } finally {
  901. runtimeDebug.tracingEnabled = !0
  902. }
  903. },
  904. untracedMethod = body =>
  905. function () {
  906. if (!runtimeDebug.tracingEnabled)
  907. return untraced(() => body(restoreOff).apply(this, arguments))
  908. runtimeDebug.tracingEnabled = !1
  909. try {
  910. return untraced(() => body(restoreOn).apply(this, arguments))
  911. } finally {
  912. runtimeDebug.tracingEnabled = !0
  913. }
  914. },
  915. restoreOn = body =>
  916. function () {
  917. if (runtimeDebug.tracingEnabled) return body.apply(this, arguments)
  918. runtimeDebug.tracingEnabled = !0
  919. try {
  920. return body.apply(this, arguments)
  921. } finally {
  922. runtimeDebug.tracingEnabled = !1
  923. }
  924. },
  925. restoreOff = body =>
  926. function () {
  927. if (!runtimeDebug.tracingEnabled) return body.apply(this, arguments)
  928. runtimeDebug.tracingEnabled = !1
  929. try {
  930. return body.apply(this, arguments)
  931. } finally {
  932. runtimeDebug.tracingEnabled = !0
  933. }
  934. },
  935. EffectTypeId = Symbol.for("@effect/io/Effect")
  936. class TracedPrimitive {
  937. [((_a = EffectTypeId), Equal_symbol)](that) {
  938. return this === that
  939. }
  940. [symbol]() {
  941. return random(this)
  942. }
  943. constructor(i0, trace) {
  944. this.i0 = i0
  945. this.trace = trace
  946. this._tag = "Traced"
  947. this.i1 = void 0
  948. this.i2 = void 0
  949. this[_a] = effectVariance
  950. }
  951. traced(trace) {
  952. return trace ? new TracedPrimitive(this, trace) : this
  953. }
  954. }
  955. const effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  956. makeTraced = (self, source) => new TracedPrimitive(self, source)
  957. var Option_a, _b
  958. const Option_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  959. Option_EffectTypeId = Symbol.for("@effect/io/Effect")
  960. class Some {
  961. [((Option_a = Option_EffectTypeId), Equal_symbol)](that) {
  962. return isOption(that) && isSome(that) && equals(that.i0, this.i0)
  963. }
  964. [symbol]() {
  965. return Hash_hash(this.i0)
  966. }
  967. toJSON() {
  968. return { _tag: this._tag, value: this.i0 }
  969. }
  970. get value() {
  971. return this.i0
  972. }
  973. constructor(i0) {
  974. this.i0 = i0
  975. this._tag = "Some"
  976. this.i1 = void 0
  977. this.i2 = void 0
  978. this.trace = void 0
  979. this[Option_a] = Option_effectVariance
  980. }
  981. traced(trace) {
  982. return trace ? makeTraced(this, trace) : this
  983. }
  984. }
  985. class None {
  986. constructor() {
  987. this._tag = "None"
  988. this.i0 = void 0
  989. this.i1 = void 0
  990. this.i2 = void 0
  991. this.trace = void 0
  992. this[_b] = Option_effectVariance
  993. }
  994. [((_b = Option_EffectTypeId), Equal_symbol)](that) {
  995. return isOption(that) && isNone(that)
  996. }
  997. [symbol]() {
  998. return Hash_hash(this._tag)
  999. }
  1000. toJSON() {
  1001. return { _tag: this._tag }
  1002. }
  1003. traced(trace) {
  1004. return trace ? makeTraced(this, trace) : this
  1005. }
  1006. }
  1007. const isOption = input =>
  1008. "object" == typeof input &&
  1009. null != input &&
  1010. "_tag" in input &&
  1011. ("None" === input._tag || "Some" === input._tag) &&
  1012. isEqual(input),
  1013. isNone = fa => "None" === fa._tag,
  1014. isSome = fa => "Some" === fa._tag,
  1015. none = new None(),
  1016. some = a => new Some(a)
  1017. var Either_a, Either_b
  1018. const Either_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  1019. Either_EffectTypeId = Symbol.for("@effect/io/Effect")
  1020. class Right {
  1021. [((Either_a = Either_EffectTypeId), Equal_symbol)](that) {
  1022. return isEither(that) && isRight(that) && equals(that.i0, this.i0)
  1023. }
  1024. [symbol]() {
  1025. return Hash_hash(this.i0)
  1026. }
  1027. get right() {
  1028. return this.i0
  1029. }
  1030. constructor(i0) {
  1031. this.i0 = i0
  1032. this._tag = "Right"
  1033. this.i1 = void 0
  1034. this.i2 = void 0
  1035. this.trace = void 0
  1036. this[Either_a] = Either_effectVariance
  1037. }
  1038. toJSON() {
  1039. return { _tag: this._tag, right: this.i0 }
  1040. }
  1041. traced(trace) {
  1042. return trace ? makeTraced(this, trace) : this
  1043. }
  1044. }
  1045. class Left {
  1046. [((Either_b = Either_EffectTypeId), Equal_symbol)](that) {
  1047. return isEither(that) && isLeft(that) && equals(that.i0, this.i0)
  1048. }
  1049. [symbol]() {
  1050. return Hash_hash(this.i0)
  1051. }
  1052. get left() {
  1053. return this.i0
  1054. }
  1055. constructor(i0) {
  1056. this.i0 = i0
  1057. this._tag = "Left"
  1058. this.i1 = void 0
  1059. this.i2 = void 0
  1060. this.trace = void 0
  1061. this[Either_b] = Either_effectVariance
  1062. }
  1063. toJSON() {
  1064. return { _tag: this._tag, left: this.i0 }
  1065. }
  1066. traced(trace) {
  1067. return trace ? makeTraced(this, trace) : this
  1068. }
  1069. }
  1070. const isEither = input =>
  1071. "object" == typeof input &&
  1072. null != input &&
  1073. "_tag" in input &&
  1074. ("Left" === input._tag || "Right" === input._tag) &&
  1075. isEqual(input),
  1076. isLeft = ma => "Left" === ma._tag,
  1077. isRight = ma => "Right" === ma._tag,
  1078. not = self => a => !self(a),
  1079. make = compare => ({
  1080. compare: (self, that) => (self === that ? 0 : compare(self, that)),
  1081. }),
  1082. Order_number = make((self, that) => (self < that ? -1 : 1)),
  1083. Order_contramap = Function_dual(2, (self, f) =>
  1084. make((b1, b2) => self.compare(f(b1), f(b2)))
  1085. ),
  1086. greaterThanOrEqualTo = O =>
  1087. Function_dual(2, (self, that) => -1 !== O.compare(self, that)),
  1088. Equivalence_make =
  1089. (Order_number.compare,
  1090. isEquivalent => (self, that) =>
  1091. self === that || isEquivalent(self, that)),
  1092. isStrictEquivalent = (x, y) => x === y,
  1093. strict = () => isStrictEquivalent,
  1094. Equivalence_string = strict(),
  1095. Semigroup_make = (
  1096. combine,
  1097. combineMany = (self, collection) => {
  1098. return ((b = self),
  1099. (f = combine),
  1100. function (iterable) {
  1101. if (Array.isArray(iterable)) return iterable.reduce(f, b)
  1102. let result = b
  1103. for (const n of iterable) result = f(result, n)
  1104. return result
  1105. })(collection)
  1106. var b, f
  1107. }
  1108. ) => ({ combine, combineMany }),
  1109. Semigroup_string = Semigroup_make((self, that) => self + that),
  1110. numberSum = Semigroup_make((self, that) => self + that),
  1111. numberMultiply = Semigroup_make(
  1112. (self, that) => self * that,
  1113. (self, collection) => {
  1114. if (0 === self) return 0
  1115. let out = self
  1116. for (const n of collection) {
  1117. if (0 === n) return 0
  1118. out *= n
  1119. }
  1120. return out
  1121. }
  1122. ),
  1123. booleanEvery = Semigroup_make(
  1124. (self, that) => self && that,
  1125. (self, collection) => {
  1126. if (!1 === self) return !1
  1127. for (const b of collection) if (!1 === b) return !1
  1128. return !0
  1129. }
  1130. ),
  1131. booleanSome = Semigroup_make(
  1132. (self, that) => self || that,
  1133. (self, collection) => {
  1134. if (!0 === self) return !0
  1135. for (const b of collection) if (!0 === b) return !0
  1136. return !1
  1137. }
  1138. ),
  1139. intercalate = Function_dual(2, (S, separator) =>
  1140. Semigroup_make((self, that) => S.combineMany(self, [separator, that]))
  1141. ),
  1142. fromSemigroup = (S, empty) => ({
  1143. combine: S.combine,
  1144. combineMany: S.combineMany,
  1145. empty,
  1146. combineAll: collection => S.combineMany(empty, collection),
  1147. }),
  1148. Monoid_string = fromSemigroup(Semigroup_string, ""),
  1149. Monoid_numberSum = fromSemigroup(numberSum, 0),
  1150. Monoid_numberMultiply = fromSemigroup(numberMultiply, 1),
  1151. Monoid_booleanEvery = fromSemigroup(booleanEvery, !0),
  1152. Monoid_booleanSome = fromSemigroup(booleanSome, !1),
  1153. Order = (numberSum.combine, numberMultiply.combine, Order_number),
  1154. MonoidMultiply = Monoid_numberMultiply,
  1155. filter =
  1156. (Monoid_numberSum.combineAll,
  1157. MonoidMultiply.combineAll,
  1158. Filterable =>
  1159. Function_dual(2, (self, predicate) =>
  1160. Filterable.filterMap(self, b => (predicate(b) ? some(b) : none))
  1161. )),
  1162. Option_none = () => none,
  1163. Option_some = some,
  1164. Option_isNone = isNone,
  1165. Option_isSome = isSome,
  1166. match = Function_dual(3, (self, onNone, onSome) =>
  1167. Option_isNone(self) ? onNone() : onSome(self.value)
  1168. ),
  1169. getOrElse = Function_dual(2, (self, onNone) =>
  1170. Option_isNone(self) ? onNone() : self.value
  1171. ),
  1172. orElse = Function_dual(2, (self, that) =>
  1173. Option_isNone(self) ? that() : self
  1174. ),
  1175. fromNullable = nullableValue =>
  1176. null == nullableValue ? Option_none() : Option_some(nullableValue),
  1177. getOrUndefined = getOrElse(Function_constUndefined),
  1178. getOrThrow = Function_dual(2, (self, onNone) => {
  1179. if (Option_isSome(self)) return self.value
  1180. throw onNone()
  1181. })(() => new Error("getOrThrow called on a None")),
  1182. Option_map = Function_dual(2, (self, f) =>
  1183. Option_isNone(self) ? Option_none() : Option_some(f(self.value))
  1184. ),
  1185. flatMap = Function_dual(2, (self, f) =>
  1186. Option_isNone(self) ? Option_none() : f(self.value)
  1187. ),
  1188. flatMapNullable = Function_dual(2, (self, f) =>
  1189. Option_isNone(self) ? Option_none() : fromNullable(f(self.value))
  1190. ),
  1191. Option_filter = filter({
  1192. partitionMap: Function_dual(2, (self, f) => {
  1193. if (Option_isNone(self)) return [Option_none(), Option_none()]
  1194. const e = f(self.value)
  1195. return isLeft(e)
  1196. ? [Option_some(e.left), Option_none()]
  1197. : [Option_none(), Option_some(e.right)]
  1198. }),
  1199. filterMap: Function_dual(2, (self, f) =>
  1200. Option_isNone(self) ? Option_none() : f(self.value)
  1201. ),
  1202. }),
  1203. liftPredicate = predicate => b =>
  1204. predicate(b) ? Option_some(b) : Option_none(),
  1205. contains = isEquivalent =>
  1206. Function_dual(
  1207. 2,
  1208. (self, a) => !Option_isNone(self) && isEquivalent(self.value, a)
  1209. ),
  1210. exists = Function_dual(
  1211. 2,
  1212. (self, predicate) => !Option_isNone(self) && predicate(self.value)
  1213. ),
  1214. Either_right = a => new Right(a),
  1215. Either_left = e => new Left(e),
  1216. Either_isLeft = isLeft,
  1217. Either_isRight = isRight,
  1218. merge = Function_dual(3, (self, onLeft, onRight) =>
  1219. Either_isLeft(self) ? onLeft(self.left) : onRight(self.right)
  1220. )(Function_identity, Function_identity),
  1221. isNonEmptyArray = self => self.length > 0,
  1222. String_Equivalence = Equivalence_string,
  1223. Semigroup = Semigroup_string,
  1224. Monoid = Monoid_string,
  1225. slice =
  1226. (Semigroup.combine,
  1227. Function_dual(3, (self, start, end) => self.slice(start, end))),
  1228. isEmpty = self => 0 === self.length,
  1229. split = Function_dual(2, (self, separator) => {
  1230. const out = self.split(separator)
  1231. return isNonEmptyArray(out) ? out : [self]
  1232. }),
  1233. includes = Function_dual(2, (self, searchString) =>
  1234. self.includes(searchString)
  1235. )
  1236. class LinesIterator {
  1237. constructor(s, stripped = !1) {
  1238. this.s = s
  1239. this.stripped = stripped
  1240. this.index = 0
  1241. this.length = s.length
  1242. }
  1243. next() {
  1244. if (this.done) return { done: !0, value: void 0 }
  1245. const start = this.index
  1246. for (; !this.done && !isLineBreak(this.s[this.index]); )
  1247. this.index = this.index + 1
  1248. let end = this.index
  1249. if (!this.done) {
  1250. const char = this.s[this.index]
  1251. this.index = this.index + 1
  1252. !this.done &&
  1253. isLineBreak2(char, this.s[this.index]) &&
  1254. (this.index = this.index + 1)
  1255. this.stripped || (end = this.index)
  1256. }
  1257. return { done: !1, value: this.s.substring(start, end) }
  1258. }
  1259. [Symbol.iterator]() {
  1260. return new LinesIterator(this.s, this.stripped)
  1261. }
  1262. get done() {
  1263. return this.index >= this.length
  1264. }
  1265. }
  1266. const isLineBreak = char => {
  1267. const code = char.charCodeAt(0)
  1268. return 13 === code || 10 === code
  1269. },
  1270. isLineBreak2 = (char0, char1) =>
  1271. 13 === char0.charCodeAt(0) && 10 === char1.charCodeAt(0),
  1272. Invariant_bindTo = F =>
  1273. Function_dual(2, (self, name) =>
  1274. F.imap(
  1275. self,
  1276. a => ({ [name]: a }),
  1277. ({ [name]: a }) => a
  1278. )
  1279. ),
  1280. makeBy = (n, f) => {
  1281. const max = Math.max(1, Math.floor(n)),
  1282. out = [f(0)]
  1283. for (let i = 1; i < max; i++) out.push(f(i))
  1284. return out
  1285. },
  1286. mjs_ReadonlyArray_fromIterable = collection =>
  1287. Array.isArray(collection) ? collection : Array.from(collection),
  1288. matchRight = Function_dual(3, (self, onEmpty, onNonEmpty) =>
  1289. isNonEmptyReadonlyArray(self)
  1290. ? onNonEmpty(initNonEmpty(self), lastNonEmpty(self))
  1291. : onEmpty()
  1292. ),
  1293. prepend = Function_dual(2, (self, head) => [head, ...self]),
  1294. append = Function_dual(2, (self, last) => [...self, last]),
  1295. isEmptyReadonlyArray = self => 0 === self.length,
  1296. isNonEmptyReadonlyArray = isNonEmptyArray,
  1297. isOutOfBound = (i, as) => i < 0 || i >= as.length,
  1298. ReadonlyArray_clamp = (i, as) =>
  1299. Math.floor(Math.min(Math.max(0, i), as.length)),
  1300. ReadonlyArray_get = Function_dual(2, (self, index) => {
  1301. const i = Math.floor(index)
  1302. return isOutOfBound(i, self) ? Option_none() : Option_some(self[i])
  1303. }),
  1304. unsafeGet = Function_dual(2, (self, index) => {
  1305. const i = Math.floor(index)
  1306. if (isOutOfBound(i, self)) throw new Error(`Index ${i} out of bounds`)
  1307. return self[i]
  1308. }),
  1309. headNonEmpty = unsafeGet(0),
  1310. lastNonEmpty = self => self[self.length - 1],
  1311. tailNonEmpty = self => self.slice(1),
  1312. initNonEmpty = self => self.slice(0, -1),
  1313. take = Function_dual(2, (self, n) => {
  1314. const input = mjs_ReadonlyArray_fromIterable(self)
  1315. return input.slice(0, ReadonlyArray_clamp(n, input))
  1316. }),
  1317. drop = Function_dual(2, (self, n) => {
  1318. const input = mjs_ReadonlyArray_fromIterable(self)
  1319. return input.slice(ReadonlyArray_clamp(n, input), input.length)
  1320. }),
  1321. findFirstIndex = Function_dual(2, (self, predicate) => {
  1322. let i = 0
  1323. for (const a of self) {
  1324. if (predicate(a)) return Option_some(i)
  1325. i++
  1326. }
  1327. return Option_none()
  1328. }),
  1329. findFirst = Function_dual(2, (self, predicate) => {
  1330. const input = mjs_ReadonlyArray_fromIterable(self)
  1331. for (let i = 0; i < input.length; i++)
  1332. if (predicate(input[i])) return Option_some(input[i])
  1333. return Option_none()
  1334. }),
  1335. findLast = Function_dual(2, (self, predicate) => {
  1336. const input = mjs_ReadonlyArray_fromIterable(self)
  1337. for (let i = input.length - 1; i >= 0; i--)
  1338. if (predicate(input[i])) return Option_some(input[i])
  1339. return Option_none()
  1340. }),
  1341. ReadonlyArray_remove = Function_dual(2, (self, i) => {
  1342. const out = Array.from(self)
  1343. if (isOutOfBound(i, out)) return out
  1344. out.splice(i, 1)
  1345. return out
  1346. }),
  1347. ReadonlyArray_reverse = self => Array.from(self).reverse(),
  1348. sort = Function_dual(2, (self, O) => {
  1349. const out = Array.from(self)
  1350. out.sort(O.compare)
  1351. return out
  1352. }),
  1353. zip = Function_dual(2, (self, that) =>
  1354. ReadonlyArray_zipWith(self, that, (a, b) => [a, b])
  1355. ),
  1356. ReadonlyArray_zipWith = Function_dual(3, (self, that, f) => {
  1357. const as = mjs_ReadonlyArray_fromIterable(self),
  1358. bs = mjs_ReadonlyArray_fromIterable(that)
  1359. return isNonEmptyReadonlyArray(as) && isNonEmptyReadonlyArray(bs)
  1360. ? zipNonEmptyWith(bs, f)(as)
  1361. : []
  1362. }),
  1363. zipNonEmptyWith = Function_dual(3, (self, that, f) => {
  1364. const cs = [f(headNonEmpty(self), headNonEmpty(that))],
  1365. len = Math.min(self.length, that.length)
  1366. for (let i = 1; i < len; i++) cs[i] = f(self[i], that[i])
  1367. return cs
  1368. }),
  1369. uniq = Function_dual(2, (self, isEquivalent) => {
  1370. const input = mjs_ReadonlyArray_fromIterable(self)
  1371. return isNonEmptyReadonlyArray(input)
  1372. ? uniqNonEmpty(isEquivalent)(input)
  1373. : []
  1374. }),
  1375. uniqNonEmpty = Function_dual(2, (self, isEquivalent) => {
  1376. const out = [headNonEmpty(self)],
  1377. rest = tailNonEmpty(self)
  1378. for (const a of rest) out.every(o => !isEquivalent(a, o)) && out.push(a)
  1379. return out
  1380. }),
  1381. ReadonlyArray_of = a => [a],
  1382. ReadonlyArray_map = Function_dual(2, (self, f) => self.map(f)),
  1383. mapNonEmpty = ReadonlyArray_map,
  1384. ReadonlyArray_Invariant = { imap: imap(ReadonlyArray_map) },
  1385. ReadonlyArray_flatMap = Function_dual(2, (self, f) => {
  1386. if (isEmptyReadonlyArray(self)) return []
  1387. const out = []
  1388. for (let i = 0; i < self.length; i++) out.push(...f(self[i], i))
  1389. return out
  1390. }),
  1391. ReadonlyArray_filterMap = Function_dual(2, (self, f) => {
  1392. const as = mjs_ReadonlyArray_fromIterable(self),
  1393. out = []
  1394. for (let i = 0; i < as.length; i++) {
  1395. const o = f(as[i], i)
  1396. Option_isSome(o) && out.push(o.value)
  1397. }
  1398. return out
  1399. }),
  1400. ReadonlyArray_compact = ReadonlyArray_filterMap(Function_identity),
  1401. ReadonlyArray_filter = Function_dual(2, (self, predicate) => {
  1402. const as = mjs_ReadonlyArray_fromIterable(self),
  1403. out = []
  1404. for (let i = 0; i < as.length; i++)
  1405. predicate(as[i], i) && out.push(as[i])
  1406. return out
  1407. }),
  1408. ReadonlyArray_reduce = Function_dual(3, (self, b, f) =>
  1409. mjs_ReadonlyArray_fromIterable(self).reduce((b, a, i) => f(b, a, i), b)
  1410. ),
  1411. ReadonlyArray_some = predicate => self => self.some(predicate),
  1412. ReadonlyArray_intercalate = M =>
  1413. Function_dual(2, (self, middle) => {
  1414. const as = mjs_ReadonlyArray_fromIterable(self)
  1415. return isNonEmptyReadonlyArray(as)
  1416. ? intercalateNonEmpty(M)(as, middle)
  1417. : M.empty
  1418. }),
  1419. intercalateNonEmpty = S =>
  1420. Function_dual(2, (self, middle) =>
  1421. intercalate(S, middle).combineMany(
  1422. headNonEmpty(self),
  1423. tailNonEmpty(self)
  1424. )
  1425. ),
  1426. join = ReadonlyArray_intercalate(Monoid),
  1427. ReadonlyArray_bindTo = Invariant_bindTo(ReadonlyArray_Invariant),
  1428. TypeId = Symbol.for("@effect/data/Chunk"),
  1429. emptyArray = []
  1430. class ChunkImpl {
  1431. constructor(backing) {
  1432. this.backing = backing
  1433. this._id = TypeId
  1434. switch (backing._tag) {
  1435. case "IEmpty":
  1436. this.length = 0
  1437. this.depth = 0
  1438. this.left = this
  1439. this.right = this
  1440. break
  1441. case "IConcat":
  1442. this.length = backing.left.length + backing.right.length
  1443. this.depth = 1 + Math.max(backing.left.depth, backing.right.depth)
  1444. this.left = backing.left
  1445. this.right = backing.right
  1446. break
  1447. case "IArray":
  1448. this.length = backing.array.length
  1449. this.depth = 0
  1450. this.left = _empty
  1451. this.right = _empty
  1452. break
  1453. case "ISingleton":
  1454. this.length = 1
  1455. this.depth = 0
  1456. this.left = _empty
  1457. this.right = _empty
  1458. }
  1459. }
  1460. toString() {
  1461. return `Chunk(${toReadonlyArray(this).map(String).join(", ")})`
  1462. }
  1463. toJSON() {
  1464. return { _tag: "Chunk", values: toReadonlyArray(this) }
  1465. }
  1466. [Symbol.for("nodejs.util.inspect.custom")]() {
  1467. return this.toJSON()
  1468. }
  1469. [Equal_symbol](that) {
  1470. return (
  1471. !(!isChunk(that) || this.length !== that.length) &&
  1472. toReadonlyArray(this).every((value, i) =>
  1473. equals(value, Chunk_unsafeGet(that, i))
  1474. )
  1475. )
  1476. }
  1477. [symbol]() {
  1478. return array(toReadonlyArray(this))
  1479. }
  1480. [Symbol.iterator]() {
  1481. switch (this.backing._tag) {
  1482. case "IArray":
  1483. return this.backing.array[Symbol.iterator]()
  1484. case "IEmpty":
  1485. return emptyArray[Symbol.iterator]()
  1486. default:
  1487. return toReadonlyArray(this)[Symbol.iterator]()
  1488. }
  1489. }
  1490. }
  1491. const copyToArray = (self, array, initial) => {
  1492. switch (self.backing._tag) {
  1493. case "IArray":
  1494. !(function (src, srcPos, dest, destPos, len) {
  1495. for (let i = 0; i < Math.min(src.length, 0 + len); i++)
  1496. dest[destPos + i - 0] = src[i]
  1497. })(self.backing.array, 0, array, initial, self.length)
  1498. break
  1499. case "IConcat":
  1500. copyToArray(self.left, array, initial)
  1501. copyToArray(self.right, array, initial + self.left.length)
  1502. break
  1503. case "ISingleton":
  1504. array[initial] = self.backing.a
  1505. }
  1506. },
  1507. isChunk = u =>
  1508. "object" == typeof u && null != u && "_id" in u && u._id === TypeId,
  1509. _empty = new ChunkImpl({ _tag: "IEmpty" }),
  1510. Chunk_empty = () => _empty,
  1511. Chunk_fromIterable = self =>
  1512. isChunk(self)
  1513. ? self
  1514. : new ChunkImpl({ _tag: "IArray", array: Array.from(self) }),
  1515. toReadonlyArray = self => {
  1516. switch (self.backing._tag) {
  1517. case "IEmpty":
  1518. return emptyArray
  1519. case "IArray":
  1520. return self.backing.array
  1521. default: {
  1522. const arr = new Array(self.length)
  1523. copyToArray(self, arr, 0)
  1524. self.backing = { _tag: "IArray", array: arr }
  1525. self.left = _empty
  1526. self.right = _empty
  1527. self.depth = 0
  1528. return arr
  1529. }
  1530. }
  1531. },
  1532. Chunk_get = Function_dual(2, (self, index) =>
  1533. index < 0 || index >= self.length
  1534. ? Option_none()
  1535. : Option_some(Chunk_unsafeGet(self, index))
  1536. ),
  1537. unsafeFromArray = self => new ChunkImpl({ _tag: "IArray", array: self }),
  1538. Chunk_unsafeGet = Function_dual(2, (self, index) => {
  1539. switch (self.backing._tag) {
  1540. case "IEmpty":
  1541. throw new Error("Index out of bounds")
  1542. case "ISingleton":
  1543. if (0 !== index) throw new Error("Index out of bounds")
  1544. return self.backing.a
  1545. case "IArray":
  1546. if (index >= self.length || index < 0)
  1547. throw new Error("Index out of bounds")
  1548. return self.backing.array[index]
  1549. case "IConcat":
  1550. return index < self.left.length
  1551. ? Chunk_unsafeGet(self.left, index)
  1552. : Chunk_unsafeGet(self.right, index - self.left.length)
  1553. }
  1554. }),
  1555. Chunk_append = Function_dual(2, (self, a) =>
  1556. Chunk_concat(self, Chunk_of(a))
  1557. ),
  1558. Chunk_prepend = Function_dual(2, (self, a) =>
  1559. Chunk_concat(Chunk_of(a), self)
  1560. ),
  1561. Chunk_take = Function_dual(2, (self, n) =>
  1562. n <= 0
  1563. ? _empty
  1564. : n >= self.length
  1565. ? self
  1566. : unsafeFromArray(take(n)(toReadonlyArray(self)))
  1567. ),
  1568. Chunk_drop = Function_dual(2, (self, n) =>
  1569. n <= 0
  1570. ? self
  1571. : n >= self.length
  1572. ? _empty
  1573. : unsafeFromArray(drop(n)(toReadonlyArray(self)))
  1574. ),
  1575. Chunk_concat = Function_dual(2, (self, that) => {
  1576. if ("IEmpty" === self.backing._tag) return that
  1577. if ("IEmpty" === that.backing._tag) return self
  1578. const diff = that.depth - self.depth
  1579. if (Math.abs(diff) <= 1)
  1580. return new ChunkImpl({ _tag: "IConcat", left: self, right: that })
  1581. if (diff < -1) {
  1582. if (self.left.depth >= self.right.depth) {
  1583. const nr = Chunk_concat(that)(self.right)
  1584. return new ChunkImpl({
  1585. _tag: "IConcat",
  1586. left: self.left,
  1587. right: nr,
  1588. })
  1589. }
  1590. {
  1591. const nrr = Chunk_concat(that)(self.right.right)
  1592. if (nrr.depth === self.depth - 3) {
  1593. const nr = new ChunkImpl({
  1594. _tag: "IConcat",
  1595. left: self.right.left,
  1596. right: nrr,
  1597. })
  1598. return new ChunkImpl({
  1599. _tag: "IConcat",
  1600. left: self.left,
  1601. right: nr,
  1602. })
  1603. }
  1604. {
  1605. const nl = new ChunkImpl({
  1606. _tag: "IConcat",
  1607. left: self.left,
  1608. right: self.right.left,
  1609. })
  1610. return new ChunkImpl({ _tag: "IConcat", left: nl, right: nrr })
  1611. }
  1612. }
  1613. }
  1614. if (that.right.depth >= that.left.depth) {
  1615. const nl = Chunk_concat(that.left)(self)
  1616. return new ChunkImpl({ _tag: "IConcat", left: nl, right: that.right })
  1617. }
  1618. {
  1619. const nll = Chunk_concat(that.left.left)(self)
  1620. if (nll.depth === that.depth - 3) {
  1621. const nl = new ChunkImpl({
  1622. _tag: "IConcat",
  1623. left: nll,
  1624. right: that.left.right,
  1625. })
  1626. return new ChunkImpl({
  1627. _tag: "IConcat",
  1628. left: nl,
  1629. right: that.right,
  1630. })
  1631. }
  1632. {
  1633. const nr = new ChunkImpl({
  1634. _tag: "IConcat",
  1635. left: that.left.right,
  1636. right: that.right,
  1637. })
  1638. return new ChunkImpl({ _tag: "IConcat", left: nll, right: nr })
  1639. }
  1640. }
  1641. }),
  1642. dedupeAdjacent = self => {
  1643. const builder = []
  1644. let lastA = Option_none()
  1645. for (const a of self)
  1646. if (Option_isNone(lastA) || !equals(a, lastA.value)) {
  1647. builder.push(a)
  1648. lastA = Option_some(a)
  1649. }
  1650. return unsafeFromArray(builder)
  1651. },
  1652. Chunk_head = Chunk_get(0),
  1653. Chunk_isEmpty = self => 0 === self.length,
  1654. Chunk_isNonEmpty = self => self.length > 0,
  1655. Chunk_reduce = Function_dual(3, (self, b, f) =>
  1656. ReadonlyArray_reduce(b, f)(toReadonlyArray(self))
  1657. ),
  1658. Chunk_join = Function_dual(2, (self, sep) =>
  1659. Chunk_reduce(self, "", (s, a) => (s.length > 0 ? `${s}${sep}${a}` : a))
  1660. ),
  1661. Chunk_of = a => new ChunkImpl({ _tag: "ISingleton", a }),
  1662. Chunk_makeBy = Function_dual(2, (n, f) =>
  1663. ((...as) => unsafeFromArray(as))(...makeBy(n, f))
  1664. ),
  1665. Chunk_map = Function_dual(2, (self, f) =>
  1666. "ISingleton" === self.backing._tag
  1667. ? Chunk_of(f(self.backing.a))
  1668. : unsafeFromArray(ReadonlyArray_map(f)(toReadonlyArray(self)))
  1669. ),
  1670. mapWithIndex = Function_dual(2, (self, f) =>
  1671. "ISingleton" === self.backing._tag
  1672. ? Chunk_of(f(self.backing.a, 0))
  1673. : unsafeFromArray(ReadonlyArray_map(f)(toReadonlyArray(self)))
  1674. ),
  1675. Chunk_reverse = self =>
  1676. unsafeFromArray(ReadonlyArray_reverse(toReadonlyArray(self))),
  1677. Chunk_sort = Function_dual(2, (self, O) =>
  1678. unsafeFromArray(sort(O)(toReadonlyArray(self)))
  1679. ),
  1680. Chunk_splitAt = Function_dual(2, (self, n) => [
  1681. Chunk_take(n)(self),
  1682. Chunk_drop(n)(self),
  1683. ]),
  1684. splitWhere = Function_dual(2, (self, f) => {
  1685. let i = 0
  1686. for (const a of toReadonlyArray(self)) {
  1687. if (f(a)) break
  1688. i++
  1689. }
  1690. return Chunk_splitAt(i)(self)
  1691. }),
  1692. Chunk_unfold = (s, f) => {
  1693. const builder = []
  1694. let cont = !0,
  1695. s1 = s
  1696. for (; cont; ) {
  1697. const x = f(s1)
  1698. if (Option_isSome(x)) {
  1699. s1 = x.value[1]
  1700. builder.push(x.value[0])
  1701. } else cont = !1
  1702. }
  1703. return unsafeFromArray(builder)
  1704. },
  1705. unsafeHead = self => Chunk_unsafeGet(0)(self),
  1706. unsafeLast = self => Chunk_unsafeGet(self.length - 1)(self),
  1707. Chunk_zip = Function_dual(2, (self, that) =>
  1708. Chunk_zipWith(self, that, (a, b) => [a, b])
  1709. ),
  1710. Chunk_zipWith = Function_dual(3, (self, that, f) => {
  1711. const selfA = toReadonlyArray(self),
  1712. thatA = toReadonlyArray(that)
  1713. return unsafeFromArray(ReadonlyArray_zipWith(thatA, f)(selfA))
  1714. }),
  1715. Chunk_headNonEmpty = unsafeHead,
  1716. Chunk_tailNonEmpty = self => Chunk_drop(self, 1)
  1717. var Context_a
  1718. const TagTypeId = Symbol.for("@effect/data/Context/Tag"),
  1719. Context_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  1720. Context_EffectTypeId = Symbol.for("@effect/io/Effect")
  1721. class TagImpl {
  1722. [((Context_a = Context_EffectTypeId), Equal_symbol)](that) {
  1723. return this === that
  1724. }
  1725. [symbol]() {
  1726. return random(this)
  1727. }
  1728. get [TagTypeId]() {
  1729. return { _S: _ => _, _I: _ => _ }
  1730. }
  1731. constructor(id) {
  1732. this._tag = "Tag"
  1733. this.i0 = void 0
  1734. this.i1 = void 0
  1735. this.i2 = void 0
  1736. this.trace = void 0
  1737. this[Context_a] = Context_effectVariance
  1738. if (void 0 !== id) return globalValue(id, () => this)
  1739. }
  1740. traced(trace) {
  1741. return trace ? makeTraced(this, trace) : this
  1742. }
  1743. }
  1744. const ContextTypeId = Symbol.for("@effect/data/Context")
  1745. class ContextImpl {
  1746. [Equal_symbol](that) {
  1747. if (isContext(that) && this.unsafeMap.size === that.unsafeMap.size) {
  1748. for (const k of this.unsafeMap.keys())
  1749. if (
  1750. !that.unsafeMap.has(k) ||
  1751. !equals(this.unsafeMap.get(k), that.unsafeMap.get(k))
  1752. )
  1753. return !1
  1754. return !0
  1755. }
  1756. return !1
  1757. }
  1758. [symbol]() {
  1759. return number(this.unsafeMap.size)
  1760. }
  1761. constructor(unsafeMap) {
  1762. this.unsafeMap = unsafeMap
  1763. this._id = ContextTypeId
  1764. this._S = _ => _
  1765. }
  1766. }
  1767. const isContext = u =>
  1768. "object" == typeof u &&
  1769. null !== u &&
  1770. "_id" in u &&
  1771. u._id === ContextTypeId,
  1772. add = Function_dual(3, (self, tag, service) => {
  1773. const map = new Map(self.unsafeMap)
  1774. map.set(tag, service)
  1775. return new ContextImpl(map)
  1776. }),
  1777. Context_get = Function_dual(2, (self, tag) => {
  1778. if (!self.unsafeMap.has(tag)) throw new Error("Service not found")
  1779. return self.unsafeMap.get(tag)
  1780. }),
  1781. Context_unsafeGet = Function_dual(2, (self, tag) => {
  1782. if (!self.unsafeMap.has(tag)) throw new Error("Service not found")
  1783. return self.unsafeMap.get(tag)
  1784. }),
  1785. Context_merge = Function_dual(2, (self, that) => {
  1786. const map = new Map(self.unsafeMap)
  1787. for (const [tag, s] of that.unsafeMap) map.set(tag, s)
  1788. return new ContextImpl(map)
  1789. }),
  1790. Tag = key => new TagImpl(key),
  1791. mjs_Context_empty = () => new ContextImpl(new Map()),
  1792. Context_add = add,
  1793. mjs_Context_get = Context_get,
  1794. mjs_Context_unsafeGet = Context_unsafeGet,
  1795. mjs_Context_merge = Context_merge,
  1796. ContextPatchTypeId = Symbol.for("@effect/data/Differ/ContextPatch")
  1797. function ContextPatch_variance(a) {
  1798. return a
  1799. }
  1800. class ContextPatch_Empty {
  1801. constructor() {
  1802. this._tag = "Empty"
  1803. this._Input = ContextPatch_variance
  1804. this._Output = ContextPatch_variance
  1805. this._id = ContextPatchTypeId
  1806. }
  1807. [symbol]() {
  1808. return string("ContextPatch(Empty)")
  1809. }
  1810. [Equal_symbol](that) {
  1811. return (
  1812. "object" == typeof that &&
  1813. null !== that &&
  1814. "_id" in that &&
  1815. that._id === this._id &&
  1816. "_tag" in that &&
  1817. that._tag === this._id
  1818. )
  1819. }
  1820. }
  1821. class ContextPatch_AndThen {
  1822. constructor(first, second) {
  1823. this.first = first
  1824. this.second = second
  1825. this._tag = "AndThen"
  1826. this._id = ContextPatchTypeId
  1827. this._Input = ContextPatch_variance
  1828. this._Output = ContextPatch_variance
  1829. }
  1830. [symbol]() {
  1831. return string("ContextPatch(AndThen)")
  1832. }
  1833. [Equal_symbol](that) {
  1834. return (
  1835. "object" == typeof that &&
  1836. null !== that &&
  1837. "_id" in that &&
  1838. that._id === this._id &&
  1839. "_tag" in that &&
  1840. that._tag === this._id &&
  1841. equals(this.first, that.first) &&
  1842. equals(this.second, that.second)
  1843. )
  1844. }
  1845. }
  1846. class AddService {
  1847. constructor(tag, service) {
  1848. this.tag = tag
  1849. this.service = service
  1850. this._tag = "AddService"
  1851. this._id = ContextPatchTypeId
  1852. this._Input = ContextPatch_variance
  1853. this._Output = ContextPatch_variance
  1854. }
  1855. [symbol]() {
  1856. return string("ContextPatch(AddService)")
  1857. }
  1858. [Equal_symbol](that) {
  1859. return (
  1860. "object" == typeof that &&
  1861. null !== that &&
  1862. "_id" in that &&
  1863. that._id === this._id &&
  1864. "_tag" in that &&
  1865. that._tag === this._id &&
  1866. equals(this.tag, that.tag) &&
  1867. equals(this.service, that.service)
  1868. )
  1869. }
  1870. }
  1871. class RemoveService {
  1872. constructor(tag) {
  1873. this.tag = tag
  1874. this._tag = "RemoveService"
  1875. this._id = ContextPatchTypeId
  1876. this._Input = ContextPatch_variance
  1877. this._Output = ContextPatch_variance
  1878. }
  1879. [symbol]() {
  1880. return string("ContextPatch(RemoveService)")
  1881. }
  1882. [Equal_symbol](that) {
  1883. return (
  1884. "object" == typeof that &&
  1885. null !== that &&
  1886. "_id" in that &&
  1887. that._id === this._id &&
  1888. "_tag" in that &&
  1889. that._tag === this._id &&
  1890. equals(this.tag, that.tag)
  1891. )
  1892. }
  1893. }
  1894. class UpdateService {
  1895. constructor(tag, update) {
  1896. this.tag = tag
  1897. this.update = update
  1898. this._tag = "UpdateService"
  1899. this._id = ContextPatchTypeId
  1900. this._Input = ContextPatch_variance
  1901. this._Output = ContextPatch_variance
  1902. }
  1903. [symbol]() {
  1904. return string("ContextPatch(AndThen)")
  1905. }
  1906. [Equal_symbol](that) {
  1907. return (
  1908. "object" == typeof that &&
  1909. null !== that &&
  1910. "_id" in that &&
  1911. that._id === this._id &&
  1912. "_tag" in that &&
  1913. that._tag === this._id &&
  1914. equals(this.tag, that.tag) &&
  1915. equals(this.update, that.update)
  1916. )
  1917. }
  1918. }
  1919. const ContextPatch_empty = () => new ContextPatch_Empty(),
  1920. ContextPatch_combine = Function_dual(
  1921. 2,
  1922. (self, that) => new ContextPatch_AndThen(self, that)
  1923. ),
  1924. ContextPatch_patch = Function_dual(2, (self, context) => {
  1925. let wasServiceUpdated = !1,
  1926. patches = Chunk_of(self)
  1927. const updatedContext = new Map(context.unsafeMap)
  1928. for (; Chunk_isNonEmpty(patches); ) {
  1929. const head = Chunk_headNonEmpty(patches),
  1930. tail = Chunk_tailNonEmpty(patches)
  1931. switch (head._tag) {
  1932. case "Empty":
  1933. patches = tail
  1934. break
  1935. case "AddService":
  1936. updatedContext.set(head.tag, head.service)
  1937. patches = tail
  1938. break
  1939. case "AndThen":
  1940. patches = Chunk_prepend(
  1941. Chunk_prepend(tail, head.second),
  1942. head.first
  1943. )
  1944. break
  1945. case "RemoveService":
  1946. updatedContext.delete(head.tag)
  1947. patches = tail
  1948. break
  1949. case "UpdateService":
  1950. updatedContext.set(
  1951. head.tag,
  1952. head.update(updatedContext.get(head.tag))
  1953. )
  1954. wasServiceUpdated = !0
  1955. patches = tail
  1956. }
  1957. }
  1958. if (!wasServiceUpdated) return new ContextImpl(updatedContext)
  1959. const map = new Map()
  1960. for (const [tag] of context.unsafeMap)
  1961. if (updatedContext.has(tag)) {
  1962. map.set(tag, updatedContext.get(tag))
  1963. updatedContext.delete(tag)
  1964. }
  1965. for (const [tag, s] of updatedContext) map.set(tag, s)
  1966. return new ContextImpl(map)
  1967. }),
  1968. Differ_ContextPatch_empty = ContextPatch_empty,
  1969. Differ_ContextPatch_combine = ContextPatch_combine,
  1970. Differ_ContextPatch_patch = ContextPatch_patch,
  1971. BUCKET_SIZE = Math.pow(2, 5),
  1972. MASK = BUCKET_SIZE - 1,
  1973. MAX_INDEX_NODE = BUCKET_SIZE / 2,
  1974. MIN_ARRAY_NODE = BUCKET_SIZE / 4
  1975. function hashFragment(shift, h) {
  1976. return (h >>> shift) & MASK
  1977. }
  1978. function toBitmap(x) {
  1979. return 1 << x
  1980. }
  1981. function fromBitmap(bitmap, bit) {
  1982. return (function (x) {
  1983. x =
  1984. ((x =
  1985. (858993459 & (x -= (x >> 1) & 1431655765)) +
  1986. ((x >> 2) & 858993459)) +
  1987. (x >> 4)) &
  1988. 252645135
  1989. return 127 & ((x += x >> 8) + (x >> 16))
  1990. })(bitmap & (bit - 1))
  1991. }
  1992. function arrayUpdate(mutate, at, v, arr) {
  1993. let out = arr
  1994. if (!mutate) {
  1995. const len = arr.length
  1996. out = new Array(len)
  1997. for (let i = 0; i < len; ++i) out[i] = arr[i]
  1998. }
  1999. out[at] = v
  2000. return out
  2001. }
  2002. function arraySpliceOut(mutate, at, arr) {
  2003. const newLen = arr.length - 1
  2004. let i = 0,
  2005. g = 0,
  2006. out = arr
  2007. if (mutate) i = g = at
  2008. else {
  2009. out = new Array(newLen)
  2010. for (; i < at; ) out[g++] = arr[i++]
  2011. }
  2012. ++i
  2013. for (; i <= newLen; ) out[g++] = arr[i++]
  2014. mutate && (out.length = newLen)
  2015. return out
  2016. }
  2017. class Stack {
  2018. constructor(value, previous) {
  2019. this.value = value
  2020. this.previous = previous
  2021. }
  2022. }
  2023. class EmptyNode {
  2024. constructor() {
  2025. this._tag = "EmptyNode"
  2026. }
  2027. modify(edit, _shift, f, hash, key, size) {
  2028. const v = f(Option_none())
  2029. if (Option_isNone(v)) return new EmptyNode()
  2030. ++size.value
  2031. return new LeafNode(edit, hash, key, v)
  2032. }
  2033. }
  2034. function isEmptyNode(a) {
  2035. return a instanceof EmptyNode
  2036. }
  2037. function canEditNode(node, edit) {
  2038. return !isEmptyNode(node) && edit === node.edit
  2039. }
  2040. class LeafNode {
  2041. constructor(edit, hash, key, value) {
  2042. this.edit = edit
  2043. this.hash = hash
  2044. this.key = key
  2045. this.value = value
  2046. this._tag = "LeafNode"
  2047. }
  2048. modify(edit, shift, f, hash, key, size) {
  2049. if (equals(key, this.key)) {
  2050. const v = f(this.value)
  2051. if (v === this.value) return this
  2052. if (Option_isNone(v)) {
  2053. --size.value
  2054. return new EmptyNode()
  2055. }
  2056. if (canEditNode(this, edit)) {
  2057. this.value = v
  2058. return this
  2059. }
  2060. return new LeafNode(edit, hash, key, v)
  2061. }
  2062. const v = f(Option_none())
  2063. if (Option_isNone(v)) return this
  2064. ++size.value
  2065. return mergeLeaves(
  2066. edit,
  2067. shift,
  2068. this.hash,
  2069. this,
  2070. hash,
  2071. new LeafNode(edit, hash, key, v)
  2072. )
  2073. }
  2074. }
  2075. class CollisionNode {
  2076. constructor(edit, hash, children) {
  2077. this.edit = edit
  2078. this.hash = hash
  2079. this.children = children
  2080. this._tag = "CollisionNode"
  2081. }
  2082. modify(edit, shift, f, hash, key, size) {
  2083. if (hash === this.hash) {
  2084. const canEdit = canEditNode(this, edit),
  2085. list = this.updateCollisionList(
  2086. canEdit,
  2087. edit,
  2088. this.hash,
  2089. this.children,
  2090. f,
  2091. key,
  2092. size
  2093. )
  2094. return list === this.children
  2095. ? this
  2096. : list.length > 1
  2097. ? new CollisionNode(edit, this.hash, list)
  2098. : list[0]
  2099. }
  2100. const v = f(Option_none())
  2101. if (Option_isNone(v)) return this
  2102. ++size.value
  2103. return mergeLeaves(
  2104. edit,
  2105. shift,
  2106. this.hash,
  2107. this,
  2108. hash,
  2109. new LeafNode(edit, hash, key, v)
  2110. )
  2111. }
  2112. updateCollisionList(mutate, edit, hash, list, f, key, size) {
  2113. const len = list.length
  2114. for (let i = 0; i < len; ++i) {
  2115. const child = list[i]
  2116. if ("key" in child && equals(key, child.key)) {
  2117. const value = child.value,
  2118. newValue = f(value)
  2119. if (newValue === value) return list
  2120. if (Option_isNone(newValue)) {
  2121. --size.value
  2122. return arraySpliceOut(mutate, i, list)
  2123. }
  2124. return arrayUpdate(
  2125. mutate,
  2126. i,
  2127. new LeafNode(edit, hash, key, newValue),
  2128. list
  2129. )
  2130. }
  2131. }
  2132. const newValue = f(Option_none())
  2133. if (Option_isNone(newValue)) return list
  2134. ++size.value
  2135. return arrayUpdate(
  2136. mutate,
  2137. len,
  2138. new LeafNode(edit, hash, key, newValue),
  2139. list
  2140. )
  2141. }
  2142. }
  2143. class IndexedNode {
  2144. constructor(edit, mask, children) {
  2145. this.edit = edit
  2146. this.mask = mask
  2147. this.children = children
  2148. this._tag = "IndexedNode"
  2149. }
  2150. modify(edit, shift, f, hash, key, size) {
  2151. const mask = this.mask,
  2152. children = this.children,
  2153. frag = hashFragment(shift, hash),
  2154. bit = toBitmap(frag),
  2155. indx = fromBitmap(mask, bit),
  2156. exists = mask & bit,
  2157. canEdit = canEditNode(this, edit)
  2158. if (!exists) {
  2159. const _newChild = new EmptyNode().modify(
  2160. edit,
  2161. shift + 5,
  2162. f,
  2163. hash,
  2164. key,
  2165. size
  2166. )
  2167. return _newChild
  2168. ? children.length >= MAX_INDEX_NODE
  2169. ? (function (edit, frag, child, bitmap, subNodes) {
  2170. const arr = []
  2171. let bit = bitmap,
  2172. count = 0
  2173. for (let i = 0; bit; ++i) {
  2174. 1 & bit && (arr[i] = subNodes[count++])
  2175. bit >>>= 1
  2176. }
  2177. arr[frag] = child
  2178. return new ArrayNode(edit, count + 1, arr)
  2179. })(edit, frag, _newChild, mask, children)
  2180. : new IndexedNode(
  2181. edit,
  2182. mask | bit,
  2183. (function (mutate, at, v, arr) {
  2184. const len = arr.length
  2185. if (mutate) {
  2186. let i = len
  2187. for (; i >= at; ) arr[i--] = arr[i]
  2188. arr[at] = v
  2189. return arr
  2190. }
  2191. let i = 0,
  2192. g = 0
  2193. const out = new Array(len + 1)
  2194. for (; i < at; ) out[g++] = arr[i++]
  2195. out[at] = v
  2196. for (; i < len; ) out[++g] = arr[i++]
  2197. return out
  2198. })(canEdit, indx, _newChild, children)
  2199. )
  2200. : this
  2201. }
  2202. const current = children[indx],
  2203. child = current.modify(edit, shift + 5, f, hash, key, size)
  2204. if (current === child) return this
  2205. let newChildren,
  2206. bitmap = mask
  2207. if (isEmptyNode(child)) {
  2208. bitmap &= ~bit
  2209. if (!bitmap) return new EmptyNode()
  2210. if (
  2211. children.length <= 2 &&
  2212. (isEmptyNode((node = children[1 ^ indx])) ||
  2213. "LeafNode" === node._tag ||
  2214. "CollisionNode" === node._tag)
  2215. )
  2216. return children[1 ^ indx]
  2217. newChildren = arraySpliceOut(canEdit, indx, children)
  2218. } else newChildren = arrayUpdate(canEdit, indx, child, children)
  2219. var node
  2220. if (canEdit) {
  2221. this.mask = bitmap
  2222. this.children = newChildren
  2223. return this
  2224. }
  2225. return new IndexedNode(edit, bitmap, newChildren)
  2226. }
  2227. }
  2228. class ArrayNode {
  2229. constructor(edit, size, children) {
  2230. this.edit = edit
  2231. this.size = size
  2232. this.children = children
  2233. this._tag = "ArrayNode"
  2234. }
  2235. modify(edit, shift, f, hash, key, size) {
  2236. let count = this.size
  2237. const children = this.children,
  2238. frag = hashFragment(shift, hash),
  2239. child = children[frag],
  2240. newChild = (child || new EmptyNode()).modify(
  2241. edit,
  2242. shift + 5,
  2243. f,
  2244. hash,
  2245. key,
  2246. size
  2247. )
  2248. if (child === newChild) return this
  2249. const canEdit = canEditNode(this, edit)
  2250. let newChildren
  2251. if (isEmptyNode(child) && !isEmptyNode(newChild)) {
  2252. ++count
  2253. newChildren = arrayUpdate(canEdit, frag, newChild, children)
  2254. } else if (!isEmptyNode(child) && isEmptyNode(newChild)) {
  2255. --count
  2256. if (count <= MIN_ARRAY_NODE)
  2257. return (function (edit, count, removed, elements) {
  2258. const children = new Array(count - 1)
  2259. let g = 0,
  2260. bitmap = 0
  2261. for (let i = 0, len = elements.length; i < len; ++i)
  2262. if (i !== removed) {
  2263. const elem = elements[i]
  2264. if (elem && !isEmptyNode(elem)) {
  2265. children[g++] = elem
  2266. bitmap |= 1 << i
  2267. }
  2268. }
  2269. return new IndexedNode(edit, bitmap, children)
  2270. })(edit, count, frag, children)
  2271. newChildren = arrayUpdate(canEdit, frag, new EmptyNode(), children)
  2272. } else newChildren = arrayUpdate(canEdit, frag, newChild, children)
  2273. if (canEdit) {
  2274. this.size = count
  2275. this.children = newChildren
  2276. return this
  2277. }
  2278. return new ArrayNode(edit, count, newChildren)
  2279. }
  2280. }
  2281. function mergeLeavesInner(edit, shift, h1, n1, h2, n2) {
  2282. if (h1 === h2) return new CollisionNode(edit, h1, [n2, n1])
  2283. const subH1 = hashFragment(shift, h1),
  2284. subH2 = hashFragment(shift, h2)
  2285. if (subH1 === subH2)
  2286. return child =>
  2287. new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), [child])
  2288. {
  2289. const children = subH1 < subH2 ? [n1, n2] : [n2, n1]
  2290. return new IndexedNode(
  2291. edit,
  2292. toBitmap(subH1) | toBitmap(subH2),
  2293. children
  2294. )
  2295. }
  2296. }
  2297. function mergeLeaves(edit, shift, h1, n1, h2, n2) {
  2298. let stack,
  2299. currentShift = shift
  2300. for (;;) {
  2301. const res = mergeLeavesInner(edit, currentShift, h1, n1, h2, n2)
  2302. if ("function" != typeof res) {
  2303. let final = res
  2304. for (; null != stack; ) {
  2305. final = stack.value(final)
  2306. stack = stack.previous
  2307. }
  2308. return final
  2309. }
  2310. stack = new Stack(res, stack)
  2311. currentShift += 5
  2312. }
  2313. }
  2314. const HashMapTypeId = Symbol.for("@effect/data/HashMap")
  2315. class HashMapImpl {
  2316. constructor(_editable, _edit, _root, _size) {
  2317. this._editable = _editable
  2318. this._edit = _edit
  2319. this._root = _root
  2320. this._size = _size
  2321. this._id = HashMapTypeId
  2322. }
  2323. [Symbol.iterator]() {
  2324. return new HashMapIterator(this, (k, v) => [k, v])
  2325. }
  2326. [symbol]() {
  2327. let hash = Hash_hash("HashMap")
  2328. for (const item of this)
  2329. hash ^= combine(Hash_hash(item[0]))(Hash_hash(item[1]))
  2330. return hash
  2331. }
  2332. [Equal_symbol](that) {
  2333. if (isHashMap(that)) {
  2334. if (that._size !== this._size) return !1
  2335. for (const item of this) {
  2336. const elem = getHash(item[0], Hash_hash(item[0]))(that)
  2337. if (Option_isNone(elem)) return !1
  2338. if (!equals(item[1], elem.value)) return !1
  2339. }
  2340. return !0
  2341. }
  2342. return !1
  2343. }
  2344. toString() {
  2345. return `HashMap(${Array.from(this)
  2346. .map(([k, v]) => `[${String(k)}, ${String(v)}]`)
  2347. .join(", ")})`
  2348. }
  2349. toJSON() {
  2350. return { _tag: "HashMap", values: Array.from(this) }
  2351. }
  2352. [Symbol.for("nodejs.util.inspect.custom")]() {
  2353. return this.toJSON()
  2354. }
  2355. }
  2356. class HashMapIterator {
  2357. constructor(map, f) {
  2358. this.map = map
  2359. this.f = f
  2360. this.v = visitLazy(this.map._root, this.f, void 0)
  2361. }
  2362. next() {
  2363. if (Option_isNone(this.v)) return { done: !0, value: void 0 }
  2364. const v0 = this.v.value
  2365. this.v = applyCont(v0.cont)
  2366. return { done: !1, value: v0.value }
  2367. }
  2368. [Symbol.iterator]() {
  2369. return new HashMapIterator(this.map, this.f)
  2370. }
  2371. }
  2372. const applyCont = cont =>
  2373. cont
  2374. ? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4])
  2375. : Option_none(),
  2376. visitLazy = (node, f, cont) => {
  2377. switch (node._tag) {
  2378. case "LeafNode":
  2379. return Option_isSome(node.value)
  2380. ? Option_some({ value: f(node.key, node.value.value), cont })
  2381. : applyCont(cont)
  2382. case "CollisionNode":
  2383. case "ArrayNode":
  2384. case "IndexedNode": {
  2385. const children = node.children
  2386. return visitLazyChildren(children.length, children, 0, f, cont)
  2387. }
  2388. default:
  2389. return applyCont(cont)
  2390. }
  2391. },
  2392. visitLazyChildren = (len, children, i, f, cont) => {
  2393. for (; i < len; ) {
  2394. const child = children[i++]
  2395. if (child && !isEmptyNode(child))
  2396. return visitLazy(child, f, [len, children, i, f, cont])
  2397. }
  2398. return applyCont(cont)
  2399. },
  2400. HashMap_empty = () => new HashMapImpl(!1, 0, new EmptyNode(), 0),
  2401. isHashMap = u =>
  2402. "object" == typeof u &&
  2403. null != u &&
  2404. "_id" in u &&
  2405. u._id === HashMapTypeId,
  2406. HashMap_get = Function_dual(2, (self, key) =>
  2407. getHash(self, key, Hash_hash(key))
  2408. ),
  2409. getHash = Function_dual(3, (self, key, hash) => {
  2410. let node = self._root,
  2411. shift = 0
  2412. for (;;)
  2413. switch (node._tag) {
  2414. case "LeafNode":
  2415. return equals(key, node.key) ? node.value : Option_none()
  2416. case "CollisionNode":
  2417. if (hash === node.hash) {
  2418. const children = node.children
  2419. for (let i = 0, len = children.length; i < len; ++i) {
  2420. const child = children[i]
  2421. if ("key" in child && equals(key, child.key))
  2422. return child.value
  2423. }
  2424. }
  2425. return Option_none()
  2426. case "IndexedNode": {
  2427. const bit = toBitmap(hashFragment(shift, hash))
  2428. if (node.mask & bit) {
  2429. node = node.children[fromBitmap(node.mask, bit)]
  2430. shift += 5
  2431. break
  2432. }
  2433. return Option_none()
  2434. }
  2435. case "ArrayNode":
  2436. node = node.children[hashFragment(shift, hash)]
  2437. if (node) {
  2438. shift += 5
  2439. break
  2440. }
  2441. return Option_none()
  2442. default:
  2443. return Option_none()
  2444. }
  2445. }),
  2446. HashMap_has = Function_dual(2, (self, key) =>
  2447. Option_isSome(getHash(self, key, Hash_hash(key)))
  2448. ),
  2449. set = Function_dual(3, (self, key, value) =>
  2450. modifyAt(self, key, () => Option_some(value))
  2451. ),
  2452. setTree = Function_dual(3, (self, newRoot, newSize) => {
  2453. if (self._editable) {
  2454. self._root = newRoot
  2455. self._size = newSize
  2456. return self
  2457. }
  2458. return newRoot === self._root
  2459. ? self
  2460. : new HashMapImpl(self._editable, self._edit, newRoot, newSize)
  2461. }),
  2462. HashMap_size = self => self._size,
  2463. beginMutation = self =>
  2464. new HashMapImpl(!0, self._edit + 1, self._root, self._size),
  2465. endMutation = self => {
  2466. self._editable = !1
  2467. return self
  2468. },
  2469. modifyAt = Function_dual(3, (self, key, f) =>
  2470. modifyHash(self, key, Hash_hash(key), f)
  2471. ),
  2472. modifyHash = Function_dual(4, (self, key, hash, f) => {
  2473. const size = { value: self._size },
  2474. newRoot = self._root.modify(
  2475. self._editable ? self._edit : NaN,
  2476. 0,
  2477. f,
  2478. hash,
  2479. key,
  2480. size
  2481. )
  2482. return setTree(newRoot, size.value)(self)
  2483. }),
  2484. HashMap_remove = Function_dual(2, (self, key) =>
  2485. modifyAt(self, key, Option_none)
  2486. ),
  2487. forEachWithIndex = Function_dual(2, (self, f) =>
  2488. HashMap_reduceWithIndex(self, void 0, (_, value, key) => f(value, key))
  2489. ),
  2490. HashMap_reduceWithIndex = Function_dual(3, (self, zero, f) => {
  2491. const root = self._root
  2492. if ("LeafNode" === root._tag)
  2493. return Option_isSome(root.value)
  2494. ? f(zero, root.value.value, root.key)
  2495. : zero
  2496. if ("EmptyNode" === root._tag) return zero
  2497. const toVisit = [root.children]
  2498. let children
  2499. for (; (children = toVisit.pop()); )
  2500. for (let i = 0, len = children.length; i < len; ) {
  2501. const child = children[i++]
  2502. child &&
  2503. !isEmptyNode(child) &&
  2504. ("LeafNode" === child._tag
  2505. ? Option_isSome(child.value) &&
  2506. (zero = f(zero, child.value.value, child.key))
  2507. : toVisit.push(child.children))
  2508. }
  2509. return zero
  2510. }),
  2511. HashSetTypeId = Symbol.for("@effect/data/HashSet")
  2512. class HashSetImpl {
  2513. constructor(_keyMap) {
  2514. this._keyMap = _keyMap
  2515. this._id = HashSetTypeId
  2516. }
  2517. [Symbol.iterator]() {
  2518. return (self => new HashMapIterator(self, key => key))(this._keyMap)
  2519. }
  2520. [symbol]() {
  2521. return combine(Hash_hash(this._keyMap))(Hash_hash("HashSet"))
  2522. }
  2523. [Equal_symbol](that) {
  2524. return (
  2525. !!isHashSet(that) &&
  2526. HashMap_size(this._keyMap) === HashMap_size(that._keyMap) &&
  2527. equals(this._keyMap, that._keyMap)
  2528. )
  2529. }
  2530. toString() {
  2531. return `HashSet(${Array.from(this).map(String).join(", ")})`
  2532. }
  2533. toJSON() {
  2534. return { _tag: "HashSet", values: Array.from(this) }
  2535. }
  2536. [Symbol.for("nodejs.util.inspect.custom")]() {
  2537. return this.toJSON()
  2538. }
  2539. }
  2540. const isHashSet = u =>
  2541. "object" == typeof u &&
  2542. null != u &&
  2543. "_id" in u &&
  2544. u._id === HashSetTypeId,
  2545. HashSet_empty = () => new HashSetImpl(HashMap_empty()),
  2546. HashSet_has = Function_dual(2, (self, value) =>
  2547. HashMap_has(self._keyMap, value)
  2548. ),
  2549. HashSet_beginMutation = self =>
  2550. new HashSetImpl(beginMutation(self._keyMap)),
  2551. HashSet_endMutation = self => {
  2552. self._keyMap._editable = !1
  2553. return self
  2554. },
  2555. HashSet_mutate = Function_dual(2, (self, f) => {
  2556. const transient = HashSet_beginMutation(self)
  2557. f(transient)
  2558. return HashSet_endMutation(transient)
  2559. }),
  2560. HashSet_add = Function_dual(2, (self, value) =>
  2561. self._keyMap._editable
  2562. ? (set(value, !0)(self._keyMap), self)
  2563. : new HashSetImpl(set(value, !0)(self._keyMap))
  2564. ),
  2565. HashSet_remove = Function_dual(2, (self, value) =>
  2566. self._keyMap._editable
  2567. ? (HashMap_remove(value)(self._keyMap), self)
  2568. : new HashSetImpl(HashMap_remove(value)(self._keyMap))
  2569. ),
  2570. HashSet_difference = Function_dual(2, (self, that) =>
  2571. HashSet_mutate(self, set => {
  2572. for (const value of that) HashSet_remove(set, value)
  2573. })
  2574. ),
  2575. HashSet_union = Function_dual(2, (self, that) =>
  2576. HashSet_mutate(HashSet_empty(), set => {
  2577. HashSet_forEach(self, value => HashSet_add(set, value))
  2578. for (const value of that) HashSet_add(set, value)
  2579. })
  2580. ),
  2581. HashSet_forEach = Function_dual(2, (self, f) =>
  2582. forEachWithIndex(self._keyMap, (_, k) => f(k))
  2583. ),
  2584. HashSet_reduce = Function_dual(3, (self, zero, f) =>
  2585. HashMap_reduceWithIndex(self._keyMap, zero, (z, _, a) => f(z, a))
  2586. ),
  2587. mjs_HashMap_empty = HashMap_empty,
  2588. mjs_HashMap_fromIterable = entries => {
  2589. const map = beginMutation(HashMap_empty())
  2590. for (const entry of entries) set(entry[0], entry[1])(map)
  2591. return endMutation(map)
  2592. },
  2593. mjs_HashMap_get = HashMap_get,
  2594. HashMap_set = set,
  2595. mjs_HashMap_size = HashMap_size,
  2596. mjs_HashSet_empty = HashSet_empty,
  2597. mjs_HashSet_fromIterable = elements => {
  2598. const set = HashSet_beginMutation(HashSet_empty())
  2599. for (const value of elements) HashSet_add(set, value)
  2600. return HashSet_endMutation(set)
  2601. },
  2602. mjs_HashSet_make = (...elements) => {
  2603. const set = HashSet_beginMutation(HashSet_empty())
  2604. for (const value of elements) HashSet_add(set, value)
  2605. return HashSet_endMutation(set)
  2606. },
  2607. mjs_HashSet_has = HashSet_has,
  2608. mjs_HashSet_size = self => HashMap_size(self._keyMap),
  2609. mjs_HashSet_add = HashSet_add,
  2610. mjs_HashSet_remove = HashSet_remove,
  2611. mjs_HashSet_difference = HashSet_difference,
  2612. mjs_HashSet_union = HashSet_union,
  2613. mjs_HashSet_forEach = HashSet_forEach,
  2614. mjs_HashSet_reduce = HashSet_reduce,
  2615. HashSetPatchTypeId = Symbol.for("@effect/data/Differ/HashSetPatch")
  2616. function HashSetPatch_variance(a) {
  2617. return a
  2618. }
  2619. class HashSetPatch_Empty {
  2620. constructor() {
  2621. this._tag = "Empty"
  2622. this._Value = HashSetPatch_variance
  2623. this._id = HashSetPatchTypeId
  2624. }
  2625. [symbol]() {
  2626. return string("HashSetPatch(Empty)")
  2627. }
  2628. [Equal_symbol](that) {
  2629. return (
  2630. "object" == typeof that &&
  2631. null !== that &&
  2632. "_id" in that &&
  2633. that._id === this._id &&
  2634. "_tag" in that &&
  2635. that._tag === this._id
  2636. )
  2637. }
  2638. }
  2639. class HashSetPatch_AndThen {
  2640. constructor(first, second) {
  2641. this.first = first
  2642. this.second = second
  2643. this._tag = "AndThen"
  2644. this._Value = HashSetPatch_variance
  2645. this._id = HashSetPatchTypeId
  2646. }
  2647. [symbol]() {
  2648. return string("HashSetPatch(AndThen)")
  2649. }
  2650. [Equal_symbol](that) {
  2651. return (
  2652. "object" == typeof that &&
  2653. null !== that &&
  2654. "_id" in that &&
  2655. that._id === this._id &&
  2656. "_tag" in that &&
  2657. that._tag === this._id &&
  2658. equals(this.first, that.first) &&
  2659. equals(this.second, that.second)
  2660. )
  2661. }
  2662. }
  2663. class HashSetPatch_Add {
  2664. constructor(value) {
  2665. this.value = value
  2666. this._tag = "Add"
  2667. this._Value = HashSetPatch_variance
  2668. this._id = HashSetPatchTypeId
  2669. }
  2670. [symbol]() {
  2671. return string("HashSetPatch(Add)")
  2672. }
  2673. [Equal_symbol](that) {
  2674. return (
  2675. "object" == typeof that &&
  2676. null !== that &&
  2677. "_id" in that &&
  2678. that._id === this._id &&
  2679. "_tag" in that &&
  2680. that._tag === this._id &&
  2681. equals(this.value, that.value)
  2682. )
  2683. }
  2684. }
  2685. class HashSetPatch_Remove {
  2686. constructor(value) {
  2687. this.value = value
  2688. this._tag = "Remove"
  2689. this._Value = HashSetPatch_variance
  2690. this._id = HashSetPatchTypeId
  2691. }
  2692. [symbol]() {
  2693. return string("HashSetPatch(Remove)")
  2694. }
  2695. [Equal_symbol](that) {
  2696. return (
  2697. "object" == typeof that &&
  2698. null !== that &&
  2699. "_id" in that &&
  2700. that._id === this._id &&
  2701. "_tag" in that &&
  2702. that._tag === this._id &&
  2703. equals(this.value, that.value)
  2704. )
  2705. }
  2706. }
  2707. const HashSetPatch_empty = () => new HashSetPatch_Empty(),
  2708. HashSetPatch_combine = Function_dual(
  2709. 2,
  2710. (self, that) => new HashSetPatch_AndThen(self, that)
  2711. ),
  2712. HashSetPatch_patch = Function_dual(2, (self, oldValue) => {
  2713. let set = oldValue,
  2714. patches = Chunk_of(self)
  2715. for (; Chunk_isNonEmpty(patches); ) {
  2716. const head = Chunk_headNonEmpty(patches),
  2717. tail = Chunk_tailNonEmpty(patches)
  2718. switch (head._tag) {
  2719. case "Empty":
  2720. patches = tail
  2721. break
  2722. case "AndThen":
  2723. patches = Chunk_prepend(head.first)(
  2724. Chunk_prepend(head.second)(tail)
  2725. )
  2726. break
  2727. case "Add":
  2728. set = mjs_HashSet_add(head.value)(set)
  2729. patches = tail
  2730. break
  2731. case "Remove":
  2732. set = mjs_HashSet_remove(head.value)(set)
  2733. patches = tail
  2734. }
  2735. }
  2736. return set
  2737. }),
  2738. Differ_HashSetPatch_empty = HashSetPatch_empty,
  2739. Differ_HashSetPatch_combine = HashSetPatch_combine,
  2740. Differ_HashSetPatch_patch = HashSetPatch_patch,
  2741. DifferTypeId = Symbol.for("@effect/data/Differ")
  2742. class DifferImpl {
  2743. constructor(params) {
  2744. this._id = DifferTypeId
  2745. this._P = Function_identity
  2746. this._V = Function_identity
  2747. this.empty = params.empty
  2748. this.diff = params.diff
  2749. this.combine = params.combine
  2750. this.patch = params.patch
  2751. }
  2752. }
  2753. const Differ_make = params => new DifferImpl(params),
  2754. Differ_diff = Function_dual(3, (self, oldValue, newValue) =>
  2755. self.diff(oldValue, newValue)
  2756. ),
  2757. Differ_combine = Function_dual(3, (self, first, second) =>
  2758. self.combine(first, second)
  2759. ),
  2760. Differ_patch = Function_dual(3, (self, patch, oldValue) =>
  2761. self.patch(patch, oldValue)
  2762. ),
  2763. mjs_Differ_make = Differ_make,
  2764. Differ_environment = () =>
  2765. Differ_make({
  2766. empty: Differ_ContextPatch_empty(),
  2767. combine: (first, second) =>
  2768. Differ_ContextPatch_combine(second)(first),
  2769. diff: (oldValue, newValue) =>
  2770. ((oldValue, newValue) => {
  2771. const missingServices = new Map(oldValue.unsafeMap)
  2772. let patch = ContextPatch_empty()
  2773. for (const [tag, newService] of newValue.unsafeMap.entries())
  2774. if (missingServices.has(tag)) {
  2775. const old = missingServices.get(tag)
  2776. missingServices.delete(tag)
  2777. equals(old, newService) ||
  2778. (patch = ContextPatch_combine(
  2779. new UpdateService(tag, () => newService)
  2780. )(patch))
  2781. } else {
  2782. missingServices.delete(tag)
  2783. patch = ContextPatch_combine(new AddService(tag, newService))(
  2784. patch
  2785. )
  2786. }
  2787. for (const [tag] of missingServices.entries())
  2788. patch = ContextPatch_combine(new RemoveService(tag))(patch)
  2789. return patch
  2790. })(oldValue, newValue),
  2791. patch: (patch, oldValue) =>
  2792. Differ_ContextPatch_patch(oldValue)(patch),
  2793. }),
  2794. Differ_hashSet = () =>
  2795. Differ_make({
  2796. empty: Differ_HashSetPatch_empty(),
  2797. combine: (first, second) =>
  2798. Differ_HashSetPatch_combine(second)(first),
  2799. diff: (oldValue, newValue) =>
  2800. ((oldValue, newValue) => {
  2801. const [removed, patch] = mjs_HashSet_reduce(
  2802. [oldValue, HashSetPatch_empty()],
  2803. ([set, patch], value) =>
  2804. mjs_HashSet_has(value)(set)
  2805. ? [mjs_HashSet_remove(value)(set), patch]
  2806. : [
  2807. set,
  2808. HashSetPatch_combine(new HashSetPatch_Add(value))(
  2809. patch
  2810. ),
  2811. ]
  2812. )(newValue)
  2813. return mjs_HashSet_reduce(patch, (patch, value) =>
  2814. HashSetPatch_combine(new HashSetPatch_Remove(value))(patch)
  2815. )(removed)
  2816. })(oldValue, newValue),
  2817. patch: (patch, oldValue) =>
  2818. Differ_HashSetPatch_patch(oldValue)(patch),
  2819. }),
  2820. Differ_update = () => {
  2821. return (
  2822. (f = (_, a) => a),
  2823. Differ_make({
  2824. empty: Function_identity,
  2825. combine: (first, second) =>
  2826. first === Function_identity
  2827. ? second
  2828. : second === Function_identity
  2829. ? first
  2830. : a => second(first(a)),
  2831. diff: (oldValue, newValue) =>
  2832. equals(oldValue, newValue)
  2833. ? Function_identity
  2834. : constant(newValue),
  2835. patch: (patch, oldValue) => f(oldValue, patch(oldValue)),
  2836. })
  2837. )
  2838. var f
  2839. },
  2840. MutableRef_TypeId = Symbol.for("@effect/data/MutableRef")
  2841. class MutableRefImpl {
  2842. constructor(current) {
  2843. this.current = current
  2844. this._T = _ => _
  2845. this._id = MutableRef_TypeId
  2846. }
  2847. toString() {
  2848. return `MutableRef(${String(this.current)})`
  2849. }
  2850. toJSON() {
  2851. return { _tag: "MutableRef", current: this.current }
  2852. }
  2853. [Symbol.for("nodejs.util.inspect.custom")]() {
  2854. return this.toJSON()
  2855. }
  2856. }
  2857. const MutableRef_make = value => new MutableRefImpl(value),
  2858. MutableRef_get = self => self.current,
  2859. getAndSet = Function_dual(2, (self, value) => {
  2860. const ret = self.current
  2861. self.current = value
  2862. return ret
  2863. }),
  2864. getAndUpdate = Function_dual(2, (self, f) =>
  2865. getAndSet(self, f(MutableRef_get(self)))
  2866. ),
  2867. MutableRef_set = Function_dual(2, (self, value) => {
  2868. self.current = value
  2869. return self
  2870. }),
  2871. MutableRef_update = Function_dual(2, (self, f) =>
  2872. MutableRef_set(self, f(MutableRef_get(self)))
  2873. )
  2874. var fiberId_a, fiberId_b
  2875. const FiberIdTypeId = Symbol.for("@effect/io/Fiber/Id")
  2876. class fiberId_None {
  2877. constructor() {
  2878. this[fiberId_a] = FiberIdTypeId
  2879. this._tag = "None"
  2880. }
  2881. [((fiberId_a = FiberIdTypeId), symbol)]() {
  2882. return combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Id"))
  2883. }
  2884. [Equal_symbol](that) {
  2885. return isFiberId(that) && "None" === that._tag
  2886. }
  2887. }
  2888. class Runtime {
  2889. constructor(id, startTimeMillis) {
  2890. this.id = id
  2891. this.startTimeMillis = startTimeMillis
  2892. this[fiberId_b] = FiberIdTypeId
  2893. this._tag = "Runtime"
  2894. }
  2895. [((fiberId_b = FiberIdTypeId), symbol)]() {
  2896. return combine(Hash_hash(this.startTimeMillis))(
  2897. combine(Hash_hash(this.id))(
  2898. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Id"))
  2899. )
  2900. )
  2901. }
  2902. [Equal_symbol](that) {
  2903. return (
  2904. isFiberId(that) &&
  2905. "Runtime" === that._tag &&
  2906. this.id === that.id &&
  2907. this.startTimeMillis === that.startTimeMillis
  2908. )
  2909. }
  2910. }
  2911. const fiberId_none = new fiberId_None(),
  2912. isFiberId = self =>
  2913. "object" == typeof self && null != self && FiberIdTypeId in self,
  2914. ids = self => {
  2915. switch (self._tag) {
  2916. case "None":
  2917. return mjs_HashSet_empty()
  2918. case "Runtime":
  2919. return mjs_HashSet_make(self.id)
  2920. case "Composite":
  2921. return mjs_HashSet_union(ids(self.right))(ids(self.left))
  2922. }
  2923. },
  2924. _fiberCounter = globalValue(
  2925. Symbol.for("@effect/io/Fiber/Id/_fiberCounter"),
  2926. () => MutableRef_make(0)
  2927. ),
  2928. threadName = self =>
  2929. Array.from(ids(self))
  2930. .map(n => `#${n}`)
  2931. .join(","),
  2932. Id_none = fiberId_none,
  2933. Id_unsafeMake = () => {
  2934. const id = MutableRef_get(_fiberCounter)
  2935. MutableRef_set(id + 1)(_fiberCounter)
  2936. return new Runtime(id, new Date().getTime())
  2937. },
  2938. active = patch => 255 & patch,
  2939. enabled = patch => (patch >> 8) & 255,
  2940. runtimeFlagsPatch_make = (active, enabled) =>
  2941. (255 & active) + ((enabled & active & 255) << 8),
  2942. runtimeFlagsPatch_empty = runtimeFlagsPatch_make(0, 0),
  2943. exclude = Function_dual(2, (self, flag) =>
  2944. runtimeFlagsPatch_make(active(self) & ~flag, enabled(self))
  2945. ),
  2946. andThen = Function_dual(2, (self, that) => self | that),
  2947. cooperativeYielding = self => runtimeFlags_isEnabled(self, 32),
  2948. runtimeFlags_enable = Function_dual(2, (self, flag) => self | flag),
  2949. interruptible = self => interruption(self) && !windDown(self),
  2950. interruption = self => runtimeFlags_isEnabled(self, 1),
  2951. runtimeFlags_isEnabled = Function_dual(
  2952. 2,
  2953. (self, flag) => 0 != (self & flag)
  2954. ),
  2955. runtimeFlags_make = (...flags) => flags.reduce((a, b) => a | b, 0),
  2956. runtimeFlags_none = runtimeFlags_make(0),
  2957. opSupervision = self => runtimeFlags_isEnabled(self, 2),
  2958. runtimeMetrics = self => runtimeFlags_isEnabled(self, 4),
  2959. windDown = self => runtimeFlags_isEnabled(self, 16),
  2960. runtimeFlags_diff = Function_dual(2, (self, that) =>
  2961. runtimeFlagsPatch_make(self ^ that, that)
  2962. ),
  2963. runtimeFlags_patch = Function_dual(
  2964. 2,
  2965. (self, patch) =>
  2966. (self & (((~active(patch) >>> 0) & 255) | enabled(patch))) |
  2967. (active(patch) & enabled(patch))
  2968. ),
  2969. Patch_empty = runtimeFlagsPatch_empty,
  2970. Patch_disable = flag => runtimeFlagsPatch_make(flag, 0),
  2971. Patch_exclude = exclude
  2972. var cause_a
  2973. const CauseTypeId = Symbol.for("@effect/io/Cause"),
  2974. proto = {
  2975. [CauseTypeId]: { _E: _ => _ },
  2976. [symbol]() {
  2977. return combine(Hash_hash(flattenCause(this)))(
  2978. Hash_hash("@effect/io/Cause")
  2979. )
  2980. },
  2981. [Equal_symbol](that) {
  2982. return isCause(that) && causeEquals(this, that)
  2983. },
  2984. },
  2985. cause_empty = (() => {
  2986. const o = Object.create(proto)
  2987. o._tag = "Empty"
  2988. return o
  2989. })(),
  2990. fail = error => {
  2991. const o = Object.create(proto)
  2992. o._tag = "Fail"
  2993. o.error = error
  2994. return o
  2995. },
  2996. die = defect => {
  2997. const o = Object.create(proto)
  2998. o._tag = "Die"
  2999. o.defect = defect
  3000. return o
  3001. },
  3002. interrupt = fiberId => {
  3003. const o = Object.create(proto)
  3004. o._tag = "Interrupt"
  3005. o.fiberId = fiberId
  3006. return o
  3007. },
  3008. annotated = (cause, annotation) => {
  3009. const o = Object.create(proto)
  3010. o._tag = "Annotated"
  3011. o.cause = cause
  3012. o.annotation = annotation
  3013. return o
  3014. },
  3015. parallel = (left, right) => {
  3016. const o = Object.create(proto)
  3017. o._tag = "Parallel"
  3018. o.left = left
  3019. o.right = right
  3020. return o
  3021. },
  3022. sequential = (left, right) => {
  3023. const o = Object.create(proto)
  3024. o._tag = "Sequential"
  3025. o.left = left
  3026. o.right = right
  3027. return o
  3028. },
  3029. isCause = u => "object" == typeof u && null != u && CauseTypeId in u,
  3030. isEmptyType = self => "Empty" === self._tag,
  3031. isInterruptedOnly = self =>
  3032. reduceWithContext(void 0, IsInterruptedOnlyCauseReducer)(self),
  3033. cause_defects = self =>
  3034. Chunk_reverse(
  3035. cause_reduce(self, Chunk_empty(), (list, cause) =>
  3036. "Die" === cause._tag
  3037. ? Option_some(Chunk_prepend(cause.defect)(list))
  3038. : Option_none()
  3039. )
  3040. ),
  3041. failureOrCause = self => {
  3042. const option = (self =>
  3043. find(self, cause =>
  3044. "Fail" === cause._tag ? Option_some(cause.error) : Option_none()
  3045. ))(self)
  3046. switch (option._tag) {
  3047. case "None":
  3048. return Either_right(self)
  3049. case "Some":
  3050. return Either_left(option.value)
  3051. }
  3052. },
  3053. stripFailures = self =>
  3054. cause_match(
  3055. self,
  3056. cause_empty,
  3057. () => cause_empty,
  3058. defect => die(defect),
  3059. fiberId => interrupt(fiberId),
  3060. (cause, annotation) =>
  3061. isEmptyType(cause) ? cause : annotated(cause, annotation),
  3062. (left, right) => sequential(left, right),
  3063. (left, right) => parallel(left, right)
  3064. ),
  3065. causeEquals = (left, right) => {
  3066. let leftStack = Chunk_of(left),
  3067. rightStack = Chunk_of(right)
  3068. for (; Chunk_isNonEmpty(leftStack) && Chunk_isNonEmpty(rightStack); ) {
  3069. const [leftParallel, leftSequential] = cause_reduce(
  3070. [mjs_HashSet_empty(), Chunk_empty()],
  3071. ([parallel, sequential], cause) => {
  3072. const [par, seq] = evaluateCause(cause)
  3073. return Option_some([
  3074. mjs_HashSet_union(par)(parallel),
  3075. Chunk_concat(seq)(sequential),
  3076. ])
  3077. }
  3078. )(Chunk_headNonEmpty(leftStack)),
  3079. [rightParallel, rightSequential] = cause_reduce(
  3080. [mjs_HashSet_empty(), Chunk_empty()],
  3081. ([parallel, sequential], cause) => {
  3082. const [par, seq] = evaluateCause(cause)
  3083. return Option_some([
  3084. mjs_HashSet_union(par)(parallel),
  3085. Chunk_concat(seq)(sequential),
  3086. ])
  3087. }
  3088. )(Chunk_headNonEmpty(rightStack))
  3089. if (!equals(leftParallel, rightParallel)) return !1
  3090. leftStack = leftSequential
  3091. rightStack = rightSequential
  3092. }
  3093. return !0
  3094. },
  3095. flattenCause = cause => flattenCauseLoop(Chunk_of(cause), Chunk_empty()),
  3096. flattenCauseLoop = (causes, flattened) => {
  3097. for (;;) {
  3098. const [parallel, sequential] = Chunk_reduce(
  3099. [mjs_HashSet_empty(), Chunk_empty()],
  3100. ([parallel, sequential], cause) => {
  3101. const [par, seq] = evaluateCause(cause)
  3102. return [
  3103. mjs_HashSet_union(par)(parallel),
  3104. Chunk_concat(seq)(sequential),
  3105. ]
  3106. }
  3107. )(causes),
  3108. updated =
  3109. mjs_HashSet_size(parallel) > 0
  3110. ? Chunk_prepend(parallel)(flattened)
  3111. : flattened
  3112. if (Chunk_isEmpty(sequential)) return Chunk_reverse(updated)
  3113. causes = sequential
  3114. flattened = updated
  3115. }
  3116. throw new Error(
  3117. "BUG: Cause.flattenCauseLoop - please report an issue at https://github.com/Effect-TS/io/issues"
  3118. )
  3119. },
  3120. find = Function_dual(2, (self, pf) => {
  3121. const stack = [self]
  3122. for (; stack.length > 0; ) {
  3123. const item = stack.pop(),
  3124. option = pf(item)
  3125. switch (option._tag) {
  3126. case "None":
  3127. switch (item._tag) {
  3128. case "Sequential":
  3129. case "Parallel":
  3130. stack.push(item.right)
  3131. stack.push(item.left)
  3132. break
  3133. case "Annotated":
  3134. stack.push(item.cause)
  3135. }
  3136. break
  3137. case "Some":
  3138. return option
  3139. }
  3140. }
  3141. return Option_none()
  3142. }),
  3143. evaluateCause = self => {
  3144. let cause = self
  3145. const stack = []
  3146. let _parallel = mjs_HashSet_empty(),
  3147. _sequential = Chunk_empty()
  3148. for (; void 0 !== cause; )
  3149. switch (cause._tag) {
  3150. case "Empty":
  3151. if (0 === stack.length) return [_parallel, _sequential]
  3152. cause = stack.pop()
  3153. break
  3154. case "Fail":
  3155. if (0 === stack.length)
  3156. return [mjs_HashSet_add(cause.error)(_parallel), _sequential]
  3157. _parallel = mjs_HashSet_add(cause.error)(_parallel)
  3158. cause = stack.pop()
  3159. break
  3160. case "Die":
  3161. if (0 === stack.length)
  3162. return [mjs_HashSet_add(cause.defect)(_parallel), _sequential]
  3163. _parallel = mjs_HashSet_add(cause.defect)(_parallel)
  3164. cause = stack.pop()
  3165. break
  3166. case "Interrupt":
  3167. if (0 === stack.length)
  3168. return [mjs_HashSet_add(cause.fiberId)(_parallel), _sequential]
  3169. _parallel = mjs_HashSet_add(cause.fiberId)(_parallel)
  3170. cause = stack.pop()
  3171. break
  3172. case "Annotated":
  3173. cause = cause.cause
  3174. break
  3175. case "Sequential":
  3176. switch (cause.left._tag) {
  3177. case "Empty":
  3178. cause = cause.right
  3179. break
  3180. case "Sequential":
  3181. cause = sequential(
  3182. cause.left.left,
  3183. sequential(cause.left.right, cause.right)
  3184. )
  3185. break
  3186. case "Parallel":
  3187. cause = parallel(
  3188. sequential(cause.left.left, cause.right),
  3189. sequential(cause.left.right, cause.right)
  3190. )
  3191. break
  3192. case "Annotated":
  3193. cause = sequential(cause.left.cause, cause.right)
  3194. break
  3195. default:
  3196. _sequential = Chunk_prepend(cause.right)(_sequential)
  3197. cause = cause.left
  3198. }
  3199. break
  3200. case "Parallel":
  3201. stack.push(cause.right)
  3202. cause = cause.left
  3203. }
  3204. throw new Error(
  3205. "BUG: Cause.evaluateCauseLoop - please report an issue at https://github.com/Effect-TS/io/issues"
  3206. )
  3207. },
  3208. IsInterruptedOnlyCauseReducer = {
  3209. emptyCase: Function_constTrue,
  3210. failCase: Function_constFalse,
  3211. dieCase: Function_constFalse,
  3212. interruptCase: Function_constTrue,
  3213. annotatedCase: (_, value) => value,
  3214. sequentialCase: (_, left, right) => left && right,
  3215. parallelCase: (_, left, right) => left && right,
  3216. },
  3217. cause_match = Function_dual(
  3218. 8,
  3219. (
  3220. self,
  3221. emptyCase,
  3222. failCase,
  3223. dieCase,
  3224. interruptCase,
  3225. annotatedCase,
  3226. sequentialCase,
  3227. parallelCase
  3228. ) =>
  3229. reduceWithContext(self, void 0, {
  3230. emptyCase: () => emptyCase,
  3231. failCase: (_, error) => failCase(error),
  3232. dieCase: (_, defect) => dieCase(defect),
  3233. interruptCase: (_, fiberId) => interruptCase(fiberId),
  3234. annotatedCase: (_, value, annotation) =>
  3235. annotatedCase(value, annotation),
  3236. sequentialCase: (_, left, right) => sequentialCase(left, right),
  3237. parallelCase: (_, left, right) => parallelCase(left, right),
  3238. })
  3239. ),
  3240. cause_reduce = Function_dual(3, (self, zero, pf) => {
  3241. let accumulator = zero,
  3242. cause = self
  3243. const causes = []
  3244. for (; void 0 !== cause; ) {
  3245. const option = pf(accumulator, cause)
  3246. accumulator = Option_isSome(option) ? option.value : accumulator
  3247. switch (cause._tag) {
  3248. case "Sequential":
  3249. case "Parallel":
  3250. causes.push(cause.right)
  3251. cause = cause.left
  3252. break
  3253. case "Annotated":
  3254. cause = cause.cause
  3255. break
  3256. default:
  3257. cause = void 0
  3258. }
  3259. void 0 === cause && causes.length > 0 && (cause = causes.pop())
  3260. }
  3261. return accumulator
  3262. }),
  3263. reduceWithContext = Function_dual(3, (self, context, reducer) => {
  3264. const input = [self],
  3265. output = []
  3266. for (; input.length > 0; ) {
  3267. const cause = input.pop()
  3268. switch (cause._tag) {
  3269. case "Empty":
  3270. output.push(Either_right(reducer.emptyCase(context)))
  3271. break
  3272. case "Fail":
  3273. output.push(Either_right(reducer.failCase(context, cause.error)))
  3274. break
  3275. case "Die":
  3276. output.push(Either_right(reducer.dieCase(context, cause.defect)))
  3277. break
  3278. case "Interrupt":
  3279. output.push(
  3280. Either_right(reducer.interruptCase(context, cause.fiberId))
  3281. )
  3282. break
  3283. case "Annotated":
  3284. input.push(cause.cause)
  3285. output.push(
  3286. Either_left({
  3287. _tag: "AnnotatedCase",
  3288. annotation: cause.annotation,
  3289. })
  3290. )
  3291. break
  3292. case "Sequential":
  3293. input.push(cause.right)
  3294. input.push(cause.left)
  3295. output.push(Either_left({ _tag: "SequentialCase" }))
  3296. break
  3297. case "Parallel":
  3298. input.push(cause.right)
  3299. input.push(cause.left)
  3300. output.push(Either_left({ _tag: "ParallelCase" }))
  3301. }
  3302. }
  3303. const accumulator = []
  3304. for (; output.length > 0; ) {
  3305. const either = output.pop()
  3306. switch (either._tag) {
  3307. case "Left":
  3308. switch (either.left._tag) {
  3309. case "SequentialCase": {
  3310. const left = accumulator.pop(),
  3311. right = accumulator.pop(),
  3312. value = reducer.sequentialCase(context, left, right)
  3313. accumulator.push(value)
  3314. break
  3315. }
  3316. case "ParallelCase": {
  3317. const left = accumulator.pop(),
  3318. right = accumulator.pop(),
  3319. value = reducer.parallelCase(context, left, right)
  3320. accumulator.push(value)
  3321. break
  3322. }
  3323. case "AnnotatedCase": {
  3324. const cause = accumulator.pop(),
  3325. value = reducer.annotatedCase(
  3326. context,
  3327. cause,
  3328. either.left.annotation
  3329. )
  3330. accumulator.push(value)
  3331. break
  3332. }
  3333. }
  3334. break
  3335. case "Right":
  3336. accumulator.push(either.right)
  3337. }
  3338. }
  3339. if (0 === accumulator.length)
  3340. throw new Error(
  3341. "BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/io/issues"
  3342. )
  3343. return accumulator.pop()
  3344. }),
  3345. makeException = (proto, tag) => {
  3346. const _tag = { value: tag, enumerable: !0 },
  3347. protoWithToString = {
  3348. ...proto,
  3349. toString() {
  3350. return `${this._tag}: ${this.message}`
  3351. },
  3352. }
  3353. return message =>
  3354. Object.create(protoWithToString, {
  3355. _tag,
  3356. message: { value: message, enumerable: !0 },
  3357. })
  3358. },
  3359. InterruptedExceptionTypeId = Symbol.for(
  3360. "@effect/io/Cause/errors/InterruptedException"
  3361. ),
  3362. isInterruptedException = u =>
  3363. "object" == typeof u && null != u && InterruptedExceptionTypeId in u,
  3364. NoSuchElementExceptionTypeId = Symbol.for(
  3365. "@effect/io/Cause/errors/NoSuchElement"
  3366. ),
  3367. NoSuchElementException = makeException(
  3368. { [NoSuchElementExceptionTypeId]: NoSuchElementExceptionTypeId },
  3369. "NoSuchElementException"
  3370. ),
  3371. StackAnnotationTypeId = Symbol.for("@effect/io/Cause/StackAnnotation")
  3372. class StackAnnotation {
  3373. constructor(stack, seq) {
  3374. this.stack = stack
  3375. this.seq = seq
  3376. this[cause_a] = StackAnnotationTypeId
  3377. }
  3378. }
  3379. cause_a = StackAnnotationTypeId
  3380. const globalErrorSeq = MutableRef_make(0),
  3381. isStackAnnotation = u =>
  3382. "object" == typeof u && null != u && StackAnnotationTypeId in u,
  3383. DeferredTypeId = Symbol.for("@effect/io/Deferred"),
  3384. deferredVariance = { _E: _ => _, _A: _ => _ },
  3385. pending = joiners => ({ _tag: "Pending", joiners }),
  3386. done = effect => ({ _tag: "Done", effect })
  3387. class DefaultScheduler {
  3388. constructor() {
  3389. this.running = !1
  3390. this.tasks = []
  3391. }
  3392. starveInternal(depth) {
  3393. const toRun = this.tasks
  3394. this.tasks = []
  3395. for (let i = 0; i < toRun.length; i++) toRun[i]()
  3396. 0 === this.tasks.length ? (this.running = !1) : this.starve(depth)
  3397. }
  3398. starve(depth = 0) {
  3399. depth >= 2048
  3400. ? setTimeout(() => this.starveInternal(0), 0)
  3401. : Promise.resolve(void 0).then(() => this.starveInternal(depth + 1))
  3402. }
  3403. scheduleTask(task) {
  3404. this.tasks.push(task)
  3405. if (!this.running) {
  3406. this.running = !0
  3407. this.starve()
  3408. }
  3409. }
  3410. }
  3411. const defaultScheduler = globalValue(
  3412. Symbol.for("@effect/io/Scheduler/defaultScheduler"),
  3413. () => new DefaultScheduler()
  3414. )
  3415. var core_a, core_b, core_c
  3416. const EffectErrorTypeId = Symbol.for("@effect/io/Effect/Error"),
  3417. isEffectError = u =>
  3418. "object" == typeof u && null != u && EffectErrorTypeId in u,
  3419. core_EffectTypeId = Symbol.for("@effect/io/Effect")
  3420. class RevertFlags {
  3421. constructor(patch) {
  3422. this.patch = patch
  3423. this._tag = "RevertFlags"
  3424. }
  3425. }
  3426. class EffectPrimitive {
  3427. constructor(_tag) {
  3428. this._tag = _tag
  3429. this.i0 = void 0
  3430. this.i1 = void 0
  3431. this.i2 = void 0
  3432. this.trace = void 0
  3433. this[core_a] = core_effectVariance
  3434. }
  3435. [((core_a = core_EffectTypeId), Equal_symbol)](that) {
  3436. return this === that
  3437. }
  3438. [symbol]() {
  3439. return random(this)
  3440. }
  3441. traced(trace) {
  3442. if (trace) {
  3443. const effect = new EffectPrimitive("Traced")
  3444. effect.i0 = this
  3445. effect.trace = trace
  3446. return effect
  3447. }
  3448. return this
  3449. }
  3450. }
  3451. class EffectPrimitiveFailure {
  3452. constructor(_tag) {
  3453. this._tag = _tag
  3454. this.i0 = void 0
  3455. this.i1 = void 0
  3456. this.i2 = void 0
  3457. this.trace = void 0
  3458. this[core_b] = core_effectVariance
  3459. }
  3460. [((core_b = core_EffectTypeId), Equal_symbol)](that) {
  3461. return this === that
  3462. }
  3463. [symbol]() {
  3464. return random(this)
  3465. }
  3466. get cause() {
  3467. return this.i0
  3468. }
  3469. traced(trace) {
  3470. if (trace) {
  3471. const effect = new EffectPrimitive("Traced")
  3472. effect.i0 = this
  3473. effect.trace = trace
  3474. return effect
  3475. }
  3476. return this
  3477. }
  3478. }
  3479. class EffectPrimitiveSuccess {
  3480. constructor(_tag) {
  3481. this._tag = _tag
  3482. this.i0 = void 0
  3483. this.i1 = void 0
  3484. this.i2 = void 0
  3485. this.trace = void 0
  3486. this[core_c] = core_effectVariance
  3487. }
  3488. [((core_c = core_EffectTypeId), Equal_symbol)](that) {
  3489. return this === that
  3490. }
  3491. [symbol]() {
  3492. return random(this)
  3493. }
  3494. get value() {
  3495. return this.i0
  3496. }
  3497. traced(trace) {
  3498. if (trace) {
  3499. const effect = new EffectPrimitive("Traced")
  3500. effect.i0 = this
  3501. effect.trace = trace
  3502. return effect
  3503. }
  3504. return this
  3505. }
  3506. }
  3507. const core_effectVariance = { _R: _ => _, _E: _ => _, _A: _ => _ },
  3508. isEffect = u =>
  3509. "object" == typeof u && null != u && core_EffectTypeId in u,
  3510. acquireUseRelease = dualWithTrace(
  3511. 3,
  3512. (trace, restoreTracing) => (acquire, use, release) =>
  3513. uninterruptibleMask(restore =>
  3514. core_flatMap(a =>
  3515. core_flatMap(exit =>
  3516. matchCauseEffect(
  3517. cause => {
  3518. switch (exit._tag) {
  3519. case "Failure":
  3520. return failCause(parallel(exit.i0, cause))
  3521. case "Success":
  3522. return failCause(cause)
  3523. }
  3524. },
  3525. () => exit
  3526. )(suspend(() => restoreTracing(release)(a, exit)))
  3527. )(core_exit(suspend(() => restore(restoreTracing(use)(a)))))
  3528. )(acquire)
  3529. ).traced(trace)
  3530. ),
  3531. core_as = dualWithTrace(
  3532. 2,
  3533. trace => (self, value) =>
  3534. core_flatMap(() => succeed(value))(self).traced(trace)
  3535. ),
  3536. core_asUnit = methodWithTrace(
  3537. trace => self => core_as(void 0)(self).traced(trace)
  3538. ),
  3539. core_async = methodWithTrace(
  3540. trace =>
  3541. (register, blockingOn = Id_none) => {
  3542. const effect = new EffectPrimitive("Async")
  3543. effect.i0 = register
  3544. effect.i1 = blockingOn
  3545. return trace ? effect.traced(trace) : effect
  3546. }
  3547. ),
  3548. asyncInterruptEither = methodWithTrace(
  3549. (trace, restore) =>
  3550. (register, blockingOn = Id_none) =>
  3551. suspend(() => {
  3552. let cancelerRef = core_unit()
  3553. return onInterrupt(() => cancelerRef)(
  3554. core_async(resume => {
  3555. const result = restore(register)(resume)
  3556. Either_isRight(result)
  3557. ? resume(result.right)
  3558. : (cancelerRef = result.left)
  3559. }, blockingOn)
  3560. )
  3561. }).traced(trace)
  3562. ),
  3563. asyncInterrupt = methodWithTrace(
  3564. (trace, restore) =>
  3565. (register, blockingOn = Id_none) =>
  3566. suspend(() => {
  3567. let cancelerRef = core_unit()
  3568. return onInterrupt(() => cancelerRef)(
  3569. core_async(resume => {
  3570. cancelerRef = restore(register)(resume)
  3571. }, blockingOn)
  3572. )
  3573. }).traced(trace)
  3574. ),
  3575. catchAll = dualWithTrace(
  3576. 2,
  3577. (trace, restore) => (self, f) =>
  3578. matchEffect(restore(f), succeed)(self).traced(trace)
  3579. ),
  3580. core_die = methodWithTrace(
  3581. trace => defect => failCause(die(defect)).traced(trace)
  3582. ),
  3583. core_either = methodWithTrace(
  3584. trace => self =>
  3585. matchEffect(
  3586. e => succeed(Either_left(e)),
  3587. a => succeed(Either_right(a))
  3588. )(self).traced(trace)
  3589. ),
  3590. context = methodWithTrace(
  3591. trace => () => suspend(() => fiberRefGet(currentContext)).traced(trace)
  3592. ),
  3593. contextWithEffect = methodWithTrace(
  3594. (trace, restore) => f =>
  3595. core_flatMap(restore(f))(context()).traced(trace)
  3596. ),
  3597. core_exit = methodWithTrace(
  3598. trace => self => matchCause(failCause, succeed)(self).traced(trace)
  3599. ),
  3600. core_fail = methodWithTrace(
  3601. trace => error => failCause(fail(error)).traced(trace)
  3602. ),
  3603. failSync = methodWithTrace(
  3604. (trace, restore) => evaluate =>
  3605. failCauseSync(() => fail(restore(evaluate)())).traced(trace)
  3606. ),
  3607. failCause = methodWithTrace(trace => cause => {
  3608. const effect = new EffectPrimitiveFailure("Failure")
  3609. effect.i0 = cause
  3610. return trace ? effect.traced(trace) : effect
  3611. }),
  3612. failCauseSync = methodWithTrace(
  3613. (trace, restore) => evaluate =>
  3614. core_flatMap(sync(restore(evaluate)), failCause).traced(trace)
  3615. ),
  3616. fiberId = methodWithTrace(
  3617. trace => () =>
  3618. withFiberRuntime(state => succeed(state.id())).traced(trace)
  3619. ),
  3620. core_flatMap = dualWithTrace(2, (trace, restore) => (self, f) => {
  3621. const effect = new EffectPrimitive("OnSuccess")
  3622. effect.i0 = self
  3623. effect.i1 = restore(f)
  3624. return trace ? effect.traced(trace) : effect
  3625. }),
  3626. core_flatten = methodWithTrace(
  3627. trace => self => core_flatMap(self, Function_identity).traced(trace)
  3628. ),
  3629. matchCause = dualWithTrace(
  3630. 3,
  3631. (trace, restore) => (self, onFailure, onSuccess) =>
  3632. matchCauseEffect(
  3633. cause => succeed(restore(onFailure)(cause)),
  3634. a => succeed(restore(onSuccess)(a))
  3635. )(self).traced(trace)
  3636. ),
  3637. matchCauseEffect = dualWithTrace(
  3638. 3,
  3639. (trace, restore) => (self, onFailure, onSuccess) => {
  3640. const effect = new EffectPrimitive("OnSuccessAndFailure")
  3641. effect.i0 = self
  3642. effect.i1 = restore(onFailure)
  3643. effect.i2 = restore(onSuccess)
  3644. return trace ? effect.traced(trace) : effect
  3645. }
  3646. ),
  3647. matchEffect = dualWithTrace(
  3648. 3,
  3649. (trace, restore) => (self, onFailure, onSuccess) =>
  3650. matchCauseEffect(
  3651. self,
  3652. cause => {
  3653. const failures = (self =>
  3654. Chunk_reverse(
  3655. cause_reduce(self, Chunk_empty(), (list, cause) =>
  3656. "Fail" === cause._tag
  3657. ? Option_some(Chunk_prepend(cause.error)(list))
  3658. : Option_none()
  3659. )
  3660. ))(cause)
  3661. return cause_defects(cause).length > 0
  3662. ? failCause(
  3663. (self =>
  3664. cause_match(
  3665. self,
  3666. cause_empty,
  3667. failure => die(failure),
  3668. defect => die(defect),
  3669. fiberId => interrupt(fiberId),
  3670. (cause, annotation) =>
  3671. isEmptyType(cause)
  3672. ? cause
  3673. : annotated(cause, annotation),
  3674. (left, right) => sequential(left, right),
  3675. (left, right) => parallel(left, right)
  3676. ))(cause)
  3677. )
  3678. : failures.length > 0
  3679. ? restore(onFailure)(unsafeHead(failures))
  3680. : failCause(cause)
  3681. },
  3682. onSuccess
  3683. ).traced(trace)
  3684. ),
  3685. core_forEach = dualWithTrace(
  3686. 2,
  3687. (trace, restore) => (self, f) =>
  3688. suspend(() => {
  3689. const arr = Array.from(self),
  3690. ret = new Array(arr.length)
  3691. let i = 0
  3692. return core_as(unsafeFromArray(ret))(
  3693. whileLoop(
  3694. () => i < arr.length,
  3695. () => restore(f)(arr[i]),
  3696. b => {
  3697. ret[i++] = b
  3698. }
  3699. )
  3700. )
  3701. }).traced(trace)
  3702. ),
  3703. forEachDiscard = dualWithTrace(
  3704. 2,
  3705. (trace, restore) => (self, f) =>
  3706. suspend(() => {
  3707. const arr = Array.from(self)
  3708. let i = 0
  3709. return whileLoop(
  3710. () => i < arr.length,
  3711. () => restore(f)(arr[i++]),
  3712. () => {}
  3713. )
  3714. }).traced(trace)
  3715. ),
  3716. core_fromOption = methodWithTrace(trace => option => {
  3717. switch (option._tag) {
  3718. case "None":
  3719. return core_fail(Option_none()).traced(trace)
  3720. case "Some":
  3721. return succeed(option.value).traced(trace)
  3722. }
  3723. }),
  3724. core_fromEither = methodWithTrace(trace => either => {
  3725. switch (either._tag) {
  3726. case "Left":
  3727. return core_fail(either.left).traced(trace)
  3728. case "Right":
  3729. return succeed(either.right).traced(trace)
  3730. }
  3731. }),
  3732. core_interruptible = methodWithTrace(trace => self => {
  3733. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3734. effect.i0 = runtimeFlagsPatch_make((flag = 1), flag)
  3735. var flag
  3736. effect.i1 = () => self
  3737. return trace ? effect.traced(trace) : effect
  3738. }),
  3739. core_map = dualWithTrace(
  3740. 2,
  3741. (trace, restore) => (self, f) =>
  3742. core_flatMap(a => sync(() => restore(f)(a)))(self).traced(trace)
  3743. ),
  3744. mapError = dualWithTrace(
  3745. 2,
  3746. (trace, restore) => (self, f) =>
  3747. matchCauseEffect(
  3748. self,
  3749. cause => {
  3750. const either = failureOrCause(cause)
  3751. switch (either._tag) {
  3752. case "Left":
  3753. return failSync(() => restore(f)(either.left))
  3754. case "Right":
  3755. return failCause(either.right)
  3756. }
  3757. },
  3758. succeed
  3759. ).traced(trace)
  3760. ),
  3761. onExit = dualWithTrace(
  3762. 2,
  3763. (trace, restoreTrace) => (self, cleanup) =>
  3764. uninterruptibleMask(restore =>
  3765. matchCauseEffect(
  3766. restore(self),
  3767. cause1 => {
  3768. const result = exitFailCause(cause1)
  3769. return matchCauseEffect(
  3770. cause2 => exitFailCause(sequential(cause1, cause2)),
  3771. () => result
  3772. )(restoreTrace(cleanup)(result))
  3773. },
  3774. success => {
  3775. const result = exitSucceed(success)
  3776. return core_zipRight(result)(restoreTrace(cleanup)(result))
  3777. }
  3778. )
  3779. ).traced(trace)
  3780. ),
  3781. onInterrupt = dualWithTrace(
  3782. 2,
  3783. (trace, restore) => (self, cleanup) =>
  3784. onExit(
  3785. self,
  3786. exitMatch(
  3787. cause =>
  3788. isInterruptedOnly(cause)
  3789. ? core_asUnit(
  3790. restore(cleanup)(
  3791. (self =>
  3792. cause_reduce(
  3793. self,
  3794. mjs_HashSet_empty(),
  3795. (set, cause) =>
  3796. "Interrupt" === cause._tag
  3797. ? Option_some(
  3798. mjs_HashSet_add(cause.fiberId)(set)
  3799. )
  3800. : Option_none()
  3801. ))(cause)
  3802. )
  3803. )
  3804. : core_unit(),
  3805. () => core_unit()
  3806. )
  3807. ).traced(trace)
  3808. ),
  3809. core_orElse = dualWithTrace(
  3810. 2,
  3811. (trace, restore) => (self, that) =>
  3812. attemptOrElse(restore(that), succeed)(self).traced(trace)
  3813. ),
  3814. orDie = methodWithTrace(
  3815. trace => self => orDieWith(self, Function_identity).traced(trace)
  3816. ),
  3817. orDieWith = dualWithTrace(
  3818. 2,
  3819. (trace, restore) => (self, f) =>
  3820. matchEffect(e => core_die(restore(f)(e)), succeed)(self).traced(trace)
  3821. ),
  3822. provideContext = dualWithTrace(
  3823. 2,
  3824. trace => (self, context) =>
  3825. fiberRefLocally(currentContext, context)(self).traced(trace)
  3826. ),
  3827. contramapContext = dualWithTrace(
  3828. 2,
  3829. (trace, restore) => (self, f) =>
  3830. contextWithEffect(context =>
  3831. provideContext(restore(f)(context))(self)
  3832. ).traced(trace)
  3833. ),
  3834. succeed = methodWithTrace(trace => value => {
  3835. const effect = new EffectPrimitiveSuccess("Success")
  3836. effect.i0 = value
  3837. return trace ? effect.traced(trace) : effect
  3838. }),
  3839. suspend = methodWithTrace(
  3840. (trace, restore) => effect =>
  3841. core_flatMap(Function_identity)(sync(restore(effect))).traced(trace)
  3842. ),
  3843. sync = methodWithTrace((trace, restore) => evaluate => {
  3844. const effect = new EffectPrimitive("Sync")
  3845. effect.i0 = restore(evaluate)
  3846. return trace ? effect.traced(trace) : effect
  3847. }),
  3848. core_tap = dualWithTrace(
  3849. 2,
  3850. (trace, restore) => (self, f) =>
  3851. core_flatMap(a => core_as(a)(restore(f)(a)))(self).traced(trace)
  3852. ),
  3853. transplant = methodWithTrace(
  3854. (trace, restore) => f =>
  3855. withFiberRuntime(state => {
  3856. const scopeOverride = state.getFiberRef(forkScopeOverride),
  3857. scope = getOrElse(() => state.scope())(scopeOverride)
  3858. return restore(f)(
  3859. fiberRefLocally(forkScopeOverride, Option_some(scope))
  3860. )
  3861. }).traced(trace)
  3862. ),
  3863. attemptOrElse = dualWithTrace(
  3864. 3,
  3865. (trace, restore) => (self, that, onSuccess) =>
  3866. matchCauseEffect(
  3867. self,
  3868. cause =>
  3869. cause_defects(cause).length > 0
  3870. ? failCause(
  3871. getOrThrow(
  3872. (self =>
  3873. cause_match(
  3874. self,
  3875. Option_none(),
  3876. failure => Option_some(die(failure)),
  3877. defect => Option_some(die(defect)),
  3878. () => Option_none(),
  3879. (option, annotation) =>
  3880. Option_map(cause => annotated(cause, annotation))(
  3881. option
  3882. ),
  3883. (left, right) =>
  3884. Option_isSome(left) && Option_isSome(right)
  3885. ? Option_some(sequential(left.value, right.value))
  3886. : Option_isSome(left) && Option_isNone(right)
  3887. ? Option_some(left.value)
  3888. : Option_isNone(left) && Option_isSome(right)
  3889. ? Option_some(right.value)
  3890. : Option_none(),
  3891. (left, right) =>
  3892. Option_isSome(left) && Option_isSome(right)
  3893. ? Option_some(parallel(left.value, right.value))
  3894. : Option_isSome(left) && Option_isNone(right)
  3895. ? Option_some(left.value)
  3896. : Option_isNone(left) && Option_isSome(right)
  3897. ? Option_some(right.value)
  3898. : Option_none()
  3899. ))(cause)
  3900. )
  3901. )
  3902. : restore(that)(),
  3903. restore(onSuccess)
  3904. ).traced(trace)
  3905. ),
  3906. uninterruptible = methodWithTrace(trace => self => {
  3907. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3908. effect.i0 = Patch_disable(1)
  3909. effect.i1 = () => self
  3910. return trace ? effect.traced(trace) : effect
  3911. }),
  3912. uninterruptibleMask = methodWithTrace((trace, restore) => f => {
  3913. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3914. effect.i0 = Patch_disable(1)
  3915. effect.i1 = oldFlags =>
  3916. interruption(oldFlags)
  3917. ? restore(f)(core_interruptible)
  3918. : restore(f)(uninterruptible)
  3919. return trace ? effect.traced(trace) : effect
  3920. }),
  3921. core_unit = methodWithTrace(trace => _ => succeed(void 0).traced(trace)),
  3922. updateRuntimeFlags = methodWithTrace(trace => patch => {
  3923. const effect = new EffectPrimitive("UpdateRuntimeFlags")
  3924. effect.i0 = patch
  3925. effect.i1 = void 0
  3926. return trace ? effect.traced(trace) : effect
  3927. }),
  3928. whenEffect = dualWithTrace(
  3929. 2,
  3930. trace => (self, predicate) =>
  3931. core_flatMap(b =>
  3932. b ? core_map(Option_some)(self) : succeed(Option_none())
  3933. )(predicate).traced(trace)
  3934. ),
  3935. whileLoop = methodWithTrace(
  3936. (trace, restore) => (check, body, process) => {
  3937. const effect = new EffectPrimitive("While")
  3938. effect.i0 = restore(check)
  3939. effect.i1 = restore(body)
  3940. effect.i2 = restore(process)
  3941. return trace ? effect.traced(trace) : effect
  3942. }
  3943. ),
  3944. withFiberRuntime = methodWithTrace((trace, restore) => withRuntime => {
  3945. const effect = new EffectPrimitive("WithRuntime")
  3946. effect.i0 = restore(withRuntime)
  3947. return trace ? effect.traced(trace) : effect
  3948. }),
  3949. withParallelism = dualWithTrace(
  3950. 2,
  3951. trace => (self, parallelism) =>
  3952. suspend(() =>
  3953. fiberRefLocally(currentParallelism, Option_some(parallelism))(self)
  3954. ).traced(trace)
  3955. ),
  3956. withParallelismUnbounded = methodWithTrace(
  3957. trace => self =>
  3958. suspend(() =>
  3959. fiberRefLocally(currentParallelism, Option_none())(self)
  3960. ).traced(trace)
  3961. ),
  3962. yieldNow = methodWithTrace(trace => () => {
  3963. const effect = new EffectPrimitive("Yield")
  3964. return trace ? effect.traced(trace) : effect
  3965. }),
  3966. core_zip = dualWithTrace(
  3967. 2,
  3968. trace => (self, that) =>
  3969. core_flatMap(self, a => core_map(that, b => [a, b])).traced(trace)
  3970. ),
  3971. core_zipLeft = dualWithTrace(
  3972. 2,
  3973. trace => (self, that) =>
  3974. core_flatMap(self, a => core_as(that, a)).traced(trace)
  3975. ),
  3976. core_zipRight = dualWithTrace(
  3977. 2,
  3978. trace => (self, that) => core_flatMap(self, () => that).traced(trace)
  3979. ),
  3980. core_zipWith = dualWithTrace(
  3981. 3,
  3982. (trace, restore) => (self, that, f) =>
  3983. core_flatMap(self, a => core_map(that, b => restore(f)(a, b))).traced(
  3984. trace
  3985. )
  3986. ),
  3987. interruptFiber = methodWithTrace(
  3988. trace => self =>
  3989. core_flatMap(fiberId => interruptAsFiber(fiberId)(self))(
  3990. fiberId()
  3991. ).traced(trace)
  3992. ),
  3993. interruptAsFiber = dualWithTrace(
  3994. 2,
  3995. trace => (self, fiberId) =>
  3996. core_flatMap(() => self.await())(
  3997. self.interruptAsFork(fiberId)
  3998. ).traced(trace)
  3999. ),
  4000. logLevelAll = {
  4001. _tag: "All",
  4002. syslog: 0,
  4003. label: "ALL",
  4004. ordinal: Number.MIN_SAFE_INTEGER,
  4005. },
  4006. logLevelInfo = { _tag: "Info", syslog: 6, label: "INFO", ordinal: 2e4 },
  4007. logLevelDebug = {
  4008. _tag: "Debug",
  4009. syslog: 7,
  4010. label: "DEBUG",
  4011. ordinal: 1e4,
  4012. },
  4013. logLevelNone = {
  4014. _tag: "None",
  4015. syslog: 7,
  4016. label: "OFF",
  4017. ordinal: Number.MAX_SAFE_INTEGER,
  4018. },
  4019. FiberRefTypeId = Symbol.for("@effect/io/FiberRef"),
  4020. fiberRefVariance = { _A: _ => _ },
  4021. fiberRefGet = methodWithTrace(
  4022. trace => self => fiberRefModify(self, a => [a, a]).traced(trace)
  4023. ),
  4024. fiberRefGetWith = dualWithTrace(
  4025. 2,
  4026. (trace, restore) => (self, f) =>
  4027. core_flatMap(fiberRefGet(self), restore(f)).traced(trace)
  4028. ),
  4029. fiberRefSet = dualWithTrace(
  4030. 2,
  4031. trace => (self, value) =>
  4032. fiberRefModify(self, () => [void 0, value]).traced(trace)
  4033. ),
  4034. fiberRefModify = dualWithTrace(
  4035. 2,
  4036. (trace, restore) => (self, f) =>
  4037. withFiberRuntime(state => {
  4038. const [b, a] = restore(f)(state.getFiberRef(self))
  4039. state.setFiberRef(self, a)
  4040. return succeed(b)
  4041. }).traced(trace)
  4042. ),
  4043. fiberRefLocally = dualWithTrace(
  4044. 3,
  4045. trace => (use, self, value) =>
  4046. acquireUseRelease(
  4047. core_zipLeft(fiberRefGet(self), fiberRefSet(self, value)),
  4048. () => use,
  4049. oldValue => fiberRefSet(self, oldValue)
  4050. ).traced(trace)
  4051. ),
  4052. fiberRefUnsafeMake = (
  4053. initial,
  4054. fork = Function_identity,
  4055. join = (_, a) => a
  4056. ) => fiberRefUnsafeMakePatch(initial, Differ_update(), fork, join),
  4057. fiberRefUnsafeMakeHashSet = initial =>
  4058. fiberRefUnsafeMakePatch(
  4059. initial,
  4060. Differ_hashSet(),
  4061. Differ_HashSetPatch_empty()
  4062. ),
  4063. fiberRefUnsafeMakeContext = initial =>
  4064. fiberRefUnsafeMakePatch(
  4065. initial,
  4066. Differ_environment(),
  4067. Differ_ContextPatch_empty()
  4068. ),
  4069. fiberRefUnsafeMakePatch = (
  4070. initial,
  4071. differ,
  4072. fork,
  4073. join = (_, n) => n
  4074. ) => ({
  4075. [FiberRefTypeId]: fiberRefVariance,
  4076. initial,
  4077. diff: (oldValue, newValue) => Differ_diff(oldValue, newValue)(differ),
  4078. combine: (first, second) => Differ_combine(first, second)(differ),
  4079. patch: patch => oldValue => Differ_patch(patch, oldValue)(differ),
  4080. fork,
  4081. join,
  4082. }),
  4083. fiberRefUnsafeMakeRuntimeFlags = initial =>
  4084. fiberRefUnsafeMakePatch(
  4085. initial,
  4086. mjs_Differ_make({
  4087. empty: runtimeFlagsPatch_empty,
  4088. diff: (oldValue, newValue) => runtimeFlags_diff(oldValue, newValue),
  4089. combine: (first, second) => andThen(second)(first),
  4090. patch: (_patch, oldValue) => runtimeFlags_patch(oldValue, _patch),
  4091. }),
  4092. Patch_empty
  4093. ),
  4094. currentContext = fiberRefUnsafeMakeContext(mjs_Context_empty()),
  4095. currentLogAnnotations = fiberRefUnsafeMake(mjs_HashMap_empty()),
  4096. currentLogLevel = fiberRefUnsafeMake(logLevelInfo),
  4097. currentLogSpan = fiberRefUnsafeMake(Chunk_empty()),
  4098. currentScheduler = fiberRefUnsafeMake(defaultScheduler),
  4099. currentParallelism = fiberRefUnsafeMake(Option_none()),
  4100. unhandledErrorLogLevel = fiberRefUnsafeMake(
  4101. Option_some(logLevelDebug),
  4102. _ => _,
  4103. (_, x) => x
  4104. ),
  4105. currentTags = fiberRefUnsafeMakeHashSet(mjs_HashSet_empty()),
  4106. forkScopeOverride = fiberRefUnsafeMake(
  4107. Option_none(),
  4108. () => Option_none(),
  4109. (parent, _) => parent
  4110. ),
  4111. interruptedCause = fiberRefUnsafeMake(
  4112. cause_empty,
  4113. () => cause_empty,
  4114. (parent, _) => parent
  4115. ),
  4116. ScopeTypeId = Symbol.for("@effect/io/Scope"),
  4117. CloseableScopeTypeId = Symbol.for("@effect/io/CloseableScope"),
  4118. scopeAddFinalizerExit = methodWithTrace(
  4119. (trace, restore) => (self, finalizer) =>
  4120. self.addFinalizer(restore(finalizer)).traced(trace)
  4121. ),
  4122. scopeClose = methodWithTrace(
  4123. trace => (self, exit) => self.close(exit).traced(trace)
  4124. ),
  4125. releaseMapAdd = dualWithTrace(
  4126. 2,
  4127. (trace, restore) => (self, finalizer) =>
  4128. core_map(
  4129. match(
  4130. () => () => core_unit(),
  4131. key => exit => releaseMapRelease(key, exit)(self)
  4132. )
  4133. )(releaseMapAddIfOpen(restore(finalizer))(self)).traced(trace)
  4134. ),
  4135. releaseMapRelease = dualWithTrace(
  4136. 3,
  4137. trace => (self, key, exit) =>
  4138. suspend(() => {
  4139. switch (self.state._tag) {
  4140. case "Exited":
  4141. return core_unit()
  4142. case "Running": {
  4143. const finalizer = self.state.finalizers.get(key)
  4144. self.state.finalizers.delete(key)
  4145. return null != finalizer
  4146. ? self.state.update(finalizer)(exit)
  4147. : core_unit()
  4148. }
  4149. }
  4150. }).traced(trace)
  4151. ),
  4152. releaseMapAddIfOpen = dualWithTrace(
  4153. 2,
  4154. (trace, restore) => (self, finalizer) =>
  4155. suspend(() => {
  4156. switch (self.state._tag) {
  4157. case "Exited":
  4158. self.state.nextKey += 1
  4159. return core_as(Option_none())(
  4160. restore(finalizer)(self.state.exit)
  4161. )
  4162. case "Running": {
  4163. const key = self.state.nextKey
  4164. self.state.finalizers.set(key, finalizer)
  4165. self.state.nextKey += 1
  4166. return succeed(Option_some(key))
  4167. }
  4168. }
  4169. }).traced(trace)
  4170. ),
  4171. releaseMapMake = methodWithTrace(
  4172. trace => () =>
  4173. sync(() => ({
  4174. state: {
  4175. _tag: "Running",
  4176. nextKey: 0,
  4177. finalizers: new Map(),
  4178. update: Function_identity,
  4179. },
  4180. })).traced(trace)
  4181. ),
  4182. exitAs = Function_dual(2, (self, value) => {
  4183. switch (self._tag) {
  4184. case "Failure":
  4185. return self
  4186. case "Success":
  4187. return exitSucceed(value)
  4188. }
  4189. }),
  4190. exitAsUnit = self => exitAs(self, void 0),
  4191. exitCollectAllPar = exits => exitCollectAllInternal(exits, parallel),
  4192. exitFail = error => exitFailCause(fail(error)),
  4193. exitFailCause = cause => {
  4194. const effect = new EffectPrimitiveFailure("Failure")
  4195. effect.i0 = cause
  4196. return effect
  4197. },
  4198. exitMap = Function_dual(2, (self, f) => {
  4199. switch (self._tag) {
  4200. case "Failure":
  4201. return self
  4202. case "Success":
  4203. return exitSucceed(f(self.i0))
  4204. }
  4205. }),
  4206. exitMatch = Function_dual(3, (self, onFailure, onSuccess) => {
  4207. switch (self._tag) {
  4208. case "Failure":
  4209. return onFailure(self.i0)
  4210. case "Success":
  4211. return onSuccess(self.i0)
  4212. }
  4213. }),
  4214. exitMatchEffect = Function_dual(3, (self, onFailure, onSuccess) => {
  4215. switch (self._tag) {
  4216. case "Failure":
  4217. return onFailure(self.i0)
  4218. case "Success":
  4219. return onSuccess(self.i0)
  4220. }
  4221. }),
  4222. exitSucceed = value => {
  4223. const effect = new EffectPrimitiveSuccess("Success")
  4224. effect.i0 = value
  4225. return effect
  4226. },
  4227. exitUnit = () => exitSucceed(void 0),
  4228. exitZipWith = Function_dual(4, (self, that, f, g) => {
  4229. switch (self._tag) {
  4230. case "Failure":
  4231. switch (that._tag) {
  4232. case "Success":
  4233. return self
  4234. case "Failure":
  4235. return exitFailCause(g(self.i0, that.i0))
  4236. }
  4237. case "Success":
  4238. switch (that._tag) {
  4239. case "Success":
  4240. return exitSucceed(f(self.i0, that.i0))
  4241. case "Failure":
  4242. return that
  4243. }
  4244. }
  4245. }),
  4246. exitCollectAllInternal = (exits, combineCauses) => {
  4247. const list = Chunk_fromIterable(exits)
  4248. return Chunk_isNonEmpty(list)
  4249. ? Option_some(
  4250. exitMap(Chunk_reverse)(
  4251. Chunk_reduce(
  4252. exitMap(Chunk_of)(Chunk_headNonEmpty(list)),
  4253. (accumulator, current) =>
  4254. exitZipWith(
  4255. current,
  4256. (list, value) => Chunk_prepend(value)(list),
  4257. combineCauses
  4258. )(accumulator)
  4259. )(Chunk_tailNonEmpty(list))
  4260. )
  4261. )
  4262. : Option_none()
  4263. },
  4264. deferredUnsafeMake = fiberId => ({
  4265. [DeferredTypeId]: deferredVariance,
  4266. state: MutableRef_make(pending([])),
  4267. blockingOn: fiberId,
  4268. }),
  4269. deferredMake = methodWithTrace(
  4270. trace => () =>
  4271. core_flatMap(id => deferredMakeAs(id))(fiberId()).traced(trace)
  4272. ),
  4273. deferredMakeAs = methodWithTrace(
  4274. trace => fiberId =>
  4275. sync(() => deferredUnsafeMake(fiberId)).traced(trace)
  4276. ),
  4277. deferredAwait = methodWithTrace(
  4278. trace => self =>
  4279. asyncInterruptEither(k => {
  4280. const state = MutableRef_get(self.state)
  4281. switch (state._tag) {
  4282. case "Done":
  4283. return Either_right(state.effect)
  4284. case "Pending":
  4285. MutableRef_set(pending([k, ...state.joiners]))(self.state)
  4286. return Either_left(deferredInterruptJoiner(self, k))
  4287. }
  4288. }, self.blockingOn).traced(trace)
  4289. ),
  4290. deferredCompleteWith = dualWithTrace(
  4291. 2,
  4292. trace => (self, effect) =>
  4293. sync(() => {
  4294. const state = MutableRef_get(self.state)
  4295. switch (state._tag) {
  4296. case "Done":
  4297. return !1
  4298. case "Pending":
  4299. MutableRef_set(done(effect))(self.state)
  4300. for (let i = 0; i < state.joiners.length; i++)
  4301. state.joiners[i](effect)
  4302. return !0
  4303. }
  4304. }).traced(trace)
  4305. ),
  4306. deferredFail = dualWithTrace(
  4307. 2,
  4308. trace => (self, error) =>
  4309. deferredCompleteWith(self, core_fail(error)).traced(trace)
  4310. ),
  4311. deferredFailCause = dualWithTrace(
  4312. 2,
  4313. trace => (self, cause) =>
  4314. deferredCompleteWith(self, failCause(cause)).traced(trace)
  4315. ),
  4316. deferredSucceed = dualWithTrace(
  4317. 2,
  4318. trace => (self, value) =>
  4319. deferredCompleteWith(self, succeed(value)).traced(trace)
  4320. ),
  4321. deferredUnsafeDone = (self, effect) => {
  4322. const state = MutableRef_get(self.state)
  4323. if ("Pending" === state._tag) {
  4324. MutableRef_set(done(effect))(self.state)
  4325. for (let i = state.joiners.length - 1; i >= 0; i--)
  4326. state.joiners[i](effect)
  4327. }
  4328. },
  4329. deferredInterruptJoiner = (self, joiner) =>
  4330. sync(() => {
  4331. const state = MutableRef_get(self.state)
  4332. "Pending" === state._tag &&
  4333. MutableRef_set(pending(state.joiners.filter(j => j !== joiner)))(
  4334. self.state
  4335. )
  4336. })
  4337. var clock_a
  4338. const ClockTypeId = Symbol.for("@effect/io/Clock"),
  4339. clockTag = Tag(ClockTypeId),
  4340. globalClockScheduler = {
  4341. unsafeSchedule(task, duration) {
  4342. if (duration.millis > 2147483647) return Function_constFalse
  4343. let completed = !1
  4344. const handle = setTimeout(() => {
  4345. completed = !0
  4346. task()
  4347. }, duration.millis)
  4348. return () => {
  4349. clearTimeout(handle)
  4350. return !completed
  4351. }
  4352. },
  4353. }
  4354. class ClockImpl {
  4355. constructor() {
  4356. this[clock_a] = ClockTypeId
  4357. }
  4358. unsafeCurrentTimeMillis() {
  4359. return new Date().getTime()
  4360. }
  4361. currentTimeMillis() {
  4362. return bodyWithTrace(trace =>
  4363. sync(() => this.unsafeCurrentTimeMillis()).traced(trace)
  4364. )
  4365. }
  4366. scheduler() {
  4367. return bodyWithTrace(trace =>
  4368. succeed(globalClockScheduler).traced(trace)
  4369. )
  4370. }
  4371. sleep(duration) {
  4372. return bodyWithTrace(trace =>
  4373. asyncInterruptEither(cb => {
  4374. const canceler = globalClockScheduler.unsafeSchedule(
  4375. () => cb(core_unit()),
  4376. duration
  4377. )
  4378. return Either_left(core_asUnit(sync(canceler)))
  4379. }).traced(trace)
  4380. )
  4381. }
  4382. }
  4383. clock_a = ClockTypeId
  4384. const ConfigErrorTypeId = Symbol.for("@effect/io/Config/Error"),
  4385. configError_proto = { [ConfigErrorTypeId]: ConfigErrorTypeId },
  4386. And = (self, that) => {
  4387. const error = Object.create(configError_proto)
  4388. error._tag = "And"
  4389. error.left = self
  4390. error.right = that
  4391. Object.defineProperty(error, "toString", {
  4392. enumerable: !1,
  4393. value() {
  4394. return `${this.left} and ${this.right}`
  4395. },
  4396. })
  4397. return error
  4398. },
  4399. Or = (self, that) => {
  4400. const error = Object.create(configError_proto)
  4401. error._tag = "Or"
  4402. error.left = self
  4403. error.right = that
  4404. Object.defineProperty(error, "toString", {
  4405. enumerable: !1,
  4406. value() {
  4407. return `${this.left} or ${this.right}`
  4408. },
  4409. })
  4410. return error
  4411. },
  4412. InvalidData = (path, message) => {
  4413. const error = Object.create(configError_proto)
  4414. error._tag = "InvalidData"
  4415. error.path = path
  4416. error.message = message
  4417. Object.defineProperty(error, "toString", {
  4418. enumerable: !1,
  4419. value() {
  4420. return `(Invalid data at ${Chunk_join(".")(this.path)}: "${
  4421. this.message
  4422. }")`
  4423. },
  4424. })
  4425. return error
  4426. },
  4427. MissingData = (path, message) => {
  4428. const error = Object.create(configError_proto)
  4429. error._tag = "MissingData"
  4430. error.path = path
  4431. error.message = message
  4432. Object.defineProperty(error, "toString", {
  4433. enumerable: !1,
  4434. value() {
  4435. return `(Missing data at ${Chunk_join(".")(this.path)}: "${
  4436. this.message
  4437. }")`
  4438. },
  4439. })
  4440. return error
  4441. },
  4442. SourceUnavailable = (path, message, cause) => {
  4443. const error = Object.create(configError_proto)
  4444. error._tag = "SourceUnavailable"
  4445. error.path = path
  4446. error.message = message
  4447. error.cause = cause
  4448. Object.defineProperty(error, "toString", {
  4449. enumerable: !1,
  4450. value() {
  4451. return `(Source unavailable at ${Chunk_join(".")(this.path)}: "${
  4452. this.message
  4453. }")`
  4454. },
  4455. })
  4456. return error
  4457. },
  4458. Unsupported = (path, message) => {
  4459. const error = Object.create(configError_proto)
  4460. error._tag = "Unsupported"
  4461. error.path = path
  4462. error.message = message
  4463. Object.defineProperty(error, "toString", {
  4464. enumerable: !1,
  4465. value() {
  4466. return `(Unsupported operation at ${Chunk_join(".")(this.path)}: "${
  4467. this.message
  4468. }")`
  4469. },
  4470. })
  4471. return error
  4472. },
  4473. prefixed = Function_dual(2, (self, prefix) => {
  4474. switch (self._tag) {
  4475. case "And":
  4476. return And(
  4477. prefixed(prefix)(self.left),
  4478. prefixed(prefix)(self.right)
  4479. )
  4480. case "Or":
  4481. return Or(prefixed(prefix)(self.left), prefixed(prefix)(self.right))
  4482. case "InvalidData":
  4483. return InvalidData(Chunk_concat(self.path)(prefix), self.message)
  4484. case "MissingData":
  4485. return MissingData(Chunk_concat(self.path)(prefix), self.message)
  4486. case "SourceUnavailable":
  4487. return SourceUnavailable(
  4488. Chunk_concat(self.path)(prefix),
  4489. self.message,
  4490. self.cause
  4491. )
  4492. case "Unsupported":
  4493. return Unsupported(Chunk_concat(self.path)(prefix), self.message)
  4494. }
  4495. })
  4496. var List_a, List_b
  4497. const ListTypeId = Symbol.for("@effect/data/List"),
  4498. listVariance = { _A: _ => _ }
  4499. class ConsImpl {
  4500. constructor(head, tail) {
  4501. this.head = head
  4502. this.tail = tail
  4503. this._tag = "Cons"
  4504. this[List_a] = listVariance
  4505. }
  4506. toString() {
  4507. return `List.Cons(${List_toReadonlyArray(this).map(String).join(", ")})`
  4508. }
  4509. toJSON() {
  4510. return { _tag: "List.Cons", values: List_toReadonlyArray(this) }
  4511. }
  4512. [((List_a = ListTypeId), Symbol.for("nodejs.util.inspect.custom"))]() {
  4513. return this.toJSON()
  4514. }
  4515. [Equal_symbol](that) {
  4516. return (
  4517. isList(that) &&
  4518. this._tag === that._tag &&
  4519. equalsWith(this, that, equals)
  4520. )
  4521. }
  4522. [symbol]() {
  4523. return string("@effect/data/List")
  4524. }
  4525. [Symbol.iterator]() {
  4526. let done = !1,
  4527. self = this
  4528. return {
  4529. next() {
  4530. if (done) return this.return()
  4531. if ("Nil" === self._tag) {
  4532. done = !0
  4533. return this.return()
  4534. }
  4535. const value = self.head
  4536. self = self.tail
  4537. return { done, value }
  4538. },
  4539. return(value) {
  4540. done || (done = !0)
  4541. return { done: !0, value }
  4542. },
  4543. }
  4544. }
  4545. }
  4546. class NilImpl {
  4547. constructor() {
  4548. this._tag = "Nil"
  4549. this[List_b] = listVariance
  4550. }
  4551. toString() {
  4552. return "List.Nil"
  4553. }
  4554. toJSON() {
  4555. return { _tag: "List.Nil" }
  4556. }
  4557. [((List_b = ListTypeId), Symbol.for("nodejs.util.inspect.custom"))]() {
  4558. return this.toJSON()
  4559. }
  4560. [symbol]() {
  4561. return array(Array.from(this))
  4562. }
  4563. [Equal_symbol](that) {
  4564. return isList(that) && this._tag === that._tag
  4565. }
  4566. [Symbol.iterator]() {
  4567. return { next: () => ({ done: !0, value: void 0 }) }
  4568. }
  4569. }
  4570. const isList = u => "object" == typeof u && null != u && ListTypeId in u,
  4571. isNil = self => "Nil" === self._tag,
  4572. isCons = self => "Cons" === self._tag,
  4573. List_length = self => {
  4574. let these = self,
  4575. len = 0
  4576. for (; !isNil(these); ) {
  4577. len += 1
  4578. these = these.tail
  4579. }
  4580. return len
  4581. },
  4582. equalsWith = Function_dual(3, (self, that, f) => {
  4583. if (self === that) return !0
  4584. if (List_length(self) !== List_length(that)) return !1
  4585. const selfIterator = self[Symbol.iterator](),
  4586. thatIterator = that[Symbol.iterator]()
  4587. let nextSelf, nextThat
  4588. for (
  4589. ;
  4590. !(nextSelf = selfIterator.next()).done &&
  4591. !(nextThat = thatIterator.next()).done;
  4592.  
  4593. )
  4594. if (!f(nextSelf.value, nextThat.value)) return !1
  4595. return !0
  4596. }),
  4597. _Nil = new NilImpl(),
  4598. cons = (head, tail) => new ConsImpl(head, tail),
  4599. List_toReadonlyArray = self => Array.from(self),
  4600. pathPatch_empty = { _tag: "Empty" },
  4601. pathPatch_patch = Function_dual(2, (path, patch) => {
  4602. let input = new ConsImpl(patch, _Nil),
  4603. output = path
  4604. for (; isCons(input); ) {
  4605. const patch = input.head
  4606. switch (patch._tag) {
  4607. case "Empty":
  4608. input = input.tail
  4609. break
  4610. case "AndThen":
  4611. input = cons(patch.first, cons(patch.second, input.tail))
  4612. break
  4613. case "MapName":
  4614. output = Chunk_map(output, patch.f)
  4615. input = input.tail
  4616. break
  4617. case "Nested":
  4618. output = Chunk_prepend(output, patch.name)
  4619. input = input.tail
  4620. break
  4621. case "Unnested":
  4622. if (!contains(String_Equivalence)(patch.name)(Chunk_head(output)))
  4623. return Either_left(
  4624. MissingData(
  4625. output,
  4626. `Expected ${patch.name} to be in path in ConfigProvider#unnested`
  4627. )
  4628. )
  4629. output = Chunk_tailNonEmpty(output)
  4630. input = input.tail
  4631. }
  4632. }
  4633. return Either_right(output)
  4634. }),
  4635. ConfigProviderTypeId = Symbol.for("@effect/io/Config/Provider"),
  4636. configProviderTag = Tag(ConfigProviderTypeId),
  4637. FlatConfigProviderTypeId = Symbol.for("@effect/io/Config/Provider/Flat"),
  4638. configProvider_make = untracedMethod(restore => (load, flattened) => ({
  4639. [ConfigProviderTypeId]: ConfigProviderTypeId,
  4640. load: methodWithTrace(
  4641. trace => config => restore(load)(config).traced(trace)
  4642. ),
  4643. flattened,
  4644. })),
  4645. makeFlat = untracedMethod(
  4646. restore => (load, enumerateChildren, patch) => ({
  4647. [FlatConfigProviderTypeId]: FlatConfigProviderTypeId,
  4648. patch,
  4649. load: methodWithTrace(
  4650. trace =>
  4651. (path, config, split = !0) =>
  4652. restore(load)(path, config, split).traced(trace)
  4653. ),
  4654. enumerateChildren: methodWithTrace(
  4655. trace => path => restore(enumerateChildren)(path).traced(trace)
  4656. ),
  4657. })
  4658. ),
  4659. fromFlat = untracedMethod(
  4660. () => flat =>
  4661. configProvider_make(
  4662. config =>
  4663. core_flatMap(
  4664. fromFlatLoop(flat, Chunk_empty(), config, !1),
  4665. chunk =>
  4666. match(
  4667. () =>
  4668. core_fail(
  4669. MissingData(
  4670. Chunk_empty(),
  4671. `Expected a single value having structure: ${config}`
  4672. )
  4673. ),
  4674. succeed
  4675. )(Chunk_head(chunk))
  4676. ),
  4677. flat
  4678. )
  4679. ),
  4680. fromEnv = untracedMethod(() => (config = {}) => {
  4681. const { pathDelim, seqDelim } = Object.assign(
  4682. {},
  4683. { pathDelim: "_", seqDelim: "," },
  4684. config
  4685. ),
  4686. getEnv = () =>
  4687. "undefined" != typeof process &&
  4688. "env" in process &&
  4689. "object" == typeof process.env
  4690. ? process.env
  4691. : {}
  4692. return fromFlat(
  4693. makeFlat(
  4694. (path, primitive, split = !0) => {
  4695. const pathString = (path => Chunk_join(pathDelim)(path))(path),
  4696. current = getEnv(),
  4697. valueOpt =
  4698. pathString in current
  4699. ? Option_some(current[pathString])
  4700. : Option_none()
  4701. return core_flatMap(value =>
  4702. parsePrimitive(value, path, primitive, seqDelim, split)
  4703. )(
  4704. mapError(() =>
  4705. MissingData(
  4706. path,
  4707. `Expected ${pathString} to exist in the process context`
  4708. )
  4709. )(core_fromOption(valueOpt))
  4710. )
  4711. },
  4712. path =>
  4713. sync(() => {
  4714. const current = getEnv(),
  4715. keys = Object.keys(current),
  4716. filteredKeyPaths = Array.from(keys)
  4717. .map(value => value.toUpperCase().split(pathDelim))
  4718. .filter(keyPath => {
  4719. for (let i = 0; i < path.length; i++) {
  4720. const pathComponent = Chunk_unsafeGet(i)(path),
  4721. currentElement = keyPath[i]
  4722. if (
  4723. void 0 === currentElement ||
  4724. pathComponent !== currentElement
  4725. )
  4726. return !1
  4727. }
  4728. return !0
  4729. })
  4730. .flatMap(keyPath =>
  4731. keyPath.slice(path.length, path.length + 1)
  4732. )
  4733. return mjs_HashSet_fromIterable(filteredKeyPaths)
  4734. }),
  4735. pathPatch_empty
  4736. )
  4737. )
  4738. }),
  4739. fromFlatLoop = (flat, prefix, config, split) => {
  4740. const op = config
  4741. switch (op._tag) {
  4742. case "Constant":
  4743. return succeed(Chunk_of(op.value))
  4744. case "Described":
  4745. return suspend(() => fromFlatLoop(flat, prefix, op.config, split))
  4746. case "Fail":
  4747. return core_fail(MissingData(prefix, op.message))
  4748. case "Fallback":
  4749. return catchAll(error1 =>
  4750. op.condition(error1)
  4751. ? catchAll(error2 => core_fail(Or(error1, error2)))(
  4752. fromFlatLoop(flat, prefix, op.second, split)
  4753. )
  4754. : core_fail(error1)
  4755. )(suspend(() => fromFlatLoop(flat, prefix, op.first, split)))
  4756. case "Lazy":
  4757. return suspend(() => fromFlatLoop(flat, prefix, op.config(), split))
  4758. case "MapOrFail":
  4759. return suspend(() =>
  4760. core_flatMap(
  4761. core_forEach(a =>
  4762. mapError(prefixed(prefix))(core_fromEither(op.mapOrFail(a)))
  4763. )
  4764. )(fromFlatLoop(flat, prefix, op.original, split))
  4765. )
  4766. case "Nested":
  4767. return suspend(() =>
  4768. fromFlatLoop(
  4769. flat,
  4770. Chunk_concat(Chunk_of(op.name))(prefix),
  4771. op.config,
  4772. split
  4773. )
  4774. )
  4775. case "Primitive":
  4776. return core_flatMap(prefix =>
  4777. core_flatMap(values => {
  4778. if (Chunk_isEmpty(values)) {
  4779. const name = getOrElse(() => "<n/a>")(
  4780. (self => Chunk_get(self, self.length - 1))(prefix)
  4781. )
  4782. return core_fail(
  4783. (
  4784. name => self =>
  4785. MissingData(
  4786. Chunk_empty(),
  4787. `Expected ${self.description} with name ${name}`
  4788. )
  4789. )(name)
  4790. )
  4791. }
  4792. return succeed(values)
  4793. })(flat.load(prefix, op, split))
  4794. )(core_fromEither(pathPatch_patch(prefix, flat.patch)))
  4795. case "Sequence":
  4796. return suspend(() =>
  4797. core_map(Chunk_of)(fromFlatLoop(flat, prefix, op.config, !0))
  4798. )
  4799. case "Table":
  4800. return suspend(() =>
  4801. core_flatMap(prefix =>
  4802. core_flatMap(keys =>
  4803. core_map(values => {
  4804. if (0 === values.length)
  4805. return Chunk_of(mjs_HashMap_empty())
  4806. const matrix = toReadonlyArray(values).map(toReadonlyArray)
  4807. return Chunk_map(values =>
  4808. mjs_HashMap_fromIterable(
  4809. Chunk_zip(Chunk_fromIterable(keys), values)
  4810. )
  4811. )(unsafeFromArray(transpose(matrix).map(unsafeFromArray)))
  4812. })(
  4813. core_forEach(key =>
  4814. fromFlatLoop(
  4815. flat,
  4816. Chunk_concat(Chunk_of(key))(prefix),
  4817. op.valueConfig,
  4818. split
  4819. )
  4820. )(keys)
  4821. )
  4822. )(flat.enumerateChildren(prefix))
  4823. )(core_fromEither(pathPatch_patch(prefix, flat.patch)))
  4824. )
  4825. case "ZipWith":
  4826. return suspend(() =>
  4827. core_flatMap(left =>
  4828. core_flatMap(right => {
  4829. if (Either_isLeft(left) && Either_isLeft(right))
  4830. return core_fail(And(left.left, right.left))
  4831. if (Either_isLeft(left) && Either_isRight(right))
  4832. return core_fail(left.left)
  4833. if (Either_isRight(left) && Either_isLeft(right))
  4834. return core_fail(right.left)
  4835. if (Either_isRight(left) && Either_isRight(right)) {
  4836. const path = Chunk_join(".")(prefix),
  4837. fail = fromFlatLoopFail(prefix, path),
  4838. [lefts, rights] = ((leftDef, rightDef, left, right) => {
  4839. const leftPad = Chunk_unfold(left.length, index =>
  4840. index >= right.length
  4841. ? Option_none()
  4842. : Option_some([leftDef(index), index + 1])
  4843. ),
  4844. rightPad = Chunk_unfold(right.length, index =>
  4845. index >= left.length
  4846. ? Option_none()
  4847. : Option_some([rightDef(index), index + 1])
  4848. )
  4849. return [
  4850. Chunk_concat(leftPad)(left),
  4851. Chunk_concat(rightPad)(right),
  4852. ]
  4853. })(
  4854. fail,
  4855. fail,
  4856. Chunk_map(Either_right)(left.right),
  4857. Chunk_map(Either_right)(right.right)
  4858. )
  4859. return core_forEach(([left, right]) =>
  4860. core_map(([left, right]) => op.zip(left, right))(
  4861. core_zip(core_fromEither(right))(core_fromEither(left))
  4862. )
  4863. )(Chunk_zip(rights)(lefts))
  4864. }
  4865. throw new Error(
  4866. "BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/io/issues"
  4867. )
  4868. })(core_either(fromFlatLoop(flat, prefix, op.right, split)))
  4869. )(core_either(fromFlatLoop(flat, prefix, op.left, split)))
  4870. )
  4871. }
  4872. },
  4873. fromFlatLoopFail = (prefix, path) => index =>
  4874. Either_left(
  4875. MissingData(
  4876. prefix,
  4877. `The element at index ${index} in a sequence at path "${path}" was missing`
  4878. )
  4879. ),
  4880. parsePrimitive = (text, path, primitive, delimiter, split) =>
  4881. split
  4882. ? mapError(prefixed(path))(
  4883. core_forEach(char =>
  4884. core_fromEither(primitive.parse(char.trim()))
  4885. )(
  4886. ((text, delim) => {
  4887. const split = text.split(
  4888. new RegExp(`\\s*${escapeRegex(delim)}\\s*`)
  4889. )
  4890. return unsafeFromArray(split)
  4891. })(text, delimiter)
  4892. )
  4893. )
  4894. : mapError(prefixed(path))(
  4895. core_map(Chunk_of)(core_fromEither(primitive.parse(text)))
  4896. ),
  4897. transpose = array =>
  4898. Object.keys(array[0]).map(column => array.map(row => row[column])),
  4899. escapeRegex = string => string.replace(/[/\-\\^$*+?.()|[\]{}]/g, "\\$&")
  4900. var random_a
  4901. const RandomTypeId = Symbol.for("@effect/io/Random"),
  4902. randomTag = Tag(RandomTypeId)
  4903. random_a = RandomTypeId
  4904. const shuffleWith = (elements, nextIntBounded) =>
  4905. suspend(() =>
  4906. core_flatMap(buffer => {
  4907. const numbers = []
  4908. for (let i = buffer.length; i >= 2; i -= 1) numbers.push(i)
  4909. return core_as(Chunk_fromIterable(buffer))(
  4910. forEachDiscard(n =>
  4911. core_map(k => swap(buffer, n - 1, k))(nextIntBounded(n))
  4912. )(numbers)
  4913. )
  4914. })(sync(() => Array.from(elements)))
  4915. ),
  4916. swap = (buffer, index1, index2) => {
  4917. const tmp = buffer[index1]
  4918. buffer[index1] = buffer[index2]
  4919. buffer[index2] = tmp
  4920. return buffer
  4921. }
  4922. var seed
  4923. const currentServices = fiberRefUnsafeMakeContext(
  4924. Context_add(
  4925. configProviderTag,
  4926. fromEnv()
  4927. )(
  4928. Context_add(
  4929. randomTag,
  4930. ((seed = (4294967296 * Math.random()) >>> 0),
  4931. new (class {
  4932. constructor(seed) {
  4933. this.seed = seed
  4934. this[random_a] = RandomTypeId
  4935. this.PRNG = new PCGRandom(seed)
  4936. }
  4937. next() {
  4938. return bodyWithTrace(trace =>
  4939. sync(() => this.PRNG.number()).traced(trace)
  4940. )
  4941. }
  4942. nextBoolean() {
  4943. return bodyWithTrace(trace =>
  4944. core_map(this.next(), n => n > 0.5).traced(trace)
  4945. )
  4946. }
  4947. nextInt() {
  4948. return bodyWithTrace(trace =>
  4949. sync(() => this.PRNG.integer(Number.MAX_SAFE_INTEGER)).traced(
  4950. trace
  4951. )
  4952. )
  4953. }
  4954. nextRange(min, max) {
  4955. return bodyWithTrace(trace =>
  4956. core_map(this.next(), n => (max - min) * n + min).traced(
  4957. trace
  4958. )
  4959. )
  4960. }
  4961. nextIntBetween(min, max) {
  4962. return bodyWithTrace(trace =>
  4963. sync(() => this.PRNG.integer(1 + max - min) + min).traced(
  4964. trace
  4965. )
  4966. )
  4967. }
  4968. shuffle(elements) {
  4969. return bodyWithTrace(trace =>
  4970. shuffleWith(elements, n => this.nextIntBetween(0, n)).traced(
  4971. trace
  4972. )
  4973. )
  4974. }
  4975. })(seed))
  4976. )(Context_add(clockTag, new ClockImpl())(mjs_Context_empty()))
  4977. )
  4978. ),
  4979. currentTimeMillis = methodWithTrace(
  4980. trace => () =>
  4981. clockWith(clock => clock.currentTimeMillis()).traced(trace)
  4982. ),
  4983. sleep = methodWithTrace(
  4984. trace => duration =>
  4985. clockWith(clock => clock.sleep(duration)).traced(trace)
  4986. ),
  4987. clockWith = methodWithTrace(
  4988. (trace, restore) => f =>
  4989. fiberRefGetWith(currentServices, services =>
  4990. restore(f)(mjs_Context_get(clockTag)(services))
  4991. ).traced(trace)
  4992. ),
  4993. Duration_TypeId = Symbol.for("@effect/data/Duration")
  4994. class DurationImpl {
  4995. constructor(millis) {
  4996. this.millis = millis
  4997. this._id = Duration_TypeId
  4998. }
  4999. [symbol]() {
  5000. return Hash_hash(this.millis)
  5001. }
  5002. [Equal_symbol](that) {
  5003. return isDuration(that) && this.millis === that.millis
  5004. }
  5005. }
  5006. const isDuration = u =>
  5007. "object" == typeof u &&
  5008. null != u &&
  5009. "_id" in u &&
  5010. u._id === Duration_TypeId,
  5011. zero = new DurationImpl(0),
  5012. millis = millis => new DurationImpl(millis),
  5013. seconds = seconds => new DurationImpl(1e3 * seconds),
  5014. Clock_sleep =
  5015. (fromSemigroup(
  5016. Semigroup_make(
  5017. Function_dual(
  5018. 2,
  5019. (self, that) => new DurationImpl(self.millis + that.millis)
  5020. )
  5021. ),
  5022. zero
  5023. ).combineAll,
  5024. sleep),
  5025. Clock_currentTimeMillis = currentTimeMillis
  5026. var fiberRefs_a
  5027. const FiberRefsSym = Symbol.for("@effect/io/FiberRefs")
  5028. class FiberRefsImpl {
  5029. constructor(locals) {
  5030. this.locals = locals
  5031. this[fiberRefs_a] = FiberRefsSym
  5032. }
  5033. }
  5034. fiberRefs_a = FiberRefsSym
  5035. const findAncestor = (
  5036. _ref,
  5037. _parentStack,
  5038. _childStack,
  5039. _childModified = !1
  5040. ) => {
  5041. const ref = _ref
  5042. let ret,
  5043. parentStack = _parentStack,
  5044. childStack = _childStack,
  5045. childModified = _childModified
  5046. for (; void 0 === ret; )
  5047. if (
  5048. isNonEmptyReadonlyArray(parentStack) &&
  5049. isNonEmptyReadonlyArray(childStack)
  5050. ) {
  5051. const parentFiberId = headNonEmpty(parentStack)[0],
  5052. parentAncestors = tailNonEmpty(parentStack),
  5053. childFiberId = headNonEmpty(childStack)[0],
  5054. childRefValue = headNonEmpty(childStack)[1],
  5055. childAncestors = tailNonEmpty(childStack)
  5056. if (parentFiberId.startTimeMillis < childFiberId.startTimeMillis) {
  5057. childStack = childAncestors
  5058. childModified = !0
  5059. } else if (
  5060. parentFiberId.startTimeMillis > childFiberId.startTimeMillis
  5061. )
  5062. parentStack = parentAncestors
  5063. else if (parentFiberId.id < childFiberId.id) {
  5064. childStack = childAncestors
  5065. childModified = !0
  5066. } else
  5067. parentFiberId.id > childFiberId.id
  5068. ? (parentStack = parentAncestors)
  5069. : (ret = [childRefValue, childModified])
  5070. } else ret = [ref.initial, !0]
  5071. return ret
  5072. },
  5073. joinAs = Function_dual(3, (self, fiberId, that) => {
  5074. const parentFiberRefs = new Map(self.locals)
  5075. for (const [fiberRef, childStack] of that.locals) {
  5076. const childValue = headNonEmpty(childStack)[1]
  5077. if (!equals(headNonEmpty(childStack)[0], fiberId)) {
  5078. if (!parentFiberRefs.has(fiberRef)) {
  5079. if (equals(childValue, fiberRef.initial)) continue
  5080. parentFiberRefs.set(fiberRef, [
  5081. [fiberId, fiberRef.join(fiberRef.initial, childValue)],
  5082. ])
  5083. continue
  5084. }
  5085. const parentStack = parentFiberRefs.get(fiberRef),
  5086. [ancestor, wasModified] = findAncestor(
  5087. fiberRef,
  5088. parentStack,
  5089. childStack
  5090. )
  5091. if (wasModified) {
  5092. const patch = fiberRef.diff(ancestor, childValue),
  5093. oldValue = headNonEmpty(parentStack)[1],
  5094. newValue = fiberRef.join(
  5095. oldValue,
  5096. fiberRef.patch(patch)(oldValue)
  5097. )
  5098. if (!equals(oldValue, newValue)) {
  5099. let newStack
  5100. const parentFiberId = headNonEmpty(parentStack)[0]
  5101. newStack = equals(parentFiberId, fiberId)
  5102. ? prepend([parentFiberId, newValue])(
  5103. tailNonEmpty(parentStack)
  5104. )
  5105. : prepend([fiberId, newValue])(parentStack)
  5106. parentFiberRefs.set(fiberRef, newStack)
  5107. }
  5108. }
  5109. }
  5110. }
  5111. return new FiberRefsImpl(new Map(parentFiberRefs))
  5112. }),
  5113. forkAs = Function_dual(2, (self, childId) => {
  5114. const map = new Map()
  5115. for (const [fiberRef, stack] of self.locals.entries()) {
  5116. const oldValue = headNonEmpty(stack)[1],
  5117. newValue = fiberRef.patch(fiberRef.fork)(oldValue)
  5118. equals(oldValue, newValue)
  5119. ? map.set(fiberRef, stack)
  5120. : map.set(fiberRef, prepend([childId, newValue])(stack))
  5121. }
  5122. return new FiberRefsImpl(map)
  5123. }),
  5124. delete_ = Function_dual(2, (self, fiberRef) => {
  5125. const locals = new Map(self.locals)
  5126. locals.delete(fiberRef)
  5127. return new FiberRefsImpl(locals)
  5128. }),
  5129. fiberRefs_get = Function_dual(2, (self, fiberRef) =>
  5130. self.locals.has(fiberRef)
  5131. ? Option_some(headNonEmpty(self.locals.get(fiberRef))[1])
  5132. : Option_none()
  5133. ),
  5134. getOrDefault = Function_dual(2, (self, fiberRef) =>
  5135. getOrElse(() => fiberRef.initial)(fiberRefs_get(self, fiberRef))
  5136. ),
  5137. updatedAs = Function_dual(4, (self, fiberId, fiberRef, value) => {
  5138. const oldStack = self.locals.has(fiberRef)
  5139. ? self.locals.get(fiberRef)
  5140. : []
  5141. let newStack
  5142. if (isEmptyReadonlyArray(oldStack))
  5143. newStack = ReadonlyArray_of([fiberId, value])
  5144. else {
  5145. const [currentId, currentValue] = headNonEmpty(oldStack)
  5146. if (equals(currentId, fiberId)) {
  5147. if (equals(currentValue, value)) return self
  5148. newStack = prepend([fiberId, value])(tailNonEmpty(oldStack))
  5149. } else newStack = prepend([fiberId, value])(oldStack)
  5150. }
  5151. const locals = new Map(self.locals)
  5152. return new FiberRefsImpl(locals.set(fiberRef, newStack))
  5153. }),
  5154. FiberRefs_forkAs = forkAs,
  5155. FiberRefs_getOrDefault = getOrDefault,
  5156. FiberRefs_updatedAs = updatedAs,
  5157. FiberRefs_unsafeMake = function (fiberRefLocals) {
  5158. return new FiberRefsImpl(fiberRefLocals)
  5159. },
  5160. patch_diff = (oldValue, newValue) => {
  5161. const missingLocals = new Map(oldValue.locals)
  5162. let patch = { _tag: "Empty" }
  5163. for (const [fiberRef, pairs] of newValue.locals.entries()) {
  5164. const newValue = headNonEmpty(pairs)[1],
  5165. old = missingLocals.get(fiberRef)
  5166. if (void 0 !== old) {
  5167. const oldValue = headNonEmpty(old)[1]
  5168. equals(oldValue, newValue) ||
  5169. (patch = patch_combine({
  5170. _tag: "Update",
  5171. fiberRef,
  5172. patch: fiberRef.diff(oldValue, newValue),
  5173. })(patch))
  5174. } else
  5175. patch = patch_combine({ _tag: "Add", fiberRef, value: newValue })(
  5176. patch
  5177. )
  5178. missingLocals.delete(fiberRef)
  5179. }
  5180. for (const [fiberRef] of missingLocals.entries())
  5181. patch = patch_combine({ _tag: "Remove", fiberRef })(patch)
  5182. return patch
  5183. },
  5184. patch_combine = Function_dual(2, (self, that) => ({
  5185. _tag: "AndThen",
  5186. first: self,
  5187. second: that,
  5188. })),
  5189. patch_patch = Function_dual(3, (self, fiberId, oldValue) => {
  5190. let fiberRefs = oldValue,
  5191. patches = ReadonlyArray_of(self)
  5192. for (; isNonEmptyReadonlyArray(patches); ) {
  5193. const head = headNonEmpty(patches),
  5194. tail = tailNonEmpty(patches)
  5195. switch (head._tag) {
  5196. case "Empty":
  5197. patches = tail
  5198. break
  5199. case "Add":
  5200. fiberRefs = updatedAs(
  5201. fiberRefs,
  5202. fiberId,
  5203. head.fiberRef,
  5204. head.value
  5205. )
  5206. patches = tail
  5207. break
  5208. case "Remove":
  5209. fiberRefs = delete_(fiberRefs, head.fiberRef)
  5210. patches = tail
  5211. break
  5212. case "Update": {
  5213. const value = getOrDefault(fiberRefs, head.fiberRef)
  5214. fiberRefs = updatedAs(
  5215. fiberRefs,
  5216. fiberId,
  5217. head.fiberRef,
  5218. head.fiberRef.patch(head.patch)(value)
  5219. )
  5220. patches = tail
  5221. break
  5222. }
  5223. case "AndThen":
  5224. patches = prepend(head.first)(prepend(head.second)(tail))
  5225. }
  5226. }
  5227. return fiberRefs
  5228. })
  5229. class SingleShotGen {
  5230. constructor(self) {
  5231. this.self = self
  5232. this.called = !1
  5233. }
  5234. next(a) {
  5235. return this.called
  5236. ? { value: a, done: !0 }
  5237. : ((this.called = !0), { value: this.self, done: !1 })
  5238. }
  5239. return(a) {
  5240. return { value: a, done: !0 }
  5241. }
  5242. throw(e) {
  5243. throw e
  5244. }
  5245. [Symbol.iterator]() {
  5246. return new SingleShotGen(this.self)
  5247. }
  5248. }
  5249. const All = logLevelAll,
  5250. Fatal = { _tag: "Fatal", syslog: 2, label: "FATAL", ordinal: 5e4 },
  5251. Level_Error = { _tag: "Error", syslog: 3, label: "ERROR", ordinal: 4e4 },
  5252. Warning = { _tag: "Warning", syslog: 4, label: "WARN", ordinal: 3e4 },
  5253. Info = logLevelInfo,
  5254. Level_Debug = logLevelDebug,
  5255. Trace = { _tag: "Trace", syslog: 7, label: "TRACE", ordinal: 0 },
  5256. Level_None = logLevelNone,
  5257. locally = dualWithTrace(
  5258. 2,
  5259. trace => (use, self) =>
  5260. fiberRefLocally(use, currentLogLevel, self).traced(trace)
  5261. ),
  5262. greaterThanEqual = greaterThanOrEqualTo(
  5263. Order_contramap(level => level.ordinal)(Order)
  5264. ),
  5265. fromLiteral = _ => {
  5266. switch (_) {
  5267. case "All":
  5268. return All
  5269. case "Debug":
  5270. return Level_Debug
  5271. case "Error":
  5272. return Level_Error
  5273. case "Fatal":
  5274. return Fatal
  5275. case "Info":
  5276. return Info
  5277. case "Trace":
  5278. return Trace
  5279. case "None":
  5280. return Level_None
  5281. case "Warning":
  5282. return Warning
  5283. }
  5284. },
  5285. Span_render = now => self =>
  5286. `${self.label.replace(/[\s="]/g, "_")}=${now - self.startTime}ms`
  5287. var ref_a
  5288. const RefTypeId = Symbol.for("@effect/io/Ref"),
  5289. refVariance = { _A: _ => _ }
  5290. class RefImpl {
  5291. constructor(ref) {
  5292. this.ref = ref
  5293. this[ref_a] = refVariance
  5294. }
  5295. modify(f) {
  5296. return bodyWithTrace((trace, restore) =>
  5297. sync(() => {
  5298. const current = MutableRef_get(this.ref),
  5299. [b, a] = restore(f)(current)
  5300. current !== a && MutableRef_set(a)(this.ref)
  5301. return b
  5302. }).traced(trace)
  5303. )
  5304. }
  5305. }
  5306. ref_a = RefTypeId
  5307. const ref_unsafeMake = value => new RefImpl(MutableRef_make(value)),
  5308. ref_make = methodWithTrace(
  5309. trace => value => sync(() => ref_unsafeMake(value)).traced(trace)
  5310. ),
  5311. ref_get = methodWithTrace(
  5312. trace => self => self.modify(a => [a, a]).traced(trace)
  5313. ),
  5314. ref_set = dualWithTrace(
  5315. 2,
  5316. trace => (self, value) =>
  5317. self.modify(() => [void 0, value]).traced(trace)
  5318. ),
  5319. ref_modify = dualWithTrace(
  5320. 2,
  5321. (trace, restore) => (self, f) => self.modify(restore(f)).traced(trace)
  5322. ),
  5323. ref_update = dualWithTrace(
  5324. 2,
  5325. (trace, restore) => (self, f) =>
  5326. self.modify(a => [void 0, restore(f)(a)]).traced(trace)
  5327. ),
  5328. Ref_make = ref_make,
  5329. Ref_get = ref_get,
  5330. Ref_set = ref_set,
  5331. effect_collectAll = methodWithTrace(
  5332. trace => effects =>
  5333. core_forEach(effects, Function_identity).traced(trace)
  5334. ),
  5335. delay = dualWithTrace(
  5336. 2,
  5337. trace => (self, duration) =>
  5338. core_zipRight(Clock_sleep(duration), self).traced(trace)
  5339. ),
  5340. diffFiberRefs = methodWithTrace(
  5341. trace => self =>
  5342. summarized(getFiberRefs(), patch_diff)(self).traced(trace)
  5343. ),
  5344. effect_Do = methodWithTrace(trace => () => succeed({}).traced(trace)),
  5345. effect_bind = dualWithTrace(
  5346. 3,
  5347. (trace, restore) => (self, tag, f) =>
  5348. core_flatMap(self, k =>
  5349. core_map(restore(f)(k), a => ({ ...k, [tag]: a }))
  5350. ).traced(trace)
  5351. ),
  5352. effect_bindDiscard = dualWithTrace(
  5353. 3,
  5354. trace => (self, tag, f) =>
  5355. core_flatMap(self, k =>
  5356. core_map(f, a => ({ ...k, [tag]: a }))
  5357. ).traced(trace)
  5358. ),
  5359. bindValue = dualWithTrace(
  5360. 3,
  5361. (trace, restore) => (self, tag, f) =>
  5362. core_map(self, k => ({ ...k, [tag]: restore(f)(k) })).traced(trace)
  5363. ),
  5364. bindValueDiscard = dualWithTrace(
  5365. 3,
  5366. trace => (self, tag, f) =>
  5367. core_map(self, k => ({ ...k, [tag]: f })).traced(trace)
  5368. ),
  5369. filterOrElse = dualWithTrace(
  5370. 3,
  5371. (trace, restore) => (self, f, orElse) =>
  5372. filterOrElseWith(self, restore(f), orElse).traced(trace)
  5373. ),
  5374. filterOrElseWith = dualWithTrace(
  5375. 3,
  5376. (trace, restore) => (self, f, orElse) =>
  5377. core_flatMap(self, a =>
  5378. restore(f)(a) ? succeed(a) : restore(orElse)(a)
  5379. ).traced(trace)
  5380. ),
  5381. filterOrFail = dualWithTrace(
  5382. 3,
  5383. (trace, restore) => (self, f, error) =>
  5384. filterOrElse(self, restore(f), () => failSync(restore(error))).traced(
  5385. trace
  5386. )
  5387. ),
  5388. effect_match = dualWithTrace(
  5389. 3,
  5390. (trace, restore) => (self, onFailure, onSuccess) =>
  5391. matchEffect(
  5392. self,
  5393. e => succeed(restore(onFailure)(e)),
  5394. a => succeed(restore(onSuccess)(a))
  5395. ).traced(trace)
  5396. )
  5397. class EffectGen {
  5398. constructor(value) {
  5399. this.value = value
  5400. }
  5401. [Symbol.iterator]() {
  5402. return new SingleShotGen(this)
  5403. }
  5404. }
  5405. const getFiberRefs = methodWithTrace(
  5406. trace => () =>
  5407. withFiberRuntime(state => succeed(state.unsafeGetFiberRefs())).traced(
  5408. trace
  5409. )
  5410. ),
  5411. ignore = methodWithTrace(
  5412. trace => self =>
  5413. effect_match(self, Function_constVoid, Function_constVoid).traced(
  5414. trace
  5415. )
  5416. ),
  5417. effect_isSuccess = methodWithTrace(
  5418. trace => self =>
  5419. effect_match(self, Function_constFalse, Function_constTrue).traced(
  5420. trace
  5421. )
  5422. ),
  5423. someError = Option_some(Level_Error),
  5424. someWarning = Option_some(Warning),
  5425. someInfo = Option_some(Info),
  5426. someDebug = Option_some(Level_Debug),
  5427. log = methodWithTrace(
  5428. trace => message =>
  5429. withFiberRuntime(fiberState => {
  5430. fiberState.log(message, cause_empty, Option_none())
  5431. return core_unit()
  5432. }).traced(trace)
  5433. ),
  5434. logDebug = methodWithTrace(
  5435. trace => message =>
  5436. withFiberRuntime(fiberState => {
  5437. fiberState.log(message, cause_empty, someDebug)
  5438. return core_unit()
  5439. }).traced(trace)
  5440. ),
  5441. logError = methodWithTrace(
  5442. trace => message =>
  5443. withFiberRuntime(fiberState => {
  5444. fiberState.log(message, cause_empty, someError)
  5445. return core_unit()
  5446. }).traced(trace)
  5447. ),
  5448. logInfo = methodWithTrace(
  5449. trace => message =>
  5450. withFiberRuntime(fiberState => {
  5451. fiberState.log(message, cause_empty, someInfo)
  5452. return core_unit()
  5453. }).traced(trace)
  5454. ),
  5455. logWarning = methodWithTrace(
  5456. trace => message =>
  5457. withFiberRuntime(fiberState => {
  5458. fiberState.log(message, cause_empty, someWarning)
  5459. return core_unit()
  5460. }).traced(trace)
  5461. ),
  5462. logAnnotate = dualWithTrace(
  5463. 3,
  5464. trace => (effect, key, value) =>
  5465. core_flatMap(fiberRefGet(currentLogAnnotations), annotations =>
  5466. suspend(() =>
  5467. fiberRefLocally(
  5468. currentLogAnnotations,
  5469. HashMap_set(key, value)(annotations)
  5470. )(effect)
  5471. )
  5472. ).traced(trace)
  5473. ),
  5474. orElseSucceed = dualWithTrace(
  5475. 2,
  5476. (trace, restore) => (self, evaluate) =>
  5477. core_orElse(self, () => sync(restore(evaluate))).traced(trace)
  5478. ),
  5479. patchFiberRefs = methodWithTrace(
  5480. trace => patch =>
  5481. updateFiberRefs((fiberId, fiberRefs) =>
  5482. patch_patch(fiberId, fiberRefs)(patch)
  5483. ).traced(trace)
  5484. ),
  5485. promise = methodWithTrace(
  5486. (trace, restore) => evaluate =>
  5487. core_async(resolve => {
  5488. restore(evaluate)()
  5489. .then(a => resolve(exitSucceed(a)))
  5490. .catch(e => resolve(exitFailCause(die(e))))
  5491. }).traced(trace)
  5492. ),
  5493. effect_sleep = Clock_sleep,
  5494. summarized = dualWithTrace(
  5495. 3,
  5496. (trace, restore) => (self, summary, f) =>
  5497. core_flatMap(summary, start =>
  5498. core_flatMap(self, value =>
  5499. core_map(summary, end =>
  5500. ((...args) => args)(restore(f)(start, end), value)
  5501. )
  5502. )
  5503. ).traced(trace)
  5504. ),
  5505. tapErrorCause = dualWithTrace(
  5506. 2,
  5507. (trace, restore) => (self, f) =>
  5508. matchCauseEffect(
  5509. self,
  5510. cause => core_zipRight(restore(f)(cause), failCause(cause)),
  5511. succeed
  5512. ).traced(trace)
  5513. ),
  5514. effect_all = methodWithTrace(
  5515. trace =>
  5516. function () {
  5517. return 1 === arguments.length
  5518. ? isEffect(arguments[0])
  5519. ? core_map(arguments[0], x => [x])
  5520. : Array.isArray(arguments[0])
  5521. ? core_map(
  5522. effect_collectAll(arguments[0]),
  5523. toReadonlyArray
  5524. ).traced(trace)
  5525. : core_map(values => {
  5526. const res = {}
  5527. for (const [k, v] of values) res[k] = v
  5528. return res
  5529. })(
  5530. core_forEach(Object.entries(arguments[0]), ([_, e]) =>
  5531. core_map(e, a => [_, a])
  5532. )
  5533. ).traced(trace)
  5534. : core_map(effect_collectAll(arguments), toReadonlyArray).traced(
  5535. trace
  5536. )
  5537. }
  5538. ),
  5539. updateFiberRefs = methodWithTrace(
  5540. (trace, restore) => f =>
  5541. withFiberRuntime(state => {
  5542. state.setFiberRefs(
  5543. restore(f)(state.id(), state.unsafeGetFiberRefs())
  5544. )
  5545. return core_unit()
  5546. }).traced(trace)
  5547. ),
  5548. MutableHashMap_TypeId = Symbol.for("@effect/data/MutableHashMap")
  5549. class MutableHashMapImpl {
  5550. constructor() {
  5551. this._id = MutableHashMap_TypeId
  5552. this.backingMap = MutableRef_make(mjs_HashMap_empty())
  5553. }
  5554. [Symbol.iterator]() {
  5555. return this.backingMap.current[Symbol.iterator]()
  5556. }
  5557. toString() {
  5558. return `MutableHashMap(${Array.from(this)
  5559. .map(([k, v]) => `[${String(k)}, ${String(v)}]`)
  5560. .join(", ")})`
  5561. }
  5562. toJSON() {
  5563. return { _tag: "MutableHashMap", values: Array.from(this) }
  5564. }
  5565. [Symbol.for("nodejs.util.inspect.custom")]() {
  5566. return this.toJSON()
  5567. }
  5568. }
  5569. const MutableHashMap_get = Function_dual(2, (self, key) =>
  5570. mjs_HashMap_get(self.backingMap.current, key)
  5571. ),
  5572. MutableHashMap_has = Function_dual(2, (self, key) =>
  5573. Option_isSome(MutableHashMap_get(self, key))
  5574. ),
  5575. MutableHashMap_set = Function_dual(3, (self, key, value) => {
  5576. MutableRef_update(self.backingMap, HashMap_set(key, value))
  5577. return self
  5578. }),
  5579. ExecutionStrategy_sequential = { _tag: "Sequential" }
  5580. var fiberStatus_a, fiberStatus_b, fiberStatus_c
  5581. const FiberStatusTypeId = Symbol.for("@effect/io/Fiber/Status")
  5582. class Done {
  5583. constructor() {
  5584. this[fiberStatus_a] = FiberStatusTypeId
  5585. this._tag = "Done"
  5586. }
  5587. [((fiberStatus_a = FiberStatusTypeId), symbol)]() {
  5588. return combine(Hash_hash(this._tag))(
  5589. Hash_hash("@effect/io/Fiber/Status")
  5590. )
  5591. }
  5592. [Equal_symbol](that) {
  5593. return isFiberStatus(that) && "Done" === that._tag
  5594. }
  5595. }
  5596. class Running {
  5597. constructor(runtimeFlags) {
  5598. this.runtimeFlags = runtimeFlags
  5599. this[fiberStatus_b] = FiberStatusTypeId
  5600. this._tag = "Running"
  5601. }
  5602. [((fiberStatus_b = FiberStatusTypeId), symbol)]() {
  5603. return combine(Hash_hash(this.runtimeFlags))(
  5604. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Status"))
  5605. )
  5606. }
  5607. [Equal_symbol](that) {
  5608. return (
  5609. isFiberStatus(that) &&
  5610. "Running" === that._tag &&
  5611. this.runtimeFlags === that.runtimeFlags
  5612. )
  5613. }
  5614. }
  5615. class Suspended {
  5616. constructor(runtimeFlags, blockingOn) {
  5617. this.runtimeFlags = runtimeFlags
  5618. this.blockingOn = blockingOn
  5619. this[fiberStatus_c] = FiberStatusTypeId
  5620. this._tag = "Suspended"
  5621. }
  5622. [((fiberStatus_c = FiberStatusTypeId), symbol)]() {
  5623. return combine(Hash_hash(this.blockingOn))(
  5624. combine(Hash_hash(this.runtimeFlags))(
  5625. combine(Hash_hash(this._tag))(Hash_hash("@effect/io/Fiber/Status"))
  5626. )
  5627. )
  5628. }
  5629. [Equal_symbol](that) {
  5630. return (
  5631. isFiberStatus(that) &&
  5632. "Suspended" === that._tag &&
  5633. this.runtimeFlags === that.runtimeFlags &&
  5634. equals(this.blockingOn, that.blockingOn)
  5635. )
  5636. }
  5637. }
  5638. const isFiberStatus = u =>
  5639. "object" == typeof u && null != u && FiberStatusTypeId in u,
  5640. Status_done = new Done(),
  5641. Status_running = runtimeFlags => new Running(runtimeFlags),
  5642. interruptSignal = cause => ({ _tag: "InterruptSignal", cause }),
  5643. stateful = onFiber => ({ _tag: "Stateful", onFiber }),
  5644. resume = effect => ({ _tag: "Resume", effect })
  5645. var fiberScope_a, fiberScope_b
  5646. const FiberScopeTypeId = Symbol.for("@effect/io/Fiber/Scope")
  5647. class Global {
  5648. constructor() {
  5649. this[fiberScope_a] = FiberScopeTypeId
  5650. this.fiberId = Id_none
  5651. this.roots = new Set()
  5652. }
  5653. add(_runtimeFlags, child) {
  5654. this.roots.add(child)
  5655. child.unsafeAddObserver(() => {
  5656. this.roots.delete(child)
  5657. })
  5658. }
  5659. }
  5660. fiberScope_a = FiberScopeTypeId
  5661. class Local {
  5662. constructor(fiberId, parent) {
  5663. this.fiberId = fiberId
  5664. this.parent = parent
  5665. this[fiberScope_b] = FiberScopeTypeId
  5666. }
  5667. add(_runtimeFlags, child) {
  5668. this.parent.tell(
  5669. stateful(parentFiber => {
  5670. parentFiber.addChild(child)
  5671. child.unsafeAddObserver(() => {
  5672. parentFiber.removeChild(child)
  5673. })
  5674. })
  5675. )
  5676. }
  5677. }
  5678. fiberScope_b = FiberScopeTypeId
  5679. const globalScope = globalValue(
  5680. Symbol.for("@effect/io/FiberScope/Global"),
  5681. () => new Global()
  5682. ),
  5683. FiberTypeId = Symbol.for("@effect/io/Fiber"),
  5684. fiberVariance = { _E: _ => _, _A: _ => _ },
  5685. RuntimeFiberTypeId = Symbol.for("@effect/io/Fiber"),
  5686. _await = methodWithTrace(trace => self => self.await().traced(trace)),
  5687. fiber_join = methodWithTrace(
  5688. trace => self =>
  5689. core_zipLeft(core_flatten(self.await()), self.inheritAll()).traced(
  5690. trace
  5691. )
  5692. ),
  5693. currentFiberURI = "@effect/io/Fiber/Current",
  5694. MutableList_TypeId = Symbol.for("@effect/data/MutableList")
  5695. class MutableListImpl {
  5696. constructor() {
  5697. this._id = MutableList_TypeId
  5698. this.head = void 0
  5699. this.tail = void 0
  5700. this._length = 0
  5701. }
  5702. [Symbol.iterator]() {
  5703. let done = !1,
  5704. head = this.head
  5705. return {
  5706. next() {
  5707. if (done) return this.return()
  5708. if (null == head) {
  5709. done = !0
  5710. return this.return()
  5711. }
  5712. const value = head.value
  5713. head = head.next
  5714. return { done, value }
  5715. },
  5716. return(value) {
  5717. done || (done = !0)
  5718. return { done: !0, value }
  5719. },
  5720. }
  5721. }
  5722. toString() {
  5723. return `MutableList(${Array.from(this).map(String).join(", ")})`
  5724. }
  5725. toJSON() {
  5726. return { _tag: "MutableList", values: Array.from(this) }
  5727. }
  5728. [Symbol.for("nodejs.util.inspect.custom")]() {
  5729. return this.toJSON()
  5730. }
  5731. }
  5732. class LinkedListNode {
  5733. constructor(value) {
  5734. this.value = value
  5735. this.removed = !1
  5736. this.prev = void 0
  5737. this.next = void 0
  5738. }
  5739. }
  5740. const MutableList_isEmpty = self => 0 === MutableList_length(self),
  5741. MutableList_length = self => self._length,
  5742. MutableList_append = Function_dual(2, (self, value) => {
  5743. const node = new LinkedListNode(value)
  5744. void 0 === self.head && (self.head = node)
  5745. if (void 0 === self.tail) self.tail = node
  5746. else {
  5747. self.tail.next = node
  5748. node.prev = self.tail
  5749. self.tail = node
  5750. }
  5751. self._length += 1
  5752. return self
  5753. }),
  5754. MutableQueue_TypeId = Symbol.for("@effect/data/MutableQueue")
  5755. class MutableQueueImpl {
  5756. constructor(capacity) {
  5757. this.capacity = capacity
  5758. this._tag = "Bounded"
  5759. this._id = MutableQueue_TypeId
  5760. this.queue = new MutableListImpl()
  5761. }
  5762. [Symbol.iterator]() {
  5763. return Array.from(this.queue)[Symbol.iterator]()
  5764. }
  5765. toString() {
  5766. return `MutableQueue(${Array.from(this).map(String).join(", ")})`
  5767. }
  5768. toJSON() {
  5769. return { _tag: "MutableQueue", values: Array.from(this) }
  5770. }
  5771. [Symbol.for("nodejs.util.inspect.custom")]() {
  5772. return this.toJSON()
  5773. }
  5774. }
  5775. const MutableQueue_isEmpty = self => MutableList_isEmpty(self.queue),
  5776. offer = Function_dual(2, (self, value) => {
  5777. const queueLength = MutableList_length(self.queue)
  5778. if (void 0 !== self.capacity && queueLength === self.capacity) return !1
  5779. MutableList_append(value)(self.queue)
  5780. return !0
  5781. }),
  5782. MutableQueue_poll = Function_dual(2, (self, def) =>
  5783. MutableList_isEmpty(self.queue)
  5784. ? def
  5785. : (self => {
  5786. const head = self.head
  5787. if (void 0 !== head) {
  5788. ;((self, node) => {
  5789. if (!node.removed) {
  5790. node.removed = !0
  5791. if (void 0 !== node.prev && void 0 !== node.next) {
  5792. node.prev.next = node.next
  5793. node.next.prev = node.prev
  5794. } else if (void 0 !== node.prev) {
  5795. self.tail = node.prev
  5796. node.prev.next = void 0
  5797. } else if (void 0 !== node.next) {
  5798. self.head = node.next
  5799. node.next.prev = void 0
  5800. } else {
  5801. self.tail = void 0
  5802. self.head = void 0
  5803. }
  5804. self._length > 0 && (self._length -= 1)
  5805. }
  5806. })(self, head)
  5807. return head.value
  5808. }
  5809. })(self.queue)
  5810. ),
  5811. renderToString = u => {
  5812. if (
  5813. "object" == typeof u &&
  5814. null != u &&
  5815. "toString" in u &&
  5816. "function" == typeof u.toString &&
  5817. u.toString !== Object.prototype.toString
  5818. )
  5819. return u.toString()
  5820. if ("string" == typeof u) return `Error: ${u}`
  5821. if (
  5822. "object" == typeof u &&
  5823. null !== u &&
  5824. "message" in u &&
  5825. "string" == typeof u.message
  5826. ) {
  5827. const raw = JSON.parse(JSON.stringify(u)),
  5828. keys = new Set(Object.keys(raw))
  5829. keys.delete("name")
  5830. keys.delete("message")
  5831. keys.delete("_tag")
  5832. if (0 === keys.size)
  5833. return `${
  5834. "name" in u && "string" == typeof u.name ? u.name : "Error"
  5835. }${
  5836. "_tag" in u && "string" == typeof u._tag ? `(${u._tag})` : ""
  5837. }: ${u.message}`
  5838. }
  5839. return `Error: ${JSON.stringify(u)}`
  5840. },
  5841. renderStack = span =>
  5842. Option_isNone(span)
  5843. ? []
  5844. : span.value.stack.length > 0
  5845. ? (chunk => {
  5846. const ret = []
  5847. for (const s of chunk) {
  5848. const r = s?.toFrame()
  5849. r &&
  5850. runtimeDebug.filterStackFrame(r) &&
  5851. ret.push(renderFrame(r))
  5852. }
  5853. return ret
  5854. })(span.value.stack)
  5855. : [],
  5856. defaultErrorToLines = error =>
  5857. error instanceof Error
  5858. ? (error => {
  5859. if (error.stack) {
  5860. const stack = runtimeDebug.parseStack(error),
  5861. traces = []
  5862. for (const frame of stack)
  5863. if (frame) {
  5864. if (!runtimeDebug.filterStackFrame(frame)) break
  5865. traces.push(renderFrame(frame))
  5866. }
  5867. return [renderToString(error), traces.join("\r\n")]
  5868. }
  5869. return [String(error), void 0]
  5870. })(error)
  5871. : [renderToString(error), void 0]
  5872. class RenderError {
  5873. constructor(seq, message, stack) {
  5874. this.seq = seq
  5875. this.message = message
  5876. this.stack = stack
  5877. }
  5878. }
  5879. const cause_pretty_pretty = cause => {
  5880. if (isInterruptedOnly(cause))
  5881. return "All fibers interrupted without errors."
  5882. const errors = prettyErrors(cause),
  5883. final = Array.from(errors)
  5884. .sort((a, b) => (a.seq === b.seq ? 0 : a.seq > b.seq ? 1 : -1))
  5885. .map(e => {
  5886. let message = e.message
  5887. e.stack && e.stack.length > 0 && (message += `\r\n${e.stack}`)
  5888. return message
  5889. })
  5890. .join("\r\n\r\n")
  5891. return final.includes("\r\n") ? `\r\n${final}\r\n` : final
  5892. },
  5893. prettyErrors = cause =>
  5894. reduceWithContext(cause, void 0, {
  5895. emptyCase: () => [],
  5896. dieCase: (_, err) => {
  5897. const rendered = defaultErrorToLines(err)
  5898. return [
  5899. {
  5900. message: rendered[0],
  5901. errorSack: rendered[1],
  5902. fiberStack: Option_none(),
  5903. },
  5904. ]
  5905. },
  5906. failCase: (_, err) => {
  5907. const rendered = defaultErrorToLines(err)
  5908. return [
  5909. {
  5910. message: rendered[0],
  5911. errorSack: rendered[1],
  5912. fiberStack: Option_none(),
  5913. },
  5914. ]
  5915. },
  5916. interruptCase: () => [],
  5917. parallelCase: (_, l, r) => [...l, ...r],
  5918. sequentialCase: (_, l, r) => [...l, ...r],
  5919. annotatedCase: (_, v, parent) =>
  5920. isStackAnnotation(parent)
  5921. ? v.map(r => ({
  5922. message: r.message,
  5923. errorSack: r.errorSack,
  5924. fiberStack: orElse(() => Option_some(parent))(
  5925. Option_map(
  5926. r.fiberStack,
  5927. annotation =>
  5928. new StackAnnotation(
  5929. annotation.stack.length <
  5930. runtimeDebug.traceStackLimit &&
  5931. parent.stack.length > 0 &&
  5932. ((annotation.stack.length > 0 &&
  5933. unsafeLast(parent.stack) !==
  5934. unsafeLast(annotation.stack)) ||
  5935. 0 === annotation.stack.length)
  5936. ? Chunk_take(runtimeDebug.traceStackLimit)(
  5937. dedupeAdjacent(
  5938. Chunk_concat(parent.stack)(annotation.stack)
  5939. )
  5940. )
  5941. : annotation.stack,
  5942. annotation.seq
  5943. )
  5944. )
  5945. ),
  5946. }))
  5947. : v,
  5948. }).flatMap(r =>
  5949. ((error, errorStack, stack) => [
  5950. new RenderError(
  5951. "Some" === stack._tag ? stack.value.seq : 0,
  5952. error,
  5953. errorStack
  5954. ? errorStack + "\r\n" + renderStack(stack).join("\r\n")
  5955. : renderStack(stack).join("\r\n")
  5956. ),
  5957. ])(r.message, r.errorSack, r.fiberStack)
  5958. )
  5959. function renderFrame(r) {
  5960. return r
  5961. ? r.name
  5962. ? ` at ${r.name} (${r.fileName}:${r.line}:${r.column})`
  5963. : ` at ${r.fileName}:${r.line}:${r.column}`
  5964. : " at <unknown>"
  5965. }
  5966. const LoggerTypeId = Symbol.for("@effect/io/Logger"),
  5967. loggerVariance = { _Message: _ => _, _Output: _ => _ },
  5968. makeLogger = log => ({ [LoggerTypeId]: loggerVariance, log }),
  5969. stringLogger = makeLogger(
  5970. (fiberId, logLevel, message, cause, _context, spans, annotations) => {
  5971. const now = new Date(),
  5972. nowMillis = now.getTime()
  5973. let output = [
  5974. `timestamp=${now.toISOString()}`,
  5975. `level=${logLevel.label}`,
  5976. `fiber=${threadName(fiberId)}`,
  5977. ].join(" ")
  5978. if (message.length > 0) {
  5979. output += " message="
  5980. output = appendQuoted(message, output)
  5981. }
  5982. if (null != cause && cause != cause_empty) {
  5983. output += " cause="
  5984. output = appendQuoted(cause_pretty_pretty(cause), output)
  5985. }
  5986. if (Chunk_isNonEmpty(spans)) {
  5987. output += " "
  5988. let first = !0
  5989. for (const span of spans) {
  5990. first ? (first = !1) : (output += " ")
  5991. output += Span_render(nowMillis)(span)
  5992. }
  5993. }
  5994. if (mjs_HashMap_size(annotations) > 0) {
  5995. output += " "
  5996. let first = !0
  5997. for (const [key, value] of annotations) {
  5998. first ? (first = !1) : (output += " ")
  5999. output += filterKeyName(key)
  6000. output += "="
  6001. output = appendQuoted(value, output)
  6002. }
  6003. }
  6004. return output
  6005. }
  6006. ),
  6007. textOnly = /^[^\s"=]+$/,
  6008. appendQuoted = (label, output) =>
  6009. output +
  6010. (label.match(textOnly)
  6011. ? label
  6012. : `"${label.replace(/\\([\s\S])|(")/g, "\\$1$2")}"`),
  6013. filterKeyName = key => key.replace(/[\s="]/g, "_"),
  6014. logger_zip = Function_dual(2, (self, that) =>
  6015. makeLogger(
  6016. (fiberId, logLevel, message, cause, context, spans, annotations) => [
  6017. self.log(
  6018. fiberId,
  6019. logLevel,
  6020. message,
  6021. cause,
  6022. context,
  6023. spans,
  6024. annotations
  6025. ),
  6026. that.log(
  6027. fiberId,
  6028. logLevel,
  6029. message,
  6030. cause,
  6031. context,
  6032. spans,
  6033. annotations
  6034. ),
  6035. ]
  6036. )
  6037. )
  6038. var keyType_a, keyType_b, _g, _h
  6039. const MetricKeyTypeTypeId = Symbol.for("@effect/io/Metric/KeyType"),
  6040. CounterKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Counter"),
  6041. FrequencyKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Frequency"),
  6042. GaugeKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Gauge"),
  6043. HistogramKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Histogram"),
  6044. SummaryKeyTypeTypeId = Symbol.for("effect/io/Metric/KeyType/Summary"),
  6045. metricKeyTypeVariance = { _In: _ => _, _Out: _ => _ }
  6046. class CounterKeyType {
  6047. constructor() {
  6048. this[keyType_a] = metricKeyTypeVariance
  6049. this[keyType_b] = CounterKeyTypeTypeId
  6050. }
  6051. [((keyType_a = MetricKeyTypeTypeId),
  6052. (keyType_b = CounterKeyTypeTypeId),
  6053. symbol)]() {
  6054. return Hash_hash("effect/io/Metric/KeyType/Counter")
  6055. }
  6056. [Equal_symbol](that) {
  6057. return isCounterKey(that)
  6058. }
  6059. }
  6060. class HistogramKeyType {
  6061. constructor(boundaries) {
  6062. this.boundaries = boundaries
  6063. this[_g] = metricKeyTypeVariance
  6064. this[_h] = HistogramKeyTypeTypeId
  6065. }
  6066. [((_g = MetricKeyTypeTypeId), (_h = HistogramKeyTypeTypeId), symbol)]() {
  6067. return combine(Hash_hash(this.boundaries))(
  6068. Hash_hash("effect/io/Metric/KeyType/Histogram")
  6069. )
  6070. }
  6071. [Equal_symbol](that) {
  6072. return isHistogramKey(that) && equals(this.boundaries, that.boundaries)
  6073. }
  6074. }
  6075. const counter = new CounterKeyType(),
  6076. isCounterKey = u =>
  6077. "object" == typeof u && null != u && CounterKeyTypeTypeId in u,
  6078. isFrequencyKey = u =>
  6079. "object" == typeof u && null != u && FrequencyKeyTypeTypeId in u,
  6080. isGaugeKey = u =>
  6081. "object" == typeof u && null != u && GaugeKeyTypeTypeId in u,
  6082. isHistogramKey = u =>
  6083. "object" == typeof u && null != u && HistogramKeyTypeTypeId in u,
  6084. isSummaryKey = u =>
  6085. "object" == typeof u && null != u && SummaryKeyTypeTypeId in u
  6086. var key_a
  6087. const MetricKeyTypeId = Symbol.for("@effect/io/Metric/Key"),
  6088. metricKeyVariance = { _Type: _ => _ }
  6089. class MetricKeyImpl {
  6090. constructor(name, keyType, tags = mjs_HashSet_empty()) {
  6091. this.name = name
  6092. this.keyType = keyType
  6093. this.tags = tags
  6094. this[key_a] = metricKeyVariance
  6095. }
  6096. [((key_a = MetricKeyTypeId), symbol)]() {
  6097. return combine(Hash_hash(this.tags))(
  6098. combine(Hash_hash(this.keyType))(Hash_hash(this.name))
  6099. )
  6100. }
  6101. [Equal_symbol](u) {
  6102. return (
  6103. isMetricKey(u) &&
  6104. this.name === u.name &&
  6105. equals(this.keyType, u.keyType) &&
  6106. equals(this.tags, u.tags)
  6107. )
  6108. }
  6109. }
  6110. const isMetricKey = u =>
  6111. "object" == typeof u && null != u && MetricKeyTypeId in u,
  6112. key_taggedWithLabelSet = Function_dual(2, (self, extraTags) =>
  6113. 0 === mjs_HashSet_size(extraTags)
  6114. ? self
  6115. : new MetricKeyImpl(
  6116. self.name,
  6117. self.keyType,
  6118. mjs_HashSet_union(extraTags)(self.tags)
  6119. )
  6120. )
  6121. var state_a,
  6122. state_b,
  6123. state_c,
  6124. state_d,
  6125. state_e,
  6126. state_f,
  6127. state_g,
  6128. state_h,
  6129. state_j,
  6130. state_k
  6131. const MetricStateTypeId = Symbol.for("@effect/io/Metric/State"),
  6132. CounterStateTypeId = Symbol.for("effect/io/Metric/State/Counter"),
  6133. FrequencyStateTypeId = Symbol.for("effect/io/Metric/State/Frequency"),
  6134. GaugeStateTypeId = Symbol.for("effect/io/Metric/State/Gauge"),
  6135. HistogramStateTypeId = Symbol.for("effect/io/Metric/State/Histogram"),
  6136. SummaryStateTypeId = Symbol.for("effect/io/Metric/State/Summary"),
  6137. metricStateVariance = { _A: _ => _ }
  6138. class CounterState {
  6139. constructor(count) {
  6140. this.count = count
  6141. this[state_a] = metricStateVariance
  6142. this[state_b] = CounterStateTypeId
  6143. }
  6144. [((state_a = MetricStateTypeId),
  6145. (state_b = CounterStateTypeId),
  6146. symbol)]() {
  6147. return combine(Hash_hash(this.count))(
  6148. Hash_hash("effect/io/Metric/State/Counter")
  6149. )
  6150. }
  6151. [Equal_symbol](that) {
  6152. return isCounterState(that) && this.count === that.count
  6153. }
  6154. }
  6155. class FrequencyState {
  6156. constructor(occurrences) {
  6157. this.occurrences = occurrences
  6158. this[state_c] = metricStateVariance
  6159. this[state_d] = FrequencyStateTypeId
  6160. }
  6161. [((state_c = MetricStateTypeId),
  6162. (state_d = FrequencyStateTypeId),
  6163. symbol)]() {
  6164. return combine(Hash_hash(this.occurrences))(
  6165. Hash_hash("effect/io/Metric/State/Frequency")
  6166. )
  6167. }
  6168. [Equal_symbol](that) {
  6169. return (
  6170. isFrequencyState(that) && equals(this.occurrences, that.occurrences)
  6171. )
  6172. }
  6173. }
  6174. class GaugeState {
  6175. constructor(value) {
  6176. this.value = value
  6177. this[state_e] = metricStateVariance
  6178. this[state_f] = GaugeStateTypeId
  6179. }
  6180. [((state_e = MetricStateTypeId),
  6181. (state_f = GaugeStateTypeId),
  6182. symbol)]() {
  6183. return combine(Hash_hash(this.value))(
  6184. Hash_hash("effect/io/Metric/State/Gauge")
  6185. )
  6186. }
  6187. [Equal_symbol](u) {
  6188. return isGaugeState(u) && this.value === u.value
  6189. }
  6190. }
  6191. class HistogramState {
  6192. constructor(buckets, count, min, max, sum) {
  6193. this.buckets = buckets
  6194. this.count = count
  6195. this.min = min
  6196. this.max = max
  6197. this.sum = sum
  6198. this[state_g] = metricStateVariance
  6199. this[state_h] = HistogramStateTypeId
  6200. }
  6201. [((state_g = MetricStateTypeId),
  6202. (state_h = HistogramStateTypeId),
  6203. symbol)]() {
  6204. return combine(Hash_hash(this.sum))(
  6205. combine(Hash_hash(this.max))(
  6206. combine(Hash_hash(this.min))(
  6207. combine(Hash_hash(this.count))(
  6208. combine(Hash_hash(this.buckets))(
  6209. Hash_hash("effect/io/Metric/State/Histogram")
  6210. )
  6211. )
  6212. )
  6213. )
  6214. )
  6215. }
  6216. [Equal_symbol](that) {
  6217. return (
  6218. isHistogramState(that) &&
  6219. equals(this.buckets, that.buckets) &&
  6220. this.count === that.count &&
  6221. this.min === that.min &&
  6222. this.max === that.max &&
  6223. this.sum === that.sum
  6224. )
  6225. }
  6226. }
  6227. class SummaryState {
  6228. constructor(error, quantiles, count, min, max, sum) {
  6229. this.error = error
  6230. this.quantiles = quantiles
  6231. this.count = count
  6232. this.min = min
  6233. this.max = max
  6234. this.sum = sum
  6235. this[state_j] = metricStateVariance
  6236. this[state_k] = SummaryStateTypeId
  6237. }
  6238. [((state_j = MetricStateTypeId),
  6239. (state_k = SummaryStateTypeId),
  6240. symbol)]() {
  6241. return combine(Hash_hash(this.sum))(
  6242. combine(Hash_hash(this.max))(
  6243. combine(Hash_hash(this.min))(
  6244. combine(Hash_hash(this.count))(
  6245. combine(Hash_hash(this.quantiles))(
  6246. combine(Hash_hash(this.error))(
  6247. Hash_hash("effect/io/Metric/State/Summary")
  6248. )
  6249. )
  6250. )
  6251. )
  6252. )
  6253. )
  6254. }
  6255. [Equal_symbol](that) {
  6256. return (
  6257. isSummaryState(that) &&
  6258. this.error === that.error &&
  6259. equals(this.quantiles, that.quantiles) &&
  6260. this.count === that.count &&
  6261. this.min === that.min &&
  6262. this.max === that.max &&
  6263. this.sum === that.sum
  6264. )
  6265. }
  6266. }
  6267. const isCounterState = u =>
  6268. "object" == typeof u && null != u && CounterStateTypeId in u,
  6269. isFrequencyState = u =>
  6270. "object" == typeof u && null != u && FrequencyStateTypeId in u,
  6271. isGaugeState = u =>
  6272. "object" == typeof u && null != u && GaugeStateTypeId in u,
  6273. isHistogramState = u =>
  6274. "object" == typeof u && null != u && HistogramStateTypeId in u,
  6275. isSummaryState = u =>
  6276. "object" == typeof u && null != u && SummaryStateTypeId in u,
  6277. MetricHookTypeId = Symbol.for("@effect/io/Metric/Hook"),
  6278. metricHookVariance = { _In: _ => _, _Out: _ => _ },
  6279. hook_make = (get, update) => ({
  6280. [MetricHookTypeId]: metricHookVariance,
  6281. update,
  6282. get,
  6283. }),
  6284. calculateQuantiles = (error, sortedQuantiles, sortedSamples) => {
  6285. const sampleCount = sortedSamples.length
  6286. if (Chunk_isEmpty(sortedQuantiles)) return Chunk_empty()
  6287. const head = unsafeHead(sortedQuantiles),
  6288. tail = Chunk_drop(1)(sortedQuantiles),
  6289. resolved = Chunk_reduce(
  6290. Chunk_of(
  6291. resolveQuantile(
  6292. error,
  6293. sampleCount,
  6294. Option_none(),
  6295. 0,
  6296. head,
  6297. sortedSamples
  6298. )
  6299. ),
  6300. (accumulator, quantile) => {
  6301. const h = unsafeHead(accumulator)
  6302. return Chunk_append(
  6303. resolveQuantile(
  6304. error,
  6305. sampleCount,
  6306. h.value,
  6307. h.consumed,
  6308. quantile,
  6309. h.rest
  6310. )
  6311. )(accumulator)
  6312. }
  6313. )(tail)
  6314. return Chunk_map(rq => [rq.quantile, rq.value])(resolved)
  6315. },
  6316. resolveQuantile = (
  6317. error,
  6318. sampleCount,
  6319. current,
  6320. consumed,
  6321. quantile,
  6322. rest
  6323. ) => {
  6324. let error_1 = error,
  6325. sampleCount_1 = sampleCount,
  6326. current_1 = current,
  6327. consumed_1 = consumed,
  6328. quantile_1 = quantile,
  6329. rest_1 = rest,
  6330. error_2 = error,
  6331. sampleCount_2 = sampleCount,
  6332. current_2 = current,
  6333. consumed_2 = consumed,
  6334. quantile_2 = quantile,
  6335. rest_2 = rest
  6336. for (;;) {
  6337. if (Chunk_isEmpty(rest_1))
  6338. return {
  6339. quantile: quantile_1,
  6340. value: Option_none(),
  6341. consumed: consumed_1,
  6342. rest: Chunk_empty(),
  6343. }
  6344. if (1 === quantile_1)
  6345. return {
  6346. quantile: quantile_1,
  6347. value: Option_some(unsafeLast(rest_1)),
  6348. consumed: consumed_1 + rest_1.length,
  6349. rest: Chunk_empty(),
  6350. }
  6351. const sameHead = splitWhere(n => n > unsafeHead(rest_1))(rest_1),
  6352. desired = quantile_1 * sampleCount_1,
  6353. allowedError = (error_1 / 2) * desired,
  6354. candConsumed = consumed_1 + sameHead[0].length,
  6355. candError = Math.abs(candConsumed - desired)
  6356. if (candConsumed < desired - allowedError) {
  6357. error_2 = error_1
  6358. sampleCount_2 = sampleCount_1
  6359. current_2 = Chunk_head(rest_1)
  6360. consumed_2 = candConsumed
  6361. quantile_2 = quantile_1
  6362. rest_2 = sameHead[1]
  6363. error_1 = error_2
  6364. sampleCount_1 = sampleCount_2
  6365. current_1 = current_2
  6366. consumed_1 = consumed_2
  6367. quantile_1 = quantile_2
  6368. rest_1 = rest_2
  6369. } else {
  6370. if (candConsumed > desired + allowedError)
  6371. return {
  6372. quantile: quantile_1,
  6373. value: current_1,
  6374. consumed: consumed_1,
  6375. rest: rest_1,
  6376. }
  6377. switch (current_1._tag) {
  6378. case "None":
  6379. error_2 = error_1
  6380. sampleCount_2 = sampleCount_1
  6381. current_2 = Chunk_head(rest_1)
  6382. consumed_2 = candConsumed
  6383. quantile_2 = quantile_1
  6384. rest_2 = sameHead[1]
  6385. error_1 = error_2
  6386. sampleCount_1 = sampleCount_2
  6387. current_1 = current_2
  6388. consumed_1 = consumed_2
  6389. quantile_1 = quantile_2
  6390. rest_1 = rest_2
  6391. continue
  6392. case "Some":
  6393. if (candError < Math.abs(desired - current_1.value)) {
  6394. error_2 = error_1
  6395. sampleCount_2 = sampleCount_1
  6396. current_2 = Chunk_head(rest_1)
  6397. consumed_2 = candConsumed
  6398. quantile_2 = quantile_1
  6399. rest_2 = sameHead[1]
  6400. error_1 = error_2
  6401. sampleCount_1 = sampleCount_2
  6402. current_1 = current_2
  6403. consumed_1 = consumed_2
  6404. quantile_1 = quantile_2
  6405. rest_1 = rest_2
  6406. continue
  6407. }
  6408. return {
  6409. quantile: quantile_1,
  6410. value: Option_some(current_1.value),
  6411. consumed: consumed_1,
  6412. rest: rest_1,
  6413. }
  6414. }
  6415. }
  6416. }
  6417. throw new Error(
  6418. "BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/io/issues"
  6419. )
  6420. },
  6421. MetricPairTypeId = Symbol.for("@effect/io/Metric/Pair"),
  6422. metricPairVariance = { _Type: _ => _ }
  6423. var registry_a
  6424. const MetricRegistryTypeId = Symbol.for("@effect/io/Metric/Registry")
  6425. class MetricRegistryImpl {
  6426. constructor() {
  6427. this[registry_a] = MetricRegistryTypeId
  6428. this.map = new MutableHashMapImpl()
  6429. }
  6430. snapshot() {
  6431. const result = []
  6432. for (const [key, hook] of this.map)
  6433. result.push(
  6434. ((metricKey = key),
  6435. (metricState = hook.get()),
  6436. { [MetricPairTypeId]: metricPairVariance, metricKey, metricState })
  6437. )
  6438. var metricKey, metricState
  6439. return mjs_HashSet_fromIterable(result)
  6440. }
  6441. get(key) {
  6442. const hook = getOrUndefined(MutableHashMap_get(key)(this.map))
  6443. if (null == hook) {
  6444. if (isCounterKey(key.keyType)) return this.getCounter(key)
  6445. if (isGaugeKey(key.keyType)) return this.getGauge(key)
  6446. if (isFrequencyKey(key.keyType)) return this.getFrequency(key)
  6447. if (isHistogramKey(key.keyType)) return this.getHistogram(key)
  6448. if (isSummaryKey(key.keyType)) return this.getSummary(key)
  6449. throw new Error(
  6450. "BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/io/issues"
  6451. )
  6452. }
  6453. return hook
  6454. }
  6455. getCounter(key) {
  6456. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6457. if (null == value) {
  6458. const counter = (_key => {
  6459. let sum = 0
  6460. return hook_make(
  6461. () => new CounterState(sum),
  6462. value => {
  6463. sum += value
  6464. }
  6465. )
  6466. })()
  6467. MutableHashMap_has(key)(this.map) ||
  6468. MutableHashMap_set(key, counter)(this.map)
  6469. value = counter
  6470. }
  6471. return value
  6472. }
  6473. getFrequency(key) {
  6474. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6475. if (null == value) {
  6476. const frequency = (_key => {
  6477. let count = 0
  6478. const values = new Map()
  6479. return hook_make(
  6480. () => {
  6481. return (
  6482. (occurrences = mjs_HashMap_fromIterable(
  6483. Array.from(values.entries()).map(([k, v]) => [k, v])
  6484. )),
  6485. new FrequencyState(occurrences)
  6486. )
  6487. var occurrences
  6488. },
  6489. word => {
  6490. count += 1
  6491. const slotCount = values.get(word) ?? 0
  6492. values.set(word, slotCount + 1)
  6493. }
  6494. )
  6495. })()
  6496. MutableHashMap_has(key)(this.map) ||
  6497. MutableHashMap_set(key, frequency)(this.map)
  6498. value = frequency
  6499. }
  6500. return value
  6501. }
  6502. getGauge(key) {
  6503. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6504. if (null == value) {
  6505. const gauge = ((_key, startAt) => {
  6506. let value = startAt
  6507. return hook_make(
  6508. () => (value => new GaugeState(value))(value),
  6509. v => {
  6510. value = v
  6511. }
  6512. )
  6513. })(0, 0)
  6514. MutableHashMap_has(key)(this.map) ||
  6515. MutableHashMap_set(key, gauge)(this.map)
  6516. value = gauge
  6517. }
  6518. return value
  6519. }
  6520. getHistogram(key) {
  6521. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6522. if (null == value) {
  6523. const histogram = (key => {
  6524. const bounds = key.keyType.boundaries.values,
  6525. size = bounds.length,
  6526. values = Array(size + 1),
  6527. boundaries = Array(size)
  6528. let count = 0,
  6529. sum = 0,
  6530. min = Number.MAX_VALUE,
  6531. max = Number.MIN_VALUE
  6532. mapWithIndex((i, n) => {
  6533. boundaries[i] = n
  6534. })(Chunk_sort(Order)(bounds))
  6535. return hook_make(
  6536. () =>
  6537. ((buckets, count, min, max, sum) =>
  6538. new HistogramState(buckets, count, min, max, sum))(
  6539. (() => {
  6540. const builder = []
  6541. let i = 0,
  6542. cumulated = 0
  6543. for (; i != size; ) {
  6544. const boundary = boundaries[i]
  6545. cumulated += values[i]
  6546. builder.push([boundary, cumulated])
  6547. i += 1
  6548. }
  6549. return Chunk_fromIterable(builder)
  6550. })(),
  6551. count,
  6552. min,
  6553. max,
  6554. sum
  6555. ),
  6556. value => {
  6557. let from = 0,
  6558. to = size
  6559. for (; from !== to; ) {
  6560. const mid = Math.floor(from + (to - from) / 2)
  6561. value <= boundaries[mid] ? (to = mid) : (from = mid)
  6562. to === from + 1 &&
  6563. (value <= boundaries[from] ? (to = from) : (from = to))
  6564. }
  6565. values[from] = values[from] + 1
  6566. count += 1
  6567. sum += value
  6568. value < min && (min = value)
  6569. value > max && (max = value)
  6570. }
  6571. )
  6572. })(key)
  6573. MutableHashMap_has(key)(this.map) ||
  6574. MutableHashMap_set(key, histogram)(this.map)
  6575. value = histogram
  6576. }
  6577. return value
  6578. }
  6579. getSummary(key) {
  6580. let value = getOrUndefined(MutableHashMap_get(key)(this.map))
  6581. if (null == value) {
  6582. const summary = (key => {
  6583. const { error, maxAge, maxSize, quantiles } = key.keyType,
  6584. sortedQuantiles = Chunk_sort(Order)(quantiles),
  6585. values = Array(maxSize)
  6586. let head = 0,
  6587. count = 0,
  6588. sum = 0,
  6589. min = Number.MAX_VALUE,
  6590. max = Number.MIN_VALUE
  6591. return hook_make(
  6592. () =>
  6593. ((error, quantiles, count, min, max, sum) =>
  6594. new SummaryState(error, quantiles, count, min, max, sum))(
  6595. error,
  6596. (now => {
  6597. const builder = []
  6598. let i = 0
  6599. for (; i !== maxSize - 1; ) {
  6600. const item = values[i]
  6601. if (null != item) {
  6602. const [t, v] = item,
  6603. age = millis(now - t)
  6604. age.millis >= 0 && age <= maxAge && builder.push(v)
  6605. }
  6606. i += 1
  6607. }
  6608. return calculateQuantiles(
  6609. error,
  6610. sortedQuantiles,
  6611. Chunk_sort(Order)(Chunk_fromIterable(builder))
  6612. )
  6613. })(Date.now()),
  6614. count,
  6615. min,
  6616. max,
  6617. sum
  6618. ),
  6619. ([value, timestamp]) =>
  6620. ((value, timestamp) => {
  6621. if (maxSize > 0) {
  6622. head += 1
  6623. values[head % maxSize] = [timestamp, value]
  6624. }
  6625. count += 1
  6626. sum += value
  6627. value < min && (min = value)
  6628. value > max && (max = value)
  6629. })(value, timestamp)
  6630. )
  6631. })(key)
  6632. MutableHashMap_has(key)(this.map) ||
  6633. MutableHashMap_set(key, summary)(this.map)
  6634. value = summary
  6635. }
  6636. return value
  6637. }
  6638. }
  6639. registry_a = MetricRegistryTypeId
  6640. const MetricTypeId = Symbol.for("@effect/io/Metric"),
  6641. metricVariance = { _Type: _ => _, _In: _ => _, _Out: _ => _ },
  6642. globalMetricRegistry = globalValue(
  6643. Symbol.for("@effect/io/Metric/globalMetricRegistry"),
  6644. () => new MetricRegistryImpl()
  6645. ),
  6646. metric_counter = name =>
  6647. fromMetricKey((name => new MetricKeyImpl(name, counter))(name)),
  6648. fromMetricKey = key => {
  6649. const hook = extraTags => {
  6650. const fullKey = key_taggedWithLabelSet(extraTags)(key)
  6651. return globalMetricRegistry.get(fullKey)
  6652. }
  6653. return (function (keyType, unsafeUpdate, unsafeValue) {
  6654. const metric = Object.assign(
  6655. methodWithTrace(
  6656. (trace, restore) => effect =>
  6657. core_tap(effect, a =>
  6658. sync(() => restore(unsafeUpdate)(a, mjs_HashSet_empty()))
  6659. ).traced(trace)
  6660. ),
  6661. {
  6662. [MetricTypeId]: metricVariance,
  6663. keyType,
  6664. unsafeUpdate,
  6665. unsafeValue,
  6666. }
  6667. )
  6668. return metric
  6669. })(
  6670. key.keyType,
  6671. (input, extraTags) => hook(extraTags).update(input),
  6672. extraTags => hook(extraTags).get()
  6673. )
  6674. },
  6675. metric_histogram = (name, boundaries) =>
  6676. fromMetricKey(
  6677. ((name, boundaries) =>
  6678. new MetricKeyImpl(
  6679. name,
  6680. (boundaries => new HistogramKeyType(boundaries))(boundaries)
  6681. ))(name, boundaries)
  6682. )
  6683. var boundaries_a
  6684. const MetricBoundariesTypeId = Symbol.for("@effect/io/Metric/Boundaries")
  6685. class MetricBoundariesImpl {
  6686. constructor(values) {
  6687. this.values = values
  6688. this[boundaries_a] = MetricBoundariesTypeId
  6689. }
  6690. [((boundaries_a = MetricBoundariesTypeId), symbol)]() {
  6691. return combine(Hash_hash(this.values))(
  6692. Hash_hash("@effect/io/Metric/Boundaries")
  6693. )
  6694. }
  6695. [Equal_symbol](u) {
  6696. return isMetricBoundaries(u) && equals(this.values, u.values)
  6697. }
  6698. }
  6699. const isMetricBoundaries = u =>
  6700. "object" == typeof u && null != u && MetricBoundariesTypeId in u,
  6701. fromChunk = chunk => {
  6702. const values = (self =>
  6703. unsafeFromArray(
  6704. uniq(
  6705. (self, that) =>
  6706. Hash_hash(self) === Hash_hash(that) && equals(self, that)
  6707. )(toReadonlyArray(self))
  6708. ))(Chunk_concat(Chunk_of(Number.POSITIVE_INFINITY))(chunk))
  6709. return new MetricBoundariesImpl(values)
  6710. },
  6711. exponential = (start, factor, count) => {
  6712. return fromChunk(
  6713. Chunk_map(i => start * Math.pow(factor, i))(
  6714. 0 <= (end = count - 1)
  6715. ? Chunk_makeBy(end - 0 + 1, i => 0 + i)
  6716. : Chunk_of(0)
  6717. )
  6718. )
  6719. var end
  6720. }
  6721. var supervisor_a, supervisor_b, supervisor_d
  6722. const SupervisorTypeId = Symbol.for("@effect/io/Supervisor"),
  6723. supervisorVariance = { _T: _ => _ }
  6724. class ProxySupervisor {
  6725. constructor(underlying, value0) {
  6726. this.underlying = underlying
  6727. this.value0 = value0
  6728. this[supervisor_a] = supervisorVariance
  6729. }
  6730. value() {
  6731. return bodyWithTrace(trace => this.value0().traced(trace))
  6732. }
  6733. onStart(context, effect, parent, fiber) {
  6734. this.underlying.onStart(context, effect, parent, fiber)
  6735. }
  6736. onEnd(value, fiber) {
  6737. this.underlying.onEnd(value, fiber)
  6738. }
  6739. onEffect(fiber, effect) {
  6740. this.underlying.onEffect(fiber, effect)
  6741. }
  6742. onSuspend(fiber) {
  6743. this.underlying.onSuspend(fiber)
  6744. }
  6745. onResume(fiber) {
  6746. this.underlying.onResume(fiber)
  6747. }
  6748. map(f) {
  6749. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  6750. }
  6751. zip(right) {
  6752. return new Zip(this, right)
  6753. }
  6754. }
  6755. supervisor_a = SupervisorTypeId
  6756. class Zip {
  6757. constructor(left, right) {
  6758. this.left = left
  6759. this.right = right
  6760. this[supervisor_b] = supervisorVariance
  6761. }
  6762. value() {
  6763. return bodyWithTrace(trace =>
  6764. core_zip(this.left.value(), this.right.value()).traced(trace)
  6765. )
  6766. }
  6767. onStart(context, effect, parent, fiber) {
  6768. this.left.onStart(context, effect, parent, fiber)
  6769. this.right.onStart(context, effect, parent, fiber)
  6770. }
  6771. onEnd(value, fiber) {
  6772. this.left.onEnd(value, fiber)
  6773. this.right.onEnd(value, fiber)
  6774. }
  6775. onEffect(fiber, effect) {
  6776. this.left.onEffect(fiber, effect)
  6777. this.right.onEffect(fiber, effect)
  6778. }
  6779. onSuspend(fiber) {
  6780. this.left.onSuspend(fiber)
  6781. this.right.onSuspend(fiber)
  6782. }
  6783. onResume(fiber) {
  6784. this.left.onResume(fiber)
  6785. this.right.onResume(fiber)
  6786. }
  6787. map(f) {
  6788. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  6789. }
  6790. zip(right) {
  6791. return new Zip(this, right)
  6792. }
  6793. }
  6794. supervisor_b = SupervisorTypeId
  6795. class Const {
  6796. constructor(effect) {
  6797. this.effect = effect
  6798. this[supervisor_d] = supervisorVariance
  6799. }
  6800. value() {
  6801. return bodyWithTrace(trace => this.effect.traced(trace))
  6802. }
  6803. onStart(_context, _effect, _parent, _fiber) {}
  6804. onEnd(_value, _fiber) {}
  6805. onEffect(_fiber, _effect) {}
  6806. onSuspend(_fiber) {}
  6807. onResume(_fiber) {}
  6808. map(f) {
  6809. return new ProxySupervisor(this, () => core_map(f)(this.value()))
  6810. }
  6811. zip(right) {
  6812. return new Zip(this, right)
  6813. }
  6814. }
  6815. supervisor_d = SupervisorTypeId
  6816. const supervisor_none = (effect => new Const(effect))(core_unit()),
  6817. supervisor_patch_empty = { _tag: "Empty" },
  6818. supervisor_patch_combine = (self, that) => ({
  6819. _tag: "AndThen",
  6820. first: self,
  6821. second: that,
  6822. }),
  6823. removeSupervisor = (self, that) =>
  6824. equals(self, that)
  6825. ? supervisor_none
  6826. : self instanceof Zip
  6827. ? removeSupervisor(self.left, that).zip(
  6828. removeSupervisor(self.right, that)
  6829. )
  6830. : self,
  6831. patch_toSet = self =>
  6832. equals(self, supervisor_none)
  6833. ? mjs_HashSet_empty()
  6834. : self instanceof Zip
  6835. ? mjs_HashSet_union(patch_toSet(self.right))(patch_toSet(self.left))
  6836. : mjs_HashSet_make(self),
  6837. patch_differ = mjs_Differ_make({
  6838. empty: supervisor_patch_empty,
  6839. patch: (self, supervisor) =>
  6840. ((_supervisor, _patches) => {
  6841. let supervisor = _supervisor,
  6842. patches = _patches
  6843. for (; Chunk_isNonEmpty(patches); ) {
  6844. const head = Chunk_headNonEmpty(patches)
  6845. switch (head._tag) {
  6846. case "Empty":
  6847. patches = Chunk_tailNonEmpty(patches)
  6848. break
  6849. case "AddSupervisor":
  6850. supervisor = supervisor.zip(head.supervisor)
  6851. patches = Chunk_tailNonEmpty(patches)
  6852. break
  6853. case "RemoveSupervisor":
  6854. supervisor = removeSupervisor(supervisor, head.supervisor)
  6855. patches = Chunk_tailNonEmpty(patches)
  6856. break
  6857. case "AndThen":
  6858. patches = Chunk_prepend(head.first)(
  6859. Chunk_prepend(head.second)(Chunk_tailNonEmpty(patches))
  6860. )
  6861. }
  6862. }
  6863. return supervisor
  6864. })(supervisor, Chunk_of(self)),
  6865. combine: supervisor_patch_combine,
  6866. diff: (oldValue, newValue) => {
  6867. if (equals(oldValue, newValue)) return supervisor_patch_empty
  6868. const oldSupervisors = patch_toSet(oldValue),
  6869. newSupervisors = patch_toSet(newValue),
  6870. added = mjs_HashSet_reduce(
  6871. supervisor_patch_empty,
  6872. (patch, supervisor) =>
  6873. supervisor_patch_combine(patch, {
  6874. _tag: "AddSupervisor",
  6875. supervisor,
  6876. })
  6877. )(mjs_HashSet_difference(oldSupervisors)(newSupervisors)),
  6878. removed = mjs_HashSet_reduce(
  6879. supervisor_patch_empty,
  6880. (patch, supervisor) =>
  6881. supervisor_patch_combine(patch, {
  6882. _tag: "RemoveSupervisor",
  6883. supervisor,
  6884. })
  6885. )(mjs_HashSet_difference(newSupervisors)(oldSupervisors))
  6886. return supervisor_patch_combine(added, removed)
  6887. },
  6888. })
  6889. var fiberRuntime_a, fiberRuntime_b
  6890. const fibersStarted = metric_counter("effect_fiber_started"),
  6891. fiberSuccesses = metric_counter("effect_fiber_successes"),
  6892. fiberFailures = metric_counter("effect_fiber_failures"),
  6893. fiberLifetimes = metric_histogram(
  6894. "effect_fiber_lifetimes",
  6895. exponential(1, 2, 100)
  6896. ),
  6897. runtimeFiberVariance = { _E: _ => _, _A: _ => _ },
  6898. fiberRuntime_absurd = _ => {
  6899. throw new Error(
  6900. `BUG: FiberRuntime - ${JSON.stringify(
  6901. _
  6902. )} - please report an issue at https://github.com/Effect-TS/io/issues`
  6903. )
  6904. },
  6905. contOpSuccess = {
  6906. OnSuccess: (_, cont, value) => cont.i1(value),
  6907. OnSuccessAndFailure: (_, cont, value) => cont.i2(value),
  6908. RevertFlags: (self, cont, value) => {
  6909. self.patchRuntimeFlags(self._runtimeFlags, cont.patch)
  6910. return interruptible(self._runtimeFlags) && self.isInterrupted()
  6911. ? exitFailCause(self.getInterruptedCause())
  6912. : exitSucceed(value)
  6913. },
  6914. While: (self, cont, value) => {
  6915. cont.i2(value)
  6916. if (cont.i0()) {
  6917. self.pushStack(cont)
  6918. return cont.i1()
  6919. }
  6920. return core_unit()
  6921. },
  6922. },
  6923. drainQueueWhileRunningTable = {
  6924. InterruptSignal: (self, runtimeFlags, cur, message) => {
  6925. self.processNewInterruptSignal(message.cause)
  6926. return interruptible(runtimeFlags)
  6927. ? exitFailCause(message.cause)
  6928. : cur
  6929. },
  6930. Resume: (_self, _runtimeFlags, _cur, _message) => {
  6931. throw new Error(
  6932. "It is illegal to have multiple concurrent run loops in a single fiber"
  6933. )
  6934. },
  6935. Stateful: (self, runtimeFlags, cur, message) => {
  6936. message.onFiber(self, Status_running(runtimeFlags))
  6937. return cur
  6938. },
  6939. YieldNow: (_self, _runtimeFlags, cur, _message) =>
  6940. core_flatMap(() => cur)(yieldNow()),
  6941. }
  6942. class FiberRuntime {
  6943. constructor(fiberId, fiberRefs0, runtimeFlags0) {
  6944. this[fiberRuntime_a] = fiberVariance
  6945. this[fiberRuntime_b] = runtimeFiberVariance
  6946. this._queue = new MutableQueueImpl()
  6947. this._children = null
  6948. this._observers = new Array()
  6949. this._running = !1
  6950. this._stack = []
  6951. this._asyncInterruptor = null
  6952. this._asyncBlockingOn = null
  6953. this._exitValue = null
  6954. this._traceStack = []
  6955. this.run = () => {
  6956. this.drainQueueOnCurrentThread()
  6957. }
  6958. this._runtimeFlags = runtimeFlags0
  6959. this._fiberId = fiberId
  6960. this._fiberRefs = fiberRefs0
  6961. if (runtimeMetrics(runtimeFlags0)) {
  6962. const tags = this.getFiberRef(currentTags)
  6963. fibersStarted.unsafeUpdate(1, tags)
  6964. }
  6965. }
  6966. id() {
  6967. return this._fiberId
  6968. }
  6969. resume(effect) {
  6970. this.tell(resume(effect))
  6971. }
  6972. status() {
  6973. return this.ask((_, status) => status)
  6974. }
  6975. runtimeFlags() {
  6976. return this.ask((state, status) =>
  6977. (self => "Done" === self._tag)(status)
  6978. ? state._runtimeFlags
  6979. : status.runtimeFlags
  6980. )
  6981. }
  6982. scope() {
  6983. return new Local((fiber = this).id(), fiber)
  6984. var fiber
  6985. }
  6986. children() {
  6987. return this.ask(fiber => Chunk_fromIterable(fiber.getChildren()))
  6988. }
  6989. getChildren() {
  6990. null === this._children && (this._children = new Set())
  6991. return this._children
  6992. }
  6993. getSupervisor() {
  6994. return this.getFiberRef(currentSupervisor)
  6995. }
  6996. getInterruptedCause() {
  6997. return this.getFiberRef(interruptedCause)
  6998. }
  6999. fiberRefs() {
  7000. return this.ask(fiber => fiber.unsafeGetFiberRefs())
  7001. }
  7002. ask(f) {
  7003. return untraced(() =>
  7004. suspend(() => {
  7005. const deferred = deferredUnsafeMake(this._fiberId)
  7006. this.tell(
  7007. stateful((fiber, status) => {
  7008. deferredUnsafeDone(
  7009. deferred,
  7010. sync(() => f(fiber, status))
  7011. )
  7012. })
  7013. )
  7014. return deferredAwait(deferred)
  7015. })
  7016. )
  7017. }
  7018. tell(message) {
  7019. offer(message)(this._queue)
  7020. if (!this._running) {
  7021. this._running = !0
  7022. this.drainQueueLaterOnExecutor()
  7023. }
  7024. }
  7025. await() {
  7026. return untraced(() =>
  7027. asyncInterrupt(resume => {
  7028. const cb = exit => resume(succeed(exit))
  7029. this.tell(
  7030. stateful((fiber, _) => {
  7031. null !== fiber._exitValue
  7032. ? cb(this._exitValue)
  7033. : fiber.unsafeAddObserver(cb)
  7034. })
  7035. )
  7036. return sync(() =>
  7037. this.tell(
  7038. stateful((fiber, _) => {
  7039. fiber.unsafeRemoveObserver(cb)
  7040. })
  7041. )
  7042. )
  7043. }, this.id())
  7044. )
  7045. }
  7046. inheritAll() {
  7047. return untraced(() =>
  7048. withFiberRuntime((parentFiber, parentStatus) => {
  7049. const parentFiberId = parentFiber.id(),
  7050. parentFiberRefs = parentFiber.unsafeGetFiberRefs(),
  7051. parentRuntimeFlags = parentStatus.runtimeFlags,
  7052. childFiberRefs = this.unsafeGetFiberRefs(),
  7053. updatedFiberRefs = joinAs(
  7054. parentFiberRefs,
  7055. parentFiberId,
  7056. childFiberRefs
  7057. )
  7058. parentFiber.setFiberRefs(updatedFiberRefs)
  7059. const updatedRuntimeFlags =
  7060. parentFiber.getFiberRef(currentRuntimeFlags),
  7061. patch = Patch_exclude(16)(
  7062. Patch_exclude(1)(
  7063. runtimeFlags_diff(parentRuntimeFlags, updatedRuntimeFlags)
  7064. )
  7065. )
  7066. return updateRuntimeFlags(patch)
  7067. })
  7068. )
  7069. }
  7070. poll() {
  7071. return untraced(() => sync(() => fromNullable(this._exitValue)))
  7072. }
  7073. unsafePoll() {
  7074. return this._exitValue
  7075. }
  7076. interruptAsFork(fiberId) {
  7077. return untraced(() =>
  7078. sync(() => this.tell(interruptSignal(interrupt(fiberId))))
  7079. )
  7080. }
  7081. unsafeAddObserver(observer) {
  7082. null !== this._exitValue
  7083. ? observer(this._exitValue)
  7084. : this._observers.push(observer)
  7085. }
  7086. unsafeRemoveObserver(observer) {
  7087. this._observers = this._observers.filter(o => o !== observer)
  7088. }
  7089. unsafeGetFiberRefs() {
  7090. this.setFiberRef(currentRuntimeFlags, this._runtimeFlags)
  7091. return this._fiberRefs
  7092. }
  7093. unsafeDeleteFiberRef(fiberRef) {
  7094. this._fiberRefs = delete_(this._fiberRefs, fiberRef)
  7095. }
  7096. getFiberRef(fiberRef) {
  7097. return getOrDefault(this._fiberRefs, fiberRef)
  7098. }
  7099. setFiberRef(fiberRef, value) {
  7100. this._fiberRefs = updatedAs(
  7101. this._fiberRefs,
  7102. this._fiberId,
  7103. fiberRef,
  7104. value
  7105. )
  7106. }
  7107. setFiberRefs(fiberRefs) {
  7108. this._fiberRefs = fiberRefs
  7109. }
  7110. addChild(child) {
  7111. this.getChildren().add(child)
  7112. }
  7113. removeChild(child) {
  7114. this.getChildren().delete(child)
  7115. }
  7116. drainQueueOnCurrentThread() {
  7117. let recurse = !0
  7118. for (; recurse; ) {
  7119. let evaluationSignal = "Continue"
  7120. const prev = globalThis[currentFiberURI]
  7121. globalThis[currentFiberURI] = this
  7122. try {
  7123. for (; "Continue" === evaluationSignal; )
  7124. evaluationSignal = MutableQueue_isEmpty(this._queue)
  7125. ? "Done"
  7126. : this.evaluateMessageWhileSuspended(
  7127. MutableQueue_poll(null)(this._queue)
  7128. )
  7129. } finally {
  7130. this._running = !1
  7131. globalThis[currentFiberURI] = prev
  7132. }
  7133. if (MutableQueue_isEmpty(this._queue) || this._running) recurse = !1
  7134. else {
  7135. this._running = !0
  7136. if ("Yield" === evaluationSignal) {
  7137. this.drainQueueLaterOnExecutor()
  7138. recurse = !1
  7139. } else recurse = !0
  7140. }
  7141. }
  7142. }
  7143. drainQueueLaterOnExecutor() {
  7144. this.getFiberRef(currentScheduler).scheduleTask(this.run)
  7145. }
  7146. drainQueueWhileRunning(runtimeFlags, cur0) {
  7147. let cur = cur0
  7148. for (; !MutableQueue_isEmpty(this._queue); ) {
  7149. const message = MutableQueue_poll(void 0)(this._queue)
  7150. cur = drainQueueWhileRunningTable[message._tag](
  7151. this,
  7152. runtimeFlags,
  7153. cur,
  7154. message
  7155. )
  7156. }
  7157. return cur
  7158. }
  7159. isInterrupted() {
  7160. return !(self =>
  7161. "Empty" === self._tag ||
  7162. cause_reduce(self, !0, (acc, cause) => {
  7163. switch (cause._tag) {
  7164. case "Empty":
  7165. return Option_some(acc)
  7166. case "Die":
  7167. case "Fail":
  7168. case "Interrupt":
  7169. return Option_some(!1)
  7170. default:
  7171. return Option_none()
  7172. }
  7173. }))(this.getFiberRef(interruptedCause))
  7174. }
  7175. addInterruptedCause(cause) {
  7176. const oldSC = this.getFiberRef(interruptedCause)
  7177. this.setFiberRef(interruptedCause, sequential(oldSC, cause))
  7178. }
  7179. processNewInterruptSignal(cause) {
  7180. this.addInterruptedCause(cause)
  7181. this.sendInterruptSignalToAllChildren()
  7182. }
  7183. sendInterruptSignalToAllChildren() {
  7184. if (null === this._children || 0 === this._children.size) return !1
  7185. let told = !1
  7186. for (const child of this._children) {
  7187. child.tell(interruptSignal(interrupt(this.id())))
  7188. told = !0
  7189. }
  7190. return told
  7191. }
  7192. interruptAllChildren() {
  7193. if (this.sendInterruptSignalToAllChildren()) {
  7194. const it = this._children.values()
  7195. this._children = null
  7196. let isDone = !1
  7197. const body = () => {
  7198. const next = it.next()
  7199. return next.done
  7200. ? sync(() => {
  7201. isDone = !0
  7202. })
  7203. : core_asUnit(next.value.await())
  7204. }
  7205. return whileLoop(
  7206. () => !isDone,
  7207. () => body(),
  7208. () => {}
  7209. )
  7210. }
  7211. return null
  7212. }
  7213. reportExitValue(exit) {
  7214. if (runtimeMetrics(this._runtimeFlags)) {
  7215. const tags = this.getFiberRef(currentTags)
  7216. switch (exit._tag) {
  7217. case "Success":
  7218. fiberSuccesses.unsafeUpdate(1, tags)
  7219. break
  7220. case "Failure":
  7221. fiberFailures.unsafeUpdate(1, tags)
  7222. }
  7223. }
  7224. if ("Failure" === exit._tag) {
  7225. const level = this.getFiberRef(unhandledErrorLogLevel)
  7226. isInterruptedOnly(exit.cause) ||
  7227. "Some" !== level._tag ||
  7228. this.log(
  7229. "Fiber terminated with a non handled error",
  7230. exit.cause,
  7231. level
  7232. )
  7233. }
  7234. }
  7235. setExitValue(exit) {
  7236. this._exitValue = exit
  7237. if (runtimeMetrics(this._runtimeFlags)) {
  7238. const tags = this.getFiberRef(currentTags),
  7239. startTimeMillis = this.id().startTimeMillis,
  7240. endTimeMillis = new Date().getTime()
  7241. fiberLifetimes.unsafeUpdate(
  7242. (endTimeMillis - startTimeMillis) / 1e3,
  7243. tags
  7244. )
  7245. }
  7246. this.reportExitValue(exit)
  7247. for (let i = this._observers.length - 1; i >= 0; i--)
  7248. this._observers[i](exit)
  7249. }
  7250. getLoggers() {
  7251. return this.getFiberRef(currentLoggers)
  7252. }
  7253. log(message, cause, overrideLogLevel) {
  7254. const logLevel = Option_isSome(overrideLogLevel)
  7255. ? overrideLogLevel.value
  7256. : this.getFiberRef(currentLogLevel),
  7257. spans = this.getFiberRef(currentLogSpan),
  7258. annotations = this.getFiberRef(currentLogAnnotations),
  7259. loggers = this.getLoggers(),
  7260. contextMap = this.unsafeGetFiberRefs()
  7261. mjs_HashSet_forEach(logger => {
  7262. logger.log(
  7263. this.id(),
  7264. logLevel,
  7265. message,
  7266. cause,
  7267. contextMap,
  7268. spans,
  7269. annotations
  7270. )
  7271. })(loggers)
  7272. }
  7273. evaluateMessageWhileSuspended(message) {
  7274. switch (message._tag) {
  7275. case "YieldNow":
  7276. return "Yield"
  7277. case "InterruptSignal":
  7278. this.processNewInterruptSignal(message.cause)
  7279. if (null !== this._asyncInterruptor) {
  7280. this._asyncInterruptor(exitFailCause(message.cause))
  7281. this._asyncInterruptor = null
  7282. }
  7283. return "Continue"
  7284. case "Resume":
  7285. this._asyncInterruptor = null
  7286. this._asyncBlockingOn = null
  7287. this.evaluateEffect(message.effect)
  7288. return "Continue"
  7289. case "Stateful":
  7290. message.onFiber(
  7291. this,
  7292. null !== this._exitValue
  7293. ? Status_done
  7294. : ((runtimeFlags = this._runtimeFlags),
  7295. (blockingOn = this._asyncBlockingOn),
  7296. new Suspended(runtimeFlags, blockingOn))
  7297. )
  7298. return "Continue"
  7299. default:
  7300. return fiberRuntime_absurd(message)
  7301. }
  7302. var runtimeFlags, blockingOn
  7303. }
  7304. evaluateEffect(effect0) {
  7305. this.getSupervisor().onResume(this)
  7306. try {
  7307. let effect =
  7308. interruptible(this._runtimeFlags) && this.isInterrupted()
  7309. ? exitFailCause(this.getInterruptedCause())
  7310. : effect0
  7311. for (; null !== effect; )
  7312. try {
  7313. const exit = this.runLoop(effect)
  7314. this._runtimeFlags = runtimeFlags_enable(16)(this._runtimeFlags)
  7315. const interruption = this.interruptAllChildren()
  7316. if (null !== interruption)
  7317. effect = untraced(() => core_flatMap(interruption, () => exit))
  7318. else {
  7319. MutableQueue_isEmpty(this._queue)
  7320. ? this.setExitValue(exit)
  7321. : this.tell(resume(exit))
  7322. effect = null
  7323. }
  7324. } catch (e) {
  7325. if (!isEffect(e)) throw e
  7326. if ("Yield" === e._tag)
  7327. if (cooperativeYielding(this._runtimeFlags)) {
  7328. this.tell({ _tag: "YieldNow" })
  7329. this.tell(resume(exitUnit()))
  7330. effect = null
  7331. } else effect = exitUnit()
  7332. else "Async" === e._tag && (effect = null)
  7333. }
  7334. } finally {
  7335. this.getSupervisor().onSuspend(this)
  7336. }
  7337. }
  7338. start(effect) {
  7339. if (this._running) this.tell(resume(effect))
  7340. else {
  7341. this._running = !0
  7342. const prev = globalThis[currentFiberURI]
  7343. globalThis[currentFiberURI] = this
  7344. try {
  7345. this.evaluateEffect(effect)
  7346. } finally {
  7347. this._running = !1
  7348. globalThis[currentFiberURI] = prev
  7349. MutableQueue_isEmpty(this._queue) ||
  7350. this.drainQueueLaterOnExecutor()
  7351. }
  7352. }
  7353. }
  7354. startFork(effect) {
  7355. this.tell(resume(effect))
  7356. }
  7357. patchRuntimeFlags(oldRuntimeFlags, patch) {
  7358. const newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, patch)
  7359. globalThis[currentFiberURI] = this
  7360. this._runtimeFlags = newRuntimeFlags
  7361. return newRuntimeFlags
  7362. }
  7363. initiateAsync(runtimeFlags, asyncRegister) {
  7364. let alreadyCalled = !1
  7365. const callback = effect => {
  7366. if (!alreadyCalled) {
  7367. alreadyCalled = !0
  7368. this.tell(resume(effect))
  7369. }
  7370. }
  7371. interruptible(runtimeFlags) && (this._asyncInterruptor = callback)
  7372. try {
  7373. asyncRegister(callback)
  7374. } catch (e) {
  7375. callback(failCause(die(e)))
  7376. }
  7377. }
  7378. pushStack(cont) {
  7379. this._stack.push(cont)
  7380. "trace" in cont && cont.trace && this._traceStack.push(cont.trace)
  7381. }
  7382. popStack() {
  7383. const item = this._stack.pop()
  7384. if (item) {
  7385. "trace" in item && item.trace && this._traceStack.pop()
  7386. return item
  7387. }
  7388. }
  7389. getNextSuccessCont() {
  7390. let frame = this.popStack()
  7391. for (; frame; ) {
  7392. if ("OnFailure" !== frame._tag && "Traced" !== frame._tag)
  7393. return frame
  7394. frame = this.popStack()
  7395. }
  7396. }
  7397. getNextFailCont() {
  7398. let frame = this.popStack()
  7399. for (; frame; ) {
  7400. if (
  7401. "OnSuccess" !== frame._tag &&
  7402. "While" !== frame._tag &&
  7403. "Traced" !== frame._tag
  7404. )
  7405. return frame
  7406. frame = this.popStack()
  7407. }
  7408. }
  7409. [((fiberRuntime_a = FiberTypeId),
  7410. (fiberRuntime_b = RuntimeFiberTypeId),
  7411. "Tag")](op) {
  7412. return core_map(fiberRefGet(currentContext), context =>
  7413. mjs_Context_unsafeGet(context, op)
  7414. )
  7415. }
  7416. Left(op) {
  7417. return exitFail(op.i0)
  7418. }
  7419. None(_) {
  7420. return exitFail(NoSuchElementException())
  7421. }
  7422. Right(op) {
  7423. return exitSucceed(op.i0)
  7424. }
  7425. Some(op) {
  7426. return exitSucceed(op.i0)
  7427. }
  7428. Sync(op) {
  7429. const value = op.i0(),
  7430. cont = this.getNextSuccessCont()
  7431. if (void 0 !== cont) {
  7432. cont._tag in contOpSuccess || fiberRuntime_absurd(cont)
  7433. return contOpSuccess[cont._tag](this, cont, value)
  7434. }
  7435. throw exitSucceed(value)
  7436. }
  7437. Success(op) {
  7438. const oldCur = op,
  7439. cont = this.getNextSuccessCont()
  7440. if (void 0 !== cont) {
  7441. cont._tag in contOpSuccess || fiberRuntime_absurd(cont)
  7442. return contOpSuccess[cont._tag](this, cont, oldCur.i0)
  7443. }
  7444. throw oldCur
  7445. }
  7446. Failure(op) {
  7447. let cause = op.i0
  7448. if (
  7449. (self => "Annotated" === self._tag)(cause) &&
  7450. isStackAnnotation(cause.annotation)
  7451. ) {
  7452. const stack = cause.annotation.stack,
  7453. currentStack = this.stackToLines()
  7454. cause = annotated(
  7455. cause.cause,
  7456. new StackAnnotation(
  7457. Chunk_take(runtimeDebug.traceStackLimit)(
  7458. dedupeAdjacent(
  7459. 0 === stack.length
  7460. ? currentStack
  7461. : 0 === currentStack.length ||
  7462. unsafeLast(stack) === unsafeLast(currentStack)
  7463. ? stack
  7464. : Chunk_concat(currentStack)(stack)
  7465. )
  7466. ),
  7467. cause.annotation.seq
  7468. )
  7469. )
  7470. } else
  7471. cause = annotated(
  7472. op.i0,
  7473. new StackAnnotation(
  7474. this.stackToLines(),
  7475. (self => getAndUpdate(self, n => n + 1))(globalErrorSeq)
  7476. )
  7477. )
  7478. const cont = this.getNextFailCont()
  7479. if (void 0 === cont) throw exitFailCause(cause)
  7480. switch (cont._tag) {
  7481. case "OnFailure":
  7482. case "OnSuccessAndFailure":
  7483. return interruptible(this._runtimeFlags) && this.isInterrupted()
  7484. ? exitFailCause(stripFailures(cause))
  7485. : cont.i1(cause)
  7486. case "RevertFlags":
  7487. this.patchRuntimeFlags(this._runtimeFlags, cont.patch)
  7488. return interruptible(this._runtimeFlags) && this.isInterrupted()
  7489. ? exitFailCause(sequential(cause, this.getInterruptedCause()))
  7490. : exitFailCause(cause)
  7491. default:
  7492. fiberRuntime_absurd(cont)
  7493. }
  7494. }
  7495. WithRuntime(op) {
  7496. return op.i0(this, Status_running(this._runtimeFlags))
  7497. }
  7498. UpdateRuntimeFlags(op) {
  7499. if (void 0 === op.i1) {
  7500. this.patchRuntimeFlags(this._runtimeFlags, op.i0)
  7501. return exitUnit()
  7502. }
  7503. {
  7504. const updateFlags = op.i0,
  7505. oldRuntimeFlags = this._runtimeFlags,
  7506. newRuntimeFlags = runtimeFlags_patch(oldRuntimeFlags, updateFlags)
  7507. if (newRuntimeFlags === oldRuntimeFlags) return op.i1(oldRuntimeFlags)
  7508. if (interruptible(newRuntimeFlags) && this.isInterrupted())
  7509. return exitFailCause(this.getInterruptedCause())
  7510. {
  7511. this.patchRuntimeFlags(this._runtimeFlags, updateFlags)
  7512. const revertFlags = runtimeFlags_diff(
  7513. newRuntimeFlags,
  7514. oldRuntimeFlags
  7515. )
  7516. this.pushStack(new RevertFlags(revertFlags))
  7517. return op.i1(oldRuntimeFlags)
  7518. }
  7519. }
  7520. }
  7521. OnSuccess(op) {
  7522. this.pushStack(op)
  7523. return op.i0
  7524. }
  7525. Traced(op) {
  7526. this.pushStack(op)
  7527. return op.i0
  7528. }
  7529. OnFailure(op) {
  7530. this.pushStack(op)
  7531. return op.i0
  7532. }
  7533. OnSuccessAndFailure(op) {
  7534. this.pushStack(op)
  7535. return op.i0
  7536. }
  7537. Async(op) {
  7538. this._asyncBlockingOn = op.i1
  7539. this.initiateAsync(this._runtimeFlags, op.i0)
  7540. throw op
  7541. }
  7542. Yield(op) {
  7543. throw op
  7544. }
  7545. While(op) {
  7546. const check = op.i0,
  7547. body = op.i1
  7548. if (check()) {
  7549. this.pushStack(op)
  7550. return body()
  7551. }
  7552. return exitUnit()
  7553. }
  7554. Commit(op) {
  7555. return op.commit()
  7556. }
  7557. runLoop(effect0) {
  7558. let cur = effect0,
  7559. ops = 0
  7560. for (;;) {
  7561. opSupervision(this._runtimeFlags) &&
  7562. this.getSupervisor().onEffect(this, cur)
  7563. cur = this.drainQueueWhileRunning(this._runtimeFlags, cur)
  7564. ops += 1
  7565. if (ops >= 2048) {
  7566. ops = 0
  7567. const oldCur = cur
  7568. cur = core_flatMap(() => oldCur)(yieldNow())
  7569. }
  7570. try {
  7571. cur._tag in this || fiberRuntime_absurd(cur)
  7572. cur = this[cur._tag](cur)
  7573. } catch (e) {
  7574. if (isEffect(e)) {
  7575. if ("Yield" === e._tag || "Async" === e._tag) throw e
  7576. if ("Success" === e._tag || "Failure" === e._tag) return e
  7577. } else
  7578. cur = isEffectError(e)
  7579. ? exitFailCause(e.cause)
  7580. : isInterruptedException(e)
  7581. ? exitFailCause(sequential(die(e), interrupt(Id_none)))
  7582. : exitFailCause(die(e))
  7583. }
  7584. }
  7585. }
  7586. stackToLines() {
  7587. if (0 === this._traceStack.length) return Chunk_empty()
  7588. const lines = []
  7589. let current = this._traceStack.length - 1
  7590. for (; current >= 0 && lines.length < runtimeDebug.traceStackLimit; ) {
  7591. const value = this._traceStack[current]
  7592. lines.push(value)
  7593. current -= 1
  7594. }
  7595. return unsafeFromArray(lines)
  7596. }
  7597. }
  7598. const currentMinimumLogLevel = fiberRefUnsafeMake(
  7599. fromLiteral(runtimeDebug.minumumLogLevel)
  7600. ),
  7601. defaultLogger = makeLogger(
  7602. (fiberId, logLevel, message, cause, context, spans, annotations) => {
  7603. const formatted = stringLogger.log(
  7604. fiberId,
  7605. logLevel,
  7606. message,
  7607. cause,
  7608. context,
  7609. spans,
  7610. annotations
  7611. ),
  7612. filter = getOrDefault(context, currentMinimumLogLevel)
  7613. greaterThanEqual(filter)(logLevel) &&
  7614. globalThis.console.log(formatted)
  7615. }
  7616. ),
  7617. currentLoggers = fiberRefUnsafeMakeHashSet(
  7618. mjs_HashSet_make(defaultLogger)
  7619. ),
  7620. acquireRelease = dualWithTrace(
  7621. 2,
  7622. (trace, restore) => (acquire, release) =>
  7623. uninterruptible(
  7624. core_tap(acquire, a =>
  7625. addFinalizer(exit => restore(release)(a, exit))
  7626. )
  7627. ).traced(trace)
  7628. ),
  7629. addFinalizer = methodWithTrace(
  7630. (trace, restore) => finalizer =>
  7631. core_flatMap(context(), context =>
  7632. core_flatMap(scope(), scope =>
  7633. scopeAddFinalizerExit(scope, exit =>
  7634. core_asUnit(provideContext(context)(restore(finalizer)(exit)))
  7635. )
  7636. )
  7637. ).traced(trace)
  7638. ),
  7639. forEachPar = dualWithTrace(
  7640. 2,
  7641. (trace, restore) => (self, f) =>
  7642. fiberRefGetWith(currentParallelism, o =>
  7643. "None" === o._tag
  7644. ? forEachParUnbounded(self, restore(f))
  7645. : forEachParN(self, o.value, f)
  7646. ).traced(trace)
  7647. ),
  7648. forEachParUnbounded = (self, f) =>
  7649. suspend(() => {
  7650. const as = Array.from(self).map((v, i) => [v, i]),
  7651. array = new Array(as.length)
  7652. return core_zipRight(
  7653. forEachParUnboundedDiscard(as, ([a, i]) =>
  7654. core_flatMap(f(a), b => sync(() => (array[i] = b)))
  7655. ),
  7656. succeed(unsafeFromArray(array))
  7657. )
  7658. }),
  7659. forEachParUnboundedDiscard = (self, f) =>
  7660. suspend(() => {
  7661. const as = Array.from(self),
  7662. size = as.length
  7663. return 0 === size
  7664. ? core_unit()
  7665. : 1 === size
  7666. ? core_asUnit(f(as[0]))
  7667. : uninterruptibleMask(restore => {
  7668. const deferred = deferredUnsafeMake(Id_none)
  7669. let ref = 0
  7670. const process = transplant(graft =>
  7671. core_forEach(as, a =>
  7672. forkDaemon(
  7673. graft(
  7674. matchCauseEffect(
  7675. cause =>
  7676. core_zipRight(
  7677. deferredFail(deferred, void 0),
  7678. failCause(cause)
  7679. ),
  7680. () => {
  7681. ref + 1 === size
  7682. ? deferredUnsafeDone(deferred, core_unit())
  7683. : (ref += 1)
  7684. return core_unit()
  7685. }
  7686. )(restore(suspend(() => f(a))))
  7687. )
  7688. )
  7689. )
  7690. )
  7691. return core_flatMap(process, fibers =>
  7692. matchCauseEffect(
  7693. restore(deferredAwait(deferred)),
  7694. cause =>
  7695. core_flatMap(
  7696. forEachParUnbounded(fibers, interruptFiber),
  7697. exits => {
  7698. const exit = exitCollectAllPar(exits)
  7699. return "Some" === exit._tag &&
  7700. (self => "Failure" === self._tag)(exit.value)
  7701. ? failCause(
  7702. parallel(stripFailures(cause), exit.value.i0)
  7703. )
  7704. : failCause(stripFailures(cause))
  7705. }
  7706. ),
  7707. () => forEachDiscard(fibers, f => f.inheritAll())
  7708. )
  7709. )
  7710. })
  7711. }),
  7712. forEachParN = (self, n, f) =>
  7713. suspend(() => {
  7714. const as = Array.from(self).map((v, i) => [v, i]),
  7715. array = new Array(as.length)
  7716. return core_zipRight(
  7717. forEachParNDiscard(as, n, ([a, i]) =>
  7718. core_map(f(a), b => (array[i] = b))
  7719. ),
  7720. succeed(unsafeFromArray(array))
  7721. )
  7722. }),
  7723. forEachParNDiscard = (self, n, f) =>
  7724. suspend(() => {
  7725. const iterator = self[Symbol.iterator](),
  7726. worker = core_flatMap(
  7727. sync(() => iterator.next()),
  7728. next =>
  7729. next.done
  7730. ? core_unit()
  7731. : core_flatMap(core_asUnit(f(next.value)), () => worker)
  7732. ),
  7733. effects = []
  7734. for (let i = 0; i < n; i++) effects.push(worker)
  7735. return forEachParUnboundedDiscard(effects, Function_identity)
  7736. }),
  7737. forkDaemon = methodWithTrace(
  7738. trace => self => forkWithScopeOverride(self, globalScope).traced(trace)
  7739. ),
  7740. unsafeMakeChildFiber = (
  7741. effect,
  7742. parentFiber,
  7743. parentRuntimeFlags,
  7744. overrideScope = null
  7745. ) => {
  7746. const childId = Id_unsafeMake(),
  7747. parentFiberRefs = parentFiber.unsafeGetFiberRefs(),
  7748. childFiberRefs = forkAs(parentFiberRefs, childId),
  7749. childFiber = new FiberRuntime(
  7750. childId,
  7751. childFiberRefs,
  7752. parentRuntimeFlags
  7753. ),
  7754. childContext = getOrDefault(childFiberRefs, currentContext),
  7755. supervisor = childFiber.getSupervisor()
  7756. supervisor.onStart(
  7757. childContext,
  7758. effect,
  7759. Option_some(parentFiber),
  7760. childFiber
  7761. )
  7762. childFiber.unsafeAddObserver(exit => supervisor.onEnd(exit, childFiber))
  7763. ;(null !== overrideScope
  7764. ? overrideScope
  7765. : getOrElse(() => parentFiber.scope())(
  7766. parentFiber.getFiberRef(forkScopeOverride)
  7767. )
  7768. ).add(parentRuntimeFlags, childFiber)
  7769. return childFiber
  7770. },
  7771. forkWithScopeOverride = (self, scopeOverride) =>
  7772. withFiberRuntime((parentFiber, parentStatus) =>
  7773. succeed(
  7774. ((
  7775. effect,
  7776. parentFiber,
  7777. parentRuntimeFlags,
  7778. overrideScope = null
  7779. ) => {
  7780. const childFiber = unsafeMakeChildFiber(
  7781. effect,
  7782. parentFiber,
  7783. parentRuntimeFlags,
  7784. overrideScope
  7785. )
  7786. childFiber.resume(effect)
  7787. return childFiber
  7788. })(self, parentFiber, parentStatus.runtimeFlags, scopeOverride)
  7789. )
  7790. ),
  7791. scope = methodWithTrace(trace => () => scopeTag.traced(trace)),
  7792. scopeWith = methodWithTrace(
  7793. (trace, restore) => f =>
  7794. core_flatMap(scopeTag, restore(f)).traced(trace)
  7795. ),
  7796. fiberRuntime_some = methodWithTrace(
  7797. trace => self =>
  7798. matchEffect(
  7799. self,
  7800. e => core_fail(Option_some(e)),
  7801. option => {
  7802. switch (option._tag) {
  7803. case "None":
  7804. return core_fail(Option_none())
  7805. case "Some":
  7806. return succeed(option.value)
  7807. }
  7808. }
  7809. ).traced(trace)
  7810. ),
  7811. unsome = methodWithTrace(
  7812. trace => self =>
  7813. matchEffect(
  7814. self,
  7815. option => {
  7816. switch (option._tag) {
  7817. case "None":
  7818. return succeed(Option_none())
  7819. case "Some":
  7820. return core_fail(option.value)
  7821. }
  7822. },
  7823. a => succeed(Option_some(a))
  7824. ).traced(trace)
  7825. ),
  7826. scopeTag = Tag(),
  7827. scopeMake = methodWithTrace(
  7828. trace =>
  7829. (strategy = ExecutionStrategy_sequential) =>
  7830. core_map(releaseMapMake(), rm => ({
  7831. [ScopeTypeId]: ScopeTypeId,
  7832. [CloseableScopeTypeId]: CloseableScopeTypeId,
  7833. fork: strategy =>
  7834. bodyWithTrace(trace =>
  7835. uninterruptible(
  7836. core_flatMap(scope =>
  7837. core_as(scope)(
  7838. core_tap(fin => scopeAddFinalizerExit(scope, fin))(
  7839. releaseMapAdd(exit => scopeClose(scope, exit))(rm)
  7840. )
  7841. )
  7842. )(scopeMake(strategy))
  7843. ).traced(trace)
  7844. ),
  7845. close: exit =>
  7846. bodyWithTrace(trace =>
  7847. core_asUnit(
  7848. (
  7849. (strategy, exit) => self =>
  7850. suspend(() => {
  7851. switch (self.state._tag) {
  7852. case "Exited":
  7853. return core_unit()
  7854. case "Running": {
  7855. const finalizersMap = self.state.finalizers,
  7856. update = self.state.update,
  7857. finalizers = Array.from(finalizersMap.keys())
  7858. .sort((a, b) => b - a)
  7859. .map(key => finalizersMap.get(key))
  7860. self.state = {
  7861. _tag: "Exited",
  7862. nextKey: self.state.nextKey,
  7863. exit,
  7864. update,
  7865. }
  7866. return (self => "Sequential" === self._tag)(
  7867. strategy
  7868. )
  7869. ? core_flatMap(results =>
  7870. getOrElse(() => exitUnit())(
  7871. Option_map(exitAsUnit)(
  7872. exitCollectAllInternal(
  7873. results,
  7874. sequential
  7875. )
  7876. )
  7877. )
  7878. )(
  7879. core_forEach(fin =>
  7880. core_exit(update(fin)(exit))
  7881. )(finalizers)
  7882. )
  7883. : (self => "Parallel" === self._tag)(strategy)
  7884. ? core_flatMap(results =>
  7885. getOrElse(() => exitUnit())(
  7886. Option_map(exitAsUnit)(
  7887. exitCollectAllPar(results)
  7888. )
  7889. )
  7890. )(
  7891. forEachPar(fin =>
  7892. core_exit(update(fin)(exit))
  7893. )(finalizers)
  7894. )
  7895. : withParallelism(strategy.parallelism)(
  7896. core_flatMap(results =>
  7897. getOrElse(() => exitUnit())(
  7898. Option_map(exitAsUnit)(
  7899. exitCollectAllPar(results)
  7900. )
  7901. )
  7902. )(
  7903. forEachPar(fin =>
  7904. core_exit(update(fin)(exit))
  7905. )(finalizers)
  7906. )
  7907. )
  7908. }
  7909. }
  7910. })
  7911. )(
  7912. strategy,
  7913. exit
  7914. )(rm)
  7915. ).traced(trace)
  7916. ),
  7917. addFinalizer: fin =>
  7918. bodyWithTrace(trace =>
  7919. core_asUnit(releaseMapAdd(fin)(rm)).traced(trace)
  7920. ),
  7921. })).traced(trace)
  7922. ),
  7923. scopeExtend = dualWithTrace(2, trace => (effect, scope) => {
  7924. return contramapContext(
  7925. effect,
  7926. mjs_Context_merge(
  7927. ((tag = scopeTag),
  7928. (service = scope),
  7929. new ContextImpl(new Map([[tag, service]])))
  7930. )
  7931. ).traced(trace)
  7932. var tag, service
  7933. }),
  7934. fiberRefUnsafeMakeSupervisor = initial =>
  7935. fiberRefUnsafeMakePatch(initial, patch_differ, supervisor_patch_empty),
  7936. fiberRefLocallyScoped = dualWithTrace(
  7937. 2,
  7938. trace => (self, value) =>
  7939. core_asUnit(
  7940. acquireRelease(
  7941. core_flatMap(oldValue =>
  7942. core_as(oldValue)(fiberRefSet(self, value))
  7943. )(fiberRefGet(self)),
  7944. oldValue => fiberRefSet(self, oldValue)
  7945. )
  7946. ).traced(trace)
  7947. ),
  7948. fiberRefLocallyScopedWith = dualWithTrace(
  7949. 2,
  7950. (trace, restore) => (self, f) =>
  7951. fiberRefGetWith(self, a =>
  7952. fiberRefLocallyScoped(self, restore(f)(a))
  7953. ).traced(trace)
  7954. ),
  7955. currentRuntimeFlags = fiberRefUnsafeMakeRuntimeFlags(runtimeFlags_none),
  7956. currentSupervisor = fiberRefUnsafeMakeSupervisor(supervisor_none),
  7957. fiberInterruptFork = methodWithTrace(
  7958. trace => self =>
  7959. core_asUnit(forkDaemon(interruptFiber(self))).traced(trace)
  7960. ),
  7961. IntervalTypeId = Symbol.for("@effect/io/Schedule/Interval"),
  7962. interval_empty = {
  7963. [IntervalTypeId]: IntervalTypeId,
  7964. startMillis: 0,
  7965. endMillis: 0,
  7966. },
  7967. Interval_empty = interval_empty,
  7968. Interval_after = startMilliseconds => {
  7969. return (
  7970. (startMillis = startMilliseconds),
  7971. (endMillis = Number.POSITIVE_INFINITY),
  7972. startMillis > endMillis
  7973. ? interval_empty
  7974. : { [IntervalTypeId]: IntervalTypeId, startMillis, endMillis }
  7975. )
  7976. var startMillis, endMillis
  7977. },
  7978. IntervalsTypeId = Symbol.for("@effect/io/Schedule/Intervals"),
  7979. Intervals_make = intervals => ({
  7980. [IntervalsTypeId]: IntervalsTypeId,
  7981. intervals,
  7982. }),
  7983. Intervals_start = self =>
  7984. getOrElse(() => Interval_empty)(Chunk_head(self.intervals)).startMillis,
  7985. Decision_continueWith = interval => ({
  7986. _tag: "Continue",
  7987. intervals: Intervals_make(Chunk_of(interval)),
  7988. })
  7989. var schedule_a, schedule_b
  7990. const ScheduleTypeId = Symbol.for("@effect/io/Schedule"),
  7991. ScheduleDriverTypeId = Symbol.for("@effect/io/Schedule/Driver"),
  7992. scheduleVariance = { _Env: _ => _, _In: _ => _, _Out: _ => _ },
  7993. scheduleDriverVariance = { _Env: _ => _, _In: _ => _, _Out: _ => _ }
  7994. class ScheduleImpl {
  7995. constructor(initial, step) {
  7996. this.initial = initial
  7997. this.step = step
  7998. this[schedule_a] = scheduleVariance
  7999. }
  8000. }
  8001. schedule_a = ScheduleTypeId
  8002. class ScheduleDriverImpl {
  8003. constructor(schedule, ref) {
  8004. this.schedule = schedule
  8005. this.ref = ref
  8006. this[schedule_b] = scheduleDriverVariance
  8007. }
  8008. state() {
  8009. return bodyWithTrace(trace =>
  8010. core_map(Ref_get(this.ref), tuple => tuple[1]).traced(trace)
  8011. )
  8012. }
  8013. last() {
  8014. return bodyWithTrace(trace =>
  8015. core_flatMap(Ref_get(this.ref), ([element, _]) => {
  8016. switch (element._tag) {
  8017. case "None":
  8018. return failSync(() => NoSuchElementException())
  8019. case "Some":
  8020. return succeed(element.value)
  8021. }
  8022. }).traced(trace)
  8023. )
  8024. }
  8025. reset() {
  8026. return bodyWithTrace(trace =>
  8027. Ref_set(this.ref, [Option_none(), this.schedule.initial]).traced(
  8028. trace
  8029. )
  8030. )
  8031. }
  8032. next(input) {
  8033. return bodyWithTrace((trace, restore) =>
  8034. core_flatMap(state =>
  8035. core_flatMap(now =>
  8036. core_flatMap(([state, out, decision]) =>
  8037. (self => "Done" === self._tag)(decision)
  8038. ? core_zipRight(core_fail(Option_none()))(
  8039. Ref_set(this.ref, [Option_some(out), state])
  8040. )
  8041. : core_as(out)(
  8042. core_zipRight(
  8043. effect_sleep(
  8044. millis(Intervals_start(decision.intervals) - now)
  8045. )
  8046. )(Ref_set(this.ref, [Option_some(out), state]))
  8047. )
  8048. )(suspend(restore(() => this.schedule.step(now, input, state))))
  8049. )(Clock_currentTimeMillis())
  8050. )(core_map(Ref_get(this.ref), tuple => tuple[1])).traced(trace)
  8051. )
  8052. }
  8053. }
  8054. schedule_b = ScheduleDriverTypeId
  8055. const makeWithState = untracedMethod(
  8056. restore => (initial, step) => new ScheduleImpl(initial, restore(step))
  8057. ),
  8058. driver = methodWithTrace(
  8059. trace => self =>
  8060. core_map(ref => new ScheduleDriverImpl(self, ref))(
  8061. Ref_make([Option_none(), self.initial])
  8062. ).traced(trace)
  8063. ),
  8064. fixed = untracedMethod(
  8065. () => interval =>
  8066. makeWithState([Option_none(), 0], (now, _, [option, n]) =>
  8067. sync(() => {
  8068. const intervalMillis = interval.millis
  8069. switch (option._tag) {
  8070. case "None":
  8071. return [
  8072. [Option_some([now, now + intervalMillis]), n + 1],
  8073. n,
  8074. Decision_continueWith(Interval_after(now + intervalMillis)),
  8075. ]
  8076. case "Some": {
  8077. const [startMillis, lastRun] = option.value,
  8078. runningBehind = now > lastRun + intervalMillis,
  8079. boundary = equals(interval, zero)
  8080. ? interval
  8081. : millis(
  8082. intervalMillis -
  8083. ((now - startMillis) % intervalMillis)
  8084. ),
  8085. sleepTime = equals(boundary, zero) ? interval : boundary,
  8086. nextRun = runningBehind ? now : now + sleepTime.millis
  8087. return [
  8088. [Option_some([startMillis, nextRun]), n + 1],
  8089. n,
  8090. Decision_continueWith(Interval_after(nextRun)),
  8091. ]
  8092. }
  8093. }
  8094. })
  8095. )
  8096. ),
  8097. repeat_Effect = dualWithTrace(
  8098. 2,
  8099. trace => (self, schedule) =>
  8100. repeatOrElse_Effect(self, schedule, (e, _) => core_fail(e)).traced(
  8101. trace
  8102. )
  8103. ),
  8104. repeatOrElse_Effect = dualWithTrace(
  8105. 3,
  8106. (trace, restore) => (self, schedule, orElse) =>
  8107. core_map(
  8108. repeatOrElseEither_Effect(self, schedule, restore(orElse)),
  8109. merge
  8110. ).traced(trace)
  8111. ),
  8112. repeatOrElseEither_Effect = dualWithTrace(
  8113. 3,
  8114. (trace, restore) => (self, schedule, orElse) =>
  8115. core_flatMap(driver(schedule), driver =>
  8116. matchEffect(
  8117. self,
  8118. error =>
  8119. core_map(Either_left)(restore(orElse)(error, Option_none())),
  8120. value =>
  8121. repeatOrElseEitherEffectLoop(
  8122. self,
  8123. driver,
  8124. restore(orElse),
  8125. value
  8126. )
  8127. )
  8128. ).traced(trace)
  8129. ),
  8130. repeatOrElseEitherEffectLoop = (self, driver, orElse, value) =>
  8131. matchEffect(
  8132. () => core_map(Either_right)(orDie(driver.last())),
  8133. b =>
  8134. matchEffect(
  8135. error => core_map(Either_left)(orElse(error, Option_some(b))),
  8136. value => repeatOrElseEitherEffectLoop(self, driver, orElse, value)
  8137. )(self)
  8138. )(driver.next(value))
  8139. var circular_b, circular_c
  8140. class Semaphore {
  8141. constructor(permits) {
  8142. this.permits = permits
  8143. this.waiters = new Array()
  8144. this.taken = 0
  8145. this.take = n =>
  8146. bodyWithTrace(trace =>
  8147. asyncInterruptEither(resume => {
  8148. if (this.free < n) {
  8149. const observer = () => {
  8150. if (this.free >= n) {
  8151. const observerIndex = this.waiters.findIndex(
  8152. cb => cb === observer
  8153. )
  8154. ;-1 !== observerIndex &&
  8155. this.waiters.splice(observerIndex, 1)
  8156. this.taken += n
  8157. resume(succeed(n))
  8158. }
  8159. }
  8160. this.waiters.push(observer)
  8161. return Either_left(
  8162. sync(() => {
  8163. const observerIndex = this.waiters.findIndex(
  8164. cb => cb === observer
  8165. )
  8166. ;-1 !== observerIndex &&
  8167. this.waiters.splice(observerIndex, 1)
  8168. })
  8169. )
  8170. }
  8171. this.taken += n
  8172. return Either_right(succeed(n))
  8173. }).traced(trace)
  8174. )
  8175. this.release = n =>
  8176. bodyWithTrace(trace =>
  8177. withFiberRuntime(fiber => {
  8178. this.taken -= n
  8179. fiber.getFiberRef(currentScheduler).scheduleTask(() => {
  8180. this.waiters.forEach(wake => wake())
  8181. })
  8182. return core_unit()
  8183. }).traced(trace)
  8184. )
  8185. this.withPermits = n =>
  8186. bodyWithTrace(
  8187. trace => self =>
  8188. untraced(() =>
  8189. uninterruptibleMask(restore =>
  8190. core_flatMap(restore(this.take(n)), permits =>
  8191. circular_ensuring(restore(self), this.release(permits))
  8192. )
  8193. )
  8194. ).traced(trace)
  8195. )
  8196. }
  8197. get free() {
  8198. return this.permits - this.taken
  8199. }
  8200. }
  8201. const circular_ensuring = dualWithTrace(
  8202. 2,
  8203. trace => (self, finalizer) =>
  8204. uninterruptibleMask(restore =>
  8205. matchCauseEffect(
  8206. restore(self),
  8207. cause1 =>
  8208. matchCauseEffect(
  8209. finalizer,
  8210. cause2 => failCause(sequential(cause1, cause2)),
  8211. () => failCause(cause1)
  8212. ),
  8213. a => core_as(finalizer, a)
  8214. )
  8215. ).traced(trace)
  8216. )
  8217. const zipWithPar = dualWithTrace(
  8218. 3,
  8219. (trace, restoreTrace) => (self, that, f) =>
  8220. uninterruptibleMask(restore =>
  8221. transplant(graft => {
  8222. const deferred = deferredUnsafeMake(Id_none),
  8223. ref = MutableRef_make(!1)
  8224. return core_flatMap(([left, right]) =>
  8225. matchCauseEffect(
  8226. cause =>
  8227. core_zipRight(
  8228. core_flatMap(([left, right]) =>
  8229. exitMatch(
  8230. causes =>
  8231. failCause(parallel(stripFailures(cause), causes)),
  8232. () => failCause(stripFailures(cause))
  8233. )(exitZipWith(right, f, parallel)(left))
  8234. )(core_zip(_await(right))(_await(left)))
  8235. )(
  8236. core_zipRight(fiberInterruptFork(right))(
  8237. fiberInterruptFork(left)
  8238. )
  8239. ),
  8240. () =>
  8241. core_zipWith(
  8242. fiber_join(left),
  8243. fiber_join(right),
  8244. restoreTrace(f)
  8245. )
  8246. )(restore(deferredAwait(deferred)))
  8247. )(
  8248. core_zip(forkZipWithPar(that, graft, restore, deferred, ref))(
  8249. forkZipWithPar(self, graft, restore, deferred, ref)
  8250. )
  8251. )
  8252. })
  8253. ).traced(trace)
  8254. ),
  8255. forkZipWithPar = (self, graft, restore, deferred, ref) =>
  8256. forkDaemon(
  8257. matchCauseEffect(
  8258. graft(restore(self)),
  8259. cause =>
  8260. core_zipRight(deferredFail(deferred, void 0), failCause(cause)),
  8261. value => {
  8262. if (MutableRef_get(ref)) {
  8263. deferredUnsafeDone(deferred, core_unit())
  8264. return succeed(value)
  8265. }
  8266. MutableRef_set(!0)(ref)
  8267. return succeed(value)
  8268. }
  8269. )
  8270. ),
  8271. SynchronizedTypeId = Symbol.for("@effect/io/Ref/Synchronized"),
  8272. synchronizedVariance = { _A: _ => _ }
  8273. class SynchronizedImpl {
  8274. constructor(ref, withLock) {
  8275. this.ref = ref
  8276. this.withLock = withLock
  8277. this[circular_b] = synchronizedVariance
  8278. this[circular_c] = refVariance
  8279. }
  8280. modify(f) {
  8281. return bodyWithTrace((trace, restore) =>
  8282. this.modifyEffect(a => succeed(restore(f)(a))).traced(trace)
  8283. )
  8284. }
  8285. modifyEffect(f) {
  8286. return bodyWithTrace((trace, restore) =>
  8287. this.withLock(
  8288. core_flatMap(([b, a]) => core_as(ref_set(this.ref, a), b))(
  8289. core_flatMap(ref_get(this.ref), restore(f))
  8290. )
  8291. ).traced(trace)
  8292. )
  8293. }
  8294. }
  8295. ;(circular_b = SynchronizedTypeId), (circular_c = RefTypeId)
  8296. const makeSynchronized = methodWithTrace(
  8297. trace => value =>
  8298. sync(() => unsafeMakeSynchronized(value)).traced(trace)
  8299. ),
  8300. unsafeMakeSynchronized = value => {
  8301. const ref = ref_unsafeMake(value),
  8302. sem = new Semaphore(1)
  8303. return new SynchronizedImpl(ref, sem.withPermits(1))
  8304. },
  8305. Cause_fail = fail,
  8306. Cause_failureOrCause = failureOrCause,
  8307. Cause_pretty = cause_pretty_pretty,
  8308. modifyEffect = dualWithTrace(
  8309. 2,
  8310. (trace, restore) => (self, f) =>
  8311. self.modifyEffect(restore(f)).traced(trace)
  8312. ),
  8313. layer_proto = {
  8314. [Symbol.for("@effect/io/Layer")]: {
  8315. _RIn: _ => _,
  8316. _E: _ => _,
  8317. _ROut: _ => _,
  8318. },
  8319. },
  8320. isFresh = self => "Fresh" === self._tag
  8321. class MemoMap {
  8322. constructor(ref) {
  8323. this.ref = ref
  8324. }
  8325. getOrElseMemoize(layer, scope) {
  8326. return core_flatten(
  8327. modifyEffect(this.ref, map => {
  8328. const inMap = map.get(layer)
  8329. if (void 0 !== inMap) {
  8330. const [acquire, release] = inMap,
  8331. cached = onExit(
  8332. exitMatch(
  8333. () => core_unit(),
  8334. () => scopeAddFinalizerExit(scope, release)
  8335. )
  8336. )(
  8337. core_flatMap(([patch, b]) =>
  8338. core_as(b)(patchFiberRefs(patch))
  8339. )(acquire)
  8340. )
  8341. return succeed([cached, map])
  8342. }
  8343. return core_flatMap(observers =>
  8344. core_flatMap(deferred =>
  8345. core_map(finalizerRef => {
  8346. const resource = uninterruptibleMask(restore =>
  8347. core_flatMap(innerScope =>
  8348. core_flatMap(exit => {
  8349. switch (exit._tag) {
  8350. case "Failure":
  8351. return core_zipRight(failCause(exit.i0))(
  8352. core_zipRight(scopeClose(innerScope, exit))(
  8353. deferredFailCause(deferred, exit.i0)
  8354. )
  8355. )
  8356. case "Success":
  8357. return core_as(exit.i0[1])(
  8358. core_zipRight(
  8359. deferredSucceed(deferred, exit.i0)
  8360. )(
  8361. core_zipRight(
  8362. scopeAddFinalizerExit(scope, exit =>
  8363. core_flatMap(finalizer =>
  8364. finalizer(exit)
  8365. )(ref_get(finalizerRef))
  8366. )
  8367. )(
  8368. core_zipRight(
  8369. ref_update(observers, n => n + 1)
  8370. )(
  8371. ref_set(finalizerRef, exit =>
  8372. core_asUnit(
  8373. whenEffect(
  8374. ref_modify(observers, n => [
  8375. 1 === n,
  8376. n - 1,
  8377. ])
  8378. )(scopeClose(innerScope, exit))
  8379. )
  8380. )
  8381. )
  8382. )
  8383. )
  8384. )
  8385. }
  8386. })(
  8387. core_exit(
  8388. restore(
  8389. core_flatMap(withScope(layer, innerScope), f =>
  8390. diffFiberRefs(f(this))
  8391. )
  8392. )
  8393. )
  8394. )
  8395. )(scopeMake())
  8396. ),
  8397. memoized = [
  8398. onExit(
  8399. exitMatchEffect(
  8400. () => core_unit(),
  8401. () => ref_update(observers, n => n + 1)
  8402. )
  8403. )(deferredAwait(deferred)),
  8404. exit =>
  8405. core_flatMap(finalizer => finalizer(exit))(
  8406. ref_get(finalizerRef)
  8407. ),
  8408. ]
  8409. return [
  8410. resource,
  8411. isFresh(layer) ? map : map.set(layer, memoized),
  8412. ]
  8413. })(ref_make(() => core_unit()))
  8414. )(deferredMake())
  8415. )(ref_make(0))
  8416. })
  8417. )
  8418. }
  8419. }
  8420. const buildWithScope = dualWithTrace(
  8421. 2,
  8422. trace => (self, scope) =>
  8423. core_flatMap(
  8424. core_map(ref => new MemoMap(ref))(makeSynchronized(new Map())),
  8425. memoMap => core_flatMap(withScope(self, scope), run => run(memoMap))
  8426. ).traced(trace)
  8427. ),
  8428. withScope = (self, scope) => {
  8429. const op = self
  8430. switch (op._tag) {
  8431. case "ExtendScope":
  8432. return sync(
  8433. () => memoMap =>
  8434. scopeWith(scope => memoMap.getOrElseMemoize(op.layer, scope))
  8435. )
  8436. case "Fold":
  8437. return sync(
  8438. () => memoMap =>
  8439. matchCauseEffect(
  8440. cause => memoMap.getOrElseMemoize(op.failureK(cause), scope),
  8441. value => memoMap.getOrElseMemoize(op.successK(value), scope)
  8442. )(memoMap.getOrElseMemoize(op.layer, scope))
  8443. )
  8444. case "Fresh":
  8445. return sync(() => _ => buildWithScope(scope)(op.layer))
  8446. case "FromEffect":
  8447. return sync(() => _ => op.effect)
  8448. case "ProvideTo":
  8449. return sync(
  8450. () => memoMap =>
  8451. core_flatMap(env =>
  8452. provideContext(env)(
  8453. memoMap.getOrElseMemoize(op.second, scope)
  8454. )
  8455. )(memoMap.getOrElseMemoize(op.first, scope))
  8456. )
  8457. case "Scoped":
  8458. return sync(() => _ => scopeExtend(op.effect, scope))
  8459. case "Suspend":
  8460. return sync(
  8461. () => memoMap => memoMap.getOrElseMemoize(op.evaluate(), scope)
  8462. )
  8463. case "ZipWith":
  8464. return sync(
  8465. () => memoMap =>
  8466. core_zipWith(
  8467. memoMap.getOrElseMemoize(op.second, scope),
  8468. op.zipK
  8469. )(memoMap.getOrElseMemoize(op.first, scope))
  8470. )
  8471. case "ZipWithPar":
  8472. return sync(
  8473. () => memoMap =>
  8474. zipWithPar(
  8475. memoMap.getOrElseMemoize(op.second, scope),
  8476. op.zipK
  8477. )(memoMap.getOrElseMemoize(op.first, scope))
  8478. )
  8479. }
  8480. },
  8481. layer_fail = error => layer_failCause(Cause_fail(error)),
  8482. layer_failCause = cause => fromEffectContext(failCause(cause)),
  8483. layer_flatMap = untracedDual(
  8484. 2,
  8485. restore => (self, f) => matchLayer(self, layer_fail, restore(f))
  8486. )
  8487. function fromEffectContext(effect) {
  8488. const fromEffect = Object.create(layer_proto)
  8489. fromEffect._tag = "FromEffect"
  8490. fromEffect.effect = effect
  8491. return fromEffect
  8492. }
  8493. const matchCauseLayer = untracedDual(
  8494. 3,
  8495. restore => (self, onFailure, onSuccess) => {
  8496. const fold = Object.create(layer_proto)
  8497. fold._tag = "Fold"
  8498. fold.layer = self
  8499. fold.failureK = restore(onFailure)
  8500. fold.successK = restore(onSuccess)
  8501. return fold
  8502. }
  8503. ),
  8504. matchLayer = untracedDual(
  8505. 3,
  8506. restore => (self, onFailure, onSuccess) =>
  8507. matchCauseLayer(
  8508. self,
  8509. cause => {
  8510. const failureOrCause = Cause_failureOrCause(cause)
  8511. switch (failureOrCause._tag) {
  8512. case "Left":
  8513. return restore(onFailure)(failureOrCause.left)
  8514. case "Right":
  8515. return layer_failCause(failureOrCause.right)
  8516. }
  8517. },
  8518. restore(onSuccess)
  8519. )
  8520. ),
  8521. layer_merge = Function_dual(2, (self, that) =>
  8522. layer_zipWithPar(self, that, (a, b) => mjs_Context_merge(b)(a))
  8523. ),
  8524. scopedDiscard = effect =>
  8525. scopedContext(core_as(mjs_Context_empty())(effect)),
  8526. scopedContext = effect => {
  8527. const scoped = Object.create(layer_proto)
  8528. scoped._tag = "Scoped"
  8529. scoped.effect = effect
  8530. return scoped
  8531. },
  8532. layer_zipWithPar = untracedDual(
  8533. 3,
  8534. restore => (self, that, f) =>
  8535. (evaluate => {
  8536. const suspend = Object.create(layer_proto)
  8537. suspend._tag = "Suspend"
  8538. suspend.evaluate = evaluate
  8539. return suspend
  8540. })(() => {
  8541. const zipWithPar = Object.create(layer_proto)
  8542. zipWithPar._tag = "ZipWithPar"
  8543. zipWithPar.first = self
  8544. zipWithPar.second = that
  8545. zipWithPar.zipK = restore(f)
  8546. return zipWithPar
  8547. })
  8548. ),
  8549. provideLayer = dualWithTrace(
  8550. 2,
  8551. trace => (self, layer) =>
  8552. acquireUseRelease(
  8553. scopeMake(),
  8554. scope =>
  8555. core_flatMap(buildWithScope(layer, scope), context =>
  8556. provideContext(self, context)
  8557. ),
  8558. (scope, exit) => scopeClose(scope, exit)
  8559. ).traced(trace)
  8560. ),
  8561. provideSomeLayer = dualWithTrace(
  8562. 2,
  8563. trace => (self, layer) =>
  8564. provideLayer(
  8565. self,
  8566. layer_merge(layer)(fromEffectContext(context()))
  8567. ).traced(trace)
  8568. ),
  8569. withMinimumLogLevel = dualWithTrace(
  8570. 2,
  8571. trace => (self, level) =>
  8572. fiberRefLocally(currentMinimumLogLevel, level)(self).traced(trace)
  8573. ),
  8574. addLogger = methodWithTrace(
  8575. trace => logger =>
  8576. scopedDiscard(
  8577. fiberRefLocallyScopedWith(
  8578. currentLoggers,
  8579. mjs_HashSet_add(logger)
  8580. ).traced(trace)
  8581. )
  8582. ),
  8583. removeLogger = untracedMethod(
  8584. () => logger =>
  8585. scopedDiscard(
  8586. fiberRefLocallyScopedWith(
  8587. currentLoggers,
  8588. mjs_HashSet_remove(logger)
  8589. )
  8590. )
  8591. ),
  8592. replaceLogger = Function_dual(2, (self, that) =>
  8593. layer_flatMap(removeLogger(self), () => addLogger(that))
  8594. )
  8595. class AsyncFiber {
  8596. constructor(fiber) {
  8597. this.fiber = fiber
  8598. this._tag = "AsyncFiber"
  8599. }
  8600. toString() {
  8601. return `Fiber #${this.fiber.id().id} has suspended work asyncroniously`
  8602. }
  8603. [Symbol.for("nodejs.util.inspect.custom")]() {
  8604. return this.toString()
  8605. }
  8606. }
  8607. const FiberFailureId = Symbol.for("@effect/io/Runtime/FiberFailure"),
  8608. FiberFailureCauseId = Symbol.for("@effect/io/Runtime/FiberFailure/Cause"),
  8609. NodePrint = Symbol.for("nodejs.util.inspect.custom"),
  8610. unsafeRunPromise = runtime =>
  8611. methodWithTrace(
  8612. trace => effect =>
  8613. new Promise((resolve, reject) => {
  8614. ;(runtime =>
  8615. methodWithTrace(trace => (self, options) => {
  8616. const fiberId = Id_unsafeMake(),
  8617. effect = self.traced(trace)
  8618. let fiberRefs = FiberRefs_updatedAs(
  8619. runtime.fiberRefs,
  8620. fiberId,
  8621. currentContext,
  8622. runtime.context
  8623. )
  8624. options?.scheduler &&
  8625. (fiberRefs = FiberRefs_updatedAs(
  8626. fiberRefs,
  8627. fiberId,
  8628. currentScheduler,
  8629. options.scheduler
  8630. ))
  8631. options?.updateRefs &&
  8632. (fiberRefs = options.updateRefs(fiberRefs, fiberId))
  8633. const fiberRuntime = new FiberRuntime(
  8634. fiberId,
  8635. FiberRefs_forkAs(fiberRefs, fiberId),
  8636. runtime.runtimeFlags
  8637. ),
  8638. supervisor = fiberRuntime.getSupervisor()
  8639. if (supervisor !== supervisor_none) {
  8640. supervisor.onStart(
  8641. runtime.context,
  8642. effect,
  8643. Option_none(),
  8644. fiberRuntime
  8645. )
  8646. fiberRuntime.unsafeAddObserver(exit =>
  8647. supervisor.onEnd(exit, fiberRuntime)
  8648. )
  8649. }
  8650. globalScope.add(runtime.runtimeFlags, fiberRuntime)
  8651. fiberRuntime.start(effect)
  8652. return fiberRuntime
  8653. }))(runtime)(effect.traced(trace)).unsafeAddObserver(result => {
  8654. switch (result._tag) {
  8655. case "Success":
  8656. resolve(result.i0)
  8657. break
  8658. case "Failure":
  8659. reject(
  8660. (cause => {
  8661. const limit = Error.stackTraceLimit
  8662. Error.stackTraceLimit = 0
  8663. const error = new Error()
  8664. Error.stackTraceLimit = limit
  8665. const pretty = prettyErrors(cause)
  8666. if (pretty.length > 0) {
  8667. error.name = pretty[0].message.split(":")[0]
  8668. error.message = pretty[0].message.substring(
  8669. error.name.length + 2
  8670. )
  8671. error.stack = `${error.name}: ${error.message}\n${pretty[0].stack}`
  8672. }
  8673. error[FiberFailureId] = FiberFailureId
  8674. error[FiberFailureCauseId] = cause
  8675. error.toString = () => cause_pretty_pretty(cause)
  8676. error[NodePrint] = () => error.toString()
  8677. return error
  8678. })(result.i0)
  8679. )
  8680. }
  8681. })
  8682. })
  8683. )
  8684. class RuntimeImpl {
  8685. constructor(context, runtimeFlags, fiberRefs) {
  8686. this.context = context
  8687. this.runtimeFlags = runtimeFlags
  8688. this.fiberRefs = fiberRefs
  8689. }
  8690. }
  8691. const runtime_make = (context, runtimeFlags, fiberRefs) =>
  8692. new RuntimeImpl(context, runtimeFlags, fiberRefs),
  8693. defaultRuntimeFlags = runtimeFlags_make(1, 32),
  8694. Effect_asUnit = core_asUnit,
  8695. Effect_delay = delay,
  8696. Effect_bind = effect_bind,
  8697. Effect_bindDiscard = effect_bindDiscard,
  8698. bindValue_ = bindValue,
  8699. Effect_letDiscard = bindValueDiscard,
  8700. Effect_Do = effect_Do,
  8701. Effect_fail = core_fail,
  8702. Effect_filterOrElse = filterOrElse,
  8703. Effect_filterOrFail = filterOrFail,
  8704. Effect_flatMap = core_flatMap,
  8705. Effect_forEach = core_forEach,
  8706. Effect_forkDaemon = forkDaemon,
  8707. Effect_fromOption = core_fromOption,
  8708. Effect_ignore = ignore,
  8709. Effect_isSuccess = effect_isSuccess,
  8710. Effect_log = log,
  8711. Effect_logDebug = logDebug,
  8712. Effect_logError = logError,
  8713. Effect_logInfo = logInfo,
  8714. Effect_logWarning = logWarning,
  8715. Effect_logAnnotate = logAnnotate,
  8716. Effect_map = core_map,
  8717. Effect_orElseSucceed = orElseSucceed,
  8718. Effect_promise = promise,
  8719. Effect_provideSomeLayer = provideSomeLayer,
  8720. Effect_repeat = repeat_Effect,
  8721. Effect_some = fiberRuntime_some,
  8722. Effect_succeed = succeed,
  8723. Effect_sync = sync,
  8724. Effect_tap = core_tap,
  8725. Effect_tapErrorCause = tapErrorCause,
  8726. Effect_all = effect_all,
  8727. Effect_unit = core_unit,
  8728. runPromise = unsafeRunPromise(
  8729. runtime_make(
  8730. mjs_Context_empty(),
  8731. defaultRuntimeFlags,
  8732. FiberRefs_unsafeMake(new Map())
  8733. )
  8734. ),
  8735. Effect_unsome = unsome,
  8736. Effect_withParallelismUnbounded = withParallelismUnbounded,
  8737. Effect_zipLeft = core_zipLeft,
  8738. Effect_zipRight = core_zipRight,
  8739. external_rxjs_namespaceObject = rxjs,
  8740. Schedule_fixed = fixed,
  8741. lib = observer => value => {
  8742. observer.next(value)
  8743. }
  8744. Promise.resolve(!1)
  8745. Promise.resolve(!0)
  8746. var PROMISE_RESOLVED_VOID = Promise.resolve()
  8747. function util_sleep(time, resolveWith) {
  8748. time || (time = 0)
  8749. return new Promise(function (res) {
  8750. return setTimeout(function () {
  8751. return res(resolveWith)
  8752. }, time)
  8753. })
  8754. }
  8755. function randomToken() {
  8756. return Math.random().toString(36).substring(2)
  8757. }
  8758. var lastMs = 0,
  8759. additional = 0
  8760. function microSeconds() {
  8761. var ms = new Date().getTime()
  8762. if (ms === lastMs) return 1e3 * ms + ++additional
  8763. lastMs = ms
  8764. additional = 0
  8765. return 1e3 * ms
  8766. }
  8767. var isNode =
  8768. "[object process]" ===
  8769. Object.prototype.toString.call(
  8770. "undefined" != typeof process ? process : 0
  8771. )
  8772. const methods_native = {
  8773. create: function (channelName) {
  8774. var state = {
  8775. messagesCallback: null,
  8776. bc: new BroadcastChannel(channelName),
  8777. subFns: [],
  8778. }
  8779. state.bc.onmessage = function (msg) {
  8780. state.messagesCallback && state.messagesCallback(msg.data)
  8781. }
  8782. return state
  8783. },
  8784. close: function (channelState) {
  8785. channelState.bc.close()
  8786. channelState.subFns = []
  8787. },
  8788. onMessage: function (channelState, fn) {
  8789. channelState.messagesCallback = fn
  8790. },
  8791. postMessage: function (channelState, messageJson) {
  8792. try {
  8793. channelState.bc.postMessage(messageJson, !1)
  8794. return PROMISE_RESOLVED_VOID
  8795. } catch (err) {
  8796. return Promise.reject(err)
  8797. }
  8798. },
  8799. canBeUsed: function () {
  8800. if (isNode && "undefined" == typeof window) return !1
  8801. if ("function" == typeof BroadcastChannel) {
  8802. if (BroadcastChannel._pubkey)
  8803. throw new Error(
  8804. "BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill"
  8805. )
  8806. return !0
  8807. }
  8808. return !1
  8809. },
  8810. type: "native",
  8811. averageResponseTime: function () {
  8812. return 150
  8813. },
  8814. microSeconds,
  8815. }
  8816. var ObliviousSet = (function () {
  8817. function ObliviousSet(ttl) {
  8818. this.ttl = ttl
  8819. this.map = new Map()
  8820. this._to = !1
  8821. }
  8822. ObliviousSet.prototype.has = function (value) {
  8823. return this.map.has(value)
  8824. }
  8825. ObliviousSet.prototype.add = function (value) {
  8826. var _this = this
  8827. this.map.set(value, now())
  8828. if (!this._to) {
  8829. this._to = !0
  8830. setTimeout(function () {
  8831. _this._to = !1
  8832. !(function (obliviousSet) {
  8833. for (
  8834. var olderThen = now() - obliviousSet.ttl,
  8835. iterator = obliviousSet.map[Symbol.iterator]();
  8836. ;
  8837.  
  8838. ) {
  8839. var next = iterator.next().value
  8840. if (!next) return
  8841. var value = next[0]
  8842. if (!(next[1] < olderThen)) return
  8843. obliviousSet.map.delete(value)
  8844. }
  8845. })(_this)
  8846. }, 0)
  8847. }
  8848. }
  8849. ObliviousSet.prototype.clear = function () {
  8850. this.map.clear()
  8851. }
  8852. return ObliviousSet
  8853. })()
  8854. function now() {
  8855. return new Date().getTime()
  8856. }
  8857. function options_fillOptionsWithDefaults() {
  8858. var originalOptions =
  8859. arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
  8860. options = JSON.parse(JSON.stringify(originalOptions))
  8861. void 0 === options.webWorkerSupport && (options.webWorkerSupport = !0)
  8862. options.idb || (options.idb = {})
  8863. options.idb.ttl || (options.idb.ttl = 45e3)
  8864. options.idb.fallbackInterval || (options.idb.fallbackInterval = 150)
  8865. originalOptions.idb &&
  8866. "function" == typeof originalOptions.idb.onclose &&
  8867. (options.idb.onclose = originalOptions.idb.onclose)
  8868. options.localstorage || (options.localstorage = {})
  8869. options.localstorage.removeTimeout ||
  8870. (options.localstorage.removeTimeout = 6e4)
  8871. originalOptions.methods && (options.methods = originalOptions.methods)
  8872. options.node || (options.node = {})
  8873. options.node.ttl || (options.node.ttl = 12e4)
  8874. options.node.maxParallelWrites || (options.node.maxParallelWrites = 2048)
  8875. void 0 === options.node.useFastPath && (options.node.useFastPath = !0)
  8876. return options
  8877. }
  8878. var TRANSACTION_SETTINGS = { durability: "relaxed" }
  8879. function getIdb() {
  8880. if ("undefined" != typeof indexedDB) return indexedDB
  8881. if ("undefined" != typeof window) {
  8882. if (void 0 !== window.mozIndexedDB) return window.mozIndexedDB
  8883. if (void 0 !== window.webkitIndexedDB) return window.webkitIndexedDB
  8884. if (void 0 !== window.msIndexedDB) return window.msIndexedDB
  8885. }
  8886. return !1
  8887. }
  8888. function commitIndexedDBTransaction(tx) {
  8889. tx.commit && tx.commit()
  8890. }
  8891. function _readLoop(state) {
  8892. state.closed ||
  8893. readNewMessages(state)
  8894. .then(function () {
  8895. return util_sleep(state.options.idb.fallbackInterval)
  8896. })
  8897. .then(function () {
  8898. return _readLoop(state)
  8899. })
  8900. }
  8901. function readNewMessages(state) {
  8902. return state.closed
  8903. ? PROMISE_RESOLVED_VOID
  8904. : state.messagesCallback
  8905. ? (function (db, lastCursorId) {
  8906. var tx = db.transaction(
  8907. "messages",
  8908. "readonly",
  8909. TRANSACTION_SETTINGS
  8910. ),
  8911. objectStore = tx.objectStore("messages"),
  8912. ret = [],
  8913. keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
  8914. if (objectStore.getAll) {
  8915. var getAllRequest = objectStore.getAll(keyRangeValue)
  8916. return new Promise(function (res, rej) {
  8917. getAllRequest.onerror = function (err) {
  8918. return rej(err)
  8919. }
  8920. getAllRequest.onsuccess = function (e) {
  8921. res(e.target.result)
  8922. }
  8923. })
  8924. }
  8925. return new Promise(function (res, rej) {
  8926. var openCursorRequest = (function () {
  8927. try {
  8928. keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, 1 / 0)
  8929. return objectStore.openCursor(keyRangeValue)
  8930. } catch (e) {
  8931. return objectStore.openCursor()
  8932. }
  8933. })()
  8934. openCursorRequest.onerror = function (err) {
  8935. return rej(err)
  8936. }
  8937. openCursorRequest.onsuccess = function (ev) {
  8938. var cursor = ev.target.result
  8939. if (cursor)
  8940. if (cursor.value.id < lastCursorId + 1)
  8941. cursor.continue(lastCursorId + 1)
  8942. else {
  8943. ret.push(cursor.value)
  8944. cursor.continue()
  8945. }
  8946. else {
  8947. commitIndexedDBTransaction(tx)
  8948. res(ret)
  8949. }
  8950. }
  8951. })
  8952. })(state.db, state.lastCursorId).then(function (newerMessages) {
  8953. var useMessages = newerMessages
  8954. .filter(function (msgObj) {
  8955. return !!msgObj
  8956. })
  8957. .map(function (msgObj) {
  8958. msgObj.id > state.lastCursorId &&
  8959. (state.lastCursorId = msgObj.id)
  8960. return msgObj
  8961. })
  8962. .filter(function (msgObj) {
  8963. return (function (msgObj, state) {
  8964. return !(
  8965. msgObj.uuid === state.uuid ||
  8966. state.eMIs.has(msgObj.id) ||
  8967. msgObj.data.time < state.messagesCallbackTime
  8968. )
  8969. })(msgObj, state)
  8970. })
  8971. .sort(function (msgObjA, msgObjB) {
  8972. return msgObjA.time - msgObjB.time
  8973. })
  8974. useMessages.forEach(function (msgObj) {
  8975. if (state.messagesCallback) {
  8976. state.eMIs.add(msgObj.id)
  8977. state.messagesCallback(msgObj.data)
  8978. }
  8979. })
  8980. return PROMISE_RESOLVED_VOID
  8981. })
  8982. : PROMISE_RESOLVED_VOID
  8983. }
  8984. const indexed_db = {
  8985. create: function (channelName, options) {
  8986. options = options_fillOptionsWithDefaults(options)
  8987. return (function (channelName) {
  8988. var dbName = "pubkey.broadcast-channel-0-" + channelName,
  8989. openRequest = getIdb().open(dbName)
  8990. openRequest.onupgradeneeded = function (ev) {
  8991. ev.target.result.createObjectStore("messages", {
  8992. keyPath: "id",
  8993. autoIncrement: !0,
  8994. })
  8995. }
  8996. return new Promise(function (res, rej) {
  8997. openRequest.onerror = function (ev) {
  8998. return rej(ev)
  8999. }
  9000. openRequest.onsuccess = function () {
  9001. res(openRequest.result)
  9002. }
  9003. })
  9004. })(channelName).then(function (db) {
  9005. var state = {
  9006. closed: !1,
  9007. lastCursorId: 0,
  9008. channelName,
  9009. options,
  9010. uuid: randomToken(),
  9011. eMIs: new ObliviousSet(2 * options.idb.ttl),
  9012. writeBlockPromise: PROMISE_RESOLVED_VOID,
  9013. messagesCallback: null,
  9014. readQueuePromises: [],
  9015. db,
  9016. }
  9017. db.onclose = function () {
  9018. state.closed = !0
  9019. options.idb.onclose && options.idb.onclose()
  9020. }
  9021. _readLoop(state)
  9022. return state
  9023. })
  9024. },
  9025. close: function (channelState) {
  9026. channelState.closed = !0
  9027. channelState.db.close()
  9028. },
  9029. onMessage: function (channelState, fn, time) {
  9030. channelState.messagesCallbackTime = time
  9031. channelState.messagesCallback = fn
  9032. readNewMessages(channelState)
  9033. },
  9034. postMessage: function (channelState, messageJson) {
  9035. channelState.writeBlockPromise = channelState.writeBlockPromise
  9036. .then(function () {
  9037. return (function (db, readerUuid, messageJson) {
  9038. var writeObject = {
  9039. uuid: readerUuid,
  9040. time: new Date().getTime(),
  9041. data: messageJson,
  9042. },
  9043. tx = db.transaction(
  9044. ["messages"],
  9045. "readwrite",
  9046. TRANSACTION_SETTINGS
  9047. )
  9048. return new Promise(function (res, rej) {
  9049. tx.oncomplete = function () {
  9050. return res()
  9051. }
  9052. tx.onerror = function (ev) {
  9053. return rej(ev)
  9054. }
  9055. tx.objectStore("messages").add(writeObject)
  9056. commitIndexedDBTransaction(tx)
  9057. })
  9058. })(channelState.db, channelState.uuid, messageJson)
  9059. })
  9060. .then(function () {
  9061. 0 === Math.floor(11 * Math.random() + 0) &&
  9062. ((db = channelState.db),
  9063. (ttl = channelState.options.idb.ttl),
  9064. (function (db, ttl) {
  9065. var olderThen = new Date().getTime() - ttl,
  9066. tx = db.transaction(
  9067. "messages",
  9068. "readonly",
  9069. TRANSACTION_SETTINGS
  9070. ),
  9071. objectStore = tx.objectStore("messages"),
  9072. ret = []
  9073. return new Promise(function (res) {
  9074. objectStore.openCursor().onsuccess = function (ev) {
  9075. var cursor = ev.target.result
  9076. if (cursor) {
  9077. var msgObk = cursor.value
  9078. if (!(msgObk.time < olderThen)) {
  9079. commitIndexedDBTransaction(tx)
  9080. res(ret)
  9081. return
  9082. }
  9083. ret.push(msgObk)
  9084. cursor.continue()
  9085. } else res(ret)
  9086. }
  9087. })
  9088. })(db, ttl).then(function (tooOld) {
  9089. return (function (db, ids) {
  9090. var objectStore = db
  9091. .transaction(
  9092. ["messages"],
  9093. "readwrite",
  9094. TRANSACTION_SETTINGS
  9095. )
  9096. .objectStore("messages")
  9097. return Promise.all(
  9098. ids.map(function (id) {
  9099. var deleteRequest = objectStore.delete(id)
  9100. return new Promise(function (res) {
  9101. deleteRequest.onsuccess = function () {
  9102. return res()
  9103. }
  9104. })
  9105. })
  9106. )
  9107. })(
  9108. db,
  9109. tooOld.map(function (msg) {
  9110. return msg.id
  9111. })
  9112. )
  9113. }))
  9114. var db, ttl
  9115. })
  9116. return channelState.writeBlockPromise
  9117. },
  9118. canBeUsed: function () {
  9119. return !isNode && !!getIdb()
  9120. },
  9121. type: "idb",
  9122. averageResponseTime: function (options) {
  9123. return 2 * options.idb.fallbackInterval
  9124. },
  9125. microSeconds,
  9126. }
  9127. function getLocalStorage() {
  9128. var localStorage
  9129. if ("undefined" == typeof window) return null
  9130. try {
  9131. localStorage = window.localStorage
  9132. localStorage =
  9133. window["ie8-eventlistener/storage"] || window.localStorage
  9134. } catch (e) {}
  9135. return localStorage
  9136. }
  9137. function storageKey(channelName) {
  9138. return "pubkey.broadcastChannel-" + channelName
  9139. }
  9140. function localstorage_canBeUsed() {
  9141. if (isNode) return !1
  9142. var ls = getLocalStorage()
  9143. if (!ls) return !1
  9144. try {
  9145. var key = "__broadcastchannel_check"
  9146. ls.setItem(key, "works")
  9147. ls.removeItem(key)
  9148. } catch (e) {
  9149. return !1
  9150. }
  9151. return !0
  9152. }
  9153. const localstorage = {
  9154. create: function (channelName, options) {
  9155. options = options_fillOptionsWithDefaults(options)
  9156. if (!localstorage_canBeUsed())
  9157. throw new Error("BroadcastChannel: localstorage cannot be used")
  9158. var uuid = randomToken(),
  9159. eMIs = new ObliviousSet(options.localstorage.removeTimeout),
  9160. state = { channelName, uuid, eMIs }
  9161. state.listener = (function (channelName, fn) {
  9162. var key = storageKey(channelName),
  9163. listener = function (ev) {
  9164. ev.key === key &&
  9165. (function (msgObj) {
  9166. if (
  9167. state.messagesCallback &&
  9168. msgObj.uuid !== uuid &&
  9169. msgObj.token &&
  9170. !eMIs.has(msgObj.token) &&
  9171. !(
  9172. msgObj.data.time &&
  9173. msgObj.data.time < state.messagesCallbackTime
  9174. )
  9175. ) {
  9176. eMIs.add(msgObj.token)
  9177. state.messagesCallback(msgObj.data)
  9178. }
  9179. })(JSON.parse(ev.newValue))
  9180. }
  9181. window.addEventListener("storage", listener)
  9182. return listener
  9183. })(channelName)
  9184. return state
  9185. },
  9186. close: function (channelState) {
  9187. ;(listener = channelState.listener),
  9188. window.removeEventListener("storage", listener)
  9189. var listener
  9190. },
  9191. onMessage: function (channelState, fn, time) {
  9192. channelState.messagesCallbackTime = time
  9193. channelState.messagesCallback = fn
  9194. },
  9195. postMessage: function (channelState, messageJson) {
  9196. return new Promise(function (res) {
  9197. util_sleep().then(function () {
  9198. var key = storageKey(channelState.channelName),
  9199. writeObj = {
  9200. token: randomToken(),
  9201. time: new Date().getTime(),
  9202. data: messageJson,
  9203. uuid: channelState.uuid,
  9204. },
  9205. value = JSON.stringify(writeObj)
  9206. getLocalStorage().setItem(key, value)
  9207. var ev = document.createEvent("Event")
  9208. ev.initEvent("storage", !0, !0)
  9209. ev.key = key
  9210. ev.newValue = value
  9211. window.dispatchEvent(ev)
  9212. res()
  9213. })
  9214. })
  9215. },
  9216. canBeUsed: localstorage_canBeUsed,
  9217. type: "localstorage",
  9218. averageResponseTime: function () {
  9219. var userAgent = navigator.userAgent.toLowerCase()
  9220. return userAgent.includes("safari") && !userAgent.includes("chrome")
  9221. ? 240
  9222. : 120
  9223. },
  9224. microSeconds,
  9225. }
  9226. var simulate_microSeconds = microSeconds,
  9227. SIMULATE_CHANNELS = new Set()
  9228. const simulate = {
  9229. create: function (channelName) {
  9230. var state = { name: channelName, messagesCallback: null }
  9231. SIMULATE_CHANNELS.add(state)
  9232. return state
  9233. },
  9234. close: function (channelState) {
  9235. SIMULATE_CHANNELS.delete(channelState)
  9236. },
  9237. onMessage: function (channelState, fn) {
  9238. channelState.messagesCallback = fn
  9239. },
  9240. postMessage: function (channelState, messageJson) {
  9241. return new Promise(function (res) {
  9242. return setTimeout(function () {
  9243. Array.from(SIMULATE_CHANNELS)
  9244. .filter(function (channel) {
  9245. return channel.name === channelState.name
  9246. })
  9247. .filter(function (channel) {
  9248. return channel !== channelState
  9249. })
  9250. .filter(function (channel) {
  9251. return !!channel.messagesCallback
  9252. })
  9253. .forEach(function (channel) {
  9254. return channel.messagesCallback(messageJson)
  9255. })
  9256. res()
  9257. }, 5)
  9258. })
  9259. },
  9260. canBeUsed: function () {
  9261. return !0
  9262. },
  9263. type: "simulate",
  9264. averageResponseTime: function () {
  9265. return 5
  9266. },
  9267. microSeconds: simulate_microSeconds,
  9268. }
  9269. var METHODS = [methods_native, indexed_db, localstorage],
  9270. OPEN_BROADCAST_CHANNELS = new Set(),
  9271. lastId = 0,
  9272. broadcast_channel_BroadcastChannel = function (name, options) {
  9273. this.id = lastId++
  9274. OPEN_BROADCAST_CHANNELS.add(this)
  9275. this.name = name
  9276. this.options = options_fillOptionsWithDefaults(options)
  9277. this.method = (function (options) {
  9278. var chooseMethods = []
  9279. .concat(options.methods, METHODS)
  9280. .filter(Boolean)
  9281. if (options.type) {
  9282. if ("simulate" === options.type) return simulate
  9283. var ret = chooseMethods.find(function (m) {
  9284. return m.type === options.type
  9285. })
  9286. if (ret) return ret
  9287. throw new Error("method-type " + options.type + " not found")
  9288. }
  9289. options.webWorkerSupport ||
  9290. isNode ||
  9291. (chooseMethods = chooseMethods.filter(function (m) {
  9292. return "idb" !== m.type
  9293. }))
  9294. var useMethod = chooseMethods.find(function (method) {
  9295. return method.canBeUsed()
  9296. })
  9297. if (useMethod) return useMethod
  9298. throw new Error(
  9299. "No useable method found in " +
  9300. JSON.stringify(
  9301. METHODS.map(function (m) {
  9302. return m.type
  9303. })
  9304. )
  9305. )
  9306. })(this.options)
  9307. this._iL = !1
  9308. this._onML = null
  9309. this._addEL = { message: [], internal: [] }
  9310. this._uMP = new Set()
  9311. this._befC = []
  9312. this._prepP = null
  9313. !(function (channel) {
  9314. var obj,
  9315. maybePromise = channel.method.create(channel.name, channel.options)
  9316. if ((obj = maybePromise) && "function" == typeof obj.then) {
  9317. channel._prepP = maybePromise
  9318. maybePromise.then(function (s) {
  9319. channel._state = s
  9320. })
  9321. } else channel._state = maybePromise
  9322. })(this)
  9323. }
  9324. broadcast_channel_BroadcastChannel._pubkey = !0
  9325. broadcast_channel_BroadcastChannel.prototype = {
  9326. postMessage: function (msg) {
  9327. if (this.closed)
  9328. throw new Error(
  9329. "BroadcastChannel.postMessage(): Cannot post message after channel has closed " +
  9330. JSON.stringify(msg)
  9331. )
  9332. return _post(this, "message", msg)
  9333. },
  9334. postInternal: function (msg) {
  9335. return _post(this, "internal", msg)
  9336. },
  9337. set onmessage(fn) {
  9338. var listenObj = { time: this.method.microSeconds(), fn }
  9339. _removeListenerObject(this, "message", this._onML)
  9340. if (fn && "function" == typeof fn) {
  9341. this._onML = listenObj
  9342. _addListenerObject(this, "message", listenObj)
  9343. } else this._onML = null
  9344. },
  9345. addEventListener: function (type, fn) {
  9346. _addListenerObject(this, type, { time: this.method.microSeconds(), fn })
  9347. },
  9348. removeEventListener: function (type, fn) {
  9349. _removeListenerObject(
  9350. this,
  9351. type,
  9352. this._addEL[type].find(function (obj) {
  9353. return obj.fn === fn
  9354. })
  9355. )
  9356. },
  9357. close: function () {
  9358. var _this = this
  9359. if (!this.closed) {
  9360. OPEN_BROADCAST_CHANNELS.delete(this)
  9361. this.closed = !0
  9362. var awaitPrepare = this._prepP ? this._prepP : PROMISE_RESOLVED_VOID
  9363. this._onML = null
  9364. this._addEL.message = []
  9365. return awaitPrepare
  9366. .then(function () {
  9367. return Promise.all(Array.from(_this._uMP))
  9368. })
  9369. .then(function () {
  9370. return Promise.all(
  9371. _this._befC.map(function (fn) {
  9372. return fn()
  9373. })
  9374. )
  9375. })
  9376. .then(function () {
  9377. return _this.method.close(_this._state)
  9378. })
  9379. }
  9380. },
  9381. get type() {
  9382. return this.method.type
  9383. },
  9384. get isClosed() {
  9385. return this.closed
  9386. },
  9387. }
  9388. function _post(broadcastChannel, type, msg) {
  9389. var msgObj = {
  9390. time: broadcastChannel.method.microSeconds(),
  9391. type,
  9392. data: msg,
  9393. }
  9394. return (
  9395. broadcastChannel._prepP
  9396. ? broadcastChannel._prepP
  9397. : PROMISE_RESOLVED_VOID
  9398. ).then(function () {
  9399. var sendPromise = broadcastChannel.method.postMessage(
  9400. broadcastChannel._state,
  9401. msgObj
  9402. )
  9403. broadcastChannel._uMP.add(sendPromise)
  9404. sendPromise.catch().then(function () {
  9405. return broadcastChannel._uMP.delete(sendPromise)
  9406. })
  9407. return sendPromise
  9408. })
  9409. }
  9410. function _hasMessageListeners(channel) {
  9411. return (
  9412. channel._addEL.message.length > 0 || channel._addEL.internal.length > 0
  9413. )
  9414. }
  9415. function _addListenerObject(channel, type, obj) {
  9416. channel._addEL[type].push(obj)
  9417. !(function (channel) {
  9418. if (!channel._iL && _hasMessageListeners(channel)) {
  9419. var listenerFn = function (msgObj) {
  9420. channel._addEL[msgObj.type].forEach(function (listenerObject) {
  9421. var minMessageTime = listenerObject.time - 1e5
  9422. msgObj.time >= minMessageTime && listenerObject.fn(msgObj.data)
  9423. })
  9424. },
  9425. time = channel.method.microSeconds()
  9426. if (channel._prepP)
  9427. channel._prepP.then(function () {
  9428. channel._iL = !0
  9429. channel.method.onMessage(channel._state, listenerFn, time)
  9430. })
  9431. else {
  9432. channel._iL = !0
  9433. channel.method.onMessage(channel._state, listenerFn, time)
  9434. }
  9435. }
  9436. })(channel)
  9437. }
  9438. function _removeListenerObject(channel, type, obj) {
  9439. channel._addEL[type] = channel._addEL[type].filter(function (o) {
  9440. return o !== obj
  9441. })
  9442. !(function (channel) {
  9443. if (channel._iL && !_hasMessageListeners(channel)) {
  9444. channel._iL = !1
  9445. var time = channel.method.microSeconds()
  9446. channel.method.onMessage(channel._state, null, time)
  9447. }
  9448. })(channel)
  9449. }
  9450. var browser = __webpack_require__(661),
  9451. browser_default = __webpack_require__.n(browser)
  9452. const es_browser = {
  9453. add: function (fn) {
  9454. if (
  9455. "function" == typeof WorkerGlobalScope &&
  9456. self instanceof WorkerGlobalScope
  9457. );
  9458. else {
  9459. if ("function" != typeof window.addEventListener) return
  9460. window.addEventListener(
  9461. "beforeunload",
  9462. function () {
  9463. fn()
  9464. },
  9465. !0
  9466. )
  9467. window.addEventListener(
  9468. "unload",
  9469. function () {
  9470. fn()
  9471. },
  9472. !0
  9473. )
  9474. }
  9475. },
  9476. }
  9477. var node_ignored_ = __webpack_require__(938),
  9478. node_ignored_default = __webpack_require__.n(node_ignored_)
  9479. browser_default() && node_ignored_default(), new Set()
  9480. const external_DeepDiff_namespaceObject = DeepDiff
  9481. var fast_deep_equal = __webpack_require__(204),
  9482. fast_deep_equal_default = __webpack_require__.n(fast_deep_equal)
  9483. const mapObject = f => o =>
  9484. pipe(Object.entries(o), ReadonlyArray_map(f), Object.fromEntries),
  9485. makePageState = mapObject(([k, v]) => [
  9486. k,
  9487. { ele: Option_none(), read: v },
  9488. ]),
  9489. removeOldChats = mainState => maxChatCount =>
  9490. pipe(
  9491. Effect_sync(() =>
  9492. mainState.flowChats.sort((a, b) =>
  9493. a.animationEnded === b.animationEnded
  9494. ? 0
  9495. : a.animationEnded
  9496. ? -1
  9497. : 1
  9498. )
  9499. ),
  9500. Effect_zipRight(
  9501. Effect_sync(() =>
  9502. mainState.flowChats.splice(
  9503. 0,
  9504. Math.max(0, mainState.flowChats.length - maxChatCount)
  9505. )
  9506. )
  9507. ),
  9508. Effect_flatMap(
  9509. Effect_forEach(x =>
  9510. pipe(
  9511. Effect_logDebug("RemoveChat"),
  9512. Effect_zipRight(
  9513. Effect_sync(() => {
  9514. x.element.remove()
  9515. })
  9516. )
  9517. )
  9518. )
  9519. )
  9520. ),
  9521. external_m_namespaceObject = m
  9522. var external_m_default = __webpack_require__.n(external_m_namespaceObject)
  9523. const getChatFontSize = mainState =>
  9524. Math.round(
  9525. ((Math.max(mainState.config.fontSize - 0.2, 0.01) *
  9526. mainState.playerRect.height) /
  9527. mainState.config.laneCount) *
  9528. (mainState.config.flowY2 - mainState.config.flowY1) *
  9529. 100
  9530. ) / 100,
  9531. textShadow = shadowColor =>
  9532. flow(
  9533. x => `${x}px`,
  9534. x => (a, b) => `${a}${x} ${b}${x} ${shadowColor}99`,
  9535. x => join(", ")([x("-", "-"), x("", "-"), x("-", ""), x("", "")])
  9536. ),
  9537. textStyle = { fontFamily: "inherit" },
  9538. renderChat = chat => mainState =>
  9539. Effect_sync(() =>
  9540. external_m_default().render(
  9541. chat.element,
  9542. ((chat, mainState) =>
  9543. pipe(
  9544. mainState.config,
  9545. config => ({ data: chat.getData(config), config }),
  9546. ({ data, config }) =>
  9547. external_m_default()(
  9548. "span",
  9549. {
  9550. style: {
  9551. fontSize: `${getChatFontSize(mainState)}px`,
  9552. visibility: config.displayChats ? "visible" : "hidden",
  9553. color:
  9554. "owner" === data.authorType
  9555. ? config.ownerColor
  9556. : "moderator" === data.authorType
  9557. ? config.moderatorColor
  9558. : "member" === data.authorType
  9559. ? config.memberColor
  9560. : config.color,
  9561. fontWeight: config.fontWeight.toString(),
  9562. fontFamily: config.font,
  9563. opacity: config.chatOpacity.toString(),
  9564. textShadow: textShadow(config.shadowColor)(
  9565. config.shadowFontWeight
  9566. ),
  9567. },
  9568. },
  9569. pipe(
  9570. [
  9571. pipe(
  9572. data.authorName,
  9573. Option_filter(x => x.visible),
  9574. Option_map(x =>
  9575. external_m_default()(
  9576. "span",
  9577. {
  9578. style: {
  9579. color: getOrUndefined(data.textColor),
  9580. fontSize: "0.84em",
  9581. ...textStyle,
  9582. },
  9583. },
  9584. `${x.content}: `
  9585. )
  9586. )
  9587. ),
  9588. pipe(
  9589. data.messageElement,
  9590. Option_map(x =>
  9591. ((message, config) => {
  9592. const eleWin =
  9593. message.ownerDocument.defaultView ?? window,
  9594. { maxChatLength } = config
  9595. return pipe(
  9596. Array.from(message.childNodes),
  9597. ReadonlyArray_reduce(
  9598. { vnodes: [], length: 0 },
  9599. ({ vnodes, length }, node) =>
  9600. length >= maxChatLength
  9601. ? { vnodes, length }
  9602. : !config.textOnly &&
  9603. node instanceof eleWin.HTMLImageElement
  9604. ? {
  9605. vnodes: [
  9606. ...vnodes,
  9607. external_m_default()("img", {
  9608. style: {
  9609. height: "1em",
  9610. width: "1em",
  9611. verticalAlign: "text-top",
  9612. },
  9613. src: node.src.replace(
  9614. /=w\d+-h\d+-c-k-nd$/,
  9615. ""
  9616. ),
  9617. alt: node.alt,
  9618. }),
  9619. ],
  9620. length: length + 1,
  9621. }
  9622. : pipe(
  9623. node.textContent ?? "",
  9624. slice(0, maxChatLength),
  9625. x =>
  9626. node instanceof
  9627. eleWin.HTMLAnchorElement
  9628. ? {
  9629. vnodes: [
  9630. ...vnodes,
  9631. external_m_default()(
  9632. "span",
  9633. {
  9634. style: {
  9635. fontSize: "0.84em",
  9636. textDecoration:
  9637. "underline",
  9638. ...textStyle,
  9639. },
  9640. },
  9641. x
  9642. ),
  9643. ],
  9644. length: length + x.length,
  9645. }
  9646. : {
  9647. vnodes: [
  9648. ...vnodes,
  9649. external_m_default().fragment(
  9650. {},
  9651. x
  9652. ),
  9653. ],
  9654. length: length + x.length,
  9655. }
  9656. )
  9657. )
  9658. )
  9659. })(x, config)
  9660. ),
  9661. Option_map(x =>
  9662. external_m_default()(
  9663. "span",
  9664. {
  9665. style: {
  9666. color: getOrUndefined(data.textColor),
  9667. ...textStyle,
  9668. },
  9669. },
  9670. x.vnodes
  9671. )
  9672. )
  9673. ),
  9674. pipe(
  9675. data.paymentInfo,
  9676. Option_filter(x => x.visible),
  9677. Option_map(x =>
  9678. external_m_default()(
  9679. "span",
  9680. {
  9681. style: {
  9682. color: getOrUndefined(data.paidColor),
  9683. fontSize: "0.84em",
  9684. ...textStyle,
  9685. },
  9686. },
  9687. external_m_default()(
  9688. "strong",
  9689. { style: textStyle },
  9690. x.content
  9691. )
  9692. )
  9693. )
  9694. ),
  9695. ],
  9696. ReadonlyArray_compact
  9697. )
  9698. )
  9699. ))(chat, mainState)
  9700. )
  9701. ),
  9702. Bicovariant_mapLeft = F =>
  9703. Function_dual(2, (self, f) => F.bimap(self, f, Function_identity)),
  9704. Bicovariant_map = F =>
  9705. Function_dual(2, (self, f) => F.bimap(self, Function_identity, f)),
  9706. getFirst = self => self[0],
  9707. getSecond = self => self[1],
  9708. Tuple_bimap = Function_dual(3, (self, f, g) => [f(self[0]), g(self[1])]),
  9709. Tuple_Bicovariant = { bimap: Tuple_bimap },
  9710. mapFirst = Bicovariant_mapLeft(Tuple_Bicovariant),
  9711. mapSecond = Bicovariant_map(Tuple_Bicovariant),
  9712. external_window_hash_it_namespaceObject = window["hash-it"]
  9713. var external_window_hash_it_default = __webpack_require__.n(
  9714. external_window_hash_it_namespaceObject
  9715. )
  9716. const external_window_micro_memoize_namespaceObject =
  9717. window["micro-memoize"]
  9718. var external_window_micro_memoize_default = __webpack_require__.n(
  9719. external_window_micro_memoize_namespaceObject
  9720. )
  9721. const getFlowChatProgress = chat =>
  9722. pipe(
  9723. chat.animation,
  9724. flatMapNullable(x => x.currentTime),
  9725. getOrElse(() => 0),
  9726. x => x / chat.animationDuration
  9727. ),
  9728. getFlowChatRect = (chat, mainState) =>
  9729. pipe(
  9730. mainState.config,
  9731. x =>
  9732. mainState.playerRect.width * x.flowX2 -
  9733. (chat.width + mainState.playerRect.width * (x.flowX2 - x.flowX1)) *
  9734. getFlowChatProgress(chat),
  9735. x => new DOMRect(x, chat.y, chat.width, chat.height)
  9736. ),
  9737. getChatLane = (flowChat, progress) => mainState => {
  9738. const flowWidth =
  9739. mainState.playerRect.width *
  9740. (mainState.config.flowX2 - mainState.config.flowX1),
  9741. chatRect = getFlowChatRect(flowChat, mainState),
  9742. chatWidth = chatRect.width,
  9743. chatHeight = chatRect.height,
  9744. chatX = chatRect.x,
  9745. { flowChats } = mainState,
  9746. chatIndex = flowChats.indexOf(flowChat),
  9747. movingChats = pipe(
  9748. flowChats,
  9749. take(chatIndex >= 0 ? chatIndex : flowChats.length),
  9750. ReadonlyArray_filter(
  9751. chat => !chat.animationEnded && chat.width > 0
  9752. ),
  9753. sort(Order_contramap(x => x.lane)(Order))
  9754. ),
  9755. tooCloseTo = external_window_micro_memoize_default()(
  9756. x => {
  9757. const otherRect = getFlowChatRect(x, mainState),
  9758. otherWidth = otherRect.width,
  9759. otherX = otherRect.x,
  9760. gap =
  9761. (chatHeight * otherWidth * chatWidth) ** 0.333 *
  9762. mainState.config.minSpacing
  9763. return (
  9764. (flowWidth - otherX) / (flowWidth + otherWidth) - progress <
  9765. (chatWidth + gap) / (flowWidth + chatWidth) ||
  9766. otherX + otherWidth + gap > chatX
  9767. )
  9768. },
  9769. { maxSize: 1e3 }
  9770. ),
  9771. occupyInfo = pipe(
  9772. movingChats,
  9773. ReadonlyArray_map(x => ({
  9774. tooClose: () => tooCloseTo(x),
  9775. lane: x.lane,
  9776. })),
  9777. append({ tooClose: () => !0, lane: mainState.config.laneCount })
  9778. ),
  9779. index = occupyInfo.findIndex(x => x.lane >= flowChat.lane),
  9780. bottomFreeLane = pipe(
  9781. occupyInfo.slice(index),
  9782. findFirst(x => x.tooClose()),
  9783. Option_map(x => x.lane),
  9784. getOrElse(() => mainState.config.laneCount)
  9785. ),
  9786. topFreeLane = pipe(
  9787. occupyInfo.slice(0, index),
  9788. findLast(x => x.tooClose()),
  9789. Option_map(x => x.lane),
  9790. getOrElse(() => -1)
  9791. ),
  9792. formerLaneInterval = Math.min(
  9793. flowChat.lane - topFreeLane,
  9794. bottomFreeLane - flowChat.lane,
  9795. 1
  9796. )
  9797. return pipe(
  9798. occupyInfo,
  9799. ReadonlyArray_reduce(
  9800. { maxInterval: 0, maxIntervalLane: 0, lastLane: -1 },
  9801. ({ maxInterval, maxIntervalLane, lastLane }, info) =>
  9802. maxInterval > 0.999 || !info.tooClose()
  9803. ? { maxInterval, maxIntervalLane, lastLane }
  9804. : (() => {
  9805. const nextLane = info.lane,
  9806. interLane = Math.min(
  9807. Math.max((lastLane + nextLane) / 2, 0),
  9808. mainState.config.laneCount - 1
  9809. ),
  9810. newInterval = Math.min(
  9811. interLane - lastLane,
  9812. nextLane - interLane,
  9813. 1
  9814. )
  9815. return newInterval - maxInterval > 0.001
  9816. ? {
  9817. maxInterval: newInterval,
  9818. maxIntervalLane: Math.max(lastLane + newInterval, 0),
  9819. lastLane: nextLane,
  9820. }
  9821. : { maxInterval, maxIntervalLane, lastLane: nextLane }
  9822. })()
  9823. ),
  9824. x => ({
  9825. lane:
  9826. Math.abs(formerLaneInterval - x.maxInterval) < 0.001
  9827. ? flowChat.lane
  9828. : x.maxIntervalLane,
  9829. interval: x.maxInterval,
  9830. })
  9831. )
  9832. },
  9833. getLaneY = (lane, mainState) =>
  9834. mainState.playerRect.height *
  9835. ((lane / mainState.config.laneCount + 0.005) *
  9836. (mainState.config.flowY2 - mainState.config.flowY1) +
  9837. mainState.config.flowY1),
  9838. intervalTooSmall = interval => config =>
  9839. config.noOverlap && interval < 0.999,
  9840. setChatPlayState = chat => mainState =>
  9841. pipe(
  9842. chat,
  9843. liftPredicate(x => !x.animationEnded),
  9844. Effect_fromOption,
  9845. Effect_map(x => x.animation),
  9846. Effect_flatMap(Effect_fromOption),
  9847. Effect_tap(x =>
  9848. Effect_sync(
  9849. mainState.chatPlaying ? () => x.play() : () => x.pause()
  9850. )
  9851. ),
  9852. Effect_flatMap(x =>
  9853. Effect_sync(() => {
  9854. x.playbackRate = mainState.config.flowSpeed / 15
  9855. })
  9856. ),
  9857. Effect_ignore
  9858. ),
  9859. getWidth = external_window_micro_memoize_default()(
  9860. ele => ele?.getBoundingClientRect().width ?? 0,
  9861. {
  9862. maxSize: 2e3,
  9863. transformKey: ReadonlyArray_map(external_window_hash_it_default()),
  9864. }
  9865. ),
  9866. setChatAnimation = chat => mainState =>
  9867. pipe(
  9868. { fontSize: getChatFontSize(mainState) },
  9869. Effect_succeed,
  9870. Effect_tap(x =>
  9871. Effect_sync(() => {
  9872. chat.element.style.transform = `translate(${
  9873. mainState.playerRect.width *
  9874. (mainState.config.flowX2 - mainState.config.flowX1)
  9875. }px, -${2 * x.fontSize}px)`
  9876. })
  9877. ),
  9878. Effect_filterOrFail(() => !chat.animationEnded, Option_none),
  9879. Effect_tap(x =>
  9880. Effect_sync(() => {
  9881. chat.animationDuration = 6400
  9882. chat.width = getWidth(chat.element.firstElementChild)
  9883. chat.height = x.fontSize
  9884. })
  9885. ),
  9886. Effect_map(() => getFlowChatProgress(chat)),
  9887. Effect_map(progress => ({
  9888. progress,
  9889. ...getChatLane(chat, progress)(mainState),
  9890. })),
  9891. Effect_filterOrElse(
  9892. x => !intervalTooSmall(x.interval)(mainState.config),
  9893. () =>
  9894. pipe(
  9895. chat.animation,
  9896. Effect_fromOption,
  9897. Effect_flatMap(x =>
  9898. Effect_sync(() => {
  9899. x.finish()
  9900. chat.animation = Option_none()
  9901. })
  9902. ),
  9903. Effect_zipRight(Effect_fail(Option_none()))
  9904. )
  9905. ),
  9906. Effect_tap(x =>
  9907. Effect_sync(() => {
  9908. chat.lane = x.lane
  9909. })
  9910. ),
  9911. Effect_map(x => ({ ...x, laneY: getLaneY(chat.lane, mainState) })),
  9912. Effect_tap(ctx =>
  9913. pipe(
  9914. [
  9915. pipe(
  9916. chat.animation,
  9917. Effect_fromOption,
  9918. Effect_flatMap(x => Effect_sync(() => x.cancel())),
  9919. Effect_ignore
  9920. ),
  9921. pipe(
  9922. [
  9923. [
  9924. mainState.playerRect.width *
  9925. (mainState.config.flowX2 - mainState.config.flowX1),
  9926. ctx.laneY,
  9927. ],
  9928. [-chat.width, ctx.laneY],
  9929. ],
  9930. ReadonlyArray_map(
  9931. pipe(
  9932. x => `${x}px`,
  9933. x => Tuple_bimap(x, x)
  9934. )
  9935. ),
  9936. ReadonlyArray_map(([x, y]) => `translate(${x}, ${y})`),
  9937. ReadonlyArray_bindTo("transform"),
  9938. x =>
  9939. Effect_sync(() =>
  9940. chat.element.animate(x, {
  9941. duration: 6400,
  9942. easing: mainState.config.timingFunction,
  9943. })
  9944. ),
  9945. Effect_tap(x =>
  9946. Effect_sync(() => {
  9947. x.onfinish = () => {
  9948. chat.animationEnded = !0
  9949. }
  9950. chat.y = ctx.laneY
  9951. const newTime = 6400 * ctx.progress
  9952. x.currentTime = newTime
  9953. })
  9954. ),
  9955. Effect_flatMap(x =>
  9956. Effect_sync(() => {
  9957. chat.animation = Option_some(x)
  9958. })
  9959. ),
  9960. Effect_zipRight(setChatPlayState(chat)(mainState))
  9961. ),
  9962. ],
  9963. x => Effect_all(x)
  9964. )
  9965. ),
  9966. Effect_isSuccess
  9967. ),
  9968. tapEffect = f =>
  9969. (0, external_rxjs_namespaceObject.concatMap)(x =>
  9970. (0, external_rxjs_namespaceObject.from)(runPromise(f(x))).pipe(
  9971. (0, external_rxjs_namespaceObject.map)(() => x)
  9972. )
  9973. ),
  9974. configStream = (provideLog, mainState, co, chatScreen, live) =>
  9975. (0, external_rxjs_namespaceObject.defer)(() =>
  9976. (0, external_rxjs_namespaceObject.merge)(
  9977. (0, external_rxjs_namespaceObject.merge)(
  9978. co.bannedWordRegexs,
  9979. co.bannedWords,
  9980. co.bannedUsers
  9981. ),
  9982. pipe(
  9983. co.fieldScale,
  9984. (0, external_rxjs_namespaceObject.startWith)(
  9985. mainState.config.fieldScale
  9986. ),
  9987. (0, external_rxjs_namespaceObject.map)(
  9988. (
  9989. live => scale =>
  9990. pipe(
  9991. live.chatField.ele,
  9992. Effect_fromOption,
  9993. Effect_flatMap(field =>
  9994. pipe(
  9995. [
  9996. pipe(
  9997. fromNullable(field.parentElement),
  9998. Option_map(x =>
  9999. Effect_sync(() =>
  10000. Object.assign(x.style, {
  10001. transformOrigin:
  10002. (scale >= 1 ? "top" : "bottom") + " left",
  10003. transform: `scale(${scale})`,
  10004. width: 100 / scale + "%",
  10005. height: 100 / scale + "%",
  10006. })
  10007. )
  10008. )
  10009. ),
  10010. pipe(
  10011. live.chatScroller.ele,
  10012. Option_map(scroller =>
  10013. Effect_sync(() => {
  10014. scroller.scrollTop = scroller.scrollHeight
  10015. })
  10016. )
  10017. ),
  10018. ],
  10019. ReadonlyArray_compact,
  10020. x => Effect_all(x)
  10021. )
  10022. ),
  10023. Effect_ignore
  10024. )
  10025. )(live)
  10026. ),
  10027. tapEffect(provideLog)
  10028. ),
  10029. pipe(
  10030. (0, external_rxjs_namespaceObject.merge)(
  10031. pipe(
  10032. (0, external_rxjs_namespaceObject.merge)(
  10033. co.font,
  10034. co.fontSize,
  10035. co.fontWeight,
  10036. co.laneCount,
  10037. co.minSpacing,
  10038. co.flowY1,
  10039. co.flowY2,
  10040. pipe(
  10041. co.flowX1,
  10042. (0, external_rxjs_namespaceObject.startWith)(
  10043. mainState.config.flowX1
  10044. ),
  10045. tapEffect(x =>
  10046. provideLog(
  10047. Effect_sync(() =>
  10048. Object.assign(chatScreen.style, {
  10049. left: 100 * x + "%",
  10050. width: 100 * (mainState.config.flowX2 - x) + "%",
  10051. })
  10052. )
  10053. )
  10054. )
  10055. ),
  10056. pipe(
  10057. co.flowX2,
  10058. tapEffect(x =>
  10059. provideLog(
  10060. Effect_sync(() =>
  10061. Object.assign(chatScreen.style, {
  10062. left: 100 * mainState.config.flowX1 + "%",
  10063. width: 100 * (x - mainState.config.flowX1) + "%",
  10064. })
  10065. )
  10066. )
  10067. )
  10068. ),
  10069. co.textOnly
  10070. ),
  10071. (0, external_rxjs_namespaceObject.map)(() => ({
  10072. render: !0,
  10073. setAnimation: !0,
  10074. }))
  10075. ),
  10076. pipe(
  10077. (0, external_rxjs_namespaceObject.merge)(
  10078. co.color,
  10079. co.ownerColor,
  10080. co.moderatorColor,
  10081. co.memberColor,
  10082. co.shadowColor,
  10083. co.chatOpacity,
  10084. co.shadowFontWeight,
  10085. co.displayChats
  10086. ),
  10087. (0, external_rxjs_namespaceObject.map)(() => ({ render: !0 }))
  10088. ),
  10089. pipe(
  10090. co.flowSpeed,
  10091. (0, external_rxjs_namespaceObject.map)(() => ({
  10092. setPlayState: !0,
  10093. }))
  10094. ),
  10095. pipe(
  10096. (0, external_rxjs_namespaceObject.merge)(
  10097. pipe(
  10098. co.maxChatCount,
  10099. (0, external_rxjs_namespaceObject.map)(
  10100. removeOldChats(mainState)
  10101. ),
  10102. tapEffect(provideLog)
  10103. ),
  10104. co.noOverlap,
  10105. co.timingFunction
  10106. ),
  10107. (0, external_rxjs_namespaceObject.map)(() => ({
  10108. setAnimation: !0,
  10109. }))
  10110. )
  10111. ),
  10112. (0, external_rxjs_namespaceObject.throttleTime)(180, void 0, {
  10113. leading: !0,
  10114. trailing: !0,
  10115. }),
  10116. (0, external_rxjs_namespaceObject.map)(x => ({
  10117. render: !1,
  10118. setAnimation: !1,
  10119. setPlayState: !1,
  10120. ...x,
  10121. })),
  10122. tapEffect(c =>
  10123. provideLog(
  10124. pipe(
  10125. mainState.flowChats,
  10126. ReadonlyArray_filter(x => !x.animationEnded),
  10127. ReadonlyArray_map(chat =>
  10128. pipe(
  10129. [
  10130. pipe(
  10131. renderChat(chat),
  10132. liftPredicate(() => c.render)
  10133. ),
  10134. c.setAnimation
  10135. ? Option_some(setChatAnimation(chat))
  10136. : c.setPlayState
  10137. ? Option_some(setChatPlayState(chat))
  10138. : Option_none(),
  10139. ],
  10140. ReadonlyArray_compact,
  10141. ReadonlyArray_map(apply(mainState)),
  10142. x => Effect_all(x)
  10143. )
  10144. ),
  10145. x => Effect_all(x),
  10146. Effect_asUnit
  10147. )
  10148. )
  10149. )
  10150. ),
  10151. co.lang,
  10152. co.maxChatLength,
  10153. co.simplifyChatField,
  10154. co.createBanButton,
  10155. co.createChats,
  10156. co.displayModName,
  10157. co.displaySuperChatAuthor,
  10158. co.fieldScale
  10159. )
  10160. ),
  10161. external_jsep_namespaceObject = jsep
  10162. var external_jsep_default = __webpack_require__.n(
  10163. external_jsep_namespaceObject
  10164. ),
  10165. u = {
  10166. "||": function (r, e) {
  10167. return r || e
  10168. },
  10169. "&&": function (r, e) {
  10170. return r && e
  10171. },
  10172. "|": function (r, e) {
  10173. return r | e
  10174. },
  10175. "^": function (r, e) {
  10176. return r ^ e
  10177. },
  10178. "&": function (r, e) {
  10179. return r & e
  10180. },
  10181. "==": function (r, e) {
  10182. return r == e
  10183. },
  10184. "!=": function (r, e) {
  10185. return r != e
  10186. },
  10187. "===": function (r, e) {
  10188. return r === e
  10189. },
  10190. "!==": function (r, e) {
  10191. return r !== e
  10192. },
  10193. "<": function (r, e) {
  10194. return r < e
  10195. },
  10196. ">": function (r, e) {
  10197. return r > e
  10198. },
  10199. "<=": function (r, e) {
  10200. return r <= e
  10201. },
  10202. ">=": function (r, e) {
  10203. return r >= e
  10204. },
  10205. "<<": function (r, e) {
  10206. return r << e
  10207. },
  10208. ">>": function (r, e) {
  10209. return r >> e
  10210. },
  10211. ">>>": function (r, e) {
  10212. return r >>> e
  10213. },
  10214. "+": function (r, e) {
  10215. return r + e
  10216. },
  10217. "-": function (r, e) {
  10218. return r - e
  10219. },
  10220. "*": function (r, e) {
  10221. return r * e
  10222. },
  10223. "/": function (r, e) {
  10224. return r / e
  10225. },
  10226. "%": function (r, e) {
  10227. return r % e
  10228. },
  10229. },
  10230. i = {
  10231. "-": function (r) {
  10232. return -r
  10233. },
  10234. "+": function (r) {
  10235. return +r
  10236. },
  10237. "~": function (r) {
  10238. return ~r
  10239. },
  10240. "!": function (r) {
  10241. return !r
  10242. },
  10243. }
  10244. function s(r, e) {
  10245. return r.map(function (r) {
  10246. return a(r, e)
  10247. })
  10248. }
  10249. function c(r, e) {
  10250. var n,
  10251. t = a(r.object, e)
  10252. if (
  10253. ((n = r.computed ? a(r.property, e) : r.property.name),
  10254. /^__proto__|prototype|constructor$/.test(n))
  10255. )
  10256. throw Error('Access to member "' + n + '" disallowed.')
  10257. return [t, t[n]]
  10258. }
  10259. function a(r, e) {
  10260. var n = r
  10261. switch (n.type) {
  10262. case "ArrayExpression":
  10263. return s(n.elements, e)
  10264. case "BinaryExpression":
  10265. return u[n.operator](a(n.left, e), a(n.right, e))
  10266. case "CallExpression":
  10267. var t, o, l
  10268. if (
  10269. ("MemberExpression" === n.callee.type
  10270. ? ((t = (l = c(n.callee, e))[0]), (o = l[1]))
  10271. : (o = a(n.callee, e)),
  10272. "function" != typeof o)
  10273. )
  10274. return
  10275. return o.apply(t, s(n.arguments, e))
  10276. case "ConditionalExpression":
  10277. return a(n.test, e) ? a(n.consequent, e) : a(n.alternate, e)
  10278. case "Identifier":
  10279. return e[n.name]
  10280. case "Literal":
  10281. return n.value
  10282. case "LogicalExpression":
  10283. return "||" === n.operator
  10284. ? a(n.left, e) || a(n.right, e)
  10285. : "&&" === n.operator
  10286. ? a(n.left, e) && a(n.right, e)
  10287. : u[n.operator](a(n.left, e), a(n.right, e))
  10288. case "MemberExpression":
  10289. return c(n, e)[1]
  10290. case "ThisExpression":
  10291. return e
  10292. case "UnaryExpression":
  10293. return i[n.operator](a(n.argument, e))
  10294. default:
  10295. return
  10296. }
  10297. }
  10298. const defaultFilter = config =>
  10299. external_jsep_default()(
  10300. `\nor([\nRA.some(\n flip(flow([inText, RA.some]))(${JSON.stringify(
  10301. config.bannedWords
  10302. )})\n)(RA.compact([\n messageText,\n paymentInfo\n])),\nRA.some(\n flip(flow([matchedByText, RA.some]))(${JSON.stringify(
  10303. config.bannedWordRegexs
  10304. )})\n)(RA.compact([\n messageText,\n paymentInfo\n])),\nO.exists(\n flip(flow([eqText, RA.some]))(${JSON.stringify(
  10305. config.bannedUsers
  10306. )})\n)(authorID)\n])\n`
  10307. ),
  10308. Chainable_bind = F =>
  10309. Function_dual(3, (self, name, f) =>
  10310. F.flatMap(self, a =>
  10311. F.map(f(a), b => Object.assign({}, a, { [name]: b }))
  10312. )
  10313. ),
  10314. Identity_map = Function_dual(2, (self, f) => f(self)),
  10315. Identity_imap = imap(Identity_map),
  10316. Identity_Covariant = { imap: Identity_imap, map: Identity_map },
  10317. Identity_Invariant = { imap: Identity_imap },
  10318. Identity_Chainable = {
  10319. imap: Identity_imap,
  10320. map: Identity_map,
  10321. flatMap: Function_dual(2, (self, f) => f(self)),
  10322. },
  10323. Identity_bindTo = Invariant_bindTo(Identity_Invariant),
  10324. Identity_let_ = let_(Identity_Covariant),
  10325. Identity_bind = Chainable_bind(Identity_Chainable),
  10326. Identity_letDiscard = letDiscard(Identity_Chainable),
  10327. external_astring_namespaceObject = astring,
  10328. fycKey = key => `FYC_${key}`,
  10329. languages = ["FYC_EN", "FYC_JA"],
  10330. stringsArgs = [
  10331. [],
  10332. flow(split(/\r\n|\n/), ReadonlyArray_filter(not(isEmpty))),
  10333. join("\n"),
  10334. ],
  10335. sc = (k, d) => {
  10336. return (
  10337. (key = fycKey(k)),
  10338. (defaultValue = d),
  10339. {
  10340. gmKey: key,
  10341. getValue: Effect_promise(
  10342. async () => (await GM.getValue(key)) ?? defaultValue
  10343. ),
  10344. defaultValue,
  10345. toGm: Function_identity,
  10346. }
  10347. )
  10348. var key, defaultValue
  10349. },
  10350. ic = (k, d, c, g) => {
  10351. return (
  10352. (key = fycKey(k)),
  10353. (toConfig = c),
  10354. pipe(
  10355. { gmKey: key, defaultValue: (defaultValue = d), toGm: g },
  10356. Identity_letDiscard(
  10357. "getValue",
  10358. pipe(
  10359. Effect_promise(() => GM.getValue(key)),
  10360. Effect_map(x => (void 0 !== x ? toConfig(x) : defaultValue))
  10361. )
  10362. )
  10363. )
  10364. )
  10365. var key, defaultValue, toConfig
  10366. },
  10367. src_defaultGMConfig = pipe(
  10368. {
  10369. lang: ic(
  10370. "LANG",
  10371. "FYC_EN",
  10372. x => (languages.includes(x) ? x : "FYC_EN"),
  10373. x => x
  10374. ),
  10375. font: sc("FONT", "MS PGothic"),
  10376. chatOpacity: sc("OPACITY", 0.8),
  10377. color: sc("COLOR", "#ffffff"),
  10378. ownerColor: sc("COLOR_OWNER", "#ffd600"),
  10379. moderatorColor: sc("COLOR_MODERATOR", "#c564ff"),
  10380. memberColor: sc("COLOR_MEMBER", "#9fffff"),
  10381. fontSize: sc("SIZE", 1),
  10382. fontWeight: sc("WEIGHT", 730),
  10383. shadowFontWeight: sc("WEIGHT_SHADOW", 1),
  10384. maxChatCount: sc("LIMIT", 40),
  10385. flowSpeed: sc("SPEED", 18),
  10386. maxChatLength: sc("MAX", 100),
  10387. laneCount: sc("LANE_DIV", 12),
  10388. bannedWords: ic("NG_WORDS", ...stringsArgs),
  10389. bannedWordRegexs: ic("NG_REG_WORDS", ...stringsArgs),
  10390. bannedUsers: ic("NG_USERS", ...stringsArgs),
  10391. createChats: sc("TOGGLE_CREATE_COMMENTS", !0),
  10392. noOverlap: sc("NO_OVERLAP", !0),
  10393. createBanButton: sc("NG_BUTTON", !0),
  10394. simplifyChatField: sc("SIMPLE_CHAT_FIELD", !1),
  10395. displayModName: sc("DISPLAY_MODERATOR_NAME", !0),
  10396. displaySuperChatAuthor: sc("DISPLAY_SUPER_CHAT_AUTHOR", !0),
  10397. textOnly: sc("TEXT_ONLY", !1),
  10398. timingFunction: sc("TIMING_FUNCTION", "linear"),
  10399. displayChats: sc("DISPLAY_COMMENTS", !0),
  10400. minSpacing: sc("MIN_SPACING", 0.5),
  10401. fieldScale: sc("FIELD_SCALE", 1),
  10402. flowY1: sc("flowY1", 0),
  10403. flowY2: sc("flowY2", 1),
  10404. flowX1: sc("flowX1", 0),
  10405. flowX2: sc("flowX2", 1),
  10406. shadowColor: sc("shadowColor", "#000000"),
  10407. logEvents: sc("logEvents", !0),
  10408. },
  10409. Identity_bind("filterExp", x =>
  10410. ic(
  10411. "filterExp",
  10412. external_jsep_default()(
  10413. `\n or([\n RA.some(\n flip(flow([inText, RA.some]))(${JSON.stringify(
  10414. x.bannedWords.defaultValue
  10415. )})\n )(RA.compact([\n messageText,\n paymentInfo\n ])),\n RA.some(\n flip(flow([matchedByText, RA.some]))(${JSON.stringify(
  10416. x.bannedWordRegexs.defaultValue
  10417. )})\n )(RA.compact([\n messageText,\n paymentInfo\n ])),\n O.exists(\n flip(flow([eqText, RA.some]))(${JSON.stringify(
  10418. x.bannedUsers.defaultValue
  10419. )})\n )(authorID)\n ])\n `
  10420. ),
  10421. external_jsep_default(),
  10422. external_astring_namespaceObject.generate
  10423. )
  10424. )
  10425. ),
  10426. src_listeningBroadcastConfigKeys = [
  10427. "lang",
  10428. "bannedWords",
  10429. "bannedWordRegexs",
  10430. "bannedUsers",
  10431. "filterExp",
  10432. "simplifyChatField",
  10433. "createBanButton",
  10434. "fieldScale",
  10435. ],
  10436. src_flatMapOption = f => self =>
  10437. Effect_flatMap(flow(f, Effect_fromOption))(self),
  10438. chatApp = pipe(
  10439. Effect_sync(() => document.querySelector("#chatframe")),
  10440. Effect_map(
  10441. flow(
  10442. fromNullable,
  10443. Option_filter(
  10444. flow(
  10445. x => x.contentDocument?.readyState,
  10446. x => "loading" === x || "complete" === x
  10447. )
  10448. ),
  10449. flatMapNullable(x => x.contentDocument),
  10450. orElse(() => Option_some(document)),
  10451. flatMapNullable(x => x.querySelector("yt-live-chat-app"))
  10452. )
  10453. ),
  10454. Effect_some
  10455. ),
  10456. livePageYt = {
  10457. toggleChatBtnParent: pipe(
  10458. Effect_sync(() => document.querySelector(".ytp-right-controls")),
  10459. Effect_map(fromNullable),
  10460. Effect_some
  10461. ),
  10462. settingsToggleNextElement: pipe(
  10463. Effect_sync(() => document.querySelector("#menu-container")),
  10464. Effect_map(
  10465. flow(
  10466. fromNullable,
  10467. Option_filter(x => null !== x.offsetParent),
  10468. flatMapNullable(x =>
  10469. x.querySelector(".dropdown-trigger.ytd-menu-renderer")
  10470. ),
  10471. orElse(() =>
  10472. fromNullable(
  10473. document.querySelector(
  10474. "#top-row .dropdown-trigger.ytd-menu-renderer"
  10475. )
  10476. )
  10477. )
  10478. )
  10479. ),
  10480. Effect_some
  10481. ),
  10482. settingsContainer: pipe(
  10483. Effect_sync(() => document.body),
  10484. Effect_map(fromNullable),
  10485. Effect_some
  10486. ),
  10487. player: pipe(
  10488. Effect_sync(() => document.querySelector("#movie_player")),
  10489. Effect_map(fromNullable),
  10490. Effect_some
  10491. ),
  10492. video: pipe(
  10493. Effect_sync(() =>
  10494. document.querySelector("video.video-stream.html5-main-video")
  10495. ),
  10496. Effect_map(fromNullable),
  10497. Effect_some
  10498. ),
  10499. chatField: pipe(
  10500. chatApp,
  10501. src_flatMapOption(
  10502. flow(
  10503. x => x.querySelector("#items.yt-live-chat-item-list-renderer"),
  10504. fromNullable
  10505. )
  10506. )
  10507. ),
  10508. chatTicker: pipe(
  10509. chatApp,
  10510. src_flatMapOption(
  10511. flow(
  10512. x => x.querySelector("#items.yt-live-chat-ticker-renderer"),
  10513. fromNullable
  10514. )
  10515. )
  10516. ),
  10517. chatScroller: pipe(
  10518. chatApp,
  10519. src_flatMapOption(
  10520. flow(
  10521. x =>
  10522. x.querySelector(
  10523. "#item-scroller.yt-live-chat-item-list-renderer"
  10524. ),
  10525. fromNullable
  10526. )
  10527. )
  10528. ),
  10529. offlineSlate: pipe(
  10530. Effect_sync(() => document.querySelector(".ytp-offline-slate")),
  10531. Effect_map(fromNullable),
  10532. Effect_some
  10533. ),
  10534. },
  10535. FiberRef_locally = fiberRefLocally,
  10536. logMeta = fiberRefUnsafeMake(Option_none()),
  10537. logWithMeta = level => message => data =>
  10538. pipe(
  10539. Effect_log(message),
  10540. FiberRef_locally(logMeta, Option_some(data)),
  10541. x => locally(level)(x)
  10542. ),
  10543. mainCss = pipe(
  10544. Effect_sync(() => document.createElement("style")),
  10545. Effect_tap(x =>
  10546. Effect_sync(() => {
  10547. x.innerHTML =
  10548. ".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}"
  10549. })
  10550. )
  10551. ),
  10552. makeChatScreen = pipe(
  10553. Effect_sync(() => document.createElement("div")),
  10554. Effect_tap(x =>
  10555. Effect_sync(() =>
  10556. Object.assign(x.style, {
  10557. pointerEvents: "none",
  10558. zIndex: "30",
  10559. position: "absolute",
  10560. overflow: "hidden",
  10561. height: "100%",
  10562. width: "100%",
  10563. })
  10564. )
  10565. )
  10566. ),
  10567. observePair = con =>
  10568. pipe(
  10569. Effect_Do(),
  10570. Effect_bindDiscard(
  10571. "subject",
  10572. Effect_sync(() => new external_rxjs_namespaceObject.Subject())
  10573. ),
  10574. Effect_bind("observer", x =>
  10575. Effect_sync(() => new con(lib(x.subject)))
  10576. )
  10577. ),
  10578. emptyElement = document.createElement("span"),
  10579. appendChatMessage = flip(chat =>
  10580. Effect_flatMap(x =>
  10581. Effect_sync(() => chat.querySelector("#content #message")?.append(x))
  10582. )
  10583. ),
  10584. external_Swal_namespaceObject = Swal
  10585. var external_Swal_default = __webpack_require__.n(
  10586. external_Swal_namespaceObject
  10587. )
  10588. const defaultToast = external_Swal_default().mixin({
  10589. toast: !0,
  10590. position: "bottom-left",
  10591. timer: 2500,
  10592. timerProgressBar: !0,
  10593. showConfirmButton: !1,
  10594. didOpen: toast => {
  10595. toast.addEventListener(
  10596. "pointerenter",
  10597. external_Swal_default().stopTimer
  10598. )
  10599. toast.addEventListener(
  10600. "pointerleave",
  10601. external_Swal_default().resumeTimer
  10602. )
  10603. },
  10604. }),
  10605. template = runPromise(
  10606. pipe(
  10607. document.createElement("button"),
  10608. Effect_succeed,
  10609. Effect_tap(x =>
  10610. Effect_sync(() =>
  10611. x.classList.add("style-scope", "yt-icon-button", "fyc_button")
  10612. )
  10613. ),
  10614. Effect_tap(x =>
  10615. Effect_sync(() =>
  10616. Object.assign(x.style, {
  10617. padding: "0px",
  10618. width: "20px",
  10619. height: "20px",
  10620. fill: "#fff",
  10621. })
  10622. )
  10623. ),
  10624. Effect_tap(x =>
  10625. Effect_sync(() =>
  10626. x.setAttribute("aria-label", "NGに入れる(Ban this user)")
  10627. )
  10628. ),
  10629. Effect_tap(x =>
  10630. Effect_sync(() => {
  10631. x.innerHTML =
  10632. '<svg class="style-scope yt-icon" style="width: 100%; height: 75%; fill: var(--yt-spec-text-secondary);" viewBox="0 0 512 512"><path 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" fill-rule="evenodd"/></svg>'
  10633. })
  10634. )
  10635. )
  10636. ),
  10637. filter_filterOperators = {
  10638. flip,
  10639. flow: fns => flow(...fns),
  10640. and: Monoid_booleanEvery.combineAll,
  10641. or: Monoid_booleanSome.combineAll,
  10642. RA: { some: ReadonlyArray_some, compact: ReadonlyArray_compact },
  10643. O: { exists },
  10644. inText: text => x => includes(x)(text.content),
  10645. eqText: text => x => text.content === x,
  10646. matchedByText: text => x => Boolean(text.content.match(RegExp(x, "u"))),
  10647. isVisible: x => x.visible,
  10648. }
  10649. var typed_assert_build = __webpack_require__(52)
  10650. const tapNonNull = (x, message) => {
  10651. typed_assert_build.Xd(x, message)
  10652. return x
  10653. },
  10654. parseChat = chat => {
  10655. const chatType = chat.querySelector(
  10656. ".yt-live-chat-ticker-paid-message-item-renderer"
  10657. )
  10658. ? "ticker"
  10659. : chat.querySelector(".yt-live-chat-membership-item-renderer")
  10660. ? "membership"
  10661. : chat.querySelector(
  10662. ".yt-live-chat-viewer-engagement-message-renderer"
  10663. )
  10664. ? "engagement"
  10665. : "normal",
  10666. isPaid =
  10667. "ticker" === chatType || Boolean(chat.querySelector("#card")),
  10668. paymentInfo = pipe(
  10669. fromNullable(
  10670. isPaid
  10671. ? chat.querySelector(
  10672. join(", ")([
  10673. "#purchase-amount",
  10674. "#purchase-amount-chip",
  10675. "#content>#text",
  10676. ])
  10677. )?.textContent
  10678. : void 0
  10679. ),
  10680. Option_map(x => ({ visible: !0, content: x }))
  10681. ),
  10682. authorType = chat.querySelector(".owner")
  10683. ? "owner"
  10684. : chat.querySelector(".moderator")
  10685. ? "moderator"
  10686. : chat.querySelector(".member")
  10687. ? "member"
  10688. : "normal",
  10689. messageElement = fromNullable(chat.querySelector("#message")),
  10690. isPaidNormal =
  10691. !!Option_isSome(paymentInfo) &&
  10692. Boolean(chat.querySelector(".yt-live-chat-paid-message-renderer")),
  10693. isPaidSticker =
  10694. !(!Option_isSome(paymentInfo) || isPaidNormal) &&
  10695. Boolean(chat.querySelector(".yt-live-chat-paid-sticker-renderer")),
  10696. textColor = fromNullable(
  10697. isPaidNormal
  10698. ? window
  10699. .getComputedStyle(tapNonNull(chat.querySelector("#header")))
  10700. .getPropertyValue("background-color")
  10701. : isPaidSticker
  10702. ? window
  10703. .getComputedStyle(chat)
  10704. .getPropertyValue(
  10705. "--yt-live-chat-paid-sticker-chip-background-color"
  10706. )
  10707. : void 0
  10708. ),
  10709. paidColor = fromNullable(
  10710. isPaidNormal
  10711. ? window
  10712. .getComputedStyle(tapNonNull(chat.querySelector("#content")))
  10713. .getPropertyValue("background-color")
  10714. : isPaidSticker
  10715. ? window
  10716. .getComputedStyle(chat)
  10717. .getPropertyValue(
  10718. "--yt-live-chat-paid-sticker-background-color"
  10719. )
  10720. : void 0
  10721. ),
  10722. authorPhotoMatches = chat
  10723. .querySelector(join(" ")(["#author-photo", "img"]))
  10724. ?.src.match(/ggpht\.com\/(ytc\/)?(.*)=/),
  10725. authorID = fromNullable(authorPhotoMatches?.at(-1)),
  10726. authorName = fromNullable(
  10727. chat.querySelector("#author-name")?.textContent
  10728. ),
  10729. message = pipe(
  10730. messageElement,
  10731. Option_map(x => ({ visible: !0, content: x.innerHTML }))
  10732. ),
  10733. messageText = pipe(
  10734. messageElement,
  10735. Option_map(x => ({ visible: !0, content: x.textContent ?? "" }))
  10736. )
  10737. return config => ({
  10738. chatType,
  10739. authorType,
  10740. authorID,
  10741. authorName: pipe(
  10742. authorName,
  10743. Option_map(x => ({
  10744. visible:
  10745. ("moderator" === authorType && config.displayModName) ||
  10746. (Option_isSome(paymentInfo) && config.displaySuperChatAuthor),
  10747. content: x,
  10748. }))
  10749. ),
  10750. messageElement,
  10751. message,
  10752. messageText,
  10753. paymentInfo,
  10754. textColor,
  10755. paidColor,
  10756. })
  10757. },
  10758. onChatFieldMutate = (chatScrn, mainState, getConfig, setConfig) =>
  10759. flow(
  10760. ReadonlyArray_flatMap(e => Array.from(e.addedNodes)),
  10761. ReadonlyArray_filter(x => x.children.length > 0),
  10762. ReadonlyArray_reverse,
  10763. ReadonlyArray_map(chat =>
  10764. pipe(
  10765. { getData: parseChat(chat), config: mainState.config },
  10766. Identity_let_("data", x => x.getData(x.config)),
  10767. Effect_succeed,
  10768. Effect_zipLeft(Effect_logDebug("Chat detected")),
  10769. Effect_bind("banned", x => {
  10770. return pipe(
  10771. ((data = x.data),
  10772. (config = x.config),
  10773. pipe(
  10774. data,
  10775. liftPredicate(() =>
  10776. pipe(config.filterExp, x =>
  10777. a(
  10778. x,
  10779. (data => ({
  10780. ...filter_filterOperators,
  10781. authorName: data.authorName,
  10782. message: data.message,
  10783. messageText: data.messageText,
  10784. paymentInfo: data.paymentInfo,
  10785. authorID: pipe(
  10786. data.authorID,
  10787. Option_map(x => ({ visible: !1, content: x }))
  10788. ),
  10789. }))(data)
  10790. )
  10791. )
  10792. ),
  10793. Option_map(x => [
  10794. pipe(
  10795. x.message,
  10796. Option_map(m => m.content)
  10797. ),
  10798. pipe(
  10799. x.paymentInfo,
  10800. Option_map(p => p.content)
  10801. ),
  10802. ]),
  10803. Option_map(ReadonlyArray_map(getOrElse(() => ""))),
  10804. Option_map(JSON.stringify),
  10805. Effect_fromOption,
  10806. Effect_flatMap(x => Effect_logDebug(`Filtered: ${x}`)),
  10807. Effect_isSuccess
  10808. ))
  10809. )
  10810. var data, config
  10811. }),
  10812. Effect_flatMap(ctx =>
  10813. ctx.banned
  10814. ? Effect_sync(() => {
  10815. chat.style.display = "none"
  10816. })
  10817. : Effect_all([
  10818. pipe(
  10819. ctx.config.createChats &&
  10820. "normal" === ctx.data.chatType,
  10821. liftPredicate(Function_identity),
  10822. Effect_fromOption,
  10823. Effect_flatMap(() =>
  10824. ((getData, chatScrn, mainState) =>
  10825. pipe(
  10826. {
  10827. getData,
  10828. element: emptyElement,
  10829. lane: -1,
  10830. animation: Option_none(),
  10831. animationDuration: 0,
  10832. animationEnded: !1,
  10833. width: 2,
  10834. height: getChatFontSize(mainState),
  10835. y: 0,
  10836. },
  10837. x => getChatLane(x, 0)(mainState).interval,
  10838. intervalTooSmall,
  10839. x => x(mainState.config)
  10840. )
  10841. ? Effect_unit()
  10842. : pipe(
  10843. mainState.flowChats,
  10844. findFirstIndex(
  10845. chat =>
  10846. chat.animationEnded ||
  10847. mainState.flowChats.length >=
  10848. mainState.config.maxChatCount
  10849. ),
  10850. offScreenIndex =>
  10851. pipe(
  10852. offScreenIndex,
  10853. Option_map(index =>
  10854. pipe(
  10855. mainState.flowChats,
  10856. unsafeGet(index),
  10857. x => x.element
  10858. )
  10859. ),
  10860. getOrElse(() =>
  10861. document.createElement("span")
  10862. ),
  10863. Effect_succeed,
  10864. Effect_tap(element =>
  10865. pipe(
  10866. offScreenIndex,
  10867. match(
  10868. () =>
  10869. pipe(
  10870. Effect_sync(() =>
  10871. chatScrn.append(element)
  10872. ),
  10873. Effect_zipLeft(
  10874. Effect_logDebug(
  10875. "Flow chat added"
  10876. )
  10877. )
  10878. ),
  10879. i =>
  10880. pipe(
  10881. Effect_sync(
  10882. () =>
  10883. mainState.flowChats.splice(
  10884. i,
  10885. 1
  10886. )?.[0]?.animation ??
  10887. Option_none()
  10888. ),
  10889. Effect_some,
  10890. Effect_flatMap(oldAnimation =>
  10891. Effect_sync(() =>
  10892. oldAnimation.cancel()
  10893. )
  10894. ),
  10895. Effect_ignore
  10896. )
  10897. )
  10898. )
  10899. )
  10900. ),
  10901. Effect_flatMap(element =>
  10902. pipe(
  10903. {
  10904. getData,
  10905. element,
  10906. lane: -1,
  10907. animation: Option_none(),
  10908. animationDuration: 0,
  10909. animationEnded: !1,
  10910. width: 2,
  10911. height: getChatFontSize(mainState),
  10912. y: 0,
  10913. },
  10914. Effect_succeed,
  10915. Effect_zipLeft(
  10916. Effect_sync(() =>
  10917. element.classList.add("fyc_chat")
  10918. )
  10919. )
  10920. )
  10921. ),
  10922. Effect_flatMap(flowChat =>
  10923. pipe(
  10924. mainState,
  10925. Effect_succeed,
  10926. Effect_tap(renderChat(flowChat)),
  10927. Effect_flatMap(
  10928. setChatAnimation(flowChat)
  10929. ),
  10930. Effect_flatMap(x =>
  10931. x
  10932. ? Effect_sync(() =>
  10933. mainState.flowChats.push(flowChat)
  10934. )
  10935. : pipe(
  10936. Effect_sync(() =>
  10937. flowChat.element.remove()
  10938. ),
  10939. Effect_zipLeft(
  10940. Effect_logDebug(
  10941. "Flow chat removed"
  10942. )
  10943. )
  10944. )
  10945. )
  10946. )
  10947. )
  10948. ))(ctx.getData, chatScrn, mainState)
  10949. ),
  10950. Effect_ignore
  10951. ),
  10952. pipe(
  10953. ctx.data.authorID,
  10954. Option_filter(() => ctx.config.createBanButton),
  10955. Option_filter(() => !chat.children.namedItem("card")),
  10956. Effect_fromOption,
  10957. Effect_flatMap(x => {
  10958. return appendChatMessage(
  10959. ((id = x),
  10960. getConfig => setConfig => chat =>
  10961. pipe(
  10962. getConfig.bannedUsers,
  10963. Effect_filterOrFail(
  10964. x => !x.includes(id),
  10965. Option_none
  10966. ),
  10967. Effect_map(
  10968. flow(uniq(String_Equivalence), append(id))
  10969. ),
  10970. Effect_flatMap(x =>
  10971. pipe(
  10972. setConfig.bannedUsers(x),
  10973. Effect_zipRight(
  10974. Effect_sync(() =>
  10975. defaultToast.fire({
  10976. title: `Added Banned User: ${id}`,
  10977. icon: "success",
  10978. })
  10979. )
  10980. )
  10981. )
  10982. ),
  10983. Effect_ignore,
  10984. Effect_zipRight(
  10985. Effect_sync(() => {
  10986. chat.style.display = "none"
  10987. })
  10988. ),
  10989. onclick =>
  10990. pipe(
  10991. Effect_promise(() => template),
  10992. Effect_map(x => x.cloneNode(!0)),
  10993. Effect_tap(x =>
  10994. Effect_sync(() => {
  10995. x.onclick = () => runPromise(onclick)
  10996. })
  10997. )
  10998. )
  10999. ))(getConfig)(setConfig)(chat)
  11000. )(chat)
  11001. var id
  11002. }),
  11003. Effect_zipLeft(Effect_logDebug("Ban button added")),
  11004. Effect_ignore
  11005. ),
  11006. pipe(
  11007. ctx.config.simplifyChatField,
  11008. liftPredicate(Function_identity),
  11009. Effect_fromOption,
  11010. Effect_flatMap(() =>
  11011. (chat =>
  11012. chat.querySelector(
  11013. ".style-scope.yt-live-chat-paid-message-renderer"
  11014. )
  11015. ? Effect_unit()
  11016. : pipe(
  11017. [
  11018. "#author-photo",
  11019. "yt-live-chat-author-chip.style-scope.yt-live-chat-text-message-renderer",
  11020. ],
  11021. ReadonlyArray_map(x =>
  11022. fromNullable(chat.querySelector(x))
  11023. ),
  11024. ReadonlyArray_compact,
  11025. ReadonlyArray_map(x =>
  11026. Effect_sync(() => {
  11027. x.style.display = "none"
  11028. })
  11029. ),
  11030. append(
  11031. Effect_sync(() => {
  11032. chat.style.borderBottom =
  11033. "1px solid var(--yt-spec-text-secondary)"
  11034. })
  11035. ),
  11036. x => Effect_all(x)
  11037. ))(chat)
  11038. ),
  11039. Effect_zipLeft(Effect_logDebug("Chat simplified")),
  11040. Effect_ignore
  11041. ),
  11042. ])
  11043. )
  11044. )
  11045. ),
  11046. x => Effect_all(x)
  11047. ),
  11048. exceptions = ["timingFunction", "lang"],
  11049. isEditable = k => v =>
  11050. ("number" == typeof v ||
  11051. "string" == typeof v ||
  11052. (Array.isArray(v) && ("string" == typeof v[0] || 0 === v.length))) &&
  11053. !ReadonlyArray_some(x => x === k)(exceptions),
  11054. Editable_of = x => [x, Option_none()],
  11055. fromValueText = v => t => [v, Option_some([t, Option_none()])],
  11056. Editable_value = getFirst,
  11057. Editable_text = flow(getSecond, Option_map(getFirst)),
  11058. error = flow(getSecond, flatMap(getSecond)),
  11059. setValue = flow(constant, x => mapFirst(x)),
  11060. setText = x =>
  11061. mapSecond(
  11062. flow(
  11063. Option_map(mapFirst(constant(x))),
  11064. orElse(constant(Option_some([x, Option_none()])))
  11065. )
  11066. ),
  11067. hasError = flow(error, Option_isSome),
  11068. RefinedConstructorsTypeId = Symbol.for("@effect/data/Brand/Refined"),
  11069. nominal = () =>
  11070. Object.assign(args => args, {
  11071. [RefinedConstructorsTypeId]: RefinedConstructorsTypeId,
  11072. option: args => Option_some(args),
  11073. either: args => Either_right(args),
  11074. refine: _args => !0,
  11075. }),
  11076. external_LZString_namespaceObject = LZString,
  11077. makeCompressedLogBlock = nominal(),
  11078. makeLog = nominal(),
  11079. decompressBlock = x =>
  11080. pipe(
  11081. (0, external_LZString_namespaceObject.decompressFromUTF16)(x),
  11082. JSON.parse
  11083. ),
  11084. importLog = s =>
  11085. makeLog(
  11086. pipe(
  11087. "<" === s[0] ? s.slice(5, -6) : s,
  11088. x => JSON.parse(x),
  11089. x => ({
  11090. nextId: x.nextId,
  11091. ...pipe(
  11092. x.blocks,
  11093. mapNonEmpty(
  11094. external_LZString_namespaceObject.decompressFromEncodedURIComponent
  11095. ),
  11096. matchRight(
  11097. () => ({ compressedBlocks: [], lastBlock: [] }),
  11098. (init, last) => ({
  11099. compressedBlocks: ReadonlyArray_map(
  11100. init,
  11101. flow(
  11102. external_LZString_namespaceObject.compressToUTF16,
  11103. makeCompressedLogBlock
  11104. )
  11105. ),
  11106. lastBlock: JSON.parse(last),
  11107. })
  11108. )
  11109. ),
  11110. })
  11111. )
  11112. ),
  11113. settingStateInit = config =>
  11114. pipe(
  11115. config,
  11116. mapObject(([k, v]) => [
  11117. k,
  11118. isEditable(k)(v) ? Editable_of(v) : "filterExp" === k ? void 0 : v,
  11119. ]),
  11120. x => ({
  11121. ...x,
  11122. showPanel: !1,
  11123. mainTab: 0,
  11124. logTab: 0,
  11125. timingStepCount: Editable_of(
  11126. parseInt(
  11127. config.timingFunction.match(/^steps\((\d+),.+/)?.[1] ?? "150",
  11128. 10
  11129. )
  11130. ),
  11131. eventLog: makeLog({
  11132. nextId: 0,
  11133. compressedBlocks: [],
  11134. lastBlock: [],
  11135. }),
  11136. panelRect: new DOMRectReadOnly(0, 0, 660, 395),
  11137. })
  11138. )
  11139. var EMPTY_OBJ = {},
  11140. EMPTY_ARR = [],
  11141. hyperapp_id = a => a,
  11142. hyperapp_map = EMPTY_ARR.map,
  11143. isArray = Array.isArray,
  11144. enqueue =
  11145. "undefined" != typeof requestAnimationFrame
  11146. ? requestAnimationFrame
  11147. : setTimeout,
  11148. createClass = obj => {
  11149. var out = ""
  11150. if ("string" == typeof obj) return obj
  11151. if (isArray(obj))
  11152. for (var tmp, k = 0; k < obj.length; k++)
  11153. (tmp = createClass(obj[k])) && (out += (out && " ") + tmp)
  11154. else for (var k in obj) obj[k] && (out += (out && " ") + k)
  11155. return out
  11156. },
  11157. shouldRestart = (a, b) => {
  11158. for (var k in { ...a, ...b })
  11159. if ("function" == typeof (isArray(a[k]) ? a[k][0] : a[k])) b[k] = a[k]
  11160. else if (a[k] !== b[k]) return !0
  11161. },
  11162. getKey = vdom => (null == vdom ? vdom : vdom.key),
  11163. patchProperty = (node, key, oldValue, newValue, listener, isSvg) => {
  11164. if ("style" === key)
  11165. for (var k in { ...oldValue, ...newValue }) {
  11166. oldValue =
  11167. null == newValue || null == newValue[k] ? "" : newValue[k]
  11168. "-" === k[0]
  11169. ? node[key].setProperty(k, oldValue)
  11170. : (node[key][k] = oldValue)
  11171. }
  11172. else
  11173. "o" === key[0] && "n" === key[1]
  11174. ? ((node.events || (node.events = {}))[(key = key.slice(2))] =
  11175. newValue)
  11176. ? oldValue || node.addEventListener(key, listener)
  11177. : node.removeEventListener(key, listener)
  11178. : !isSvg && "list" !== key && "form" !== key && key in node
  11179. ? (node[key] = newValue ?? "")
  11180. : null == newValue || !1 === newValue
  11181. ? node.removeAttribute(key)
  11182. : node.setAttribute(key, newValue)
  11183. },
  11184. createNode = (vdom, listener, isSvg) => {
  11185. var props = vdom.props,
  11186. node =
  11187. 3 === vdom.type
  11188. ? document.createTextNode(vdom.tag)
  11189. : (isSvg = isSvg || "svg" === vdom.tag)
  11190. ? document.createElementNS(
  11191. "http://www.w3.org/2000/svg",
  11192. vdom.tag,
  11193. props.is && props
  11194. )
  11195. : document.createElement(vdom.tag, props.is && props)
  11196. for (var k in props)
  11197. patchProperty(node, k, null, props[k], listener, isSvg)
  11198. for (var i = 0; i < vdom.children.length; i++)
  11199. node.appendChild(
  11200. createNode(
  11201. (vdom.children[i] = maybeVNode(vdom.children[i])),
  11202. listener,
  11203. isSvg
  11204. )
  11205. )
  11206. return (vdom.node = node)
  11207. },
  11208. hyperapp_patch = (parent, node, oldVNode, newVNode, listener, isSvg) => {
  11209. if (oldVNode === newVNode);
  11210. else if (null != oldVNode && 3 === oldVNode.type && 3 === newVNode.type)
  11211. oldVNode.tag !== newVNode.tag && (node.nodeValue = newVNode.tag)
  11212. else if (null == oldVNode || oldVNode.tag !== newVNode.tag) {
  11213. node = parent.insertBefore(
  11214. createNode((newVNode = maybeVNode(newVNode)), listener, isSvg),
  11215. node
  11216. )
  11217. null != oldVNode && parent.removeChild(oldVNode.node)
  11218. } else {
  11219. var tmpVKid,
  11220. oldVKid,
  11221. oldKey,
  11222. newKey,
  11223. oldProps = oldVNode.props,
  11224. newProps = newVNode.props,
  11225. oldVKids = oldVNode.children,
  11226. newVKids = newVNode.children,
  11227. oldHead = 0,
  11228. newHead = 0,
  11229. oldTail = oldVKids.length - 1,
  11230. newTail = newVKids.length - 1
  11231. isSvg = isSvg || "svg" === newVNode.tag
  11232. for (var i in { ...oldProps, ...newProps })
  11233. ("value" === i || "selected" === i || "checked" === i
  11234. ? node[i]
  11235. : oldProps[i]) !== newProps[i] &&
  11236. patchProperty(node, i, oldProps[i], newProps[i], listener, isSvg)
  11237. for (
  11238. ;
  11239. newHead <= newTail &&
  11240. oldHead <= oldTail &&
  11241. null != (oldKey = getKey(oldVKids[oldHead])) &&
  11242. oldKey === getKey(newVKids[newHead]);
  11243.  
  11244. )
  11245. hyperapp_patch(
  11246. node,
  11247. oldVKids[oldHead].node,
  11248. oldVKids[oldHead],
  11249. (newVKids[newHead] = maybeVNode(
  11250. newVKids[newHead++],
  11251. oldVKids[oldHead++]
  11252. )),
  11253. listener,
  11254. isSvg
  11255. )
  11256. for (
  11257. ;
  11258. newHead <= newTail &&
  11259. oldHead <= oldTail &&
  11260. null != (oldKey = getKey(oldVKids[oldTail])) &&
  11261. oldKey === getKey(newVKids[newTail]);
  11262.  
  11263. )
  11264. hyperapp_patch(
  11265. node,
  11266. oldVKids[oldTail].node,
  11267. oldVKids[oldTail],
  11268. (newVKids[newTail] = maybeVNode(
  11269. newVKids[newTail--],
  11270. oldVKids[oldTail--]
  11271. )),
  11272. listener,
  11273. isSvg
  11274. )
  11275. if (oldHead > oldTail)
  11276. for (; newHead <= newTail; )
  11277. node.insertBefore(
  11278. createNode(
  11279. (newVKids[newHead] = maybeVNode(newVKids[newHead++])),
  11280. listener,
  11281. isSvg
  11282. ),
  11283. (oldVKid = oldVKids[oldHead]) && oldVKid.node
  11284. )
  11285. else if (newHead > newTail)
  11286. for (; oldHead <= oldTail; )
  11287. node.removeChild(oldVKids[oldHead++].node)
  11288. else {
  11289. var keyed = {},
  11290. newKeyed = {}
  11291. for (i = oldHead; i <= oldTail; i++)
  11292. null != (oldKey = oldVKids[i].key) &&
  11293. (keyed[oldKey] = oldVKids[i])
  11294. for (; newHead <= newTail; ) {
  11295. oldKey = getKey((oldVKid = oldVKids[oldHead]))
  11296. newKey = getKey(
  11297. (newVKids[newHead] = maybeVNode(newVKids[newHead], oldVKid))
  11298. )
  11299. if (
  11300. newKeyed[oldKey] ||
  11301. (null != newKey && newKey === getKey(oldVKids[oldHead + 1]))
  11302. ) {
  11303. null == oldKey && node.removeChild(oldVKid.node)
  11304. oldHead++
  11305. } else if (null == newKey || 1 === oldVNode.type) {
  11306. if (null == oldKey) {
  11307. hyperapp_patch(
  11308. node,
  11309. oldVKid && oldVKid.node,
  11310. oldVKid,
  11311. newVKids[newHead],
  11312. listener,
  11313. isSvg
  11314. )
  11315. newHead++
  11316. }
  11317. oldHead++
  11318. } else {
  11319. if (oldKey === newKey) {
  11320. hyperapp_patch(
  11321. node,
  11322. oldVKid.node,
  11323. oldVKid,
  11324. newVKids[newHead],
  11325. listener,
  11326. isSvg
  11327. )
  11328. newKeyed[newKey] = !0
  11329. oldHead++
  11330. } else if (null != (tmpVKid = keyed[newKey])) {
  11331. hyperapp_patch(
  11332. node,
  11333. node.insertBefore(tmpVKid.node, oldVKid && oldVKid.node),
  11334. tmpVKid,
  11335. newVKids[newHead],
  11336. listener,
  11337. isSvg
  11338. )
  11339. newKeyed[newKey] = !0
  11340. } else
  11341. hyperapp_patch(
  11342. node,
  11343. oldVKid && oldVKid.node,
  11344. null,
  11345. newVKids[newHead],
  11346. listener,
  11347. isSvg
  11348. )
  11349. newHead++
  11350. }
  11351. }
  11352. for (; oldHead <= oldTail; )
  11353. null == getKey((oldVKid = oldVKids[oldHead++])) &&
  11354. node.removeChild(oldVKid.node)
  11355. for (var i in keyed)
  11356. null == newKeyed[i] && node.removeChild(keyed[i].node)
  11357. }
  11358. }
  11359. return (newVNode.node = node)
  11360. },
  11361. maybeVNode = (newVNode, oldVNode) =>
  11362. !0 !== newVNode && !1 !== newVNode && newVNode
  11363. ? "function" == typeof newVNode.tag
  11364. ? ((!oldVNode ||
  11365. null == oldVNode.memo ||
  11366. ((a, b) => {
  11367. for (var k in a) if (a[k] !== b[k]) return !0
  11368. for (var k in b) if (a[k] !== b[k]) return !0
  11369. })(oldVNode.memo, newVNode.memo)) &&
  11370. ((oldVNode = newVNode.tag(newVNode.memo)).memo = newVNode.memo),
  11371. oldVNode)
  11372. : newVNode
  11373. : hyperapp_text(""),
  11374. recycleNode = node =>
  11375. 3 === node.nodeType
  11376. ? hyperapp_text(node.nodeValue, node)
  11377. : createVNode(
  11378. node.nodeName.toLowerCase(),
  11379. EMPTY_OBJ,
  11380. hyperapp_map.call(node.childNodes, recycleNode),
  11381. 1,
  11382. node
  11383. ),
  11384. createVNode = (tag, { key, ...props }, children, type, node) => ({
  11385. tag,
  11386. props,
  11387. key,
  11388. children,
  11389. type,
  11390. node,
  11391. }),
  11392. hyperapp_text = (value, node) =>
  11393. createVNode(value, EMPTY_OBJ, EMPTY_ARR, 3, node),
  11394. h = (tag, { class: c, ...props }, children = EMPTY_ARR) =>
  11395. createVNode(
  11396. tag,
  11397. { ...props, ...(c ? { class: createClass(c) } : EMPTY_OBJ) },
  11398. isArray(children) ? children : [children]
  11399. ),
  11400. app = ({
  11401. node,
  11402. view,
  11403. subscriptions,
  11404. dispatch = hyperapp_id,
  11405. init = EMPTY_OBJ,
  11406. }) => {
  11407. var state,
  11408. busy,
  11409. vdom = node && recycleNode(node),
  11410. subs = [],
  11411. update = newState => {
  11412. if (state !== newState) {
  11413. null == (state = newState) &&
  11414. (dispatch = subscriptions = render = hyperapp_id)
  11415. subscriptions &&
  11416. (subs = ((oldSubs, newSubs = EMPTY_ARR, dispatch) => {
  11417. for (
  11418. var oldSub, newSub, subs = [], i = 0;
  11419. i < oldSubs.length || i < newSubs.length;
  11420. i++
  11421. ) {
  11422. oldSub = oldSubs[i]
  11423. newSub = newSubs[i]
  11424. subs.push(
  11425. newSub && !0 !== newSub
  11426. ? !oldSub ||
  11427. newSub[0] !== oldSub[0] ||
  11428. shouldRestart(newSub[1], oldSub[1])
  11429. ? [
  11430. newSub[0],
  11431. newSub[1],
  11432. (oldSub && oldSub[2](),
  11433. newSub[0](dispatch, newSub[1])),
  11434. ]
  11435. : oldSub
  11436. : oldSub && oldSub[2]()
  11437. )
  11438. }
  11439. return subs
  11440. })(subs, subscriptions(state), dispatch))
  11441. view && !busy && enqueue(render, (busy = !0))
  11442. }
  11443. },
  11444. render = () =>
  11445. (node = hyperapp_patch(
  11446. node.parentNode,
  11447. node,
  11448. vdom,
  11449. (vdom = view(state)),
  11450. listener,
  11451. (busy = !1)
  11452. )),
  11453. listener = function (event) {
  11454. dispatch(this.events[event.type], event)
  11455. }
  11456. return (
  11457. (dispatch = dispatch((action, props) =>
  11458. "function" == typeof action
  11459. ? dispatch(action(state, props))
  11460. : isArray(action)
  11461. ? "function" == typeof action[0]
  11462. ? dispatch(action[0], action[1])
  11463. : action
  11464. .slice(1)
  11465. .map(
  11466. fx => fx && !0 !== fx && (fx[0] || fx)(dispatch, fx[1]),
  11467. update(action[0])
  11468. )
  11469. : update(action)
  11470. ))(init),
  11471. dispatch
  11472. )
  11473. }
  11474. const makeComponent = x => tag => ({ tag, view: x(tag) }),
  11475. src_flip =
  11476. x =>
  11477. (...b) =>
  11478. (...a) =>
  11479. x(...a)(...b),
  11480. defaultText = {
  11481. setting: ["Settings", "設定"],
  11482. font: ["Font", "フォント"],
  11483. color: ["Color(Normal)", "色(通常)"],
  11484. ownerColor: ["Color(Owner)", "色(オーナー)"],
  11485. moderatorColor: ["Color(Moderator)", "色(モデレーター)"],
  11486. memberColor: ["Color(Member)", "色(メンバー)"],
  11487. feedback: ["Feedback", "バグ報告と要望"],
  11488. eventLog: ["Event log", "イベントログ"],
  11489. giveFeedback: [
  11490. "Give your feedbacks here(Please attach the event log for bug reports)",
  11491. "バグ報告、要望はこちら(バグの場合は、イベントログを添付してください)",
  11492. ],
  11493. chatOpacity: ["Opacity", "不透明度"],
  11494. fontSize: ["Size", "サイズ"],
  11495. fontWeight: ["Weight", "太さ"],
  11496. shadowFontWeight: ["Weight(Shadow)", "太さ(影)"],
  11497. flowSpeed: ["Speed", "速度"],
  11498. maxChatCount: ["Max number of chats", "最大表示数"],
  11499. maxChatLength: ["Max number of characters", "最大文字数"],
  11500. laneCount: ["Number of rows", "行数"],
  11501. bannedWords: ["Banned Words", "NGワード"],
  11502. bannedWordRegexs: ["Banned Words(Regex)", "NGワード(正規表現)"],
  11503. bannedUsers: ["Banned Users", "NGユーザー"],
  11504. simplifyChatField: ["Simplify", "簡略化する"],
  11505. createBanButton: ["Show ban button", "NGボタンを表示する"],
  11506. displayModName: [
  11507. "Show moderator's name",
  11508. "モデレーターの名前を表示する",
  11509. ],
  11510. displaySuperChatAuthor: [
  11511. "Show super chat author",
  11512. "スパチャの作成者を表示する",
  11513. ],
  11514. createChats: ["Create flowing chats", "チャットを流す"],
  11515. textOnly: ["Text only(ignore emojis)", "文字のみ(絵文字を無視する)"],
  11516. error: ["Error", "エラー"],
  11517. video: ["Video", "画面"],
  11518. chatField: ["Chat Window", "チャット欄"],
  11519. useStepTiming: ["Move chat in steps", "チャットを段階的に動かす"],
  11520. timingStepCount: ["└Step Count", "└段階数"],
  11521. chatFilter: ["Chat Filter", "チャットフィルター"],
  11522. flowChat: ["Flow Chat", "チャット流れ"],
  11523. clearFlowChats: ["Clear Flowing Chats", "流れるチャットをクリアする"],
  11524. flowNewChatIf: [
  11525. "A new chat will appear if all of the followings are met:",
  11526. "新しいチャットは以下のすべてを満たす場合に流れます:",
  11527. ],
  11528. noOverlap: ["└Chats won't overlap", "└他のチャットと重ならない"],
  11529. minSpacing: ["Min spacing between chats", "チャットの最小間隔"],
  11530. fieldScale: ["Scale", "拡大率"],
  11531. copy: ["Copy", "コピーする"],
  11532. showChats: ["Show chats", "チャットを表示する"],
  11533. hideChats: ["Hide chats", "チャットを非表示にする"],
  11534. flowY1: ["Flow area top edge", "流れ範囲の上端"],
  11535. flowY2: ["Flow area bottom edge", "流れ範囲の下端"],
  11536. flowX1: ["Flow area left edge", "流れ範囲の左端"],
  11537. flowX2: ["Flow area right edge", "流れ範囲の右端"],
  11538. shadowColor: ["Color(Shadow)", "色(影)"],
  11539. invalidColor: ["Invalid color", "無効な色"],
  11540. inputNonNumberic: ["Input isn't a number", "入力値が数字でない"],
  11541. invalidSetting: ["Invalid setting", "無効な設定値"],
  11542. logEvents: ["Enable event logging", "イベントログを有効にする"],
  11543. importLog: ["Import event log", "イベントログを取り込む"],
  11544. },
  11545. getText = key => language =>
  11546. defaultText[key]["FYC_EN" === language ? 0 : 1],
  11547. languageLabels = ["English", "日本語"],
  11548. computed = {
  11549. useStepTiming: s => Boolean(s.timingFunction.match(/^steps\(.+/)),
  11550. },
  11551. getState = k => (k in computed ? computed[k] : s => s[k]),
  11552. configEffect = (k, v) => c => () =>
  11553. runPromise(c.provideLog(c.setConfig[k](v))),
  11554. stepTiming = stepCount => `steps(${stepCount}, jump-end)`,
  11555. setComputed = {
  11556. useStepTiming: v => c => s =>
  11557. pipe(
  11558. v ? stepTiming(Editable_value(s.timingStepCount)) : "linear",
  11559. timingFunction => [
  11560. { ...s, timingFunction },
  11561. configEffect("timingFunction", timingFunction)(c),
  11562. ]
  11563. ),
  11564. },
  11565. settingUI_setComputed = setComputed,
  11566. setRange = keyA => keyB => bFn => vA => commander => s =>
  11567. pipe(
  11568. { a: Editable_value(vA) },
  11569. Identity_let_("b", ({ a }) => bFn(a)(Editable_value(s[keyB]))),
  11570. ({ a, b }) =>
  11571. pipe(
  11572. [configEffect(keyA, a), configEffect(keyB, b)],
  11573. xs => c =>
  11574. pipe(
  11575. xs,
  11576. ReadonlyArray_map(x => x(c)),
  11577. effects => [
  11578. { ...s, [keyA]: vA, [keyB]: setValue(b)(s[keyB]) },
  11579. ...effects,
  11580. ]
  11581. )
  11582. )(commander)
  11583. ),
  11584. setState = {
  11585. flowY1: setRange("flowY1")("flowY2")(a => b => Math.max(b, a + 0.05)),
  11586. flowY2: setRange("flowY2")("flowY1")(a => b => Math.min(b, a - 0.05)),
  11587. flowX1: setRange("flowX1")("flowX2")(a => b => Math.max(b, a + 0.05)),
  11588. flowX2: setRange("flowX2")("flowX1")(a => b => Math.min(b, a - 0.05)),
  11589. timingStepCount: v => c => s =>
  11590. pipe(stepTiming(Editable_value(v)), timingFunction => [
  11591. { ...s, timingStepCount: v, timingFunction },
  11592. configEffect("timingFunction", timingFunction)(c),
  11593. ]),
  11594. },
  11595. settingUI_setState = setState,
  11596. updateAt = k => v =>
  11597. pipe(
  11598. k in settingUI_setComputed
  11599. ? settingUI_setComputed[k](v)
  11600. : k in settingUI_setState
  11601. ? settingUI_setState[k](v)
  11602. : c => s =>
  11603. [
  11604. { ...s, [k]: v },
  11605. ...(k in c.setConfig && "filterExp" !== k
  11606. ? [
  11607. configEffect(
  11608. k,
  11609. Array.isArray(v) &&
  11610. 2 === v.length &&
  11611. isEditable(k)(v[0])
  11612. ? Editable_value(v)
  11613. : v
  11614. )(c),
  11615. ]
  11616. : []),
  11617. ]
  11618. )
  11619. var util, objectUtil
  11620. !(function (util) {
  11621. util.assertEqual = val => val
  11622. util.assertIs = function (_arg) {}
  11623. util.assertNever = function (_x) {
  11624. throw new Error()
  11625. }
  11626. util.arrayToEnum = items => {
  11627. const obj = {}
  11628. for (const item of items) obj[item] = item
  11629. return obj
  11630. }
  11631. util.getValidEnumValues = obj => {
  11632. const validKeys = util
  11633. .objectKeys(obj)
  11634. .filter(k => "number" != typeof obj[obj[k]]),
  11635. filtered = {}
  11636. for (const k of validKeys) filtered[k] = obj[k]
  11637. return util.objectValues(filtered)
  11638. }
  11639. util.objectValues = obj =>
  11640. util.objectKeys(obj).map(function (e) {
  11641. return obj[e]
  11642. })
  11643. util.objectKeys =
  11644. "function" == typeof Object.keys
  11645. ? obj => Object.keys(obj)
  11646. : object => {
  11647. const keys = []
  11648. for (const key in object)
  11649. Object.prototype.hasOwnProperty.call(object, key) &&
  11650. keys.push(key)
  11651. return keys
  11652. }
  11653. util.find = (arr, checker) => {
  11654. for (const item of arr) if (checker(item)) return item
  11655. }
  11656. util.isInteger =
  11657. "function" == typeof Number.isInteger
  11658. ? val => Number.isInteger(val)
  11659. : val =>
  11660. "number" == typeof val && isFinite(val) && Math.floor(val) === val
  11661. util.joinValues = function (array, separator = " | ") {
  11662. return array
  11663. .map(val => ("string" == typeof val ? `'${val}'` : val))
  11664. .join(separator)
  11665. }
  11666. util.jsonStringifyReplacer = (_, value) =>
  11667. "bigint" == typeof value ? value.toString() : value
  11668. })(util || (util = {}))
  11669. !(function (objectUtil) {
  11670. objectUtil.mergeShapes = (first, second) => ({ ...first, ...second })
  11671. })(objectUtil || (objectUtil = {}))
  11672. const ZodParsedType = util.arrayToEnum([
  11673. "string",
  11674. "nan",
  11675. "number",
  11676. "integer",
  11677. "float",
  11678. "boolean",
  11679. "date",
  11680. "bigint",
  11681. "symbol",
  11682. "function",
  11683. "undefined",
  11684. "null",
  11685. "array",
  11686. "object",
  11687. "unknown",
  11688. "promise",
  11689. "void",
  11690. "never",
  11691. "map",
  11692. "set",
  11693. ]),
  11694. getParsedType = data => {
  11695. switch (typeof data) {
  11696. case "undefined":
  11697. return ZodParsedType.undefined
  11698. case "string":
  11699. return ZodParsedType.string
  11700. case "number":
  11701. return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number
  11702. case "boolean":
  11703. return ZodParsedType.boolean
  11704. case "function":
  11705. return ZodParsedType.function
  11706. case "bigint":
  11707. return ZodParsedType.bigint
  11708. case "symbol":
  11709. return ZodParsedType.symbol
  11710. case "object":
  11711. return Array.isArray(data)
  11712. ? ZodParsedType.array
  11713. : null === data
  11714. ? ZodParsedType.null
  11715. : data.then &&
  11716. "function" == typeof data.then &&
  11717. data.catch &&
  11718. "function" == typeof data.catch
  11719. ? ZodParsedType.promise
  11720. : "undefined" != typeof Map && data instanceof Map
  11721. ? ZodParsedType.map
  11722. : "undefined" != typeof Set && data instanceof Set
  11723. ? ZodParsedType.set
  11724. : "undefined" != typeof Date && data instanceof Date
  11725. ? ZodParsedType.date
  11726. : ZodParsedType.object
  11727. default:
  11728. return ZodParsedType.unknown
  11729. }
  11730. },
  11731. ZodIssueCode = util.arrayToEnum([
  11732. "invalid_type",
  11733. "invalid_literal",
  11734. "custom",
  11735. "invalid_union",
  11736. "invalid_union_discriminator",
  11737. "invalid_enum_value",
  11738. "unrecognized_keys",
  11739. "invalid_arguments",
  11740. "invalid_return_type",
  11741. "invalid_date",
  11742. "invalid_string",
  11743. "too_small",
  11744. "too_big",
  11745. "invalid_intersection_types",
  11746. "not_multiple_of",
  11747. "not_finite",
  11748. ])
  11749. class ZodError extends Error {
  11750. constructor(issues) {
  11751. super()
  11752. this.issues = []
  11753. this.addIssue = sub => {
  11754. this.issues = [...this.issues, sub]
  11755. }
  11756. this.addIssues = (subs = []) => {
  11757. this.issues = [...this.issues, ...subs]
  11758. }
  11759. const actualProto = new.target.prototype
  11760. Object.setPrototypeOf
  11761. ? Object.setPrototypeOf(this, actualProto)
  11762. : (this.__proto__ = actualProto)
  11763. this.name = "ZodError"
  11764. this.issues = issues
  11765. }
  11766. get errors() {
  11767. return this.issues
  11768. }
  11769. format(_mapper) {
  11770. const mapper =
  11771. _mapper ||
  11772. function (issue) {
  11773. return issue.message
  11774. },
  11775. fieldErrors = { _errors: [] },
  11776. processError = error => {
  11777. for (const issue of error.issues)
  11778. if ("invalid_union" === issue.code)
  11779. issue.unionErrors.map(processError)
  11780. else if ("invalid_return_type" === issue.code)
  11781. processError(issue.returnTypeError)
  11782. else if ("invalid_arguments" === issue.code)
  11783. processError(issue.argumentsError)
  11784. else if (0 === issue.path.length)
  11785. fieldErrors._errors.push(mapper(issue))
  11786. else {
  11787. let curr = fieldErrors,
  11788. i = 0
  11789. for (; i < issue.path.length; ) {
  11790. const el = issue.path[i]
  11791. if (i === issue.path.length - 1) {
  11792. curr[el] = curr[el] || { _errors: [] }
  11793. curr[el]._errors.push(mapper(issue))
  11794. } else curr[el] = curr[el] || { _errors: [] }
  11795. curr = curr[el]
  11796. i++
  11797. }
  11798. }
  11799. }
  11800. processError(this)
  11801. return fieldErrors
  11802. }
  11803. toString() {
  11804. return this.message
  11805. }
  11806. get message() {
  11807. return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2)
  11808. }
  11809. get isEmpty() {
  11810. return 0 === this.issues.length
  11811. }
  11812. flatten(mapper = issue => issue.message) {
  11813. const fieldErrors = {},
  11814. formErrors = []
  11815. for (const sub of this.issues)
  11816. if (sub.path.length > 0) {
  11817. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []
  11818. fieldErrors[sub.path[0]].push(mapper(sub))
  11819. } else formErrors.push(mapper(sub))
  11820. return { formErrors, fieldErrors }
  11821. }
  11822. get formErrors() {
  11823. return this.flatten()
  11824. }
  11825. }
  11826. ZodError.create = issues => new ZodError(issues)
  11827. const errorMap = (issue, _ctx) => {
  11828. let message
  11829. switch (issue.code) {
  11830. case ZodIssueCode.invalid_type:
  11831. message =
  11832. issue.received === ZodParsedType.undefined
  11833. ? "Required"
  11834. : `Expected ${issue.expected}, received ${issue.received}`
  11835. break
  11836. case ZodIssueCode.invalid_literal:
  11837. message = `Invalid literal value, expected ${JSON.stringify(
  11838. issue.expected,
  11839. util.jsonStringifyReplacer
  11840. )}`
  11841. break
  11842. case ZodIssueCode.unrecognized_keys:
  11843. message = `Unrecognized key(s) in object: ${util.joinValues(
  11844. issue.keys,
  11845. ", "
  11846. )}`
  11847. break
  11848. case ZodIssueCode.invalid_union:
  11849. message = "Invalid input"
  11850. break
  11851. case ZodIssueCode.invalid_union_discriminator:
  11852. message = `Invalid discriminator value. Expected ${util.joinValues(
  11853. issue.options
  11854. )}`
  11855. break
  11856. case ZodIssueCode.invalid_enum_value:
  11857. message = `Invalid enum value. Expected ${util.joinValues(
  11858. issue.options
  11859. )}, received '${issue.received}'`
  11860. break
  11861. case ZodIssueCode.invalid_arguments:
  11862. message = "Invalid function arguments"
  11863. break
  11864. case ZodIssueCode.invalid_return_type:
  11865. message = "Invalid function return type"
  11866. break
  11867. case ZodIssueCode.invalid_date:
  11868. message = "Invalid date"
  11869. break
  11870. case ZodIssueCode.invalid_string:
  11871. if ("object" == typeof issue.validation)
  11872. if ("includes" in issue.validation) {
  11873. message = `Invalid input: must include "${issue.validation.includes}"`
  11874. "number" == typeof issue.validation.position &&
  11875. (message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`)
  11876. } else
  11877. "startsWith" in issue.validation
  11878. ? (message = `Invalid input: must start with "${issue.validation.startsWith}"`)
  11879. : "endsWith" in issue.validation
  11880. ? (message = `Invalid input: must end with "${issue.validation.endsWith}"`)
  11881. : util.assertNever(issue.validation)
  11882. else
  11883. message =
  11884. "regex" !== issue.validation
  11885. ? `Invalid ${issue.validation}`
  11886. : "Invalid"
  11887. break
  11888. case ZodIssueCode.too_small:
  11889. message =
  11890. "array" === issue.type
  11891. ? `Array must contain ${
  11892. issue.exact
  11893. ? "exactly"
  11894. : issue.inclusive
  11895. ? "at least"
  11896. : "more than"
  11897. } ${issue.minimum} element(s)`
  11898. : "string" === issue.type
  11899. ? `String must contain ${
  11900. issue.exact
  11901. ? "exactly"
  11902. : issue.inclusive
  11903. ? "at least"
  11904. : "over"
  11905. } ${issue.minimum} character(s)`
  11906. : "number" === issue.type
  11907. ? `Number must be ${
  11908. issue.exact
  11909. ? "exactly equal to "
  11910. : issue.inclusive
  11911. ? "greater than or equal to "
  11912. : "greater than "
  11913. }${issue.minimum}`
  11914. : "date" === issue.type
  11915. ? `Date must be ${
  11916. issue.exact
  11917. ? "exactly equal to "
  11918. : issue.inclusive
  11919. ? "greater than or equal to "
  11920. : "greater than "
  11921. }${new Date(Number(issue.minimum))}`
  11922. : "Invalid input"
  11923. break
  11924. case ZodIssueCode.too_big:
  11925. message =
  11926. "array" === issue.type
  11927. ? `Array must contain ${
  11928. issue.exact
  11929. ? "exactly"
  11930. : issue.inclusive
  11931. ? "at most"
  11932. : "less than"
  11933. } ${issue.maximum} element(s)`
  11934. : "string" === issue.type
  11935. ? `String must contain ${
  11936. issue.exact
  11937. ? "exactly"
  11938. : issue.inclusive
  11939. ? "at most"
  11940. : "under"
  11941. } ${issue.maximum} character(s)`
  11942. : "number" === issue.type
  11943. ? `Number must be ${
  11944. issue.exact
  11945. ? "exactly"
  11946. : issue.inclusive
  11947. ? "less than or equal to"
  11948. : "less than"
  11949. } ${issue.maximum}`
  11950. : "bigint" === issue.type
  11951. ? `BigInt must be ${
  11952. issue.exact
  11953. ? "exactly"
  11954. : issue.inclusive
  11955. ? "less than or equal to"
  11956. : "less than"
  11957. } ${issue.maximum}`
  11958. : "date" === issue.type
  11959. ? `Date must be ${
  11960. issue.exact
  11961. ? "exactly"
  11962. : issue.inclusive
  11963. ? "smaller than or equal to"
  11964. : "smaller than"
  11965. } ${new Date(Number(issue.maximum))}`
  11966. : "Invalid input"
  11967. break
  11968. case ZodIssueCode.custom:
  11969. message = "Invalid input"
  11970. break
  11971. case ZodIssueCode.invalid_intersection_types:
  11972. message = "Intersection results could not be merged"
  11973. break
  11974. case ZodIssueCode.not_multiple_of:
  11975. message = `Number must be a multiple of ${issue.multipleOf}`
  11976. break
  11977. case ZodIssueCode.not_finite:
  11978. message = "Number must be finite"
  11979. break
  11980. default:
  11981. message = _ctx.defaultError
  11982. util.assertNever(issue)
  11983. }
  11984. return { message }
  11985. }
  11986. let overrideErrorMap = errorMap
  11987. function getErrorMap() {
  11988. return overrideErrorMap
  11989. }
  11990. const makeIssue = params => {
  11991. const { data, path, errorMaps, issueData } = params,
  11992. fullPath = [...path, ...(issueData.path || [])],
  11993. fullIssue = { ...issueData, path: fullPath }
  11994. let errorMessage = ""
  11995. const maps = errorMaps
  11996. .filter(m => !!m)
  11997. .slice()
  11998. .reverse()
  11999. for (const map of maps)
  12000. errorMessage = map(fullIssue, {
  12001. data,
  12002. defaultError: errorMessage,
  12003. }).message
  12004. return {
  12005. ...issueData,
  12006. path: fullPath,
  12007. message: issueData.message || errorMessage,
  12008. }
  12009. }
  12010. function addIssueToContext(ctx, issueData) {
  12011. const issue = makeIssue({
  12012. issueData,
  12013. data: ctx.data,
  12014. path: ctx.path,
  12015. errorMaps: [
  12016. ctx.common.contextualErrorMap,
  12017. ctx.schemaErrorMap,
  12018. getErrorMap(),
  12019. errorMap,
  12020. ].filter(x => !!x),
  12021. })
  12022. ctx.common.issues.push(issue)
  12023. }
  12024. class ParseStatus {
  12025. constructor() {
  12026. this.value = "valid"
  12027. }
  12028. dirty() {
  12029. "valid" === this.value && (this.value = "dirty")
  12030. }
  12031. abort() {
  12032. "aborted" !== this.value && (this.value = "aborted")
  12033. }
  12034. static mergeArray(status, results) {
  12035. const arrayValue = []
  12036. for (const s of results) {
  12037. if ("aborted" === s.status) return INVALID
  12038. "dirty" === s.status && status.dirty()
  12039. arrayValue.push(s.value)
  12040. }
  12041. return { status: status.value, value: arrayValue }
  12042. }
  12043. static async mergeObjectAsync(status, pairs) {
  12044. const syncPairs = []
  12045. for (const pair of pairs)
  12046. syncPairs.push({ key: await pair.key, value: await pair.value })
  12047. return ParseStatus.mergeObjectSync(status, syncPairs)
  12048. }
  12049. static mergeObjectSync(status, pairs) {
  12050. const finalObject = {}
  12051. for (const pair of pairs) {
  12052. const { key, value } = pair
  12053. if ("aborted" === key.status) return INVALID
  12054. if ("aborted" === value.status) return INVALID
  12055. "dirty" === key.status && status.dirty()
  12056. "dirty" === value.status && status.dirty()
  12057. ;(void 0 !== value.value || pair.alwaysSet) &&
  12058. (finalObject[key.value] = value.value)
  12059. }
  12060. return { status: status.value, value: finalObject }
  12061. }
  12062. }
  12063. const INVALID = Object.freeze({ status: "aborted" }),
  12064. DIRTY = value => ({ status: "dirty", value }),
  12065. OK = value => ({ status: "valid", value }),
  12066. isAborted = x => "aborted" === x.status,
  12067. isDirty = x => "dirty" === x.status,
  12068. isValid = x => "valid" === x.status,
  12069. isAsync = x => "undefined" != typeof Promise && x instanceof Promise
  12070. var errorUtil
  12071. !(function (errorUtil) {
  12072. errorUtil.errToObj = message =>
  12073. "string" == typeof message ? { message } : message || {}
  12074. errorUtil.toString = message =>
  12075. "string" == typeof message
  12076. ? message
  12077. : null == message
  12078. ? void 0
  12079. : message.message
  12080. })(errorUtil || (errorUtil = {}))
  12081. class ParseInputLazyPath {
  12082. constructor(parent, value, path, key) {
  12083. this._cachedPath = []
  12084. this.parent = parent
  12085. this.data = value
  12086. this._path = path
  12087. this._key = key
  12088. }
  12089. get path() {
  12090. this._cachedPath.length ||
  12091. (this._key instanceof Array
  12092. ? this._cachedPath.push(...this._path, ...this._key)
  12093. : this._cachedPath.push(...this._path, this._key))
  12094. return this._cachedPath
  12095. }
  12096. }
  12097. const handleResult = (ctx, result) => {
  12098. if (isValid(result)) return { success: !0, data: result.value }
  12099. if (!ctx.common.issues.length)
  12100. throw new Error("Validation failed but no issues detected.")
  12101. return {
  12102. success: !1,
  12103. get error() {
  12104. if (this._error) return this._error
  12105. const error = new ZodError(ctx.common.issues)
  12106. this._error = error
  12107. return this._error
  12108. },
  12109. }
  12110. }
  12111. function processCreateParams(params) {
  12112. if (!params) return {}
  12113. const { errorMap, invalid_type_error, required_error, description } =
  12114. params
  12115. if (errorMap && (invalid_type_error || required_error))
  12116. throw new Error(
  12117. 'Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.'
  12118. )
  12119. return errorMap
  12120. ? { errorMap, description }
  12121. : {
  12122. errorMap: (iss, ctx) =>
  12123. "invalid_type" !== iss.code
  12124. ? { message: ctx.defaultError }
  12125. : void 0 === ctx.data
  12126. ? {
  12127. message:
  12128. null != required_error
  12129. ? required_error
  12130. : ctx.defaultError,
  12131. }
  12132. : {
  12133. message:
  12134. null != invalid_type_error
  12135. ? invalid_type_error
  12136. : ctx.defaultError,
  12137. },
  12138. description,
  12139. }
  12140. }
  12141. class ZodType {
  12142. constructor(def) {
  12143. this.spa = this.safeParseAsync
  12144. this._def = def
  12145. this.parse = this.parse.bind(this)
  12146. this.safeParse = this.safeParse.bind(this)
  12147. this.parseAsync = this.parseAsync.bind(this)
  12148. this.safeParseAsync = this.safeParseAsync.bind(this)
  12149. this.spa = this.spa.bind(this)
  12150. this.refine = this.refine.bind(this)
  12151. this.refinement = this.refinement.bind(this)
  12152. this.superRefine = this.superRefine.bind(this)
  12153. this.optional = this.optional.bind(this)
  12154. this.nullable = this.nullable.bind(this)
  12155. this.nullish = this.nullish.bind(this)
  12156. this.array = this.array.bind(this)
  12157. this.promise = this.promise.bind(this)
  12158. this.or = this.or.bind(this)
  12159. this.and = this.and.bind(this)
  12160. this.transform = this.transform.bind(this)
  12161. this.brand = this.brand.bind(this)
  12162. this.default = this.default.bind(this)
  12163. this.catch = this.catch.bind(this)
  12164. this.describe = this.describe.bind(this)
  12165. this.pipe = this.pipe.bind(this)
  12166. this.isNullable = this.isNullable.bind(this)
  12167. this.isOptional = this.isOptional.bind(this)
  12168. }
  12169. get description() {
  12170. return this._def.description
  12171. }
  12172. _getType(input) {
  12173. return getParsedType(input.data)
  12174. }
  12175. _getOrReturnCtx(input, ctx) {
  12176. return (
  12177. ctx || {
  12178. common: input.parent.common,
  12179. data: input.data,
  12180. parsedType: getParsedType(input.data),
  12181. schemaErrorMap: this._def.errorMap,
  12182. path: input.path,
  12183. parent: input.parent,
  12184. }
  12185. )
  12186. }
  12187. _processInputParams(input) {
  12188. return {
  12189. status: new ParseStatus(),
  12190. ctx: {
  12191. common: input.parent.common,
  12192. data: input.data,
  12193. parsedType: getParsedType(input.data),
  12194. schemaErrorMap: this._def.errorMap,
  12195. path: input.path,
  12196. parent: input.parent,
  12197. },
  12198. }
  12199. }
  12200. _parseSync(input) {
  12201. const result = this._parse(input)
  12202. if (isAsync(result))
  12203. throw new Error("Synchronous parse encountered promise.")
  12204. return result
  12205. }
  12206. _parseAsync(input) {
  12207. const result = this._parse(input)
  12208. return Promise.resolve(result)
  12209. }
  12210. parse(data, params) {
  12211. const result = this.safeParse(data, params)
  12212. if (result.success) return result.data
  12213. throw result.error
  12214. }
  12215. safeParse(data, params) {
  12216. var _a
  12217. const ctx = {
  12218. common: {
  12219. issues: [],
  12220. async:
  12221. null !== (_a = null == params ? void 0 : params.async) &&
  12222. void 0 !== _a &&
  12223. _a,
  12224. contextualErrorMap: null == params ? void 0 : params.errorMap,
  12225. },
  12226. path: (null == params ? void 0 : params.path) || [],
  12227. schemaErrorMap: this._def.errorMap,
  12228. parent: null,
  12229. data,
  12230. parsedType: getParsedType(data),
  12231. },
  12232. result = this._parseSync({ data, path: ctx.path, parent: ctx })
  12233. return handleResult(ctx, result)
  12234. }
  12235. async parseAsync(data, params) {
  12236. const result = await this.safeParseAsync(data, params)
  12237. if (result.success) return result.data
  12238. throw result.error
  12239. }
  12240. async safeParseAsync(data, params) {
  12241. const ctx = {
  12242. common: {
  12243. issues: [],
  12244. contextualErrorMap: null == params ? void 0 : params.errorMap,
  12245. async: !0,
  12246. },
  12247. path: (null == params ? void 0 : params.path) || [],
  12248. schemaErrorMap: this._def.errorMap,
  12249. parent: null,
  12250. data,
  12251. parsedType: getParsedType(data),
  12252. },
  12253. maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }),
  12254. result = await (isAsync(maybeAsyncResult)
  12255. ? maybeAsyncResult
  12256. : Promise.resolve(maybeAsyncResult))
  12257. return handleResult(ctx, result)
  12258. }
  12259. refine(check, message) {
  12260. const getIssueProperties = val =>
  12261. "string" == typeof message || void 0 === message
  12262. ? { message }
  12263. : "function" == typeof message
  12264. ? message(val)
  12265. : message
  12266. return this._refinement((val, ctx) => {
  12267. const result = check(val),
  12268. setError = () =>
  12269. ctx.addIssue({
  12270. code: ZodIssueCode.custom,
  12271. ...getIssueProperties(val),
  12272. })
  12273. if ("undefined" != typeof Promise && result instanceof Promise)
  12274. return result.then(data => {
  12275. if (data) return !0
  12276. setError()
  12277. return !1
  12278. })
  12279. if (result) return !0
  12280. setError()
  12281. return !1
  12282. })
  12283. }
  12284. refinement(check, refinementData) {
  12285. return this._refinement((val, ctx) => {
  12286. if (check(val)) return !0
  12287. ctx.addIssue(
  12288. "function" == typeof refinementData
  12289. ? refinementData(val, ctx)
  12290. : refinementData
  12291. )
  12292. return !1
  12293. })
  12294. }
  12295. _refinement(refinement) {
  12296. return new ZodEffects({
  12297. schema: this,
  12298. typeName: ZodFirstPartyTypeKind.ZodEffects,
  12299. effect: { type: "refinement", refinement },
  12300. })
  12301. }
  12302. superRefine(refinement) {
  12303. return this._refinement(refinement)
  12304. }
  12305. optional() {
  12306. return ZodOptional.create(this, this._def)
  12307. }
  12308. nullable() {
  12309. return ZodNullable.create(this, this._def)
  12310. }
  12311. nullish() {
  12312. return this.nullable().optional()
  12313. }
  12314. array() {
  12315. return ZodArray.create(this, this._def)
  12316. }
  12317. promise() {
  12318. return ZodPromise.create(this, this._def)
  12319. }
  12320. or(option) {
  12321. return ZodUnion.create([this, option], this._def)
  12322. }
  12323. and(incoming) {
  12324. return ZodIntersection.create(this, incoming, this._def)
  12325. }
  12326. transform(transform) {
  12327. return new ZodEffects({
  12328. ...processCreateParams(this._def),
  12329. schema: this,
  12330. typeName: ZodFirstPartyTypeKind.ZodEffects,
  12331. effect: { type: "transform", transform },
  12332. })
  12333. }
  12334. default(def) {
  12335. const defaultValueFunc = "function" == typeof def ? def : () => def
  12336. return new ZodDefault({
  12337. ...processCreateParams(this._def),
  12338. innerType: this,
  12339. defaultValue: defaultValueFunc,
  12340. typeName: ZodFirstPartyTypeKind.ZodDefault,
  12341. })
  12342. }
  12343. brand() {
  12344. return new ZodBranded({
  12345. typeName: ZodFirstPartyTypeKind.ZodBranded,
  12346. type: this,
  12347. ...processCreateParams(this._def),
  12348. })
  12349. }
  12350. catch(def) {
  12351. const catchValueFunc = "function" == typeof def ? def : () => def
  12352. return new ZodCatch({
  12353. ...processCreateParams(this._def),
  12354. innerType: this,
  12355. catchValue: catchValueFunc,
  12356. typeName: ZodFirstPartyTypeKind.ZodCatch,
  12357. })
  12358. }
  12359. describe(description) {
  12360. return new (0, this.constructor)({ ...this._def, description })
  12361. }
  12362. pipe(target) {
  12363. return ZodPipeline.create(this, target)
  12364. }
  12365. isOptional() {
  12366. return this.safeParse(void 0).success
  12367. }
  12368. isNullable() {
  12369. return this.safeParse(null).success
  12370. }
  12371. }
  12372. const cuidRegex = /^c[^\s-]{8,}$/i,
  12373. cuid2Regex = /^[a-z][a-z0-9]*$/,
  12374. ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/,
  12375. uuidRegex =
  12376. /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i,
  12377. emailRegex =
  12378. /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/,
  12379. emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,
  12380. ipv4Regex =
  12381. /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,
  12382. ipv6Regex =
  12383. /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/
  12384. class ZodString extends ZodType {
  12385. constructor() {
  12386. super(...arguments)
  12387. this._regex = (regex, validation, message) =>
  12388. this.refinement(data => regex.test(data), {
  12389. validation,
  12390. code: ZodIssueCode.invalid_string,
  12391. ...errorUtil.errToObj(message),
  12392. })
  12393. this.nonempty = message => this.min(1, errorUtil.errToObj(message))
  12394. this.trim = () =>
  12395. new ZodString({
  12396. ...this._def,
  12397. checks: [...this._def.checks, { kind: "trim" }],
  12398. })
  12399. this.toLowerCase = () =>
  12400. new ZodString({
  12401. ...this._def,
  12402. checks: [...this._def.checks, { kind: "toLowerCase" }],
  12403. })
  12404. this.toUpperCase = () =>
  12405. new ZodString({
  12406. ...this._def,
  12407. checks: [...this._def.checks, { kind: "toUpperCase" }],
  12408. })
  12409. }
  12410. _parse(input) {
  12411. this._def.coerce && (input.data = String(input.data))
  12412. if (this._getType(input) !== ZodParsedType.string) {
  12413. const ctx = this._getOrReturnCtx(input)
  12414. addIssueToContext(ctx, {
  12415. code: ZodIssueCode.invalid_type,
  12416. expected: ZodParsedType.string,
  12417. received: ctx.parsedType,
  12418. })
  12419. return INVALID
  12420. }
  12421. const status = new ParseStatus()
  12422. let ctx
  12423. for (const check of this._def.checks)
  12424. if ("min" === check.kind) {
  12425. if (input.data.length < check.value) {
  12426. ctx = this._getOrReturnCtx(input, ctx)
  12427. addIssueToContext(ctx, {
  12428. code: ZodIssueCode.too_small,
  12429. minimum: check.value,
  12430. type: "string",
  12431. inclusive: !0,
  12432. exact: !1,
  12433. message: check.message,
  12434. })
  12435. status.dirty()
  12436. }
  12437. } else if ("max" === check.kind) {
  12438. if (input.data.length > check.value) {
  12439. ctx = this._getOrReturnCtx(input, ctx)
  12440. addIssueToContext(ctx, {
  12441. code: ZodIssueCode.too_big,
  12442. maximum: check.value,
  12443. type: "string",
  12444. inclusive: !0,
  12445. exact: !1,
  12446. message: check.message,
  12447. })
  12448. status.dirty()
  12449. }
  12450. } else if ("length" === check.kind) {
  12451. const tooBig = input.data.length > check.value,
  12452. tooSmall = input.data.length < check.value
  12453. if (tooBig || tooSmall) {
  12454. ctx = this._getOrReturnCtx(input, ctx)
  12455. tooBig
  12456. ? addIssueToContext(ctx, {
  12457. code: ZodIssueCode.too_big,
  12458. maximum: check.value,
  12459. type: "string",
  12460. inclusive: !0,
  12461. exact: !0,
  12462. message: check.message,
  12463. })
  12464. : tooSmall &&
  12465. addIssueToContext(ctx, {
  12466. code: ZodIssueCode.too_small,
  12467. minimum: check.value,
  12468. type: "string",
  12469. inclusive: !0,
  12470. exact: !0,
  12471. message: check.message,
  12472. })
  12473. status.dirty()
  12474. }
  12475. } else if ("email" === check.kind) {
  12476. if (!emailRegex.test(input.data)) {
  12477. ctx = this._getOrReturnCtx(input, ctx)
  12478. addIssueToContext(ctx, {
  12479. validation: "email",
  12480. code: ZodIssueCode.invalid_string,
  12481. message: check.message,
  12482. })
  12483. status.dirty()
  12484. }
  12485. } else if ("emoji" === check.kind) {
  12486. if (!emojiRegex.test(input.data)) {
  12487. ctx = this._getOrReturnCtx(input, ctx)
  12488. addIssueToContext(ctx, {
  12489. validation: "emoji",
  12490. code: ZodIssueCode.invalid_string,
  12491. message: check.message,
  12492. })
  12493. status.dirty()
  12494. }
  12495. } else if ("uuid" === check.kind) {
  12496. if (!uuidRegex.test(input.data)) {
  12497. ctx = this._getOrReturnCtx(input, ctx)
  12498. addIssueToContext(ctx, {
  12499. validation: "uuid",
  12500. code: ZodIssueCode.invalid_string,
  12501. message: check.message,
  12502. })
  12503. status.dirty()
  12504. }
  12505. } else if ("cuid" === check.kind) {
  12506. if (!cuidRegex.test(input.data)) {
  12507. ctx = this._getOrReturnCtx(input, ctx)
  12508. addIssueToContext(ctx, {
  12509. validation: "cuid",
  12510. code: ZodIssueCode.invalid_string,
  12511. message: check.message,
  12512. })
  12513. status.dirty()
  12514. }
  12515. } else if ("cuid2" === check.kind) {
  12516. if (!cuid2Regex.test(input.data)) {
  12517. ctx = this._getOrReturnCtx(input, ctx)
  12518. addIssueToContext(ctx, {
  12519. validation: "cuid2",
  12520. code: ZodIssueCode.invalid_string,
  12521. message: check.message,
  12522. })
  12523. status.dirty()
  12524. }
  12525. } else if ("ulid" === check.kind) {
  12526. if (!ulidRegex.test(input.data)) {
  12527. ctx = this._getOrReturnCtx(input, ctx)
  12528. addIssueToContext(ctx, {
  12529. validation: "ulid",
  12530. code: ZodIssueCode.invalid_string,
  12531. message: check.message,
  12532. })
  12533. status.dirty()
  12534. }
  12535. } else if ("url" === check.kind)
  12536. try {
  12537. new URL(input.data)
  12538. } catch (_a) {
  12539. ctx = this._getOrReturnCtx(input, ctx)
  12540. addIssueToContext(ctx, {
  12541. validation: "url",
  12542. code: ZodIssueCode.invalid_string,
  12543. message: check.message,
  12544. })
  12545. status.dirty()
  12546. }
  12547. else if ("regex" === check.kind) {
  12548. check.regex.lastIndex = 0
  12549. if (!check.regex.test(input.data)) {
  12550. ctx = this._getOrReturnCtx(input, ctx)
  12551. addIssueToContext(ctx, {
  12552. validation: "regex",
  12553. code: ZodIssueCode.invalid_string,
  12554. message: check.message,
  12555. })
  12556. status.dirty()
  12557. }
  12558. } else if ("trim" === check.kind) input.data = input.data.trim()
  12559. else if ("includes" === check.kind) {
  12560. if (!input.data.includes(check.value, check.position)) {
  12561. ctx = this._getOrReturnCtx(input, ctx)
  12562. addIssueToContext(ctx, {
  12563. code: ZodIssueCode.invalid_string,
  12564. validation: { includes: check.value, position: check.position },
  12565. message: check.message,
  12566. })
  12567. status.dirty()
  12568. }
  12569. } else if ("toLowerCase" === check.kind)
  12570. input.data = input.data.toLowerCase()
  12571. else if ("toUpperCase" === check.kind)
  12572. input.data = input.data.toUpperCase()
  12573. else if ("startsWith" === check.kind) {
  12574. if (!input.data.startsWith(check.value)) {
  12575. ctx = this._getOrReturnCtx(input, ctx)
  12576. addIssueToContext(ctx, {
  12577. code: ZodIssueCode.invalid_string,
  12578. validation: { startsWith: check.value },
  12579. message: check.message,
  12580. })
  12581. status.dirty()
  12582. }
  12583. } else if ("endsWith" === check.kind) {
  12584. if (!input.data.endsWith(check.value)) {
  12585. ctx = this._getOrReturnCtx(input, ctx)
  12586. addIssueToContext(ctx, {
  12587. code: ZodIssueCode.invalid_string,
  12588. validation: { endsWith: check.value },
  12589. message: check.message,
  12590. })
  12591. status.dirty()
  12592. }
  12593. } else if ("datetime" === check.kind) {
  12594. if (
  12595. !(
  12596. (args = check).precision
  12597. ? args.offset
  12598. ? new RegExp(
  12599. `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`
  12600. )
  12601. : new RegExp(
  12602. `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`
  12603. )
  12604. : 0 === args.precision
  12605. ? args.offset
  12606. ? new RegExp(
  12607. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"
  12608. )
  12609. : new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$")
  12610. : args.offset
  12611. ? new RegExp(
  12612. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"
  12613. )
  12614. : new RegExp(
  12615. "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"
  12616. )
  12617. ).test(input.data)
  12618. ) {
  12619. ctx = this._getOrReturnCtx(input, ctx)
  12620. addIssueToContext(ctx, {
  12621. code: ZodIssueCode.invalid_string,
  12622. validation: "datetime",
  12623. message: check.message,
  12624. })
  12625. status.dirty()
  12626. }
  12627. } else if ("ip" === check.kind) {
  12628. if (
  12629. !((ip = input.data),
  12630. (version = check.version),
  12631. (("v4" === version || !version) && ipv4Regex.test(ip)) ||
  12632. (("v6" === version || !version) && ipv6Regex.test(ip)))
  12633. ) {
  12634. ctx = this._getOrReturnCtx(input, ctx)
  12635. addIssueToContext(ctx, {
  12636. validation: "ip",
  12637. code: ZodIssueCode.invalid_string,
  12638. message: check.message,
  12639. })
  12640. status.dirty()
  12641. }
  12642. } else util.assertNever(check)
  12643. var ip, version, args
  12644. return { status: status.value, value: input.data }
  12645. }
  12646. _addCheck(check) {
  12647. return new ZodString({
  12648. ...this._def,
  12649. checks: [...this._def.checks, check],
  12650. })
  12651. }
  12652. email(message) {
  12653. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) })
  12654. }
  12655. url(message) {
  12656. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) })
  12657. }
  12658. emoji(message) {
  12659. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) })
  12660. }
  12661. uuid(message) {
  12662. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) })
  12663. }
  12664. cuid(message) {
  12665. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) })
  12666. }
  12667. cuid2(message) {
  12668. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) })
  12669. }
  12670. ulid(message) {
  12671. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) })
  12672. }
  12673. ip(options) {
  12674. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) })
  12675. }
  12676. datetime(options) {
  12677. var _a
  12678. return "string" == typeof options
  12679. ? this._addCheck({
  12680. kind: "datetime",
  12681. precision: null,
  12682. offset: !1,
  12683. message: options,
  12684. })
  12685. : this._addCheck({
  12686. kind: "datetime",
  12687. precision:
  12688. void 0 === (null == options ? void 0 : options.precision)
  12689. ? null
  12690. : null == options
  12691. ? void 0
  12692. : options.precision,
  12693. offset:
  12694. null !== (_a = null == options ? void 0 : options.offset) &&
  12695. void 0 !== _a &&
  12696. _a,
  12697. ...errorUtil.errToObj(null == options ? void 0 : options.message),
  12698. })
  12699. }
  12700. regex(regex, message) {
  12701. return this._addCheck({
  12702. kind: "regex",
  12703. regex,
  12704. ...errorUtil.errToObj(message),
  12705. })
  12706. }
  12707. includes(value, options) {
  12708. return this._addCheck({
  12709. kind: "includes",
  12710. value,
  12711. position: null == options ? void 0 : options.position,
  12712. ...errorUtil.errToObj(null == options ? void 0 : options.message),
  12713. })
  12714. }
  12715. startsWith(value, message) {
  12716. return this._addCheck({
  12717. kind: "startsWith",
  12718. value,
  12719. ...errorUtil.errToObj(message),
  12720. })
  12721. }
  12722. endsWith(value, message) {
  12723. return this._addCheck({
  12724. kind: "endsWith",
  12725. value,
  12726. ...errorUtil.errToObj(message),
  12727. })
  12728. }
  12729. min(minLength, message) {
  12730. return this._addCheck({
  12731. kind: "min",
  12732. value: minLength,
  12733. ...errorUtil.errToObj(message),
  12734. })
  12735. }
  12736. max(maxLength, message) {
  12737. return this._addCheck({
  12738. kind: "max",
  12739. value: maxLength,
  12740. ...errorUtil.errToObj(message),
  12741. })
  12742. }
  12743. length(len, message) {
  12744. return this._addCheck({
  12745. kind: "length",
  12746. value: len,
  12747. ...errorUtil.errToObj(message),
  12748. })
  12749. }
  12750. get isDatetime() {
  12751. return !!this._def.checks.find(ch => "datetime" === ch.kind)
  12752. }
  12753. get isEmail() {
  12754. return !!this._def.checks.find(ch => "email" === ch.kind)
  12755. }
  12756. get isURL() {
  12757. return !!this._def.checks.find(ch => "url" === ch.kind)
  12758. }
  12759. get isEmoji() {
  12760. return !!this._def.checks.find(ch => "emoji" === ch.kind)
  12761. }
  12762. get isUUID() {
  12763. return !!this._def.checks.find(ch => "uuid" === ch.kind)
  12764. }
  12765. get isCUID() {
  12766. return !!this._def.checks.find(ch => "cuid" === ch.kind)
  12767. }
  12768. get isCUID2() {
  12769. return !!this._def.checks.find(ch => "cuid2" === ch.kind)
  12770. }
  12771. get isULID() {
  12772. return !!this._def.checks.find(ch => "ulid" === ch.kind)
  12773. }
  12774. get isIP() {
  12775. return !!this._def.checks.find(ch => "ip" === ch.kind)
  12776. }
  12777. get minLength() {
  12778. let min = null
  12779. for (const ch of this._def.checks)
  12780. "min" === ch.kind &&
  12781. (null === min || ch.value > min) &&
  12782. (min = ch.value)
  12783. return min
  12784. }
  12785. get maxLength() {
  12786. let max = null
  12787. for (const ch of this._def.checks)
  12788. "max" === ch.kind &&
  12789. (null === max || ch.value < max) &&
  12790. (max = ch.value)
  12791. return max
  12792. }
  12793. }
  12794. ZodString.create = params => {
  12795. var _a
  12796. return new ZodString({
  12797. checks: [],
  12798. typeName: ZodFirstPartyTypeKind.ZodString,
  12799. coerce:
  12800. null !== (_a = null == params ? void 0 : params.coerce) &&
  12801. void 0 !== _a &&
  12802. _a,
  12803. ...processCreateParams(params),
  12804. })
  12805. }
  12806. function floatSafeRemainder(val, step) {
  12807. const valDecCount = (val.toString().split(".")[1] || "").length,
  12808. stepDecCount = (step.toString().split(".")[1] || "").length,
  12809. decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount
  12810. return (
  12811. (parseInt(val.toFixed(decCount).replace(".", "")) %
  12812. parseInt(step.toFixed(decCount).replace(".", ""))) /
  12813. Math.pow(10, decCount)
  12814. )
  12815. }
  12816. class ZodNumber extends ZodType {
  12817. constructor() {
  12818. super(...arguments)
  12819. this.min = this.gte
  12820. this.max = this.lte
  12821. this.step = this.multipleOf
  12822. }
  12823. _parse(input) {
  12824. this._def.coerce && (input.data = Number(input.data))
  12825. if (this._getType(input) !== ZodParsedType.number) {
  12826. const ctx = this._getOrReturnCtx(input)
  12827. addIssueToContext(ctx, {
  12828. code: ZodIssueCode.invalid_type,
  12829. expected: ZodParsedType.number,
  12830. received: ctx.parsedType,
  12831. })
  12832. return INVALID
  12833. }
  12834. let ctx
  12835. const status = new ParseStatus()
  12836. for (const check of this._def.checks)
  12837. if ("int" === check.kind) {
  12838. if (!util.isInteger(input.data)) {
  12839. ctx = this._getOrReturnCtx(input, ctx)
  12840. addIssueToContext(ctx, {
  12841. code: ZodIssueCode.invalid_type,
  12842. expected: "integer",
  12843. received: "float",
  12844. message: check.message,
  12845. })
  12846. status.dirty()
  12847. }
  12848. } else if ("min" === check.kind) {
  12849. if (
  12850. check.inclusive
  12851. ? input.data < check.value
  12852. : input.data <= check.value
  12853. ) {
  12854. ctx = this._getOrReturnCtx(input, ctx)
  12855. addIssueToContext(ctx, {
  12856. code: ZodIssueCode.too_small,
  12857. minimum: check.value,
  12858. type: "number",
  12859. inclusive: check.inclusive,
  12860. exact: !1,
  12861. message: check.message,
  12862. })
  12863. status.dirty()
  12864. }
  12865. } else if ("max" === check.kind) {
  12866. if (
  12867. check.inclusive
  12868. ? input.data > check.value
  12869. : input.data >= check.value
  12870. ) {
  12871. ctx = this._getOrReturnCtx(input, ctx)
  12872. addIssueToContext(ctx, {
  12873. code: ZodIssueCode.too_big,
  12874. maximum: check.value,
  12875. type: "number",
  12876. inclusive: check.inclusive,
  12877. exact: !1,
  12878. message: check.message,
  12879. })
  12880. status.dirty()
  12881. }
  12882. } else if ("multipleOf" === check.kind) {
  12883. if (0 !== floatSafeRemainder(input.data, check.value)) {
  12884. ctx = this._getOrReturnCtx(input, ctx)
  12885. addIssueToContext(ctx, {
  12886. code: ZodIssueCode.not_multiple_of,
  12887. multipleOf: check.value,
  12888. message: check.message,
  12889. })
  12890. status.dirty()
  12891. }
  12892. } else if ("finite" === check.kind) {
  12893. if (!Number.isFinite(input.data)) {
  12894. ctx = this._getOrReturnCtx(input, ctx)
  12895. addIssueToContext(ctx, {
  12896. code: ZodIssueCode.not_finite,
  12897. message: check.message,
  12898. })
  12899. status.dirty()
  12900. }
  12901. } else util.assertNever(check)
  12902. return { status: status.value, value: input.data }
  12903. }
  12904. gte(value, message) {
  12905. return this.setLimit("min", value, !0, errorUtil.toString(message))
  12906. }
  12907. gt(value, message) {
  12908. return this.setLimit("min", value, !1, errorUtil.toString(message))
  12909. }
  12910. lte(value, message) {
  12911. return this.setLimit("max", value, !0, errorUtil.toString(message))
  12912. }
  12913. lt(value, message) {
  12914. return this.setLimit("max", value, !1, errorUtil.toString(message))
  12915. }
  12916. setLimit(kind, value, inclusive, message) {
  12917. return new ZodNumber({
  12918. ...this._def,
  12919. checks: [
  12920. ...this._def.checks,
  12921. { kind, value, inclusive, message: errorUtil.toString(message) },
  12922. ],
  12923. })
  12924. }
  12925. _addCheck(check) {
  12926. return new ZodNumber({
  12927. ...this._def,
  12928. checks: [...this._def.checks, check],
  12929. })
  12930. }
  12931. int(message) {
  12932. return this._addCheck({
  12933. kind: "int",
  12934. message: errorUtil.toString(message),
  12935. })
  12936. }
  12937. positive(message) {
  12938. return this._addCheck({
  12939. kind: "min",
  12940. value: 0,
  12941. inclusive: !1,
  12942. message: errorUtil.toString(message),
  12943. })
  12944. }
  12945. negative(message) {
  12946. return this._addCheck({
  12947. kind: "max",
  12948. value: 0,
  12949. inclusive: !1,
  12950. message: errorUtil.toString(message),
  12951. })
  12952. }
  12953. nonpositive(message) {
  12954. return this._addCheck({
  12955. kind: "max",
  12956. value: 0,
  12957. inclusive: !0,
  12958. message: errorUtil.toString(message),
  12959. })
  12960. }
  12961. nonnegative(message) {
  12962. return this._addCheck({
  12963. kind: "min",
  12964. value: 0,
  12965. inclusive: !0,
  12966. message: errorUtil.toString(message),
  12967. })
  12968. }
  12969. multipleOf(value, message) {
  12970. return this._addCheck({
  12971. kind: "multipleOf",
  12972. value,
  12973. message: errorUtil.toString(message),
  12974. })
  12975. }
  12976. finite(message) {
  12977. return this._addCheck({
  12978. kind: "finite",
  12979. message: errorUtil.toString(message),
  12980. })
  12981. }
  12982. safe(message) {
  12983. return this._addCheck({
  12984. kind: "min",
  12985. inclusive: !0,
  12986. value: Number.MIN_SAFE_INTEGER,
  12987. message: errorUtil.toString(message),
  12988. })._addCheck({
  12989. kind: "max",
  12990. inclusive: !0,
  12991. value: Number.MAX_SAFE_INTEGER,
  12992. message: errorUtil.toString(message),
  12993. })
  12994. }
  12995. get minValue() {
  12996. let min = null
  12997. for (const ch of this._def.checks)
  12998. "min" === ch.kind &&
  12999. (null === min || ch.value > min) &&
  13000. (min = ch.value)
  13001. return min
  13002. }
  13003. get maxValue() {
  13004. let max = null
  13005. for (const ch of this._def.checks)
  13006. "max" === ch.kind &&
  13007. (null === max || ch.value < max) &&
  13008. (max = ch.value)
  13009. return max
  13010. }
  13011. get isInt() {
  13012. return !!this._def.checks.find(
  13013. ch =>
  13014. "int" === ch.kind ||
  13015. ("multipleOf" === ch.kind && util.isInteger(ch.value))
  13016. )
  13017. }
  13018. get isFinite() {
  13019. let max = null,
  13020. min = null
  13021. for (const ch of this._def.checks) {
  13022. if (
  13023. "finite" === ch.kind ||
  13024. "int" === ch.kind ||
  13025. "multipleOf" === ch.kind
  13026. )
  13027. return !0
  13028. "min" === ch.kind
  13029. ? (null === min || ch.value > min) && (min = ch.value)
  13030. : "max" === ch.kind &&
  13031. (null === max || ch.value < max) &&
  13032. (max = ch.value)
  13033. }
  13034. return Number.isFinite(min) && Number.isFinite(max)
  13035. }
  13036. }
  13037. ZodNumber.create = params =>
  13038. new ZodNumber({
  13039. checks: [],
  13040. typeName: ZodFirstPartyTypeKind.ZodNumber,
  13041. coerce: (null == params ? void 0 : params.coerce) || !1,
  13042. ...processCreateParams(params),
  13043. })
  13044. class ZodBigInt extends ZodType {
  13045. constructor() {
  13046. super(...arguments)
  13047. this.min = this.gte
  13048. this.max = this.lte
  13049. }
  13050. _parse(input) {
  13051. this._def.coerce && (input.data = BigInt(input.data))
  13052. if (this._getType(input) !== ZodParsedType.bigint) {
  13053. const ctx = this._getOrReturnCtx(input)
  13054. addIssueToContext(ctx, {
  13055. code: ZodIssueCode.invalid_type,
  13056. expected: ZodParsedType.bigint,
  13057. received: ctx.parsedType,
  13058. })
  13059. return INVALID
  13060. }
  13061. let ctx
  13062. const status = new ParseStatus()
  13063. for (const check of this._def.checks)
  13064. if ("min" === check.kind) {
  13065. if (
  13066. check.inclusive
  13067. ? input.data < check.value
  13068. : input.data <= check.value
  13069. ) {
  13070. ctx = this._getOrReturnCtx(input, ctx)
  13071. addIssueToContext(ctx, {
  13072. code: ZodIssueCode.too_small,
  13073. type: "bigint",
  13074. minimum: check.value,
  13075. inclusive: check.inclusive,
  13076. message: check.message,
  13077. })
  13078. status.dirty()
  13079. }
  13080. } else if ("max" === check.kind) {
  13081. if (
  13082. check.inclusive
  13083. ? input.data > check.value
  13084. : input.data >= check.value
  13085. ) {
  13086. ctx = this._getOrReturnCtx(input, ctx)
  13087. addIssueToContext(ctx, {
  13088. code: ZodIssueCode.too_big,
  13089. type: "bigint",
  13090. maximum: check.value,
  13091. inclusive: check.inclusive,
  13092. message: check.message,
  13093. })
  13094. status.dirty()
  13095. }
  13096. } else if ("multipleOf" === check.kind) {
  13097. if (input.data % check.value !== BigInt(0)) {
  13098. ctx = this._getOrReturnCtx(input, ctx)
  13099. addIssueToContext(ctx, {
  13100. code: ZodIssueCode.not_multiple_of,
  13101. multipleOf: check.value,
  13102. message: check.message,
  13103. })
  13104. status.dirty()
  13105. }
  13106. } else util.assertNever(check)
  13107. return { status: status.value, value: input.data }
  13108. }
  13109. gte(value, message) {
  13110. return this.setLimit("min", value, !0, errorUtil.toString(message))
  13111. }
  13112. gt(value, message) {
  13113. return this.setLimit("min", value, !1, errorUtil.toString(message))
  13114. }
  13115. lte(value, message) {
  13116. return this.setLimit("max", value, !0, errorUtil.toString(message))
  13117. }
  13118. lt(value, message) {
  13119. return this.setLimit("max", value, !1, errorUtil.toString(message))
  13120. }
  13121. setLimit(kind, value, inclusive, message) {
  13122. return new ZodBigInt({
  13123. ...this._def,
  13124. checks: [
  13125. ...this._def.checks,
  13126. { kind, value, inclusive, message: errorUtil.toString(message) },
  13127. ],
  13128. })
  13129. }
  13130. _addCheck(check) {
  13131. return new ZodBigInt({
  13132. ...this._def,
  13133. checks: [...this._def.checks, check],
  13134. })
  13135. }
  13136. positive(message) {
  13137. return this._addCheck({
  13138. kind: "min",
  13139. value: BigInt(0),
  13140. inclusive: !1,
  13141. message: errorUtil.toString(message),
  13142. })
  13143. }
  13144. negative(message) {
  13145. return this._addCheck({
  13146. kind: "max",
  13147. value: BigInt(0),
  13148. inclusive: !1,
  13149. message: errorUtil.toString(message),
  13150. })
  13151. }
  13152. nonpositive(message) {
  13153. return this._addCheck({
  13154. kind: "max",
  13155. value: BigInt(0),
  13156. inclusive: !0,
  13157. message: errorUtil.toString(message),
  13158. })
  13159. }
  13160. nonnegative(message) {
  13161. return this._addCheck({
  13162. kind: "min",
  13163. value: BigInt(0),
  13164. inclusive: !0,
  13165. message: errorUtil.toString(message),
  13166. })
  13167. }
  13168. multipleOf(value, message) {
  13169. return this._addCheck({
  13170. kind: "multipleOf",
  13171. value,
  13172. message: errorUtil.toString(message),
  13173. })
  13174. }
  13175. get minValue() {
  13176. let min = null
  13177. for (const ch of this._def.checks)
  13178. "min" === ch.kind &&
  13179. (null === min || ch.value > min) &&
  13180. (min = ch.value)
  13181. return min
  13182. }
  13183. get maxValue() {
  13184. let max = null
  13185. for (const ch of this._def.checks)
  13186. "max" === ch.kind &&
  13187. (null === max || ch.value < max) &&
  13188. (max = ch.value)
  13189. return max
  13190. }
  13191. }
  13192. ZodBigInt.create = params => {
  13193. var _a
  13194. return new ZodBigInt({
  13195. checks: [],
  13196. typeName: ZodFirstPartyTypeKind.ZodBigInt,
  13197. coerce:
  13198. null !== (_a = null == params ? void 0 : params.coerce) &&
  13199. void 0 !== _a &&
  13200. _a,
  13201. ...processCreateParams(params),
  13202. })
  13203. }
  13204. class ZodBoolean extends ZodType {
  13205. _parse(input) {
  13206. this._def.coerce && (input.data = Boolean(input.data))
  13207. if (this._getType(input) !== ZodParsedType.boolean) {
  13208. const ctx = this._getOrReturnCtx(input)
  13209. addIssueToContext(ctx, {
  13210. code: ZodIssueCode.invalid_type,
  13211. expected: ZodParsedType.boolean,
  13212. received: ctx.parsedType,
  13213. })
  13214. return INVALID
  13215. }
  13216. return OK(input.data)
  13217. }
  13218. }
  13219. ZodBoolean.create = params =>
  13220. new ZodBoolean({
  13221. typeName: ZodFirstPartyTypeKind.ZodBoolean,
  13222. coerce: (null == params ? void 0 : params.coerce) || !1,
  13223. ...processCreateParams(params),
  13224. })
  13225. class ZodDate extends ZodType {
  13226. _parse(input) {
  13227. this._def.coerce && (input.data = new Date(input.data))
  13228. if (this._getType(input) !== ZodParsedType.date) {
  13229. const ctx = this._getOrReturnCtx(input)
  13230. addIssueToContext(ctx, {
  13231. code: ZodIssueCode.invalid_type,
  13232. expected: ZodParsedType.date,
  13233. received: ctx.parsedType,
  13234. })
  13235. return INVALID
  13236. }
  13237. if (isNaN(input.data.getTime())) {
  13238. addIssueToContext(this._getOrReturnCtx(input), {
  13239. code: ZodIssueCode.invalid_date,
  13240. })
  13241. return INVALID
  13242. }
  13243. const status = new ParseStatus()
  13244. let ctx
  13245. for (const check of this._def.checks)
  13246. if ("min" === check.kind) {
  13247. if (input.data.getTime() < check.value) {
  13248. ctx = this._getOrReturnCtx(input, ctx)
  13249. addIssueToContext(ctx, {
  13250. code: ZodIssueCode.too_small,
  13251. message: check.message,
  13252. inclusive: !0,
  13253. exact: !1,
  13254. minimum: check.value,
  13255. type: "date",
  13256. })
  13257. status.dirty()
  13258. }
  13259. } else if ("max" === check.kind) {
  13260. if (input.data.getTime() > check.value) {
  13261. ctx = this._getOrReturnCtx(input, ctx)
  13262. addIssueToContext(ctx, {
  13263. code: ZodIssueCode.too_big,
  13264. message: check.message,
  13265. inclusive: !0,
  13266. exact: !1,
  13267. maximum: check.value,
  13268. type: "date",
  13269. })
  13270. status.dirty()
  13271. }
  13272. } else util.assertNever(check)
  13273. return { status: status.value, value: new Date(input.data.getTime()) }
  13274. }
  13275. _addCheck(check) {
  13276. return new ZodDate({
  13277. ...this._def,
  13278. checks: [...this._def.checks, check],
  13279. })
  13280. }
  13281. min(minDate, message) {
  13282. return this._addCheck({
  13283. kind: "min",
  13284. value: minDate.getTime(),
  13285. message: errorUtil.toString(message),
  13286. })
  13287. }
  13288. max(maxDate, message) {
  13289. return this._addCheck({
  13290. kind: "max",
  13291. value: maxDate.getTime(),
  13292. message: errorUtil.toString(message),
  13293. })
  13294. }
  13295. get minDate() {
  13296. let min = null
  13297. for (const ch of this._def.checks)
  13298. "min" === ch.kind &&
  13299. (null === min || ch.value > min) &&
  13300. (min = ch.value)
  13301. return null != min ? new Date(min) : null
  13302. }
  13303. get maxDate() {
  13304. let max = null
  13305. for (const ch of this._def.checks)
  13306. "max" === ch.kind &&
  13307. (null === max || ch.value < max) &&
  13308. (max = ch.value)
  13309. return null != max ? new Date(max) : null
  13310. }
  13311. }
  13312. ZodDate.create = params =>
  13313. new ZodDate({
  13314. checks: [],
  13315. coerce: (null == params ? void 0 : params.coerce) || !1,
  13316. typeName: ZodFirstPartyTypeKind.ZodDate,
  13317. ...processCreateParams(params),
  13318. })
  13319. class ZodSymbol extends ZodType {
  13320. _parse(input) {
  13321. if (this._getType(input) !== ZodParsedType.symbol) {
  13322. const ctx = this._getOrReturnCtx(input)
  13323. addIssueToContext(ctx, {
  13324. code: ZodIssueCode.invalid_type,
  13325. expected: ZodParsedType.symbol,
  13326. received: ctx.parsedType,
  13327. })
  13328. return INVALID
  13329. }
  13330. return OK(input.data)
  13331. }
  13332. }
  13333. ZodSymbol.create = params =>
  13334. new ZodSymbol({
  13335. typeName: ZodFirstPartyTypeKind.ZodSymbol,
  13336. ...processCreateParams(params),
  13337. })
  13338. class ZodUndefined extends ZodType {
  13339. _parse(input) {
  13340. if (this._getType(input) !== ZodParsedType.undefined) {
  13341. const ctx = this._getOrReturnCtx(input)
  13342. addIssueToContext(ctx, {
  13343. code: ZodIssueCode.invalid_type,
  13344. expected: ZodParsedType.undefined,
  13345. received: ctx.parsedType,
  13346. })
  13347. return INVALID
  13348. }
  13349. return OK(input.data)
  13350. }
  13351. }
  13352. ZodUndefined.create = params =>
  13353. new ZodUndefined({
  13354. typeName: ZodFirstPartyTypeKind.ZodUndefined,
  13355. ...processCreateParams(params),
  13356. })
  13357. class ZodNull extends ZodType {
  13358. _parse(input) {
  13359. if (this._getType(input) !== ZodParsedType.null) {
  13360. const ctx = this._getOrReturnCtx(input)
  13361. addIssueToContext(ctx, {
  13362. code: ZodIssueCode.invalid_type,
  13363. expected: ZodParsedType.null,
  13364. received: ctx.parsedType,
  13365. })
  13366. return INVALID
  13367. }
  13368. return OK(input.data)
  13369. }
  13370. }
  13371. ZodNull.create = params =>
  13372. new ZodNull({
  13373. typeName: ZodFirstPartyTypeKind.ZodNull,
  13374. ...processCreateParams(params),
  13375. })
  13376. class ZodAny extends ZodType {
  13377. constructor() {
  13378. super(...arguments)
  13379. this._any = !0
  13380. }
  13381. _parse(input) {
  13382. return OK(input.data)
  13383. }
  13384. }
  13385. ZodAny.create = params =>
  13386. new ZodAny({
  13387. typeName: ZodFirstPartyTypeKind.ZodAny,
  13388. ...processCreateParams(params),
  13389. })
  13390. class ZodUnknown extends ZodType {
  13391. constructor() {
  13392. super(...arguments)
  13393. this._unknown = !0
  13394. }
  13395. _parse(input) {
  13396. return OK(input.data)
  13397. }
  13398. }
  13399. ZodUnknown.create = params =>
  13400. new ZodUnknown({
  13401. typeName: ZodFirstPartyTypeKind.ZodUnknown,
  13402. ...processCreateParams(params),
  13403. })
  13404. class ZodNever extends ZodType {
  13405. _parse(input) {
  13406. const ctx = this._getOrReturnCtx(input)
  13407. addIssueToContext(ctx, {
  13408. code: ZodIssueCode.invalid_type,
  13409. expected: ZodParsedType.never,
  13410. received: ctx.parsedType,
  13411. })
  13412. return INVALID
  13413. }
  13414. }
  13415. ZodNever.create = params =>
  13416. new ZodNever({
  13417. typeName: ZodFirstPartyTypeKind.ZodNever,
  13418. ...processCreateParams(params),
  13419. })
  13420. class ZodVoid extends ZodType {
  13421. _parse(input) {
  13422. if (this._getType(input) !== ZodParsedType.undefined) {
  13423. const ctx = this._getOrReturnCtx(input)
  13424. addIssueToContext(ctx, {
  13425. code: ZodIssueCode.invalid_type,
  13426. expected: ZodParsedType.void,
  13427. received: ctx.parsedType,
  13428. })
  13429. return INVALID
  13430. }
  13431. return OK(input.data)
  13432. }
  13433. }
  13434. ZodVoid.create = params =>
  13435. new ZodVoid({
  13436. typeName: ZodFirstPartyTypeKind.ZodVoid,
  13437. ...processCreateParams(params),
  13438. })
  13439. class ZodArray extends ZodType {
  13440. _parse(input) {
  13441. const { ctx, status } = this._processInputParams(input),
  13442. def = this._def
  13443. if (ctx.parsedType !== ZodParsedType.array) {
  13444. addIssueToContext(ctx, {
  13445. code: ZodIssueCode.invalid_type,
  13446. expected: ZodParsedType.array,
  13447. received: ctx.parsedType,
  13448. })
  13449. return INVALID
  13450. }
  13451. if (null !== def.exactLength) {
  13452. const tooBig = ctx.data.length > def.exactLength.value,
  13453. tooSmall = ctx.data.length < def.exactLength.value
  13454. if (tooBig || tooSmall) {
  13455. addIssueToContext(ctx, {
  13456. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  13457. minimum: tooSmall ? def.exactLength.value : void 0,
  13458. maximum: tooBig ? def.exactLength.value : void 0,
  13459. type: "array",
  13460. inclusive: !0,
  13461. exact: !0,
  13462. message: def.exactLength.message,
  13463. })
  13464. status.dirty()
  13465. }
  13466. }
  13467. if (null !== def.minLength && ctx.data.length < def.minLength.value) {
  13468. addIssueToContext(ctx, {
  13469. code: ZodIssueCode.too_small,
  13470. minimum: def.minLength.value,
  13471. type: "array",
  13472. inclusive: !0,
  13473. exact: !1,
  13474. message: def.minLength.message,
  13475. })
  13476. status.dirty()
  13477. }
  13478. if (null !== def.maxLength && ctx.data.length > def.maxLength.value) {
  13479. addIssueToContext(ctx, {
  13480. code: ZodIssueCode.too_big,
  13481. maximum: def.maxLength.value,
  13482. type: "array",
  13483. inclusive: !0,
  13484. exact: !1,
  13485. message: def.maxLength.message,
  13486. })
  13487. status.dirty()
  13488. }
  13489. if (ctx.common.async)
  13490. return Promise.all(
  13491. [...ctx.data].map((item, i) =>
  13492. def.type._parseAsync(
  13493. new ParseInputLazyPath(ctx, item, ctx.path, i)
  13494. )
  13495. )
  13496. ).then(result => ParseStatus.mergeArray(status, result))
  13497. const result = [...ctx.data].map((item, i) =>
  13498. def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i))
  13499. )
  13500. return ParseStatus.mergeArray(status, result)
  13501. }
  13502. get element() {
  13503. return this._def.type
  13504. }
  13505. min(minLength, message) {
  13506. return new ZodArray({
  13507. ...this._def,
  13508. minLength: { value: minLength, message: errorUtil.toString(message) },
  13509. })
  13510. }
  13511. max(maxLength, message) {
  13512. return new ZodArray({
  13513. ...this._def,
  13514. maxLength: { value: maxLength, message: errorUtil.toString(message) },
  13515. })
  13516. }
  13517. length(len, message) {
  13518. return new ZodArray({
  13519. ...this._def,
  13520. exactLength: { value: len, message: errorUtil.toString(message) },
  13521. })
  13522. }
  13523. nonempty(message) {
  13524. return this.min(1, message)
  13525. }
  13526. }
  13527. ZodArray.create = (schema, params) =>
  13528. new ZodArray({
  13529. type: schema,
  13530. minLength: null,
  13531. maxLength: null,
  13532. exactLength: null,
  13533. typeName: ZodFirstPartyTypeKind.ZodArray,
  13534. ...processCreateParams(params),
  13535. })
  13536. function deepPartialify(schema) {
  13537. if (schema instanceof ZodObject) {
  13538. const newShape = {}
  13539. for (const key in schema.shape) {
  13540. const fieldSchema = schema.shape[key]
  13541. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema))
  13542. }
  13543. return new ZodObject({ ...schema._def, shape: () => newShape })
  13544. }
  13545. return schema instanceof ZodArray
  13546. ? new ZodArray({ ...schema._def, type: deepPartialify(schema.element) })
  13547. : schema instanceof ZodOptional
  13548. ? ZodOptional.create(deepPartialify(schema.unwrap()))
  13549. : schema instanceof ZodNullable
  13550. ? ZodNullable.create(deepPartialify(schema.unwrap()))
  13551. : schema instanceof ZodTuple
  13552. ? ZodTuple.create(schema.items.map(item => deepPartialify(item)))
  13553. : schema
  13554. }
  13555. class ZodObject extends ZodType {
  13556. constructor() {
  13557. super(...arguments)
  13558. this._cached = null
  13559. this.nonstrict = this.passthrough
  13560. this.augment = this.extend
  13561. }
  13562. _getCached() {
  13563. if (null !== this._cached) return this._cached
  13564. const shape = this._def.shape(),
  13565. keys = util.objectKeys(shape)
  13566. return (this._cached = { shape, keys })
  13567. }
  13568. _parse(input) {
  13569. if (this._getType(input) !== ZodParsedType.object) {
  13570. const ctx = this._getOrReturnCtx(input)
  13571. addIssueToContext(ctx, {
  13572. code: ZodIssueCode.invalid_type,
  13573. expected: ZodParsedType.object,
  13574. received: ctx.parsedType,
  13575. })
  13576. return INVALID
  13577. }
  13578. const { status, ctx } = this._processInputParams(input),
  13579. { shape, keys: shapeKeys } = this._getCached(),
  13580. extraKeys = []
  13581. if (
  13582. !(
  13583. this._def.catchall instanceof ZodNever &&
  13584. "strip" === this._def.unknownKeys
  13585. )
  13586. )
  13587. for (const key in ctx.data)
  13588. shapeKeys.includes(key) || extraKeys.push(key)
  13589. const pairs = []
  13590. for (const key of shapeKeys) {
  13591. const keyValidator = shape[key],
  13592. value = ctx.data[key]
  13593. pairs.push({
  13594. key: { status: "valid", value: key },
  13595. value: keyValidator._parse(
  13596. new ParseInputLazyPath(ctx, value, ctx.path, key)
  13597. ),
  13598. alwaysSet: key in ctx.data,
  13599. })
  13600. }
  13601. if (this._def.catchall instanceof ZodNever) {
  13602. const unknownKeys = this._def.unknownKeys
  13603. if ("passthrough" === unknownKeys)
  13604. for (const key of extraKeys)
  13605. pairs.push({
  13606. key: { status: "valid", value: key },
  13607. value: { status: "valid", value: ctx.data[key] },
  13608. })
  13609. else if ("strict" === unknownKeys) {
  13610. if (extraKeys.length > 0) {
  13611. addIssueToContext(ctx, {
  13612. code: ZodIssueCode.unrecognized_keys,
  13613. keys: extraKeys,
  13614. })
  13615. status.dirty()
  13616. }
  13617. } else if ("strip" !== unknownKeys)
  13618. throw new Error(
  13619. "Internal ZodObject error: invalid unknownKeys value."
  13620. )
  13621. } else {
  13622. const catchall = this._def.catchall
  13623. for (const key of extraKeys) {
  13624. const value = ctx.data[key]
  13625. pairs.push({
  13626. key: { status: "valid", value: key },
  13627. value: catchall._parse(
  13628. new ParseInputLazyPath(ctx, value, ctx.path, key)
  13629. ),
  13630. alwaysSet: key in ctx.data,
  13631. })
  13632. }
  13633. }
  13634. return ctx.common.async
  13635. ? Promise.resolve()
  13636. .then(async () => {
  13637. const syncPairs = []
  13638. for (const pair of pairs) {
  13639. const key = await pair.key
  13640. syncPairs.push({
  13641. key,
  13642. value: await pair.value,
  13643. alwaysSet: pair.alwaysSet,
  13644. })
  13645. }
  13646. return syncPairs
  13647. })
  13648. .then(syncPairs => ParseStatus.mergeObjectSync(status, syncPairs))
  13649. : ParseStatus.mergeObjectSync(status, pairs)
  13650. }
  13651. get shape() {
  13652. return this._def.shape()
  13653. }
  13654. strict(message) {
  13655. errorUtil.errToObj
  13656. return new ZodObject({
  13657. ...this._def,
  13658. unknownKeys: "strict",
  13659. ...(void 0 !== message
  13660. ? {
  13661. errorMap: (issue, ctx) => {
  13662. var _a, _b, _c, _d
  13663. const defaultError =
  13664. null !==
  13665. (_c =
  13666. null === (_b = (_a = this._def).errorMap) ||
  13667. void 0 === _b
  13668. ? void 0
  13669. : _b.call(_a, issue, ctx).message) && void 0 !== _c
  13670. ? _c
  13671. : ctx.defaultError
  13672. return "unrecognized_keys" === issue.code
  13673. ? {
  13674. message:
  13675. null !== (_d = errorUtil.errToObj(message).message) &&
  13676. void 0 !== _d
  13677. ? _d
  13678. : defaultError,
  13679. }
  13680. : { message: defaultError }
  13681. },
  13682. }
  13683. : {}),
  13684. })
  13685. }
  13686. strip() {
  13687. return new ZodObject({ ...this._def, unknownKeys: "strip" })
  13688. }
  13689. passthrough() {
  13690. return new ZodObject({ ...this._def, unknownKeys: "passthrough" })
  13691. }
  13692. extend(augmentation) {
  13693. return new ZodObject({
  13694. ...this._def,
  13695. shape: () => ({ ...this._def.shape(), ...augmentation }),
  13696. })
  13697. }
  13698. merge(merging) {
  13699. return new ZodObject({
  13700. unknownKeys: merging._def.unknownKeys,
  13701. catchall: merging._def.catchall,
  13702. shape: () => ({ ...this._def.shape(), ...merging._def.shape() }),
  13703. typeName: ZodFirstPartyTypeKind.ZodObject,
  13704. })
  13705. }
  13706. setKey(key, schema) {
  13707. return this.augment({ [key]: schema })
  13708. }
  13709. catchall(index) {
  13710. return new ZodObject({ ...this._def, catchall: index })
  13711. }
  13712. pick(mask) {
  13713. const shape = {}
  13714. util.objectKeys(mask).forEach(key => {
  13715. mask[key] && this.shape[key] && (shape[key] = this.shape[key])
  13716. })
  13717. return new ZodObject({ ...this._def, shape: () => shape })
  13718. }
  13719. omit(mask) {
  13720. const shape = {}
  13721. util.objectKeys(this.shape).forEach(key => {
  13722. mask[key] || (shape[key] = this.shape[key])
  13723. })
  13724. return new ZodObject({ ...this._def, shape: () => shape })
  13725. }
  13726. deepPartial() {
  13727. return deepPartialify(this)
  13728. }
  13729. partial(mask) {
  13730. const newShape = {}
  13731. util.objectKeys(this.shape).forEach(key => {
  13732. const fieldSchema = this.shape[key]
  13733. mask && !mask[key]
  13734. ? (newShape[key] = fieldSchema)
  13735. : (newShape[key] = fieldSchema.optional())
  13736. })
  13737. return new ZodObject({ ...this._def, shape: () => newShape })
  13738. }
  13739. required(mask) {
  13740. const newShape = {}
  13741. util.objectKeys(this.shape).forEach(key => {
  13742. if (mask && !mask[key]) newShape[key] = this.shape[key]
  13743. else {
  13744. let newField = this.shape[key]
  13745. for (; newField instanceof ZodOptional; )
  13746. newField = newField._def.innerType
  13747. newShape[key] = newField
  13748. }
  13749. })
  13750. return new ZodObject({ ...this._def, shape: () => newShape })
  13751. }
  13752. keyof() {
  13753. return createZodEnum(util.objectKeys(this.shape))
  13754. }
  13755. }
  13756. ZodObject.create = (shape, params) =>
  13757. new ZodObject({
  13758. shape: () => shape,
  13759. unknownKeys: "strip",
  13760. catchall: ZodNever.create(),
  13761. typeName: ZodFirstPartyTypeKind.ZodObject,
  13762. ...processCreateParams(params),
  13763. })
  13764. ZodObject.strictCreate = (shape, params) =>
  13765. new ZodObject({
  13766. shape: () => shape,
  13767. unknownKeys: "strict",
  13768. catchall: ZodNever.create(),
  13769. typeName: ZodFirstPartyTypeKind.ZodObject,
  13770. ...processCreateParams(params),
  13771. })
  13772. ZodObject.lazycreate = (shape, params) =>
  13773. new ZodObject({
  13774. shape,
  13775. unknownKeys: "strip",
  13776. catchall: ZodNever.create(),
  13777. typeName: ZodFirstPartyTypeKind.ZodObject,
  13778. ...processCreateParams(params),
  13779. })
  13780. class ZodUnion extends ZodType {
  13781. _parse(input) {
  13782. const { ctx } = this._processInputParams(input),
  13783. options = this._def.options
  13784. if (ctx.common.async)
  13785. return Promise.all(
  13786. options.map(async option => {
  13787. const childCtx = {
  13788. ...ctx,
  13789. common: { ...ctx.common, issues: [] },
  13790. parent: null,
  13791. }
  13792. return {
  13793. result: await option._parseAsync({
  13794. data: ctx.data,
  13795. path: ctx.path,
  13796. parent: childCtx,
  13797. }),
  13798. ctx: childCtx,
  13799. }
  13800. })
  13801. ).then(function (results) {
  13802. for (const result of results)
  13803. if ("valid" === result.result.status) return result.result
  13804. for (const result of results)
  13805. if ("dirty" === result.result.status) {
  13806. ctx.common.issues.push(...result.ctx.common.issues)
  13807. return result.result
  13808. }
  13809. const unionErrors = results.map(
  13810. result => new ZodError(result.ctx.common.issues)
  13811. )
  13812. addIssueToContext(ctx, {
  13813. code: ZodIssueCode.invalid_union,
  13814. unionErrors,
  13815. })
  13816. return INVALID
  13817. })
  13818. {
  13819. let dirty
  13820. const issues = []
  13821. for (const option of options) {
  13822. const childCtx = {
  13823. ...ctx,
  13824. common: { ...ctx.common, issues: [] },
  13825. parent: null,
  13826. },
  13827. result = option._parseSync({
  13828. data: ctx.data,
  13829. path: ctx.path,
  13830. parent: childCtx,
  13831. })
  13832. if ("valid" === result.status) return result
  13833. "dirty" !== result.status ||
  13834. dirty ||
  13835. (dirty = { result, ctx: childCtx })
  13836. childCtx.common.issues.length && issues.push(childCtx.common.issues)
  13837. }
  13838. if (dirty) {
  13839. ctx.common.issues.push(...dirty.ctx.common.issues)
  13840. return dirty.result
  13841. }
  13842. const unionErrors = issues.map(issues => new ZodError(issues))
  13843. addIssueToContext(ctx, {
  13844. code: ZodIssueCode.invalid_union,
  13845. unionErrors,
  13846. })
  13847. return INVALID
  13848. }
  13849. }
  13850. get options() {
  13851. return this._def.options
  13852. }
  13853. }
  13854. ZodUnion.create = (types, params) =>
  13855. new ZodUnion({
  13856. options: types,
  13857. typeName: ZodFirstPartyTypeKind.ZodUnion,
  13858. ...processCreateParams(params),
  13859. })
  13860. const getDiscriminator = type =>
  13861. type instanceof ZodLazy
  13862. ? getDiscriminator(type.schema)
  13863. : type instanceof ZodEffects
  13864. ? getDiscriminator(type.innerType())
  13865. : type instanceof ZodLiteral
  13866. ? [type.value]
  13867. : type instanceof ZodEnum
  13868. ? type.options
  13869. : type instanceof ZodNativeEnum
  13870. ? Object.keys(type.enum)
  13871. : type instanceof ZodDefault
  13872. ? getDiscriminator(type._def.innerType)
  13873. : type instanceof ZodUndefined
  13874. ? [void 0]
  13875. : type instanceof ZodNull
  13876. ? [null]
  13877. : null
  13878. class ZodDiscriminatedUnion extends ZodType {
  13879. _parse(input) {
  13880. const { ctx } = this._processInputParams(input)
  13881. if (ctx.parsedType !== ZodParsedType.object) {
  13882. addIssueToContext(ctx, {
  13883. code: ZodIssueCode.invalid_type,
  13884. expected: ZodParsedType.object,
  13885. received: ctx.parsedType,
  13886. })
  13887. return INVALID
  13888. }
  13889. const discriminator = this.discriminator,
  13890. discriminatorValue = ctx.data[discriminator],
  13891. option = this.optionsMap.get(discriminatorValue)
  13892. if (!option) {
  13893. addIssueToContext(ctx, {
  13894. code: ZodIssueCode.invalid_union_discriminator,
  13895. options: Array.from(this.optionsMap.keys()),
  13896. path: [discriminator],
  13897. })
  13898. return INVALID
  13899. }
  13900. return ctx.common.async
  13901. ? option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  13902. : option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })
  13903. }
  13904. get discriminator() {
  13905. return this._def.discriminator
  13906. }
  13907. get options() {
  13908. return this._def.options
  13909. }
  13910. get optionsMap() {
  13911. return this._def.optionsMap
  13912. }
  13913. static create(discriminator, options, params) {
  13914. const optionsMap = new Map()
  13915. for (const type of options) {
  13916. const discriminatorValues = getDiscriminator(
  13917. type.shape[discriminator]
  13918. )
  13919. if (!discriminatorValues)
  13920. throw new Error(
  13921. `A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`
  13922. )
  13923. for (const value of discriminatorValues) {
  13924. if (optionsMap.has(value))
  13925. throw new Error(
  13926. `Discriminator property ${String(
  13927. discriminator
  13928. )} has duplicate value ${String(value)}`
  13929. )
  13930. optionsMap.set(value, type)
  13931. }
  13932. }
  13933. return new ZodDiscriminatedUnion({
  13934. typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  13935. discriminator,
  13936. options,
  13937. optionsMap,
  13938. ...processCreateParams(params),
  13939. })
  13940. }
  13941. }
  13942. function mergeValues(a, b) {
  13943. const aType = getParsedType(a),
  13944. bType = getParsedType(b)
  13945. if (a === b) return { valid: !0, data: a }
  13946. if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  13947. const bKeys = util.objectKeys(b),
  13948. sharedKeys = util
  13949. .objectKeys(a)
  13950. .filter(key => -1 !== bKeys.indexOf(key)),
  13951. newObj = { ...a, ...b }
  13952. for (const key of sharedKeys) {
  13953. const sharedValue = mergeValues(a[key], b[key])
  13954. if (!sharedValue.valid) return { valid: !1 }
  13955. newObj[key] = sharedValue.data
  13956. }
  13957. return { valid: !0, data: newObj }
  13958. }
  13959. if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  13960. if (a.length !== b.length) return { valid: !1 }
  13961. const newArray = []
  13962. for (let index = 0; index < a.length; index++) {
  13963. const sharedValue = mergeValues(a[index], b[index])
  13964. if (!sharedValue.valid) return { valid: !1 }
  13965. newArray.push(sharedValue.data)
  13966. }
  13967. return { valid: !0, data: newArray }
  13968. }
  13969. return aType === ZodParsedType.date &&
  13970. bType === ZodParsedType.date &&
  13971. +a == +b
  13972. ? { valid: !0, data: a }
  13973. : { valid: !1 }
  13974. }
  13975. class ZodIntersection extends ZodType {
  13976. _parse(input) {
  13977. const { status, ctx } = this._processInputParams(input),
  13978. handleParsed = (parsedLeft, parsedRight) => {
  13979. if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID
  13980. const merged = mergeValues(parsedLeft.value, parsedRight.value)
  13981. if (!merged.valid) {
  13982. addIssueToContext(ctx, {
  13983. code: ZodIssueCode.invalid_intersection_types,
  13984. })
  13985. return INVALID
  13986. }
  13987. ;(isDirty(parsedLeft) || isDirty(parsedRight)) && status.dirty()
  13988. return { status: status.value, value: merged.data }
  13989. }
  13990. return ctx.common.async
  13991. ? Promise.all([
  13992. this._def.left._parseAsync({
  13993. data: ctx.data,
  13994. path: ctx.path,
  13995. parent: ctx,
  13996. }),
  13997. this._def.right._parseAsync({
  13998. data: ctx.data,
  13999. path: ctx.path,
  14000. parent: ctx,
  14001. }),
  14002. ]).then(([left, right]) => handleParsed(left, right))
  14003. : handleParsed(
  14004. this._def.left._parseSync({
  14005. data: ctx.data,
  14006. path: ctx.path,
  14007. parent: ctx,
  14008. }),
  14009. this._def.right._parseSync({
  14010. data: ctx.data,
  14011. path: ctx.path,
  14012. parent: ctx,
  14013. })
  14014. )
  14015. }
  14016. }
  14017. ZodIntersection.create = (left, right, params) =>
  14018. new ZodIntersection({
  14019. left,
  14020. right,
  14021. typeName: ZodFirstPartyTypeKind.ZodIntersection,
  14022. ...processCreateParams(params),
  14023. })
  14024. class ZodTuple extends ZodType {
  14025. _parse(input) {
  14026. const { status, ctx } = this._processInputParams(input)
  14027. if (ctx.parsedType !== ZodParsedType.array) {
  14028. addIssueToContext(ctx, {
  14029. code: ZodIssueCode.invalid_type,
  14030. expected: ZodParsedType.array,
  14031. received: ctx.parsedType,
  14032. })
  14033. return INVALID
  14034. }
  14035. if (ctx.data.length < this._def.items.length) {
  14036. addIssueToContext(ctx, {
  14037. code: ZodIssueCode.too_small,
  14038. minimum: this._def.items.length,
  14039. inclusive: !0,
  14040. exact: !1,
  14041. type: "array",
  14042. })
  14043. return INVALID
  14044. }
  14045. if (!this._def.rest && ctx.data.length > this._def.items.length) {
  14046. addIssueToContext(ctx, {
  14047. code: ZodIssueCode.too_big,
  14048. maximum: this._def.items.length,
  14049. inclusive: !0,
  14050. exact: !1,
  14051. type: "array",
  14052. })
  14053. status.dirty()
  14054. }
  14055. const items = [...ctx.data]
  14056. .map((item, itemIndex) => {
  14057. const schema = this._def.items[itemIndex] || this._def.rest
  14058. return schema
  14059. ? schema._parse(
  14060. new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)
  14061. )
  14062. : null
  14063. })
  14064. .filter(x => !!x)
  14065. return ctx.common.async
  14066. ? Promise.all(items).then(results =>
  14067. ParseStatus.mergeArray(status, results)
  14068. )
  14069. : ParseStatus.mergeArray(status, items)
  14070. }
  14071. get items() {
  14072. return this._def.items
  14073. }
  14074. rest(rest) {
  14075. return new ZodTuple({ ...this._def, rest })
  14076. }
  14077. }
  14078. ZodTuple.create = (schemas, params) => {
  14079. if (!Array.isArray(schemas))
  14080. throw new Error("You must pass an array of schemas to z.tuple([ ... ])")
  14081. return new ZodTuple({
  14082. items: schemas,
  14083. typeName: ZodFirstPartyTypeKind.ZodTuple,
  14084. rest: null,
  14085. ...processCreateParams(params),
  14086. })
  14087. }
  14088. class ZodRecord extends ZodType {
  14089. get keySchema() {
  14090. return this._def.keyType
  14091. }
  14092. get valueSchema() {
  14093. return this._def.valueType
  14094. }
  14095. _parse(input) {
  14096. const { status, ctx } = this._processInputParams(input)
  14097. if (ctx.parsedType !== ZodParsedType.object) {
  14098. addIssueToContext(ctx, {
  14099. code: ZodIssueCode.invalid_type,
  14100. expected: ZodParsedType.object,
  14101. received: ctx.parsedType,
  14102. })
  14103. return INVALID
  14104. }
  14105. const pairs = [],
  14106. keyType = this._def.keyType,
  14107. valueType = this._def.valueType
  14108. for (const key in ctx.data)
  14109. pairs.push({
  14110. key: keyType._parse(
  14111. new ParseInputLazyPath(ctx, key, ctx.path, key)
  14112. ),
  14113. value: valueType._parse(
  14114. new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)
  14115. ),
  14116. })
  14117. return ctx.common.async
  14118. ? ParseStatus.mergeObjectAsync(status, pairs)
  14119. : ParseStatus.mergeObjectSync(status, pairs)
  14120. }
  14121. get element() {
  14122. return this._def.valueType
  14123. }
  14124. static create(first, second, third) {
  14125. return new ZodRecord(
  14126. second instanceof ZodType
  14127. ? {
  14128. keyType: first,
  14129. valueType: second,
  14130. typeName: ZodFirstPartyTypeKind.ZodRecord,
  14131. ...processCreateParams(third),
  14132. }
  14133. : {
  14134. keyType: ZodString.create(),
  14135. valueType: first,
  14136. typeName: ZodFirstPartyTypeKind.ZodRecord,
  14137. ...processCreateParams(second),
  14138. }
  14139. )
  14140. }
  14141. }
  14142. class ZodMap extends ZodType {
  14143. _parse(input) {
  14144. const { status, ctx } = this._processInputParams(input)
  14145. if (ctx.parsedType !== ZodParsedType.map) {
  14146. addIssueToContext(ctx, {
  14147. code: ZodIssueCode.invalid_type,
  14148. expected: ZodParsedType.map,
  14149. received: ctx.parsedType,
  14150. })
  14151. return INVALID
  14152. }
  14153. const keyType = this._def.keyType,
  14154. valueType = this._def.valueType,
  14155. pairs = [...ctx.data.entries()].map(([key, value], index) => ({
  14156. key: keyType._parse(
  14157. new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])
  14158. ),
  14159. value: valueType._parse(
  14160. new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])
  14161. ),
  14162. }))
  14163. if (ctx.common.async) {
  14164. const finalMap = new Map()
  14165. return Promise.resolve().then(async () => {
  14166. for (const pair of pairs) {
  14167. const key = await pair.key,
  14168. value = await pair.value
  14169. if ("aborted" === key.status || "aborted" === value.status)
  14170. return INVALID
  14171. ;("dirty" !== key.status && "dirty" !== value.status) ||
  14172. status.dirty()
  14173. finalMap.set(key.value, value.value)
  14174. }
  14175. return { status: status.value, value: finalMap }
  14176. })
  14177. }
  14178. {
  14179. const finalMap = new Map()
  14180. for (const pair of pairs) {
  14181. const key = pair.key,
  14182. value = pair.value
  14183. if ("aborted" === key.status || "aborted" === value.status)
  14184. return INVALID
  14185. ;("dirty" !== key.status && "dirty" !== value.status) ||
  14186. status.dirty()
  14187. finalMap.set(key.value, value.value)
  14188. }
  14189. return { status: status.value, value: finalMap }
  14190. }
  14191. }
  14192. }
  14193. ZodMap.create = (keyType, valueType, params) =>
  14194. new ZodMap({
  14195. valueType,
  14196. keyType,
  14197. typeName: ZodFirstPartyTypeKind.ZodMap,
  14198. ...processCreateParams(params),
  14199. })
  14200. class ZodSet extends ZodType {
  14201. _parse(input) {
  14202. const { status, ctx } = this._processInputParams(input)
  14203. if (ctx.parsedType !== ZodParsedType.set) {
  14204. addIssueToContext(ctx, {
  14205. code: ZodIssueCode.invalid_type,
  14206. expected: ZodParsedType.set,
  14207. received: ctx.parsedType,
  14208. })
  14209. return INVALID
  14210. }
  14211. const def = this._def
  14212. if (null !== def.minSize && ctx.data.size < def.minSize.value) {
  14213. addIssueToContext(ctx, {
  14214. code: ZodIssueCode.too_small,
  14215. minimum: def.minSize.value,
  14216. type: "set",
  14217. inclusive: !0,
  14218. exact: !1,
  14219. message: def.minSize.message,
  14220. })
  14221. status.dirty()
  14222. }
  14223. if (null !== def.maxSize && ctx.data.size > def.maxSize.value) {
  14224. addIssueToContext(ctx, {
  14225. code: ZodIssueCode.too_big,
  14226. maximum: def.maxSize.value,
  14227. type: "set",
  14228. inclusive: !0,
  14229. exact: !1,
  14230. message: def.maxSize.message,
  14231. })
  14232. status.dirty()
  14233. }
  14234. const valueType = this._def.valueType
  14235. function finalizeSet(elements) {
  14236. const parsedSet = new Set()
  14237. for (const element of elements) {
  14238. if ("aborted" === element.status) return INVALID
  14239. "dirty" === element.status && status.dirty()
  14240. parsedSet.add(element.value)
  14241. }
  14242. return { status: status.value, value: parsedSet }
  14243. }
  14244. const elements = [...ctx.data.values()].map((item, i) =>
  14245. valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))
  14246. )
  14247. return ctx.common.async
  14248. ? Promise.all(elements).then(elements => finalizeSet(elements))
  14249. : finalizeSet(elements)
  14250. }
  14251. min(minSize, message) {
  14252. return new ZodSet({
  14253. ...this._def,
  14254. minSize: { value: minSize, message: errorUtil.toString(message) },
  14255. })
  14256. }
  14257. max(maxSize, message) {
  14258. return new ZodSet({
  14259. ...this._def,
  14260. maxSize: { value: maxSize, message: errorUtil.toString(message) },
  14261. })
  14262. }
  14263. size(size, message) {
  14264. return this.min(size, message).max(size, message)
  14265. }
  14266. nonempty(message) {
  14267. return this.min(1, message)
  14268. }
  14269. }
  14270. ZodSet.create = (valueType, params) =>
  14271. new ZodSet({
  14272. valueType,
  14273. minSize: null,
  14274. maxSize: null,
  14275. typeName: ZodFirstPartyTypeKind.ZodSet,
  14276. ...processCreateParams(params),
  14277. })
  14278. class ZodFunction extends ZodType {
  14279. constructor() {
  14280. super(...arguments)
  14281. this.validate = this.implement
  14282. }
  14283. _parse(input) {
  14284. const { ctx } = this._processInputParams(input)
  14285. if (ctx.parsedType !== ZodParsedType.function) {
  14286. addIssueToContext(ctx, {
  14287. code: ZodIssueCode.invalid_type,
  14288. expected: ZodParsedType.function,
  14289. received: ctx.parsedType,
  14290. })
  14291. return INVALID
  14292. }
  14293. function makeArgsIssue(args, error) {
  14294. return makeIssue({
  14295. data: args,
  14296. path: ctx.path,
  14297. errorMaps: [
  14298. ctx.common.contextualErrorMap,
  14299. ctx.schemaErrorMap,
  14300. getErrorMap(),
  14301. errorMap,
  14302. ].filter(x => !!x),
  14303. issueData: {
  14304. code: ZodIssueCode.invalid_arguments,
  14305. argumentsError: error,
  14306. },
  14307. })
  14308. }
  14309. function makeReturnsIssue(returns, error) {
  14310. return makeIssue({
  14311. data: returns,
  14312. path: ctx.path,
  14313. errorMaps: [
  14314. ctx.common.contextualErrorMap,
  14315. ctx.schemaErrorMap,
  14316. getErrorMap(),
  14317. errorMap,
  14318. ].filter(x => !!x),
  14319. issueData: {
  14320. code: ZodIssueCode.invalid_return_type,
  14321. returnTypeError: error,
  14322. },
  14323. })
  14324. }
  14325. const params = { errorMap: ctx.common.contextualErrorMap },
  14326. fn = ctx.data
  14327. return this._def.returns instanceof ZodPromise
  14328. ? OK(async (...args) => {
  14329. const error = new ZodError([]),
  14330. parsedArgs = await this._def.args
  14331. .parseAsync(args, params)
  14332. .catch(e => {
  14333. error.addIssue(makeArgsIssue(args, e))
  14334. throw error
  14335. }),
  14336. result = await fn(...parsedArgs)
  14337. return await this._def.returns._def.type
  14338. .parseAsync(result, params)
  14339. .catch(e => {
  14340. error.addIssue(makeReturnsIssue(result, e))
  14341. throw error
  14342. })
  14343. })
  14344. : OK((...args) => {
  14345. const parsedArgs = this._def.args.safeParse(args, params)
  14346. if (!parsedArgs.success)
  14347. throw new ZodError([makeArgsIssue(args, parsedArgs.error)])
  14348. const result = fn(...parsedArgs.data),
  14349. parsedReturns = this._def.returns.safeParse(result, params)
  14350. if (!parsedReturns.success)
  14351. throw new ZodError([
  14352. makeReturnsIssue(result, parsedReturns.error),
  14353. ])
  14354. return parsedReturns.data
  14355. })
  14356. }
  14357. parameters() {
  14358. return this._def.args
  14359. }
  14360. returnType() {
  14361. return this._def.returns
  14362. }
  14363. args(...items) {
  14364. return new ZodFunction({
  14365. ...this._def,
  14366. args: ZodTuple.create(items).rest(ZodUnknown.create()),
  14367. })
  14368. }
  14369. returns(returnType) {
  14370. return new ZodFunction({ ...this._def, returns: returnType })
  14371. }
  14372. implement(func) {
  14373. return this.parse(func)
  14374. }
  14375. strictImplement(func) {
  14376. return this.parse(func)
  14377. }
  14378. static create(args, returns, params) {
  14379. return new ZodFunction({
  14380. args: args || ZodTuple.create([]).rest(ZodUnknown.create()),
  14381. returns: returns || ZodUnknown.create(),
  14382. typeName: ZodFirstPartyTypeKind.ZodFunction,
  14383. ...processCreateParams(params),
  14384. })
  14385. }
  14386. }
  14387. class ZodLazy extends ZodType {
  14388. get schema() {
  14389. return this._def.getter()
  14390. }
  14391. _parse(input) {
  14392. const { ctx } = this._processInputParams(input)
  14393. return this._def
  14394. .getter()
  14395. ._parse({ data: ctx.data, path: ctx.path, parent: ctx })
  14396. }
  14397. }
  14398. ZodLazy.create = (getter, params) =>
  14399. new ZodLazy({
  14400. getter,
  14401. typeName: ZodFirstPartyTypeKind.ZodLazy,
  14402. ...processCreateParams(params),
  14403. })
  14404. class ZodLiteral extends ZodType {
  14405. _parse(input) {
  14406. if (input.data !== this._def.value) {
  14407. const ctx = this._getOrReturnCtx(input)
  14408. addIssueToContext(ctx, {
  14409. received: ctx.data,
  14410. code: ZodIssueCode.invalid_literal,
  14411. expected: this._def.value,
  14412. })
  14413. return INVALID
  14414. }
  14415. return { status: "valid", value: input.data }
  14416. }
  14417. get value() {
  14418. return this._def.value
  14419. }
  14420. }
  14421. ZodLiteral.create = (value, params) =>
  14422. new ZodLiteral({
  14423. value,
  14424. typeName: ZodFirstPartyTypeKind.ZodLiteral,
  14425. ...processCreateParams(params),
  14426. })
  14427. function createZodEnum(values, params) {
  14428. return new ZodEnum({
  14429. values,
  14430. typeName: ZodFirstPartyTypeKind.ZodEnum,
  14431. ...processCreateParams(params),
  14432. })
  14433. }
  14434. class ZodEnum extends ZodType {
  14435. _parse(input) {
  14436. if ("string" != typeof input.data) {
  14437. const ctx = this._getOrReturnCtx(input),
  14438. expectedValues = this._def.values
  14439. addIssueToContext(ctx, {
  14440. expected: util.joinValues(expectedValues),
  14441. received: ctx.parsedType,
  14442. code: ZodIssueCode.invalid_type,
  14443. })
  14444. return INVALID
  14445. }
  14446. if (-1 === this._def.values.indexOf(input.data)) {
  14447. const ctx = this._getOrReturnCtx(input),
  14448. expectedValues = this._def.values
  14449. addIssueToContext(ctx, {
  14450. received: ctx.data,
  14451. code: ZodIssueCode.invalid_enum_value,
  14452. options: expectedValues,
  14453. })
  14454. return INVALID
  14455. }
  14456. return OK(input.data)
  14457. }
  14458. get options() {
  14459. return this._def.values
  14460. }
  14461. get enum() {
  14462. const enumValues = {}
  14463. for (const val of this._def.values) enumValues[val] = val
  14464. return enumValues
  14465. }
  14466. get Values() {
  14467. const enumValues = {}
  14468. for (const val of this._def.values) enumValues[val] = val
  14469. return enumValues
  14470. }
  14471. get Enum() {
  14472. const enumValues = {}
  14473. for (const val of this._def.values) enumValues[val] = val
  14474. return enumValues
  14475. }
  14476. extract(values) {
  14477. return ZodEnum.create(values)
  14478. }
  14479. exclude(values) {
  14480. return ZodEnum.create(this.options.filter(opt => !values.includes(opt)))
  14481. }
  14482. }
  14483. ZodEnum.create = createZodEnum
  14484. class ZodNativeEnum extends ZodType {
  14485. _parse(input) {
  14486. const nativeEnumValues = util.getValidEnumValues(this._def.values),
  14487. ctx = this._getOrReturnCtx(input)
  14488. if (
  14489. ctx.parsedType !== ZodParsedType.string &&
  14490. ctx.parsedType !== ZodParsedType.number
  14491. ) {
  14492. const expectedValues = util.objectValues(nativeEnumValues)
  14493. addIssueToContext(ctx, {
  14494. expected: util.joinValues(expectedValues),
  14495. received: ctx.parsedType,
  14496. code: ZodIssueCode.invalid_type,
  14497. })
  14498. return INVALID
  14499. }
  14500. if (-1 === nativeEnumValues.indexOf(input.data)) {
  14501. const expectedValues = util.objectValues(nativeEnumValues)
  14502. addIssueToContext(ctx, {
  14503. received: ctx.data,
  14504. code: ZodIssueCode.invalid_enum_value,
  14505. options: expectedValues,
  14506. })
  14507. return INVALID
  14508. }
  14509. return OK(input.data)
  14510. }
  14511. get enum() {
  14512. return this._def.values
  14513. }
  14514. }
  14515. ZodNativeEnum.create = (values, params) =>
  14516. new ZodNativeEnum({
  14517. values,
  14518. typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
  14519. ...processCreateParams(params),
  14520. })
  14521. class ZodPromise extends ZodType {
  14522. unwrap() {
  14523. return this._def.type
  14524. }
  14525. _parse(input) {
  14526. const { ctx } = this._processInputParams(input)
  14527. if (
  14528. ctx.parsedType !== ZodParsedType.promise &&
  14529. !1 === ctx.common.async
  14530. ) {
  14531. addIssueToContext(ctx, {
  14532. code: ZodIssueCode.invalid_type,
  14533. expected: ZodParsedType.promise,
  14534. received: ctx.parsedType,
  14535. })
  14536. return INVALID
  14537. }
  14538. const promisified =
  14539. ctx.parsedType === ZodParsedType.promise
  14540. ? ctx.data
  14541. : Promise.resolve(ctx.data)
  14542. return OK(
  14543. promisified.then(data =>
  14544. this._def.type.parseAsync(data, {
  14545. path: ctx.path,
  14546. errorMap: ctx.common.contextualErrorMap,
  14547. })
  14548. )
  14549. )
  14550. }
  14551. }
  14552. ZodPromise.create = (schema, params) =>
  14553. new ZodPromise({
  14554. type: schema,
  14555. typeName: ZodFirstPartyTypeKind.ZodPromise,
  14556. ...processCreateParams(params),
  14557. })
  14558. class ZodEffects extends ZodType {
  14559. innerType() {
  14560. return this._def.schema
  14561. }
  14562. sourceType() {
  14563. return this._def.schema._def.typeName ===
  14564. ZodFirstPartyTypeKind.ZodEffects
  14565. ? this._def.schema.sourceType()
  14566. : this._def.schema
  14567. }
  14568. _parse(input) {
  14569. const { status, ctx } = this._processInputParams(input),
  14570. effect = this._def.effect || null
  14571. if ("preprocess" === effect.type) {
  14572. const processed = effect.transform(ctx.data)
  14573. return ctx.common.async
  14574. ? Promise.resolve(processed).then(processed =>
  14575. this._def.schema._parseAsync({
  14576. data: processed,
  14577. path: ctx.path,
  14578. parent: ctx,
  14579. })
  14580. )
  14581. : this._def.schema._parseSync({
  14582. data: processed,
  14583. path: ctx.path,
  14584. parent: ctx,
  14585. })
  14586. }
  14587. const checkCtx = {
  14588. addIssue: arg => {
  14589. addIssueToContext(ctx, arg)
  14590. arg.fatal ? status.abort() : status.dirty()
  14591. },
  14592. get path() {
  14593. return ctx.path
  14594. },
  14595. }
  14596. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx)
  14597. if ("refinement" === effect.type) {
  14598. const executeRefinement = acc => {
  14599. const result = effect.refinement(acc, checkCtx)
  14600. if (ctx.common.async) return Promise.resolve(result)
  14601. if (result instanceof Promise)
  14602. throw new Error(
  14603. "Async refinement encountered during synchronous parse operation. Use .parseAsync instead."
  14604. )
  14605. return acc
  14606. }
  14607. if (!1 === ctx.common.async) {
  14608. const inner = this._def.schema._parseSync({
  14609. data: ctx.data,
  14610. path: ctx.path,
  14611. parent: ctx,
  14612. })
  14613. if ("aborted" === inner.status) return INVALID
  14614. "dirty" === inner.status && status.dirty()
  14615. executeRefinement(inner.value)
  14616. return { status: status.value, value: inner.value }
  14617. }
  14618. return this._def.schema
  14619. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  14620. .then(inner => {
  14621. if ("aborted" === inner.status) return INVALID
  14622. "dirty" === inner.status && status.dirty()
  14623. return executeRefinement(inner.value).then(() => ({
  14624. status: status.value,
  14625. value: inner.value,
  14626. }))
  14627. })
  14628. }
  14629. if ("transform" === effect.type) {
  14630. if (!1 === ctx.common.async) {
  14631. const base = this._def.schema._parseSync({
  14632. data: ctx.data,
  14633. path: ctx.path,
  14634. parent: ctx,
  14635. })
  14636. if (!isValid(base)) return base
  14637. const result = effect.transform(base.value, checkCtx)
  14638. if (result instanceof Promise)
  14639. throw new Error(
  14640. "Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead."
  14641. )
  14642. return { status: status.value, value: result }
  14643. }
  14644. return this._def.schema
  14645. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  14646. .then(base =>
  14647. isValid(base)
  14648. ? Promise.resolve(effect.transform(base.value, checkCtx)).then(
  14649. result => ({ status: status.value, value: result })
  14650. )
  14651. : base
  14652. )
  14653. }
  14654. util.assertNever(effect)
  14655. }
  14656. }
  14657. ZodEffects.create = (schema, effect, params) =>
  14658. new ZodEffects({
  14659. schema,
  14660. typeName: ZodFirstPartyTypeKind.ZodEffects,
  14661. effect,
  14662. ...processCreateParams(params),
  14663. })
  14664. ZodEffects.createWithPreprocess = (preprocess, schema, params) =>
  14665. new ZodEffects({
  14666. schema,
  14667. effect: { type: "preprocess", transform: preprocess },
  14668. typeName: ZodFirstPartyTypeKind.ZodEffects,
  14669. ...processCreateParams(params),
  14670. })
  14671. class ZodOptional extends ZodType {
  14672. _parse(input) {
  14673. return this._getType(input) === ZodParsedType.undefined
  14674. ? OK(void 0)
  14675. : this._def.innerType._parse(input)
  14676. }
  14677. unwrap() {
  14678. return this._def.innerType
  14679. }
  14680. }
  14681. ZodOptional.create = (type, params) =>
  14682. new ZodOptional({
  14683. innerType: type,
  14684. typeName: ZodFirstPartyTypeKind.ZodOptional,
  14685. ...processCreateParams(params),
  14686. })
  14687. class ZodNullable extends ZodType {
  14688. _parse(input) {
  14689. return this._getType(input) === ZodParsedType.null
  14690. ? OK(null)
  14691. : this._def.innerType._parse(input)
  14692. }
  14693. unwrap() {
  14694. return this._def.innerType
  14695. }
  14696. }
  14697. ZodNullable.create = (type, params) =>
  14698. new ZodNullable({
  14699. innerType: type,
  14700. typeName: ZodFirstPartyTypeKind.ZodNullable,
  14701. ...processCreateParams(params),
  14702. })
  14703. class ZodDefault extends ZodType {
  14704. _parse(input) {
  14705. const { ctx } = this._processInputParams(input)
  14706. let data = ctx.data
  14707. ctx.parsedType === ZodParsedType.undefined &&
  14708. (data = this._def.defaultValue())
  14709. return this._def.innerType._parse({ data, path: ctx.path, parent: ctx })
  14710. }
  14711. removeDefault() {
  14712. return this._def.innerType
  14713. }
  14714. }
  14715. ZodDefault.create = (type, params) =>
  14716. new ZodDefault({
  14717. innerType: type,
  14718. typeName: ZodFirstPartyTypeKind.ZodDefault,
  14719. defaultValue:
  14720. "function" == typeof params.default
  14721. ? params.default
  14722. : () => params.default,
  14723. ...processCreateParams(params),
  14724. })
  14725. class ZodCatch extends ZodType {
  14726. _parse(input) {
  14727. const { ctx } = this._processInputParams(input),
  14728. newCtx = { ...ctx, common: { ...ctx.common, issues: [] } },
  14729. result = this._def.innerType._parse({
  14730. data: newCtx.data,
  14731. path: newCtx.path,
  14732. parent: { ...newCtx },
  14733. })
  14734. return isAsync(result)
  14735. ? result.then(result => ({
  14736. status: "valid",
  14737. value:
  14738. "valid" === result.status
  14739. ? result.value
  14740. : this._def.catchValue({
  14741. get error() {
  14742. return new ZodError(newCtx.common.issues)
  14743. },
  14744. input: newCtx.data,
  14745. }),
  14746. }))
  14747. : {
  14748. status: "valid",
  14749. value:
  14750. "valid" === result.status
  14751. ? result.value
  14752. : this._def.catchValue({
  14753. get error() {
  14754. return new ZodError(newCtx.common.issues)
  14755. },
  14756. input: newCtx.data,
  14757. }),
  14758. }
  14759. }
  14760. removeCatch() {
  14761. return this._def.innerType
  14762. }
  14763. }
  14764. ZodCatch.create = (type, params) =>
  14765. new ZodCatch({
  14766. innerType: type,
  14767. typeName: ZodFirstPartyTypeKind.ZodCatch,
  14768. catchValue:
  14769. "function" == typeof params.catch ? params.catch : () => params.catch,
  14770. ...processCreateParams(params),
  14771. })
  14772. class ZodNaN extends ZodType {
  14773. _parse(input) {
  14774. if (this._getType(input) !== ZodParsedType.nan) {
  14775. const ctx = this._getOrReturnCtx(input)
  14776. addIssueToContext(ctx, {
  14777. code: ZodIssueCode.invalid_type,
  14778. expected: ZodParsedType.nan,
  14779. received: ctx.parsedType,
  14780. })
  14781. return INVALID
  14782. }
  14783. return { status: "valid", value: input.data }
  14784. }
  14785. }
  14786. ZodNaN.create = params =>
  14787. new ZodNaN({
  14788. typeName: ZodFirstPartyTypeKind.ZodNaN,
  14789. ...processCreateParams(params),
  14790. })
  14791. const BRAND = Symbol("zod_brand")
  14792. class ZodBranded extends ZodType {
  14793. _parse(input) {
  14794. const { ctx } = this._processInputParams(input),
  14795. data = ctx.data
  14796. return this._def.type._parse({ data, path: ctx.path, parent: ctx })
  14797. }
  14798. unwrap() {
  14799. return this._def.type
  14800. }
  14801. }
  14802. class ZodPipeline extends ZodType {
  14803. _parse(input) {
  14804. const { status, ctx } = this._processInputParams(input)
  14805. if (ctx.common.async)
  14806. return (async () => {
  14807. const inResult = await this._def.in._parseAsync({
  14808. data: ctx.data,
  14809. path: ctx.path,
  14810. parent: ctx,
  14811. })
  14812. if ("aborted" === inResult.status) return INVALID
  14813. if ("dirty" === inResult.status) {
  14814. status.dirty()
  14815. return DIRTY(inResult.value)
  14816. }
  14817. return this._def.out._parseAsync({
  14818. data: inResult.value,
  14819. path: ctx.path,
  14820. parent: ctx,
  14821. })
  14822. })()
  14823. {
  14824. const inResult = this._def.in._parseSync({
  14825. data: ctx.data,
  14826. path: ctx.path,
  14827. parent: ctx,
  14828. })
  14829. if ("aborted" === inResult.status) return INVALID
  14830. if ("dirty" === inResult.status) {
  14831. status.dirty()
  14832. return { status: "dirty", value: inResult.value }
  14833. }
  14834. return this._def.out._parseSync({
  14835. data: inResult.value,
  14836. path: ctx.path,
  14837. parent: ctx,
  14838. })
  14839. }
  14840. }
  14841. static create(a, b) {
  14842. return new ZodPipeline({
  14843. in: a,
  14844. out: b,
  14845. typeName: ZodFirstPartyTypeKind.ZodPipeline,
  14846. })
  14847. }
  14848. }
  14849. const custom = (check, params = {}, fatal) =>
  14850. check
  14851. ? ZodAny.create().superRefine((data, ctx) => {
  14852. var _a, _b
  14853. if (!check(data)) {
  14854. const p =
  14855. "function" == typeof params
  14856. ? params(data)
  14857. : "string" == typeof params
  14858. ? { message: params }
  14859. : params,
  14860. _fatal =
  14861. null ===
  14862. (_b =
  14863. null !== (_a = p.fatal) && void 0 !== _a
  14864. ? _a
  14865. : fatal) ||
  14866. void 0 === _b ||
  14867. _b,
  14868. p2 = "string" == typeof p ? { message: p } : p
  14869. ctx.addIssue({ code: "custom", ...p2, fatal: _fatal })
  14870. }
  14871. })
  14872. : ZodAny.create(),
  14873. late = { object: ZodObject.lazycreate }
  14874. var ZodFirstPartyTypeKind
  14875. !(function (ZodFirstPartyTypeKind) {
  14876. ZodFirstPartyTypeKind.ZodString = "ZodString"
  14877. ZodFirstPartyTypeKind.ZodNumber = "ZodNumber"
  14878. ZodFirstPartyTypeKind.ZodNaN = "ZodNaN"
  14879. ZodFirstPartyTypeKind.ZodBigInt = "ZodBigInt"
  14880. ZodFirstPartyTypeKind.ZodBoolean = "ZodBoolean"
  14881. ZodFirstPartyTypeKind.ZodDate = "ZodDate"
  14882. ZodFirstPartyTypeKind.ZodSymbol = "ZodSymbol"
  14883. ZodFirstPartyTypeKind.ZodUndefined = "ZodUndefined"
  14884. ZodFirstPartyTypeKind.ZodNull = "ZodNull"
  14885. ZodFirstPartyTypeKind.ZodAny = "ZodAny"
  14886. ZodFirstPartyTypeKind.ZodUnknown = "ZodUnknown"
  14887. ZodFirstPartyTypeKind.ZodNever = "ZodNever"
  14888. ZodFirstPartyTypeKind.ZodVoid = "ZodVoid"
  14889. ZodFirstPartyTypeKind.ZodArray = "ZodArray"
  14890. ZodFirstPartyTypeKind.ZodObject = "ZodObject"
  14891. ZodFirstPartyTypeKind.ZodUnion = "ZodUnion"
  14892. ZodFirstPartyTypeKind.ZodDiscriminatedUnion = "ZodDiscriminatedUnion"
  14893. ZodFirstPartyTypeKind.ZodIntersection = "ZodIntersection"
  14894. ZodFirstPartyTypeKind.ZodTuple = "ZodTuple"
  14895. ZodFirstPartyTypeKind.ZodRecord = "ZodRecord"
  14896. ZodFirstPartyTypeKind.ZodMap = "ZodMap"
  14897. ZodFirstPartyTypeKind.ZodSet = "ZodSet"
  14898. ZodFirstPartyTypeKind.ZodFunction = "ZodFunction"
  14899. ZodFirstPartyTypeKind.ZodLazy = "ZodLazy"
  14900. ZodFirstPartyTypeKind.ZodLiteral = "ZodLiteral"
  14901. ZodFirstPartyTypeKind.ZodEnum = "ZodEnum"
  14902. ZodFirstPartyTypeKind.ZodEffects = "ZodEffects"
  14903. ZodFirstPartyTypeKind.ZodNativeEnum = "ZodNativeEnum"
  14904. ZodFirstPartyTypeKind.ZodOptional = "ZodOptional"
  14905. ZodFirstPartyTypeKind.ZodNullable = "ZodNullable"
  14906. ZodFirstPartyTypeKind.ZodDefault = "ZodDefault"
  14907. ZodFirstPartyTypeKind.ZodCatch = "ZodCatch"
  14908. ZodFirstPartyTypeKind.ZodPromise = "ZodPromise"
  14909. ZodFirstPartyTypeKind.ZodBranded = "ZodBranded"
  14910. ZodFirstPartyTypeKind.ZodPipeline = "ZodPipeline"
  14911. })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}))
  14912. const stringType = ZodString.create,
  14913. numberType = ZodNumber.create,
  14914. nanType = ZodNaN.create,
  14915. bigIntType = ZodBigInt.create,
  14916. booleanType = ZodBoolean.create,
  14917. dateType = ZodDate.create,
  14918. symbolType = ZodSymbol.create,
  14919. undefinedType = ZodUndefined.create,
  14920. nullType = ZodNull.create,
  14921. anyType = ZodAny.create,
  14922. unknownType = ZodUnknown.create,
  14923. neverType = ZodNever.create,
  14924. voidType = ZodVoid.create,
  14925. arrayType = ZodArray.create,
  14926. objectType = ZodObject.create,
  14927. strictObjectType = ZodObject.strictCreate,
  14928. unionType = ZodUnion.create,
  14929. discriminatedUnionType = ZodDiscriminatedUnion.create,
  14930. intersectionType = ZodIntersection.create,
  14931. tupleType = ZodTuple.create,
  14932. recordType = ZodRecord.create,
  14933. lib_mapType = ZodMap.create,
  14934. setType = ZodSet.create,
  14935. functionType = ZodFunction.create,
  14936. lazyType = ZodLazy.create,
  14937. literalType = ZodLiteral.create,
  14938. enumType = ZodEnum.create,
  14939. nativeEnumType = ZodNativeEnum.create,
  14940. promiseType = ZodPromise.create,
  14941. effectsType = ZodEffects.create,
  14942. optionalType = ZodOptional.create,
  14943. nullableType = ZodNullable.create,
  14944. preprocessType = ZodEffects.createWithPreprocess,
  14945. pipelineType = ZodPipeline.create,
  14946. coerce = {
  14947. string: arg => ZodString.create({ ...arg, coerce: !0 }),
  14948. number: arg => ZodNumber.create({ ...arg, coerce: !0 }),
  14949. boolean: arg => ZodBoolean.create({ ...arg, coerce: !0 }),
  14950. bigint: arg => ZodBigInt.create({ ...arg, coerce: !0 }),
  14951. date: arg => ZodDate.create({ ...arg, coerce: !0 }),
  14952. },
  14953. NEVER = INVALID
  14954. var z = Object.freeze({
  14955. __proto__: null,
  14956. defaultErrorMap: errorMap,
  14957. setErrorMap: function (map) {
  14958. overrideErrorMap = map
  14959. },
  14960. getErrorMap,
  14961. makeIssue,
  14962. EMPTY_PATH: [],
  14963. addIssueToContext,
  14964. ParseStatus,
  14965. INVALID,
  14966. DIRTY,
  14967. OK,
  14968. isAborted,
  14969. isDirty,
  14970. isValid,
  14971. isAsync,
  14972. get util() {
  14973. return util
  14974. },
  14975. get objectUtil() {
  14976. return objectUtil
  14977. },
  14978. ZodParsedType,
  14979. getParsedType,
  14980. ZodType,
  14981. ZodString,
  14982. ZodNumber,
  14983. ZodBigInt,
  14984. ZodBoolean,
  14985. ZodDate,
  14986. ZodSymbol,
  14987. ZodUndefined,
  14988. ZodNull,
  14989. ZodAny,
  14990. ZodUnknown,
  14991. ZodNever,
  14992. ZodVoid,
  14993. ZodArray,
  14994. ZodObject,
  14995. ZodUnion,
  14996. ZodDiscriminatedUnion,
  14997. ZodIntersection,
  14998. ZodTuple,
  14999. ZodRecord,
  15000. ZodMap,
  15001. ZodSet,
  15002. ZodFunction,
  15003. ZodLazy,
  15004. ZodLiteral,
  15005. ZodEnum,
  15006. ZodNativeEnum,
  15007. ZodPromise,
  15008. ZodEffects,
  15009. ZodTransformer: ZodEffects,
  15010. ZodOptional,
  15011. ZodNullable,
  15012. ZodDefault,
  15013. ZodCatch,
  15014. ZodNaN,
  15015. BRAND,
  15016. ZodBranded,
  15017. ZodPipeline,
  15018. custom,
  15019. Schema: ZodType,
  15020. ZodSchema: ZodType,
  15021. late,
  15022. get ZodFirstPartyTypeKind() {
  15023. return ZodFirstPartyTypeKind
  15024. },
  15025. coerce,
  15026. any: anyType,
  15027. array: arrayType,
  15028. bigint: bigIntType,
  15029. boolean: booleanType,
  15030. date: dateType,
  15031. discriminatedUnion: discriminatedUnionType,
  15032. effect: effectsType,
  15033. enum: enumType,
  15034. function: functionType,
  15035. instanceof: (
  15036. cls,
  15037. params = { message: `Input not instance of ${cls.name}` }
  15038. ) => custom(data => data instanceof cls, params),
  15039. intersection: intersectionType,
  15040. lazy: lazyType,
  15041. literal: literalType,
  15042. map: lib_mapType,
  15043. nan: nanType,
  15044. nativeEnum: nativeEnumType,
  15045. never: neverType,
  15046. null: nullType,
  15047. nullable: nullableType,
  15048. number: numberType,
  15049. object: objectType,
  15050. oboolean: () => booleanType().optional(),
  15051. onumber: () => numberType().optional(),
  15052. optional: optionalType,
  15053. ostring: () => stringType().optional(),
  15054. pipeline: pipelineType,
  15055. preprocess: preprocessType,
  15056. promise: promiseType,
  15057. record: recordType,
  15058. set: setType,
  15059. strictObject: strictObjectType,
  15060. string: stringType,
  15061. symbol: symbolType,
  15062. transformer: effectsType,
  15063. tuple: tupleType,
  15064. undefined: undefinedType,
  15065. union: unionType,
  15066. unknown: unknownType,
  15067. void: voidType,
  15068. NEVER,
  15069. ZodIssueCode,
  15070. quotelessJson: obj =>
  15071. JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:"),
  15072. ZodError,
  15073. })
  15074. const checkboxNode = label => c => s => {
  15075. return ((label, checked, onchange) =>
  15076. h(
  15077. "div",
  15078. {},
  15079. h("label", {}, [
  15080. hyperapp_text(label),
  15081. h("input", { type: "checkbox", checked, onchange }),
  15082. ])
  15083. ))(
  15084. getText(label)(s.lang),
  15085. getState(label)(s),
  15086. ((key = label),
  15087. src_flip((s, e) =>
  15088. pipe(
  15089. (e =>
  15090. z.instanceof(HTMLInputElement).parse(e.currentTarget).checked)(
  15091. e
  15092. ),
  15093. updateAt(key),
  15094. src_flip,
  15095. apply(s)
  15096. )
  15097. ))(c)
  15098. )
  15099. var key
  15100. },
  15101. mapSettingNodes = f => xs => c => s =>
  15102. pipe(
  15103. xs,
  15104. ReadonlyArray_map(x => x(c)(s)),
  15105. f
  15106. ),
  15107. updateInput = setter => key =>
  15108. src_flip((s, e) =>
  15109. pipe(
  15110. (e => {
  15111. const target = e.currentTarget ?? e.__target
  15112. if (
  15113. target instanceof HTMLSelectElement ||
  15114. target instanceof HTMLTextAreaElement ||
  15115. target instanceof HTMLInputElement
  15116. )
  15117. return target.value
  15118. throw Error("Event target type isn't acceptable.")
  15119. })(e),
  15120. setter,
  15121. apply(getState(key)(s)),
  15122. updateAt(key),
  15123. src_flip,
  15124. apply(s)
  15125. )
  15126. ),
  15127. editAction = (key, setter) => c => ({
  15128. oninput: (s, e) => updateInput(setter(!0))(key)(c)(s, e),
  15129. onchange: (s, e) => updateInput(setter(!1))(key)(c)(s, e),
  15130. }),
  15131. setEditNumber = editing => value => state =>
  15132. pipe(
  15133. value,
  15134. Number.parseFloat,
  15135. editing
  15136. ? x =>
  15137. Number.isNaN(x) || "." === value.at(-1)
  15138. ? pipe(state, setText(value))
  15139. : fromValueText(x)(value)
  15140. : x =>
  15141. Number.isNaN(x)
  15142. ? pipe(
  15143. state,
  15144. mapSecond(constant(Option_some([value, Option_some("")])))
  15145. )
  15146. : Editable_of(x)
  15147. ),
  15148. errorText = subject => edit =>
  15149. pipe(
  15150. edit,
  15151. error,
  15152. Option_map(x => `${subject}${"" === x ? "" : ": "}${x}`),
  15153. getOrElse(constant(""))
  15154. ),
  15155. rangeRow = (min, max, step, action) => value =>
  15156. h("div", {}, [
  15157. h("input", {
  15158. style: { width: "150px", verticalAlign: "middle" },
  15159. type: "range",
  15160. min,
  15161. max,
  15162. step,
  15163. value: Editable_value(value).toString(),
  15164. oninput: action.onchange,
  15165. }),
  15166. h("input", {
  15167. style: {
  15168. width: "30px",
  15169. backgroundColor: "transparent",
  15170. color: "inherit",
  15171. borderWidth: "1px",
  15172. verticalAlign: "middle",
  15173. borderColor: hasError(value) ? "#f55" : void 0,
  15174. },
  15175. inputmode: "decimal",
  15176. value: pipe(
  15177. value,
  15178. Editable_text,
  15179. getOrElse(
  15180. constant(
  15181. Editable_value(value)
  15182. .toFixed(4)
  15183. .replace(/\.?0+$/, "")
  15184. )
  15185. )
  15186. ),
  15187. ...action,
  15188. }),
  15189. ]),
  15190. settingRow = (label, error, content) =>
  15191. h("div", {}, [
  15192. h("span", {}, hyperapp_text(label)),
  15193. h(
  15194. "span",
  15195. {
  15196. style: {
  15197. color: "#f55",
  15198. marginLeft: "5px",
  15199. whiteSpace: "pre-wrap",
  15200. },
  15201. },
  15202. hyperapp_text(error)
  15203. ),
  15204. h("div", {}, content),
  15205. ]),
  15206. numberNode = (label, min, max, step) => c => s =>
  15207. settingRow(
  15208. getText(label)(s.lang),
  15209. errorText(getText("inputNonNumberic")(s.lang))(s[label]),
  15210. [
  15211. rangeRow(
  15212. min,
  15213. max,
  15214. step,
  15215. editAction(label, setEditNumber)(c)
  15216. )(getState(label)(s)),
  15217. ]
  15218. ),
  15219. panelBoxStyle = width => ({
  15220. flex: `0 0 ${width}px`,
  15221. width: `${width}px`,
  15222. margin: "2px",
  15223. }),
  15224. settingUI_chatFieldPanel = pipe(
  15225. [
  15226. pipe(
  15227. [
  15228. numberNode("fieldScale", 0.7, 1.5, 0.05),
  15229. checkboxNode("simplifyChatField"),
  15230. checkboxNode("createBanButton"),
  15231. ],
  15232. mapSettingNodes(x => h("div", { style: panelBoxStyle(644) }, x))
  15233. ),
  15234. ],
  15235. mapSettingNodes(Function_identity)
  15236. ),
  15237. action = {
  15238. copy: () => s =>
  15239. Effect_map(
  15240. Effect_promise(async () => {
  15241. return GM.setClipboard(
  15242. ((x = s.eventLog),
  15243. `<pre>${JSON.stringify({
  15244. nextId: x.nextId,
  15245. blocks: pipe(
  15246. x.compressedBlocks,
  15247. ReadonlyArray_map(
  15248. external_LZString_namespaceObject.decompressFromUTF16
  15249. ),
  15250. append(JSON.stringify(x.lastBlock)),
  15251. mapNonEmpty(
  15252. external_LZString_namespaceObject.compressToEncodedURIComponent
  15253. )
  15254. ),
  15255. })}</pre>`)
  15256. )
  15257. var x
  15258. }),
  15259. () => s
  15260. ),
  15261. clearFlowChats: c => s => Effect_map(c.act.clearFlowChats, () => s),
  15262. importLog: () => s =>
  15263. pipe(
  15264. Effect_promise(() =>
  15265. external_Swal_default().fire({
  15266. input: "textarea",
  15267. inputLabel: getText("importLog")(s.lang),
  15268. })
  15269. ),
  15270. Effect_map(x =>
  15271. x.isConfirmed ? { ...s, eventLog: importLog(x.value ?? "") } : s
  15272. )
  15273. ),
  15274. },
  15275. buttonNode = label => c => state =>
  15276. h(
  15277. "button",
  15278. {
  15279. type: "button",
  15280. onclick: s => [
  15281. s,
  15282. d =>
  15283. runPromise(
  15284. c.provideLog(
  15285. pipe(
  15286. action[label](c)(s),
  15287. Effect_flatMap(newS => Effect_sync(() => d(newS)))
  15288. )
  15289. )
  15290. ),
  15291. ],
  15292. },
  15293. hyperapp_text(getText(label)(state.lang))
  15294. ),
  15295. tabContainer = style => ontabSelect => labels => tabs => mainTab =>
  15296. h("div", { style: style.container }, [
  15297. h(
  15298. "div",
  15299. {},
  15300. pipe(
  15301. labels,
  15302. ReadonlyArray_map((x, i) =>
  15303. h(
  15304. "span",
  15305. {
  15306. style: {
  15307. ...style.label,
  15308. ...(mainTab === i ? style.labelFocus : {}),
  15309. display: "inline-block",
  15310. },
  15311. onpointerdown: [ontabSelect, i],
  15312. },
  15313. hyperapp_text(x)
  15314. )
  15315. )
  15316. )
  15317. ),
  15318. h(
  15319. "div",
  15320. {
  15321. style: {
  15322. ...style.tab,
  15323. overflow: "auto",
  15324. boxSizing: "border-box",
  15325. },
  15326. },
  15327. pipe(
  15328. tabs,
  15329. ReadonlyArray_get(mainTab),
  15330. match(
  15331. () => {},
  15332. x => x()
  15333. )
  15334. )
  15335. ),
  15336. ]),
  15337. feedbackPanel = c => s =>
  15338. pipe(
  15339. getState("eventLog")(s).compressedBlocks.length + 1,
  15340. logPageCount => [
  15341. pipe(
  15342. [checkboxNode("logEvents"), buttonNode("importLog")],
  15343. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  15344. )(c)(s),
  15345. h("div", { style: panelBoxStyle(428) }, [
  15346. h(
  15347. "a",
  15348. {
  15349. style: { color: "#f0f" },
  15350. href: "https://greasyfork.org/en/scripts/411442-flow-youtube-chat/feedback",
  15351. target: "_blank",
  15352. },
  15353. hyperapp_text(getText("giveFeedback")(s.lang))
  15354. ),
  15355. h("div", {}, [
  15356. h("span", {}, hyperapp_text(getText("eventLog")(s.lang))),
  15357. buttonNode("copy")(c)(s),
  15358. tabContainer({
  15359. container: {},
  15360. label: { padding: "4px", width: "2em", textAlign: "center" },
  15361. labelFocus: { background: "#666" },
  15362. tab: {
  15363. height: "251px",
  15364. display: "flex",
  15365. flexDirection: "column",
  15366. padding: "6px",
  15367. },
  15368. })((_, n) => updateAt("logTab")(n)(c))(
  15369. pipe(makeBy(logPageCount, x => `${x}`))
  15370. )(
  15371. pipe(getState("eventLog")(s), l =>
  15372. makeBy(
  15373. logPageCount,
  15374. i => () =>
  15375. pipe(
  15376. ReadonlyArray_get(l.compressedBlocks, i),
  15377. Option_map(decompressBlock),
  15378. getOrElse(() => l.lastBlock),
  15379. ReadonlyArray_map((x, j) =>
  15380. h("div", { style: { display: "flex" } }, [
  15381. h(
  15382. "div",
  15383. {
  15384. style: {
  15385. userSelect: "none",
  15386. flex: "0 0 2em",
  15387. },
  15388. },
  15389. hyperapp_text(x.id)
  15390. ),
  15391. h(
  15392. "div",
  15393. {
  15394. style: {
  15395. background: j % 2 == 0 ? "#fff" : "#ddd",
  15396. color: "#000",
  15397. flex: "auto",
  15398. wordBreak: "break-all",
  15399. whiteSpace: "break-spaces",
  15400. padding: "0 2px",
  15401. },
  15402. },
  15403. hyperapp_text(`[${x.level}] ${x.text}`)
  15404. ),
  15405. ])
  15406. )
  15407. )
  15408. )
  15409. )
  15410. )(getState("logTab")(s)),
  15411. ]),
  15412. ]),
  15413. ]
  15414. ),
  15415. setEditRegexs = editing => value =>
  15416. pipe(
  15417. value,
  15418. split(/\r\n|\n/),
  15419. ReadonlyArray_filter(not(isEmpty)),
  15420. Identity_bindTo("regexs"),
  15421. Identity_let_("errors", ({ regexs }) =>
  15422. pipe(
  15423. regexs,
  15424. ReadonlyArray_map((x, i) => {
  15425. try {
  15426. RegExp(x, "u")
  15427. return Option_none()
  15428. } catch (e) {
  15429. return Option_some(`${e} in regex number ${i}`)
  15430. }
  15431. }),
  15432. (Semigroup =>
  15433. fromSemigroup(
  15434. Semigroup_make((self, that) =>
  15435. Option_isNone(self)
  15436. ? that
  15437. : Option_isNone(that)
  15438. ? self
  15439. : Option_some(Semigroup.combine(self.value, that.value))
  15440. ),
  15441. Option_none()
  15442. ))(intercalate("\n")(Semigroup)).combineAll
  15443. )
  15444. ),
  15445. ctx =>
  15446. editing
  15447. ? setText(value)
  15448. : pipe(
  15449. ctx.errors,
  15450. Option_map(x =>
  15451. mapSecond(() => Option_some([value, Option_some(x)]))
  15452. ),
  15453. getOrElse(() => () => Editable_of(ctx.regexs))
  15454. )
  15455. ),
  15456. setEditStrings = editing => value =>
  15457. pipe(value, split(/\r\n|\n/), ReadonlyArray_filter(not(isEmpty)), x =>
  15458. constant(
  15459. editing ? [x, Option_some([value, Option_none()])] : Editable_of(x)
  15460. )
  15461. ),
  15462. textAreaRow = (rows, action) => value =>
  15463. h("textarea", {
  15464. rows,
  15465. style: {
  15466. resize: "none",
  15467. boxSizing: "border-box",
  15468. width: "100%",
  15469. borderColor: hasError(value) ? "#f55" : void 0,
  15470. },
  15471. value: pipe(
  15472. value,
  15473. Editable_text,
  15474. getOrElse(pipe(Editable_value(value), join("\n"), constant))
  15475. ),
  15476. ...action,
  15477. }),
  15478. textAreaNode = (label, rows, setter) => c => s =>
  15479. settingRow(
  15480. getText(label)(s.lang),
  15481. errorText(getText("invalidSetting")(s.lang))(s[label]),
  15482. [textAreaRow(rows, editAction(label, setter)(c))(getState(label)(s))]
  15483. ),
  15484. filterPanelOld = c => s =>
  15485. [
  15486. h(
  15487. "div",
  15488. { style: panelBoxStyle(212) },
  15489. textAreaNode("bannedWords", 18, setEditStrings)(c)(s)
  15490. ),
  15491. h(
  15492. "div",
  15493. { style: panelBoxStyle(212) },
  15494. textAreaNode("bannedWordRegexs", 18, setEditRegexs)(c)(s)
  15495. ),
  15496. h(
  15497. "div",
  15498. { style: panelBoxStyle(212) },
  15499. textAreaNode("bannedUsers", 18, setEditStrings)(c)(s)
  15500. ),
  15501. ]
  15502. var validate_color_lib = __webpack_require__(694),
  15503. lib_default = __webpack_require__.n(validate_color_lib)
  15504. const validColor = x => lib_default()(x.replace(/grey/gi, "gray")),
  15505. setEditColor = editing => value =>
  15506. editing
  15507. ? validColor(value)
  15508. ? constant(fromValueText(value)(value))
  15509. : setText(value)
  15510. : validColor(value)
  15511. ? constant(Editable_of(value))
  15512. : mapSecond(constant(Option_some([value, Option_some("")]))),
  15513. colorPicker = action => color =>
  15514. h("input", {
  15515. style: { width: "36px", verticalAlign: "middle" },
  15516. type: "color",
  15517. value: color,
  15518. oninput: action.onchange,
  15519. }),
  15520. textInput = action => value =>
  15521. h("input", {
  15522. style: {
  15523. verticalAlign: "middle",
  15524. width: "5.5em",
  15525. borderColor: hasError(value) ? "#f55" : void 0,
  15526. },
  15527. maxlength: 20,
  15528. value: pipe(
  15529. value,
  15530. Editable_text,
  15531. getOrElse(constant(Editable_value(value)))
  15532. ),
  15533. ...action,
  15534. }),
  15535. setEditInt = editing => value => state =>
  15536. pipe(
  15537. value,
  15538. Number.parseInt,
  15539. editing
  15540. ? x =>
  15541. Number.isNaN(x) || "." === value.at(-1)
  15542. ? pipe(state, setText(value))
  15543. : fromValueText(x)(value)
  15544. : x =>
  15545. Number.isNaN(x)
  15546. ? pipe(
  15547. state,
  15548. mapSecond(constant(Option_some([value, Option_some("")])))
  15549. )
  15550. : Editable_of(x)
  15551. ),
  15552. intNode = (label, min, max, step) => c => s =>
  15553. settingRow(
  15554. getText(label)(s.lang),
  15555. errorText(getText("inputNonNumberic")(s.lang))(s[label]),
  15556. [
  15557. rangeRow(
  15558. min,
  15559. max,
  15560. step,
  15561. editAction(label, setEditInt)(c)
  15562. )(getState(label)(s)),
  15563. ]
  15564. ),
  15565. fonts = currentFont => [
  15566. ["", "Default", "デフォルト"],
  15567. ["arial", "Arial", "Arial"],
  15568. ["arial black", "Arial Black", "Arial Black"],
  15569. ["arial narrow", "Arial Narrow", "Arial Narrow"],
  15570. ["Century", "Century", "Century"],
  15571. ["Comic Sans MS", "Comic Sans MS", "Comic Sans MS"],
  15572. ["Courier", "Courier", "Courier"],
  15573. ["cursive", "cursive", "cursive"],
  15574. ["fantasy", "fantasy", "fantasy"],
  15575. ["Impact", "Impact", "Impact"],
  15576. ["Meiryo", "Meiryo", "メイリオ"],
  15577. ["Meiryo UI", "Meiryo UI", "メイリオ UI"],
  15578. ["monospace", "monospace", "monospace"],
  15579. ["Monotype Corsiva", "Monotype Corsiva", "Monotype Corsiva"],
  15580. ["MS PGothic", "MS PGothic", "MS Pゴシック"],
  15581. ["MS Gothic", "MS Gothic", "MS ゴシック"],
  15582. ["MS Sans Serif", "MS Sans Serif", "MS Sans Serif"],
  15583. ["MS Serif", "MS Serif", "MS Serif"],
  15584. ["MS UI Gothic", "MS UI Gothic", "MS UI Gothic"],
  15585. ["sans-serif", "Sans-serif", "Sans-serif"],
  15586. ["serif", "Serif", "Serif"],
  15587. ["Times New Roman", "Times New Roman", "Times New Roman"],
  15588. ["Yu Gothic", "Yu Gothic", "遊ゴシック"],
  15589. ["YuGothic", "YuGothic", "游ゴシック体"],
  15590. [currentFont, "Custom", "カスタム"],
  15591. ],
  15592. setEditString = editing =>
  15593. flow(x => constant(editing ? fromValueText(x)(x) : Editable_of(x))),
  15594. settingUI_textRowStyle = { width: "70%", boxSizing: "border-box" },
  15595. ui_option = (value, label, selected) =>
  15596. h("option", { value, selected }, hyperapp_text(label)),
  15597. exampleTextStyle = s => ({
  15598. fontFamily: Editable_value(s.font),
  15599. fontWeight: Editable_value(s.fontWeight).toString(),
  15600. textShadow: textShadow(Editable_value(s.shadowColor))(
  15601. Editable_value(s.shadowFontWeight)
  15602. ),
  15603. }),
  15604. colorTextOutput = textStyle => color =>
  15605. h(
  15606. "span",
  15607. { style: { ...textStyle, color } },
  15608. hyperapp_text("Aa1あア亜")
  15609. ),
  15610. textColorNode = label => c => s =>
  15611. settingRow(
  15612. getText(label)(s.lang),
  15613. errorText(getText("invalidColor")(s.lang))(s[label]),
  15614. pipe(
  15615. {
  15616. a: editAction(label, setEditColor)(c),
  15617. v: Editable_value(s[label]),
  15618. },
  15619. ({ a, v }) => [
  15620. colorPicker(a)(v),
  15621. textInput(a)(s[label]),
  15622. colorTextOutput(exampleTextStyle(s))(v),
  15623. ]
  15624. )
  15625. ),
  15626. flowChatPanel = pipe(
  15627. [
  15628. pipe(
  15629. [
  15630. c => s =>
  15631. pipe(Editable_value(s.font), font =>
  15632. settingRow(getText("font")(s.lang), "", [
  15633. h(
  15634. "select",
  15635. {
  15636. style: settingUI_textRowStyle,
  15637. onchange: updateInput(setEditString(!1))("font")(c),
  15638. },
  15639. pipe(
  15640. fonts(font),
  15641. findFirstIndex(x => x[0] === font),
  15642. getOrElse(() => 0),
  15643. index =>
  15644. pipe(
  15645. fonts(font),
  15646. ReadonlyArray_map((f, i) =>
  15647. ui_option(
  15648. f[0],
  15649. pipe(
  15650. languages,
  15651. findFirstIndex(x => x === s.lang),
  15652. Option_map(x => unsafeGet(x + 1)(f)),
  15653. getOrElse(() => "Error")
  15654. ),
  15655. i === index
  15656. )
  15657. )
  15658. )
  15659. )
  15660. ),
  15661. h("input", {
  15662. style: settingUI_textRowStyle,
  15663. maxlength: 20,
  15664. value: font,
  15665. ...editAction("font", setEditString),
  15666. }),
  15667. ])
  15668. ),
  15669. textColorNode("color"),
  15670. textColorNode("ownerColor"),
  15671. textColorNode("moderatorColor"),
  15672. textColorNode("memberColor"),
  15673. ((label = "shadowColor"),
  15674. c => s =>
  15675. settingRow(
  15676. getText(label)(s.lang),
  15677. errorText(getText("invalidColor")(s.lang))(s[label]),
  15678. pipe(editAction(label, setEditColor)(c), x => [
  15679. colorPicker(x)(Editable_value(s[label])),
  15680. textInput(x)(s[label]),
  15681. ])
  15682. )),
  15683. ],
  15684. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  15685. ),
  15686. pipe(
  15687. [
  15688. numberNode("chatOpacity", 0, 1, 0.05),
  15689. numberNode("fontSize", 0.3, 2, 0.05),
  15690. numberNode("fontWeight", 10, 1e3, 10),
  15691. numberNode("shadowFontWeight", 0, 3, 0.1),
  15692. numberNode("flowSpeed", 1, 50, 1),
  15693. intNode("maxChatCount", 5, 200, 5),
  15694. intNode("maxChatLength", 5, 200, 5),
  15695. intNode("laneCount", 1, 25, 1),
  15696. ],
  15697. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  15698. ),
  15699. pipe(
  15700. [
  15701. numberNode("flowY1", 0, 0.95, 0.01),
  15702. numberNode("flowY2", 0.05, 1, 0.01),
  15703. numberNode("flowX1", 0, 0.95, 0.01),
  15704. numberNode("flowX2", 0.05, 1, 0.01),
  15705. numberNode("minSpacing", 0, 2.5, 0.1),
  15706. c => s =>
  15707. h("div", {}, [
  15708. checkboxNode("useStepTiming")(c)(s),
  15709. h(
  15710. "div",
  15711. {
  15712. style: {
  15713. opacity: getState("useStepTiming")(s) ? void 0 : "0.5",
  15714. },
  15715. },
  15716. intNode("timingStepCount", 1, 400, 1)(c)(s)
  15717. ),
  15718. ]),
  15719. checkboxNode("createChats"),
  15720. checkboxNode("displayModName"),
  15721. checkboxNode("displaySuperChatAuthor"),
  15722. checkboxNode("textOnly"),
  15723. () => s => hyperapp_text(getText("flowNewChatIf")(s.lang)),
  15724. checkboxNode("noOverlap"),
  15725. buttonNode("clearFlowChats"),
  15726. ],
  15727. mapSettingNodes(x => h("div", { style: panelBoxStyle(212) }, x))
  15728. ),
  15729. ],
  15730. mapSettingNodes(Function_identity)
  15731. )
  15732. var label
  15733. const settingUI_flowChatPanel = flowChatPanel,
  15734. setString = flow(Function_identity, constant),
  15735. simpleWrap = (comp, init) =>
  15736. pipe(
  15737. Effect_sync(() => document.createElement(comp.tag)),
  15738. Effect_flatMap(node =>
  15739. Effect_sync(() => ({
  15740. node,
  15741. dispatch: app({ init, view: comp.view, node }),
  15742. }))
  15743. )
  15744. ),
  15745. toggleSettingsPanelComponent = flow(
  15746. syncState => (x, e) =>
  15747. pipe({ ...x, showPanel: !x.showPanel }, newState => [
  15748. newState,
  15749. x.showPanel
  15750. ? () => z.instanceof(HTMLElement).parse(e.currentTarget).blur()
  15751. : () => {},
  15752. () =>
  15753. runPromise(syncState(oldState => ({ ...oldState, ...newState }))),
  15754. ]),
  15755. toggle => state =>
  15756. h(
  15757. "button",
  15758. {
  15759. class: "fyc_button",
  15760. style: {
  15761. background: "rgba(0,0,0,0)",
  15762. marginLeft: "10px",
  15763. whiteSpace: "nowrap",
  15764. },
  15765. onclick: toggle,
  15766. },
  15767. [
  15768. h(
  15769. "svg",
  15770. {
  15771. preserveAspectRatio: "xMidYMid meet",
  15772. viewBox: "0 0 640 640",
  15773. width: "15",
  15774. height: "15",
  15775. style: { position: "relative", top: "1px" },
  15776. },
  15777. [
  15778. h(
  15779. "defs",
  15780. {},
  15781. h("path", {
  15782. id: "d1TbzTC1zI",
  15783. 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",
  15784. })
  15785. ),
  15786. h("use", {
  15787. href: "#d1TbzTC1zI",
  15788. opacity: "1",
  15789. fill: "var(--iron-icon-fill-color, currentcolor)",
  15790. "fill-opacity": "1",
  15791. }),
  15792. ]
  15793. ),
  15794. h(
  15795. "span",
  15796. {
  15797. style: {
  15798. position: "relative",
  15799. top: "-2px",
  15800. marginLeft: "8px,",
  15801. },
  15802. },
  15803. hyperapp_text(getText("setting")(state.lang))
  15804. ),
  15805. ]
  15806. ),
  15807. button =>
  15808. makeComponent(
  15809. tag => s => h(tag, { style: { display: "flex" } }, button(s))
  15810. )("span")
  15811. ),
  15812. videoToggleStream = video =>
  15813. pipe(
  15814. [["playing"], ["waiting", "pause"]],
  15815. ReadonlyArray_map((x, i) => [x, 0 === i]),
  15816. ReadonlyArray_flatMap(([xs, b]) =>
  15817. pipe(
  15818. xs,
  15819. ReadonlyArray_map(x => [x, b])
  15820. )
  15821. ),
  15822. ReadonlyArray_map(([x, b]) =>
  15823. pipe(
  15824. (0, external_rxjs_namespaceObject.fromEvent)(video, x),
  15825. (0, external_rxjs_namespaceObject.map)(() => b)
  15826. )
  15827. ),
  15828. x => (0, external_rxjs_namespaceObject.merge)(...x)
  15829. ),
  15830. Logger_make = makeLogger,
  15831. Logger_replace = replaceLogger,
  15832. Logger_withMinimumLogLevel = withMinimumLogLevel,
  15833. Logger_zip = logger_zip,
  15834. Logger_defaultLogger = defaultLogger
  15835. var LogAnnotationKeys
  15836. !(function (LogAnnotationKeys) {
  15837. LogAnnotationKeys.name = "name"
  15838. })(LogAnnotationKeys || (LogAnnotationKeys = {}))
  15839. const src_LogAnnotationKeys = LogAnnotationKeys,
  15840. maxEventLogBlockCount = Math.floor(50),
  15841. preserveEventLogBlockCount = Math.floor(0.2 * maxEventLogBlockCount),
  15842. getConsoleLog = x =>
  15843. (x === Trace
  15844. ? console.trace
  15845. : x === Level_Debug
  15846. ? console.debug
  15847. : x === Info
  15848. ? console.info
  15849. : x === Warning
  15850. ? console.warn
  15851. : x === Level_Error || x === Fatal
  15852. ? console.error
  15853. : console.log
  15854. ).bind(console),
  15855. metaLogger = Logger_make(
  15856. (fiberId, logLevel, message, cause, context, span, annotations) =>
  15857. runPromise(
  15858. pipe(
  15859. () =>
  15860. `${pipe(
  15861. annotations,
  15862. mjs_HashMap_get(src_LogAnnotationKeys.name),
  15863. match(
  15864. () => "",
  15865. x => `[${x}] `
  15866. )
  15867. )}${message}`,
  15868. getStr =>
  15869. pipe(
  15870. FiberRefs_getOrDefault(context, logMeta),
  15871. match(
  15872. () =>
  15873. greaterThanEqual(Warning)(logLevel)
  15874. ? Effect_sync(() => getConsoleLog(logLevel)(getStr()))
  15875. : Effect_unit(),
  15876. meta =>
  15877. Effect_sync(() =>
  15878. getConsoleLog(logLevel)(`${getStr()}: `, meta)
  15879. )
  15880. )
  15881. )
  15882. )
  15883. )
  15884. )
  15885. runPromise(
  15886. pipe(
  15887. Effect_Do(),
  15888. Effect_letDiscard(
  15889. "settingUpdateApps",
  15890. new external_rxjs_namespaceObject.BehaviorSubject([])
  15891. ),
  15892. bindValue_("provideLog", x => {
  15893. return (
  15894. (settingUpdateApps = x.settingUpdateApps),
  15895. effect => {
  15896. return pipe(
  15897. Effect_succeed(
  15898. Logger_replace(
  15899. Logger_defaultLogger,
  15900. Logger_zip(metaLogger)(
  15901. ((apps = settingUpdateApps),
  15902. Logger_make((fiberId, logLevel, message) =>
  15903. runPromise(
  15904. (
  15905. apps => dispatchable =>
  15906. pipe(
  15907. apps,
  15908. ReadonlyArray_map(x =>
  15909. Effect_sync(() => x(dispatchable))
  15910. ),
  15911. x => Effect_all(x)
  15912. )
  15913. )(apps.getValue())(s => {
  15914. return s.logEvents
  15915. ? {
  15916. ...s,
  15917. eventLog: ((text = message),
  15918. (level = logLevel.label),
  15919. flow(
  15920. x =>
  15921. x.compressedBlocks.length ===
  15922. maxEventLogBlockCount
  15923. ? (
  15924. i => log =>
  15925. i > log.compressedBlocks.length
  15926. ? log
  15927. : makeLog({
  15928. nextId: log.nextId,
  15929. ...(i ===
  15930. log.compressedBlocks.length
  15931. ? {
  15932. lastBlock: [],
  15933. compressedBlocks:
  15934. log.compressedBlocks,
  15935. }
  15936. : {
  15937. lastBlock:
  15938. log.lastBlock,
  15939. compressedBlocks:
  15940. ReadonlyArray_remove(
  15941. log.compressedBlocks,
  15942. i
  15943. ),
  15944. }),
  15945. })
  15946. )(
  15947. Math.floor(
  15948. preserveEventLogBlockCount
  15949. )
  15950. )(x)
  15951. : x,
  15952. (
  15953. (text, level) => log =>
  15954. makeLog({
  15955. nextId: log.nextId + 1,
  15956. ...pipe(
  15957. log.lastBlock,
  15958. append({
  15959. id: log.nextId,
  15960. text,
  15961. level,
  15962. }),
  15963. x =>
  15964. 200 === x.length
  15965. ? {
  15966. compressedBlocks: append(
  15967. log.compressedBlocks,
  15968. makeCompressedLogBlock(
  15969. (0,
  15970. external_LZString_namespaceObject.compressToUTF16)(
  15971. JSON.stringify(x)
  15972. )
  15973. )
  15974. ),
  15975. lastBlock: [],
  15976. }
  15977. : {
  15978. compressedBlocks:
  15979. log.compressedBlocks,
  15980. lastBlock: x,
  15981. }
  15982. ),
  15983. })
  15984. )(text, level)
  15985. ))(s.eventLog),
  15986. }
  15987. : s
  15988. var text, level
  15989. })
  15990. )
  15991. ))
  15992. )
  15993. )
  15994. ),
  15995. Effect_flatMap(logLayer =>
  15996. pipe(
  15997. effect,
  15998. Effect_tapErrorCause(x => Effect_logError(Cause_pretty(x))),
  15999. Effect_provideSomeLayer(logLayer)
  16000. )
  16001. ),
  16002. Effect_logAnnotate(src_LogAnnotationKeys.name, "FYC"),
  16003. Logger_withMinimumLogLevel(Level_Debug)
  16004. )
  16005. var apps
  16006. }
  16007. )
  16008. var settingUpdateApps
  16009. }),
  16010. Effect_flatMap(({ settingUpdateApps, provideLog }) =>
  16011. provideLog(
  16012. pipe(
  16013. src_defaultGMConfig,
  16014. x => ({ gmConfig: x, configKeys: Object.keys(x) }),
  16015. Effect_succeed,
  16016. Effect_letDiscard("updateSettingState", dispatchable =>
  16017. provideLog(
  16018. pipe(
  16019. settingUpdateApps.getValue(),
  16020. ReadonlyArray_map(x => Effect_sync(() => x(dispatchable))),
  16021. x => Effect_all(x)
  16022. )
  16023. )
  16024. ),
  16025. Effect_bind("config", ctx => {
  16026. return (
  16027. (config = ctx.gmConfig),
  16028. pipe(
  16029. Object.entries(config),
  16030. ReadonlyArray_map(([k, c]) =>
  16031. pipe(
  16032. c.getValue,
  16033. Effect_map(x => [k, x])
  16034. )
  16035. ),
  16036. x => Effect_all(x),
  16037. Effect_map(Object.fromEntries)
  16038. )
  16039. )
  16040. var config
  16041. }),
  16042. bindValue_("getConfig", ctx =>
  16043. (c =>
  16044. pipe(
  16045. c,
  16046. mapObject(([x]) => [x, () => c[x]])
  16047. ))(ctx.config)
  16048. ),
  16049. flow(
  16050. bindValue_("mainState", x => ({
  16051. chatPlaying: !0,
  16052. playerRect: new DOMRectReadOnly(0, 0, 600, 400),
  16053. config: x.config,
  16054. flowChats: [],
  16055. })),
  16056. bindValue_("configSubject", ctx =>
  16057. pipe(
  16058. ctx.configKeys,
  16059. ReadonlyArray_map(x => [
  16060. x,
  16061. new external_rxjs_namespaceObject.Subject(),
  16062. ]),
  16063. Object.fromEntries
  16064. )
  16065. ),
  16066. bindValue_("setterFromKeysMap", ctx =>
  16067. (
  16068. keys => f =>
  16069. pipe(
  16070. keys,
  16071. ReadonlyArray_map(x => [x, f(x)]),
  16072. Object.fromEntries
  16073. )
  16074. )(ctx.configKeys)
  16075. ),
  16076. bindValue_("setConfigPlain", ctx =>
  16077. ctx.setterFromKeysMap(
  16078. key => val =>
  16079. Effect_promise(async () => {
  16080. Object.assign(ctx.mainState.config, { [key]: val })
  16081. ctx.configSubject[key].next(val)
  16082. })
  16083. )
  16084. ),
  16085. bindValue_(
  16086. "changedConfigMap",
  16087. ctx => key => val =>
  16088. pipe(
  16089. Effect_promise(async () => ctx.config[key]),
  16090. Effect_filterOrFail(
  16091. x => !fast_deep_equal_default()(x, val),
  16092. Option_none
  16093. ),
  16094. Effect_flatMap(() => ctx.setConfigPlain[key](val))
  16095. )
  16096. ),
  16097. bindValue_("setChangedConfig", ctx =>
  16098. ctx.setterFromKeysMap(
  16099. key => val =>
  16100. pipe(ctx.changedConfigMap(key)(val), Effect_ignore)
  16101. )
  16102. ),
  16103. Effect_letDiscard(
  16104. "channel",
  16105. new broadcast_channel_BroadcastChannel("fyc-0615654655528523")
  16106. )
  16107. ),
  16108. flow(
  16109. bindValue_("setConfig", ctx =>
  16110. ctx.setterFromKeysMap(
  16111. key => val =>
  16112. pipe(
  16113. ctx.changedConfigMap(key)(val),
  16114. Effect_zipRight(
  16115. Effect_promise(() =>
  16116. ctx.channel.postMessage([key, val])
  16117. )
  16118. ),
  16119. Effect_zipRight(
  16120. Effect_promise(() =>
  16121. pipe(ctx.gmConfig[key], x =>
  16122. GM.setValue(x.gmKey, x.toGm(val))
  16123. )
  16124. )
  16125. ),
  16126. Effect_ignore
  16127. )
  16128. )
  16129. ),
  16130. Effect_bindDiscard(
  16131. "reinitSubject",
  16132. Effect_sync(() => new external_rxjs_namespaceObject.Subject())
  16133. ),
  16134. bindValue_("reinitialize", ctx =>
  16135. provideLog(
  16136. Effect_sync(() => {
  16137. requestAnimationFrame(() => lib(ctx.reinitSubject)())
  16138. })
  16139. )
  16140. ),
  16141. Effect_tap(ctx =>
  16142. ctx.setConfigPlain.filterExp(defaultFilter(ctx.config))
  16143. ),
  16144. bindValue_("toggleChatButtonInit", ctx => ({
  16145. lang: ctx.config.lang,
  16146. displayChats: ctx.config.displayChats,
  16147. })),
  16148. Effect_bind("wrappedToggleChat", ctx => {
  16149. return simpleWrap(
  16150. ((setConfig = ctx.setConfig),
  16151. pipe(
  16152. "button",
  16153. makeComponent(
  16154. tag => state =>
  16155. pipe(
  16156. getText(
  16157. state.displayChats ? "hideChats" : "showChats"
  16158. )(state.lang),
  16159. label =>
  16160. h(
  16161. tag,
  16162. {
  16163. class: "ytp-button",
  16164. style: {
  16165. background: "none",
  16166. border: "none",
  16167. cursor: "pointer",
  16168. float: "left",
  16169. fontSize: "1em",
  16170. height: "4em",
  16171. outline: "none",
  16172. overflow: "visible",
  16173. padding: "0 0 0em",
  16174. position: "relative",
  16175. width: "3em",
  16176. },
  16177. type: "button",
  16178. "aria-label": label,
  16179. title: label,
  16180. onclick: s =>
  16181. pipe(!s.displayChats, displayChats => [
  16182. { ...s, displayChats },
  16183. () =>
  16184. runPromise(
  16185. setConfig.displayChats(displayChats)
  16186. ),
  16187. ]),
  16188. },
  16189. [
  16190. h(
  16191. "svg",
  16192. {
  16193. style: { width: "100%" },
  16194. viewBox: "0 0 36 36",
  16195. },
  16196. [
  16197. h("path", {
  16198. class: "chat-button-path",
  16199. d: "m11 12h17q1 0 1 1v9q0 1-1 1h-1v2l-4-2h-12q-1 0-1-1v-9q0-1 1-1z",
  16200. fill: "#fff",
  16201. "fill-opacity": state.displayChats
  16202. ? "1"
  16203. : "0",
  16204. stroke: "#fff",
  16205. "stroke-width": "2",
  16206. }),
  16207. ]
  16208. ),
  16209. ]
  16210. )
  16211. )
  16212. )
  16213. )),
  16214. ctx.toggleChatButtonInit
  16215. )
  16216. var setConfig
  16217. }),
  16218. Effect_bind("wrappedSettings", ctx =>
  16219. simpleWrap(
  16220. pipe(
  16221. (
  16222. c => state =>
  16223. state.showPanel
  16224. ? h(
  16225. "div",
  16226. {
  16227. class: "fyc_panel",
  16228. style: {
  16229. backgroundColor: "rgba(30,30,30,0.9)",
  16230. position: "absolute",
  16231. zIndex: "1000",
  16232. color: "#fff",
  16233. fontSize: "14px",
  16234. overflow: "auto",
  16235. left: `${state.panelRect.x}px`,
  16236. top: `${state.panelRect.y}px`,
  16237. width: `${state.panelRect.width}px`,
  16238. height: `${state.panelRect.height}px`,
  16239. border: "solid 1px #666",
  16240. fontFamily: "MS PGothic",
  16241. lineHeight: "1.2",
  16242. colorScheme: "dark",
  16243. },
  16244. },
  16245. [
  16246. h(
  16247. "div",
  16248. {
  16249. style: {
  16250. position: "absolute",
  16251. inset: "3px 3px auto auto",
  16252. },
  16253. },
  16254. [
  16255. hyperapp_text("🌐"),
  16256. h(
  16257. "select",
  16258. {
  16259. onchange:
  16260. updateInput(setString)("lang")(c),
  16261. },
  16262. pipe(
  16263. languages,
  16264. zip(languageLabels),
  16265. ReadonlyArray_map(([lang, label]) =>
  16266. ui_option(
  16267. lang,
  16268. label,
  16269. lang === state.lang
  16270. )
  16271. )
  16272. )
  16273. ),
  16274. ]
  16275. ),
  16276. tabContainer({
  16277. container: {},
  16278. label: { padding: "6px" },
  16279. labelFocus: { background: "#666" },
  16280. tab: {
  16281. height: "364px",
  16282. display: "flex",
  16283. padding: "6px",
  16284. },
  16285. })((s, n) => updateAt("mainTab")(n)(c)(s))(
  16286. pipe(
  16287. [
  16288. "flowChat",
  16289. "chatFilter",
  16290. "chatField",
  16291. "feedback",
  16292. ],
  16293. ReadonlyArray_map(getText),
  16294. ReadonlyArray_map(apply(state.lang))
  16295. )
  16296. )(
  16297. pipe(
  16298. [
  16299. settingUI_flowChatPanel,
  16300. filterPanelOld,
  16301. settingUI_chatFieldPanel,
  16302. feedbackPanel,
  16303. ],
  16304. ReadonlyArray_map(apply(c)),
  16305. ReadonlyArray_map(constant),
  16306. ReadonlyArray_map(src_flip),
  16307. ReadonlyArray_map(apply(state))
  16308. )
  16309. )(getState("mainTab")(state)),
  16310. ]
  16311. )
  16312. : h("div", {})
  16313. )({
  16314. setConfig: ctx.setConfig,
  16315. act: {
  16316. clearFlowChats: removeOldChats(ctx.mainState)(0),
  16317. },
  16318. provideLog,
  16319. }),
  16320. panel =>
  16321. makeComponent(
  16322. tag => s =>
  16323. h(tag, { style: { display: "contents" } }, panel(s))
  16324. )("span")
  16325. ),
  16326. settingStateInit(ctx.config)
  16327. )
  16328. ),
  16329. Effect_bind("wrappedToggleSettings", ctx =>
  16330. simpleWrap(
  16331. toggleSettingsPanelComponent(ctx.updateSettingState),
  16332. settingStateInit(ctx.config)
  16333. )
  16334. )
  16335. ),
  16336. flow(
  16337. Effect_tap(ctx =>
  16338. Effect_sync(() =>
  16339. settingUpdateApps.next([
  16340. ctx.wrappedSettings.dispatch,
  16341. ctx.wrappedToggleSettings.dispatch,
  16342. ])
  16343. )
  16344. ),
  16345. Effect_letDiscard(
  16346. "settingsRectSubject",
  16347. new external_rxjs_namespaceObject.BehaviorSubject(
  16348. new DOMRectReadOnly(0, 0, 660, 395)
  16349. )
  16350. ),
  16351. Effect_tap(ctx =>
  16352. pipe(
  16353. [
  16354. "Version: 1.16.0",
  16355. `User Agent: ${window.navigator.userAgent}`,
  16356. `GMConfig: ${JSON.stringify(ctx.config, void 0, "\t")}`,
  16357. ],
  16358. ReadonlyArray_map(Effect_logDebug),
  16359. x => Effect_all(x)
  16360. )
  16361. ),
  16362. Effect_zipLeft(
  16363. pipe(
  16364. Effect_logDebug("10s..."),
  16365. Effect_repeat(Schedule_fixed(seconds(10))),
  16366. Effect_delay(seconds(10)),
  16367. Effect_forkDaemon
  16368. )
  16369. )
  16370. ),
  16371. bindValue_("co", ctx =>
  16372. pipe(
  16373. ctx.configSubject,
  16374. mapObject(([k, value]) => [
  16375. k,
  16376. pipe(
  16377. value,
  16378. tapEffect(v => {
  16379. return provideLog(
  16380. pipe(
  16381. v,
  16382. x => s => ({ ...s, [k]: x }),
  16383. Effect_succeed,
  16384. Effect_tap(() => {
  16385. return ctx.updateSettingState(
  16386. ((key = k),
  16387. value => state => ({
  16388. ...state,
  16389. [key]: isEditable(key)(value)
  16390. ? setValue(value)(state[key])
  16391. : "filterExp" === key
  16392. ? void 0
  16393. : value,
  16394. }))(v)
  16395. )
  16396. var key
  16397. }),
  16398. Effect_zipLeft(
  16399. pipe(
  16400. [
  16401. "bannedWords",
  16402. "bannedUsers",
  16403. "bannedWordRegexs",
  16404. ],
  16405. ((isEquivalent = String_Equivalence),
  16406. Function_dual(2, (self, a) => {
  16407. for (const i of self)
  16408. if (isEquivalent(a, i)) return !0
  16409. return !1
  16410. }))(k),
  16411. x =>
  16412. x
  16413. ? ctx.setConfig.filterExp(
  16414. defaultFilter(ctx.config)
  16415. )
  16416. : Effect_unit()
  16417. )
  16418. ),
  16419. Effect_flatMap(x =>
  16420. k in ctx.toggleChatButtonInit
  16421. ? Effect_sync(() =>
  16422. ctx.wrappedToggleChat.dispatch(x)
  16423. )
  16424. : Effect_unit()
  16425. ),
  16426. x => () => runPromise(provideLog(x)),
  16427. x => Effect_sync(() => requestAnimationFrame(x))
  16428. )
  16429. )
  16430. var isEquivalent
  16431. }),
  16432. (0, external_rxjs_namespaceObject.share)()
  16433. ),
  16434. ])
  16435. )
  16436. ),
  16437. Effect_letDiscard("livePage", livePageYt),
  16438. bindValue_("live", ctx => makePageState(ctx.livePage)),
  16439. Effect_bindDiscard("chatScreen", makeChatScreen),
  16440. Effect_bind("all$", ctx => {
  16441. return pipe(
  16442. {
  16443. eq:
  16444. ((E = strict()),
  16445. Equivalence_make(
  16446. (x, y) =>
  16447. x === y ||
  16448. (Option_isNone(x)
  16449. ? Option_isNone(y)
  16450. : !Option_isNone(y) && E(x.value, y.value))
  16451. )),
  16452. initDelay: 100,
  16453. urlDelay: 1700,
  16454. changeDetectInterval: 700,
  16455. bodyResizeDetectInterval: 300,
  16456. errorRetryInterval: 5e3,
  16457. liveElementKeys: Object.keys(ctx.livePage),
  16458. tapUpdateSettingsRect: ob =>
  16459. (0, external_rxjs_namespaceObject.switchMap)(value => {
  16460. return pipe(
  16461. ctx.settingsRectSubject,
  16462. (0, external_rxjs_namespaceObject.first)(),
  16463. (0, external_rxjs_namespaceObject.map)(
  16464. ((toggleSettingsElement =
  16465. ctx.wrappedToggleSettings.node),
  16466. nextSettingsRect => last =>
  16467. pipe(
  16468. Effect_succeed(toggleSettingsElement),
  16469. Effect_filterOrFail(
  16470. x => null !== x.offsetParent,
  16471. Option_none
  16472. ),
  16473. Effect_map(x => x.getBoundingClientRect()),
  16474. Effect_map(
  16475. x =>
  16476. new DOMRectReadOnly(
  16477. Math.max(
  16478. 0,
  16479. x.right + window.scrollX - 660
  16480. ),
  16481. Math.max(0, x.y + window.scrollY - 395),
  16482. 660,
  16483. Math.min(x.y + window.scrollY, 395)
  16484. )
  16485. ),
  16486. Effect_orElseSucceed(
  16487. () =>
  16488. new DOMRectReadOnly(-660, -395, 660, 395)
  16489. ),
  16490. Effect_filterOrFail(
  16491. x =>
  16492. x.x !== last.x ||
  16493. x.y !== last.y ||
  16494. x.width !== last.width ||
  16495. x.height !== last.height,
  16496. Option_none
  16497. ),
  16498. Effect_tap(nextSettingsRect),
  16499. Effect_ignore
  16500. ))(rect =>
  16501. Effect_sync(() =>
  16502. ctx.settingsRectSubject.next(rect)
  16503. )
  16504. )
  16505. ),
  16506. tapEffect(provideLog),
  16507. (0, external_rxjs_namespaceObject.map)(() => value)
  16508. )
  16509. var toggleSettingsElement
  16510. })(ob),
  16511. config$: configStream(
  16512. provideLog,
  16513. ctx.mainState,
  16514. ctx.co,
  16515. ctx.chatScreen,
  16516. ctx.live
  16517. ),
  16518. },
  16519. Effect_succeed,
  16520. Effect_bindDiscard("css", mainCss),
  16521. Effect_bindDiscard(
  16522. "documentMutationPair",
  16523. observePair(MutationObserver)
  16524. ),
  16525. Effect_bindDiscard(
  16526. "chatMutationPair",
  16527. observePair(MutationObserver)
  16528. ),
  16529. Effect_bindDiscard(
  16530. "playerResizePair",
  16531. observePair(ResizeObserver)
  16532. ),
  16533. Effect_bindDiscard(
  16534. "bodyResizePair",
  16535. observePair(ResizeObserver)
  16536. ),
  16537. Effect_map(c =>
  16538. pipe(
  16539. ctx.reinitSubject,
  16540. (0, external_rxjs_namespaceObject.observeOn)(
  16541. external_rxjs_namespaceObject.asyncScheduler
  16542. ),
  16543. (0, external_rxjs_namespaceObject.delay)(c.initDelay),
  16544. tapEffect(() => provideLog(Effect_logInfo("Init"))),
  16545. (0, external_rxjs_namespaceObject.switchMap)(() =>
  16546. pipe(
  16547. (0, external_rxjs_namespaceObject.interval)(
  16548. c.changeDetectInterval
  16549. ),
  16550. c.tapUpdateSettingsRect,
  16551. (0, external_rxjs_namespaceObject.concatMap)(index =>
  16552. pipe(
  16553. (0, external_rxjs_namespaceObject.from)(
  16554. runPromise(
  16555. provideLog(
  16556. pipe(
  16557. c.liveElementKeys,
  16558. ReadonlyArray_map(key =>
  16559. pipe(
  16560. ctx.live[key],
  16561. x => x.read,
  16562. Effect_unsome,
  16563. Effect_map(
  16564. liftPredicate(
  16565. newEle =>
  16566. !c.eq(ctx.live[key].ele, newEle)
  16567. )
  16568. ),
  16569. Effect_map(
  16570. Option_map(
  16571. flow(
  16572. Effect_succeed,
  16573. Effect_tap(x =>
  16574. Effect_sync(() => {
  16575. ctx.live[key].ele = x
  16576. })
  16577. ),
  16578. Effect_map(Option_isSome),
  16579. Effect_map(
  16580. x =>
  16581. `${key} ${
  16582. x ? "found" : "lost"
  16583. }`
  16584. ),
  16585. Effect_flatMap(Effect_logDebug)
  16586. )
  16587. )
  16588. ),
  16589. Effect_flatMap(
  16590. match(
  16591. () => Effect_succeed(!1),
  16592. Effect_zipRight(
  16593. Effect_succeed(!0)
  16594. )
  16595. )
  16596. )
  16597. )
  16598. ),
  16599. x => Effect_all(x),
  16600. Effect_map(
  16601. ReadonlyArray_some(Function_identity)
  16602. )
  16603. )
  16604. )
  16605. )
  16606. ),
  16607. (0, external_rxjs_namespaceObject.filter)(
  16608. Function_identity
  16609. ),
  16610. (0, external_rxjs_namespaceObject.map)(
  16611. () => index
  16612. )
  16613. )
  16614. ),
  16615. (0, external_rxjs_namespaceObject.startWith)(0)
  16616. )
  16617. ),
  16618. tapEffect(() =>
  16619. provideLog(
  16620. pipe(
  16621. Effect_logDebug("Loading..."),
  16622. Effect_zipRight(removeOldChats(ctx.mainState)(0)),
  16623. Effect_zipRight(
  16624. Effect_sync(() => {
  16625. c.documentMutationPair.observer.disconnect()
  16626. c.documentMutationPair.observer.observe(
  16627. document,
  16628. { childList: !0, subtree: !0 }
  16629. )
  16630. c.chatMutationPair.observer.disconnect()
  16631. c.playerResizePair.observer.disconnect()
  16632. c.bodyResizePair.observer.disconnect()
  16633. document.head.append(c.css)
  16634. })
  16635. ),
  16636. Effect_zipRight(
  16637. pipe(
  16638. [
  16639. pipe(
  16640. ctx.live.chatField.ele,
  16641. Option_map(x =>
  16642. Effect_sync(() =>
  16643. c.chatMutationPair.observer.observe(x, {
  16644. childList: !0,
  16645. })
  16646. )
  16647. )
  16648. ),
  16649. pipe(
  16650. ctx.live.chatTicker.ele,
  16651. Option_map(x =>
  16652. Effect_sync(() =>
  16653. c.chatMutationPair.observer.observe(x, {
  16654. childList: !0,
  16655. })
  16656. )
  16657. )
  16658. ),
  16659. pipe(
  16660. ctx.live.player.ele,
  16661. Option_map(
  16662. flow(
  16663. Effect_succeed,
  16664. Effect_tap(x =>
  16665. Effect_sync(() =>
  16666. c.playerResizePair.observer.observe(
  16667. x
  16668. )
  16669. )
  16670. ),
  16671. Effect_flatMap(x =>
  16672. Effect_sync(() =>
  16673. x.prepend(ctx.chatScreen)
  16674. )
  16675. )
  16676. )
  16677. )
  16678. ),
  16679. pipe(
  16680. ctx.live.toggleChatBtnParent.ele,
  16681. Option_map(x =>
  16682. Effect_sync(() =>
  16683. x.prepend(ctx.wrappedToggleChat.node)
  16684. )
  16685. )
  16686. ),
  16687. pipe(
  16688. ctx.live.settingsToggleNextElement.ele,
  16689. Option_map(x =>
  16690. Effect_sync(() =>
  16691. x.before(ctx.wrappedToggleSettings.node)
  16692. )
  16693. )
  16694. ),
  16695. pipe(
  16696. ctx.live.settingsContainer.ele,
  16697. Option_map(x =>
  16698. Effect_sync(() =>
  16699. x.append(ctx.wrappedSettings.node)
  16700. )
  16701. )
  16702. ),
  16703. pipe(
  16704. document.body,
  16705. fromNullable,
  16706. Option_map(x =>
  16707. Effect_sync(() =>
  16708. c.bodyResizePair.observer.observe(x)
  16709. )
  16710. )
  16711. ),
  16712. ],
  16713. ReadonlyArray_compact,
  16714. append(
  16715. pipe(
  16716. ctx.live.video.ele,
  16717. Option_filter(x => !x.paused),
  16718. orElse(() => ctx.live.offlineSlate.ele),
  16719. Option_isSome,
  16720. x =>
  16721. Effect_sync(() => {
  16722. Object.assign(ctx.mainState, {
  16723. chatPlaying: x,
  16724. })
  16725. })
  16726. )
  16727. ),
  16728. x => Effect_all(x)
  16729. )
  16730. )
  16731. )
  16732. )
  16733. ),
  16734. (0, external_rxjs_namespaceObject.switchMap)(() =>
  16735. (0, external_rxjs_namespaceObject.merge)(
  16736. pipe(
  16737. (0, external_rxjs_namespaceObject.fromEvent)(
  16738. ctx.channel,
  16739. "message"
  16740. ),
  16741. (0, external_rxjs_namespaceObject.map)(
  16742. ([key, val]) =>
  16743. pipe(
  16744. src_listeningBroadcastConfigKeys.includes(
  16745. key
  16746. ),
  16747. x =>
  16748. x
  16749. ? ctx.setChangedConfig[key](val)
  16750. : Effect_sync(() => {})
  16751. )
  16752. ),
  16753. tapEffect(provideLog)
  16754. ),
  16755. ...pipe(
  16756. ctx.configKeys,
  16757. ReadonlyArray_map(key =>
  16758. pipe(
  16759. ctx.co[key],
  16760. (0, external_rxjs_namespaceObject.startWith)(
  16761. ctx.config[key]
  16762. ),
  16763. (0, external_rxjs_namespaceObject.bufferCount)(
  16764. 2,
  16765. 1
  16766. ),
  16767. (0, external_rxjs_namespaceObject.map)(
  16768. ([x, y]) =>
  16769. (0, external_DeepDiff_namespaceObject.diff)(
  16770. x,
  16771. y
  16772. )
  16773. ),
  16774. (0, external_rxjs_namespaceObject.map)(x =>
  16775. Effect_logDebug(
  16776. `Config ${key}: ${JSON.stringify(
  16777. x,
  16778. void 0,
  16779. 2
  16780. )}`
  16781. )
  16782. ),
  16783. tapEffect(provideLog)
  16784. )
  16785. )
  16786. ),
  16787. c.config$,
  16788. pipe(
  16789. ctx.live.video.ele,
  16790. match(
  16791. () => external_rxjs_namespaceObject.EMPTY,
  16792. flow(
  16793. videoToggleStream,
  16794. (0, external_rxjs_namespaceObject.map)(
  16795. playing =>
  16796. playing ||
  16797. Option_isSome(ctx.live.offlineSlate.ele)
  16798. ),
  16799. (0, external_rxjs_namespaceObject.map)(
  16800. chatPlaying =>
  16801. pipe(
  16802. Effect_sync(() => {
  16803. ctx.mainState.chatPlaying = chatPlaying
  16804. }),
  16805. Effect_zipRight(
  16806. pipe(
  16807. ctx.mainState.flowChats,
  16808. ReadonlyArray_map(setChatPlayState),
  16809. ReadonlyArray_map(
  16810. apply(ctx.mainState)
  16811. ),
  16812. x => Effect_all(x)
  16813. )
  16814. )
  16815. )
  16816. ),
  16817. tapEffect(provideLog)
  16818. )
  16819. )
  16820. ),
  16821. pipe(
  16822. c.chatMutationPair.subject,
  16823. (0, external_rxjs_namespaceObject.map)(
  16824. onChatFieldMutate(
  16825. ctx.chatScreen,
  16826. ctx.mainState,
  16827. ctx.getConfig,
  16828. ctx.setConfig
  16829. )
  16830. ),
  16831. tapEffect(provideLog)
  16832. ),
  16833. pipe(
  16834. c.documentMutationPair.subject,
  16835. (0, external_rxjs_namespaceObject.map)(
  16836. () => window.location.href
  16837. ),
  16838. (0,
  16839. external_rxjs_namespaceObject.distinctUntilChanged)(),
  16840. (0, external_rxjs_namespaceObject.skip)(1),
  16841. c.tapUpdateSettingsRect,
  16842. (0, external_rxjs_namespaceObject.map)(x =>
  16843. Effect_all([
  16844. Effect_logDebug(`URL Changed: ${x}`),
  16845. removeOldChats(ctx.mainState)(0),
  16846. Effect_logDebug(`Wait for ${c.urlDelay}ms...`),
  16847. ])
  16848. ),
  16849. tapEffect(provideLog),
  16850. (0, external_rxjs_namespaceObject.delay)(
  16851. c.urlDelay
  16852. ),
  16853. tapEffect(() => ctx.reinitialize)
  16854. ),
  16855. pipe(
  16856. c.playerResizePair.subject,
  16857. (0, external_rxjs_namespaceObject.throttleTime)(
  16858. 500,
  16859. void 0,
  16860. { leading: !0, trailing: !0 }
  16861. ),
  16862. (0, external_rxjs_namespaceObject.startWith)([]),
  16863. (0, external_rxjs_namespaceObject.map)(
  16864. flow(
  16865. () => ctx.live.player.ele,
  16866. Option_map(x => x.getBoundingClientRect()),
  16867. match(
  16868. () => Effect_unit(),
  16869. x => {
  16870. return (
  16871. (rect = x),
  16872. (mainState = ctx.mainState),
  16873. pipe(
  16874. rect,
  16875. Effect_succeed,
  16876. Effect_tap(x =>
  16877. Effect_logDebug(
  16878. `Resize [${x.width.toFixed(
  16879. 1
  16880. )}, ${x.height.toFixed(1)}]`
  16881. )
  16882. ),
  16883. Effect_flatMap(
  16884. flow(
  16885. x =>
  16886. Effect_sync(() =>
  16887. Object.assign(mainState, {
  16888. playerRect: x,
  16889. })
  16890. ),
  16891. Effect_map(
  16892. () => mainState.flowChats
  16893. ),
  16894. Effect_map(
  16895. ReadonlyArray_flatMap(x => [
  16896. renderChat(x)(mainState),
  16897. setChatAnimation(x)(mainState),
  16898. ])
  16899. ),
  16900. Effect_flatMap(x => Effect_all(x))
  16901. )
  16902. )
  16903. )
  16904. )
  16905. var rect, mainState
  16906. }
  16907. )
  16908. )
  16909. ),
  16910. tapEffect(provideLog)
  16911. ),
  16912. pipe(
  16913. c.bodyResizePair.subject,
  16914. (0, external_rxjs_namespaceObject.throttleTime)(
  16915. c.bodyResizeDetectInterval,
  16916. void 0,
  16917. { leading: !0, trailing: !0 }
  16918. ),
  16919. (0, external_rxjs_namespaceObject.startWith)([]),
  16920. c.tapUpdateSettingsRect
  16921. ),
  16922. pipe(
  16923. ctx.settingsRectSubject,
  16924. tapEffect(panelRect =>
  16925. ctx.updateSettingState(s => ({ ...s, panelRect }))
  16926. )
  16927. )
  16928. )
  16929. ),
  16930. (0, external_rxjs_namespaceObject.retry)({
  16931. delay: e =>
  16932. pipe(
  16933. e,
  16934. external_rxjs_namespaceObject.of,
  16935. tapEffect(() =>
  16936. provideLog(
  16937. logWithMeta(Level_Error)(`Errored: ${e}`)(e)
  16938. )
  16939. ),
  16940. (0, external_rxjs_namespaceObject.delay)(
  16941. c.errorRetryInterval
  16942. ),
  16943. tapEffect(() => ctx.reinitialize)
  16944. ),
  16945. })
  16946. )
  16947. )
  16948. )
  16949. var E
  16950. }),
  16951. Effect_tap(ctx =>
  16952. Effect_sync(() =>
  16953. ctx.all$.subscribe({
  16954. error: x =>
  16955. runPromise(
  16956. logWithMeta(Level_Error)(`Stream Errored: ${x}`)(x)
  16957. ),
  16958. complete: () =>
  16959. runPromise(Effect_logWarning("Stream complete")),
  16960. })
  16961. )
  16962. ),
  16963. Effect_tap(ctx => ctx.reinitialize)
  16964. )
  16965. )
  16966. ),
  16967. Effect_withParallelismUnbounded
  16968. )
  16969. )
  16970. })()
  16971. })()