lib:newallfuncs

none

当前为 2025-03-06 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name lib:newallfuncs
  3. // @version 12
  4. // @description none
  5. // @run-at document-start
  6. // @author rssaromeo
  7. // @license GPLv3
  8. // @match *://*/*
  9. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABICAMAAABiM0N1AAAAAXNSR0IB2cksfwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAHJQTFRFAAAAEIijAo2yAI60BYyuF4WaFIifAY6zBI2wB4usGIaZEYigIoiZCIyrE4igG4iYD4mjEomhFoedCoqpDIqnDomlBYyvE4efEYmiDYqlA42xBoytD4mkCYqqGYSUFYidC4qoC4upAo6yCoupDYqmCYur4zowOQAAACZ0Uk5TAO////9vr////1+/D/+/L+/Pf/////+f3///////H4////////+5G91rAAACgUlEQVR4nM2Y22KjIBCGidg1264liZqDadK03X3/V2wNKHMC7MpF/xthHD5mgERAqZhWhfYqH6K+Qf2qNNf625hCoFj9/gblMUi5q5jLkXLCKudgyiRm0FMK82cWJp1fLbV5VmvJbCIc0GCYaFqqlDJgADdBjncqAXYobm1xh72aFMflbysteFfdy2Yi1XGOm5HGBzQ1dq7TzEoxjeNTjQZb7VA3e1c7+ImgasAgQ9+xusNVNZIo5xmOMgihIS2PbCQIiHEUdTvhxCcS/kPomfFI2zHy2PkWmA6aNatIJpKFJyekyy02xh5Y3DI9T4aOT6VhIUrsNTFp1pf79Z4SIIVDegl6IJO6cHiL/GimIZDhgTu/BlYWCQzHMl0zBWT/T3KAhtxOuUB9FtBrpsz0RV4xsjHmW+UCaffcSy/5viMGer0/6HdFNMZBq/vjJL38H9Dqx4Fuy0Em12DbZy+9pGtiDijbglwAehyj11n0tRD3WUBm+lwulE/8h4BuA+iWAQQnteg2Xm63WQLTpnMnpjdge0Mgu/GRPsV4xdjQ94Lfi624fabhDkfUqIKNrM64Q837v8yL0prasepCgrtvw1sJpoqanGEX7b5mQboNW8eawXaWXTMfMGxub472hzWzHSn6Sg2G9+6TAyRruE71s+zAzjWaknoyJCQzwxrghH2k5FDT4eqWunuNxyN9QCGcxVod5oADbYnIUkDTGZEf1xDJnSFteQ3KdsT8zYDMQXcHxsevcLH1TrsABzkNPyA/L7b0jg704viMMlpQI96WsHknCt/3YH0kOEo9zcGkwrFK39ck72rmoehmKqo2RKlilzSy/nJKEV45CT38myJp456fezktHjN5aeMAAAAASUVORK5CYII=
  10. // @grant none
  11. // @namespace https://greasyfork.org/users/1184528
  12. // ==/UserScript==
  13.  
  14. // fix gettype in test func
  15. /*
  16. // @noregex
  17. // @name remove ai comments
  18. // @regex (//) \.\.\..*
  19. // @replace
  20. // @endregex
  21. // @regex maketype\((\w+),
  22. // @replace $1 = maketype($1,
  23. // @endregex
  24. */
  25. /**
  26. * @typedef {Object} TestUtils
  27. * @property {function(...*): void} ifunset - Sets default values for undefined inputs.
  28. * @property {function(*): string} gettype - Checks the type of a value.
  29. * @property {function(number): void} pass - Validates that the current parameter is correct.
  30. * @property {function(): boolean} end - Validates that all parameters have been checked.
  31. * @property {function(*, Array<*>): boolean} isany - Checks if a value is in a list of options.
  32. * @property {function(string, RegExp): boolean} matchesregex - Checks if a value matches a regex pattern.
  33. * @property {function(*, *): boolean} issame - Checks if two values are strictly equal.
  34. * @property {function(number, Array<string>): boolean} trymaketype - Attempts to convert a value to one of the specified types.
  35. */
  36. /**
  37. * @callback TestFunction
  38. * @param {TestUtils} testUtils - An object containing utility functions for testing.
  39. * @returns {boolean} Returns true if all validations pass.
  40. */
  41. /**
  42. * @param {Function} func - The function to wrap in a test.
  43. * @param {TestFunction} testfunc - The function to test func against.
  44. * @returns {Function} - The wrapped function.
  45. */
  46.  
  47. ;(() => {
  48. function newfunc(func, testfunc) {
  49. var funcname = func.name || func.prototype.name
  50. var retfunc = function () {
  51. var i = 0
  52. var inputargs = [...arguments]
  53. return testfunc({
  54. funcname,
  55. args: inputargs,
  56. /**
  57. *
  58. * @param {*} thing - anything
  59. * @param {Array} _enum - list of posable things thing can be
  60. * @returns {Error|*}
  61. */
  62. makeenum: function makeenum(thing, _enum) {
  63. for (var thing2 of _enum) {
  64. if (thing == thing2) return thing2
  65. }
  66. throw new Error(
  67. `makeenum: in function ${this.funcname} input ${i} is invalid, should match enum [${_enum}] but is instead ${thing}`
  68. )
  69. }.bind(retfunc),
  70. trymakeenum: function trymakeenum(thing, _enum) {
  71. try {
  72. this.makeenum(thing, _enum)
  73. return true
  74. } catch (e) {
  75. return false
  76. }
  77. }.bind(retfunc),
  78. /**
  79. * Sets default values for input if they are undefined.
  80. * @param {...*} input - The default values to set.
  81. */
  82. ifunset: function ifunset(...newinputs) {
  83. for (var i in newinputs) {
  84. if (inputargs[i] === undefined)
  85. inputargs[i] = newinputs[i]
  86. }
  87. }.bind(retfunc),
  88. /**
  89. *
  90. * @param {Number} i - tries to make thing become a type in types
  91. * @param {Array|string} types - array of types to try to be
  92. * @returns {boolean}
  93. */
  94. trymaketype: function trymaketype(thing, types) {
  95. try {
  96. this.maketype(thing, types)
  97. return true
  98. } catch (e) {
  99. return false
  100. }
  101. }.bind(retfunc),
  102. /**
  103. *
  104. * @param {Number} i - tries to make thing become a type in types
  105. * @param {Array|string} types - array of types to try to be
  106. * @returns {Error|true}
  107. */
  108. maketype: function maketype(thing, types) {
  109. // if (types.includes("any")) return true
  110. if (gettype(thing, types)) return true
  111. for (var type of types) {
  112. if (gettype(thing, "string") && type == "number") {
  113. thing = Number(thing)
  114. }
  115. if (gettype(thing, "number") && type == "string") {
  116. thing = String(thing)
  117. }
  118. if (gettype(thing, "string") && type == "number") {
  119. thing = Number(thing)
  120. }
  121. if (gettype(thing, "number") && type == "string") {
  122. thing = String(thing)
  123. }
  124. if (gettype(thing, "boolean") && type == 1) {
  125. thing = true
  126. }
  127. if (type == "boolean" && (thing == 0 || thing == "")) {
  128. thing = false
  129. }
  130. if (gettype(thing, type)) return thing
  131. }
  132. throw new Error(
  133. `trymaketype: in function ${
  134. this.funcname
  135. } input ${i} is invalid, should be type [${types}] but is instead type ${gettype(
  136. thing
  137. )}`
  138. )
  139. }.bind(retfunc),
  140. /**
  141. *
  142. * @param {*} thing - the thing to get the type of
  143. * @param {string|Array|undefined} match - if set the type to check aganst or array of ytpes to check aganst
  144. * @returns {boolean|string}
  145. */
  146. trygettype: gettype,
  147. gettype: function gettype(a, s) {
  148. if (gettype(a, s)) return true
  149. throw new Error(
  150. `gettype: in function ${
  151. this.funcname
  152. } input ${i} is invalid, should be type [${types}] but is instead type ${gettype(
  153. thing
  154. )}`
  155. )
  156. }.bind(retfunc),
  157. /**
  158. * tells that the test function has ended and to try and call the main function
  159. * @returns {boolean|undefined}
  160. */
  161. end: function end() {
  162. return func.call(func, ...inputargs)
  163. }.bind(retfunc),
  164. })
  165. }
  166. retfunc.name = retfunc.prototype.name =
  167. "strict " + (funcname ?? "function")
  168. retfunc.funcname = funcname
  169. return retfunc.bind(retfunc)
  170. /**
  171. *
  172. * @param {*} thing - the thing to get the type of
  173. * @param {string|Array|undefined} match - if set the type to check aganst or array of ytpes to check aganst
  174. * @returns {boolean|string}
  175. */
  176. function gettype(thing, match) {
  177. if (
  178. !match ||
  179. (Object.prototype.toString
  180. .call(match)
  181. .toLowerCase()
  182. .match(/^\[[a-z]+ (.+)\]$/)[1] == "string" &&
  183. !match.includes("|"))
  184. ) {
  185. var type = Object.prototype.toString
  186. .call(thing)
  187. .toLowerCase()
  188. .match(/^\[[a-z]+ (.+)\]$/)[1]
  189. if (type !== "function") if (type == match) return true
  190. if (match == "normalfunction") return type == "function"
  191. if (type == "htmldocument" && match == "document") return true
  192. if (match == "body" && type == "htmlbodyelement") return true
  193. if (match && new RegExp(`^html${match}element$`).test(type))
  194. return true
  195. if (/^html\w+element$/.test(type)) type = "element"
  196. if (type == "htmldocument") type = "element"
  197. if (type == "asyncfunction") type = "function"
  198. if (type == "generatorfunction") type = "function"
  199. if (type == "regexp") type = "regex"
  200. if (match == "regexp") match = "regex"
  201. if (match == "element" && type == "window") return true
  202. if (match == "element" && type == "shadowroot") return true
  203. if (match == "event" && /\w+event$/.test(type)) return true
  204. if (/^(html|svg).*element$/.test(type)) type = "element"
  205. if (type == "function") {
  206. type = /^\s*class\s/.test(
  207. Function.prototype.toString.call(thing)
  208. )
  209. ? "class"
  210. : "function"
  211. }
  212. if (match == "none")
  213. return (
  214. type == "nan" || type == "undefined" || type == "null"
  215. )
  216. try {
  217. if (type === "number" && isNaN(thing) && match == "nan")
  218. return true
  219. } catch (e) {
  220. error(thing)
  221. }
  222. return match ? match === type : type
  223. } else {
  224. if (match.includes("|")) match = match.split("|")
  225. match = [...new Set(match)]
  226. return !!match.find((e) => gettype(thing, e))
  227. }
  228. }
  229. }
  230. const a = {}
  231. var x = newfunc(
  232. function foreach(arr, func) {
  233. var type = a.gettype(arr)
  234. if (type == "array") arr.forEach(func)
  235. else if (type == "object") {
  236. Reflect.ownKeys(arr).forEach((e, i) => {
  237. func(e, arr[e], i)
  238. })
  239. } else {
  240. ;[arr].forEach(func)
  241. }
  242. },
  243. ({ args: [arr, func], end, maketype }) => {
  244. arr = maketype(arr, ["array", "object", "any"])
  245. func = maketype(func, ["function"])
  246. return end()
  247. }
  248. )
  249.  
  250. a.wait = newfunc(
  251. function wait(ms) {
  252. return new Promise(function (a) {
  253. var last = Date.now()
  254. setTimeout(() => Date.now() - last - ms, ms)
  255. })
  256. },
  257. function ({ ifunset, end, args: [ms], maketype }) {
  258. ifunset([0])
  259. ms = maketype(ms, ["number"])
  260. return end()
  261. }
  262. )
  263.  
  264. a.waituntil = newfunc(
  265. function waituntil(q, cb) {
  266. return new Promise((resolve) => {
  267. var last = Date.now()
  268. var int = setInterval(
  269. function (q, cb) {
  270. if (!!q()) {
  271. clearInterval(int)
  272. try{
  273. cb(Date.now() - last)
  274. }catch(e){}
  275. resolve(Date.now() - last)
  276. }
  277. },
  278. 0,
  279. q,
  280. cb
  281. )
  282. })
  283. },
  284. function ({ end, args: [q, cb], maketype }) {
  285. q = maketype(q, ["function"])
  286. cb = maketype(cb, ["function", "undefined"])
  287. return end()
  288. }
  289. )
  290.  
  291. a.keeponlyone = newfunc(
  292. function keeponlyone(arr) {
  293. return [...new Set(arr)]
  294. },
  295. function ({ end, args: [arr], maketype }) {
  296. arr = maketype(arr, ["array"])
  297. return end()
  298. }
  299. )
  300.  
  301. a.matchall = newfunc(
  302. function matchall(x, y) {
  303. return [...x.matchAll(y)].map((e) =>
  304. e[1] !== undefined ? [...e] : e[0]
  305. )
  306. },
  307. function ({ args: [x, y], end, maketype }) {
  308. x = maketype(x, ["string"])
  309. y = maketype(y, ["regex"])
  310. return end()
  311. }
  312. )
  313.  
  314. a.randfrom = newfunc(
  315. function randfrom(min, max) {
  316. if (max === undefined)
  317. return min.length
  318. ? min[this(0, min.length - 1)]
  319. : this(0, min)
  320. if (min == max) return min
  321. if (max) return Math.round(Math.random() * (max - min)) + min
  322. return min[Math.round(Math.random() * (min.length - 1))]
  323. },
  324. function ({ args: [min, max], end, maketype }) {
  325. min = maketype(min, ["number", "array"])
  326. max = maketype(max, ["number", "undefined"])
  327. return end()
  328. }
  329. )
  330.  
  331. a.listen = newfunc(
  332. function listen(elem, type, cb, istrue = false) {
  333. var all = []
  334. if (a.gettype(type, "array")) {
  335. var temp = {}
  336. a.foreach(type, (e) => (temp[e] = cb))
  337. type = temp
  338. }
  339. if (a.gettype(type, "object")) {
  340. istrue = cb
  341. a.foreach(type, function (type, cb) {
  342. if (a.gettype(type, "string"))
  343. type = a.matchall(type, /[a-z]+/g)
  344. type.forEach((type) => {
  345. const newcb = function (...e) {
  346. cb(...e)
  347. }
  348. elem.addEventListener(type, newcb, istrue)
  349. all.push([elem, type, newcb])
  350. })
  351. })
  352. } else if (a.gettype(type, "string")) {
  353. type = a.matchall(type, /[a-z]+/g)
  354. type.forEach((type) => {
  355. const newcb = function (e) {
  356. cb(e, type)
  357. }
  358. elem.addEventListener(type, newcb, istrue)
  359. all.push([elem, type, newcb])
  360. })
  361. }
  362. return all
  363. },
  364. function ({
  365. gettype,
  366. trygettype,
  367. args: [elem, type, cb, istrue],
  368. end,
  369. maketype,
  370. }) {
  371. elem = maketype(elem, ["element", "window"])
  372. type = maketype(type, ["array", "object", "string"])
  373. if (trygettype(type, ["array", "any"])) {
  374. for (var temp in type) gettype(temp, "string")
  375. } else if (trygettype(type, "object")) {
  376. for (var temp in Object.values(type))
  377. gettype(temp, "function")
  378. }
  379. if (trygettype(type, "object")) cb = maketype(cb, ["undefined"])
  380. else cb = maketype(cb, ["function"])
  381. istrue = maketype(istrue, ["boolean", "undefined"])
  382. return end()
  383. }
  384. )
  385.  
  386. a.toelem = newfunc(
  387. function toelem(elem, single) {
  388. if (a.gettype(elem, "element")) return elem
  389. switch (a.gettype(elem)) {
  390. case "string":
  391. return single ? a.qs(elem) : a.qsa(elem)
  392. case "array":
  393. return elem.map((elem) => {
  394. return a.toelem(elem, single)
  395. })
  396. case "object":
  397. var newobj = {
  398. ...elem,
  399. }
  400. if (single)
  401. return {
  402. [Object.keys(newobj)[0]]: a.toelem(
  403. newobj[Object.keys(newobj)[0]],
  404. single
  405. ),
  406. }
  407. a.foreach(newobj, function (a, s) {
  408. newobj[a] = a.toelem(s)
  409. })
  410. return newobj
  411. default:
  412. error(elem, "inside [toelem] - not an element?")
  413. return undefined
  414. }
  415. },
  416. function ({ ifunset, end, args: [elem, single] }) {
  417. ifunset([undefined, false])
  418. elem = maketype(elem, ["element", "string", "array", "object"])
  419. single = maketype(single, ["boolean"])
  420. return end()
  421. }
  422. )
  423.  
  424. a.geturlperams = newfunc(
  425. function geturlperams(e = location.href) {
  426. var arr = {}
  427. ;[
  428. ...e.matchAll(/[?&]([^&\s]+?)(?:=([^&\s]*?))?(?=&|$|\s)/g),
  429. ].forEach((e) => {
  430. if (e[1].includes("#")) arr["#"] = e[1].match(/#(.*$)/)[1]
  431. if (e[2].includes("#")) arr["#"] = e[2].match(/#(.*$)/)[1]
  432. e[1] = e[1].replace(/#.*$/, "")
  433. e[2] = e[2].replace(/#.*$/, "")
  434. arr[decodeURIComponent(e[1]).replaceAll("+", " ")] =
  435. e[2] === undefined
  436. ? undefined
  437. : decodeURIComponent(e[2]).replaceAll("+", " ")
  438. })
  439. return arr
  440. },
  441. function ({ end, maketype, args: [e] }) {
  442. e = maketype(e, ["string"])
  443. return end()
  444. }
  445. )
  446.  
  447. a.updateurlperam = newfunc(
  448. function updateurlperam(key, value, cangoback) {
  449. var g = {
  450. ...a.geturlperams(),
  451. [key]: value,
  452. }
  453. var k = ""
  454. var hash = ""
  455. a.foreach(g, function (key, value) {
  456. if (key == "#") return (hash = key + value)
  457. key = encodeURIComponent(key)
  458. value = encodeURIComponent(value)
  459. k += "&" + (value === undefined ? key : key + "=" + value)
  460. })
  461. k = k.replace("&", "?")
  462. k += hash
  463. cangoback
  464. ? history.pushState(null, null, k)
  465. : history.replaceState(null, null, k)
  466. return key
  467. },
  468. function ({
  469. ifunset,
  470. end,
  471. maketype,
  472. args: [key, value, cangoback],
  473. }) {
  474. ifunset([undefined, undefined, true])
  475. key = maketype(key, ["string"])
  476. value = maketype(value, ["string"])
  477. cangoback = maketype(cangoback, ["boolean"])
  478. return end()
  479. }
  480. )
  481.  
  482. a.rerange = newfunc(
  483. function rerange(val, low1, high1, low2, high2) {
  484. return ((val - low1) / (high1 - low1)) * (high2 - low2) + low2
  485. },
  486. function ({
  487. end,
  488. maketype,
  489. args: [val, low1, high1, low2, high2],
  490. }) {
  491. val = maketype(val, ["number"])
  492. low1 = maketype(low1, ["number"])
  493. high1 = maketype(high1, ["number"])
  494. low2 = maketype(low2, ["number"])
  495. high2 = maketype(high2, ["number"])
  496. return end()
  497. }
  498. )
  499.  
  500. a.destring = newfunc(
  501. function destring(inp) {
  502. var out = inp
  503. if (/^[\-0-9]+$/.test(inp)) return Number(inp)
  504. if (a.gettype((out = JSON.parse(inp)), "array")) return out
  505. if (
  506. a.gettype(
  507. (out = JSON.parse(
  508. inp.replaceAll("'", '"').replaceAll("`", '"')
  509. )),
  510. "object"
  511. )
  512. )
  513. return out
  514. if (inp == "true") return true
  515. if (inp == "false") return false
  516. if (inp == "undefined") return undefined
  517. if (inp == "NaN") return NaN
  518. return inp
  519. },
  520. function ({ end, maketype, args: [inp] }) {
  521. inp = maketype(inp, ["string"])
  522. return end()
  523. }
  524. )
  525.  
  526. a.eachelem = newfunc(
  527. function eachelem(arr1, cb) {
  528. var arr = []
  529. var elem = []
  530. if (a.gettype(arr1, "array")) {
  531. arr1.foreach((e) => {
  532. elem = [
  533. ...elem,
  534. ...(a.gettype(e, "string") ? a.qsa(e) : [e]),
  535. ]
  536. })
  537. } else {
  538. elem = a.gettype(arr1, "string") ? a.qsa(ar1) : [arr1]
  539. }
  540. elem = elem.filter((e) => {
  541. return e instanceof Element
  542. })
  543. elem.foreach(function (...a) {
  544. arr.push(cb(...a))
  545. })
  546. if (arr.length == 1) arr = arr[0]
  547. return arr
  548. },
  549. function ({ end, maketype, args: [arr1, cb] }) {
  550. arr1 = maketype(arr1, ["string", "array", "element"])
  551. cb = maketype(cb, ["function"])
  552. return end()
  553. }
  554. )
  555.  
  556. a.remove = newfunc(
  557. function remove(arr, idx, isidx) {
  558. arr = [...arr]
  559. idx = isidx ? idx : arr.indexOf(idx)
  560. if (idx < 0 || typeof idx !== "number") return arr
  561. arr.splice(idx, 1)
  562. return arr
  563. },
  564. function ({
  565. ifunset,
  566. gettype,
  567. end,
  568. maketype,
  569. trymaketype,
  570. trygettype,
  571. args: [arr, idx, isidx],
  572. }) {
  573. ifunset([undefined, undefined, true])
  574. isidx = maketype(isidx, ["boolean"])
  575. if (isidx) idx = maketype(idx, ["number"])
  576. arr = maketype(arr, ["array"])
  577. return end()
  578. }
  579. )
  580.  
  581. a.createelem = newfunc(
  582. function createelem(parent, elem, data = {}) {
  583. var type = elem
  584. var issvg =
  585. elem == "svg" || parent?.tagName?.toLowerCase?.() == "svg"
  586. elem = issvg
  587. ? document.createElementNS("http://www.w3.org/2000/svg", elem)
  588. : document.createElement(elem)
  589. if (data.class)
  590. data.class.split(" ").forEach((e) => {
  591. elem.classList.add(e)
  592. })
  593. if (data.options && type == "select")
  594. data.options = data.options.map((e) =>
  595. a.gettype(e, "array")
  596. ? a.createelem(elem, "option", {
  597. innerHTML: e[0],
  598. value: e[1],
  599. })
  600. : a.createelem(elem, "option", {
  601. innerHTML: e,
  602. value: e,
  603. })
  604. )
  605. if (type == "label" && "for" in data) {
  606. data.htmlFor = data.for
  607. }
  608. Object.assign(elem.style, data)
  609. if (type == "select") {
  610. a.foreach(data, function (a, s) {
  611. elem[a] = s
  612. })
  613. } else if (issvg) {
  614. Object.keys(data).forEach((e) => (elem[e] = data[e]))
  615. } else {
  616. Object.assign(elem, data)
  617. }
  618. if (typeof parent == "string") parent = a.qs(parent)
  619. parent?.appendChild?.(elem)
  620. return elem
  621. },
  622. function ({
  623. ifunset,
  624. gettype,
  625. end,
  626. maketype,
  627. trymaketype,
  628. trygettype,
  629. args: [parent, elem, data],
  630. }) {
  631. ifunset([undefined, undefined, {}])
  632. parent = maketype(parent, ["element", "none"])
  633. elem = maketype(elem, ["string"])
  634. data = maketype(data, ["object"])
  635. return end()
  636. }
  637. )
  638. a.newelem = newfunc(
  639. function newelem(type, data = {}, inside = []) {
  640. var parent = a.createelem(null, type, data)
  641. inside.forEach((elem) => {
  642. parent.appendChild(elem)
  643. })
  644. return parent
  645. },
  646. function ({
  647. ifunset,
  648. gettype,
  649. end,
  650. maketype,
  651. trymaketype,
  652. trygettype,
  653. args: [type, data, inside],
  654. }) {
  655. ifunset([null, {}, []])
  656. type = maketype(type, ["string"])
  657. data = maketype(data, ["object", "undefined", "null"])
  658. maketype(inside, ["array", "undefined", "null"])
  659. return end()
  660. }
  661. )
  662. a.gettype = newfunc(
  663. function gettype(thing, match) {
  664. if (
  665. !match ||
  666. (Object.prototype.toString
  667. .call(match)
  668. .toLowerCase()
  669. .match(/^\[[a-z]+ (.+)\]$/)[1] == "string" &&
  670. !match.includes("|"))
  671. ) {
  672. var type = Object.prototype.toString
  673. .call(thing)
  674. .toLowerCase()
  675. .match(/^\[[a-z]+ (.+)\]$/)[1]
  676. if (type !== "function") if (type == match) return true
  677. if (match == "normalfunction") return type == "function"
  678. if (type == "htmldocument" && match == "document") return true
  679. if (match == "body" && type == "htmlbodyelement") return true
  680. if (match && new RegExp(`^html${match}element$`).test(type))
  681. return true
  682. if (/^html\w+element$/.test(type)) type = "element"
  683. if (type == "htmldocument") type = "element"
  684. if (type == "asyncfunction") type = "function"
  685. if (type == "generatorfunction") type = "function"
  686. if (type == "regexp") type = "regex"
  687. if (match == "regexp") match = "regex"
  688. if (match == "element" && type == "window") return true
  689. if (match == "element" && type == "shadowroot") return true
  690. if (match == "event" && /\w+event$/.test(type)) return true
  691. if (/^(html|svg).*element$/.test(type)) type = "element"
  692. if (type == "function") {
  693. type = /^\s*class\s/.test(
  694. Function.prototype.toString.call(thing)
  695. )
  696. ? "class"
  697. : "function"
  698. }
  699. if (match == "none")
  700. return (
  701. type == "nan" || type == "undefined" || type == "null"
  702. )
  703. try {
  704. if (type === "number" && isNaN(thing) && match == "nan")
  705. return true
  706. } catch (e) {
  707. error(thing)
  708. }
  709. return match ? match === type : type
  710. } else {
  711. if (match.includes("|")) match = match.split("|")
  712. match = [...new Set(match)]
  713. return match.filter((e) => a.gettype(thing, e)).length > 0
  714. }
  715. },
  716. function ({
  717. ifunset,
  718. gettype,
  719. end,
  720. maketype,
  721. trymaketype,
  722. trygettype,
  723. args: [_thing, match],
  724. }) {
  725. // _thing = maketype(_thing, ["any"])
  726. match = maketype(match, ["array", "string", "none"])
  727. return end()
  728. }
  729. )
  730.  
  731. a.waitforelem = newfunc(
  732. async function waitforelem(selector) {
  733. if (a.gettype(selector, "string")) {
  734. selector = [selector]
  735. }
  736. await a.bodyload()
  737. var g = false
  738. return new Promise((resolve) => {
  739. var observer = new MutationObserver(check)
  740. observer.observe(document.body, {
  741. childList: true,
  742. subtree: true,
  743. attributes: true,
  744. characterData: false,
  745. })
  746. check()
  747. function check() {
  748. if (g) return
  749. if (selector.find((selector) => !a.qs(selector))) return
  750. observer.disconnect()
  751. resolve(
  752. selector.length == 1
  753. ? a.qs(selector[0])
  754. : selector.map((e) => a.qs(e))
  755. )
  756. }
  757. })
  758. },
  759. function ({ ifunset, end, args: [selector], maketype }) {
  760. ifunset([undefined])
  761. selector = maketype(selector, ["string", "array"])
  762. return end()
  763. }
  764. )
  765.  
  766. a.getallvars = newfunc(
  767. function getallvars() {
  768. var obj = {}
  769. var variables = []
  770. for (var name in this)
  771. if (
  772. !`window self document name location customElements history locationbar menubar personalbar scrollbars statusbar toolbar status closed frames length top opener parent frameElement navigator origin external screen innerWidth innerHeight scrollX pageXOffset scrollY pageYOffset visualViewport screenX screenY outerWidth outerHeight devicePixelRatio clientInformation screenLeft screenTop styleMedia onsearch isSecureContext trustedTypes performance onappinstalled onbeforeinstallprompt crypto indexedDB sessionStorage localStorage onbeforexrselect onabort onbeforeinput onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextlost oncontextmenu oncontextrestored oncuechange ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended onerror onfocus onformdata oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onresize onscroll onsecuritypolicyviolation onseeked onseeking onselect onslotchange onstalled onsubmit onsuspend ontimeupdate ontoggle onvolumechange onwaiting onwebkitanimationend onwebkitanimationiteration onwebkitanimationstart onwebkittransitionend onwheel onauxclick ongotpointercapture onlostpointercapture onpointerdown onpointermove onpointerrawupdate onpointerup onpointercancel onpointerover onpointerout onpointerenter onpointerleave onselectstart onselectionchange onanimationend onanimationiteration onanimationstart ontransitionrun ontransitionstart ontransitionend ontransitioncancel onafterprint onbeforeprint onbeforeunload onhashchange onlanguagechange onmessage onmessageerror onoffline ononline onpagehide onpageshow onpopstate onrejectionhandled onstorage onunhandledrejection onunload crossOriginIsolated scheduler alert atob blur btoa cancelAnimationFrame cancelIdleCallback captureEvents clearInterval clearTimeout close confirm createImageBitmap fetch find focus getComputedStyle getSelection matchMedia moveBy moveTo open postMessage print prompt queueMicrotask releaseEvents reportError requestAnimationFrame requestIdleCallback resizeBy resizeTo scroll scrollBy scrollTo setInterval setTimeout stop structuredClone webkitCancelAnimationFrame webkitRequestAnimationFrame originAgentCluster navigation webkitStorageInfo speechSynthesis oncontentvisibilityautostatechange openDatabase webkitRequestFileSystem webkitResolveLocalFileSystemURL chrome caches cookieStore ondevicemotion ondeviceorientation ondeviceorientationabsolute launchQueue onbeforematch getDigitalGoodsService getScreenDetails queryLocalFonts showDirectoryPicker showOpenFilePicker showSaveFilePicker TEMPORARY PERSISTENT addEventListener dispatchEvent removeEventListener`
  773. .split(" ")
  774. .includes(name)
  775. )
  776. variables.push(name)
  777. variables.forEach((e) => {
  778. var c = String(a.gettype(this[e]))
  779. if (c === "object") c = "variable"
  780. if (!obj[c]) obj[c] = []
  781. obj[c].push(e)
  782. })
  783. return obj
  784. },
  785. function ({ end }) {
  786. return end()
  787. }
  788. )
  789.  
  790. a.sha = newfunc(
  791. function sha(s = "", includesymbols) {
  792. var tab
  793. if (typeof includesymbols == "string") {
  794. tab = includesymbols
  795. } else if (includesymbols) {
  796. tab =
  797. "`~\\|[];',./{}:<>?\"!@#$%^&*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  798. } else {
  799. tab =
  800. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  801. }
  802. return binb2b64(core_sha1(str2binb(s), s.length * 8))
  803. function core_sha1(x, len) {
  804. x[len >> 5] |= 0x80 << (24 - len)
  805. x[(((len + 64) >> 9) << 4) + 15] = len
  806. var w = Array(80)
  807. var a = 1732584193
  808. var b = -271733879
  809. var c = -1732584194
  810. var d = 271733878
  811. var e = -1009589776
  812. for (var i = 0; i < x.length; i += 16) {
  813. var olda = a
  814. var oldb = b
  815. var oldc = c
  816. var oldd = d
  817. var olde = e
  818. for (var j = 0; j < 80; j++) {
  819. if (j < 16) w[j] = x[i + j]
  820. else
  821. w[j] = rol(
  822. w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16],
  823. 1
  824. )
  825. var t = safe_add(
  826. safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
  827. safe_add(safe_add(e, w[j]), sha1_kt(j))
  828. )
  829. e = d
  830. d = c
  831. c = rol(b, 30)
  832. b = a
  833. a = t
  834. }
  835. a = safe_add(a, olda)
  836. b = safe_add(b, oldb)
  837. c = safe_add(c, oldc)
  838. d = safe_add(d, oldd)
  839. e = safe_add(e, olde)
  840. }
  841. return Array(a, b, c, d, e)
  842. }
  843. function sha1_ft(t, b, c, d) {
  844. if (t < 20) return (b & c) | (~b & d)
  845. if (t < 40) return b ^ c ^ d
  846. if (t < 60) return (b & c) | (b & d) | (c & d)
  847. return b ^ c ^ d
  848. }
  849. function sha1_kt(t) {
  850. return t < 20
  851. ? 1518500249
  852. : t < 40
  853. ? 1859775393
  854. : t < 60
  855. ? -1894007588
  856. : -899497514
  857. }
  858. function safe_add(x, y) {
  859. var lsw = (x & 0xffff) + (y & 0xffff)
  860. var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
  861. return (msw << 16) | (lsw & 0xffff)
  862. }
  863. function rol(num, cnt) {
  864. return (num << cnt) | (num >>> (32 - cnt))
  865. }
  866. function str2binb(str) {
  867. var bin = Array()
  868. var mask = (1 << 8) - 1
  869. for (var i = 0; i < str.length * 8; i += 8)
  870. bin[i >> 5] |= (str.charCodeAt(i / 8) & mask) << (24 - i)
  871. return bin
  872. }
  873. function binb2b64(binarray) {
  874. var str = ""
  875. for (var i = 0; i < binarray.length * 4; i += 3) {
  876. var triplet =
  877. (((binarray[i >> 2] >> (8 * (3 - (i % 4)))) & 0xff) <<
  878. 16) |
  879. (((binarray[(i + 1) >> 2] >> (8 * (3 - ((i + 1) % 4)))) &
  880. 0xff) <<
  881. 8) |
  882. ((binarray[(i + 2) >> 2] >> (8 * (3 - ((i + 2) % 4)))) &
  883. 0xff)
  884. for (var j = 0; j < 4; j++) {
  885. if (i * 8 + j * 6 > binarray.length * 32) str += ""
  886. else str += tab.charAt((triplet >> (6 * (3 - j))) & 0x3f)
  887. }
  888. }
  889. return str
  890. }
  891. },
  892. function ({ ifunset, end, args: [s, includesymbols] }) {
  893. ifunset([undefined, false])
  894. s = maketype(s, ["string"])
  895. includesymbols = maketype(includesymbols, ["boolean", "string"])
  896. return end()
  897. }
  898. )
  899.  
  900. a.qs = newfunc(
  901. function qs(text, parent = document) {
  902. return parent.querySelector(text)
  903. },
  904. function ({ end, args: [text, parent], maketype }) {
  905. parent = maketype(parent, ["element", "undefined"])
  906. text = maketype(text, ["string"])
  907. return end()
  908. }
  909. )
  910.  
  911. a.qsa = newfunc(
  912. function qsa(text, parent = document) {
  913. return Array.from(parent.querySelectorAll(text))
  914. },
  915. function ({ end, args: [text, parent], maketype }) {
  916. parent = maketype(parent, ["element", "undefined"])
  917. text = maketype(text, ["string"])
  918. return end()
  919. }
  920. )
  921.  
  922. a.csspath = newfunc(
  923. function csspath(el) {
  924. if (a.gettype(el, "array"))
  925. return a.map(el, (e) => a.csspath(e))
  926. if (!(el instanceof Element)) return
  927. var path = []
  928. while (el.nodeType === Node.ELEMENT_NODE) {
  929. var selector = el.nodeName.toLowerCase()
  930. if (el.id) {
  931. selector += "#" + el.id
  932. path.unshift(selector)
  933. break
  934. } else {
  935. var sib = el,
  936. nth = 1
  937. while ((sib = sib.previousElementSibling)) {
  938. if (sib.nodeName.toLowerCase() == selector) nth++
  939. }
  940. if (nth != 1) selector += ":nth-of-type(" + nth + ")"
  941. }
  942. path.unshift(selector)
  943. el = el.parentNode
  944. }
  945. return path.join(" > ")
  946. },
  947. function ({ end, args: [el], maketype }) {
  948. el = maketype(el, ["element", "array"])
  949. return end()
  950. }
  951. )
  952.  
  953. a.fromms = newfunc(
  954. function fromms(ms) {
  955. ms = Number(ms)
  956. return {
  957. years: Math.floor(ms / 1000 / 60 / 60 / 24 / 365),
  958. days: Math.floor(ms / 1000 / 60 / 60 / 24) % 365,
  959. hours: Math.floor(ms / 1000 / 60 / 60) % 24,
  960. mins: Math.floor(ms / 1000 / 60) % 60,
  961. secs: Math.floor(ms / 1000) % 60,
  962. ms: Math.floor(ms) % 1000,
  963. }
  964. },
  965. function ({ ifunset, end, args: [ms] }) {
  966. ifunset([0]) // Default value for ms
  967. ms = maketype(ms, ["number"]) // Ensure ms is a number
  968. return end()
  969. }
  970. )
  971.  
  972. a.fromms = newfunc(
  973. function fromms(ms) {
  974. ms = Number(ms)
  975. return {
  976. years: Math.floor(ms / 1000 / 60 / 60 / 24 / 365),
  977. days: Math.floor(ms / 1000 / 60 / 60 / 24) % 365,
  978. hours: Math.floor(ms / 1000 / 60 / 60) % 24,
  979. mins: Math.floor(ms / 1000 / 60) % 60,
  980. secs: Math.floor(ms / 1000) % 60,
  981. ms: Math.floor(ms) % 1000,
  982. }
  983. },
  984. function ({ ifunset, end, args: [ms] }) {
  985. ifunset([0]) // Default value for ms
  986. ms = maketype(ms, ["number"]) // Ensure ms is a number
  987. return end()
  988. }
  989. )
  990.  
  991. a.rect = newfunc(
  992. function rect(e) {
  993. if (a.gettype(e, "string")) e = a.qs(e)
  994. var { x, y, width, height } = e.getBoundingClientRect().toJSON()
  995. return {
  996. x,
  997. y,
  998. w: width,
  999. h: height,
  1000. }
  1001. },
  1002. function ({ end, args: [e] }) {
  1003. e = maketype(e, ["element", "string"]) // Ensure e is an element or string
  1004. return end()
  1005. }
  1006. )
  1007.  
  1008. a.setelem = newfunc(
  1009. function setelem(elem, data) {
  1010. var issvg =
  1011. elem == "svg" || parent?.tagName?.toLowerCase?.() == "svg"
  1012. if (data.class)
  1013. data.class.split(" ").forEach((e) => {
  1014. elem.classList.add(e)
  1015. })
  1016. if (data.options && elem.tagName.toLowerCase() == "select")
  1017. data.options = data.options.map((e) =>
  1018. a.gettype(e, "array")
  1019. ? a.createelem(elem, "option", {
  1020. innerHTML: e[0],
  1021. value: e[1],
  1022. })
  1023. : a.createelem(elem, "option", {
  1024. innerHTML: e,
  1025. value: e,
  1026. })
  1027. )
  1028. if (elem.tagName.toLowerCase() == "label" && "for" in data) {
  1029. data.htmlFor = data.for
  1030. }
  1031. Object.assign(elem.style, data)
  1032. if (elem.tagName.toLowerCase() == "select") {
  1033. a.foreach(data, function (a, s) {
  1034. elem[a] = s
  1035. })
  1036. } else if (issvg) {
  1037. Object.keys(data).forEach((e) => (elem[e] = data[e]))
  1038. } else {
  1039. Object.assign(elem, data)
  1040. }
  1041. return elem
  1042. },
  1043. function ({ ifunset, end, args: [elem, data] }) {
  1044. ifunset([undefined, {}]) // Default value for data
  1045. elem = maketype(elem, ["element", "string"]) // Ensure elem is an element or string
  1046. data = maketype(data, ["object"]) // Ensure data is an object
  1047. return end()
  1048. }
  1049. )
  1050.  
  1051. a.watchvar = newfunc(
  1052. function watchvar(varname, onset, onget, obj = window) {
  1053. obj = obj || window
  1054. obj[`_${varname}`] = undefined
  1055. obj[`${varname}`] = undefined
  1056. Object.defineProperty(obj, varname, {
  1057. configurable: false,
  1058. get() {
  1059. if (onget) return onget(obj[`_${varname}`])
  1060. return obj[`_${varname}`]
  1061. },
  1062. set(value) {
  1063. if (value === obj[`_${varname}`]) {
  1064. return
  1065. }
  1066. var s = onset(value, obj[`_${varname}`])
  1067. if (s) obj[`_${varname}`] = value
  1068. },
  1069. })
  1070. },
  1071. function ({ ifunset, end, args: [varname, onset, onget, obj] }) {
  1072. ifunset([undefined, () => {}, () => {}, window]) // Default values
  1073. varname = maketype(varname, ["string"]) // Ensure varname is a string
  1074. onset = maketype(onset, ["function"]) // Ensure onset is a function
  1075. onget = maketype(onget, ["function", "undefined"]) // Ensure onget is a function or undefined
  1076. obj = maketype(obj, ["object", "undefined"]) // Ensure obj is an object or undefined
  1077. return end()
  1078. }
  1079. )
  1080.  
  1081. a.randomizeorder = newfunc(
  1082. function randomizeorder(arr) {
  1083. arr = [...arr]
  1084. var arr2 = []
  1085. var count = arr.length
  1086. for (var i = 0; i < count; i++) {
  1087. var idx = a.randfrom(0, arr.length - 1)
  1088. arr2.push(arr[idx])
  1089. arr.splice(idx, 1)
  1090. }
  1091. return arr2
  1092. },
  1093. function ({ end, args: [arr], maketype }) {
  1094. arr = maketype(arr, ["array"]) // Ensure arr is an array
  1095. return end()
  1096. }
  1097. )
  1098.  
  1099. a.constrainvar = newfunc(
  1100. function constrainvar(varname, min, max) {
  1101. window[`_${varname}`] = undefined
  1102. window[`${varname}`] = undefined
  1103. Object.defineProperty(window, varname, {
  1104. configurable: false,
  1105. get() {
  1106. return window[`_${varname}`]
  1107. },
  1108. set(value) {
  1109. if (value === window[`_${varname}`]) {
  1110. return
  1111. }
  1112. if (value > max) value = max
  1113. if (value < min) value = min
  1114. window[`_${varname}`] = value
  1115. },
  1116. })
  1117. },
  1118. function ({ ifunset, end, args: [varname, min, max] }) {
  1119. ifunset([undefined, -Infinity, Infinity]) // Default values for min and max
  1120. varname = maketype(varname, ["string"]) // Ensure varname is a string
  1121. min = maketype(min, ["number"]) // Ensure min is a number
  1122. max = maketype(max, ["number"]) // Ensure max is a number
  1123. return end()
  1124. }
  1125. )
  1126.  
  1127. a.isbetween = newfunc(
  1128. function isbetween(z, x, c) {
  1129. if (x == c) return false
  1130. var big, small
  1131. if (x > c) {
  1132. big = x
  1133. small = c
  1134. } else {
  1135. big = c
  1136. small = x
  1137. }
  1138. return z > big && z < small
  1139. },
  1140. function ({ args: [z, x, c], end, maketype }) {
  1141. z = maketype(z, ["number"])
  1142. x = maketype(x, ["number"])
  1143. c = maketype(c, ["number"])
  1144. return end()
  1145. }
  1146. )
  1147.  
  1148. a.indexsof = newfunc(
  1149. function indexsof(y, x) {
  1150. var i = 0
  1151. var arr = []
  1152. y.split(x).forEach((e, k) => {
  1153. i += e.length
  1154. arr.push(i + k)
  1155. })
  1156. arr.pop()
  1157. return arr
  1158. },
  1159. function ({ args: [y, x], end, maketype }) {
  1160. y = maketype(y, ["string"]) // Ensure y is a string
  1161. x = maketype(x, ["string"]) // Ensure x is a string
  1162. return end()
  1163. }
  1164. )
  1165.  
  1166. a._export = newfunc(
  1167. function _export() {
  1168. var s = []
  1169. a.qsa("input, textarea").foreach((e) => {
  1170. s.push({
  1171. path: a.csspath(e),
  1172. value: escape(e.value),
  1173. checked: e.checked,
  1174. })
  1175. })
  1176. return JSON.stringify(s)
  1177. },
  1178. function ({ end }) {
  1179. return end()
  1180. }
  1181. )
  1182.  
  1183. a._import = newfunc(
  1184. function _import(data) {
  1185. data.forEach((e) => {
  1186. var s = a.qs(e.path)
  1187. s.checked = e.checked
  1188. s.value = unescape(e.value)
  1189. })
  1190. return data
  1191. },
  1192. function ({ end, args: [data] }) {
  1193. data = maketype(data, ["array"]) // Ensure data is an array
  1194. return end()
  1195. }
  1196. )
  1197.  
  1198. a.popup = newfunc(
  1199. function popup(data, x, y, w, h) {
  1200. if (x || x === 0) {
  1201. x = (screen.width / 100) * x
  1202. y = (screen.height / 100) * y
  1203. w = (screen.width / 100) * w
  1204. h = (screen.height / 100) * h
  1205. var win = open(
  1206. "",
  1207. "",
  1208. `left=${x}, top=${y} width=${w},height=${h}`
  1209. )
  1210. win.document.write(data)
  1211. return win
  1212. } else {
  1213. var win = open("")
  1214. win.document.write(data)
  1215. return win
  1216. }
  1217. },
  1218. function ({ end, maketype, args: [data, x, y, w, h] }) {
  1219. data = maketype(data, ["string"])
  1220. x = maketype(x, ["number"])
  1221. y = maketype(y, ["number"])
  1222. w = maketype(w, ["number"])
  1223. h = maketype(h, ["number"])
  1224. return end()
  1225. }
  1226. )
  1227.  
  1228. a.same = newfunc(
  1229. function same(...a) {
  1230. if (a.length == 1) a = a[0]
  1231. return (
  1232. [...new Set(a.map((e) => JSON.stringify(e)))].length === 1
  1233. )
  1234. },
  1235. function ({ end }) {
  1236. return end()
  1237. }
  1238. )
  1239.  
  1240. a.containsany = newfunc(
  1241. function containsany(arr1, arr2) {
  1242. return !!arr2.find((e) => arr1.includes(e))
  1243. },
  1244. function ({ end, args: [arr1, arr2] }) {
  1245. arr1 = maketype(arr1, ["string", "array"])
  1246. arr2 = maketype(arr2, ["string", "array"])
  1247. return end()
  1248. }
  1249. )
  1250.  
  1251. a.getprops = newfunc(
  1252. function getprops(func, peramsonly) {
  1253. return peramsonly
  1254. ? getprops(func)
  1255. .vars.map((e) => e.var)
  1256. .filter((e) => e)
  1257. : getprops(func)
  1258. },
  1259. function ({ end, args: [func, peramsonly] }) {
  1260. func = maketype(func, ["function"]) // Ensure func is a function
  1261. peramsonly = maketype(peramsonly, ["boolean", "undefined"]) // Ensure peramsonly is a boolean or undefined
  1262. return end()
  1263. }
  1264. )
  1265.  
  1266. a.bodyload = newfunc(
  1267. function bodyload() {
  1268. return new Promise((resolve) => {
  1269. if (document.body) resolve()
  1270. var observer = new MutationObserver(function () {
  1271. if (document.body) {
  1272. resolve()
  1273. observer.disconnect()
  1274. }
  1275. })
  1276. observer.observe(document.documentElement, {
  1277. childList: true,
  1278. })
  1279. })
  1280. },
  1281. function ({ end }) {
  1282. return end()
  1283. }
  1284. )
  1285.  
  1286. a.repeat = newfunc(
  1287. function repeat(func, count, delay, instantstart, waituntildone) {
  1288. if (delay || waituntildone)
  1289. return new Promise(async (resolve) => {
  1290. if (delay) {
  1291. var extra = 0
  1292. for (var i = 0; i < count; i++) {
  1293. if (instantstart)
  1294. waituntildone ? await func(i) : func(i)
  1295. extra = await a.wait(delay - extra)
  1296. if (!instantstart)
  1297. waituntildone ? await func(i) : func(i)
  1298. }
  1299. resolve()
  1300. } else
  1301. for (var i = 0; i < count; i++)
  1302. waituntildone ? await func(i) : func(i)
  1303. resolve()
  1304. })
  1305. for (var i = 0; i < count; i++) func(i)
  1306. return
  1307. },
  1308. function ({
  1309. end,
  1310. args: [func, count, delay, instantstart, waituntildone],
  1311. maketype,
  1312. }) {
  1313. func = maketype(func, ["function"]) // Ensure func is a function
  1314. count = maketype(count, ["number"]) // Ensure count is a number
  1315. delay = maketype(delay, ["number", "undefined"]) // Ensure delay is a number or undefined
  1316. instantstart = maketype(instantstart, ["boolean", "undefined"]) // Ensure instantstart is a boolean or undefined
  1317. waituntildone = maketype(waituntildone, [
  1318. "boolean",
  1319. "undefined",
  1320. ]) // Ensure waituntildone is a boolean or undefined
  1321. return end()
  1322. }
  1323. )
  1324.  
  1325. a.repeatuntil = newfunc(
  1326. function repeatuntil(
  1327. func,
  1328. donecheck,
  1329. delay,
  1330. instantstart,
  1331. waituntildone
  1332. ) {
  1333. return new Promise(async (resolve) => {
  1334. if (delay) {
  1335. var extra = 0
  1336. var i = 0
  1337. while (!donecheck()) {
  1338. i++
  1339. if (instantstart) {
  1340. waituntildone ? await func(i) : func(i)
  1341. }
  1342. extra = await a.wait(delay - extra)
  1343. if (!instantstart) {
  1344. waituntildone ? await func(i) : func(i)
  1345. }
  1346. }
  1347. resolve()
  1348. } else {
  1349. var i = 0
  1350. while (!donecheck()) {
  1351. i++
  1352. waituntildone ? await func(i) : func(i)
  1353. }
  1354. resolve()
  1355. }
  1356. })
  1357. },
  1358. function ({
  1359. end,
  1360. args: [func, donecheck, delay, instantstart, waituntildone],
  1361. }) {
  1362. func = maketype(func, ["function"]) // Ensure func is a function
  1363. donecheck = maketype(donecheck, ["function"]) // Ensure donecheck is a function
  1364. delay = maketype(delay, ["number", "undefined"]) // Ensure delay is a number or undefined
  1365. instantstart = maketype(instantstart, ["boolean", "undefined"]) // Ensure instantstart is a boolean or undefined
  1366. waituntildone = maketype(waituntildone, [
  1367. "boolean",
  1368. "undefined",
  1369. ]) // Ensure waituntildone is a boolean or undefined
  1370. return end()
  1371. }
  1372. )
  1373.  
  1374. a.getfolderpath = newfunc(
  1375. async function getfolderpath(folder) {
  1376. async function parsedir(dir, x) {
  1377. if (!x) {
  1378. return [
  1379. {
  1380. name: dir.name,
  1381. inside: await parsedir(dir, true),
  1382. type: "folder",
  1383. handle: dir,
  1384. },
  1385. ]
  1386. } else var arr = []
  1387. for await (const [name, handle] of dir.entries()) {
  1388. arr.push(
  1389. a.gettype(handle, "filesystemdirectoryhandle")
  1390. ? {
  1391. type: "folder",
  1392. inside: await parsedir(handle, true),
  1393. name,
  1394. handle,
  1395. }
  1396. : { type: "file", handle, name }
  1397. )
  1398. }
  1399. return arr
  1400. }
  1401. return parsedir(folder)
  1402. },
  1403. function ({ end, args: [folder] }) {
  1404. folder = maketype(folder, ["filesystemdirectoryhandle"]) // Ensure folder is a valid filesystem directory handle
  1405. return end()
  1406. }
  1407. )
  1408.  
  1409. a.getfiles = newfunc(
  1410. async function getfiles(
  1411. oldway,
  1412. multiple,
  1413. accept = [],
  1414. options = {}
  1415. ) {
  1416. const supportsFileSystemAccess =
  1417. "showOpenFilePicker" in window &&
  1418. (() => {
  1419. try {
  1420. return window.self === window.top
  1421. } catch {
  1422. return false
  1423. }
  1424. })()
  1425. if (!oldway) {
  1426. if (!supportsFileSystemAccess) throw new Error("no access")
  1427. let fileOrFiles = undefined
  1428. try {
  1429. const handles = await showOpenFilePicker({
  1430. types: [
  1431. {
  1432. accept: {
  1433. "*/*": accept,
  1434. },
  1435. },
  1436. ],
  1437. multiple,
  1438. ...options,
  1439. })
  1440. if (!multiple) {
  1441. fileOrFiles = handles[0]
  1442. } else {
  1443. fileOrFiles = await Promise.all(handles)
  1444. }
  1445. } catch (err) {
  1446. if (err.name !== "AbortError") {
  1447. error(err.name, err.message)
  1448. }
  1449. }
  1450. return fileOrFiles
  1451. }
  1452. return new Promise(async (resolve) => {
  1453. await a.bodyload()
  1454. const input = document.createElement("input")
  1455. input.style.display = "none"
  1456. input.type = "file"
  1457. if (accept) input.accept = accept
  1458. document.body.append(input)
  1459. if (multiple) {
  1460. input.multiple = true
  1461. }
  1462. input.addEventListener("change", () => {
  1463. input.remove()
  1464. resolve(multiple ? Array.from(input.files) : input.files[0])
  1465. })
  1466. if ("showPicker" in HTMLInputElement.prototype) {
  1467. input.showPicker()
  1468. } else {
  1469. input.click()
  1470. }
  1471. })
  1472. },
  1473. function ({ end, args: [oldway, multiple, accept, options] }) {
  1474. oldway = maketype(oldway, ["boolean"]) // Ensure oldway is a boolean
  1475. multiple = maketype(multiple, ["boolean"]) // Ensure multiple is a boolean
  1476. accept = maketype(accept, ["array", "string", "undefined"]) // Ensure accept is an array or string
  1477. options = maketype(options, ["object"]) // Ensure options is an object
  1478. return end()
  1479. }
  1480. )
  1481. // Test function for getfolderpath and getfiles
  1482.  
  1483. // newfunc(
  1484. // async function testGetFunctions() {
  1485. // const folderHandle = await showDirectoryPicker() // Assuming the user selects a directory
  1486. // const folderContents = await getfolderpath(folderHandle)
  1487. // console.log("Folder Contents:", folderContents)
  1488. // const files = await getfiles(false, true, [".txt", ".jpg"]) // Example for getting files
  1489. // console.log("Selected Files:", files)
  1490. // },
  1491. // function ({ end }) {
  1492. // return end() // No additional validation needed for this test function
  1493. // }
  1494. // )
  1495.  
  1496. a.map = newfunc(
  1497. function map(arr, func) {
  1498. var type = a.gettype(arr)
  1499. if (type == "array") return arr.map(func)
  1500. else if (type == "object") {
  1501. var temparr = {}
  1502. Reflect.ownKeys(arr).forEach((e, i) => {
  1503. temparr = {
  1504. ...temparr,
  1505. ...func(e, arr[e], i),
  1506. }
  1507. })
  1508. return temparr
  1509. } else {
  1510. return [arr].map(func)
  1511. }
  1512. },
  1513. function ({ end, args: [arr, func] }) {
  1514. arr = maketype(arr, ["array", "object"]) // Ensure arr is an array or object
  1515. func = maketype(func, ["function"]) // Ensure func is a function
  1516. return end()
  1517. }
  1518. )
  1519.  
  1520. a.find = newfunc(
  1521. function find(arr, func) {
  1522. var type = a.gettype(arr)
  1523. if (type == "array") return arr.find(func)
  1524. else if (type == "object") {
  1525. return Reflect.ownKeys(arr).find((e, i) => {
  1526. return func(e, arr[e], i)
  1527. })
  1528. } else {
  1529. return [arr].find(func)
  1530. }
  1531. },
  1532. function ({ end, args: [arr, func] }) {
  1533. arr = maketype(arr, ["array", "object"]) // Ensure arr is an array or object
  1534. func = maketype(func, ["function"]) // Ensure func is a function
  1535. return end()
  1536. }
  1537. )
  1538.  
  1539. a.filteridx = newfunc(
  1540. function filteridx(arr, func) {
  1541. if (a.gettype(arr, "object")) arr = [arr]
  1542. return a
  1543. .map(arr, (e, i) => (func(e, i) ? i : undefined))
  1544. .filter((e) => e !== undefined)
  1545. },
  1546. function ({ end, args: [arr, func] }) {
  1547. arr = maketype(arr, ["array", "object"]) // Ensure arr is an array or object
  1548. func = maketype(func, ["function"]) // Ensure func is a function
  1549. return end()
  1550. }
  1551. )
  1552.  
  1553. a.filter = newfunc(
  1554. function filter(arr, func) {
  1555. var type = a.gettype(arr)
  1556. if (type == "array") return arr.filter(func)
  1557. else if (type == "object") {
  1558. var temparr = {}
  1559. Reflect.ownKeys(arr).forEach((e, i) => {
  1560. if (func(e, arr[e], i))
  1561. temparr = {
  1562. ...temparr,
  1563. [e]: arr[e],
  1564. }
  1565. })
  1566. return temparr
  1567. } else {
  1568. return [arr].filter(func)
  1569. }
  1570. },
  1571. function ({ end, args: [arr, func] }) {
  1572. arr = maketype(arr, ["array", "object"]) // Ensure arr is an array or object
  1573. func = maketype(func, ["function"]) // Ensure func is a function
  1574. return end()
  1575. }
  1576. )
  1577.  
  1578. a.unique = newfunc(
  1579. function unique() /*object*/ {
  1580. return last || (last = different.new())
  1581. },
  1582. function ({ end }) {
  1583. return end()
  1584. }
  1585. )
  1586. // Test function for the new functions
  1587.  
  1588. // newfunc(
  1589. // async function testNewFunctions() {
  1590. // const testArray = [1, 2, 3, 4, 5]
  1591. // const testFunc = (x) => x > 2
  1592. // const mapped = await map(testArray, (x) => x * 2)
  1593. // console.log("Mapped:", mapped) // [2, 4, 6, 8, 10]
  1594. // const found = await find(testArray, testFunc)
  1595. // console.log("Found:", found) // 3
  1596. // const filteredIdx = await filteridx(testArray, testFunc)
  1597. // console.log("Filtered Indices:", filteredIdx) // [2, 3, 4]
  1598. // const filtered = await filter(testArray, testFunc)
  1599. // console.log("Filtered:", filtered) // [3, 4, 5]
  1600. // const uniqueResult = await unique()
  1601. // console.log("Unique Result:", uniqueResult) // Depends on the implementation of unique
  1602. // },
  1603. // function ({ end }) {
  1604. // return end() // No additional validation needed for this test function
  1605. // }
  1606. // )
  1607.  
  1608. a.tostring = newfunc(
  1609. function tostring(e) {
  1610. if (["object", "array"].includes(a.gettype(e)))
  1611. return JSON.stringify(e)
  1612. if (a.gettype(e, "element")) return a.csspath(e)
  1613. return String(e)
  1614. },
  1615. function ({ end, args: [e] }) {
  1616. e = maketype(e, ["any"]) // Ensure e can be any type
  1617. return end()
  1618. }
  1619. )
  1620. // Test function for tostring
  1621.  
  1622. // newfunc(
  1623. // async function testTostring() {
  1624. // const testObject = { key: "value" }
  1625. // const testArray = [1, 2, 3]
  1626. // const testElement = document.createElement("div")
  1627. // testElement.id = "testElement"
  1628. // console.log("Object to String:", await tostring(testObject)) // Should log the JSON string of the object
  1629. // console.log("Array to String:", await tostring(testArray)) // Should log the JSON string of the array
  1630. // console.log("Element to String:", await tostring(testElement)) // Should log the CSS path of the element
  1631. // console.log("Number to String:", await tostring(123)) // Should log "123"
  1632. // console.log("String to String:", await tostring("Hello")) // Should log "Hello"
  1633. // },
  1634. // function ({ end }) {
  1635. // return end() // No additional validation needed for this test function
  1636. // }
  1637. // )
  1638.  
  1639. a.toregex = newfunc(
  1640. function toregex(d, s) {
  1641. if (a.gettype(d, "array")) var temp = d
  1642. if (s) var temp = [d, s]
  1643. else if (String(d).match(/^\/(.*)\/(\w*)$/)) {
  1644. var m = String(d).match(/^\/(.*)\/(\w*)$/)
  1645. var temp = [m[1], m[2]]
  1646. } else var temp = [String(d), ""]
  1647. temp[1] = temp[1].toLowerCase()
  1648. if (temp[1].includes("w")) {
  1649. temp[1] = temp[1].replace("w", "")
  1650. temp[0] = `(?<=[^a-z0-9]|^)${temp[0]}(?=[^a-z0-9]|$)`
  1651. }
  1652. return new RegExp(
  1653. temp[0],
  1654. temp[1].replaceAll(/(.)(?=.*\1)/g, "")
  1655. )
  1656. },
  1657. function ({ end, args: [d, s] }) {
  1658. d = maketype(d, ["string", "array"]) // Ensure d is a string or array
  1659. s = maketype(s, ["string", "undefined"]) // Ensure s is a string or undefined
  1660. return end()
  1661. }
  1662. )
  1663.  
  1664. a.isregex = newfunc(
  1665. function isregex(s) {
  1666. if (a.gettype(s, "regex")) return true
  1667. return (
  1668. /^\/.*(?<!\\)\/[gimusy]*$/.test(s) && !/^\/\*.*\*\/$/.test(s)
  1669. )
  1670. },
  1671. function ({ end, args: [s] }) {
  1672. s = maketype(s, ["string"]) // Ensure s is a string
  1673. return end()
  1674. }
  1675. )
  1676.  
  1677. a.ispressed = newfunc(
  1678. function ispressed(e /*event*/, code) {
  1679. code = code.toLowerCase()
  1680. var temp =
  1681. e.shiftKey == code.includes("shift") &&
  1682. e.altKey == code.includes("alt") &&
  1683. e.ctrlKey == code.includes("ctrl") &&
  1684. e.metaKey == code.includes("meta") &&
  1685. e.key.toLowerCase() ==
  1686. code.replaceAll(/alt|ctrl|shift|meta/g, "").trim()
  1687. if (temp && !a) e.preventDefault()
  1688. return temp
  1689. },
  1690. function ({ end, args: [e, code] }) {
  1691. e = maketype(e, ["object"]) // Ensure e is an event object
  1692. code = maketype(code, ["string"]) // Ensure code is a string
  1693. return end()
  1694. }
  1695. )
  1696. // Test function for toregex, isregex, and ispressed
  1697.  
  1698. // newfunc(
  1699. // async function testRegexFunctions() {
  1700. // const regex1 = toregex("abc", "g")
  1701. // console.log("Regex 1:", regex1) // Should log the regex for "abc"
  1702. // const regex2 = toregex("/abc/i")
  1703. // console.log("Regex 2:", regex2) // Should log the regex for "abc" with case insensitive
  1704. // console.log("Is regex1 a regex?", isregex(regex1)) // Should log true
  1705. // console.log("Is 'abc' a regex?", isregex("abc")) // Should log false
  1706. // // Simulating a keypress event for testing ispressed
  1707. // const mockEvent = {
  1708. // key: "a",
  1709. // shiftKey: false,
  1710. // altKey: false,
  1711. // ctrlKey: false,
  1712. // metaKey: false,
  1713. // }
  1714. // console.log("Is 'a' pressed?", ispressed(mockEvent, "a")) // Should log true
  1715. // console.log("Is 'Shift+a' pressed?", ispressed(mockEvent, "Shift+a")) // Should log false
  1716. // },
  1717. // function ({ end }) {
  1718. // return end() // No additional validation needed for this test function
  1719. // }
  1720. // )
  1721.  
  1722. a.controller_vibrate = newfunc(
  1723. function controller_vibrate(
  1724. pad,
  1725. duration = 1000,
  1726. strongMagnitude = 0,
  1727. weakMagnitude = 0
  1728. ) {
  1729. getpad(pad).vibrationActuator.playEffect("dual-rumble", {
  1730. duration,
  1731. strongMagnitude,
  1732. weakMagnitude,
  1733. })
  1734. return pad
  1735. },
  1736. function ({
  1737. end,
  1738. args: [pad, duration, strongMagnitude, weakMagnitude],
  1739. }) {
  1740. pad = maketype(pad, ["element"]) // Ensure pad is a valid element
  1741. duration = maketype(duration, ["number"]) // Ensure duration is a number
  1742. strongMagnitude = maketype(strongMagnitude, ["number"]) // Ensure strongMagnitude is a number
  1743. weakMagnitude = maketype(weakMagnitude, ["number"]) // Ensure weakMagnitude is a number
  1744. return end()
  1745. }
  1746. )
  1747.  
  1748. a.controller_getbutton = newfunc(
  1749. function controller_getbutton(pad, button) {
  1750. return button
  1751. ? getpad(pad).buttons[button].value
  1752. : getpad(pad).buttons.map((e) => e.value)
  1753. },
  1754. function ({ end, args: [pad, button] }) {
  1755. pad = maketype(pad, ["element"]) // Ensure pad is a valid element
  1756. button = maketype(button, ["number", "undefined"]) // Ensure button is a number or undefined
  1757. return end()
  1758. }
  1759. )
  1760.  
  1761. a.controller_getaxes = newfunc(
  1762. function controller_getaxes(pad, axes) {
  1763. return axes ? getpad(pad).axes[axes] : getpad(pad).axes
  1764. },
  1765. function ({ end, args: [pad, axes] }) {
  1766. pad = maketype(pad, ["element"]) // Ensure pad is a valid element
  1767. axes = maketype(axes, ["number", "undefined"]) // Ensure axes is a number or undefined
  1768. return end()
  1769. }
  1770. )
  1771.  
  1772. a.controller_exists = newfunc(
  1773. function controller_exists(pad) {
  1774. return pad === undefined
  1775. ? getpad().filter((e) => e).length
  1776. : !!getpad(pad)
  1777. },
  1778. function ({ end, args: [pad] }) {
  1779. pad = maketype(pad, ["element", "undefined"]) // Ensure pad is a valid element or undefined
  1780. return end()
  1781. }
  1782. )
  1783. // Test function for the new controller functions
  1784.  
  1785. // newfunc(
  1786. // async function testControllerFunctions() {
  1787. // const pad = getpad(0) // Assuming you have a way to get the first pad
  1788. // console.log("Controller Exists:", await controller_exists(pad)) // Should log true or false
  1789. // console.log(
  1790. // "Controller Vibrate:",
  1791. // await controller_vibrate(pad, 2000, 1, 0.5)
  1792. // ) // Should trigger vibration
  1793. // console.log("Button Value:", await controller_getbutton(pad, 0)) // Should log the value of the first button
  1794. // console.log("Axes Values:", await controller_getaxes(pad)) // Should log the axes values
  1795. // },
  1796. // function ({ end }) {
  1797. // return end() // No additional validation needed for this test function
  1798. // }
  1799. // )
  1800.  
  1801. a.readfile = newfunc(
  1802. async function readfile(file, type = "Text") {
  1803. return new Promise(function (done, error) {
  1804. var f = new FileReader()
  1805. f.onerror = error
  1806. f.onload = () =>
  1807. done(type == "json" ? JSON.parse(f.result) : f.result)
  1808. f["readAs" + (type == "json" ? "Text" : type)](file)
  1809. })
  1810. },
  1811. function ({ end, args: [file, type] }) {
  1812. type = maketype(type, ["string"]) // Ensure type is a string
  1813. return end()
  1814. }
  1815. )
  1816.  
  1817. a.writefile = newfunc(
  1818. async function writefile(file, text) {
  1819. var f = await file.createWritable()
  1820. await f.write(text)
  1821. await f.close()
  1822. return file
  1823. },
  1824. function ({ end, args: [file, text] }) {
  1825. text = maketype(text, ["string"]) // Ensure text is a string
  1826. return end()
  1827. }
  1828. )
  1829.  
  1830. a.getfileperms = newfunc(
  1831. async function getfileperms(fileHandle, readWrite) {
  1832. const options = {}
  1833. if (readWrite) {
  1834. options.mode = "readwrite"
  1835. }
  1836. return (
  1837. (await fileHandle.queryPermission(options)) === "granted" ||
  1838. (await fileHandle.requestPermission(options)) === "granted"
  1839. )
  1840. },
  1841. function ({ end, args: [fileHandle, readWrite] }) {
  1842. readWrite = maketype(readWrite, ["boolean", "undefined"]) // Ensure readWrite is a boolean or undefined
  1843. return end()
  1844. }
  1845. )
  1846. // Test function for readfile, writefile, and getfileperms
  1847.  
  1848. // newfunc(
  1849. // async function testFileFunctions() {
  1850. // const fileHandle = await showOpenFilePicker() // Assuming the user selects a file
  1851. // const file = fileHandle[0] // Get the first file handle
  1852. // // Test readfile
  1853. // const content = await readfile(file, "Text")
  1854. // console.log("File Content:", content)
  1855. // // Test writefile
  1856. // const updatedFile = await writefile(file, "New content")
  1857. // console.log("Updated File:", updatedFile)
  1858. // // Test getfileperms
  1859. // const hasPerms = await getfileperms(fileHandle[0], true)
  1860. // console.log("File Permissions Granted:", hasPerms)
  1861. // },
  1862. // function ({ end }) {
  1863. // return end() // No additional validation needed for this test function
  1864. // }
  1865. // )
  1866.  
  1867. a.indexeddb_set = newfunc(
  1868. async function indexeddb_set(place, obj) {
  1869. return new Promise((done, error) =>
  1870. place.put(
  1871. obj,
  1872. (e) => done(e),
  1873. (e) => error(e)
  1874. )
  1875. )
  1876. },
  1877. function ({ end, args: [place, obj] }) {
  1878. place = maketype(place, ["object"]) // Ensure place is an object
  1879. obj = maketype(obj, ["object"]) // Ensure obj is an object
  1880. return end()
  1881. }
  1882. )
  1883.  
  1884. a.indexeddb_get = newfunc(
  1885. async function indexeddb_get(place, obj) {
  1886. return new Promise((done, error) =>
  1887. place.get(
  1888. obj,
  1889. (e) => done(e),
  1890. (e) => error(e)
  1891. )
  1892. )
  1893. },
  1894. function ({ end, args: [place, obj] }) {
  1895. place = maketype(place, ["object"]) // Ensure place is an object
  1896. obj = maketype(obj, ["string"]) // Ensure obj is a string
  1897. return end()
  1898. }
  1899. )
  1900.  
  1901. a.indexeddb_getall = newfunc(
  1902. async function indexeddb_getall(place) {
  1903. return new Promise((done, error) =>
  1904. place.getAll(
  1905. (e) => done(e),
  1906. (e) => error(e)
  1907. )
  1908. )
  1909. },
  1910. function ({ end, args: [place] }) {
  1911. place = maketype(place, ["object"]) // Ensure place is an object
  1912. return end()
  1913. }
  1914. )
  1915.  
  1916. a.indexeddb_clearall = newfunc(
  1917. async function indexeddb_clearall(place) {
  1918. return new Promise((done, error) =>
  1919. place.clear(
  1920. (e) => done(e),
  1921. (e) => error(e)
  1922. )
  1923. )
  1924. },
  1925. function ({ end, args: [place] }) {
  1926. place = maketype(place, ["object"]) // Ensure place is an object
  1927. return end()
  1928. }
  1929. )
  1930.  
  1931. a.indexeddb_remove = newfunc(
  1932. async function indexeddb_remove(place, obj) {
  1933. return new Promise((done, error) =>
  1934. place.remove(
  1935. obj,
  1936. (e) => done(e),
  1937. (e) => error(e)
  1938. )
  1939. )
  1940. },
  1941. function ({ end, args: [place, obj] }) {
  1942. place = maketype(place, ["object"]) // Ensure place is an object
  1943. obj = maketype(obj, ["string"]) // Ensure obj is a string
  1944. return end()
  1945. }
  1946. )
  1947. // Test function for the indexeddb functions
  1948.  
  1949. // newfunc(
  1950. // async function testIndexedDBFunctions() {
  1951. // const dbName = "testDB"
  1952. // const storeName = "testStore"
  1953. // const request = indexedDB.open(dbName)
  1954. // request.onsuccess = async function () {
  1955. // const db = request.result
  1956. // const transaction = db.transaction(storeName, "readwrite")
  1957. // const store = transaction.objectStore(storeName)
  1958. // // Test indexeddb_set
  1959. // await indexeddb_set(store, { id: 1, name: "Test Item" })
  1960. // console.log("Item added")
  1961. // // Test indexeddb_get
  1962. // const item = await indexeddb_get(store, 1)
  1963. // console.log("Retrieved Item:", item)
  1964. // // Test indexeddb_getall
  1965. // const allItems = await indexeddb_getall(store)
  1966. // console.log("All Items:", allItems)
  1967. // // Test indexeddb_remove
  1968. // await indexeddb_remove(store, 1)
  1969. // console.log("Item removed")
  1970. // // Test indexeddb_clearall
  1971. // await indexeddb_clearall(store)
  1972. // console.log("All items cleared")
  1973. // }
  1974. // request.onerror = function () {
  1975. // console.error("Database error:", request.error)
  1976. // }
  1977. // },
  1978. // function ({ end }) {
  1979. // return end() // No additional validation needed for this test function
  1980. // }
  1981. // )
  1982.  
  1983. a.indexeddb_setup = newfunc(
  1984. async function indexeddb_setup(obj) {
  1985. return new Promise((e) => {
  1986. var x
  1987. obj = {
  1988. dbVersion: 1,
  1989. storeName: "tempstorename",
  1990. keyPath: "id",
  1991. autoIncrement: true,
  1992. ...obj,
  1993. onStoreReady() {
  1994. e(x)
  1995. },
  1996. }
  1997. if (!window.IDBStore) {
  1998. ;(function (p, h, k) {
  1999. "function" === typeof define
  2000. ? define(h)
  2001. : "undefined" !== typeof module && module.exports
  2002. ? (module.exports = h())
  2003. : (k[p] = h())
  2004. })(
  2005. "IDBStore",
  2006. function () {
  2007. function p(a, b) {
  2008. var c, d
  2009. for (c in b)
  2010. (d = b[c]), d !== u[c] && d !== a[c] && (a[c] = d)
  2011. return a
  2012. }
  2013. var h = function (a) {
  2014. throw a
  2015. },
  2016. k = function () {},
  2017. r = {
  2018. storeName: "Store",
  2019. storePrefix: "IDBWrapper-",
  2020. dbVersion: 1,
  2021. keyPath: "id",
  2022. autoIncrement: !0,
  2023. onStoreReady: function () {},
  2024. onError: h,
  2025. indexes: [],
  2026. implementationPreference: [
  2027. "indexedDB",
  2028. "webkitIndexedDB",
  2029. "mozIndexedDB",
  2030. "shimIndexedDB",
  2031. ],
  2032. },
  2033. q = function (a, b) {
  2034. "undefined" == typeof b &&
  2035. "function" == typeof a &&
  2036. (b = a)
  2037. "[object Object]" !=
  2038. Object.prototype.toString.call(a) && (a = {})
  2039. for (var c in r)
  2040. this[c] = "undefined" != typeof a[c] ? a[c] : r[c]
  2041. this.dbName = this.storePrefix + this.storeName
  2042. this.dbVersion = parseInt(this.dbVersion, 10) || 1
  2043. b && (this.onStoreReady = b)
  2044. var d = "object" == typeof window ? window : self
  2045. this.implementation =
  2046. this.implementationPreference.filter(function (
  2047. a
  2048. ) {
  2049. return a in d
  2050. })[0]
  2051. this.idb = d[this.implementation]
  2052. this.keyRange =
  2053. d.IDBKeyRange ||
  2054. d.webkitIDBKeyRange ||
  2055. d.mozIDBKeyRange
  2056. this.consts = {
  2057. READ_ONLY: "readonly",
  2058. READ_WRITE: "readwrite",
  2059. VERSION_CHANGE: "versionchange",
  2060. NEXT: "next",
  2061. NEXT_NO_DUPLICATE: "nextunique",
  2062. PREV: "prev",
  2063. PREV_NO_DUPLICATE: "prevunique",
  2064. }
  2065. this.openDB()
  2066. },
  2067. t = {
  2068. constructor: q,
  2069. version: "1.7.2",
  2070. db: null,
  2071. dbName: null,
  2072. dbVersion: null,
  2073. store: null,
  2074. storeName: null,
  2075. storePrefix: null,
  2076. keyPath: null,
  2077. autoIncrement: null,
  2078. indexes: null,
  2079. implementationPreference: null,
  2080. implementation: "",
  2081. onStoreReady: null,
  2082. onError: null,
  2083. _insertIdCount: 0,
  2084. openDB: function () {
  2085. var a = this.idb.open(
  2086. this.dbName,
  2087. this.dbVersion
  2088. ),
  2089. b = !1
  2090. a.onerror = function (a) {
  2091. var b
  2092. b =
  2093. "error" in a.target
  2094. ? "VersionError" == a.target.error.name
  2095. : "errorCode" in a.target
  2096. ? 12 == a.target.errorCode
  2097. : !1
  2098. if (b)
  2099. this.onError(
  2100. Error(
  2101. "The version number provided is lower than the existing one."
  2102. )
  2103. )
  2104. else
  2105. a.target.error
  2106. ? (a = a.target.error)
  2107. : ((b =
  2108. "IndexedDB unknown error occurred when opening DB " +
  2109. this.dbName +
  2110. " version " +
  2111. this.dbVersion),
  2112. "errorCode" in a.target &&
  2113. (b +=
  2114. " with error code " +
  2115. a.target.errorCode),
  2116. (a = Error(b))),
  2117. this.onError(a)
  2118. }.bind(this)
  2119. a.onsuccess = function (a) {
  2120. if (!b)
  2121. if (this.db) this.onStoreReady()
  2122. else if (
  2123. ((this.db = a.target.result),
  2124. "string" == typeof this.db.version)
  2125. )
  2126. this.onError(
  2127. Error(
  2128. "The IndexedDB implementation in this browser is outdated. Please upgrade your browser."
  2129. )
  2130. )
  2131. else if (
  2132. this.db.objectStoreNames.contains(
  2133. this.storeName
  2134. )
  2135. ) {
  2136. this.store = this.db
  2137. .transaction(
  2138. [this.storeName],
  2139. this.consts.READ_ONLY
  2140. )
  2141. .objectStore(this.storeName)
  2142. var d = Array.prototype.slice.call(
  2143. this.getIndexList()
  2144. )
  2145. this.indexes.forEach(function (a) {
  2146. var c = a.name
  2147. if (c)
  2148. if (
  2149. (this.normalizeIndexData(a),
  2150. this.hasIndex(c))
  2151. ) {
  2152. var g = this.store.index(c)
  2153. this.indexComplies(g, a) ||
  2154. ((b = !0),
  2155. this.onError(
  2156. Error(
  2157. 'Cannot modify index "' +
  2158. c +
  2159. '" for current version. Please bump version number to ' +
  2160. (this.dbVersion + 1) +
  2161. "."
  2162. )
  2163. ))
  2164. d.splice(d.indexOf(c), 1)
  2165. } else
  2166. (b = !0),
  2167. this.onError(
  2168. Error(
  2169. 'Cannot create new index "' +
  2170. c +
  2171. '" for current version. Please bump version number to ' +
  2172. (this.dbVersion + 1) +
  2173. "."
  2174. )
  2175. )
  2176. else
  2177. (b = !0),
  2178. this.onError(
  2179. Error(
  2180. "Cannot create index: No index name given."
  2181. )
  2182. )
  2183. }, this)
  2184. d.length &&
  2185. ((b = !0),
  2186. this.onError(
  2187. Error(
  2188. 'Cannot delete index(es) "' +
  2189. d.toString() +
  2190. '" for current version. Please bump version number to ' +
  2191. (this.dbVersion + 1) +
  2192. "."
  2193. )
  2194. ))
  2195. b || this.onStoreReady()
  2196. } else
  2197. this.onError(
  2198. Error("Object store couldn't be created.")
  2199. )
  2200. }.bind(this)
  2201. a.onupgradeneeded = function (a) {
  2202. this.db = a.target.result
  2203. this.db.objectStoreNames.contains(
  2204. this.storeName
  2205. )
  2206. ? (this.store =
  2207. a.target.transaction.objectStore(
  2208. this.storeName
  2209. ))
  2210. : ((a = {
  2211. autoIncrement: this.autoIncrement,
  2212. }),
  2213. null !== this.keyPath &&
  2214. (a.keyPath = this.keyPath),
  2215. (this.store = this.db.createObjectStore(
  2216. this.storeName,
  2217. a
  2218. )))
  2219. var d = Array.prototype.slice.call(
  2220. this.getIndexList()
  2221. )
  2222. this.indexes.forEach(function (a) {
  2223. var c = a.name
  2224. c ||
  2225. ((b = !0),
  2226. this.onError(
  2227. Error(
  2228. "Cannot create index: No index name given."
  2229. )
  2230. ))
  2231. this.normalizeIndexData(a)
  2232. if (this.hasIndex(c)) {
  2233. var g = this.store.index(c)
  2234. this.indexComplies(g, a) ||
  2235. (this.store.deleteIndex(c),
  2236. this.store.createIndex(c, a.keyPath, {
  2237. unique: a.unique,
  2238. multiEntry: a.multiEntry,
  2239. }))
  2240. d.splice(d.indexOf(c), 1)
  2241. } else
  2242. this.store.createIndex(c, a.keyPath, {
  2243. unique: a.unique,
  2244. multiEntry: a.multiEntry,
  2245. })
  2246. }, this)
  2247. d.length &&
  2248. d.forEach(function (a) {
  2249. this.store.deleteIndex(a)
  2250. }, this)
  2251. }.bind(this)
  2252. },
  2253. deleteDatabase: function (a, b) {
  2254. if (this.idb.deleteDatabase) {
  2255. this.db.close()
  2256. var c = this.idb.deleteDatabase(this.dbName)
  2257. c.onsuccess = a
  2258. c.onerror = b
  2259. } else
  2260. b(
  2261. Error(
  2262. "Browser does not support IndexedDB deleteDatabase!"
  2263. )
  2264. )
  2265. },
  2266. put: function (a, b, c, d) {
  2267. null !== this.keyPath &&
  2268. ((d = c), (c = b), (b = a))
  2269. d || (d = h)
  2270. c || (c = k)
  2271. var f = !1,
  2272. e = null,
  2273. g = this.db.transaction(
  2274. [this.storeName],
  2275. this.consts.READ_WRITE
  2276. )
  2277. g.oncomplete = function () {
  2278. ;(f ? c : d)(e)
  2279. }
  2280. g.onabort = d
  2281. g.onerror = d
  2282. null !== this.keyPath
  2283. ? (this._addIdPropertyIfNeeded(b),
  2284. (a = g.objectStore(this.storeName).put(
  2285. (() => {
  2286. function isFilesystemHandle(obj) {
  2287. return (
  2288. obj &&
  2289. (obj instanceof
  2290. FileSystemFileHandle ||
  2291. obj instanceof
  2292. FileSystemDirectoryHandle)
  2293. )
  2294. }
  2295. function replaceProxies(obj) {
  2296. if (isFilesystemHandle(obj)) {
  2297. return obj
  2298. }
  2299. if (
  2300. typeof obj !== "object" ||
  2301. obj === null
  2302. ) {
  2303. return obj
  2304. }
  2305. if (Array.isArray(obj)) {
  2306. return obj.map((item) =>
  2307. replaceProxies(item)
  2308. )
  2309. }
  2310. const result = {}
  2311. for (const key in obj) {
  2312. if (obj.hasOwnProperty(key)) {
  2313. result[key] = replaceProxies(
  2314. obj[key]
  2315. )
  2316. }
  2317. }
  2318. return result
  2319. }
  2320. return replaceProxies(b)
  2321. })()
  2322. )))
  2323. : (a = g.objectStore(this.storeName).put(b, a))
  2324. a.onsuccess = function (a) {
  2325. f = !0
  2326. e = a.target.result
  2327. }
  2328. a.onerror = d
  2329. return g
  2330. },
  2331. get: function (a, b, c) {
  2332. c || (c = h)
  2333. b || (b = k)
  2334. var d = !1,
  2335. f = null,
  2336. e = this.db.transaction(
  2337. [this.storeName],
  2338. this.consts.READ_ONLY
  2339. )
  2340. e.oncomplete = function () {
  2341. ;(d ? b : c)(f)
  2342. }
  2343. e.onabort = c
  2344. e.onerror = c
  2345. a = e.objectStore(this.storeName).get(a)
  2346. a.onsuccess = function (a) {
  2347. d = !0
  2348. f = a.target.result
  2349. }
  2350. a.onerror = c
  2351. return e
  2352. },
  2353. remove: function (a, b, c) {
  2354. c || (c = h)
  2355. b || (b = k)
  2356. var d = !1,
  2357. f = null,
  2358. e = this.db.transaction(
  2359. [this.storeName],
  2360. this.consts.READ_WRITE
  2361. )
  2362. e.oncomplete = function () {
  2363. ;(d ? b : c)(f)
  2364. }
  2365. e.onabort = c
  2366. e.onerror = c
  2367. a = e.objectStore(this.storeName)["delete"](a)
  2368. a.onsuccess = function (a) {
  2369. d = !0
  2370. f = a.target.result
  2371. }
  2372. a.onerror = c
  2373. return e
  2374. },
  2375. batch: function (a, b, c) {
  2376. c || (c = h)
  2377. b || (b = k)
  2378. if (
  2379. "[object Array]" !=
  2380. Object.prototype.toString.call(a)
  2381. )
  2382. c(
  2383. Error(
  2384. "dataArray argument must be of type Array."
  2385. )
  2386. )
  2387. else if (0 === a.length) return b(!0)
  2388. var d = a.length,
  2389. f = !1,
  2390. e = !1,
  2391. g = this.db.transaction(
  2392. [this.storeName],
  2393. this.consts.READ_WRITE
  2394. )
  2395. g.oncomplete = function () {
  2396. ;(e ? b : c)(e)
  2397. }
  2398. g.onabort = c
  2399. g.onerror = c
  2400. var l = function () {
  2401. d--
  2402. 0 !== d || f || (e = f = !0)
  2403. }
  2404. a.forEach(function (a) {
  2405. var b = a.type,
  2406. d = a.key,
  2407. e = a.value
  2408. a = function (a) {
  2409. g.abort()
  2410. f || ((f = !0), c(a, b, d))
  2411. }
  2412. "remove" == b
  2413. ? ((e = g
  2414. .objectStore(this.storeName)
  2415. ["delete"](d)),
  2416. (e.onsuccess = l),
  2417. (e.onerror = a))
  2418. : "put" == b &&
  2419. (null !== this.keyPath
  2420. ? (this._addIdPropertyIfNeeded(e),
  2421. (e = g
  2422. .objectStore(this.storeName)
  2423. .put(e)))
  2424. : (e = g
  2425. .objectStore(this.storeName)
  2426. .put(e, d)),
  2427. (e.onsuccess = l),
  2428. (e.onerror = a))
  2429. }, this)
  2430. return g
  2431. },
  2432. putBatch: function (a, b, c) {
  2433. a = a.map(function (a) {
  2434. return { type: "put", value: a }
  2435. })
  2436. return this.batch(a, b, c)
  2437. },
  2438. upsertBatch: function (a, b, c, d) {
  2439. "function" == typeof b && ((d = c = b), (b = {}))
  2440. d || (d = h)
  2441. c || (c = k)
  2442. b || (b = {})
  2443. "[object Array]" !=
  2444. Object.prototype.toString.call(a) &&
  2445. d(
  2446. Error(
  2447. "dataArray argument must be of type Array."
  2448. )
  2449. )
  2450. var f = b.keyField || this.keyPath,
  2451. e = a.length,
  2452. g = !1,
  2453. l = !1,
  2454. n = 0,
  2455. m = this.db.transaction(
  2456. [this.storeName],
  2457. this.consts.READ_WRITE
  2458. )
  2459. m.oncomplete = function () {
  2460. l ? c(a) : d(!1)
  2461. }
  2462. m.onabort = d
  2463. m.onerror = d
  2464. var v = function (b) {
  2465. a[n++][f] = b.target.result
  2466. e--
  2467. 0 !== e || g || (l = g = !0)
  2468. }
  2469. a.forEach(function (a) {
  2470. var b = a.key
  2471. null !== this.keyPath
  2472. ? (this._addIdPropertyIfNeeded(a),
  2473. (a = m.objectStore(this.storeName).put(a)))
  2474. : (a = m
  2475. .objectStore(this.storeName)
  2476. .put(a, b))
  2477. a.onsuccess = v
  2478. a.onerror = function (a) {
  2479. m.abort()
  2480. g || ((g = !0), d(a))
  2481. }
  2482. }, this)
  2483. return m
  2484. },
  2485. removeBatch: function (a, b, c) {
  2486. a = a.map(function (a) {
  2487. return { type: "remove", key: a }
  2488. })
  2489. return this.batch(a, b, c)
  2490. },
  2491. getBatch: function (a, b, c, d) {
  2492. c || (c = h)
  2493. b || (b = k)
  2494. d || (d = "sparse")
  2495. if (
  2496. "[object Array]" !=
  2497. Object.prototype.toString.call(a)
  2498. )
  2499. c(
  2500. Error(
  2501. "keyArray argument must be of type Array."
  2502. )
  2503. )
  2504. else if (0 === a.length) return b([])
  2505. var f = [],
  2506. e = a.length,
  2507. g = !1,
  2508. l = null,
  2509. n = this.db.transaction(
  2510. [this.storeName],
  2511. this.consts.READ_ONLY
  2512. )
  2513. n.oncomplete = function () {
  2514. ;(g ? b : c)(l)
  2515. }
  2516. n.onabort = c
  2517. n.onerror = c
  2518. var m = function (a) {
  2519. a.target.result || "dense" == d
  2520. ? f.push(a.target.result)
  2521. : "sparse" == d && f.length++
  2522. e--
  2523. 0 === e && ((g = !0), (l = f))
  2524. }
  2525. a.forEach(function (a) {
  2526. a = n.objectStore(this.storeName).get(a)
  2527. a.onsuccess = m
  2528. a.onerror = function (a) {
  2529. l = a
  2530. c(a)
  2531. n.abort()
  2532. }
  2533. }, this)
  2534. return n
  2535. },
  2536. getAll: function (a, b) {
  2537. b || (b = h)
  2538. a || (a = k)
  2539. var c = this.db.transaction(
  2540. [this.storeName],
  2541. this.consts.READ_ONLY
  2542. ),
  2543. d = c.objectStore(this.storeName)
  2544. d.getAll
  2545. ? this._getAllNative(c, d, a, b)
  2546. : this._getAllCursor(c, d, a, b)
  2547. return c
  2548. },
  2549. _getAllNative: function (a, b, c, d) {
  2550. var f = !1,
  2551. e = null
  2552. a.oncomplete = function () {
  2553. ;(f ? c : d)(e)
  2554. }
  2555. a.onabort = d
  2556. a.onerror = d
  2557. a = b.getAll()
  2558. a.onsuccess = function (a) {
  2559. f = !0
  2560. e = a.target.result
  2561. }
  2562. a.onerror = d
  2563. },
  2564. _getAllCursor: function (a, b, c, d) {
  2565. var f = [],
  2566. e = !1,
  2567. g = null
  2568. a.oncomplete = function () {
  2569. ;(e ? c : d)(g)
  2570. }
  2571. a.onabort = d
  2572. a.onerror = d
  2573. a = b.openCursor()
  2574. a.onsuccess = function (a) {
  2575. ;(a = a.target.result)
  2576. ? (f.push(a.value), a["continue"]())
  2577. : ((e = !0), (g = f))
  2578. }
  2579. a.onError = d
  2580. },
  2581. clear: function (a, b) {
  2582. b || (b = h)
  2583. a || (a = k)
  2584. var c = !1,
  2585. d = null,
  2586. f = this.db.transaction(
  2587. [this.storeName],
  2588. this.consts.READ_WRITE
  2589. )
  2590. f.oncomplete = function () {
  2591. ;(c ? a : b)(d)
  2592. }
  2593. f.onabort = b
  2594. f.onerror = b
  2595. var e = f.objectStore(this.storeName).clear()
  2596. e.onsuccess = function (a) {
  2597. c = !0
  2598. d = a.target.result
  2599. }
  2600. e.onerror = b
  2601. return f
  2602. },
  2603. _addIdPropertyIfNeeded: function (a) {
  2604. "undefined" == typeof a[this.keyPath] &&
  2605. (a[this.keyPath] =
  2606. this._insertIdCount++ + Date.now())
  2607. },
  2608. getIndexList: function () {
  2609. return this.store.indexNames
  2610. },
  2611. hasIndex: function (a) {
  2612. return this.store.indexNames.contains(a)
  2613. },
  2614. normalizeIndexData: function (a) {
  2615. a.keyPath = a.keyPath || a.name
  2616. a.unique = !!a.unique
  2617. a.multiEntry = !!a.multiEntry
  2618. },
  2619. indexComplies: function (a, b) {
  2620. return ["keyPath", "unique", "multiEntry"].every(
  2621. function (c) {
  2622. if (
  2623. "multiEntry" == c &&
  2624. void 0 === a[c] &&
  2625. !1 === b[c]
  2626. )
  2627. return !0
  2628. if (
  2629. "keyPath" == c &&
  2630. "[object Array]" ==
  2631. Object.prototype.toString.call(b[c])
  2632. ) {
  2633. c = b.keyPath
  2634. var d = a.keyPath
  2635. if ("string" == typeof d)
  2636. return c.toString() == d
  2637. if (
  2638. ("function" != typeof d.contains &&
  2639. "function" != typeof d.indexOf) ||
  2640. d.length !== c.length
  2641. )
  2642. return !1
  2643. for (var f = 0, e = c.length; f < e; f++)
  2644. if (
  2645. !(
  2646. (d.contains && d.contains(c[f])) ||
  2647. d.indexOf(-1 !== c[f])
  2648. )
  2649. )
  2650. return !1
  2651. return !0
  2652. }
  2653. return b[c] == a[c]
  2654. }
  2655. )
  2656. },
  2657. iterate: function (a, b) {
  2658. b = p(
  2659. {
  2660. index: null,
  2661. order: "ASC",
  2662. autoContinue: !0,
  2663. filterDuplicates: !1,
  2664. keyRange: null,
  2665. writeAccess: !1,
  2666. onEnd: null,
  2667. onError: h,
  2668. limit: Infinity,
  2669. offset: 0,
  2670. allowItemRejection: !1,
  2671. },
  2672. b || {}
  2673. )
  2674. var c =
  2675. "desc" == b.order.toLowerCase()
  2676. ? "PREV"
  2677. : "NEXT"
  2678. b.filterDuplicates && (c += "_NO_DUPLICATE")
  2679. var d = !1,
  2680. f = this.db.transaction(
  2681. [this.storeName],
  2682. this.consts[
  2683. b.writeAccess ? "READ_WRITE" : "READ_ONLY"
  2684. ]
  2685. ),
  2686. e = f.objectStore(this.storeName)
  2687. b.index && (e = e.index(b.index))
  2688. var g = 0
  2689. f.oncomplete = function () {
  2690. if (d)
  2691. if (b.onEnd) b.onEnd()
  2692. else a(null)
  2693. else b.onError(null)
  2694. }
  2695. f.onabort = b.onError
  2696. f.onerror = b.onError
  2697. c = e.openCursor(b.keyRange, this.consts[c])
  2698. c.onerror = b.onError
  2699. c.onsuccess = function (c) {
  2700. if ((c = c.target.result))
  2701. if (b.offset)
  2702. c.advance(b.offset), (b.offset = 0)
  2703. else {
  2704. var e = a(c.value, c, f)
  2705. ;(b.allowItemRejection && !1 === e) || g++
  2706. if (b.autoContinue)
  2707. if (g + b.offset < b.limit)
  2708. c["continue"]()
  2709. else d = !0
  2710. }
  2711. else d = !0
  2712. }
  2713. return f
  2714. },
  2715. query: function (a, b) {
  2716. var c = [],
  2717. d = 0
  2718. b = b || {}
  2719. b.autoContinue = !0
  2720. b.writeAccess = !1
  2721. b.allowItemRejection = !!b.filter
  2722. b.onEnd = function () {
  2723. a(c, d)
  2724. }
  2725. return this.iterate(function (a) {
  2726. d++
  2727. var e = b.filter ? b.filter(a) : !0
  2728. !1 !== e && c.push(a)
  2729. return e
  2730. }, b)
  2731. },
  2732. count: function (a, b) {
  2733. b = p({ index: null, keyRange: null }, b || {})
  2734. var c = b.onError || h,
  2735. d = !1,
  2736. f = null,
  2737. e = this.db.transaction(
  2738. [this.storeName],
  2739. this.consts.READ_ONLY
  2740. )
  2741. e.oncomplete = function () {
  2742. ;(d ? a : c)(f)
  2743. }
  2744. e.onabort = c
  2745. e.onerror = c
  2746. var g = e.objectStore(this.storeName)
  2747. b.index && (g = g.index(b.index))
  2748. g = g.count(b.keyRange)
  2749. g.onsuccess = function (a) {
  2750. d = !0
  2751. f = a.target.result
  2752. }
  2753. g.onError = c
  2754. return e
  2755. },
  2756. makeKeyRange: function (a) {
  2757. var b = "undefined" != typeof a.lower,
  2758. c = "undefined" != typeof a.upper,
  2759. d = "undefined" != typeof a.only
  2760. switch (!0) {
  2761. case d:
  2762. a = this.keyRange.only(a.only)
  2763. break
  2764. case b && c:
  2765. a = this.keyRange.bound(
  2766. a.lower,
  2767. a.upper,
  2768. a.excludeLower,
  2769. a.excludeUpper
  2770. )
  2771. break
  2772. case b:
  2773. a = this.keyRange.lowerBound(
  2774. a.lower,
  2775. a.excludeLower
  2776. )
  2777. break
  2778. case c:
  2779. a = this.keyRange.upperBound(
  2780. a.upper,
  2781. a.excludeUpper
  2782. )
  2783. break
  2784. default:
  2785. throw Error(
  2786. 'Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.'
  2787. )
  2788. }
  2789. return a
  2790. },
  2791. },
  2792. u = {}
  2793. q.prototype = t
  2794. q.version = t.version
  2795. return q
  2796. },
  2797. this
  2798. )
  2799. }
  2800. x = new IDBStore(obj)
  2801. })
  2802. },
  2803. function ({
  2804. ifunset,
  2805. gettype,
  2806. end,
  2807. maketype,
  2808. makeenum,
  2809. trymaketype,
  2810. trymakeenum,
  2811. trygettype,
  2812. args: [obj],
  2813. }) {
  2814. obj = maketype(obj, ["object"])
  2815. return end()
  2816. }
  2817. )
  2818.  
  2819. a.readfileslow = newfunc(
  2820. function readfileslow(
  2821. file,
  2822. type = "Text",
  2823. cb1 = (e) => e,
  2824. cb2 = (e) => e
  2825. ) {
  2826. var fileSize = file.size
  2827. var chunkSize = 64 * 1024 * 50
  2828. var offset = 0
  2829. var chunkReaderBlock = null
  2830. var arr = []
  2831. var lastidx
  2832. var readEventHandler = function (evt, idx) {
  2833. if (evt.target.error == null) {
  2834. arr.push([idx, evt.target.result])
  2835. cb1(a.rerange(arr.length, 0, lastidx, 0, 100))
  2836. if (arr.length === lastidx)
  2837. cb2(arr.sort((e) => e[0]).map((e) => e[1]))
  2838. } else {
  2839. return error("Read error: " + evt.target.error)
  2840. }
  2841. }
  2842. chunkReaderBlock = function (_offset, length, _file, idx) {
  2843. var r = new FileReader()
  2844. var blob = _file.slice(_offset, length + _offset)
  2845. const zzz = idx + 1
  2846. r.onload = function (e) {
  2847. readEventHandler(e, zzz - 1)
  2848. }
  2849. r["readAs" + type](blob)
  2850. }
  2851. let idx = 0
  2852. while (offset < fileSize) {
  2853. idx++
  2854. chunkReaderBlock(offset, chunkSize, file, idx)
  2855. offset += chunkSize
  2856. }
  2857. lastidx = idx
  2858. },
  2859. function ({ end, args: [file, type, cb1, cb2] }) {
  2860. file = maketype(file, ["object"]) // Ensure file is an object
  2861. type = maketype(type, ["string"]) // Ensure type is a string
  2862. cb1 = maketype(cb1, ["function"]) // Ensure cb1 is a function
  2863. cb2 = maketype(cb2, ["function"]) // Ensure cb2 is a function
  2864. return end()
  2865. }
  2866. )
  2867.  
  2868. a.cbtoasync = newfunc(
  2869. function cbtoasync(func, ...args) {
  2870. return new Promise(function (resolve) {
  2871. func(...args, resolve)
  2872. })
  2873. },
  2874. function ({ end, args: [func, ...args] }) {
  2875. func = maketype(func, ["function"]) // Ensure func is a function
  2876. return end()
  2877. }
  2878. )
  2879.  
  2880. a.asynctocb = newfunc(
  2881. function asynctocb(func, ...args) {
  2882. var cb = args.pop()
  2883. return func(...args).then(cb)
  2884. },
  2885. function ({ end, args: [func, ...args] }) {
  2886. func = maketype(func, ["function"]) // Ensure func is a function
  2887. return end()
  2888. }
  2889. )
  2890.  
  2891. a.randstr = newfunc(
  2892. function randstr({
  2893. lower = true,
  2894. upper = false,
  2895. number = false,
  2896. symbol = false,
  2897. length = 20,
  2898. }) {
  2899. var rand = ""
  2900. a.repeat(() => {
  2901. rand += a.randfrom(
  2902. `${lower ? "asdfghjklzxcvbnmqwertyuiop" : ""}${
  2903. upper ? "ASDFGHJKLQWERTYUIOPZXCVBNM" : ""
  2904. }${number ? "0123456789" : ""}${
  2905. symbol ? ",./;'[]-=\\`~!@#$%^&*()_+|{}:\"<>?" : ""
  2906. }`.split("")
  2907. )
  2908. }, length)
  2909. return rand
  2910. },
  2911. function ({ end, maketype, args: [options], ifunset }) {
  2912. ifunset([
  2913. {
  2914. lower: true,
  2915. upper: false,
  2916. number: false,
  2917. symbol: false,
  2918. length: 20,
  2919. },
  2920. ])
  2921. options = maketype(options, ["object", "undefined"]) // Ensure options is an object
  2922. return end()
  2923. }
  2924. )
  2925.  
  2926. a.toplaces = newfunc(
  2927. function toplaces(num, pre, post = 0, func = Math.round) {
  2928. num = String(num).split(".")
  2929. if (num.length == 1) num.push("")
  2930. if (pre !== undefined) {
  2931. num[0] = num[0].substring(num[0].length - pre, num[0].length)
  2932. while (num[0].length < pre) num[0] = "0" + num[0]
  2933. }
  2934. var temp = num[1].substring(post, post + 1) ?? 0
  2935. num[1] = num[1].substring(0, post)
  2936. while (num[1].length < post) num[1] += "0"
  2937. if (post > 0) {
  2938. temp = func(num[1].at(-1) + "." + temp)
  2939. num[1] = num[1].split("")
  2940. num[1].pop()
  2941. num[1].push(temp)
  2942. num[1] = num[1].join("")
  2943. num = num.join(".")
  2944. } else num = num[0]
  2945. return num
  2946. },
  2947. function ({ end, maketype, args: [num, pre, post, func] }) {
  2948. num = maketype(num, ["number"]) // Ensure num is a number
  2949. pre = maketype(pre, ["number"]) // Ensure pre is a number
  2950. post = maketype(post, ["number"]) // Ensure post is a number
  2951. func = maketype(func, ["function", "undefined"]) // Ensure func is a function or undefined
  2952. return end()
  2953. }
  2954. )
  2955.  
  2956. a.fetch = newfunc(
  2957. async function fetch(url, type = "text", ...args) {
  2958. return await (await fetch(url, ...args))[type]()
  2959. },
  2960. function ({ end, maketype, args: [url, type] }) {
  2961. url = maketype(url, ["string"]) // Ensure url is a string
  2962. type = maketype(type, ["string"]) // Ensure type is a string
  2963. type = makeenum(type, ["text", "json"])
  2964. return end()
  2965. }
  2966. )
  2967.  
  2968. a.replaceall = newfunc(
  2969. function replaceall(text, regex, replacewith) {
  2970. return text.replaceAll(
  2971. a.toregex(String(a.toregex(regex)) + "g"),
  2972. replacewith
  2973. )
  2974. },
  2975. function ({
  2976. ifunset,
  2977. gettype,
  2978. end,
  2979. maketype,
  2980. makeenum,
  2981. trymaketype,
  2982. trymakeenum,
  2983. trygettype,
  2984. args: [text, regex, replacewith],
  2985. }) {
  2986. text = maketype(text, ["string"])
  2987. regex = maketype(regex, ["regex"])
  2988. replacewith = maketype(replacewith, ["string"])
  2989. return end()
  2990. }
  2991. )
  2992.  
  2993. a.setrange = newfunc(
  2994. function setrange(num, min, max) {
  2995. return num < min ? min : num > max ? max : num
  2996. },
  2997. function ({
  2998. ifunset,
  2999. gettype,
  3000. end,
  3001. maketype,
  3002. makeenum,
  3003. trymaketype,
  3004. trymakeenum,
  3005. trygettype,
  3006. args: [num, min, max],
  3007. }) {
  3008. num = maketype(num, ["number"])
  3009. min = maketype(min, ["number"])
  3010. max = maketype(max, ["number"])
  3011. return end()
  3012. }
  3013. )
  3014.  
  3015. a.ondrop = newfunc(
  3016. function ondrop(obj) {
  3017. if (!obj.types) obj.types = "all"
  3018. obj.types = a.toarray(obj.types)
  3019. if (!obj.func) throw new Error('object is missing "func"')
  3020. var oldelem = obj.elem
  3021. if (obj.elem) obj.elem = a.toelem(obj.elem, true)
  3022. if (obj.elem && !a.gettype(obj.elem, "element"))
  3023. throw new Error(
  3024. `elem is not an elem, ${oldelem} -> ${obj.elem}`
  3025. )
  3026. drops.push(obj)
  3027. return obj
  3028. },
  3029. function ({
  3030. ifunset,
  3031. gettype,
  3032. end,
  3033. maketype,
  3034. makeenum,
  3035. trymaketype,
  3036. trymakeenum,
  3037. trygettype,
  3038. args: [obj],
  3039. }) {
  3040. obj = maketype(obj, ["object"])
  3041. return end()
  3042. }
  3043. )
  3044. loadlib("libloader").savelib("newallfuncs", a)
  3045. })()