@clivly/sdk 0.7.2 → 0.7.4

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/README.md CHANGED
@@ -1,193 +1,333 @@
1
1
  # @clivly/sdk
2
2
 
3
- Connect an app to Clivly Cloud. The SDK sends heartbeats, reports schema
4
- discovery data, syncs source rows to Clivly over outbound HTTPS, and can expose
5
- a signed trigger route so Clivly can start a sync from the dashboard.
3
+ Connect your app to Clivly Cloud. The SDK sends a heartbeat, reports your schema
4
+ for entity mapping, and mirrors your contacts and companies into Clivly over
5
+ outbound HTTPS. If you configure `syncTrigger`, Clivly can also call back into
6
+ your app to start a sync from the dashboard.
6
7
 
7
- ## Which package should I install?
8
+ Clivly never connects to your database — the SDK runs inside your app and is the
9
+ only thing that touches your data.
8
10
 
9
- For most new integrations, install the consolidated public package:
11
+ > **The canonical end-to-end integration guide is
12
+ > [Connecting to Clivly Cloud](../../docs/guides/connecting-to-clivly-cloud.md).**
13
+ > This README is the API-level reference for the SDK surface itself.
14
+
15
+ ## Prerequisites
16
+
17
+ | Requirement | Version / note |
18
+ | --- | --- |
19
+ | Node.js | **≥ 22** |
20
+ | `drizzle-orm` | Optional peer — only for `clivly/drizzle` |
21
+ | `vite` | Optional peer — only for `clivly/vite` |
22
+ | A Clivly org + secret key | Dashboard → **Connect app**, or **Settings → API keys** |
23
+
24
+ ## Installation
10
25
 
11
26
  ```bash
12
27
  npm install clivly
13
28
  ```
14
29
 
15
- and import from:
30
+ Install `clivly`, not `@clivly/sdk`. The `clivly` package re-exports this SDK at
31
+ `clivly/sdk` and is what `clivly init` installs, so you get the CLI and the
32
+ runtime from one dependency at one version.
33
+
34
+ > `@clivly/sdk` is published and works standalone if you want the runtime
35
+ > without the CLI. Every import path below then drops the `clivly/` prefix:
36
+ > `@clivly/sdk`, `@clivly/sdk/drizzle`, `@clivly/sdk/vite`,
37
+ > `@clivly/sdk/chat-session`.
38
+
39
+ > **Never `import` from the bare `clivly` specifier.** That entry is the CLI
40
+ > binary; it pulls `node:fs` and `node:child_process` in at module scope and
41
+ > throws on Workers and other edge runtimes. Use `clivly/sdk`.
42
+
43
+ ## Five-minute quick start
16
44
 
17
45
  ```ts
46
+ // clivly.config.ts
18
47
  import { createClivlySDK, defineClivlyConfig } from "clivly/sdk";
19
- import { fromDrizzle } from "clivly/drizzle";
20
- ```
48
+ import { discoverFromDrizzle, fromDrizzle } from "clivly/drizzle";
49
+ import * as schema from "./db/schema";
50
+ import { db } from "./db";
21
51
 
22
- `@clivly/sdk` remains a public package if you prefer a direct dependency on the
23
- SDK package itself:
52
+ const entities = defineClivlyConfig({
53
+ entities: {
54
+ users: {
55
+ concept: "contact",
56
+ source: "users",
57
+ fields: { name: "full_name", email: "email" },
58
+ },
59
+ },
60
+ });
24
61
 
25
- ```bash
26
- npm install @clivly/sdk
62
+ export default createClivlySDK({
63
+ apiKey: process.env.CLIVLY_SECRET_KEY!, // sk_live_… — never ships to a browser
64
+ entities,
65
+ schema: discoverFromDrizzle(schema),
66
+ source: {
67
+ contacts: fromDrizzle(db, schema.users, {
68
+ entity: "users",
69
+ cursorField: "updatedAt",
70
+ }),
71
+ },
72
+ });
27
73
  ```
28
74
 
29
- with imports from:
30
-
31
75
  ```ts
32
- import { createClivlySDK, defineClivlyConfig } from "@clivly/sdk";
33
- import { fromDrizzle } from "@clivly/sdk/drizzle";
76
+ // somewhere that runs at boot
77
+ import clivly from "./clivly.config";
78
+
79
+ const result = await clivly.connect();
80
+ if (!result.ok) throw new Error(`Clivly: ${result.reason}`);
81
+
82
+ await clivly.start(); // long-lived hosts only — see below
34
83
  ```
35
84
 
36
- Stable releases publish on npm's `latest` tag. Use `@next` only when you are
37
- intentionally validating a prerelease build.
85
+ `createClivlySDK(...)` is a **pure factory**. Constructing it — or importing a
86
+ module that constructs it — does nothing on its own: no heartbeat, no sync, no
87
+ network call. That keeps the SDK tree-shakeable (`sideEffects: false`), but it
88
+ means a bare `import "./clivly.config"` will never connect. You must call an
89
+ entry point.
38
90
 
