clivly 0.24.0-next.1 → 0.25.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.
Files changed (72) hide show
  1. package/README.md +34 -7
  2. package/{app-id-DcQ4u1c8.cjs → app-id-C2F25WhK.cjs} +1 -1
  3. package/{app-id-5cB6yioz.mjs → app-id-CMMadyIC.mjs} +1 -1
  4. package/auth-better-auth.cjs +51 -0
  5. package/auth-better-auth.d.cts +51 -1
  6. package/auth-better-auth.d.mts +51 -1
  7. package/auth-better-auth.mjs +51 -1
  8. package/auth-clerk.cjs +53 -0
  9. package/auth-clerk.d.cts +12 -1
  10. package/auth-clerk.d.mts +12 -1
  11. package/auth-clerk.mjs +53 -1
  12. package/auth-supabase.cjs +10 -0
  13. package/auth-supabase.d.cts +17 -1
  14. package/auth-supabase.d.mts +17 -1
  15. package/auth-supabase.mjs +10 -1
  16. package/auth-webhook-3if7gY6b.mjs +162 -0
  17. package/auth-webhook-BihEUc9C.cjs +197 -0
  18. package/auth-webhook-DKdaCZrW.d.cts +30 -0
  19. package/auth-webhook-DKdaCZrW.d.mts +30 -0
  20. package/auth-workos.cjs +43 -0
  21. package/auth-workos.d.cts +12 -1
  22. package/auth-workos.d.mts +12 -1
  23. package/auth-workos.mjs +43 -1
  24. package/drizzle.cjs +264 -17
  25. package/drizzle.d.cts +23 -3
  26. package/drizzle.d.mts +23 -3
  27. package/drizzle.mjs +265 -19
  28. package/{from-sql-CFgXkCe2.cjs → from-sql-Dw2ipynp.cjs} +7 -1
  29. package/{from-sql-S8dSvU-e.d.cts → from-sql-MyPE5elx.d.cts} +1 -1
  30. package/{from-sql-CpGP7K3J.d.mts → from-sql-YW6LfdVK.d.mts} +1 -1
  31. package/{from-sql-BD7gR4bC.mjs → from-sql-kqs9CbQ-.mjs} +7 -1
  32. package/{index-CIupXz_w.d.cts → index-B4kWWHYm.d.cts} +2 -2
  33. package/{index-BoemTWH4.d.mts → index-CKElWhvq.d.mts} +2 -2
  34. package/index.cjs +3354 -2829
  35. package/index.d.cts +3 -3
  36. package/index.d.mts +3 -3
  37. package/index.mjs +3354 -2829
  38. package/{introspector-5w2x89RD.mjs → introspector-B1S7qmvy.mjs} +4 -4
  39. package/{introspector-DT_Ma59k.cjs → introspector-DRmEXDai.cjs} +4 -4
  40. package/kysely.cjs +163 -2
  41. package/kysely.d.cts +16 -3
  42. package/kysely.d.mts +16 -3
  43. package/kysely.mjs +163 -3
  44. package/{namespace-probe-CUR2zG2l.d.mts → namespace-probe-LKC4OU5X.d.mts} +54 -19
  45. package/package.json +1 -1
  46. package/{projection-guard-DOt_nbGn.mjs → projection-guard-CADdAdzg.mjs} +1 -1
  47. package/{projection-guard-C70l5U24.cjs → projection-guard-yhVTvx37.cjs} +1 -1
  48. package/sdk.cjs +1 -1
  49. package/sdk.d.cts +1 -1
  50. package/sdk.d.mts +1 -1
  51. package/sdk.mjs +1 -1
  52. package/sql.cjs +5 -5
  53. package/sql.d.cts +2 -2
  54. package/sql.d.mts +2 -2
  55. package/sql.mjs +5 -5
  56. package/{src-CZIdwwI2.cjs → src-BQasv4EL.cjs} +368 -38
  57. package/{src-tFhC1Ru2.mjs → src-CAn-zrEl.mjs} +368 -38
  58. package/{supabase-contact-BXQ0nnLq.cjs → supabase-contact-0GmBVpiQ.cjs} +24 -15
  59. package/{supabase-contact-3ke1KKUs.mjs → supabase-contact-D-oDC4Qk.mjs} +24 -15
  60. package/supabase.cjs +39 -9
  61. package/supabase.d.cts +3 -2
  62. package/supabase.d.mts +3 -2
  63. package/supabase.mjs +39 -9
  64. package/{sync-Q0O-2kFI.mjs → sync-CnWT5juF.mjs} +65 -5
  65. package/{sync-CdA9dgZz.cjs → sync-R0iVlooB.cjs} +94 -4
  66. package/track-writes-4yyZbTZX.d.cts +17 -0
  67. package/track-writes-BJSWg8wg.d.mts +17 -0
  68. package/track-writes-BnZAig2Y.mjs +77 -0
  69. package/track-writes-C22_e_W-.cjs +112 -0
  70. package/{types-CzL7lUH9.d.cts → types-BPG4l-oM.d.cts} +53 -18
  71. package/vite.d.cts +1 -1
  72. package/vite.d.mts +1 -1
