@terreno/test 57.18.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,377 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runTestShardCli = exports.parseTestShardArgs = exports.parseGlobList = exports.formatRunSummary = exports.runProcessGroups = exports.buildBunTestCommand = exports.planProcessGroups = exports.parseShardSpec = exports.buildShards = exports.estimateTestWeight = exports.countTests = void 0;
7
+ /**
8
+ * Splits test files into weight-balanced shards and runs one shard with `bun test`.
9
+ *
10
+ * Why: suites that share one database connection run sequentially inside a single Bun worker,
11
+ * so the only way to cut wall-clock time is to run disjoint subsets of files on separate CI
12
+ * machines. Shards are discovered by walking the filesystem, so a newly added test file is
13
+ * always picked up by exactly one shard instead of being silently skipped.
14
+ *
15
+ * Balancing: files are weighted by `lines + linesPerTest * testCount` and assigned heaviest
16
+ * first to the currently lightest shard (longest-processing-time-first). A file's runtime is
17
+ * roughly a fixed cost per test (server setup, auth, transaction open/abort) plus a cost that
18
+ * grows with how much its bodies do; neither term alone is a good proxy.
19
+ *
20
+ * Isolation: `mock.module()` is process-wide in Bun, so files that register (or are victims
21
+ * of) leaking module mocks can be moved into their own `bun test` process with `--isolate`,
22
+ * or every directory/file can get its own process with `--process-per`.
23
+ */
24
+ const node_fs_1 = require("node:fs");
25
+ const node_path_1 = __importDefault(require("node:path"));
26
+ const node_util_1 = require("node:util");
27
+ const collectFiles_1 = require("./collectFiles");
28
+ /** Lines of test code that cost about as much wall time as one test's fixed setup overhead. */
29
+ const DEFAULT_LINES_PER_TEST = 50;
30
+ const TEST_CALL_PATTERN = /^\s*(it|test)(\.\w+)*\s*\(/gm;
31
+ /** Process granularity for the files in one shard. */
32
+ const PROCESS_PER = {
33
+ dir: "dir",
34
+ file: "file",
35
+ shard: "shard",
36
+ };
37
+ /** Counts `it(`/`test(` calls (including `.only`, `.each`, etc.) that start a line. */
38
+ const countTests = ({ source }) => ({
39
+ testCount: (source.match(TEST_CALL_PATTERN) ?? []).length,
40
+ });
41
+ exports.countTests = countTests;
42
+ /** Estimates a file's relative runtime as `lines + linesPerTest * testCount`. */
43
+ const estimateTestWeight = ({ source, linesPerTest = DEFAULT_LINES_PER_TEST, }) => {
44
+ const { testCount } = (0, exports.countTests)({ source });
45
+ return { weight: source.split("\n").length + linesPerTest * testCount };
46
+ };
47
+ exports.estimateTestWeight = estimateTestWeight;
48
+ /**
49
+ * Assigns files to `total` shards, heaviest first, always filling the lightest shard next. Ties
50
+ * break on file name and lowest shard index so every CI node computes the same assignment.
51
+ */
52
+ const buildShards = ({ files, total }) => {
53
+ const sorted = [...files].sort((a, b) => b.weight - a.weight || a.file.localeCompare(b.file));
54
+ const shards = Array.from({ length: total }, () => ({ files: [], weight: 0 }));
55
+ for (const { file, weight } of sorted) {
56
+ let lightest = 0;
57
+ for (let i = 1; i < shards.length; i++) {
58
+ if (shards[i].weight < shards[lightest].weight) {
59
+ lightest = i;
60
+ }
61
+ }
62
+ shards[lightest].files.push(file);
63
+ shards[lightest].weight += weight;
64
+ }
65
+ for (const shard of shards) {
66
+ shard.files.sort();
67
+ }
68
+ return shards;
69
+ };
70
+ exports.buildShards = buildShards;
71
+ /** Parses a 1-based `<index>/<total>` shard spec such as `2/4`. */
72
+ const parseShardSpec = ({ spec, }) => {
73
+ const match = spec.match(/^(\d+)\/(\d+)$/);
74
+ if (!match) {
75
+ return { error: `Invalid shard spec "${spec}"; expected <index>/<total>, e.g. 2/4` };
76
+ }
77
+ const index = Number(match[1]);
78
+ const total = Number(match[2]);
79
+ if (total < 1 || index < 1 || index > total) {
80
+ return { error: `Shard index ${index} is out of range for ${total} shard(s)` };
81
+ }
82
+ return { index, total };
83
+ };
84
+ exports.parseShardSpec = parseShardSpec;
85
+ const groupKeyForDir = ({ file, dirDepth }) => {
86
+ const segments = file.split("/").slice(0, -1);
87
+ if (segments.length === 0) {
88
+ return ".";
89
+ }
90
+ return segments.slice(0, dirDepth).join("/");
91
+ };
92
+ /**
93
+ * Splits one shard's files into `bun test` processes. Files matching an `isolate` glob always get
94
+ * a process of their own; the rest share one process (`shard`), one per directory prefix of
95
+ * `dirDepth` segments (`dir`), or one each (`file`).
96
+ */
97
+ const planProcessGroups = ({ files, processPer = PROCESS_PER.shard, isolate = [], dirDepth = 1, }) => {
98
+ const isolated = files.filter((file) => (0, collectFiles_1.matchesAnyGlob)({ filePath: file, globs: isolate }));
99
+ const isolatedSet = new Set(isolated);
100
+ const shared = files.filter((file) => !isolatedSet.has(file));
101
+ const groups = [];
102
+ if (processPer === PROCESS_PER.file) {
103
+ groups.push(...shared.map((file) => ({ files: [file], name: file })));
104
+ }
105
+ else if (processPer === PROCESS_PER.dir) {
106
+ const byDir = new Map();
107
+ for (const file of shared) {
108
+ const key = groupKeyForDir({ dirDepth, file });
109
+ byDir.set(key, [...(byDir.get(key) ?? []), file]);
110
+ }
111
+ for (const key of [...byDir.keys()].sort()) {
112
+ groups.push({ files: byDir.get(key) ?? [], name: key });
113
+ }
114
+ }
115
+ else if (shared.length > 0) {
116
+ groups.push({ files: shared, name: "shared" });
117
+ }
118
+ groups.push(...isolated.map((file) => ({ files: [file], name: `${file} (isolated)` })));
119
+ return groups;
120
+ };
121
+ exports.planProcessGroups = planProcessGroups;
122
+ /**
123
+ * Builds the `bun test` argv for a group. Paths are `./`-prefixed because Bun treats bare
124
+ * positional arguments as substring filters (a bare `tests` also matches every `__tests__`).
125
+ */
126
+ const buildBunTestCommand = ({ files, bunArgs = [], }) => ({
127
+ cmd: [
128
+ "bun",
129
+ "test",
130
+ ...bunArgs,
131
+ ...files.map((file) => (file.startsWith(".") || node_path_1.default.isAbsolute(file) ? file : `./${file}`)),
132
+ ],
133
+ });
134
+ exports.buildBunTestCommand = buildBunTestCommand;
135
+ const spawnWithBun = ({ cmd, cwd }) => {
136
+ const proc = Bun.spawnSync({ cmd, cwd, stdio: ["inherit", "inherit", "inherit"] });
137
+ return { exitCode: proc.exitCode ?? 1 };
138
+ };
139
+ /** Runs each group in its own `bun test` process, optionally stopping at the first failure. */
140
+ const runProcessGroups = ({ groups, cwd, bunArgs = [], failFast = false, spawn = spawnWithBun, logger = console, }) => {
141
+ const results = [];
142
+ for (const group of groups) {
143
+ if (groups.length > 1) {
144
+ logger.info(`\n=== ${group.name} (${group.files.length} file(s)) ===`);
145
+ }
146
+ const start = performance.now();
147
+ const { cmd } = (0, exports.buildBunTestCommand)({ bunArgs, files: group.files });
148
+ const { exitCode } = spawn({ cmd, cwd });
149
+ const success = exitCode === 0;
150
+ results.push({ durationMs: performance.now() - start, group, success });
151
+ if (!success && failFast) {
152
+ logger.error(`\n"${group.name}" failed; stopping (--fail-fast).`);
153
+ break;
154
+ }
155
+ }
156
+ const skipped = groups.slice(results.length);
157
+ return {
158
+ allPassed: skipped.length === 0 && results.every((result) => result.success),
159
+ results,
160
+ skipped,
161
+ };
162
+ };
163
+ exports.runProcessGroups = runProcessGroups;
164
+ /** Formats the PASS/FAIL/SKIP block printed after a multi-process run. */
165
+ const formatRunSummary = ({ results, skipped }) => {
166
+ const lines = ["=== Summary ==="];
167
+ for (const result of results) {
168
+ const status = result.success ? "PASS" : "FAIL";
169
+ lines.push(`${status} ${result.group.name} (${(result.durationMs / 1000).toFixed(2)}s)`);
170
+ }
171
+ for (const group of skipped) {
172
+ lines.push(`SKIP ${group.name}`);
173
+ }
174
+ return { text: lines.join("\n") };
175
+ };
176
+ exports.formatRunSummary = formatRunSummary;
177
+ /** Reads newline-separated globs, ignoring blank lines and `#` comments. */
178
+ const parseGlobList = ({ text }) => ({
179
+ globs: text
180
+ .split("\n")
181
+ .map((line) => line.replace(/#.*$/, "").trim())
182
+ .filter((line) => line.length > 0),
183
+ });
184
+ exports.parseGlobList = parseGlobList;
185
+ const TEST_SHARD_USAGE = `Usage: terreno-test-shard [options] [<index>/<total>] [path ...] [-- <bun test args>]
186
+
187
+ Splits test files under the given paths (default ".") into weight-balanced shards and runs
188
+ one shard with \`bun test\`. Everything after a literal \`--\` is forwarded to \`bun test\`.
189
+
190
+ Options:
191
+ --shard <i>/<n> 1-based shard to run (default 1/1). May also be the first positional.
192
+ --list Print the shard's files and process groups without running them.
193
+ --pattern <glob> Test file glob relative to the cwd (repeatable).
194
+ Default: ${collectFiles_1.DEFAULT_TEST_PATTERNS.join(", ")}
195
+ --exclude <glob> Drop files matching this cwd-relative glob (repeatable).
196
+ --exclude-dir <name> Skip directories with this name at any depth (repeatable).
197
+ Added to: ${collectFiles_1.DEFAULT_EXCLUDED_DIRS.join(", ")}
198
+ --isolate <glob> Run matching files in their own process (repeatable).
199
+ --isolate-file <path> File of isolate globs, one per line, # comments allowed.
200
+ --process-per <mode> shard (default) | dir | file: process granularity for other files.
201
+ --dir-depth <n> Leading path segments that define a directory for --process-per dir
202
+ (default 1).
203
+ --lines-per-test <n> Weight of one test in lines (default ${DEFAULT_LINES_PER_TEST}).
204
+ --fail-fast Stop after the first failing process.
205
+ --cwd <dir> Directory paths and globs are relative to (default: process cwd).
206
+ -h, --help Show this help.
207
+
208
+ Exit code: the bun test result (1 if any process failed), 0 for an empty shard, or 1 when no
209
+ test files match at all (a silently empty run would let CI pass without running anything).`;
210
+ const isProcessPer = (value) => Object.values(PROCESS_PER).includes(value);
211
+ const parsePositiveInt = ({ value, flag }) => {
212
+ const parsed = Number(value);
213
+ if (!Number.isInteger(parsed) || parsed < 0) {
214
+ return `${flag} must be a non-negative integer, got "${value}"`;
215
+ }
216
+ return parsed;
217
+ };
218
+ /** Throws on unknown flags or missing flag values (strict mode). */
219
+ const parseCliFlags = (args) => (0, node_util_1.parseArgs)({
220
+ allowPositionals: true,
221
+ args,
222
+ options: {
223
+ cwd: { type: "string" },
224
+ "dir-depth": { type: "string" },
225
+ exclude: { multiple: true, type: "string" },
226
+ "exclude-dir": { multiple: true, type: "string" },
227
+ "fail-fast": { type: "boolean" },
228
+ help: { short: "h", type: "boolean" },
229
+ isolate: { multiple: true, type: "string" },
230
+ "isolate-file": { multiple: true, type: "string" },
231
+ "lines-per-test": { type: "string" },
232
+ list: { type: "boolean" },
233
+ pattern: { multiple: true, type: "string" },
234
+ "process-per": { type: "string" },
235
+ shard: { type: "string" },
236
+ },
237
+ strict: true,
238
+ });
239
+ /** Parses CLI arguments; returns `{error}` with a message on invalid input. */
240
+ const parseTestShardArgs = ({ argv, cwd, }) => {
241
+ const separatorIndex = argv.indexOf("--");
242
+ const ownArgs = separatorIndex === -1 ? argv : argv.slice(0, separatorIndex);
243
+ const bunArgs = separatorIndex === -1 ? [] : argv.slice(separatorIndex + 1);
244
+ let parsed;
245
+ try {
246
+ parsed = parseCliFlags(ownArgs);
247
+ }
248
+ catch (error) {
249
+ return { error: error.message };
250
+ }
251
+ const { values, positionals } = parsed;
252
+ let shardSpec = values.shard;
253
+ const paths = [...positionals];
254
+ if (!shardSpec && paths.length > 0 && /^\d+\/\d+$/.test(paths[0])) {
255
+ shardSpec = paths.shift();
256
+ }
257
+ const shard = (0, exports.parseShardSpec)({ spec: shardSpec ?? "1/1" });
258
+ if ("error" in shard) {
259
+ return { error: shard.error };
260
+ }
261
+ const processPer = values["process-per"] ?? PROCESS_PER.shard;
262
+ if (!isProcessPer(processPer)) {
263
+ return { error: `--process-per must be one of shard, dir, file; got "${processPer}"` };
264
+ }
265
+ const dirDepth = parsePositiveInt({ flag: "--dir-depth", value: values["dir-depth"] ?? "1" });
266
+ if (typeof dirDepth === "string") {
267
+ return { error: dirDepth };
268
+ }
269
+ const linesPerTest = parsePositiveInt({
270
+ flag: "--lines-per-test",
271
+ value: values["lines-per-test"] ?? String(DEFAULT_LINES_PER_TEST),
272
+ });
273
+ if (typeof linesPerTest === "string") {
274
+ return { error: linesPerTest };
275
+ }
276
+ return {
277
+ options: {
278
+ bunArgs,
279
+ cwd: node_path_1.default.resolve(cwd, values.cwd ?? "."),
280
+ dirDepth: Math.max(dirDepth, 1),
281
+ exclude: values.exclude ?? [],
282
+ excludeDirs: [...collectFiles_1.DEFAULT_EXCLUDED_DIRS, ...(values["exclude-dir"] ?? [])],
283
+ failFast: values["fail-fast"] ?? false,
284
+ isHelp: values.help ?? false,
285
+ isListOnly: values.list ?? false,
286
+ isolate: values.isolate ?? [],
287
+ isolateFiles: values["isolate-file"] ?? [],
288
+ linesPerTest,
289
+ paths: paths.length > 0 ? paths : ["."],
290
+ patterns: values.pattern ?? [...collectFiles_1.DEFAULT_TEST_PATTERNS],
291
+ processPer,
292
+ shard,
293
+ },
294
+ };
295
+ };
296
+ exports.parseTestShardArgs = parseTestShardArgs;
297
+ /**
298
+ * CLI entry point: discovers files, balances them into shards, prints the selected shard, and
299
+ * (unless `--list`) runs it. Returns the process exit code instead of exiting so it is testable.
300
+ */
301
+ const runTestShardCli = ({ argv, cwd = process.cwd(), spawn = spawnWithBun, logger = console, }) => {
302
+ const parsed = (0, exports.parseTestShardArgs)({ argv, cwd });
303
+ if ("error" in parsed) {
304
+ logger.error(`${parsed.error}\n\n${TEST_SHARD_USAGE}`);
305
+ return { exitCode: 2 };
306
+ }
307
+ const { options } = parsed;
308
+ if (options.isHelp) {
309
+ logger.info(TEST_SHARD_USAGE);
310
+ return { exitCode: 0 };
311
+ }
312
+ const { files, missingPaths } = (0, collectFiles_1.collectFiles)({
313
+ cwd: options.cwd,
314
+ exclude: options.exclude,
315
+ excludeDirs: options.excludeDirs,
316
+ paths: options.paths,
317
+ patterns: options.patterns,
318
+ });
319
+ if (missingPaths.length > 0) {
320
+ logger.error(`Path(s) do not exist: ${missingPaths.join(", ")}`);
321
+ return { exitCode: 1 };
322
+ }
323
+ if (files.length === 0) {
324
+ logger.error(`No test files matching ${options.patterns.join(", ")} under: ${options.paths.join(", ")}`);
325
+ return { exitCode: 1 };
326
+ }
327
+ const isolate = [
328
+ ...options.isolate,
329
+ ...options.isolateFiles.flatMap((file) => (0, exports.parseGlobList)({ text: (0, node_fs_1.readFileSync)(node_path_1.default.resolve(options.cwd, file), "utf-8") }).globs),
330
+ ];
331
+ const weighted = files.map((file) => ({
332
+ file,
333
+ weight: (0, exports.estimateTestWeight)({
334
+ linesPerTest: options.linesPerTest,
335
+ source: (0, node_fs_1.readFileSync)(node_path_1.default.join(options.cwd, file), "utf-8"),
336
+ }).weight,
337
+ }));
338
+ const shards = (0, exports.buildShards)({ files: weighted, total: options.shard.total });
339
+ const shard = shards[options.shard.index - 1];
340
+ const groups = (0, exports.planProcessGroups)({
341
+ dirDepth: options.dirDepth,
342
+ files: shard.files,
343
+ isolate,
344
+ processPer: options.processPer,
345
+ });
346
+ logger.info(`Shard ${options.shard.index}/${options.shard.total}: ${shard.files.length} of ${files.length} files, ` +
347
+ `weight ${shard.weight} (all shards: ${shards.map((s) => s.weight).join(", ")}), ` +
348
+ `${groups.length} process(es)`);
349
+ for (const group of groups) {
350
+ if (groups.length > 1) {
351
+ logger.info(` [${group.name}]`);
352
+ }
353
+ for (const file of group.files) {
354
+ logger.info(` ${file}`);
355
+ }
356
+ }
357
+ if (options.isListOnly) {
358
+ return { exitCode: 0 };
359
+ }
360
+ if (groups.length === 0) {
361
+ logger.info("Nothing to run for this shard.");
362
+ return { exitCode: 0 };
363
+ }
364
+ const outcome = (0, exports.runProcessGroups)({
365
+ bunArgs: options.bunArgs,
366
+ cwd: options.cwd,
367
+ failFast: options.failFast,
368
+ groups,
369
+ logger,
370
+ spawn,
371
+ });
372
+ if (groups.length > 1) {
373
+ logger.info(`\n${(0, exports.formatRunSummary)(outcome).text}`);
374
+ }
375
+ return { exitCode: outcome.allPassed ? 0 : 1 };
376
+ };
377
+ exports.runTestShardCli = runTestShardCli;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const testShard_1 = require("./testShard");
5
+ process.exitCode = (0, testShard_1.runTestShardCli)({ argv: process.argv.slice(2) }).exitCode;
@@ -0,0 +1,76 @@
1
+ import { type Mock } from "bun:test";
2
+ import type { ModuleMockMap } from "./mockHelpers";
3
+ /** Keys `@terreno/rtk` JWT auth (`generateAuthSlice`, `emptyApi`) reads and writes. */
4
+ export declare const TERRENO_AUTH_TOKEN_KEYS: {
5
+ readonly authToken: "AUTH_TOKEN";
6
+ readonly refreshToken: "REFRESH_TOKEN";
7
+ };
8
+ /**
9
+ * Keys a `@terreno/rtk` Better Auth client stores under: the `@better-auth/expo` cookie jar and
10
+ * session cache (native), and the bearer token (web, `webAuth: "bearer"`).
11
+ */
12
+ export declare const getBetterAuthStorageKeys: (storagePrefix?: string) => {
13
+ bearerToken: string;
14
+ cookie: string;
15
+ sessionData: string;
16
+ };
17
+ /** In-memory backing store for the `expo-secure-store` stand-in. Tests may read it directly. */
18
+ export declare const secureStore: Record<string, string>;
19
+ /** In-memory backing store for the AsyncStorage stand-in. Tests may read it directly. */
20
+ export declare const asyncStorage: Record<string, string>;
21
+ type MockedApi<T extends Record<string, (...args: never[]) => unknown>> = {
22
+ [K in keyof T]: Mock<T[K]>;
23
+ };
24
+ /** Stable `expo-secure-store` stand-in backed by `secureStore` (sync and async APIs). */
25
+ export declare const secureStoreMock: MockedApi<{
26
+ deleteItemAsync: (key: string) => Promise<void>;
27
+ getItem: (key: string) => string | null;
28
+ getItemAsync: (key: string) => Promise<string | null>;
29
+ isAvailableAsync: () => Promise<boolean>;
30
+ setItem: (key: string, value: string) => void;
31
+ setItemAsync: (key: string, value: string) => Promise<void>;
32
+ }>;
33
+ /** Stable `@react-native-async-storage/async-storage` stand-in backed by `asyncStorage`. */
34
+ export declare const asyncStorageMock: MockedApi<{
35
+ clear: () => Promise<void>;
36
+ getAllKeys: () => Promise<string[]>;
37
+ getItem: (key: string) => Promise<string | null>;
38
+ mergeItem: (key: string, value: string) => Promise<void>;
39
+ multiGet: (keys: readonly string[]) => Promise<[string, string | null][]>;
40
+ multiRemove: (keys: readonly string[]) => Promise<void>;
41
+ multiSet: (pairs: readonly [string, string][]) => Promise<void>;
42
+ removeItem: (key: string) => Promise<void>;
43
+ setItem: (key: string, value: string) => Promise<void>;
44
+ }>;
45
+ /** Module factories for the two storage packages, for composing into a larger mock map. */
46
+ export declare const createAuthTokenStorageModuleMocks: () => ModuleMockMap;
47
+ /**
48
+ * Points every storage mock back at its in-memory implementation and clears its call history,
49
+ * undoing a suite's `mockImplementation`, `mockReset()`, or `jest.clearAllMocks()`.
50
+ */
51
+ export declare const resetAuthTokenStorageMocks: () => void;
52
+ /**
53
+ * Registers in-memory `expo-secure-store` and AsyncStorage mocks and resets them
54
+ * (`resetAuthTokenStorageMocks`). Call it again from `beforeEach` when another suite in the same
55
+ * process registers its own SecureStore or AsyncStorage mock.
56
+ */
57
+ export declare const registerAuthTokenStorageMocks: () => void;
58
+ /**
59
+ * Removes stored values from both in-memory stores. With `keys`, removes only those keys;
60
+ * without, empties both stores so nothing a test wrote leaks into the next one.
61
+ */
62
+ export declare const clearAuthTokenStorage: ({ keys }?: {
63
+ keys?: readonly string[];
64
+ }) => void;
65
+ /** Where `setAuthTokens` writes: native reads SecureStore, web reads AsyncStorage. */
66
+ export type AuthTokenStorageTarget = "asyncStorage" | "both" | "secureStore";
67
+ /**
68
+ * Seeds the JWT tokens `@terreno/rtk` reads (`AUTH_TOKEN` / `REFRESH_TOKEN`), so a test can
69
+ * start signed in. Writes to SecureStore (native) by default.
70
+ */
71
+ export declare const setAuthTokens: ({ authToken, refreshToken, target, }: {
72
+ authToken: string;
73
+ refreshToken?: string;
74
+ target?: AuthTokenStorageTarget;
75
+ }) => void;
76
+ export {};
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setAuthTokens = exports.clearAuthTokenStorage = exports.registerAuthTokenStorageMocks = exports.resetAuthTokenStorageMocks = exports.createAuthTokenStorageModuleMocks = exports.asyncStorageMock = exports.secureStoreMock = exports.asyncStorage = exports.secureStore = exports.getBetterAuthStorageKeys = exports.TERRENO_AUTH_TOKEN_KEYS = void 0;
4
+ const bun_test_1 = require("bun:test");
5
+ /** Keys `@terreno/rtk` JWT auth (`generateAuthSlice`, `emptyApi`) reads and writes. */
6
+ exports.TERRENO_AUTH_TOKEN_KEYS = {
7
+ authToken: "AUTH_TOKEN",
8
+ refreshToken: "REFRESH_TOKEN",
9
+ };
10
+ /** Default `storagePrefix` `@terreno/rtk`'s `createBetterAuthClient` uses. */
11
+ const DEFAULT_BETTER_AUTH_STORAGE_PREFIX = "terreno";
12
+ /**
13
+ * Keys a `@terreno/rtk` Better Auth client stores under: the `@better-auth/expo` cookie jar and
14
+ * session cache (native), and the bearer token (web, `webAuth: "bearer"`).
15
+ */
16
+ const getBetterAuthStorageKeys = (storagePrefix = DEFAULT_BETTER_AUTH_STORAGE_PREFIX) => ({
17
+ bearerToken: `${storagePrefix}_bearer_token`,
18
+ cookie: `${storagePrefix}_cookie`,
19
+ sessionData: `${storagePrefix}_session_data`,
20
+ });
21
+ exports.getBetterAuthStorageKeys = getBetterAuthStorageKeys;
22
+ /** In-memory backing store for the `expo-secure-store` stand-in. Tests may read it directly. */
23
+ exports.secureStore = {};
24
+ /** In-memory backing store for the AsyncStorage stand-in. Tests may read it directly. */
25
+ exports.asyncStorage = {};
26
+ const readKey = (store, key) => Object.hasOwn(store, key) ? store[key] : null;
27
+ const writeKey = (store, key, value) => {
28
+ store[key] = String(value);
29
+ };
30
+ const deleteKey = (store, key) => {
31
+ delete store[key];
32
+ };
33
+ const emptyStore = (store) => {
34
+ for (const key of Object.keys(store)) {
35
+ delete store[key];
36
+ }
37
+ };
38
+ /** The implementation each storage mock is reset to, so a `mockImplementation` cannot leak. */
39
+ const secureStoreImplementations = {
40
+ deleteItemAsync: async (key) => deleteKey(exports.secureStore, key),
41
+ getItem: (key) => readKey(exports.secureStore, key),
42
+ getItemAsync: async (key) => readKey(exports.secureStore, key),
43
+ isAvailableAsync: async () => true,
44
+ setItem: (key, value) => writeKey(exports.secureStore, key, value),
45
+ setItemAsync: async (key, value) => writeKey(exports.secureStore, key, value),
46
+ };
47
+ const asyncStorageImplementations = {
48
+ clear: async () => emptyStore(exports.asyncStorage),
49
+ getAllKeys: async () => Object.keys(exports.asyncStorage),
50
+ getItem: async (key) => readKey(exports.asyncStorage, key),
51
+ mergeItem: async (key, value) => {
52
+ const current = JSON.parse(readKey(exports.asyncStorage, key) ?? "{}");
53
+ writeKey(exports.asyncStorage, key, JSON.stringify({ ...current, ...JSON.parse(value) }));
54
+ },
55
+ multiGet: async (keys) => keys.map((key) => [key, readKey(exports.asyncStorage, key)]),
56
+ multiRemove: async (keys) => {
57
+ for (const key of keys) {
58
+ deleteKey(exports.asyncStorage, key);
59
+ }
60
+ },
61
+ multiSet: async (pairs) => {
62
+ for (const [key, value] of pairs) {
63
+ writeKey(exports.asyncStorage, key, value);
64
+ }
65
+ },
66
+ removeItem: async (key) => deleteKey(exports.asyncStorage, key),
67
+ setItem: async (key, value) => writeKey(exports.asyncStorage, key, value),
68
+ };
69
+ const mockApi = (implementations) => {
70
+ const api = {};
71
+ for (const key of Object.keys(implementations)) {
72
+ api[key] = (0, bun_test_1.mock)(implementations[key]);
73
+ }
74
+ return api;
75
+ };
76
+ /** Stable `expo-secure-store` stand-in backed by `secureStore` (sync and async APIs). */
77
+ exports.secureStoreMock = mockApi(secureStoreImplementations);
78
+ /** Stable `@react-native-async-storage/async-storage` stand-in backed by `asyncStorage`. */
79
+ exports.asyncStorageMock = mockApi(asyncStorageImplementations);
80
+ const resetApi = (api, implementations) => {
81
+ for (const key of Object.keys(implementations)) {
82
+ api[key].mockClear();
83
+ api[key].mockImplementation(implementations[key]);
84
+ }
85
+ };
86
+ /** Module factories for the two storage packages, for composing into a larger mock map. */
87
+ const createAuthTokenStorageModuleMocks = () => ({
88
+ "@react-native-async-storage/async-storage": () => ({
89
+ ...exports.asyncStorageMock,
90
+ default: exports.asyncStorageMock,
91
+ }),
92
+ "expo-secure-store": () => ({
93
+ ...exports.secureStoreMock,
94
+ AFTER_FIRST_UNLOCK: 0,
95
+ AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: 1,
96
+ ALWAYS: 2,
97
+ ALWAYS_THIS_DEVICE_ONLY: 4,
98
+ WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: 3,
99
+ WHEN_UNLOCKED: 5,
100
+ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 6,
101
+ }),
102
+ });
103
+ exports.createAuthTokenStorageModuleMocks = createAuthTokenStorageModuleMocks;
104
+ /**
105
+ * Points every storage mock back at its in-memory implementation and clears its call history,
106
+ * undoing a suite's `mockImplementation`, `mockReset()`, or `jest.clearAllMocks()`.
107
+ */
108
+ const resetAuthTokenStorageMocks = () => {
109
+ resetApi(exports.secureStoreMock, secureStoreImplementations);
110
+ resetApi(exports.asyncStorageMock, asyncStorageImplementations);
111
+ };
112
+ exports.resetAuthTokenStorageMocks = resetAuthTokenStorageMocks;
113
+ /**
114
+ * Registers in-memory `expo-secure-store` and AsyncStorage mocks and resets them
115
+ * (`resetAuthTokenStorageMocks`). Call it again from `beforeEach` when another suite in the same
116
+ * process registers its own SecureStore or AsyncStorage mock.
117
+ */
118
+ const registerAuthTokenStorageMocks = () => {
119
+ for (const [specifier, factory] of Object.entries((0, exports.createAuthTokenStorageModuleMocks)())) {
120
+ bun_test_1.mock.module(specifier, factory);
121
+ }
122
+ (0, exports.resetAuthTokenStorageMocks)();
123
+ };
124
+ exports.registerAuthTokenStorageMocks = registerAuthTokenStorageMocks;
125
+ /**
126
+ * Removes stored values from both in-memory stores. With `keys`, removes only those keys;
127
+ * without, empties both stores so nothing a test wrote leaks into the next one.
128
+ */
129
+ const clearAuthTokenStorage = ({ keys } = {}) => {
130
+ if (!keys) {
131
+ emptyStore(exports.secureStore);
132
+ emptyStore(exports.asyncStorage);
133
+ return;
134
+ }
135
+ for (const key of keys) {
136
+ deleteKey(exports.secureStore, key);
137
+ deleteKey(exports.asyncStorage, key);
138
+ }
139
+ };
140
+ exports.clearAuthTokenStorage = clearAuthTokenStorage;
141
+ /**
142
+ * Seeds the JWT tokens `@terreno/rtk` reads (`AUTH_TOKEN` / `REFRESH_TOKEN`), so a test can
143
+ * start signed in. Writes to SecureStore (native) by default.
144
+ */
145
+ const setAuthTokens = ({ authToken, refreshToken, target = "secureStore", }) => {
146
+ const stores = [];
147
+ if (target !== "asyncStorage") {
148
+ stores.push(exports.secureStore);
149
+ }
150
+ if (target !== "secureStore") {
151
+ stores.push(exports.asyncStorage);
152
+ }
153
+ for (const store of stores) {
154
+ writeKey(store, exports.TERRENO_AUTH_TOKEN_KEYS.authToken, authToken);
155
+ if (refreshToken !== undefined) {
156
+ writeKey(store, exports.TERRENO_AUTH_TOKEN_KEYS.refreshToken, refreshToken);
157
+ }
158
+ }
159
+ };
160
+ exports.setAuthTokens = setAuthTokens;
@@ -0,0 +1,24 @@
1
+ import { type ExpoTestPlatform, type ModuleMockMap } from "./mockHelpers";
2
+ /** Options for the generated Expo module stand-ins. */
3
+ export interface ExpoModuleMockOptions {
4
+ /** `expo-constants` `expoConfig` (an app.json `expo` block). Default `{extra: {}, name: "test", slug: "test"}`. */
5
+ expoConfig?: Record<string, unknown>;
6
+ /** Locale reported by `expo-localization`. Default `"en-US"`. */
7
+ locale?: string;
8
+ /** Platform reported through `expo-modules-core` and `expo-device`. Default `"ios"`. */
9
+ platform?: ExpoTestPlatform;
10
+ /** Deep-link scheme `expo-linking.createURL` builds on. Default `expoConfig.scheme` or `"exp"`. */
11
+ scheme?: string;
12
+ /** IANA zone `expo-localization` reports. Default `"America/New_York"`. */
13
+ timeZone?: string;
14
+ }
15
+ /** Icon families mocked under `@expo/vector-icons` and `@expo/vector-icons/<Family>`. */
16
+ export declare const VECTOR_ICON_FAMILIES: readonly ["AntDesign", "Entypo", "EvilIcons", "Feather", "FontAwesome", "FontAwesome5", "FontAwesome6", "Fontisto", "Foundation", "Ionicons", "MaterialCommunityIcons", "MaterialIcons", "Octicons", "SimpleLineIcons", "Zocial"];
17
+ /** The `globalThis.expo` object `expo-modules-core` reads when it loads. */
18
+ export declare const createExpoGlobal: () => Record<string, unknown>;
19
+ /**
20
+ * Builds stand-ins for the Expo SDK modules most apps import: the `expo` / `expo-modules-core`
21
+ * native bridge, `expo-router`, `expo-constants`, `expo-linking`, `expo-font`, and the common
22
+ * device APIs. `expo-secure-store` lives in `authTokenStorage.ts`.
23
+ */
24
+ export declare const createExpoModuleMocks: ({ expoConfig, locale, platform, scheme, timeZone, }?: ExpoModuleMockOptions) => ModuleMockMap;