clivly 0.23.1 → 0.24.0-next.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 +42 -2
  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/app-id-5cB6yioz.mjs +53 -0
  5. package/app-id-DcQ4u1c8.cjs +70 -0
  6. package/{auth-adapter-BIa-ZyVV.d.mts → auth-adapter-C17dzlzF.d.cts} +1 -1
  7. package/{auth-adapter-DwtMJb7D.d.cts → auth-adapter-CizFv7oU.d.mts} +1 -1
  8. package/auth-better-auth.d.cts +1 -1
  9. package/auth-better-auth.d.mts +1 -1
  10. package/auth-clerk.d.cts +1 -1
  11. package/auth-clerk.d.mts +1 -1
  12. package/auth-supabase.cjs +121 -0
  13. package/auth-supabase.d.cts +23 -0
  14. package/auth-supabase.d.mts +23 -0
  15. package/auth-supabase.mjs +119 -0
  16. package/auth-workos.d.cts +1 -1
  17. package/auth-workos.d.mts +1 -1
  18. package/core-adapter.d.cts +1 -1
  19. package/core-adapter.d.mts +1 -1
  20. package/core-auth-adapter.d.cts +1 -1
  21. package/core-auth-adapter.d.mts +1 -1
  22. package/core-mapping-score.d.cts +1 -0
  23. package/core-sync-engine.cjs +1 -1
  24. package/core-sync-engine.mjs +1 -1
  25. package/core-types.cjs +5 -1
  26. package/core-types.d.cts +2 -2
  27. package/core-types.d.mts +2 -2
  28. package/core-types.mjs +1 -1
  29. package/core-view-compiler.cjs +1 -1
  30. package/core-view-compiler.mjs +1 -1
  31. package/core.cjs +9 -5
  32. package/core.d.cts +6 -6
  33. package/core.d.mts +6 -6
  34. package/core.mjs +6 -6
  35. package/drizzle.cjs +121 -14
  36. package/drizzle.d.cts +8 -2
  37. package/drizzle.d.mts +8 -2
  38. package/drizzle.mjs +126 -19
  39. package/executor-CJEWurjZ.mjs +23 -0
  40. package/executor-CU-jRgpC.cjs +40 -0
  41. package/from-sql-BD7gR4bC.mjs +282 -0
  42. package/from-sql-CFgXkCe2.cjs +347 -0
  43. package/from-sql-CpGP7K3J.d.mts +70 -0
  44. package/from-sql-S8dSvU-e.d.cts +70 -0
  45. package/index-BoemTWH4.d.mts +134 -0
  46. package/index-CIupXz_w.d.cts +134 -0
  47. package/{index-Bh7o2J7K.d.mts → index-DOoX2GgI.d.mts} +3 -3
  48. package/{index-DRRTE5IJ.d.cts → index-uFDiQEjj.d.cts} +231 -5
  49. package/index.cjs +1079 -36
  50. package/index.d.cts +36 -0
  51. package/index.d.mts +35 -0
  52. package/index.mjs +1077 -34
  53. package/{internal-CdfVkh4O.d.mts → internal-D_2q2BOB.d.mts} +1 -1
  54. package/internal-adapter.d.cts +1 -1
  55. package/internal-adapter.d.mts +1 -1
  56. package/internal-auth-adapter.d.cts +1 -1
  57. package/internal-auth-adapter.d.mts +1 -1
  58. package/internal-sync-engine.cjs +1 -1
  59. package/internal-sync-engine.mjs +1 -1
  60. package/internal-types.cjs +5 -1
  61. package/internal-types.d.cts +2 -2
  62. package/internal-types.d.mts +2 -2
  63. package/internal-types.mjs +1 -1
  64. package/internal-view-compiler.cjs +1 -1
  65. package/internal-view-compiler.mjs +1 -1
  66. package/internal.cjs +9 -5
  67. package/internal.d.cts +5 -6
  68. package/internal.d.mts +6 -6
  69. package/internal.mjs +6 -6
  70. package/introspector-5w2x89RD.mjs +55 -0
  71. package/introspector-DT_Ma59k.cjs +60 -0
  72. package/kysely.cjs +56 -0
  73. package/kysely.d.cts +45 -0
  74. package/kysely.d.mts +45 -0
  75. package/kysely.mjs +54 -0
  76. package/{namespace-probe-JuHriruA.d.mts → namespace-probe-CUR2zG2l.d.mts} +41 -4
  77. package/package.json +45 -1
  78. package/projection-guard-C70l5U24.cjs +170 -0
  79. package/projection-guard-DOt_nbGn.mjs +147 -0
  80. package/{projection-sql-DQQdjw9I.mjs → projection-sql-2joBkLz2.mjs} +13 -3
  81. package/{projection-sql-BkrHR2ea.cjs → projection-sql-DS5sVTY-.cjs} +18 -2
  82. package/sdk-Bzkr24NW.cjs +207 -0
  83. package/sdk-D2WwGBzk.mjs +178 -0
  84. package/sdk.cjs +8 -6
  85. package/sdk.d.cts +7 -1
  86. package/sdk.d.mts +7 -1
  87. package/sdk.mjs +3 -2
  88. package/sql.cjs +20 -0
  89. package/sql.d.cts +3 -0
  90. package/sql.d.mts +3 -0
  91. package/sql.mjs +7 -0
  92. package/{sdk-BOarpe5I.cjs → src-CZIdwwI2.cjs} +203 -583
  93. package/{sdk-BkMDOfCk.mjs → src-tFhC1Ru2.mjs} +175 -531
  94. package/supabase-contact-3ke1KKUs.mjs +595 -0
  95. package/supabase-contact-BXQ0nnLq.cjs +624 -0
  96. package/supabase.cjs +165 -0
  97. package/supabase.d.cts +20 -0
  98. package/supabase.d.mts +20 -0
  99. package/supabase.mjs +164 -0
  100. package/sync-CdA9dgZz.cjs +519 -0
  101. package/sync-Q0O-2kFI.mjs +382 -0
  102. package/{sync-engine-yFLEyId3.mjs → sync-engine-D0mJUeqP.mjs} +1 -1
  103. package/{sync-engine-DNSoZeo0.cjs → sync-engine-hU041kXO.cjs} +1 -1
  104. package/{namespace-probe-CcL6Wj8E.d.cts → types-CzL7lUH9.d.cts} +84 -47
  105. package/types-KMH5D5Lg.mjs +32 -0
  106. package/{types-BBfwsDxe.d.cts → types-f-Vcv-pl.d.cts} +18 -2
  107. package/{types-BBfwsDxe.d.mts → types-f-Vcv-pl.d.mts} +18 -2
  108. package/types-kR1kUlmz.cjs +67 -0
  109. package/{view-compiler-CSHSqZl7.mjs → view-compiler-BhKiezRH.mjs} +1 -1
  110. package/{view-compiler-NqiortOA.cjs → view-compiler-DgZadq1F.cjs} +1 -1
  111. package/vite.d.cts +1 -1
  112. package/vite.d.mts +1 -1
  113. package/drizzle-meta-BPnRLpsB.cjs +0 -8
  114. package/drizzle-meta-D00lFvAk.mjs +0 -3
  115. package/internal-D7qVRIFb.d.cts +0 -228
  116. package/types-8KSw2AWg.mjs +0 -8
  117. package/types-B8m39L1s.cjs +0 -19
