@terreno/test 0.22.1

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 (69) hide show
  1. package/bunfig.toml +3 -0
  2. package/dist/cache/mongoTestCache.d.ts +16 -0
  3. package/dist/cache/mongoTestCache.js +541 -0
  4. package/dist/env/setTerrenoTestEnv.d.ts +13 -0
  5. package/dist/env/setTerrenoTestEnv.js +89 -0
  6. package/dist/http/authAsUser.d.ts +17 -0
  7. package/dist/http/authAsUser.js +165 -0
  8. package/dist/http/authAsUser.test.d.ts +1 -0
  9. package/dist/http/authAsUser.test.js +93 -0
  10. package/dist/http/getBaseServer.d.ts +9 -0
  11. package/dist/http/getBaseServer.js +33 -0
  12. package/dist/http/getBaseServer.test.d.ts +1 -0
  13. package/dist/http/getBaseServer.test.js +76 -0
  14. package/dist/index.d.ts +14 -0
  15. package/dist/index.js +46 -0
  16. package/dist/logging/setupEnvironment.d.ts +2 -0
  17. package/dist/logging/setupEnvironment.js +19 -0
  18. package/dist/logging/silenceLogs.d.ts +20 -0
  19. package/dist/logging/silenceLogs.js +168 -0
  20. package/dist/logging/testLogger.d.ts +7 -0
  21. package/dist/logging/testLogger.js +22 -0
  22. package/dist/mocks/sentryBun.d.ts +2 -0
  23. package/dist/mocks/sentryBun.js +136 -0
  24. package/dist/mongo/connection.d.ts +16 -0
  25. package/dist/mongo/connection.js +134 -0
  26. package/dist/mongo/connection.test.d.ts +1 -0
  27. package/dist/mongo/connection.test.js +28 -0
  28. package/dist/mongo/ensureMongoBinary.d.ts +6 -0
  29. package/dist/mongo/ensureMongoBinary.js +104 -0
  30. package/dist/mongo/mongoServer.d.ts +26 -0
  31. package/dist/mongo/mongoServer.js +424 -0
  32. package/dist/preload/defaultBackendPreload.d.ts +1 -0
  33. package/dist/preload/defaultBackendPreload.js +8 -0
  34. package/dist/preload/memoryMongo.d.ts +0 -0
  35. package/dist/preload/memoryMongo.js +2 -0
  36. package/dist/preload/registerBackendPreload.d.ts +33 -0
  37. package/dist/preload/registerBackendPreload.js +302 -0
  38. package/dist/transaction/testTransaction.d.ts +91 -0
  39. package/dist/transaction/testTransaction.js +719 -0
  40. package/dist/utils/ensureAllIndexes.d.ts +2 -0
  41. package/dist/utils/ensureAllIndexes.js +84 -0
  42. package/dist/utils/timeout.d.ts +1 -0
  43. package/dist/utils/timeout.js +45 -0
  44. package/dist/utils/waitForDocuments.d.ts +13 -0
  45. package/dist/utils/waitForDocuments.js +127 -0
  46. package/package.json +65 -0
  47. package/src/cache/mongoTestCache.ts +311 -0
  48. package/src/env/setTerrenoTestEnv.ts +50 -0
  49. package/src/http/authAsUser.test.ts +40 -0
  50. package/src/http/authAsUser.ts +59 -0
  51. package/src/http/getBaseServer.test.ts +30 -0
  52. package/src/http/getBaseServer.ts +34 -0
  53. package/src/index.ts +53 -0
  54. package/src/logging/setupEnvironment.ts +15 -0
  55. package/src/logging/silenceLogs.ts +134 -0
  56. package/src/logging/testLogger.ts +19 -0
  57. package/src/mocks/sentryBun.ts +140 -0
  58. package/src/mongo/connection.test.ts +30 -0
  59. package/src/mongo/connection.ts +65 -0
  60. package/src/mongo/ensureMongoBinary.ts +25 -0
  61. package/src/mongo/mongoServer.ts +214 -0
  62. package/src/preload/defaultBackendPreload.ts +7 -0
  63. package/src/preload/memoryMongo.ts +1 -0
  64. package/src/preload/registerBackendPreload.ts +174 -0
  65. package/src/transaction/testTransaction.ts +524 -0
  66. package/src/utils/ensureAllIndexes.ts +11 -0
  67. package/src/utils/timeout.ts +3 -0
  68. package/src/utils/waitForDocuments.ts +50 -0
  69. package/tsconfig.json +31 -0
