clivly 0.23.1 → 0.24.0-next.0

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 (103) hide show
  1. package/README.md +28 -0
  2. package/{adapter-B4v4dwgD.d.mts → adapter--YV7du3i.d.cts} +1 -1
  3. package/{adapter-BK3gsby5.d.cts → adapter-DD3K3dCW.d.mts} +1 -1
  4. package/{auth-adapter-BIa-ZyVV.d.mts → auth-adapter-C17dzlzF.d.cts} +1 -1
  5. package/{auth-adapter-DwtMJb7D.d.cts → auth-adapter-CizFv7oU.d.mts} +1 -1
  6. package/auth-better-auth.d.cts +1 -1
  7. package/auth-better-auth.d.mts +1 -1
  8. package/auth-clerk.d.cts +1 -1
  9. package/auth-clerk.d.mts +1 -1
  10. package/auth-supabase.cjs +121 -0
  11. package/auth-supabase.d.cts +23 -0
  12. package/auth-supabase.d.mts +23 -0
  13. package/auth-supabase.mjs +119 -0
  14. package/auth-workos.d.cts +1 -1
  15. package/auth-workos.d.mts +1 -1
  16. package/core-adapter.d.cts +1 -1
  17. package/core-adapter.d.mts +1 -1
  18. package/core-auth-adapter.d.cts +1 -1
  19. package/core-auth-adapter.d.mts +1 -1
  20. package/core-mapping-score.d.cts +1 -0
  21. package/core-sync-engine.cjs +1 -1
  22. package/core-sync-engine.mjs +1 -1
  23. package/core-types.cjs +5 -1
  24. package/core-types.d.cts +2 -2
  25. package/core-types.d.mts +2 -2
  26. package/core-types.mjs +1 -1
  27. package/core-view-compiler.cjs +1 -1
  28. package/core-view-compiler.mjs +1 -1
  29. package/core.cjs +9 -5
  30. package/core.d.cts +6 -6
  31. package/core.d.mts +6 -6
  32. package/core.mjs +6 -6
  33. package/discover-BZIPXl23.cjs +200 -0
  34. package/discover-CFIi43Qn.mjs +195 -0
  35. package/drizzle.cjs +1 -1
  36. package/drizzle.d.cts +2 -2
  37. package/drizzle.d.mts +2 -2
  38. package/drizzle.mjs +1 -1
  39. package/executor-CJEWurjZ.mjs +23 -0
  40. package/executor-CU-jRgpC.cjs +40 -0
  41. package/index-CZkp8TV4.d.cts +108 -0
  42. package/index-Cnrz4ywf.d.mts +108 -0
  43. package/{index-Bh7o2J7K.d.mts → index-DOoX2GgI.d.mts} +3 -3
  44. package/{index-DRRTE5IJ.d.cts → index-uFDiQEjj.d.cts} +231 -5
  45. package/index.cjs +903 -30
  46. package/index.d.cts +27 -0
  47. package/index.d.mts +26 -0
  48. package/index.mjs +901 -28
  49. package/{internal-CdfVkh4O.d.mts → internal-D_2q2BOB.d.mts} +1 -1
  50. package/internal-adapter.d.cts +1 -1
  51. package/internal-adapter.d.mts +1 -1
  52. package/internal-auth-adapter.d.cts +1 -1
  53. package/internal-auth-adapter.d.mts +1 -1
  54. package/internal-sync-engine.cjs +1 -1
  55. package/internal-sync-engine.mjs +1 -1
  56. package/internal-types.cjs +5 -1
  57. package/internal-types.d.cts +2 -2
  58. package/internal-types.d.mts +2 -2
  59. package/internal-types.mjs +1 -1
  60. package/internal-view-compiler.cjs +1 -1
  61. package/internal-view-compiler.mjs +1 -1
  62. package/internal.cjs +9 -5
  63. package/internal.d.cts +5 -6
  64. package/internal.d.mts +6 -6
  65. package/internal.mjs +6 -6
  66. package/introspector-BwYgHGcS.cjs +363 -0
  67. package/introspector-Bz52xOUr.mjs +334 -0
  68. package/{namespace-probe-JuHriruA.d.mts → namespace-probe--GvxJ06J.d.mts} +8 -1
  69. package/package.json +31 -1
  70. package/projection-guard-7AMY0aCk.mjs +389 -0
  71. package/projection-guard-D8VUhCz7.cjs +508 -0
  72. package/{projection-sql-DQQdjw9I.mjs → projection-sql-2joBkLz2.mjs} +13 -3
  73. package/{projection-sql-BkrHR2ea.cjs → projection-sql-DS5sVTY-.cjs} +18 -2
  74. package/sdk-Bzkr24NW.cjs +207 -0
  75. package/sdk-D2WwGBzk.mjs +178 -0
  76. package/sdk.cjs +8 -6
  77. package/sdk.d.cts +7 -1
  78. package/sdk.d.mts +7 -1
  79. package/sdk.mjs +3 -2
  80. package/sql.cjs +13 -0
  81. package/sql.d.cts +2 -0
  82. package/sql.d.mts +2 -0
  83. package/sql.mjs +4 -0
  84. package/{sdk-BkMDOfCk.mjs → src-Dq2nY1Sj.mjs} +36 -495
  85. package/{sdk-BOarpe5I.cjs → src-X0-yIA3O.cjs} +63 -546
  86. package/supabase.cjs +255 -0
  87. package/supabase.d.cts +19 -0
  88. package/supabase.d.mts +19 -0
  89. package/supabase.mjs +254 -0
  90. package/{sync-engine-yFLEyId3.mjs → sync-engine-D0mJUeqP.mjs} +1 -1
  91. package/{sync-engine-DNSoZeo0.cjs → sync-engine-hU041kXO.cjs} +1 -1
  92. package/types-KMH5D5Lg.mjs +32 -0
  93. package/{namespace-probe-CcL6Wj8E.d.cts → types-UR-tT4c1.d.cts} +52 -45
  94. package/{types-BBfwsDxe.d.cts → types-f-Vcv-pl.d.cts} +18 -2
  95. package/{types-BBfwsDxe.d.mts → types-f-Vcv-pl.d.mts} +18 -2
  96. package/types-kR1kUlmz.cjs +67 -0
  97. package/{view-compiler-CSHSqZl7.mjs → view-compiler-BhKiezRH.mjs} +1 -1
  98. package/{view-compiler-NqiortOA.cjs → view-compiler-DgZadq1F.cjs} +1 -1
  99. package/vite.d.cts +1 -1
  100. package/vite.d.mts +1 -1
  101. package/internal-D7qVRIFb.d.cts +0 -228
  102. package/types-8KSw2AWg.mjs +0 -8
  103. package/types-B8m39L1s.cjs +0 -19
