neon-testing 2.7.0 → 3.0.0-beta.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 (80) hide show
  1. package/README.md +58 -41
  2. package/dist/bun.d.ts +11 -0
  3. package/dist/bun.d.ts.map +1 -0
  4. package/dist/bun.js +10 -0
  5. package/dist/bun.js.map +1 -0
  6. package/dist/{index.d.ts → core.d.ts} +49 -29
  7. package/dist/core.d.ts.map +1 -0
  8. package/dist/{index.js → core.js} +34 -122
  9. package/dist/core.js.map +1 -0
  10. package/dist/lib/barrier.d.ts.map +1 -0
  11. package/dist/lib/barrier.js.map +1 -0
  12. package/dist/lib/cleared-database-url.d.ts +10 -0
  13. package/dist/lib/cleared-database-url.d.ts.map +1 -0
  14. package/dist/lib/cleared-database-url.js +10 -0
  15. package/dist/lib/cleared-database-url.js.map +1 -0
  16. package/dist/lib/expires-in.d.ts +5 -0
  17. package/dist/lib/expires-in.d.ts.map +1 -0
  18. package/dist/lib/expires-in.js +21 -0
  19. package/dist/lib/expires-in.js.map +1 -0
  20. package/dist/lib/singleton.d.ts.map +1 -0
  21. package/dist/lib/singleton.js.map +1 -0
  22. package/dist/lib/ssl.d.ts +9 -0
  23. package/dist/lib/ssl.d.ts.map +1 -0
  24. package/dist/lib/ssl.js +21 -0
  25. package/dist/lib/ssl.js.map +1 -0
  26. package/dist/lib/with-retry.d.ts +12 -0
  27. package/dist/lib/with-retry.d.ts.map +1 -0
  28. package/dist/lib/with-retry.js +39 -0
  29. package/dist/lib/with-retry.js.map +1 -0
  30. package/dist/lib/ws-error.d.ts +6 -0
  31. package/dist/lib/ws-error.d.ts.map +1 -0
  32. package/dist/lib/ws-error.js +15 -0
  33. package/dist/lib/ws-error.js.map +1 -0
  34. package/dist/setup.d.ts +2 -0
  35. package/dist/setup.d.ts.map +1 -0
  36. package/dist/setup.js +9 -0
  37. package/dist/setup.js.map +1 -0
  38. package/dist/utils.d.ts +2 -8
  39. package/dist/utils.d.ts.map +1 -1
  40. package/dist/utils.js +2 -8
  41. package/dist/utils.js.map +1 -1
  42. package/dist/vitest.d.ts +11 -0
  43. package/dist/vitest.d.ts.map +1 -0
  44. package/dist/vitest.js +9 -0
  45. package/dist/vitest.js.map +1 -0
  46. package/package.json +62 -30
  47. package/src/bun.ts +13 -0
  48. package/src/core.ts +375 -0
  49. package/src/lib/barrier.ts +22 -0
  50. package/src/lib/cleared-database-url.ts +9 -0
  51. package/src/lib/expires-in.ts +24 -0
  52. package/src/lib/singleton.ts +10 -0
  53. package/src/lib/ssl.ts +24 -0
  54. package/src/lib/with-retry.ts +55 -0
  55. package/src/lib/ws-error.ts +17 -0
  56. package/src/setup.ts +10 -0
  57. package/src/utils.ts +2 -0
  58. package/src/vitest.ts +12 -0
  59. package/dist/barrier.d.ts.map +0 -1
  60. package/dist/barrier.js.map +0 -1
  61. package/dist/browser-empty.d.ts +0 -2
  62. package/dist/browser-empty.d.ts.map +0 -1
  63. package/dist/browser-empty.js +0 -4
  64. package/dist/browser-empty.js.map +0 -1
  65. package/dist/index.d.ts.map +0 -1
  66. package/dist/index.js.map +0 -1
  67. package/dist/singleton.d.ts.map +0 -1
  68. package/dist/singleton.js.map +0 -1
  69. package/dist/vite-plugin.d.ts +0 -13
  70. package/dist/vite-plugin.d.ts.map +0 -1
  71. package/dist/vite-plugin.js +0 -26
  72. package/dist/vite-plugin.js.map +0 -1
  73. package/dist/vitest-setup.d.ts +0 -3
  74. package/dist/vitest-setup.d.ts.map +0 -1
  75. package/dist/vitest-setup.js +0 -10
  76. package/dist/vitest-setup.js.map +0 -1
  77. /package/dist/{barrier.d.ts → lib/barrier.d.ts} +0 -0
  78. /package/dist/{barrier.js → lib/barrier.js} +0 -0
  79. /package/dist/{singleton.d.ts → lib/singleton.d.ts} +0 -0
  80. /package/dist/{singleton.js → lib/singleton.js} +0 -0
