๐Ÿ“ฆ colinhacks / zshy

๐Ÿ“„ zshy.test.ts ยท 261 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261import { spawnSync } from "node:child_process";
import { existsSync, readFileSync, rmSync } from "node:fs";
import { afterEach, beforeEach, describe, expect, it } from "vitest";

describe("zshy with different tsconfig configurations", () => {
  beforeEach(() => {
    // Clean up any existing output directories
    const outputDirs = ["dist", "build", "lib", "output", "types"];
    outputDirs.forEach((dir) => {
      if (existsSync(dir)) {
        rmSync(dir, { recursive: true, force: true });
      }
    });

    // Clean up any generated JS/declaration files in root
    const rootFiles = [
      "index.js",
      "index.d.ts",
      "index.d.ts.map",
      "index.cjs",
      "index.d.cts",
      "index.d.cts.map",
      "index.mjs",
      "index.d.mts",
      "index.d.mts.map",
      "utils.js",
      "utils.d.ts",
      "utils.d.ts.map",
      "utils.cjs",
      "utils.d.cts",
      "utils.d.cts.map",
      "utils.mjs",
      "utils.d.mts",
      "utils.d.mts.map",
      "plugins",
    ];
    rootFiles.forEach((file) => {
      // check is file or directory, then unlink
      if (existsSync(file)) {
        if (file === "plugins") {
          rmSync(file, { recursive: true, force: true });
        } else {
          rmSync(file, { force: true });
        }
      }
    });
  });

  afterEach(() => {
    // Clean up after each test
    const outputDirs = ["dist", "build", "lib", "output", "types"];
    outputDirs.forEach((dir) => {
      if (existsSync(dir)) {
        rmSync(dir, { recursive: true, force: true });
      }
    });
  });

  // Helper function to run zshy with a specific tsconfig
  const runZshyWithTsconfig = (tsconfigFile: string, opts: { dryRun: boolean; cwd: string }) => {
    let stdout = "";
    let stderr = "";
    let exitCode = 0;

    try {
      // Run zshy using tsx with --project flag in verbose mode and dry-run from test directory
      const args = ["../../src/index.ts", "--project", `./${tsconfigFile}`, "--verbose"];
      if (opts.dryRun) {
        args.push("--dry-run");
      }

      const result = spawnSync("tsx", args, {
        shell: true,
        encoding: "utf8",
        timeout: 30000, // Increase timeout for CI
        cwd: opts.cwd, // Use relative path that works in CI
        env: {
          ...process.env,
          // Force UTF-8 encoding
          LC_ALL: "C.UTF-8",
          LANG: "C.UTF-8",
        },
      });

      stdout = result.stdout || "";
      stderr = result.stderr || "";
      exitCode = result.status || 0;

      // Handle spawn errors
      if (result.error) {
        stderr = result.error.message;
        exitCode = 1;
      }
    } catch (error: any) {
      stderr = error.message || "";
      exitCode = 1;
    }

    // Combine stdout and stderr for comprehensive output capture
    const combinedOutput = [stdout, stderr].filter(Boolean).join("\n");

    // Debug logging for CI issues
    if (process.env.CI && !combinedOutput.trim()) {
      console.log("DEBUG - No output captured:");
      console.log("Exit code:", exitCode);
      console.log("Stdout length:", stdout.length);
      console.log("Stderr length:", stderr.length);
      console.log("Combined output length:", combinedOutput.length);
      console.log("Working directory:", process.cwd());
    }

    return {
      exitCode,
      stdout: normalizeOutput(combinedOutput),
      stderr: normalizeOutput(stderr),
    };
  };

  it("should work with basic.test.tsconfig.json", () => {
    // only run this one with dryRun: false
    // results are tracked in git
    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd: process.cwd() + "/test/basic",
    });

    expect(snapshot).toMatchSnapshot();
  });

  it("should work with custom outDir and declarationDir", () => {
    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd: process.cwd() + "/test/custom-paths",
    });
    expect(snapshot).toMatchSnapshot();
  });

  it("should work with flat build (outDir: '.')", () => {
    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd: process.cwd() + "/test/flat",
    });
    expect(snapshot).toMatchSnapshot();
  });

  it("should not edit package.json when noEdit is true", () => {
    const cwd = process.cwd() + "/test/no-edit-package-json";
    const packageJsonPath = cwd + "/package.json";
    const originalPackageJson = readFileSync(packageJsonPath, "utf-8");

    const snapshot = runZshyWithTsconfig("tsconfig.json", { dryRun: false, cwd });

    const newPackageJson = readFileSync(packageJsonPath, "utf-8");
    expect(newPackageJson).toEqual(originalPackageJson);
    expect(snapshot).toMatchSnapshot();
  });

  it("should work with custom conditions", () => {
    // Run from the custom-conditions directory
    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd: process.cwd() + "/test/custom-conditions",
    });
    expect(snapshot).toMatchSnapshot();
  });

  it("should skip CJS build when commonjs is false", () => {
    // Run from the esm-only directory
    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd: process.cwd() + "/test/esm-only",
    });
    expect(snapshot).toMatchSnapshot();
  });

  it("should copy exports to jsr.json when jsr.json exists", () => {
    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd: process.cwd() + "/test/jsr",
    });
    expect(snapshot).toMatchSnapshot();
  });

  it("should support multiple bin entries", () => {
    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd: process.cwd() + "/test/multi-bin",
    });
    expect(snapshot).toMatchSnapshot();
  });

  it("should support bin without exports (should not overwrite existing exports)", () => {
    const cwd = process.cwd() + "/test/bin";
    const packageJsonPath = cwd + "/package.json";
    
    // Read original exports field
    const originalPackageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
    const originalExports = originalPackageJson.exports;

    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd,
    });

    // Verify exports were not modified
    const newPackageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
    expect(newPackageJson.exports).toEqual(originalExports);
    
    // Verify bin was updated
    expect(newPackageJson.bin).toBe("./dist/cli.cjs");
    
    expect(snapshot).toMatchSnapshot();
  });

  it("should support tsconfig paths aliases with at-sign", () => {
    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd: process.cwd() + "/test/tsconfig-paths",
    });
    expect(snapshot).toMatchSnapshot();
  });

  it("should reproduce issue #53 - test files in __tests__ directories are included in build", () => {
    const snapshot = runZshyWithTsconfig("tsconfig.json", {
      dryRun: false,
      cwd: process.cwd() + "/test/ignore-tests",
    });
    expect(snapshot).toMatchSnapshot();
  });
});