package/drizzle.mjs CHANGED
@@ -1,15 +1,46 @@
1
1
  import { n as buildUniqueConstraints, r as discoverFromDrizzle, t as buildColumnsMeta } from "./drizzle-CZuOzIu4.mjs";
2
- import { t as DRIZZLE_META } from "./drizzle-meta-D00lFvAk.mjs";
2
+ import { S as isAnonymousFilter, b as authTableKind, g as AUTH_USERS_COLUMNS, h as DRIZZLE_META, v as AUTH_USERS_TABLE } from "./sync-Q0O-2kFI.mjs";
3
3
  import { t as BASE_REF } from "./projection-CzBI2NL8.mjs";
4
- import { a as compileProjectionPreview, i as compileProjectionJoins, n as compileProjectionFrom, r as compileProjectionIdentity, s as quoteIdent } from "./projection-sql-DQQdjw9I.mjs";
5
- import { asc, getTableColumns, getTableName, sql } from "drizzle-orm";
4
+ import { a as compileProjectionPreview, i as compileProjectionJoins, n as compileProjectionFrom, r as compileProjectionIdentity, s as quoteIdent$1 } from "./projection-sql-2joBkLz2.mjs";
5
+ import { a as CURSOR_ALIAS, c as hideCursorAlias, d as postgresDialect, l as keysetPage, o as EXACT_FORMAT, r as narrowedMetaValue, s as exactCursorRead } from "./from-sql-BD7gR4bC.mjs";
6
+ import { n as appIdLockdownSql, t as APP_ID_TABLE$1 } from "./app-id-5cB6yioz.mjs";
7
+ import { and, getTableColumns, getTableName, sql } from "drizzle-orm";
8
+ import { getTableConfig } from "drizzle-orm/pg-core";
9
+ // ../sdk/src/drizzle-keyset.ts
10
+ /**
11
+ * The `KeysetReads` of a Drizzle source (`fromDrizzle`,
12
+ * `fromDrizzleProjection`): the predicates `sqlKeysetReads` uses, built as
13
+ * Drizzle SQL so the id is a bound parameter. `cursor` is the raw column.
14
+ *
15
+ * `nullable` false (a NOT NULL column) skips the NULL-cursor read. A
16
+ * `timestamp` cursor also reads its `infinity` / `-infinity` rows in that
17
+ * first phase, by id: `to_char` reads them as NULL and no Date holds them, so
18
+ * in the `(cursor, id)` phase they would leave a full page with no position.
19
+ */
20
+ function drizzleKeysetReads(cursor, id, opts, page) {
21
+ const parts = [];
22
+ if (opts.nullable) parts.push(sql`${cursor} IS NULL`);
23
+ if (opts.timestamp) parts.push(sql`${cursor} = '-infinity'`, sql`${cursor} = 'infinity'`);
24
+ const unpositioned = parts.length === 0 ? null : sql`(${sql.join(parts, sql` OR `)})`;
25
+ const positioned = opts.timestamp ? sql`${cursor} > '-infinity' AND ${cursor} < 'infinity'` : sql`${cursor} IS NOT NULL`;
26
+ const below = opts.timestamp ? sql` AND ${cursor} < 'infinity'` : sql``;
27
+ const order = sql`${cursor} asc, ${id} asc`;
28
+ return {
29
+ ...unpositioned === null ? {} : { nulls: (afterId, n) => page(afterId === null ? unpositioned : sql`${unpositioned} AND ${id} > ${afterId}`, sql`${id} asc`, n) },
30
+ values: (after, n) => {
31
+ if (!after) return page(positioned, order, n);
32
+ const literal = sql.raw(after.literal);
33
+ return page(sql`(${cursor}, ${id}) > (${literal}, ${after.id}) AND ${cursor} >= ${literal}${below}`, order, n);
34
+ }
35
+ };
36
+ }
6
37
  // ../sdk/src/drizzle-projection.ts
