clivly 0.24.0-next.0 → 0.24.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 (54) hide show
  1. package/README.md +26 -14
  2. package/app-id-5cB6yioz.mjs +53 -0
  3. package/app-id-DcQ4u1c8.cjs +70 -0
  4. package/drizzle.cjs +120 -13
  5. package/drizzle.d.cts +7 -1
  6. package/drizzle.d.mts +7 -1
  7. package/drizzle.mjs +126 -19
  8. package/from-sql-BD7gR4bC.mjs +282 -0
  9. package/from-sql-CFgXkCe2.cjs +347 -0
  10. package/{index-CZkp8TV4.d.cts → from-sql-CpGP7K3J.d.mts} +8 -46
  11. package/{index-Cnrz4ywf.d.mts → from-sql-S8dSvU-e.d.cts} +8 -46
  12. package/index-BoemTWH4.d.mts +134 -0
  13. package/index-CIupXz_w.d.cts +134 -0
  14. package/index.cjs +246 -76
  15. package/index.d.cts +11 -2
  16. package/index.d.mts +11 -2
  17. package/index.mjs +245 -75
  18. package/introspector-5w2x89RD.mjs +55 -0
  19. package/introspector-DT_Ma59k.cjs +60 -0
  20. package/kysely.cjs +56 -0
  21. package/kysely.d.cts +45 -0
  22. package/kysely.d.mts +45 -0
  23. package/kysely.mjs +54 -0
  24. package/{namespace-probe--GvxJ06J.d.mts → namespace-probe-CUR2zG2l.d.mts} +33 -3
  25. package/package.json +15 -1
  26. package/projection-guard-C70l5U24.cjs +170 -0
  27. package/projection-guard-DOt_nbGn.mjs +147 -0
  28. package/sdk.cjs +1 -1
  29. package/sdk.d.cts +1 -1
  30. package/sdk.d.mts +1 -1
  31. package/sdk.mjs +1 -1
  32. package/sql.cjs +14 -7
  33. package/sql.d.cts +3 -2
  34. package/sql.d.mts +3 -2
  35. package/sql.mjs +6 -3
  36. package/{src-X0-yIA3O.cjs → src-CZIdwwI2.cjs} +162 -59
  37. package/{src-Dq2nY1Sj.mjs → src-tFhC1Ru2.mjs} +141 -38
  38. package/supabase-contact-3ke1KKUs.mjs +595 -0
  39. package/supabase-contact-BXQ0nnLq.cjs +624 -0
  40. package/supabase.cjs +30 -120
  41. package/supabase.d.cts +2 -1
  42. package/supabase.d.mts +2 -1
  43. package/supabase.mjs +27 -117
  44. package/{projection-guard-D8VUhCz7.cjs → sync-CdA9dgZz.cjs} +165 -154
  45. package/{projection-guard-7AMY0aCk.mjs → sync-Q0O-2kFI.mjs} +136 -143
  46. package/{types-UR-tT4c1.d.cts → types-CzL7lUH9.d.cts} +33 -3
  47. package/vite.d.cts +1 -1
  48. package/vite.d.mts +1 -1
  49. package/discover-BZIPXl23.cjs +0 -200
  50. package/discover-CFIi43Qn.mjs +0 -195
  51. package/drizzle-meta-BPnRLpsB.cjs +0 -8
  52. package/drizzle-meta-D00lFvAk.mjs +0 -3
  53. package/introspector-BwYgHGcS.cjs +0 -363
  54. package/introspector-Bz52xOUr.mjs +0 -334
@@ -1,7 +1,7 @@
1
1
  import { _ as validateProjection, s as customObjectDeclarations, w as primaryKeyColumns } from "./entity-config-CI5CGfaN.mjs";
2
2
  import { t as entitiesToMappings } from "./mappings-config-Opw7ZM6Y.mjs";
