clivly 0.8.0 → 0.9.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 (112) hide show
  1. package/README.md +330 -134
  2. package/core-drizzle.cjs +3 -1
  3. package/core-drizzle.d.cts +3 -2
  4. package/core-drizzle.d.mts +3 -2
  5. package/core-drizzle.mjs +2 -2
  6. package/core-entity-config.cjs +2 -1
  7. package/core-entity-config.d.cts +2 -2
  8. package/core-entity-config.d.mts +2 -2
  9. package/core-entity-config.mjs +2 -2
  10. package/core-entity-heuristics.d.cts +3 -2
  11. package/core-entity-heuristics.d.mts +3 -2
  12. package/core-mapping-form.d.cts +1 -1
  13. package/core-mapping-form.d.mts +1 -1
  14. package/core-mappings-config.cjs +1 -1
  15. package/core-mappings-config.d.cts +1 -1
  16. package/core-mappings-config.d.mts +1 -1
  17. package/core-mappings-config.mjs +1 -1
  18. package/core-sync-engine.cjs +1 -1
  19. package/core-sync-engine.d.cts +1 -1
  20. package/core-sync-engine.d.mts +1 -1
  21. package/core-sync-engine.mjs +1 -1
  22. package/core-view-compiler.cjs +2 -1
  23. package/core-view-compiler.d.cts +2 -2
  24. package/core-view-compiler.d.mts +2 -2
  25. package/core-view-compiler.mjs +2 -2
  26. package/core.cjs +21 -5
  27. package/core.d.cts +7 -6
  28. package/core.d.mts +7 -6
  29. package/core.mjs +7 -6
  30. package/drizzle-3kvhkwO7.mjs +110 -0
  31. package/drizzle-DooDUGqO.d.mts +41 -0
  32. package/drizzle-bfjVzYR6.cjs +127 -0
  33. package/drizzle-jz0lrAgl.d.cts +41 -0
  34. package/drizzle.cjs +12 -40
  35. package/drizzle.d.cts +3 -11
  36. package/drizzle.d.mts +3 -11
  37. package/drizzle.mjs +12 -41
  38. package/entity-config-D08zAeFY.mjs +657 -0
  39. package/{entity-config-DoUCXtq5.d.cts → entity-config-fKQhimtD.d.cts} +263 -2
  40. package/{entity-config-DoUCXtq5.d.mts → entity-config-fKQhimtD.d.mts} +263 -2
  41. package/entity-config-nuXge6rY.cjs +778 -0
  42. package/index.cjs +768 -122
  43. package/index.d.cts +12 -0
  44. package/index.d.mts +12 -0
  45. package/index.mjs +769 -123
  46. package/internal-BGVUG312.mjs +68 -0
  47. package/internal-BLCK81kB.d.mts +72 -0
  48. package/internal-C-YBW2DB.d.cts +72 -0
  49. package/internal-D4HDi2GC.cjs +97 -0
  50. package/internal-drizzle.cjs +3 -1
  51. package/internal-drizzle.d.cts +2 -2
  52. package/internal-drizzle.d.mts +2 -2
  53. package/internal-drizzle.mjs +2 -2
  54. package/internal-entity-config.cjs +2 -1
  55. package/internal-entity-config.d.cts +2 -2
  56. package/internal-entity-config.d.mts +2 -2
  57. package/internal-entity-config.mjs +2 -2
  58. package/internal-entity-heuristics.cjs +28 -8
  59. package/internal-entity-heuristics.d.cts +2 -12
  60. package/internal-entity-heuristics.d.mts +2 -12
  61. package/internal-entity-heuristics.mjs +28 -8
  62. package/internal-mapping-form.d.cts +1 -1
  63. package/internal-mapping-form.d.mts +1 -1
  64. package/internal-mappings-config.cjs +1 -1
  65. package/internal-mappings-config.d.cts +1 -1
  66. package/internal-mappings-config.d.mts +1 -1
  67. package/internal-mappings-config.mjs +1 -1
  68. package/internal-sync-engine.cjs +1 -1
  69. package/internal-sync-engine.d.cts +1 -1
  70. package/internal-sync-engine.d.mts +1 -1
  71. package/internal-sync-engine.mjs +1 -1
  72. package/internal-view-compiler.cjs +2 -1
  73. package/internal-view-compiler.d.cts +2 -2
  74. package/internal-view-compiler.d.mts +2 -2
  75. package/internal-view-compiler.mjs +2 -2
  76. package/internal.cjs +21 -4
  77. package/internal.d.cts +7 -6
  78. package/internal.d.mts +7 -6
  79. package/internal.mjs +7 -5
  80. package/{mapping-form-D93lhHEc.d.mts → mapping-form-DhY0iFmN.d.cts} +1 -1
  81. package/{mapping-form-lfyEE7EJ.d.cts → mapping-form-Du36VZr1.d.mts} +1 -1
  82. package/{mappings-config-DsUa7-1w.d.mts → mappings-config-B1qNM8VL.d.cts} +7 -1
  83. package/{mappings-config-XmzB4dag.d.cts → mappings-config-BChZsany.d.mts} +7 -1
  84. package/{mappings-config-BsRADNRv.cjs → mappings-config-C8ynKmDK.cjs} +32 -6
  85. package/{mappings-config-Dbgxx3Nv.mjs → mappings-config-DNaYGyKN.mjs} +32 -6
  86. package/namespace-probe-BkUs8raG.d.mts +381 -0
  87. package/namespace-probe-aRFmpU85.d.cts +381 -0
  88. package/package.json +1 -1
  89. package/{entity-config-va2bkH5o.mjs → projection-C5244vGa.cjs} +130 -309
  90. package/{entity-config-D87rV-tE.cjs → projection-D7xmQP4S.mjs} +60 -381
  91. package/{sdk-iqOXeWIp.cjs → sdk-Bj-ZDf4u.cjs} +126 -28
  92. package/{sdk-C6WANW8M.mjs → sdk-BvRD2jAp.mjs} +126 -28
  93. package/sdk.cjs +2 -2
  94. package/sdk.d.cts +36 -1
  95. package/sdk.d.mts +36 -1
  96. package/sdk.mjs +2 -2
  97. package/{sync-engine-DGk_AeHJ.d.mts → sync-engine-DHQ7rXZe.d.mts} +2 -2
  98. package/{sync-engine-B7QIbXro.d.cts → sync-engine-DiPjH53O.d.cts} +2 -2
  99. package/{sync-engine-Do5ru3WF.mjs → sync-engine-SuxSzbZ4.mjs} +9 -2
  100. package/{sync-engine-CzEbpQGv.cjs → sync-engine-abE94g6X.cjs} +9 -2
  101. package/{view-compiler-BIwvm-o2.cjs → view-compiler-Blu4OXJ7.cjs} +103 -12
  102. package/{view-compiler-ChWr_Lml.mjs → view-compiler-CQx8TRrW.mjs} +98 -13
  103. package/{view-compiler-BWz0sGdm.d.cts → view-compiler-CcUwzZut.d.mts} +12 -2
  104. package/{view-compiler-Bn_EJJMO.d.mts → view-compiler-DqAdVxLq.d.cts} +12 -2
  105. package/vite.d.cts +1 -1
  106. package/vite.d.mts +1 -1
  107. package/drizzle-B89tLo4T.mjs +0 -31
  108. package/drizzle-CFOr9dU9.d.mts +0 -20
  109. package/drizzle-DiReZf6d.cjs +0 -36
  110. package/drizzle-DmeKSqeF.d.cts +0 -20
  111. package/types-CsL0rFYh.d.cts +0 -155
  112. package/types-CsL0rFYh.d.mts +0 -155
