clivly 0.23.1 → 0.24.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +28 -0
  2. package/{adapter-B4v4dwgD.d.mts → adapter--YV7du3i.d.cts} +1 -1
  3. package/{adapter-BK3gsby5.d.cts → adapter-DD3K3dCW.d.mts} +1 -1
  4. package/{auth-adapter-BIa-ZyVV.d.mts → auth-adapter-C17dzlzF.d.cts} +1 -1
  5. package/{auth-adapter-DwtMJb7D.d.cts → auth-adapter-CizFv7oU.d.mts} +1 -1
  6. package/auth-better-auth.d.cts +1 -1
  7. package/auth-better-auth.d.mts +1 -1
  8. package/auth-clerk.d.cts +1 -1
  9. package/auth-clerk.d.mts +1 -1
  10. package/auth-supabase.cjs +121 -0
  11. package/auth-supabase.d.cts +23 -0
  12. package/auth-supabase.d.mts +23 -0
  13. package/auth-supabase.mjs +119 -0
  14. package/auth-workos.d.cts +1 -1
  15. package/auth-workos.d.mts +1 -1
  16. package/core-adapter.d.cts +1 -1
  17. package/core-adapter.d.mts +1 -1
  18. package/core-auth-adapter.d.cts +1 -1
  19. package/core-auth-adapter.d.mts +1 -1
  20. package/core-mapping-score.d.cts +1 -0
  21. package/core-sync-engine.cjs +1 -1
  22. package/core-sync-engine.mjs +1 -1
  23. package/core-types.cjs +5 -1
  24. package/core-types.d.cts +2 -2
  25. package/core-types.d.mts +2 -2
  26. package/core-types.mjs +1 -1
  27. package/core-view-compiler.cjs +1 -1
  28. package/core-view-compiler.mjs +1 -1
  29. package/core.cjs +9 -5
  30. package/core.d.cts +6 -6
  31. package/core.d.mts +6 -6
  32. package/core.mjs +6 -6
  33. package/discover-BZIPXl23.cjs +200 -0
  34. package/discover-CFIi43Qn.mjs +195 -0
  35. package/drizzle.cjs +1 -1
  36. package/drizzle.d.cts +2 -2
  37. package/drizzle.d.mts +2 -2
  38. package/drizzle.mjs +1 -1
  39. package/executor-CJEWurjZ.mjs +23 -0
  40. package/executor-CU-jRgpC.cjs +40 -0
  41. package/index-CZkp8TV4.d.cts +108 -0
  42. package/index-Cnrz4ywf.d.mts +108 -0
  43. package/{index-Bh7o2J7K.d.mts → index-DOoX2GgI.d.mts} +3 -3
  44. package/{index-DRRTE5IJ.d.cts → index-uFDiQEjj.d.cts} +231 -5
  45. package/index.cjs +903 -30
  46. package/index.d.cts +27 -0
  47. package/index.d.mts +26 -0
  48. package/index.mjs +901 -28
  49. package/{internal-CdfVkh4O.d.mts → internal-D_2q2BOB.d.mts} +1 -1
  50. package/internal-adapter.d.cts +1 -1
  51. package/internal-adapter.d.mts +1 -1
  52. package/internal-auth-adapter.d.cts +1 -1
  53. package/internal-auth-adapter.d.mts +1 -1
  54. package/internal-sync-engine.cjs +1 -1
  55. package/internal-sync-engine.mjs +1 -1
  56. package/internal-types.cjs +5 -1
  57. package/internal-types.d.cts +2 -2
  58. package/internal-types.d.mts +2 -2
  59. package/internal-types.mjs +1 -1
  60. package/internal-view-compiler.cjs +1 -1
  61. package/internal-view-compiler.mjs +1 -1
  62. package/internal.cjs +9 -5
  63. package/internal.d.cts +5 -6
  64. package/internal.d.mts +6 -6
  65. package/internal.mjs +6 -6
  66. package/introspector-BwYgHGcS.cjs +363 -0
  67. package/introspector-Bz52xOUr.mjs +334 -0
  68. package/{namespace-probe-JuHriruA.d.mts → namespace-probe--GvxJ06J.d.mts} +8 -1
  69. package/package.json +31 -1
  70. package/projection-guard-7AMY0aCk.mjs +389 -0
  71. package/projection-guard-D8VUhCz7.cjs +508 -0
  72. package/{projection-sql-DQQdjw9I.mjs → projection-sql-2joBkLz2.mjs} +13 -3
  73. package/{projection-sql-BkrHR2ea.cjs → projection-sql-DS5sVTY-.cjs} +18 -2
  74. package/sdk-Bzkr24NW.cjs +207 -0
  75. package/sdk-D2WwGBzk.mjs +178 -0
  76. package/sdk.cjs +8 -6
  77. package/sdk.d.cts +7 -1
  78. package/sdk.d.mts +7 -1
  79. package/sdk.mjs +3 -2
  80. package/sql.cjs +13 -0
  81. package/sql.d.cts +2 -0
  82. package/sql.d.mts +2 -0
  83. package/sql.mjs +4 -0
  84. package/{sdk-BkMDOfCk.mjs → src-Dq2nY1Sj.mjs} +36 -495
  85. package/{sdk-BOarpe5I.cjs → src-X0-yIA3O.cjs} +63 -546
  86. package/supabase.cjs +255 -0
  87. package/supabase.d.cts +19 -0
  88. package/supabase.d.mts +19 -0
  89. package/supabase.mjs +254 -0
  90. package/{sync-engine-yFLEyId3.mjs → sync-engine-D0mJUeqP.mjs} +1 -1
  91. package/{sync-engine-DNSoZeo0.cjs → sync-engine-hU041kXO.cjs} +1 -1
  92. package/types-KMH5D5Lg.mjs +32 -0
  93. package/{namespace-probe-CcL6Wj8E.d.cts → types-UR-tT4c1.d.cts} +52 -45
  94. package/{types-BBfwsDxe.d.cts → types-f-Vcv-pl.d.cts} +18 -2
  95. package/{types-BBfwsDxe.d.mts → types-f-Vcv-pl.d.mts} +18 -2
  96. package/types-kR1kUlmz.cjs +67 -0
  97. package/{view-compiler-CSHSqZl7.mjs → view-compiler-BhKiezRH.mjs} +1 -1
  98. package/{view-compiler-NqiortOA.cjs → view-compiler-DgZadq1F.cjs} +1 -1
  99. package/vite.d.cts +1 -1
  100. package/vite.d.mts +1 -1
  101. package/internal-D7qVRIFb.d.cts +0 -228
  102. package/types-8KSw2AWg.mjs +0 -8
  103. package/types-B8m39L1s.cjs +0 -19
package/index.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ import { t as discoverFromSql } from "./discover-CFIi43Qn.mjs";
3
+ import { n as pgExecutor, r as postgresJsExecutor } from "./executor-CJEWurjZ.mjs";
2
4
  import { t as CANONICAL_FIELDS } from "./entity-config-CI5CGfaN.mjs";
3
5
  import { d as suggestCursorField, i as isFrameworkTable, l as scoreFieldMap, n as hasDefiningColumn, o as matchesConcept, p as toFieldMap, s as requiredFieldsFor, u as scoreRelationships } from "./entity-heuristics-DAxqagJA.mjs";
4
6
  import "./mapping-score-CS-MTDL9.mjs";
5
- import { n as createClivlySDK, u as isPlaceholderUrl } from "./sdk-BkMDOfCk.mjs";
7
+ import { n as createClivlySDK, o as isPlaceholderUrl } from "./src-Dq2nY1Sj.mjs";
6
8
  import { createRequire } from "node:module";
7
9
  import { spawn } from "node:child_process";
8
10
  import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, watch, writeFileSync } from "node:fs";
@@ -13,7 +15,7 @@ import { createJiti } from "jiti";
13
15
  import { fileURLToPath, pathToFileURL } from "node:url";
14
16
  import { Socket } from "node:net";
15
17
  // ../core/src/env-file.ts
