@geekmidas/testkit 10.0.0-alpha.17 → 10.0.0-alpha.170
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.
- package/README.md +108 -0
- package/dist/PostgresKyselyMigrator.d.cts +1 -1
- package/dist/PostgresKyselyMigrator.d.mts +1 -1
- package/dist/{PostgresMigrator-CoHQ95cT.d.cts → PostgresMigrator-CDPnnwMJ.d.cts} +10 -3
- package/dist/PostgresMigrator-CDPnnwMJ.d.cts.map +1 -0
- package/dist/{PostgresMigrator-CoHQ95cT.d.mts → PostgresMigrator-CDPnnwMJ.d.mts} +10 -3
- package/dist/PostgresMigrator-CDPnnwMJ.d.mts.map +1 -0
- package/dist/PostgresMigrator.cjs +14 -5
- package/dist/PostgresMigrator.cjs.map +1 -1
- package/dist/PostgresMigrator.d.cts +1 -1
- package/dist/PostgresMigrator.d.mts +1 -1
- package/dist/PostgresMigrator.mjs +14 -5
- package/dist/PostgresMigrator.mjs.map +1 -1
- package/dist/PostgresObjectionMigrator.d.cts +1 -1
- package/dist/PostgresObjectionMigrator.d.mts +1 -1
- package/dist/browser.cjs +211 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +113 -0
- package/dist/browser.d.cts.map +1 -0
- package/dist/browser.d.mts +113 -0
- package/dist/browser.d.mts.map +1 -0
- package/dist/browser.mjs +207 -0
- package/dist/browser.mjs.map +1 -0
- package/dist/context.cjs +80 -0
- package/dist/context.cjs.map +1 -0
- package/dist/context.d.cts +55 -0
- package/dist/context.d.cts.map +1 -0
- package/dist/context.d.mts +55 -0
- package/dist/context.d.mts.map +1 -0
- package/dist/context.mjs +73 -0
- package/dist/context.mjs.map +1 -0
- package/dist/faker.cjs +51 -0
- package/dist/faker.cjs.map +1 -1
- package/dist/faker.d.cts +26 -19
- package/dist/faker.d.cts.map +1 -1
- package/dist/faker.d.mts +26 -19
- package/dist/faker.d.mts.map +1 -1
- package/dist/faker.mjs +51 -1
- package/dist/faker.mjs.map +1 -1
- package/dist/mailbox.cjs +107 -0
- package/dist/mailbox.cjs.map +1 -0
- package/dist/mailbox.d.cts +58 -0
- package/dist/mailbox.d.cts.map +1 -0
- package/dist/mailbox.d.mts +58 -0
- package/dist/mailbox.d.mts.map +1 -0
- package/dist/mailbox.mjs +103 -0
- package/dist/mailbox.mjs.map +1 -0
- package/dist/transactions.cjs +239 -0
- package/dist/transactions.cjs.map +1 -0
- package/dist/transactions.d.cts +44 -0
- package/dist/transactions.d.cts.map +1 -0
- package/dist/transactions.d.mts +44 -0
- package/dist/transactions.d.mts.map +1 -0
- package/dist/transactions.mjs +234 -0
- package/dist/transactions.mjs.map +1 -0
- package/package.json +57 -8
- package/dist/PostgresMigrator-CoHQ95cT.d.cts.map +0 -1
- package/dist/PostgresMigrator-CoHQ95cT.d.mts.map +0 -1
package/README.md
CHANGED
|
@@ -54,6 +54,12 @@ import { itWithDir } from '@geekmidas/testkit/os';
|
|
|
54
54
|
import { createMockContext, createMockV1Event, createMockV2Event } from '@geekmidas/testkit/aws';
|
|
55
55
|
import { createMockLogger } from '@geekmidas/testkit/logger';
|
|
56
56
|
import { memoryAdapter } from '@geekmidas/testkit/better-auth';
|
|
57
|
+
|
|
58
|
+
// Feature tests: the primitives `@geekmidas/constructs/testing` builds on
|
|
59
|
+
import { Browser } from '@geekmidas/testkit/browser';
|
|
60
|
+
import { createMailbox } from '@geekmidas/testkit/mailbox';
|
|
61
|
+
import { runInTestContext, installContextFetch } from '@geekmidas/testkit/context';
|
|
62
|
+
import { TransactionRegistry } from '@geekmidas/testkit/transactions';
|
|
57
63
|
```
|
|
58
64
|
|
|
59
65
|
## Quick Start
|
|
@@ -321,6 +327,85 @@ describe('Authentication', () => {
|
|
|
321
327
|
});
|
|
322
328
|
```
|
|
323
329
|
|
|
330
|
+
## Feature Test Primitives
|
|
331
|
+
|
|
332
|
+
The pieces a feature test is built from — a test that drives an app the way it
|
|
333
|
+
runs deployed: a browser signs in, calls the API, the API calls the auth server,
|
|
334
|
+
each over a URL, every database in a transaction that is rolled back. The wiring
|
|
335
|
+
that knows about constructs lives in `@geekmidas/constructs/testing`; these know
|
|
336
|
+
nothing about them.
|
|
337
|
+
|
|
338
|
+
### `Browser`
|
|
339
|
+
|
|
340
|
+
A `fetch` with a cookie jar that follows the browser's rules (RFC 6265): a
|
|
341
|
+
`Set-Cookie` lands in the jar, and every later request to a URL the cookie
|
|
342
|
+
belongs to carries it. Redirects are followed hop by hop, keeping each hop's
|
|
343
|
+
cookies. Give it to an app's real clients:
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
import { Browser as TestBrowser } from '@geekmidas/testkit/browser';
|
|
347
|
+
|
|
348
|
+
export class Browser extends TestBrowser {
|
|
349
|
+
readonly api = createApi({ baseURL: process.env.API_URL, fetch: this.fetch });
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const browser = new Browser();
|
|
353
|
+
await browser.visit(magicLink); // 302 + Set-Cookie → the jar
|
|
354
|
+
await browser.api.get('/profile'); // sent with the session cookie
|
|
355
|
+
const restore = browser.install(); // the global fetch, for module-level clients
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
On the server side of a test — a handler serving a request — `browser.fetch` is
|
|
359
|
+
the plain `fetch`: a server forwards what it was handed and never reaches into a
|
|
360
|
+
browser's jar.
|
|
361
|
+
|
|
362
|
+
Given the address of a site on every subdomain, `on(slug)` is the same browser
|
|
363
|
+
(the same jar, address and clients) on that tenant's host. It sends `Origin` on
|
|
364
|
+
every request and opens a relative `visit` there:
|
|
365
|
+
|
|
366
|
+
```typescript
|
|
367
|
+
const browser = new Browser({ site: 'https://*.test.shop.localhost:8443' });
|
|
368
|
+
await browser.on('acme').api.get('/orders'); // Origin: https://acme.test.shop.localhost:8443
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
A feature test passes `site` itself when the app declares one.
|
|
372
|
+
|
|
373
|
+
### `createMailbox`
|
|
374
|
+
|
|
375
|
+
Reads the mail an app actually sent, from Mailpit's HTTP API. One address per
|
|
376
|
+
test keeps tests apart, since Mailpit has one inbox and no transactions:
|
|
377
|
+
|
|
378
|
+
```typescript
|
|
379
|
+
const mailbox = createMailbox({ inbox: process.env.MAILER_INBOX_URL! });
|
|
380
|
+
|
|
381
|
+
const email = await mailbox('ada@shop.test').last(); // waits for it to arrive
|
|
382
|
+
await browser.visit(email.link!);
|
|
383
|
+
await mailbox('ada@shop.test').clear();
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
### Test context
|
|
387
|
+
|
|
388
|
+
`runInTestContext(id, fn)` carries a test's id through every await;
|
|
389
|
+
`installContextFetch()` stamps it onto every outgoing request as
|
|
390
|
+
`x-test-context-id`, so whatever serves a URL in-process finds the test the
|
|
391
|
+
request belongs to — including a request the code under test made while
|
|
392
|
+
handling another one.
|
|
393
|
+
|
|
394
|
+
### `TransactionRegistry`
|
|
395
|
+
|
|
396
|
+
One transaction per database per test — an app's database and a schema tenant
|
|
397
|
+
each on their own connection, as deployed — opened the first time the test
|
|
398
|
+
touches it and rolled back by `rollbackAll()`. Code under test may use
|
|
399
|
+
transactions freely: a `BEGIN` becomes a savepoint, so nothing it does can end
|
|
400
|
+
the test's transaction.
|
|
401
|
+
|
|
402
|
+
```typescript
|
|
403
|
+
const registry = new TransactionRegistry();
|
|
404
|
+
const db = await registry.get('Database', process.env.DATABASE_URL!);
|
|
405
|
+
// …
|
|
406
|
+
await registry.rollbackAll();
|
|
407
|
+
```
|
|
408
|
+
|
|
324
409
|
## Database Migration
|
|
325
410
|
|
|
326
411
|
TestKit includes utilities for managing test database migrations.
|
|
@@ -724,6 +809,29 @@ function memoryAdapter(config?: {
|
|
|
724
809
|
|
|
725
810
|
We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for details.
|
|
726
811
|
|
|
812
|
+
## Optional peers
|
|
813
|
+
|
|
814
|
+
<!-- optional-peers:start -->
|
|
815
|
+
|
|
816
|
+
<!-- Generated by `node scripts/check-optional-peers.mjs --write-docs`; CI fails when it drifts. -->
|
|
817
|
+
|
|
818
|
+
Each of these entries imports an optional peer when it loads, so using it means installing that peer:
|
|
819
|
+
|
|
820
|
+
| Entry | Install |
|
|
821
|
+
| --- | --- |
|
|
822
|
+
| `@geekmidas/testkit/aws` | `vitest` |
|
|
823
|
+
| `@geekmidas/testkit/better-auth` | `better-auth` |
|
|
824
|
+
| `@geekmidas/testkit/kysely` | `kysely`, `pg` |
|
|
825
|
+
| `@geekmidas/testkit/logger` | `vitest` |
|
|
826
|
+
| `@geekmidas/testkit/objection` | `pg` |
|
|
827
|
+
| `@geekmidas/testkit/os` | `vitest` |
|
|
828
|
+
| `@geekmidas/testkit/postgres` | `pg` |
|
|
829
|
+
| `@geekmidas/testkit/transactions` | `kysely`, `pg` |
|
|
830
|
+
|
|
831
|
+
No other entry imports an optional peer when it loads. `@geekmidas/emailkit`, `@types/aws-lambda`, `db-errors`, `knex`, `objection` are loaded only when a feature that uses one runs (an `import()` inside a `try`, whose error names the package to install), or named only in types.
|
|
832
|
+
|
|
833
|
+
<!-- optional-peers:end -->
|
|
834
|
+
|
|
727
835
|
## License
|
|
728
836
|
|
|
729
837
|
This project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as PostgresMigrator } from "./PostgresMigrator-
|
|
1
|
+
import { t as PostgresMigrator } from "./PostgresMigrator-CDPnnwMJ.cjs";
|
|
2
2
|
import { Kysely } from "kysely";
|
|
3
3
|
import { MigrationProvider } from "kysely/migration";
|
|
4
4
|
//#region src/PostgresKyselyMigrator.d.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as PostgresMigrator } from "./PostgresMigrator-
|
|
1
|
+
import { t as PostgresMigrator } from "./PostgresMigrator-CDPnnwMJ.mjs";
|
|
2
2
|
import { MigrationProvider } from "kysely/migration";
|
|
3
3
|
import { Kysely } from "kysely";
|
|
4
4
|
//#region src/PostgresKyselyMigrator.d.ts
|
|
@@ -71,9 +71,16 @@ declare abstract class PostgresMigrator {
|
|
|
71
71
|
private static drop;
|
|
72
72
|
/**
|
|
73
73
|
* Starts the migration process by creating the database and running migrations.
|
|
74
|
-
* Returns a cleanup function that
|
|
74
|
+
* Returns a cleanup function that drops the database — if this call created
|
|
75
|
+
* it.
|
|
75
76
|
*
|
|
76
|
-
*
|
|
77
|
+
* A database that was already there belongs to whoever made it, and the
|
|
78
|
+
* cleanup leaves it alone. `gkm test` provisions the test database before
|
|
79
|
+
* the suite starts, with an owner role that may migrate it but not drop it:
|
|
80
|
+
* dropping it was never the suite's to do, and failed there as a permission
|
|
81
|
+
* error on the way out of an otherwise green run.
|
|
82
|
+
*
|
|
83
|
+
* @returns Async cleanup function that drops the database if it created it
|
|
77
84
|
*
|
|
78
85
|
* @example
|
|
79
86
|
* ```typescript
|
|
@@ -95,4 +102,4 @@ declare abstract class PostgresMigrator {
|
|
|
95
102
|
}
|
|
96
103
|
//#endregion
|
|
97
104
|
export { PostgresMigrator as t };
|
|
98
|
-
//# sourceMappingURL=PostgresMigrator-
|
|
105
|
+
//# sourceMappingURL=PostgresMigrator-CDPnnwMJ.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PostgresMigrator-CDPnnwMJ.d.cts","names":[],"sources":["../src/PostgresMigrator.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBA4EsB;UAQZ;UACA;;;;;;;EAFT,YACS,aACA,gBAAe,gBAAgB;;;;;;;WAS/B,WAAW;;;;;;;;;iBAUC;;;;;;;;;iBA4CA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuCf,SAAK,cAAA"}
|
|
@@ -71,9 +71,16 @@ declare abstract class PostgresMigrator {
|
|
|
71
71
|
private static drop;
|
|
72
72
|
/**
|
|
73
73
|
* Starts the migration process by creating the database and running migrations.
|
|
74
|
-
* Returns a cleanup function that
|
|
74
|
+
* Returns a cleanup function that drops the database — if this call created
|
|
75
|
+
* it.
|
|
75
76
|
*
|
|
76
|
-
*
|
|
77
|
+
* A database that was already there belongs to whoever made it, and the
|
|
78
|
+
* cleanup leaves it alone. `gkm test` provisions the test database before
|
|
79
|
+
* the suite starts, with an owner role that may migrate it but not drop it:
|
|
80
|
+
* dropping it was never the suite's to do, and failed there as a permission
|
|
81
|
+
* error on the way out of an otherwise green run.
|
|
82
|
+
*
|
|
83
|
+
* @returns Async cleanup function that drops the database if it created it
|
|
77
84
|
*
|
|
78
85
|
* @example
|
|
79
86
|
* ```typescript
|
|
@@ -95,4 +102,4 @@ declare abstract class PostgresMigrator {
|
|
|
95
102
|
}
|
|
96
103
|
//#endregion
|
|
97
104
|
export { PostgresMigrator as t };
|
|
98
|
-
//# sourceMappingURL=PostgresMigrator-
|
|
105
|
+
//# sourceMappingURL=PostgresMigrator-CDPnnwMJ.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PostgresMigrator-CDPnnwMJ.d.mts","names":[],"sources":["../src/PostgresMigrator.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBA4EsB;UAQZ;UACA;;;;;;;EAFT,YACS,aACA,gBAAe,gBAAgB;;;;;;;WAS/B,WAAW;;;;;;;;;iBAUC;;;;;;;;;iBA4CA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuCf,SAAK,cAAA"}
|
|
@@ -102,7 +102,7 @@ var PostgresMigrator = class PostgresMigrator {
|
|
|
102
102
|
if (result.rowCount === 0) try {
|
|
103
103
|
await db.query(`CREATE DATABASE "${database}"`);
|
|
104
104
|
} catch (error) {
|
|
105
|
-
if (error?.code === "42P04") return { alreadyExisted: true };
|
|
105
|
+
if (error?.code === "42P04" || error?.code === "23505" && error?.constraint === "pg_database_datname_index") return { alreadyExisted: true };
|
|
106
106
|
throw error;
|
|
107
107
|
}
|
|
108
108
|
return { alreadyExisted: result.rowCount ? result.rowCount > 0 : false };
|
|
@@ -129,9 +129,16 @@ var PostgresMigrator = class PostgresMigrator {
|
|
|
129
129
|
}
|
|
130
130
|
/**
|
|
131
131
|
* Starts the migration process by creating the database and running migrations.
|
|
132
|
-
* Returns a cleanup function that
|
|
132
|
+
* Returns a cleanup function that drops the database — if this call created
|
|
133
|
+
* it.
|
|
133
134
|
*
|
|
134
|
-
*
|
|
135
|
+
* A database that was already there belongs to whoever made it, and the
|
|
136
|
+
* cleanup leaves it alone. `gkm test` provisions the test database before
|
|
137
|
+
* the suite starts, with an owner role that may migrate it but not drop it:
|
|
138
|
+
* dropping it was never the suite's to do, and failed there as a permission
|
|
139
|
+
* error on the way out of an otherwise green run.
|
|
140
|
+
*
|
|
141
|
+
* @returns Async cleanup function that drops the database if it created it
|
|
135
142
|
*
|
|
136
143
|
* @example
|
|
137
144
|
* ```typescript
|
|
@@ -151,8 +158,10 @@ var PostgresMigrator = class PostgresMigrator {
|
|
|
151
158
|
*/
|
|
152
159
|
async start() {
|
|
153
160
|
const { database, db } = await setupClient(this.uri);
|
|
161
|
+
let created = false;
|
|
154
162
|
try {
|
|
155
|
-
await PostgresMigrator.create(this.uri);
|
|
163
|
+
const { alreadyExisted } = await PostgresMigrator.create(this.uri);
|
|
164
|
+
created = !alreadyExisted;
|
|
156
165
|
if (this.afterCreate) await this.afterCreate(this.uri);
|
|
157
166
|
await this.migrate();
|
|
158
167
|
logger.log(`Migrating database: ${database}`);
|
|
@@ -160,7 +169,7 @@ var PostgresMigrator = class PostgresMigrator {
|
|
|
160
169
|
await db.end();
|
|
161
170
|
}
|
|
162
171
|
return async () => {
|
|
163
|
-
await PostgresMigrator.drop(this.uri);
|
|
172
|
+
if (created) await PostgresMigrator.drop(this.uri);
|
|
164
173
|
};
|
|
165
174
|
}
|
|
166
175
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresMigrator.cjs","names":[],"sources":["../src/PostgresMigrator.ts"],"sourcesContent":["import pg from 'pg';\n\nconst { Client } = pg;\n\n/**\n * Creates a PostgreSQL client connected to the 'postgres' database.\n * Extracts connection details from the provided URI.\n *\n * @param uri - PostgreSQL connection URI\n * @returns Object containing the target database name and client instance\n *\n * @example\n * ```typescript\n * const { database, db } = await setupClient('postgresql://user:pass@localhost:5432/mydb');\n * // database = 'mydb'\n * // db = Client instance connected to 'postgres' database\n * ```\n */\nasync function setupClient(uri: string) {\n\tconst url = new URL(uri);\n\n\tconst db = new Client({\n\t\tuser: url.username,\n\t\tpassword: url.password,\n\t\thost: url.hostname,\n\t\tport: parseInt(url.port, 10),\n\t\tdatabase: 'postgres',\n\t});\n\n\tlet database = url.pathname.slice(1);\n\tif (database.includes('?')) {\n\t\tdatabase = database.substring(0, database.indexOf('?'));\n\t}\n\treturn { database, db };\n}\n\n/**\n * Default logger instance for migration operations.\n */\nconst logger = console;\n\n/**\n * Abstract base class for PostgreSQL database migration utilities.\n * Provides database creation, migration, and cleanup functionality for testing.\n * Subclasses must implement the migrate() method to define migration logic.\n *\n * @example\n * ```typescript\n * class MyMigrator extends PostgresMigrator {\n * async migrate(): Promise<void> {\n * // Run your migrations here\n * await this.runMigrations();\n * }\n * }\n *\n * // Use in tests\n * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n * const cleanup = await migrator.start();\n *\n * // With afterCreate hook (e.g. run init script to create per-app users)\n * import { runInitScript } from '@geekmidas/testkit/postgres';\n *\n * const migrator = new MyMigrator(\n * 'postgresql://localhost:5432/test_db',\n * async (uri) => {\n * await runInitScript('docker/postgres/init.sh', uri, env);\n * },\n * );\n * const cleanup = await migrator.start();\n *\n * // Run tests...\n *\n * // Clean up\n * await cleanup();\n * ```\n */\nexport abstract class PostgresMigrator {\n\t/**\n\t * Creates a new PostgresMigrator instance.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @param afterCreate - Optional hook called after database creation but before migrations\n\t */\n\tconstructor(\n\t\tprivate uri: string,\n\t\tprivate afterCreate?: (uri: string) => Promise<void>,\n\t) {}\n\n\t/**\n\t * Abstract method to be implemented by subclasses.\n\t * Should contain the migration logic for setting up database schema.\n\t *\n\t * @returns Promise that resolves when migrations are complete\n\t */\n\tabstract migrate(): Promise<void>;\n\n\t/**\n\t * Creates a PostgreSQL database if it doesn't already exist.\n\t * Connects to the 'postgres' database to check and create the target database.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @returns Object indicating whether the database already existed\n\t * @private\n\t */\n\tprivate static async create(\n\t\turi: string,\n\t): Promise<{ alreadyExisted: boolean }> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT * FROM pg_catalog.pg_database WHERE datname = '${database}'`,\n\t\t\t);\n\n\t\t\tif (result.rowCount === 0) {\n\t\t\t\ttry {\n\t\t\t\t\tawait db.query(`CREATE DATABASE \"${database}\"`);\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\t//
|
|
1
|
+
{"version":3,"file":"PostgresMigrator.cjs","names":[],"sources":["../src/PostgresMigrator.ts"],"sourcesContent":["import pg from 'pg';\n\nconst { Client } = pg;\n\n/**\n * Creates a PostgreSQL client connected to the 'postgres' database.\n * Extracts connection details from the provided URI.\n *\n * @param uri - PostgreSQL connection URI\n * @returns Object containing the target database name and client instance\n *\n * @example\n * ```typescript\n * const { database, db } = await setupClient('postgresql://user:pass@localhost:5432/mydb');\n * // database = 'mydb'\n * // db = Client instance connected to 'postgres' database\n * ```\n */\nasync function setupClient(uri: string) {\n\tconst url = new URL(uri);\n\n\tconst db = new Client({\n\t\tuser: url.username,\n\t\tpassword: url.password,\n\t\thost: url.hostname,\n\t\tport: parseInt(url.port, 10),\n\t\tdatabase: 'postgres',\n\t});\n\n\tlet database = url.pathname.slice(1);\n\tif (database.includes('?')) {\n\t\tdatabase = database.substring(0, database.indexOf('?'));\n\t}\n\treturn { database, db };\n}\n\n/**\n * Default logger instance for migration operations.\n */\nconst logger = console;\n\n/**\n * Abstract base class for PostgreSQL database migration utilities.\n * Provides database creation, migration, and cleanup functionality for testing.\n * Subclasses must implement the migrate() method to define migration logic.\n *\n * @example\n * ```typescript\n * class MyMigrator extends PostgresMigrator {\n * async migrate(): Promise<void> {\n * // Run your migrations here\n * await this.runMigrations();\n * }\n * }\n *\n * // Use in tests\n * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n * const cleanup = await migrator.start();\n *\n * // With afterCreate hook (e.g. run init script to create per-app users)\n * import { runInitScript } from '@geekmidas/testkit/postgres';\n *\n * const migrator = new MyMigrator(\n * 'postgresql://localhost:5432/test_db',\n * async (uri) => {\n * await runInitScript('docker/postgres/init.sh', uri, env);\n * },\n * );\n * const cleanup = await migrator.start();\n *\n * // Run tests...\n *\n * // Clean up\n * await cleanup();\n * ```\n */\nexport abstract class PostgresMigrator {\n\t/**\n\t * Creates a new PostgresMigrator instance.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @param afterCreate - Optional hook called after database creation but before migrations\n\t */\n\tconstructor(\n\t\tprivate uri: string,\n\t\tprivate afterCreate?: (uri: string) => Promise<void>,\n\t) {}\n\n\t/**\n\t * Abstract method to be implemented by subclasses.\n\t * Should contain the migration logic for setting up database schema.\n\t *\n\t * @returns Promise that resolves when migrations are complete\n\t */\n\tabstract migrate(): Promise<void>;\n\n\t/**\n\t * Creates a PostgreSQL database if it doesn't already exist.\n\t * Connects to the 'postgres' database to check and create the target database.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @returns Object indicating whether the database already existed\n\t * @private\n\t */\n\tprivate static async create(\n\t\turi: string,\n\t): Promise<{ alreadyExisted: boolean }> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT * FROM pg_catalog.pg_database WHERE datname = '${database}'`,\n\t\t\t);\n\n\t\t\tif (result.rowCount === 0) {\n\t\t\t\ttry {\n\t\t\t\t\tawait db.query(`CREATE DATABASE \"${database}\"`);\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\t// Another process created it between our check and our create. Postgres\n\t\t\t\t\t// reports that as 42P04 (duplicate_database) — or, when the two creates\n\t\t\t\t\t// race inside the catalog itself, as 23505 on pg_database's name index.\n\t\t\t\t\tif (\n\t\t\t\t\t\terror?.code === '42P04' ||\n\t\t\t\t\t\t(error?.code === '23505' &&\n\t\t\t\t\t\t\terror?.constraint === 'pg_database_datname_index')\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn { alreadyExisted: true };\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\talreadyExisted: result.rowCount ? result.rowCount > 0 : false,\n\t\t\t};\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\t}\n\n\t/**\n\t * Drops a PostgreSQL database.\n\t * Used for cleanup after tests are complete.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @throws Error if database cannot be dropped\n\t * @private\n\t */\n\tprivate static async drop(uri: string): Promise<void> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tawait db.query(`DROP DATABASE \"${database}\"`);\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\t}\n\n\t/**\n\t * Starts the migration process by creating the database and running migrations.\n\t * Returns a cleanup function that drops the database — if this call created\n\t * it.\n\t *\n\t * A database that was already there belongs to whoever made it, and the\n\t * cleanup leaves it alone. `gkm test` provisions the test database before\n\t * the suite starts, with an owner role that may migrate it but not drop it:\n\t * dropping it was never the suite's to do, and failed there as a permission\n\t * error on the way out of an otherwise green run.\n\t *\n\t * @returns Async cleanup function that drops the database if it created it\n\t *\n\t * @example\n\t * ```typescript\n\t * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n\t *\n\t * // Start migrations and get cleanup function\n\t * const cleanup = await migrator.start();\n\t *\n\t * try {\n\t * // Run your tests here\n\t * await runTests();\n\t * } finally {\n\t * // Always clean up\n\t * await cleanup();\n\t * }\n\t * ```\n\t */\n\tasync start() {\n\t\tconst { database, db } = await setupClient(this.uri);\n\t\tlet created = false;\n\t\ttry {\n\t\t\tconst { alreadyExisted } = await PostgresMigrator.create(this.uri);\n\t\t\tcreated = !alreadyExisted;\n\t\t\tif (this.afterCreate) {\n\t\t\t\tawait this.afterCreate(this.uri);\n\t\t\t}\n\t\t\tawait this.migrate();\n\t\t\tlogger.log(`Migrating database: ${database}`);\n\t\t\t// Example: await db.query('CREATE TABLE example (id SERIAL PRIMARY KEY)');\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\n\t\treturn async () => {\n\t\t\tif (created) await PostgresMigrator.drop(this.uri);\n\t\t};\n\t}\n}\n"],"mappings":";;;;;AAEA,MAAM,EAAE,WAAW,GAAA;;;;;;;;;;;;;;;AAgBnB,eAAe,YAAY,KAAa;CACvC,MAAM,MAAM,IAAI,IAAI,GAAG;CAEvB,MAAM,KAAK,IAAI,OAAO;EACrB,MAAM,IAAI;EACV,UAAU,IAAI;EACd,MAAM,IAAI;EACV,MAAM,SAAS,IAAI,MAAM,EAAE;EAC3B,UAAU;CACX,CAAC;CAED,IAAI,WAAW,IAAI,SAAS,MAAM,CAAC;CACnC,IAAI,SAAS,SAAS,GAAG,GACxB,WAAW,SAAS,UAAU,GAAG,SAAS,QAAQ,GAAG,CAAC;CAEvD,OAAO;EAAE;EAAU;CAAG;AACvB;;;;AAKA,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCf,IAAsB,mBAAtB,MAAsB,iBAAiB;CAQ7B;CACA;;;;;;;CAFT,YACC,KACA,aACC;EAFO,KAAA,MAAA;EACA,KAAA,cAAA;CACN;;;;;;;;;CAkBH,aAAqB,OACpB,KACuC;EACvC,MAAM,EAAE,UAAU,OAAO,MAAM,YAAY,GAAG;EAC9C,IAAI;GACH,MAAM,GAAG,QAAQ;GACjB,MAAM,SAAS,MAAM,GAAG,MACvB,yDAAyD,SAAS,EACnE;GAEA,IAAI,OAAO,aAAa,GACvB,IAAI;IACH,MAAM,GAAG,MAAM,oBAAoB,SAAS,EAAE;GAC/C,SAAS,OAAY;IAIpB,IACC,OAAO,SAAS,WACf,OAAO,SAAS,WAChB,OAAO,eAAe,6BAEvB,OAAO,EAAE,gBAAgB,KAAK;IAE/B,MAAM;GACP;GAGD,OAAO,EACN,gBAAgB,OAAO,WAAW,OAAO,WAAW,IAAI,MACzD;EACD,UAAU;GACT,MAAM,GAAG,IAAI;EACd;CACD;;;;;;;;;CAUA,aAAqB,KAAK,KAA4B;EACrD,MAAM,EAAE,UAAU,OAAO,MAAM,YAAY,GAAG;EAC9C,IAAI;GACH,MAAM,GAAG,QAAQ;GACjB,MAAM,GAAG,MAAM,kBAAkB,SAAS,EAAE;EAC7C,UAAU;GACT,MAAM,GAAG,IAAI;EACd;CACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BA,MAAM,QAAQ;EACb,MAAM,EAAE,UAAU,OAAO,MAAM,YAAY,KAAK,GAAG;EACnD,IAAI,UAAU;EACd,IAAI;GACH,MAAM,EAAE,mBAAmB,MAAM,iBAAiB,OAAO,KAAK,GAAG;GACjE,UAAU,CAAC;GACX,IAAI,KAAK,aACR,MAAM,KAAK,YAAY,KAAK,GAAG;GAEhC,MAAM,KAAK,QAAQ;GACnB,OAAO,IAAI,uBAAuB,UAAU;EAE7C,UAAU;GACT,MAAM,GAAG,IAAI;EACd;EAEA,OAAO,YAAY;GAClB,IAAI,SAAS,MAAM,iBAAiB,KAAK,KAAK,GAAG;EAClD;CACD;AACD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as PostgresMigrator } from "./PostgresMigrator-
|
|
1
|
+
import { t as PostgresMigrator } from "./PostgresMigrator-CDPnnwMJ.cjs";
|
|
2
2
|
export { PostgresMigrator };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as PostgresMigrator } from "./PostgresMigrator-
|
|
1
|
+
import { t as PostgresMigrator } from "./PostgresMigrator-CDPnnwMJ.mjs";
|
|
2
2
|
export { PostgresMigrator };
|
|
@@ -99,7 +99,7 @@ var PostgresMigrator = class PostgresMigrator {
|
|
|
99
99
|
if (result.rowCount === 0) try {
|
|
100
100
|
await db.query(`CREATE DATABASE "${database}"`);
|
|
101
101
|
} catch (error) {
|
|
102
|
-
if (error?.code === "42P04") return { alreadyExisted: true };
|
|
102
|
+
if (error?.code === "42P04" || error?.code === "23505" && error?.constraint === "pg_database_datname_index") return { alreadyExisted: true };
|
|
103
103
|
throw error;
|
|
104
104
|
}
|
|
105
105
|
return { alreadyExisted: result.rowCount ? result.rowCount > 0 : false };
|
|
@@ -126,9 +126,16 @@ var PostgresMigrator = class PostgresMigrator {
|
|
|
126
126
|
}
|
|
127
127
|
/**
|
|
128
128
|
* Starts the migration process by creating the database and running migrations.
|
|
129
|
-
* Returns a cleanup function that
|
|
129
|
+
* Returns a cleanup function that drops the database — if this call created
|
|
130
|
+
* it.
|
|
130
131
|
*
|
|
131
|
-
*
|
|
132
|
+
* A database that was already there belongs to whoever made it, and the
|
|
133
|
+
* cleanup leaves it alone. `gkm test` provisions the test database before
|
|
134
|
+
* the suite starts, with an owner role that may migrate it but not drop it:
|
|
135
|
+
* dropping it was never the suite's to do, and failed there as a permission
|
|
136
|
+
* error on the way out of an otherwise green run.
|
|
137
|
+
*
|
|
138
|
+
* @returns Async cleanup function that drops the database if it created it
|
|
132
139
|
*
|
|
133
140
|
* @example
|
|
134
141
|
* ```typescript
|
|
@@ -148,8 +155,10 @@ var PostgresMigrator = class PostgresMigrator {
|
|
|
148
155
|
*/
|
|
149
156
|
async start() {
|
|
150
157
|
const { database, db } = await setupClient(this.uri);
|
|
158
|
+
let created = false;
|
|
151
159
|
try {
|
|
152
|
-
await PostgresMigrator.create(this.uri);
|
|
160
|
+
const { alreadyExisted } = await PostgresMigrator.create(this.uri);
|
|
161
|
+
created = !alreadyExisted;
|
|
153
162
|
if (this.afterCreate) await this.afterCreate(this.uri);
|
|
154
163
|
await this.migrate();
|
|
155
164
|
logger.log(`Migrating database: ${database}`);
|
|
@@ -157,7 +166,7 @@ var PostgresMigrator = class PostgresMigrator {
|
|
|
157
166
|
await db.end();
|
|
158
167
|
}
|
|
159
168
|
return async () => {
|
|
160
|
-
await PostgresMigrator.drop(this.uri);
|
|
169
|
+
if (created) await PostgresMigrator.drop(this.uri);
|
|
161
170
|
};
|
|
162
171
|
}
|
|
163
172
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresMigrator.mjs","names":[],"sources":["../src/PostgresMigrator.ts"],"sourcesContent":["import pg from 'pg';\n\nconst { Client } = pg;\n\n/**\n * Creates a PostgreSQL client connected to the 'postgres' database.\n * Extracts connection details from the provided URI.\n *\n * @param uri - PostgreSQL connection URI\n * @returns Object containing the target database name and client instance\n *\n * @example\n * ```typescript\n * const { database, db } = await setupClient('postgresql://user:pass@localhost:5432/mydb');\n * // database = 'mydb'\n * // db = Client instance connected to 'postgres' database\n * ```\n */\nasync function setupClient(uri: string) {\n\tconst url = new URL(uri);\n\n\tconst db = new Client({\n\t\tuser: url.username,\n\t\tpassword: url.password,\n\t\thost: url.hostname,\n\t\tport: parseInt(url.port, 10),\n\t\tdatabase: 'postgres',\n\t});\n\n\tlet database = url.pathname.slice(1);\n\tif (database.includes('?')) {\n\t\tdatabase = database.substring(0, database.indexOf('?'));\n\t}\n\treturn { database, db };\n}\n\n/**\n * Default logger instance for migration operations.\n */\nconst logger = console;\n\n/**\n * Abstract base class for PostgreSQL database migration utilities.\n * Provides database creation, migration, and cleanup functionality for testing.\n * Subclasses must implement the migrate() method to define migration logic.\n *\n * @example\n * ```typescript\n * class MyMigrator extends PostgresMigrator {\n * async migrate(): Promise<void> {\n * // Run your migrations here\n * await this.runMigrations();\n * }\n * }\n *\n * // Use in tests\n * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n * const cleanup = await migrator.start();\n *\n * // With afterCreate hook (e.g. run init script to create per-app users)\n * import { runInitScript } from '@geekmidas/testkit/postgres';\n *\n * const migrator = new MyMigrator(\n * 'postgresql://localhost:5432/test_db',\n * async (uri) => {\n * await runInitScript('docker/postgres/init.sh', uri, env);\n * },\n * );\n * const cleanup = await migrator.start();\n *\n * // Run tests...\n *\n * // Clean up\n * await cleanup();\n * ```\n */\nexport abstract class PostgresMigrator {\n\t/**\n\t * Creates a new PostgresMigrator instance.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @param afterCreate - Optional hook called after database creation but before migrations\n\t */\n\tconstructor(\n\t\tprivate uri: string,\n\t\tprivate afterCreate?: (uri: string) => Promise<void>,\n\t) {}\n\n\t/**\n\t * Abstract method to be implemented by subclasses.\n\t * Should contain the migration logic for setting up database schema.\n\t *\n\t * @returns Promise that resolves when migrations are complete\n\t */\n\tabstract migrate(): Promise<void>;\n\n\t/**\n\t * Creates a PostgreSQL database if it doesn't already exist.\n\t * Connects to the 'postgres' database to check and create the target database.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @returns Object indicating whether the database already existed\n\t * @private\n\t */\n\tprivate static async create(\n\t\turi: string,\n\t): Promise<{ alreadyExisted: boolean }> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT * FROM pg_catalog.pg_database WHERE datname = '${database}'`,\n\t\t\t);\n\n\t\t\tif (result.rowCount === 0) {\n\t\t\t\ttry {\n\t\t\t\t\tawait db.query(`CREATE DATABASE \"${database}\"`);\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\t//
|
|
1
|
+
{"version":3,"file":"PostgresMigrator.mjs","names":[],"sources":["../src/PostgresMigrator.ts"],"sourcesContent":["import pg from 'pg';\n\nconst { Client } = pg;\n\n/**\n * Creates a PostgreSQL client connected to the 'postgres' database.\n * Extracts connection details from the provided URI.\n *\n * @param uri - PostgreSQL connection URI\n * @returns Object containing the target database name and client instance\n *\n * @example\n * ```typescript\n * const { database, db } = await setupClient('postgresql://user:pass@localhost:5432/mydb');\n * // database = 'mydb'\n * // db = Client instance connected to 'postgres' database\n * ```\n */\nasync function setupClient(uri: string) {\n\tconst url = new URL(uri);\n\n\tconst db = new Client({\n\t\tuser: url.username,\n\t\tpassword: url.password,\n\t\thost: url.hostname,\n\t\tport: parseInt(url.port, 10),\n\t\tdatabase: 'postgres',\n\t});\n\n\tlet database = url.pathname.slice(1);\n\tif (database.includes('?')) {\n\t\tdatabase = database.substring(0, database.indexOf('?'));\n\t}\n\treturn { database, db };\n}\n\n/**\n * Default logger instance for migration operations.\n */\nconst logger = console;\n\n/**\n * Abstract base class for PostgreSQL database migration utilities.\n * Provides database creation, migration, and cleanup functionality for testing.\n * Subclasses must implement the migrate() method to define migration logic.\n *\n * @example\n * ```typescript\n * class MyMigrator extends PostgresMigrator {\n * async migrate(): Promise<void> {\n * // Run your migrations here\n * await this.runMigrations();\n * }\n * }\n *\n * // Use in tests\n * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n * const cleanup = await migrator.start();\n *\n * // With afterCreate hook (e.g. run init script to create per-app users)\n * import { runInitScript } from '@geekmidas/testkit/postgres';\n *\n * const migrator = new MyMigrator(\n * 'postgresql://localhost:5432/test_db',\n * async (uri) => {\n * await runInitScript('docker/postgres/init.sh', uri, env);\n * },\n * );\n * const cleanup = await migrator.start();\n *\n * // Run tests...\n *\n * // Clean up\n * await cleanup();\n * ```\n */\nexport abstract class PostgresMigrator {\n\t/**\n\t * Creates a new PostgresMigrator instance.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @param afterCreate - Optional hook called after database creation but before migrations\n\t */\n\tconstructor(\n\t\tprivate uri: string,\n\t\tprivate afterCreate?: (uri: string) => Promise<void>,\n\t) {}\n\n\t/**\n\t * Abstract method to be implemented by subclasses.\n\t * Should contain the migration logic for setting up database schema.\n\t *\n\t * @returns Promise that resolves when migrations are complete\n\t */\n\tabstract migrate(): Promise<void>;\n\n\t/**\n\t * Creates a PostgreSQL database if it doesn't already exist.\n\t * Connects to the 'postgres' database to check and create the target database.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @returns Object indicating whether the database already existed\n\t * @private\n\t */\n\tprivate static async create(\n\t\turi: string,\n\t): Promise<{ alreadyExisted: boolean }> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT * FROM pg_catalog.pg_database WHERE datname = '${database}'`,\n\t\t\t);\n\n\t\t\tif (result.rowCount === 0) {\n\t\t\t\ttry {\n\t\t\t\t\tawait db.query(`CREATE DATABASE \"${database}\"`);\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\t// Another process created it between our check and our create. Postgres\n\t\t\t\t\t// reports that as 42P04 (duplicate_database) — or, when the two creates\n\t\t\t\t\t// race inside the catalog itself, as 23505 on pg_database's name index.\n\t\t\t\t\tif (\n\t\t\t\t\t\terror?.code === '42P04' ||\n\t\t\t\t\t\t(error?.code === '23505' &&\n\t\t\t\t\t\t\terror?.constraint === 'pg_database_datname_index')\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn { alreadyExisted: true };\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\talreadyExisted: result.rowCount ? result.rowCount > 0 : false,\n\t\t\t};\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\t}\n\n\t/**\n\t * Drops a PostgreSQL database.\n\t * Used for cleanup after tests are complete.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @throws Error if database cannot be dropped\n\t * @private\n\t */\n\tprivate static async drop(uri: string): Promise<void> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tawait db.query(`DROP DATABASE \"${database}\"`);\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\t}\n\n\t/**\n\t * Starts the migration process by creating the database and running migrations.\n\t * Returns a cleanup function that drops the database — if this call created\n\t * it.\n\t *\n\t * A database that was already there belongs to whoever made it, and the\n\t * cleanup leaves it alone. `gkm test` provisions the test database before\n\t * the suite starts, with an owner role that may migrate it but not drop it:\n\t * dropping it was never the suite's to do, and failed there as a permission\n\t * error on the way out of an otherwise green run.\n\t *\n\t * @returns Async cleanup function that drops the database if it created it\n\t *\n\t * @example\n\t * ```typescript\n\t * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n\t *\n\t * // Start migrations and get cleanup function\n\t * const cleanup = await migrator.start();\n\t *\n\t * try {\n\t * // Run your tests here\n\t * await runTests();\n\t * } finally {\n\t * // Always clean up\n\t * await cleanup();\n\t * }\n\t * ```\n\t */\n\tasync start() {\n\t\tconst { database, db } = await setupClient(this.uri);\n\t\tlet created = false;\n\t\ttry {\n\t\t\tconst { alreadyExisted } = await PostgresMigrator.create(this.uri);\n\t\t\tcreated = !alreadyExisted;\n\t\t\tif (this.afterCreate) {\n\t\t\t\tawait this.afterCreate(this.uri);\n\t\t\t}\n\t\t\tawait this.migrate();\n\t\t\tlogger.log(`Migrating database: ${database}`);\n\t\t\t// Example: await db.query('CREATE TABLE example (id SERIAL PRIMARY KEY)');\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\n\t\treturn async () => {\n\t\t\tif (created) await PostgresMigrator.drop(this.uri);\n\t\t};\n\t}\n}\n"],"mappings":";;AAEA,MAAM,EAAE,WAAW;;;;;;;;;;;;;;;AAgBnB,eAAe,YAAY,KAAa;CACvC,MAAM,MAAM,IAAI,IAAI,GAAG;CAEvB,MAAM,KAAK,IAAI,OAAO;EACrB,MAAM,IAAI;EACV,UAAU,IAAI;EACd,MAAM,IAAI;EACV,MAAM,SAAS,IAAI,MAAM,EAAE;EAC3B,UAAU;CACX,CAAC;CAED,IAAI,WAAW,IAAI,SAAS,MAAM,CAAC;CACnC,IAAI,SAAS,SAAS,GAAG,GACxB,WAAW,SAAS,UAAU,GAAG,SAAS,QAAQ,GAAG,CAAC;CAEvD,OAAO;EAAE;EAAU;C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AU;GACT,MAAM,GAAG,IAAI;EACd;EAEA,OAAO,YAAY;GAClB,IAAI,SAAS,MAAM,iBAAiB,KAAK,KAAK,GAAG;EAClD;CACD;AACD"}
|
package/dist/browser.cjs
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_context = require("./context.cjs");
|
|
3
|
+
let node_crypto = require("node:crypto");
|
|
4
|
+
let tough_cookie = require("tough-cookie");
|
|
5
|
+
//#region src/browser.ts
|
|
6
|
+
/**
|
|
7
|
+
* A browser, for tests: a `fetch` that keeps cookies the way a browser does.
|
|
8
|
+
*
|
|
9
|
+
* An app's real clients — its typed API client, better-auth's client — run on
|
|
10
|
+
* whatever `fetch` they are given. Give them this one and a test signs in the
|
|
11
|
+
* way a person does: the auth server's `Set-Cookie` lands in the jar, and every
|
|
12
|
+
* later request to a URL the cookie belongs to carries it. The jar follows the
|
|
13
|
+
* browser's rules (RFC 6265 — Domain, Path, Secure, Expires), so a cookie set
|
|
14
|
+
* for the wrong domain is not sent, exactly as a browser would not send it.
|
|
15
|
+
*
|
|
16
|
+
* Extend it once per app with that app's clients:
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* export class Browser extends TestBrowser {
|
|
20
|
+
* readonly api = createApi({ baseURL: process.env.API_URL, fetch: this.fetch });
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
/** How many redirects `fetch` follows before giving up, as browsers do. */
|
|
25
|
+
const MAX_REDIRECTS = 20;
|
|
26
|
+
var Browser = class {
|
|
27
|
+
/** The cookies this browser holds. */
|
|
28
|
+
jar;
|
|
29
|
+
/**
|
|
30
|
+
* The page this browser is on, sent as `Origin` — what a surface's CORS
|
|
31
|
+
* and an auth server's trusted origins check, and what a multi-tenant app
|
|
32
|
+
* reads its tenant from. None until {@link Browser.on} gives it one.
|
|
33
|
+
*/
|
|
34
|
+
origin;
|
|
35
|
+
/**
|
|
36
|
+
* The address this browser connects from, sent as `x-forwarded-for` the way
|
|
37
|
+
* a proxy in front of the app adds it. Each browser is a different person on
|
|
38
|
+
* a different connection, so what an app keys by client — an auth server's
|
|
39
|
+
* rate limit — counts each on its own. Without it every browser was the same
|
|
40
|
+
* client, and concurrent tests queued on the same rate-limit row of each
|
|
41
|
+
* other's open transactions. A request that sets the header itself — a test
|
|
42
|
+
* that is several machines — keeps its own.
|
|
43
|
+
*/
|
|
44
|
+
address;
|
|
45
|
+
/**
|
|
46
|
+
* This browser's `fetch`: cookies from the jar on the way out, `Set-Cookie`
|
|
47
|
+
* into the jar on the way back, redirects followed hop by hop so each hop's
|
|
48
|
+
* cookies are kept.
|
|
49
|
+
*
|
|
50
|
+
* On the server side of a test — a handler serving a request — it is the
|
|
51
|
+
* plain `fetch`: a server forwards what it was handed and never reaches into
|
|
52
|
+
* a browser's jar.
|
|
53
|
+
*/
|
|
54
|
+
fetch;
|
|
55
|
+
send;
|
|
56
|
+
site;
|
|
57
|
+
constructor(options = {}) {
|
|
58
|
+
this.send = options.fetch ?? globalThis.fetch;
|
|
59
|
+
this.address = options.address ?? privateAddress();
|
|
60
|
+
this.jar = options.jar ?? new tough_cookie.CookieJar();
|
|
61
|
+
if (options.site) this.site = options.site;
|
|
62
|
+
if (options.origin) this.origin = options.origin;
|
|
63
|
+
this.fetch = (input, init) => {
|
|
64
|
+
if (require_context.currentTestContext()?.side === "server") return this.send(input, init);
|
|
65
|
+
return this.start(new Request(input, init), init?.redirect);
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Open a URL the way clicking a link does: a GET, redirects followed. A
|
|
70
|
+
* path is opened on the page this browser is on.
|
|
71
|
+
*/
|
|
72
|
+
visit(url) {
|
|
73
|
+
return this.fetch(this.origin ? new URL(url, this.origin).toString() : String(url));
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The same person on a tenant's host: this browser — its cookies, its
|
|
77
|
+
* address, its clients — on `https://<slug>.<domain>`, the app's site on
|
|
78
|
+
* every subdomain. Each request it makes says so in `Origin`, as a page on
|
|
79
|
+
* that host would, so a test signs in once and calls the app as two
|
|
80
|
+
* tenants:
|
|
81
|
+
*
|
|
82
|
+
* ```ts
|
|
83
|
+
* await browser.signIn();
|
|
84
|
+
* await browser.on('acme').api.post('/orders', { body });
|
|
85
|
+
* expect(await browser.on('globex').api.get('/orders')).toEqual([]);
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
on(slug) {
|
|
89
|
+
if (!this.site) throw new NoWildcardSite(slug);
|
|
90
|
+
if (!SLUG.test(slug)) throw new NotATenantSlug(slug);
|
|
91
|
+
const origin = new URL(this.site.replace("*", slug)).origin;
|
|
92
|
+
const Same = this.constructor;
|
|
93
|
+
return new Same({
|
|
94
|
+
fetch: this.send,
|
|
95
|
+
address: this.address,
|
|
96
|
+
jar: this.jar,
|
|
97
|
+
site: this.site,
|
|
98
|
+
origin
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** The cookies this browser would send to `url`, as a header value. */
|
|
102
|
+
cookieHeader(url) {
|
|
103
|
+
return this.jar.getCookieString(String(url));
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Make this browser the global `fetch`, for code that uses the global one —
|
|
107
|
+
* an app's module-level clients. Returns what puts the previous one back.
|
|
108
|
+
*/
|
|
109
|
+
install() {
|
|
110
|
+
const previous = globalThis.fetch;
|
|
111
|
+
globalThis.fetch = this.fetch;
|
|
112
|
+
return () => {
|
|
113
|
+
globalThis.fetch = previous;
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** Read the body once, so a redirect that keeps the method can send it again. */
|
|
117
|
+
async start(request, redirect) {
|
|
118
|
+
const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.arrayBuffer();
|
|
119
|
+
const headers = new Headers(request.headers);
|
|
120
|
+
if (!headers.has("x-forwarded-for")) headers.set("x-forwarded-for", this.address);
|
|
121
|
+
if (this.origin && !headers.has("origin")) headers.set("origin", this.origin);
|
|
122
|
+
return this.request({
|
|
123
|
+
url: request.url,
|
|
124
|
+
method: request.method,
|
|
125
|
+
headers,
|
|
126
|
+
body
|
|
127
|
+
}, redirect);
|
|
128
|
+
}
|
|
129
|
+
async request(request, redirect, hops = 0) {
|
|
130
|
+
const headers = new Headers(request.headers);
|
|
131
|
+
const cookie = await this.jar.getCookieString(request.url);
|
|
132
|
+
if (cookie) {
|
|
133
|
+
const existing = headers.get("cookie");
|
|
134
|
+
headers.set("cookie", existing ? `${existing}; ${cookie}` : cookie);
|
|
135
|
+
}
|
|
136
|
+
const response = await this.send(request.url, {
|
|
137
|
+
method: request.method,
|
|
138
|
+
headers,
|
|
139
|
+
body: request.body,
|
|
140
|
+
redirect: "manual"
|
|
141
|
+
});
|
|
142
|
+
for (const set of response.headers.getSetCookie()) await this.jar.setCookie(set, request.url, { ignoreError: true });
|
|
143
|
+
const location = response.headers.get("location");
|
|
144
|
+
if (redirect === "manual" || !location || response.status < 300 || response.status >= 400) return response;
|
|
145
|
+
if (hops >= MAX_REDIRECTS) throw new TooManyRedirects(request.url, MAX_REDIRECTS);
|
|
146
|
+
const keepsMethod = response.status === 307 || response.status === 308 || request.method === "GET" || request.method === "HEAD";
|
|
147
|
+
const url = new URL(location, request.url).toString();
|
|
148
|
+
const next = keepsMethod ? {
|
|
149
|
+
...request,
|
|
150
|
+
url
|
|
151
|
+
} : {
|
|
152
|
+
url,
|
|
153
|
+
method: "GET",
|
|
154
|
+
headers: withoutBody(request.headers)
|
|
155
|
+
};
|
|
156
|
+
return this.request(next, redirect, hops + 1);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
/** Headers for a request that no longer carries the body they described. */
|
|
160
|
+
function withoutBody(headers) {
|
|
161
|
+
const next = new Headers(headers);
|
|
162
|
+
next.delete("content-type");
|
|
163
|
+
next.delete("content-length");
|
|
164
|
+
return next;
|
|
165
|
+
}
|
|
166
|
+
/** A redirect chain longer than any browser follows. */
|
|
167
|
+
var TooManyRedirects = class extends Error {
|
|
168
|
+
url;
|
|
169
|
+
limit;
|
|
170
|
+
constructor(url, limit) {
|
|
171
|
+
super(`${url} redirected more than ${limit} times. A browser gives up here too — look for a redirect loop.`);
|
|
172
|
+
this.url = url;
|
|
173
|
+
this.limit = limit;
|
|
174
|
+
this.name = "TooManyRedirects";
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
/** One DNS label, as a tenant's slug is. */
|
|
178
|
+
const SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
179
|
+
/** `browser.on(slug)` in an app with no site on every subdomain. */
|
|
180
|
+
var NoWildcardSite = class extends Error {
|
|
181
|
+
slug;
|
|
182
|
+
constructor(slug) {
|
|
183
|
+
super(`browser.on('${slug}') puts a tenant's slug into the app's site on every subdomain, and this browser knows of none. Declare a StaticSite with subdomain: '*', or pass its address as \`site\`.`);
|
|
184
|
+
this.slug = slug;
|
|
185
|
+
this.name = "NoWildcardSite";
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
/** `browser.on(slug)` with something no host can start with. */
|
|
189
|
+
var NotATenantSlug = class extends Error {
|
|
190
|
+
slug;
|
|
191
|
+
constructor(slug) {
|
|
192
|
+
super(`'${slug}' is not a tenant's slug: one DNS label of lowercase letters, digits and inner hyphens, such as 'acme'.`);
|
|
193
|
+
this.slug = slug;
|
|
194
|
+
this.name = "NotATenantSlug";
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* An address from 10.0.0.0/8, which nothing routes to. Random rather than
|
|
199
|
+
* counted: test files run in separate workers that share no counter.
|
|
200
|
+
*/
|
|
201
|
+
function privateAddress() {
|
|
202
|
+
const n = (0, node_crypto.randomInt)(1, 2 ** 24 - 1);
|
|
203
|
+
return `10.${n >> 16 & 255}.${n >> 8 & 255}.${n & 255}`;
|
|
204
|
+
}
|
|
205
|
+
//#endregion
|
|
206
|
+
exports.Browser = Browser;
|
|
207
|
+
exports.NoWildcardSite = NoWildcardSite;
|
|
208
|
+
exports.NotATenantSlug = NotATenantSlug;
|
|
209
|
+
exports.TooManyRedirects = TooManyRedirects;
|
|
210
|
+
|
|
211
|
+
//# sourceMappingURL=browser.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.cjs","names":["CookieJar","currentTestContext","randomInt"],"sources":["../src/browser.ts"],"sourcesContent":["/**\n * A browser, for tests: a `fetch` that keeps cookies the way a browser does.\n *\n * An app's real clients — its typed API client, better-auth's client — run on\n * whatever `fetch` they are given. Give them this one and a test signs in the\n * way a person does: the auth server's `Set-Cookie` lands in the jar, and every\n * later request to a URL the cookie belongs to carries it. The jar follows the\n * browser's rules (RFC 6265 — Domain, Path, Secure, Expires), so a cookie set\n * for the wrong domain is not sent, exactly as a browser would not send it.\n *\n * Extend it once per app with that app's clients:\n *\n * ```ts\n * export class Browser extends TestBrowser {\n * readonly api = createApi({ baseURL: process.env.API_URL, fetch: this.fetch });\n * }\n * ```\n */\n\nimport { randomInt } from 'node:crypto';\nimport { CookieJar } from 'tough-cookie';\nimport { currentTestContext } from './context';\n\n/** How many redirects `fetch` follows before giving up, as browsers do. */\nconst MAX_REDIRECTS = 20;\n\nexport interface BrowserOptions {\n\t/**\n\t * The `fetch` requests go out on. Defaults to the global one at the time\n\t * the browser is created — so a browser made inside a test goes through\n\t * whatever the test installed (MSW, the context stamp) and never through\n\t * itself once installed.\n\t */\n\tfetch?: typeof fetch;\n\t/**\n\t * The address this browser connects from. A fresh one by default, from a\n\t * private range nothing routes to — see {@link Browser.address}.\n\t */\n\taddress?: string;\n\t/**\n\t * The cookies it starts with — another browser's jar, to be the same\n\t * person on another tab. A fresh jar by default.\n\t */\n\tjar?: CookieJar;\n\t/**\n\t * The address of the app's site on every subdomain,\n\t * `https://*.test.shop.localhost:8443`, which {@link Browser.on} puts a\n\t * tenant's slug into. A feature test passes it when the app declares one.\n\t */\n\tsite?: string;\n\t/**\n\t * The page this browser is on: sent as `Origin` on every request that does\n\t * not set its own, and what a relative {@link Browser.visit} resolves\n\t * against. See {@link Browser.on}.\n\t */\n\torigin?: string;\n}\n\nexport class Browser {\n\t/** The cookies this browser holds. */\n\treadonly jar: CookieJar;\n\n\t/**\n\t * The page this browser is on, sent as `Origin` — what a surface's CORS\n\t * and an auth server's trusted origins check, and what a multi-tenant app\n\t * reads its tenant from. None until {@link Browser.on} gives it one.\n\t */\n\treadonly origin?: string;\n\n\t/**\n\t * The address this browser connects from, sent as `x-forwarded-for` the way\n\t * a proxy in front of the app adds it. Each browser is a different person on\n\t * a different connection, so what an app keys by client — an auth server's\n\t * rate limit — counts each on its own. Without it every browser was the same\n\t * client, and concurrent tests queued on the same rate-limit row of each\n\t * other's open transactions. A request that sets the header itself — a test\n\t * that is several machines — keeps its own.\n\t */\n\treadonly address: string;\n\n\t/**\n\t * This browser's `fetch`: cookies from the jar on the way out, `Set-Cookie`\n\t * into the jar on the way back, redirects followed hop by hop so each hop's\n\t * cookies are kept.\n\t *\n\t * On the server side of a test — a handler serving a request — it is the\n\t * plain `fetch`: a server forwards what it was handed and never reaches into\n\t * a browser's jar.\n\t */\n\treadonly fetch: typeof fetch;\n\n\tprivate readonly send: typeof fetch;\n\tprivate readonly site?: string;\n\n\tconstructor(options: BrowserOptions = {}) {\n\t\tthis.send = options.fetch ?? globalThis.fetch;\n\t\tthis.address = options.address ?? privateAddress();\n\t\tthis.jar = options.jar ?? new CookieJar();\n\t\tif (options.site) this.site = options.site;\n\t\tif (options.origin) this.origin = options.origin;\n\t\tthis.fetch = (input, init) => {\n\t\t\tif (currentTestContext()?.side === 'server') {\n\t\t\t\treturn this.send(input, init);\n\t\t\t}\n\t\t\treturn this.start(new Request(input, init), init?.redirect);\n\t\t};\n\t}\n\n\t/**\n\t * Open a URL the way clicking a link does: a GET, redirects followed. A\n\t * path is opened on the page this browser is on.\n\t */\n\tvisit(url: string | URL): Promise<Response> {\n\t\treturn this.fetch(\n\t\t\tthis.origin ? new URL(url, this.origin).toString() : String(url),\n\t\t);\n\t}\n\n\t/**\n\t * The same person on a tenant's host: this browser — its cookies, its\n\t * address, its clients — on `https://<slug>.<domain>`, the app's site on\n\t * every subdomain. Each request it makes says so in `Origin`, as a page on\n\t * that host would, so a test signs in once and calls the app as two\n\t * tenants:\n\t *\n\t * ```ts\n\t * await browser.signIn();\n\t * await browser.on('acme').api.post('/orders', { body });\n\t * expect(await browser.on('globex').api.get('/orders')).toEqual([]);\n\t * ```\n\t */\n\ton(slug: string): this {\n\t\tif (!this.site) throw new NoWildcardSite(slug);\n\t\tif (!SLUG.test(slug)) throw new NotATenantSlug(slug);\n\n\t\tconst origin = new URL(this.site.replace('*', slug)).origin;\n\t\tconst Same = this.constructor as new (options: BrowserOptions) => this;\n\t\treturn new Same({\n\t\t\tfetch: this.send,\n\t\t\taddress: this.address,\n\t\t\tjar: this.jar,\n\t\t\tsite: this.site,\n\t\t\torigin,\n\t\t});\n\t}\n\n\t/** The cookies this browser would send to `url`, as a header value. */\n\tcookieHeader(url: string | URL): Promise<string> {\n\t\treturn this.jar.getCookieString(String(url));\n\t}\n\n\t/**\n\t * Make this browser the global `fetch`, for code that uses the global one —\n\t * an app's module-level clients. Returns what puts the previous one back.\n\t */\n\tinstall(): () => void {\n\t\tconst previous = globalThis.fetch;\n\t\tglobalThis.fetch = this.fetch;\n\t\treturn () => {\n\t\t\tglobalThis.fetch = previous;\n\t\t};\n\t}\n\n\t/** Read the body once, so a redirect that keeps the method can send it again. */\n\tprivate async start(\n\t\trequest: Request,\n\t\tredirect: RequestInit['redirect'],\n\t): Promise<Response> {\n\t\tconst body =\n\t\t\trequest.method === 'GET' || request.method === 'HEAD'\n\t\t\t\t? undefined\n\t\t\t\t: await request.arrayBuffer();\n\t\tconst headers = new Headers(request.headers);\n\t\tif (!headers.has('x-forwarded-for')) {\n\t\t\theaders.set('x-forwarded-for', this.address);\n\t\t}\n\t\tif (this.origin && !headers.has('origin')) {\n\t\t\theaders.set('origin', this.origin);\n\t\t}\n\t\treturn this.request(\n\t\t\t{ url: request.url, method: request.method, headers, body },\n\t\t\tredirect,\n\t\t);\n\t}\n\n\tprivate async request(\n\t\trequest: Hop,\n\t\tredirect: RequestInit['redirect'],\n\t\thops = 0,\n\t): Promise<Response> {\n\t\tconst headers = new Headers(request.headers);\n\t\tconst cookie = await this.jar.getCookieString(request.url);\n\t\tif (cookie) {\n\t\t\tconst existing = headers.get('cookie');\n\t\t\theaders.set('cookie', existing ? `${existing}; ${cookie}` : cookie);\n\t\t}\n\n\t\tconst response = await this.send(request.url, {\n\t\t\tmethod: request.method,\n\t\t\theaders,\n\t\t\tbody: request.body,\n\t\t\tredirect: 'manual',\n\t\t});\n\n\t\tfor (const set of response.headers.getSetCookie()) {\n\t\t\t// A cookie a browser would refuse — the wrong domain, Secure over\n\t\t\t// plain HTTP — is dropped silently, as a browser drops it.\n\t\t\tawait this.jar.setCookie(set, request.url, { ignoreError: true });\n\t\t}\n\n\t\tconst location = response.headers.get('location');\n\t\tif (\n\t\t\tredirect === 'manual' ||\n\t\t\t!location ||\n\t\t\tresponse.status < 300 ||\n\t\t\tresponse.status >= 400\n\t\t) {\n\t\t\treturn response;\n\t\t}\n\n\t\tif (hops >= MAX_REDIRECTS) {\n\t\t\tthrow new TooManyRedirects(request.url, MAX_REDIRECTS);\n\t\t}\n\n\t\t// 303, and 301/302 after a POST, continue as a GET without a body — what\n\t\t// every browser does, whatever the spec once said about 302.\n\t\tconst keepsMethod =\n\t\t\tresponse.status === 307 ||\n\t\t\tresponse.status === 308 ||\n\t\t\trequest.method === 'GET' ||\n\t\t\trequest.method === 'HEAD';\n\n\t\tconst url = new URL(location, request.url).toString();\n\t\tconst next: Hop = keepsMethod\n\t\t\t? { ...request, url }\n\t\t\t: { url, method: 'GET', headers: withoutBody(request.headers) };\n\n\t\treturn this.request(next, redirect, hops + 1);\n\t}\n}\n\n/** One request in a redirect chain, with its body already read. */\ninterface Hop {\n\turl: string;\n\tmethod: string;\n\theaders: Headers;\n\tbody?: ArrayBuffer;\n}\n\n/** Headers for a request that no longer carries the body they described. */\nfunction withoutBody(headers: Headers): Headers {\n\tconst next = new Headers(headers);\n\tnext.delete('content-type');\n\tnext.delete('content-length');\n\treturn next;\n}\n\n/** A redirect chain longer than any browser follows. */\nexport class TooManyRedirects extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly limit: number,\n\t) {\n\t\tsuper(\n\t\t\t`${url} redirected more than ${limit} times. A browser gives up here ` +\n\t\t\t\t`too — look for a redirect loop.`,\n\t\t);\n\t\tthis.name = 'TooManyRedirects';\n\t}\n}\n\n/** One DNS label, as a tenant's slug is. */\nconst SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/** `browser.on(slug)` in an app with no site on every subdomain. */\nexport class NoWildcardSite extends Error {\n\tconstructor(readonly slug: string) {\n\t\tsuper(\n\t\t\t`browser.on('${slug}') puts a tenant's slug into the app's site on ` +\n\t\t\t\t`every subdomain, and this browser knows of none. Declare a ` +\n\t\t\t\t`StaticSite with subdomain: '*', or pass its address as \\`site\\`.`,\n\t\t);\n\t\tthis.name = 'NoWildcardSite';\n\t}\n}\n\n/** `browser.on(slug)` with something no host can start with. */\nexport class NotATenantSlug extends Error {\n\tconstructor(readonly slug: string) {\n\t\tsuper(\n\t\t\t`'${slug}' is not a tenant's slug: one DNS label of lowercase ` +\n\t\t\t\t`letters, digits and inner hyphens, such as 'acme'.`,\n\t\t);\n\t\tthis.name = 'NotATenantSlug';\n\t}\n}\n\n/**\n * An address from 10.0.0.0/8, which nothing routes to. Random rather than\n * counted: test files run in separate workers that share no counter.\n */\nfunction privateAddress(): string {\n\tconst n = randomInt(1, 2 ** 24 - 1);\n\treturn `10.${(n >> 16) & 255}.${(n >> 8) & 255}.${n & 255}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,gBAAgB;AAkCtB,IAAa,UAAb,MAAqB;;CAEpB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