transform-file.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import gensync, { type Handler } from "gensync";
  2. import loadConfig from "./config/index.ts";
  3. import type { InputOptions, ResolvedConfig } from "./config/index.ts";
  4. import { run } from "./transformation/index.ts";
  5. import type { FileResult, FileResultCallback } from "./transformation/index.ts";
  6. import * as fs from "./gensync-utils/fs.ts";
  7. type transformFileBrowserType = typeof import("./transform-file-browser");
  8. type transformFileType = typeof import("./transform-file");
  9. // Kind of gross, but essentially asserting that the exports of this module are the same as the
  10. // exports of transform-file-browser, since this file may be replaced at bundle time with
  11. // transform-file-browser.
  12. ({}) as any as transformFileBrowserType as transformFileType;
  13. const transformFileRunner = gensync(function* (
  14. filename: string,
  15. opts?: InputOptions,
  16. ): Handler<FileResult | null> {
  17. const options = { ...opts, filename };
  18. const config: ResolvedConfig | null = yield* loadConfig(options);
  19. if (config === null) return null;
  20. const code = yield* fs.readFile(filename, "utf8");
  21. return yield* run(config, code);
  22. });
  23. // @ts-expect-error TS doesn't detect that this signature is compatible
  24. export function transformFile(
  25. filename: string,
  26. callback: FileResultCallback,
  27. ): void;
  28. export function transformFile(
  29. filename: string,
  30. opts: InputOptions | undefined | null,
  31. callback: FileResultCallback,
  32. ): void;
  33. export function transformFile(
  34. ...args: Parameters<typeof transformFileRunner.errback>
  35. ) {
  36. transformFileRunner.errback(...args);
  37. }
  38. export function transformFileSync(
  39. ...args: Parameters<typeof transformFileRunner.sync>
  40. ) {
  41. return transformFileRunner.sync(...args);
  42. }
  43. export function transformFileAsync(
  44. ...args: Parameters<typeof transformFileRunner.async>
  45. ) {
  46. return transformFileRunner.async(...args);
  47. }