@@ -1,8 +1,8 @@
1
- import { i as projectionSchema } from "./projection-CzBI2NL8.mjs";
2
1
  import { _ as validateProjection, s as customObjectDeclarations, w as primaryKeyColumns } from "./entity-config-CI5CGfaN.mjs";
3
- import { a as isSensitiveColumn } from "./entity-heuristics-DAxqagJA.mjs";
4
2
  import { t as entitiesToMappings } from "./mappings-config-Opw7ZM6Y.mjs";
3
+ import { c as parseWireCursors, d as toWireCursor, f as customPushSource, h as resolveEntitySource, i as projectionExposureErrors, l as sourceTimeFields, m as pushSourceOf, o as fullSyncSource, p as expectedSourceKey, r as exposableColumns, s as nextCursor, t as ProjectionRefusedError, u as syncSource } from "./projection-guard-7AMY0aCk.mjs";
5
4
  import { t as DRIZZLE_META } from "./drizzle-meta-D00lFvAk.mjs";
5
+ import { i as projectionSchema } from "./projection-CzBI2NL8.mjs";
6
6
  // ../sdk/src/deployment-identity.ts
7
7
  const MAX_DEPLOYMENT_ID_LENGTH = 128;
8
8
  const PLATFORM_DEPLOYMENT_KEYS = [
@@ -44,76 +44,6 @@ function resolveDeploymentId(env, configured) {
44
44
  if (deploymentId) return deploymentId.slice(0, MAX_DEPLOYMENT_ID_LENGTH);
45
45
  return `local-${hashLocalIdentity(firstNonBlank([env.HOSTNAME]) ?? "unidentified-host")}`;
46
46
  }
47
- // ../sdk/src/entity-source.ts
48
- const CONCEPT_KEYS = {
49
- contact: "contacts",
50
- company: "companies",
51
- deal: "deals"
52
- };
53
- function resolveEntitySource(config, entityKey) {
54
- const entity = config.entities?.entities?.[entityKey];
55
- const src = config.source;
56
- if (!(entity && src)) return null;
57
- const conceptKey = CONCEPT_KEYS[entity.concept];
58
- if (conceptKey) {
59
- const source = src[conceptKey];
60
- return source ? {
61
- concept: entity.concept,
62
- expectedKey: conceptKey,
63
- source
64
- } : null;
65
- }
66
- if (entity.concept === "custom") {
67
- const match = (src.custom ?? []).find((c) => c.entity === entity.source || c.entity === entityKey);
68
- return match ? {
69
- concept: "custom",
70
- expectedKey: "custom",
71
- source: match
72
- } : null;
73
- }
74
- return null;
75
- }
76
- /** The `config.source` key an entity's concept requires, present or not. */
77
- function expectedSourceKey(concept) {
78
- return CONCEPT_KEYS[concept] ?? "custom";
79
- }
80
- /**
81
- * The `source` label a push must carry for the server to find its mapping.
82
- *
83
- * `entity` is the SDK's own name for a source — the cursor-store key, and what
84
- * the developer wrote in `config.source`. It is NOT always what the server
85
- * filed the mapping under: for a projection, `ensureSchema` stores
86
- * `sourceTable` as `projection.baseTable`, because a projection entity's key
87
- * doubles as a kebab-case object slug and cannot also be the snake_case
88
- * `projection.entityKey`.
89
- *
90
- * Pushing under `entity` therefore dropped 100% of a projection's rows while
91
- * every local signal said the setup was correct. One function so the three
92
- * push sites cannot drift apart again.
93
- */
94
- function pushSourceOf(source) {
95
- return source.pushSource ?? source.entity;
96
- }
97
- /**
98
- * The push label for a custom source, resolved against the config.
99
- *
100
- * `fromDrizzleProjection` stamps `pushSource` itself, but a projection source
101
- * can equally be hand-built — `fromDrizzle` with an overridden `fetchPage` is
102
- * what the README's own example leads you to, and next-finance did exactly
103
- * that. Such a source has no `pushSource`, so the label has to come from the
104
- * one place that is true either way: the entity's declared
105
- * `projection.baseTable`.
106
- *
107
- * Matched on the source's `entity`, which for a custom source is also the
108
- * config entity key (that is what `resolveEntitySource` above pairs them by).
109
- * Falls back to `pushSourceOf`, so a non-projection custom source and an
110
- * already-stamped one both keep their current label.
111
- */
112
- function customPushSource(config, source) {
113
- if (source.pushSource) return source.pushSource;
114
- const entities = config.entities?.entities;
115
- return (entities?.[source.entity] ?? Object.values(entities ?? {}).find((e) => e.source === source.entity))?.projection?.baseTable ?? source.entity;
116
- }
117
47
  // ../sdk/src/concept-coverage.ts
118
48
  const CHECK_NAME$1 = "Entity → source coverage";
119
49
  function configuredKeys(config) {
@@ -469,8 +399,7 @@ const TEMPORAL_CURSOR_TYPES = [
469
399
  function cursorMonotonicityCheck(source) {
470
400
  const meta = source[DRIZZLE_META];
471
401
  if (!meta?.columnsMeta) return null;
472
- const index = meta.columnKeys.indexOf(meta.cursorField);
473
- const type = meta.columnsMeta[index]?.type?.toLowerCase();
402
+ const type = (meta.kind === "sql" ? meta.columnsMeta.find((c) => c.name === meta.cursorField) : meta.columnsMeta[meta.columnKeys.indexOf(meta.cursorField)])?.type?.toLowerCase();
474
403
  if (!type) return null;
475
404
  const temporal = TEMPORAL_CURSOR_TYPES.some((t) => type.startsWith(t));
476
405
  const name = `Cursor tracks updates (${source.entity})`;
@@ -1103,78 +1032,6 @@ function resolvePresenceTransport(host, configured) {
1103
1032
  transport: DEFAULT_TRANSPORT
1104
1033
  };
1105
1034
  }
1106
- // ../sdk/src/projection-guard.ts
1107
- /**
1108
- * Tables auth libraries keep live credentials in. Whole-table: their secrets
1109
- * sit in columns with generic names (`token`, `value`) that a column rule
1110
- * cannot single out. `user`, `member` and `organization` are not here — they
1111
- * are legitimate contact and company sources.
1112
- */
1113
- const CREDENTIAL_TABLES = /* @__PURE__ */ new Set([
1114
- "session",
1115
- "verification",
1116
- "two_factor",
1117
- "twofactor",
1118
- "passkey",
1119
- "apikey",
1120
- "api_key",
1121
- "jwks"
1122
- ]);
1123
- const BASE_ALIAS = "base";
1124
- function normalise(name) {
1125
- return name.toLowerCase().replaceAll("-", "_");
1126
- }
1127
- /** Every (table, column) a projection reads, with join aliases resolved. */
1128
- function readColumns(projection) {
1129
- const tableOf = /* @__PURE__ */ new Map([[BASE_ALIAS, projection.baseTable]]);
1130
- for (const join of projection.joins) tableOf.set(join.key, join.table);
1131
- const refs = [];
1132
- for (const join of projection.joins) for (const condition of join.on) refs.push(condition.left, condition.right);
1133
- for (const binding of Object.values(projection.fieldBindings)) refs.push(binding.from);
1134
- const { identity } = projection;
1135
- if (identity.kind === "column") refs.push(identity.from);
1136
- else if (identity.kind === "composite") refs.push(...identity.parts);
1137
- else if (identity.column) refs.push({
1138
- table: BASE_ALIAS,
1139
- column: identity.column
1140
- });
1141
- return refs.map((ref) => ({
1142
- table: tableOf.get(ref.table) ?? ref.table,
1143
- column: ref.column
1144
- }));
1145
- }
1146
- function referencedTables(projection) {
1147
- return [projection.baseTable, ...projection.joins.map((join) => join.table)];
1148
- }
1149
- /** Why this projection may not run here; empty when it may. */
1150
- function projectionExposureErrors(projection, policy = {}) {
1151
- const allowed = new Set((policy.allowSensitive ?? []).map(normalise));
1152
- const errors = [];
1153
- for (const table of referencedTables(projection)) {
1154
- if (CREDENTIAL_TABLES.has(normalise(table)) && !allowed.has(normalise(`${table}.*`))) errors.push(`Table "${table}" holds credentials and is never synced.`);
1155
- if (policy.tables && !(table in policy.tables)) errors.push(`Table "${table}" is not in this app's exposure.tables allowlist.`);
1156
- }
1157
- for (const { table, column } of readColumns(projection)) {
1158
- const ref = `${table}.${column}`;
1159
- if (isSensitiveColumn(column) && !allowed.has(normalise(ref))) errors.push(`Column "${ref}" looks like a credential and is never synced. List it in exposure.allowSensitive if it is safe.`);
1160
- const columns = policy.tables?.[table];
1161
- if (Array.isArray(columns) && !columns.includes(column)) errors.push(`Column "${ref}" is not in this app's exposure.tables allowlist.`);
1162
- }
1163
- return [...new Set(errors)];
1164
- }
1165
- /** Drop credential columns, and columns outside the allowlist, from a raw-row preview. */
1166
- function exposableColumns(table, columns, policy = {}) {
1167
- const allowed = new Set((policy.allowSensitive ?? []).map(normalise));
1168
- const result = /* @__PURE__ */ new Set();
1169
- if (CREDENTIAL_TABLES.has(normalise(table)) && !allowed.has(normalise(`${table}.*`)) || policy.tables !== void 0 && !(table in policy.tables)) return result;
1170
- const listed = policy.tables?.[table];
1171
- for (const column of columns) {
1172
- if (isSensitiveColumn(column) && !allowed.has(normalise(`${table}.${column}`))) continue;
1173
- if (Array.isArray(listed) && !listed.includes(column)) continue;
1174
- result.add(column);
1175
- }
1176
- return result;
1177
- }
1178
1035
  // ../sdk/src/push-outcome.ts
1179
1036
  function isCount(value) {
1180
1037
  return typeof value === "number" && Number.isFinite(value);
@@ -1449,162 +1306,6 @@ function selfCheck(input) {
1449
1306
  });
1450
1307
  return issues;
1451
1308
  }
1452
- // ../sdk/src/sync.ts
1453
- const DEFAULT_ID_FIELD$1 = "id";
1454
- function isAfter(candidate, current) {
1455
- const ct = candidate.time.getTime();
1456
- const bt = current.time.getTime();
1457
- if (ct !== bt) return ct > bt;
1458
- return candidate.id > current.id;
1459
- }
1460
- function nextCursor(rows, cursorField, idField, current) {
1461
- let max = current;
1462
- for (const row of rows) {
1463
- const raw = row[cursorField];
1464
- if (raw === null || raw === void 0) continue;
1465
- const time = raw instanceof Date ? raw : new Date(String(raw));
1466
- if (Number.isNaN(time.getTime())) continue;
1467
- const idRaw = row[idField];
1468
- const candidate = {
1469
- time,
1470
- id: idRaw === null || idRaw === void 0 ? "" : String(idRaw)
1471
- };
1472
- if (!max || isAfter(candidate, max)) max = candidate;
1473
- }
1474
- return max;
1475
- }
1476
- const CREATED_AT_CANDIDATES = [
1477
- "created_at",
1478
- "createdAt",
1479
- "inserted_at",
1480
- "insertedAt",
1481
- "signed_up_at",
1482
- "signedUpAt",
1483
- "joined_at",
1484
- "joinedAt"
1485
- ];
1486
- /**
1487
- * Which columns of these rows hold their times: the cursor column (it moves
1488
- * when a row changes) and the creation column, configured or detected from
1489
- * the rows' own keys. A creation column the rows do not carry is left out.
1490
- */
1491
- function sourceTimeFields(source, rows) {
1492
- const first = rows[0] ?? {};
1493
- const createdAt = source.createdAtField ?? CREATED_AT_CANDIDATES.find((column) => column in first);
1494
- return createdAt === void 0 ? { updatedAt: source.cursorField } : {
1495
- updatedAt: source.cursorField,
1496
- createdAt
1497
- };
1498
- }
1499
- function toWireCursor(cursor) {
1500
- return {
1501
- id: cursor.id,
1502
- time: cursor.time.toISOString()
1503
- };
1504
- }
1505
- /**
1506
- * Read the positions Clivly sent with a triggered sync. Anything malformed is
1507
- * dropped, so that source falls back to the app's own cursor store.
1508
- */
1509
- function parseWireCursors(value) {
1510
- if (value === null || typeof value !== "object" || Array.isArray(value)) return;
1511
- const out = {};
1512
- for (const [entity, raw] of Object.entries(value)) {
1513
- if (raw === null || typeof raw !== "object") continue;
1514
- const { id, time } = raw;
1515
- if (typeof id !== "string" || typeof time !== "string") continue;
1516
- const parsed = new Date(time);
1517
- if (!Number.isNaN(parsed.getTime())) out[entity] = {
1518
- id,
1519
- time: parsed
1520
- };
1521
- }
1522
- return out;
1523
- }
1524
- function cursorReport(source, cursor, report) {
1525
- return report && cursor ? {
1526
- entity: source.entity,
1527
- nextCursor: toWireCursor(cursor)
1528
- } : {};
1529
- }
1530
- async function syncSource(args) {
1531
- const { source, path, since, batchSize, push, objectType, maxRows } = args;
1532
- const reportCursor = args.reportCursor ?? true;
1533
- const idField = source.idField ?? DEFAULT_ID_FIELD$1;
1534
- let cursor = since;
1535
- let pushed = 0;
1536
- const resumedFrom = since === null ? null : since.time.toISOString();
1537
- for (;;) {
1538
- const rows = await source.fetchPage({
1539
- since: cursor,
1540
- limit: batchSize
1541
- });
1542
- if (rows.length === 0) break;
1543
- const capped = maxRows === void 0 ? rows : rows.slice(0, maxRows);
1544
- const next = nextCursor(capped, source.cursorField, idField, cursor);
1545
- if (!await push(path, {
1546
- source: pushSourceOf(source),
1547
- rows: capped,
1548
- mode: "delta",
1549
- fetched: rows.length,
1550
- cursor: resumedFrom,
1551
- sourceFields: sourceTimeFields(source, capped),
1552
- ...cursorReport(source, next, reportCursor),
1553
- ...objectType ? { objectType } : {}
1554
- })) return {
1555
- pushed,
1556
- cursor,
1557
- ok: false
1558
- };
1559
- pushed += capped.length;
1560
- cursor = next;
1561
- if (maxRows !== void 0 || rows.length < batchSize) break;
1562
- }
1563
- return {
1564
- pushed,
1565
- cursor,
1566
- ok: true
1567
- };
1568
- }
1569
- async function fullSyncSource(args) {
1570
- const { source, path, batchSize, push, objectType } = args;
1571
- const reportCursor = args.reportCursor ?? true;
1572
- const idField = source.idField ?? DEFAULT_ID_FIELD$1;
1573
- const all = [];
1574
- let cursor = null;
1575
- for (;;) {
1576
- const rows = await source.fetchPage({
1577
- since: cursor,
1578
- limit: batchSize
1579
- });
1580
- if (rows.length === 0) break;
1581
- all.push(...rows);
1582
- const next = nextCursor(rows, source.cursorField, idField, cursor);
1583
- const stalled = next !== null && cursor !== null && next.time.getTime() === cursor.time.getTime() && next.id === cursor.id;
1584
- cursor = next;
1585
- if (rows.length < batchSize || stalled) break;
1586
- }
1587
- if (all.length === 0) return {
1588
- pushed: 0,
1589
- cursor: null,
1590
- ok: true
1591
- };
1592
- const ok = await push(path, {
1593
- source: pushSourceOf(source),
1594
- rows: all,
1595
- mode: "full",
1596
- fetched: all.length,
1597
- cursor: null,
1598
- sourceFields: sourceTimeFields(source, all),
1599
- ...cursorReport(source, cursor, reportCursor),
1600
- ...objectType ? { objectType } : {}
1601
- });
1602
- return {
1603
- pushed: ok ? all.length : 0,
1604
- cursor,
1605
- ok
1606
- };
1607
- }
1608
1309
  // ../sdk/src/source-ids.ts
1609
1310
  /**
1610
1311
  * The daily delete check (continuous sync D20). A delta pull never sees a row
@@ -1814,183 +1515,6 @@ function resolveTriggerUrl(args) {
1814
1515
  if (origin && args.configuredPath) return `${origin}${args.configuredPath.startsWith("/") ? args.configuredPath : `/${args.configuredPath}`}`;
1815
1516
  return args.observedUrl;
1816
1517
  }
1817
- // ../sdk/src/chat-session.ts
1818
- const DEFAULT_API_URL$1 = "https://api.clivly.com";
1819
- const JSON_HEADERS = { "content-type": "application/json" };
1820
- const TRAILING_SLASH$1 = /\/$/;
1821
- function jsonResponse$1(body, status) {
1822
- return new Response(JSON.stringify(body), {
1823
- status,
1824
- headers: JSON_HEADERS
1825
- });
1826
- }
1827
- function normalizeApiUrl(apiUrl) {
1828
- return apiUrl.replace(TRAILING_SLASH$1, "");
1829
- }
1830
- /**
1831
- * The origin *claimed* by the request, for reporting upstream.
1832
- *
1833
- * Falls back to the request URL so Clivly still receives an origin for a
1834
- * non-browser caller. This value is reported, never trusted: only a real
1835
- * `Origin` header is evidence of where a request came from, so the access
1836
- * decision uses {@link trustedOrigin} instead. Keeping the two apart is the
1837
- * point — conflating them let a caller that simply omitted the header be
1838
- * judged against the server's own origin, which is usually in the allowlist.
1839
- */
1840
- function reportedOrigin(req) {
1841
- const headerOrigin = trustedOrigin(req);
1842
- if (headerOrigin) return headerOrigin;
1843
- try {
1844
- return new URL(req.url).origin;
1845
- } catch {
1846
- return null;
1847
- }
1848
- }
1849
- /**
1850
- * The only origin worth an access decision: one the browser set itself.
1851
- *
1852
- * A missing header means "not a browser request we can vouch for", which is
1853
- * untrusted — never the server's own origin.
1854
- */
1855
- function trustedOrigin(req) {
1856
- return req.headers.get("origin");
1857
- }
1858
- /**
1859
- * The visitor's address as the host's platform reported it. Clivly throttles
1860
- * new chats per visitor on it; without it the only address Clivly sees is this
1861
- * server's, so every visitor shared one bucket.
1862
- */
1863
- function defaultVisitorIp(req) {
1864
- const direct = req.headers.get("cf-connecting-ip") ?? req.headers.get("x-real-ip");
1865
- if (direct) return direct.trim();
1866
- return req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || null;
1867
- }
1868
- function isChatSessionRequestBody(value) {
1869
- if (typeof value !== "object" || value === null) return false;
1870
- const body = value;
1871
- if (typeof body.widgetId !== "string" || body.widgetId.trim().length === 0) return false;
1872
- if (typeof body.visitor !== "object" || body.visitor === null || Array.isArray(body.visitor)) return false;
1873
- const visitor = body.visitor;
1874
- if (typeof visitor.name !== "string" || visitor.name.trim().length === 0) return false;
1875
- if (typeof visitor.email !== "string" || visitor.email.trim().length === 0) return false;
1876
- return body.visitorToken === void 0 || body.visitorToken === null || typeof body.visitorToken === "string";
1877
- }
1878
- /**
1879
- * Judge a request against the configured allowlist.
1880
- *
1881
- * `origin` must be a *trusted* origin (see {@link trustedOrigin}) — passing
1882
- * the reported one would reinstate the bypass this guards against.
1883
- *
1884
- * An unset allowlist still admits every origin, because requiring it would
1885
- * break every existing deployment on upgrade. The unset case is instead
1886
- * warned about once at construction, so the permissive default is loud
1887
- * rather than silent.
1888
- */
1889
- function originAllowed(origin, allowedOrigins) {
1890
- if (!allowedOrigins || allowedOrigins.length === 0) return true;
1891
- if (!origin) return false;
1892
- return allowedOrigins.includes(origin);
1893
- }
1894
- async function safeHostUser(resolveUser, request) {
1895
- if (!resolveUser) return null;
1896
- try {
1897
- return await resolveUser(request);
1898
- } catch {
1899
- console.warn("[clivly] resolveUser threw; continuing without host identity");
1900
- return null;
1901
- }
1902
- }
1903
- function safeVisitorIp(resolveVisitorIp, request) {
1904
- try {
1905
- return resolveVisitorIp(request);
1906
- } catch {
1907
- return null;
1908
- }
1909
- }
1910
- function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl = DEFAULT_API_URL$1, fetchImpl = fetch, resolveUser, resolveVisitorIp = defaultVisitorIp }) {
1911
- const sessionUrl = `${normalizeApiUrl(apiUrl)}/clivly/widget/session`;
1912
- if (!allowedOrigins || allowedOrigins.length === 0) console.warn("[clivly] createChatSessionHandler has no allowedOrigins; every origin can open a chat session against this workspace. Pass allowedOrigins to restrict it.");
1913
- return async (request) => {
1914
- if (request.method !== "POST") return new Response(JSON.stringify({ error: "method_not_allowed" }), {
1915
- status: 405,
1916
- headers: {
1917
- ...JSON_HEADERS,
1918
- allow: "POST"
1919
- }
1920
- });
1921
- if (!originAllowed(trustedOrigin(request), allowedOrigins)) return jsonResponse$1({ error: "origin_not_allowed" }, 403);
1922
- const origin = reportedOrigin(request);
1923
- let body;
1924
- try {
1925
- body = await request.json();
1926
- } catch {
1927
- return jsonResponse$1({ error: "invalid_json" }, 400);
1928
- }
1929
- if (!isChatSessionRequestBody(body)) return jsonResponse$1({ error: "invalid_request" }, 400);
1930
- const hostUser = await safeHostUser(resolveUser, request);
1931
- const visitorIp = safeVisitorIp(resolveVisitorIp, request);
1932
- try {
1933
- const upstream = await fetchImpl(sessionUrl, {
1934
- method: "POST",
1935
- headers: {
1936
- authorization: `Bearer ${apiKey}`,
1937
- "content-type": "application/json",
1938
- ...origin ? { origin } : {}
1939
- },
1940
- body: JSON.stringify({
1941
- widgetId: body.widgetId,
1942
- visitor: body.visitor,
1943
- visitorToken: body.visitorToken,
1944
- origin,
1945
- ...hostUser ? { hostUser } : {},
1946
- ...visitorIp ? { visitorIp } : {}
1947
- })
1948
- });
1949
- const responseBody = await upstream.text();
1950
- return new Response(responseBody, {
1951
- status: upstream.status,
1952
- headers: { "content-type": upstream.headers.get("content-type") ?? "application/json" }
1953
- });
1954
- } catch {
1955
- return jsonResponse$1({ error: "upstream_unreachable" }, 502);
1956
- }
1957
- };
1958
- }
1959
- // ../sdk/src/errors.ts
1960
- var ClivlyError = class ClivlyError extends Error {
1961
- /** HTTP status, or null when the request never completed (network error). */
1962
- status;
1963
- reason;
1964
- /** Whether a retry could plausibly succeed (network, 429, 5xx). */
1965
- retryable;
1966
- constructor(result, message) {
1967
- super(message ?? `Clivly connection failed: ${result.reason}`);
1968
- this.name = new.target.name;
1969
- this.status = result.status;
1970
- this.reason = result.reason;
1971
- this.retryable = result.retryable;
1972
- }
1973
- /**
1974
- * Build the error subclass matching a failed result's reason, or `null` when
1975
- * the result is `ok`.
1976
- */
1977
- static from(result) {
1978
- if (result.ok) return null;
1979
- switch (result.reason) {
1980
- case "invalid_api_key":
1981
- case "forbidden": return new ClivlyAuthError(result);
1982
- case "rate_limited": return new ClivlyRateLimitError(result);
1983
- case "network_error": return new ClivlyNetworkError(result);
1984
- default: return new ClivlyError(result);
1985
- }
1986
- }
1987
- };
1988
- /** The API key was rejected (401) or lacks access (403). Not retryable. */
1989
- var ClivlyAuthError = class extends ClivlyError {};
1990
- /** Rate limited (429). Retryable after backoff / `Retry-After`. */
1991
- var ClivlyRateLimitError = class extends ClivlyError {};
1992
- /** The request never reached the server (network/DNS/TLS). Retryable. */
1993
- var ClivlyNetworkError = class extends ClivlyError {};
1994
1518
  // ../sdk/src/index.ts