39
- Add `drizzle-orm` when you use the Drizzle helpers, and `vite` when you use the
40
- Vite/TanStack Start plugin.
91
+ ## Step-by-step configuration
41
92
 
42
- ## Surface
93
+ ### Choose the runtime entry point
43
94
 
44
- Public exports from this package:
95
+ The single most consequential decision in the setup.
45
96
 
46
- - `@clivly/sdk`:
47
- `createClivlySDK`, `defineClivlyConfig`, `createChatSessionHandler`,
48
- `ClivlyError`, `ClivlyNetworkError`, `ClivlyRateLimitError`,
49
- `ClivlyAuthError`
50
- - `@clivly/sdk/drizzle`:
51
- Drizzle source helpers such as `fromDrizzle`
52
- - `@clivly/sdk/vite`:
53
- the Vite/TanStack Start lifecycle plugin
54
- - `@clivly/sdk/chat-session`:
55
- chat-session handler helpers when you want that subpath explicitly
97
+ | Host runtime | Use | Why |
98
+ | --- | --- | --- |
99
+ | Long-lived Node server, Vite dev | `clivlyVite(sdk)` or `await sdk.start()` | The `setInterval` keep-alive loop persists |
100
+ | Cloudflare Workers, Vercel, Lambda | `sdk.createClivlyHandler()` at a route, and/or `sdk.runScheduled()` from cron | `setInterval` does **not** survive between invocations |
101
+ | One-off health check | `await sdk.connect()` | Structured `{ ok, status, reason, retryable, org? }` |
56
102
 
57
- ## Basic usage
103
+ `start()` emits a console warning when it detects a serverless runtime, because
104
+ there it stops ticking after the first response.
58
105
 