package/drizzle.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  import { n as buildUniqueConstraints, r as discoverFromDrizzle, t as buildColumnsMeta } from "./drizzle-CZuOzIu4.mjs";
2
- import { S as isAnonymousFilter, b as authTableKind, g as AUTH_USERS_COLUMNS, h as DRIZZLE_META, v as AUTH_USERS_TABLE } from "./sync-Q0O-2kFI.mjs";
2
+ import { C as AUTH_USERS_TABLE, D as isAnonymousFilter, T as authTableKind, b as DRIZZLE_META, g as assertNoStrayIdColumn, x as AUTH_USERS_COLUMNS, y as withFetchByIds } from "./sync-CnWT5juF.mjs";
3
3
  import { t as BASE_REF } from "./projection-CzBI2NL8.mjs";
4
4
  import { a as compileProjectionPreview, i as compileProjectionJoins, n as compileProjectionFrom, r as compileProjectionIdentity, s as quoteIdent$1 } from "./projection-sql-2joBkLz2.mjs";
5
- import { a as CURSOR_ALIAS, c as hideCursorAlias, d as postgresDialect, l as keysetPage, o as EXACT_FORMAT, r as narrowedMetaValue, s as exactCursorRead } from "./from-sql-BD7gR4bC.mjs";
6
- import { n as appIdLockdownSql, t as APP_ID_TABLE$1 } from "./app-id-5cB6yioz.mjs";
7
- import { and, getTableColumns, getTableName, sql } from "drizzle-orm";
5
+ import { a as CURSOR_ALIAS, c as hideCursorAlias, d as postgresDialect, l as keysetPage, o as EXACT_FORMAT, r as narrowedMetaValue, s as exactCursorRead } from "./from-sql-kqs9CbQ-.mjs";
6
+ import { a as trackedId, n as isTracked, o as untracked, r as markTracked, t as createReporter } from "./track-writes-BnZAig2Y.mjs";
7
+ import { n as appIdLockdownSql, t as APP_ID_TABLE$1 } from "./app-id-CMMadyIC.mjs";
8
+ import { Param, SQL, StringChunk, and, getTableColumns, getTableName, is, sql } from "drizzle-orm";
8
9
  import { getTableConfig } from "drizzle-orm/pg-core";
9
10
  // ../sdk/src/drizzle-keyset.ts
10
11
  /**
@@ -67,7 +68,7 @@ function normalizeRows(result) {
67
68
  throw new Error("fromDrizzleProjection: db.execute() returned neither an array of rows nor { rows }.");
68
69
  }
69
70
  function fromDrizzleProjection(db, projection, opts) {
70
- const client = db;
71
+ const client = untracked(db);
71
72
  const known = /* @__PURE__ */ new Set([BASE_REF, ...projection.joins.map((j) => j.key)]);
72
73
  if (projection.identity.kind === "base_pk" && projection.identity.column === void 0 && opts.basePkColumn === void 0) throw new Error(`fromDrizzleProjection: projection "${projection.entityKey}" has a base_pk identity with no column — pass { basePkColumn }.`);
73
74
  for (const [field, binding] of Object.entries(projection.fieldBindings)) assertKnownRef(binding.from, known, `field "${field}"`);
@@ -91,7 +92,7 @@ function fromDrizzleProjection(db, projection, opts) {
91
92
  const head = [`select ${selectItems.join(", ")}`, fromClause].join(" ");
92
93
  const idSql = sql.raw(identityExpr);
93
94
  const page = async (where, order, limit) => normalizeRows(await client.execute(sql`${sql.raw(head)} where ${where} order by ${order} limit ${limit}`));
94
- return {
95
+ return withFetchByIds({
95
96
  entity: opts.entity,
96
97
  pushSource: projection.baseTable,
97
98
  cursorField: cursorToken,
@@ -104,7 +105,7 @@ function fromDrizzleProjection(db, projection, opts) {
104
105
  }, page));
105
106
  return hideCursorAlias(rows);
106
107
  }
107
- };
108
+ }, async (ids) => hideCursorAlias(await page(sql`${idSql} in (${sql.join(ids.map((id) => sql`${id}`), sql`, `)})`, sql`${idSql}`, ids.length)));
108
109
  }