1995
1519
  const DEFAULT_API_URL = "https://api.clivly.com";
1996
1520
  const DEFAULT_HEARTBEAT_MS = 6e4;
@@ -2132,6 +1656,14 @@ function isLikelyServerless() {
2132
1656
  const env = runtime.process?.env;
2133
1657
  return Boolean(env?.AWS_LAMBDA_FUNCTION_NAME || env?.VERCEL);
2134
1658
  }
1659
+ /**
1660
+ * The host's environment, or `{}` where there is no `process` (Deno edge
1661
+ * functions, bare workers). Read through `globalThis` so a missing global is
1662
+ * `undefined`, not a ReferenceError.
1663
+ */
1664
+ function readProcessEnv() {
1665
+ return globalThis.process?.env ?? {};
1666
+ }
2135
1667
  function jsonResponse(body, status) {
2136
1668
  return new Response(JSON.stringify(body), {
2137
1669
  status,
@@ -2339,11 +1871,19 @@ async function handleProjectionPreviewRequest(config, request) {
2339
1871
  error: "projection_refused",
2340
1872
  reasons: refused
2341
1873
  }, FORBIDDEN_STATUS);
2342
- const rows = await run.call(config.introspector, parsed.data, { limit: request.limit });
2343
- return jsonResponse({
2344
- rows,
2345
- sampledCount: rows.length
2346
- }, 200);
1874
+ try {
1875
+ const rows = await run.call(config.introspector, parsed.data, { limit: request.limit });
1876
+ return jsonResponse({
1877
+ rows,
1878
+ sampledCount: rows.length
1879
+ }, 200);
1880
+ } catch (error) {
1881
+ if (error instanceof ProjectionRefusedError) return jsonResponse({
1882
+ error: "projection_refused",
1883
+ reasons: error.reasons
1884
+ }, FORBIDDEN_STATUS);
1885
+ throw error;
1886
+ }
2347
1887
  }
2348
1888
  function failureMessage(body, status) {
2349
1889
  if (typeof body.message === "string") return body.message;
@@ -2362,11 +1902,11 @@ function createClivlySDK(config) {
2362
1902
  const syncIntervalMs = config.sync?.intervalMs ?? heartbeatIntervalMs;
2363
1903
  const serverless = isLikelyServerless();
2364
1904
  const presenceEnabled = resolvePresenceTransport({
2365
- env: config.env ?? process.env,
1905
+ env: config.env ?? readProcessEnv(),
2366
1906
  hasWebSocket: typeof WebSocket === "function",
2367
1907
  serverless
2368
1908
  }, config.presence?.transport).transport === "websocket";
2369
- const deploymentId = presenceEnabled ? resolveDeploymentId(config.env ?? process.env, config.presence?.deploymentId) : null;
1909
+ const deploymentId = presenceEnabled ? resolveDeploymentId(config.env ?? readProcessEnv(), config.presence?.deploymentId) : null;
2370
1910
  const timers = {
2371
1911
  heartbeat: null,
2372
1912
  sync: null
@@ -2446,10 +1986,11 @@ function createClivlySDK(config) {
2446
1986
  return status !== null && status >= CLIENT_ERROR_FLOOR && status < RETRYABLE_STATUS_FLOOR ? new TriggerRequestError(status, message) : new Error(message);
2447
1987
  };
2448
1988
  const syncOne = async (source, path, mode, objectType, runId, batchSizeOverride, maxRowsOverride, persistCursor = true, clivlyCursors) => {
2449
- const since = mode === "full" ? null : clivlyCursors?.[source.entity] ?? await cursorStore.get(source.entity) ?? null;
1989
+ const effectiveMode = source.mode === "full" && maxRowsOverride === void 0 ? "full" : mode;
1990
+ const since = effectiveMode === "full" ? null : clivlyCursors?.[source.entity] ?? await cursorStore.get(source.entity) ?? null;
2450
1991
  const push = createPush(runId);
2451
1992
  const effectiveBatchSize = batchSizeOverride ?? batchSize;
2452
- const result = mode === "full" ? await fullSyncSource({
1993
+ const result = effectiveMode === "full" ? await fullSyncSource({
2453
1994
  source,
2454
1995
  path,
2455
1996
  batchSize: effectiveBatchSize,
@@ -2582,7 +2123,7 @@ function createClivlySDK(config) {
2582
2123
  };
2583
2124
  const instantTarget = (entityKey) => {
2584
2125
  if (config.sync?.instant !== true) return null;
2585
- if (isInstantPushDisabled(config.env ?? process.env)) return null;
2126
+ if (isInstantPushDisabled(config.env ?? readProcessEnv())) return null;
2586
2127
  const resolved = resolveEntitySource(config, entityKey);
2587
2128
  if (!resolved) {
2588
2129
  console.warn(`Clivly instant push: no source is configured for entity "${entityKey}" — this row was not pushed. It will still sync on the next delta run once \`entities\` declares it.`);
@@ -2666,7 +2207,7 @@ function createClivlySDK(config) {
2666
2207
  resolved: resolveTriggerUrl({
2667
2208
  configuredUrl: config.syncTrigger?.url,
2668
2209
  configuredPath: config.syncTrigger?.path,
2669
- env: config.env ?? process.env,
2210
+ env: config.env ?? readProcessEnv(),
2670
2211
  observedUrl
2671
2212
  })
2672
2213
  });
@@ -2722,7 +2263,7 @@ function createClivlySDK(config) {
2722
2263
  namespaceReady: config.namespaceReady ?? false,
2723
2264
  schema: buildSchema(config),
2724
2265
  heartbeatIntervalMs,
2725
- environment: detectHostEnvironment(config.env ?? process.env, config.environment),
2266
+ environment: detectHostEnvironment(config.env ?? readProcessEnv(), config.environment),
2726
2267
  issues: selfCheck({
2727
2268
  hasTriggerSecret: Boolean(config.syncTrigger?.secret),
2728
2269
  reportsTriggerUrl: Boolean(triggerUrl),
@@ -2948,7 +2489,7 @@ function createClivlySDK(config) {
2948
2489
  const refuseDisallowedMethod = (req) => {
2949
2490
  const decision = resolveTriggerMethod({
2950
2491
  enforceDefault: true,
2951
- env: config.env ?? process.env,
2492
+ env: config.env ?? readProcessEnv(),
2952
2493
  method: req.method
2953
2494
  });
2954
2495
  if (decision.warn && !warnedNonPostTrigger) {
@@ -3031,7 +2572,7 @@ function createClivlySDK(config) {
3031
2572
  presenceClient = createPresenceClient({
3032
2573
  apiUrl,
3033
2574
  deploymentId,
3034
- environment: detectHostEnvironment(config.env ?? process.env, config.environment),
2575
+ environment: detectHostEnvironment(config.env ?? readProcessEnv(), config.environment),
3035
2576
  fetcher,
3036
2577
  getHello: () => ({
3037
2578
  issues: selfCheck({
@@ -3039,7 +2580,7 @@ function createClivlySDK(config) {
3039
2580
  reportsTriggerUrl: Boolean(resolveTriggerUrl({
3040
2581
  configuredUrl: config.syncTrigger?.url,
3041
2582
  configuredPath: config.syncTrigger?.path,
3042
- env: config.env ?? process.env,
2583
+ env: config.env ?? readProcessEnv(),
3043
2584
  observedUrl
3044
2585
  })),
3045
2586
  lastPushFailed: lastPush.failed,
@@ -3125,4 +2666,4 @@ function createClivlySDK(config) {
3125
2666
  recordConsent
3126
2667
  };
3127
2668
  }
3128
- export { ClivlyAuthError as a, ClivlyRateLimitError as c, memoryCursorStore as i, createChatSessionHandler as l, createClivlySDK as n, ClivlyError as o, kvCursorStore as r, ClivlyNetworkError as s, CURSOR_KEY_PREFIX as t, isPlaceholderUrl as u };
2669
+ export { readProcessEnv as a, memoryCursorStore as i, createClivlySDK as n, isPlaceholderUrl as o, kvCursorStore as r, CURSOR_KEY_PREFIX as t };