diff --git a/biome.json b/biome.json index a72cde6..c5bc134 100644 --- a/biome.json +++ b/biome.json @@ -1,11 +1,10 @@ { "$schema": "https://biomejs.dev/schemas/2.6.5/schema.json", "root": true, - "extends": ["@rigelbuild/biome-config/biome"], + "extends": ["./packages/biome-config/biome.json"], "files": { "includes": [ "**", - "!rumdl-extends.test.ts", "!go/commentscan/testdata", "!go/ledger/testdata", "!**/CHANGELOG.md" diff --git a/go/internal/repochecks/package_bins_test.go b/go/internal/repochecks/package_bins_test.go new file mode 100644 index 0000000..71b24cb --- /dev/null +++ b/go/internal/repochecks/package_bins_test.go @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +package repochecks + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// declaredBins returns the bin paths a package.json record declares, as a string or an object. +func declaredBins(t *testing.T, manifest json5Record) []string { + t.Helper() + switch bin := manifest["bin"].(type) { + case nil: + return nil + case string: + return []string{bin} + case map[string]any: + paths := make([]string, 0, len(bin)) + for _, value := range bin { + path, ok := value.(string) + if !ok { + t.Fatalf("bin entry %v is not a string", value) + } + paths = append(paths, path) + } + return paths + default: + t.Fatalf("bin has unexpected type %T", bin) + return nil + } +} + +// packageBin is one bin declared by a package under packages/. +type packageBin struct { + pkg string + bin string + path string +} + +// readPackageBins lists every bin declared by the packages under root/packages. +func readPackageBins(t *testing.T, root string) []packageBin { + t.Helper() + packages := filepath.Join(root, "packages") + entries, err := os.ReadDir(packages) + if err != nil { + t.Fatal(err) + } + var bins []packageBin + for _, entry := range entries { + if !entry.IsDir() { + continue + } + manifest := readJSON5Record(t, filepath.Join(packages, entry.Name(), "package.json")) + for _, bin := range declaredBins(t, manifest) { + bins = append(bins, packageBin{ + pkg: entry.Name(), + bin: bin, + path: filepath.Join(packages, entry.Name(), bin), + }) + } + } + return bins +} + +func TestPackageBins(t *testing.T) { + root := filepath.Dir(moduleRoot(t)) + bins := readPackageBins(t, root) + + t.Run("reads string, object, and absent bin declarations", func(t *testing.T) { + if got := declaredBins(t, json5Record{"bin": "./cli.ts"}); len(got) != 1 || got[0] != "./cli.ts" { + t.Fatalf("string bin = %q, want [./cli.ts]", got) + } + object := declaredBins(t, json5Record{"bin": json5Record{"a": "./a.ts", "b": "./b.ts"}}) + if len(object) != 2 || !containsString(object, "./a.ts") || !containsString(object, "./b.ts") { + t.Fatalf("object bin = %q, want [./a.ts ./b.ts]", object) + } + if got := declaredBins(t, json5Record{}); len(got) != 0 { + t.Fatalf("absent bin = %q, want none", got) + } + }) + + t.Run("at least one package declares a bin", func(t *testing.T) { + if len(bins) == 0 { + t.Fatal("no package under packages/ declares a bin") + } + }) + + t.Run("each bin starts with the bun shebang", func(t *testing.T) { + for _, bin := range bins { + content, err := os.ReadFile(bin.path) + if err != nil { + t.Fatal(err) + } + firstLine, _, _ := strings.Cut(string(content), "\n") + if firstLine != "#!/usr/bin/env bun" { + t.Errorf("%s bin %s first line = %q, want #!/usr/bin/env bun", bin.pkg, bin.bin, firstLine) + } + } + }) + + t.Run("each bin is npm-normalized without a leading ./", func(t *testing.T) { + // npm publish rewrites a "./" bin path and warns; keep manifests in the form npm publishes. + for _, bin := range bins { + if strings.HasPrefix(bin.bin, "./") { + t.Errorf("%s bin %s starts with ./", bin.pkg, bin.bin) + } + } + }) +} diff --git a/go/internal/repochecks/process_test.go b/go/internal/repochecks/process_test.go new file mode 100644 index 0000000..41eb4f1 --- /dev/null +++ b/go/internal/repochecks/process_test.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +package repochecks + +import ( + "bytes" + "errors" + "os" + "os/exec" + "testing" +) + +// processResult holds the exit status and captured streams of a child process. +type processResult struct { + status int + stdout string + stderr string +} + +// runProcess runs name in dir with env and returns its status and output. +// A nil env inherits the test process environment. +func runProcess(t *testing.T, dir string, env []string, name string, args ...string) processResult { + t.Helper() + cmd := exec.CommandContext(t.Context(), name, args...) + cmd.Dir = dir + cmd.Env = env + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + var result processResult + err := cmd.Run() + if err != nil { + var exitErr *exec.ExitError + if !errors.As(err, &exitErr) { + t.Fatalf("run %s: %v", name, err) + } + result.status = exitErr.ExitCode() + if result.status < 0 { + // A process killed by a signal has no exit code, so report it as a failure. + result.status = 1 + } + } + result.stdout = stdout.String() + result.stderr = stderr.String() + return result +} + +func writeFixtureFile(t *testing.T, path, content string) { + t.Helper() + err := os.WriteFile(path, []byte(content), 0o600) + if err != nil { + t.Fatal(err) + } +} + +func readFixtureFile(t *testing.T, path string) string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(data) +} diff --git a/go/internal/repochecks/rumdl_extends_test.go b/go/internal/repochecks/rumdl_extends_test.go new file mode 100644 index 0000000..49b707d --- /dev/null +++ b/go/internal/repochecks/rumdl_extends_test.go @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +package repochecks + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/RigelBuild/meissa/go/internal/jstext" +) + +// longParagraph is one sentence that exceeds the default MD013 line width. +const longParagraph = "A paragraph whose length exceeds the default maximum line width " + + "without violating other default rules. " + +func TestSharedRumdlPolicyInheritance(t *testing.T) { + baseConfig := os.Getenv("RUMDL_BASE_CONFIG") + if baseConfig == "" { + t.Fatal("RUMDL_BASE_CONFIG is not set") + } + rumdl := os.Getenv("RUMDL_BIN") + if rumdl == "" { + t.Fatal("RUMDL_BIN is not set") + } + pathRumdl, err := exec.LookPath("rumdl") + if err != nil { + t.Fatalf("look up rumdl on PATH: %v (RUMDL_BIN %s)", err, rumdl) + } + if pathRumdl != rumdl { + t.Fatalf("PATH rumdl (%s) does not match RUMDL_BIN", pathRumdl) + } + + t.Run("extends inherits disabled MD013 for a long heading-less paragraph", func(t *testing.T) { + // The TOML holds the literal placeholder; rumdl expands it from RUMDL_BASE_CONFIG. + config := "extends = \"$RUMDL_BASE_CONFIG\"\n\n[MD041]\nenabled = false\n" + result := checkWithRumdl(t, rumdl, baseConfig, config) + if result.status != 0 { + t.Fatalf("rumdl exit = %d, want 0: %s%s", result.status, result.stdout, result.stderr) + } + }) + + t.Run("the heading-less control without extends reports MD013", func(t *testing.T) { + result := checkWithRumdl(t, rumdl, baseConfig, "[MD041]\nenabled = false\n") + if result.status != 1 { + t.Fatalf("rumdl exit = %d, want 1: %s%s", result.status, result.stdout, result.stderr) + } + if output := result.stdout + result.stderr; !strings.Contains(output, "MD013") { + t.Fatalf("output lacks MD013: %s", output) + } + }) +} + +// checkWithRumdl writes config and a long heading-less paragraph, then runs rumdl check on them. +func checkWithRumdl(t *testing.T, rumdl, baseConfig, config string) processResult { + t.Helper() + directory := t.TempDir() + configPath := filepath.Join(directory, ".rumdl.toml") + markdownPath := filepath.Join(directory, "headingless.md") + writeFixtureFile(t, configPath, config) + writeFixtureFile(t, markdownPath, jstext.TrimRight(strings.Repeat(longParagraph, 2))+"\n") + env := append(os.Environ(), "RUMDL_BASE_CONFIG="+baseConfig) + return runProcess(t, directory, env, rumdl, "check", "--no-cache", "--config", configPath, markdownPath) +} diff --git a/go/internal/repochecks/shared_configs_test.go b/go/internal/repochecks/shared_configs_test.go new file mode 100644 index 0000000..3e6b6e0 --- /dev/null +++ b/go/internal/repochecks/shared_configs_test.go @@ -0,0 +1,263 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +package repochecks + +import ( + "encoding/json" + "maps" + "net/url" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + + "github.com/RigelBuild/meissa/go/internal/jstext" +) + +// consumerFixture is a git repository that holds a copy of the biome-config package under node_modules. +type consumerFixture struct { + directory string + packageDirectory string + configPath string + fixturePath string +} + +// copyPackage copies the named files of a package directory into destination. +func copyPackage(t *testing.T, source, destination string, files ...string) { + t.Helper() + err := os.MkdirAll(destination, 0o755) + if err != nil { + t.Fatal(err) + } + for _, name := range files { + writeFixtureFile(t, filepath.Join(destination, name), readFixtureFile(t, filepath.Join(source, name))) + } +} + +func newConsumerFixture(t *testing.T) consumerFixture { + t.Helper() + directory := t.TempDir() + // The preset enables VCS ignore files, so a consumer fixture must be a git repo. + initResult := runProcess(t, "", nil, "git", "init", "-q", directory) + if initResult.status != 0 { + t.Fatalf("git init: %s", initResult.stderr) + } + writeFixtureFile(t, filepath.Join(directory, ".gitignore"), "node_modules/\ngenerated/\n") + // Biome resolves a bare extends only when the consumer directory has a package.json. + writeFixtureFile(t, filepath.Join(directory, "package.json"), + "{\n\t\"name\": \"consumer\",\n\t\"private\": true\n}\n") + + packageDirectory := filepath.Join(directory, "node_modules", "@rigelbuild", "biome-config") + source := filepath.Join(filepath.Dir(moduleRoot(t)), "packages", "biome-config") + copyPackage(t, source, packageDirectory, "package.json", "biome.json") + configPath := filepath.Join(directory, "biome.json") + writeFixtureFile(t, configPath, + "{\n\t\"root\": true,\n\t\"extends\": [\"./space.json\", \"@rigelbuild/biome-config/biome\"]\n}\n") + writeFixtureFile(t, filepath.Join(directory, "space.json"), + "{\n\t\"root\": false,\n\t\"formatter\": { \"indentStyle\": \"space\" }\n}\n") + return consumerFixture{ + directory: directory, + packageDirectory: packageDirectory, + configPath: configPath, + fixturePath: filepath.Join(directory, "fixture.ts"), + } +} + +func biomeFormat(t *testing.T, f consumerFixture) processResult { + t.Helper() + return runProcess(t, f.directory, nil, "biome", "format", "--write", "--config-path", f.configPath, f.fixturePath) +} + +func biomeCI(t *testing.T, f consumerFixture) processResult { + t.Helper() + return runProcess(t, f.directory, nil, "biome", "ci", "--config-path", f.configPath, ".") +} + +// isBiomePreset reports whether value has the preset fields the tests read. +func isBiomePreset(value map[string]any) bool { + formatter, ok := value["formatter"].(map[string]any) + if !ok { + return false + } + if _, ok := formatter["indentStyle"].(string); !ok { + return false + } + linter, ok := value["linter"].(map[string]any) + if !ok { + return false + } + if _, ok := linter["enabled"].(bool); !ok { + return false + } + rules, ok := linter["rules"].(map[string]any) + if !ok { + return false + } + _, ok = rules["preset"].(string) + return ok +} + +func parseBiomePreset(t *testing.T, source string) map[string]any { + t.Helper() + var value map[string]any + err := json.Unmarshal([]byte(source), &value) + if err != nil { + t.Fatalf("parse Biome preset: %v", err) + } + if !isBiomePreset(value) { + t.Fatal("Invalid Biome preset fixture") + } + return value +} + +func TestSharedConfigurationPackages(t *testing.T) { + t.Run("Node resolves both exported config subpaths", func(t *testing.T) { + root := filepath.Dir(moduleRoot(t)) + // Node reports realpaths, and macOS temp dirs sit behind a symlink. + directory, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + tsconfigDirectory := filepath.Join(directory, "node_modules", "@rigelbuild", "tsconfig") + biomeDirectory := filepath.Join(directory, "node_modules", "@rigelbuild", "biome-config") + copyPackage(t, filepath.Join(root, "packages", "tsconfig"), tsconfigDirectory, "package.json", "base.json") + copyPackage(t, filepath.Join(root, "packages", "biome-config"), biomeDirectory, "package.json", "biome.json") + script := `console.log(import.meta.resolve("@rigelbuild/tsconfig/base.json")); ` + + `console.log(import.meta.resolve("@rigelbuild/biome-config/biome"))` + result := runProcess(t, directory, nil, "node", "--input-type=module", "-e", script) + if result.status != 0 { + t.Fatalf("node exit = %d: %s", result.status, result.stderr) + } + lines := strings.Split(jstext.Trim(result.stdout), "\n") + got := make([]string, 0, len(lines)) + for _, line := range lines { + parsed, err := url.Parse(line) + if err != nil { + t.Fatal(err) + } + got = append(got, parsed.Path) + } + want := []string{ + filepath.Join(tsconfigDirectory, "base.json"), + filepath.Join(biomeDirectory, "biome.json"), + } + if !slices.Equal(got, want) { + t.Fatalf("resolved %q, want %q", got, want) + } + }) + + t.Run("Node rejects the Biome subpath when its export key is removed", func(t *testing.T) { + f := newConsumerFixture(t) + manifestPath := filepath.Join(f.packageDirectory, "package.json") + originalManifest := readFixtureFile(t, manifestPath) + manifestWithoutBiomeExport := strings.Replace(originalManifest, + `"./biome": "./biome.json"`, `"./other": "./biome.json"`, 1) + if manifestWithoutBiomeExport == originalManifest { + t.Fatal("manifest has no ./biome export to remove") + } + writeFixtureFile(t, manifestPath, manifestWithoutBiomeExport) + resolverPath := filepath.Join(f.directory, "resolve.mjs") + writeFixtureFile(t, resolverPath, "import.meta.resolve(\"@rigelbuild/biome-config/biome\");\n") + + result := runProcess(t, f.directory, nil, "node", resolverPath) + if result.status == 0 { + t.Fatal("node resolved the removed ./biome export") + } + if !strings.Contains(result.stderr, "ERR_PACKAGE_PATH_NOT_EXPORTED") { + t.Fatalf("stderr = %q, want ERR_PACKAGE_PATH_NOT_EXPORTED", result.stderr) + } + }) + + t.Run("shared preset preserves tabs and converts spaces to tabs", func(t *testing.T) { + f := newConsumerFixture(t) + tabInput := "export const preset = {\n\tshared: true,\n};\n" + writeFixtureFile(t, f.fixturePath, tabInput) + tabResult := biomeFormat(t, f) + if tabResult.status != 0 { + t.Fatalf("biome format exit = %d: %s", tabResult.status, tabResult.stderr) + } + if got := readFixtureFile(t, f.fixturePath); got != tabInput { + t.Fatalf("tab input formatted to %q, want %q", got, tabInput) + } + + writeFixtureFile(t, f.fixturePath, "export const preset = {\n shared: true,\n};\n") + spaceResult := biomeFormat(t, f) + if spaceResult.status != 0 { + t.Fatalf("biome format exit = %d: %s", spaceResult.status, spaceResult.stderr) + } + if got := readFixtureFile(t, f.fixturePath); got != tabInput { + t.Fatalf("space input formatted to %q, want %q", got, tabInput) + } + }) + + t.Run("removing preset indentStyle restores the earlier space setting", func(t *testing.T) { + f := newConsumerFixture(t) + presetPath := filepath.Join(f.packageDirectory, "biome.json") + preset := parseBiomePreset(t, readFixtureFile(t, presetPath)) + withoutFormatter := maps.Clone(preset) + delete(withoutFormatter, "formatter") + if reflect.DeepEqual(withoutFormatter, preset) { + t.Fatal("removing the formatter left the preset unchanged") + } + tabInput := "export const preset = {\n\tshared: true,\n};\n" + writeFixtureFile(t, f.fixturePath, tabInput) + encoded, err := json.MarshalIndent(withoutFormatter, "", "\t") + if err != nil { + t.Fatal(err) + } + writeFixtureFile(t, presetPath, string(encoded)+"\n") + + result := biomeFormat(t, f) + if result.status != 0 { + t.Fatalf("biome format exit = %d: %s", result.status, result.stderr) + } + formatted := readFixtureFile(t, f.fixturePath) + if formatted == tabInput { + t.Fatal("formatting kept tabs after the preset indentStyle was removed") + } + if !strings.Contains(formatted, " shared: true") { + t.Fatalf("formatted = %q, want two-space indent", formatted) + } + }) + + t.Run("Biome CI accepts a consumer fixture extending the shared preset", func(t *testing.T) { + f := newConsumerFixture(t) + writeFixtureFile(t, f.fixturePath, "export const preset = {\n\tshared: true,\n};\n") + result := biomeCI(t, f) + if result.status != 0 { + t.Fatalf("biome ci exit = %d: %s%s", result.status, result.stdout, result.stderr) + } + }) + + t.Run("a consumer extending the preset skips gitignored files", func(t *testing.T) { + f := newConsumerFixture(t) + writeFixtureFile(t, f.configPath, + "{\n\t\"root\": true,\n\t\"extends\": [\"@rigelbuild/biome-config/biome\"]\n}\n") + writeFixtureFile(t, f.fixturePath, "export const ok = true;\n") + generated := filepath.Join(f.directory, "generated") + err := os.Mkdir(generated, 0o755) + if err != nil { + t.Fatal(err) + } + writeFixtureFile(t, filepath.Join(generated, "bad.ts"), "export const bad = 1\n") + result := biomeCI(t, f) + if result.status != 0 { + t.Fatalf("biome ci exit = %d: %s%s", result.status, result.stdout, result.stderr) + } + }) + + t.Run("Biome CI rejects debugger under recommended lint rules", func(t *testing.T) { + f := newConsumerFixture(t) + writeFixtureFile(t, f.fixturePath, "debugger;\n") + if result := biomeCI(t, f); result.status == 0 { + t.Fatal("biome ci accepted debugger") + } + writeFixtureFile(t, f.fixturePath, "const ready = true;\n") + result := biomeCI(t, f) + if result.status != 0 { + t.Fatalf("biome ci exit = %d: %s%s", result.status, result.stdout, result.stderr) + } + }) +} diff --git a/moon.yml b/moon.yml index ad04605..f41db64 100644 --- a/moon.yml +++ b/moon.yml @@ -13,7 +13,6 @@ tasks: lint: command: "biome check ." - deps: ["install"] options: cache: false runFromWorkspaceRoot: true @@ -40,12 +39,17 @@ tasks: runFromWorkspaceRoot: true test: - command: "bun test package-bins.test.ts rumdl-extends.test.ts tools/release/publish.test.ts shared-configs.test.ts" + deps: ["go:test"] + options: + runFromWorkspaceRoot: true + + publish-test: + command: "bun test tools/release/publish.test.ts" deps: ["install"] options: runFromWorkspaceRoot: true ci: - deps: ["lint", "markdownlint", "refgate", "test"] + deps: ["lint", "markdownlint", "refgate", "test", "publish-test"] options: cache: false diff --git a/package-bins.test.ts b/package-bins.test.ts deleted file mode 100644 index 8c9f990..0000000 --- a/package-bins.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { readdirSync, readFileSync } from "node:fs"; -import { join } from "node:path"; - -const PACKAGES = "packages"; - -function declaredBins(manifest: { bin?: unknown }): string[] { - const bin = manifest.bin; - if (bin === undefined) return []; - if (typeof bin === "string") return [bin]; - return Object.values(bin as Record); -} - -const declared = readdirSync(PACKAGES, { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .flatMap((entry) => - declaredBins( - JSON.parse( - readFileSync(join(PACKAGES, entry.name, "package.json"), "utf8"), - ), - ).map((bin) => ({ pkg: entry.name, bin })), - ); -const bins = declared.map(({ pkg, bin }) => join(PACKAGES, pkg, bin)); - -// A bin without a shebang fails with ENOEXEC when run from node_modules/.bin. -describe("package bins", () => { - test("reads string, object, and absent bin declarations", () => { - expect(declaredBins({ bin: "./cli.ts" })).toEqual(["./cli.ts"]); - expect(declaredBins({ bin: { a: "./a.ts", b: "./b.ts" } })).toEqual([ - "./a.ts", - "./b.ts", - ]); - expect(declaredBins({})).toEqual([]); - }); - - test("at least one package declares a bin", () => { - expect(bins.length).toBeGreaterThan(0); - }); - - test.each(bins)("%s starts with the bun shebang", (path) => { - expect(readFileSync(path, "utf8").split("\n", 1)[0]).toBe( - "#!/usr/bin/env bun", - ); - }); - - // npm publish rewrites a "./" bin path and warns; keep manifests in the form npm publishes. - test.each(declared)("$pkg bin $bin is npm-normalized", ({ bin }) => { - expect(bin.startsWith("./")).toBe(false); - }); -}); diff --git a/rumdl-extends.test.ts b/rumdl-extends.test.ts deleted file mode 100644 index d4f2493..0000000 --- a/rumdl-extends.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { afterEach, describe, expect, test } from "bun:test"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; - -const directories: string[] = []; -const baseConfig = process.env.RUMDL_BASE_CONFIG; -const rumdl = process.env.RUMDL_BIN; -const pathRumdl = Bun.which("rumdl"); - -if (!baseConfig) throw new Error("RUMDL_BASE_CONFIG is not set"); -if (!rumdl) throw new Error("RUMDL_BIN is not set"); -if (pathRumdl !== rumdl) { - throw new Error(`PATH rumdl (${pathRumdl ?? "not found"}) does not match RUMDL_BIN`); -} - -async function checkWithConfig(config: string): Promise<{ status: number; output: string }> { - const directory = await mkdtemp(join(tmpdir(), "meissa-rumdl-extends-")); - directories.push(directory); - const configPath = join(directory, ".rumdl.toml"); - const markdownPath = join(directory, "headingless.md"); - await writeFile(configPath, config); - const paragraph = "A paragraph whose length exceeds the default maximum line width without violating other default rules. ".repeat(2).trimEnd(); - await writeFile(markdownPath, `${paragraph}\n`); - - const result = Bun.spawnSync( - [rumdl, "check", "--no-cache", "--config", configPath, markdownPath], - { - cwd: directory, - env: { ...process.env, RUMDL_BASE_CONFIG: baseConfig }, - stdout: "pipe", - stderr: "pipe", - }, - ); - return { - status: result.exitCode ?? 1, - output: `${result.stdout.toString()}${result.stderr.toString()}`, - }; -} - -afterEach(async () => { - await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))); -}); - -describe("shared rumdl policy inheritance", () => { - test("extends inherits disabled MD013 for a long heading-less paragraph", async () => { - const result = await checkWithConfig('extends = "$RUMDL_BASE_CONFIG"\n\n[MD041]\nenabled = false\n'); - expect(result.status).toBe(0); - }); - - test("the heading-less control without extends reports MD013", async () => { - const result = await checkWithConfig("[MD041]\nenabled = false\n"); - expect(result.status).toBe(1); - expect(result.output).toContain("MD013"); - }); -}); diff --git a/shared-configs.test.ts b/shared-configs.test.ts deleted file mode 100644 index 89cc7e1..0000000 --- a/shared-configs.test.ts +++ /dev/null @@ -1,286 +0,0 @@ -import { afterAll, describe, expect, test } from "bun:test"; -import { - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { fileURLToPath } from "node:url"; - -const temporaryDirectories: string[] = []; - -type BiomePreset = { - [key: string]: unknown; - formatter: { [key: string]: unknown; indentStyle: string }; - linter: { - enabled: boolean; - rules: { preset: string }; - }; -}; - -function isBiomePreset(value: unknown): value is BiomePreset { - return ( - typeof value === "object" && - value !== null && - "formatter" in value && - typeof value.formatter === "object" && - value.formatter !== null && - "indentStyle" in value.formatter && - typeof value.formatter.indentStyle === "string" && - "linter" in value && - typeof value.linter === "object" && - value.linter !== null && - "enabled" in value.linter && - typeof value.linter.enabled === "boolean" && - "rules" in value.linter && - typeof value.linter.rules === "object" && - value.linter.rules !== null && - "preset" in value.linter.rules && - typeof value.linter.rules.preset === "string" - ); -} - -function parseBiomePreset(source: string): BiomePreset { - const value: unknown = JSON.parse(source); - if (!isBiomePreset(value)) throw new Error("Invalid Biome preset fixture"); - return value; -} - -function consumerFixture(prefix: string) { - const directory = mkdtempSync(join(tmpdir(), prefix)); - temporaryDirectories.push(directory); - // The preset enables VCS ignore files, so a consumer fixture must be a git repo. - Bun.spawnSync({ cmd: ["git", "init", "-q", directory] }); - writeFileSync(join(directory, ".gitignore"), "node_modules/\ngenerated/\n"); - const packageDirectory = join( - directory, - "node_modules", - "@rigelbuild", - "biome-config", - ); - mkdirSync(packageDirectory, { recursive: true }); - const sourceDirectory = join(import.meta.dir, "packages", "biome-config"); - for (const filename of ["package.json", "biome.json"]) { - writeFileSync( - join(packageDirectory, filename), - readFileSync(join(sourceDirectory, filename)), - ); - } - const configPath = join(directory, "biome.json"); - const spaceConfigPath = join(directory, "space.json"); - const fixturePath = join(directory, "fixture.ts"); - writeFileSync( - configPath, - '{\n\t"root": true,\n\t"extends": ["./space.json", "@rigelbuild/biome-config/biome"]\n}\n', - ); - writeFileSync( - spaceConfigPath, - '{\n\t"root": false,\n\t"formatter": { "indentStyle": "space" }\n}\n', - ); - return { directory, packageDirectory, configPath, fixturePath }; -} - -afterAll(() => { - for (const directory of temporaryDirectories) { - rmSync(directory, { recursive: true, force: true }); - } -}); - -describe("shared configuration packages", () => { - test("Node resolves both exported config subpaths", () => { - const result = Bun.spawnSync({ - cmd: [ - "node", - "--input-type=module", - "-e", - 'console.log(import.meta.resolve("@rigelbuild/tsconfig/base.json")); console.log(import.meta.resolve("@rigelbuild/biome-config/biome"))', - ], - cwd: import.meta.dir, - stdout: "pipe", - stderr: "pipe", - }); - expect(result.exitCode).toBe(0); - const urls = new TextDecoder() - .decode(result.stdout) - .trim() - .split("\n") - .map(fileURLToPath); - expect(urls).toEqual([ - join(import.meta.dir, "packages", "tsconfig", "base.json"), - join(import.meta.dir, "packages", "biome-config", "biome.json"), - ]); - }); - - test("Node rejects the Biome subpath when its export key is removed", () => { - const { directory, packageDirectory } = consumerFixture( - "meissa-biome-export-", - ); - const manifestPath = join(packageDirectory, "package.json"); - const originalManifest = readFileSync(manifestPath, "utf8"); - const manifestWithoutBiomeExport = originalManifest.replace( - '"./biome": "./biome.json"', - '"./other": "./biome.json"', - ); - expect(manifestWithoutBiomeExport).not.toBe(originalManifest); - writeFileSync(manifestPath, manifestWithoutBiomeExport); - const resolverPath = join(directory, "resolve.mjs"); - writeFileSync( - resolverPath, - 'import.meta.resolve("@rigelbuild/biome-config/biome");\n', - ); - - const result = Bun.spawnSync({ - cmd: ["node", resolverPath], - cwd: directory, - stdout: "pipe", - stderr: "pipe", - }); - expect(result.exitCode).not.toBe(0); - expect(new TextDecoder().decode(result.stderr)).toContain( - "ERR_PACKAGE_PATH_NOT_EXPORTED", - ); - }); - - test("shared preset preserves tabs and converts spaces to tabs", () => { - const { directory, configPath, fixturePath } = consumerFixture( - "meissa-biome-format-", - ); - const tabInput = "export const preset = {\n\tshared: true,\n};\n"; - writeFileSync(fixturePath, tabInput); - - const tabResult = Bun.spawnSync({ - cmd: [ - "biome", - "format", - "--write", - "--config-path", - configPath, - fixturePath, - ], - cwd: directory, - stdout: "pipe", - stderr: "pipe", - }); - expect(tabResult.exitCode).toBe(0); - expect(readFileSync(fixturePath, "utf8")).toBe(tabInput); - - writeFileSync( - fixturePath, - "export const preset = {\n shared: true,\n};\n", - ); - const spaceResult = Bun.spawnSync({ - cmd: [ - "biome", - "format", - "--write", - "--config-path", - configPath, - fixturePath, - ], - cwd: directory, - stdout: "pipe", - stderr: "pipe", - }); - expect(spaceResult.exitCode).toBe(0); - expect(readFileSync(fixturePath, "utf8")).toBe(tabInput); - }); - - test("removing preset indentStyle restores the earlier space setting", () => { - const { directory, packageDirectory, configPath, fixturePath } = - consumerFixture("meissa-biome-format-mutation-"); - const presetPath = join(packageDirectory, "biome.json"); - const originalPreset = readFileSync(presetPath, "utf8"); - const parsedPreset = parseBiomePreset(originalPreset); - const presetWithTabs = parsedPreset; - const { formatter: _formatter, ...presetWithoutIndentStyle } = - presetWithTabs; - expect(presetWithoutIndentStyle).not.toEqual(presetWithTabs); - const tabInput = "export const preset = {\n\tshared: true,\n};\n"; - writeFileSync(fixturePath, tabInput); - writeFileSync( - presetPath, - `${JSON.stringify(presetWithoutIndentStyle, null, "\t")}\n`, - ); - const formatResult = Bun.spawnSync({ - cmd: [ - "biome", - "format", - "--write", - "--config-path", - configPath, - fixturePath, - ], - cwd: directory, - stdout: "pipe", - stderr: "pipe", - }); - expect(formatResult.exitCode).toBe(0); - const formatted = readFileSync(fixturePath, "utf8"); - expect(formatted).not.toBe(tabInput); - expect(formatted).toContain(" shared: true"); - }); - - test("Biome CI accepts a consumer fixture extending the shared preset", () => { - const { directory, configPath, fixturePath } = consumerFixture( - "meissa-biome-preset-", - ); - writeFileSync( - fixturePath, - "export const preset = {\n\tshared: true,\n};\n", - ); - - const result = Bun.spawnSync({ - cmd: ["biome", "ci", "--config-path", configPath, "."], - cwd: directory, - stdout: "pipe", - stderr: "pipe", - }); - expect(result.exitCode).toBe(0); - }); - - test("a consumer extending the preset skips gitignored files", () => { - const { directory, configPath, fixturePath } = - consumerFixture("meissa-biome-vcs-"); - writeFileSync( - configPath, - '{\n\t"root": true,\n\t"extends": ["@rigelbuild/biome-config/biome"]\n}\n', - ); - writeFileSync(fixturePath, "export const ok = true;\n"); - mkdirSync(join(directory, "generated")); - writeFileSync( - join(directory, "generated", "bad.ts"), - "export const bad = 1\n", - ); - const result = Bun.spawnSync({ - cmd: ["biome", "ci", "--config-path", configPath, "."], - cwd: directory, - stdout: "pipe", - stderr: "pipe", - }); - expect(result.exitCode).toBe(0); - }); - test("Biome CI rejects debugger under recommended lint rules", () => { - const { directory, configPath, fixturePath } = consumerFixture( - "meissa-biome-recommended-rule-", - ); - writeFileSync(fixturePath, "debugger;\n"); - const invalidResult = Bun.spawnSync({ - cmd: ["biome", "ci", "--config-path", configPath, "."], - cwd: directory, - stdout: "pipe", - stderr: "pipe", - }); - expect(invalidResult.exitCode).not.toBe(0); - writeFileSync(fixturePath, "const ready = true;\n"); - const validResult = Bun.spawnSync({ - cmd: ["biome", "ci", "--config-path", configPath, "."], - cwd: directory, - stdout: "pipe", - stderr: "pipe", - }); - expect(validResult.exitCode).toBe(0); - }); -});