package/src/core.ts ADDED
@@ -0,0 +1,375 @@
1
+ /**
2
+ * https://neon.com/docs/reference/typescript-sdk
3
+ */
4
+ import {
5
+ createApiClient,
6
+ EndpointType,
7
+ type Branch,
8
+ } from "@neondatabase/api-client";
9
+ import { applySslMode } from "./lib/ssl.js";
10
+ import { validateExpiresIn } from "./lib/expires-in.js";
11
+ import { neonWsErrorHandler } from "./lib/ws-error.js";
12
+ import { withRetry } from "./lib/with-retry.js";
13
+ import { CLEARED_DATABASE_URL } from "./lib/cleared-database-url.js";
14
+
15
+ /**
16
+ * Test-runner lifecycle hooks
17
+ *
18
+ * Injected so the core stays runner-agnostic. Most users don't build these by
19
+ * hand — import the pre-wired factory from `neon-testing/vitest` or
20
+ * `neon-testing/bun`, which supply them automatically.
21
+ */
22
+ export interface NeonTestingHooks {
23
+ beforeAll: (fn: () => void | Promise<void>) => void;
24
+ afterAll: (fn: () => void | Promise<void>) => void;
25
+ }
26
+
27
+ /**
28
+ * Configuration for the Neon test-branch factory.
29
+ *
30
+ * `hooks` are injected by the per-runner entry (`neon-testing/vitest` or
31
+ * `neon-testing/bun`); the remaining fields control how each test branch is
32
+ * created and torn down.
33
+ */
34
+ export interface MakeNeonTestingCoreOptions {
35
+ /**
36
+ * Test-runner lifecycle hooks (supplied by `neon-testing/vitest` or
37
+ * `neon-testing/bun`)
38
+ */
39
+ hooks: NeonTestingHooks;
40
+ /**
41
+ * The Neon API key, this is used to create and teardown test branches (required)
42
+ *
43
+ * https://neon.com/docs/manage/api-keys#creating-api-keys
44
+ */
45
+ apiKey: string;
46
+ /**
47
+ * The Neon project ID to operate on (required)
48
+ *
49
+ * https://console.neon.tech/app/projects
50
+ */
51
+ projectId: string;
52
+ /**
53
+ * The parent branch ID for the new branch (default: undefined)
54
+ *
55
+ * If omitted or undefined, test branches will be created from the project's
56
+ * default branch.
57
+ */
58
+ parentBranchId?: string;
59
+ /**
60
+ * Whether to create a schema-only branch (default: false)
61
+ */
62
+ schemaOnly?: boolean;
63
+ /**
64
+ * The type of connection to create (default: "pooler")
65
+ */
66
+ endpoint?: "pooler" | "direct";
67
+ /**
68
+ * Delete the test branch in afterAll (default: true)
69
+ *
70
+ * Disabling this will leave each test branch in the Neon project after the
71
+ * test suite runs
72
+ */
73
+ deleteBranch?: boolean;
74
+ /**
75
+ * Automatically close Neon WebSocket connections opened during tests before
76
+ * deleting the branch (default: false)
77
+ *
78
+ * Suppresses the specific Neon WebSocket "Connection terminated unexpectedly"
79
+ * error that may surface when deleting a branch with open WebSocket
80
+ * connections
81
+ *
82
+ * Vitest only — under Bun the uncaughtException suppression does not
83
+ * intercept, so close connections explicitly there instead.
84
+ */
85
+ autoCloseWebSockets?: boolean;
86
+ /**
87
+ * Time in seconds until the branch expires and is automatically deleted
88
+ * (default: 600 = 10 minutes)
89
+ *
90
+ * This provides automatic cleanup for dangling branches from interrupted or
91
+ * failed test runs. Set to `null` to disable automatic expiration.
92
+ *
93
+ * Must be a positive integer. Maximum 30 days (2,592,000 seconds).
94
+ *
95
+ * https://neon.com/docs/guides/branch-expiration
96
+ */
97
+ expiresIn?: number | null;
98
+ /**
99
+ * The database role to connect as (default: project owner role)
100
+ *
101
+ * The role must exist in the parent branch. Roles are automatically
102
+ * copied to test branches when branching.
103
+ */
104
+ roleName?: string;
105
+ /**
106
+ * The database to connect to (default: project default database)
107
+ */
108
+ databaseName?: string;
109
+ /**
110
+ * Override the `sslmode` query param on the connection URI (default:
111
+ * undefined — URI is passed through unchanged)
112
+ *
113
+ * Neon's API returns URIs with `sslmode=require`. In pg v9 the meaning of
114
+ * `require` changes to libpq semantics (encrypt, but don't verify the CA).
115
+ *
116
+ * - `"verify-full"` — strict CA verification (silences the pg v9 warning)
117
+ * - `"require"` — preserves today's effective behavior under pg v9 by also
118
+ * setting `uselibpqcompat=true`
119
+ *
120
+ * Only affects drivers that parse `sslmode` (e.g. `pg`). The Neon
121
+ * serverless driver ignores it.
122
+ */
123
+ sslMode?: "verify-full" | "require";
124
+ }
125
+
126
+ /** Options for the `makeNeonTesting` factories — core options minus the injected hooks */
127
+ export type MakeNeonTestingOptions = Omit<MakeNeonTestingCoreOptions, "hooks">;
128
+
129
+ /** Per-file overrides accepted by the returned `neonTesting()` function */
130
+ export type NeonTestingOptions = Partial<
131
+ Omit<MakeNeonTestingOptions, "apiKey">
132
+ >;
133
+
134
+ /**
135
+ * Low-level factory that creates a Neon test-branch setup/teardown function.
136
+ * Runner-agnostic — you inject the lifecycle hooks via `options.hooks`.
137
+ *
138
+ * Most users want a pre-wired entry instead: `neon-testing/vitest` or
139
+ * `neon-testing/bun`. Reach for this core factory only for other runners
140
+ * (jest, node:test, …).
141
+ *
142
+ * @param factoryOptions - see {@link MakeNeonTestingCoreOptions}
143
+ * @returns A setup/teardown function with attached utilities:
144
+ * - `deleteAllTestBranches()` - delete all test branches
145
+ * - `api` - the Neon API client
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * import { beforeAll, afterAll } from "vitest"; // or any runner
150
+ * import { makeNeonTestingCore } from "neon-testing/core";
151
+ *
152
+ * export const neonTesting = makeNeonTestingCore({
153
+ * apiKey: process.env.NEON_API_KEY!,
154
+ * projectId: process.env.NEON_PROJECT_ID!,
155
+ * hooks: { beforeAll, afterAll },
156
+ * });
157
+ * ```
158
+ */
159
+ export function makeNeonTestingCore(
160
+ factoryOptions: MakeNeonTestingCoreOptions,
161
+ ) {
162
+ // Validate factory options
163
+ validateExpiresIn(factoryOptions.expiresIn);
164
+
165
+ const apiClient = createApiClient({ apiKey: factoryOptions.apiKey });
166
+
167
+ /**
168
+ * Delete all test branches (branches with the "integration-test: true" annotation)
169
+ */
170
+ async function deleteAllTestBranches() {
171
+ const { data } = await apiClient.listProjectBranches({
172
+ projectId: factoryOptions.projectId,
173
+ });
174
+
175
+ for (const branch of data.branches) {
176
+ const isTestBranch =
177
+ data.annotations[branch.id]?.value["integration-test"] === "true";
178
+
179
+ if (isTestBranch) {
180
+ await apiClient.deleteProjectBranch(
181
+ factoryOptions.projectId,
182
+ branch.id,
183
+ );
184
+ }
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Setup/teardown function for a test file.
190
+ *
191
+ * Registers lifecycle hooks (via the injected `hooks`) that:
192
+ * - Create an isolated test branch from your parent branch
193
+ * - Set `DATABASE_URL` environment variable to the test branch connection URI
194
+ * - Automatically delete the test branch after tests complete (unless `deleteBranch: false`)
195
+ * - Automatically expire branches after 10 minutes for cleanup (unless `expiresIn: null`)
196
+ *
197
+ * @param overrides - Optional per-file overrides for the factory options
198
+ * @returns A function that provides access to the current Neon branch object
199
+ */
200
+ const neonTesting = (
201
+ /** Override any factory options except apiKey */
202
+ overrides?: NeonTestingOptions,
203
+ ) => {
204
+ // Validate overrides
205
+ if (overrides?.expiresIn !== undefined) {
206
+ validateExpiresIn(overrides.expiresIn);
207
+ }
208
+
209
+ // Merge factory options with overrides
210
+ const options = { ...factoryOptions, ...overrides };
211
+
212
+ // Each test file gets its own branch and database client
213
+ let branch: Branch | undefined;
214
+
215
+ // List of tracked Neon WebSocket connections
216
+ // Lazily initialized when autoCloseWebSockets is enabled (avoids
217
+ // referencing the WebSocket global on runtimes that lack it, e.g. Node 20)
218
+ let neonSockets: Set<WebSocket> | undefined;
219
+
220
+ /**
221
+ * Create a new test branch
222
+ *
223
+ * @returns The connection URI for the new branch
224
+ */
225
+ async function createBranch() {
226
+ // Calculate expiration timestamp if expiresIn is set
227
+ const expiresIn =
228
+ options.expiresIn === undefined ? 600 : options.expiresIn; // Default: 10 minutes
229
+
230
+ const expiresAt =
231
+ expiresIn !== null
232
+ ? new Date(Date.now() + expiresIn * 1000).toISOString()
233
+ : undefined;
234
+
235
+ const { data } = await apiClient.createProjectBranch(options.projectId, {
236
+ branch: {
237
+ name: `test/${crypto.randomUUID()}`,
238
+ ...(options.parentBranchId
239
+ ? { parent_id: options.parentBranchId }
240
+ : {}),
241
+ ...(options.schemaOnly ? { init_source: "schema-only" } : {}),
242
+ ...(expiresAt ? { expires_at: expiresAt } : {}),
243
+ },
244
+ endpoints: [{ type: EndpointType.ReadWrite }],
245
+ annotation_value: {
246
+ "integration-test": "true",
247
+ },
248
+ });
249
+
250
+ branch = data.branch;
251
+
252
+ // Determine role and database (handles multi-role/database projects)
253
+ const targetRole =
254
+ options.roleName ??
255
+ data.roles?.find((r) => r.name === "neondb_owner")?.name ??
256
+ data.roles?.[0]?.name;
257
+ const targetDatabase =
258
+ options.databaseName ??
259
+ data.databases?.find((d) => d.name === "neondb")?.name ??
260
+ data.databases?.[0]?.name;
261
+
262
+ if (!targetRole) {
263
+ throw new Error("No role available in branch");
264
+ }
265
+ if (!targetDatabase) {
266
+ throw new Error("No database available in branch");
267
+ }
268
+
269
+ // Validate specified role exists
270
+ if (
271
+ options.roleName &&
272
+ !data.roles?.some((r) => r.name === options.roleName)
273
+ ) {
274
+ throw new Error(`Role not found: ${options.roleName}`);
275
+ }
276
+
277
+ // Validate specified database exists
278
+ if (
279
+ options.databaseName &&
280
+ !data.databases?.some((d) => d.name === options.databaseName)
281
+ ) {
282
+ throw new Error(`Database not found: ${options.databaseName}`);
283
+ }
284
+
285
+ // Use getConnectionUri API (works for all cases, including multi-role projects)
286
+ const { data: uriData } = await apiClient.getConnectionUri({
287
+ projectId: options.projectId,
288
+ branch_id: branch.id,
289
+ role_name: targetRole,
290
+ database_name: targetDatabase,
291
+ pooled: options.endpoint !== "direct",
292
+ });
293
+
294
+ return applySslMode(uriData.uri, options.sslMode);
295
+ }
296
+
297
+ /**
298
+ * Delete the test branch
299
+ */
300
+ async function deleteBranch() {
301
+ if (!branch?.id) {
302
+ throw new Error("No branch to delete");
303
+ }
304
+
305
+ await apiClient.deleteProjectBranch(options.projectId, branch.id);
306
+ branch = undefined;
307
+ }
308
+
309
+ factoryOptions.hooks.beforeAll(async () => {
310
+ process.env.DATABASE_URL = await withRetry(createBranch, {
311
+ maxRetries: 8,
312
+ baseDelayMs: 1000,
313
+ });
314
+
315
+ if (options.autoCloseWebSockets) {
316
+ neonSockets = new Set<WebSocket>();
317
+
318
+ // Custom WebSocket constructor that tracks Neon WebSocket connections
319
+ class TrackingWebSocket extends WebSocket {
320
+ constructor(url: string) {
321
+ super(url);
322
+
323
+ // Only track Neon WebSocket connections
324
+ if (!url.includes(".neon.tech/")) return;
325
+
326
+ neonSockets!.add(this);
327
+ }
328
+ }
329
+
330
+ // Install a custom WebSocket constructor that tracks Neon WebSocket
331
+ // connections and closes them before deleting the branch
332
+ try {
333
+ const { neonConfig } = await import("@neondatabase/serverless");
334
+ neonConfig.webSocketConstructor = TrackingWebSocket;
335
+ } catch {
336
+ throw new Error(
337
+ "autoCloseWebSockets requires @neondatabase/serverless to be installed. Run: npm install @neondatabase/serverless",
338
+ );
339
+ }
340
+ }
341
+ });
342
+
343
+ factoryOptions.hooks.afterAll(async () => {
344
+ // Overwrite (not `delete`) so DATABASE_URL no longer points at the test
345
+ // branch; see CLEARED_DATABASE_URL for why a sentinel rather than delete.
346
+ process.env.DATABASE_URL = CLEARED_DATABASE_URL;
347
+
348
+ // Close all tracked Neon WebSocket connections before deleting the branch
349
+ if (options.autoCloseWebSockets && neonSockets) {
350
+ // Suppress Neon WebSocket "Connection terminated unexpectedly" error
351
+ process.prependListener("uncaughtException", neonWsErrorHandler);
352
+
353
+ // Close tracked Neon WebSocket connections before deleting the branch
354
+ neonSockets.forEach((ws) => ws.close());
355
+ }
356
+
357
+ if (options.deleteBranch !== false) {
358
+ await deleteBranch();
359
+ }
360
+ });
361
+
362
+ /**
363
+ * Return the Neon branch object
364
+ *
365
+ * @returns The Neon branch object
366
+ */
367
+ return () => branch;
368
+ };
369
+
370
+ // Attach utilities
371
+ neonTesting.deleteAllTestBranches = deleteAllTestBranches;
372
+ neonTesting.api = apiClient;
373
+
374
+ return neonTesting;
375
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Creates a synchronization barrier that blocks until `count` callers have
3
+ * arrived, then releases all of them simultaneously
4
+ */
5
+ export function createBarrier(count: number) {
6
+ let arrived = 0;
7
+ let release: () => void;
8
+
9
+ const barrier = new Promise<void>((resolve) => {
10
+ release = resolve;
11
+ });
12
+
13
+ return async () => {
14
+ arrived++;
15
+
16
+ if (arrived === count) {
17
+ release();
18
+ }
19
+
20
+ await barrier;
21
+ };
22
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Sentinel written to `DATABASE_URL` to clear it, instead of `delete`.
3
+ *
4
+ * Keeps the value a string for consumers that type `DATABASE_URL` as required
5
+ * (so the library never has to fight their env typing), and is an invalid
6
+ * connection string so a test that forgot `neonTesting()` fails loudly rather
7
+ * than silently reaching a real database.
8
+ */
9
+ export const CLEARED_DATABASE_URL = `neon-testing: DATABASE_URL cleared, call neonTesting()`;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Validates the expiresIn option
3
+ */
4
+ export function validateExpiresIn(expiresIn: number | null | undefined) {
5
+ if (expiresIn === null) {
6
+ return;
7
+ }
8
+
9
+ if (expiresIn === undefined) {
10
+ return;
11
+ }
12
+
13
+ if (!Number.isInteger(expiresIn)) {
14
+ throw new Error("expiresIn must be an integer");
15
+ }
16
+
17
+ if (expiresIn <= 0) {
18
+ throw new Error("expiresIn must be a positive integer");
19
+ }
20
+
21
+ if (expiresIn > 2592000) {
22
+ throw new Error("expiresIn must not exceed 30 days (2,592,000 seconds)");
23
+ }
24
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Create a lazy singleton from a factory function
3
+ */
4
+ export function lazySingleton<T>(factory: () => T): () => T {
5
+ let instance: T | undefined;
6
+ return () => {
7
+ instance ??= factory();
8
+ return instance;
9
+ };
10
+ }
package/src/lib/ssl.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Rewrite the `sslmode` (and related) query params on a Neon connection URI.
3
+ *
4
+ * Neon's API returns URIs with `sslmode=require`. In pg v9 /
5
+ * pg-connection-string v3 this mode will adopt libpq semantics (encrypt
6
+ * without CA verification) instead of today's effective `verify-full`.
7
+ */
8
+ export function applySslMode(
9
+ uri: string,
10
+ mode: "verify-full" | "require" | undefined,
11
+ ): string {
12
+ if (mode === undefined) return uri;
13
+
14
+ const url = new URL(uri);
15
+ url.searchParams.set("sslmode", mode);
16
+
17
+ if (mode === "require") {
18
+ url.searchParams.set("uselibpqcompat", "true");
19
+ } else {
20
+ url.searchParams.delete("uselibpqcompat");
21
+ }
22
+
23
+ return url.toString();
24
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Reusable API call wrapper with automatic retry on 423 errors with exponential
3
+ * backoff
4
+ *
5
+ * https://neon.com/docs/reference/typescript-sdk#error-handling
6
+ * https://neon.com/docs/changelog/2022-07-20
7
+ */
8
+ export async function withRetry<T>(
9
+ fn: () => Promise<T>,
10
+ options: {
11
+ maxRetries: number;
12
+ baseDelayMs: number;
13
+ },
14
+ ): Promise<T> {
15
+ if (!Number.isInteger(options.maxRetries) || options.maxRetries <= 0) {
16
+ throw new Error("maxRetries must be a positive integer");
17
+ }
18
+
19
+ if (!Number.isInteger(options.baseDelayMs) || options.baseDelayMs <= 0) {
20
+ throw new Error("baseDelayMs must be a positive integer");
21
+ }
22
+
23
+ for (let attempt = 1; attempt <= options.maxRetries; attempt++) {
24
+ try {
25
+ return await fn();
26
+ } catch (error: any) {
27
+ const status = error?.response?.status;
28
+
29
+ // Retry on 423 (resource locked) with exponential backoff
30
+ if (status === 423 && attempt < options.maxRetries) {
31
+ const delay = options.baseDelayMs * Math.pow(2, attempt - 1);
32
+
33
+ console.log(
34
+ `API call failed with 423, retrying in ${delay}ms (attempt ${attempt}/${options.maxRetries})`,
35
+ );
36
+ await new Promise((resolve) => setTimeout(resolve, delay));
37
+
38
+ continue;
39
+ }
40
+
41
+ // Surface Neon API error details that are otherwise buried in the Axios error
42
+ if (error?.response?.data?.code) {
43
+ const { code, message } = error.response.data;
44
+ throw new Error(
45
+ `Neon API error - HTTP ${status} - ${code} - ${message}`,
46
+ { cause: error },
47
+ );
48
+ }
49
+
50
+ // Non-API errors (network, timeouts, etc.) pass through as-is
51
+ throw error;
52
+ }
53
+ }
54
+ throw new Error("apiCallWithRetry reached unexpected end");
55
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Error handler: Suppress Neon WebSocket "Connection terminated unexpectedly"
3
+ * error
4
+ */
5
+ export const neonWsErrorHandler = (error: Error) => {
6
+ const isNeonWsClose =
7
+ error.message.includes("Connection terminated unexpectedly") &&
8
+ error.stack?.includes("@neondatabase/serverless");
9
+
10
+ if (isNeonWsClose) {
11
+ // Swallow this specific Neon WS termination error
12
+ return;
13
+ }
14
+
15
+ // For any other error, detach and rethrow
16
+ throw error;
17
+ };
package/src/setup.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { CLEARED_DATABASE_URL } from "./lib/cleared-database-url.js";
2
+
3
+ // Overwrites any existing DATABASE_URL so a test file that forgot to call
4
+ // `neonTesting()` can't reach the pre-configured database. Loaded as a
5
+ // test-runner preload (Vitest `setupFiles` / Bun `bunfig` `preload`).
6
+ if (process.env.DATABASE_URL && process.env.NEON_TESTING_DEBUG === "true") {
7
+ console.debug("[neon-testing] Overwriting existing DATABASE_URL");
8
+ }
9
+
10
+ process.env.DATABASE_URL = CLEARED_DATABASE_URL;
package/src/utils.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { lazySingleton } from "./lib/singleton.js";
2
+ export { createBarrier } from "./lib/barrier.js";
package/src/vitest.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { beforeAll, afterAll } from "vitest";
2
+ import { makeNeonTestingCore } from "./core.js";
3
+ import type { MakeNeonTestingOptions } from "./core.js";
4
+
5
+ export type { MakeNeonTestingOptions, NeonTestingOptions } from "./core.js";
6
+
7
+ /**
8
+ * Create a Neon test-branch factory wired to Vitest's lifecycle hooks.
9
+ */
10
+ export function makeNeonTesting(options: MakeNeonTestingOptions) {
11
+ return makeNeonTestingCore({ ...options, hooks: { beforeAll, afterAll } });
12
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"barrier.d.ts","sourceRoot":"","sources":["../src/barrier.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,uBAiB1C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"barrier.js","sourceRoot":"","sources":["../src/barrier.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,OAAmB,CAAC;IAExB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;QAC5C,OAAO,GAAG,OAAO,CAAC;IACpB,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,IAAI,EAAE;QAChB,OAAO,EAAE,CAAC;QAEV,IAAI,OAAO,KAAK,KAAK,EAAE,CAAC;YACtB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,OAAO,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Creates a synchronization barrier that blocks until `count` callers have\n * arrived, then releases all of them simultaneously\n */\nexport function createBarrier(count: number) {\n let arrived = 0;\n let release: () => void;\n\n const barrier = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n return async () => {\n arrived++;\n\n if (arrived === count) {\n release();\n }\n\n await barrier;\n };\n}\n"]}
@@ -1,2 +0,0 @@
1
- export declare function neonTesting(): void;
2
- //# sourceMappingURL=browser-empty.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"browser-empty.d.ts","sourceRoot":"","sources":["../src/browser-empty.ts"],"names":[],"mappings":"AAAA,wBAAgB,WAAW,SAE1B"}
@@ -1,4 +0,0 @@
1
- export function neonTesting() {
2
- throw new Error("neon-testing/vite is Node-only (Vite/Vitest context).");
3
- }
4
- //# sourceMappingURL=browser-empty.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"browser-empty.js","sourceRoot":"","sources":["../src/browser-empty.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,WAAW;IACzB,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["export function neonTesting() {\n throw new Error(\"neon-testing/vite is Node-only (Vite/Vitest context).\");\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAGL,KAAK,MAAM,EACZ,MAAM,0BAA0B,CAAC;AA6ClC,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;OAEG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;OAEG;IACH,QAAQ,CAAC,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC/B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;;;;;OAOG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B;;;;;;;;;;OAUG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC;CACrC;AAED,mEAAmE;AACnE,MAAM,MAAM,oBAAoB,GAAG,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,EAAE,QAAQ,CAAC,CAAC;AAE/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,eAAe,CAAC,cAAc,EAAE,kBAAkB;iBAyClD,oBAAoB;;;EAyKnC"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EACL,eAAe,EACf,YAAY,GAEb,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,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AAE,CAAC;QACpB,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,MAAM,MAAM,GAAG,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC;YAEvC,0DAA0D;YAC1D,IAAI,MAAM,KAAK,GAAG,IAAI,OAAO,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;gBACnD,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,CAAC,CAAC;gBAE7D,OAAO,CAAC,GAAG,CACT,yCAAyC,KAAK,eAAe,OAAO,IAAI,OAAO,CAAC,UAAU,GAAG,CAC9F,CAAC;gBACF,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;gBAE3D,SAAS;YACX,CAAC;YAED,8EAA8E;YAC9E,IAAI,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;gBAChC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;gBAC9C,MAAM,IAAI,KAAK,CACb,yBAAyB,MAAM,MAAM,IAAI,MAAM,OAAO,EAAE,EACxD,EAAE,KAAK,EAAE,KAAK,EAAE,CACjB,CAAC;YACJ,CAAC;YAED,8DAA8D;YAC9D,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["/**\n * https://neon.com/docs/reference/typescript-sdk\n */\nimport {\n createApiClient,\n EndpointType,\n type Branch,\n} from \"@neondatabase/api-client\";\nimport { afterAll, beforeAll } from \"vitest\";\n\n/**\n * Rewrite the `sslmode` (and related) query params on a Neon connection URI.\n *\n * Neon's API returns URIs with `sslmode=require`. In pg v9 /\n * pg-connection-string v3 this mode will adopt libpq semantics (encrypt\n * without CA verification) instead of today's effective `verify-full`.\n */\nfunction applySslMode(\n uri: string,\n mode: \"verify-full\" | \"require\" | undefined,\n): string {\n if (mode === undefined) return uri;\n\n const url = new URL(uri);\n url.searchParams.set(\"sslmode\", mode);\n if (mode === \"require\") {\n url.searchParams.set(\"uselibpqcompat\", \"true\");\n } else {\n url.searchParams.delete(\"uselibpqcompat\");\n }\n return url.toString();\n}\n\n/**\n * Validates the expiresIn option\n */\nfunction validateExpiresIn(expiresIn: number | null | undefined) {\n if (expiresIn !== null && expiresIn !== undefined) {\n if (!Number.isInteger(expiresIn)) {\n throw new Error(\"expiresIn must be an integer\");\n }\n\n if (expiresIn <= 0) {\n throw new Error(\"expiresIn must be a positive integer\");\n }\n\n if (expiresIn > 2592000) {\n throw new Error(\"expiresIn must not exceed 30 days (2,592,000 seconds)\");\n }\n }\n}\n\nexport interface NeonTestingOptions {\n /**\n * The Neon API key, this is used to create and teardown test branches (required)\n *\n * https://neon.com/docs/manage/api-keys#creating-api-keys\n */\n apiKey: string;\n /**\n * The Neon project ID to operate on (required)\n *\n * https://console.neon.tech/app/projects\n */\n projectId: string;\n /**\n * The parent branch ID for the new branch (default: undefined)\n *\n * If omitted or undefined, test branches will be created from the project's\n * default branch.\n */\n parentBranchId?: string;\n /**\n * Whether to create a schema-only branch (default: false)\n */\n schemaOnly?: boolean;\n /**\n * The type of connection to create (default: \"pooler\")\n */\n endpoint?: \"pooler\" | \"direct\";\n /**\n * Delete the test branch in afterAll (default: true)\n *\n * Disabling this will leave each test branch in the Neon project after the\n * test suite runs\n */\n deleteBranch?: boolean;\n /**\n * Automatically close Neon WebSocket connections opened during tests before\n * deleting the branch (default: false)\n *\n * Suppresses the specific Neon WebSocket \"Connection terminated unexpectedly\"\n * error that may surface when deleting a branch with open WebSocket\n * connections\n */\n autoCloseWebSockets?: boolean;\n /**\n * Time in seconds until the branch expires and is automatically deleted\n * (default: 600 = 10 minutes)\n *\n * This provides automatic cleanup for dangling branches from interrupted or\n * failed test runs. Set to `null` to disable automatic expiration.\n *\n * Must be a positive integer. Maximum 30 days (2,592,000 seconds).\n *\n * https://neon.com/docs/guides/branch-expiration\n */\n expiresIn?: number | null;\n /**\n * The database role to connect as (default: project owner role)\n *\n * The role must exist in the parent branch. Roles are automatically\n * copied to test branches when branching.\n */\n roleName?: string;\n /**\n * The database to connect to (default: project default database)\n */\n databaseName?: string;\n /**\n * Override the `sslmode` query param on the connection URI (default:\n * undefined — URI is passed through unchanged)\n *\n * Neon's API returns URIs with `sslmode=require`. In pg v9 the meaning of\n * `require` changes to libpq semantics (encrypt, but don't verify the CA).\n *\n * - `\"verify-full\"` — strict CA verification (silences the pg v9 warning)\n * - `\"require\"` — preserves today's effective behavior under pg v9 by also\n * setting `uselibpqcompat=true`\n *\n * Only affects drivers that parse `sslmode` (e.g. `pg`). The Neon\n * serverless driver ignores it.\n */\n sslMode?: \"verify-full\" | \"require\";\n}\n\n/** Options for overriding test database setup (excludes apiKey) */\nexport type NeonTestingOverrides = Omit<Partial<NeonTestingOptions>, \"apiKey\">;\n\n/**\n * Factory function that creates a Neon test database setup/teardown function\n * for Vitest test suites.\n *\n * @param factoryOptions - Configuration options (see {@link NeonTestingOptions})\n * @returns A setup/teardown function with attached utilities:\n * - `deleteAllTestBranches()` - Cleanup method to delete all test branches\n * - `api` - Direct access to the Neon API client\n *\n * @example\n * ```ts\n * // neon-testing.ts\n * import { makeNeonTesting } from \"neon-testing\";\n *\n * export const neonTesting = makeNeonTesting({\n * apiKey: \"apiKey\",\n * projectId: \"projectId\",\n * });\n * ```\n *\n * @example\n * ```ts\n * // my-test.test.ts\n * import { neonTesting } from \"./neon-testing\";\n *\n * const getBranch = neonTesting();\n *\n * test(\"my test\", () => {\n * const branch = getBranch();\n * console.log(branch.id);\n * });\n * ```\n */\nexport function makeNeonTesting(factoryOptions: NeonTestingOptions) {\n // Validate factory options\n validateExpiresIn(factoryOptions.expiresIn);\n\n const apiClient = createApiClient({ apiKey: factoryOptions.apiKey });\n\n /**\n * Delete all test branches (branches with the \"integration-test: true\" annotation)\n */\n async function deleteAllTestBranches() {\n const { data } = await apiClient.listProjectBranches({\n projectId: factoryOptions.projectId,\n });\n\n for (const branch of data.branches) {\n const isTestBranch =\n data.annotations[branch.id]?.value[\"integration-test\"] === \"true\";\n\n if (isTestBranch) {\n await apiClient.deleteProjectBranch(\n factoryOptions.projectId,\n branch.id,\n );\n }\n }\n }\n\n /**\n * Setup/teardown function for Vitest test suites\n *\n * Registers Vitest lifecycle hooks that:\n * - Create an isolated test branch from your parent branch\n * - Set `DATABASE_URL` environment variable to the test branch connection URI\n * - Automatically delete the test branch after tests complete (unless `deleteBranch: false`)\n * - Automatically expire branches after 10 minutes for cleanup (unless `expiresIn: null`)\n *\n * @param overrides - Optional overrides for the factory options\n * @returns A function that provides access to the current Neon branch object\n */\n const neonTesting = (\n /** Override any factory options except apiKey */\n overrides?: NeonTestingOverrides,\n ) => {\n // Validate overrides\n if (overrides?.expiresIn !== undefined) {\n validateExpiresIn(overrides.expiresIn);\n }\n\n // Merge factory options with overrides\n const options = { ...factoryOptions, ...overrides };\n\n // Each test file gets its own branch and database client\n let branch: Branch | undefined;\n\n // List of tracked Neon WebSocket connections\n // Lazily initialized when autoCloseWebSockets is enabled (avoids\n // referencing the WebSocket global on runtimes that lack it, e.g. Node 20)\n let neonSockets: Set<WebSocket> | undefined;\n\n /**\n * Create a new test branch\n *\n * @returns The connection URI for the new branch\n */\n async function createBranch() {\n // Calculate expiration timestamp if expiresIn is set\n const expiresIn =\n options.expiresIn === undefined ? 600 : options.expiresIn; // Default: 10 minutes\n\n const expiresAt =\n expiresIn !== null\n ? new Date(Date.now() + expiresIn * 1000).toISOString()\n : undefined;\n\n const { data } = await apiClient.createProjectBranch(options.projectId, {\n branch: {\n name: `test/${crypto.randomUUID()}`,\n parent_id: options.parentBranchId,\n init_source: options.schemaOnly ? \"schema-only\" : undefined,\n expires_at: expiresAt,\n },\n endpoints: [{ type: EndpointType.ReadWrite }],\n annotation_value: {\n \"integration-test\": \"true\",\n },\n });\n\n branch = data.branch;\n\n // Determine role and database (handles multi-role/database projects)\n const targetRole =\n options.roleName ??\n data.roles?.find((r) => r.name === \"neondb_owner\")?.name ??\n data.roles?.[0]?.name;\n const targetDatabase =\n options.databaseName ??\n data.databases?.find((d) => d.name === \"neondb\")?.name ??\n data.databases?.[0]?.name;\n\n if (!targetRole) {\n throw new Error(\"No role available in branch\");\n }\n if (!targetDatabase) {\n throw new Error(\"No database available in branch\");\n }\n\n // Validate specified role exists\n if (\n options.roleName &&\n !data.roles?.some((r) => r.name === options.roleName)\n ) {\n throw new Error(`Role not found: ${options.roleName}`);\n }\n\n // Validate specified database exists\n if (\n options.databaseName &&\n !data.databases?.some((d) => d.name === options.databaseName)\n ) {\n throw new Error(`Database not found: ${options.databaseName}`);\n }\n\n // Use getConnectionUri API (works for all cases, including multi-role projects)\n const { data: uriData } = await apiClient.getConnectionUri({\n projectId: options.projectId,\n branch_id: branch.id,\n role_name: targetRole,\n database_name: targetDatabase,\n pooled: options.endpoint !== \"direct\",\n });\n\n return applySslMode(uriData.uri, options.sslMode);\n }\n\n /**\n * Delete the test branch\n */\n async function deleteBranch() {\n if (!branch?.id) {\n throw new Error(\"No branch to delete\");\n }\n\n await apiClient.deleteProjectBranch(options.projectId, branch.id);\n branch = undefined;\n }\n\n beforeAll(async () => {\n process.env.DATABASE_URL = await withRetry(createBranch, {\n maxRetries: 8,\n baseDelayMs: 1000,\n });\n\n if (options.autoCloseWebSockets) {\n neonSockets = new Set<WebSocket>();\n\n // Custom WebSocket constructor that tracks Neon WebSocket connections\n class TrackingWebSocket extends WebSocket {\n constructor(url: string) {\n super(url);\n\n // Only track Neon WebSocket connections\n if (!url.includes(\".neon.tech/\")) return;\n\n neonSockets!.add(this);\n }\n }\n\n // Install a custom WebSocket constructor that tracks Neon WebSocket\n // connections and closes them before deleting the branch\n try {\n const { neonConfig } = await import(\"@neondatabase/serverless\");\n neonConfig.webSocketConstructor = TrackingWebSocket;\n } catch {\n throw new Error(\n \"autoCloseWebSockets requires @neondatabase/serverless to be installed. Run: npm install @neondatabase/serverless\",\n );\n }\n }\n });\n\n afterAll(async () => {\n process.env.DATABASE_URL = undefined;\n\n // Close all tracked Neon WebSocket connections before deleting the branch\n if (options.autoCloseWebSockets && neonSockets) {\n // Suppress Neon WebSocket \"Connection terminated unexpectedly\" error\n process.prependListener(\"uncaughtException\", neonWsErrorHandler);\n\n // Close tracked Neon WebSocket connections before deleting the branch\n neonSockets.forEach((ws) => ws.close());\n }\n\n if (options.deleteBranch !== false) {\n await deleteBranch();\n }\n });\n\n /**\n * Return the Neon branch object\n *\n * @returns The Neon branch object\n */\n return () => branch;\n };\n\n // Attach utilities\n neonTesting.deleteAllTestBranches = deleteAllTestBranches;\n neonTesting.api = apiClient;\n\n return neonTesting;\n}\n\n/**\n * Error handler: Suppress Neon WebSocket \"Connection terminated unexpectedly\"\n * error\n */\nconst neonWsErrorHandler = (error: Error) => {\n const isNeonWsClose =\n error.message.includes(\"Connection terminated unexpectedly\") &&\n error.stack?.includes(\"@neondatabase/serverless\");\n\n if (isNeonWsClose) {\n // Swallow this specific Neon WS termination error\n return;\n }\n\n // For any other error, detach and rethrow\n throw error;\n};\n\n/**\n * Reusable API call wrapper with automatic retry on 423 errors with exponential\n * backoff\n *\n * https://neon.com/docs/reference/typescript-sdk#error-handling\n * https://neon.com/docs/changelog/2022-07-20\n */\nasync function withRetry<T>(\n fn: () => Promise<T>,\n options: {\n maxRetries: number;\n baseDelayMs: number;\n },\n): Promise<T> {\n if (!Number.isInteger(options.maxRetries) || options.maxRetries <= 0) {\n throw new Error(\"maxRetries must be a positive integer\");\n }\n\n if (!Number.isInteger(options.baseDelayMs) || options.baseDelayMs <= 0) {\n throw new Error(\"baseDelayMs must be a positive integer\");\n }\n\n for (let attempt = 1; attempt <= options.maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error: any) {\n const status = error?.response?.status;\n\n // Retry on 423 (resource locked) with exponential backoff\n if (status === 423 && attempt < options.maxRetries) {\n const delay = options.baseDelayMs * Math.pow(2, attempt - 1);\n\n console.log(\n `API call failed with 423, retrying in ${delay}ms (attempt ${attempt}/${options.maxRetries})`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n continue;\n }\n\n // Surface Neon API error details that are otherwise buried in the Axios error\n if (error?.response?.data?.code) {\n const { code, message } = error.response.data;\n throw new Error(\n `Neon API error - HTTP ${status} - ${code} - ${message}`,\n { cause: error },\n );\n }\n\n // Non-API errors (network, timeouts, etc.) pass through as-is\n throw error;\n }\n }\n throw new Error(\"apiCallWithRetry reached unexpected end\");\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"singleton.d.ts","sourceRoot":"","sources":["../src/singleton.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,GAAG,MAAM,CAAC,CAM1D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"singleton.js","sourceRoot":"","sources":["../src/singleton.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,UAAU,aAAa,CAAI,OAAgB;IAC/C,IAAI,QAAuB,CAAC;IAC5B,OAAO,GAAG,EAAE;QACV,QAAQ,KAAK,OAAO,EAAE,CAAC;QACvB,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Create a lazy singleton from a factory function\n */\nexport function lazySingleton<T>(factory: () => T): () => T {\n let instance: T | undefined;\n return () => {\n instance ??= factory();\n return instance;\n };\n}\n"]}