All files / src/lib/compiler buildRunner.ts

16.13% Statements 5/31
0% Branches 0/13
0% Functions 0/6
13.33% Lines 4/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 751x 1x     1x                       1x                                                                                                                    
import Path from "path";
import { Worker } from "worker_threads";
import compileData from "./compileData";
import { BuildTaskResponse, BuildWorkerData } from "./buildWorker";
import { getL10NData } from "shared/lib/lang/l10n";
 
type BuilderRunnerResult = {
  kill: () => void;
  result: ReturnType<typeof compileData>;
};
 
type BuildRunnerOptions = Omit<BuildWorkerData, "l10nData"> & {
  progress: (msg: string) => void;
  warnings: (msg: string) => void;
};
 
export const buildRunner = ({
  progress,
  warnings,
  ...options
}: BuildRunnerOptions): BuilderRunnerResult => {
  let worker: Worker | undefined;
  let cancelling = false;
 
  const compiledData = new Promise<Awaited<ReturnType<typeof compileData>>>(
    (resolve, reject) => {
      const workerPath = Path.resolve(__dirname, "./buildWorker.js");
      const workerData: BuildWorkerData = {
        ...options,
        l10nData: getL10NData(),
      };
 
      worker = new Worker(workerPath, {
        workerData,
      });
 
      worker.on("message", (message: BuildTaskResponse) => {
        Iif (cancelling) {
          return;
        }
        if (message.action === "progress") {
          progress(message.payload.message);
        } else if (message.action === "warning") {
          warnings(message.payload.message);
        } else Iif (message.action === "complete") {
          resolve(message.payload);
        }
      });
      worker.on("error", (error) => {
        reject(error);
      });
      worker.on("exit", (code) => {
        Iif (code !== 0) {
          reject(code ?? 1);
        }
      });
    }
  );
 
  const kill = () => {
    Iif (cancelling) {
      return;
    }
    cancelling = true;
    Iif (worker) {
      worker.postMessage({ action: "terminate" });
    }
  };
 
  return {
    kill,
    result: compiledData,
  };
};