59
- ```ts
60
- import { createClivlySDK, defineClivlyConfig } from "@clivly/sdk";
61
- import { fromDrizzle } from "@clivly/sdk/drizzle";
62
- import { db, participants, accounts } from "./db";
106
+ ### Entities vs. sources — the distinction that bites
63
107
 
108
+ ```ts
64
109
  const entities = defineClivlyConfig({
65
110
  entities: {
66
- participants: {
67
- concept: "contact",
68
- source: "participants",
111
+ participants: { // ← your entity key, arbitrary
112
+ concept: "contact", // ← CRM concept
113
+ source: "participants", // ← a HOST TABLE NAME
69
114
  fields: { name: "full_name", email: "email" },
70
115
  },
71
- accounts: {
72
- concept: "company",
73
- source: "accounts",
74
- fields: { name: "legal_name", domain: "website" },
75
- },
76
116
  },
77
117
  });
78
118
 
79
- const clivly = createClivlySDK({
80
- apiKey: process.env.CLIVLY_SECRET_KEY!,
119
+ createClivlySDK({
81
120
  entities,
82
- source: {
83
- contacts: fromDrizzle(db, participants, {
84
- entity: "participants",
85
- cursorField: "updatedAt",
86
- }),
87
- companies: fromDrizzle(db, accounts, {
88
- entity: "accounts",
89
- cursorField: "updatedAt",
90
- }),
121
+ source: { // ← keyed by CRM CONCEPT, never by entity key
122
+ contacts: fromDrizzle(db, participants, { … }),
91
123
  },
92
- sync: { onBoot: true, intervalMs: 30_000, batchSize: 500 },
93
124
  });
125
+ ```
94
126
 
95
- const status = await clivly.connect();
96
- if (!status.ok) {
97
- throw new Error(`Clivly: ${status.reason}`);
98
- }
127
+ `config.source` accepts only `contacts` / `companies` / `deals` / `custom`.
128
+ Conflating the two axes means an entity resolves to no source and silently syncs
129
+ nothing, without erroring. `clivly status` cross-checks this for you.
99
130
 
100
- await clivly.start();
101
- ```
131
+ ### Sources
102
132
 
103
- `fromDrizzle` builds the keyset-paginated `fetchPage` function the SDK needs.
104
- `cursorField` and `idField` are Drizzle property keys such as `updatedAt`, not
105
- database column names such as `updated_at`. Non-Drizzle apps can provide their
106
- own `fetchPage` implementation.
133
+ `fromDrizzle` generates the keyset-paginated `fetchPage` the SDK needs,
134
+ inferring the tie-breaker id from the table's primary key — pass `idField` to
135
+ override.
107
136
 
108
- ## Remote sync trigger
137
+ ```ts
138
+ fromDrizzle(db, schema.users, {
139
+ entity: "users", // the host table name
140
+ cursorField: "updatedAt", // Drizzle PROPERTY key, not the DB column
141
+ idField: "id", // optional; defaults to the primary key
142
+ })
143
+ ```
109
144
 
110
- If you configure `syncTrigger`, Clivly can ask your app to run a sync from the
111
- dashboard:
145
+ `cursorField` and `idField` are Drizzle property keys (`updatedAt`), **not**
146
+ database column names (`updated_at`). `entities[].fields` goes the other way:
147
+ its values are real **column** names (`full_name`), which is what
148
+ `discoverFromDrizzle` reports and what the dashboard's mapping table stores.
149
+ Clivly applies that field map on its side, so re-mapping never needs a
150
+ redeploy.
151
+
152
+ `fromDrizzle` projects every column under its real database name, so rows arrive
153
+ column-keyed and the field map resolves. The `SyncSource` it returns therefore
154
+ reports `cursorField` / `idField` as **column names** too — you still pass
155
+ Drizzle property keys in, and it translates once.
156
+
157
+ > **Upgrading from `clivly@0.7.3` or earlier?** Those versions returned rows
158
+ > keyed by Drizzle **property** names, so on a snake_case schema any field whose
159
+ > property key differed from its column name mirrored as empty — silently
160
+ > (`email` worked by coincidence). `clivly status` reports it as
161
+ > `❌ Field mapping dry run … missing mapped column(s): name → full_name`.
162
+ > If you worked around it by mapping to the Drizzle key
163
+ > (`fields: { name: "fullName" }`), **revert that to the column name** on
164
+ > upgrade — the workaround is what breaks now.
165
+
166
+ Non-Drizzle hosts pass a hand-written `fetchPage` instead. Page on the compound
167
+ `(cursorField, idField)` watermark:
112
168
 
113
169
  ```ts
114
- const clivly = createClivlySDK({
115
- apiKey: process.env.CLIVLY_SECRET_KEY!,
116
- entities,
117
- source: { /* ... */ },
118
- syncTrigger: {
119
- path: "/api/clivly/tick",
120
- url: process.env.CLIVLY_SYNC_TRIGGER_URL,
121
- secret: process.env.CLIVLY_SYNC_TRIGGER_SECRET,
170
+ source: {
171
+ contacts: {
172
+ entity: "users",
173
+ cursorField: "updated_at",
174
+ idField: "id",
175
+ async fetchPage({ since, limit }) {
176
+ // WHERE (updated_at, id) > (:since.time, :since.id)
177
+ // ORDER BY updated_at ASC, id ASC LIMIT :limit
178
+ // (when `since` is null, return the first page ordered the same way)
179
+ return await myDb.query(/* … */);
180
+ },
122
181
  },
123
- });
182
+ },
183
+ ```
124
184
 
125
- export async function POST(request: Request) {
126
- return clivly.createClivlyHandler()(request);
127
- }
185
+ ### Remote sync trigger
186
+
187
+ ```ts
188
+ syncTrigger: {
189
+ path: "/api/clivly/tick",
190
+ url: process.env.CLIVLY_SYNC_TRIGGER_URL,
191
+ secret: process.env.CLIVLY_SYNC_TRIGGER_SECRET, // whsec_… from Integrations → Remote sync
192
+ },
128
193
  ```
129
194
 
130
- With `syncTrigger.url` and `syncTrigger.secret` configured, the SDK reports the
131
- trigger URL on each heartbeat and rejects unsigned or badly-signed requests.
132
- Without `syncTrigger`, cloud mode is push-only: Clivly can observe the app but
133
- cannot start a sync from the dashboard.
195
+ ```ts
196
+ // mount it — this is a plain (Request) => Promise<Response>
197
+ export const POST = (request: Request) => clivly.createClivlyHandler()(request);
198
+ ```
199
+
200
+ With `url` + `secret` configured, the SDK reports the trigger URL on each
201
+ heartbeat and rejects unsigned or badly-signed requests with `401`. **Without a
202
+ secret the route stays open to anyone who can reach it** — always set one if the
203
+ route is publicly routable. Without `syncTrigger` at all, cloud mode is
204
+ push-only: Clivly can observe the app but cannot start a sync from the
205
+ dashboard.
206
+
207
+ `url` is optional — the SDK discovers it from the hosting platform's environment
208
+ or from the first request the route serves. Set it only to pin an address the
209
+ SDK cannot infer.
210
+
211
+ ## Complete working example
134
212
 
135
- ## Vite / TanStack Start
213
+ See [the guide's worked example](../../docs/guides/connecting-to-clivly-cloud.md#6-complete-working-example)
214
+ for a full Next.js + Drizzle + Vercel setup with `.env`, config, and route file.
136
215
 
137
- For long-lived Vite dev servers, wire the SDK lifecycle through the plugin:
216
+ ### Vite / TanStack Start
138
217
 
139
218
  ```ts
140
- import { clivlyVite } from "@clivly/sdk/vite";
141
- import clivly from "./clivly.config";
219
+ // vite.config.ts
142
220
  import { defineConfig } from "vite";
221
+ import { clivlyVite } from "clivly/vite";
222
+ import clivly from "./clivly.config";
143
223
 
144
224
  export default defineConfig({
145
225
  plugins: [clivlyVite(clivly)],
146
226
  });
147
227
  ```
148
228
 
149
- The plugin calls `connect()` for a startup status line, then `start()` for the
150
- heartbeat and sync loop. It is dev-server only; use `runScheduled()` or
151
- `createClivlyHandler()` for request-scoped runtimes.
152
-
153
- ## Verify your setup
229
+ The plugin calls `connect()` for a clear startup status line, then `start()` for
230
+ the heartbeat and sync loop, and `stop()` on shutdown. It is **dev-server
231
+ only**; use `runScheduled()` or `createClivlyHandler()` for serverless
232
+ production runtimes.
154
233
 
155
- If your instance lives in `clivly.config.ts`, the CLI can validate the setup:
234
+ ### Serverless / edge
156
235
 
157
- ```bash
158
- npx clivly ping
159
- npx clivly doctor
236
+ ```ts
237
+ // Cloudflare Workers
238
+ export default {
239
+ scheduled: () => clivly.runScheduled(), // cron: one heartbeat + one sync
240
+ fetch: clivly.createClivlyHandler(), // or drive via an uptime ping
241
+ };
160
242
  ```
161
243
 
162
- In code, `await clivly.doctor()` returns the same structured read-only checks.
244
+ `runScheduled()` throws if a sync push fails, so a cron run is marked failed.
245
+ `createClivlyHandler()` returns `200` when the triggered run finishes
246
+ successfully and `500` otherwise, with `{ ok, runId, durationMs }` or
247
+ `{ ok: false, runId, error }` in the body — which is how Clivly learns the
248
+ outcome of a run it triggered.
163
249
 
164
- ## Serverless / edge
250
+ ## Verify the integration
165
251
 
166
- On request-scoped runtimes such as Cloudflare Workers, Vercel, or Lambda, do
167
- not call `start()`. Use `runScheduled()` or mount `createClivlyHandler()`
168
- instead:
252
+ ```bash
253
+ npx clivly status # the whole ladder
254
+ npx clivly status --config ./apps/web/clivly.config.ts # in a monorepo
255
+ ```
256
+
257
+ Put your instance in `clivly.config.ts` (`export default createClivlySDK({...})`)
258
+ so the CLI can find it. `ping`, `connect` and `doctor` remain as deprecated
259
+ aliases running parts of the same ladder.
260
+
261
+ In code, `await clivly.doctor()` returns `{ ok, checks }` — read-only, never
262
+ mutating. The checks it currently runs:
263
+
264
+ | Check | Verifies |
265
+ | --- | --- |
266
+ | API key present | `apiKey` is set |
267
+ | Entities configured | At least one entity |
268
+ | Sources configured | `source` is present and reachable |
269
+ | Concept coverage | Every configured concept has a source |
270
+ | Cursor / id columns | Drizzle sources page on a column that changes on edit |
271
+ | Sample fetch | `fetchPage` actually returns rows |
272
+ | Mapping dry-run | Each entity's compiled view runs |
273
+ | Custom object slugs | Custom object types are valid |
274
+ | Heartbeat | Clivly is reachable with this key |
275
+ | Namespace reachable | Every mapped table/column exists (needs `introspector`) |
276
+
277
+ `ok` is the AND of every non-skipped check. Checks can also come back
278
+ `warn: true` — a working setup with a risk worth stating, such as paging on a
279
+ column that never changes when a row is edited. **Warnings do not fail the
280
+ report**, because training people to ignore a red ladder on a working setup
281
+ would be worse.
282
+
283
+ `namespaceReady` in your config is *self-reported* and sent as-is on every
284
+ heartbeat; only `doctor()` with an `introspector` performs a live check:
169
285
 
170
286
  ```ts
171
- export default {
172
- scheduled: () => clivly.runScheduled(),
173
- fetch: clivly.createClivlyHandler(),
174
- };
287
+ import { drizzleIntrospector } from "clivly/drizzle";
288
+
289
+ createClivlySDK({ /* … */, introspector: drizzleIntrospector(db) });
175
290
  ```
176
291
 
177
- `runScheduled()` throws on a failed push so cron jobs surface failures.
178
- `createClivlyHandler()` returns `200` on success and `500` on a failed run.
292
+ ## Common errors and troubleshooting
293
+
294
+ | Symptom | Cause | Fix |
295
+ | --- | --- | --- |
296
+ | Nothing connects, no error | You imported the config but never called an entry point | Call `start()` / `runScheduled()`, or add `clivlyVite(sdk)` |
297
+ | `reason: "invalid_api_key"` | `CLIVLY_SECRET_KEY` missing, wrong, or revoked by a regeneration | Re-run `npx clivly login` |
298
+ | Sync works once on serverless, then stops | `start()`'s `setInterval` cannot persist | Use `runScheduled()` or `createClivlyHandler()` |
299
+ | Every cold start re-reads everything | The default cursor store is in-memory | Pass a persistent [`cursorStore`](#persisting-the-delta-cursor) |
300
+ | `401` on the tick route | Trigger secret differs between your app and Clivly | Redeploy with the current `CLIVLY_SYNC_TRIGGER_SECRET` |
301
+ | An entity syncs nothing, silently | `source` keyed by entity key instead of CRM concept | Key it `contacts` / `companies` / `deals` / `custom` |
302
+ | Rows sync on insert but never on edit | `cursorField` does not change on edit | Add an `updated_at` column and use it. `doctor()` warns about this |
303
+ | `Field mapping dry run … missing mapped column(s)` | You are on `clivly@0.7.3` or earlier, where `fromDrizzle` returned Drizzle property keys | Upgrade — see the upgrade note above |
304
+ | Push fails for one entity | See the thrown message | It names the HTTP status and what to check |
305
+ | Config throws at import on Workers | Something in `clivly.config.ts` touched the filesystem | See [the edge contract](../../docs/guides/connecting-to-clivly-cloud.md#the-edge-contract-what-may-go-in-clivlyconfigts) |
306
+
307
+ A failed push throws a message naming the cause, not a bare "push failed" — e.g.
308
+ *"the API key was rejected — check CLIVLY_API_KEY is set to a valid key for this
309
+ org"*, or *"couldn't reach Clivly at https://api.clivly.com"*.
310
+
311
+ Errors are also available as classes: `ClivlyError`, `ClivlyAuthError`,
312
+ `ClivlyNetworkError`, `ClivlyRateLimitError`. `ClivlyError.from(result)` turns a
313
+ failed `connect()` result into a throwable.
314
+
315
+ ## Advanced configuration
179
316
 
180
317
  ### Persisting the delta cursor
181
318
 
182
- By default the delta cursor lives in memory. For serverless runtimes, pass a
183
- persistent `cursorStore`:
319
+ Delta sync tracks a per-entity cursor so each run only pages rows changed since
320
+ the last one. By default that cursor lives in memory — fine for a long-lived
321
+ process, but **lost on every serverless cold start**, so a fresh isolate would
322
+ re-page the whole entity.
184
323
 
185
324
  ```ts
186
325
  const clivly = createClivlySDK({
187
326
  apiKey: process.env.CLIVLY_SECRET_KEY!,
188
327
  entities,
189
- source: { /* ... */ },
328
+ source: { /* … */ },
190
329
  cursorStore: {
330
+ // `SyncCursor` is { id: string; time: Date } — serialize `time` yourself.
191
331
  get: async (entity) => {
192
332
  const raw = await kv.get(`clivly:cursor:${entity}`);
193
333
  return raw ? { id: raw.id, time: new Date(raw.time) } : null;
@@ -195,30 +335,131 @@ const clivly = createClivlySDK({
195
335
  set: (entity, cursor) =>
196
336
  kv.put(
197
337
  `clivly:cursor:${entity}`,
198
- cursor ? { id: cursor.id, time: cursor.time.toISOString() } : null
338
+ cursor && { id: cursor.id, time: cursor.time.toISOString() }
199
339
  ),
200
340
  },
201
341
  });
202
342
  ```
203
343
 
204
- Delta sync is at-least-once. Without a persisted cursor after a cold start,
205
- rows may be re-sent; they are not silently skipped.
344
+ Delta sync is **at-least-once**: after a cold start with no persisted cursor,
345
+ rows since the last push may be re-sent (the server dedupes by id) — it never
346
+ silently skips rows. Use `sync({ mode: "full" })` when you need the server to
347
+ reconcile deletions (archive-on-leave); a delta cannot tell absence from
348
+ "unchanged".
206
349
 
207
- ## Known limitations
350
+ ### Sync ordering
351
+
352
+ `runSync` pushes **companies first**, then contacts, then deals, then custom
353
+ objects, so contact→company links resolve on the server.
354
+
355
+ ### Many-to-many company membership
208
356
 
209
- - `start()` is for long-lived runtimes only.
210
- - `fromDrizzle` is the first-class generated source path today.
211
- - The legacy flat `contactEntity` / `contactFields` config is still accepted but
212
- deprecated in favor of `defineClivlyConfig({ entities: ... })`.
357
+ If a mapping links contacts to companies through a join table
358
+ (`via: { through: … }`), that entity's source must return **one row per
359
+ membership**, each row carrying the join table's foreign-key column.
213
360
 
214
- ## More docs
361
+ ```ts
362
+ // Ada belongs to two organizations: two rows, differing only in org_id.
363
+ { id: "u1", full_name: "Ada", email: "ada@acme.test", org_id: "acme" }
364
+ { id: "u1", full_name: "Ada", email: "ada@acme.test", org_id: "globex" }
365
+ ```
366
+
367
+ This mirrors what the embedded model produces with `LEFT JOIN <join table>`, and
368
+ it is what lets Clivly keep one CRM row per membership instead of collapsing the
369
+ person onto whichever company happened to come first.
370
+
371
+ A person with no membership may omit the column entirely or send it as `null` —
372
+ both are accepted. But if **no** pushed row carries the column, the push is
373
+ rejected with `400 invalid_config`: silently keeping one membership would be
374
+ worse than failing, because the row counts look correct either way.
375
+
376
+ ### Retry policy
377
+
378
+ ```ts
379
+ retry: {
380
+ maxAttempts: 3, // total attempts including the first; minimum 1
381
+ baseDelayMs: 500, // doubled each attempt, plus jitter
382
+ }
383
+ ```
384
+
385
+ Network errors, `429` and `5xx` are retried; a `Retry-After` header on a `429`
386
+ is honoured. Other `4xx` responses return immediately.
387
+
388
+ ## Configuration reference
389
+
390
+ ### `createClivlySDK(config)`
391
+
392
+ | Field | Type | Default | Notes |
393
+ | --- | --- | --- | --- |
394
+ | `apiKey` | `string` | — | **Required.** `sk_live_…` |
395
+ | `apiUrl` | `string` | `https://api.clivly.com` | Non-default backend |
396
+ | `entities` | `ClivlyEntitiesConfig` | — | From `defineClivlyConfig({ entities })` |
397
+ | `schema` | `DiscoveredTable[]` | — | Use `discoverFromDrizzle(schema)` |
398
+ | `source` | `{ contacts, companies?, deals?, custom? }` | — | Keyed by CRM concept. `contacts` is required when `source` is present |
399
+ | `cursorStore` | `CursorStore` | in-memory | Persist on serverless |
400
+ | `heartbeatIntervalMs` | `number` | `60000` | |
401
+ | `sync.onBoot` | `boolean` | `true` | Only affects `start()` |
402
+ | `sync.intervalMs` | `number` | `heartbeatIntervalMs` | |
403
+ | `sync.batchSize` | `number` | `500` | Rows per page |
404
+ | `retry.maxAttempts` / `retry.baseDelayMs` | `number` | `3` / `500` | |
405
+ | `syncTrigger.path` / `.url` / `.secret` | `string` | — | See above |
406
+ | `verifyToken` | `string` | — | For `createAuthVerifyHandler`. **Nothing calls that endpoint today** |
407
+ | `introspector` | `NamespaceIntrospector` | — | `drizzleIntrospector(db)`. Used only by `doctor()` |
408
+ | `namespaceReady` | `boolean` | `false` | Self-reported; no live check |
409
+ | `env` | `Record<string, string \| undefined>` | `process.env` | For trigger-URL discovery in non-Node runtimes |
410
+ | `framework` / `orm` / `sdkVersion` | `string` | — | Reported for dashboard display |
411
+ | `contactEntity` / `contactFields` | `string` / `string[]` | — | **Deprecated.** Use `entities` |
412
+ | `experimental` | `object` | — | **Not implemented.** `tunnelToken` and `writeBack` are reserved and have no effect |
413
+
414
+ ### `ClivlySDK` methods
415
+
416
+ | Method | Returns | Notes |
417
+ | --- | --- | --- |
418
+ | `connect()` | `Promise<ClivlyConnectResult>` | One heartbeat, structured. Never throws |
419
+ | `heartbeat()` | `Promise<boolean>` | One heartbeat, boolean |
420
+ | `start()` | `Promise<void>` | Heartbeat + boot sync + timers. Long-lived hosts only |
421
+ | `stop()` | `void` | Clears the timers |
422
+ | `sync(options?)` | `Promise<void>` | `{ mode?: "delta" \| "full", runId?: string }`. Throws on push failure |
423
+ | `runScheduled(options?)` | `Promise<void>` | One heartbeat + one sync, no timers. Throws on push failure |
424
+ | `createClivlyHandler()` | `(Request) => Promise<Response>` | Mount at a route |
425
+ | `createAuthVerifyHandler(resolveUser)` | `(Request) => Promise<Response>` | `503` unless `verifyToken` is set |
426
+ | `doctor()` | `Promise<DoctorReport>` | `{ ok, checks }` |
427
+
428
+ ### `ClivlyConnectResult.reason`
429
+
430
+ `ok` · `invalid_api_key` (401) · `forbidden` (403) · `rate_limited` (429) ·
431
+ `server_error` (5xx) · `client_error` (other 4xx) · `network_error` (no
432
+ response).
433
+
434
+ ### Subpath exports
435
+
436
+ | From `clivly` | From `@clivly/sdk` | Contents |
437
+ | --- | --- | --- |
438
+ | `clivly/sdk` | `@clivly/sdk` | `createClivlySDK`, `defineClivlyConfig`, `createChatSessionHandler`, error classes, all types |
439
+ | `clivly/drizzle` | `@clivly/sdk/drizzle` | `fromDrizzle`, `discoverFromDrizzle`, `drizzleIntrospector` |
440
+ | `clivly/vite` | `@clivly/sdk/vite` | `clivlyVite` |
441
+ | — | `@clivly/sdk/chat-session` | `createChatSessionHandler` (also on the root) |
442
+
443
+ ## Known limitations
215
444
 
216
- - Cloud onboarding guide:
217
- [Connecting to Clivly Cloud](https://github.com/amani-joseph/clivly.com/blob/master/docs/guides/connecting-to-clivly-cloud.md)
218
- - CLI reference:
219
- [packages/cli/README.md](https://github.com/amani-joseph/clivly.com/blob/master/packages/cli/README.md)
220
- - Release notes:
221
- [CHANGELOG.md](https://github.com/amani-joseph/clivly.com/blob/master/CHANGELOG.md)
445
+ - `start()` is for long-lived runtimes only. On serverless/edge, use
446
+ `runScheduled()` or `createClivlyHandler()`.
447
+ - `fromDrizzle` is the only generated source path. Non-Drizzle hosts write
448
+ `fetchPage` by hand.
449
+ - The flat `contactEntity` / `contactFields` config still works but is
450
+ deprecated in favour of `defineClivlyConfig({ entities: … })`.
451
+ - `config.experimental` (tunnel token, CRM write-back) is **reserved and does
452
+ nothing today**.
453
+ - `createAuthVerifyHandler` is inert — no Clivly Cloud consumer calls
454
+ `/clivly/auth/verify` yet.
455
+
456
+ ## Related documentation
457
+
458
+ - **[Connecting to Clivly Cloud](../../docs/guides/connecting-to-clivly-cloud.md)** — the canonical end-to-end guide
459
+ - [`clivly` CLI README](../cli/README.md) — every command and flag
460
+ - [`@clivly/core` README](../core/README.md) — entity config, `$raw` filters
461
+ - [`STABILITY.md`](../../STABILITY.md) — import tiers before 1.0
462
+ - [`CHANGELOG.md`](../../CHANGELOG.md) — release notes
222
463
 
223
464
  ## License
224
465
 
@@ -1,4 +1,4 @@
1
- import { c as CreateChatSessionHandlerOptions } from "./types-DTaz5mLi.cjs";
1
+ import { c as CreateChatSessionHandlerOptions } from "./types-DPSn54S6.cjs";
2
2
  //#region src/chat-session.d.ts
3
3
  declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { c as CreateChatSessionHandlerOptions } from "./types-DTaz5mLi.mjs";
1
+ import { c as CreateChatSessionHandlerOptions } from "./types-DPSn54S6.mjs";
2
2
  //#region src/chat-session.d.ts
3
3
  declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
4
4
  //#endregion
package/dist/drizzle.cjs CHANGED
@@ -65,11 +65,15 @@ function fromDrizzle(db, table, opts) {
65
65
  const idColumn = columns[idField];
66
66
  if (!cursorColumn) throw new Error(`fromDrizzle: cursorField "${opts.cursorField}" is not a column on "${(0, drizzle_orm.getTableName)(table)}".`);
67
67
  if (!idColumn) throw new Error(`fromDrizzle: idField "${idField}" is not a column on "${(0, drizzle_orm.getTableName)(table)}".`);
68
+ const projection = {};
69
+ for (const column of Object.values(columns)) projection[column.name] = column;
70
+ const cursorColumnName = cursorColumn.name;
71
+ const idColumnName = idColumn.name;
68
72
  const source = {
69
73
  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)
74
+ cursorField: cursorColumnName,
75
+ idField: idColumnName,
76
+ 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
77
  };
74
78
  const meta = {
75
79
  columnKeys: Object.keys(columns),
@@ -1,4 +1,4 @@
1
- import { m as NamespaceIntrospector, p as SyncSource } from "./types-DTaz5mLi.cjs";
1
+ import { m as NamespaceIntrospector, p as SyncSource } from "./types-DPSn54S6.cjs";
2
2
  import { Table } from "drizzle-orm";
3
3
  import { discoverFromDrizzle } from "@clivly/core/drizzle";
4
4
  //#region src/drizzle.d.ts
@@ -1,4 +1,4 @@
1
- import { m as NamespaceIntrospector, p as SyncSource } from "./types-DTaz5mLi.mjs";
1
+ import { m as NamespaceIntrospector, p as SyncSource } from "./types-DPSn54S6.mjs";
2
2
  import { Table } from "drizzle-orm";
3
3
  import { discoverFromDrizzle } from "@clivly/core/drizzle";
4
4
  //#region src/drizzle.d.ts
package/dist/drizzle.mjs CHANGED
@@ -64,11 +64,15 @@ function fromDrizzle(db, table, opts) {
64
64
  const idColumn = columns[idField];
65
65
  if (!cursorColumn) throw new Error(`fromDrizzle: cursorField "${opts.cursorField}" is not a column on "${getTableName(table)}".`);
66
66
  if (!idColumn) throw new Error(`fromDrizzle: idField "${idField}" is not a column on "${getTableName(table)}".`);
67
+ const projection = {};
68
+ for (const column of Object.values(columns)) projection[column.name] = column;
69
+ const cursorColumnName = cursorColumn.name;
70
+ const idColumnName = idColumn.name;
67
71
  const source = {
68
72
  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)
73
+ cursorField: cursorColumnName,
74
+ idField: idColumnName,
75
+ 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
76
  };
73
77
  const meta = {
74
78
  columnKeys: Object.keys(columns),
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-DPSn54S6.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-DPSn54S6.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,
@@ -225,14 +225,33 @@ interface DoctorCheck {
225
225
  ok: boolean;
226
226
  /** True when the check could not run (e.g. a hand-written source). */
227
227
  skipped?: boolean;
228
+ /**
229
+ * True when the setup works but carries a risk worth stating.
230
+ *
231
+ * Distinct from `ok: false`, which means "this is broken, fix it before you
232
+ * rely on it". A warning is for a configuration that will run and sync, yet
233
+ * behaves in a way the developer probably did not intend — the cursor check
234
+ * below is the motivating case: syncing from an `id` column succeeds, mirrors
235
+ * every insert, and silently never re-syncs an edited row.
236
+ *
237
+ * Warnings do not fail `doctor`. Reporting them as failures would train
238
+ * people to ignore a red ladder on a working setup, which is worse than not
239
+ * reporting them at all.
240
+ */
241
+ warn?: boolean;
228
242
  }
229
243
  interface DoctorReport {
230
244
  checks: DoctorCheck[];
231
245
  /** AND of every non-skipped check's `ok`. */
232
246
  ok: boolean;
233
247
  }
234
- type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "network_error";
248
+ type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "server_too_old" | "network_error";
235
249
  interface ClivlyConnectResult {
250
+ /**
251
+ * When the org's app last heartbeated, or null if it never has. Set only by
252
+ * `ping()` — `connect()` IS a heartbeat, so the question is meaningless there.
253
+ */
254
+ appLastSeenAt?: string | null;
236
255
  ok: boolean;
237
256
  /** Org resolved from a successful heartbeat, when the server returns it. */
238
257
  org?: {
@@ -310,6 +329,14 @@ interface ClivlySDK {
310
329
  * loop and back-compat; use `connect()` when you need the failure reason.
311
330
  */
312
331
  heartbeat(): Promise<boolean>;
332
+ /**
333
+ * Read-only diagnostic probe. Proves the API key is valid and Clivly is
334
+ * reachable, and resolves the org — without reporting anything about the
335
+ * host app. Use this for `clivly status` and other diagnostics; use
336
+ * `connect()` only from the running app, which is entitled to report its
337
+ * own state.
338
+ */
339
+ ping(): Promise<ClivlyConnectResult>;
313
340
  /**
314
341
  * One-shot heartbeat + a single sync, with no keep-alive timers. The correct
315
342
  * entry point on serverless/edge (Workers, Vercel, Lambda), where `start()`'s
@@ -225,14 +225,33 @@ interface DoctorCheck {
225
225
  ok: boolean;
226
226
  /** True when the check could not run (e.g. a hand-written source). */
227
227
  skipped?: boolean;
228
+ /**
229
+ * True when the setup works but carries a risk worth stating.
230
+ *
231
+ * Distinct from `ok: false`, which means "this is broken, fix it before you
232
+ * rely on it". A warning is for a configuration that will run and sync, yet
233
+ * behaves in a way the developer probably did not intend — the cursor check
234
+ * below is the motivating case: syncing from an `id` column succeeds, mirrors
235
+ * every insert, and silently never re-syncs an edited row.
236
+ *
237
+ * Warnings do not fail `doctor`. Reporting them as failures would train
238
+ * people to ignore a red ladder on a working setup, which is worse than not
239
+ * reporting them at all.
240
+ */
241
+ warn?: boolean;
228
242
  }
229
243
  interface DoctorReport {
230
244
  checks: DoctorCheck[];
231
245
  /** AND of every non-skipped check's `ok`. */
232
246
  ok: boolean;
233
247
  }
234
- type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "network_error";
248
+ type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "server_too_old" | "network_error";
235
249
  interface ClivlyConnectResult {
250
+ /**
251
+ * When the org's app last heartbeated, or null if it never has. Set only by
252
+ * `ping()` — `connect()` IS a heartbeat, so the question is meaningless there.
253
+ */
254
+ appLastSeenAt?: string | null;
236
255
  ok: boolean;
237
256
  /** Org resolved from a successful heartbeat, when the server returns it. */
238
257
  org?: {
@@ -310,6 +329,14 @@ interface ClivlySDK {
310
329
  * loop and back-compat; use `connect()` when you need the failure reason.
311
330
  */
312
331
  heartbeat(): Promise<boolean>;
332
+ /**
333
+ * Read-only diagnostic probe. Proves the API key is valid and Clivly is
334
+ * reachable, and resolves the org — without reporting anything about the
335
+ * host app. Use this for `clivly status` and other diagnostics; use
336
+ * `connect()` only from the running app, which is entitled to report its
337
+ * own state.
338
+ */
339
+ ping(): Promise<ClivlyConnectResult>;
313
340
  /**
314
341
  * One-shot heartbeat + a single sync, with no keep-alive timers. The correct
315
342
  * entry point on serverless/edge (Workers, Vercel, Lambda), where `start()`'s
package/dist/vite.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ClivlySDK } from "./types-DTaz5mLi.cjs";
1
+ import { a as ClivlySDK } from "./types-DPSn54S6.cjs";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/vite.d.ts
4
4
  interface ClivlyViteOptions {
package/dist/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ClivlySDK } from "./types-DTaz5mLi.mjs";
1
+ import { a as ClivlySDK } from "./types-DPSn54S6.mjs";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/vite.d.ts
4
4
  interface ClivlyViteOptions {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clivly/sdk",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Clivly SDK — connect your app to Clivly Cloud (heartbeat, discovery, auth bridge).",
@@ -55,7 +55,7 @@
55
55
  "access": "public"
56
56
  },
57
57
  "dependencies": {
58
- "@clivly/core": "0.7.2"
58
+ "@clivly/core": "0.7.4"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "drizzle-orm": ">=0.30 || >=1.0.0-rc.0",