@tailor-platform/sdk 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,88 @@
1
+ import { PGliteClient } from "../pglite-kysely.mjs";
2
+ //#region src/vitest/mocks/tailordb-pglite.d.ts
3
+ /** A query executed through the PGlite-backed TailorDB client. */
4
+ interface ExecutedPGliteQuery {
5
+ /** Namespace of the `getDB` call that issued the query. */
6
+ namespace: string;
7
+ /** SQL text with positional (`$1`, `$2`, ...) placeholders. */
8
+ query: string;
9
+ /** Parameter values bound to the placeholders. */
10
+ params: unknown[];
11
+ }
12
+ /** Options for {@link mockTailordbWithPGlite}. */
13
+ interface MockTailordbPGliteOptions {
14
+ /**
15
+ * PGlite instance per `getDB` namespace. A `getDB` call for a namespace
16
+ * missing here throws instead of falling back to another instance. Pass the
17
+ * same instance under several namespaces to share one database between them.
18
+ */
19
+ namespaces: Record<string, PGliteClient>;
20
+ }
21
+ interface CreatedClient {
22
+ namespace: string;
23
+ ended: boolean;
24
+ }
25
+ /**
26
+ * Acquire a disposable mock that backs the generated `getDB(namespace)` with
27
+ * PGlite, so resolver/executor/workflow code runs unchanged and its queries
28
+ * execute as real SQL on an in-memory Postgres. Restored on dispose; the
29
+ * PGlite instances are borrowed, never closed — close them yourself (e.g. in
30
+ * `afterAll`).
31
+ *
32
+ * Create the tables a test needs up front with `CREATE TABLE` statements
33
+ * matching the generated Kysely types. PGlite runs full PostgreSQL while
34
+ * TailorDB supports a subset of it, so a statement passing here can still be
35
+ * rejected by the platform.
36
+ *
37
+ * Transactions on a shared instance are serialized: while one is open,
38
+ * queries from other `getDB` instances on the same PGlite instance wait for
39
+ * it to finish. Do not run such tests with `test.concurrent`, and do not
40
+ * query the same instance through a second `getDB` from inside a transaction
41
+ * — that waits on itself.
42
+ * @param options - PGlite instance registration per namespace
43
+ * @returns Disposable TailorDB mock control object
44
+ * @example
45
+ * ```typescript
46
+ * import { PGlite } from "@electric-sql/pglite";
47
+ * import { mockTailordbWithPGlite } from "@tailor-platform/sdk/vitest";
48
+ * import { getDB } from "../generated/tailordb";
49
+ *
50
+ * const pglite = new PGlite();
51
+ * afterAll(() => pglite.close());
52
+ *
53
+ * test("real SQL", async () => {
54
+ * using _db = mockTailordbWithPGlite({ namespaces: { tailordb: pglite } });
55
+ * await pglite.query(`CREATE TABLE "User" ("id" uuid PRIMARY KEY, "name" text NOT NULL)`);
56
+ * await getDB("tailordb").insertInto("User").values({ id: crypto.randomUUID(), name: "a" }).execute();
57
+ * });
58
+ * ```
59
+ */
60
+ declare function mockTailordbWithPGlite(options: MockTailordbPGliteOptions): {
61
+ /** The mock `tailordb.Client` constructor (`vi.fn`). */
62
+ Client: import("vitest").Mock<(this: any, config?: {
63
+ namespace?: string;
64
+ }) => void>;
65
+ /**
66
+ * All queries executed on the PGlite instances, in order, with the
67
+ * namespace that issued each.
68
+ * @returns Executed queries array
69
+ */
70
+ readonly executedQueries: ExecutedPGliteQuery[];
71
+ /**
72
+ * All TailorDB clients created, with their namespace and end state.
73
+ * @returns Created clients array
74
+ */
75
+ readonly createdClients: CreatedClient[];
76
+ /**
77
+ * Clear recorded queries and clients while keeping the mock installed.
78
+ * Throws if a transaction is open.
79
+ */
80
+ clear(): void;
81
+ /**
82
+ * Reset recorded state and restore the default client behavior.
83
+ * Throws if a transaction is open.
84
+ */
85
+ reset(): void;
86
+ } & Disposable;
87
+ //#endregion
88
+ export { ExecutedPGliteQuery, MockTailordbPGliteOptions, mockTailordbWithPGlite };
@@ -1,5 +1,16 @@
1
1
  import { ColumnType, Kysely } from "kysely";
2
2
  //#region src/vitest/pglite-kysely.d.ts
