@jterrazz/test 5.3.2 → 6.1.0

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.
@@ -0,0 +1,32 @@
1
+ const require_chunk = require("./chunk.cjs");
2
+ let mockdate = require("mockdate");
3
+ mockdate = require_chunk.__toESM(mockdate, 1);
4
+ let vitest_mock_extended = require("vitest-mock-extended");
5
+ //#region src/mocking/mock-of-date.ts
6
+ /**
7
+ * Freeze or reset the global Date for deterministic time-dependent tests.
8
+ * Wraps the `mockdate` package.
9
+ */
10
+ const mockOfDate = mockdate.default;
11
+ //#endregion
12
+ //#region src/mocking/mock-of.ts
13
+ /**
14
+ * Create a deep mock proxy for a given type.
15
+ * Wraps `vitest-mock-extended`'s `mockDeep` for convenient port mocking.
16
+ */
17
+ const mockOf = vitest_mock_extended.mockDeep;
18
+ //#endregion
19
+ Object.defineProperty(exports, "mockOf", {
20
+ enumerable: true,
21
+ get: function() {
22
+ return mockOf;
23
+ }
24
+ });
25
+ Object.defineProperty(exports, "mockOfDate", {
26
+ enumerable: true,
27
+ get: function() {
28
+ return mockOfDate;
29
+ }
30
+ });
31
+
32
+ //# sourceMappingURL=mock-of.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mock-of.cjs","names":["MockDatePackage","mockDeep"],"sources":["../src/mocking/mock-of-date.ts","../src/mocking/mock-of.ts"],"sourcesContent":["import MockDatePackage from 'mockdate';\n\n/** Interface for freezing and resetting the global Date in tests. */\nexport interface MockDatePort {\n /** Restore the real Date object. */\n reset: () => void;\n /** Freeze `Date.now()` and `new Date()` to the given value. */\n set: (date: Date | number | string) => void;\n}\n\n/**\n * Freeze or reset the global Date for deterministic time-dependent tests.\n * Wraps the `mockdate` package.\n */\nexport const mockOfDate: MockDatePort = MockDatePackage;\n","import { type DeepMockProxy, mockDeep } from 'vitest-mock-extended';\n\n/** Factory signature that creates a deep mock proxy for any interface. */\nexport type MockPort = <T>() => DeepMockProxy<T>;\n\n/**\n * Create a deep mock proxy for a given type.\n * Wraps `vitest-mock-extended`'s `mockDeep` for convenient port mocking.\n */\nexport const mockOf: MockPort = mockDeep;\n"],"mappings":";;;;;;;;;AAcA,MAAa,aAA2BA,SAAAA;;;;;;;ACLxC,MAAa,SAAmBC,qBAAAA"}
@@ -0,0 +1,27 @@
1
+ import { DeepMockProxy } from "vitest-mock-extended";
2
+
3
+ //#region src/mocking/mock-of-date.d.ts
4
+ /** Interface for freezing and resetting the global Date in tests. */
5
+ interface MockDatePort {
6
+ /** Restore the real Date object. */
7
+ reset: () => void;
8
+ /** Freeze `Date.now()` and `new Date()` to the given value. */
9
+ set: (date: Date | number | string) => void;
10
+ }
11
+ /**
12
+ * Freeze or reset the global Date for deterministic time-dependent tests.
13
+ * Wraps the `mockdate` package.
14
+ */
15
+ declare const mockOfDate: MockDatePort;
16
+ //#endregion
17
+ //#region src/mocking/mock-of.d.ts
18
+ /** Factory signature that creates a deep mock proxy for any interface. */
19
+ type MockPort = <T>() => DeepMockProxy<T>;
20
+ /**
21
+ * Create a deep mock proxy for a given type.
22
+ * Wraps `vitest-mock-extended`'s `mockDeep` for convenient port mocking.
23
+ */
24
+ declare const mockOf: MockPort;
25
+ //#endregion
26
+ export { mockOfDate as i, mockOf as n, MockDatePort as r, MockPort as t };
27
+ //# sourceMappingURL=mock-of.d.cts.map
@@ -0,0 +1,27 @@
1
+ import { DeepMockProxy } from "vitest-mock-extended";
2
+
3
+ //#region src/mocking/mock-of-date.d.ts
4
+ /** Interface for freezing and resetting the global Date in tests. */
5
+ interface MockDatePort {
6
+ /** Restore the real Date object. */
7
+ reset: () => void;
8
+ /** Freeze `Date.now()` and `new Date()` to the given value. */
9
+ set: (date: Date | number | string) => void;
10
+ }
11
+ /**
12
+ * Freeze or reset the global Date for deterministic time-dependent tests.
13
+ * Wraps the `mockdate` package.
14
+ */
15
+ declare const mockOfDate: MockDatePort;
16
+ //#endregion
17
+ //#region src/mocking/mock-of.d.ts
18
+ /** Factory signature that creates a deep mock proxy for any interface. */
19
+ type MockPort = <T>() => DeepMockProxy<T>;
20
+ /**
21
+ * Create a deep mock proxy for a given type.
22
+ * Wraps `vitest-mock-extended`'s `mockDeep` for convenient port mocking.
23
+ */
24
+ declare const mockOf: MockPort;
25
+ //#endregion
26
+ export { mockOfDate as i, mockOf as n, MockDatePort as r, MockPort as t };
27
+ //# sourceMappingURL=mock-of.d.ts.map
@@ -0,0 +1,19 @@
1
+ import MockDatePackage from "mockdate";
2
+ import { mockDeep } from "vitest-mock-extended";
3
+ //#region src/mocking/mock-of-date.ts
4
+ /**
5
+ * Freeze or reset the global Date for deterministic time-dependent tests.
6
+ * Wraps the `mockdate` package.
7
+ */
8
+ const mockOfDate = MockDatePackage;
9
+ //#endregion
10
+ //#region src/mocking/mock-of.ts
11
+ /**
12
+ * Create a deep mock proxy for a given type.
13
+ * Wraps `vitest-mock-extended`'s `mockDeep` for convenient port mocking.
14
+ */
15
+ const mockOf = mockDeep;
16
+ //#endregion
17
+ export { mockOfDate as n, mockOf as t };
18
+
19
+ //# sourceMappingURL=mock-of.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mock-of.js","names":[],"sources":["../src/mocking/mock-of-date.ts","../src/mocking/mock-of.ts"],"sourcesContent":["import MockDatePackage from 'mockdate';\n\n/** Interface for freezing and resetting the global Date in tests. */\nexport interface MockDatePort {\n /** Restore the real Date object. */\n reset: () => void;\n /** Freeze `Date.now()` and `new Date()` to the given value. */\n set: (date: Date | number | string) => void;\n}\n\n/**\n * Freeze or reset the global Date for deterministic time-dependent tests.\n * Wraps the `mockdate` package.\n */\nexport const mockOfDate: MockDatePort = MockDatePackage;\n","import { type DeepMockProxy, mockDeep } from 'vitest-mock-extended';\n\n/** Factory signature that creates a deep mock proxy for any interface. */\nexport type MockPort = <T>() => DeepMockProxy<T>;\n\n/**\n * Create a deep mock proxy for a given type.\n * Wraps `vitest-mock-extended`'s `mockDeep` for convenient port mocking.\n */\nexport const mockOf: MockPort = mockDeep;\n"],"mappings":";;;;;;;AAcA,MAAa,aAA2B;;;;;;;ACLxC,MAAa,SAAmB"}
package/dist/mock.cjs ADDED
@@ -0,0 +1,4 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_mock_of = require("./mock-of.cjs");
3
+ exports.mockOf = require_mock_of.mockOf;
4
+ exports.mockOfDate = require_mock_of.mockOfDate;
@@ -0,0 +1,2 @@
1
+ import { i as mockOfDate, n as mockOf, r as MockDatePort, t as MockPort } from "./mock-of.cjs";
2
+ export { type MockDatePort, type MockPort, mockOf, mockOfDate };
package/dist/mock.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { i as mockOfDate, n as mockOf, r as MockDatePort, t as MockPort } from "./mock-of.js";
2
+ export { type MockDatePort, type MockPort, mockOf, mockOfDate };
package/dist/mock.js ADDED
@@ -0,0 +1,2 @@
1
+ import { n as mockOfDate, t as mockOf } from "./mock-of.js";
2
+ export { mockOf, mockOfDate };
@@ -0,0 +1,5 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sqlite_adapter = require("./sqlite.adapter.cjs");
3
+ exports.postgres = require_sqlite_adapter.postgres;
4
+ exports.redis = require_sqlite_adapter.redis;
5
+ exports.sqlite = require_sqlite_adapter.sqlite;
@@ -0,0 +1,2 @@
1
+ import { a as PostgresOptions, i as redis, n as sqlite, o as postgres, r as RedisOptions, t as SqliteOptions } from "./sqlite.adapter.cjs";
2
+ export { type PostgresOptions, type RedisOptions, type SqliteOptions, postgres, redis, sqlite };
@@ -0,0 +1,2 @@
1
+ import { a as PostgresOptions, i as redis, n as sqlite, o as postgres, r as RedisOptions, t as SqliteOptions } from "./sqlite.adapter.js";
2
+ export { type PostgresOptions, type RedisOptions, type SqliteOptions, postgres, redis, sqlite };
@@ -0,0 +1,2 @@
1
+ import { n as redis, r as postgres, t as sqlite } from "./sqlite.adapter.js";
2
+ export { postgres, redis, sqlite };
@@ -0,0 +1,331 @@
1
+ const require_chunk = require("./chunk.cjs");
2
+ let node_fs = require("node:fs");
3
+ let node_os = require("node:os");
4
+ let node_path = require("node:path");
5
+ let pg = require("pg");
6
+ let better_sqlite3 = require("better-sqlite3");
7
+ better_sqlite3 = require_chunk.__toESM(better_sqlite3, 1);
8
+ //#region src/adapters/postgres.adapter.ts
9
+ var PostgresHandle = class {
10
+ type = "postgres";
11
+ composeName;
12
+ defaultPort = 5432;
13
+ defaultImage;
14
+ environment;
15
+ connectionString = "";
16
+ started = false;
17
+ client = null;
18
+ originalConnectionString = "";
19
+ schema = "public";
20
+ constructor(options = {}) {
21
+ this.composeName = options.compose ?? null;
22
+ this.defaultImage = options.image ?? "postgres:17";
23
+ this.environment = {
24
+ POSTGRES_DB: "test",
25
+ POSTGRES_PASSWORD: "test",
26
+ POSTGRES_USER: "test",
27
+ ...options.env
28
+ };
29
+ }
30
+ buildConnectionString(host, port) {
31
+ return `postgresql://${this.environment.POSTGRES_USER ?? "test"}:${this.environment.POSTGRES_PASSWORD ?? "test"}@${host}:${port}/${this.environment.POSTGRES_DB ?? "test"}`;
32
+ }
33
+ createDatabaseAdapter() {
34
+ return this;
35
+ }
36
+ async healthcheck() {
37
+ if (!this.connectionString) throw new Error("postgres: cannot healthcheck — no connection string");
38
+ try {
39
+ const client = new pg.Client({ connectionString: this.connectionString });
40
+ await client.connect();
41
+ await client.query("SELECT 1");
42
+ await client.end();
43
+ } catch (error) {
44
+ throw new Error(`postgres healthcheck failed: ${error.message || error.code || String(error)}`, { cause: error });
45
+ }
46
+ }
47
+ async initialize(composeDir) {
48
+ if (!this.composeName) return;
49
+ const initPaths = [(0, node_path.resolve)(composeDir, `${this.composeName}/init.sql`), (0, node_path.resolve)(composeDir, "postgres/init.sql")];
50
+ for (const initPath of initPaths) if ((0, node_fs.existsSync)(initPath)) {
51
+ const sql = (0, node_fs.readFileSync)(initPath, "utf8");
52
+ try {
53
+ await this.seed(sql);
54
+ } catch (error) {
55
+ throw new Error(`postgres init script failed (${initPath}):\n${error.message}`, { cause: error });
56
+ }
57
+ return;
58
+ }
59
+ }
60
+ async getClient() {
61
+ if (this.client) return this.client;
62
+ const client = new pg.Client({ connectionString: this.connectionString });
63
+ client.on("error", () => {
64
+ this.client = null;
65
+ });
66
+ await client.connect();
67
+ this.client = client;
68
+ return client;
69
+ }
70
+ async seed(sql) {
71
+ await (await this.getClient()).query(sql);
72
+ }
73
+ async reset() {
74
+ const client = await this.getClient();
75
+ const result = await client.query(`
76
+ SELECT tablename FROM pg_tables
77
+ WHERE schemaname = '${this.schema}'
78
+ AND tablename NOT LIKE '_prisma%'
79
+ `);
80
+ for (const row of result.rows) await client.query(`TRUNCATE "${this.schema}"."${row.tablename}" CASCADE`);
81
+ }
82
+ async query(table, columns) {
83
+ const client = await this.getClient();
84
+ const columnList = columns.join(", ");
85
+ return (await client.query(`SELECT ${columnList} FROM "${this.schema}"."${table}" ORDER BY 1`)).rows.map((row) => columns.map((col) => row[col]));
86
+ }
87
+ isolation() {
88
+ return {
89
+ acquire: async (workerId) => {
90
+ const workerSchema = `worker_${workerId}`;
91
+ this.originalConnectionString = this.connectionString;
92
+ const client = await this.getClient();
93
+ await client.query(`DROP SCHEMA IF EXISTS "${workerSchema}" CASCADE`);
94
+ await client.query(`CREATE SCHEMA "${workerSchema}"`);
95
+ const tables = await client.query(`
96
+ SELECT tablename FROM pg_tables
97
+ WHERE schemaname = 'public'
98
+ AND tablename NOT LIKE '_prisma%'
99
+ `);
100
+ for (const row of tables.rows) await client.query(`CREATE TABLE "${workerSchema}"."${row.tablename}" (LIKE "public"."${row.tablename}" INCLUDING ALL)`);
101
+ this.schema = workerSchema;
102
+ await client.query(`SET search_path TO "${workerSchema}", public`);
103
+ const url = new URL(this.connectionString);
104
+ url.searchParams.set("options", `-c search_path=${workerSchema},public`);
105
+ this.connectionString = url.toString();
106
+ },
107
+ reset: async () => {
108
+ await this.reset();
109
+ },
110
+ release: async () => {
111
+ const client = await this.getClient();
112
+ const workerSchema = this.schema;
113
+ this.schema = "public";
114
+ this.connectionString = this.originalConnectionString;
115
+ await client.query(`SET search_path TO public`);
116
+ await client.query(`DROP SCHEMA IF EXISTS "${workerSchema}" CASCADE`);
117
+ }
118
+ };
119
+ }
120
+ };
121
+ /**
122
+ * Create a PostgreSQL service handle.
123
+ *
124
+ * @example
125
+ * const db = postgres({ compose: "db" });
126
+ * // After start: db.connectionString is populated
127
+ */
128
+ function postgres(options = {}) {
129
+ return new PostgresHandle(options);
130
+ }
131
+ //#endregion
132
+ //#region src/adapters/redis.adapter.ts
133
+ var RedisHandle = class {
134
+ type = "redis";
135
+ composeName;
136
+ defaultPort = 6379;
137
+ defaultImage;
138
+ environment = {};
139
+ connectionString = "";
140
+ started = false;
141
+ dbIndex = 0;
142
+ constructor(options = {}) {
143
+ this.composeName = options.compose ?? null;
144
+ this.defaultImage = options.image ?? "redis:7";
145
+ }
146
+ buildConnectionString(host, port) {
147
+ return `redis://${host}:${port}`;
148
+ }
149
+ createDatabaseAdapter() {
150
+ return null;
151
+ }
152
+ async healthcheck() {
153
+ if (!this.connectionString) throw new Error("redis: cannot healthcheck — no connection string");
154
+ try {
155
+ const { createClient } = await import("redis");
156
+ const client = createClient({ url: this.connectionString });
157
+ await client.connect();
158
+ await client.ping();
159
+ await client.disconnect();
160
+ } catch (error) {
161
+ throw new Error(`redis healthcheck failed: ${error.message || error.code || String(error)}`, { cause: error });
162
+ }
163
+ }
164
+ async initialize() {}
165
+ async reset() {
166
+ const { createClient } = await import("redis");
167
+ const client = createClient({
168
+ url: this.connectionString,
169
+ database: this.dbIndex
170
+ });
171
+ await client.connect();
172
+ try {
173
+ await client.flushDb();
174
+ } finally {
175
+ await client.disconnect();
176
+ }
177
+ }
178
+ isolation() {
179
+ return {
180
+ acquire: async (workerId) => {
181
+ this.dbIndex = (Number.parseInt(workerId, 10) || 0) % 15 + 1;
182
+ },
183
+ reset: async () => {
184
+ await this.reset();
185
+ },
186
+ release: async () => {
187
+ await this.reset();
188
+ this.dbIndex = 0;
189
+ }
190
+ };
191
+ }
192
+ };
193
+ /**
194
+ * Create a Redis service handle.
195
+ *
196
+ * @example
197
+ * const cache = redis({ compose: "cache" });
198
+ * // After start: cache.connectionString is populated
199
+ */
200
+ function redis(options = {}) {
201
+ return new RedisHandle(options);
202
+ }
203
+ //#endregion
204
+ //#region src/adapters/sqlite.adapter.ts
205
+ var SqliteHandle = class {
206
+ type = "sqlite";
207
+ composeName = null;
208
+ defaultPort = 0;
209
+ defaultImage = "";
210
+ environment = {};
211
+ connectionString = "";
212
+ started = false;
213
+ db = null;
214
+ templatePath = "";
215
+ workerDbPath = "";
216
+ initSql;
217
+ prismaSchema;
218
+ constructor(options = {}) {
219
+ this.initSql = options.init ?? null;
220
+ this.prismaSchema = options.prismaSchema ?? null;
221
+ }
222
+ buildConnectionString() {
223
+ return `file:${this.workerDbPath || this.templatePath}`;
224
+ }
225
+ createDatabaseAdapter() {
226
+ return this;
227
+ }
228
+ async healthcheck() {}
229
+ async initialize() {
230
+ this.templatePath = (0, node_path.resolve)((0, node_os.tmpdir)(), `test-template-${Date.now()}.sqlite`);
231
+ if (this.prismaSchema) {
232
+ const { execSync } = await import("node:child_process");
233
+ execSync("npx prisma db push --force-reset --skip-generate", {
234
+ env: {
235
+ ...process.env,
236
+ DATABASE_URL: `file:${this.templatePath}`
237
+ },
238
+ stdio: "pipe"
239
+ });
240
+ } else if (this.initSql) {
241
+ const sql = (0, node_fs.readFileSync)(this.initSql, "utf8");
242
+ const templateDb = new better_sqlite3.default(this.templatePath);
243
+ templateDb.exec(sql);
244
+ templateDb.close();
245
+ } else new better_sqlite3.default(this.templatePath).close();
246
+ this.connectionString = `file:${this.templatePath}`;
247
+ this.started = true;
248
+ }
249
+ getDb() {
250
+ const dbPath = this.workerDbPath || this.templatePath;
251
+ if (!this.db) {
252
+ this.db = new better_sqlite3.default(dbPath);
253
+ this.db.pragma("journal_mode = WAL");
254
+ }
255
+ return this.db;
256
+ }
257
+ closeDb() {
258
+ if (this.db) {
259
+ this.db.close();
260
+ this.db = null;
261
+ }
262
+ }
263
+ async seed(sql) {
264
+ this.getDb().exec(sql);
265
+ }
266
+ async query(table, columns) {
267
+ const columnList = columns.join(", ");
268
+ return this.getDb().prepare(`SELECT ${columnList} FROM "${table}" ORDER BY 1`).all().map((row) => columns.map((col) => row[col]));
269
+ }
270
+ async reset() {
271
+ const db = this.getDb();
272
+ const tables = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE '_prisma%' AND name != 'sqlite_sequence'`).all();
273
+ for (const { name } of tables) db.exec(`DELETE FROM "${name}"`);
274
+ }
275
+ isolation() {
276
+ return {
277
+ acquire: async (workerId) => {
278
+ this.closeDb();
279
+ this.workerDbPath = (0, node_path.resolve)((0, node_os.tmpdir)(), `test-worker-${workerId}-${Date.now()}.sqlite`);
280
+ (0, node_fs.copyFileSync)(this.templatePath, this.workerDbPath);
281
+ this.connectionString = `file:${this.workerDbPath}`;
282
+ },
283
+ reset: async () => {
284
+ await this.reset();
285
+ },
286
+ release: async () => {
287
+ this.closeDb();
288
+ if (this.workerDbPath && (0, node_fs.existsSync)(this.workerDbPath)) (0, node_fs.unlinkSync)(this.workerDbPath);
289
+ this.workerDbPath = "";
290
+ this.connectionString = `file:${this.templatePath}`;
291
+ }
292
+ };
293
+ }
294
+ };
295
+ /**
296
+ * Create a SQLite service handle. Uses file-copy isolation for parallel tests.
297
+ *
298
+ * @example
299
+ * // With Prisma schema
300
+ * const db = sqlite({ prismaSchema: './prisma/schema' });
301
+ *
302
+ * // With raw SQL init
303
+ * const db = sqlite({ init: './schema.sql' });
304
+ *
305
+ * // Empty database
306
+ * const db = sqlite();
307
+ */
308
+ function sqlite(options = {}) {
309
+ return new SqliteHandle(options);
310
+ }
311
+ //#endregion
312
+ Object.defineProperty(exports, "postgres", {
313
+ enumerable: true,
314
+ get: function() {
315
+ return postgres;
316
+ }
317
+ });
318
+ Object.defineProperty(exports, "redis", {
319
+ enumerable: true,
320
+ get: function() {
321
+ return redis;
322
+ }
323
+ });
324
+ Object.defineProperty(exports, "sqlite", {
325
+ enumerable: true,
326
+ get: function() {
327
+ return sqlite;
328
+ }
329
+ });
330
+
331
+ //# sourceMappingURL=sqlite.adapter.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite.adapter.cjs","names":["Client","Database"],"sources":["../src/adapters/postgres.adapter.ts","../src/adapters/redis.adapter.ts","../src/adapters/sqlite.adapter.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { Client } from 'pg';\n\nimport type { DatabasePort } from '../ports/database.port.js';\nimport type { IsolationStrategy } from '../ports/isolation.port.js';\nimport type { ServiceHandle } from '../ports/service.port.js';\n\nexport interface PostgresOptions {\n /** Map to a service in docker-compose.test.yaml. */\n compose?: string;\n /** Override image. */\n image?: string;\n /** Override environment variables. */\n env?: Record<string, string>;\n}\n\nexport class PostgresHandle implements DatabasePort, ServiceHandle {\n readonly type = 'postgres';\n readonly composeName: null | string;\n readonly defaultPort = 5432;\n readonly defaultImage: string;\n readonly environment: Record<string, string>;\n\n connectionString = '';\n started = false;\n\n private client: Client | null = null;\n private originalConnectionString = '';\n private schema = 'public';\n\n constructor(options: PostgresOptions = {}) {\n this.composeName = options.compose ?? null;\n this.defaultImage = options.image ?? 'postgres:17';\n this.environment = {\n POSTGRES_DB: 'test',\n POSTGRES_PASSWORD: 'test',\n POSTGRES_USER: 'test',\n ...options.env,\n };\n }\n\n buildConnectionString(host: string, port: number): string {\n const user = this.environment.POSTGRES_USER ?? 'test';\n const password = this.environment.POSTGRES_PASSWORD ?? 'test';\n const db = this.environment.POSTGRES_DB ?? 'test';\n return `postgresql://${user}:${password}@${host}:${port}/${db}`;\n }\n\n createDatabaseAdapter(): DatabasePort {\n return this;\n }\n\n async healthcheck(): Promise<void> {\n if (!this.connectionString) {\n throw new Error('postgres: cannot healthcheck — no connection string');\n }\n\n // Healthcheck uses a throwaway client (connection might not be established yet)\n try {\n const client = new Client({ connectionString: this.connectionString });\n await client.connect();\n await client.query('SELECT 1');\n await client.end();\n } catch (error: any) {\n throw new Error(\n `postgres healthcheck failed: ${error.message || error.code || String(error)}`,\n { cause: error },\n );\n }\n }\n\n async initialize(composeDir: string): Promise<void> {\n if (!this.composeName) {\n return;\n }\n\n const initPaths = [\n resolve(composeDir, `${this.composeName}/init.sql`),\n resolve(composeDir, 'postgres/init.sql'),\n ];\n\n for (const initPath of initPaths) {\n if (existsSync(initPath)) {\n const sql = readFileSync(initPath, 'utf8');\n try {\n await this.seed(sql);\n } catch (error: any) {\n throw new Error(\n `postgres init script failed (${initPath}):\\n${error.message}`,\n {\n cause: error,\n },\n );\n }\n return;\n }\n }\n }\n\n private async getClient(): Promise<Client> {\n if (this.client) {\n return this.client;\n }\n const client = new Client({ connectionString: this.connectionString });\n client.on('error', () => {\n // Connection dropped (container stopped) — reset so next call reconnects\n this.client = null;\n });\n await client.connect();\n this.client = client;\n return client;\n }\n\n async seed(sql: string): Promise<void> {\n const client = await this.getClient();\n await client.query(sql);\n }\n\n async reset(): Promise<void> {\n const client = await this.getClient();\n const result = await client.query(`\n SELECT tablename FROM pg_tables\n WHERE schemaname = '${this.schema}'\n AND tablename NOT LIKE '_prisma%'\n `);\n for (const row of result.rows) {\n await client.query(`TRUNCATE \"${this.schema}\".\"${row.tablename}\" CASCADE`);\n }\n }\n\n async query(table: string, columns: string[]): Promise<unknown[][]> {\n const client = await this.getClient();\n const columnList = columns.join(', ');\n const result = await client.query(\n `SELECT ${columnList} FROM \"${this.schema}\".\"${table}\" ORDER BY 1`,\n );\n return result.rows.map((row: Record<string, unknown>) => columns.map((col) => row[col]));\n }\n\n isolation(): IsolationStrategy {\n return {\n acquire: async (workerId: string) => {\n const workerSchema = `worker_${workerId}`;\n this.originalConnectionString = this.connectionString;\n const client = await this.getClient();\n\n // Create schema by cloning all tables from public\n await client.query(`DROP SCHEMA IF EXISTS \"${workerSchema}\" CASCADE`);\n await client.query(`CREATE SCHEMA \"${workerSchema}\"`);\n\n // Copy table structures (no data) from public\n const tables = await client.query(`\n SELECT tablename FROM pg_tables\n WHERE schemaname = 'public'\n AND tablename NOT LIKE '_prisma%'\n `);\n for (const row of tables.rows) {\n await client.query(\n `CREATE TABLE \"${workerSchema}\".\"${row.tablename}\" (LIKE \"public\".\"${row.tablename}\" INCLUDING ALL)`,\n );\n }\n\n // Switch this handle to use the worker schema\n this.schema = workerSchema;\n await client.query(`SET search_path TO \"${workerSchema}\", public`);\n\n // Update connectionString so app connections also use the worker schema\n const url = new URL(this.connectionString);\n url.searchParams.set('options', `-c search_path=${workerSchema},public`);\n this.connectionString = url.toString();\n },\n\n reset: async () => {\n await this.reset();\n },\n\n release: async () => {\n const client = await this.getClient();\n const workerSchema = this.schema;\n this.schema = 'public';\n this.connectionString = this.originalConnectionString;\n await client.query(`SET search_path TO public`);\n await client.query(`DROP SCHEMA IF EXISTS \"${workerSchema}\" CASCADE`);\n },\n };\n }\n}\n\n/**\n * Create a PostgreSQL service handle.\n *\n * @example\n * const db = postgres({ compose: \"db\" });\n * // After start: db.connectionString is populated\n */\nexport function postgres(options: PostgresOptions = {}): PostgresHandle {\n return new PostgresHandle(options);\n}\n","import type { DatabasePort } from '../ports/database.port.js';\nimport type { IsolationStrategy } from '../ports/isolation.port.js';\nimport type { ServiceHandle } from '../ports/service.port.js';\n\nexport interface RedisOptions {\n /** Map to a service in docker-compose.test.yaml. */\n compose?: string;\n /** Override image. */\n image?: string;\n}\n\nexport class RedisHandle implements ServiceHandle {\n readonly type = 'redis';\n readonly composeName: null | string;\n readonly defaultPort = 6379;\n readonly defaultImage: string;\n readonly environment: Record<string, string> = {};\n\n connectionString = '';\n started = false;\n\n private dbIndex = 0;\n\n constructor(options: RedisOptions = {}) {\n this.composeName = options.compose ?? null;\n this.defaultImage = options.image ?? 'redis:7';\n }\n\n buildConnectionString(host: string, port: number): string {\n return `redis://${host}:${port}`;\n }\n\n createDatabaseAdapter(): DatabasePort | null {\n return null;\n }\n\n async healthcheck(): Promise<void> {\n if (!this.connectionString) {\n throw new Error('redis: cannot healthcheck — no connection string');\n }\n\n try {\n const { createClient } = await import('redis');\n const client = createClient({ url: this.connectionString });\n await client.connect();\n await client.ping();\n await client.disconnect();\n } catch (error: any) {\n throw new Error(\n `redis healthcheck failed: ${error.message || error.code || String(error)}`,\n {\n cause: error,\n },\n );\n }\n }\n\n async initialize(): Promise<void> {\n // Redis doesn't need initialization scripts\n }\n\n async reset(): Promise<void> {\n const { createClient } = await import('redis');\n const client = createClient({ url: this.connectionString, database: this.dbIndex });\n await client.connect();\n try {\n await client.flushDb();\n } finally {\n await client.disconnect();\n }\n }\n\n isolation(): IsolationStrategy {\n return {\n acquire: async (workerId: string) => {\n // Use Redis database index 1-15 for workers (0 is default/shared)\n const numericId = Number.parseInt(workerId, 10) || 0;\n this.dbIndex = (numericId % 15) + 1;\n },\n\n reset: async () => {\n await this.reset();\n },\n\n release: async () => {\n await this.reset();\n this.dbIndex = 0;\n },\n };\n }\n}\n\n/**\n * Create a Redis service handle.\n *\n * @example\n * const cache = redis({ compose: \"cache\" });\n * // After start: cache.connectionString is populated\n */\nexport function redis(options: RedisOptions = {}): RedisHandle {\n return new RedisHandle(options);\n}\n","import Database from 'better-sqlite3';\nimport { copyFileSync, existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { resolve } from 'node:path';\n\nimport type { DatabasePort } from '../ports/database.port.js';\nimport type { IsolationStrategy } from '../ports/isolation.port.js';\nimport type { ServiceHandle } from '../ports/service.port.js';\n\nexport interface SqliteOptions {\n /**\n * Path to a SQL file used to initialize the database schema.\n * Mutually exclusive with `prismaSchema`.\n */\n init?: string;\n /**\n * Path to a Prisma schema directory or file.\n * The adapter runs `prisma db push` to create the template.\n * Mutually exclusive with `init`.\n */\n prismaSchema?: string;\n}\n\nexport class SqliteHandle implements DatabasePort, ServiceHandle {\n readonly type = 'sqlite';\n readonly composeName = null;\n readonly defaultPort = 0;\n readonly defaultImage = '';\n readonly environment: Record<string, string> = {};\n\n connectionString = '';\n started = false;\n\n private db: Database.Database | null = null;\n private templatePath = '';\n private workerDbPath = '';\n private initSql: null | string;\n private prismaSchema: null | string;\n\n constructor(options: SqliteOptions = {}) {\n this.initSql = options.init ?? null;\n this.prismaSchema = options.prismaSchema ?? null;\n }\n\n buildConnectionString(): string {\n return `file:${this.workerDbPath || this.templatePath}`;\n }\n\n createDatabaseAdapter(): DatabasePort {\n return this;\n }\n\n async healthcheck(): Promise<void> {\n // SQLite is always ready — it's a file\n }\n\n async initialize(): Promise<void> {\n // Create the template database\n this.templatePath = resolve(tmpdir(), `test-template-${Date.now()}.sqlite`);\n\n if (this.prismaSchema) {\n // Use Prisma to create schema\n const { execSync } = await import('node:child_process');\n execSync('npx prisma db push --force-reset --skip-generate', {\n env: {\n ...process.env,\n DATABASE_URL: `file:${this.templatePath}`,\n },\n stdio: 'pipe',\n });\n } else if (this.initSql) {\n // Use raw SQL to create schema\n const sql = readFileSync(this.initSql, 'utf8');\n const templateDb = new Database(this.templatePath);\n templateDb.exec(sql);\n templateDb.close();\n } else {\n // Empty database — consumer will seed\n const templateDb = new Database(this.templatePath);\n templateDb.close();\n }\n\n this.connectionString = `file:${this.templatePath}`;\n this.started = true;\n }\n\n private getDb(): Database.Database {\n const dbPath = this.workerDbPath || this.templatePath;\n if (!this.db) {\n this.db = new Database(dbPath);\n this.db.pragma('journal_mode = WAL');\n }\n return this.db;\n }\n\n private closeDb(): void {\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n }\n\n async seed(sql: string): Promise<void> {\n this.getDb().exec(sql);\n }\n\n async query(table: string, columns: string[]): Promise<unknown[][]> {\n const columnList = columns.join(', ');\n const rows = this.getDb()\n .prepare(`SELECT ${columnList} FROM \"${table}\" ORDER BY 1`)\n .all() as Record<string, unknown>[];\n return rows.map((row) => columns.map((col) => row[col]));\n }\n\n async reset(): Promise<void> {\n const db = this.getDb();\n const tables = db\n .prepare(\n `SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE '_prisma%' AND name != 'sqlite_sequence'`,\n )\n .all() as { name: string }[];\n for (const { name } of tables) {\n db.exec(`DELETE FROM \"${name}\"`);\n }\n }\n\n isolation(): IsolationStrategy {\n return {\n acquire: async (workerId: string) => {\n this.closeDb();\n this.workerDbPath = resolve(\n tmpdir(),\n `test-worker-${workerId}-${Date.now()}.sqlite`,\n );\n copyFileSync(this.templatePath, this.workerDbPath);\n this.connectionString = `file:${this.workerDbPath}`;\n },\n\n reset: async () => {\n await this.reset();\n },\n\n release: async () => {\n this.closeDb();\n if (this.workerDbPath && existsSync(this.workerDbPath)) {\n unlinkSync(this.workerDbPath);\n }\n this.workerDbPath = '';\n this.connectionString = `file:${this.templatePath}`;\n },\n };\n }\n}\n\n/**\n * Create a SQLite service handle. Uses file-copy isolation for parallel tests.\n *\n * @example\n * // With Prisma schema\n * const db = sqlite({ prismaSchema: './prisma/schema' });\n *\n * // With raw SQL init\n * const db = sqlite({ init: './schema.sql' });\n *\n * // Empty database\n * const db = sqlite();\n */\nexport function sqlite(options: SqliteOptions = {}): SqliteHandle {\n return new SqliteHandle(options);\n}\n"],"mappings":";;;;;;;;AAiBA,IAAa,iBAAb,MAAmE;CAC/D,OAAgB;CAChB;CACA,cAAuB;CACvB;CACA;CAEA,mBAAmB;CACnB,UAAU;CAEV,SAAgC;CAChC,2BAAmC;CACnC,SAAiB;CAEjB,YAAY,UAA2B,EAAE,EAAE;AACvC,OAAK,cAAc,QAAQ,WAAW;AACtC,OAAK,eAAe,QAAQ,SAAS;AACrC,OAAK,cAAc;GACf,aAAa;GACb,mBAAmB;GACnB,eAAe;GACf,GAAG,QAAQ;GACd;;CAGL,sBAAsB,MAAc,MAAsB;AAItD,SAAO,gBAHM,KAAK,YAAY,iBAAiB,OAGnB,GAFX,KAAK,YAAY,qBAAqB,OAEf,GAAG,KAAK,GAAG,KAAK,GAD7C,KAAK,YAAY,eAAe;;CAI/C,wBAAsC;AAClC,SAAO;;CAGX,MAAM,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