// Verifies the workspace member `node_modules` directories created by
// `deno install`.

function assertDir(path: string) {
  const stat = Deno.statSync(path);
  if (!stat.isDirectory) {
    throw new Error(`expected a directory at ${path}`);
  }
}

function assertExists(path: string) {
  // lstat (not stat) so a `.bin` entry counts as present whether it is a
  // symlink (Unix) or a shim file (Windows), and without following it.
  try {
    Deno.lstatSync(path);
  } catch (err) {
    if (err instanceof Deno.errors.NotFound) {
      throw new Error(`expected ${path} to exist`);
    }
    throw err;
  }
}

// A member's own npm dependency is materialized in its local `node_modules`
// (https://github.com/denoland/deno/issues/26743).
assertDir("package1/node_modules/@denotest/esm-basic");

// A member's devDependency is materialized in its local `node_modules` too.
assertDir("package2/node_modules/@denotest/cjs-default-export");

// A sibling workspace member is symlinked into the member's `node_modules`
// (https://github.com/denoland/deno/issues/27550).
assertDir("package2/node_modules/package1");

// and the link actually points at the sibling member.
const pkg = JSON.parse(
  Deno.readTextFileSync("package2/node_modules/package1/package.json"),
);
if (pkg.name !== "package1") {
  throw new Error(`expected package1, got ${pkg.name}`);
}

// A member's `.bin` is populated with its dependencies' executables, so a tool
// invoked as `node_modules/.bin/<tool>` from within the member resolves the
// member's own copy, the way npm and pnpm lay workspaces out. Both members
// declare `@denotest/bin`, which ships a `cli-esm` executable.
assertExists("package1/node_modules/.bin/cli-esm");
assertExists("package2/node_modules/.bin/cli-esm");

// The workspace root's `node_modules` is populated as before: the per-member
// linking must not touch it. (If the `is_root` check regressed, the root would
// be treated as a member with no declared deps and get pruned to nothing.)
assertDir("node_modules/@denotest/esm-basic");
assertDir("node_modules/@denotest/cjs-default-export");

console.log("ok");