109
110
  /**
110
111
  * The identity-only paging path `fromDrizzleProjection` takes when
@@ -123,7 +124,7 @@ function fromDrizzleProjectionByIdentity(client, projection, identityExpr, fromC
123
124
  selectItems.push(`${refSql(binding.from)} AS ${quoteIdent$1(token)}`);
124
125
  }
125
126
  const head = [`select ${selectItems.join(", ")}`, fromClause].join(" ");
126
- return {
127
+ return withFetchByIds({
127
128
  entity: opts.entity,
128
129
  pushSource: projection.baseTable,
129
130
  cursorField: "id",
@@ -135,7 +136,7 @@ function fromDrizzleProjectionByIdentity(client, projection, identityExpr, fromC
135
136
  const query = sql`${sql.raw(head)}${where} order by ${sql.raw(identityExpr)} asc limit ${limit}`;
136
137
  return normalizeRows(await client.execute(query));
137
138
  }
138
- };
139
+ }, async (ids) => normalizeRows(await client.execute(sql`${sql.raw(head)} where ${sql.raw(identityExpr)} in (${sql.join(ids.map((id) => sql`${id}`), sql`, `)}) limit ${ids.length}`)));
139
140
  }
140
141
  // ../sdk/src/projection-preview.ts
141
142
  /** `db.execute` returns either an array or `{ rows }`, depending on driver. */
@@ -146,10 +147,248 @@ function rowsOf(result) {
146
147
  throw new Error("previewProjection: db.execute() returned neither an array of rows nor { rows }.");
147
148
  }
148
149
  async function previewProjection(db, projection, opts) {
149
- const client = db;
150
+ const client = untracked(db);
150
151
  const { sql } = await import("drizzle-orm");
151
152
  return rowsOf(await client.execute(sql.raw(compileProjectionPreview(projection, opts.limit))));
152
153
  }