function normalizeOutput(output: string): string {
  const slashPattern = /[\\/]+/g;
  return (
    output
      // Loosely normalize path sep to `/`. Note that we also normalize double
      // escaped backslashes since we `JSON.stringify` some paths in the output.
      .replaceAll(slashPattern, "/")
      .replaceAll(process.cwd().replaceAll(slashPattern, "/"), "<root>")
      // Normalize timestamps and timing info
      .replace(/\d+ms/g, "<time>")
      // Normalize any specific file counts that might vary
      // .replace(/\(\d+ matches\)/g, "(<count> matches)")
      .replace(/Detected package manager: [^\n]+/g, "Detected package manager: <pm>")
      // Remove any ANSI color codes
      // biome-ignore lint: intentional
      .replace(/\u001b\[[0-9;]*m/g, "")
      // Remove emoji characters that cause encoding issues in CI
      .replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, "")
      // Remove specific Unicode symbols that might cause issues
      .replace(/๐Ÿ’Ž|๐Ÿงฑ|๐ŸŽ‰|โš™๏ธ|๐Ÿ“ฆ|๐Ÿ“|๐Ÿ—‘๏ธ|โžก๏ธ|๐Ÿ”ง|๐ŸŸจ|๐Ÿข|๐Ÿ“œ|๐Ÿ”|โš ๏ธ/gu, "")
      // Normalize line endings
      .replace(/\r\n/g, "\n")
      // Trim trailing whitespace
      .split("\n")
      .map((line) => line.trimEnd())
      .join("\n")
      .trim()
  );
}