7
38
  /** `<ref>.<column>` — the token `fields` carries and cloud-ingest reads. */
8
39
  function refToken(ref) {
9
40
  return `${ref.table}.${ref.column}`;
10
41
  }
11
42
  function refSql(ref) {
12
- return `${quoteIdent(ref.table)}.${quoteIdent(ref.column)}`;
43
+ return `${quoteIdent$1(ref.table)}.${quoteIdent$1(ref.column)}`;
13
44
  }
14
45
  function parseRef(value) {
15
46
  if (typeof value !== "string") return value;
@@ -46,17 +77,20 @@ function fromDrizzleProjection(db, projection, opts) {
46
77
  const cursorRef = parseRef(opts.cursorField);
47
78
  assertKnownRef(cursorRef, known, "cursorField");
48
79
  const cursorToken = refToken(cursorRef);
49
- const cursorExpr = `CAST(${refSql(cursorRef)} AS timestamptz)`;
50
- const cursorRead = `to_char(${cursorExpr} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;
51
- const selectItems = [`${identityExpr} AS ${quoteIdent("id")}`, `${cursorRead} AS ${quoteIdent(cursorToken)}`];
80
+ const cursorRaw = refSql(cursorRef);
81
+ const cursorRead = `to_char(CAST(${cursorRaw} AS timestamptz) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;
82
+ const selectItems = [`${identityExpr} AS ${quoteIdent$1("id")}`, `${cursorRead} AS ${quoteIdent$1(cursorToken)}`];
52
83
  const emitted = /* @__PURE__ */ new Set([cursorToken]);
53
84
  for (const binding of Object.values(projection.fieldBindings)) {
54
85
  const token = refToken(binding.from);
55
86
  if (emitted.has(token)) continue;
56
87
  emitted.add(token);
57
- selectItems.push(`${refSql(binding.from)} AS ${quoteIdent(token)}`);
88
+ selectItems.push(`${refSql(binding.from)} AS ${quoteIdent$1(token)}`);
58
89
  }
90
+ selectItems.push(`${exactCursorRead(cursorRaw)} AS ${quoteIdent$1(CURSOR_ALIAS)}`);
59
91
  const head = [`select ${selectItems.join(", ")}`, fromClause].join(" ");
92
+ const idSql = sql.raw(identityExpr);
93
+ const page = async (where, order, limit) => normalizeRows(await client.execute(sql`${sql.raw(head)} where ${where} order by ${order} limit ${limit}`));
60
94
  return {
61
95
  entity: opts.entity,
62
96
  pushSource: projection.baseTable,
@@ -64,9 +98,11 @@ function fromDrizzleProjection(db, projection, opts) {
64
98
  idField: "id",
65
99
  ...opts.objectType === void 0 ? {} : { objectType: opts.objectType },
66
100
  fetchPage: async ({ since, limit }) => {
67
- const where = since ? sql` where (${sql.raw(cursorExpr)}, ${sql.raw(identityExpr)}) > (${since.time.toISOString()}::timestamptz, ${since.id})` : sql``;
68
- const query = sql`${sql.raw(head)}${where} order by ${sql.raw(cursorExpr)} asc, ${sql.raw(identityExpr)} asc limit ${limit}`;
69
- return normalizeRows(await client.execute(query));
101
+ const rows = await keysetPage(since, limit, drizzleKeysetReads(sql.raw(cursorRaw), idSql, {
102
+ nullable: opts.cursorNullable ?? true,
103
+ timestamp: true
104
+ }, page));
105
+ return hideCursorAlias(rows);
70
106
  }
71
107
  };
72
108
  }
@@ -78,13 +114,13 @@ function fromDrizzleProjection(db, projection, opts) {
78
114
  * `"id"`, the alias every row carries either way.
79
115
  */
80
116
  function fromDrizzleProjectionByIdentity(client, projection, identityExpr, fromClause, opts) {
81
- const selectItems = [`${identityExpr} AS ${quoteIdent("id")}`];
117
+ const selectItems = [`${identityExpr} AS ${quoteIdent$1("id")}`];
82
118
  const emitted = /* @__PURE__ */ new Set();
83
119
  for (const binding of Object.values(projection.fieldBindings)) {
84
120
  const token = refToken(binding.from);
85
121
  if (emitted.has(token)) continue;
86
122
  emitted.add(token);
87
- selectItems.push(`${refSql(binding.from)} AS ${quoteIdent(token)}`);
123
+ selectItems.push(`${refSql(binding.from)} AS ${quoteIdent$1(token)}`);
88
124
  }
89
125
  const head = [`select ${selectItems.join(", ")}`, fromClause].join(" ");
90
126
  return {
@@ -92,6 +128,7 @@ function fromDrizzleProjectionByIdentity(client, projection, identityExpr, fromC
92
128
  pushSource: projection.baseTable,
93
129
  cursorField: "id",
94
130
  idField: "id",
131
+ mode: "full",
95
132
  ...opts.objectType === void 0 ? {} : { objectType: opts.objectType },
96
133
  fetchPage: async ({ since, limit }) => {
97
134
  const where = since ? sql` where ${sql.raw(identityExpr)} > ${since.id}` : sql``;
@@ -125,24 +162,94 @@ function inferIdField(table) {
125
162
  const kind = primaryKeys.length === 0 ? "no" : "a composite";
126
163
  throw new Error(`fromDrizzle: table "${getTableName(table)}" has ${kind} single-column primary key — pass { idField } explicitly.`);
127
164
  }
165
+ const AUTH_USERS_ALLOWED = AUTH_USERS_COLUMNS;
166
+ const META_COLUMN = "raw_user_meta_data";
167
+ const { quoteIdent } = postgresDialect;
168
+ function qualifiedTableName(table) {
169
+ const name = getTableName(table);
170
+ try {
171
+ const { schema } = getTableConfig(table);
172
+ return schema ? `${schema}.${name}` : name;
173
+ } catch {
174
+ return name;
175
+ }
176
+ }
177
+ /**
178
+ * The columns `fromDrizzle` may read from `table`, keyed by property key. A
179
+ * table in Supabase's `auth` schema gets the same rules as the no-ORM path:
180
+ * only `auth.users` is readable, only its allowlisted columns leave the
181
+ * database, and nothing else in `auth` is read at all. Whatever the host's
182
+ * Drizzle schema declares, it cannot widen that.
183
+ *
184
+ * The check is on the schema the table DECLARES. A bare `pgTable("users")`
185
+ * that the connection's `search_path` resolves to `auth.users` is not
186
+ * caught: nothing here reads `search_path`, deliberately (no extra query per
187
+ * source). The docs tell hosts to declare it with `pgSchema("auth")`, and the
188
+ * read-only role's column grant is the guarantee if they do not.
189
+ */
190
+ function readableColumns(table, opts) {
191
+ const all = getTableColumns(table);
192
+ const qualified = qualifiedTableName(table);
193
+ const kind = authTableKind(qualified);
194
+ if (kind === "other") throw new Error(`fromDrizzle: "${qualified}" is in the auth schema and cannot be read — only ${AUTH_USERS_TABLE} is exposed.`);
195
+ if (kind !== "users") return {
196
+ columns: all,
197
+ isAuthUsers: false
198
+ };
199
+ for (const key of [opts.cursorField, opts.idField]) {
200
+ const column = all[key];
201
+ if (column && !AUTH_USERS_ALLOWED.includes(column.name)) throw new Error(`fromDrizzle: column "${column.name}" is not exposed; ${AUTH_USERS_TABLE} only exposes ${AUTH_USERS_COLUMNS.join(", ")}.`);
202
+ }
203
+ const columns = {};
204
+ for (const [key, column] of Object.entries(all)) if (AUTH_USERS_ALLOWED.includes(column.name)) columns[key] = column;
205
+ return {
206
+ columns,
207
+ isAuthUsers: true
208
+ };
209
+ }
210
+ const TIMESTAMP_TYPE = /^timestamp/i;
211
+ const WITH_TIME_ZONE = /with time zone|^timestamptz/i;
212
+ /**
213
+ * The cursor column read as text for the internal position alias: a
214
+ * timestamp at full precision (`YYYY-MM-DDTHH:MM:SS.ffffffZ`, see
215
+ * `sql/keyset.ts`), anything else as its own text (only its NULL-ness is used).
216
+ */
217
+ function exactRead(column) {
218
+ const type = column.getSQLType();
219
+ if (!TIMESTAMP_TYPE.test(type)) return sql`${column}::text`;
220
+ const format = sql.raw(EXACT_FORMAT);
221
+ return WITH_TIME_ZONE.test(type) ? sql`to_char(${column} at time zone 'UTC', ${format})` : sql`to_char(${column}, ${format})`;
222
+ }
128
223
  function fromDrizzle(db, table, opts) {
129
224
  const drizzleDb = db;
130
225
  const idField = opts.idField ?? inferIdField(table);
131
- const columns = getTableColumns(table);
226
+ const { columns, isAuthUsers } = readableColumns(table, {
227
+ cursorField: opts.cursorField,
228
+ idField
229
+ });
132
230
  const cursorColumn = columns[opts.cursorField];
133
231
  const idColumn = columns[idField];
134
232
  if (!cursorColumn) throw new Error(`fromDrizzle: cursorField "${opts.cursorField}" is not a column on "${getTableName(table)}".`);
135
233
  if (!idColumn) throw new Error(`fromDrizzle: idField "${idField}" is not a column on "${getTableName(table)}".`);
136
234
  const projection = {};
137
- for (const column of Object.values(columns)) projection[column.name] = column;
235
+ for (const column of Object.values(columns)) projection[column.name] = isAuthUsers && column.name === META_COLUMN ? sql.raw(narrowedMetaValue(quoteIdent(META_COLUMN))).mapWith(column) : column;
138
236
  const cursorColumnName = cursorColumn.name;
139
237
  const idColumnName = idColumn.name;
238
+ const selected = {
239
+ ...projection,
240
+ [CURSOR_ALIAS]: exactRead(cursorColumn)
241
+ };
242
+ const scope = isAuthUsers ? sql.raw(`(${isAnonymousFilter})`) : void 0;
243
+ const page = (where, order, limit) => drizzleDb.select(selected).from(table).where(and(where, scope)).orderBy(order).limit(limit);
140
244
  const source = {
141
245
  entity: opts.entity,
142
246
  ...opts.pushSource === void 0 ? {} : { pushSource: opts.pushSource },
143
247
  cursorField: cursorColumnName,
144
248
  idField: idColumnName,
145
- fetchPage: ({ since, limit }) => drizzleDb.select(projection).from(table).where(since ? sql`(${cursorColumn}, ${idColumn}) > (${since.time}, ${since.id})` : void 0).orderBy(asc(cursorColumn), asc(idColumn)).limit(limit),
249
+ fetchPage: async ({ since, limit }) => hideCursorAlias(await keysetPage(since, limit, drizzleKeysetReads(cursorColumn, idColumn, {
250
+ nullable: !cursorColumn.notNull,
251
+ timestamp: TIMESTAMP_TYPE.test(cursorColumn.getSQLType())
252
+ }, page))),
146
253
  ...opts.objectType === void 0 ? {} : { objectType: opts.objectType }
147
254
  };
148
255
  const uniqueConstraints = buildUniqueConstraints(table);
@@ -151,7 +258,7 @@ function fromDrizzle(db, table, opts) {
151
258
  cursorField: opts.cursorField,
152
259
  idField,
153
260
  tableName: getTableName(table),
154
- columnsMeta: buildColumnsMeta(table),
261
+ columnsMeta: buildColumnsMeta(table).filter((column) => !isAuthUsers || AUTH_USERS_ALLOWED.includes(column.name)),
155
262
  ...uniqueConstraints === void 0 ? {} : { uniqueConstraints }
156
263
  };
157
264
  Object.defineProperty(source, DRIZZLE_META, {
@@ -224,7 +331,7 @@ function insertAndPush(clivly, db, table, opts) {
224
331
  };
225
332
  }
226
333
  /** The one-row host table that keeps the ID Clivly issued this app. */
227
- const APP_ID_TABLE = "crm_clivly_app";
334
+ const APP_ID_TABLE = APP_ID_TABLE$1;
228
335
  /**
229
336
  * An `AppIdStore` backed by a one-row `crm_clivly_app` table in this database,
230
337
  * created on first use. Clivly issues the ID on the first heartbeat and uses
@@ -240,7 +347,7 @@ function drizzleAppIdStore(db) {
240
347
  const table = sql.identifier(APP_ID_TABLE);
241
348
  let ready = null;
242
349
  const ensureTable = () => {
243
- ready ??= client.execute(sql`create table if not exists ${table} (app_id text primary key, created_at timestamptz not null default now())`).catch((error) => {
350
+ ready ??= client.execute(sql`create table if not exists ${table} (app_id text primary key, created_at timestamptz not null default now())`).then(() => client.execute(sql.raw(appIdLockdownSql(quoteIdent(APP_ID_TABLE))))).catch((error) => {
244
351
  ready = null;
245
352
  throw error;
246
353
  });
@@ -0,0 +1,23 @@
1
+ // ../sdk/src/sql/executor.ts
2
+ /** Covers pg.Pool, pg.Client and PGlite. */
3
+ function pgExecutor(client) {
4
+ return { async query(text, params) {
5
+ return (await client.query(text, params ? [...params] : void 0)).rows;
6
+ } };
7
+ }
8
+ function postgresJsExecutor(sql) {
9
+ return { async query(text, params) {
10
+ return await sql.unsafe(text, params ? [...params] : void 0);
11
+ } };
12
+ }
13
+ /**
14
+ * The postgres.js factory is injected so the SDK takes no dependency on it.
15
+ * `prepare: false` keeps it working behind transaction-mode poolers.
16
+ */
17
+ function connectPostgresJs(url, postgres) {
18
+ return postgresJsExecutor(postgres(url, {
19
+ prepare: false,
20
+ max: 1
21
+ }));
22
+ }
23
+ export { pgExecutor as n, postgresJsExecutor as r, connectPostgresJs as t };
@@ -0,0 +1,40 @@
1
+ // ../sdk/src/sql/executor.ts
2
+ /** Covers pg.Pool, pg.Client and PGlite. */
3
+ function pgExecutor(client) {
4
+ return { async query(text, params) {
5
+ return (await client.query(text, params ? [...params] : void 0)).rows;
6
+ } };
7
+ }
8
+ function postgresJsExecutor(sql) {
9
+ return { async query(text, params) {
10
+ return await sql.unsafe(text, params ? [...params] : void 0);
11
+ } };
12
+ }
13
+ /**
14
+ * The postgres.js factory is injected so the SDK takes no dependency on it.
15
+ * `prepare: false` keeps it working behind transaction-mode poolers.
16
+ */
17
+ function connectPostgresJs(url, postgres) {
18
+ return postgresJsExecutor(postgres(url, {
19
+ prepare: false,
20
+ max: 1
21
+ }));
22
+ }
23
+ Object.defineProperty(exports, "connectPostgresJs", {
24
+ enumerable: true,
25
+ get: function() {
26
+ return connectPostgresJs;
27
+ }
28
+ });
29
+ Object.defineProperty(exports, "pgExecutor", {
30
+ enumerable: true,
31
+ get: function() {
32
+ return pgExecutor;
33
+ }
34
+ });
35
+ Object.defineProperty(exports, "postgresJsExecutor", {
36
+ enumerable: true,
37
+ get: function() {
38
+ return postgresJsExecutor;
39
+ }
40
+ });
@@ -0,0 +1,282 @@
1
+ import { S as isAnonymousFilter, _ as AUTH_USERS_META_KEYS, a as isExactCursorTime, b as authTableKind, g as AUTH_USERS_COLUMNS, h as DRIZZLE_META, n as ROW_EXACT_CURSOR_KEY, o as isValidIsoTime, t as ROW_CURSOR_KEY, v as AUTH_USERS_TABLE, x as filtersAnonymous } from "./sync-Q0O-2kFI.mjs";
2
+ import { c as quoteTableRef, s as quoteIdent } from "./projection-sql-2joBkLz2.mjs";
3
+ // ../sdk/src/sql/dialect.ts
4
+ const postgresDialect = {
5
+ name: "postgres",
6
+ quoteIdent,
7
+ quoteTableRef,
8
+ param: (index) => `$${index}`,
9
+ timestampParam: (index) => `$${index}::timestamptz`
10
+ };
11
+ // ../sdk/src/sql/keyset.ts
12
+ /**
13
+ * Keyset paging shared by every cursored source (`fromDrizzle`,
14
+ * `fromDrizzleProjection`, `fromSql`, `fromSqlProjection`).
15
+ *
16
+ * Rows are ordered on the RAW `(cursor, id)` columns, so an index on them is
17
+ * walked in order. The position is carried at the database's precision: each
18
+ * row also reads its cursor as text with microseconds (`exactCursorRead`), and
19
+ * the next page compares `(cursor, id) > ('<that text>', id)` in Postgres. A
20
+ * JS Date keeps only milliseconds, and a cursor truncated to one re-read every
21
+ * row inside that millisecond, forever when a whole page shared it.
22
+ *
23
+ * Rows with no position come first, as if at the epoch (the `fromSql`
24
+ * semantics), read by id in a query of their own so neither query orders on
25
+ * an expression: a NULL cursor, and an `infinity` / `-infinity` timestamp,
26
+ * which `to_char` reads as NULL and no Date can hold. Every row is synced; an
27
+ * infinite stamp simply never moves the position.
28
+ */
29
+ /** Internal alias a page query reads the exact cursor under; never pushed. */
30
+ const CURSOR_ALIAS = "__clivly_cursor__";
31
+ /** `to_char` format of an exact cursor time. */
32
+ const EXACT_FORMAT = `'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'`;
33
+ const CURSOR_LITERAL = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z$/;
34
+ const UNSUPPORTED = "unsupported:";
35
+ /**
36
+ * SQL reading a timestamp cursor column as `YYYY-MM-DDTHH:MM:SS.ffffffZ`: the
37
+ * UTC instant of a `timestamptz`, the wall time of a `timestamp` (read as UTC,
38
+ * the convention Drizzle's own column mapping uses), for a caller that does
39
+ * not know which it has. Every branch type-checks for a text or date column
40
+ * too, which reads as `unsupported:<type>` and fails the page with a clear
41
+ * error (`hideCursorAlias`); keyset order on those would be wrong.
42
+ */
43
+ function exactCursorRead(column) {
44
+ return `case pg_typeof(${column}) when 'timestamp with time zone'::regtype then to_char(CAST(${column} AS timestamptz) at time zone 'UTC', ${EXACT_FORMAT}) when 'timestamp without time zone'::regtype then to_char(CAST(${column} AS timestamp), ${EXACT_FORMAT}) else '${UNSUPPORTED}' || pg_typeof(${column})::text end`;
45
+ }
46
+ const TIMESTAMP_TYPE = /^timestamp/i;
47
+ /** True for a timestamp type, or an undiscovered one (`undefined`). */
48
+ const isTimestampType = (type) => type === void 0 || TIMESTAMP_TYPE.test(type);
49
+ /**
50
+ * Throw at construction when a column's known type cannot be a cursor. Only
51
+ * `timestamp` and `timestamptz` order and compare as times; `undefined` (type
52
+ * not discovered) is left to the read-time check.
53
+ */
54
+ function assertTimestampCursor(label, column, type) {
55
+ if (!isTimestampType(type)) throw new Error(`${label}: cursorField "${column}" is ${type}; a cursor must be a timestamp or timestamptz column.`);
56
+ }
57
+ /**
58
+ * The rows with no position (see above), or null when the column can hold
59
+ * none: not nullable and not a timestamp. `timestamp` false is a Drizzle
60
+ * column of another type, which cannot hold `infinity`.
61
+ */
62
+ function unpositionedPredicate(column, opts) {
63
+ const parts = [];
64
+ if (opts.nullable) parts.push(`${column} IS NULL`);
65
+ if (opts.timestamp) parts.push(`${column} = '-infinity'`, `${column} = 'infinity'`);
66
+ return parts.length === 0 ? null : `(${parts.join(" OR ")})`;
67
+ }
68
+ /** The rows with a position: what `unpositionedPredicate` leaves out. */
69
+ function positionedPredicate(column, opts) {
70
+ return opts.timestamp ? `${column} > '-infinity' AND ${column} < 'infinity'` : `${column} IS NOT NULL`;
71
+ }
72
+ /**
73
+ * `since` as an untyped SQL literal. Untyped, it takes the cursor column's own
74
+ * type, so the comparison runs in Postgres at that type's precision, and no
75
+ * driver serialises a Date for it (node-postgres would send local time).
76
+ * Validated to plain ISO 8601 that names a real instant, so it can never
77
+ * carry a quote, and a value like month 99 fails here rather than in SQL.
78
+ */
79
+ function cursorLiteral(since) {
80
+ const value = since.exact ?? since.time.toISOString();
81
+ if (!(CURSOR_LITERAL.test(value) && isValidIsoTime(value))) throw new Error(`clivly: cursor time "${value}" is not ISO 8601 UTC.`);
82
+ return `'${value}'`;
83
+ }
84
+ /**
85
+ * Whether `since` stands among the NULL-cursor rows: the epoch with no exact
86
+ * value. A real row exactly at the epoch carries an exact value.
87
+ */
88
+ function isNullGroup(since) {
89
+ return since.exact === void 0 && since.time.getTime() === 0;
90
+ }
91
+ /** One page in `(unpositioned rows first, then (cursor, id))` order. */
92
+ async function keysetPage(since, limit, reads) {
93
+ if (since && !isNullGroup(since)) return await reads.values({
94
+ id: since.id,
95
+ literal: cursorLiteral(since)
96
+ }, limit);
97
+ const nulls = reads.nulls ? await reads.nulls(since?.id ?? null, limit) : [];
98
+ if (nulls.length >= limit) return nulls;
99
+ return [...nulls, ...await reads.values(null, limit - nulls.length)];
100
+ }
101
+ /**
102
+ * Move the exact-cursor alias off each row's visible keys, so the pushed row
103
+ * keeps its own (possibly NULL) cursor value. The position stays on the row,
104
+ * non-enumerable: the exact text, or the epoch for a row with no position.
105
+ */
106
+ function hideCursorAlias(rows) {
107
+ return rows.map((row) => {
108
+ if (!("__clivly_cursor__" in row)) return row;
109
+ const { [CURSOR_ALIAS]: exact, ...visible } = row;
110
+ if (typeof exact === "string" && exact.startsWith(UNSUPPORTED)) throw new Error(`clivly: the cursor column is ${exact.slice(12)}; a cursor must be a timestamp or timestamptz column.`);
111
+ if (exact === null || exact === void 0) Object.defineProperty(visible, ROW_CURSOR_KEY, {
112
+ value: /* @__PURE__ */ new Date(0),
113
+ enumerable: false
114
+ });
115
+ else if (typeof exact === "string" && isExactCursorTime(exact)) Object.defineProperty(visible, ROW_EXACT_CURSOR_KEY, {
116
+ value: exact,
117
+ enumerable: false
118
+ });
119
+ return visible;
120
+ });
121
+ }
122
+ /**
123
+ * The `KeysetReads` of a raw-SQL source (`fromSql`, `fromSqlProjection`) over
124
+ * a timestamp cursor: the same predicates and order for both.
125
+ */
126
+ function sqlKeysetReads(cursor, id, nullable, page) {
127
+ const unpositioned = unpositionedPredicate(cursor, {
128
+ nullable,
129
+ timestamp: true
130
+ });
131
+ const order = `${cursor}, ${id}`;
132
+ return {
133
+ ...unpositioned === null ? {} : { nulls: (afterId, n) => afterId === null ? page(unpositioned, id, [], n) : page(`${unpositioned} AND ${id} > $1`, id, [afterId], n) },
134
+ values: (after, n) => after ? page(`(${cursor}, ${id}) > (${after.literal}, $1) AND ${cursor} >= ${after.literal} AND ${cursor} < 'infinity'`, order, [after.id], n) : page(positionedPredicate(cursor, { timestamp: true }), order, [], n)
135
+ };
136
+ }
137
+ // ../sdk/src/sql/from-sql.ts
138
+ const DEFAULT_CURSOR_COLUMN = "updated_at";
139
+ /**
140
+ * Whether `table` is Supabase's `auth.users`; throws for any other `auth.*`
141
+ * table, which holds sessions, tokens or identities and is never read.
142
+ */
143
+ function authUsersOrRefuse(label, table) {
144
+ const kind = authTableKind(table);
145
+ if (kind === "other") throw new Error(`${label}: "${table}" is in the auth schema and cannot be read — only ${AUTH_USERS_TABLE} is exposed.`);
146
+ return kind === "users";
147
+ }
148
+ const META_COLUMN = "raw_user_meta_data";
149
+ const dialect = postgresDialect;
150
+ function inferIdField(meta, table) {
151
+ const primaryKeys = (meta.columnsMeta ?? []).filter((c) => c.isPrimaryKey);
152
+ const only = primaryKeys[0];
153
+ if (primaryKeys.length === 1 && only) return only.name;
154
+ const kind = primaryKeys.length === 0 ? "no" : "a composite";
155
+ throw new Error(`fromSql: table "${table}" has ${kind} single-column primary key — pass { idField } explicitly.`);
156
+ }
157
+ const quoteLiteral = (value) => `'${value.replaceAll("'", "''")}'`;
158
+ function narrowedMetaValue(columnSql) {
159
+ return `case when ${columnSql} is null then null else jsonb_strip_nulls(jsonb_build_object(${AUTH_USERS_META_KEYS.map((key) => `${quoteLiteral(key)}, ${columnSql}->${quoteLiteral(key)}`).join(", ")})) end`;
160
+ }
161
+ function narrowedMetaExpression() {
162
+ const col = dialect.quoteIdent(META_COLUMN);
163
+ return `${narrowedMetaValue(col)} as ${col}`;
164
+ }
165
+ function selectItem(column, isAuthUsers) {
166
+ if (isAuthUsers && column === META_COLUMN) return narrowedMetaExpression();
167
+ return dialect.quoteIdent(column);
168
+ }
169
+ function normaliseValue(value) {
170
+ if (typeof value !== "bigint") return value;
171
+ const asNumber = Number(value);
172
+ return Number.isSafeInteger(asNumber) ? asNumber : value.toString();
173
+ }
174
+ function normaliseRows(rows) {
175
+ return rows.map((row) => {
176
+ const out = {};
177
+ for (const [key, value] of Object.entries(row)) out[key] = normaliseValue(value);
178
+ return out;
179
+ });
180
+ }
181
+ function resolveColumns(opts, isAuthUsers, required) {
182
+ if (isAuthUsers) return [...AUTH_USERS_COLUMNS];
183
+ const base = opts.columns ?? opts.meta.columns;
184
+ return [.../* @__PURE__ */ new Set([...base, ...required])];
185
+ }
186
+ function assertColumn(meta, table, label, column) {
187
+ if (!meta.columns.includes(column)) throw new Error(`fromSql: ${label} "${column}" is not a column on "${table}".`);
188
+ }
189
+ function buildPredicate(opts, excludeAnonymous, keyset) {
190
+ const parts = [];
191
+ if (keyset) parts.push(keyset);
192
+ if (opts.where) parts.push(`(${opts.where})`);
193
+ if (excludeAnonymous) parts.push(`(${isAnonymousFilter})`);
194
+ return parts.length === 0 ? "" : ` where ${parts.join(" and ")}`;
195
+ }
196
+ /**
197
+ * The id and cursor of every auth.users row leave the host, so each must be
198
+ * an allowlisted column, and never `raw_user_meta_data` (which is narrowed
199
+ * only when read as a field). `resolveColumns` ignores `required` for
200
+ * auth.users, so without this the cursor read would still reach the column.
201
+ */
202
+ function assertAuthUsersKey(option, column) {
203
+ if (column === void 0 || column !== META_COLUMN && AUTH_USERS_COLUMNS.includes(column)) return;
204
+ throw new Error(`fromSql: ${option} "${column}" is not allowed; auth.users only allows ${AUTH_USERS_COLUMNS.filter((c) => c !== META_COLUMN).join(", ")} as ${option}.`);
205
+ }
206
+ function fromSql(executor, opts) {
207
+ const { meta, table } = opts;
208
+ const isAuthUsers = authUsersOrRefuse("fromSql", table);
209
+ const excludeAnonymous = isAuthUsers && filtersAnonymous(meta);
210
+ const idField = opts.idField ?? inferIdField(meta, table);
211
+ assertColumn(meta, table, "idField", idField);
212
+ const defaultMeta = meta.columnsMeta?.find((c) => c.name === DEFAULT_CURSOR_COLUMN);
213
+ const cursorField = opts.cursorField ?? (meta.columns.includes(DEFAULT_CURSOR_COLUMN) && isTimestampType(defaultMeta?.type) ? DEFAULT_CURSOR_COLUMN : void 0);
214
+ const cursorMeta = meta.columnsMeta?.find((c) => c.name === cursorField);
215
+ if (cursorField !== void 0) {
216
+ assertColumn(meta, table, "cursorField", cursorField);
217
+ assertTimestampCursor("fromSql", cursorField, cursorMeta?.type);
218
+ }
219
+ if (isAuthUsers) {
220
+ assertAuthUsersKey("idField", idField);
221
+ assertAuthUsersKey("cursorField", cursorField);
222
+ }
223
+ const cursorNullable = cursorMeta?.nullable !== false;
224
+ const columns = resolveColumns(opts, isAuthUsers, cursorField === void 0 ? [idField] : [cursorField, idField]);
225
+ const items = columns.map((c) => selectItem(c, isAuthUsers));
226
+ if (cursorField !== void 0) items.push(`${exactCursorRead(dialect.quoteIdent(cursorField))} as ${dialect.quoteIdent(CURSOR_ALIAS)}`);
227
+ const head = `select ${items.join(", ")} from ${dialect.quoteTableRef(table)}`;
228
+ const idSql = dialect.quoteIdent(idField);
229
+ const page = async (keyset, order, params, limit) => {
230
+ const all = [...params, limit];
231
+ const text = `${head}${buildPredicate(opts, excludeAnonymous, keyset)} order by ${order} limit ${dialect.param(all.length)}`;
232
+ return normaliseRows(await executor.query(text, all));
233
+ };
234
+ const fetchIdPage = async ({ afterId, limit }) => await page(afterId === null ? null : `${idSql} > ${dialect.param(1)}`, idSql, afterId === null ? [] : [afterId], limit);
235
+ const fetchPage = async ({ since, limit }) => {
236
+ if (cursorField === void 0) return await fetchIdPage({
237
+ afterId: since?.id ?? null,
238
+ limit
239
+ });
240
+ return hideCursorAlias(await keysetPage(since, limit, sqlKeysetReads(dialect.quoteIdent(cursorField), idSql, cursorNullable, page)));
241
+ };
242
+ const source = {
243
+ entity: opts.entity,
244
+ ...opts.pushSource === void 0 ? {} : { pushSource: opts.pushSource },
245
+ cursorField: cursorField ?? idField,
246
+ idField,
247
+ ...cursorField === void 0 ? { mode: "full" } : {},
248
+ fetchPage,
249
+ fetchIdPage,
250
+ ...opts.objectType === void 0 ? {} : { objectType: opts.objectType }
251
+ };
252
+ const sourceMeta = {
253
+ kind: "sql",
254
+ columnKeys: columns,
255
+ columnsMeta: meta.columnsMeta,
256
+ cursorField: cursorField ?? idField,
257
+ idField,
258
+ tableName: table,
259
+ ...meta.uniqueConstraints === void 0 ? {} : { uniqueConstraints: meta.uniqueConstraints }
260
+ };
261
+ Object.defineProperty(source, DRIZZLE_META, {
262
+ value: sourceMeta,
263
+ enumerable: false
264
+ });
265
+ return source;
266
+ }
267
+ /**
268
+ * Whether `fromSql` would sync at least one row for `table`: one
269
+ * `exists(... limit 1)` under `buildPredicate`, the predicate every page query
270
+ * uses, so the `auth.users` anonymous exclusion cannot drift. The projection
271
+ * path (`baseGuard` in projection.ts) applies the same `isAnonymousFilter`;
272
+ * keep the two in step. A boolean on purpose: `/clivly/connect` is a public GET,
273
+ * so it must not reveal how many users exist or run a full count.
274
+ */
275
+ async function existsFromSql(executor, opts) {
276
+ const isAuthUsers = authUsersOrRefuse("existsFromSql", opts.table);
277
+ const predicate = buildPredicate({ where: opts.where }, isAuthUsers && opts.filterAnonymous !== false, null);
278
+ const text = `select exists(select 1 from ${dialect.quoteTableRef(opts.table)}${predicate} limit 1) as present`;
279
+ const [row] = await executor.query(text, []);
280
+ return row?.present === true;
281
+ }
282
+ export { CURSOR_ALIAS as a, hideCursorAlias as c, postgresDialect as d, normaliseRows as i, keysetPage as l, fromSql as n, EXACT_FORMAT as o, narrowedMetaValue as r, exactCursorRead as s, existsFromSql as t, sqlKeysetReads as u };