154
+ // ../sdk/src/track-drizzle.ts
155
+ const noop = () => void 0;
156
+ function safely(look) {
157
+ try {
158
+ return look();
159
+ } catch {
160
+ return null;
161
+ }
162
+ }
163
+ const WRITES = /* @__PURE__ */ new Set([
164
+ "insert",
165
+ "update",
166
+ "delete"
167
+ ]);
168
+ const USES_DATABASE = /* @__PURE__ */ new Set([
169
+ "select",
170
+ "selectDistinct",
171
+ "selectDistinctOn",
172
+ "query",
173
+ "execute",
174
+ "$count"
175
+ ]);
176
+ const PUBLIC_SCHEMA = "public";
177
+ function tableLabel(table) {
178
+ const name = getTableName(table);
179
+ try {
180
+ const { schema } = getTableConfig(table);
181
+ return schema && schema !== PUBLIC_SCHEMA ? `${schema}.${name}` : name;
182
+ } catch {
183
+ return name;
184
+ }
185
+ }
186
+ function keyOf(table) {
187
+ const keys = Object.entries(getTableColumns(table)).filter(([, column]) => column.primary);
188
+ const [only] = keys;
189
+ return only && keys.length === 1 ? {
190
+ property: only[0],
191
+ column: only[1]
192
+ } : null;
193
+ }
194
+ const chunkText = (chunk) => is(chunk, StringChunk) ? [chunk.value].flat().join("") : "";
195
+ function idsOfParams(params) {
196
+ const ids = [];
197
+ for (const param of params) {
198
+ const id = trackedId(is(param, Param) ? param.value : param);
199
+ if (id === null) return null;
200
+ ids.push(id);
201
+ }
202
+ return ids;
203
+ }
204
+ /** The ids of exactly `key = x` or `key in (x, y)`; null for anything else. */
205
+ function idsOfWhere(where, key) {
206
+ if (!is(where, SQL)) return null;
207
+ const chunks = where.queryChunks.filter((chunk) => !(is(chunk, StringChunk) && chunkText(chunk) === ""));
208
+ const [left, operator, right] = chunks;
209
+ if (chunks.length !== 3 || left !== key.column) return null;
210
+ const op = chunkText(operator).trim();
211
+ if (op === "=") return idsOfParams([right]);
212
+ return op === "in" && Array.isArray(right) ? idsOfParams(right) : null;
213
+ }
214
+ const sqlText = (part) => is(part, SQL) ? part.queryChunks.map(sqlText).join("") : chunkText(part);
215
+ /** Whether a conflict can only touch the row being inserted. */
216
+ function conflictKeepsId(onConflict, key) {
217
+ if (onConflict === void 0) return true;
218
+ const text = sqlText(onConflict);
219
+ return text.startsWith(`("${key.column.name}")`) || text.includes("do nothing");
220
+ }
221
+ function idsOfValues(values, key) {
222
+ return Array.isArray(values) ? idsOfParams(values.map((row) => row[key.property])) : null;
223
+ }
224
+ /** The ids the statement returned, under whatever name the host asked for. */
225
+ function idsOfResult(builder, result, key) {
226
+ const path = builder.config?.returning?.find(({ field }) => field === key.column)?.path;
227
+ if (!(path && Array.isArray(result))) return null;
228
+ const ids = [];
229
+ for (const row of result) {
230
+ let value = row;
231
+ for (const step of path) value = value?.[step];
232
+ const id = trackedId(value);
233
+ if (id === null) return null;
234
+ ids.push(id);
235
+ }
236
+ return ids;
237
+ }
238
+ function idsOfStatement(kind, { config }, key) {
239
+ if (kind === "insert") return conflictKeepsId(config?.onConflict, key) ? idsOfValues(config?.values, key) : null;
240
+ return kind === "update" && config?.set?.[key.property] !== void 0 ? null : idsOfWhere(config?.where, key);
241
+ }
242
+ const watched = /* @__PURE__ */ new WeakMap();
243
+ function fixGeneratedIds(builder, key) {
244
+ const { config } = builder;
245
+ const { defaultFn } = key?.column ?? {};
246
+ const values = config?.values;
247
+ if (!(config && key && defaultFn && Array.isArray(values))) return () => void 0;
248
+ config.values = values.map((row) => {
249
+ const given = row[key.property];
250
+ if (!(given === void 0 || is(given, Param) && given.value === void 0)) return row;
251
+ const id = defaultFn();
252
+ return {
253
+ ...row,
254
+ [key.property]: is(id, SQL) ? id : new Param(id, key.column)
255
+ };
256
+ });
257
+ return () => {
258
+ config.values = values;
259
+ };
260
+ }
261
+ function watchBuilder(builder, kind, table, sink) {
262
+ const key = safely(() => keyOf(table));
263
+ let ids = null;
264
+ const prepare = builder._prepare;
265
+ if (typeof prepare !== "function") return;
266
+ builder._prepare = (...args) => {
267
+ const undo = safely(() => fixGeneratedIds(builder, key)) ?? noop;
268
+ ids = key ? safely(() => idsOfStatement(kind, builder, key)) : null;
269
+ try {
270
+ return prepare.apply(builder, args);
271
+ } finally {
272
+ safely(undo);
273
+ }
274
+ };
275
+ const entry = { done(result) {
276
+ const known = (key && safely(() => idsOfResult(builder, result, key))) ?? ids;
277
+ return {
278
+ table: tableLabel(table),
279
+ key: key?.column.name ?? "",
280
+ deleted: kind === "delete",
281
+ ids: known ?? [],
282
+ complete: known !== null
283
+ };
284
+ } };
285
+ watched.set(builder, entry);
286
+ const { execute } = builder;
287
+ builder.execute = async (...args) => {
288
+ const result = await execute.apply(builder, args);
289
+ try {
290
+ sink(entry.done(result));
291
+ } catch {}
292
+ return result;
293
+ };
294
+ }
295
+ const isBuilder = (value) => typeof value?.execute === "function";
296
+ /** `db.insert` / `update` / `delete`, watching the builder each produces. */
297
+ function trackWriteMethod(kind, make, sink) {
298
+ return (...args) => {
299
+ const started = make(...args);
300
+ const table = args[0];
301
+ if (isBuilder(started)) {
302
+ safely(() => watchBuilder(started, kind, table, sink));
303
+ return started;
304
+ }
305
+ for (const step of [
306
+ "values",
307
+ "select",
308
+ "set"
309
+ ]) {
310
+ const original = started?.[step];
311
+ if (typeof original === "function") started[step] = (...stepArgs) => {
312
+ const next = original.apply(started, stepArgs);
313
+ if (isBuilder(next)) safely(() => watchBuilder(next, kind, table, sink));
314
+ return next;
315
+ };
316
+ }
317
+ return started;
318
+ };
319
+ }
320
+ function trackedWith(parts, sink) {
321
+ const out = { ...parts };
322
+ for (const kind of [
323
+ "insert",
324
+ "update",
325
+ "delete"
326
+ ]) {
327
+ const make = out[kind];
328
+ if (typeof make === "function") out[kind] = trackWriteMethod(kind, make, sink);
329
+ }
330
+ return out;
331
+ }
332
+ function trackClient(db, reporter, emit) {
333
+ const sink = (write) => emit([write]);
334
+ const transaction = (original) => async (work, ...rest) => {
335
+ const held = [];
336
+ const result = await original((tx) => work(trackClient(tx, reporter, (writes) => held.push(...writes))), ...rest);
337
+ emit(held);
338
+ return result;
339
+ };
340
+ const batch = (original) => async (queries, ...rest) => {
341
+ const results = await original(queries, ...rest);
342
+ try {
343
+ emit(queries.flatMap((query, i) => {
344
+ const entry = watched.get(query);
345
+ return entry ? [entry.done(results[i])] : [];
346
+ }));
347
+ } catch {}
348
+ return results;
349
+ };
350
+ return new Proxy(db, { get(target, property) {
351
+ const value = Reflect.get(target, property, target);
352
+ if (USES_DATABASE.has(property) || WRITES.has(property)) reporter.noteActivity();
353
+ if (typeof value !== "function") return value;
354
+ const call = (...args) => value.apply(target, args);
355
+ if (WRITES.has(property)) return trackWriteMethod(property, call, sink);
356
+ switch (property) {
357
+ case "transaction": return transaction(call);
358
+ case "batch": return batch(call);
359
+ case "with": return (...args) => trackedWith(call(...args), sink);
360
+ case "constructor": return value;
361
+ default: return call;
362
+ }
363
+ } });
364
+ }
365
+ /**
366
+ * Wrap a Drizzle client once, and every committed insert, update and delete it
367
+ * makes to a mapped table reaches Clivly right away.
368
+ *
369
+ * ```ts
370
+ * export const db = trackDrizzle(drizzle(process.env.DATABASE_URL!));
371
+ * ```
372
+ *
373
+ * The SQL, the results and the errors are the host's own: nothing is added to
374
+ * a query, so a policy or grant that allows the write today still does. A
375
+ * transaction is reported after it commits; one that rolls back is not. Raw
376
+ * SQL (`db.execute`) and `.prepare()`d statements are not seen, and reach
377
+ * Clivly with the next catch-up or pull.
378
+ *
379
+ * It finds the SDK your app creates, so the database module need not import
380
+ * your Clivly config. Wrapping twice is harmless.
381
+ */
382
+ function trackDrizzle(db, options = {}) {
383
+ if (isTracked(db)) return db;
384
+ const reporter = createReporter(options);
385
+ const tracked = trackClient(db, reporter, (writes) => {
386
+ reporter.noteActivity();
387
+ reporter.report(writes);
388
+ });
389
+ markTracked(tracked, db);
390
+ return tracked;
391
+ }
153
392
  // ../sdk/src/drizzle.ts