3
+ /** Result of a {@link PGliteClient.query} call. */
4
+ interface PGliteQueryResult {
5
+ /** Rows returned by the statement. */
6
+ rows: unknown[];
7
+ /** Number of rows an INSERT/UPDATE/DELETE touched. */
8
+ affectedRows?: number;
9
+ /** Postgres command tag of the statement (`"SELECT"`, `"INSERT"`, ...). */
10
+ command?: string;
11
+ /** Row count reported alongside the command tag. */
12
+ rowCount?: number;
13
+ }
3
14
  /**
4
15
  * The subset of a `@electric-sql/pglite` `PGlite` instance used by
5
16
  * {@link createKyselyPGlite}. Any client with a compatible `query`/`close`
@@ -7,10 +18,7 @@ import { ColumnType, Kysely } from "kysely";
7
18
  */
8
19
  interface PGliteClient {
9
20
  /** Run a single SQL statement with positional (`$1`, `$2`, ...) parameters. */
10
- query(query: string, params?: unknown[]): Promise<{
11
- rows: unknown[];
12
- affectedRows?: number;
13
- }>;
21
+ query(query: string, params?: unknown[]): Promise<PGliteQueryResult>;
14
22
  /** Release the underlying database. Called by `db.destroy()`. */
15
23
  close(): Promise<void>;
16
24
  }
