clivly 0.24.0-next.0 → 0.24.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 (54) hide show
  1. package/README.md +26 -14
  2. package/app-id-5cB6yioz.mjs +53 -0
  3. package/app-id-DcQ4u1c8.cjs +70 -0
  4. package/drizzle.cjs +120 -13
  5. package/drizzle.d.cts +7 -1
  6. package/drizzle.d.mts +7 -1
  7. package/drizzle.mjs +126 -19
  8. package/from-sql-BD7gR4bC.mjs +282 -0
  9. package/from-sql-CFgXkCe2.cjs +347 -0
  10. package/{index-CZkp8TV4.d.cts → from-sql-CpGP7K3J.d.mts} +8 -46
  11. package/{index-Cnrz4ywf.d.mts → from-sql-S8dSvU-e.d.cts} +8 -46
  12. package/index-BoemTWH4.d.mts +134 -0
  13. package/index-CIupXz_w.d.cts +134 -0
  14. package/index.cjs +246 -76
  15. package/index.d.cts +11 -2
  16. package/index.d.mts +11 -2
  17. package/index.mjs +245 -75
  18. package/introspector-5w2x89RD.mjs +55 -0
  19. package/introspector-DT_Ma59k.cjs +60 -0
  20. package/kysely.cjs +56 -0
  21. package/kysely.d.cts +45 -0
  22. package/kysely.d.mts +45 -0
  23. package/kysely.mjs +54 -0
  24. package/{namespace-probe--GvxJ06J.d.mts → namespace-probe-CUR2zG2l.d.mts} +33 -3
  25. package/package.json +15 -1
  26. package/projection-guard-C70l5U24.cjs +170 -0
  27. package/projection-guard-DOt_nbGn.mjs +147 -0
  28. package/sdk.cjs +1 -1
  29. package/sdk.d.cts +1 -1
  30. package/sdk.d.mts +1 -1
  31. package/sdk.mjs +1 -1
  32. package/sql.cjs +14 -7
  33. package/sql.d.cts +3 -2
  34. package/sql.d.mts +3 -2
  35. package/sql.mjs +6 -3
  36. package/{src-X0-yIA3O.cjs → src-CZIdwwI2.cjs} +162 -59
  37. package/{src-Dq2nY1Sj.mjs → src-tFhC1Ru2.mjs} +141 -38
  38. package/supabase-contact-3ke1KKUs.mjs +595 -0
  39. package/supabase-contact-BXQ0nnLq.cjs +624 -0
  40. package/supabase.cjs +30 -120
  41. package/supabase.d.cts +2 -1
  42. package/supabase.d.mts +2 -1
  43. package/supabase.mjs +27 -117
  44. package/{projection-guard-D8VUhCz7.cjs → sync-CdA9dgZz.cjs} +165 -154
  45. package/{projection-guard-7AMY0aCk.mjs → sync-Q0O-2kFI.mjs} +136 -143
  46. package/{types-UR-tT4c1.d.cts → types-CzL7lUH9.d.cts} +33 -3
  47. package/vite.d.cts +1 -1
  48. package/vite.d.mts +1 -1
  49. package/discover-BZIPXl23.cjs +0 -200
  50. package/discover-CFIi43Qn.mjs +0 -195
  51. package/drizzle-meta-BPnRLpsB.cjs +0 -8
  52. package/drizzle-meta-D00lFvAk.mjs +0 -3
  53. package/introspector-BwYgHGcS.cjs +0 -363
  54. package/introspector-Bz52xOUr.mjs +0 -334
package/README.md CHANGED
@@ -184,20 +184,32 @@ When the app has no Drizzle schema, `init` takes one of two paths.
184
184
 
185
185
  - **Server apps** (Next.js, TanStack Start and others), when `init` can read the
186
186
  schema: it writes `clivly.config.ts` using `fromSql`, `discoverFromSql`,
