@clivly/sdk 0.8.0 → 0.9.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.
package/dist/drizzle.cjs CHANGED
@@ -1,43 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_drizzle_meta = require("./drizzle-meta-CdCs30q3.cjs");
3
- let drizzle_orm = require("drizzle-orm");
4
- let drizzle_orm_pg_core = require("drizzle-orm/pg-core");
5
3
  let _clivly_core_drizzle = require("@clivly/core/drizzle");
4
+ let drizzle_orm = require("drizzle-orm");
6
5
  //#region src/drizzle.ts
7
- function buildColumnsMeta(table) {
8
- const columns = (0, drizzle_orm.getTableColumns)(table);
9
- const fkByColumn = /* @__PURE__ */ new Map();
10
- try {
11
- for (const fk of (0, drizzle_orm_pg_core.getTableConfig)(table).foreignKeys) {
12
- const ref = fk.reference();
13
- const foreignTable = (0, drizzle_orm.getTableName)(ref.foreignTable);
14
- ref.columns.forEach((col, i) => {
15
- const foreignCol = ref.foreignColumns[i];
16
- if (foreignCol) fkByColumn.set(col.name, {
17
- table: foreignTable,
18
- column: foreignCol.name
19
- });
20
- });
21
- }
22
- } catch {}
23
- return Object.values(columns).map((col) => {
24
- const references = fkByColumn.get(col.name);
25
- let type;
26
- try {
27
- type = col.getSQLType();
28
- } catch {
29
- type = void 0;
30
- }
31
- return {
32
- name: col.name,
33
- type,
34
- nullable: !col.notNull,
35
- isPrimaryKey: Boolean(col.primary),
36
- isForeignKey: references !== void 0,
37
- ...references ? { references } : {}
38
- };
39
- });
40
- }
41
6
  function inferIdField(table) {
42
7
  const columns = (0, drizzle_orm.getTableColumns)(table);
43
8
  const primaryKeys = Object.entries(columns).filter(([, column]) => column.primary);
@@ -65,18 +30,24 @@ function fromDrizzle(db, table, opts) {
65
30
  const idColumn = columns[idField];
66
31
  if (!cursorColumn) throw new Error(`fromDrizzle: cursorField "${opts.cursorField}" is not a column on "${(0, drizzle_orm.getTableName)(table)}".`);
67
32
  if (!idColumn) throw new Error(`fromDrizzle: idField "${idField}" is not a column on "${(0, drizzle_orm.getTableName)(table)}".`);
33
+ const projection = {};
34
+ for (const column of Object.values(columns)) projection[column.name] = column;
35
+ const cursorColumnName = cursorColumn.name;
36
+ const idColumnName = idColumn.name;
68
37
  const source = {
69
38
  entity: opts.entity,
70
- cursorField: opts.cursorField,
71
- idField,
72
- fetchPage: ({ since, limit }) => drizzleDb.select().from(table).where(since ? drizzle_orm.sql`(${cursorColumn}, ${idColumn}) > (${since.time}, ${since.id})` : void 0).orderBy((0, drizzle_orm.asc)(cursorColumn), (0, drizzle_orm.asc)(idColumn)).limit(limit)
39
+ cursorField: cursorColumnName,
40
+ idField: idColumnName,
41
+ fetchPage: ({ since, limit }) => drizzleDb.select(projection).from(table).where(since ? drizzle_orm.sql`(${cursorColumn}, ${idColumn}) > (${since.time}, ${since.id})` : void 0).orderBy((0, drizzle_orm.asc)(cursorColumn), (0, drizzle_orm.asc)(idColumn)).limit(limit)
73
42
  };
43
+ const uniqueConstraints = (0, _clivly_core_drizzle.buildUniqueConstraints)(table);
74
44
  const meta = {
75
45
  columnKeys: Object.keys(columns),
76
46
  cursorField: opts.cursorField,
77
47
  idField,
78
48
  tableName: (0, drizzle_orm.getTableName)(table),
79
- columnsMeta: buildColumnsMeta(table)
49
+ columnsMeta: (0, _clivly_core_drizzle.buildColumnsMeta)(table),
50
+ ...uniqueConstraints === void 0 ? {} : { uniqueConstraints }
80
51
  };
81
52
  Object.defineProperty(source, require_drizzle_meta.DRIZZLE_META, {
82
53
  value: meta,
@@ -104,6 +75,12 @@ function drizzleIntrospector(db) {
104
75
  };
105
76
  }
106
77
  //#endregion
78
+ Object.defineProperty(exports, "buildUniqueConstraints", {
79
+ enumerable: true,
80
+ get: function() {
81
+ return _clivly_core_drizzle.buildUniqueConstraints;
82
+ }
83
+ });
107
84
  Object.defineProperty(exports, "discoverFromDrizzle", {
108
85
  enumerable: true,
109
86
  get: function() {
@@ -1,6 +1,6 @@
1
- import { m as NamespaceIntrospector, p as SyncSource } from "./types-DTaz5mLi.cjs";
1
+ import { m as NamespaceIntrospector, p as SyncSource } from "./types-QPbki8ur.cjs";
2
2
  import { Table } from "drizzle-orm";
3
- import { discoverFromDrizzle } from "@clivly/core/drizzle";
3
+ import { buildUniqueConstraints, discoverFromDrizzle } from "@clivly/core/drizzle";
4
4
  //#region src/drizzle.d.ts
5
5
  interface DrizzleDb {
6
6
  select: (...args: any[]) => any;
@@ -25,4 +25,4 @@ declare function fromDrizzle(db: DrizzleDb, table: Table, opts: {
25
25
  */
26
26
  declare function drizzleIntrospector(db: unknown): NamespaceIntrospector;
27
27
  //#endregion
28
- export { discoverFromDrizzle, drizzleIntrospector, fromDrizzle };
28
+ export { buildUniqueConstraints, discoverFromDrizzle, drizzleIntrospector, fromDrizzle };
@@ -1,6 +1,6 @@
1
- import { m as NamespaceIntrospector, p as SyncSource } from "./types-DTaz5mLi.mjs";
1
+ import { m as NamespaceIntrospector, p as SyncSource } from "./types-QPbki8ur.mjs";
2
+ import { buildUniqueConstraints, discoverFromDrizzle } from "@clivly/core/drizzle";
2
3
  import { Table } from "drizzle-orm";
3
- import { discoverFromDrizzle } from "@clivly/core/drizzle";
4
4
  //#region src/drizzle.d.ts
5
5
  interface DrizzleDb {
6
6
  select: (...args: any[]) => any;
@@ -25,4 +25,4 @@ declare function fromDrizzle(db: DrizzleDb, table: Table, opts: {
25
25
  */
26
26
  declare function drizzleIntrospector(db: unknown): NamespaceIntrospector;
27
27
  //#endregion
28
- export { discoverFromDrizzle, drizzleIntrospector, fromDrizzle };
28
+ export { buildUniqueConstraints, discoverFromDrizzle, drizzleIntrospector, fromDrizzle };
package/dist/drizzle.mjs CHANGED
@@ -1,42 +1,7 @@
1
1
  import { t as DRIZZLE_META } from "./drizzle-meta-DNqzkREf.mjs";
2
+ import { buildColumnsMeta, buildUniqueConstraints, buildUniqueConstraints as buildUniqueConstraints$1, discoverFromDrizzle } from "@clivly/core/drizzle";
2
3
  import { asc, getTableColumns, getTableName, sql } from "drizzle-orm";
3
- import { getTableConfig } from "drizzle-orm/pg-core";
4
- import { discoverFromDrizzle } from "@clivly/core/drizzle";
5
4
  //#region src/drizzle.ts
6
- function buildColumnsMeta(table) {
7
- const columns = getTableColumns(table);
8
- const fkByColumn = /* @__PURE__ */ new Map();
9
- try {
10
- for (const fk of getTableConfig(table).foreignKeys) {
11
- const ref = fk.reference();
12
- const foreignTable = getTableName(ref.foreignTable);
13
- ref.columns.forEach((col, i) => {
14
- const foreignCol = ref.foreignColumns[i];
15
- if (foreignCol) fkByColumn.set(col.name, {
16
- table: foreignTable,
17
- column: foreignCol.name
18
- });
19
- });
20
- }
21
- } catch {}
22
- return Object.values(columns).map((col) => {
23
- const references = fkByColumn.get(col.name);
24
- let type;
25
- try {
26
- type = col.getSQLType();
27
- } catch {
28
- type = void 0;
29
- }
30
- return {
31
- name: col.name,
32
- type,
33
- nullable: !col.notNull,
34
- isPrimaryKey: Boolean(col.primary),
35
- isForeignKey: references !== void 0,
36
- ...references ? { references } : {}
37
- };
38
- });
39
- }
40
5
  function inferIdField(table) {
41
6
  const columns = getTableColumns(table);
42
7
  const primaryKeys = Object.entries(columns).filter(([, column]) => column.primary);
@@ -64,18 +29,24 @@ function fromDrizzle(db, table, opts) {
64
29
  const idColumn = columns[idField];
65
30
  if (!cursorColumn) throw new Error(`fromDrizzle: cursorField "${opts.cursorField}" is not a column on "${getTableName(table)}".`);
66
31
  if (!idColumn) throw new Error(`fromDrizzle: idField "${idField}" is not a column on "${getTableName(table)}".`);
32
+ const projection = {};
33
+ for (const column of Object.values(columns)) projection[column.name] = column;
34
+ const cursorColumnName = cursorColumn.name;
35
+ const idColumnName = idColumn.name;
67
36
  const source = {
68
37
  entity: opts.entity,
69
- cursorField: opts.cursorField,
70
- idField,
71
- fetchPage: ({ since, limit }) => drizzleDb.select().from(table).where(since ? sql`(${cursorColumn}, ${idColumn}) > (${since.time}, ${since.id})` : void 0).orderBy(asc(cursorColumn), asc(idColumn)).limit(limit)
38
+ cursorField: cursorColumnName,
39
+ idField: idColumnName,
40
+ fetchPage: ({ since, limit }) => drizzleDb.select(projection).from(table).where(since ? sql`(${cursorColumn}, ${idColumn}) > (${since.time}, ${since.id})` : void 0).orderBy(asc(cursorColumn), asc(idColumn)).limit(limit)
72
41
  };
42
+ const uniqueConstraints = buildUniqueConstraints$1(table);
73
43
  const meta = {
74
44
  columnKeys: Object.keys(columns),
75
45
  cursorField: opts.cursorField,
76
46
  idField,
77
47
  tableName: getTableName(table),
78
- columnsMeta: buildColumnsMeta(table)
48
+ columnsMeta: buildColumnsMeta(table),
49
+ ...uniqueConstraints === void 0 ? {} : { uniqueConstraints }
79
50
  };
80
51
  Object.defineProperty(source, DRIZZLE_META, {
81
52
  value: meta,
@@ -103,4 +74,4 @@ function drizzleIntrospector(db) {
103
74
  };
104
75
  }
105
76
  //#endregion
106
- export { discoverFromDrizzle, drizzleIntrospector, fromDrizzle };
77
+ export { buildUniqueConstraints, discoverFromDrizzle, drizzleIntrospector, fromDrizzle };
package/dist/index.cjs CHANGED
@@ -279,6 +279,46 @@ function errorMessage(error) {
279
279
  }
280
280
  //#endregion
281
281
  //#region src/doctor.ts
282
+ const TEMPORAL_CURSOR_TYPES = [
283
+ "timestamp",
284
+ "timestamptz",
285
+ "datetime",
286
+ "date",
287
+ "time"
288
+ ];
289
+ /**
290
+ * Warn when the sync cursor cannot observe an update.
291
+ *
292
+ * `clivly init` falls back to the primary key when a table has no
293
+ * `updated_at`-like column, and emits a TODO saying "confirm it is monotonic".
294
+ * A serial `id` *is* monotonic, so the note reads as satisfied — but monotonic
295
+ * is only half the requirement. An `id` never changes, so every insert mirrors
296
+ * and **no edit ever does**: a contact who changes their email keeps the old one
297
+ * in the CRM forever, with nothing anywhere reporting a problem.
298
+ *
299
+ * A code comment could not enforce this; a real integrator shipped exactly this
300
+ * configuration to production. This is the check that says so out loud.
301
+ */
302
+ function cursorMonotonicityCheck(source) {
303
+ const meta = source[require_drizzle_meta.DRIZZLE_META];
304
+ if (!meta?.columnsMeta) return null;
305
+ const index = meta.columnKeys.indexOf(meta.cursorField);
306
+ const type = meta.columnsMeta[index]?.type?.toLowerCase();
307
+ if (!type) return null;
308
+ const temporal = TEMPORAL_CURSOR_TYPES.some((t) => type.startsWith(t));
309
+ const name = `Cursor tracks updates (${source.entity})`;
310
+ if (temporal) return {
311
+ name,
312
+ ok: true,
313
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}) — edits re-sync.`
314
+ };
315
+ return {
316
+ name,
317
+ ok: true,
318
+ warn: true,
319
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}), which does not change when a row is edited — inserts will sync, edits will not. Add an updated_at column to "${meta.tableName ?? source.entity}" and set it as the cursor, or accept insert-only mirroring.`
320
+ };
321
+ }
282
322
  function configuredSources(config) {
283
323
  const sources = [];
284
324
  if (config.source?.contacts) sources.push(config.source.contacts);
@@ -307,32 +347,12 @@ async function mappingDryRunChecks(config) {
307
347
  return checks;
308
348
  }
309
349
  /**
310
- * Run the read-only setup checks and return a structured report. Every check
311
- * captures its own error into `detail` rather than throwing, so one failure never
312
- * hides the rest. `ok` is the AND of all non-skipped checks.
350
+ * Confirm each drizzle source actually has the cursor and id columns the sync
351
+ * pages on. Hand-written sources have no column metadata, so they are skipped
352
+ * rather than failed.
313
353
  */
314
- async function runDoctor(args) {
315
- const { config, connect } = args;
354
+ function cursorColumnChecks(sources) {
316
355
  const checks = [];
317
- const sources = configuredSources(config);
318
- const hasKey = Boolean(config.apiKey);
319
- checks.push({
320
- name: "API key present",
321
- ok: hasKey,
322
- detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
323
- });
324
- const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
325
- checks.push({
326
- name: "Entities configured",
327
- ok: entityCount > 0,
328
- detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
329
- });
330
- checks.push({
331
- name: "Sources configured",
332
- ok: sources.length > 0,
333
- detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
334
- });
335
- checks.push(checkConceptCoverage(config));
336
356
  for (const source of sources) {
337
357
  const meta = source[require_drizzle_meta.DRIZZLE_META];
338
358
  if (!meta) {
@@ -344,7 +364,7 @@ async function runDoctor(args) {
344
364
  });
345
365
  continue;
346
366
  }
347
- const idField = source.idField ?? "id";
367
+ const idField = meta.idField ?? source.idField ?? "id";
348
368
  const missing = [meta.cursorField, idField].filter((field) => !meta.columnKeys.includes(field));
349
369
  checks.push({
350
370
  name: `Cursor/id columns exist (${source.entity})`,
@@ -352,6 +372,14 @@ async function runDoctor(args) {
352
372
  detail: missing.length === 0 ? `"${source.entity}": ${meta.cursorField} + ${idField} present.` : `"${source.entity}" missing column(s): ${missing.join(", ")}.`
353
373
  });
354
374
  }
375
+ return checks;
376
+ }
377
+ /**
378
+ * Read one row from each source to prove the query works and that rows actually
379
+ * carry the cursor key. Fetch errors are captured as failures, never thrown.
380
+ */
381
+ async function sampleFetchChecks(sources) {
382
+ const checks = [];
355
383
  for (const source of sources) try {
356
384
  const rows = await source.fetchPage({
357
385
  since: null,
@@ -371,10 +399,45 @@ async function runDoctor(args) {
371
399
  detail: describeFetchError(source.entity, error)
372
400
  });
373
401
  }
402
+ return checks;
403
+ }
404
+ /**
405
+ * Run the read-only setup checks and return a structured report. Every check
406
+ * captures its own error into `detail` rather than throwing, so one failure never
407
+ * hides the rest. `ok` is the AND of all non-skipped checks.
408
+ */
409
+ async function runDoctor(args) {
410
+ const { config, probe } = args;
411
+ const checks = [];
412
+ const sources = configuredSources(config);
413
+ const hasKey = Boolean(config.apiKey);
414
+ checks.push({
415
+ name: "API key present",
416
+ ok: hasKey,
417
+ detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
418
+ });
419
+ const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
420
+ checks.push({
421
+ name: "Entities configured",
422
+ ok: entityCount > 0,
423
+ detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
424
+ });
425
+ checks.push({
426
+ name: "Sources configured",
427
+ ok: sources.length > 0,
428
+ detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
429
+ });
430
+ checks.push(checkConceptCoverage(config));
431
+ checks.push(...cursorColumnChecks(sources));
432
+ for (const source of sources) {
433
+ const check = cursorMonotonicityCheck(source);
434
+ if (check) checks.push(check);
435
+ }
436
+ checks.push(...await sampleFetchChecks(sources));
374
437
  checks.push(...await mappingDryRunChecks(config));
375
- const result = await connect();
438
+ const result = await probe();
376
439
  checks.push({
377
- name: "Heartbeat",
440
+ name: "Clivly reachable",
378
441
  ok: result.ok,
379
442
  detail: result.ok ? `Reached Clivly — org "${result.org?.name ?? "(unnamed)"}".` : `Could not connect (${result.reason}).`
380
443
  });
@@ -724,6 +787,7 @@ const UNAUTHORIZED_STATUS = 401;
724
787
  const FORBIDDEN_STATUS = 403;
725
788
  const CLIENT_ERROR_FLOOR = 400;
726
789
  const SERVICE_UNAVAILABLE_STATUS = 503;
790
+ const NOT_FOUND_STATUS = 404;
727
791
  function connectReason(status) {
728
792
  if (status === UNAUTHORIZED_STATUS) return "invalid_api_key";
729
793
  if (status === FORBIDDEN_STATUS) return "forbidden";
@@ -732,6 +796,10 @@ function connectReason(status) {
732
796
  if (status >= CLIENT_ERROR_FLOOR) return "client_error";
733
797
  return "server_error";
734
798
  }
799
+ function pingReason(status) {
800
+ if (status === NOT_FOUND_STATUS) return "server_too_old";
801
+ return connectReason(status);
802
+ }
735
803
  async function resolveOrg(response) {
736
804
  try {
737
805
  return (await response.json())?.org;
@@ -963,9 +1031,38 @@ function createClivlySDK(config) {
963
1031
  retryable: isRetryableStatus(response.status)
964
1032
  };
965
1033
  };
1034
+ const ping = async () => {
1035
+ const response = await fetcher(`${apiUrl}/clivly/sdk/ping`, {
1036
+ method: "GET",
1037
+ headers: { authorization: `Bearer ${config.apiKey}` }
1038
+ });
1039
+ if (response === null) return {
1040
+ ok: false,
1041
+ status: null,
1042
+ reason: "network_error",
1043
+ retryable: true
1044
+ };
1045
+ if (response.ok) {
1046
+ const body = await response.json().catch(() => ({}));
1047
+ return {
1048
+ ok: true,
1049
+ status: response.status,
1050
+ reason: "ok",
1051
+ retryable: false,
1052
+ org: body?.org,
1053
+ ..."appLastSeenAt" in body ? { appLastSeenAt: body.appLastSeenAt ?? null } : {}
1054
+ };
1055
+ }
1056
+ return {
1057
+ ok: false,
1058
+ status: response.status,
1059
+ reason: pingReason(response.status),
1060
+ retryable: isRetryableStatus(response.status)
1061
+ };
1062
+ };
966
1063
  const doctor = () => runDoctor({
967
1064
  config,
968
- connect
1065
+ probe: ping
969
1066
  });
970
1067
  const runScheduled = async (options) => {
971
1068
  await heartbeat();
@@ -1058,6 +1155,7 @@ function createClivlySDK(config) {
1058
1155
  stop,
1059
1156
  heartbeat,
1060
1157
  connect,
1158
+ ping,
1061
1159
  doctor,
1062
1160
  runScheduled,
1063
1161
  createClivlyHandler,
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ClivlySDK, c as CreateChatSessionHandlerOptions, d as DoctorCheck, f as DoctorReport, i as ClivlyConnectResult, l as CursorStore, n as ChatWidgetVisitor, o as ClivlySDKConfig, r as ClivlyConnectReason, s as ClivlyUser, t as ChatSessionRequestBody, u as DiscoveredTable } from "./types-DTaz5mLi.cjs";
1
+ import { a as ClivlySDK, c as CreateChatSessionHandlerOptions, d as DoctorCheck, f as DoctorReport, i as ClivlyConnectResult, l as CursorStore, n as ChatWidgetVisitor, o as ClivlySDKConfig, r as ClivlyConnectReason, s as ClivlyUser, t as ChatSessionRequestBody, u as DiscoveredTable } from "./types-QPbki8ur.cjs";
2
2
  import { createChatSessionHandler } from "./chat-session.cjs";
3
3
  import { ClivlyEntitiesConfig, defineClivlyConfig } from "@clivly/core/entity-config";
4
4
  //#region src/errors.d.ts
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ClivlySDK, c as CreateChatSessionHandlerOptions, d as DoctorCheck, f as DoctorReport, i as ClivlyConnectResult, l as CursorStore, n as ChatWidgetVisitor, o as ClivlySDKConfig, r as ClivlyConnectReason, s as ClivlyUser, t as ChatSessionRequestBody, u as DiscoveredTable } from "./types-DTaz5mLi.mjs";
1
+ import { a as ClivlySDK, c as CreateChatSessionHandlerOptions, d as DoctorCheck, f as DoctorReport, i as ClivlyConnectResult, l as CursorStore, n as ChatWidgetVisitor, o as ClivlySDKConfig, r as ClivlyConnectReason, s as ClivlyUser, t as ChatSessionRequestBody, u as DiscoveredTable } from "./types-QPbki8ur.mjs";
2
2
  import { createChatSessionHandler } from "./chat-session.mjs";
3
3
  import { ClivlyEntitiesConfig, defineClivlyConfig } from "@clivly/core/entity-config";
4
4
  //#region src/errors.d.ts
package/dist/index.mjs CHANGED
@@ -278,6 +278,46 @@ function errorMessage(error) {
278
278
  }
279
279
  //#endregion
280
280
  //#region src/doctor.ts
281
+ const TEMPORAL_CURSOR_TYPES = [
282
+ "timestamp",
283
+ "timestamptz",
284
+ "datetime",
285
+ "date",
286
+ "time"
287
+ ];
288
+ /**
289
+ * Warn when the sync cursor cannot observe an update.
290
+ *
291
+ * `clivly init` falls back to the primary key when a table has no
292
+ * `updated_at`-like column, and emits a TODO saying "confirm it is monotonic".
293
+ * A serial `id` *is* monotonic, so the note reads as satisfied — but monotonic
294
+ * is only half the requirement. An `id` never changes, so every insert mirrors
295
+ * and **no edit ever does**: a contact who changes their email keeps the old one
296
+ * in the CRM forever, with nothing anywhere reporting a problem.
297
+ *
298
+ * A code comment could not enforce this; a real integrator shipped exactly this
299
+ * configuration to production. This is the check that says so out loud.
300
+ */
301
+ function cursorMonotonicityCheck(source) {
302
+ const meta = source[DRIZZLE_META];
303
+ if (!meta?.columnsMeta) return null;
304
+ const index = meta.columnKeys.indexOf(meta.cursorField);
305
+ const type = meta.columnsMeta[index]?.type?.toLowerCase();
306
+ if (!type) return null;
307
+ const temporal = TEMPORAL_CURSOR_TYPES.some((t) => type.startsWith(t));
308
+ const name = `Cursor tracks updates (${source.entity})`;
309
+ if (temporal) return {
310
+ name,
311
+ ok: true,
312
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}) — edits re-sync.`
313
+ };
314
+ return {
315
+ name,
316
+ ok: true,
317
+ warn: true,
318
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}), which does not change when a row is edited — inserts will sync, edits will not. Add an updated_at column to "${meta.tableName ?? source.entity}" and set it as the cursor, or accept insert-only mirroring.`
319
+ };
320
+ }
281
321
  function configuredSources(config) {
282
322
  const sources = [];
283
323
  if (config.source?.contacts) sources.push(config.source.contacts);
@@ -306,32 +346,12 @@ async function mappingDryRunChecks(config) {
306
346
  return checks;
307
347
  }
308
348
  /**
309
- * Run the read-only setup checks and return a structured report. Every check
310
- * captures its own error into `detail` rather than throwing, so one failure never
311
- * hides the rest. `ok` is the AND of all non-skipped checks.
349
+ * Confirm each drizzle source actually has the cursor and id columns the sync
350
+ * pages on. Hand-written sources have no column metadata, so they are skipped
351
+ * rather than failed.
312
352
  */
313
- async function runDoctor(args) {
314
- const { config, connect } = args;
353
+ function cursorColumnChecks(sources) {
315
354
  const checks = [];
316
- const sources = configuredSources(config);
317
- const hasKey = Boolean(config.apiKey);
318
- checks.push({
319
- name: "API key present",
320
- ok: hasKey,
321
- detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
322
- });
323
- const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
324
- checks.push({
325
- name: "Entities configured",
326
- ok: entityCount > 0,
327
- detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
328
- });
329
- checks.push({
330
- name: "Sources configured",
331
- ok: sources.length > 0,
332
- detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
333
- });
334
- checks.push(checkConceptCoverage(config));
335
355
  for (const source of sources) {
336
356
  const meta = source[DRIZZLE_META];
337
357
  if (!meta) {
@@ -343,7 +363,7 @@ async function runDoctor(args) {
343
363
  });
344
364
  continue;
345
365
  }
346
- const idField = source.idField ?? "id";
366
+ const idField = meta.idField ?? source.idField ?? "id";
347
367
  const missing = [meta.cursorField, idField].filter((field) => !meta.columnKeys.includes(field));
348
368
  checks.push({
349
369
  name: `Cursor/id columns exist (${source.entity})`,
@@ -351,6 +371,14 @@ async function runDoctor(args) {
351
371
  detail: missing.length === 0 ? `"${source.entity}": ${meta.cursorField} + ${idField} present.` : `"${source.entity}" missing column(s): ${missing.join(", ")}.`
352
372
  });
353
373
  }
374
+ return checks;
375
+ }
376
+ /**
377
+ * Read one row from each source to prove the query works and that rows actually
378
+ * carry the cursor key. Fetch errors are captured as failures, never thrown.
379
+ */
380
+ async function sampleFetchChecks(sources) {
381
+ const checks = [];
354
382
  for (const source of sources) try {
355
383
  const rows = await source.fetchPage({
356
384
  since: null,
@@ -370,10 +398,45 @@ async function runDoctor(args) {
370
398
  detail: describeFetchError(source.entity, error)
371
399
  });
372
400
  }
401
+ return checks;
402
+ }
403
+ /**
404
+ * Run the read-only setup checks and return a structured report. Every check
405
+ * captures its own error into `detail` rather than throwing, so one failure never
406
+ * hides the rest. `ok` is the AND of all non-skipped checks.
407
+ */
408
+ async function runDoctor(args) {
409
+ const { config, probe } = args;
410
+ const checks = [];
411
+ const sources = configuredSources(config);
412
+ const hasKey = Boolean(config.apiKey);
413
+ checks.push({
414
+ name: "API key present",
415
+ ok: hasKey,
416
+ detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
417
+ });
418
+ const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
419
+ checks.push({
420
+ name: "Entities configured",
421
+ ok: entityCount > 0,
422
+ detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
423
+ });
424
+ checks.push({
425
+ name: "Sources configured",
426
+ ok: sources.length > 0,
427
+ detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
428
+ });
429
+ checks.push(checkConceptCoverage(config));
430
+ checks.push(...cursorColumnChecks(sources));
431
+ for (const source of sources) {
432
+ const check = cursorMonotonicityCheck(source);
433
+ if (check) checks.push(check);
434
+ }
435
+ checks.push(...await sampleFetchChecks(sources));
373
436
  checks.push(...await mappingDryRunChecks(config));
374
- const result = await connect();
437
+ const result = await probe();
375
438
  checks.push({
376
- name: "Heartbeat",
439
+ name: "Clivly reachable",
377
440
  ok: result.ok,
378
441
  detail: result.ok ? `Reached Clivly — org "${result.org?.name ?? "(unnamed)"}".` : `Could not connect (${result.reason}).`
379
442
  });
@@ -723,6 +786,7 @@ const UNAUTHORIZED_STATUS = 401;
723
786
  const FORBIDDEN_STATUS = 403;
724
787
  const CLIENT_ERROR_FLOOR = 400;
725
788
  const SERVICE_UNAVAILABLE_STATUS = 503;
789
+ const NOT_FOUND_STATUS = 404;
726
790
  function connectReason(status) {
727
791
  if (status === UNAUTHORIZED_STATUS) return "invalid_api_key";
728
792
  if (status === FORBIDDEN_STATUS) return "forbidden";
@@ -731,6 +795,10 @@ function connectReason(status) {
731
795
  if (status >= CLIENT_ERROR_FLOOR) return "client_error";
732
796
  return "server_error";
733
797
  }
798
+ function pingReason(status) {
799
+ if (status === NOT_FOUND_STATUS) return "server_too_old";
800
+ return connectReason(status);
801
+ }
734
802
  async function resolveOrg(response) {
735
803
  try {
736
804
  return (await response.json())?.org;
@@ -962,9 +1030,38 @@ function createClivlySDK(config) {
962
1030
  retryable: isRetryableStatus(response.status)
963
1031
  };
964
1032
  };
1033
+ const ping = async () => {
1034
+ const response = await fetcher(`${apiUrl}/clivly/sdk/ping`, {
1035
+ method: "GET",
1036
+ headers: { authorization: `Bearer ${config.apiKey}` }
1037
+ });
1038
+ if (response === null) return {
1039
+ ok: false,
1040
+ status: null,
1041
+ reason: "network_error",
1042
+ retryable: true
1043
+ };
1044
+ if (response.ok) {
1045
+ const body = await response.json().catch(() => ({}));
1046
+ return {
1047
+ ok: true,
1048
+ status: response.status,
1049
+ reason: "ok",
1050
+ retryable: false,
1051
+ org: body?.org,
1052
+ ..."appLastSeenAt" in body ? { appLastSeenAt: body.appLastSeenAt ?? null } : {}
1053
+ };
1054
+ }
1055
+ return {
1056
+ ok: false,
1057
+ status: response.status,
1058
+ reason: pingReason(response.status),
1059
+ retryable: isRetryableStatus(response.status)
1060
+ };
1061
+ };
965
1062
  const doctor = () => runDoctor({
966
1063
  config,
967
- connect
1064
+ probe: ping
968
1065
  });
969
1066
  const runScheduled = async (options) => {
970
1067
  await heartbeat();
@@ -1057,6 +1154,7 @@ function createClivlySDK(config) {
1057
1154
  stop,
1058
1155
  heartbeat,
1059
1156
  connect,
1157
+ ping,
1060
1158
  doctor,
1061
1159
  runScheduled,
1062
1160
  createClivlyHandler,