clivly 0.1.0 → 0.2.1

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 +63 -3
  2. package/adapter-nLfZpgIG.d.cts +40 -0
  3. package/adapter-xs04z0KX.d.mts +40 -0
  4. package/auth-adapter-CBOKDhlc.cjs +11 -0
  5. package/auth-adapter-FEOR1nx-.d.mts +30 -0
  6. package/auth-adapter-wqnnEjo3.mjs +6 -0
  7. package/auth-adapter-wvfGKsOJ.d.cts +30 -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 +926 -0
  79. package/index.d.cts +56 -0
  80. package/index.d.mts +56 -0
  81. package/index.mjs +925 -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 +224 -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-C4POUcvk.d.mts +158 -0
  108. package/types-LJTBhkcN.d.cts +158 -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 -193
package/sdk.cjs ADDED
@@ -0,0 +1,7 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk = require("./sdk-CP_mYZa5.cjs");
3
+ exports.ClivlyAuthError = require_sdk.ClivlyAuthError;
4
+ exports.ClivlyError = require_sdk.ClivlyError;
5
+ exports.ClivlyNetworkError = require_sdk.ClivlyNetworkError;
6
+ exports.ClivlyRateLimitError = require_sdk.ClivlyRateLimitError;
7
+ exports.createClivlySDK = require_sdk.createClivlySDK;
package/sdk.d.cts ADDED
@@ -0,0 +1,33 @@
1
+ import { a as ClivlySDKConfig, c as DiscoveredTable, i as ClivlySDK, l as DoctorCheck, n as ClivlyConnectReason, o as ClivlyUser, r as ClivlyConnectResult, s as CursorStore, u as DoctorReport } from "./namespace-probe-BtS0nXcr.cjs";
2
+
3
+ //#region ../sdk/src/errors.d.ts
4
+ declare class ClivlyError extends Error {
5
+ /** HTTP status, or null when the request never completed (network error). */
6
+ readonly status: number | null;
7
+ readonly reason: ClivlyConnectResult["reason"];
8
+ /** Whether a retry could plausibly succeed (network, 429, 5xx). */
9
+ readonly retryable: boolean;
10
+ constructor(result: ClivlyConnectResult, message?: string);
11
+ /**
12
+ * Build the error subclass matching a failed result's reason, or `null` when
13
+ * the result is `ok`.
14
+ */
15
+ static from(result: ClivlyConnectResult): ClivlyError | null;
16
+ }
17
+ /** The API key was rejected (401) or lacks access (403). Not retryable. */
18
+ declare class ClivlyAuthError extends ClivlyError {}
19
+ /** Rate limited (429). Retryable after backoff / `Retry-After`. */
20
+ declare class ClivlyRateLimitError extends ClivlyError {}
21
+ /** The request never reached the server (network/DNS/TLS). Retryable. */
22
+ declare class ClivlyNetworkError extends ClivlyError {}
23
+ //#endregion
24
+ //#region ../sdk/src/index.d.ts
25
+ /**
26
+ * Create the Clivly SDK. The implemented surface — heartbeat/discovery reporting
27
+ * and the auth-verify handler — connects a developer's app to a running Clivly
28
+ * backend today. Tunnel management and CRM write-back are scaffolded (see the
29
+ * clearly-marked TODOs) and land with the Cloudflare infrastructure.
30
+ */
31
+ declare function createClivlySDK(config: ClivlySDKConfig): ClivlySDK;
32
+ //#endregion
33
+ export { ClivlyAuthError, type ClivlyConnectReason, type ClivlyConnectResult, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, type ClivlySDK, type ClivlySDKConfig, type ClivlyUser, type CursorStore, type DiscoveredTable, type DoctorCheck, type DoctorReport, createClivlySDK };
package/sdk.d.mts ADDED
@@ -0,0 +1,33 @@
1
+ import { a as ClivlySDKConfig, c as DiscoveredTable, i as ClivlySDK, l as DoctorCheck, n as ClivlyConnectReason, o as ClivlyUser, r as ClivlyConnectResult, s as CursorStore, u as DoctorReport } from "./namespace-probe-CYMie-BI.mjs";
2
+
3
+ //#region ../sdk/src/errors.d.ts
4
+ declare class ClivlyError extends Error {
5
+ /** HTTP status, or null when the request never completed (network error). */
6
+ readonly status: number | null;
7
+ readonly reason: ClivlyConnectResult["reason"];
8
+ /** Whether a retry could plausibly succeed (network, 429, 5xx). */
9
+ readonly retryable: boolean;
10
+ constructor(result: ClivlyConnectResult, message?: string);
11
+ /**
12
+ * Build the error subclass matching a failed result's reason, or `null` when
13
+ * the result is `ok`.
14
+ */
15
+ static from(result: ClivlyConnectResult): ClivlyError | null;
16
+ }
17
+ /** The API key was rejected (401) or lacks access (403). Not retryable. */
18
+ declare class ClivlyAuthError extends ClivlyError {}
19
+ /** Rate limited (429). Retryable after backoff / `Retry-After`. */
20
+ declare class ClivlyRateLimitError extends ClivlyError {}
21
+ /** The request never reached the server (network/DNS/TLS). Retryable. */
22
+ declare class ClivlyNetworkError extends ClivlyError {}
23
+ //#endregion
24
+ //#region ../sdk/src/index.d.ts
25
+ /**
26
+ * Create the Clivly SDK. The implemented surface — heartbeat/discovery reporting
27
+ * and the auth-verify handler — connects a developer's app to a running Clivly
28
+ * backend today. Tunnel management and CRM write-back are scaffolded (see the
29
+ * clearly-marked TODOs) and land with the Cloudflare infrastructure.
30
+ */
31
+ declare function createClivlySDK(config: ClivlySDKConfig): ClivlySDK;
32
+ //#endregion
33
+ export { ClivlyAuthError, type ClivlyConnectReason, type ClivlyConnectResult, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, type ClivlySDK, type ClivlySDKConfig, type ClivlyUser, type CursorStore, type DiscoveredTable, type DoctorCheck, type DoctorReport, createClivlySDK };
package/sdk.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { a as ClivlyRateLimitError, i as ClivlyNetworkError, n as ClivlyAuthError, r as ClivlyError, t as createClivlySDK } from "./sdk-BZUn6wzs.mjs";
2
+ export { ClivlyAuthError, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, createClivlySDK };
@@ -0,0 +1,230 @@
1
+ const require_view_compiler = require("./view-compiler-BHzbI9b7.cjs");
2
+ //#region ../core/src/sync-engine.ts
3
+ /**
4
+ * Diff a view's rows against the current mirror population for one entity.
5
+ *
6
+ * - source row with no mirror row → create
7
+ * - source row with a live mirror row → update (overwrite identity fields)
8
+ * - source row with an archived mirror → restore (re-activate + update)
9
+ * - live mirror row absent from source → archive (soft delete, keep history)
10
+ * - archived mirror row absent from source → no-op
11
+ *
12
+ * Source rows are de-duplicated by the reconciliation key (first wins). In
13
+ * simple mode (default) the key is `sourceRef`. In composite mode — used for
14
+ * `through` (join-table) entities, where the compiled view fans a person out
15
+ * into one row per membership — the key is `(sourceRef, companyRef)`, so a
16
+ * person in several companies materializes one mirror row per company and a
17
+ * single membership leaving archives only that one row.
18
+ */
19
+ function reconcile(source, mirror, opts = {}) {
20
+ const keyOf = (sourceRef, companyRef) => opts.composite ? `${sourceRef}\0${companyRef ?? ""}` : sourceRef;
21
+ const seen = /* @__PURE__ */ new Set();
22
+ const rows = [];
23
+ for (const row of source) {
24
+ const key = keyOf(row.sourceRef, row.companyRef ?? null);
25
+ if (!seen.has(key)) {
26
+ seen.add(key);
27
+ rows.push(row);
28
+ }
29
+ }
30
+ const byKey = new Map(mirror.map((m) => [keyOf(m.sourceRef, m.companyRef), m]));
31
+ const liveKeys = /* @__PURE__ */ new Set();
32
+ const actions = [];
33
+ for (const row of rows) {
34
+ const companyRef = row.companyRef ?? null;
35
+ const key = keyOf(row.sourceRef, companyRef);
36
+ liveKeys.add(key);
37
+ const existing = byKey.get(key);
38
+ if (!existing) actions.push({
39
+ kind: "create",
40
+ sourceRef: row.sourceRef,
41
+ fields: row.fields,
42
+ companyRef
43
+ });
44
+ else if (existing.archivedAt) actions.push({
45
+ kind: "restore",
46
+ id: existing.id,
47
+ sourceRef: row.sourceRef,
48
+ fields: row.fields,
49
+ companyRef
50
+ });
51
+ else actions.push({
52
+ kind: "update",
53
+ id: existing.id,
54
+ sourceRef: row.sourceRef,
55
+ fields: row.fields,
56
+ companyRef
57
+ });
58
+ }
59
+ for (const m of mirror) {
60
+ const key = keyOf(m.sourceRef, m.companyRef);
61
+ if (!(liveKeys.has(key) || m.archivedAt)) actions.push({
62
+ kind: "archive",
63
+ id: m.id,
64
+ sourceRef: m.sourceRef
65
+ });
66
+ }
67
+ return actions;
68
+ }
69
+ const CONCEPT_ORDER = {
70
+ company: 0,
71
+ contact: 1
72
+ };
73
+ /** Companies before contacts, so contact company_refs resolve to a live mirror. */
74
+ function syncOrder(a, b) {
75
+ return (CONCEPT_ORDER[a.concept] ?? 99) - (CONCEPT_ORDER[b.concept] ?? 99);
76
+ }
77
+ async function resolveActions(store, actions) {
78
+ const refs = /* @__PURE__ */ new Set();
79
+ for (const action of actions) if (action.kind !== "archive" && action.companyRef) refs.add(action.companyRef);
80
+ const resolved = refs.size ? await store.resolveCompanyRefs([...refs]) : /* @__PURE__ */ new Map();
81
+ return actions.map((action) => {
82
+ if (action.kind === "archive") return action;
83
+ const companyId = action.companyRef ? resolved.get(action.companyRef) ?? null : null;
84
+ return {
85
+ kind: action.kind,
86
+ id: "id" in action ? action.id : "",
87
+ sourceRef: action.sourceRef,
88
+ fields: action.fields,
89
+ companyId,
90
+ companySourceRef: action.companyRef ?? null
91
+ };
92
+ });
93
+ }
94
+ function emptyTally() {
95
+ return {
96
+ create: 0,
97
+ update: 0,
98
+ restore: 0,
99
+ archive: 0
100
+ };
101
+ }
102
+ /**
103
+ * An entity whose company relationship is a `through` (join-table) join fans out
104
+ * into one source row per membership, so its mirror must be keyed compositely.
105
+ */
106
+ function isCompositeEntity(config, entityKey) {
107
+ const entity = config.entities[entityKey];
108
+ if (!entity?.relationships) return false;
109
+ return Object.values(entity.relationships).some((rel) => "through" in rel.via);
110
+ }
111
+ /**
112
+ * Run a full sync: compile the config's views, then reconcile + persist each,
113
+ * companies first. Returns per-entity and total action counts.
114
+ */
115
+ async function runSync(config, store, options = {}) {
116
+ const allViews = require_view_compiler.compileEntityViews(config, options).sort(syncOrder);
117
+ const views = options.sample ? allViews.filter((v) => v.entityKey === options.sample?.entityKey) : allViews;
118
+ const entities = [];
119
+ const totals = {
120
+ created: 0,
121
+ updated: 0,
122
+ restored: 0,
123
+ archived: 0
124
+ };
125
+ for (const view of views) {
126
+ const objectTypeId = config.entities[view.entityKey]?.targetObjectTypeId;
127
+ const [source, mirror] = await Promise.all([store.readView(view, options.sample ? { limit: 1 } : void 0), store.listMirror({
128
+ concept: view.concept,
129
+ role: view.role,
130
+ objectTypeId
131
+ })]);
132
+ const actions = reconcile(source, mirror, { composite: isCompositeEntity(config, view.entityKey) }).filter((a) => !(options.sample && a.kind === "archive"));
133
+ const persistActions = await resolveActions(store, actions);
134
+ await store.persist({
135
+ concept: view.concept,
136
+ role: view.role,
137
+ objectTypeId,
138
+ actions: persistActions
139
+ });
140
+ const counts = emptyTally();
141
+ for (const action of actions) counts[action.kind] += 1;
142
+ const result = {
143
+ entityKey: view.entityKey,
144
+ concept: view.concept,
145
+ role: view.role,
146
+ created: counts.create,
147
+ updated: counts.update,
148
+ restored: counts.restore,
149
+ archived: counts.archive
150
+ };
151
+ entities.push(result);
152
+ totals.created += result.created;
153
+ totals.updated += result.updated;
154
+ totals.restored += result.restored;
155
+ totals.archived += result.archived;
156
+ }
157
+ return {
158
+ entities,
159
+ totals
160
+ };
161
+ }
162
+ function isEmptyValue(value) {
163
+ return value === null || value === void 0 || value === "";
164
+ }
165
+ /**
166
+ * Sample-scoped data-quality warnings over projected preview rows. Each mapped
167
+ * (or required-but-unmapped) field yields at most one warning, by precedence:
168
+ * a required field empty in ≥1 row → `K/N` form; an optional field empty in
169
+ * ALL rows → all-empty form; zero source rows → a single table-level warning.
170
+ */
171
+ function computeSampleWarnings(rows, requiredFields, sourceTable) {
172
+ if (rows.length === 0) return [{ message: `no rows found in ${sourceTable}` }];
173
+ const required = new Set(requiredFields);
174
+ const fields = new Set(requiredFields);
175
+ for (const row of rows) for (const key of Object.keys(row.fields)) fields.add(key);
176
+ const warnings = [];
177
+ for (const field of [...fields].sort()) {
178
+ const emptyCount = rows.filter((row) => isEmptyValue(row.fields[field])).length;
179
+ if (required.has(field)) {
180
+ if (emptyCount > 0) warnings.push({
181
+ field,
182
+ message: `${field} empty in ${emptyCount}/${rows.length} sampled`
183
+ });
184
+ } else if (emptyCount === rows.length) warnings.push({
185
+ field,
186
+ message: `${field} is empty in all ${rows.length} sampled rows`
187
+ });
188
+ }
189
+ return warnings;
190
+ }
191
+ /**
192
+ * Zero-write preview: read ≤`limit` rows through the compiled view (a pure
193
+ * SELECT whose SQL already projects each row into its mapped fields) and
194
+ * compute sample warnings. Calls ONLY `store.readView` — never a write path —
195
+ * so it can never mutate the mirror. The distinct, write-one-row sibling is
196
+ * `runSync`'s sample mode (T13).
197
+ */
198
+ async function previewSync(store, view, opts) {
199
+ const rows = await store.readView(view, { limit: opts.limit });
200
+ return {
201
+ rows,
202
+ sampledCount: rows.length,
203
+ warnings: computeSampleWarnings(rows, opts.requiredFields, opts.sourceTable)
204
+ };
205
+ }
206
+ //#endregion
207
+ Object.defineProperty(exports, "computeSampleWarnings", {
208
+ enumerable: true,
209
+ get: function() {
210
+ return computeSampleWarnings;
211
+ }
212
+ });
213
+ Object.defineProperty(exports, "previewSync", {
214
+ enumerable: true,
215
+ get: function() {
216
+ return previewSync;
217
+ }
218
+ });
219
+ Object.defineProperty(exports, "reconcile", {
220
+ enumerable: true,
221
+ get: function() {
222
+ return reconcile;
223
+ }
224
+ });
225
+ Object.defineProperty(exports, "runSync", {
226
+ enumerable: true,
227
+ get: function() {
228
+ return runSync;
229
+ }
230
+ });
@@ -0,0 +1,183 @@
1
+ import { a as ClivlyEntitiesConfig } from "./entity-config-D1DFyeUp.mjs";
2
+ import { n as CompiledView, t as CompileOptions } from "./view-compiler-i_xFf-L0.mjs";
3
+
4
+ //#region ../core/src/sync-engine.d.ts
5
+ /**
6
+ * Sync engine (Phase 3) — materializes the read-only entity views into Clivly's
7
+ * own mirror tables (`crm_companies`, `crm_contacts`).
8
+ *
9
+ * The reconciliation is the heart of the design: rows present in a view are
10
+ * created or updated in the mirror; rows that *leave* a view (e.g. an owner
11
+ * demoted to a member) are **archived, not deleted**, so their deals/activities
12
+ * survive. Identity fields are host-owned and overwritten each run; Clivly-owned
13
+ * CRM fields are never touched here.
14
+ *
15
+ * `reconcile()` is a pure function and independently testable. `runSync()`
16
+ * orchestrates: compile views → for each (companies first, so contact
17
+ * `company_ref`s resolve to a live `crm_companies.id`) read the view, reconcile
18
+ * against the current mirror, resolve company refs, and persist. All DB I/O is
19
+ * behind the `SyncStore` port — core stays ORM-agnostic; the SDK/drizzle
20
+ * package provides the concrete store.
21
+ */
22
+ /** A row read from a compiled view (what Postgres returns). */
23
+ interface SourceRow {
24
+ /** Host-side company key from `<relationship>_ref`; resolved before persist. */
25
+ companyRef?: string | null;
26
+ /** Mapped identity fields (clivly field → value). */
27
+ fields: Record<string, string | null>;
28
+ /** The source primary key — becomes the mirror row's `source_ref`. */
29
+ sourceRef: string;
30
+ }
31
+ /** An existing mirror row, as far as reconciliation needs to know. */
32
+ interface MirrorRecord {
33
+ archivedAt: Date | null;
34
+ /** Host-side company key; only consulted in composite (join-table) mode. */
35
+ companyRef: string | null;
36
+ id: string;
37
+ sourceRef: string;
38
+ }
39
+ type SyncAction = {
40
+ kind: "create";
41
+ sourceRef: string;
42
+ fields: Record<string, string | null>;
43
+ companyRef: string | null;
44
+ } | {
45
+ kind: "update";
46
+ id: string;
47
+ sourceRef: string;
48
+ fields: Record<string, string | null>;
49
+ companyRef: string | null;
50
+ } | {
51
+ kind: "restore";
52
+ id: string;
53
+ sourceRef: string;
54
+ fields: Record<string, string | null>;
55
+ companyRef: string | null;
56
+ } | {
57
+ kind: "archive";
58
+ id: string;
59
+ sourceRef: string;
60
+ };
61
+ /** A persist action with the company ref resolved to a `crm_companies.id`. */
62
+ type PersistAction = {
63
+ kind: "create";
64
+ sourceRef: string;
65
+ fields: Record<string, string | null>;
66
+ companyId: string | null;
67
+ companySourceRef: string | null;
68
+ } | {
69
+ kind: "update";
70
+ id: string;
71
+ sourceRef: string;
72
+ fields: Record<string, string | null>;
73
+ companyId: string | null;
74
+ companySourceRef: string | null;
75
+ } | {
76
+ kind: "restore";
77
+ id: string;
78
+ sourceRef: string;
79
+ fields: Record<string, string | null>;
80
+ companyId: string | null;
81
+ companySourceRef: string | null;
82
+ } | {
83
+ kind: "archive";
84
+ id: string;
85
+ sourceRef: string;
86
+ };
87
+ /**
88
+ * Diff a view's rows against the current mirror population for one entity.
89
+ *
90
+ * - source row with no mirror row → create
91
+ * - source row with a live mirror row → update (overwrite identity fields)
92
+ * - source row with an archived mirror → restore (re-activate + update)
93
+ * - live mirror row absent from source → archive (soft delete, keep history)
94
+ * - archived mirror row absent from source → no-op
95
+ *
96
+ * Source rows are de-duplicated by the reconciliation key (first wins). In
97
+ * simple mode (default) the key is `sourceRef`. In composite mode — used for
98
+ * `through` (join-table) entities, where the compiled view fans a person out
99
+ * into one row per membership — the key is `(sourceRef, companyRef)`, so a
100
+ * person in several companies materializes one mirror row per company and a
101
+ * single membership leaving archives only that one row.
102
+ */
103
+ declare function reconcile(source: SourceRow[], mirror: MirrorRecord[], opts?: {
104
+ composite?: boolean;
105
+ }): SyncAction[];
106
+ /** DB I/O port. The concrete store lives in the SDK/drizzle package. */
107
+ interface SyncStore {
108
+ /** Current mirror rows for a concept + role (including archived). */
109
+ listMirror(input: {
110
+ concept: string;
111
+ role: string; /** Target custom-object type id, for `concept: "custom"` entities. */
112
+ objectTypeId?: string;
113
+ }): Promise<MirrorRecord[]>;
114
+ /** Apply the resolved actions to the mirror table for this concept + role. */
115
+ persist(input: {
116
+ concept: string;
117
+ role: string; /** Target custom-object type id, for `concept: "custom"` entities. */
118
+ objectTypeId?: string;
119
+ actions: PersistAction[];
120
+ }): Promise<void>;
121
+ /**
122
+ * Execute the view's SQL and return its rows. `opts.limit`, when given,
123
+ * caps the number of rows returned (used by `runSync`'s sample mode).
124
+ */
125
+ readView(view: CompiledView, opts?: {
126
+ limit?: number;
127
+ }): Promise<SourceRow[]>;
128
+ /** Map host-side company refs → `crm_companies.id` (already-synced companies only). */
129
+ resolveCompanyRefs(refs: string[]): Promise<Map<string, string>>;
130
+ }
131
+ interface EntitySyncResult {
132
+ archived: number;
133
+ concept: string;
134
+ created: number;
135
+ entityKey: string;
136
+ restored: number;
137
+ role: string;
138
+ updated: number;
139
+ }
140
+ interface SyncResult {
141
+ entities: EntitySyncResult[];
142
+ totals: {
143
+ created: number;
144
+ updated: number;
145
+ restored: number;
146
+ archived: number;
147
+ };
148
+ }
149
+ /**
150
+ * Run a full sync: compile the config's views, then reconcile + persist each,
151
+ * companies first. Returns per-entity and total action counts.
152
+ */
153
+ declare function runSync(config: ClivlyEntitiesConfig, store: SyncStore, options?: CompileOptions): Promise<SyncResult>;
154
+ interface PreviewWarning {
155
+ field?: string;
156
+ message: string;
157
+ }
158
+ interface PreviewResult {
159
+ rows: SourceRow[];
160
+ sampledCount: number;
161
+ warnings: PreviewWarning[];
162
+ }
163
+ /**
164
+ * Sample-scoped data-quality warnings over projected preview rows. Each mapped
165
+ * (or required-but-unmapped) field yields at most one warning, by precedence:
166
+ * a required field empty in ≥1 row → `K/N` form; an optional field empty in
167
+ * ALL rows → all-empty form; zero source rows → a single table-level warning.
168
+ */
169
+ declare function computeSampleWarnings(rows: SourceRow[], requiredFields: string[], sourceTable: string): PreviewWarning[];
170
+ /**
171
+ * Zero-write preview: read ≤`limit` rows through the compiled view (a pure
172
+ * SELECT whose SQL already projects each row into its mapped fields) and
173
+ * compute sample warnings. Calls ONLY `store.readView` — never a write path —
174
+ * so it can never mutate the mirror. The distinct, write-one-row sibling is
175
+ * `runSync`'s sample mode (T13).
176
+ */
177
+ declare function previewSync(store: SyncStore, view: CompiledView, opts: {
178
+ limit: number;
179
+ requiredFields: string[];
180
+ sourceTable: string;
181
+ }): Promise<PreviewResult>;
182
+ //#endregion
183
+ export { PreviewWarning as a, SyncResult as c, previewSync as d, reconcile as f, PreviewResult as i, SyncStore as l, MirrorRecord as n, SourceRow as o, runSync as p, PersistAction as r, SyncAction as s, EntitySyncResult as t, computeSampleWarnings as u };