187
- `sqlIntrospector` and `sqlAppIdStore` from `clivly/sql`. It reads the schema
188
- from `DATABASE_URL` or `SUPABASE_DB_URL` (environment, `.env.local` or
189
- `.env`; never printed or stored), or from the linked Supabase CLI
190
- (`supabase db query --linked --output json`), and needs your app's own
191
- `postgres` or `pg` package. The config reads `DATABASE_URL || SUPABASE_DB_URL`;
192
- with neither set the app builds, but at runtime it logs one error and never
193
- contacts Clivly.
187
+ `sqlIntrospector` and `sqlAppIdStore` from `clivly/sql`, with `pgExecutor`
188
+ or `connectPostgresJs` as the client. A Supabase Auth contact is read through
189
+ `supabaseContactSource`, which joins `public.profiles` when its id
190
+ references `auth.users` and gives each contact a flat `full_name`. It reads
191
+ the schema from `DATABASE_URL` or `SUPABASE_DB_URL` (environment,
192
+ `.env.local` or `.env`; never printed or stored), which uses your app's
193
+ `postgres` or `pg`, or from the linked Supabase CLI
194
+ (`supabase db query --linked --output json`, falling back to
195
+ `npx --yes supabase`), which needs no driver. The CLI runs only once the
196
+ project is linked (`supabase/.temp/project-ref` exists); otherwise `init`
197
+ prints the `npx supabase link` hint and downloads nothing. If the app has
198
+ neither driver,
199
+ `init` installs `postgres` for the generated config. The config reads
200
+ `DATABASE_URL || SUPABASE_DB_URL`; with neither set the app builds, but at
201
+ runtime it logs one error and never contacts Clivly.
194
202
  - **Browser-only apps** (Vite SPA, Lovable, Bolt), or when no schema could be
195
203
  read: it writes `supabase/functions/clivly/index.ts`, `deno.json` and a
196
- `[functions.clivly] verify_jwt = false` block in `supabase/config.toml`. Set
197
- `CLIVLY_SECRET_KEY` and `CLIVLY_SYNC_TRIGGER_SECRET` as function secrets,
198
- deploy with `supabase functions deploy clivly`, then run
199
- `npx clivly connect --supabase` (`--project-url` overrides detection). It
200
- succeeds only when at least one contact would sync.
204
+ `[functions.clivly] verify_jwt = false` block in `supabase/config.toml`. In
205
+ this order: set `CLIVLY_SECRET_KEY` as a function secret, deploy with
206
+ `npx supabase functions deploy clivly`, run `npx clivly connect --supabase`
207
+ (`--project-url` overrides detection; it succeeds only when at least one
208
+ contact would sync, and sends the first heartbeat), then generate the trigger
209
+ secret at Connections → Setup → "Clivly can start a sync" and set it with
210
+ `npx supabase secrets set CLIVLY_SYNC_TRIGGER_SECRET=…` (no redeploy).
211
+ Start the first sync: Clivly dashboard → Connections → Setup →
212
+ "Run the first sync".
201
213
 
202
214
  `auth.users` contributes only `id`, `email`, `phone`, `created_at`,
203
215
  `updated_at`, `last_sign_in_at` and `full_name`, `name` and `avatar_url` from
@@ -298,7 +310,7 @@ the CLI requires pairing.
298
310
  | Value | Where to get it | Notes |
299
311
  | --- | --- | --- |
300
312
  | `CLIVLY_SECRET_KEY` | Dashboard → **Connect app**, or **Settings → API keys** | **Shown once.** Copy it immediately; you cannot retrieve it later, only regenerate. Regenerating **revokes the previous key**, so redeploy after rotating. The legacy name `CLIVLY_API_KEY` is still accepted as a fallback |
301
- | `CLIVLY_SYNC_TRIGGER_SECRET` | Dashboard → **Integrations → Remote sync** | Must match the value in your app's env exactly. A mismatch surfaces as a `401` on the signed trigger |
313
+ | `CLIVLY_SYNC_TRIGGER_SECRET` | Dashboard → **Connections → Setup → "Clivly can start a sync"** (Generate secret; unlocks after the first heartbeat) | Must match the value in your app's env exactly. A mismatch surfaces as a `401` on the signed trigger |
302
314
  | `CLIVLY_SYNC_TRIGGER_URL` | Your own deployment | The public URL of your mounted tick route. `init` and `login` leave the variable empty and add a commented `https://<yourDomain.com>/api/clivly/tick` example. Most platforms derive it automatically; uncomment and replace the example only when needed. Optional until you deploy — push-only setups can leave it empty |
303
315
  | `CLIVLY_PUBLISHABLE_KEY` | Same place as the secret key | Only needed for the chat widget. Safe to expose in client code |
304
316
 
@@ -450,7 +462,7 @@ Clivly push-schema
450
462
  ✅ Schema reported to Clivly.
