Basic Functions (For userscripts)

Useful functions for myself

Tätä skriptiä ei tulisi asentaa suoraan. Se on kirjasto muita skriptejä varten sisällytettäväksi metadirektiivillä // @require https://update.greatest.deepsurf.us/scripts/456034/1558509/Basic%20Functions%20%28For%20userscripts%29.js.

  1. // ==UserScript==
  2. // @name Basic Functions (For userscripts)
  3. // @name:zh-CN 常用函数(用户脚本)
  4. // @name:en Basic Functions (For userscripts)
  5. // @namespace PY-DNG Userscripts
  6. // @version 1.8.1
  7. // @description Useful functions for myself
  8. // @description:zh-CN 自用函数
  9. // @description:en Useful functions for myself
  10. // @author PY-DNG
  11. // @license GPL-3.0-or-later
  12. // ==/UserScript==
  13.  
  14. /* eslint-disable no-multi-spaces */
  15. /* eslint-disable no-return-assign */
  16.  
  17. // Note: version 0.8.2.1 is modified just the license and it's not uploaded to GF yet 23-11-26 15:03
  18. // Note: version 0.8.3.1 is added just the description of parseArgs and has not uploaded to GF yet 24-02-03 18:55
  19.  
  20. let [
  21. // Console & Debug
  22. LogLevel, DoLog, Err, Assert,
  23.  
  24. // DOM
  25. $, $All, $CrE, $AEL, $$CrE, addStyle, detectDom, destroyEvent,
  26.  
  27. // Data
  28. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  29.  
  30. // Environment & Browser
  31. getUrlArgv, dl_browser, dl_GM,
  32.  
  33. // Logic & Task
  34. AsyncManager, queueTask, FunctionLoader, loadFuncs, require, isLoaded
  35. ] = (function() {
  36. const [LogLevel, DoLog] = (function() {
  37. /**
  38. * level defination for DoLog function, bigger ones has higher possibility to be printed in console
  39. * @typedef {Object} LogLevel
  40. * @property {0} None - 0
  41. * @property {1} Error - 1
  42. * @property {2} Success - 2
  43. * @property {3} Warning - 3
  44. * @property {4} Info - 4
  45. */
  46. /** @type {LogLevel} */
  47. const LogLevel = {
  48. None: 0,
  49. Error: 1,
  50. Success: 2,
  51. Warning: 3,
  52. Info: 4,
  53. };
  54.  
  55. return [LogLevel, DoLog];
  56.  
  57. /**
  58. * @overload
  59. * @param {String} content - log content
  60. */
  61. /**
  62. * @overload
  63. * @param {Number} level - level specified in LogLevel object
  64. * @param {String} content - log content
  65. */
  66. /**
  67. * Logger with level and logger function specification
  68. * @overload
  69. * @param {Number} level - level specified in LogLevel object
  70. * @param {String} content - log content
  71. * @param {String} logger - which log function to use (in window.console[logger])
  72. */
  73. function DoLog() {
  74. // Get window
  75. const win = (typeof(unsafeWindow) === 'object' && unsafeWindow !== null) ? unsafeWindow : window;
  76.  
  77. const LogLevelMap = {};
  78. LogLevelMap[LogLevel.None] = {
  79. prefix: '',
  80. color: 'color:#ffffff'
  81. }
  82. LogLevelMap[LogLevel.Error] = {
  83. prefix: '[Error]',
  84. color: 'color:#ff0000'
  85. }
  86. LogLevelMap[LogLevel.Success] = {
  87. prefix: '[Success]',
  88. color: 'color:#00aa00'
  89. }
  90. LogLevelMap[LogLevel.Warning] = {
  91. prefix: '[Warning]',
  92. color: 'color:#ffa500'
  93. }
  94. LogLevelMap[LogLevel.Info] = {
  95. prefix: '[Info]',
  96. color: 'color:#888888'
  97. }
  98. LogLevelMap[LogLevel.Elements] = {
  99. prefix: '[Elements]',
  100. color: 'color:#000000'
  101. }
  102.  
  103. // Current log level
  104. DoLog.logLevel = (win.isPY_DNG && win.userscriptDebugging) ? LogLevel.Info : LogLevel.Warning; // Info Warning Success Error
  105.  
  106. // Log counter
  107. DoLog.logCount === undefined && (DoLog.logCount = 0);
  108.  
  109. // Get args
  110. let [level, logContent, logger] = parseArgs([...arguments], [
  111. [2],
  112. [1,2],
  113. [1,2,3]
  114. ], [LogLevel.Info, 'DoLog initialized.', 'log']);
  115.  
  116. let msg = '%c' + LogLevelMap[level].prefix + (typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + (LogLevelMap[level].prefix ? ' ' : '');
  117. let subst = LogLevelMap[level].color;
  118.  
  119. switch (typeof(logContent)) {
  120. case 'string':
  121. msg += '%s';
  122. break;
  123. case 'number':
  124. msg += '%d';
  125. break;
  126. default:
  127. msg += '%o';
  128. break;
  129. }
  130.  
  131. // Log when log level permits
  132. if (level <= DoLog.logLevel) {
  133. // Log to console when log level permits
  134. if (level <= DoLog.logLevel) {
  135. if (++DoLog.logCount > 512) {
  136. console.clear();
  137. DoLog.logCount = 0;
  138. }
  139. console[logger](msg, subst, logContent);
  140. }
  141. }
  142. }
  143. }) ();
  144.  
  145. /**
  146. * Throw an error
  147. * @param {String} msg - the error message
  148. * @param {Error} [ErrorConstructor=Error] - which error constructor to use, defaulting to Error()
  149. */
  150. function Err(msg, ErrorConstructor=Error) {
  151. throw new ErrorConstructor((typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + msg);
  152. }
  153.  
  154. /**
  155. * Assert given condition is true-like, otherwise throws given error
  156. * @param {*} condition
  157. * @param {string} errmsg
  158. * @param {Error} [ErrorConstructor=Error]
  159. */
  160. function Assert(condition, errmsg, ErrorConstructor=Error) {
  161. condition || Err(errmsg, ErrorConstructor);
  162. }
  163.  
  164. /**
  165. * Convenient function to querySelector
  166. * @overload
  167. * @param {Element|Document|DocumentFragment} [root] - which target to call querySelector on
  168. * @param {string} selector - querySelector selector
  169. * @returns {Element|null}
  170. */
  171. function $() {
  172. switch(arguments.length) {
  173. case 2:
  174. return arguments[0].querySelector(arguments[1]);
  175. default:
  176. return document.querySelector(arguments[0]);
  177. }
  178. }
  179. /**
  180. * Convenient function to querySelectorAll
  181. * @overload
  182. * @param {Element|Document|DocumentFragment} [root] - which target to call querySelectorAll on
  183. * @param {string} selector - querySelectorAll selector
  184. * @returns {NodeList}
  185. */
  186. function $All() {
  187. switch(arguments.length) {
  188. case 2:
  189. return arguments[0].querySelectorAll(arguments[1]);
  190. break;
  191. default:
  192. return document.querySelectorAll(arguments[0]);
  193. }
  194. }
  195. /**
  196. * Convenient function to querySelectorAll
  197. * @overload
  198. * @param {Document} [root] - which document to call createElement on
  199. * @param {string} tagName
  200. * @returns {HTMLElement}
  201. */
  202. function $CrE() {
  203. switch(arguments.length) {
  204. case 2:
  205. return arguments[0].createElement(arguments[1]);
  206. break;
  207. default:
  208. return document.createElement(arguments[0]);
  209. }
  210. }
  211. /**
  212. * Convenient function to addEventListener
  213. * @overload
  214. * @param {EventTarget} target - which target to call addEventListener on
  215. * @param {string} type
  216. * @param {EventListenerOrEventListenerObject | null} callback
  217. * @param {AddEventListenerOptions | boolean} [options]
  218. */
  219. function $AEL(...args) {
  220. /** @type {EventTarget} */
  221. const target = args.shift();
  222. return target.addEventListener.apply(target, args);
  223. }
  224. /**
  225. * @typedef {[type: string, callback: EventListenerOrEventListenerObject | null, options: AddEventListenerOptions | boolean]} $AEL_Arguments
  226. */
  227. /**
  228. * @typedef {Object} $$CrE_Options
  229. * @property {string} tagName
  230. * @property {object} [props] - properties set by `element[prop] = value;`
  231. * @property {object} [attrs] - attributes set by `element.setAttribute(attr, value);`
  232. * @property {string | string[]} [classes] - class names to be set
  233. * @property {object} [styles] - styles set by `element[style_name] = style_value;`
  234. * @property {$AEL_Arguments[]} [listeners] - event listeners added by `$AEL(element, ...listener);`
  235. */
  236. /**
  237. * @overload
  238. * @param {$$CrE_Options} options
  239. * @returns {HTMLElement}
  240. */
  241. /**
  242. * Create configorated element
  243. * @overload
  244. * @param {string} tagName
  245. * @param {object} [props] - properties set by `element[prop] = value;`
  246. * @param {object} [attrs] - attributes set by `element.setAttribute(attr, value);`
  247. * @param {string | string[]} [classes] - class names to be set
  248. * @param {object} [styles] - styles set by `element[style_name] = style_value;`
  249. * @param {$AEL_Arguments[]} [listeners] - event listeners added by `$AEL(element, ...listener);`
  250. * @returns {HTMLElement}
  251. */
  252. function $$CrE() {
  253. const [tagName, props, attrs, classes, styles, listeners] = parseArgs([...arguments], [
  254. function(args, defaultValues) {
  255. const arg = args[0];
  256. return {
  257. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  258. 'object': () => ['tagName', 'props', 'attrs', 'classes', 'styles', 'listeners'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  259. }[typeof arg]();
  260. },
  261. [1,2],
  262. [1,2,3],
  263. [1,2,3,4],
  264. [1,2,3,4,5]
  265. ], ['div', {}, {}, [], {}, []]);
  266. const elm = $CrE(tagName);
  267. for (const [name, val] of Object.entries(props)) {
  268. elm[name] = val;
  269. }
  270. for (const [name, val] of Object.entries(attrs)) {
  271. elm.setAttribute(name, val);
  272. }
  273. for (const cls of Array.isArray(classes) ? classes : [classes]) {
  274. elm.classList.add(cls);
  275. }
  276. for (const [name, val] of Object.entries(styles)) {
  277. elm.style[name] = val;
  278. }
  279. for (const listener of listeners) {
  280. $AEL(elm, ...listener);
  281. }
  282. return elm;
  283. }
  284.  
  285. /**
  286. * @overload
  287. * @param {string} css - css content
  288. * @returns {HTMLStyleElement}
  289. */
  290. /**
  291. * @overload
  292. * @param {string} css - css content
  293. * @param {string} id - `id` attribute for <style> element
  294. * @returns {HTMLStyleElement}
  295. */
  296. /**
  297. * Append a style text to document(<head>) with a <style> element \
  298. * removes existing <style> elements with same id if id provided, so style updates can be done by using one same id
  299. *
  300. * Uses `GM_addElement` if `GM_addElement` exists and param `id` not specified. (`GM_addElement` uses id attribute, so specifing id manually when using `GM_addElement` takes no effect) \
  301. * In another case `GM_addStyle` instead of `GM_addElement` exists, and both `id` and `parentElement` not specified, `GM_addStyle` will be used. \
  302. * `document.createElement('style')` will be used otherwise.
  303. * @overload
  304. * @param {HTMLElement} parentElement - parent element to place <style> element
  305. * @param {string} css - css content
  306. * @param {string} id - `id` attribute for <style> element
  307. * @returns {HTMLStyleElement}
  308. */
  309. function addStyle() {
  310. // Get arguments
  311. const [parentElement, css, id] = parseArgs([...arguments], [
  312. [2],
  313. [2,3],
  314. [1,2,3]
  315. ], [null, '', null]);
  316.  
  317. if (typeof GM_addElement === 'function' && id === null) {
  318. return GM_addElement(parentElement, 'style', { textContent: css });
  319. } else if (typeof GM_addStyle === 'function' && parentElement === null && id === null) {
  320. return GM_addStyle(css);
  321. } else {
  322. // Make <style>
  323. const style = $CrE('style');
  324. style.innerHTML = css;
  325. id !== null && (style.id = id);
  326. id !== null && Array.from($All(`style#${id}`)).forEach(elm => elm.remove());
  327.  
  328. // Append to parentElement
  329. (parentElement ?? document.head).appendChild(style);
  330. return style;
  331. }
  332. }
  333.  
  334. /**
  335. * @typedef {Object} detectDom_options
  336. * @property {Node} root - root target to observe on
  337. * @property {string | string[]} [selector] - selector(s) to observe for, be aware that in options object it is named selector, but is named selectors in param
  338. * @property {boolean} [attributes] - whether to observe existing elements' attribute changes
  339. * @property {function} [callback] - if provided, use callback instead of Promise when selector element found
  340. */
  341. /**
  342. * @overload
  343. * @param {detectDom_options} options
  344. * @returns {MutationObserver}
  345. */
  346. /**
  347. * Get callback / resolve promise when specific dom/element appearce in document \
  348. * uses MutationObserver for implementation \
  349. * This behavior is different from versions that equals to or older than 0.8.4.2, so be careful when using it.
  350. * @overload
  351. * @param {Node} root - root target to observe on
  352. * @param {string | string[]} [selectors] - selector(s) to observe for
  353. * @param {boolean} [attributes] - whether to observe existing elements' attribute changes
  354. * @param {function} [callback] - if provided, use callback instead of Promise when selector element found
  355. * @returns {MutationObserver}
  356. */
  357. function detectDom() {
  358. let [selectors, root, attributes, callback] = parseArgs([...arguments], [
  359. function(args, defaultValues) {
  360. const arg = args[0];
  361. return {
  362. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  363. 'object': () => ['selector', 'root', 'attributes', 'callback'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  364. }[typeof arg]();
  365. },
  366. [2,1],
  367. [2,1,3],
  368. [2,1,3,4],
  369. ], [[''], document, false, null]);
  370. !Array.isArray(selectors) && (selectors = [selectors]);
  371.  
  372. if (select(root, selectors)) {
  373. for (const elm of selectAll(root, selectors)) {
  374. if (callback) {
  375. setTimeout(callback.bind(null, elm));
  376. } else {
  377. return Promise.resolve(elm);
  378. }
  379. }
  380. }
  381.  
  382. const observer = new MutationObserver(mCallback);
  383. observer.observe(root, {
  384. childList: true,
  385. subtree: true,
  386. attributes,
  387. });
  388.  
  389. let isPromise = !callback;
  390. return callback ? observer : new Promise((resolve, reject) => callback = resolve);
  391.  
  392. function mCallback(mutationList, observer) {
  393. const addedNodes = mutationList.reduce((an, mutation) => {
  394. switch (mutation.type) {
  395. case 'childList':
  396. an.push(...mutation.addedNodes);
  397. break;
  398. case 'attributes':
  399. an.push(mutation.target);
  400. break;
  401. }
  402. return an;
  403. }, []);
  404. const addedSelectorNodes = addedNodes.reduce((nodes, anode) => {
  405. if (anode.matches && match(anode, selectors)) {
  406. nodes.add(anode);
  407. }
  408. const childMatches = anode.querySelectorAll ? selectAll(anode, selectors) : [];
  409. for (const cm of childMatches) {
  410. nodes.add(cm);
  411. }
  412. return nodes;
  413. }, new Set());
  414. for (const node of addedSelectorNodes) {
  415. callback(node);
  416. isPromise && observer.disconnect();
  417. }
  418. }
  419.  
  420. function selectAll(elm, selectors) {
  421. !Array.isArray(selectors) && (selectors = [selectors]);
  422. return selectors.map(selector => [...$All(elm, selector)]).reduce((all, arr) => {
  423. all.push(...arr);
  424. return all;
  425. }, []);
  426. }
  427.  
  428. function select(elm, selectors) {
  429. const all = selectAll(elm, selectors);
  430. return all.length ? all[0] : null;
  431. }
  432.  
  433. function match(elm, selectors) {
  434. return !!elm.matches && selectors.some(selector => elm.matches(selector));
  435. }
  436. }
  437.  
  438. /**
  439. * Just stopPropagation and preventDefault
  440. * @param {Event} e
  441. */
  442. function destroyEvent(e) {
  443. if (!e) {return false;};
  444. if (!e instanceof Event) {return false;};
  445. e.stopPropagation();
  446. e.preventDefault();
  447. }
  448.  
  449. /**
  450. * copy property value from obj1 to obj2 if exists
  451. * @param {object} obj1
  452. * @param {object} obj2
  453. * @param {string|Symbol} prop
  454. */
  455. function copyProp(obj1, obj2, prop) {obj1.hasOwnProperty(prop) && (obj2[prop] = obj1[prop]);}
  456. /**
  457. * copy property values from obj1 to obj2 if exists
  458. * @param {object} obj1
  459. * @param {object} obj2
  460. * @param {string|Symbol} [props] - properties to copy, copy all enumerable properties if not specified
  461. */
  462. function copyProps(obj1, obj2, props) {(props ?? Object.keys(obj1)).forEach((prop) => (copyProp(obj1, obj2, prop)));}
  463.  
  464. /**
  465. * Argument parser with sorting and defaultValue support \
  466. * See use cases in other functions
  467. * @param {Array} args - original arguments' value to be parsed
  468. * @param {(number[]|function)[]} rules - rules to sort arguments or custom function to parse arguments
  469. * @param {Array} defaultValues - default values for arguments not provided a value
  470. * @returns {Array}
  471. */
  472. function parseArgs(args, rules, defaultValues=[]) {
  473. // args and rules should be array, but not just iterable (string is also iterable)
  474. if (!Array.isArray(args) || !Array.isArray(rules)) {
  475. throw new TypeError('parseArgs: args and rules should be array')
  476. }
  477.  
  478. // fill rules[0]
  479. (!Array.isArray(rules[0]) || rules[0].length === 1) && rules.splice(0, 0, []);
  480.  
  481. // max arguments length
  482. const count = rules.length - 1;
  483.  
  484. // args.length must <= count
  485. if (args.length > count) {
  486. throw new TypeError(`parseArgs: args has more elements(${args.length}) longer than ruless'(${count})`);
  487. }
  488.  
  489. // rules[i].length should be === i if rules[i] is an array, otherwise it should be a function
  490. for (let i = 1; i <= count; i++) {
  491. const rule = rules[i];
  492. if (Array.isArray(rule)) {
  493. if (rule.length !== i) {
  494. throw new TypeError(`parseArgs: rules[${i}](${rule}) should have ${i} numbers, but given ${rules[i].length}`);
  495. }
  496. if (!rule.every((num) => (typeof num === 'number' && num <= count))) {
  497. throw new TypeError(`parseArgs: rules[${i}](${rule}) should contain numbers smaller than count(${count}) only`);
  498. }
  499. } else if (typeof rule !== 'function') {
  500. throw new TypeError(`parseArgs: rules[${i}](${rule}) should be an array or a function.`)
  501. }
  502. }
  503.  
  504. // Parse
  505. const rule = rules[args.length];
  506. let parsed;
  507. if (Array.isArray(rule)) {
  508. parsed = [...defaultValues];
  509. for (let i = 0; i < rule.length; i++) {
  510. parsed[rule[i]-1] = args[i];
  511. }
  512. } else {
  513. parsed = rule(args, defaultValues);
  514. }
  515. return parsed;
  516. }
  517.  
  518. /**
  519. * escape str into javascript written format
  520. * @param {string} str
  521. * @param {string} [quote]
  522. * @returns
  523. */
  524. function escJsStr(str, quote='"') {
  525. str = str.replaceAll('\\', '\\\\').replaceAll(quote, '\\' + quote).replaceAll('\t', '\\t');
  526. str = quote === '`' ? str.replaceAll(/(\$\{[^\}]*\})/g, '\\$1') : str.replaceAll('\r', '\\r').replaceAll('\n', '\\n');
  527. return quote + str + quote;
  528. }
  529. /**
  530. * Replace given text with no mismatching of replacing replaced text
  531. *
  532. * e.g. replaceText('aaaabbbbccccdddd', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'}) === 'bbbbccccddddeeee' \
  533. * replaceText('abcdAABBAA', {'BB': 'AA', 'AAAAAA': 'This is a trap!'}) === 'abcdAAAAAA' \
  534. * replaceText('abcd{AAAA}BB}', {'{AAAA}': '{BB', '{BBBB}': 'This is a trap!'}) === 'abcd{BBBB}' \
  535. * replaceText('abcd', {}) === 'abcd'
  536. *
  537. * **Note**: \
  538. * replaceText will replace in sort of replacer's iterating sort \
  539. * e.g. currently replaceText('abcdAABBAA', {'BBAA': 'TEXT', 'AABB': 'TEXT'}) === 'abcdAATEXT' \
  540. * but remember: (As MDN Web Doc said,) Although the keys of an ordinary Object are ordered now, this was \
  541. * not always the case, and the order is complex. As a result, it's best not to rely on property order. \
  542. * So, don't expect replaceText will treat replacer key-values in any specific sort. Use replaceText to \
  543. * replace irrelevance replacer keys only.
  544. * @param {string} text
  545. * @param {object} replacer
  546. * @returns {string}
  547. */
  548. function replaceText(text, replacer) {
  549. if (Object.entries(replacer).length === 0) {return text;}
  550. const [models, targets] = Object.entries(replacer);
  551. const len = models.length;
  552. let text_arr = [{text: text, replacable: true}];
  553. for (const [model, target] of Object.entries(replacer)) {
  554. text_arr = replace(text_arr, model, target);
  555. }
  556. return text_arr.map((text_obj) => (text_obj.text)).join('');
  557.  
  558. function replace(text_arr, model, target) {
  559. const result_arr = [];
  560. for (const text_obj of text_arr) {
  561. if (text_obj.replacable) {
  562. const splited = text_obj.text.split(model);
  563. for (const part of splited) {
  564. result_arr.push({text: part, replacable: true});
  565. result_arr.push({text: target, replacable: false});
  566. }
  567. result_arr.pop();
  568. } else {
  569. result_arr.push(text_obj);
  570. }
  571. }
  572. return result_arr;
  573. }
  574. }
  575.  
  576. /**
  577. * @typedef {Object} getUrlArgv_options
  578. * @property {string} name
  579. * @property {string} [url]
  580. * @property {string} [defaultValue]
  581. * @property {function} [dealFunc] - function that inputs original getUrlArgv result and outputs final return value
  582. */
  583. /**
  584. * @overload
  585. * @param {Object} getUrlArgv_options
  586. * @returns
  587. */
  588. /**
  589. * Get a url argument from location.href
  590. * @param {string} name
  591. * @param {string} [url]
  592. * @param {string} [defaultValue]
  593. * @param {function} [dealFunc] - function that inputs original getUrlArgv result and outputs final return value
  594. */
  595. function getUrlArgv() {
  596. const [name, url, defaultValue, dealFunc] = parseArgs([...arguments], [
  597. function(args, defaultValues) {
  598. const arg = args[0];
  599. return {
  600. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  601. 'object': () => ['name', 'url', 'defaultValue', 'dealFunc'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  602. }[typeof arg]();
  603. },
  604. [2,1],
  605. [2,1,3],
  606. [2,1,3,4]
  607. ], [null, location.href, null, a => a]);
  608.  
  609. if (name === null) { return null; }
  610.  
  611. const search = new URL(url).search;
  612. const objSearch = new URLSearchParams(search);
  613. const raw = objSearch.has(name) ? objSearch.get(name) : defaultValue;
  614. const argv = dealFunc(raw);
  615.  
  616. return argv;
  617. }
  618.  
  619. /**
  620. * download file from given url by simulating <a download="..." href=""></a> clicks \
  621. * a common use case is to download Blob objects as file from `URL.createObjectURL`
  622. * @param {string} url
  623. * @param {string} filename
  624. */
  625. function dl_browser(url, filename) {
  626. const a = document.createElement('a');
  627. a.href = url;
  628. a.download = filename;
  629. a.click();
  630. }
  631.  
  632. /**
  633. * File download function \
  634. * details looks like the detail of GM_xmlhttpRequest \
  635. * onload function will be called after file saved to disk
  636. * @param {object} details
  637. */
  638. function dl_GM(details) {
  639. if (!details.url || !details.name) {return false;};
  640.  
  641. // Configure request object
  642. const requestObj = {
  643. url: details.url,
  644. responseType: 'blob',
  645. onload: function(e) {
  646. // Save file
  647. dl_browser(URL.createObjectURL(e.response), details.name);
  648.  
  649. // onload callback
  650. details.onload ? details.onload(e) : function() {};
  651. }
  652. }
  653. if (details.onloadstart ) {requestObj.onloadstart = details.onloadstart;};
  654. if (details.onprogress ) {requestObj.onprogress = details.onprogress;};
  655. if (details.onerror ) {requestObj.onerror = details.onerror;};
  656. if (details.onabort ) {requestObj.onabort = details.onabort;};
  657. if (details.onreadystatechange) {requestObj.onreadystatechange = details.onreadystatechange;};
  658. if (details.ontimeout ) {requestObj.ontimeout = details.ontimeout;};
  659.  
  660. // Send request
  661. Assert(typeof GM_xmlhttpRequest === 'function', 'GM_xmlhttpRequest should be provided in order to use dl_GM', TypeError);
  662. GM_xmlhttpRequest(requestObj);
  663. }
  664.  
  665. /**
  666. * Manager to manager async tasks \
  667. * This was written when I haven't learnt Promise, so for fluent promise users, just ignore it:)
  668. *
  669. * # Usage
  670. * ```javascript
  671. * // This simulates a async task, it can be a XMLHttpRequest, some file reading, or so on...
  672. * function someAsyncTask(callback, duration) {
  673. * const result = Math.random();
  674. * setTimeout(() => callback(result), duration);
  675. * }
  676. *
  677. * // Do 10 async tasks, and log all results when all async tasks finished
  678. * const AM = new AsyncManager();
  679. * const results = [];
  680. * AM.onfinish = function() {
  681. * console.log('All tasks finished!');
  682. * console.log(results);
  683. * }
  684. *
  685. * for (let i = 0; i < 10; i++) {
  686. * AM.add();
  687. * const duration = (Math.random() * 5 + 5) * 1000;
  688. * const index = i;
  689. * someAsyncTask(result => {
  690. * console.log(`Task ${index} finished after ${duration}ms!`);
  691. * results[index] = result;
  692. * }, duration);
  693. * console.log(`Task ${index} started!`);
  694. * }
  695. *
  696. * // Set AM.finishEvent to true after all tasks added, allowing AsyncManager to call onfinish callback
  697. * ```
  698. * @constructor
  699. */
  700. function AsyncManager() {
  701. const AM = this;
  702.  
  703. // Ongoing tasks count
  704. this.taskCount = 0;
  705.  
  706. // Whether generate finish events
  707. let finishEvent = false;
  708. Object.defineProperty(this, 'finishEvent', {
  709. configurable: true,
  710. enumerable: true,
  711. get: () => (finishEvent),
  712. set: (b) => {
  713. finishEvent = b;
  714. b && AM.taskCount === 0 && AM.onfinish && AM.onfinish();
  715. }
  716. });
  717.  
  718. // Add one task
  719. this.add = () => (++AM.taskCount);
  720.  
  721. // Finish one task
  722. this.finish = () => ((--AM.taskCount === 0 && AM.finishEvent && AM.onfinish && AM.onfinish(), AM.taskCount));
  723. }
  724.  
  725. /**
  726. * Put tasks in specific queue and order their execution \
  727. * Set `queueTask[queueId].max`, `queueTask[queueId].sleep` to custom queue's max ongoing tasks and sleep time between tasks
  728. * @param {function} task - task function to run
  729. * @param {string | Symbol} queueId - identifier to specify a target queue. if provided, given task will be added into specified queue.
  730. * @returns
  731. */
  732. function queueTask(task, queueId='default') {
  733. init();
  734.  
  735. return new Promise((resolve, reject) => {
  736. queueTask.hasOwnProperty(queueId) || (queueTask[queueId] = { tasks: [], ongoing: 0 });
  737. queueTask[queueId].tasks.push({task, resolve, reject});
  738. checkTask(queueId);
  739. });
  740.  
  741. function init() {
  742. if (!queueTask[queueId]?.initialized) {
  743. queueTask[queueId] = {
  744. // defaults
  745. tasks: [],
  746. ongoing: 0,
  747. max: 3,
  748. sleep: 500,
  749.  
  750. // user's pre-sets
  751. ...(queueTask[queueId] || {}),
  752.  
  753. // initialized flag
  754. initialized: true
  755. }
  756. };
  757. }
  758.  
  759. function checkTask() {
  760. const queue = queueTask[queueId];
  761. setTimeout(() => {
  762. if (queue.ongoing < queue.max && queue.tasks.length) {
  763. const task = queue.tasks.shift();
  764. queue.ongoing++;
  765. setTimeout(
  766. () => task.task().then(v => {
  767. queue.ongoing--;
  768. task.resolve(v);
  769. checkTask(queueId);
  770. }).catch(e => {
  771. queue.ongoing--;
  772. task.reject(e);
  773. checkTask(queueId);
  774. }),
  775. queue.sleep
  776. );
  777. }
  778. });
  779. }
  780. }
  781.  
  782. const [FunctionLoader, loadFuncs, require, isLoaded] = (function() {
  783. /**
  784. * 一般用作函数对象oFunc的加载条件,检测当前环境是否适合/需要该oFunc加载
  785. * @typedef {Object} checker_func
  786. * @property {string} type - checker's identifier
  787. * @property {function} func - actual internal judgement implementation
  788. */
  789. /**
  790. * 一般用作函数对象oFunc的加载条件,检测当前环境是否适合/需要该oFunc加载
  791. * @typedef {Object} checker
  792. * @property {string} type - checker's identifier
  793. * @property {*} value - param that goes into checker function
  794. */
  795. /**
  796. * 需要使用的substorage名称
  797. * @typedef {"GM_setValue" | "GM_getValue" | "GM_listValues" | "GM_deleteValue"} substorage_value
  798. */
  799. /**
  800. * 可以传入params的字符串名称
  801. * @typedef {'oFunc' | substorage_value} param
  802. */
  803. /**
  804. * 被加载函数对象的func函数
  805. * @callback oFuncBody
  806. * @param {oFunc} oFunc
  807. * @returns {*|Promise<*>}
  808. */
  809. /**
  810. * 被加载执行的函数对象
  811. * @typedef {Object} oFunc
  812. * @property {string} id - 每次load(每个FuncPool实例)内唯一的标识符
  813. * @property {boolean} [disabled] - 为真值时,无论checkers还是detectDom等任何其他条件通过或未通过,均不执行此函数对象;默认为false
  814. * @property {checker[]|checker} [checkers] - oFunc执行的条件
  815. * @property {string[]|string} [detectDom] - 如果提供,开始checker检查前会首先等待其中所有css选择器对应的元素在document中出现
  816. * @property {string[]|string} [dependencies] - 如果提供,应为其他函数对象的id或者id列表;开始checker检查前会首先等待其中所有指定的函数对象加载完毕
  817. * @property {boolean} [readonly] - 指定该函数的返回值是否应该被Proxy保护为不可修改对象
  818. * @property {param[]|param} params - 可选,指定传入oFunc.func的参数列表;可以为参数本身或其组成的数组
  819. * 参数可以为 字符串 或是 其他类型,如果是字符串就传入对应的FunctionLoader提供的内置值(见下),如果是其他类型则按照原样传入
  820. * - "oFunc":
  821. * 函数对象本身
  822. * - "GM_setValue", "GM_getValue", "GM_listValues", "GM_deleteValue":
  823. * 和脚本管理器提供的函数一致,但是读取和写入的对象是以oFunc.id为键的子空间
  824. * 比如,GM_getValue("prop") 就相当于调用脚本管理器提供的的 GM_getValue(oFunc.id)["prop"]
  825. * @property {oFuncBody} func - 实际实现了功能的函数
  826. * @property {boolean} [STOP] - [调试用] 指定不执行此函数对象
  827. */
  828.  
  829. const registered_checkers = {
  830. switch: value => value,
  831. url: value => location.href === value,
  832. path: value => location.pathname === value,
  833. regurl: value => !!location.href.match(value),
  834. regpath: value => !!location.pathname.match(value),
  835. starturl: value => location.href.startsWith(value),
  836. startpath: value => location.pathname.startsWith(value),
  837. func: value => value()
  838. };
  839.  
  840. class FuncPool extends EventTarget {
  841. static #STILL_LOADING = Symbol('oFunc still loading');
  842. static FunctionNotFound = Symbol('Function not found');
  843. static FunctionNotLoaded = Symbol('Function not loaded');
  844. static CheckerNotPass = Symbol('Function checker does not pass');
  845.  
  846. /** @typedef {symbol|*} return_value */
  847. /** @type {Map<oFunc, return_value>} */
  848. #oFuncs = new Map();
  849.  
  850. #GM_funcs;
  851.  
  852. /**
  853. * 创建新函数池
  854. * @param {Object} [details={}] - 可选,默认为{}空对象
  855. * @param {function} [details.GM_getValue] - 可选,读取脚本存储的函数;如果提供,使用提供的值,否则使用上下文中的值
  856. * @param {function} [details.GM_setValue] - 可选,写入脚本存储的函数;如果提供,使用提供的值,否则使用上下文中的值
  857. * @param {function} [details.GM_deleteValue] - 可选,删除脚本存储的函数;如果提供,使用提供的值,否则使用上下文中的值
  858. * @param {function} [details.GM_listValues] - 可选,列出脚本存储的函数;如果提供,使用提供的值,否则使用上下文中的值
  859. * @param {oFunc | oFunc[]} [oFuncs] - 可选,需要立即加载的函数对象
  860. * @returns {FuncPool}
  861. */
  862. constructor({
  863. GM_getValue: _GM_getValue = typeof GM_getValue === 'function' ? GM_getValue : null,
  864. GM_setValue: _GM_setValue = typeof GM_setValue === 'function' ? GM_setValue : null,
  865. GM_deleteValue: _GM_deleteValue = typeof GM_deleteValue === 'function' ? GM_deleteValue : null,
  866. GM_listValues: _GM_listValues = typeof GM_listValues === 'function' ? GM_listValues : null,
  867. oFuncs = []
  868. } = {}) {
  869. super();
  870. this.#GM_funcs = {
  871. GM_getValue: _GM_getValue,
  872. GM_setValue: _GM_setValue,
  873. GM_deleteValue: _GM_deleteValue,
  874. GM_listValues: _GM_listValues
  875. };
  876. this.load(oFuncs);
  877. }
  878.  
  879. /**
  880. * 加载提供的一个或多个函数对象,并将其加入到函数池中 \
  881. * 异步函数,当所有传入的函数对象都彻底load完毕/checkers确定不加载时resolve
  882. * @param {oFunc[]|oFunc} [oFuncs] - 可选,需要加载的函数对象或其数组,不提供时默认为空数组
  883. */
  884. async load(oFuncs=[]) {
  885. oFuncs = Array.isArray(oFuncs) ? oFuncs : [oFuncs];
  886. await Promise.all(oFuncs.map(oFunc => this.#load(oFunc)));
  887. }
  888.  
  889. /**
  890. * 加载一个函数对象,并将其加入到函数池中 \
  891. * 当id重复时,直接报错RedeclarationError \
  892. * 异步函数,当彻底load完毕/checkers确定不加载时resolve \
  893. * 当加载完毕时,广播load事件;如果全部加载完毕,还广播all_load事件
  894. * @todo 当checker确定不加载时,广播什么事件?后续all_load是否仍然触发?
  895. * @param {oFunc} oFunc
  896. * @returns {Promise<undefined>}
  897. */
  898. async #load(oFunc) {
  899. const that = this;
  900.  
  901. // disabled的函数对象,不执行
  902. if (oFunc.disabled) {
  903. return;
  904. }
  905.  
  906. // 已经在函数池中的函数对象,不重复load
  907. if (this.#oFuncs.has(oFunc)) {
  908. return;
  909. }
  910.  
  911. // 检查有无重复id
  912. for (const o of this.#oFuncs.keys()) {
  913. if (o.id === oFunc.id) {
  914. throw new RedeclarationError(`Attempts to load oFunc with id already in use: ${oFunc.id}`);
  915. }
  916. }
  917.  
  918. // 设置当前返回值为STILL_LOADING
  919. this.#oFuncs.set(oFunc, FuncPool.#STILL_LOADING);
  920.  
  921. // 加载依赖
  922. const dependencies = Array.isArray(oFunc.dependencies) ? oFunc.dependencies : ( oFunc.dependencies ? [oFunc.dependencies] : [] );
  923. await Promise.all(dependencies.map(id => new Promise((resolve, reject) => {
  924. $AEL(that, 'load', e => e.detail.oFunc.id === id && resolve());
  925. })));
  926.  
  927. // 检测checkers加载条件
  928. const checkers = Array.isArray(oFunc.checkers) ? oFunc.checkers : ( oFunc.checkers ? [oFunc.checkers] : [] );
  929. if (!testCheckers(checkers, oFunc)) {
  930. this.#oFuncs.set(oFunc, FuncPool.CheckerNotPass);
  931. return;
  932. }
  933.  
  934. // 检测detectDOM中css选择器指定的元素出现
  935. const selectors = Array.isArray(oFunc.detectDom) ? oFunc.detectDom : ( oFunc.detectDom ? [oFunc.detectDom] : [] );
  936. await Promise.all(selectors.map(selector => detectDom(selector)));
  937.  
  938. // 处理substorage
  939. const substorage = this.#MakeSubStorage(oFunc.id);
  940.  
  941. // 处理函数参数
  942. const builtins = {
  943. oFunc,
  944. ...substorage
  945. };
  946. const params = oFunc.params ? (Array.isArray(oFunc.params) ? oFunc.params : [oFunc.params]) : [];
  947. const args = params.map(param => typeof param === 'string' ? builtins[param] : param);
  948.  
  949. // 执行函数对象
  950. const raw_return_value = oFunc.func(...args);
  951. const return_value = await Promise.resolve(raw_return_value);
  952.  
  953. // 设置返回值
  954. this.#oFuncs.set(oFunc, return_value);
  955.  
  956. // 广播事件
  957. this.dispatchEvent(new CustomEvent('load', {
  958. detail: {
  959. oFunc, id: oFunc.id, return_value
  960. }
  961. }));
  962. Array.from(this.#oFuncs.values()).every(v => v !== FuncPool.#STILL_LOADING) &&
  963. this.dispatchEvent(new CustomEvent('all_load', {}));
  964. }
  965.  
  966. /**
  967. * 获取指定函数对象的返回值 \
  968. * 如果指定的函数对象不存在,返回FuncPool.FunctionNotFound \
  969. * 如果指定的函数对象存在但尚未加载,返回FuncPool.FunctionNotLoaded \
  970. * 如果函数对象指定了readonly为真值,则返回前用Proxy包装返回值,使其不可修改
  971. * @param {string} id - 函数对象的id
  972. * @returns {*}
  973. */
  974. require(id) {
  975. for (const [oFunc, return_value] of this.#oFuncs.entries()) {
  976. if (oFunc.id === id) {
  977. if (return_value === FuncPool.#STILL_LOADING) {
  978. return FuncPool.FunctionNotLoaded;
  979. } else {
  980. return oFunc.readonly ? FuncPool.#MakeReadonlyObj(return_value) : return_value;
  981. }
  982. }
  983. }
  984. return FuncPool.FunctionNotFound;
  985. }
  986.  
  987. isLoaded(id) {
  988. for (const [oFunc, return_value] of this.#oFuncs.entries()) {
  989. if (oFunc.id === id) {
  990. if (return_value === FuncPool.#STILL_LOADING) {
  991. return false;
  992. } else {
  993. return true;
  994. }
  995. }
  996. return false;
  997. }
  998. }
  999.  
  1000. get GM_funcs() {
  1001. return { ...this.#GM_funcs };
  1002. }
  1003.  
  1004. /**
  1005. * 以Proxy包装value,使其属性只读 \
  1006. * 如果传入的不是object,则直接返回value \
  1007. * @param {Object} val
  1008. * @returns {Proxy}
  1009. */
  1010. static #MakeReadonlyObj(val) {
  1011. return isObject(val) ? new Proxy(val, {
  1012. get: function(target, property, receiver) {
  1013. return FuncPool.#MakeReadonlyObj(target[property]);
  1014. },
  1015. set: function(target, property, value, receiver) {},
  1016. has: function(target, prop) {},
  1017. setPrototypeOf(target, newProto) {
  1018. return false;
  1019. },
  1020. defineProperty(target, property, descriptor) {
  1021. return true;
  1022. },
  1023. deleteProperty(target, property) {
  1024. return false;
  1025. },
  1026. preventExtensions(target) {
  1027. return false;
  1028. }
  1029. }) : val;
  1030.  
  1031. function isObject(value) {
  1032. return ['object', 'function'].includes(typeof value) && value !== null;
  1033. }
  1034. }
  1035.  
  1036. /**
  1037. * 创建适用于子功能函数的 GM_setValue, GM_getValue, GM_deleteValue 和 GM_listValues \
  1038. * 调用返回的`GM_setValue(str, val)`相当于对脚本管理器提供的GM*函数进行如下调用:
  1039. * ``` javascript
  1040. * const obj = GM_getValue(key, {});
  1041. * if (typeof obj !== 'object' or obj === null) { throw new TypeError(''); }
  1042. * obj[str] = val;
  1043. * GM_setValue(key, obj);
  1044. * ```
  1045. * @param {string} key - 实际调用用户脚本管理器的GM*函数时提供的key,一般是子功能函数id
  1046. * @returns {{ GM_setValue: function, GM_getValue: function, GM_deleteValue: function, GM_listValues: function }}
  1047. */
  1048. #MakeSubStorage(key) {
  1049. const GM_funcs = this.#GM_funcs;
  1050. return {
  1051. GM_setValue(name, val) {
  1052. checkGrant(['GM_setValue', 'GM_getValue'], 'GM_setValue');
  1053. const obj = GM_funcs.GM_getValue(key, {});
  1054. Assert(isObject(obj), `FunctionLoader: storage item of key ${name} should be an object`, TypeError);
  1055. obj[name] = val;
  1056. GM_funcs.GM_setValue(key, obj);
  1057. },
  1058. GM_getValue(name, default_value=null) {
  1059. checkGrant(['GM_getValue'], 'GM_getValue');
  1060. const obj = GM_funcs.GM_getValue(key, {});
  1061. return obj.hasOwnProperty(name) ? obj[name] : default_value;
  1062. },
  1063. GM_deleteValue(name) {
  1064. checkGrant(['GM_setValue', 'GM_getValue'], 'GM_deleteValue');
  1065. const obj = GM_funcs.GM_getValue(key, {});
  1066. delete obj[name];
  1067. GM_funcs.GM_setValue(key, obj);
  1068. },
  1069. GM_listValues() {
  1070. checkGrant(['GM_getValue'], 'GM_listValues');
  1071. const obj = GM_funcs.GM_getValue(key, {});
  1072. return Object.keys(obj);
  1073. }
  1074. };
  1075.  
  1076. /**
  1077. * 检查指定的GM_*函数是否存在,不存在就抛出错误
  1078. * @param {string|string[]} funcnames
  1079. * @param {string} calling - 正在调用的GM_函数的名字,输出错误信息时用
  1080. */
  1081. function checkGrant(funcnames, calling) {
  1082. Array.isArray(funcnames) || (funcnames = [funcnames]);
  1083. for (const funcname of funcnames) {
  1084. Assert(GM_funcs[funcname], `FunctionLoader: @grant ${funcname} in userscript metadata before using ${calling}`, TypeError);
  1085. }
  1086. }
  1087.  
  1088. function isObject(val) {
  1089. return typeof val === 'object' && val !== null;
  1090. }
  1091. }
  1092. }
  1093. class RedeclarationError extends TypeError {}
  1094. class CircularDependencyError extends ReferenceError {}
  1095.  
  1096.  
  1097. // 预置的函数池
  1098. const default_pool = new FuncPool();
  1099.  
  1100. /**
  1101. * 在预置的函数池中加载函数对象或其数组
  1102. * @param {oFunc[]|oFunc} oFuncs - 需要执行的函数对象
  1103. * @returns {FuncPool}
  1104. */
  1105. function loadFuncs(oFuncs) {
  1106. default_pool.load(oFuncs);
  1107. return default_pool;
  1108. }
  1109.  
  1110. /**
  1111. * 在预置的函数池中获取函数对象的返回值
  1112. * @param {string} id - 函数对象的字符串id
  1113. * @returns {*}
  1114. */
  1115. function require(id) {
  1116. return default_pool.require(id);
  1117. }
  1118.  
  1119. /**
  1120. * 在预置的函数池中检查指定函数对象是否已经加载完毕(有返回值可用)
  1121. * @param {string} id - 函数对象的字符串id
  1122. * @returns {boolean}
  1123. */
  1124. function isLoaded(id) {
  1125. return default_pool.isLoaded(id);
  1126. }
  1127.  
  1128. /**
  1129. * 测试给定checker是否检测通过 \
  1130. * 给定多个checker时,checkers之间是 或 关系,有一个checker通过即算作整体通过 \
  1131. * 注意此函数设计和旧版testChecker的设计不同,旧版中一个checker可以有多个值,还可通过checker.all指定多值之间的关系为 与 还是 或
  1132. * @param {checker[]|checker} [checkers] - 需要检测的checkers
  1133. * @param {oFunc|*} [this_value] - 如提供,将用作checkers运行时的this值;一般而言为checkers所属的函数对象
  1134. * @returns {boolean}
  1135. */
  1136. function testCheckers(checkers=[], this_value=null) {
  1137. checkers = Array.isArray(checkers) ? checkers : [checkers];
  1138. return checkers.length === 0 || checkers.some(checker => !!registered_checkers[checker.type]?.call(this_value, checker.value));
  1139. }
  1140.  
  1141. /**
  1142. * 注册新checker \
  1143. * 如果给定type已经被其他checker占用,则会报错RedeclarationError \
  1144. * @param {string} type - checker类名
  1145. * @param {function} func - checker implementation
  1146. */
  1147. function registerChecker(type, func) {
  1148. if (registered_checkers.hasOwnProperty(type)) {
  1149. throw RedeclarationError(`Attempts to register checker with type already in use: ${type}`);
  1150. }
  1151. registered_checkers[type] = func;
  1152. }
  1153.  
  1154. const FunctionLoader = {
  1155. FuncPool,
  1156. testCheckers,
  1157. registerChecker,
  1158. get checkers() {
  1159. return Object.assign({}, registered_checkers);
  1160. },
  1161. Error: {
  1162. RedeclarationError,
  1163. CircularDependencyError
  1164. }
  1165. };
  1166. return [FunctionLoader, loadFuncs, require, isLoaded];
  1167. }) ();
  1168.  
  1169. return [
  1170. // Console & Debug
  1171. LogLevel, DoLog, Err, Assert,
  1172.  
  1173. // DOM
  1174. $, $All, $CrE, $AEL, $$CrE, addStyle, detectDom, destroyEvent,
  1175.  
  1176. // Data
  1177. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  1178.  
  1179. // Environment & Browser
  1180. getUrlArgv, dl_browser, dl_GM,
  1181.  
  1182. // Logic & Task
  1183. AsyncManager, queueTask, FunctionLoader, loadFuncs, require, isLoaded
  1184. ];
  1185. }) ();