154
393
  function inferIdField(table) {
155
394
  const columns = getTableColumns(table);
@@ -162,6 +401,10 @@ function inferIdField(table) {
162
401
  const kind = primaryKeys.length === 0 ? "no" : "a composite";
163
402
  throw new Error(`fromDrizzle: table "${getTableName(table)}" has ${kind} single-column primary key — pass { idField } explicitly.`);
164
403
  }
404
+ function singlePrimaryKeyOrId(table) {
405
+ const primaryKeys = Object.entries(getTableColumns(table)).filter(([, column]) => column.primary);
406
+ return primaryKeys.length === 1 ? primaryKeys[0]?.[0] ?? "id" : "id";
407
+ }
165
408
  const AUTH_USERS_ALLOWED = AUTH_USERS_COLUMNS;
166
409
  const META_COLUMN = "raw_user_meta_data";
167
410
  const { quoteIdent } = postgresDialect;
@@ -221,7 +464,7 @@ function exactRead(column) {
221
464
  return WITH_TIME_ZONE.test(type) ? sql`to_char(${column} at time zone 'UTC', ${format})` : sql`to_char(${column}, ${format})`;
222
465
  }
223
466
  function fromDrizzle(db, table, opts) {
224
- const drizzleDb = db;
467
+ const drizzleDb = untracked(db);
225
468
  const idField = opts.idField ?? inferIdField(table);
226
469
  const { columns, isAuthUsers } = readableColumns(table, {
227
470
  cursorField: opts.cursorField,
@@ -235,6 +478,7 @@ function fromDrizzle(db, table, opts) {
235
478
  for (const column of Object.values(columns)) projection[column.name] = isAuthUsers && column.name === META_COLUMN ? sql.raw(narrowedMetaValue(quoteIdent(META_COLUMN))).mapWith(column) : column;
236
479
  const cursorColumnName = cursorColumn.name;
237
480
  const idColumnName = idColumn.name;
481
+ assertNoStrayIdColumn("fromDrizzle", getTableName(table), Object.values(columns).map((column) => column.name), idColumnName);
238
482
  const selected = {
239
483
  ...projection,
240
484
  [CURSOR_ALIAS]: exactRead(cursorColumn)
@@ -252,6 +496,7 @@ function fromDrizzle(db, table, opts) {
252
496
  }, page))),
253
497
  ...opts.objectType === void 0 ? {} : { objectType: opts.objectType }
254
498
  };
499
+ withFetchByIds(source, async (ids) => hideCursorAlias(await page(sql`${idColumn} in (${sql.join(ids.map((id) => sql`${id}`), sql`, `)})`, sql`${idColumn}`, ids.length)));
255
500
  const uniqueConstraints = buildUniqueConstraints(table);
256
501
  const meta = {
257
502
  columnKeys: Object.keys(columns),
@@ -319,7 +564,7 @@ function toColumnKeyedRow(table, row) {
319
564
  return out;
320
565
  }
321
566
  function insertAndPush(clivly, db, table, opts) {
322
- const insertableDb = db;
567
+ const insertableDb = untracked(db);
323
568
  return async (values, waitUntil) => {
324
569
  const [created] = await insertableDb.insert(table).values(values).returning();
325
570
  if (!created) throw new Error(`insertAndPush: insert into "${getTableName(table)}" returned no row.`);
@@ -343,7 +588,7 @@ const APP_ID_TABLE = APP_ID_TABLE$1;
343
588
  * your drizzle config so push does not offer to drop the table.
344
589
  */
345
590
  function drizzleAppIdStore(db) {
346
- const client = db;
591
+ const client = untracked(db);
347
592
  const table = sql.identifier(APP_ID_TABLE);
348
593
  let ready = null;
349
594
  const ensureTable = () => {
@@ -371,7 +616,7 @@ function drizzleAppIdStore(db) {
371
616
  * (`current_schema()`), so it reports exactly the tables the app can reach.
372
617
  */
373
618
  function drizzleIntrospector(db) {
374
- const client = db;
619
+ const client = untracked(db);
375
620
  return {
376
621
  async listTables() {
377
622
  return (await client.execute(sql`
@@ -413,7 +658,7 @@ function settle(pushed, waitUntil) {
413
658
  * ```
414
659
  */
415
660
  function updateAndPush(clivly, db, table, opts) {
416
- const updatableDb = db;
661
+ const updatableDb = untracked(db);
417
662
  return async (where, values, waitUntil) => {
418
663
  const updated = await updatableDb.update(table).set(values).where(where).returning();
419
664
  await settle(Promise.all(updated.map((row) => clivly.pushOne(opts.entity, toColumnKeyedRow(table, row)))).then(() => void 0), waitUntil);
@@ -424,7 +669,8 @@ function updateAndPush(clivly, db, table, opts) {
424
669
  * Delete rows of a mapped Drizzle table and tell Clivly at once, so their CRM
425
670
  * records are archived (never deleted) within a second (continuous sync D9).
426
671
  * Without it, a deletion reaches Clivly at its daily delete check. `idField`
427
- * is the property holding the row id; it defaults to `id`.
672
+ * is the property holding the row id; it defaults to the table's
673
+ * single-column primary key, else `id`.
428
674
  *
429
675
  * ```ts
430
676
  * const deleteUser = deleteAndPush(clivly, db, schema.user, { entity: "user" });
@@ -432,8 +678,8 @@ function updateAndPush(clivly, db, table, opts) {
432
678
  * ```
433
679
  */
434
680
  function deleteAndPush(clivly, db, table, opts) {
435
- const deletableDb = db;
436
- const idField = opts.idField ?? "id";
681
+ const deletableDb = untracked(db);
682
+ const idField = opts.idField ?? singlePrimaryKeyOrId(table);
437
683
  return async (where, waitUntil) => {
438
684
  const deleted = await deletableDb.delete(table).where(where).returning();
439
685
  const ids = deleted.map((row) => row[idField]).filter((id) => id !== null && id !== void 0).map((id) => typeof id === "number" ? id : String(id));
@@ -441,4 +687,4 @@ function deleteAndPush(clivly, db, table, opts) {
441
687
  return deleted;
442
688
  };
443
689
  }
444
- export { APP_ID_TABLE, buildUniqueConstraints, deleteAndPush, discoverFromDrizzle, drizzleAppIdStore, drizzleIntrospector, fromDrizzle, fromDrizzleProjection, insertAndPush, toColumnKeyedRow, updateAndPush };
690
+ export { APP_ID_TABLE, buildUniqueConstraints, deleteAndPush, discoverFromDrizzle, drizzleAppIdStore, drizzleIntrospector, fromDrizzle, fromDrizzleProjection, insertAndPush, toColumnKeyedRow, trackDrizzle, updateAndPush };
@@ -1,4 +1,4 @@
1
- const require_sync = require("./sync-CdA9dgZz.cjs");
1
+ const require_sync = require("./sync-R0iVlooB.cjs");
2
2
  const require_projection_sql = require("./projection-sql-DS5sVTY-.cjs");
3
3
  // ../sdk/src/sql/dialect.ts
4
4
  const postgresDialect = {
@@ -222,6 +222,7 @@ function fromSql(executor, opts) {
222
222
  }
223
223
  const cursorNullable = cursorMeta?.nullable !== false;
224
224
  const columns = resolveColumns(opts, isAuthUsers, cursorField === void 0 ? [idField] : [cursorField, idField]);
225
+ require_sync.assertNoStrayIdColumn("fromSql", table, columns, idField);
225
226
  const items = columns.map((c) => selectItem(c, isAuthUsers));
226
227
  if (cursorField !== void 0) items.push(`${exactCursorRead(dialect.quoteIdent(cursorField))} as ${dialect.quoteIdent(CURSOR_ALIAS)}`);
227
228
  const head = `select ${items.join(", ")} from ${dialect.quoteTableRef(table)}`;
@@ -239,6 +240,10 @@ function fromSql(executor, opts) {
239
240
  });
240
241
  return hideCursorAlias(await keysetPage(since, limit, sqlKeysetReads(dialect.quoteIdent(cursorField), idSql, cursorNullable, page)));
241
242
  };
243
+ const fetchByIds = async (ids) => {
244
+ const list = ids.map((_, i) => dialect.param(i + 1)).join(", ");
245
+ return hideCursorAlias(await page(`${idSql} in (${list})`, idSql, [...ids], ids.length));
246
+ };
242
247
  const source = {
243
248
  entity: opts.entity,
244
249
  ...opts.pushSource === void 0 ? {} : { pushSource: opts.pushSource },
@@ -249,6 +254,7 @@ function fromSql(executor, opts) {
249
254
  fetchIdPage,
250
255
  ...opts.objectType === void 0 ? {} : { objectType: opts.objectType }
251
256
  };
257
+ require_sync.withFetchByIds(source, fetchByIds);
252
258
  const sourceMeta = {
253
259
  kind: "sql",
254
260
  columnKeys: columns,
@@ -1,5 +1,5 @@
1
1
  import { m as DiscoveredSchemaTable } from "./entity-config-CXpGowQa.cjs";
2
- import { b as SyncSource } from "./types-CzL7lUH9.cjs";
2
+ import { x as SyncSource } from "./types-BPG4l-oM.cjs";
3
3
  /** The one raw-SQL seam: every host driver is adapted to this. */
4
4
  interface SqlExecutor {
5
5
  query(text: string, params?: readonly unknown[]): Promise<Record<string, unknown>[]>;
@@ -1,5 +1,5 @@
1
1
  import { m as DiscoveredSchemaTable } from "./entity-config-CXpGowQa.mjs";
2
- import { x as SyncSource } from "./namespace-probe-CUR2zG2l.mjs";
2
+ import { S as SyncSource } from "./namespace-probe-LKC4OU5X.mjs";
3
3
  /** The one raw-SQL seam: every host driver is adapted to this. */
4
4
  interface SqlExecutor {
5
5
  query(text: string, params?: readonly unknown[]): Promise<Record<string, unknown>[]>;
@@ -1,4 +1,4 @@
1
- import { S as isAnonymousFilter, _ as AUTH_USERS_META_KEYS, a as isExactCursorTime, b as authTableKind, g as AUTH_USERS_COLUMNS, h as DRIZZLE_META, n as ROW_EXACT_CURSOR_KEY, o as isValidIsoTime, t as ROW_CURSOR_KEY, v as AUTH_USERS_TABLE, x as filtersAnonymous } from "./sync-Q0O-2kFI.mjs";
1
+ import { C as AUTH_USERS_TABLE, D as isAnonymousFilter, E as filtersAnonymous, S as AUTH_USERS_META_KEYS, T as authTableKind, a as isExactCursorTime, b as DRIZZLE_META, g as assertNoStrayIdColumn, n as ROW_EXACT_CURSOR_KEY, o as isValidIsoTime, t as ROW_CURSOR_KEY, x as AUTH_USERS_COLUMNS, y as withFetchByIds } from "./sync-CnWT5juF.mjs";
2
2
  import { c as quoteTableRef, s as quoteIdent } from "./projection-sql-2joBkLz2.mjs";
3
3
  // ../sdk/src/sql/dialect.ts
4
4
  const postgresDialect = {
@@ -222,6 +222,7 @@ function fromSql(executor, opts) {
222
222
  }
223
223
  const cursorNullable = cursorMeta?.nullable !== false;
224
224
  const columns = resolveColumns(opts, isAuthUsers, cursorField === void 0 ? [idField] : [cursorField, idField]);
225
+ assertNoStrayIdColumn("fromSql", table, columns, idField);
225
226
  const items = columns.map((c) => selectItem(c, isAuthUsers));
226
227
  if (cursorField !== void 0) items.push(`${exactCursorRead(dialect.quoteIdent(cursorField))} as ${dialect.quoteIdent(CURSOR_ALIAS)}`);
227
228
  const head = `select ${items.join(", ")} from ${dialect.quoteTableRef(table)}`;
@@ -239,6 +240,10 @@ function fromSql(executor, opts) {
239
240
  });
240
241
  return hideCursorAlias(await keysetPage(since, limit, sqlKeysetReads(dialect.quoteIdent(cursorField), idSql, cursorNullable, page)));
241
242
  };
243
+ const fetchByIds = async (ids) => {
244
+ const list = ids.map((_, i) => dialect.param(i + 1)).join(", ");
245
+ return hideCursorAlias(await page(`${idSql} in (${list})`, idSql, [...ids], ids.length));
246
+ };
242
247
  const source = {
243
248
  entity: opts.entity,
244
249
  ...opts.pushSource === void 0 ? {} : { pushSource: opts.pushSource },
@@ -249,6 +254,7 @@ function fromSql(executor, opts) {
249
254
  fetchIdPage,
250
255
  ...opts.objectType === void 0 ? {} : { objectType: opts.objectType }
251
256
  };
257
+ withFetchByIds(source, fetchByIds);
252
258
  const sourceMeta = {
253
259
  kind: "sql",
254
260
  columnKeys: columns,
@@ -1,5 +1,5 @@
1
- import { C as NamespaceIntrospector, b as SyncSource, t as AppIdStore } from "./types-CzL7lUH9.cjs";
2
- import { i as SqlExecutor } from "./from-sql-S8dSvU-e.cjs";
1
+ import { t as AppIdStore, w as NamespaceIntrospector, x as SyncSource } from "./types-BPG4l-oM.cjs";
2
+ import { i as SqlExecutor } from "./from-sql-MyPE5elx.cjs";
3
3
  import { R as ProjectionMapping, m as DiscoveredSchemaTable, z as ProjectionRef } from "./entity-config-CXpGowQa.cjs";
4
4
  import "./index-uFDiQEjj.cjs";
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { n as AppIdStore, t as NamespaceIntrospector, x as SyncSource } from "./namespace-probe-CUR2zG2l.mjs";
2
- import { i as SqlExecutor } from "./from-sql-CpGP7K3J.mjs";
1
+ import { S as SyncSource, n as AppIdStore, t as NamespaceIntrospector } from "./namespace-probe-LKC4OU5X.mjs";
2
+ import { i as SqlExecutor } from "./from-sql-YW6LfdVK.mjs";
3
3
  import { R as ProjectionMapping, m as DiscoveredSchemaTable, z as ProjectionRef } from "./entity-config-CXpGowQa.mjs";
4
4
  import "./index-DOoX2GgI.mjs";
5
5
  /**