@terreno/test 57.17.0 → 57.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +1681 -0
  2. package/README.md +6 -0
  3. package/dist/assertions/expectAPIError.d.ts +18 -0
  4. package/dist/assertions/expectAPIError.js +33 -0
  5. package/dist/assertions/strictResponseProperties.d.ts +14 -0
  6. package/dist/assertions/strictResponseProperties.js +37 -0
  7. package/dist/cache/mongoTestCache.js +2 -2
  8. package/dist/cli/collectFiles.d.ts +38 -0
  9. package/dist/cli/collectFiles.js +73 -0
  10. package/dist/cli/testHygiene.d.ts +134 -0
  11. package/dist/cli/testHygiene.js +357 -0
  12. package/dist/cli/testHygieneCli.d.ts +2 -0
  13. package/dist/cli/testHygieneCli.js +5 -0
  14. package/dist/cli/testHygieneRules.d.ts +58 -0
  15. package/dist/cli/testHygieneRules.js +517 -0
  16. package/dist/cli/testShard.d.ts +155 -0
  17. package/dist/cli/testShard.js +377 -0
  18. package/dist/cli/testShardCli.d.ts +2 -0
  19. package/dist/cli/testShardCli.js +5 -0
  20. package/dist/expo/authTokenStorage.d.ts +76 -0
  21. package/dist/expo/authTokenStorage.js +160 -0
  22. package/dist/expo/expoModuleMocks.d.ts +24 -0
  23. package/dist/expo/expoModuleMocks.js +456 -0
  24. package/dist/expo/libraryModuleMocks.d.ts +17 -0
  25. package/dist/expo/libraryModuleMocks.js +347 -0
  26. package/dist/expo/mockHelpers.d.ts +39 -0
  27. package/dist/expo/mockHelpers.js +45 -0
  28. package/dist/expo/mockModuleAliases.d.ts +50 -0
  29. package/dist/expo/mockModuleAliases.js +174 -0
  30. package/dist/expo/reactNativeMock.d.ts +39 -0
  31. package/dist/expo/reactNativeMock.js +421 -0
  32. package/dist/expo/registerExpoTestEnvironment.d.ts +69 -0
  33. package/dist/expo/registerExpoTestEnvironment.js +163 -0
  34. package/dist/expo/renderWithTerreno.d.ts +47 -0
  35. package/dist/expo/renderWithTerreno.js +47 -0
  36. package/dist/http/authWithToken.d.ts +20 -0
  37. package/dist/http/authWithToken.js +30 -0
  38. package/dist/index.d.ts +14 -1
  39. package/dist/index.js +33 -1
  40. package/dist/logging/silenceLogs.js +0 -2
  41. package/dist/mocks/aiSdk.d.ts +77 -0
  42. package/dist/mocks/aiSdk.js +102 -0
  43. package/dist/mocks/cloudTasks.d.ts +91 -0
  44. package/dist/mocks/cloudTasks.js +197 -0
  45. package/dist/mocks/expoPush.d.ts +53 -0
  46. package/dist/mocks/expoPush.js +57 -0
  47. package/dist/mocks/gcs.d.ts +101 -0
  48. package/dist/mocks/gcs.js +162 -0
  49. package/dist/mocks/googleAuth.d.ts +69 -0
  50. package/dist/mocks/googleAuth.js +55 -0
  51. package/dist/mocks/mockGroup.d.ts +11 -0
  52. package/dist/mocks/mockGroup.js +21 -0
  53. package/dist/mocks/notifiers.d.ts +21 -0
  54. package/dist/mocks/notifiers.js +26 -0
  55. package/dist/mocks/sendgrid.d.ts +22 -0
  56. package/dist/mocks/sendgrid.js +32 -0
  57. package/dist/mocks/twilio.d.ts +72 -0
  58. package/dist/mocks/twilio.js +64 -0
  59. package/dist/preload/registerBackendPreload.js +4 -1
  60. package/dist/time/freezeTime.d.ts +16 -0
  61. package/dist/time/freezeTime.js +49 -0
  62. package/dist/transaction/testTransaction.d.ts +43 -6
  63. package/dist/transaction/testTransaction.js +371 -92
  64. package/dist/utils/waitUntil.d.ts +22 -0
  65. package/dist/utils/waitUntil.js +34 -0
  66. package/package.json +53 -8
  67. package/src/assertions/expectAPIError.ts +51 -0
  68. package/src/assertions/strictResponseProperties.ts +42 -0
  69. package/src/cache/mongoTestCache.ts +2 -2
  70. package/src/cli/collectFiles.ts +115 -0
  71. package/src/cli/testHygiene.ts +539 -0
  72. package/src/cli/testHygieneCli.ts +4 -0
  73. package/src/cli/testHygieneRules.ts +719 -0
  74. package/src/cli/testShard.ts +532 -0
  75. package/src/cli/testShardCli.ts +4 -0
  76. package/src/expo/authTokenStorage.ts +198 -0
  77. package/src/expo/expoModuleMocks.ts +503 -0
  78. package/src/expo/libraryModuleMocks.ts +411 -0
  79. package/src/expo/mockHelpers.ts +73 -0
  80. package/src/expo/mockModuleAliases.ts +252 -0
  81. package/src/expo/reactNativeMock.ts +534 -0
  82. package/src/expo/registerExpoTestEnvironment.ts +260 -0
  83. package/src/expo/renderWithTerreno.ts +79 -0
  84. package/src/http/authWithToken.ts +38 -0
  85. package/src/index.ts +82 -1
  86. package/src/logging/silenceLogs.ts +0 -2
  87. package/src/mocks/aiSdk.ts +199 -0
  88. package/src/mocks/cloudTasks.ts +323 -0
  89. package/src/mocks/expoPush.ts +134 -0
  90. package/src/mocks/gcs.ts +305 -0
  91. package/src/mocks/googleAuth.ts +136 -0
  92. package/src/mocks/mockGroup.ts +32 -0
  93. package/src/mocks/notifiers.ts +36 -0
  94. package/src/mocks/sendgrid.ts +57 -0
  95. package/src/mocks/twilio.ts +143 -0
  96. package/src/preload/registerBackendPreload.ts +4 -1
  97. package/src/time/freezeTime.ts +61 -0
  98. package/src/transaction/testTransaction.ts +456 -124
  99. package/src/utils/waitUntil.ts +47 -0
  100. package/biome.jsonc +0 -20
  101. package/bunfig.toml +0 -16
  102. package/src/cache/mongoTestCache.test.ts +0 -103
  103. package/src/env/setTerrenoTestEnv.test.ts +0 -26
  104. package/src/http/authAsUser.test.ts +0 -40
  105. package/src/http/getBaseServer.test.ts +0 -45
  106. package/src/logging/setupEnvironment.test.ts +0 -24
  107. package/src/logging/silenceLogs.test.ts +0 -52
  108. package/src/logging/testLogger.test.ts +0 -58
  109. package/src/mocks/sentryBun.test.ts +0 -230
  110. package/src/mongo/connection.test.ts +0 -43
  111. package/src/mongo/mongoServer.test.ts +0 -99
  112. package/src/preload/registerBackendPreload.test.ts +0 -10
  113. package/src/transaction/testTransaction.test.ts +0 -64
  114. package/src/utils/helpers.test.ts +0 -46
  115. package/tsconfig.json +0 -18
