post-build-global.mts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { access, constants as fsconstants, readFile, writeFile } from "fs/promises";
  2. import { resolve } from "path";
  3. import packageJson from "../package.json" assert { type: "json" };
  4. const { exit } = process;
  5. const iifeScriptPath = resolve("dist/index.global.js");
  6. async function run() {
  7. if(!await exists(iifeScriptPath)) {
  8. console.error(`No global script found at path '${iifeScriptPath}'`);
  9. setImmediate(() => exit(1));
  10. return;
  11. }
  12. const libHeader = `\
  13. // ==UserScript==
  14. // @namespace ${packageJson.homepage}
  15. // @exclude *
  16. // @author ${packageJson.author.name}
  17. // @supportURL ${packageJson.bugs.url}
  18. // @homepageURL ${packageJson.homepage}#readme
  19. // @supportURL ${packageJson.homepage}/issues
  20. // ==UserLibrary==
  21. // @name UserUtils
  22. // @description ${packageJson.description}
  23. // @version ${packageJson.version}
  24. // @license ${packageJson.license}
  25. // @copyright ${packageJson.author.name} (${packageJson.author.url})
  26. // ==/UserScript==
  27. // ==/UserLibrary==
  28. // ==OpenUserJS==
  29. // @author Sv443
  30. // ==/OpenUserJS==
  31. `;
  32. const initialScript = await readFile(iifeScriptPath, "utf8");
  33. let finalScript = `\
  34. ${libHeader}
  35. var UserUtils = ${initialScript}`;
  36. finalScript = finalScript.replace(/^\s*'use strict';\s*\r?\n{1,2}/gm, "");
  37. await writeFile(iifeScriptPath, finalScript, "utf8");
  38. console.log(`Global script at path '${iifeScriptPath}' has been updated`);
  39. setImmediate(() => exit(0));
  40. }
  41. async function exists(path: string) {
  42. try {
  43. await access(path, fsconstants.R_OK | fsconstants.W_OK);
  44. return true;
  45. }
  46. catch(err) {
  47. return false;
  48. }
  49. }
  50. run();