451
463
  ✅ Created 1 custom object: client_accounts.
452
464
  ✅ Mapped 2 entities: clients, advisors.
453
- Open Integrations → Mapping to review them.
465
+ Open Clivly dashboard → Connections → What syncs to review them.
454
466
  ```
455
467
 
456
468
  **Exits `1` if Clivly refuses your config** — most often because an entity would
@@ -0,0 +1,53 @@
1
+ import { d as postgresDialect } from "./from-sql-BD7gR4bC.mjs";
2
+ // ../sdk/src/sql/app-id.ts
3
+ /** The one-row host table that keeps the ID Clivly issued this app. */
4
+ const APP_ID_TABLE = "crm_clivly_app";
5
+ /** Roles Supabase's Data API serves as. Plain Postgres has neither. */
6
+ const DATA_API_ROLES = ["anon", "authenticated"];
7
+ /**
8
+ * Keeps `crm_clivly_app` off Supabase's Data API. Supabase grants `anon` and
9
+ * `authenticated` ALL on every new `public` table, and the anon key ships in
10
+ * every frontend, so without this anyone could read or rewrite the app ID
11
+ * over `/rest/v1/crm_clivly_app` (and Security Advisor flags "RLS disabled in
12
+ * public"). Enabling RLS with no policies hides the rows from both roles; the
13
+ * revoke removes the grant itself. The SDK connects as the table's owner, so
14
+ * neither affects it.
15
+ *
16
+ * One `do` block, safe to run on every boot: each role is revoked only when
17
+ * `pg_roles` has it, so plain Postgres is untouched, and a connection that
18
+ * does not own the table (it was created by another role) skips the RLS step
19
+ * with a warning instead of failing the heartbeat.
20
+ */
21
+ function appIdLockdownSql(quotedTable) {
22
+ const revokes = DATA_API_ROLES.map((role) => `if exists (select 1 from pg_roles where rolname = '${role}') then revoke all on table ${quotedTable} from ${role}; end if;`).join(" ");
23
+ return `do $clivly$ begin begin alter table ${quotedTable} enable row level security; exception when insufficient_privilege then raise warning 'clivly: could not enable row level security on ${quotedTable.replaceAll("\"", "")}'; end; ${revokes} end $clivly$`;
24
+ }
25
+ /**
26
+ * The raw-SQL twin of `drizzleAppIdStore`: an `AppIdStore` backed by a
27
+ * one-row `crm_clivly_app` table, created on first use. The only write Clivly
28
+ * ever makes to a host database.
29
+ */
30
+ function sqlAppIdStore(executor) {
31
+ const { quoteIdent, param } = postgresDialect;
32
+ const table = quoteIdent(APP_ID_TABLE);
33
+ let ready = null;
34
+ const ensureTable = () => {
35
+ ready ??= executor.query(`create table if not exists ${table} (app_id text primary key, created_at timestamptz not null default now())`).then(() => executor.query(appIdLockdownSql(table))).catch((error) => {
36
+ ready = null;
37
+ throw error;
38
+ });
39
+ return ready;
40
+ };
41
+ return {
42
+ async get() {
43
+ await ensureTable();
44
+ const value = (await executor.query(`select app_id from ${table} order by created_at limit 1`))[0]?.app_id;
45
+ return typeof value === "string" ? value : null;
46
+ },
47
+ async set(appId) {
48
+ await ensureTable();
49
+ await executor.query(`insert into ${table} (app_id) select ${param(1)} where not exists (select 1 from ${table})`, [appId]);
50
+ }
51
+ };
52
+ }
53
+ export { appIdLockdownSql as n, sqlAppIdStore as r, APP_ID_TABLE as t };
@@ -0,0 +1,70 @@
1
+ const require_from_sql = require("./from-sql-CFgXkCe2.cjs");
2
+ // ../sdk/src/sql/app-id.ts
3
+ /** The one-row host table that keeps the ID Clivly issued this app. */
4
+ const APP_ID_TABLE = "crm_clivly_app";
5
+ /** Roles Supabase's Data API serves as. Plain Postgres has neither. */
6
+ const DATA_API_ROLES = ["anon", "authenticated"];
7
+ /**
8
+ * Keeps `crm_clivly_app` off Supabase's Data API. Supabase grants `anon` and
9
+ * `authenticated` ALL on every new `public` table, and the anon key ships in
10
+ * every frontend, so without this anyone could read or rewrite the app ID
11
+ * over `/rest/v1/crm_clivly_app` (and Security Advisor flags "RLS disabled in
12
+ * public"). Enabling RLS with no policies hides the rows from both roles; the
13
+ * revoke removes the grant itself. The SDK connects as the table's owner, so
14
+ * neither affects it.
15
+ *
16
+ * One `do` block, safe to run on every boot: each role is revoked only when
17
+ * `pg_roles` has it, so plain Postgres is untouched, and a connection that
18
+ * does not own the table (it was created by another role) skips the RLS step
19
+ * with a warning instead of failing the heartbeat.
20
+ */
21
+ function appIdLockdownSql(quotedTable) {
22
+ const revokes = DATA_API_ROLES.map((role) => `if exists (select 1 from pg_roles where rolname = '${role}') then revoke all on table ${quotedTable} from ${role}; end if;`).join(" ");
23
+ return `do $clivly$ begin begin alter table ${quotedTable} enable row level security; exception when insufficient_privilege then raise warning 'clivly: could not enable row level security on ${quotedTable.replaceAll("\"", "")}'; end; ${revokes} end $clivly$`;
24
+ }
25
+ /**
26
+ * The raw-SQL twin of `drizzleAppIdStore`: an `AppIdStore` backed by a
27
+ * one-row `crm_clivly_app` table, created on first use. The only write Clivly
28
+ * ever makes to a host database.
29
+ */
30
+ function sqlAppIdStore(executor) {
31
+ const { quoteIdent, param } = require_from_sql.postgresDialect;
32
+ const table = quoteIdent(APP_ID_TABLE);
33
+ let ready = null;
34
+ const ensureTable = () => {
35
+ ready ??= executor.query(`create table if not exists ${table} (app_id text primary key, created_at timestamptz not null default now())`).then(() => executor.query(appIdLockdownSql(table))).catch((error) => {
36
+ ready = null;
37
+ throw error;
38
+ });
39
+ return ready;
40
+ };
41
+ return {
42
+ async get() {
43
+ await ensureTable();
44
+ const value = (await executor.query(`select app_id from ${table} order by created_at limit 1`))[0]?.app_id;
45
+ return typeof value === "string" ? value : null;
46
+ },
47
+ async set(appId) {
48
+ await ensureTable();
49
+ await executor.query(`insert into ${table} (app_id) select ${param(1)} where not exists (select 1 from ${table})`, [appId]);
50
+ }
51
+ };
52
+ }
53
+ Object.defineProperty(exports, "APP_ID_TABLE", {
54
+ enumerable: true,
55
+ get: function() {
56
+ return APP_ID_TABLE;
57
+ }
58
+ });
59
+ Object.defineProperty(exports, "appIdLockdownSql", {
60
+ enumerable: true,
61
+ get: function() {
62
+ return appIdLockdownSql;
63
+ }
64
+ });
65
+ Object.defineProperty(exports, "sqlAppIdStore", {
66
+ enumerable: true,
67
+ get: function() {
68
+ return sqlAppIdStore;
69
+ }
70
+ });
package/drizzle.cjs CHANGED
@@ -1,9 +1,40 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_drizzle = require("./drizzle-C0bfX-6a.cjs");
3
- const require_drizzle_meta = require("./drizzle-meta-BPnRLpsB.cjs");
3
+ const require_sync = require("./sync-CdA9dgZz.cjs");
4
4
  const require_projection = require("./projection-w4Z6vSL2.cjs");
5
5
  const require_projection_sql = require("./projection-sql-DS5sVTY-.cjs");
6
+ const require_from_sql = require("./from-sql-CFgXkCe2.cjs");
7
+ const require_app_id = require("./app-id-DcQ4u1c8.cjs");
6
8
  let drizzle_orm = require("drizzle-orm");
9
+ let drizzle_orm_pg_core = require("drizzle-orm/pg-core");
10
+ // ../sdk/src/drizzle-keyset.ts
11
+ /**
12
+ * The `KeysetReads` of a Drizzle source (`fromDrizzle`,
13
+ * `fromDrizzleProjection`): the predicates `sqlKeysetReads` uses, built as
14
+ * Drizzle SQL so the id is a bound parameter. `cursor` is the raw column.
15
+ *
16
+ * `nullable` false (a NOT NULL column) skips the NULL-cursor read. A
17
+ * `timestamp` cursor also reads its `infinity` / `-infinity` rows in that
18
+ * first phase, by id: `to_char` reads them as NULL and no Date holds them, so
19
+ * in the `(cursor, id)` phase they would leave a full page with no position.
20
+ */
21
+ function drizzleKeysetReads(cursor, id, opts, page) {
22
+ const parts = [];
23
+ if (opts.nullable) parts.push(drizzle_orm.sql`${cursor} IS NULL`);
24
+ if (opts.timestamp) parts.push(drizzle_orm.sql`${cursor} = '-infinity'`, drizzle_orm.sql`${cursor} = 'infinity'`);
25
+ const unpositioned = parts.length === 0 ? null : drizzle_orm.sql`(${drizzle_orm.sql.join(parts, drizzle_orm.sql` OR `)})`;
26
+ const positioned = opts.timestamp ? drizzle_orm.sql`${cursor} > '-infinity' AND ${cursor} < 'infinity'` : drizzle_orm.sql`${cursor} IS NOT NULL`;
27
+ const below = opts.timestamp ? drizzle_orm.sql` AND ${cursor} < 'infinity'` : drizzle_orm.sql``;
28
+ const order = drizzle_orm.sql`${cursor} asc, ${id} asc`;
29
+ return {
30
+ ...unpositioned === null ? {} : { nulls: (afterId, n) => page(afterId === null ? unpositioned : drizzle_orm.sql`${unpositioned} AND ${id} > ${afterId}`, drizzle_orm.sql`${id} asc`, n) },
31
+ values: (after, n) => {
32
+ if (!after) return page(positioned, order, n);
33
+ const literal = drizzle_orm.sql.raw(after.literal);
34
+ return page(drizzle_orm.sql`(${cursor}, ${id}) > (${literal}, ${after.id}) AND ${cursor} >= ${literal}${below}`, order, n);
35
+ }
36
+ };
37
+ }
7
38
  // ../sdk/src/drizzle-projection.ts
8
39
  /** `<ref>.<column>` — the token `fields` carries and cloud-ingest reads. */
9
40
  function refToken(ref) {
@@ -47,8 +78,8 @@ function fromDrizzleProjection(db, projection, opts) {
47
78
  const cursorRef = parseRef(opts.cursorField);
48
79
  assertKnownRef(cursorRef, known, "cursorField");
49
80
  const cursorToken = refToken(cursorRef);
50
- const cursorExpr = `CAST(${refSql(cursorRef)} AS timestamptz)`;
51
- const cursorRead = `to_char(${cursorExpr} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;
81
+ const cursorRaw = refSql(cursorRef);
82
+ const cursorRead = `to_char(CAST(${cursorRaw} AS timestamptz) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;
52
83
  const selectItems = [`${identityExpr} AS ${require_projection_sql.quoteIdent("id")}`, `${cursorRead} AS ${require_projection_sql.quoteIdent(cursorToken)}`];
53
84
  const emitted = /* @__PURE__ */ new Set([cursorToken]);
54
85
  for (const binding of Object.values(projection.fieldBindings)) {
@@ -57,7 +88,10 @@ function fromDrizzleProjection(db, projection, opts) {
57
88
  emitted.add(token);
58
89
  selectItems.push(`${refSql(binding.from)} AS ${require_projection_sql.quoteIdent(token)}`);
59
90
  }
91
+ selectItems.push(`${require_from_sql.exactCursorRead(cursorRaw)} AS ${require_projection_sql.quoteIdent(require_from_sql.CURSOR_ALIAS)}`);
60
92
  const head = [`select ${selectItems.join(", ")}`, fromClause].join(" ");
93
+ const idSql = drizzle_orm.sql.raw(identityExpr);
94
+ const page = async (where, order, limit) => normalizeRows(await client.execute(drizzle_orm.sql`${drizzle_orm.sql.raw(head)} where ${where} order by ${order} limit ${limit}`));
61
95
  return {
62
96
  entity: opts.entity,
63
97
  pushSource: projection.baseTable,
@@ -65,9 +99,11 @@ function fromDrizzleProjection(db, projection, opts) {
65
99
  idField: "id",
66
100
  ...opts.objectType === void 0 ? {} : { objectType: opts.objectType },
67
101
  fetchPage: async ({ since, limit }) => {
68
- const where = since ? drizzle_orm.sql` where (${drizzle_orm.sql.raw(cursorExpr)}, ${drizzle_orm.sql.raw(identityExpr)}) > (${since.time.toISOString()}::timestamptz, ${since.id})` : drizzle_orm.sql``;
69
- const query = drizzle_orm.sql`${drizzle_orm.sql.raw(head)}${where} order by ${drizzle_orm.sql.raw(cursorExpr)} asc, ${drizzle_orm.sql.raw(identityExpr)} asc limit ${limit}`;
70
- return normalizeRows(await client.execute(query));
102
+ const rows = await require_from_sql.keysetPage(since, limit, drizzleKeysetReads(drizzle_orm.sql.raw(cursorRaw), idSql, {
103
+ nullable: opts.cursorNullable ?? true,
104
+ timestamp: true
105
+ }, page));
106
+ return require_from_sql.hideCursorAlias(rows);
71
107
  }
72
108
  };
73
109
  }
@@ -93,6 +129,7 @@ function fromDrizzleProjectionByIdentity(client, projection, identityExpr, fromC
93
129
  pushSource: projection.baseTable,
94
130
  cursorField: "id",
95
131
  idField: "id",
132
+ mode: "full",
96
133
  ...opts.objectType === void 0 ? {} : { objectType: opts.objectType },
97
134
  fetchPage: async ({ since, limit }) => {
98
135
  const where = since ? drizzle_orm.sql` where ${drizzle_orm.sql.raw(identityExpr)} > ${since.id}` : drizzle_orm.sql``;
@@ -126,24 +163,94 @@ function inferIdField(table) {
126
163
  const kind = primaryKeys.length === 0 ? "no" : "a composite";
127
164
  throw new Error(`fromDrizzle: table "${(0, drizzle_orm.getTableName)(table)}" has ${kind} single-column primary key — pass { idField } explicitly.`);
128
165
  }
166
+ const AUTH_USERS_ALLOWED = require_sync.AUTH_USERS_COLUMNS;
167
+ const META_COLUMN = "raw_user_meta_data";
168
+ const { quoteIdent } = require_from_sql.postgresDialect;
169
+ function qualifiedTableName(table) {
170
+ const name = (0, drizzle_orm.getTableName)(table);
171
+ try {
172
+ const { schema } = (0, drizzle_orm_pg_core.getTableConfig)(table);
173
+ return schema ? `${schema}.${name}` : name;
174
+ } catch {
175
+ return name;
176
+ }
177
+ }
178
+ /**
179
+ * The columns `fromDrizzle` may read from `table`, keyed by property key. A
180
+ * table in Supabase's `auth` schema gets the same rules as the no-ORM path:
181
+ * only `auth.users` is readable, only its allowlisted columns leave the
182
+ * database, and nothing else in `auth` is read at all. Whatever the host's
183
+ * Drizzle schema declares, it cannot widen that.
184
+ *
185
+ * The check is on the schema the table DECLARES. A bare `pgTable("users")`
186
+ * that the connection's `search_path` resolves to `auth.users` is not
187
+ * caught: nothing here reads `search_path`, deliberately (no extra query per
188
+ * source). The docs tell hosts to declare it with `pgSchema("auth")`, and the
189
+ * read-only role's column grant is the guarantee if they do not.
190
+ */
191
+ function readableColumns(table, opts) {
192
+ const all = (0, drizzle_orm.getTableColumns)(table);
193
+ const qualified = qualifiedTableName(table);
194
+ const kind = require_sync.authTableKind(qualified);
195
+ if (kind === "other") throw new Error(`fromDrizzle: "${qualified}" is in the auth schema and cannot be read — only ${require_sync.AUTH_USERS_TABLE} is exposed.`);
196
+ if (kind !== "users") return {
197
+ columns: all,
198
+ isAuthUsers: false
199
+ };
200
+ for (const key of [opts.cursorField, opts.idField]) {
201
+ const column = all[key];
202
+ if (column && !AUTH_USERS_ALLOWED.includes(column.name)) throw new Error(`fromDrizzle: column "${column.name}" is not exposed; ${require_sync.AUTH_USERS_TABLE} only exposes ${require_sync.AUTH_USERS_COLUMNS.join(", ")}.`);
203
+ }
204
+ const columns = {};
205
+ for (const [key, column] of Object.entries(all)) if (AUTH_USERS_ALLOWED.includes(column.name)) columns[key] = column;
206
+ return {
207
+ columns,
208
+ isAuthUsers: true
209
+ };
210
+ }
211
+ const TIMESTAMP_TYPE = /^timestamp/i;
212
+ const WITH_TIME_ZONE = /with time zone|^timestamptz/i;
213
+ /**
214
+ * The cursor column read as text for the internal position alias: a
215
+ * timestamp at full precision (`YYYY-MM-DDTHH:MM:SS.ffffffZ`, see
216
+ * `sql/keyset.ts`), anything else as its own text (only its NULL-ness is used).
217
+ */
218
+ function exactRead(column) {
219
+ const type = column.getSQLType();
220
+ if (!TIMESTAMP_TYPE.test(type)) return drizzle_orm.sql`${column}::text`;
221
+ const format = drizzle_orm.sql.raw(require_from_sql.EXACT_FORMAT);
222
+ return WITH_TIME_ZONE.test(type) ? drizzle_orm.sql`to_char(${column} at time zone 'UTC', ${format})` : drizzle_orm.sql`to_char(${column}, ${format})`;
223
+ }
129
224
  function fromDrizzle(db, table, opts) {
130
225
  const drizzleDb = db;
131
226
  const idField = opts.idField ?? inferIdField(table);
132
- const columns = (0, drizzle_orm.getTableColumns)(table);
227
+ const { columns, isAuthUsers } = readableColumns(table, {
228
+ cursorField: opts.cursorField,
229
+ idField
230
+ });
133
231
  const cursorColumn = columns[opts.cursorField];
134
232
  const idColumn = columns[idField];
135
233
  if (!cursorColumn) throw new Error(`fromDrizzle: cursorField "${opts.cursorField}" is not a column on "${(0, drizzle_orm.getTableName)(table)}".`);
136
234
  if (!idColumn) throw new Error(`fromDrizzle: idField "${idField}" is not a column on "${(0, drizzle_orm.getTableName)(table)}".`);
137
235
  const projection = {};
138
- for (const column of Object.values(columns)) projection[column.name] = column;
236
+ for (const column of Object.values(columns)) projection[column.name] = isAuthUsers && column.name === META_COLUMN ? drizzle_orm.sql.raw(require_from_sql.narrowedMetaValue(quoteIdent(META_COLUMN))).mapWith(column) : column;
139
237
  const cursorColumnName = cursorColumn.name;
140
238
  const idColumnName = idColumn.name;
239
+ const selected = {
240
+ ...projection,
241
+ [require_from_sql.CURSOR_ALIAS]: exactRead(cursorColumn)
242
+ };
243
+ const scope = isAuthUsers ? drizzle_orm.sql.raw(`(${require_sync.isAnonymousFilter})`) : void 0;
244
+ const page = (where, order, limit) => drizzleDb.select(selected).from(table).where((0, drizzle_orm.and)(where, scope)).orderBy(order).limit(limit);
141
245
  const source = {
142
246
  entity: opts.entity,
143
247
  ...opts.pushSource === void 0 ? {} : { pushSource: opts.pushSource },
144
248
  cursorField: cursorColumnName,
145
249
  idField: idColumnName,
146
- fetchPage: ({ since, limit }) => drizzleDb.select(projection).from(table).where(since ? drizzle_orm.sql`(${cursorColumn}, ${idColumn}) > (${since.time}, ${since.id})` : void 0).orderBy((0, drizzle_orm.asc)(cursorColumn), (0, drizzle_orm.asc)(idColumn)).limit(limit),
250
+ fetchPage: async ({ since, limit }) => require_from_sql.hideCursorAlias(await require_from_sql.keysetPage(since, limit, drizzleKeysetReads(cursorColumn, idColumn, {
251
+ nullable: !cursorColumn.notNull,
252
+ timestamp: TIMESTAMP_TYPE.test(cursorColumn.getSQLType())
253
+ }, page))),
147
254
  ...opts.objectType === void 0 ? {} : { objectType: opts.objectType }
148
255
  };
149
256
  const uniqueConstraints = require_drizzle.buildUniqueConstraints(table);
@@ -152,10 +259,10 @@ function fromDrizzle(db, table, opts) {
152
259
  cursorField: opts.cursorField,
153
260
  idField,
154
261
  tableName: (0, drizzle_orm.getTableName)(table),
155
- columnsMeta: require_drizzle.buildColumnsMeta(table),
262
+ columnsMeta: require_drizzle.buildColumnsMeta(table).filter((column) => !isAuthUsers || AUTH_USERS_ALLOWED.includes(column.name)),
156
263
  ...uniqueConstraints === void 0 ? {} : { uniqueConstraints }
157
264
  };
158
- Object.defineProperty(source, require_drizzle_meta.DRIZZLE_META, {
265
+ Object.defineProperty(source, require_sync.DRIZZLE_META, {
159
266
  value: meta,
160
267
  enumerable: false
161
268
  });
@@ -225,7 +332,7 @@ function insertAndPush(clivly, db, table, opts) {
225
332
  };
226
333
  }
227
334
  /** The one-row host table that keeps the ID Clivly issued this app. */
228
- const APP_ID_TABLE = "crm_clivly_app";
335
+ const APP_ID_TABLE = require_app_id.APP_ID_TABLE;
229
336
  /**
230
337
  * An `AppIdStore` backed by a one-row `crm_clivly_app` table in this database,
231
338
  * created on first use. Clivly issues the ID on the first heartbeat and uses
@@ -241,7 +348,7 @@ function drizzleAppIdStore(db) {
241
348
  const table = drizzle_orm.sql.identifier(APP_ID_TABLE);
242
349
  let ready = null;
243
350
  const ensureTable = () => {
244
- ready ??= client.execute(drizzle_orm.sql`create table if not exists ${table} (app_id text primary key, created_at timestamptz not null default now())`).catch((error) => {
351
+ ready ??= client.execute(drizzle_orm.sql`create table if not exists ${table} (app_id text primary key, created_at timestamptz not null default now())`).then(() => client.execute(drizzle_orm.sql.raw(require_app_id.appIdLockdownSql(quoteIdent(APP_ID_TABLE))))).catch((error) => {
245
352
  ready = null;
246
353
  throw error;
247
354
  });
package/drizzle.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { R as ProjectionMapping, z as ProjectionRef } from "./entity-config-CXpGowQa.cjs";
2
- import { C as NamespaceIntrospector, b as SyncSource, t as AppIdStore } from "./types-UR-tT4c1.cjs";
2
+ import { C as NamespaceIntrospector, b as SyncSource, t as AppIdStore } from "./types-CzL7lUH9.cjs";
3
3
  import { n as buildUniqueConstraints, r as discoverFromDrizzle } from "./drizzle-BNHGQXiY.cjs";
4
4
  import "./index-uFDiQEjj.cjs";
5
5
  import { Table } from "drizzle-orm";
@@ -45,6 +45,12 @@ interface FromDrizzleProjectionOptions {
45
45
  * timestamp involved.
46
46
  */
47
47
  cursorField?: string | ProjectionRef;
48
+ /**
49
+ * False when the cursor column is NOT NULL (and on the base table, or an
50
+ * inner join), which skips the read of NULL-cursor rows. A projection
51
+ * carries no column metadata, so it defaults to true.
52
+ */
53
+ cursorNullable?: boolean;
48
54
  /** The source name rows are pushed under. */
49
55
  entity: string;
50
56
  /**
package/drizzle.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { R as ProjectionMapping, z as ProjectionRef } from "./entity-config-CXpGowQa.mjs";
2
- import { n as AppIdStore, t as NamespaceIntrospector, x as SyncSource } from "./namespace-probe--GvxJ06J.mjs";
2
+ import { n as AppIdStore, t as NamespaceIntrospector, x as SyncSource } from "./namespace-probe-CUR2zG2l.mjs";
3
3
  import { n as buildUniqueConstraints, r as discoverFromDrizzle } from "./drizzle-DFe7ILmd.mjs";
4
4
  import "./index-DOoX2GgI.mjs";
5
5
  import { Table } from "drizzle-orm";
@@ -45,6 +45,12 @@ interface FromDrizzleProjectionOptions {
45
45
  * timestamp involved.
46
46
  */
47
47
  cursorField?: string | ProjectionRef;
48
+ /**
49
+ * False when the cursor column is NOT NULL (and on the base table, or an
50
+ * inner join), which skips the read of NULL-cursor rows. A projection
51
+ * carries no column metadata, so it defaults to true.
52
+ */
53
+ cursorNullable?: boolean;
48
54
  /** The source name rows are pushed under. */
49
55
  entity: string;
50
56
  /**