@@ -276,6 +276,46 @@ function errorMessage(error) {
276
276
  }
277
277
  //#endregion
278
278
  //#region ../sdk/src/doctor.ts
279
+ const TEMPORAL_CURSOR_TYPES = [
280
+ "timestamp",
281
+ "timestamptz",
282
+ "datetime",
283
+ "date",
284
+ "time"
285
+ ];
286
+ /**
287
+ * Warn when the sync cursor cannot observe an update.
288
+ *
289
+ * `clivly init` falls back to the primary key when a table has no
290
+ * `updated_at`-like column, and emits a TODO saying "confirm it is monotonic".
291
+ * A serial `id` *is* monotonic, so the note reads as satisfied — but monotonic
292
+ * is only half the requirement. An `id` never changes, so every insert mirrors
293
+ * and **no edit ever does**: a contact who changes their email keeps the old one
294
+ * in the CRM forever, with nothing anywhere reporting a problem.
295
+ *
296
+ * A code comment could not enforce this; a real integrator shipped exactly this
297
+ * configuration to production. This is the check that says so out loud.
298
+ */
299
+ function cursorMonotonicityCheck(source) {
300
+ const meta = source[DRIZZLE_META];
301
+ if (!meta?.columnsMeta) return null;
302
+ const index = meta.columnKeys.indexOf(meta.cursorField);
303
+ const type = meta.columnsMeta[index]?.type?.toLowerCase();
304
+ if (!type) return null;
305
+ const temporal = TEMPORAL_CURSOR_TYPES.some((t) => type.startsWith(t));
306
+ const name = `Cursor tracks updates (${source.entity})`;
307
+ if (temporal) return {
308
+ name,
309
+ ok: true,
310
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}) — edits re-sync.`
311
+ };
312
+ return {
313
+ name,
314
+ ok: true,
315
+ warn: true,
316
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}), which does not change when a row is edited — inserts will sync, edits will not. Add an updated_at column to "${meta.tableName ?? source.entity}" and set it as the cursor, or accept insert-only mirroring.`
317
+ };
318
+ }
279
319
  function configuredSources(config) {
280
320
  const sources = [];
281
321
  if (config.source?.contacts) sources.push(config.source.contacts);
@@ -304,32 +344,12 @@ async function mappingDryRunChecks(config) {
304
344
  return checks;
305
345
  }
306
346
  /**
307
- * Run the read-only setup checks and return a structured report. Every check
308
- * captures its own error into `detail` rather than throwing, so one failure never
309
- * hides the rest. `ok` is the AND of all non-skipped checks.
347
+ * Confirm each drizzle source actually has the cursor and id columns the sync
348
+ * pages on. Hand-written sources have no column metadata, so they are skipped
349
+ * rather than failed.
310
350
  */
311
- async function runDoctor(args) {
312
- const { config, connect } = args;
351
+ function cursorColumnChecks(sources) {
313
352
  const checks = [];
314
- const sources = configuredSources(config);
315
- const hasKey = Boolean(config.apiKey);
316
- checks.push({
317
- name: "API key present",
318
- ok: hasKey,
319
- detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
320
- });
321
- const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
322
- checks.push({
323
- name: "Entities configured",
324
- ok: entityCount > 0,
325
- detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
326
- });
327
- checks.push({
328
- name: "Sources configured",
329
- ok: sources.length > 0,
330
- detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
331
- });
332
- checks.push(checkConceptCoverage(config));
333
353
  for (const source of sources) {
334
354
  const meta = source[DRIZZLE_META];
335
355
  if (!meta) {
@@ -341,7 +361,7 @@ async function runDoctor(args) {
341
361
  });
342
362
  continue;
343
363
  }
344
- const idField = source.idField ?? "id";
364
+ const idField = meta.idField ?? source.idField ?? "id";
345
365
  const missing = [meta.cursorField, idField].filter((field) => !meta.columnKeys.includes(field));
346
366
  checks.push({
347
367
  name: `Cursor/id columns exist (${source.entity})`,
@@ -349,6 +369,14 @@ async function runDoctor(args) {
349
369
  detail: missing.length === 0 ? `"${source.entity}": ${meta.cursorField} + ${idField} present.` : `"${source.entity}" missing column(s): ${missing.join(", ")}.`
350
370
  });
351
371
  }
372
+ return checks;
373
+ }
374
+ /**
375
+ * Read one row from each source to prove the query works and that rows actually
376
+ * carry the cursor key. Fetch errors are captured as failures, never thrown.
377
+ */
378
+ async function sampleFetchChecks(sources) {
379
+ const checks = [];
352
380
  for (const source of sources) try {
353
381
  const rows = await source.fetchPage({
354
382
  since: null,
@@ -368,10 +396,45 @@ async function runDoctor(args) {
368
396
  detail: describeFetchError(source.entity, error)
369
397
  });
370
398
  }
399
+ return checks;
400
+ }
401
+ /**
402
+ * Run the read-only setup checks and return a structured report. Every check
403
+ * captures its own error into `detail` rather than throwing, so one failure never
404
+ * hides the rest. `ok` is the AND of all non-skipped checks.
405
+ */
406
+ async function runDoctor(args) {
407
+ const { config, probe } = args;
408
+ const checks = [];
409
+ const sources = configuredSources(config);
410
+ const hasKey = Boolean(config.apiKey);
411
+ checks.push({
412
+ name: "API key present",
413
+ ok: hasKey,
414
+ detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
415
+ });
416
+ const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
417
+ checks.push({
418
+ name: "Entities configured",
419
+ ok: entityCount > 0,
420
+ detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
421
+ });
422
+ checks.push({
423
+ name: "Sources configured",
424
+ ok: sources.length > 0,
425
+ detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
426
+ });
427
+ checks.push(checkConceptCoverage(config));
428
+ checks.push(...cursorColumnChecks(sources));
429
+ for (const source of sources) {
430
+ const check = cursorMonotonicityCheck(source);
431
+ if (check) checks.push(check);
432
+ }
433
+ checks.push(...await sampleFetchChecks(sources));
371
434
  checks.push(...await mappingDryRunChecks(config));
372
- const result = await connect();
435
+ const result = await probe();
373
436
  checks.push({
374
- name: "Heartbeat",
437
+ name: "Clivly reachable",
375
438
  ok: result.ok,
376
439
  detail: result.ok ? `Reached Clivly — org "${result.org?.name ?? "(unnamed)"}".` : `Could not connect (${result.reason}).`
377
440
  });
@@ -810,6 +873,7 @@ const UNAUTHORIZED_STATUS = 401;
810
873
  const FORBIDDEN_STATUS = 403;
811
874
  const CLIENT_ERROR_FLOOR = 400;
812
875
  const SERVICE_UNAVAILABLE_STATUS = 503;
876
+ const NOT_FOUND_STATUS = 404;
813
877
  function connectReason(status) {
814
878
  if (status === UNAUTHORIZED_STATUS) return "invalid_api_key";
815
879
  if (status === FORBIDDEN_STATUS) return "forbidden";
@@ -818,6 +882,10 @@ function connectReason(status) {
818
882
  if (status >= CLIENT_ERROR_FLOOR) return "client_error";
819
883
  return "server_error";
820
884
  }
885
+ function pingReason(status) {
886
+ if (status === NOT_FOUND_STATUS) return "server_too_old";
887
+ return connectReason(status);
888
+ }
821
889
  async function resolveOrg(response) {
822
890
  try {
823
891
  return (await response.json())?.org;
@@ -1049,9 +1117,38 @@ function createClivlySDK(config) {
1049
1117
  retryable: isRetryableStatus(response.status)
1050
1118
  };
1051
1119
  };
1120
+ const ping = async () => {
1121
+ const response = await fetcher(`${apiUrl}/clivly/sdk/ping`, {
1122
+ method: "GET",
1123
+ headers: { authorization: `Bearer ${config.apiKey}` }
1124
+ });
1125
+ if (response === null) return {
1126
+ ok: false,
1127
+ status: null,
1128
+ reason: "network_error",
1129
+ retryable: true
1130
+ };
1131
+ if (response.ok) {
1132
+ const body = await response.json().catch(() => ({}));
1133
+ return {
1134
+ ok: true,
1135
+ status: response.status,
1136
+ reason: "ok",
1137
+ retryable: false,
1138
+ org: body?.org,
1139
+ ..."appLastSeenAt" in body ? { appLastSeenAt: body.appLastSeenAt ?? null } : {}
1140
+ };
1141
+ }
1142
+ return {
1143
+ ok: false,
1144
+ status: response.status,
1145
+ reason: pingReason(response.status),
1146
+ retryable: isRetryableStatus(response.status)
1147
+ };
1148
+ };
1052
1149
  const doctor = () => runDoctor({
1053
1150
  config,
1054
- connect
1151
+ probe: ping
1055
1152
  });
1056
1153
  const runScheduled = async (options) => {
1057
1154
  await heartbeat();
@@ -1144,6 +1241,7 @@ function createClivlySDK(config) {
1144
1241
  stop,
1145
1242
  heartbeat,
1146
1243
  connect,
1244
+ ping,
1147
1245
  doctor,
1148
1246
  runScheduled,
1149
1247
  createClivlyHandler,
package/sdk.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_entity_config = require("./entity-config-D87rV-tE.cjs");
3
- const require_sdk = require("./sdk-iqOXeWIp.cjs");
2
+ const require_entity_config = require("./entity-config-nuXge6rY.cjs");
3
+ const require_sdk = require("./sdk-Bj-ZDf4u.cjs");
4
4
  exports.ClivlyAuthError = require_sdk.ClivlyAuthError;
5
5
  exports.ClivlyError = require_sdk.ClivlyError;
6
6
  exports.ClivlyNetworkError = require_sdk.ClivlyNetworkError;
package/sdk.d.cts CHANGED
@@ -1 +1,36 @@
1
- export {}
1
+ import { a as ClivlyEntitiesConfig, x as defineClivlyConfig } from "./entity-config-fKQhimtD.cjs";
2
+ import { a as ClivlyConnectResult, c as ClivlyUser, d as DiscoveredTable, f as DoctorCheck, i as ClivlyConnectReason, l as CreateChatSessionHandlerOptions, n as ChatSessionRequestBody, o as ClivlySDK, p as DoctorReport, r as ChatWidgetVisitor, s as ClivlySDKConfig, u as CursorStore } from "./namespace-probe-aRFmpU85.cjs";
3
+ //#region ../sdk/src/chat-session.d.ts
4
+ declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
5
+ //#endregion
6
+ //#region ../sdk/src/errors.d.ts
7
+ declare class ClivlyError extends Error {
8
+ /** HTTP status, or null when the request never completed (network error). */
9
+ readonly status: number | null;
10
+ readonly reason: ClivlyConnectResult["reason"];
11
+ /** Whether a retry could plausibly succeed (network, 429, 5xx). */
12
+ readonly retryable: boolean;
13
+ constructor(result: ClivlyConnectResult, message?: string);
14
+ /**
15
+ * Build the error subclass matching a failed result's reason, or `null` when
16
+ * the result is `ok`.
17
+ */
18
+ static from(result: ClivlyConnectResult): ClivlyError | null;
19
+ }
20
+ /** The API key was rejected (401) or lacks access (403). Not retryable. */
21
+ declare class ClivlyAuthError extends ClivlyError {}
22
+ /** Rate limited (429). Retryable after backoff / `Retry-After`. */
23
+ declare class ClivlyRateLimitError extends ClivlyError {}
24
+ /** The request never reached the server (network/DNS/TLS). Retryable. */
25
+ declare class ClivlyNetworkError extends ClivlyError {}
26
+ //#endregion
27
+ //#region ../sdk/src/index.d.ts
28
+ /**
29
+ * Create the Clivly SDK. The implemented surface — heartbeat/discovery reporting
30
+ * and the auth-verify handler — connects a developer's app to a running Clivly
31
+ * backend today. Tunnel management and CRM write-back are scaffolded (see the
32
+ * clearly-marked TODOs) and land with the Cloudflare infrastructure.
33
+ */
34
+ declare function createClivlySDK(config: ClivlySDKConfig): ClivlySDK;
35
+ //#endregion
36
+ export { type ChatSessionRequestBody, type ChatWidgetVisitor, ClivlyAuthError, type ClivlyConnectReason, type ClivlyConnectResult, type ClivlyEntitiesConfig, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, type ClivlySDK, type ClivlySDKConfig, type ClivlyUser, type CreateChatSessionHandlerOptions, type CursorStore, type DiscoveredTable, type DoctorCheck, type DoctorReport, createChatSessionHandler, createClivlySDK, defineClivlyConfig };
package/sdk.d.mts CHANGED
@@ -1 +1,36 @@
1
- export {}
1
+ import { a as ClivlyEntitiesConfig, x as defineClivlyConfig } from "./entity-config-fKQhimtD.mjs";
2
+ import { a as ClivlyConnectResult, c as ClivlyUser, d as DiscoveredTable, f as DoctorCheck, i as ClivlyConnectReason, l as CreateChatSessionHandlerOptions, n as ChatSessionRequestBody, o as ClivlySDK, p as DoctorReport, r as ChatWidgetVisitor, s as ClivlySDKConfig, u as CursorStore } from "./namespace-probe-BkUs8raG.mjs";
3
+ //#region ../sdk/src/chat-session.d.ts
4
+ declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
5
+ //#endregion
6
+ //#region ../sdk/src/errors.d.ts
7
+ declare class ClivlyError extends Error {
8
+ /** HTTP status, or null when the request never completed (network error). */
9
+ readonly status: number | null;
10
+ readonly reason: ClivlyConnectResult["reason"];
11
+ /** Whether a retry could plausibly succeed (network, 429, 5xx). */
12
+ readonly retryable: boolean;
13
+ constructor(result: ClivlyConnectResult, message?: string);
14
+ /**
15
+ * Build the error subclass matching a failed result's reason, or `null` when
16
+ * the result is `ok`.
17
+ */
18
+ static from(result: ClivlyConnectResult): ClivlyError | null;
19
+ }
20
+ /** The API key was rejected (401) or lacks access (403). Not retryable. */
21
+ declare class ClivlyAuthError extends ClivlyError {}
22
+ /** Rate limited (429). Retryable after backoff / `Retry-After`. */
23
+ declare class ClivlyRateLimitError extends ClivlyError {}
24
+ /** The request never reached the server (network/DNS/TLS). Retryable. */
25
+ declare class ClivlyNetworkError extends ClivlyError {}
26
+ //#endregion
27
+ //#region ../sdk/src/index.d.ts
28
+ /**
29
+ * Create the Clivly SDK. The implemented surface — heartbeat/discovery reporting
30
+ * and the auth-verify handler — connects a developer's app to a running Clivly
31
+ * backend today. Tunnel management and CRM write-back are scaffolded (see the
32
+ * clearly-marked TODOs) and land with the Cloudflare infrastructure.
33
+ */
34
+ declare function createClivlySDK(config: ClivlySDKConfig): ClivlySDK;
35
+ //#endregion
36
+ export { type ChatSessionRequestBody, type ChatWidgetVisitor, ClivlyAuthError, type ClivlyConnectReason, type ClivlyConnectResult, type ClivlyEntitiesConfig, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, type ClivlySDK, type ClivlySDKConfig, type ClivlyUser, type CreateChatSessionHandlerOptions, type CursorStore, type DiscoveredTable, type DoctorCheck, type DoctorReport, createChatSessionHandler, createClivlySDK, defineClivlyConfig };
package/sdk.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { o as defineClivlyConfig } from "./entity-config-va2bkH5o.mjs";
2
- import { a as ClivlyRateLimitError, i as ClivlyNetworkError, n as ClivlyAuthError, o as createChatSessionHandler, r as ClivlyError, t as createClivlySDK } from "./sdk-C6WANW8M.mjs";
1
+ import { o as defineClivlyConfig } from "./entity-config-D08zAeFY.mjs";
2
+ import { a as ClivlyRateLimitError, i as ClivlyNetworkError, n as ClivlyAuthError, o as createChatSessionHandler, r as ClivlyError, t as createClivlySDK } from "./sdk-BvRD2jAp.mjs";
3
3
  export { ClivlyAuthError, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, createChatSessionHandler, createClivlySDK, defineClivlyConfig };
@@ -1,5 +1,5 @@
1
- import { a as ClivlyEntitiesConfig } from "./entity-config-DoUCXtq5.mjs";
2
- import { n as CompiledView, t as CompileOptions } from "./view-compiler-Bn_EJJMO.mjs";
1
+ import { a as ClivlyEntitiesConfig } from "./entity-config-fKQhimtD.mjs";
2
+ import { n as CompiledView, t as CompileOptions } from "./view-compiler-CcUwzZut.mjs";
3
3
  //#region ../core/src/sync-engine.d.ts
4
4
  /**
5
5
  * Sync engine (Phase 3) — materializes the read-only entity views into Clivly's
@@ -1,5 +1,5 @@
1
- import { a as ClivlyEntitiesConfig } from "./entity-config-DoUCXtq5.cjs";
2
- import { n as CompiledView, t as CompileOptions } from "./view-compiler-BWz0sGdm.cjs";
1
+ import { a as ClivlyEntitiesConfig } from "./entity-config-fKQhimtD.cjs";
2
+ import { n as CompiledView, t as CompileOptions } from "./view-compiler-DqAdVxLq.cjs";
3
3
  //#region ../core/src/sync-engine.d.ts
4
4
  /**
5
5
  * Sync engine (Phase 3) — materializes the read-only entity views into Clivly's
@@ -1,4 +1,4 @@
1
- import { r as compileEntityViews } from "./view-compiler-ChWr_Lml.mjs";
1
+ import { r as compileEntityViews } from "./view-compiler-CQx8TRrW.mjs";
2
2
  //#region ../core/src/sync-engine.ts
3
3
  /**
4
4
  * Diff a view's rows against the current mirror population for one entity.
@@ -170,10 +170,17 @@ function isEmptyValue(value) {
170
170
  */
171
171
  function computeSampleWarnings(rows, requiredFields, sourceTable) {
172
172
  if (rows.length === 0) return [{ message: `no rows found in ${sourceTable}` }];
173
+ const seenRefs = /* @__PURE__ */ new Set();
174
+ const duplicateRefs = /* @__PURE__ */ new Set();
175
+ for (const row of rows) {
176
+ if (seenRefs.has(row.sourceRef)) duplicateRefs.add(row.sourceRef);
177
+ seenRefs.add(row.sourceRef);
178
+ }
179
+ const identityWarnings = duplicateRefs.size > 0 ? [{ message: `duplicate id in ${duplicateRefs.size} of ${rows.length} sampled rows — identity is not unique, so sync would collapse these into one record` }] : [];
173
180
  const required = new Set(requiredFields);
174
181
  const fields = new Set(requiredFields);
175
182
  for (const row of rows) for (const key of Object.keys(row.fields)) fields.add(key);
176
- const warnings = [];
183
+ const warnings = [...identityWarnings];
177
184
  for (const field of [...fields].sort()) {
178
185
  const emptyCount = rows.filter((row) => isEmptyValue(row.fields[field])).length;
179
186
  if (required.has(field)) {
@@ -1,4 +1,4 @@
1
- const require_view_compiler = require("./view-compiler-BIwvm-o2.cjs");
1
+ const require_view_compiler = require("./view-compiler-Blu4OXJ7.cjs");
2
2
  //#region ../core/src/sync-engine.ts
3
3
  /**
4
4
  * Diff a view's rows against the current mirror population for one entity.
@@ -170,10 +170,17 @@ function isEmptyValue(value) {
170
170
  */
171
171
  function computeSampleWarnings(rows, requiredFields, sourceTable) {
172
172
  if (rows.length === 0) return [{ message: `no rows found in ${sourceTable}` }];
173
+ const seenRefs = /* @__PURE__ */ new Set();
174
+ const duplicateRefs = /* @__PURE__ */ new Set();
175
+ for (const row of rows) {
176
+ if (seenRefs.has(row.sourceRef)) duplicateRefs.add(row.sourceRef);
177
+ seenRefs.add(row.sourceRef);
178
+ }
179
+ const identityWarnings = duplicateRefs.size > 0 ? [{ message: `duplicate id in ${duplicateRefs.size} of ${rows.length} sampled rows — identity is not unique, so sync would collapse these into one record` }] : [];
173
180
  const required = new Set(requiredFields);
174
181
  const fields = new Set(requiredFields);
175
182
  for (const row of rows) for (const key of Object.keys(row.fields)) fields.add(key);
176
- const warnings = [];
183
+ const warnings = [...identityWarnings];
177
184
  for (const field of [...fields].sort()) {
178
185
  const emptyCount = rows.filter((row) => isEmptyValue(row.fields[field])).length;
179
186
  if (required.has(field)) {
@@ -1,3 +1,58 @@
1
+ const require_projection = require("./projection-C5244vGa.cjs");
2
+ //#region ../core/src/projection-sql.ts
3
+ /**
4
+ * SQL generation for projection-backed entities.
5
+ *
6
+ * Base and joins are aliased by their ref key (`base`, then each join's `key`),
7
+ * which is what allows the same table to be joined twice and keeps generated
8
+ * SQL independent of host table names.
9
+ *
10
+ * Pure string generation — no DB access. Identifiers are escaped so output is
11
+ * deterministic and injection-safe.
12
+ */
13
+ /** Quote a single identifier part, escaping embedded double-quotes. */
14
+ function quoteIdent(name) {
15
+ return `"${name.replace(/"/g, "\"\"")}"`;
16
+ }
17
+ function refSql(ref) {
18
+ return `${quoteIdent(ref.table)}.${quoteIdent(ref.column)}`;
19
+ }
20
+ /**
21
+ * The identity expression, aliased as `id`. Composite identities concatenate
22
+ * their parts with `::`; validation guarantees every part is NOT NULL and
23
+ * non-text, which is what makes the concatenation collision-free.
24
+ */
25
+ function identitySql(projection, basePkColumn) {
26
+ const refs = require_projection.identityRefs(projection.identity, basePkColumn);
27
+ if (projection.identity.kind === "composite") return `CONCAT_WS('::', ${refs.map((ref) => `${refSql(ref)}::text`).join(", ")}) AS ${quoteIdent("id")}`;
28
+ const [ref] = refs;
29
+ if (!ref) throw new Error("projection identity resolved to no column");
30
+ return `${refSql(ref)} AS ${quoteIdent("id")}`;
31
+ }
32
+ function compileProjectionSelect(projection, basePkColumn) {
33
+ const selectItems = [identitySql(projection, basePkColumn)];
34
+ const columns = ["id"];
35
+ for (const [field, binding] of Object.entries(projection.fieldBindings)) {
36
+ selectItems.push(`${refSql(binding.from)} AS ${quoteIdent(field)}`);
37
+ columns.push(field);
38
+ }
39
+ return {
40
+ columns,
41
+ selectItems
42
+ };
43
+ }
44
+ function compileProjectionJoins(projection) {
45
+ return projection.joins.map((join) => {
46
+ const keyword = join.type === "inner" ? "INNER JOIN" : "LEFT JOIN";
47
+ const on = join.on.map((c) => `${refSql(c.left)} = ${refSql(c.right)}`).join(" AND ");
48
+ return `${keyword} ${quoteIdent(join.table)} AS ${quoteIdent(join.key)} ON ${on}`;
49
+ });
50
+ }
51
+ /** `FROM <baseTable> AS "base"` — the alias every ref resolves against. */
52
+ function compileProjectionFrom(projection) {
53
+ return `FROM ${quoteIdent(projection.baseTable)} AS ${quoteIdent(require_projection.BASE_REF)}`;
54
+ }
55
+ //#endregion
1
56
  //#region ../core/src/view-compiler.ts
2
57
  /**
3
58
  * View compiler (Phase 2) — turns a validated entity config into read-only
@@ -22,10 +77,6 @@
22
77
  const SOURCE_KEY = "id";
23
78
  const DEFAULT_VIEW_PREFIX = "crm_src_";
24
79
  const DEFAULT_ROLE = "primary";
25
- /** Quote a single identifier part, escaping embedded double-quotes. */
26
- function quoteIdent(name) {
27
- return `"${name.replace(/"/g, "\"\"")}"`;
28
- }
29
80
  /** Emit a SQL literal for a scalar filter value. */
30
81
  function quoteLiteral(value) {
31
82
  if (typeof value === "number") return String(value);
@@ -106,17 +157,24 @@ function compileRelationship(relName, rel, source, related) {
106
157
  refColumn: refCol
107
158
  };
108
159
  }
109
- function compileEntityView(config, entityKey, options = {}) {
110
- const entity = config.entities[entityKey];
111
- if (!entity) throw new Error(`entity "${entityKey}" is not defined`);
112
- const viewName = `${options.viewPrefix ?? "crm_src_"}${entityKey}`;
113
- const src = entity.source;
160
+ /** SELECT items for a legacy single-table entity: source key, then fields. */
161
+ function legacySelect(entity, src) {
114
162
  const selectItems = [`${quoteIdent(src)}.${quoteIdent(SOURCE_KEY)} AS ${quoteIdent("id")}`];
115
163
  const columns = ["id"];
116
164
  for (const [field, column] of Object.entries(entity.fields)) {
117
165
  selectItems.push(`${quoteIdent(src)}.${quoteIdent(column)} AS ${quoteIdent(field)}`);
118
166
  columns.push(field);
119
167
  }
168
+ return {
169
+ columns,
170
+ selectItems
171
+ };
172
+ }
173
+ /**
174
+ * Relationship JOINs for a legacy entity. Appends each relationship's ref
175
+ * column to `columns`/`selectItems` in place, preserving the existing order.
176
+ */
177
+ function legacyJoins(config, entity, columns, selectItems) {
120
178
  const joins = [];
121
179
  for (const [relName, rel] of Object.entries(entity.relationships ?? {})) {
122
180
  const compiled = compileRelationship(relName, rel, entity, config.entities[rel.entity]);
@@ -126,12 +184,39 @@ function compileEntityView(config, entityKey, options = {}) {
126
184
  columns.push(compiled.refColumn);
127
185
  }
128
186
  }
129
- const conditions = compileFilterConditions(src, entity.filter);
130
- if (options.orgScope) conditions.push(`${quoteIdent(src)}.${quoteIdent(options.orgScope.column)} = ${quoteLiteral(options.orgScope.value)}`);
187
+ return joins;
188
+ }
189
+ /**
190
+ * Translate a driver error from executing a compiled view into something
191
+ * actionable, or `undefined` when it is not one we recognise (caller rethrows).
192
+ *
193
+ * The case that matters: `WITH (security_invoker = true)` needs Postgres 15,
194
+ * and PG 14 rejects it with sqlstate 22023 naming a Postgres internal
195
+ * (`reloptions.c`) — no mention of Clivly, the option, or the version. The
196
+ * compiler cannot catch this itself because the host executes the SQL.
197
+ */
198
+ function explainViewExecutionError(error) {
199
+ if (typeof error !== "object" || error === null) return;
200
+ const { code, routine } = error;
201
+ const message = error instanceof Error ? error.message : "";
202
+ if (!(code === "22023" && (routine === "parseRelOptionsInternal" || message.includes("security_invoker")))) return;
203
+ return "CREATE VIEW … WITH (security_invoker = true) requires Postgres 15+. Pass `securityInvoker: false` to compile without it — but note the view then runs with its owner's privileges instead of the querying role's, which bypasses row-level security (RLS) on the underlying tables. Prefer upgrading Postgres if you rely on RLS to separate tenants.";
204
+ }
205
+ function compileEntityView(config, entityKey, options = {}) {
206
+ const entity = config.entities[entityKey];
207
+ if (!entity) throw new Error(`entity "${entityKey}" is not defined`);
208
+ const viewName = `${options.viewPrefix ?? "crm_src_"}${entityKey}`;
209
+ const src = entity.source;
210
+ const projection = entity.projection;
211
+ const filterTable = projection ? require_projection.BASE_REF : src;
212
+ const { selectItems, columns } = projection ? compileProjectionSelect(projection, SOURCE_KEY) : legacySelect(entity, src);
213
+ const joins = projection ? compileProjectionJoins(projection) : legacyJoins(config, entity, columns, selectItems);
214
+ const conditions = compileFilterConditions(filterTable, entity.filter);
215
+ if (options.orgScope) conditions.push(`${quoteIdent(filterTable)}.${quoteIdent(options.orgScope.column)} = ${quoteLiteral(options.orgScope.value)}`);
131
216
  const lines = [
132
217
  options.securityInvoker ?? true ? `CREATE OR REPLACE VIEW ${quoteIdent(viewName)} WITH (security_invoker = true) AS` : `CREATE OR REPLACE VIEW ${quoteIdent(viewName)} AS`,
133
218
  `SELECT ${selectItems.join(", ")}`,
134
- `FROM ${quoteIdent(src)}`,
219
+ projection ? compileProjectionFrom(projection) : `FROM ${quoteIdent(src)}`,
135
220
  ...joins
136
221
  ];
137
222
  if (conditions.length > 0) lines.push(`WHERE ${conditions.join(" AND ")}`);
@@ -206,3 +291,9 @@ Object.defineProperty(exports, "explainEntitiesConfig", {
206
291
  return explainEntitiesConfig;
207
292
  }
208
293
  });
294
+ Object.defineProperty(exports, "explainViewExecutionError", {
295
+ enumerable: true,
296
+ get: function() {
297
+ return explainViewExecutionError;
298
+ }
299
+ });