iterate.com / stdlib

git clone https://git.iterate.com/repos/stdlib

stdlib / testing / mind-loader.mjsmain at 41005ca

// mind-loader.mjs — WHAT THE MIND'S LOADER GIVES A MODULE, FOR NODE: a test of any repo imports
// this file first (`import "@repos/stdlib/testing/mind-loader.mjs"`) when it loads a module that
// the mind loads (an app.ts, worker.ts). In the mind a file that is not code is imported as its
// text, a folder (an import that ends in `/`) as every file under it by path, and
// `cloudflare:workers` is the runtime's own module. Node has none of the three: the hooks below
// give the first two as the loader does, and for the third the base classes alone, which hold
// what they are given. ../files.d.ts says the same to the type checker. A file of another repo is
// `@repos/<name>/<path>`: Node finds the repo where the importing repo's install linked it.
import { readdirSync, readFileSync } from "node:fs";
import { registerHooks } from "node:module";
import { fileURLToPath } from "node:url";

const WORKERS = "mind-loader:cloudflare-workers";

// Where a file or a folder of a repo is on this disk, as a URL: `./x` and `../x` beside the
// importer, and `@repos/<name>/x` in the folder that an install linked as that package.
// Undefined for any other import.
function fileOf(specifier, context, next) {
  if (specifier.startsWith("./") || specifier.startsWith("../"))
    return new URL(specifier, context.parentURL).href;
  const named = /^(@repos\/[^/]+)\/(.*)$/.exec(specifier);
  if (named) return new URL(named[2], next(`${named[1]}/package.json`, context).url).href;
}

registerHooks({
  resolve(specifier, context, next) {
    if (specifier === "cloudflare:workers") return { url: WORKERS, shortCircuit: true };
    const kind = specifier.endsWith("/") ? "folder" : /\.(html|css)$/.test(specifier) ? "text" : "";
    const file = kind && fileOf(specifier, context, next);
    if (file) return { url: `${file}?${kind}`, shortCircuit: true };
    return next(specifier, context);
  },
  load(url, context, next) {
    if (url === WORKERS)
      return {
        format: "module",
        shortCircuit: true,
        source: `
          class Held { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }
          export class WorkerEntrypoint extends Held {}
          export class DurableObject extends Held {}
          export class RpcTarget {}
          export class RpcStub {}
          export const env = {};
          export const waitUntil = () => {};
        `,
      };
    if (url.endsWith("?text")) {
      const text = readFileSync(fileURLToPath(url.slice(0, -"?text".length)), "utf8");
      return { format: "module", shortCircuit: true, source: `export default ${JSON.stringify(text)};` };
    }
    if (url.endsWith("?folder")) {
      const dir = fileURLToPath(url.slice(0, -"?folder".length));
      const files = Object.fromEntries(
        readdirSync(dir, { recursive: true, withFileTypes: true })
          .filter((entry) => entry.isFile())
          .map((entry) => {
            const path = `${entry.parentPath.replace(/\/$/, "")}/${entry.name}`;
            return [path.slice(dir.length), readFileSync(path, "utf8")];
          })
          .sort(([a], [b]) => a.localeCompare(b)),
      );
      return { format: "module", shortCircuit: true, source: `export default ${JSON.stringify(files)};` };
    }
    return next(url, context);
  },
});