#!/bin/sh
node <<'EOF'
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { fdir } from "fdir";

test("fdir crawls a temporary directory correctly", async () => {
  // Create a real temporary directory
  const root = await mkdtemp(join(tmpdir(), "fdir-test-"));

  try {
    // Build a test directory structure
    await mkdir(join(root, "a/b"), { recursive: true });
    await writeFile(join(root, "a/file1.txt"), "hello");
    await writeFile(join(root, "a/b/file2.js"), "console.log('x')");
    await writeFile(join(root, "root.txt"), "root");

    // Run fdir
    const crawler = new fdir()
      .withFullPaths()
      .crawl(root);

    const files = crawler.sync();

    // Expected files
    const expected = [
      join(root, "a/file1.txt"),
      join(root, "a/b/file2.js"),
      join(root, "root.txt")
    ];

    // Sort for stable comparison
    console.log(files)
    files.sort();
    expected.sort();

    assert.deepEqual(files, expected);
  } finally {
    // Always delete the temporary directory
    await rm(root, { recursive: true, force: true });
  }
})
EOF