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
@@ -0,0 +1,60 @@
1
+ const require_projection_sql = require("./projection-sql-DS5sVTY-.cjs");
2
+ const require_projection_guard = require("./projection-guard-C70l5U24.cjs");
3
+ const require_from_sql = require("./from-sql-CFgXkCe2.cjs");
4
+ const require_supabase_contact = require("./supabase-contact-BXQ0nnLq.cjs");
5
+ const require_sync = require("./sync-CdA9dgZz.cjs");
6
+ // ../sdk/src/sql/introspector.ts
7
+ function assertAuthRule(projection) {
8
+ const refused = require_projection_guard.authExposureErrors(projection);
9
+ if (refused.length > 0) throw new require_projection_guard.ProjectionRefusedError(refused);
10
+ }
11
+ const PREVIEW_ENTITY = "preview";
12
+ function touchesAuthUsers(projection) {
13
+ return [projection.baseTable, ...projection.joins.map((j) => j.table)].some((table) => require_sync.authTableKind(table) === "users");
14
+ }
15
+ async function previewThroughSource(executor, projection, limit, basePkColumn = "id") {
16
+ return (await require_supabase_contact.fromSqlProjection(executor, projection, {
17
+ entity: PREVIEW_ENTITY,
18
+ objectType: PREVIEW_ENTITY,
19
+ basePkColumn
20
+ }).fetchPage({
21
+ since: null,
22
+ limit: Math.max(1, Math.min(Math.floor(limit), 50))
23
+ })).map((row) => ({
24
+ id: row.id,
25
+ ...Object.fromEntries(Object.entries(projection.fieldBindings).map(([field, binding]) => [field, row[`${binding.from.table}.${binding.from.column}`]]))
26
+ }));
27
+ }
28
+ /**
29
+ * The raw-SQL twin of `drizzleIntrospector`, for apps with no ORM.
30
+ * Read-only: every statement here is a SELECT.
31
+ */
32
+ function sqlIntrospector(executor) {
33
+ return {
34
+ async listTables() {
35
+ return (await require_supabase_contact.discoverFromSql(executor)).map((t) => t.name);
36
+ },
37
+ async sampleSelect(table) {
38
+ await executor.query(`select 1 from ${require_from_sql.postgresDialect.quoteTableRef(table)} limit 1`);
39
+ },
40
+ async runProjection(projection, previewOpts) {
41
+ assertAuthRule(projection);
42
+ if (touchesAuthUsers(projection)) return await previewThroughSource(executor, projection, previewOpts.limit, previewOpts.basePkColumn);
43
+ return await executor.query(require_projection_sql.compileProjectionPreview(projection, previewOpts.limit));
44
+ },
45
+ projectionSource(projection, sourceOpts) {
46
+ assertAuthRule(projection);
47
+ return require_supabase_contact.fromSqlProjection(executor, projection, {
48
+ entity: sourceOpts.objectType,
49
+ objectType: sourceOpts.objectType,
50
+ ...sourceOpts.basePkColumn ? { basePkColumn: sourceOpts.basePkColumn } : {}
51
+ });
52
+ }
53
+ };
54
+ }
55
+ Object.defineProperty(exports, "sqlIntrospector", {
56
+ enumerable: true,
57
+ get: function() {
58
+ return sqlIntrospector;
59
+ }
60
+ });
package/kysely.cjs ADDED
@@ -0,0 +1,56 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_from_sql = require("./from-sql-CFgXkCe2.cjs");
3
+ let kysely = require("kysely");
4
+ // ../sdk/src/kysely/executor.ts
5
+ const NOT_POSTGRES_PREFIX = "kyselyExecutor: only Postgres is supported";
6
+ const PROBE_SQL = "select version() as version";
7
+ const POSTGRES_VERSION_PREFIX = "PostgreSQL";
8
+ const FOUND_PREVIEW_LENGTH = 40;
9
+ const checks = /* @__PURE__ */ new WeakMap();
10
+ async function runRaw(db, text, params) {
11
+ return (await db.executeQuery(kysely.CompiledQuery.raw(text, [...params]))).rows;
12
+ }
13
+ async function confirmPostgres(db) {
14
+ let version;
15
+ try {
16
+ const [row] = await runRaw(db, PROBE_SQL, []);
17
+ version = row?.version;
18
+ } catch (cause) {
19
+ const message = cause instanceof Error ? cause.message : String(cause);
20
+ throw new Error(`${NOT_POSTGRES_PREFIX}, and checking the database version failed: ${message}`, { cause });
21
+ }
22
+ if (typeof version === "string" && version.startsWith(POSTGRES_VERSION_PREFIX)) return;
23
+ const found = String(version).slice(0, FOUND_PREVIEW_LENGTH);
24
+ throw new Error(`${NOT_POSTGRES_PREFIX} (found "${found}"); MySQL support is planned.`);
25
+ }
26
+ function ensurePostgres(db, raw) {
27
+ let check = checks.get(db);
28
+ if (!check) {
29
+ check = confirmPostgres(raw);
30
+ checks.set(db, check);
31
+ check.catch(() => checks.delete(db));
32
+ }
33
+ return check;
34
+ }
35
+ /**
36
+ * Adapts a Kysely instance to Clivly's raw-SQL seam, so `fromSql`,
37
+ * `discoverFromSql`, `sqlIntrospector` and `sqlAppIdStore` run through the
38
+ * app's own Kysely connection and its `log` config. Host plugins are bypassed
39
+ * (as Kysely's own `db.introspection` does): a result-rewriting plugin such as
40
+ * `CamelCasePlugin` would rename the column-keyed rows and internal aliases
41
+ * Clivly's SQL relies on. Postgres only: the first query checks `version()`
42
+ * once per Kysely instance.
43
+ */
44
+ function kyselyExecutor(db) {
45
+ const raw = db.withoutPlugins();
46
+ return { async query(text, params) {
47
+ await ensurePostgres(db, raw);
48
+ return runRaw(raw, text, params ?? []);
49
+ } };
50
+ }
51
+ // ../sdk/src/kysely/from-kysely.ts
52
+ function fromKysely(db, opts) {
53
+ return require_from_sql.fromSql(kyselyExecutor(db), opts);
54
+ }
55
+ exports.fromKysely = fromKysely;
56
+ exports.kyselyExecutor = kyselyExecutor;
package/kysely.d.cts ADDED
@@ -0,0 +1,45 @@
1
+ import { i as SqlExecutor, t as FromSqlOptions } from "./from-sql-S8dSvU-e.cjs";
2
+ import { b as SyncSource } from "./types-CzL7lUH9.cjs";
3
+ import { Kysely } from "kysely";
4
+ /**
5
+ * The Kysely methods the adapter uses. Structural on purpose: apps often
6
+ * carry two copies of Kysely (better-auth bundles its own), so nothing here
7
+ * may rely on `instanceof` a Kysely class.
8
+ */
9
+ type AnyKysely = Kysely<any>;
10
+ type KyselyQueryRunner = Pick<AnyKysely, "executeQuery" | "withoutPlugins">;
11
+ /**
12
+ * Adapts a Kysely instance to Clivly's raw-SQL seam, so `fromSql`,
13
+ * `discoverFromSql`, `sqlIntrospector` and `sqlAppIdStore` run through the
14
+ * app's own Kysely connection and its `log` config. Host plugins are bypassed
15
+ * (as Kysely's own `db.introspection` does): a result-rewriting plugin such as
16
+ * `CamelCasePlugin` would rename the column-keyed rows and internal aliases
17
+ * Clivly's SQL relies on. Postgres only: the first query checks `version()`
18
+ * once per Kysely instance.
19
+ */
20
+ export declare function kyselyExecutor(db: KyselyQueryRunner): SqlExecutor;
21
+ /** A table in Kysely's `DB` type. `Kysely<any>` widens this to `string`. */
22
+ type TableName<DB> = keyof DB & string;
23
+ type ColumnName<DB, T extends TableName<DB>> = keyof DB[T] & string;
24
+ interface FromKyselyOptions<DB, T extends TableName<DB>> extends Omit<FromSqlOptions, "table" | "columns" | "cursorField" | "idField"> {
25
+ /** Columns to read; defaults to every column. Ignored for `auth.users`. */
26
+ columns?: ColumnName<DB, T>[];
27
+ /** Column holding when a row changed; defaults to `updated_at` when present. */
28
+ cursorField?: ColumnName<DB, T>;
29
+ /** Unique tie-breaker column; defaults to the table's single-column PK. */
30
+ idField?: ColumnName<DB, T>;
31
+ /** A table in `DB`, schema-qualified (`"auth.users"`) outside the default schema. */
32
+ table: T;
33
+ }
34
+ /**
35
+ * The Kysely twin of `fromDrizzle`: a read-only, keyset-paginated `SyncSource`
36
+ * over one Postgres table, with table and column names checked against the
37
+ * app's Kysely `DB` type. `meta` is this table's entry from `discoverFromSql`.
38
+ */
39
+ export declare function fromKysely<DB, T extends TableName<DB>>(db: Kysely<DB>, opts: FromKyselyOptions<DB, T> & {
40
+ objectType: string;
41
+ }): SyncSource & {
42
+ objectType: string;
43
+ };
44
+ export declare function fromKysely<DB, T extends TableName<DB>>(db: Kysely<DB>, opts: FromKyselyOptions<DB, T>): SyncSource;
45
+ export type { FromKyselyOptions, KyselyQueryRunner };
package/kysely.d.mts ADDED
@@ -0,0 +1,45 @@
1
+ import { i as SqlExecutor, t as FromSqlOptions } from "./from-sql-CpGP7K3J.mjs";
2
+ import { x as SyncSource } from "./namespace-probe-CUR2zG2l.mjs";
3
+ import { Kysely } from "kysely";
4
+ /**
5
+ * The Kysely methods the adapter uses. Structural on purpose: apps often
6
+ * carry two copies of Kysely (better-auth bundles its own), so nothing here
7
+ * may rely on `instanceof` a Kysely class.
8
+ */
9
+ type AnyKysely = Kysely<any>;
10
+ type KyselyQueryRunner = Pick<AnyKysely, "executeQuery" | "withoutPlugins">;
11
+ /**
12
+ * Adapts a Kysely instance to Clivly's raw-SQL seam, so `fromSql`,
13
+ * `discoverFromSql`, `sqlIntrospector` and `sqlAppIdStore` run through the
14
+ * app's own Kysely connection and its `log` config. Host plugins are bypassed
15
+ * (as Kysely's own `db.introspection` does): a result-rewriting plugin such as
16
+ * `CamelCasePlugin` would rename the column-keyed rows and internal aliases
17
+ * Clivly's SQL relies on. Postgres only: the first query checks `version()`
18
+ * once per Kysely instance.
19
+ */
20
+ export declare function kyselyExecutor(db: KyselyQueryRunner): SqlExecutor;
21
+ /** A table in Kysely's `DB` type. `Kysely<any>` widens this to `string`. */
22
+ type TableName<DB> = keyof DB & string;
23
+ type ColumnName<DB, T extends TableName<DB>> = keyof DB[T] & string;
24
+ interface FromKyselyOptions<DB, T extends TableName<DB>> extends Omit<FromSqlOptions, "table" | "columns" | "cursorField" | "idField"> {
25
+ /** Columns to read; defaults to every column. Ignored for `auth.users`. */
26
+ columns?: ColumnName<DB, T>[];
27
+ /** Column holding when a row changed; defaults to `updated_at` when present. */
28
+ cursorField?: ColumnName<DB, T>;
29
+ /** Unique tie-breaker column; defaults to the table's single-column PK. */
30
+ idField?: ColumnName<DB, T>;
31
+ /** A table in `DB`, schema-qualified (`"auth.users"`) outside the default schema. */
32
+ table: T;
33
+ }
34
+ /**
35
+ * The Kysely twin of `fromDrizzle`: a read-only, keyset-paginated `SyncSource`
36
+ * over one Postgres table, with table and column names checked against the
37
+ * app's Kysely `DB` type. `meta` is this table's entry from `discoverFromSql`.
38
+ */
39
+ export declare function fromKysely<DB, T extends TableName<DB>>(db: Kysely<DB>, opts: FromKyselyOptions<DB, T> & {
40
+ objectType: string;
41
+ }): SyncSource & {
42
+ objectType: string;
43
+ };
44
+ export declare function fromKysely<DB, T extends TableName<DB>>(db: Kysely<DB>, opts: FromKyselyOptions<DB, T>): SyncSource;
45
+ export type { FromKyselyOptions, KyselyQueryRunner };
package/kysely.mjs ADDED
@@ -0,0 +1,54 @@
1
+ import { n as fromSql } from "./from-sql-BD7gR4bC.mjs";
2
+ import { CompiledQuery } from "kysely";
3
+ // ../sdk/src/kysely/executor.ts
4
+ const NOT_POSTGRES_PREFIX = "kyselyExecutor: only Postgres is supported";
5
+ const PROBE_SQL = "select version() as version";
6
+ const POSTGRES_VERSION_PREFIX = "PostgreSQL";
7
+ const FOUND_PREVIEW_LENGTH = 40;
8
+ const checks = /* @__PURE__ */ new WeakMap();
9
+ async function runRaw(db, text, params) {
10
+ return (await db.executeQuery(CompiledQuery.raw(text, [...params]))).rows;
11
+ }
12
+ async function confirmPostgres(db) {
13
+ let version;
14
+ try {
15
+ const [row] = await runRaw(db, PROBE_SQL, []);
16
+ version = row?.version;
17
+ } catch (cause) {
18
+ const message = cause instanceof Error ? cause.message : String(cause);
19
+ throw new Error(`${NOT_POSTGRES_PREFIX}, and checking the database version failed: ${message}`, { cause });
20
+ }
21
+ if (typeof version === "string" && version.startsWith(POSTGRES_VERSION_PREFIX)) return;
22
+ const found = String(version).slice(0, FOUND_PREVIEW_LENGTH);
23
+ throw new Error(`${NOT_POSTGRES_PREFIX} (found "${found}"); MySQL support is planned.`);
24
+ }
25
+ function ensurePostgres(db, raw) {
26
+ let check = checks.get(db);
27
+ if (!check) {
28
+ check = confirmPostgres(raw);
29
+ checks.set(db, check);
30
+ check.catch(() => checks.delete(db));
31
+ }
32
+ return check;
33
+ }
34
+ /**
35
+ * Adapts a Kysely instance to Clivly's raw-SQL seam, so `fromSql`,
36
+ * `discoverFromSql`, `sqlIntrospector` and `sqlAppIdStore` run through the
37
+ * app's own Kysely connection and its `log` config. Host plugins are bypassed
38
+ * (as Kysely's own `db.introspection` does): a result-rewriting plugin such as
39
+ * `CamelCasePlugin` would rename the column-keyed rows and internal aliases
40
+ * Clivly's SQL relies on. Postgres only: the first query checks `version()`
41
+ * once per Kysely instance.
42
+ */
43
+ function kyselyExecutor(db) {
44
+ const raw = db.withoutPlugins();
45
+ return { async query(text, params) {
46
+ await ensurePostgres(db, raw);
47
+ return runRaw(raw, text, params ?? []);
48
+ } };
49
+ }
50
+ // ../sdk/src/kysely/from-kysely.ts
51
+ function fromKysely(db, opts) {
52
+ return fromSql(kyselyExecutor(db), opts);
53
+ }
54
+ export { fromKysely, kyselyExecutor };
@@ -7,6 +7,13 @@ interface DrizzleSourceMeta {
7
7
  /** Schema-v2 typed column metadata derived from the Drizzle table. */
8
8
  columnsMeta?: DiscoveredColumn[];
9
9
  cursorField: string;
10
+ /**
11
+ * Columns of the pushed rows that do not come from `tableName` (a joined
12
+ * table's, or one the SDK computes), so that table's own column rules,
13
+ * such as the `auth.users` allowlist, do not apply to them. The source's
14
+ * query already decides what they hold.
15
+ */
16
+ derivedColumns?: string[];
10
17
  idField: string;
11
18
  /** Which source builder attached this: `fromDrizzle` (default) or `fromSql`. */
12
19
  kind?: "drizzle" | "sql";
@@ -243,8 +250,8 @@ interface ClivlySDKConfig {
243
250
  */
244
251
  path?: string;
245
252
  /**
246
- * Signing secret (`whsec_…`) issued by Clivly under Integrations → Remote
247
- * sync. Required: without it `createClivlyHandler()` refuses every request
253
+ * Signing secret (`whsec_…`) issued by Clivly under Connections → Setup →
254
+ * "Clivly can start a sync". Required: without it `createClivlyHandler()` refuses every request
248
255
  * (403 `signature_required`), including Clivly's own "Run sync". With it,
249
256
  * any request that isn't validly signed is rejected.
250
257
  */
@@ -377,6 +384,11 @@ interface ClivlyConnectResult {
377
384
  workspace?: IntegrationState | null;
378
385
  }
379
386
  interface SyncCursor {
387
+ /**
388
+ * The cursor at the database's precision (`YYYY-MM-DDTHH:MM:SS.ffffffZ`),
389
+ * when the source reads it. `time` is that value cut to the millisecond.
390
+ */
391
+ exact?: string;
380
392
  /** The row's id, breaking ties when timestamps collide. */
381
393
  id: string;
382
394
  /** The row's cursor-field value (typically `updated_at`). */
@@ -391,6 +403,17 @@ interface SyncSource {
391
403
  createdAtField?: string;
392
404
  cursorField: string;
393
405
  entity: string;
406
+ /**
407
+ * Rows ordered by id alone, after `afterId` when given. The daily delete
408
+ * check lists IDs with it when present: a listing paged on the change
409
+ * cursor misses a row whose position moves backwards mid-listing (a
410
+ * deleted profile lowers the Supabase join's `greatest`), and a missed ID
411
+ * is archived. Set by `fromSql` and `fromSqlProjection`.
412
+ */
413
+ fetchIdPage?(args: {
414
+ afterId: string | null;
415
+ limit: number;
416
+ }): Promise<Record<string, unknown>[]>;
394
417
  fetchPage(args: {
395
418
  since: SyncCursor | null;
396
419
  limit: number;
@@ -731,7 +754,14 @@ interface NamespaceIntrospector {
731
754
  * that set `introspector` for the "Namespace reachable" check gains preview
732
755
  * without touching a line.
733
756
  */
734
- runProjection?(projection: ProjectionMapping, opts: {
757
+ runProjection?(projection: ProjectionMapping,
758
+ /**
759
+ * `basePkColumn` is the base table's primary key from local discovery,
760
+ * for a `base_pk` identity that names no column. The same value the
761
+ * sync path resolves, so preview and sync key rows alike.
762
+ */
763
+ opts: {
764
+ basePkColumn?: string;
735
765
  limit: number;
736
766
  }): Promise<Record<string, unknown>[]>;
737
767
  /** Prove a table is genuinely selectable (SELECT ... LIMIT 1). Throws if unreachable/denied. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clivly",
3
- "version": "0.24.0-next.0",
3
+ "version": "0.24.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Clivly CLI — scaffold a CRM into your app (clivly init).",
@@ -319,6 +319,16 @@
319
319
  "default": "./drizzle.cjs"
320
320
  }
321
321
  },
322
+ "./kysely": {
323
+ "import": {
324
+ "types": "./kysely.d.mts",
325
+ "default": "./kysely.mjs"
326
+ },
327
+ "require": {
328
+ "types": "./kysely.d.cts",
329
+ "default": "./kysely.cjs"
330
+ }
331
+ },
322
332
  "./sql": {
323
333
  "import": {
324
334
  "types": "./sql.d.mts",
@@ -400,6 +410,7 @@
400
410
  "@workos-inc/node": ">=7",
401
411
  "better-auth": ">=1.6.22",
402
412
  "drizzle-orm": ">=0.30 || >=1.0.0-rc.0",
413
+ "kysely": ">=0.27",
403
414
  "vite": ">=5"
404
415
  },
405
416
  "peerDependenciesMeta": {
@@ -415,6 +426,9 @@
415
426
  "drizzle-orm": {
416
427
  "optional": true
417
428
  },
429
+ "kysely": {
430
+ "optional": true
431
+ },
418
432
  "vite": {
419
433
  "optional": true
420
434
  }
@@ -0,0 +1,170 @@
1
+ const require_entity_heuristics = require("./entity-heuristics-DNmrcd0b.cjs");
2
+ const require_sync = require("./sync-CdA9dgZz.cjs");
3
+ // ../sdk/src/projection-guard.ts
4
+ /**
5
+ * Tables auth libraries keep live credentials in. Whole-table: their secrets
6
+ * sit in columns with generic names (`token`, `value`) that a column rule
7
+ * cannot single out. `user`, `member` and `organization` are not here — they
8
+ * are legitimate contact and company sources.
9
+ */
10
+ const CREDENTIAL_TABLES = /* @__PURE__ */ new Set([
11
+ "session",
12
+ "verification",
13
+ "two_factor",
14
+ "twofactor",
15
+ "passkey",
16
+ "apikey",
17
+ "api_key",
18
+ "jwks"
19
+ ]);
20
+ const BASE_ALIAS = "base";
21
+ const AUTH_USERS_ALLOWED = require_sync.AUTH_USERS_COLUMNS;
22
+ /**
23
+ * Supabase's `auth` schema: only `auth.users`, and only its allowlisted
24
+ * columns. `allowSensitive` never widens this.
25
+ */
26
+ function authTableError(table) {
27
+ return require_sync.authTableKind(table) === "other" ? `Table "${table}" is in Supabase's auth schema and is never synced; only auth.users is readable.` : null;
28
+ }
29
+ function normalise(name) {
30
+ return name.toLowerCase().replaceAll("-", "_");
31
+ }
32
+ /**
33
+ * Whether a table name, bare or schema-qualified (`app.session`,
34
+ * `"app"."session"`), names a credential table: matched on its last segment.
35
+ */
36
+ function isCredentialTable(table) {
37
+ const last = table.replaceAll("\"", "").trim().split(".").at(-1) ?? "";
38
+ return CREDENTIAL_TABLES.has(normalise(last));
39
+ }
40
+ const META_COLUMN = "raw_user_meta_data";
41
+ const metaOutsideBindingError = (table) => `Column "${table}.${META_COLUMN}" can only be read as a field, never as an identity or join key.`;
42
+ function authColumnErrors(read) {
43
+ const { table, column, binding } = read;
44
+ if (require_sync.authTableKind(table) !== "users") return [];
45
+ if (!AUTH_USERS_ALLOWED.includes(column)) return [`Column "${table}.${column}" is not exposed; auth.users only exposes ${require_sync.AUTH_USERS_COLUMNS.join(", ")}.`];
46
+ return !binding && column === META_COLUMN ? [metaOutsideBindingError(table)] : [];
47
+ }
48
+ /** Every (table, column) a projection reads, with join aliases resolved. */
49
+ function readColumns(projection) {
50
+ const tableOf = /* @__PURE__ */ new Map([[BASE_ALIAS, projection.baseTable]]);
51
+ for (const join of projection.joins) tableOf.set(join.key, join.table);
52
+ const reads = [];
53
+ const add = (ref, binding) => {
54
+ reads.push({
55
+ table: tableOf.get(ref.table) ?? ref.table,
56
+ column: ref.column,
57
+ binding
58
+ });
59
+ };
60
+ for (const join of projection.joins) for (const condition of join.on) {
61
+ add(condition.left, false);
62
+ add(condition.right, false);
63
+ }
64
+ for (const binding of Object.values(projection.fieldBindings)) add(binding.from, true);
65
+ const { identity } = projection;
66
+ if (identity.kind === "column") add(identity.from, false);
67
+ else if (identity.kind === "composite") for (const part of identity.parts) add(part, false);
68
+ else if (identity.column) add({
69
+ table: BASE_ALIAS,
70
+ column: identity.column
71
+ }, false);
72
+ return reads;
73
+ }
74
+ function referencedTables(projection) {
75
+ return [projection.baseTable, ...projection.joins.map((join) => join.table)];
76
+ }
77
+ /** Thrown where a projection is refused outside the route-level checks. */
78
+ var ProjectionRefusedError = class extends Error {
79
+ reasons;
80
+ constructor(reasons) {
81
+ super(`projection refused: ${reasons.join("; ")}`);
82
+ this.name = "ProjectionRefusedError";
83
+ this.reasons = reasons;
84
+ }
85
+ };
86
+ /**
87
+ * Only the unconditional Supabase `auth.*` rule: no other auth table, and only
88
+ * the allowlisted `auth.users` columns. No policy can widen it, so it needs no
89
+ * options and the raw-SQL sources can enforce it on their own.
90
+ */
91
+ function authExposureErrors(projection) {
92
+ const errors = [];
93
+ for (const table of referencedTables(projection)) {
94
+ const authError = authTableError(table);
95
+ if (authError) errors.push(authError);
96
+ }
97
+ for (const read of readColumns(projection)) errors.push(...authColumnErrors(read));
98
+ return [...new Set(errors)];
99
+ }
100
+ /** Why this projection may not run here; empty when it may. */
101
+ function projectionExposureErrors(projection, policy = {}) {
102
+ const allowed = new Set((policy.allowSensitive ?? []).map(normalise));
103
+ const errors = [];
104
+ for (const table of referencedTables(projection)) {
105
+ const authError = authTableError(table);
106
+ if (authError) errors.push(authError);
107
+ if (isCredentialTable(table) && !allowed.has(normalise(`${table}.*`))) errors.push(`Table "${table}" holds credentials and is never synced.`);
108
+ if (policy.tables && !(table in policy.tables)) errors.push(`Table "${table}" is not in this app's exposure.tables allowlist.`);
109
+ }
110
+ for (const read of readColumns(projection)) {
111
+ const { table, column } = read;
112
+ const ref = `${table}.${column}`;
113
+ const authErrors = authColumnErrors(read);
114
+ if (authErrors.length > 0) {
115
+ errors.push(...authErrors);
116
+ continue;
117
+ }
118
+ if (require_entity_heuristics.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.`);
119
+ const columns = policy.tables?.[table];
120
+ if (Array.isArray(columns) && !columns.includes(column)) errors.push(`Column "${ref}" is not in this app's exposure.tables allowlist.`);
121
+ }
122
+ return [...new Set(errors)];
123
+ }
124
+ /**
125
+ * Drop credential columns, and columns outside the allowlist, from a raw-row
126
+ * preview. `derived` names columns of the source's rows that do not come from
127
+ * `table` (a joined profile column, the SDK's `full_name`): the `auth.users`
128
+ * column allowlist is not applied to them, the credential and policy rules
129
+ * still are.
130
+ */
131
+ function exposableColumns(table, columns, policy = {}, derived = []) {
132
+ const fromElsewhere = new Set(derived);
133
+ const allowed = new Set((policy.allowSensitive ?? []).map(normalise));
134
+ const result = /* @__PURE__ */ new Set();
135
+ const authKind = require_sync.authTableKind(table);
136
+ if (authKind === "other") return result;
137
+ if (isCredentialTable(table) && !allowed.has(normalise(`${table}.*`)) || policy.tables !== void 0 && !(table in policy.tables)) return result;
138
+ const listed = policy.tables?.[table];
139
+ for (const column of columns) {
140
+ if (authKind === "users" && !(AUTH_USERS_ALLOWED.includes(column) || fromElsewhere.has(column))) continue;
141
+ if (require_entity_heuristics.isSensitiveColumn(column) && !allowed.has(normalise(`${table}.${column}`))) continue;
142
+ if (Array.isArray(listed) && !listed.includes(column)) continue;
143
+ result.add(column);
144
+ }
145
+ return result;
146
+ }
147
+ Object.defineProperty(exports, "ProjectionRefusedError", {
148
+ enumerable: true,
149
+ get: function() {
150
+ return ProjectionRefusedError;
151
+ }
152
+ });
153
+ Object.defineProperty(exports, "authExposureErrors", {
154
+ enumerable: true,
155
+ get: function() {
156
+ return authExposureErrors;
157
+ }
158
+ });
159
+ Object.defineProperty(exports, "exposableColumns", {
160
+ enumerable: true,
161
+ get: function() {
162
+ return exposableColumns;
163
+ }
164
+ });
165
+ Object.defineProperty(exports, "projectionExposureErrors", {
166
+ enumerable: true,
167
+ get: function() {
168
+ return projectionExposureErrors;
169
+ }
170
+ });