clivly 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.
@@ -101,7 +101,10 @@ const CONCEPT_FIELDS = {
101
101
  "name",
102
102
  "full_name",
103
103
  "fullname",
104
- "display_name"
104
+ "display_name",
105
+ "first_name",
106
+ "firstname",
107
+ "given_name"
105
108
  ],
106
109
  required: false
107
110
  }, {
@@ -224,12 +227,28 @@ function suggestCursorField(columnKeys) {
224
227
  return null;
225
228
  }
226
229
  const MATERIALIZING = new Set(require_entity_config.MATERIALIZING_CONCEPTS);
230
+ const ENDS_IN_CONSONANT_Y = /[^aeiou]y$/;
231
+ const NEEDS_ES = /(s|x|z|ch|sh)$/;
232
+ const IRREGULAR_PLURALS = {
233
+ person: "people",
234
+ child: "children",
235
+ man: "men",
236
+ woman: "women"
237
+ };
238
+ function pluralize(name) {
239
+ const irregular = IRREGULAR_PLURALS[name];
240
+ if (irregular) return irregular;
241
+ if (ENDS_IN_CONSONANT_Y.test(name)) return `${name.slice(0, -1)}ies`;
242
+ if (NEEDS_ES.test(name)) return `${name}es`;
243
+ return `${name}s`;
244
+ }
227
245
  function matchesConcept(tableName, concept) {
228
246
  const normalized = tableName.toLowerCase();
229
247
  const entry = TABLE_PATTERNS.find((p) => p.concept === concept);
230
248
  if (!entry) return null;
231
- if (entry.names.includes(normalized)) return { exact: true };
232
- if (entry.names.some((name) => normalized.includes(name))) return { exact: false };
249
+ const candidates = [normalized, pluralize(normalized)];
250
+ if (candidates.some((candidate) => entry.names.includes(candidate))) return { exact: true };
251
+ if (entry.names.some((name) => candidates.some((candidate) => candidate.includes(name)))) return { exact: false };
233
252
  return null;
234
253
  }
235
254
  function metaFor(table, column) {
@@ -245,17 +264,18 @@ function scoreConcepts(table) {
245
264
  for (const concept of TARGET_CONCEPTS) {
246
265
  if (!MATERIALIZING.has(concept)) continue;
247
266
  const nameMatch = matchesConcept(table.name, concept);
248
- if (!nameMatch) continue;
267
+ const definingColumns = hasDefiningColumn(concept, table.columns);
268
+ if (!(nameMatch || definingColumns)) continue;
249
269
  let score = 0;
250
270
  const reasons = [];
251
- if (nameMatch.exact) {
271
+ if (nameMatch?.exact) {
252
272
  score += require_mapping_score.W.nameExact;
253
273
  reasons.push(`name matches "${table.name}"`);
254
- } else {
274
+ } else if (nameMatch) {
255
275
  score += require_mapping_score.W.nameSubstring;
256
276
  reasons.push(`name looks like ${concept}`);
257
277
  }
258
- if (hasDefiningColumn(concept, table.columns)) {
278
+ if (definingColumns) {
259
279
  score += require_mapping_score.W.definingColumn;
260
280
  reasons.push(`has the columns a ${concept} needs`);
261
281
  }
@@ -100,7 +100,10 @@ const CONCEPT_FIELDS = {
100
100
  "name",
101
101
  "full_name",
102
102
  "fullname",
103
- "display_name"
103
+ "display_name",
104
+ "first_name",
105
+ "firstname",
106
+ "given_name"
104
107
  ],
105
108
  required: false
106
109
  }, {
@@ -223,12 +226,28 @@ function suggestCursorField(columnKeys) {
223
226
  return null;
224
227
  }
225
228
  const MATERIALIZING = new Set(MATERIALIZING_CONCEPTS);
229
+ const ENDS_IN_CONSONANT_Y = /[^aeiou]y$/;
230
+ const NEEDS_ES = /(s|x|z|ch|sh)$/;
231
+ const IRREGULAR_PLURALS = {
232
+ person: "people",
233
+ child: "children",
234
+ man: "men",
235
+ woman: "women"
236
+ };
237
+ function pluralize(name) {
238
+ const irregular = IRREGULAR_PLURALS[name];
239
+ if (irregular) return irregular;
240
+ if (ENDS_IN_CONSONANT_Y.test(name)) return `${name.slice(0, -1)}ies`;
241
+ if (NEEDS_ES.test(name)) return `${name}es`;
242
+ return `${name}s`;
243
+ }
226
244
  function matchesConcept(tableName, concept) {
227
245
  const normalized = tableName.toLowerCase();
228
246
  const entry = TABLE_PATTERNS.find((p) => p.concept === concept);
229
247
  if (!entry) return null;
230
- if (entry.names.includes(normalized)) return { exact: true };
231
- if (entry.names.some((name) => normalized.includes(name))) return { exact: false };
248
+ const candidates = [normalized, pluralize(normalized)];
249
+ if (candidates.some((candidate) => entry.names.includes(candidate))) return { exact: true };
250
+ if (entry.names.some((name) => candidates.some((candidate) => candidate.includes(name)))) return { exact: false };
232
251
  return null;
233
252
  }
234
253
  function metaFor(table, column) {
@@ -244,17 +263,18 @@ function scoreConcepts(table) {
244
263
  for (const concept of TARGET_CONCEPTS) {
245
264
  if (!MATERIALIZING.has(concept)) continue;
246
265
  const nameMatch = matchesConcept(table.name, concept);
247
- if (!nameMatch) continue;
266
+ const definingColumns = hasDefiningColumn(concept, table.columns);
267
+ if (!(nameMatch || definingColumns)) continue;
248
268
  let score = 0;
249
269
  const reasons = [];
250
- if (nameMatch.exact) {
270
+ if (nameMatch?.exact) {
251
271
  score += W.nameExact;
252
272
  reasons.push(`name matches "${table.name}"`);
253
- } else {
273
+ } else if (nameMatch) {
254
274
  score += W.nameSubstring;
255
275
  reasons.push(`name looks like ${concept}`);
256
276
  }
257
- if (hasDefiningColumn(concept, table.columns)) {
277
+ if (definingColumns) {
258
278
  score += W.definingColumn;
259
279
  reasons.push(`has the columns a ${concept} needs`);
260
280
  }
@@ -0,0 +1,372 @@
1
+ import { a as ClivlyEntitiesConfig } from "./entity-config-DoUCXtq5.mjs";
2
+ //#region ../sdk/src/drizzle-meta.d.ts
3
+ declare const DRIZZLE_META: "__clivly_drizzle_source_meta__";
4
+ interface DrizzleSourceMeta {
5
+ /** Drizzle property keys of every column on the source table. */
6
+ columnKeys: string[];
7
+ /** Schema-v2 typed column metadata derived from the Drizzle table. */
8
+ columnsMeta?: DiscoveredColumn[];
9
+ cursorField: string;
10
+ idField: string;
11
+ /** The backing table's real name, so discovery can key metadata by table. */
12
+ tableName?: string;
13
+ }
14
+ //#endregion
15
+ //#region ../sdk/src/types.d.ts
16
+ interface DiscoveredColumn {
17
+ isForeignKey?: boolean;
18
+ isPrimaryKey?: boolean;
19
+ name: string;
20
+ nullable?: boolean;
21
+ /** The column this FK points at, when it is a foreign key. */
22
+ references?: {
23
+ table: string;
24
+ column: string;
25
+ };
26
+ /** SQL/driver type, e.g. "text", "integer", "timestamp". */
27
+ type?: string;
28
+ }
29
+ interface DiscoveredTable {
30
+ columns: string[];
31
+ /** Schema-v2 typed column metadata (types, PK/FK, nullability). */
32
+ columnsMeta?: DiscoveredColumn[];
33
+ name: string;
34
+ /** Approximate source row count, when cheaply derivable. */
35
+ rowCount?: number;
36
+ }
37
+ interface ClivlySDKConfig {
38
+ /** Org-scoped API token (sk_live_…) from Settings → API keys. */
39
+ apiKey: string;
40
+ /** Clivly API base URL. Defaults to https://api.clivly.com. */
41
+ apiUrl?: string;
42
+ /**
43
+ * The host table Clivly treats as the contact entity.
44
+ * @deprecated Prefer `entities` — the same mapping-derived shape
45
+ * `crm_entity_mappings` (and `@clivly/core`'s `mappingsToEntitiesConfig`)
46
+ * produce, so the SDK, the mappings table, and the sync engine share one
47
+ * model. A bare `contactEntity` is treated as a single contact entity.
48
+ */
49
+ contactEntity?: string;
50
+ /** Which columns of the contact entity Clivly may read. */
51
+ contactFields?: string[];
52
+ /**
53
+ * Where per-entity delta cursors are persisted between syncs. Defaults to an
54
+ * in-memory store (fine for a long-lived process). On serverless/edge, pass a
55
+ * store backed by your own KV/DB so a cold start resumes delta sync instead of
56
+ * re-paging the whole entity. See `CursorStore`.
57
+ */
58
+ cursorStore?: CursorStore;
59
+ /**
60
+ * Declarative entity config — the single source of truth shared with
61
+ * `crm_entity_mappings`. When set, discovery and heartbeat are derived from
62
+ * it (each entity's `source` table + mapped columns), superseding the flat
63
+ * `contactEntity`.
64
+ */
65
+ entities?: ClivlyEntitiesConfig;
66
+ /**
67
+ * Environment to read platform variables from when discovering the public
68
+ * trigger URL. Defaults to `process.env`. Injectable so tests and non-Node
69
+ * runtimes can supply their own.
70
+ */
71
+ env?: Record<string, string | undefined>;
72
+ /**
73
+ * 🚧 Not implemented in 0.1.x. Reserved options for tunnel mode and CRM
74
+ * write-back — they have NO effect yet and land with the Cloudflare
75
+ * infrastructure. Grouped under `experimental` so the stable config surface
76
+ * above is unambiguous; nothing here is part of the supported API.
77
+ */
78
+ experimental?: {
79
+ /** Cloudflare Tunnel token — reserved for tunnel mode. Not wired up yet. */
80
+ tunnelToken?: string;
81
+ /** CRM write-back target — reserved. Not wired up yet. */
82
+ writeBack?: {
83
+ enabled?: boolean;
84
+ /** Only crm_* tables are ever accepted; this narrows further. */
85
+ tables?: string[];
86
+ };
87
+ };
88
+ /** Reported to the portal so it can show the detected stack. */
89
+ framework?: string;
90
+ /** Heartbeat cadence in ms. Defaults to 60s. */
91
+ heartbeatIntervalMs?: number;
92
+ /**
93
+ * Optional live namespace probe, used on-demand by `doctor()`'s "Namespace
94
+ * reachable" check to verify every required source table + column is
95
+ * genuinely reachable. Not consulted by the heartbeat. Build one with
96
+ * `drizzleIntrospector(db)` from `@clivly/sdk/drizzle`.
97
+ */
98
+ introspector?: NamespaceIntrospector;
99
+ /**
100
+ * Self-reported readiness sent on every heartbeat as-is (no live check).
101
+ * For a real reachability check, configure `introspector` and run
102
+ * `doctor()`.
103
+ */
104
+ namespaceReady?: boolean;
105
+ orm?: string;
106
+ /**
107
+ * Network retry policy for outbound calls (heartbeat + sync push). Transient
108
+ * failures (network errors, HTTP 429, HTTP 5xx) are retried with exponential
109
+ * backoff + jitter; a `Retry-After` header on a 429 is honoured. Non-transient
110
+ * responses (e.g. 4xx other than 429) are returned immediately, not retried.
111
+ */
112
+ retry?: {
113
+ /** Total attempts including the first. Defaults to 3. Min 1. */
114
+ maxAttempts?: number;
115
+ /** Base backoff in ms (doubled each attempt). Defaults to 500. */
116
+ baseDelayMs?: number;
117
+ };
118
+ /** Tables/columns to report for entity discovery + mapping. */
119
+ schema?: DiscoveredTable[];
120
+ sdkVersion?: string;
121
+ /** Host entities to mirror into Clivly Cloud. */
122
+ source?: {
123
+ contacts: SyncSource;
124
+ companies?: SyncSource;
125
+ deals?: SyncSource;
126
+ /** Org-defined custom objects to mirror. Each carries its object-type slug. */
127
+ custom?: Array<SyncSource & {
128
+ objectType: string;
129
+ }>;
130
+ };
131
+ sync?: {
132
+ onBoot?: boolean;
133
+ /**
134
+ * Sync cadence in ms for the background keep-alive loop. Defaults to
135
+ * `heartbeatIntervalMs` (60s) so sync and heartbeat share a tick unless you
136
+ * decouple them — e.g. a slow full-mirror alongside frequent heartbeats.
137
+ */
138
+ intervalMs?: number;
139
+ batchSize?: number;
140
+ };
141
+ /**
142
+ * The remote sync trigger: how Clivly Cloud asks this app to run a sync.
143
+ *
144
+ * Without it, cloud mode is push-only — Clivly can watch the app but can't
145
+ * start anything, so the dashboard's "Run sync" has nothing to call. With it,
146
+ * the SDK reports `url` on each heartbeat and requires every trigger request to
147
+ * be signed with `secret`.
148
+ */
149
+ syncTrigger?: {
150
+ /**
151
+ * Public URL of the route where `createClivlyHandler()` is mounted, e.g.
152
+ * `https://app.example.com/api/clivly/tick`. Reported to Clivly on each
153
+ * heartbeat; a URL set in the dashboard overrides it.
154
+ *
155
+ * Optional — leave it unset and the SDK discovers the URL itself, from the
156
+ * hosting platform's environment or from the first request the route
157
+ * serves. Set it only to pin an address the SDK can't infer.
158
+ */
159
+ url?: string;
160
+ /**
161
+ * Path where `createClivlyHandler()` is mounted, e.g. `/api/clivly/tick`.
162
+ * Written by `clivly init`. Combined with the origin detected from the
163
+ * hosting platform so the SDK can report a trigger URL on its very first
164
+ * heartbeat, before any request has arrived to observe.
165
+ */
166
+ path?: string;
167
+ /**
168
+ * Signing secret (`whsec_…`) issued by Clivly under Integrations → Remote
169
+ * sync. When set, `createClivlyHandler()` rejects any request that isn't
170
+ * validly signed. Leave unset only if the route is already unreachable from
171
+ * the public internet.
172
+ */
173
+ secret?: string;
174
+ };
175
+ /**
176
+ * Shared secret Clivly Cloud presents (as `Authorization: Bearer <token>`) when
177
+ * calling the `/clivly/auth/verify` endpoint. Required for the verify handler to
178
+ * authenticate the caller; without it the handler fails closed (HTTP 503). No
179
+ * cloud consumer calls this endpoint yet — it is an inert primitive reserved for
180
+ * a future CRM/dashboard auth-passthrough.
181
+ */
182
+ verifyToken?: string;
183
+ }
184
+ interface ClivlyUser {
185
+ email: string;
186
+ id: string;
187
+ name?: string;
188
+ }
189
+ interface ChatWidgetVisitor {
190
+ email: string;
191
+ name: string;
192
+ }
193
+ interface ChatSessionRequestBody {
194
+ visitor: ChatWidgetVisitor;
195
+ visitorToken?: string | null;
196
+ widgetId: string;
197
+ }
198
+ interface CreateChatSessionHandlerOptions {
199
+ allowedOrigins?: string[];
200
+ apiKey: string;
201
+ apiUrl?: string;
202
+ fetchImpl?: typeof fetch;
203
+ /**
204
+ * Optional host-auth hook. When provided, it runs on the incoming browser
205
+ * request (session cookies intact) and, on a non-null `ClivlyUser`, the host
206
+ * vouches for that verified identity to Clivly Cloud. Absent/null/throwing =
207
+ * the visitor stays self-reported. Never fails the session.
208
+ */
209
+ resolveUser?: (req: Request) => Promise<ClivlyUser | null> | ClivlyUser | null;
210
+ }
211
+ interface DoctorCheck {
212
+ /** Human-readable outcome — what passed, or why it failed. */
213
+ detail: string;
214
+ /** Short label, e.g. "API key present". */
215
+ name: string;
216
+ /** True when the check passed. Ignored when `skipped` is true. */
217
+ ok: boolean;
218
+ /** True when the check could not run (e.g. a hand-written source). */
219
+ skipped?: boolean;
220
+ /**
221
+ * True when the setup works but carries a risk worth stating.
222
+ *
223
+ * Distinct from `ok: false`, which means "this is broken, fix it before you
224
+ * rely on it". A warning is for a configuration that will run and sync, yet
225
+ * behaves in a way the developer probably did not intend — the cursor check
226
+ * below is the motivating case: syncing from an `id` column succeeds, mirrors
227
+ * every insert, and silently never re-syncs an edited row.
228
+ *
229
+ * Warnings do not fail `doctor`. Reporting them as failures would train
230
+ * people to ignore a red ladder on a working setup, which is worse than not
231
+ * reporting them at all.
232
+ */
233
+ warn?: boolean;
234
+ }
235
+ interface DoctorReport {
236
+ checks: DoctorCheck[];
237
+ /** AND of every non-skipped check's `ok`. */
238
+ ok: boolean;
239
+ }
240
+ type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "server_too_old" | "network_error";
241
+ interface ClivlyConnectResult {
242
+ /**
243
+ * When the org's app last heartbeated, or null if it never has. Set only by
244
+ * `ping()` — `connect()` IS a heartbeat, so the question is meaningless there.
245
+ */
246
+ appLastSeenAt?: string | null;
247
+ ok: boolean;
248
+ /** Org resolved from a successful heartbeat, when the server returns it. */
249
+ org?: {
250
+ id?: string;
251
+ name?: string;
252
+ };
253
+ reason: ClivlyConnectReason;
254
+ /** Whether a retry could plausibly succeed (network, 429, 5xx). */
255
+ retryable: boolean;
256
+ /** HTTP status, or null when the request never completed (network error). */
257
+ status: number | null;
258
+ }
259
+ interface SyncCursor {
260
+ /** The row's id, breaking ties when timestamps collide. */
261
+ id: string;
262
+ /** The row's cursor-field value (typically `updated_at`). */
263
+ time: Date;
264
+ }
265
+ interface SyncSource {
266
+ cursorField: string;
267
+ entity: string;
268
+ fetchPage(args: {
269
+ since: SyncCursor | null;
270
+ limit: number;
271
+ }): Promise<Record<string, unknown>[]>;
272
+ /** Stable, unique tie-breaker column for keyset paging. Defaults to "id". */
273
+ idField?: string;
274
+ /** Set by `fromDrizzle`; lets `doctor` introspect the backing table. */
275
+ [DRIZZLE_META]?: DrizzleSourceMeta;
276
+ }
277
+ type SyncMode = "delta" | "full";
278
+ interface CursorStore {
279
+ get(entity: string): Promise<SyncCursor | null> | SyncCursor | null;
280
+ set(entity: string, cursor: SyncCursor | null): Promise<void> | void;
281
+ }
282
+ interface ClivlySDK {
283
+ /**
284
+ * Send a single heartbeat and report the outcome richly: `ok`, the HTTP
285
+ * `status` (null on network failure), a coarse `reason`, whether it's
286
+ * `retryable`, and the resolved `org` when the server returns it. Never throws
287
+ * — inspect the result, or turn a failure into an exception with
288
+ * `ClivlyError.from(result)`. Prefer this over `heartbeat()` for onboarding,
289
+ * health checks, and one-shot serverless calls.
290
+ */
291
+ connect(): Promise<ClivlyConnectResult>;
292
+ /**
293
+ * Build the `/clivly/auth/verify` handler the developer mounts in their app.
294
+ * Clivly's cloud calls it to validate a CRM user's identity against the host
295
+ * app's session. Pass a resolver that reads the host session from the request.
296
+ *
297
+ * The handler authenticates the caller against `config.verifyToken` (presented
298
+ * as `Authorization: Bearer <token>`) before invoking the resolver, so the
299
+ * endpoint can't be used by third parties to probe host sessions. It fails
300
+ * closed with HTTP 503 if `verifyToken` is unset (a missing config value, not a
301
+ * server fault — so it won't trip the host's 5xx error alerting).
302
+ */
303
+ createAuthVerifyHandler(resolveUser: (req: Request) => Promise<ClivlyUser | null> | ClivlyUser | null): (req: Request) => Promise<Response>;
304
+ /**
305
+ * A fetch handler to mount at a route. Each request runs one `runScheduled()`
306
+ * and returns JSON: 200 when the sync succeeded, 500 otherwise.
307
+ *
308
+ * Two callers use it: Clivly Cloud (when someone clicks "Run sync" — those
309
+ * requests are HMAC-signed and carry a run id), and the host's own scheduler
310
+ * (Workers cron, an uptime ping — no body).
311
+ *
312
+ * When `syncTrigger.secret` is set the handler rejects unsigned or
313
+ * badly-signed requests with 401. When it isn't, the route stays open to
314
+ * anyone who can reach it — set a secret if it's publicly routable.
315
+ */
316
+ createClivlyHandler(): (req: Request) => Promise<Response>;
317
+ /** Validate this setup end-to-end (read-only) before the first sync. */
318
+ doctor(): Promise<DoctorReport>;
319
+ /**
320
+ * Send a single heartbeat now. Returns true on success. Kept for the keep-alive
321
+ * loop and back-compat; use `connect()` when you need the failure reason.
322
+ */
323
+ heartbeat(): Promise<boolean>;
324
+ /**
325
+ * Read-only diagnostic probe. Proves the API key is valid and Clivly is
326
+ * reachable, and resolves the org — without reporting anything about the
327
+ * host app. Use this for `clivly status` and other diagnostics; use
328
+ * `connect()` only from the running app, which is entitled to report its
329
+ * own state.
330
+ */
331
+ ping(): Promise<ClivlyConnectResult>;
332
+ /**
333
+ * One-shot heartbeat + a single sync, with no keep-alive timers. The correct
334
+ * entry point on serverless/edge (Workers, Vercel, Lambda), where `start()`'s
335
+ * `setInterval` loop can't persist between invocations — call this from a
336
+ * scheduled/cron trigger. Throws if a sync push fails (so the run is marked
337
+ * failed); heartbeat is best-effort.
338
+ */
339
+ runScheduled(options?: {
340
+ mode?: SyncMode;
341
+ runId?: string;
342
+ }): Promise<void>;
343
+ /**
344
+ * Send the initial heartbeat and start the keep-alive loop. For long-lived
345
+ * hosts only — on serverless/edge the interval can't persist, so prefer
346
+ * `runScheduled()` / `createClivlyHandler()`. Emits a warning if a serverless
347
+ * runtime is detected.
348
+ */
349
+ start(): Promise<void>;
350
+ /** Stop the keep-alive loop. */
351
+ stop(): void;
352
+ /**
353
+ * Sync all configured sources now. `delta` (default) pages changed rows since
354
+ * the last cursor; `full` pushes each complete entity so the server can
355
+ * reconcile leavers (archive-on-leave). Throws if a push fails, so callers see
356
+ * the failure — the background keep-alive loop swallows and retries instead.
357
+ */
358
+ sync(options?: {
359
+ mode?: SyncMode;
360
+ runId?: string;
361
+ }): Promise<void>;
362
+ }
363
+ //#endregion
364
+ //#region ../sdk/src/namespace-probe.d.ts
365
+ interface NamespaceIntrospector {
366
+ /** All base table names in the reachable schema. */
367
+ listTables(): Promise<string[]>;
368
+ /** Prove a table is genuinely selectable (SELECT ... LIMIT 1). Throws if unreachable/denied. */
369
+ sampleSelect(table: string): Promise<void>;
370
+ }
371
+ //#endregion
372
+ export { ClivlyConnectResult as a, ClivlyUser as c, DiscoveredTable as d, DoctorCheck as f, ClivlyConnectReason as i, CreateChatSessionHandlerOptions as l, SyncSource as m, ChatSessionRequestBody as n, ClivlySDK as o, DoctorReport as p, ChatWidgetVisitor as r, ClivlySDKConfig as s, NamespaceIntrospector as t, CursorStore as u };