clivly 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +54 -3
  2. package/adapter-Cd6D_3JD.d.mts +46 -0
  3. package/adapter-Cy4q2CLs.d.cts +46 -0
  4. package/auth-adapter-CBOKDhlc.cjs +11 -0
  5. package/auth-adapter-CRBW4elj.d.mts +30 -0
  6. package/auth-adapter-CdLODn2p.d.cts +30 -0
  7. package/auth-adapter-wqnnEjo3.mjs +6 -0
  8. package/auth-better-auth.cjs +28 -0
  9. package/auth-better-auth.d.cts +33 -0
  10. package/auth-better-auth.d.mts +33 -0
  11. package/auth-better-auth.mjs +26 -0
  12. package/auth-clerk.cjs +34 -0
  13. package/auth-clerk.d.cts +32 -0
  14. package/auth-clerk.d.mts +32 -0
  15. package/auth-clerk.mjs +32 -0
  16. package/auth-workos.cjs +47 -0
  17. package/auth-workos.d.cts +30 -0
  18. package/auth-workos.d.mts +30 -0
  19. package/auth-workos.mjs +45 -0
  20. package/core-adapter.cjs +0 -0
  21. package/core-adapter.d.cts +2 -0
  22. package/core-adapter.d.mts +2 -0
  23. package/core-adapter.mjs +1 -0
  24. package/core-auth-adapter.cjs +3 -0
  25. package/core-auth-adapter.d.cts +2 -0
  26. package/core-auth-adapter.d.mts +2 -0
  27. package/core-auth-adapter.mjs +2 -0
  28. package/core-drizzle.cjs +32 -0
  29. package/core-drizzle.d.cts +21 -0
  30. package/core-drizzle.d.mts +21 -0
  31. package/core-drizzle.mjs +31 -0
  32. package/core-entity-config.cjs +13 -0
  33. package/core-entity-config.d.cts +2 -0
  34. package/core-entity-config.d.mts +2 -0
  35. package/core-entity-config.mjs +2 -0
  36. package/core-entity-heuristics.cjs +442 -0
  37. package/core-entity-heuristics.d.cts +68 -0
  38. package/core-entity-heuristics.d.mts +68 -0
  39. package/core-entity-heuristics.mjs +431 -0
  40. package/core-mapping-form.cjs +5 -0
  41. package/core-mapping-form.d.cts +2 -0
  42. package/core-mapping-form.d.mts +2 -0
  43. package/core-mapping-form.mjs +2 -0
  44. package/core-mapping-score.cjs +12 -0
  45. package/core-mapping-score.d.cts +2 -0
  46. package/core-mapping-score.d.mts +2 -0
  47. package/core-mapping-score.mjs +2 -0
  48. package/core-mappings-config.cjs +3 -0
  49. package/core-mappings-config.d.cts +2 -0
  50. package/core-mappings-config.d.mts +2 -0
  51. package/core-mappings-config.mjs +2 -0
  52. package/core-sync-engine.cjs +6 -0
  53. package/core-sync-engine.d.cts +2 -0
  54. package/core-sync-engine.d.mts +2 -0
  55. package/core-sync-engine.mjs +2 -0
  56. package/core-types.cjs +0 -0
  57. package/core-types.d.cts +2 -0
  58. package/core-types.d.mts +2 -0
  59. package/core-types.mjs +1 -0
  60. package/core-view-compiler.cjs +5 -0
  61. package/core-view-compiler.d.cts +2 -0
  62. package/core-view-compiler.d.mts +2 -0
  63. package/core-view-compiler.mjs +2 -0
  64. package/core.cjs +27 -0
  65. package/core.d.cts +9 -0
  66. package/core.d.mts +9 -0
  67. package/core.mjs +7 -0
  68. package/drizzle-meta-BGn0BqGb.cjs +9 -0
  69. package/drizzle-meta-CnC336L-.mjs +4 -0
  70. package/drizzle.cjs +107 -0
  71. package/drizzle.d.cts +28 -0
  72. package/drizzle.d.mts +28 -0
  73. package/drizzle.mjs +105 -0
  74. package/entity-config-Cvjo1cpv.cjs +4598 -0
  75. package/entity-config-D1DFyeUp.d.mts +2403 -0
  76. package/entity-config-DoR0khce.mjs +4533 -0
  77. package/entity-config-GczjD3y8.d.cts +2403 -0
  78. package/index.cjs +961 -0
  79. package/index.d.cts +57 -0
  80. package/index.d.mts +57 -0
  81. package/index.mjs +960 -0
  82. package/mapping-form-BHtPexzI.mjs +47 -0
  83. package/mapping-form-CUlFVfG8.d.cts +35 -0
  84. package/mapping-form-DdmDebC3.cjs +64 -0
  85. package/mapping-form-kjSiJaCX.d.mts +35 -0
  86. package/mapping-score-A2lRnlpk.d.mts +49 -0
  87. package/mapping-score-BJNe0lFn.mjs +87 -0
  88. package/mapping-score-BcjC0ZQs.d.cts +49 -0
  89. package/mapping-score-D9gfhtRu.cjs +146 -0
  90. package/mappings-config-CYPrzB3K.mjs +99 -0
  91. package/mappings-config-DTu_2cyx.cjs +104 -0
  92. package/mappings-config-DjRLCb2Q.d.cts +42 -0
  93. package/mappings-config-GxiYsSBQ.d.mts +42 -0
  94. package/namespace-probe-BtS0nXcr.d.cts +299 -0
  95. package/namespace-probe-CYMie-BI.d.mts +299 -0
  96. package/package.json +244 -21
  97. package/sdk-BZUn6wzs.mjs +764 -0
  98. package/sdk-CP_mYZa5.cjs +793 -0
  99. package/sdk.cjs +7 -0
  100. package/sdk.d.cts +33 -0
  101. package/sdk.d.mts +33 -0
  102. package/sdk.mjs +2 -0
  103. package/sync-engine-DUc0qWgo.cjs +230 -0
  104. package/sync-engine-DWnQPjV3.d.mts +183 -0
  105. package/sync-engine-DedXngop.mjs +207 -0
  106. package/sync-engine-uhfzKM-e.d.cts +183 -0
  107. package/types-BpsKVccL.d.cts +159 -0
  108. package/types-_qbJXMt_.d.mts +159 -0
  109. package/view-compiler-B4UYTvRM.d.cts +71 -0
  110. package/view-compiler-BHzbI9b7.cjs +202 -0
  111. package/view-compiler-CosFGar8.mjs +185 -0
  112. package/view-compiler-i_xFf-L0.d.mts +71 -0
  113. package/vite.cjs +38 -0
  114. package/vite.d.cts +23 -0
  115. package/vite.d.mts +23 -0
  116. package/vite.mjs +37 -0
  117. package/dist/index.mjs +0 -542