3
- import { c as parseWireCursors, d as toWireCursor, f as customPushSource, h as resolveEntitySource, i as projectionExposureErrors, l as sourceTimeFields, m as pushSourceOf, o as fullSyncSource, p as expectedSourceKey, r as exposableColumns, s as nextCursor, t as ProjectionRefusedError, u as syncSource } from "./projection-guard-7AMY0aCk.mjs";
4
- import { t as DRIZZLE_META } from "./drizzle-meta-D00lFvAk.mjs";
3
+ import { a as isExactCursorTime, c as sourceTimeFields, d as customPushSource, f as expectedSourceKey, h as DRIZZLE_META, i as fullSyncSource, l as syncSource, m as resolveEntitySource, p as pushSourceOf, r as advanceCursor, s as parseWireCursors, u as toWireCursor } from "./sync-Q0O-2kFI.mjs";
4
+ import { i as projectionExposureErrors, r as exposableColumns, t as ProjectionRefusedError } from "./projection-guard-DOt_nbGn.mjs";
5
5
  import { i as projectionSchema } from "./projection-CzBI2NL8.mjs";
6
6
  // ../sdk/src/deployment-identity.ts
7
7
  const MAX_DEPLOYMENT_ID_LENGTH = 128;
@@ -372,7 +372,7 @@ function mappingReadinessCheck(requested, result) {
372
372
  return {
373
373
  name: CHECK_NAME,
374
374
  ok: false,
375
- detail: `No active mapping receives ${names}, so rows pushed for ${unmapped.length === 1 ? "it" : "them"} are dropped. Map them in Integrations → Mapping in Clivly, then sync again.`
375
+ detail: `No active mapping receives ${names}, so rows pushed for ${unmapped.length === 1 ? "it" : "them"} are dropped. Map them in Clivly dashboard → Connections → What syncs, then sync again.`
376
376
  };
377
377
  }
378
378
  // ../sdk/src/doctor.ts