@@ -0,0 +1,532 @@
1
+ /**
2
+ * Splits test files into weight-balanced shards and runs one shard with `bun test`.
3
+ *
4
+ * Why: suites that share one database connection run sequentially inside a single Bun worker,
5
+ * so the only way to cut wall-clock time is to run disjoint subsets of files on separate CI
6
+ * machines. Shards are discovered by walking the filesystem, so a newly added test file is
7
+ * always picked up by exactly one shard instead of being silently skipped.
8
+ *
9
+ * Balancing: files are weighted by `lines + linesPerTest * testCount` and assigned heaviest
10
+ * first to the currently lightest shard (longest-processing-time-first). A file's runtime is
11
+ * roughly a fixed cost per test (server setup, auth, transaction open/abort) plus a cost that
12
+ * grows with how much its bodies do; neither term alone is a good proxy.
13
+ *
14
+ * Isolation: `mock.module()` is process-wide in Bun, so files that register (or are victims
15
+ * of) leaking module mocks can be moved into their own `bun test` process with `--isolate`,
16
+ * or every directory/file can get its own process with `--process-per`.
17
+ */
18
+ import {readFileSync} from "node:fs";
19
+ import path from "node:path";
20
+ import {parseArgs} from "node:util";
21
+
22
+ import {
23
+ collectFiles,
24
+ DEFAULT_EXCLUDED_DIRS,
25
+ DEFAULT_TEST_PATTERNS,
26
+ matchesAnyGlob,
27
+ } from "./collectFiles";
28
+
29
+ /** Lines of test code that cost about as much wall time as one test's fixed setup overhead. */
30
+ const DEFAULT_LINES_PER_TEST = 50;
31
+
32
+ const TEST_CALL_PATTERN = /^\s*(it|test)(\.\w+)*\s*\(/gm;
33
+
34
+ /** Process granularity for the files in one shard. */
35
+ const PROCESS_PER = {
36
+ dir: "dir",
37
+ file: "file",
38
+ shard: "shard",
39
+ } as const;
40
+
41
+ export type ProcessPer = (typeof PROCESS_PER)[keyof typeof PROCESS_PER];
42
+
43
+ interface WeightedFile {
44
+ file: string;
45
+ weight: number;
46
+ }
47
+
48
+ export interface Shard {
49
+ files: string[];
50
+ weight: number;
51
+ }
52
+
53
+ export interface ProcessGroup {
54
+ /** Label for progress and summary output. */
55
+ name: string;
56
+ /** `cwd`-relative POSIX paths run together in one `bun test` process. */
57
+ files: string[];
58
+ }
59
+
60
+ interface ProcessGroupResult {
61
+ group: ProcessGroup;
62
+ success: boolean;
63
+ durationMs: number;
64
+ }
65
+
66
+ export interface RunProcessGroupsOutcome {
67
+ results: ProcessGroupResult[];
68
+ /** Groups never started because an earlier group failed under `failFast`. */
69
+ skipped: ProcessGroup[];
70
+ allPassed: boolean;
71
+ }
72
+
73
+ /** Runs one command to completion and reports its exit code. Injectable for tests. */
74
+ export type SpawnCommand = (options: {cmd: string[]; cwd: string}) => {exitCode: number};
75
+
76
+ export interface CliLogger {
77
+ info: (message: string) => void;
78
+ error: (message: string) => void;
79
+ }
80
+
81
+ /** Counts `it(`/`test(` calls (including `.only`, `.each`, etc.) that start a line. */
82
+ export const countTests = ({source}: {source: string}): {testCount: number} => ({
83
+ testCount: (source.match(TEST_CALL_PATTERN) ?? []).length,
84
+ });
85
+
86
+ /** Estimates a file's relative runtime as `lines + linesPerTest * testCount`. */
87
+ export const estimateTestWeight = ({
88
+ source,
89
+ linesPerTest = DEFAULT_LINES_PER_TEST,
90
+ }: {
91
+ source: string;
92
+ linesPerTest?: number;
93
+ }): {weight: number} => {
94
+ const {testCount} = countTests({source});
95
+ return {weight: source.split("\n").length + linesPerTest * testCount};
96
+ };
97
+
98
+ /**
99
+ * Assigns files to `total` shards, heaviest first, always filling the lightest shard next. Ties
100
+ * break on file name and lowest shard index so every CI node computes the same assignment.
101
+ */
102
+ export const buildShards = ({files, total}: {files: WeightedFile[]; total: number}): Shard[] => {
103
+ const sorted = [...files].sort((a, b) => b.weight - a.weight || a.file.localeCompare(b.file));
104
+ const shards: Shard[] = Array.from({length: total}, () => ({files: [], weight: 0}));
105
+ for (const {file, weight} of sorted) {
106
+ let lightest = 0;
107
+ for (let i = 1; i < shards.length; i++) {
108
+ if (shards[i].weight < shards[lightest].weight) {
109
+ lightest = i;
110
+ }
111
+ }
112
+ shards[lightest].files.push(file);
113
+ shards[lightest].weight += weight;
114
+ }
115
+ for (const shard of shards) {
116
+ shard.files.sort();
117
+ }
118
+ return shards;
119
+ };
120
+
121
+ /** Parses a 1-based `<index>/<total>` shard spec such as `2/4`. */
122
+ export const parseShardSpec = ({
123
+ spec,
124
+ }: {
125
+ spec: string;
126
+ }): {index: number; total: number} | {error: string} => {
127
+ const match = spec.match(/^(\d+)\/(\d+)$/);
128
+ if (!match) {
129
+ return {error: `Invalid shard spec "${spec}"; expected <index>/<total>, e.g. 2/4`};
130
+ }
131
+ const index = Number(match[1]);
132
+ const total = Number(match[2]);
133
+ if (total < 1 || index < 1 || index > total) {
134
+ return {error: `Shard index ${index} is out of range for ${total} shard(s)`};
135
+ }
136
+ return {index, total};
137
+ };
138
+
139
+ const groupKeyForDir = ({file, dirDepth}: {file: string; dirDepth: number}): string => {
140
+ const segments = file.split("/").slice(0, -1);
141
+ if (segments.length === 0) {
142
+ return ".";
143
+ }
144
+ return segments.slice(0, dirDepth).join("/");
145
+ };
146
+
147
+ /**
148
+ * Splits one shard's files into `bun test` processes. Files matching an `isolate` glob always get
149
+ * a process of their own; the rest share one process (`shard`), one per directory prefix of
150
+ * `dirDepth` segments (`dir`), or one each (`file`).
151
+ */
152
+ export const planProcessGroups = ({
153
+ files,
154
+ processPer = PROCESS_PER.shard,
155
+ isolate = [],
156
+ dirDepth = 1,
157
+ }: {
158
+ files: string[];
159
+ processPer?: ProcessPer;
160
+ isolate?: readonly string[];
161
+ dirDepth?: number;
162
+ }): ProcessGroup[] => {
163
+ const isolated = files.filter((file) => matchesAnyGlob({filePath: file, globs: isolate}));
164
+ const isolatedSet = new Set(isolated);
165
+ const shared = files.filter((file) => !isolatedSet.has(file));
166
+ const groups: ProcessGroup[] = [];
167
+
168
+ if (processPer === PROCESS_PER.file) {
169
+ groups.push(...shared.map((file) => ({files: [file], name: file})));
170
+ } else if (processPer === PROCESS_PER.dir) {
171
+ const byDir = new Map<string, string[]>();
172
+ for (const file of shared) {
173
+ const key = groupKeyForDir({dirDepth, file});
174
+ byDir.set(key, [...(byDir.get(key) ?? []), file]);
175
+ }
176
+ for (const key of [...byDir.keys()].sort()) {
177
+ groups.push({files: byDir.get(key) ?? [], name: key});
178
+ }
179
+ } else if (shared.length > 0) {
180
+ groups.push({files: shared, name: "shared"});
181
+ }
182
+
183
+ groups.push(...isolated.map((file) => ({files: [file], name: `${file} (isolated)`})));
184
+ return groups;
185
+ };
186
+
187
+ /**
188
+ * Builds the `bun test` argv for a group. Paths are `./`-prefixed because Bun treats bare
189
+ * positional arguments as substring filters (a bare `tests` also matches every `__tests__`).
190
+ */
191
+ export const buildBunTestCommand = ({
192
+ files,
193
+ bunArgs = [],
194
+ }: {
195
+ files: string[];
196
+ bunArgs?: readonly string[];
197
+ }): {cmd: string[]} => ({
198
+ cmd: [
199
+ "bun",
200
+ "test",
201
+ ...bunArgs,
202
+ ...files.map((file) => (file.startsWith(".") || path.isAbsolute(file) ? file : `./${file}`)),
203
+ ],
204
+ });
205
+
206
+ const spawnWithBun: SpawnCommand = ({cmd, cwd}) => {
207
+ const proc = Bun.spawnSync({cmd, cwd, stdio: ["inherit", "inherit", "inherit"]});
208
+ return {exitCode: proc.exitCode ?? 1};
209
+ };
210
+
211
+ /** Runs each group in its own `bun test` process, optionally stopping at the first failure. */
212
+ export const runProcessGroups = ({
213
+ groups,
214
+ cwd,
215
+ bunArgs = [],
216
+ failFast = false,
217
+ spawn = spawnWithBun,
218
+ logger = console,
219
+ }: {
220
+ groups: ProcessGroup[];
221
+ cwd: string;
222
+ bunArgs?: readonly string[];
223
+ failFast?: boolean;
224
+ spawn?: SpawnCommand;
225
+ logger?: CliLogger;
226
+ }): RunProcessGroupsOutcome => {
227
+ const results: ProcessGroupResult[] = [];
228
+ for (const group of groups) {
229
+ if (groups.length > 1) {
230
+ logger.info(`\n=== ${group.name} (${group.files.length} file(s)) ===`);
231
+ }
232
+ const start = performance.now();
233
+ const {cmd} = buildBunTestCommand({bunArgs, files: group.files});
234
+ const {exitCode} = spawn({cmd, cwd});
235
+ const success = exitCode === 0;
236
+ results.push({durationMs: performance.now() - start, group, success});
237
+ if (!success && failFast) {
238
+ logger.error(`\n"${group.name}" failed; stopping (--fail-fast).`);
239
+ break;
240
+ }
241
+ }
242
+ const skipped = groups.slice(results.length);
243
+ return {
244
+ allPassed: skipped.length === 0 && results.every((result) => result.success),
245
+ results,
246
+ skipped,
247
+ };
248
+ };
249
+
250
+ /** Formats the PASS/FAIL/SKIP block printed after a multi-process run. */
251
+ export const formatRunSummary = ({results, skipped}: RunProcessGroupsOutcome): {text: string} => {
252
+ const lines = ["=== Summary ==="];
253
+ for (const result of results) {
254
+ const status = result.success ? "PASS" : "FAIL";
255
+ lines.push(`${status} ${result.group.name} (${(result.durationMs / 1000).toFixed(2)}s)`);
256
+ }
257
+ for (const group of skipped) {
258
+ lines.push(`SKIP ${group.name}`);
259
+ }
260
+ return {text: lines.join("\n")};
261
+ };
262
+
263
+ /** Reads newline-separated globs, ignoring blank lines and `#` comments. */
264
+ export const parseGlobList = ({text}: {text: string}): {globs: string[]} => ({
265
+ globs: text
266
+ .split("\n")
267
+ .map((line) => line.replace(/#.*$/, "").trim())
268
+ .filter((line) => line.length > 0),
269
+ });
270
+
271
+ const TEST_SHARD_USAGE = `Usage: terreno-test-shard [options] [<index>/<total>] [path ...] [-- <bun test args>]
272
+
273
+ Splits test files under the given paths (default ".") into weight-balanced shards and runs
274
+ one shard with \`bun test\`. Everything after a literal \`--\` is forwarded to \`bun test\`.
275
+
276
+ Options:
277
+ --shard <i>/<n> 1-based shard to run (default 1/1). May also be the first positional.
278
+ --list Print the shard's files and process groups without running them.
279
+ --pattern <glob> Test file glob relative to the cwd (repeatable).
280
+ Default: ${DEFAULT_TEST_PATTERNS.join(", ")}
281
+ --exclude <glob> Drop files matching this cwd-relative glob (repeatable).
282
+ --exclude-dir <name> Skip directories with this name at any depth (repeatable).
283
+ Added to: ${DEFAULT_EXCLUDED_DIRS.join(", ")}
284
+ --isolate <glob> Run matching files in their own process (repeatable).
285
+ --isolate-file <path> File of isolate globs, one per line, # comments allowed.
286
+ --process-per <mode> shard (default) | dir | file: process granularity for other files.
287
+ --dir-depth <n> Leading path segments that define a directory for --process-per dir
288
+ (default 1).
289
+ --lines-per-test <n> Weight of one test in lines (default ${DEFAULT_LINES_PER_TEST}).
290
+ --fail-fast Stop after the first failing process.
291
+ --cwd <dir> Directory paths and globs are relative to (default: process cwd).
292
+ -h, --help Show this help.
293
+
294
+ Exit code: the bun test result (1 if any process failed), 0 for an empty shard, or 1 when no
295
+ test files match at all (a silently empty run would let CI pass without running anything).`;
296
+
297
+ const isProcessPer = (value: string): value is ProcessPer =>
298
+ Object.values(PROCESS_PER).includes(value as ProcessPer);
299
+
300
+ const parsePositiveInt = ({value, flag}: {value: string; flag: string}): number | string => {
301
+ const parsed = Number(value);
302
+ if (!Number.isInteger(parsed) || parsed < 0) {
303
+ return `${flag} must be a non-negative integer, got "${value}"`;
304
+ }
305
+ return parsed;
306
+ };
307
+
308
+ export interface TestShardCliOptions {
309
+ shard: {index: number; total: number};
310
+ paths: string[];
311
+ patterns: string[];
312
+ exclude: string[];
313
+ excludeDirs: string[];
314
+ isolate: string[];
315
+ isolateFiles: string[];
316
+ processPer: ProcessPer;
317
+ dirDepth: number;
318
+ linesPerTest: number;
319
+ isListOnly: boolean;
320
+ failFast: boolean;
321
+ cwd: string;
322
+ bunArgs: string[];
323
+ isHelp: boolean;
324
+ }
325
+
326
+ interface ShardFlagValues {
327
+ cwd?: string;
328
+ "dir-depth"?: string;
329
+ exclude?: string[];
330
+ "exclude-dir"?: string[];
331
+ "fail-fast"?: boolean;
332
+ help?: boolean;
333
+ isolate?: string[];
334
+ "isolate-file"?: string[];
335
+ "lines-per-test"?: string;
336
+ list?: boolean;
337
+ pattern?: string[];
338
+ "process-per"?: string;
339
+ shard?: string;
340
+ }
341
+
342
+ /** Throws on unknown flags or missing flag values (strict mode). */
343
+ const parseCliFlags = (args: string[]): {values: ShardFlagValues; positionals: string[]} =>
344
+ parseArgs({
345
+ allowPositionals: true,
346
+ args,
347
+ options: {
348
+ cwd: {type: "string"},
349
+ "dir-depth": {type: "string"},
350
+ exclude: {multiple: true, type: "string"},
351
+ "exclude-dir": {multiple: true, type: "string"},
352
+ "fail-fast": {type: "boolean"},
353
+ help: {short: "h", type: "boolean"},
354
+ isolate: {multiple: true, type: "string"},
355
+ "isolate-file": {multiple: true, type: "string"},
356
+ "lines-per-test": {type: "string"},
357
+ list: {type: "boolean"},
358
+ pattern: {multiple: true, type: "string"},
359
+ "process-per": {type: "string"},
360
+ shard: {type: "string"},
361
+ },
362
+ strict: true,
363
+ });
364
+
365
+ /** Parses CLI arguments; returns `{error}` with a message on invalid input. */
366
+ export const parseTestShardArgs = ({
367
+ argv,
368
+ cwd,
369
+ }: {
370
+ argv: string[];
371
+ cwd: string;
372
+ }): {options: TestShardCliOptions} | {error: string} => {
373
+ const separatorIndex = argv.indexOf("--");
374
+ const ownArgs = separatorIndex === -1 ? argv : argv.slice(0, separatorIndex);
375
+ const bunArgs = separatorIndex === -1 ? [] : argv.slice(separatorIndex + 1);
376
+
377
+ let parsed: {values: ShardFlagValues; positionals: string[]};
378
+ try {
379
+ parsed = parseCliFlags(ownArgs);
380
+ } catch (error) {
381
+ return {error: (error as Error).message};
382
+ }
383
+ const {values, positionals} = parsed;
384
+
385
+ let shardSpec = values.shard;
386
+ const paths = [...positionals];
387
+ if (!shardSpec && paths.length > 0 && /^\d+\/\d+$/.test(paths[0])) {
388
+ shardSpec = paths.shift();
389
+ }
390
+ const shard = parseShardSpec({spec: shardSpec ?? "1/1"});
391
+ if ("error" in shard) {
392
+ return {error: shard.error};
393
+ }
394
+
395
+ const processPer = values["process-per"] ?? PROCESS_PER.shard;
396
+ if (!isProcessPer(processPer)) {
397
+ return {error: `--process-per must be one of shard, dir, file; got "${processPer}"`};
398
+ }
399
+ const dirDepth = parsePositiveInt({flag: "--dir-depth", value: values["dir-depth"] ?? "1"});
400
+ if (typeof dirDepth === "string") {
401
+ return {error: dirDepth};
402
+ }
403
+ const linesPerTest = parsePositiveInt({
404
+ flag: "--lines-per-test",
405
+ value: values["lines-per-test"] ?? String(DEFAULT_LINES_PER_TEST),
406
+ });
407
+ if (typeof linesPerTest === "string") {
408
+ return {error: linesPerTest};
409
+ }
410
+
411
+ return {
412
+ options: {
413
+ bunArgs,
414
+ cwd: path.resolve(cwd, values.cwd ?? "."),
415
+ dirDepth: Math.max(dirDepth, 1),
416
+ exclude: values.exclude ?? [],
417
+ excludeDirs: [...DEFAULT_EXCLUDED_DIRS, ...(values["exclude-dir"] ?? [])],
418
+ failFast: values["fail-fast"] ?? false,
419
+ isHelp: values.help ?? false,
420
+ isListOnly: values.list ?? false,
421
+ isolate: values.isolate ?? [],
422
+ isolateFiles: values["isolate-file"] ?? [],
423
+ linesPerTest,
424
+ paths: paths.length > 0 ? paths : ["."],
425
+ patterns: values.pattern ?? [...DEFAULT_TEST_PATTERNS],
426
+ processPer,
427
+ shard,
428
+ },
429
+ };
430
+ };
431
+
432
+ /**
433
+ * CLI entry point: discovers files, balances them into shards, prints the selected shard, and
434
+ * (unless `--list`) runs it. Returns the process exit code instead of exiting so it is testable.
435
+ */
436
+ export const runTestShardCli = ({
437
+ argv,
438
+ cwd = process.cwd(),
439
+ spawn = spawnWithBun,
440
+ logger = console,
441
+ }: {
442
+ argv: string[];
443
+ cwd?: string;
444
+ spawn?: SpawnCommand;
445
+ logger?: CliLogger;
446
+ }): {exitCode: number} => {
447
+ const parsed = parseTestShardArgs({argv, cwd});
448
+ if ("error" in parsed) {
449
+ logger.error(`${parsed.error}\n\n${TEST_SHARD_USAGE}`);
450
+ return {exitCode: 2};
451
+ }
452
+ const {options} = parsed;
453
+ if (options.isHelp) {
454
+ logger.info(TEST_SHARD_USAGE);
455
+ return {exitCode: 0};
456
+ }
457
+
458
+ const {files, missingPaths} = collectFiles({
459
+ cwd: options.cwd,
460
+ exclude: options.exclude,
461
+ excludeDirs: options.excludeDirs,
462
+ paths: options.paths,
463
+ patterns: options.patterns,
464
+ });
465
+ if (missingPaths.length > 0) {
466
+ logger.error(`Path(s) do not exist: ${missingPaths.join(", ")}`);
467
+ return {exitCode: 1};
468
+ }
469
+ if (files.length === 0) {
470
+ logger.error(
471
+ `No test files matching ${options.patterns.join(", ")} under: ${options.paths.join(", ")}`
472
+ );
473
+ return {exitCode: 1};
474
+ }
475
+
476
+ const isolate = [
477
+ ...options.isolate,
478
+ ...options.isolateFiles.flatMap(
479
+ (file) => parseGlobList({text: readFileSync(path.resolve(options.cwd, file), "utf-8")}).globs
480
+ ),
481
+ ];
482
+ const weighted = files.map((file) => ({
483
+ file,
484
+ weight: estimateTestWeight({
485
+ linesPerTest: options.linesPerTest,
486
+ source: readFileSync(path.join(options.cwd, file), "utf-8"),
487
+ }).weight,
488
+ }));
489
+ const shards = buildShards({files: weighted, total: options.shard.total});
490
+ const shard = shards[options.shard.index - 1];
491
+ const groups = planProcessGroups({
492
+ dirDepth: options.dirDepth,
493
+ files: shard.files,
494
+ isolate,
495
+ processPer: options.processPer,
496
+ });
497
+
498
+ logger.info(
499
+ `Shard ${options.shard.index}/${options.shard.total}: ${shard.files.length} of ${files.length} files, ` +
500
+ `weight ${shard.weight} (all shards: ${shards.map((s) => s.weight).join(", ")}), ` +
501
+ `${groups.length} process(es)`
502
+ );
503
+ for (const group of groups) {
504
+ if (groups.length > 1) {
505
+ logger.info(` [${group.name}]`);
506
+ }
507
+ for (const file of group.files) {
508
+ logger.info(` ${file}`);
509
+ }
510
+ }
511
+
512
+ if (options.isListOnly) {
513
+ return {exitCode: 0};
514
+ }
515
+ if (groups.length === 0) {
516
+ logger.info("Nothing to run for this shard.");
517
+ return {exitCode: 0};
518
+ }
519
+
520
+ const outcome = runProcessGroups({
521
+ bunArgs: options.bunArgs,
522
+ cwd: options.cwd,
523
+ failFast: options.failFast,
524
+ groups,
525
+ logger,
526
+ spawn,
527
+ });
528
+ if (groups.length > 1) {
529
+ logger.info(`\n${formatRunSummary(outcome).text}`);
530
+ }
531
+ return {exitCode: outcome.allPassed ? 0 : 1};
532
+ };
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bun
2
+ import {runTestShardCli} from "./testShard";
3
+
4
+ process.exitCode = runTestShardCli({argv: process.argv.slice(2)}).exitCode;