@@ -0,0 +1,104 @@
1
+ const require_entity_config = require("./entity-config-Cvjo1cpv.cjs");
2
+ //#region ../core/src/mappings-config.ts
3
+ const RESERVED_FIELD = "id";
4
+ /**
5
+ * Restrict a persisted field map to what the mirror can actually store: drop
6
+ * the reserved `id` key (for every concept) and, for materialized concepts
7
+ * (contact/company), any key that isn't canonical. This makes the pipeline
8
+ * resilient to legacy or mis-suggested field maps — a stray `id` no longer
9
+ * blocks the whole sync.
10
+ */
11
+ function canonicalFields(concept, fieldMap) {
12
+ const allowed = require_entity_config.CANONICAL_FIELDS[concept];
13
+ const result = {};
14
+ for (const [field, column] of Object.entries(fieldMap)) {
15
+ if (field === RESERVED_FIELD) continue;
16
+ if (allowed && !allowed.includes(field)) continue;
17
+ result[field] = column;
18
+ }
19
+ return result;
20
+ }
21
+ const DEFAULT_ROLE = "primary";
22
+ const ACTIVE_STATUS = "active";
23
+ function isEligible(row) {
24
+ return (row.status ?? ACTIVE_STATUS) === ACTIVE_STATUS && Object.keys(row.fieldMap ?? {}).length > 0;
25
+ }
26
+ /**
27
+ * Preferred key for a row: the bare source table when it backs a single entity,
28
+ * else role-suffixed so multiple roles on one table stay distinct and stable
29
+ * (the primary role keeps the bare name). Uniqueness is still enforced by the
30
+ * caller in case two rows land on the same preferred key.
31
+ */
32
+ function preferredKey(row, tableCounts) {
33
+ const role = row.role ?? DEFAULT_ROLE;
34
+ if ((tableCounts.get(row.sourceTable) ?? 0) <= 1) return row.sourceTable;
35
+ return role === DEFAULT_ROLE ? row.sourceTable : `${row.sourceTable}__${role}`;
36
+ }
37
+ function uniquify(base, used) {
38
+ if (!used.has(base)) {
39
+ used.add(base);
40
+ return base;
41
+ }
42
+ let suffix = 2;
43
+ while (used.has(`${base}__${suffix}`)) suffix++;
44
+ const key = `${base}__${suffix}`;
45
+ used.add(key);
46
+ return key;
47
+ }
48
+ function buildEntity(row, refIndex) {
49
+ const entity = {
50
+ concept: row.targetConcept,
51
+ source: row.sourceTable,
52
+ role: row.role ?? DEFAULT_ROLE,
53
+ fields: canonicalFields(row.targetConcept, row.fieldMap)
54
+ };
55
+ if (row.targetConcept === "custom" && row.targetObjectTypeId) entity.targetObjectTypeId = row.targetObjectTypeId;
56
+ if (row.filter && Object.keys(row.filter).length > 0) entity.filter = row.filter;
57
+ if (row.relationships && Object.keys(row.relationships).length > 0) {
58
+ const relationships = {};
59
+ for (const [name, spec] of Object.entries(row.relationships)) {
60
+ const rel = spec;
61
+ relationships[name] = {
62
+ entity: refIndex.get(rel.entity) ?? rel.entity,
63
+ via: rel.via
64
+ };
65
+ }
66
+ entity.relationships = relationships;
67
+ }
68
+ return entity;
69
+ }
70
+ /**
71
+ * Compile persisted mapping rows into a `ClivlyEntitiesConfig`. Only `active`
72
+ * rows with at least one mapped field are included; disabled/suggested rows and
73
+ * unmapped rows are skipped. Returns `{ entities: {} }` when nothing is
74
+ * eligible — a no-op the view compiler and sync engine both tolerate.
75
+ */
76
+ function mappingsToEntitiesConfig(rows) {
77
+ const eligible = rows.filter(isEligible);
78
+ const tableCounts = /* @__PURE__ */ new Map();
79
+ for (const row of eligible) tableCounts.set(row.sourceTable, (tableCounts.get(row.sourceTable) ?? 0) + 1);
80
+ const used = /* @__PURE__ */ new Set();
81
+ const tableAnchor = /* @__PURE__ */ new Map();
82
+ const assigned = [];
83
+ for (const row of eligible) {
84
+ const key = uniquify(preferredKey(row, tableCounts), used);
85
+ assigned.push({
86
+ row,
87
+ key
88
+ });
89
+ if ((row.role ?? DEFAULT_ROLE) === DEFAULT_ROLE || !tableAnchor.has(row.sourceTable)) tableAnchor.set(row.sourceTable, key);
90
+ }
91
+ const refIndex = /* @__PURE__ */ new Map();
92
+ for (const { key } of assigned) refIndex.set(key, key);
93
+ for (const [table, key] of tableAnchor) if (!refIndex.has(table)) refIndex.set(table, key);
94
+ const entities = {};
95
+ for (const { row, key } of assigned) entities[key] = buildEntity(row, refIndex);
96
+ return { entities };
97
+ }
98
+ //#endregion
99
+ Object.defineProperty(exports, "mappingsToEntitiesConfig", {
100
+ enumerable: true,
101
+ get: function() {
102
+ return mappingsToEntitiesConfig;
103
+ }
104
+ });
@@ -0,0 +1,42 @@
1
+ import { a as ClivlyEntitiesConfig } from "./entity-config-GczjD3y8.cjs";
2
+
3
+ //#region ../core/src/mappings-config.d.ts
4
+ /**
5
+ * Mappings → Entity Config bridge.
6
+ *
7
+ * `crm_entity_mappings` rows are the single source of truth for how a host
8
+ * schema maps onto Clivly's CRM concepts. This module compiles those rows into
9
+ * a `ClivlyEntitiesConfig` — the contract the view compiler and sync engine
10
+ * consume — so the persisted mapping and the runtime pipeline never diverge.
11
+ *
12
+ * The row model has no explicit entity-key column (it's keyed by
13
+ * `sourceTable + targetConcept + role`), but the config's `relationships`
14
+ * reference other entities *by key*. This builder therefore derives a stable
15
+ * key per row and resolves each relationship's `entity` reference through the
16
+ * same derivation — so a relationship stored as `entity: "<relatedTable>"`
17
+ * (the shape `mappings.suggest` produces) resolves to the right entity.
18
+ */
19
+ /**
20
+ * A persisted `crm_entity_mappings` row, narrowed to the columns the builder
21
+ * reads. Structurally compatible with the Drizzle row (jsonb columns typed
22
+ * loosely) so the API layer can pass `db.select()` results straight in.
23
+ */
24
+ interface EntityMappingRow {
25
+ fieldMap: Record<string, string>;
26
+ filter?: Record<string, unknown> | null;
27
+ relationships?: Record<string, unknown> | null;
28
+ role?: string | null;
29
+ sourceTable: string;
30
+ status?: string | null;
31
+ targetConcept: string;
32
+ targetObjectTypeId?: string | null;
33
+ }
34
+ /**
35
+ * Compile persisted mapping rows into a `ClivlyEntitiesConfig`. Only `active`
36
+ * rows with at least one mapped field are included; disabled/suggested rows and
37
+ * unmapped rows are skipped. Returns `{ entities: {} }` when nothing is
38
+ * eligible — a no-op the view compiler and sync engine both tolerate.
39
+ */
40
+ declare function mappingsToEntitiesConfig(rows: EntityMappingRow[]): ClivlyEntitiesConfig;
41
+ //#endregion
42
+ export { mappingsToEntitiesConfig as n, EntityMappingRow as t };
@@ -0,0 +1,42 @@
1
+ import { a as ClivlyEntitiesConfig } from "./entity-config-D1DFyeUp.mjs";
2
+
3
+ //#region ../core/src/mappings-config.d.ts
4
+ /**
5
+ * Mappings → Entity Config bridge.
6
+ *
7
+ * `crm_entity_mappings` rows are the single source of truth for how a host
8
+ * schema maps onto Clivly's CRM concepts. This module compiles those rows into
9
+ * a `ClivlyEntitiesConfig` — the contract the view compiler and sync engine
10
+ * consume — so the persisted mapping and the runtime pipeline never diverge.
11
+ *
12
+ * The row model has no explicit entity-key column (it's keyed by
13
+ * `sourceTable + targetConcept + role`), but the config's `relationships`
14
+ * reference other entities *by key*. This builder therefore derives a stable
15
+ * key per row and resolves each relationship's `entity` reference through the
16
+ * same derivation — so a relationship stored as `entity: "<relatedTable>"`
17
+ * (the shape `mappings.suggest` produces) resolves to the right entity.
18
+ */
19
+ /**
20
+ * A persisted `crm_entity_mappings` row, narrowed to the columns the builder
21
+ * reads. Structurally compatible with the Drizzle row (jsonb columns typed
22
+ * loosely) so the API layer can pass `db.select()` results straight in.
23
+ */
24
+ interface EntityMappingRow {
25
+ fieldMap: Record<string, string>;
26
+ filter?: Record<string, unknown> | null;
27
+ relationships?: Record<string, unknown> | null;
28
+ role?: string | null;
29
+ sourceTable: string;
30
+ status?: string | null;
31
+ targetConcept: string;
32
+ targetObjectTypeId?: string | null;
33
+ }
34
+ /**
35
+ * Compile persisted mapping rows into a `ClivlyEntitiesConfig`. Only `active`
36
+ * rows with at least one mapped field are included; disabled/suggested rows and
37
+ * unmapped rows are skipped. Returns `{ entities: {} }` when nothing is
38
+ * eligible — a no-op the view compiler and sync engine both tolerate.
39
+ */
40
+ declare function mappingsToEntitiesConfig(rows: EntityMappingRow[]): ClivlyEntitiesConfig;
41
+ //#endregion
42
+ export { mappingsToEntitiesConfig as n, EntityMappingRow as t };
@@ -0,0 +1,299 @@
1
+ import { a as ClivlyEntitiesConfig } from "./entity-config-GczjD3y8.cjs";
2
+
3
+ //#region ../sdk/src/drizzle-meta.d.ts
4
+ declare const DRIZZLE_META: "__clivly_drizzle_source_meta__";
5
+ interface DrizzleSourceMeta {
6
+ /** Drizzle property keys of every column on the source table. */
7
+ columnKeys: string[];
8
+ /** Schema-v2 typed column metadata derived from the Drizzle table. */
9
+ columnsMeta?: DiscoveredColumn[];
10
+ cursorField: string;
11
+ idField: string;
12
+ /** The backing table's real name, so discovery can key metadata by table. */
13
+ tableName?: string;
14
+ }
15
+ //#endregion
16
+ //#region ../sdk/src/types.d.ts
17
+ interface DiscoveredColumn {
18
+ isForeignKey?: boolean;
19
+ isPrimaryKey?: boolean;
20
+ name: string;
21
+ nullable?: boolean;
22
+ /** The column this FK points at, when it is a foreign key. */
23
+ references?: {
24
+ table: string;
25
+ column: string;
26
+ };
27
+ /** SQL/driver type, e.g. "text", "integer", "timestamp". */
28
+ type?: string;
29
+ }
30
+ interface DiscoveredTable {
31
+ columns: string[];
32
+ /** Schema-v2 typed column metadata (types, PK/FK, nullability). */
33
+ columnsMeta?: DiscoveredColumn[];
34
+ name: string;
35
+ /** Approximate source row count, when cheaply derivable. */
36
+ rowCount?: number;
37
+ }
38
+ interface ClivlySDKConfig {
39
+ /** Org-scoped API token (sk_live_…) from Settings → API keys. */
40
+ apiKey: string;
41
+ /** Clivly API base URL. Defaults to https://api.clivly.com. */
42
+ apiUrl?: string;
43
+ /**
44
+ * The host table Clivly treats as the contact entity.
45
+ * @deprecated Prefer `entities` — the same mapping-derived shape
46
+ * `crm_entity_mappings` (and `@clivly/core`'s `mappingsToEntitiesConfig`)
47
+ * produce, so the SDK, the mappings table, and the sync engine share one
48
+ * model. A bare `contactEntity` is treated as a single contact entity.
49
+ */
50
+ contactEntity?: string;
51
+ /** Which columns of the contact entity Clivly may read. */
52
+ contactFields?: string[];
53
+ /**
54
+ * Where per-entity delta cursors are persisted between syncs. Defaults to an
55
+ * in-memory store (fine for a long-lived process). On serverless/edge, pass a
56
+ * store backed by your own KV/DB so a cold start resumes delta sync instead of
57
+ * re-paging the whole entity. See `CursorStore`.
58
+ */
59
+ cursorStore?: CursorStore;
60
+ /**
61
+ * Declarative entity config — the single source of truth shared with
62
+ * `crm_entity_mappings`. When set, discovery and heartbeat are derived from
63
+ * it (each entity's `source` table + mapped columns), superseding the flat
64
+ * `contactEntity`.
65
+ */
66
+ entities?: ClivlyEntitiesConfig;
67
+ /**
68
+ * 🚧 Not implemented in 0.1.x. Reserved options for tunnel mode and CRM
69
+ * write-back — they have NO effect yet and land with the Cloudflare
70
+ * infrastructure. Grouped under `experimental` so the stable config surface
71
+ * above is unambiguous; nothing here is part of the supported API.
72
+ */
73
+ experimental?: {
74
+ /** Cloudflare Tunnel token — reserved for tunnel mode. Not wired up yet. */tunnelToken?: string; /** CRM write-back target — reserved. Not wired up yet. */
75
+ writeBack?: {
76
+ enabled?: boolean; /** Only crm_* tables are ever accepted; this narrows further. */
77
+ tables?: string[];
78
+ };
79
+ };
80
+ /** Reported to the portal so it can show the detected stack. */
81
+ framework?: string;
82
+ /** Heartbeat cadence in ms. Defaults to 60s. */
83
+ heartbeatIntervalMs?: number;
84
+ /**
85
+ * Optional live namespace probe, used on-demand by `doctor()`'s "Namespace
86
+ * reachable" check to verify every required source table + column is
87
+ * genuinely reachable. Not consulted by the heartbeat. Build one with
88
+ * `drizzleIntrospector(db)` from `@clivly/sdk/drizzle`.
89
+ */
90
+ introspector?: NamespaceIntrospector;
91
+ /**
92
+ * Self-reported readiness sent on every heartbeat as-is (no live check).
93
+ * For a real reachability check, configure `introspector` and run
94
+ * `doctor()`.
95
+ */
96
+ namespaceReady?: boolean;
97
+ orm?: string;
98
+ /**
99
+ * Network retry policy for outbound calls (heartbeat + sync push). Transient
100
+ * failures (network errors, HTTP 429, HTTP 5xx) are retried with exponential
101
+ * backoff + jitter; a `Retry-After` header on a 429 is honoured. Non-transient
102
+ * responses (e.g. 4xx other than 429) are returned immediately, not retried.
103
+ */
104
+ retry?: {
105
+ /** Total attempts including the first. Defaults to 3. Min 1. */maxAttempts?: number; /** Base backoff in ms (doubled each attempt). Defaults to 500. */
106
+ baseDelayMs?: number;
107
+ };
108
+ /** Tables/columns to report for entity discovery + mapping. */
109
+ schema?: DiscoveredTable[];
110
+ sdkVersion?: string;
111
+ /** Host entities to mirror into Clivly Cloud. */
112
+ source?: {
113
+ contacts: SyncSource;
114
+ companies?: SyncSource;
115
+ deals?: SyncSource; /** Org-defined custom objects to mirror. Each carries its object-type slug. */
116
+ custom?: Array<SyncSource & {
117
+ objectType: string;
118
+ }>;
119
+ };
120
+ sync?: {
121
+ onBoot?: boolean;
122
+ /**
123
+ * Sync cadence in ms for the background keep-alive loop. Defaults to
124
+ * `heartbeatIntervalMs` (60s) so sync and heartbeat share a tick unless you
125
+ * decouple them — e.g. a slow full-mirror alongside frequent heartbeats.
126
+ */
127
+ intervalMs?: number;
128
+ batchSize?: number;
129
+ };
130
+ /**
131
+ * The remote sync trigger: how Clivly Cloud asks this app to run a sync.
132
+ *
133
+ * Without it, cloud mode is push-only — Clivly can watch the app but can't
134
+ * start anything, so the dashboard's "Run sync" has nothing to call. With it,
135
+ * the SDK reports `url` on each heartbeat and requires every trigger request to
136
+ * be signed with `secret`.
137
+ */
138
+ syncTrigger?: {
139
+ /**
140
+ * Public URL of the route where `createClivlyHandler()` is mounted, e.g.
141
+ * `https://app.example.com/api/clivly/tick`. Reported to Clivly on each
142
+ * heartbeat; a URL set in the dashboard overrides it.
143
+ */
144
+ url?: string;
145
+ /**
146
+ * Signing secret (`whsec_…`) issued by Clivly under Integrations → Remote
147
+ * sync. When set, `createClivlyHandler()` rejects any request that isn't
148
+ * validly signed. Leave unset only if the route is already unreachable from
149
+ * the public internet.
150
+ */
151
+ secret?: string;
152
+ };
153
+ /**
154
+ * Shared secret Clivly Cloud presents (as `Authorization: Bearer <token>`) when
155
+ * calling the `/clivly/auth/verify` endpoint. Required for the verify handler to
156
+ * authenticate the caller; without it the handler fails closed (HTTP 503).
157
+ */
158
+ verifyToken?: string;
159
+ }
160
+ interface ClivlyUser {
161
+ email: string;
162
+ id: string;
163
+ name?: string;
164
+ }
165
+ interface DoctorCheck {
166
+ /** Human-readable outcome — what passed, or why it failed. */
167
+ detail: string;
168
+ /** Short label, e.g. "API key present". */
169
+ name: string;
170
+ /** True when the check passed. Ignored when `skipped` is true. */
171
+ ok: boolean;
172
+ /** True when the check could not run (e.g. a hand-written source). */
173
+ skipped?: boolean;
174
+ }
175
+ interface DoctorReport {
176
+ checks: DoctorCheck[];
177
+ /** AND of every non-skipped check's `ok`. */
178
+ ok: boolean;
179
+ }
180
+ type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "network_error";
181
+ interface ClivlyConnectResult {
182
+ ok: boolean;
183
+ /** Org resolved from a successful heartbeat, when the server returns it. */
184
+ org?: {
185
+ id?: string;
186
+ name?: string;
187
+ };
188
+ reason: ClivlyConnectReason;
189
+ /** Whether a retry could plausibly succeed (network, 429, 5xx). */
190
+ retryable: boolean;
191
+ /** HTTP status, or null when the request never completed (network error). */
192
+ status: number | null;
193
+ }
194
+ interface SyncCursor {
195
+ /** The row's id, breaking ties when timestamps collide. */
196
+ id: string;
197
+ /** The row's cursor-field value (typically `updated_at`). */
198
+ time: Date;
199
+ }
200
+ interface SyncSource {
201
+ cursorField: string;
202
+ entity: string;
203
+ fetchPage(args: {
204
+ since: SyncCursor | null;
205
+ limit: number;
206
+ }): Promise<Record<string, unknown>[]>;
207
+ /** Stable, unique tie-breaker column for keyset paging. Defaults to "id". */
208
+ idField?: string;
209
+ /** Set by `fromDrizzle`; lets `doctor` introspect the backing table. */
210
+ [DRIZZLE_META]?: DrizzleSourceMeta;
211
+ }
212
+ type SyncMode = "delta" | "full";
213
+ interface CursorStore {
214
+ get(entity: string): Promise<SyncCursor | null> | SyncCursor | null;
215
+ set(entity: string, cursor: SyncCursor | null): Promise<void> | void;
216
+ }
217
+ interface ClivlySDK {
218
+ /**
219
+ * Send a single heartbeat and report the outcome richly: `ok`, the HTTP
220
+ * `status` (null on network failure), a coarse `reason`, whether it's
221
+ * `retryable`, and the resolved `org` when the server returns it. Never throws
222
+ * — inspect the result, or turn a failure into an exception with
223
+ * `ClivlyError.from(result)`. Prefer this over `heartbeat()` for onboarding,
224
+ * health checks, and one-shot serverless calls.
225
+ */
226
+ connect(): Promise<ClivlyConnectResult>;
227
+ /**
228
+ * Build the `/clivly/auth/verify` handler the developer mounts in their app.
229
+ * Clivly's cloud calls it to validate a CRM user's identity against the host
230
+ * app's session. Pass a resolver that reads the host session from the request.
231
+ *
232
+ * The handler authenticates the caller against `config.verifyToken` (presented
233
+ * as `Authorization: Bearer <token>`) before invoking the resolver, so the
234
+ * endpoint can't be used by third parties to probe host sessions. It fails
235
+ * closed with HTTP 503 if `verifyToken` is unset (a missing config value, not a
236
+ * server fault — so it won't trip the host's 5xx error alerting).
237
+ */
238
+ createAuthVerifyHandler(resolveUser: (req: Request) => Promise<ClivlyUser | null> | ClivlyUser | null): (req: Request) => Promise<Response>;
239
+ /**
240
+ * A fetch handler to mount at a route. Each request runs one `runScheduled()`
241
+ * and returns JSON: 200 when the sync succeeded, 500 otherwise.
242
+ *
243
+ * Two callers use it: Clivly Cloud (when someone clicks "Run sync" — those
244
+ * requests are HMAC-signed and carry a run id), and the host's own scheduler
245
+ * (Workers cron, an uptime ping — no body).
246
+ *
247
+ * When `syncTrigger.secret` is set the handler rejects unsigned or
248
+ * badly-signed requests with 401. When it isn't, the route stays open to
249
+ * anyone who can reach it — set a secret if it's publicly routable.
250
+ */
251
+ createClivlyHandler(): (req: Request) => Promise<Response>;
252
+ /** Validate this setup end-to-end (read-only) before the first sync. */
253
+ doctor(): Promise<DoctorReport>;
254
+ /**
255
+ * Send a single heartbeat now. Returns true on success. Kept for the keep-alive
256
+ * loop and back-compat; use `connect()` when you need the failure reason.
257
+ */
258
+ heartbeat(): Promise<boolean>;
259
+ /**
260
+ * One-shot heartbeat + a single sync, with no keep-alive timers. The correct
261
+ * entry point on serverless/edge (Workers, Vercel, Lambda), where `start()`'s
262
+ * `setInterval` loop can't persist between invocations — call this from a
263
+ * scheduled/cron trigger. Throws if a sync push fails (so the run is marked
264
+ * failed); heartbeat is best-effort.
265
+ */
266
+ runScheduled(options?: {
267
+ mode?: SyncMode;
268
+ runId?: string;
269
+ }): Promise<void>;
270
+ /**
271
+ * Send the initial heartbeat and start the keep-alive loop. For long-lived
272
+ * hosts only — on serverless/edge the interval can't persist, so prefer
273
+ * `runScheduled()` / `createClivlyHandler()`. Emits a warning if a serverless
274
+ * runtime is detected.
275
+ */
276
+ start(): Promise<void>;
277
+ /** Stop the keep-alive loop. */
278
+ stop(): void;
279
+ /**
280
+ * Sync all configured sources now. `delta` (default) pages changed rows since
281
+ * the last cursor; `full` pushes each complete entity so the server can
282
+ * reconcile leavers (archive-on-leave). Throws if a push fails, so callers see
283
+ * the failure — the background keep-alive loop swallows and retries instead.
284
+ */
285
+ sync(options?: {
286
+ mode?: SyncMode;
287
+ runId?: string;
288
+ }): Promise<void>;
289
+ }
290
+ //#endregion
291
+ //#region ../sdk/src/namespace-probe.d.ts
292
+ interface NamespaceIntrospector {
293
+ /** All base table names in the reachable schema. */
294
+ listTables(): Promise<string[]>;
295
+ /** Prove a table is genuinely selectable (SELECT ... LIMIT 1). Throws if unreachable/denied. */
296
+ sampleSelect(table: string): Promise<void>;
297
+ }
298
+ //#endregion
299
+ export { ClivlySDKConfig as a, DiscoveredTable as c, SyncSource as d, ClivlySDK as i, DoctorCheck as l, ClivlyConnectReason as n, ClivlyUser as o, ClivlyConnectResult as r, CursorStore as s, NamespaceIntrospector as t, DoctorReport as u };