lib:allfuncs

none

当前为 2025-04-20 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址