@@ -0,0 +1,524 @@
1
+ /**
2
+ * Transaction-based test isolation for MongoDB.
3
+ *
4
+ * Instead of clearing and reloading all collections before every test,
5
+ * this module wraps each test in a MongoDB transaction that is aborted
6
+ * after the test completes. This rolls back all changes made during the
7
+ * test, leaving the database in its original state for the next test.
8
+ *
9
+ * How it works:
10
+ * 1. Mongoose operations (Query.exec, Model.save, Aggregate.exec, etc.)
11
+ * are monkey-patched to inject the current test session when active.
12
+ * 2. Before each test, a session is started and a transaction is begun.
13
+ * 3. After each test, the transaction is aborted and the session is ended.
14
+ * 4. All DB operations during the test see the pre-test snapshot and any
15
+ * writes made within the transaction, but nothing is persisted.
16
+ *
17
+ * Session reuse: a single MongoDB session is reused across all tests within
18
+ * a worker to avoid transaction number mismatches caused by the MongoDB driver's
19
+ * server session pool. When sessions are ended and reacquired from the pool,
20
+ * in-flight operations from a previous test can arrive with a stale transaction
21
+ * number, causing NoSuchTransaction errors. Reusing one session avoids this.
22
+ *
23
+ * Operation serialization: MongoDB does not support concurrent operations on
24
+ * the same session within a transaction. When app code uses Promise.all() to
25
+ * run DB operations in parallel, concurrent operations on the same session
26
+ * cause TransientTransactionError / NoSuchTransaction. We solve this with a
27
+ * reentrant async mutex:
28
+ * - Top-level operations (the ones fired by Promise.all) are serialized
29
+ * - Nested operations (e.g. pre-save hooks that do queries) detect they're
30
+ * already inside a serialized block and skip the mutex, preventing deadlocks
31
+ * - AsyncLocalStorage tracks the serialization context across the async chain
32
+ *
33
+ * Limitations:
34
+ * - App code that creates its own sessions (e.g. explicit transactions in
35
+ * route handlers) will have those sessions' operations redirected through
36
+ * the test session. The app's own commit/abort calls become no-ops.
37
+ * - Native driver operations (mongoose.connection.db.collection(...)) are
38
+ * NOT patched. Only Mongoose-level operations are covered.
39
+ */
40
+
41
+ import {AsyncLocalStorage} from "async_hooks";
42
+ import type {ClientSession} from "mongoose";
43
+ import mongoose from "mongoose";
44
+
45
+ let currentTestSession: ClientSession | null = null;
46
+ let patchesInstalled = false;
47
+
48
+ // ============================================================================
49
+ // Reentrant Async Mutex
50
+ // ============================================================================
51
+
52
+ /**
53
+ * Tracks whether the current async context is already inside a serialized
54
+ * DB operation. When true, nested operations skip the mutex to avoid deadlocks.
55
+ */
56
+ const serializationContext = new AsyncLocalStorage<{active: boolean}>();
57
+
58
+ /**
59
+ * Async mutex that serializes access to the MongoDB session.
60
+ * Only one DB operation can be in-flight at a time when a test session is active.
61
+ */
62
+ class AsyncMutex {
63
+ private queue: Array<() => void> = [];
64
+ private locked = false;
65
+
66
+ async acquire(): Promise<void> {
67
+ if (!this.locked) {
68
+ this.locked = true;
69
+ return;
70
+ }
71
+ return new Promise<void>((resolve) => {
72
+ this.queue.push(resolve);
73
+ });
74
+ }
75
+
76
+ release(): void {
77
+ const next = this.queue.shift();
78
+ if (next) {
79
+ next();
80
+ } else {
81
+ this.locked = false;
82
+ }
83
+ }
84
+
85
+ reset(): void {
86
+ this.locked = false;
87
+ this.queue = [];
88
+ }
89
+ }
90
+
91
+ const sessionMutex = new AsyncMutex();
92
+
93
+ /**
94
+ * Returns whether the active test transaction session can be attached to DB
95
+ * operations on the given Mongoose connection. The Node driver's
96
+ * `ClientSession` must belong to the same `MongoClient` as the collection;
97
+ * otherwise operations throw `MongoInvalidArgumentError` (observed in CI when
98
+ * mixing connections).
99
+ *
100
+ * @param connection - Mongoose connection (`Model.db`), or undefined when unknown
101
+ * @returns True when the session should be passed into driver options / `.session()`
102
+ */
103
+ const shouldAttachTestSessionToConnection = (
104
+ connection: {getClient?: () => unknown} | null | undefined
105
+ ): boolean => {
106
+ if (!currentTestSession) {
107
+ return false;
108
+ }
109
+ const sessionClient = (currentTestSession as {client?: unknown}).client;
110
+ if (!connection || typeof connection.getClient !== "function") {
111
+ return true;
112
+ }
113
+ const connClient = connection.getClient();
114
+ if (!sessionClient || !connClient) {
115
+ return true;
116
+ }
117
+ return sessionClient === connClient;
118
+ };
119
+
120
+ /**
121
+ * Waits until all serialized DB operations have completed before test teardown.
122
+ *
123
+ * This prevents operations that were queued near test completion from leaking
124
+ * into the next test's transaction window, which can surface as intermittent
125
+ * NoSuchTransaction / transaction-number mismatch errors.
126
+ */
127
+ const waitForSerializedOperationsToDrain = async (timeoutMs = 5000): Promise<void> => {
128
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
129
+ try {
130
+ await Promise.race([
131
+ (async () => {
132
+ await sessionMutex.acquire();
133
+ sessionMutex.release();
134
+ })(),
135
+ new Promise<void>((_, reject) => {
136
+ timeoutId = setTimeout(() => {
137
+ reject(
138
+ new Error(`[testTransaction] Timed out waiting for serialized operations to drain`)
139
+ );
140
+ }, timeoutMs);
141
+ }),
142
+ ]);
143
+ } finally {
144
+ if (timeoutId) {
145
+ clearTimeout(timeoutId);
146
+ }
147
+ }
148
+ };
149
+
150
+ /**
151
+ * Wraps an async DB operation with the session mutex. Reentrant: if the current
152
+ * async context is already inside a serialized block, the operation runs directly
153
+ * without acquiring the mutex (preventing deadlocks from nested operations like
154
+ * pre-save hooks that do queries).
155
+ */
156
+ const serialized = <T>(fn: () => T | Promise<T>): T | Promise<T> => {
157
+ // If no test session is active, skip serialization entirely
158
+ if (!currentTestSession) {
159
+ return fn();
160
+ }
161
+
162
+ // If we're already inside a serialized block (nested call), run directly
163
+ const store = serializationContext.getStore();
164
+ if (store?.active) {
165
+ return fn();
166
+ }
167
+
168
+ // Top-level call: acquire mutex, then run inside the serialization context
169
+ const run = async (): Promise<T> => {
170
+ let hasRetried = false;
171
+
172
+ while (true) {
173
+ await sessionMutex.acquire();
174
+ try {
175
+ return await serializationContext.run({active: true}, fn);
176
+ } catch (error: any) {
177
+ // If this error aborted the transaction (e.g. E11000 duplicate key),
178
+ // restart it and retry once so transient transaction-number mismatches
179
+ // don't fail the test immediately.
180
+ const isTransactionAborted =
181
+ error?.errorLabels?.includes?.("TransientTransactionError") ||
182
+ (currentTestSession && !currentTestSession.inTransaction());
183
+
184
+ if (!hasRetried && isTransactionAborted && currentTestSession) {
185
+ hasRetried = true;
186
+ try {
187
+ // Explicitly abort client-side transaction state before restart.
188
+ if (currentTestSession.inTransaction()) {
189
+ await currentTestSession.abortTransaction();
190
+ }
191
+ currentTestSession.startTransaction();
192
+ continue;
193
+ } catch {
194
+ // Ignore — fallback to throwing original error below.
195
+ }
196
+ }
197
+
198
+ throw error;
199
+ } finally {
200
+ sessionMutex.release();
201
+ }
202
+ }
203
+ };
204
+ return run();
205
+ };
206
+
207
+ // ============================================================================
208
+ // Public API
209
+ // ============================================================================
210
+
211
+ /** Returns the current test session, or null if not in a test transaction. */
212
+ export const getTestSession = (): ClientSession | null => currentTestSession;
213
+
214
+ /**
215
+ * Starts a new test transaction. Call in beforeEach.
216
+ *
217
+ * Reuses the existing MongoDB session when possible. A new session is only
218
+ * created on the very first call or after the previous session has been
219
+ * explicitly ended (e.g., due to an error).
220
+ */
221
+ export const startTestTransaction = async (): Promise<void> => {
222
+ if (currentTestSession) {
223
+ // Abort any leftover transaction from a previous test that wasn't cleaned up
224
+ try {
225
+ if (currentTestSession.inTransaction()) {
226
+ await currentTestSession.abortTransaction();
227
+ }
228
+ } catch {
229
+ // Session may be in a bad state — create a fresh one below
230
+ try {
231
+ await currentTestSession.endSession();
232
+ } catch {
233
+ // Ignore
234
+ }
235
+ currentTestSession = null;
236
+ }
237
+ }
238
+
239
+ if (!currentTestSession) {
240
+ currentTestSession = await mongoose.startSession();
241
+ }
242
+
243
+ sessionMutex.reset();
244
+ currentTestSession.startTransaction();
245
+ };
246
+
247
+ /**
248
+ * Aborts the current test transaction. Call in afterEach.
249
+ *
250
+ * The session is intentionally kept alive (not ended) so it can be reused by
251
+ * the next test. This avoids returning the session to the driver's server
252
+ * session pool, which prevents transaction number mismatches when in-flight
253
+ * operations from a previous test complete after the session has been recycled.
254
+ */
255
+ export const abortTestTransaction = async (): Promise<void> => {
256
+ if (!currentTestSession) {
257
+ return;
258
+ }
259
+
260
+ try {
261
+ // Ensure any in-flight/queued DB work from the current test has settled
262
+ // before aborting and starting the next transaction.
263
+ await waitForSerializedOperationsToDrain();
264
+
265
+ if (currentTestSession.inTransaction()) {
266
+ await currentTestSession.abortTransaction();
267
+ }
268
+ } catch (error) {
269
+ // biome-ignore lint/suspicious/noConsole: test harness diagnostic when abort fails
270
+ console.warn("[testTransaction] Error aborting transaction:", error);
271
+ // If the abort failed, the session may be in a bad state. End it so
272
+ // startTestTransaction creates a fresh one.
273
+ try {
274
+ await currentTestSession.endSession();
275
+ } catch {
276
+ // Ignore
277
+ }
278
+ currentTestSession = null;
279
+ } finally {
280
+ // Clean slate for the next test transaction.
281
+ sessionMutex.reset();
282
+ }
283
+ };
284
+
285
+ /**
286
+ * Drops the cached test session after an out-of-band mongoose reconnect.
287
+ *
288
+ * Reconnects can swap the underlying MongoClient, which invalidates any active
289
+ * ClientSession. Clearing here prevents subsequent tests from reusing a stale
290
+ * or expired session.
291
+ */
292
+ export const resetTestSessionAfterReconnect = async (): Promise<void> => {
293
+ if (!currentTestSession) {
294
+ sessionMutex.reset();
295
+ return;
296
+ }
297
+
298
+ try {
299
+ if (currentTestSession.inTransaction()) {
300
+ await currentTestSession.abortTransaction();
301
+ }
302
+ await currentTestSession.endSession();
303
+ } catch {
304
+ // Ignore cleanup failures; session is being discarded regardless.
305
+ } finally {
306
+ currentTestSession = null;
307
+ sessionMutex.reset();
308
+ }
309
+ };
310
+
311
+ // ============================================================================
312
+ // Mongoose Monkey-Patches
313
+ // ============================================================================
314
+
315
+ /**
316
+ * Installs Mongoose monkey-patches that inject the test session into all DB operations.
317
+ *
318
+ * Patches are idempotent — calling this multiple times is safe.
319
+ * The patches only activate when currentTestSession is non-null (i.e., during a test).
320
+ * All operations are serialized through the async mutex to prevent concurrent
321
+ * operations on the same MongoDB session.
322
+ *
323
+ * Patched operations:
324
+ * - Query.prototype.exec — covers find, findOne, updateOne, deleteMany, countDocuments, etc.
325
+ * - Model.prototype.save and $save — covers save() and create() (Model.create calls $save)
326
+ * - Aggregate.prototype.exec — covers aggregation pipelines
327
+ * - Model.bulkWrite — covers bulk write operations
328
+ * - Model.insertMany — covers bulk inserts (uses native driver, not save)
329
+ * - Model.distinct — bypasses Query, calls native driver directly
330
+ * - Model.startSession — returns a no-op wrapper so app-level transactions don't conflict
331
+ * - Collection.prototype (insertOne, updateOne, deleteOne, etc.) — covers native driver
332
+ * operations used by tests that call Model.collection.insertOne() directly
333
+ *
334
+ * When a model or collection uses a different MongoClient than the one that
335
+ * created the test session, patches skip session injection for that operation
336
+ * so the driver does not reject mismatched clients.
337
+ */
338
+ export const installTransactionPatches = (): void => {
339
+ if (patchesInstalled) {
340
+ return;
341
+ }
342
+
343
+ // --- Query.prototype.exec ---
344
+ const originalQueryExec = mongoose.Query.prototype.exec;
345
+ mongoose.Query.prototype.exec = function (this: any) {
346
+ if (currentTestSession) {
347
+ if (!shouldAttachTestSessionToConnection(this.model?.db)) {
348
+ return originalQueryExec.apply(this);
349
+ }
350
+ this.session(currentTestSession);
351
+ return serialized(() => originalQueryExec.apply(this));
352
+ }
353
+ return originalQueryExec.apply(this);
354
+ } as any;
355
+
356
+ // --- Model.prototype.save and $save ---
357
+ // In Mongoose 8, Model.create() calls $save (not save). $save is assigned from
358
+ // save at module load time (Model.prototype.$save = Model.prototype.save), so we
359
+ // must patch both to ensure Model.create() goes through our session injection.
360
+ const patchSave = (original: Function) =>
361
+ function (this: any, options?: any) {
362
+ if (currentTestSession) {
363
+ const connection = this.constructor?.db;
364
+ if (!shouldAttachTestSessionToConnection(connection)) {
365
+ return original.call(this, options);
366
+ }
367
+ if (typeof options === "function") {
368
+ this.$session(currentTestSession);
369
+ return serialized(() => original.call(this, options));
370
+ }
371
+ options = {...(options || {}), session: currentTestSession};
372
+ return serialized(() => original.call(this, options));
373
+ }
374
+ return original.call(this, options);
375
+ };
376
+
377
+ const originalSave = mongoose.Model.prototype.save;
378
+ mongoose.Model.prototype.save = patchSave(originalSave) as any;
379
+
380
+ // $save is what Model.create() actually calls
381
+ const original$Save = mongoose.Model.prototype.$save;
382
+ mongoose.Model.prototype.$save = patchSave(original$Save) as any;
383
+
384
+ // --- Aggregate.prototype.exec ---
385
+ const originalAggExec = mongoose.Aggregate.prototype.exec;
386
+ mongoose.Aggregate.prototype.exec = function (this: any) {
387
+ if (currentTestSession) {
388
+ const connection = this._model?.db ?? this._connection;
389
+ if (!shouldAttachTestSessionToConnection(connection)) {
390
+ return originalAggExec.apply(this);
391
+ }
392
+ this.session(currentTestSession);
393
+ return serialized(() => originalAggExec.apply(this));
394
+ }
395
+ return originalAggExec.apply(this);
396
+ } as any;
397
+
398
+ // --- Model.bulkWrite (static) ---
399
+ const originalBulkWrite = mongoose.Model.bulkWrite;
400
+ (mongoose.Model as any).bulkWrite = function (this: any, ops: any[], options?: any) {
401
+ if (currentTestSession) {
402
+ if (!shouldAttachTestSessionToConnection(this.db)) {
403
+ return originalBulkWrite.call(this, ops, options);
404
+ }
405
+ options = {...(options || {}), session: currentTestSession};
406
+ return serialized(() => originalBulkWrite.call(this, ops, options));
407
+ }
408
+ return originalBulkWrite.call(this, ops, options);
409
+ };
410
+
411
+ // --- Model.insertMany (static) ---
412
+ const originalInsertMany = mongoose.Model.insertMany;
413
+ (mongoose.Model as any).insertMany = function (this: any, docs: any, options?: any) {
414
+ if (currentTestSession) {
415
+ if (!shouldAttachTestSessionToConnection(this.db)) {
416
+ return (originalInsertMany as any).call(this, docs, options);
417
+ }
418
+ options = {...(options || {}), session: currentTestSession};
419
+ return serialized(() => (originalInsertMany as any).call(this, docs, options));
420
+ }
421
+ return (originalInsertMany as any).call(this, docs, options);
422
+ };
423
+
424
+ // --- Model.create (static) ---
425
+ // Some code paths call Model.create() directly (including through
426
+ // mongoose.Model.create.call(...)), which can otherwise bypass our top-level
427
+ // serialization guard and race with other operations on the shared test
428
+ // session. Wrapping create ensures transient transaction aborts trigger the
429
+ // same auto-restart logic in serialized().
430
+ const originalCreate = mongoose.Model.create;
431
+ (mongoose.Model as any).create = function (this: any, ...args: any[]) {
432
+ if (currentTestSession) {
433
+ if (!shouldAttachTestSessionToConnection(this.db)) {
434
+ return (originalCreate as any).apply(this, args);
435
+ }
436
+ return serialized(() => (originalCreate as any).apply(this, args));
437
+ }
438
+ return (originalCreate as any).apply(this, args);
439
+ };
440
+
441
+ // --- Model.startSession (static) ---
442
+ // When test session is active, return a wrapper that redirects operations
443
+ // through the test session. This ensures app code that creates its own
444
+ // transactions (e.g. userExplorerAcquisitionUpload.ts) doesn't bypass
445
+ // test isolation.
446
+ const originalStartSession = mongoose.Model.startSession;
447
+ (mongoose.Model as any).startSession = async function (this: any, options?: any) {
448
+ if (currentTestSession) {
449
+ return {
450
+ ...currentTestSession,
451
+ startTransaction: () => {},
452
+ commitTransaction: async () => {},
453
+ abortTransaction: async () => {},
454
+ endSession: async () => {},
455
+ id: currentTestSession.id,
456
+ inTransaction: () => currentTestSession?.inTransaction() ?? false,
457
+ };
458
+ }
459
+ return originalStartSession.call(this, options);
460
+ };
461
+
462
+ // --- Collection.prototype (native driver operations) ---
463
+ // Some test files call Model.collection.insertOne() etc. directly, bypassing
464
+ // Mongoose. We patch the Mongoose Collection wrapper to inject the session
465
+ // into these operations so they participate in the test transaction.
466
+ //
467
+ // Methods are grouped by their options argument position:
468
+ // - optionsAt1: (docOrFilter, options?) — insertOne, deleteOne, deleteMany, findOne, etc.
469
+ // - optionsAt2: (filter, update, options?) — updateOne, updateMany, findOneAndUpdate, etc.
470
+ const patchCollectionMethod = (method: string, optionsIndex: number): void => {
471
+ const original = (mongoose.Collection.prototype as any)[method];
472
+ if (typeof original !== "function") {
473
+ return;
474
+ }
475
+ (mongoose.Collection.prototype as any)[method] = function (this: any, ...args: any[]) {
476
+ if (!currentTestSession) {
477
+ return original.apply(this, args);
478
+ }
479
+ if (!shouldAttachTestSessionToConnection(this.conn)) {
480
+ return original.apply(this, args);
481
+ }
482
+ return serialized(() => {
483
+ // Inject session into the options argument at the correct position
484
+ if (args[optionsIndex] && typeof args[optionsIndex] === "object") {
485
+ args[optionsIndex] = {...args[optionsIndex], session: currentTestSession};
486
+ } else {
487
+ args[optionsIndex] = {session: currentTestSession};
488
+ }
489
+ return original.apply(this, args);
490
+ });
491
+ };
492
+ };
493
+
494
+ // (docOrFilter, options?) — options at index 1
495
+ for (const method of [
496
+ "insertOne",
497
+ "insertMany",
498
+ "deleteOne",
499
+ "deleteMany",
500
+ "findOne",
501
+ "findOneAndDelete",
502
+ "countDocuments",
503
+ "aggregate",
504
+ ]) {
505
+ patchCollectionMethod(method, 1);
506
+ }
507
+
508
+ // (filter, update/replacement, options?) — options at index 2
509
+ for (const method of [
510
+ "updateOne",
511
+ "updateMany",
512
+ "findOneAndUpdate",
513
+ "findOneAndReplace",
514
+ "replaceOne",
515
+ ]) {
516
+ patchCollectionMethod(method, 2);
517
+ }
518
+
519
+ patchesInstalled = true;
520
+ if (process.env.DEBUG_TEST_TRANSACTION === "true") {
521
+ // biome-ignore lint/suspicious/noConsole: optional debug for patch installation
522
+ console.debug("[testTransaction] Mongoose patches installed");
523
+ }
524
+ };
@@ -0,0 +1,11 @@
1
+ import mongoose from "mongoose";
2
+
3
+ /** Ensures all registered Mongoose model indexes exist on the database. */
4
+ export const ensureAllIndexes = async (): Promise<void> => {
5
+ const models = Object.keys(mongoose.models);
6
+ const indexPromises: Array<Promise<unknown>> = [];
7
+ for (const modelName of models) {
8
+ indexPromises.push(mongoose.models[modelName].createIndexes());
9
+ }
10
+ await Promise.all(indexPromises);
11
+ };
@@ -0,0 +1,3 @@
1
+ export const timeout = async (ms: number): Promise<NodeJS.Timeout> => {
2
+ return new Promise((resolve) => setTimeout(resolve, ms));
3
+ };
@@ -0,0 +1,50 @@
1
+ import type {FilterQuery, Model} from "mongoose";
2
+
3
+ export interface WaitForDocumentsOptions {
4
+ timeoutMs?: number;
5
+ intervalMs?: number;
6
+ sort?: Record<string, 1 | -1>;
7
+ }
8
+
9
+ /**
10
+ * Polls until at least `count` documents match the query.
11
+ * Useful when writes are asynchronous (audit logs, webhooks, etc.).
12
+ */
13
+ export const waitForDocuments = async <T>(
14
+ model: Model<T>,
15
+ query: FilterQuery<T>,
16
+ count = 1,
17
+ {
18
+ timeoutMs = 5000,
19
+ intervalMs = 100,
20
+ sort,
21
+ }: WaitForDocumentsOptions = {}
22
+ ): Promise<T[]> => {
23
+ const start = Date.now();
24
+ while (Date.now() - start < timeoutMs) {
25
+ let q = model.find(query);
26
+ if (sort) {
27
+ q = q.sort(sort);
28
+ }
29
+ const documents = await q.exec();
30
+ if (documents.length >= count) {
31
+ return documents;
32
+ }
33
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
34
+ }
35
+
36
+ const found = await model.countDocuments(query);
37
+ throw new Error(
38
+ `Timed out after ${timeoutMs}ms waiting for ${count} document(s) on ${model.modelName} matching ${JSON.stringify(query)} (found ${found})`
39
+ );
40
+ };
41
+
42
+ /** Polls until a single document matches the query. */
43
+ export const waitForDocument = async <T>(
44
+ model: Model<T>,
45
+ query: FilterQuery<T>,
46
+ options: WaitForDocumentsOptions = {}
47
+ ): Promise<T> => {
48
+ const results = await waitForDocuments(model, query, 1, options);
49
+ return results[0];
50
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "allowSyntheticDefaultImports": true,
5
+ "baseUrl": "./",
6
+ "declaration": true,
7
+ "downlevelIteration": true,
8
+ "esModuleInterop": true,
9
+ "forceConsistentCasingInFileNames": true,
10
+ "jsx": "react",
11
+ "lib": ["es2017", "dom", "es2017.object"],
12
+ "module": "commonjs",
13
+ "moduleResolution": "node",
14
+ "noEmit": false,
15
+ "noImplicitAny": false,
16
+ "noImplicitReturns": true,
17
+ "noImplicitThis": true,
18
+ "noUnusedLocals": false,
19
+ "noUnusedParameters": false,
20
+ "outDir": "./dist",
21
+ "preserveConstEnums": true,
22
+ "removeComments": false,
23
+ "skipLibCheck": true,
24
+ "strict": true,
25
+ "strictFunctionTypes": true,
26
+ "strictNullChecks": true,
27
+ "target": "es5"
28
+ },
29
+ "exclude": ["node_modules", "src/mongo/ensureMongoBinary.ts"],
30
+ "include": ["src/**/*.ts"]
31
+ }