@@ -399,6 +399,11 @@ const TEMPORAL_CURSOR_TYPES = [
399
399
  function cursorMonotonicityCheck(source) {
400
400
  const meta = source[DRIZZLE_META];
401
401
  if (!meta?.columnsMeta) return null;
402
+ if (source.mode === "full") return {
403
+ name: `Cursor tracks updates (${source.entity})`,
404
+ ok: true,
405
+ detail: `"${source.entity}" is read as a full snapshot by ${meta.idField} — edits re-sync on every full read.`
406
+ };
402
407
  const type = (meta.kind === "sql" ? meta.columnsMeta.find((c) => c.name === meta.cursorField) : meta.columnsMeta[meta.columnKeys.indexOf(meta.cursorField)])?.type?.toLowerCase();
403
408
  if (!type) return null;
404
409
  const temporal = TEMPORAL_CURSOR_TYPES.some((t) => type.startsWith(t));
@@ -1050,7 +1055,7 @@ function describeSilentPush(target, body) {
1050
1055
  const { received, upserted, archived } = body;
1051
1056
  if (!(isCount(received) && isCount(upserted) && isCount(archived))) return null;
1052
1057
  if (received === 0 || upserted > 0 || archived > 0) return null;
1053
- return `Clivly sync: pushed ${received} row(s) for ${objectType ? `"${source}" → "${objectType}"` : `"${source}"`} and none were stored — no active mapping in this workspace targets it, so the rows were dropped. Map it in Integrations → Mapping, then sync again.`;
1058
+ return `Clivly sync: pushed ${received} row(s) for ${objectType ? `"${source}" → "${objectType}"` : `"${source}"`} and none were stored — no active mapping in this workspace targets it, so the rows were dropped. Map it in Clivly dashboard → Connections → What syncs, then sync again.`;
1054
1059
  }
1055
1060
  // ../sdk/src/remote-projections.ts
1056
1061
  const SYNC_CUSTOM_PATH$1 = "/clivly/sdk/sync/custom";
@@ -1140,6 +1145,23 @@ function resolveOne(entry, schema, introspector, exposure) {
1140
1145
  const PROJECTIONS_PATH = "/clivly/sdk/projections";
1141
1146
  const PROJECTIONS_REPORT_PATH = "/clivly/sdk/projections/report";
1142
1147
  const MAX_REASON = 2e3;
1148
+ /** SQLSTATE class 42: syntax error or access rule violation (a bad column, table or permission). */
1149
+ const SQL_SHAPE_SQLSTATE = /^42[0-9A-Z]{3}$/;
1150
+ /**
1151
+ * What an execution failure tells Clivly. The report leaves the host, so only
1152
+ * text that helps the workspace author fix the projection travels: the SDK's
1153
+ * own refusals and Postgres SQL-shape errors (SQLSTATE class 42, "column does
1154
+ * not exist"). Anything else — a connection (class 08) or login (class 28)
1155
+ * failure, a DNS error — can name the database host or user, so it becomes a
1156
+ * fixed code and the full error is logged here, on the host.
1157
+ */
1158
+ function executionFailureReason(entity, error) {
1159
+ const code = error?.code;
1160
+ const sqlShape = typeof code === "string" && SQL_SHAPE_SQLSTATE.test(code);
1161
+ if (error instanceof Error && (error instanceof ProjectionRefusedError || sqlShape)) return `the projection failed to execute: ${error.message}`;
1162
+ console.error(`Clivly: remote projection "${entity}" failed to execute; Clivly was told only projection_execution_failed.`, error);
1163
+ return "the projection failed to execute (projection_execution_failed). The full error is in the app's own log.";
1164
+ }
1143
1165
  /**
1144
1166
  * Merge what resolution decided with what the push actually did.
1145
1167
  *
@@ -1261,11 +1283,10 @@ async function pushRemoteProjections(args) {
1261
1283
  try {
1262
1284
  all = await fetchAllPages(source, pageSize);
1263
1285
  } catch (error) {
1264
- const message = error instanceof Error ? error.message : String(error);
1265
1286
  pushed.set(source.entity, {
1266
1287
  count: 0,
1267
1288
  ok: false,
1268
- reason: `the projection failed to execute: ${message}`.slice(0, MAX_REASON)
1289
+ reason: executionFailureReason(source.entity, error).slice(0, MAX_REASON)
1269
1290
  });
1270
1291
  continue;
1271
1292
  }
@@ -1317,7 +1338,6 @@ function selfCheck(input) {
1317
1338
  */
1318
1339
  /** Most IDs one page may return; matches the server's cap. */
1319
1340
  const IDS_PAGE_MAX = 5e3;
1320
- const DEFAULT_ID_FIELD = "id";
1321
1341
  const SOURCE_KEY = "id";
1322
1342
  /** The configured source whose cursor entity is `entity`. */
1323
1343
  function findSourceByEntity(config, entity) {
@@ -1343,8 +1363,65 @@ function readLimit(value) {
1343
1363
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? Math.min(value, IDS_PAGE_MAX) : IDS_PAGE_MAX;
1344
1364
  }
1345
1365
  /**
1346
- * One page of a source's IDs, in the same order a delta pull reads it, and
1347
- * where the next page starts (null on the last page).
1366
+ * The `time` an id-ordered listing puts on its `next` position. Not a time on
1367
+ * purpose: Clivly echoes `next` back unread, and an SDK that predates id
1368
+ * ordering drops a position it cannot parse and starts over, which only
1369
+ * repeats IDs. A cursor-ordered position read here starts over too, so a
1370
+ * deploy part-way through a listing can never skip an ID.
1371
+ */
1372
+ const ID_ORDER_POSITION = "id-order";
1373
+ function idsOf(rows) {
1374
+ const ids = [];
1375
+ for (const row of rows) {
1376
+ const id = row[SOURCE_KEY];
1377
+ if (id !== null && id !== void 0 && id !== "") ids.push(String(id));
1378
+ }
1379
+ return ids;
1380
+ }
1381
+ /** Where an id-ordered listing resumes: the last id of an `ID_ORDER_POSITION`. */
1382
+ function idOrderAfter(after) {
1383
+ if (after === null || typeof after !== "object") return null;
1384
+ const { id, time } = after;
1385
+ return time === "id-order" && typeof id === "string" ? id : null;
1386
+ }
1387
+ /**
1388
+ * A page in id order alone. The change cursor can move backwards (deleting a
1389
+ * profile lowers the Supabase join's `greatest`), and a row that jumps behind
1390
+ * a cursor-ordered listing is left out of it and archived. An id never moves.
1391
+ */
1392
+ async function idOrderPage(fetchIdPage, after, limit) {
1393
+ const rows = await fetchIdPage({
1394
+ afterId: idOrderAfter(after),
1395
+ limit
1396
+ });
1397
+ const ids = idsOf(rows);
1398
+ const last = ids.at(-1);
1399
+ return {
1400
+ ids,
1401
+ next: rows.length < limit || last === void 0 ? null : {
1402
+ id: last,
1403
+ time: ID_ORDER_POSITION
1404
+ }
1405
+ };
1406
+ }
1407
+ /** A page in the order a delta pull reads, for a source with no id listing. */
1408
+ async function cursorOrderPage(source, after, limit) {
1409
+ const since = parseWireCursors({ after })?.after ?? null;
1410
+ const rows = await source.fetchPage({
1411
+ since,
1412
+ limit
1413
+ });
1414
+ const cursor = advanceCursor(source, rows, since);
1415
+ const stalled = cursor !== null && since !== null && cursor.time.getTime() === since.time.getTime() && cursor.id === since.id;
1416
+ return {
1417
+ ids: idsOf(rows),
1418
+ next: rows.length < limit || cursor === null || stalled ? null : toWireCursor(cursor)
1419
+ };
1420
+ }
1421
+ /**
1422
+ * One page of a source's IDs and where the next page starts (null on the
1423
+ * last page): in id order when the source can list that way
1424
+ * (`fetchIdPage`), else in the order a delta pull reads it.
1348
1425
  */
1349
1426
  async function listSourceIds(config, request) {
1350
1427
  if (typeof request.entity !== "string") return {
@@ -1364,19 +1441,7 @@ async function listSourceIds(config, request) {
1364
1441
  };
1365
1442
  const { source } = found;
1366
1443
  const limit = readLimit(request.limit);
1367
- const after = parseWireCursors({ after: request.after })?.after ?? null;
1368
- const rows = await source.fetchPage({
1369
- since: after,
1370
- limit
1371
- });
1372
- const ids = [];
1373
- for (const row of rows) {
1374
- const id = row[SOURCE_KEY];
1375
- if (id !== null && id !== void 0 && id !== "") ids.push(String(id));
1376
- }
1377
- const cursor = nextCursor(rows, source.cursorField, source.idField ?? DEFAULT_ID_FIELD, after);
1378
- const stalled = cursor !== null && after !== null && cursor.time.getTime() === after.time.getTime() && cursor.id === after.id;
1379
- const next = rows.length < limit || cursor === null || stalled ? null : toWireCursor(cursor);
1444
+ const { ids, next } = source.fetchIdPage ? await idOrderPage(source.fetchIdPage.bind(source), request.after ?? null, limit) : await cursorOrderPage(source, request.after ?? null, limit);
1380
1445
  return {
1381
1446
  status: 200,
1382
1447
  body: {
@@ -1390,6 +1455,36 @@ async function listSourceIds(config, request) {
1390
1455
  }
1391
1456
  };
1392
1457
  }
1458
+ // ../sdk/src/tick-failure.ts
1459
+ /**
1460
+ * An error whose message the SDK composed from its own words and Clivly's own
1461
+ * responses (a refused push, an unknown sample entity), so it is safe to send
1462
+ * back to Clivly as is.
1463
+ */
1464
+ var ReportableSyncError = class extends Error {
1465
+ code;
1466
+ constructor(message, code) {
1467
+ super(message);
1468
+ this.name = new.target.name;
1469
+ this.code = code;
1470
+ }
1471
+ };
1472
+ const SYNC_FAILED_MESSAGE = "The sync failed inside the app (sync_failed). The full error is in the app's own log.";
1473
+ /**
1474
+ * The code and text to send Clivly for a failed sync. An error the SDK did not
1475
+ * write is logged here, in full, with `log` (console.error by default).
1476
+ */
1477
+ function describeTickFailure(error, log = console.error) {
1478
+ if (error instanceof ReportableSyncError) return {
1479
+ code: error.code,
1480
+ message: error.message
1481
+ };
1482
+ log("Clivly sync failed. Clivly was told only `sync_failed`; the full error:", error);
1483
+ return {
1484
+ code: "sync_failed",
1485
+ message: SYNC_FAILED_MESSAGE
1486
+ };
1487
+ }
1393
1488
  // ../sdk/src/trigger-method.ts
1394
1489
  /** Host-side override, mirroring `CLIVLY_INSTANT_PUSH_DISABLED`. */
1395
1490
  const REQUIRE_POST_ENV_VAR = "CLIVLY_TRIGGER_REQUIRE_POST";
@@ -1633,7 +1728,12 @@ function kvCursorStore(kv, options) {
1633
1728
  const parsed = JSON.parse(raw);
1634
1729
  if (typeof parsed.id !== "string" || typeof parsed.time !== "string") return null;
1635
1730
  const time = new Date(parsed.time);
1636
- return Number.isNaN(time.getTime()) ? null : {
1731
+ if (Number.isNaN(time.getTime())) return null;
1732
+ return isExactCursorTime(parsed.time) ? {
1733
+ id: parsed.id,
1734
+ time,
1735
+ exact: parsed.time
1736
+ } : {
1637
1737
  id: parsed.id,
1638
1738
  time
1639
1739
  };
@@ -1642,10 +1742,7 @@ function kvCursorStore(kv, options) {
1642
1742
  }
1643
1743
  },
1644
1744
  set: async (entity, cursor) => {
1645
- await kv.put(keyFor(entity), cursor === null ? "" : JSON.stringify({
1646
- id: cursor.id,
1647
- time: cursor.time.toISOString()
1648
- }));
1745
+ await kv.put(keyFor(entity), cursor === null ? "" : JSON.stringify(toWireCursor(cursor)));
1649
1746
  }
1650
1747
  };
1651
1748
  }
@@ -1693,11 +1790,10 @@ function trustedCursors(auth, payload) {
1693
1790
  * configuration mismatch the caller can fix — surfacing it as "your app
1694
1791
  * crashed" sends a developer hunting through their own sync handler instead.
1695
1792
  */
1696
- var TriggerRequestError = class extends Error {
1793
+ var TriggerRequestError = class extends ReportableSyncError {
1697
1794
  status;
1698
- constructor(status, message) {
1699
- super(message);
1700
- this.name = new.target.name;
1795
+ constructor(status, message, code) {
1796
+ super(message, code);
1701
1797
  this.status = status;
1702
1798
  }
1703
1799
  };
@@ -1851,7 +1947,7 @@ async function handlePreviewRequest(config, preview) {
1851
1947
  idField,
1852
1948
  ...Object.values(preview.fieldMap),
1853
1949
  ...filterColumns
1854
- ], config.exposure);
1950
+ ], config.exposure, source[DRIZZLE_META]?.derivedColumns);
1855
1951
  const rows = (await source.fetchPage({
1856
1952
  since: null,
1857
1953
  limit: PREVIEW_LIMIT
@@ -1872,7 +1968,11 @@ async function handleProjectionPreviewRequest(config, request) {
1872
1968
  reasons: refused
1873
1969
  }, FORBIDDEN_STATUS);
1874
1970
  try {
1875
- const rows = await run.call(config.introspector, parsed.data, { limit: request.limit });
1971
+ const basePkColumn = resolveLocalBasePk(parsed.data, buildSchema(config));
1972
+ const rows = await run.call(config.introspector, parsed.data, {
1973
+ limit: request.limit,
1974
+ ...basePkColumn ? { basePkColumn } : {}
1975
+ });
1876
1976
  return jsonResponse({
1877
1977
  rows,
1878
1978
  sampledCount: rows.length
@@ -1983,7 +2083,7 @@ function createClivlySDK(config) {
1983
2083
  };
1984
2084
  const pushFailureError = (message) => {
1985
2085
  const status = lastPushFailure?.status ?? null;
1986
- return status !== null && status >= CLIENT_ERROR_FLOOR && status < RETRYABLE_STATUS_FLOOR ? new TriggerRequestError(status, message) : new Error(message);
2086
+ return status !== null && status >= CLIENT_ERROR_FLOOR && status < RETRYABLE_STATUS_FLOOR ? new TriggerRequestError(status, message, "push_failed") : new ReportableSyncError(message, "push_failed");
1987
2087
  };
1988
2088
  const syncOne = async (source, path, mode, objectType, runId, batchSizeOverride, maxRowsOverride, persistCursor = true, clivlyCursors) => {
1989
2089
  const effectiveMode = source.mode === "full" && maxRowsOverride === void 0 ? "full" : mode;
@@ -2007,7 +2107,8 @@ function createClivlySDK(config) {
2007
2107
  maxRows: maxRowsOverride,
2008
2108
  reportCursor: persistCursor
2009
2109
  });
2010
- if (persistCursor) await cursorStore.set(source.entity, result.cursor);
2110
+ const keepsCursor = effectiveMode === "full" && !result.ok;
2111
+ if (persistCursor && !keepsCursor) await cursorStore.set(source.entity, result.cursor);
2011
2112
  return result.ok;
2012
2113
  };
2013
2114
  const syncCustomSources = async (customSources, mode, runId, clivlyCursors) => {
@@ -2084,7 +2185,7 @@ function createClivlySDK(config) {
2084
2185
  };
2085
2186
  const runSampleSync = async (entityKey, runId) => {
2086
2187
  const resolved = resolveSampleSource(config, entityKey);
2087
- if (!resolved) throw new TriggerRequestError(400, `Clivly sync: no source is configured for entity "${entityKey}". The dashboard maps this table, but clivly.config declares no matching entity — add it to \`entities\`, or remove the mapping in Integrations → Mapping.`);
2188
+ if (!resolved) throw new TriggerRequestError(400, `Clivly sync: no source is configured for entity "${entityKey}". The dashboard maps this table, but clivly.config declares no matching entity — add it to \`entities\`, or remove the mapping in Clivly dashboard → Connections → What syncs.`, "unknown_entity");
2088
2189
  lastPushFailure = null;
2089
2190
  if (!await syncOne(resolved.source, resolved.path, "delta", resolved.objectType, runId, SAMPLE_BATCH_SIZE, SAMPLE_BATCH_SIZE, false)) throw pushFailureError(describePushFailure([resolved.source.entity]));
2090
2191
  };
@@ -2556,10 +2657,12 @@ function createClivlySDK(config) {
2556
2657
  durationMs: Date.now() - startedAt
2557
2658
  }, 200);
2558
2659
  } catch (error) {
2660
+ const failure = describeTickFailure(error);
2559
2661
  return jsonResponse({
2560
2662
  ok: false,
2561
2663
  runId,
2562
- error: error instanceof Error ? error.message : String(error)
2664
+ code: failure.code,
2665
+ error: failure.message
2563
2666
  }, triggerErrorStatus(error));
2564
2667
  }
2565
2668
  };
@@ -2610,7 +2713,7 @@ function createClivlySDK(config) {
2610
2713
  } catch (error) {
2611
2714
  return {
2612
2715
  ok: false,
2613
- error: error instanceof Error ? error.message : String(error)
2716
+ error: describeTickFailure(error).message
2614
2717
  };
2615
2718
  }
2616
2719
  },