16
- const ENV_FILES = {
18
+ const ENV_FILES$1 = {
17
19
  next: ".env.local",
18
20
  "tanstack-start": ".env",
19
21
  sveltekit: ".env",
@@ -23,7 +25,7 @@ const ENV_FILES = {
23
25
  };
24
26
  /** The conventional env file for a framework. `.env` when we do not know. */
25
27
  function envFileFor(framework) {
26
- return ENV_FILES[normalizeFramework(framework)] ?? ".env";
28
+ return ENV_FILES$1[normalizeFramework(framework)] ?? ".env";
27
29
  }
28
30
  const ALIASES = {
29
31
  next: "next",
@@ -769,11 +771,11 @@ async function runDev(options) {
769
771
  }
770
772
  // src/dev-override.ts
771
773
  const TRIGGER_URL_PATH = "/clivly/sdk/trigger-url";
772
- const HTTP_UNAUTHORIZED = 401;
773
- const HTTP_NOT_FOUND = 404;
774
+ const HTTP_UNAUTHORIZED$1 = 401;
775
+ const HTTP_NOT_FOUND$1 = 404;
774
776
  function kindForStatus(status) {
775
- if (status === HTTP_UNAUTHORIZED) return "unauthorized";
776
- if (status === HTTP_NOT_FOUND) return "not_enabled";
777
+ if (status === HTTP_UNAUTHORIZED$1) return "unauthorized";
778
+ if (status === HTTP_NOT_FOUND$1) return "not_enabled";
777
779
  return "unexpected_response";
778
780
  }
779
781
  function failureFor(status) {
@@ -1354,6 +1356,8 @@ Usage:
1354
1356
  Deprecated aliases — each runs part of \`clivly status\` and still works:
1355
1357
  clivly ping credential + reachability
1356
1358
  clivly connect the above, plus config and trigger URL
1359
+ clivly connect --supabase check a Supabase Edge Function is live and has
1360
+ contacts to sync (--project-url <url> to override)
1357
1361
  clivly doctor config, setup checks and edge safety
1358
1362
 
1359
1363
  Prefer \`clivly status\`: it runs the whole ladder and tells you which step you
@@ -1368,7 +1372,7 @@ Usage:
1368
1372
  clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]
1369
1373
  [--schema <path|package>] [--db-import <specifier>]
1370
1374
  [--auth-import <specifier>] [--contact-table <table>]
1371
- [--company-table <table>] [--framework <name>]
1375
+ [--company-table <table>] [--framework <name>] [--no-orm]
1372
1376
 
1373
1377
  Scaffolds clivly.config.ts, the Clivly route files, and .env placeholders.
1374
1378
  Detects your framework, ORM, auth adapter and app layout from the project.
@@ -1387,6 +1391,9 @@ Options:
1387
1391
  --auth-import <s> Module specifier exporting your auth instance
1388
1392
  --contact-table <t> Table to map as contacts
1389
1393
  --company-table <t> Table to map as companies
1394
+ --no-orm Read the schema from the live database (DATABASE_URL)
1395
+ instead of an ORM schema. Implied for Supabase apps
1396
+ with no ORM; an SPA gets a Supabase Edge Function
1390
1397
  `,
1391
1398
  add: `clivly add widget — scaffold the chat-session route
1392
1399
 
@@ -1468,7 +1475,7 @@ function isHelpRequest(argv) {
1468
1475
  }
1469
1476
  function helpFor(command) {
1470
1477
  if (!command) return ROOT_HELP;
1471
- return COMMAND_HELP[command] ?? "clivly — embed a CRM in your app\n\nUsage:\n clivly init [options] Scaffold Clivly (config, routes, env file) for your app\n clivly add widget [options] Scaffold the chat-session route\n clivly status [options] Check your setup, step by step\n clivly push-schema [options] Push schema, custom objects and mappings to Clivly\n clivly dev [options] Tunnel localhost so remote sync can reach you\n clivly login [options] Pair this machine and write credentials to your env file\n clivly --version Print the installed clivly version\n\nDeprecated aliases — each runs part of `clivly status` and still works:\n clivly ping credential + reachability\n clivly connect the above, plus config and trigger URL\n clivly doctor config, setup checks and edge safety\n\nPrefer `clivly status`: it runs the whole ladder and tells you which step you\nare on. The aliases are kept because output and docs have recommended them.\n\nRun `clivly <command> --help` for details on a command.\n";
1478
+ return COMMAND_HELP[command] ?? "clivly — embed a CRM in your app\n\nUsage:\n clivly init [options] Scaffold Clivly (config, routes, env file) for your app\n clivly add widget [options] Scaffold the chat-session route\n clivly status [options] Check your setup, step by step\n clivly push-schema [options] Push schema, custom objects and mappings to Clivly\n clivly dev [options] Tunnel localhost so remote sync can reach you\n clivly login [options] Pair this machine and write credentials to your env file\n clivly --version Print the installed clivly version\n\nDeprecated aliases — each runs part of `clivly status` and still works:\n clivly ping credential + reachability\n clivly connect the above, plus config and trigger URL\n clivly connect --supabase check a Supabase Edge Function is live and has\n contacts to sync (--project-url <url> to override)\n clivly doctor config, setup checks and edge safety\n\nPrefer `clivly status`: it runs the whole ladder and tells you which step you\nare on. The aliases are kept because output and docs have recommended them.\n\nRun `clivly <command> --help` for details on a command.\n";
1472
1479
  }
1473
1480
  // src/install.ts
1474
1481
  const defaultRun = (command, args, cwd) => new Promise((resolvePromise, reject) => {
@@ -1638,6 +1645,222 @@ function loadEnv(cwd, env = process.env, options = {}) {
1638
1645
  files
1639
1646
  };
1640
1647
  }
1648
+ // src/live-schema.ts
1649
+ const CONNECTION_KEYS = ["DATABASE_URL", "SUPABASE_DB_URL"];
1650
+ const CONNECTION_ENV_FILES = [".env.local", ".env"];
1651
+ /**
1652
+ * `db query` against the linked project, machine-readable, non-interactive.
1653
+ * `--linked` is accepted by every CLI that has `db query` (v3 keeps it as a
1654
+ * hidden alias of a bare `--remote`), `--output json` prints the rows, and
1655
+ * `--yes` answers the hosted-database confirmation a script cannot.
1656
+ */
1657
+ const SUPABASE_CLI_QUERY_ARGS = [
1658
+ "db",
1659
+ "query",
1660
+ "--linked",
1661
+ "--output",
1662
+ "json",
1663
+ "--yes"
1664
+ ];
1665
+ const CLI_TIMEOUT_MS = 6e4;
1666
+ const CONNECT_TIMEOUT_SECONDS = 10;
1667
+ const MS_PER_SECOND = 1e3;
1668
+ /** The connection string and where it came from, or null when none is set. */
1669
+ function resolveConnectionString(env, readFile, cwd) {
1670
+ for (const key of CONNECTION_KEYS) {
1671
+ const value = env[key]?.trim();
1672
+ if (value) return {
1673
+ label: key,
1674
+ value
1675
+ };
1676
+ }
1677
+ for (const name of CONNECTION_ENV_FILES) {
1678
+ const contents = readFile(join(cwd, name));
1679
+ if (contents === null) continue;
1680
+ const parsed = parseEnv(contents);
1681
+ for (const key of CONNECTION_KEYS) {
1682
+ const value = parsed[key]?.trim();
1683
+ if (value) return {
1684
+ label: key,
1685
+ value
1686
+ };
1687
+ }
1688
+ }
1689
+ return null;
1690
+ }
1691
+ const JSON_START = /[[{]/;
1692
+ const POSTGRES_ARRAY = /^\{(.*)\}$/s;
1693
+ function normaliseValue(value) {
1694
+ if (typeof value !== "string") return value;
1695
+ const match = POSTGRES_ARRAY.exec(value);
1696
+ if (!match) return value;
1697
+ const inner = match[1] ?? "";
1698
+ return inner === "" ? [] : inner.split(",").map((part) => part.replaceAll("\"", ""));
1699
+ }
1700
+ /** The rows `supabase db query --output json` printed, in either shape. */
1701
+ function parseSupabaseCliRows(stdout) {
1702
+ const start = stdout.search(JSON_START);
1703
+ if (start === -1) throw new Error("supabase db query printed no JSON");
1704
+ const parsed = JSON.parse(stdout.slice(start));
1705
+ const rows = Array.isArray(parsed) || parsed === null || typeof parsed !== "object" || !("rows" in parsed) ? parsed : parsed.rows;
1706
+ if (!Array.isArray(rows)) throw new Error("supabase db query printed no rows");
1707
+ return rows.map((row) => Object.fromEntries(Object.entries(row).map(([k, v]) => [k, normaliseValue(v)])));
1708
+ }
1709
+ const quoteLiteral = (value) => `'${value.replaceAll("'", "''")}'`;
1710
+ function literalFor(param) {
1711
+ if (Array.isArray(param)) return `ARRAY[${param.map((p) => quoteLiteral(String(p))).join(", ")}]`;
1712
+ if (param === null || param === void 0) return "null";
1713
+ return quoteLiteral(String(param));
1714
+ }
1715
+ const PARAM_REF = /\$(\d+)/g;
1716
+ /**
1717
+ * An executor over `supabase db query`. The CLI takes one SQL string and no
1718
+ * bind parameters, so parameters are inlined as quoted literals. Only the
1719
+ * catalog queries discovery issues go through here, and their one parameter
1720
+ * is the list of schema names.
1721
+ */
1722
+ function supabaseCliExecutor(run) {
1723
+ return { async query(text, params) {
1724
+ const sql = params ? text.replace(PARAM_REF, (_, n) => literalFor(params[Number(n) - 1])) : text;
1725
+ const result = await run([...SUPABASE_CLI_QUERY_ARGS, sql]);
1726
+ if (result.code !== 0) throw new SupabaseCliFailed(result.code);
1727
+ return parseSupabaseCliRows(result.stdout);
1728
+ } };
1729
+ }
1730
+ var SupabaseCliFailed = class extends Error {
1731
+ code;
1732
+ constructor(code) {
1733
+ super(`supabase exited with ${code}`);
1734
+ this.code = code;
1735
+ }
1736
+ };
1737
+ async function discoverOrNull(executor) {
1738
+ const tables = await discoverFromSql(executor);
1739
+ return tables.length === 0 ? null : tables;
1740
+ }
1741
+ async function fromConnectionString(opts, out) {
1742
+ const label = opts.connectionLabel ?? "DATABASE_URL";
1743
+ let connection = null;
1744
+ try {
1745
+ connection = await (opts.connect ?? missingDriver)(opts.connectionString);
1746
+ return await discoverOrNull(connection.executor);
1747
+ } catch (error) {
1748
+ opts.onFailure?.(error instanceof DriverMissing ? "driver_missing" : "connect_failed");
1749
+ out(error instanceof DriverMissing ? ` Couldn't read the schema from ${label}: install \`postgres\` or \`pg\` in this app so init can connect.\n` : ` Couldn't read the schema from ${label}.\n`);
1750
+ return null;
1751
+ } finally {
1752
+ await connection?.close().catch(() => void 0);
1753
+ }
1754
+ }
1755
+ async function fromSupabaseCli(run, out, onFailure) {
1756
+ try {
1757
+ return await discoverOrNull(supabaseCliExecutor(run));
1758
+ } catch (error) {
1759
+ if (!(error instanceof SupabaseCliFailed && error.code === 127)) {
1760
+ onFailure?.("cli_failed");
1761
+ out(" Couldn't read the schema through the Supabase CLI (is this project linked? `supabase link`).\n");
1762
+ }
1763
+ return null;
1764
+ }
1765
+ }
1766
+ async function readLiveSchema(opts) {
1767
+ const out = opts.out ?? (() => void 0);
1768
+ if (opts.connectionString) {
1769
+ const tables = await fromConnectionString({
1770
+ ...opts,
1771
+ connectionString: opts.connectionString
1772
+ }, out);
1773
+ if (tables) return tables;
1774
+ }
1775
+ if (opts.runSupabaseCli) return fromSupabaseCli(opts.runSupabaseCli, out, opts.onFailure);
1776
+ return null;
1777
+ }
1778
+ var DriverMissing = class extends Error {};
1779
+ function missingDriver() {
1780
+ return Promise.reject(new DriverMissing());
1781
+ }
1782
+ async function importFromHost(cwd, name) {
1783
+ try {
1784
+ const resolved = createRequire(join(cwd, "package.json")).resolve(name);
1785
+ const mod = await import(pathToFileURL(resolved).href);
1786
+ return mod.default ?? mod;
1787
+ } catch {
1788
+ return null;
1789
+ }
1790
+ }
1791
+ /**
1792
+ * Opens the database with the driver the host app already has — `postgres`
1793
+ * first, then `pg`. The CLI ships neither, so an app with no driver gets the
1794
+ * "install one" message and falls through to the next source.
1795
+ */
1796
+ function defaultConnect$1(cwd) {
1797
+ return async (url) => {
1798
+ const postgres = await importFromHost(cwd, "postgres");
1799
+ if (typeof postgres === "function") {
1800
+ const sql = postgres(url, {
1801
+ prepare: false,
1802
+ max: 1,
1803
+ connect_timeout: CONNECT_TIMEOUT_SECONDS
1804
+ });
1805
+ return {
1806
+ executor: postgresJsExecutor(sql),
1807
+ close: () => sql.end()
1808
+ };
1809
+ }
1810
+ const pg = await importFromHost(cwd, "pg");
1811
+ if (pg?.Client) {
1812
+ const client = new pg.Client({
1813
+ connectionString: url,
1814
+ connectionTimeoutMillis: CONNECT_TIMEOUT_SECONDS * MS_PER_SECOND
1815
+ });
1816
+ await client.connect();
1817
+ return {
1818
+ executor: pgExecutor(client),
1819
+ close: () => client.end()
1820
+ };
1821
+ }
1822
+ throw new DriverMissing();
1823
+ };
1824
+ }
1825
+ /**
1826
+ * Runs `supabase` with an args array (no shell), in the app directory. A
1827
+ * missing binary (ENOENT) reports SUPABASE_CLI_MISSING rather than throwing.
1828
+ */
1829
+ function defaultRunSupabaseCli(cwd) {
1830
+ return (args) => new Promise((resolve) => {
1831
+ let stdout = "";
1832
+ let settled = false;
1833
+ const finish = (code) => {
1834
+ if (!settled) {
1835
+ settled = true;
1836
+ clearTimeout(timer);
1837
+ resolve({
1838
+ code,
1839
+ stdout
1840
+ });
1841
+ }
1842
+ };
1843
+ const child = spawn("supabase", args, {
1844
+ cwd,
1845
+ stdio: [
1846
+ "ignore",
1847
+ "pipe",
1848
+ "ignore"
1849
+ ]
1850
+ });
1851
+ const timer = setTimeout(() => {
1852
+ child.kill();
1853
+ finish(1);
1854
+ }, CLI_TIMEOUT_MS);
1855
+ child.stdout?.on("data", (chunk) => {
1856
+ stdout += chunk.toString("utf8");
1857
+ });
1858
+ child.on("error", (error) => {
1859
+ finish(error.code === "ENOENT" ? 127 : 1);
1860
+ });
1861
+ child.on("close", (code) => finish(code ?? 1));
1862
+ });
1863
+ }
1641
1864
  // src/secret-key-env.ts
1642
1865
  const SECRET_KEY_ENV = "CLIVLY_SECRET_KEY";
1643
1866
  const LEGACY_SECRET_KEY_ENV = "CLIVLY_API_KEY";
@@ -2275,7 +2498,7 @@ function renderEntity(key, entity) {
2275
2498
  fields: ${renderFields(entity.fields)}${renderRelationships(entity)},
2276
2499
  }`;
2277
2500
  }
2278
- function renderSource(role, entity, dbExpr) {
2501
+ function renderSource$1(role, entity, dbExpr) {
2279
2502
  const opts = entity.idField === null ? `{ entity: "${entity.tableName}", cursorField: "${entity.cursorField}" }` : `{ entity: "${entity.tableName}", cursorField: "${entity.cursorField}", idField: "${entity.idField}" }`;
2280
2503
  return ` ${role}: fromDrizzle(${dbExpr}, schema.${entity.moduleKey}, ${opts})`;
2281
2504
  }
@@ -2328,8 +2551,8 @@ function renderInitConfig(plan) {
2328
2551
  const dbExpr = renderDbExpr(plan);
2329
2552
  const entities = [renderEntity(plan.contact.moduleKey, plan.contact)];
2330
2553
  if (plan.company) entities.push(renderEntity(plan.company.moduleKey, plan.company));
2331
- const sources = [renderSource("contacts", plan.contact, dbExpr)];
2332
- if (plan.company) sources.push(renderSource("companies", plan.company, dbExpr));
2554
+ const sources = [renderSource$1("contacts", plan.contact, dbExpr)];
2555
+ if (plan.company) sources.push(renderSource$1("companies", plan.company, dbExpr));
2333
2556
  return `${renderTodoHeader(plan.todos)}${renderImports(plan)}
2334
2557
 
2335
2558
  const entities = defineClivlyConfig({
@@ -2424,6 +2647,28 @@ function workosWiring() {
2424
2647
  ${RESOLVE_USER}`
2425
2648
  };
2426
2649
  }
2650
+ function supabaseWiring() {
2651
+ return {
2652
+ complete: true,
2653
+ envKeys: ["SUPABASE_URL", "SUPABASE_ANON_KEY"],
2654
+ hostImport: null,
2655
+ imports: ["import { createSupabaseAuthAdapter } from \"clivly/auth/supabase\";"],
2656
+ packages: [],
2657
+ body: `const supabaseUrl = process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.VITE_SUPABASE_URL;
2658
+ const supabaseAnonKey = process.env.SUPABASE_ANON_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || process.env.VITE_SUPABASE_ANON_KEY || process.env.SUPABASE_PUBLISHABLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY || process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
2659
+ const adapter =
2660
+ supabaseUrl && supabaseAnonKey
2661
+ ? createSupabaseAuthAdapter({ supabaseUrl, anonKey: supabaseAnonKey })
2662
+ : {
2663
+ getUser(_req: Request): never {
2664
+ throw new Error(
2665
+ "Clivly: the auth/verify route needs your Supabase project URL and anon key. Set SUPABASE_URL (or NEXT_PUBLIC_SUPABASE_URL / VITE_SUPABASE_URL) and SUPABASE_ANON_KEY (or NEXT_PUBLIC_SUPABASE_ANON_KEY / VITE_SUPABASE_ANON_KEY, or a *_SUPABASE_PUBLISHABLE_KEY)."
2666
+ );
2667
+ },
2668
+ };
2669
+ ${RESOLVE_USER}`
2670
+ };
2671
+ }
2427
2672
  function hostImportFor(instance) {
2428
2673
  if (instance === null) return {
2429
2674
  binding: "auth",
@@ -2451,6 +2696,7 @@ function renderAuthWiring(auth, authInstance = null) {
2451
2696
  case "clerk": return clerkWiring();
2452
2697
  case "workos": return workosWiring();
2453
2698
  case "better-auth": return betterAuthWiring(authInstance);
2699
+ case "supabase": return supabaseWiring();
2454
2700
  default: return STUB;
2455
2701
  }
2456
2702
  }
@@ -2753,7 +2999,7 @@ function planFiles(args) {
2753
2999
  const mutations = [];
2754
3000
  const bootPath = bootHookPath(args.framework, args.layout);
2755
3001
  const render = (path) => {
2756
- if (path === "clivly.config.ts") return renderInitConfig(args.plan);
3002
+ if (path === "clivly.config.ts") return (args.renderConfig ?? renderInitConfig)(args.plan);
2757
3003
  if (bootPath !== null && path === bootPath) return renderBootHook(args.framework, args.layout);
2758
3004
  const kind = path.includes("verify") ? "verify" : "tick";
2759
3005
  return renderRouteFile(args.framework, kind, args.authWiring, args.layout, parseTsconfig(args.readFile(join(args.cwd, "tsconfig.json")) ?? "")?.paths);
@@ -2775,10 +3021,16 @@ function envAction(addedCount, existingLength) {
2775
3021
  function planEnv(args) {
2776
3022
  const existing = args.readEnv(args.cwd);
2777
3023
  const addedKeys = CLIVLY_ENV_KEYS.filter((entry) => !hasKey(existing, entry.key)).map((entry) => entry.key);
3024
+ let contents = appendEnvKeys(existing, CLIVLY_ENV_KEYS);
3025
+ for (const { block, key } of args.commentedEnv ?? []) if (!(hasKey(existing, key) || contents.includes(block))) {
3026
+ const lead = contents.length === 0 || contents.endsWith("\n") ? "" : "\n";
3027
+ contents = `${contents}${lead}${block}\n`;
3028
+ addedKeys.push(key);
3029
+ }
2778
3030
  return {
2779
3031
  path: ".env",
2780
3032
  addedKeys,
2781
- contents: appendEnvKeys(existing, CLIVLY_ENV_KEYS),
3033
+ contents,
2782
3034
  action: envAction(addedKeys.length, existing.length)
2783
3035
  };
2784
3036
  }
@@ -3077,6 +3329,294 @@ async function runPushSchema(options) {
3077
3329
  out(" Open Integrations → Mapping to map your tables.\n");
3078
3330
  return 0;
3079
3331
  }
3332
+ // src/render-sql-config.ts
3333
+ const AUTH_USERS = "auth.users";
3334
+ const EMAIL_COLUMNS = /* @__PURE__ */ new Set(["email", "email_address"]);
3335
+ const NON_IDENTIFIER = /[^A-Za-z0-9_$]/g;
3336
+ const NO_CURSOR_TODO = /^No updated_at-like column on "([^"]+)"/;
3337
+ /** An entity key for a table: its bare name, made a valid identifier. */
3338
+ function entityKeyFor(name, taken) {
3339
+ const bare = name.slice(name.lastIndexOf(".") + 1).replace(NON_IDENTIFIER, "_");
3340
+ const key = taken.has(bare) ? name.replace(NON_IDENTIFIER, "_") : bare;
3341
+ taken.add(key);
3342
+ return key;
3343
+ }
3344
+ function toDiscoveredSchema(tables) {
3345
+ const taken = /* @__PURE__ */ new Set();
3346
+ return {
3347
+ importPath: "your database",
3348
+ db: null,
3349
+ tables: tables.map((table) => ({
3350
+ tableName: table.name,
3351
+ moduleKey: entityKeyFor(table.name, taken),
3352
+ columns: (table.columnsMeta ?? table.columns.map((name) => ({ name }))).map((column) => {
3353
+ const meta = column;
3354
+ return {
3355
+ key: meta.name,
3356
+ dbName: meta.name,
3357
+ isPrimary: meta.isPrimaryKey ?? false,
3358
+ ...meta.type === void 0 ? {} : { type: meta.type },
3359
+ ...meta.nullable === void 0 ? {} : { nullable: meta.nullable },
3360
+ ...meta.references ? { references: meta.references } : {}
3361
+ };
3362
+ }),
3363
+ ...table.uniqueConstraints ? { uniqueConstraints: table.uniqueConstraints } : {}
3364
+ }))
3365
+ };
3366
+ }
3367
+ /**
3368
+ * The contact table for a live schema: Supabase Auth's `auth.users` when it is
3369
+ * there, else the Drizzle path's heuristic pick, else the first table with an
3370
+ * email column. Undefined when nothing qualifies.
3371
+ */
3372
+ function chooseSqlContactTable(tables) {
3373
+ if (tables.some((table) => table.name === AUTH_USERS)) return AUTH_USERS;
3374
+ const heuristic = planInit(toDiscoveredSchema(tables)).contact?.tableName;
3375
+ if (heuristic) return heuristic;
3376
+ return tables.find((table) => table.columns.some((column) => EMAIL_COLUMNS.has(column.toLowerCase())))?.name;
3377
+ }
3378
+ /** `planInit` over a live schema, with the SQL contact-table default applied. */
3379
+ function planSqlInit(tables, overrides = {}) {
3380
+ const plan = planInit(toDiscoveredSchema(tables), {
3381
+ contactTable: overrides.contactTable ?? chooseSqlContactTable(tables),
3382
+ companyTable: overrides.companyTable
3383
+ });
3384
+ const todos = plan.todos.map((todo) => {
3385
+ const table = NO_CURSOR_TODO.exec(todo)?.[1];
3386
+ return table === void 0 ? todo : `No updated_at column on "${table}" — Clivly re-reads the whole table on each sync.`;
3387
+ });
3388
+ return {
3389
+ ...plan,
3390
+ todos
3391
+ };
3392
+ }
3393
+ function cursorOption(entity, plan) {
3394
+ if (plan.todos.some((todo) => todo.includes(`"${entity.tableName}"`) && todo.startsWith("No updated_at column")) || entity.cursorField === "updated_at") return "";
3395
+ return `, cursorField: ${JSON.stringify(entity.cursorField)}`;
3396
+ }
3397
+ function renderSource(role, entity, plan) {
3398
+ const table = JSON.stringify(entity.tableName);
3399
+ const id = entity.idField === null ? "" : `, idField: ${JSON.stringify(entity.idField)}`;
3400
+ return ` ${role}: fromSql(executor, { entity: ${table}, table: ${table}, meta: table(${table})${cursorOption(entity, plan)}${id} })`;
3401
+ }
3402
+ function renderDriver(driver) {
3403
+ if (driver === "pg") return {
3404
+ imports: `import pg from "pg";
3405
+ import { type ClivlySDK, createClivlySDK, defineClivlyConfig } from "clivly/sdk";
3406
+ import {
3407
+ discoverFromSql,
3408
+ fromSql,
3409
+ pgExecutor,
3410
+ type SqlExecutor,
3411
+ sqlAppIdStore,
3412
+ sqlIntrospector,
3413
+ } from "clivly/sql";`,
3414
+ connect: "pgExecutor(new pg.Pool({ connectionString: databaseUrl }))"
3415
+ };
3416
+ return {
3417
+ imports: `import postgres from "postgres";
3418
+ import { type ClivlySDK, createClivlySDK, defineClivlyConfig } from "clivly/sdk";
3419
+ import {
3420
+ connectPostgresJs,
3421
+ discoverFromSql,
3422
+ fromSql,
3423
+ type SqlExecutor,
3424
+ sqlAppIdStore,
3425
+ sqlIntrospector,
3426
+ } from "clivly/sql";`,
3427
+ connect: "connectPostgresJs(databaseUrl, postgres)"
3428
+ };
3429
+ }
3430
+ function renderSqlConfig(plan) {
3431
+ const { imports, connect } = renderDriver(plan.driver);
3432
+ const entities = [renderEntity(plan.contact.moduleKey, plan.contact)];
3433
+ const sources = [renderSource("contacts", plan.contact, plan)];
3434
+ if (plan.company) {
3435
+ entities.push(renderEntity(plan.company.moduleKey, plan.company));
3436
+ sources.push(renderSource("companies", plan.company, plan));
3437
+ }
3438
+ return `${renderTodoHeader(plan.todos)}${imports}
3439
+
3440
+ // Your database, read with SELECT only. Clivly's one write is its own one-row
3441
+ // \`crm_clivly_app\` table, which keeps the ID Clivly issues this app.
3442
+ const databaseUrl = process.env.DATABASE_URL || process.env.SUPABASE_DB_URL;
3443
+ const executor = databaseUrl ? ${connect} : null;
3444
+
3445
+ // Every table in your database, read once at boot, so the Clivly dashboard can
3446
+ // offer them all when you add a mapping — not just the sources below.
3447
+ const schema = executor ? await discoverFromSql(executor) : [];
3448
+
3449
+ const table = (name: string) => {
3450
+ const meta = schema.find((t) => t.name === name);
3451
+ if (!meta) {
3452
+ throw new Error(\`clivly.config.ts: table "\${name}" is not in your database.\`);
3453
+ }
3454
+ return meta;
3455
+ };
3456
+
3457
+ const entities = defineClivlyConfig({
3458
+ entities: {
3459
+ ${entities.join(",\n")},
3460
+ },
3461
+ });
3462
+
3463
+ // Clivly over the live database. Built only once there is a connection string.
3464
+ function connectedClivly(executor: SqlExecutor): ClivlySDK {
3465
+ return createClivlySDK({
3466
+ apiKey: process.env.CLIVLY_SECRET_KEY ?? process.env.CLIVLY_API_KEY!,
3467
+ entities,
3468
+ schema,
3469
+ // Lets derived objects authored in the dashboard run against this database.
3470
+ introspector: sqlIntrospector(executor),
3471
+ appIdStore: sqlAppIdStore(executor),
3472
+ source: {
3473
+ // Keyed by CRM concept — contacts/companies/deals/custom.
3474
+ // NOT by your entity key. The entity's own \`source:\` above is a table name.
3475
+ ${sources.join(",\n")},
3476
+ },
3477
+ syncTrigger: {
3478
+ // Where Clivly Cloud calls to start a sync — your mounted tick route.
3479
+ // \`path\` lets the SDK build its public URL from the hosting platform's
3480
+ // environment; \`url\` overrides that when you need to.
3481
+ path: "${CLIVLY_TICK_PATH}",
3482
+ url: process.env.CLIVLY_SYNC_TRIGGER_URL,
3483
+ secret: process.env.CLIVLY_SYNC_TRIGGER_SECRET,
3484
+ },
3485
+ // Changes arrive with Clivly's scheduled sync; there is no instant push
3486
+ // without an ORM write helper.
3487
+ });
3488
+ }
3489
+
3490
+ const MISSING_DATABASE_URL =
3491
+ "[clivly] Not connecting: set DATABASE_URL (or SUPABASE_DB_URL) to your Postgres connection string, then restart the app.";
3492
+
3493
+ // No connection string (a build step, or a deploy missing the variable): no
3494
+ // SDK is built, so nothing reaches Clivly — no heartbeat, no partial schema.
3495
+ // Each member answers as the real SDK does when it cannot deliver, and the
3496
+ // first call logs the error once. \`satisfies\` keeps it in step with the SDK.
3497
+ function clivlyWithoutDatabase(): ClivlySDK {
3498
+ let logged = false;
3499
+ const warnOnce = () => {
3500
+ if (!logged) {
3501
+ logged = true;
3502
+ console.error(MISSING_DATABASE_URL);
3503
+ }
3504
+ };
3505
+ const notConnected = async () => {
3506
+ warnOnce();
3507
+ return { ok: false, reason: "client_error", retryable: false, status: null } as const;
3508
+ };
3509
+ const refuse = async (): Promise<never> => {
3510
+ warnOnce();
3511
+ throw new Error(MISSING_DATABASE_URL);
3512
+ };
3513
+ const unavailable = () => async (_req: Request) => {
3514
+ warnOnce();
3515
+ return Response.json({ ok: false, error: MISSING_DATABASE_URL }, { status: 503 });
3516
+ };
3517
+ return {
3518
+ connect: notConnected,
3519
+ ping: notConnected,
3520
+ heartbeat: async () => {
3521
+ warnOnce();
3522
+ return false;
3523
+ },
3524
+ doctor: async () => {
3525
+ warnOnce();
3526
+ return {
3527
+ ok: false,
3528
+ checks: [{ name: "Database connection string", ok: false, detail: MISSING_DATABASE_URL }],
3529
+ };
3530
+ },
3531
+ ensureSchema: async () => {
3532
+ warnOnce();
3533
+ return null;
3534
+ },
3535
+ ensureCustomObjects: async () => {
3536
+ warnOnce();
3537
+ return null;
3538
+ },
3539
+ describeSyncTrigger: () => ({
3540
+ configured: process.env.CLIVLY_SYNC_TRIGGER_URL,
3541
+ hasSecret: Boolean(process.env.CLIVLY_SYNC_TRIGGER_SECRET),
3542
+ resolved: undefined,
3543
+ }),
3544
+ describeRemoteProjections: () => ({
3545
+ capable: false,
3546
+ failed: 0,
3547
+ invalid: 0,
3548
+ ok: 0,
3549
+ ran: false,
3550
+ skipped: 0,
3551
+ }),
3552
+ createClivlyHandler: unavailable,
3553
+ createAuthVerifyHandler: unavailable,
3554
+ recordConsent: async () => {
3555
+ warnOnce();
3556
+ return { ok: false, error: MISSING_DATABASE_URL, status: null };
3557
+ },
3558
+ pushOne: async () => warnOnce(),
3559
+ pushDelete: async () => warnOnce(),
3560
+ start: async () => warnOnce(),
3561
+ stop: async () => undefined,
3562
+ sync: refuse,
3563
+ runScheduled: refuse,
3564
+ } satisfies ClivlySDK;
3565
+ }
3566
+
3567
+ export default executor ? connectedClivly(executor) : clivlyWithoutDatabase();
3568
+ `;
3569
+ }
3570
+ // src/render-supabase.ts
3571
+ const SUPABASE_FUNCTION_INDEX = "supabase/functions/clivly/index.ts";
3572
+ const SUPABASE_DENO_JSON = "supabase/functions/clivly/deno.json";
3573
+ const SUPABASE_CONFIG_TOML = "supabase/config.toml";
3574
+ /** The runtime default `createSupabaseClivly` picks when `contact` is omitted. */
3575
+ const DEFAULT_CONTACT_TABLE = "auth.users";
3576
+ const CLIVLY_FUNCTION_BLOCK = "[functions.clivly]\nverify_jwt = false\n";
3577
+ const CLIVLY_FUNCTION_HEADER = /^[ \t]*\[functions\.clivly\][ \t]*(#.*)?$/m;
3578
+ const DENO_JSON = `${JSON.stringify({ imports: {} }, null, 2)}\n`;
3579
+ function hasClivlyFunctionBlock(toml) {
3580
+ return CLIVLY_FUNCTION_HEADER.test(toml);
3581
+ }
3582
+ const TABLE_HEADER = /^[ \t]*\[/m;
3583
+ const VERIFY_JWT_TRUE = /^[ \t]*verify_jwt[ \t]*=[ \t]*true\b/m;
3584
+ /** True when an existing `[functions.clivly]` block turns the JWT check on. */
3585
+ function clivlyBlockVerifiesJwt(toml) {
3586
+ const header = CLIVLY_FUNCTION_HEADER.exec(toml);
3587
+ if (!header) return false;
3588
+ const rest = toml.slice(header.index + header[0].length);
3589
+ const next = rest.search(TABLE_HEADER);
3590
+ return VERIFY_JWT_TRUE.test(next === -1 ? rest : rest.slice(0, next));
3591
+ }
3592
+ function renderConfigToml(existing) {
3593
+ if (!existing) return CLIVLY_FUNCTION_BLOCK;
3594
+ if (hasClivlyFunctionBlock(existing)) return existing;
3595
+ return `${existing}${existing.endsWith("\n") ? "\n" : "\n\n"}${CLIVLY_FUNCTION_BLOCK}`;
3596
+ }
3597
+ function renderIndex(plan) {
3598
+ const pkg = `clivly@${plan.version}`;
3599
+ return `import postgres from "npm:postgres@3";
3600
+ import { connectPostgresJs } from "npm:${pkg}/sql";
3601
+ import { createSupabaseClivly } from "npm:${pkg}/supabase";
3602
+
3603
+ const env = Deno.env.toObject();
3604
+ const handler = createSupabaseClivly({
3605
+ env,
3606
+ executor: connectPostgresJs(env.SUPABASE_DB_URL, postgres),
3607
+ waitUntil: (p) => EdgeRuntime.waitUntil(p),
3608
+ ${plan.contactTable && plan.contactTable !== DEFAULT_CONTACT_TABLE ? ` contact: { table: ${JSON.stringify(plan.contactTable)} },\n` : ""}});
3609
+
3610
+ Deno.serve(handler);
3611
+ `;
3612
+ }
3613
+ function renderSupabaseFunction(plan) {
3614
+ return { files: {
3615
+ [SUPABASE_FUNCTION_INDEX]: renderIndex(plan),
3616
+ [SUPABASE_DENO_JSON]: DENO_JSON,
3617
+ [SUPABASE_CONFIG_TOML]: renderConfigToml(plan.existingConfigToml)
3618
+ } };
3619
+ }
3080
3620
  // src/resolve-schema-path.ts
3081
3621
  const COMMON_PATHS = [
3082
3622
  "src/db/schema.ts",
@@ -4029,6 +4569,127 @@ async function runStatus(options) {
4029
4569
  if (code !== 0 && results.some((result) => result.state === "pending")) out("\nSetup is incomplete — finish the steps above and re-run.\n");
4030
4570
  return code;
4031
4571
  }
4572
+ // src/supabase-detect.ts
4573
+ const SUPABASE_DEPS = ["@supabase/supabase-js", "@supabase/ssr"];
4574
+ const CONFIG_TOML = "supabase/config.toml";
4575
+ const LOVABLE_CLIENT = "src/integrations/supabase/client.ts";
4576
+ const ENV_FILES = [
4577
+ ".env",
4578
+ ".env.local",
4579
+ ".env.development",
4580
+ ".env.development.local"
4581
+ ];
4582
+ const URL_KEYS = [
4583
+ "VITE_SUPABASE_URL",
4584
+ "NEXT_PUBLIC_SUPABASE_URL",
4585
+ "SUPABASE_URL"
4586
+ ];
4587
+ const PROJECT_URL_LITERAL = /https:\/\/[a-z0-9]+\.supabase\.co\b/i;
4588
+ function defaultReadFile$1(path) {
4589
+ return existsSync(path) ? readFileSync(path, "utf8") : null;
4590
+ }
4591
+ function urlFromEnvFiles(cwd, readFile) {
4592
+ const merged = {};
4593
+ for (const name of ENV_FILES) {
4594
+ const contents = readFile(join(cwd, name));
4595
+ if (contents !== null) Object.assign(merged, parseEnv(contents));
4596
+ }
4597
+ for (const key of URL_KEYS) {
4598
+ const value = merged[key]?.trim();
4599
+ if (value) return value;
4600
+ }
4601
+ return null;
4602
+ }
4603
+ function detectSupabase(deps, fileExists, cwd, readFile = defaultReadFile$1) {
4604
+ const clientPath = join(cwd, LOVABLE_CLIENT);
4605
+ const hasClient = fileExists(clientPath);
4606
+ const present = SUPABASE_DEPS.some((dep) => dep in deps) || fileExists(join(cwd, CONFIG_TOML)) || hasClient;
4607
+ if (!present) return {
4608
+ present: false,
4609
+ projectUrl: null
4610
+ };
4611
+ const fromEnv = urlFromEnvFiles(cwd, readFile);
4612
+ if (fromEnv) return {
4613
+ present,
4614
+ projectUrl: fromEnv
4615
+ };
4616
+ return {
4617
+ present,
4618
+ projectUrl: (hasClient ? PROJECT_URL_LITERAL.exec(readFile(clientPath) ?? "")?.[0] : void 0) ?? null
4619
+ };
4620
+ }
4621
+ // src/supabase-connect.ts
4622
+ const FAILURE = 1;
4623
+ const SUCCESS = 0;
4624
+ const HTTP_UNAUTHORIZED = 401;
4625
+ const HTTP_FORBIDDEN = 403;
4626
+ const HTTP_NOT_FOUND = 404;
4627
+ const HTTP_UNAVAILABLE = 503;
4628
+ const TRAILING_SLASHES = /\/+$/;
4629
+ const SECRET_KEY_HELP = "CLIVLY_SECRET_KEY is not set on the function. Add it in the Supabase dashboard (Edge Functions → Secrets), or in Lovable's Secrets panel, then run this again.\n";
4630
+ const NOT_DEPLOYED_HELP = "The clivly function is not deployed yet. Deploy it, then run this again:\n npx supabase functions deploy clivly\n";
4631
+ const VERIFY_JWT_HELP = "Could not reach the clivly function. The most likely cause is JWT verification being on. Set it off in supabase/config.toml and redeploy:\n [functions.clivly]\n verify_jwt = false\n";
4632
+ const REDEPLOY_HELP = "The deployed clivly function is out of date. Update `clivly` and redeploy it, then run this again:\n npx supabase functions deploy clivly\n";
4633
+ const ZERO_ROWS_HELP = "The function is live, but 0 contacts would sync, so nothing is syncing yet.\nThat can be normal for a brand-new app with no sign-ups (anonymous users are not counted). Sign up a test user and run this again.\n";
4634
+ async function readBody(response) {
4635
+ try {
4636
+ const parsed = await response.json();
4637
+ return parsed && typeof parsed === "object" ? parsed : {};
4638
+ } catch {
4639
+ return {};
4640
+ }
4641
+ }
4642
+ function failureText(status, body) {
4643
+ if (status === HTTP_NOT_FOUND) return NOT_DEPLOYED_HELP;
4644
+ if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) return VERIFY_JWT_HELP;
4645
+ if (status === HTTP_UNAVAILABLE && body.reason === "missing_secret_key") return SECRET_KEY_HELP;
4646
+ return null;
4647
+ }
4648
+ async function runSupabaseConnect(deps) {
4649
+ const { out } = deps;
4650
+ const base = deps.projectUrl.replace(TRAILING_SLASHES, "");
4651
+ let response;
4652
+ try {
4653
+ response = await deps.fetch(`${base}/functions/v1/clivly/connect`, { method: "GET" });
4654
+ } catch {
4655
+ out(VERIFY_JWT_HELP);
4656
+ return { code: FAILURE };
4657
+ }
4658
+ const body = await readBody(response);
4659
+ if (response.ok && body.ok === true) {
4660
+ if (body.hasContacts === false) {
4661
+ out(ZERO_ROWS_HELP);
4662
+ return { code: FAILURE };
4663
+ }
4664
+ if (body.hasContacts !== true) {
4665
+ out(REDEPLOY_HELP);
4666
+ return { code: FAILURE };
4667
+ }
4668
+ out(`Connected${typeof body.org?.name === "string" ? ` to ${body.org.name}` : ""}.\n`);
4669
+ return { code: SUCCESS };
4670
+ }
4671
+ const help = failureText(response.status, body);
4672
+ if (help) {
4673
+ out(help);
4674
+ return { code: FAILURE };
4675
+ }
4676
+ out(`The clivly function reported a problem (${typeof body.reason === "string" ? body.reason : "unknown"}).\n`);
4677
+ return { code: FAILURE };
4678
+ }
4679
+ /** The project URL from `--project-url`, else the app's own Supabase config. */
4680
+ function resolveSupabaseProjectUrl(cwd, override) {
4681
+ if (override) return override;
4682
+ let deps = {};
4683
+ const pkgPath = join(cwd, "package.json");
4684
+ if (existsSync(pkgPath)) try {
4685
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
4686
+ deps = {
4687
+ ...pkg.dependencies,
4688
+ ...pkg.devDependencies
4689
+ };
4690
+ } catch {}
4691
+ return detectSupabase(deps, existsSync, cwd).projectUrl;
4692
+ }
4032
4693
  // src/index.ts
4033
4694
  const ENV_FILE_CANDIDATES = [
4034
4695
  ".env",
@@ -4280,7 +4941,10 @@ function resolveInitDeps(options) {
4280
4941
  })),
4281
4942
  framework: "unknown",
4282
4943
  layout: "app",
4283
- authWiring: renderAuthWiring("unknown")
4944
+ authWiring: renderAuthWiring("unknown"),
4945
+ renderConfig: void 0,
4946
+ commentedEnv: [],
4947
+ extraPackages: []
4284
4948
  };
4285
4949
  }
4286
4950
  /**
@@ -4293,7 +4957,42 @@ function resolveInitDeps(options) {
4293
4957
  function renderDetectionLines(detection) {
4294
4958
  const from = (source) => source ? ` (from ${source})` : "";
4295
4959
  const frameworkNote = detection.frameworkForced ? " (--framework)" : from(detection.sources.framework);
4296
- return ` Framework: ${FRAMEWORK_LABELS[detection.framework]}${frameworkNote}\n ORM: ${detection.orm}${from(detection.sources.orm)}\n Auth: ${detection.auth}${from(detection.sources.auth)}${detection.authWired ? " (wired)" : ""}\n`;
4960
+ return ` Framework: ${FRAMEWORK_LABELS[detection.framework]}${frameworkNote}\n ORM: ${detection.orm}${from(detection.sources.orm)}\n` + (detection.authNote === void 0 ? ` Auth: ${detection.auth}${from(detection.sources.auth)}${detection.authWired ? " (wired)" : ""}\n` : ` Auth: ${detection.authNote}\n`);
4961
+ }
4962
+ /**
4963
+ * Supabase Auth is never inferred from dependencies (supabase-js is often
4964
+ * there for storage alone, and the Drizzle path must not change). A Supabase
4965
+ * app on the no-ORM path with no other auth library opts into it here.
4966
+ */
4967
+ function effectiveAuth(detected, noOrm) {
4968
+ return detected === "unknown" && noOrm?.noOrm.supabase.present ? "supabase" : detected;
4969
+ }
4970
+ function authNoteFor(noOrm, framework) {
4971
+ return noOrm && framework === "unknown" ? "not needed for the Edge Function" : void 0;
4972
+ }
4973
+ function noOrmTarget(options, deps, appDeps, orm) {
4974
+ if (orm !== "unknown" || options.schemaFlag) return null;
4975
+ const supabase = detectSupabase(appDeps, deps.fileExists, options.cwd, deps.readFile);
4976
+ return supabase.present || options.noOrm ? { noOrm: {
4977
+ appDeps,
4978
+ supabase
4979
+ } } : null;
4980
+ }
4981
+ const NO_SUPABASE_URL_HELP = "Couldn't find your Supabase project URL. Pass it: npx clivly connect --supabase --project-url https://<project-ref>.supabase.co\n";
4982
+ async function connectSupabase(argv) {
4983
+ const projectUrl = resolveSupabaseProjectUrl(process.cwd(), flagValue(argv, "--project-url"));
4984
+ if (!projectUrl) {
4985
+ process.stdout.write(NO_SUPABASE_URL_HELP);
4986
+ return 1;
4987
+ }
4988
+ const { code } = await runSupabaseConnect({
4989
+ projectUrl,
4990
+ fetch,
4991
+ out: (text) => {
4992
+ process.stdout.write(text);
4993
+ }
4994
+ });
4995
+ return code;
4297
4996
  }
4298
4997
  async function acquireSchema(options, deps) {
4299
4998
  const { out } = deps;
@@ -4308,7 +5007,9 @@ async function acquireSchema(options, deps) {
4308
5007
  }));
4309
5008
  const detected = detectAcrossWorkspace(appDeps, workspacePackages);
4310
5009
  const framework = options.frameworkFlag ?? detected.framework;
4311
- const { auth, orm, sources } = detected;
5010
+ const { orm, sources } = detected;
5011
+ const noOrm = noOrmTarget(options, deps, appDeps, orm);
5012
+ const auth = effectiveAuth(detected.auth, noOrm);
4312
5013
  deps.framework = framework;
4313
5014
  const layout = deps.resolveAppLayout(options.cwd, deps.fileExists);
4314
5015
  deps.layout = layout;
@@ -4316,6 +5017,7 @@ async function acquireSchema(options, deps) {
4316
5017
  deps.authWiring = renderAuthWiring(auth, auth === "better-auth" ? authInstanceFromFlag(options.authImportFlag) ?? await deps.probeAuth(options.cwd) : null);
4317
5018
  out(renderDetectionLines({
4318
5019
  auth,
5020
+ authNote: authNoteFor(noOrm, framework),
4319
5021
  authWired: deps.authWiring.complete,
4320
5022
  framework,
4321
5023
  frameworkForced: options.frameworkFlag !== void 0,
@@ -4327,6 +5029,7 @@ async function acquireSchema(options, deps) {
4327
5029
  if (frameworkCaution) out(`\n${frameworkCaution}`);
4328
5030
  if (auth === "better-auth" && !deps.authWiring.complete) out("\n ⚠️ Could not locate your better-auth instance.\n The verify route will import a placeholder path that does not\n resolve. Point it at the real module with:\n\n clivly init --force --auth-import <specifier>\n\n Accepts an alias ($lib/server/auth, @/lib/auth), a package name,\n or a project-relative path (src/lib/server/auth).\n");
4329
5031
  out("\n");
5032
+ if (noOrm) return noOrm;
4330
5033
  if (orm !== "drizzle" && !options.schemaFlag) {
4331
5034
  out(`clivly init currently generates config for Drizzle only. Detected ORM: ${orm}\n`);
4332
5035
  out(workspaceHint("orm", workspacePackages.length));
@@ -4377,11 +5080,13 @@ function mutationsFor(options, deps, plan) {
4377
5080
  authWiring: deps.authWiring,
4378
5081
  plan,
4379
5082
  readFile: deps.readFile,
4380
- readEnv: deps.readEnv
5083
+ readEnv: deps.readEnv,
5084
+ renderConfig: deps.renderConfig,
5085
+ commentedEnv: deps.commentedEnv
4381
5086
  });
4382
5087
  }
4383
- function applyMutations(options, deps, mutations) {
4384
- for (const file of mutations.files) {
5088
+ function applyFiles(options, deps, files) {
5089
+ for (const file of files) {
4385
5090
  if (file.action === "unchanged") {
4386
5091
  deps.out(` · ${file.path} already up to date\n`);
4387
5092
  continue;
@@ -4393,6 +5098,9 @@ function applyMutations(options, deps, mutations) {
4393
5098
  deps.writeConfig(join(options.cwd, file.path), file.contents);
4394
5099
  deps.out(` ✓ ${file.path}\n`);
4395
5100
  }
5101
+ }
5102
+ function applyMutations(options, deps, mutations) {
5103
+ applyFiles(options, deps, mutations.files);
4396
5104
  if (mutations.env.action === "skip") deps.out(" • .env already has every CLIVLY_* key — skipped\n");
4397
5105
  else {
4398
5106
  deps.writeEnv(options.cwd, mutations.env.contents);
@@ -4472,7 +5180,11 @@ function resolveRuntimeInstallSpec(deps, env = process.env) {
4472
5180
  async function scaffold(options, deps, plan) {
4473
5181
  const { out } = deps;
4474
5182
  const pm = deps.detectPackageManager(options.cwd);
4475
- const packages = [resolveRuntimeInstallSpec(deps), ...deps.authWiring.packages];
5183
+ const packages = [
5184
+ resolveRuntimeInstallSpec(deps),
5185
+ ...deps.authWiring.packages,
5186
+ ...deps.extraPackages
5187
+ ];
4476
5188
  const mutations = mutationsFor(options, deps, plan);
4477
5189
  const shadowing = shadowedAppDirError(options.cwd, deps.framework, mutations.files.map((file) => file.path), deps.fileExists);
4478
5190
  if (shadowing) {
@@ -4511,6 +5223,161 @@ async function scaffold(options, deps, plan) {
4511
5223
  printNextSteps(out, deps.authWiring.complete, loginRan, envFileFor(initFramework), initFramework === "sveltekit" && deps.authWiring.hostImport !== null);
4512
5224
  return 0;
4513
5225
  }
5226
+ const DATABASE_URL_PLACEHOLDER = {
5227
+ key: "DATABASE_URL",
5228
+ block: "# Postgres connection string clivly.config.ts reads its schema and rows with\n# (Supabase: Project Settings → Database → Connection string). Uncomment and set:\n# DATABASE_URL=postgresql://postgres:[YOUR-PASSWORD]@db.<project-ref>.supabase.co:5432/postgres"
5229
+ };
5230
+ const SUPABASE_SECRETS_LOCATION = "Supabase dashboard → Edge Functions → Secrets (on Lovable: the Secrets panel)";
5231
+ function sqlDriverFor(appDeps) {
5232
+ if ("postgres" in appDeps) return {
5233
+ driver: "postgres",
5234
+ install: []
5235
+ };
5236
+ if ("pg" in appDeps) return {
5237
+ driver: "pg",
5238
+ install: []
5239
+ };
5240
+ return {
5241
+ driver: "postgres",
5242
+ install: ["postgres"]
5243
+ };
5244
+ }
5245
+ /**
5246
+ * `clivly init` for an app with no ORM: read the live schema (connection
5247
+ * string, then the linked Supabase CLI), then write either the server config
5248
+ * and route files or, for an SPA or when no schema could be read, the Supabase
5249
+ * Edge Function in its deploy-first form.
5250
+ */
5251
+ async function runNoOrmInit(options, deps, target) {
5252
+ const { out } = deps;
5253
+ const { supabase } = target;
5254
+ if (supabase.present) out(` Supabase: detected${supabase.projectUrl ? ` (${supabase.projectUrl})` : ""}\n\n`);
5255
+ if (!supabase.present && deps.framework === "unknown") {
5256
+ out("clivly init doesn't recognise your framework yet (looked for Next.js, TanStack Start, SvelteKit, Remix, Nuxt). Without one, --no-orm needs a Supabase project to host the Edge Function.\n");
5257
+ return 1;
5258
+ }
5259
+ const connection = resolveConnectionString(options.processEnv ?? process.env, deps.readFile, options.cwd);
5260
+ const read = options.readLiveSchema ?? ((opts) => readLiveSchema({
5261
+ ...opts,
5262
+ connect: defaultConnect$1(options.cwd),
5263
+ runSupabaseCli: defaultRunSupabaseCli(options.cwd)
5264
+ }));
5265
+ const failures = /* @__PURE__ */ new Set();
5266
+ const tables = await read({
5267
+ connectionString: connection?.value,
5268
+ connectionLabel: connection?.label,
5269
+ onFailure: (reason) => failures.add(reason),
5270
+ out
5271
+ });
5272
+ if (tables) out(` Schema: live database (${tables.length} tables)\n\n`);
5273
+ const source = {
5274
+ connectionLabel: connection?.label ?? null,
5275
+ driverMissing: failures.has("driver_missing")
5276
+ };
5277
+ if (tables && deps.framework !== "unknown") return scaffoldSqlServer(options, deps, target.appDeps, tables, source);
5278
+ if (!supabase.present) {
5279
+ out(source.driverMissing ? "Couldn't read your schema: install `postgres` or `pg` in this app, then re-run `clivly init --no-orm`.\n" : "Couldn't read your schema. Set DATABASE_URL to your Postgres connection string and re-run `clivly init --no-orm`.\n");
5280
+ return 1;
5281
+ }
5282
+ return writeSupabaseFunction(options, deps, tables, source);
5283
+ }
5284
+ async function scaffoldSqlServer(options, deps, appDeps, tables, source) {
5285
+ const plan = planSqlInit(tables, {
5286
+ contactTable: options.contactTableFlag,
5287
+ companyTable: options.companyTableFlag
5288
+ });
5289
+ const { contact } = plan;
5290
+ if (!contact) {
5291
+ printNoContactGuidance(deps.out, plan, options);
5292
+ return options.dryRun ? 0 : 1;
5293
+ }
5294
+ const { driver, install } = sqlDriverFor(appDeps);
5295
+ deps.renderConfig = (renderable) => renderSqlConfig({
5296
+ ...renderable,
5297
+ driver
5298
+ });
5299
+ deps.commentedEnv = source.connectionLabel === null ? [DATABASE_URL_PLACEHOLDER] : [];
5300
+ deps.extraPackages = install;
5301
+ const renderable = {
5302
+ ...plan,
5303
+ contact
5304
+ };
5305
+ printPlan(deps.out, renderable);
5306
+ const code = await scaffold(options, deps, renderable);
5307
+ if (code === 0 && !options.dryRun && !options.diff) printSqlServerSteps(deps, source);
5308
+ return code;
5309
+ }
5310
+ function printSqlServerSteps(deps, source) {
5311
+ if (source.connectionLabel === null) deps.out("\n ! Set DATABASE_URL (your Supabase connection string) before starting the app —\n clivly.config.ts reads its schema and rows with it.\n");
5312
+ const { envKeys } = deps.authWiring;
5313
+ if (envKeys.length > 0) deps.out(`\n The auth/verify route reads ${envKeys.join(" and ")} from the environment.\n`);
5314
+ }
5315
+ function supabaseFunctionMutations(options, deps, contactTable, version, existingToml) {
5316
+ const tomlPath = SUPABASE_CONFIG_TOML;
5317
+ const { files } = renderSupabaseFunction({
5318
+ contactTable,
5319
+ existingConfigToml: existingToml,
5320
+ version
5321
+ });
5322
+ return Object.entries(files).map(([path, contents]) => {
5323
+ if (path !== tomlPath) return {
5324
+ path,
5325
+ contents,
5326
+ action: fileAction(deps.readFile(join(options.cwd, path)), contents, options.force)
5327
+ };
5328
+ let action = "patch";
5329
+ if (existingToml === null) action = "create";
5330
+ else if (existingToml === contents) action = "unchanged";
5331
+ return {
5332
+ path,
5333
+ contents,
5334
+ action
5335
+ };
5336
+ });
5337
+ }
5338
+ function writeSupabaseFunction(options, deps, tables, source) {
5339
+ const { out } = deps;
5340
+ const version = deps.readOwnVersion();
5341
+ if (!version) {
5342
+ out("Couldn't read this CLI's version, so the Edge Function can't pin `npm:clivly@<version>`. Reinstall clivly and re-run `clivly init`.\n");
5343
+ return 1;
5344
+ }
5345
+ const contactTable = tables ? planSqlInit(tables, { contactTable: options.contactTableFlag }).contact?.tableName : void 0;
5346
+ const existingToml = deps.readFile(join(options.cwd, SUPABASE_CONFIG_TOML));
5347
+ const files = supabaseFunctionMutations(options, deps, contactTable, version, existingToml);
5348
+ if (options.dryRun || options.diff) {
5349
+ out("\nDry run — nothing was written.\n\n");
5350
+ for (const file of files) out(` ${file.action.padEnd(9)} ${file.path}\n`);
5351
+ out("\nRe-run without --dry-run to apply.\n");
5352
+ return 0;
5353
+ }
5354
+ out("\nWriting the Clivly Edge Function:\n");
5355
+ applyFiles(options, deps, files);
5356
+ if (tables) out(`\n Contacts: ${contactTable && contactTable !== "auth.users" ? contactTable : "your Supabase Auth users (auth.users)"}\n`);
5357
+ else {
5358
+ out("\n Couldn't read your schema from here, so the function is written deploy-first:\n contacts default to your Supabase Auth users (auth.users), and the function\n reports your other tables to clivly.com once it is deployed.\n");
5359
+ if (deps.framework !== "unknown") out(` ${routeFilesHint(source, FRAMEWORK_LABELS[deps.framework])}\n`);
5360
+ }
5361
+ if (existingToml !== null && clivlyBlockVerifiesJwt(existingToml)) out(`\n ! ${SUPABASE_CONFIG_TOML} has [functions.clivly] with verify_jwt = true.\n Set it to verify_jwt = false: Clivly calls the function with its own signed
5362
+ request, not a Supabase user JWT, so the gateway would reject every call.
5363
+ `);
5364
+ printDeployFirstSteps(out);
5365
+ return 0;
5366
+ }
5367
+ function routeFilesHint(source, framework) {
5368
+ if (source.driverMissing) return `To generate route files for ${framework} instead, install \`postgres\` or \`pg\` in this app, then re-run.`;
5369
+ if (source.connectionLabel) return `Check ${source.connectionLabel}, then re-run to generate route files for ${framework} instead.`;
5370
+ return `Re-run with DATABASE_URL set to generate route files for ${framework} instead.`;
5371
+ }
5372
+ function printDeployFirstSteps(out) {
5373
+ out("\nNext steps:\n");
5374
+ out(` 1. Set both secrets on the function (values from the Clivly dashboard):
5375
+ CLIVLY_SECRET_KEY ${CREDENTIALS_LOCATION}\n CLIVLY_SYNC_TRIGGER_SECRET ${SYNC_SECRET_LOCATION}\n Set them in ${SUPABASE_SECRETS_LOCATION},\n or from a terminal: supabase secrets set CLIVLY_SECRET_KEY=… CLIVLY_SYNC_TRIGGER_SECRET=…
5376
+ `);
5377
+ out(" 2. Deploy it: supabase functions deploy clivly (on Lovable: push the change)\n");
5378
+ out(" 3. Connect it to Clivly:\n\n");
5379
+ out(" npx clivly connect --supabase\n");
5380
+ }
4514
5381
  function normalizeAppRoot(options) {
4515
5382
  const resolution = (options.resolveTargetApp ?? resolveTargetApp)(options.cwd);
4516
5383
  const out = options.out ?? ((line) => process.stdout.write(line));
@@ -4539,6 +5406,7 @@ async function runInit(options) {
4539
5406
  const deps = resolveInitDeps(resolvedOptions);
4540
5407
  const acquired = await acquireSchema(resolvedOptions, deps);
4541
5408
  if ("code" in acquired) return acquired.code;
5409
+ if ("noOrm" in acquired) return runNoOrmInit(resolvedOptions, deps, acquired.noOrm);
4542
5410
  const dbOverride = importOverride(resolvedOptions.dbImportFlag, "db");
4543
5411
  const plan = planInit(dbOverride ? {
4544
5412
  ...acquired,
@@ -4777,6 +5645,7 @@ function runInitFromArgv(argv, cwd) {
4777
5645
  diff: argv.includes("--diff"),
4778
5646
  yes: argv.includes("--yes"),
4779
5647
  noLogin: argv.includes("--no-login"),
5648
+ noOrm: argv.includes("--no-orm"),
4780
5649
  openBrowser: !argv.includes("--no-browser"),
4781
5650
  schemaFlag: flagValue(argv, "--schema"),
4782
5651
  frameworkFlag,
@@ -4786,6 +5655,15 @@ function runInitFromArgv(argv, cwd) {
4786
5655
  companyTableFlag: flagValue(argv, "--company-table")
4787
5656
  });
4788
5657
  }
5658
+ function failedEngineCheck() {
5659
+ if (process.env.CLIVLY_SKIP_ENGINE_CHECK) return false;
5660
+ const engineProblem = engineError(process.version, readOwnEngines());
5661
+ if (engineProblem) {
5662
+ process.stderr.write(engineProblem);
5663
+ return true;
5664
+ }
5665
+ return false;
5666
+ }
4789
5667
  async function main(argv) {
4790
5668
  const [command, ...rest] = argv;
4791
5669
  if (command === "-h" || command === "--help" || isHelpRequest(rest)) {
@@ -4796,13 +5674,7 @@ async function main(argv) {
4796
5674
  process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
4797
5675
  return 0;
4798
5676
  }
4799
- if (!process.env.CLIVLY_SKIP_ENGINE_CHECK) {
4800
- const engineProblem = engineError(process.version, readOwnEngines());
4801
- if (engineProblem) {
4802
- process.stderr.write(engineProblem);
4803
- return 1;
4804
- }
4805
- }
5677
+ if (failedEngineCheck()) return 1;
4806
5678
  let cliEnvFiles = [];
4807
5679
  try {
4808
5680
  cliEnvFiles = (await loadCliConfig(process.cwd()))?.envFiles ?? [];
@@ -4822,6 +5694,7 @@ async function main(argv) {
4822
5694
  case "ping":
4823
5695
  case "doctor":
4824
5696
  case "connect":
5697
+ if (command === "connect" && rest.includes("--supabase")) return await connectSupabase(rest);
4825
5698
  if (command !== "status") process.stderr.write(`\`clivly ${command}\` is a deprecated alias that runs part of \`clivly status\`. Prefer \`clivly status\`.\n`);
4826
5699
  return await runStatus({
4827
5700
  cwd: process.cwd(),