generate-helpers.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import fs from "fs";
  2. import { join } from "path";
  3. import { URL, fileURLToPath } from "url";
  4. import { minify } from "terser"; // eslint-disable-line import/no-extraneous-dependencies
  5. const HELPERS_FOLDER = new URL("../src/helpers", import.meta.url);
  6. const IGNORED_FILES = new Set(["package.json"]);
  7. export default async function generateHelpers() {
  8. let output = `/*
  9. * This file is auto-generated! Do not modify it directly.
  10. * To re-generate run 'yarn gulp generate-runtime-helpers'
  11. */
  12. import template from "@babel/template";
  13. function helper(minVersion: string, source: string) {
  14. return Object.freeze({
  15. minVersion,
  16. ast: () => template.program.ast(source, { preserveComments: true }),
  17. })
  18. }
  19. export default Object.freeze({
  20. `;
  21. for (const file of (await fs.promises.readdir(HELPERS_FOLDER)).sort()) {
  22. if (IGNORED_FILES.has(file)) continue;
  23. if (file.startsWith(".")) continue; // ignore e.g. vim swap files
  24. const [helperName] = file.split(".");
  25. const filePath = join(fileURLToPath(HELPERS_FOLDER), file);
  26. if (!file.endsWith(".js")) {
  27. console.error("ignoring", filePath);
  28. continue;
  29. }
  30. const fileContents = await fs.promises.readFile(filePath, "utf8");
  31. const minVersionMatch = fileContents.match(
  32. /^\s*\/\*\s*@minVersion\s+(?<minVersion>\S+)\s*\*\/\s*$/m
  33. );
  34. if (!minVersionMatch) {
  35. throw new Error(`@minVersion number missing in ${filePath}`);
  36. }
  37. const { minVersion } = minVersionMatch.groups;
  38. const source = await minify(fileContents, {
  39. mangle: false,
  40. // The _typeof helper has a custom directive that we must keep
  41. compress: { directives: false },
  42. });
  43. output += `\
  44. ${JSON.stringify(helperName)}: helper(
  45. ${JSON.stringify(minVersion)},
  46. ${JSON.stringify(source.code)},
  47. ),
  48. `;
  49. }
  50. output += "});";
  51. return output;
  52. }