clivly 0.7.1 → 0.7.3

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.
@@ -276,6 +276,46 @@ function errorMessage(error) {
276
276
  }
277
277
  //#endregion
278
278
  //#region ../sdk/src/doctor.ts
279
+ const TEMPORAL_CURSOR_TYPES = [
280
+ "timestamp",
281
+ "timestamptz",
282
+ "datetime",
283
+ "date",
284
+ "time"
285
+ ];
286
+ /**
287
+ * Warn when the sync cursor cannot observe an update.
288
+ *
289
+ * `clivly init` falls back to the primary key when a table has no
290
+ * `updated_at`-like column, and emits a TODO saying "confirm it is monotonic".
291
+ * A serial `id` *is* monotonic, so the note reads as satisfied — but monotonic
292
+ * is only half the requirement. An `id` never changes, so every insert mirrors
293
+ * and **no edit ever does**: a contact who changes their email keeps the old one
294
+ * in the CRM forever, with nothing anywhere reporting a problem.
295
+ *
296
+ * A code comment could not enforce this; a real integrator shipped exactly this
297
+ * configuration to production. This is the check that says so out loud.
298
+ */
299
+ function cursorMonotonicityCheck(source) {
300
+ const meta = source[DRIZZLE_META];
301
+ if (!meta?.columnsMeta) return null;
302
+ const index = meta.columnKeys.indexOf(meta.cursorField);
303
+ const type = meta.columnsMeta[index]?.type?.toLowerCase();
304
+ if (!type) return null;
305
+ const temporal = TEMPORAL_CURSOR_TYPES.some((t) => type.startsWith(t));
306
+ const name = `Cursor tracks updates (${source.entity})`;
307
+ if (temporal) return {
308
+ name,
309
+ ok: true,
310
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}) — edits re-sync.`
311
+ };
312
+ return {
313
+ name,
314
+ ok: true,
315
+ warn: true,
316
+ 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.`
317
+ };
318
+ }
279
319
  function configuredSources(config) {
280
320
  const sources = [];
281
321
  if (config.source?.contacts) sources.push(config.source.contacts);
@@ -304,32 +344,12 @@ async function mappingDryRunChecks(config) {
304
344
  return checks;
305
345
  }
306
346
  /**
307
- * Run the read-only setup checks and return a structured report. Every check
308
- * captures its own error into `detail` rather than throwing, so one failure never
309
- * hides the rest. `ok` is the AND of all non-skipped checks.
347
+ * Confirm each drizzle source actually has the cursor and id columns the sync
348
+ * pages on. Hand-written sources have no column metadata, so they are skipped
349
+ * rather than failed.
310
350
  */
311
- async function runDoctor(args) {
312
- const { config, connect } = args;
351
+ function cursorColumnChecks(sources) {
313
352
  const checks = [];
314
- const sources = configuredSources(config);
315
- const hasKey = Boolean(config.apiKey);
316
- checks.push({
317
- name: "API key present",
318
- ok: hasKey,
319
- detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
320
- });
321
- const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
322
- checks.push({
323
- name: "Entities configured",
324
- ok: entityCount > 0,
325
- detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
326
- });
327
- checks.push({
328
- name: "Sources configured",
329
- ok: sources.length > 0,
330
- detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
331
- });
332
- checks.push(checkConceptCoverage(config));
333
353
  for (const source of sources) {
334
354
  const meta = source[DRIZZLE_META];
335
355
  if (!meta) {
@@ -349,6 +369,14 @@ async function runDoctor(args) {
349
369
  detail: missing.length === 0 ? `"${source.entity}": ${meta.cursorField} + ${idField} present.` : `"${source.entity}" missing column(s): ${missing.join(", ")}.`
350
370
  });
351
371
  }
372
+ return checks;
373
+ }
374
+ /**
375
+ * Read one row from each source to prove the query works and that rows actually
376
+ * carry the cursor key. Fetch errors are captured as failures, never thrown.
377
+ */
378
+ async function sampleFetchChecks(sources) {
379
+ const checks = [];
352
380
  for (const source of sources) try {
353
381
  const rows = await source.fetchPage({
354
382
  since: null,
@@ -368,10 +396,45 @@ async function runDoctor(args) {
368
396
  detail: describeFetchError(source.entity, error)
369
397
  });
370
398
  }
399
+ return checks;
400
+ }
401
+ /**
402
+ * Run the read-only setup checks and return a structured report. Every check
403
+ * captures its own error into `detail` rather than throwing, so one failure never
404
+ * hides the rest. `ok` is the AND of all non-skipped checks.
405
+ */
406
+ async function runDoctor(args) {
407
+ const { config, probe } = args;
408
+ const checks = [];
409
+ const sources = configuredSources(config);
410
+ const hasKey = Boolean(config.apiKey);
411
+ checks.push({
412
+ name: "API key present",
413
+ ok: hasKey,
414
+ detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
415
+ });
416
+ const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
417
+ checks.push({
418
+ name: "Entities configured",
419
+ ok: entityCount > 0,
420
+ detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
421
+ });
422
+ checks.push({
423
+ name: "Sources configured",
424
+ ok: sources.length > 0,
425
+ detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
426
+ });
427
+ checks.push(checkConceptCoverage(config));
428
+ checks.push(...cursorColumnChecks(sources));
429
+ for (const source of sources) {
430
+ const check = cursorMonotonicityCheck(source);
431
+ if (check) checks.push(check);
432
+ }
433
+ checks.push(...await sampleFetchChecks(sources));
371
434
  checks.push(...await mappingDryRunChecks(config));
372
- const result = await connect();
435
+ const result = await probe();
373
436
  checks.push({
374
- name: "Heartbeat",
437
+ name: "Clivly reachable",
375
438
  ok: result.ok,
376
439
  detail: result.ok ? `Reached Clivly — org "${result.org?.name ?? "(unnamed)"}".` : `Could not connect (${result.reason}).`
377
440
  });
@@ -810,6 +873,7 @@ const UNAUTHORIZED_STATUS = 401;
810
873
  const FORBIDDEN_STATUS = 403;
811
874
  const CLIENT_ERROR_FLOOR = 400;
812
875
  const SERVICE_UNAVAILABLE_STATUS = 503;
876
+ const NOT_FOUND_STATUS = 404;
813
877
  function connectReason(status) {
814
878
  if (status === UNAUTHORIZED_STATUS) return "invalid_api_key";
815
879
  if (status === FORBIDDEN_STATUS) return "forbidden";
@@ -818,6 +882,10 @@ function connectReason(status) {
818
882
  if (status >= CLIENT_ERROR_FLOOR) return "client_error";
819
883
  return "server_error";
820
884
  }
885
+ function pingReason(status) {
886
+ if (status === NOT_FOUND_STATUS) return "server_too_old";
887
+ return connectReason(status);
888
+ }
821
889
  async function resolveOrg(response) {
822
890
  try {
823
891
  return (await response.json())?.org;
@@ -1049,9 +1117,38 @@ function createClivlySDK(config) {
1049
1117
  retryable: isRetryableStatus(response.status)
1050
1118
  };
1051
1119
  };
1120
+ const ping = async () => {
1121
+ const response = await fetcher(`${apiUrl}/clivly/sdk/ping`, {
1122
+ method: "GET",
1123
+ headers: { authorization: `Bearer ${config.apiKey}` }
1124
+ });
1125
+ if (response === null) return {
1126
+ ok: false,
1127
+ status: null,
1128
+ reason: "network_error",
1129
+ retryable: true
1130
+ };
1131
+ if (response.ok) {
1132
+ const body = await response.json().catch(() => ({}));
1133
+ return {
1134
+ ok: true,
1135
+ status: response.status,
1136
+ reason: "ok",
1137
+ retryable: false,
1138
+ org: body?.org,
1139
+ ..."appLastSeenAt" in body ? { appLastSeenAt: body.appLastSeenAt ?? null } : {}
1140
+ };
1141
+ }
1142
+ return {
1143
+ ok: false,
1144
+ status: response.status,
1145
+ reason: pingReason(response.status),
1146
+ retryable: isRetryableStatus(response.status)
1147
+ };
1148
+ };
1052
1149
  const doctor = () => runDoctor({
1053
1150
  config,
1054
- connect
1151
+ probe: ping
1055
1152
  });
1056
1153
  const runScheduled = async (options) => {
1057
1154
  await heartbeat();
@@ -1144,6 +1241,7 @@ function createClivlySDK(config) {
1144
1241
  stop,
1145
1242
  heartbeat,
1146
1243
  connect,
1244
+ ping,
1147
1245
  doctor,
1148
1246
  runScheduled,
1149
1247
  createClivlyHandler,
package/sdk.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_entity_config = require("./entity-config-D87rV-tE.cjs");
3
- const require_sdk = require("./sdk-iqOXeWIp.cjs");
3
+ const require_sdk = require("./sdk-BrQYA-GT.cjs");
4
4
  exports.ClivlyAuthError = require_sdk.ClivlyAuthError;
5
5
  exports.ClivlyError = require_sdk.ClivlyError;
6
6
  exports.ClivlyNetworkError = require_sdk.ClivlyNetworkError;
package/sdk.d.cts CHANGED
@@ -1 +1,36 @@
1
- export {}
1
+ import { a as ClivlyEntitiesConfig, v as defineClivlyConfig } from "./entity-config-DoUCXtq5.cjs";
2
+ import { a as ClivlyConnectResult, c as ClivlyUser, d as DiscoveredTable, f as DoctorCheck, i as ClivlyConnectReason, l as CreateChatSessionHandlerOptions, n as ChatSessionRequestBody, o as ClivlySDK, p as DoctorReport, r as ChatWidgetVisitor, s as ClivlySDKConfig, u as CursorStore } from "./namespace-probe-DRzOtaRT.cjs";
3
+ //#region ../sdk/src/chat-session.d.ts
4
+ declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
5
+ //#endregion
6
+ //#region ../sdk/src/errors.d.ts
7
+ declare class ClivlyError extends Error {
8
+ /** HTTP status, or null when the request never completed (network error). */
9
+ readonly status: number | null;
10
+ readonly reason: ClivlyConnectResult["reason"];
11
+ /** Whether a retry could plausibly succeed (network, 429, 5xx). */
12
+ readonly retryable: boolean;
13
+ constructor(result: ClivlyConnectResult, message?: string);
14
+ /**
15
+ * Build the error subclass matching a failed result's reason, or `null` when
16
+ * the result is `ok`.
17
+ */
18
+ static from(result: ClivlyConnectResult): ClivlyError | null;
19
+ }
20
+ /** The API key was rejected (401) or lacks access (403). Not retryable. */
21
+ declare class ClivlyAuthError extends ClivlyError {}
22
+ /** Rate limited (429). Retryable after backoff / `Retry-After`. */
23
+ declare class ClivlyRateLimitError extends ClivlyError {}
24
+ /** The request never reached the server (network/DNS/TLS). Retryable. */
25
+ declare class ClivlyNetworkError extends ClivlyError {}
26
+ //#endregion
27
+ //#region ../sdk/src/index.d.ts
28
+ /**
29
+ * Create the Clivly SDK. The implemented surface — heartbeat/discovery reporting
30
+ * and the auth-verify handler — connects a developer's app to a running Clivly
31
+ * backend today. Tunnel management and CRM write-back are scaffolded (see the
32
+ * clearly-marked TODOs) and land with the Cloudflare infrastructure.
33
+ */
34
+ declare function createClivlySDK(config: ClivlySDKConfig): ClivlySDK;
35
+ //#endregion
36
+ export { type ChatSessionRequestBody, type ChatWidgetVisitor, ClivlyAuthError, type ClivlyConnectReason, type ClivlyConnectResult, type ClivlyEntitiesConfig, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, type ClivlySDK, type ClivlySDKConfig, type ClivlyUser, type CreateChatSessionHandlerOptions, type CursorStore, type DiscoveredTable, type DoctorCheck, type DoctorReport, createChatSessionHandler, createClivlySDK, defineClivlyConfig };
package/sdk.d.mts CHANGED
@@ -1 +1,36 @@
1
- export {}
1
+ import { a as ClivlyEntitiesConfig, v as defineClivlyConfig } from "./entity-config-DoUCXtq5.mjs";
2
+ import { a as ClivlyConnectResult, c as ClivlyUser, d as DiscoveredTable, f as DoctorCheck, i as ClivlyConnectReason, l as CreateChatSessionHandlerOptions, n as ChatSessionRequestBody, o as ClivlySDK, p as DoctorReport, r as ChatWidgetVisitor, s as ClivlySDKConfig, u as CursorStore } from "./namespace-probe-B4WE45TH.mjs";
3
+ //#region ../sdk/src/chat-session.d.ts
4
+ declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
5
+ //#endregion
6
+ //#region ../sdk/src/errors.d.ts
7
+ declare class ClivlyError extends Error {
8
+ /** HTTP status, or null when the request never completed (network error). */
9
+ readonly status: number | null;
10
+ readonly reason: ClivlyConnectResult["reason"];
11
+ /** Whether a retry could plausibly succeed (network, 429, 5xx). */
12
+ readonly retryable: boolean;
13
+ constructor(result: ClivlyConnectResult, message?: string);
14
+ /**
15
+ * Build the error subclass matching a failed result's reason, or `null` when
16
+ * the result is `ok`.
17
+ */
18
+ static from(result: ClivlyConnectResult): ClivlyError | null;
19
+ }
20
+ /** The API key was rejected (401) or lacks access (403). Not retryable. */
21
+ declare class ClivlyAuthError extends ClivlyError {}
22
+ /** Rate limited (429). Retryable after backoff / `Retry-After`. */
23
+ declare class ClivlyRateLimitError extends ClivlyError {}
24
+ /** The request never reached the server (network/DNS/TLS). Retryable. */
25
+ declare class ClivlyNetworkError extends ClivlyError {}
26
+ //#endregion
27
+ //#region ../sdk/src/index.d.ts
28
+ /**
29
+ * Create the Clivly SDK. The implemented surface — heartbeat/discovery reporting
30
+ * and the auth-verify handler — connects a developer's app to a running Clivly
31
+ * backend today. Tunnel management and CRM write-back are scaffolded (see the
32
+ * clearly-marked TODOs) and land with the Cloudflare infrastructure.
33
+ */
34
+ declare function createClivlySDK(config: ClivlySDKConfig): ClivlySDK;
35
+ //#endregion
36
+ export { type ChatSessionRequestBody, type ChatWidgetVisitor, ClivlyAuthError, type ClivlyConnectReason, type ClivlyConnectResult, type ClivlyEntitiesConfig, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, type ClivlySDK, type ClivlySDKConfig, type ClivlyUser, type CreateChatSessionHandlerOptions, type CursorStore, type DiscoveredTable, type DoctorCheck, type DoctorReport, createChatSessionHandler, createClivlySDK, defineClivlyConfig };
package/sdk.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  import { o as defineClivlyConfig } from "./entity-config-va2bkH5o.mjs";
2
- import { a as ClivlyRateLimitError, i as ClivlyNetworkError, n as ClivlyAuthError, o as createChatSessionHandler, r as ClivlyError, t as createClivlySDK } from "./sdk-C6WANW8M.mjs";
2
+ import { a as ClivlyRateLimitError, i as ClivlyNetworkError, n as ClivlyAuthError, o as createChatSessionHandler, r as ClivlyError, t as createClivlySDK } from "./sdk-C2VL28du.mjs";
3
3
  export { ClivlyAuthError, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, createChatSessionHandler, createClivlySDK, defineClivlyConfig };
package/vite.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as ClivlySDK } from "./types-CsL0rFYh.cjs";
1
+ import { o as ClivlySDK } from "./namespace-probe-DRzOtaRT.cjs";
2
2
  import { Plugin } from "vite";
3
3
  //#region ../sdk/src/vite.d.ts
4
4
  interface ClivlyViteOptions {
package/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as ClivlySDK } from "./types-CsL0rFYh.mjs";
1
+ import { o as ClivlySDK } from "./namespace-probe-B4WE45TH.mjs";
2
2
  import { Plugin } from "vite";
3
3
  //#region ../sdk/src/vite.d.ts
4
4
  interface ClivlyViteOptions {
@@ -1,155 +0,0 @@
1
- //#region ../sdk/src/drizzle-meta.d.ts
2
- declare const DRIZZLE_META: "__clivly_drizzle_source_meta__";
3
- interface DrizzleSourceMeta {
4
- /** Drizzle property keys of every column on the source table. */
5
- columnKeys: string[];
6
- /** Schema-v2 typed column metadata derived from the Drizzle table. */
7
- columnsMeta?: DiscoveredColumn[];
8
- cursorField: string;
9
- idField: string;
10
- /** The backing table's real name, so discovery can key metadata by table. */
11
- tableName?: string;
12
- }
13
- //#endregion
14
- //#region ../sdk/src/types.d.ts
15
- interface DiscoveredColumn {
16
- isForeignKey?: boolean;
17
- isPrimaryKey?: boolean;
18
- name: string;
19
- nullable?: boolean;
20
- /** The column this FK points at, when it is a foreign key. */
21
- references?: {
22
- table: string;
23
- column: string;
24
- };
25
- /** SQL/driver type, e.g. "text", "integer", "timestamp". */
26
- type?: string;
27
- }
28
- interface ClivlyUser {
29
- email: string;
30
- id: string;
31
- name?: string;
32
- }
33
- interface DoctorCheck {
34
- /** Human-readable outcome — what passed, or why it failed. */
35
- detail: string;
36
- /** Short label, e.g. "API key present". */
37
- name: string;
38
- /** True when the check passed. Ignored when `skipped` is true. */
39
- ok: boolean;
40
- /** True when the check could not run (e.g. a hand-written source). */
41
- skipped?: boolean;
42
- }
43
- interface DoctorReport {
44
- checks: DoctorCheck[];
45
- /** AND of every non-skipped check's `ok`. */
46
- ok: boolean;
47
- }
48
- type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "network_error";
49
- interface ClivlyConnectResult {
50
- ok: boolean;
51
- /** Org resolved from a successful heartbeat, when the server returns it. */
52
- org?: {
53
- id?: string;
54
- name?: string;
55
- };
56
- reason: ClivlyConnectReason;
57
- /** Whether a retry could plausibly succeed (network, 429, 5xx). */
58
- retryable: boolean;
59
- /** HTTP status, or null when the request never completed (network error). */
60
- status: number | null;
61
- }
62
- interface SyncCursor {
63
- /** The row's id, breaking ties when timestamps collide. */
64
- id: string;
65
- /** The row's cursor-field value (typically `updated_at`). */
66
- time: Date;
67
- }
68
- interface SyncSource {
69
- cursorField: string;
70
- entity: string;
71
- fetchPage(args: {
72
- since: SyncCursor | null;
73
- limit: number;
74
- }): Promise<Record<string, unknown>[]>;
75
- /** Stable, unique tie-breaker column for keyset paging. Defaults to "id". */
76
- idField?: string;
77
- /** Set by `fromDrizzle`; lets `doctor` introspect the backing table. */
78
- [DRIZZLE_META]?: DrizzleSourceMeta;
79
- }
80
- type SyncMode = "delta" | "full";
81
- interface ClivlySDK {
82
- /**
83
- * Send a single heartbeat and report the outcome richly: `ok`, the HTTP
84
- * `status` (null on network failure), a coarse `reason`, whether it's
85
- * `retryable`, and the resolved `org` when the server returns it. Never throws
86
- * — inspect the result, or turn a failure into an exception with
87
- * `ClivlyError.from(result)`. Prefer this over `heartbeat()` for onboarding,
88
- * health checks, and one-shot serverless calls.
89
- */
90
- connect(): Promise<ClivlyConnectResult>;
91
- /**
92
- * Build the `/clivly/auth/verify` handler the developer mounts in their app.
93
- * Clivly's cloud calls it to validate a CRM user's identity against the host
94
- * app's session. Pass a resolver that reads the host session from the request.
95
- *
96
- * The handler authenticates the caller against `config.verifyToken` (presented
97
- * as `Authorization: Bearer <token>`) before invoking the resolver, so the
98
- * endpoint can't be used by third parties to probe host sessions. It fails
99
- * closed with HTTP 503 if `verifyToken` is unset (a missing config value, not a
100
- * server fault — so it won't trip the host's 5xx error alerting).
101
- */
102
- createAuthVerifyHandler(resolveUser: (req: Request) => Promise<ClivlyUser | null> | ClivlyUser | null): (req: Request) => Promise<Response>;
103
- /**
104
- * A fetch handler to mount at a route. Each request runs one `runScheduled()`
105
- * and returns JSON: 200 when the sync succeeded, 500 otherwise.
106
- *
107
- * Two callers use it: Clivly Cloud (when someone clicks "Run sync" — those
108
- * requests are HMAC-signed and carry a run id), and the host's own scheduler
109
- * (Workers cron, an uptime ping — no body).
110
- *
111
- * When `syncTrigger.secret` is set the handler rejects unsigned or
112
- * badly-signed requests with 401. When it isn't, the route stays open to
113
- * anyone who can reach it — set a secret if it's publicly routable.
114
- */
115
- createClivlyHandler(): (req: Request) => Promise<Response>;
116
- /** Validate this setup end-to-end (read-only) before the first sync. */
117
- doctor(): Promise<DoctorReport>;
118
- /**
119
- * Send a single heartbeat now. Returns true on success. Kept for the keep-alive
120
- * loop and back-compat; use `connect()` when you need the failure reason.
121
- */
122
- heartbeat(): Promise<boolean>;
123
- /**
124
- * One-shot heartbeat + a single sync, with no keep-alive timers. The correct
125
- * entry point on serverless/edge (Workers, Vercel, Lambda), where `start()`'s
126
- * `setInterval` loop can't persist between invocations — call this from a
127
- * scheduled/cron trigger. Throws if a sync push fails (so the run is marked
128
- * failed); heartbeat is best-effort.
129
- */
130
- runScheduled(options?: {
131
- mode?: SyncMode;
132
- runId?: string;
133
- }): Promise<void>;
134
- /**
135
- * Send the initial heartbeat and start the keep-alive loop. For long-lived
136
- * hosts only — on serverless/edge the interval can't persist, so prefer
137
- * `runScheduled()` / `createClivlyHandler()`. Emits a warning if a serverless
138
- * runtime is detected.
139
- */
140
- start(): Promise<void>;
141
- /** Stop the keep-alive loop. */
142
- stop(): void;
143
- /**
144
- * Sync all configured sources now. `delta` (default) pages changed rows since
145
- * the last cursor; `full` pushes each complete entity so the server can
146
- * reconcile leavers (archive-on-leave). Throws if a push fails, so callers see
147
- * the failure — the background keep-alive loop swallows and retries instead.
148
- */
149
- sync(options?: {
150
- mode?: SyncMode;
151
- runId?: string;
152
- }): Promise<void>;
153
- }
154
- //#endregion
155
- export { SyncSource as n, ClivlySDK as t };
@@ -1,155 +0,0 @@
1
- //#region ../sdk/src/drizzle-meta.d.ts
2
- declare const DRIZZLE_META: "__clivly_drizzle_source_meta__";
3
- interface DrizzleSourceMeta {
4
- /** Drizzle property keys of every column on the source table. */
5
- columnKeys: string[];
6
- /** Schema-v2 typed column metadata derived from the Drizzle table. */
7
- columnsMeta?: DiscoveredColumn[];
8
- cursorField: string;
9
- idField: string;
10
- /** The backing table's real name, so discovery can key metadata by table. */
11
- tableName?: string;
12
- }
13
- //#endregion
14
- //#region ../sdk/src/types.d.ts
15
- interface DiscoveredColumn {
16
- isForeignKey?: boolean;
17
- isPrimaryKey?: boolean;
18
- name: string;
19
- nullable?: boolean;
20
- /** The column this FK points at, when it is a foreign key. */
21
- references?: {
22
- table: string;
23
- column: string;
24
- };
25
- /** SQL/driver type, e.g. "text", "integer", "timestamp". */
26
- type?: string;
27
- }
28
- interface ClivlyUser {
29
- email: string;
30
- id: string;
31
- name?: string;
32
- }
33
- interface DoctorCheck {
34
- /** Human-readable outcome — what passed, or why it failed. */
35
- detail: string;
36
- /** Short label, e.g. "API key present". */
37
- name: string;
38
- /** True when the check passed. Ignored when `skipped` is true. */
39
- ok: boolean;
40
- /** True when the check could not run (e.g. a hand-written source). */
41
- skipped?: boolean;
42
- }
43
- interface DoctorReport {
44
- checks: DoctorCheck[];
45
- /** AND of every non-skipped check's `ok`. */
46
- ok: boolean;
47
- }
48
- type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "network_error";
49
- interface ClivlyConnectResult {
50
- ok: boolean;
51
- /** Org resolved from a successful heartbeat, when the server returns it. */
52
- org?: {
53
- id?: string;
54
- name?: string;
55
- };
56
- reason: ClivlyConnectReason;
57
- /** Whether a retry could plausibly succeed (network, 429, 5xx). */
58
- retryable: boolean;
59
- /** HTTP status, or null when the request never completed (network error). */
60
- status: number | null;
61
- }
62
- interface SyncCursor {
63
- /** The row's id, breaking ties when timestamps collide. */
64
- id: string;
65
- /** The row's cursor-field value (typically `updated_at`). */
66
- time: Date;
67
- }
68
- interface SyncSource {
69
- cursorField: string;
70
- entity: string;
71
- fetchPage(args: {
72
- since: SyncCursor | null;
73
- limit: number;
74
- }): Promise<Record<string, unknown>[]>;
75
- /** Stable, unique tie-breaker column for keyset paging. Defaults to "id". */
76
- idField?: string;
77
- /** Set by `fromDrizzle`; lets `doctor` introspect the backing table. */
78
- [DRIZZLE_META]?: DrizzleSourceMeta;
79
- }
80
- type SyncMode = "delta" | "full";
81
- interface ClivlySDK {
82
- /**
83
- * Send a single heartbeat and report the outcome richly: `ok`, the HTTP
84
- * `status` (null on network failure), a coarse `reason`, whether it's
85
- * `retryable`, and the resolved `org` when the server returns it. Never throws
86
- * — inspect the result, or turn a failure into an exception with
87
- * `ClivlyError.from(result)`. Prefer this over `heartbeat()` for onboarding,
88
- * health checks, and one-shot serverless calls.
89
- */
90
- connect(): Promise<ClivlyConnectResult>;
91
- /**
92
- * Build the `/clivly/auth/verify` handler the developer mounts in their app.
93
- * Clivly's cloud calls it to validate a CRM user's identity against the host
94
- * app's session. Pass a resolver that reads the host session from the request.
95
- *
96
- * The handler authenticates the caller against `config.verifyToken` (presented
97
- * as `Authorization: Bearer <token>`) before invoking the resolver, so the
98
- * endpoint can't be used by third parties to probe host sessions. It fails
99
- * closed with HTTP 503 if `verifyToken` is unset (a missing config value, not a
100
- * server fault — so it won't trip the host's 5xx error alerting).
101
- */
102
- createAuthVerifyHandler(resolveUser: (req: Request) => Promise<ClivlyUser | null> | ClivlyUser | null): (req: Request) => Promise<Response>;
103
- /**
104
- * A fetch handler to mount at a route. Each request runs one `runScheduled()`
105
- * and returns JSON: 200 when the sync succeeded, 500 otherwise.
106
- *
107
- * Two callers use it: Clivly Cloud (when someone clicks "Run sync" — those
108
- * requests are HMAC-signed and carry a run id), and the host's own scheduler
109
- * (Workers cron, an uptime ping — no body).
110
- *
111
- * When `syncTrigger.secret` is set the handler rejects unsigned or
112
- * badly-signed requests with 401. When it isn't, the route stays open to
113
- * anyone who can reach it — set a secret if it's publicly routable.
114
- */
115
- createClivlyHandler(): (req: Request) => Promise<Response>;
116
- /** Validate this setup end-to-end (read-only) before the first sync. */
117
- doctor(): Promise<DoctorReport>;
118
- /**
119
- * Send a single heartbeat now. Returns true on success. Kept for the keep-alive
120
- * loop and back-compat; use `connect()` when you need the failure reason.
121
- */
122
- heartbeat(): Promise<boolean>;
123
- /**
124
- * One-shot heartbeat + a single sync, with no keep-alive timers. The correct
125
- * entry point on serverless/edge (Workers, Vercel, Lambda), where `start()`'s
126
- * `setInterval` loop can't persist between invocations — call this from a
127
- * scheduled/cron trigger. Throws if a sync push fails (so the run is marked
128
- * failed); heartbeat is best-effort.
129
- */
130
- runScheduled(options?: {
131
- mode?: SyncMode;
132
- runId?: string;
133
- }): Promise<void>;
134
- /**
135
- * Send the initial heartbeat and start the keep-alive loop. For long-lived
136
- * hosts only — on serverless/edge the interval can't persist, so prefer
137
- * `runScheduled()` / `createClivlyHandler()`. Emits a warning if a serverless
138
- * runtime is detected.
139
- */
140
- start(): Promise<void>;
141
- /** Stop the keep-alive loop. */
142
- stop(): void;
143
- /**
144
- * Sync all configured sources now. `delta` (default) pages changed rows since
145
- * the last cursor; `full` pushes each complete entity so the server can
146
- * reconcile leavers (archive-on-leave). Throws if a push fails, so callers see
147
- * the failure — the background keep-alive loop swallows and retries instead.
148
- */
149
- sync(options?: {
150
- mode?: SyncMode;
151
- runId?: string;
152
- }): Promise<void>;
153
- }
154
- //#endregion
155
- export { SyncSource as n, ClivlySDK as t };