@@ -62,4 +70,4 @@ type Unmigrated<DB> = { [T in keyof DB]: { [C in keyof DB[T]]: UnmigratedColumn<
62
70
  */
63
71
  declare function createKyselyPGlite<DB = Record<string, never>>(client: PGliteClient): Kysely<DB>;
64
72
  //#endregion
65
- export { PGliteClient, Unmigrated, createKyselyPGlite };
73
+ export { PGliteClient, PGliteQueryResult, Unmigrated, createKyselyPGlite };
@@ -83,6 +83,13 @@ interface Plugin<TableConfig = unknown, PluginConfig = unknown> {
83
83
  | `executors` | `PluginGeneratedExecutor[]` | Additional executors to generate |
84
84
  | `extends` | `{ fields?: Record<string, TailorAnyDBField> }` | Fields to add to the source table |
85
85
 
86
+ Tables in `tables` are validated as complete TailorDB table definitions before registration.
87
+ Fields in `extends.fields` are validated as part of the resulting source table. You can return a
88
+ table builder directly or a structural copy such as `{ ...db.table(...) }`; a copy is accepted as
89
+ long as it retains valid table schema properties. Malformed output stops the build with an error
90
+ that identifies the plugin and relevant table output, without partially registering tables from
91
+ that source table's plugin processing.
92
+
86
93
  **Use cases**:
87
94
 
88
95
  - Generate derived tables (e.g., archive tables, history tables) from user-defined tables
@@ -115,6 +122,10 @@ onTableLoaded(context) {
115
122
 
116
123
  Same as `TablePluginOutput` but without `extends` (namespace plugins cannot extend a source table).
117
124
 
125
+ Tables in `tables` undergo the same validation and support structural copies. If any returned
126
+ table is malformed, the build stops before namespace-generated tables are registered and the
127
+ error identifies the plugin and relevant table output.
128
+
118
129
  **Use cases**:
119
130
 
120
131
  - Generate tables that don't derive from a specific user table (e.g., audit log, settings table)
@@ -102,6 +102,11 @@ Plugins can generate:
102
102
  - **Field Extensions**: Additional fields added to the source table
103
103
  - **Output Files**: TypeScript code and other files via generation-time hooks
104
104
 
105
+ Tables produced by definition-time hooks are validated before registration. This includes
106
+ generated tables and source tables after field extensions are applied. Malformed output stops
107
+ the build with an error that identifies the plugin and relevant table output, without partially
108
+ registering tables from that processing step.
109
+
105
110
  Generated files are placed under `.tailor/<plugin-id>/` (the plugin ID is sanitized,
106
111
  e.g. `@example/soft-delete` → `example-soft-delete`), such as:
107
112
 
package/docs/testing.md CHANGED
@@ -24,6 +24,7 @@ For anonymous direct calls:
24
24
  Platform API mocks under `@tailor-platform/sdk/vitest` (for use with the [`tailor-runtime` Vitest environment](#runtime-environment-emulation-beta) below):
25
25
 
26
26
  - `mockTailordb` — TailorDB query stubs and call recording
27
+ - `mockTailordbWithPGlite` — TailorDB backed by a real in-memory Postgres (PGlite)
27
28
  - `mockWorkflow` — `tailor.workflow` job / wait / resolve mocks
28
29
  - `runWorkflowLocally` — local full-chain workflow runner
29
30
  - `mockSecretmanager`, `mockAuthconnection`, `mockIdp`, `mockFile`, `mockIconv`, `mockAigateway`, `mockLogger` — corresponding platform API mocks
@@ -63,7 +64,7 @@ export default defineConfig({
63
64
 
64
65
  ### Acquiring mocks with `using`
65
66
 
66
- Each mock controller (`mockTailordb`, `mockWorkflow`, `mockSecretmanager`, `mockAuthconnection`, `mockIdp`, `mockFile`, `mockIconv`, `mockAigateway`, `mockLogger`) is a **factory function**. Acquire it inside a test with a [`using` declaration](https://github.com/tc39/proposal-explicit-resource-management) — its state is reset automatically when the test scope exits, so you no longer need `beforeEach(() => mock.reset())`:
67
+ Each mock controller (`mockTailordb`, `mockTailordbWithPGlite`, `mockWorkflow`, `mockSecretmanager`, `mockAuthconnection`, `mockIdp`, `mockFile`, `mockIconv`, `mockAigateway`, `mockLogger`) is a **factory function**. Acquire it inside a test with a [`using` declaration](https://github.com/tc39/proposal-explicit-resource-management) — its state is reset automatically when the test scope exits, so you no longer need `beforeEach(() => mock.reset())`:
67
68
 
68
69
  ```typescript
69
70
  import { mockTailordb } from "@tailor-platform/sdk/vitest";
@@ -144,6 +145,81 @@ Within one `mockTailordb()` instance, use either `onQuery()` matchers or a direc
144
145
 
145
146
  Pass `{ onUnhandled: "error" }` to make an unmatched query fail instead of returning an empty result.
146
147
 
148
+ #### Real SQL execution with PGlite (`mockTailordbWithPGlite`)
149
+
150
+ Instead of staging responses, back TailorDB with [`@electric-sql/pglite`](https://pglite.dev/) — an in-memory PostgreSQL (install it as a devDependency) — so the queries a resolver, executor, or workflow job issues through `getDB()` execute against real data. `getDB(namespace)` needs no test-side swap: acquire the mock, and each namespace you list resolves to its PGlite instance.
151
+
152
+ Create the tables the test touches with `CREATE TABLE` statements matching the generated Kysely types — `text` for string and enum fields, `timestamptz` for date/datetime, `jsonb` for nested objects. The schema only has to match what your code reads and writes, not TailorDB's storage; relations are not enforced.
153
+
154
+ ```typescript
155
+ import { PGlite } from "@electric-sql/pglite";
156
+ import { mockTailordbWithPGlite } from "@tailor-platform/sdk/vitest";
157
+ import { afterAll, beforeAll, expect, test } from "vitest";
158
+ import { getDB } from "../generated/db";
159
+ import resolver from "./upsertUsers";
160
+
161
+ const pglite = new PGlite();
162
+
163
+ beforeAll(async () => {
164
+ await pglite.exec(`
165
+ CREATE TABLE "User" (
166
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
167
+ "name" text NOT NULL,
168
+ "email" text NOT NULL,
169
+ "age" integer NOT NULL
170
+ );
171
+ `);
172
+ });
173
+
174
+ afterAll(async () => {
175
+ await pglite.close();
176
+ });
177
+
178
+ test("upserts against real rows", async () => {
179
+ using _db = mockTailordbWithPGlite({ namespaces: { "main-db": pglite } });
180
+ const db = getDB("main-db");
181
+ await db
182
+ .insertInto("User")
183
+ .values({ name: "Existing", email: "exists@example.com", age: 40 })
184
+ .execute();
185
+
186
+ const result = await resolver.body({
187
+ input: {
188
+ users: [
189
+ { name: "Newcomer", email: "new@example.com", age: 22 },
190
+ { name: "Existing", email: "exists@example.com", age: 41 },
191
+ ],
192
+ },
193
+ caller: null,
194
+ invoker: null,
195
+ env: { appName: "Resolver Template", version: 1 },
196
+ });
197
+
198
+ expect(result).toEqual({ created: 1, updated: 1 });
199
+ const rows = await db.selectFrom("User").selectAll().orderBy("email", "asc").execute();
200
+ expect(rows.map((row) => row.age)).toEqual([41, 22]);
201
+ });
202
+ ```
203
+
204
+ A `.serial()` field is omitted from generated `getDB()` inserts, so its PGlite column must generate a value. Use an identity for an integer serial. For a formatted string serial, create a sequence and reproduce the format in its `DEFAULT` expression:
205
+
206
+ ```sql
207
+ CREATE SEQUENCE "invoiceNumberSequence" START WITH 1000;
208
+ CREATE TABLE "Invoice" (
209
+ "sequentialId" integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1),
210
+ "invoiceNumber" text NOT NULL
211
+ DEFAULT ('INV-' || lpad(nextval('"invoiceNumberSequence"')::text, 5, '0'))
212
+ );
213
+ ```
214
+
215
+ PGlite does not apply the TailorDB `.serial()` configuration itself. Match the `start`, `format`, and any limit that the behavior under test relies on.
216
+
217
+ - The PGlite instance is yours: the mock never closes it, so close it in `afterAll`. Reuse one instance across a suite — creating one per test is slow.
218
+ - Pass the same instance under several namespaces to drive them against one shared database.
219
+ - Seed through `getDB` itself. When a column type rejects a value that only the test must stage, use `createKyselyPGlite<Unmigrated<...>>(pglite)` instead — see [Testing Migrations Locally](./services/tailordb-migration.md#testing-migrations-locally). This only affects test setup; it cannot supply a `.serial()` value for an insert issued by the code under test.
220
+ - Transactions on a shared instance are serialized: while one is open, queries from other `getDB` instances wait. Do not use `test.concurrent` with a shared instance, and do not query the same instance through a second `getDB` from inside a transaction — that waits on itself.
221
+ - PGlite runs full PostgreSQL while TailorDB supports a subset of it, and TailorDB hooks, validations, and permissions do not run here — a test passing on PGlite can still behave differently on the platform. Keep [`mockTailordb`](#tailordb-mock) or [`createKyselyMock`](#kysely-layer-mock-createkyselymock) tests for query shape and error paths, and E2E tests for platform behavior.
222
+
147
223
  ### Workflow Mock
148
224
 
149
225
  Workflow job `.start()` calls use the platform workflow runtime. Acquire `mockWorkflow()` when you want to provide start responses with `setJobHandler` / `enqueueResult` or assert on `startedJobs`. If no response is configured, the mock throws so missing job mocks fail loudly. Use `job(definition)` or `workflow(definition)` to get a stable, fully typed Vitest mock for one definition:
@@ -592,7 +668,7 @@ describe("upsertUsers resolver", () => {
592
668
  });
593
669
  ```
594
670
 
595
- Reach for [`mockTailordb`](#mocking-the-tailordb-client) instead when you want to drive the raw query sequence at the `tailordb.Client` level rather than at the Kysely layer.
671
+ Reach for [`mockTailordb`](#mocking-the-tailordb-client) instead when you want to drive the raw query sequence at the `tailordb.Client` level rather than at the Kysely layer, or [`mockTailordbWithPGlite`](#real-sql-execution-with-pglite-mocktailordbwithpglite) to execute the queries against a real in-memory Postgres.
596
672
 
597
673
  TailorDB migration scripts (`migrate.ts`) are unit-tested the same way: the generated `db.ts` exports the `Database` interface to type the mock, and `tailor tailordb migration script <N> --with-test` scaffolds a ready-to-fill test. To execute a migration script against real rows in an in-memory Postgres, use `createKyselyPGlite` with `@electric-sql/pglite`. See [Testing Migrations Locally](./services/tailordb-migration.md#testing-migrations-locally).
598
674
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tailor-platform/sdk",
3
- "version": "2.10.0",
3
+ "version": "2.11.0",
4
4
  "description": "Tailor Platform SDK - The SDK to work with Tailor Platform",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -169,13 +169,13 @@
169
169
  "@secretlint/secretlint-rule-preset-recommend": "13.0.5",
170
170
  "@standard-schema/spec": "1.1.0",
171
171
  "@tailor-platform/function-kysely-tailordb": "0.1.3",
172
- "@toiroakr/lines-db": "0.12.2",
172
+ "@toiroakr/lines-db": "0.12.5",
173
173
  "@toiroakr/read-multiline": "0.4.1",
174
174
  "@urql/core": "6.0.3",
175
175
  "amaro": "1.1.11",
176
176
  "confbox": "0.2.4",
177
177
  "date-fns": "4.4.0",
178
- "es-toolkit": "1.51.0",
178
+ "es-toolkit": "1.52.0",
179
179
  "find-up-simple": "1.0.1",
180
180
  "get-east-asian-width": "1.6.0",
181
181
  "get-tsconfig": "4.14.3",
@@ -191,7 +191,7 @@
191
191
  "pgsql-ast-parser": "12.0.2",
192
192
  "pkg-types": "2.3.1",
193
193
  "politty": "0.11.9",
194
- "rolldown": "1.2.5",
194
+ "rolldown": "1.2.6",
195
195
  "semver": "7.8.5",
196
196
  "sql-highlight": "6.1.0",
197
197
  "std-env": "4.2.0",
@@ -242,7 +242,7 @@
242
242
  "scripts": {
243
243
  "test": "vitest",
244
244
  "test:unit": "vitest --project=unit*",
245
- "test:e2e": "vitest --project=e2e",
245
+ "test:e2e": "vitest --project=e2e*",
246
246
  "test:coverage": "vitest --coverage",
247
247
  "docs:check": "vitest run --project=unit* src/cli/docs.test.ts",
248
248
  "docs:update": "POLITTY_DOCS_UPDATE=true vitest run --project=unit* src/cli/docs.test.ts",