clivly 0.7.2 → 0.7.3

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.
package/index.cjs CHANGED
@@ -3,7 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const require_entity_config = require("./entity-config-D87rV-tE.cjs");
4
4
  require("./mapping-score-CaB3F4Uu.cjs");
5
5
  const require_internal_entity_heuristics = require("./internal-entity-heuristics.cjs");
6
- const require_sdk = require("./sdk-iqOXeWIp.cjs");
6
+ const require_sdk = require("./sdk-BrQYA-GT.cjs");
7
7
  let node_child_process = require("node:child_process");
8
8
  let node_fs = require("node:fs");
9
9
  let node_module = require("node:module");
@@ -12,6 +12,72 @@ let node_path = require("node:path");
12
12
  let node_readline_promises = require("node:readline/promises");
13
13
  let jiti = require("jiti");
14
14
  let node_url = require("node:url");
15
+ //#region ../core/src/env-file.ts
16
+ const ENV_FILES = {
17
+ next: ".env.local",
18
+ "tanstack-start": ".env",
19
+ sveltekit: ".env",
20
+ remix: ".env",
21
+ nuxt: ".env",
22
+ "hono-workers": ".dev.vars"
23
+ };
24
+ /** The conventional env file for a framework. `.env` when we do not know. */
25
+ function envFileFor(framework) {
26
+ return ENV_FILES[normalizeFramework(framework)] ?? ".env";
27
+ }
28
+ const ALIASES = {
29
+ next: "next",
30
+ nextjs: "next",
31
+ "next.js": "next",
32
+ "tanstack-start": "tanstack-start",
33
+ tanstack: "tanstack-start",
34
+ sveltekit: "sveltekit",
35
+ remix: "remix",
36
+ nuxt: "nuxt",
37
+ "hono-workers": "hono-workers",
38
+ hono: "hono-workers",
39
+ workers: "hono-workers"
40
+ };
41
+ /** The canonical id for a framework name, or null when unrecognised. */
42
+ function normalizeFramework(framework) {
43
+ if (!framework) return null;
44
+ return ALIASES[framework.toLowerCase()] ?? null;
45
+ }
46
+ /**
47
+ * Which env file to actually write to.
48
+ *
49
+ * Prefers a file that already holds the key over the conventional one: a
50
+ * project that has been running with credentials in `.env` must not suddenly
51
+ * get a second copy in `.env.local`, leaving two files disagreeing and the
52
+ * stale one still loading. Convention applies to new setups, not to a working
53
+ * one someone already has.
54
+ */
55
+ function resolveEnvFile(input) {
56
+ const conventional = envFileFor(input.framework);
57
+ if (input.existing.includes(conventional)) return conventional;
58
+ return input.existing[0] ?? conventional;
59
+ }
60
+ //#endregion
61
+ //#region src/app-layout.ts
62
+ function resolveAppLayout(cwd, fileExists = node_fs.existsSync) {
63
+ if (fileExists((0, node_path.join)(cwd, "src", "app"))) return "src/app";
64
+ if (fileExists((0, node_path.join)(cwd, "app"))) return "app";
65
+ return fileExists((0, node_path.join)(cwd, "src")) ? "src/app" : "app";
66
+ }
67
+ function shadowedAppDirError(cwd, framework, plannedPaths, fileExists = node_fs.existsSync) {
68
+ if (framework !== "nextjs") return null;
69
+ if (!plannedPaths.some((path) => path.startsWith("app/"))) return null;
70
+ if (!fileExists((0, node_path.join)(cwd, "src", "app"))) return null;
71
+ return `This project has a src/app directory, so writing routes to app/ would shadow it.
72
+
73
+ Next.js reads either app/ or src/app/, never both. A root app/ directory wins,
74
+ and every route under src/app/ disappears from the build.
75
+
76
+ Nothing was written. Please report this at https://github.com/amani-joseph/clivly/issues
77
+ — Clivly should have detected the src/app layout automatically.
78
+ `;
79
+ }
80
+ //#endregion
15
81
  //#region src/load-config.ts
16
82
  const CONFIG_HINT = "Expected clivly.config.ts at your app root exporting `createClivlySDK({...})`.";
17
83
  function resolveConfigPath(cwd, configPath) {
@@ -109,6 +175,14 @@ async function loadCliConfig(cwd) {
109
175
  return envFiles ? { envFiles } : {};
110
176
  }
111
177
  //#endregion
178
+ //#region src/dashboard-locations.ts
179
+ /** Secret + publishable keys. The Connect dialog mints them and shows the secret once. */
180
+ const CREDENTIALS_LOCATION = "Clivly dashboard → Connect app (or Settings → API keys)";
181
+ /** The signing secret Clivly Cloud uses on sync-trigger callbacks. */
182
+ const SYNC_SECRET_LOCATION = "Clivly dashboard → Integrations → Remote sync";
183
+ /** Chat widget records and their allowed origins. */
184
+ const WIDGET_LOCATION = "Clivly dashboard → Settings → Chat widget";
185
+ //#endregion
112
186
  //#region src/detect.ts
113
187
  const FRAMEWORK_MARKERS = [
114
188
  {
@@ -312,10 +386,14 @@ async function runDev(options) {
312
386
  if (result.ok) deps.out("Dashboard-triggered sync now points at this local session.");
313
387
  else deps.out(overrideFailureMessage(result.kind));
314
388
  });
389
+ const stopWatching = deps.watchConfig?.(options.cwd, () => {
390
+ deps.out("clivly.config.ts changed — restart your app for it to take effect.");
391
+ }) ?? null;
315
392
  return await new Promise((resolve) => {
316
393
  const shutdown = async (code) => {
317
394
  if (shuttingDown) return;
318
395
  shuttingDown = true;
396
+ stopWatching?.();
319
397
  tunnel.kill();
320
398
  app?.kill();
321
399
  if (!(await deps.clear().catch(() => UNREACHABLE_RESULT)).ok) deps.out("Warning: could not clear the tunnel override on exit.");
@@ -768,6 +846,29 @@ async function discoverSchema(opts) {
768
846
  };
769
847
  }
770
848
  //#endregion
849
+ //#region src/engine-check.ts
850
+ const MAJOR = /^v?(\d+)/;
851
+ const FIRST_NUMBER = /(\d+)/;
852
+ function currentMajor(version) {
853
+ const match = MAJOR.exec(version);
854
+ return match ? Number(match[1]) : null;
855
+ }
856
+ function requiredMajor(range) {
857
+ if (!range) return null;
858
+ const match = FIRST_NUMBER.exec(range);
859
+ return match ? Number(match[1]) : null;
860
+ }
861
+ function engineError(currentVersion, enginesRange) {
862
+ const have = currentMajor(currentVersion);
863
+ const need = requiredMajor(enginesRange);
864
+ if (have === null || need === null || have >= need) return null;
865
+ return `Clivly requires Node.js ${need} or newer. You are running ${currentVersion}.
866
+
867
+ Upgrade with \`nvm install ${need}\` (or your version manager of choice), then re-run.
868
+ Set CLIVLY_SKIP_ENGINE_CHECK=1 to run anyway — expect unrelated-looking failures.
869
+ `;
870
+ }
871
+ //#endregion
771
872
  //#region src/env-file.ts
772
873
  const REGEX_METACHARACTERS = /[.*+?^${}()|[\]\\]/g;
773
874
  function escapeForRegExp(key) {
@@ -852,6 +953,123 @@ function upsertEnvValues(existing, entries, options = {}) {
852
953
  };
853
954
  }
854
955
  //#endregion
956
+ //#region src/help.ts
957
+ const ROOT_HELP = `clivly — embed a CRM in your app
958
+
959
+ Usage:
960
+ clivly init [options] Scaffold Clivly (config, routes, env file) for your app
961
+ clivly add widget [options] Scaffold the chat-session route
962
+ clivly status [options] Check your setup, step by step
963
+ clivly push-schema [options] Report your schema to Clivly without deploying
964
+ clivly dev [options] Tunnel localhost so remote sync can reach you
965
+ clivly login [options] Pair this machine and write credentials to your env file
966
+ clivly --version Print the installed clivly version
967
+
968
+ Deprecated aliases — each runs part of \`clivly status\` and still works:
969
+ clivly ping credential + reachability
970
+ clivly connect the above, plus config and trigger URL
971
+ clivly doctor config, setup checks and edge safety
972
+
973
+ Prefer \`clivly status\`: it runs the whole ladder and tells you which step you
974
+ are on. The aliases are kept because output and docs have recommended them.
975
+
976
+ Run \`clivly <command> --help\` for details on a command.
977
+ `;
978
+ const COMMAND_HELP = {
979
+ init: `clivly init — scaffold Clivly into this app
980
+
981
+ Usage:
982
+ clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]
983
+ [--schema <path|package>] [--db-import <specifier>]
984
+ [--auth-import <specifier>] [--contact-table <table>]
985
+ [--company-table <table>]
986
+
987
+ Scaffolds clivly.config.ts, the Clivly route files, and .env placeholders.
988
+ Detects your framework, ORM, auth adapter and app layout from the project.
989
+
990
+ Options:
991
+ --dry-run Show what would be written; write nothing
992
+ --diff Show a diff for files that already exist
993
+ --force Overwrite files Clivly owns
994
+ --yes Skip prompts
995
+ --no-login Skip browser pairing
996
+ --schema <p> Path or package holding your ORM schema
997
+ --db-import <s> Module specifier exporting your database instance
998
+ --auth-import <s> Module specifier exporting your auth instance
999
+ --contact-table <t> Table to map as contacts
1000
+ --company-table <t> Table to map as companies
1001
+ `,
1002
+ add: `clivly add widget — scaffold the chat-session route
1003
+
1004
+ Usage:
1005
+ clivly add widget [--force] [--dry-run]
1006
+
1007
+ Writes the route that mints chat-widget sessions. Creates no widget record —
1008
+ that lives in the Clivly dashboard.
1009
+
1010
+ Options:
1011
+ --dry-run Show what would be written; write nothing
1012
+ --force Overwrite the route if it already exists
1013
+ `,
1014
+ status: `clivly status — check your setup, step by step
1015
+
1016
+ Usage:
1017
+ clivly status [--verbose] [--config <path>] [--env-file <path>]
1018
+
1019
+ Runs the setup ladder: credential, reachability, config load, edge-safety,
1020
+ setup checks, sync trigger. Read-only — writes nothing.
1021
+
1022
+ Options:
1023
+ --verbose Show every check, including those that passed
1024
+ --config <path> Path to clivly.config.ts
1025
+ --env-file <path> Extra env file to load
1026
+ `,
1027
+ "push-schema": `clivly push-schema — report your schema without deploying
1028
+
1029
+ Usage:
1030
+ clivly push-schema [--config <path>]
1031
+
1032
+ Sends your discovered tables to Clivly so the dashboard can offer them for
1033
+ mapping. Reads your config; writes nothing locally.
1034
+ `,
1035
+ dev: `clivly dev — tunnel localhost so remote sync can reach you
1036
+
1037
+ Usage:
1038
+ clivly dev [--port <n>] [--api-url <url>] [--route-path <path>] [-- <cmd>]
1039
+
1040
+ Opens a tunnel to your local app and points Clivly's sync trigger at it.
1041
+ Everything after \`--\` runs as your app's dev command.
1042
+
1043
+ Options:
1044
+ --port <n> Local port your app listens on
1045
+ --route-path <path> Path to your mounted tick route
1046
+ `,
1047
+ login: `clivly login — pair this machine with Clivly
1048
+
1049
+ Usage:
1050
+ clivly login [--force] [--rotate] [--api-url <url>] [--no-browser]
1051
+
1052
+ Opens a browser to approve this machine, then writes CLIVLY_SECRET_KEY and
1053
+ CLIVLY_SYNC_TRIGGER_SECRET to .env.
1054
+
1055
+ Options:
1056
+ --force Re-pair even if credentials already exist
1057
+ --rotate Replace the existing credentials
1058
+ --no-browser Print the URL instead of opening a browser
1059
+ `
1060
+ };
1061
+ function isHelpRequest(argv) {
1062
+ for (const arg of argv) {
1063
+ if (arg === "--") return false;
1064
+ if (arg === "--help" || arg === "-h") return true;
1065
+ }
1066
+ return false;
1067
+ }
1068
+ function helpFor(command) {
1069
+ if (!command) return ROOT_HELP;
1070
+ return COMMAND_HELP[command] ?? ROOT_HELP;
1071
+ }
1072
+ //#endregion
855
1073
  //#region src/install.ts
856
1074
  const defaultRun = (command, args, cwd) => new Promise((resolvePromise, reject) => {
857
1075
  const child = (0, node_child_process.spawn)(command, args, {
@@ -1091,11 +1309,11 @@ function credentialEntries(credentials) {
1091
1309
  return [{
1092
1310
  key: SECRET_KEY_ENV,
1093
1311
  value: credentials.apiKey,
1094
- comment: "Org secret key — Settings → API keys"
1312
+ comment: `Org secret key — ${CREDENTIALS_LOCATION}`
1095
1313
  }, {
1096
1314
  key: "CLIVLY_SYNC_TRIGGER_SECRET",
1097
1315
  value: credentials.triggerSecret,
1098
- comment: "Signing secret — Integrations → Remote sync"
1316
+ comment: `Signing secret — ${SYNC_SECRET_LOCATION}`
1099
1317
  }];
1100
1318
  }
1101
1319
  function writeCredentials(options, credentials) {
@@ -1182,12 +1400,19 @@ function chooseSyncFields(table, todos) {
1182
1400
  idField
1183
1401
  };
1184
1402
  }
1403
+ const SPLIT_NAME_COLUMNS = /* @__PURE__ */ new Set([
1404
+ "first_name",
1405
+ "firstname",
1406
+ "given_name"
1407
+ ]);
1185
1408
  function buildEntity(table, concept, todos) {
1186
1409
  const canonical = require_entity_config.CANONICAL_FIELDS[concept];
1187
1410
  const suggested = require_internal_entity_heuristics.toFieldMap(require_internal_entity_heuristics.scoreFieldMap(concept, toScoredTable(table)));
1188
1411
  const fields = {};
1189
1412
  for (const [key, column] of Object.entries(suggested)) if (canonical.includes(key)) fields[key] = column;
1190
1413
  for (const required of require_internal_entity_heuristics.requiredFieldsFor(concept)) if (!fields[required]) todos.push(`Could not map required ${concept} field "${required}" on "${table.tableName}" — add it manually.`);
1414
+ const nameColumn = fields.name?.toLowerCase();
1415
+ if (nameColumn && SPLIT_NAME_COLUMNS.has(nameColumn)) todos.push(`Mapped ${concept} "name" to "${fields.name}" on "${table.tableName}" — that is the given name only. Clivly mirrors one column per field, so add a full-name column if you want surnames.`);
1191
1416
  const { cursorField, idField } = chooseSyncFields(table, todos);
1192
1417
  return {
1193
1418
  moduleKey: table.moduleKey,
@@ -1258,15 +1483,99 @@ function planInit(schema, overrides = {}) {
1258
1483
  contact,
1259
1484
  company,
1260
1485
  tableNames: schema.tables.map((table) => table.tableName),
1486
+ contactCandidates: rankContactCandidates(schema.tables),
1261
1487
  todos
1262
1488
  };
1263
1489
  }
1490
+ const CONTACT_COLUMN_EVIDENCE = [
1491
+ {
1492
+ label: "email",
1493
+ names: ["email", "email_address"],
1494
+ weight: 3
1495
+ },
1496
+ {
1497
+ label: "phone",
1498
+ names: [
1499
+ "phone",
1500
+ "phone_number",
1501
+ "mobile"
1502
+ ],
1503
+ weight: 2
1504
+ },
1505
+ {
1506
+ label: "first name",
1507
+ names: [
1508
+ "first_name",
1509
+ "firstname",
1510
+ "given_name"
1511
+ ],
1512
+ weight: 2
1513
+ },
1514
+ {
1515
+ label: "last name",
1516
+ names: [
1517
+ "last_name",
1518
+ "lastname",
1519
+ "surname",
1520
+ "family_name"
1521
+ ],
1522
+ weight: 2
1523
+ },
1524
+ {
1525
+ label: "name",
1526
+ names: [
1527
+ "name",
1528
+ "full_name",
1529
+ "display_name"
1530
+ ],
1531
+ weight: 1
1532
+ }
1533
+ ];
1534
+ const NAME_MATCH_WEIGHT = 4;
1535
+ /**
1536
+ * Rank the schema's tables by how much they look like people, best first.
1537
+ *
1538
+ * Used only on the failure path, where detection found nothing mappable and the
1539
+ * developer has to choose. `init` previously suggested `tableNames[0]` — the
1540
+ * first table in schema order — so a rental app was told to map its `lease`
1541
+ * table as contacts. Wrong guidance is worse than none: it is confident, and
1542
+ * the developer has no way to see it is wrong.
1543
+ *
1544
+ * Deliberately evidence-based rather than name-based alone, so a table whose
1545
+ * name Clivly has never heard of still surfaces on the strength of its columns.
1546
+ */
1547
+ function rankContactCandidates(tables) {
1548
+ return tables.map((table) => {
1549
+ const columns = new Set(table.columns.flatMap((c) => [c.dbName.toLowerCase(), c.key.toLowerCase()]));
1550
+ const reasons = [];
1551
+ let score = 0;
1552
+ if (require_internal_entity_heuristics.matchesConcept(table.tableName, "contact")) {
1553
+ score += NAME_MATCH_WEIGHT;
1554
+ reasons.push("the name looks like a people table");
1555
+ }
1556
+ for (const evidence of CONTACT_COLUMN_EVIDENCE) {
1557
+ const hit = evidence.names.find((name) => columns.has(name));
1558
+ if (hit) {
1559
+ score += evidence.weight;
1560
+ reasons.push(hit);
1561
+ }
1562
+ }
1563
+ return {
1564
+ reasons,
1565
+ score,
1566
+ table: table.tableName
1567
+ };
1568
+ }).filter((candidate) => candidate.score > 0).sort((a, b) => b.score - a.score || a.table.localeCompare(b.table)).map(({ reasons, table }) => ({
1569
+ reasons,
1570
+ table
1571
+ }));
1572
+ }
1264
1573
  //#endregion
1265
1574
  //#region src/render-config.ts
1266
1575
  const CLIVLY_ENV_KEYS = [
1267
1576
  {
1268
1577
  key: "CLIVLY_SECRET_KEY",
1269
- comment: "Org secret key — Settings → API keys"
1578
+ comment: `Org secret key — ${CREDENTIALS_LOCATION}`
1270
1579
  },
1271
1580
  {
1272
1581
  key: "CLIVLY_SYNC_TRIGGER_URL",
@@ -1274,7 +1583,7 @@ const CLIVLY_ENV_KEYS = [
1274
1583
  },
1275
1584
  {
1276
1585
  key: "CLIVLY_SYNC_TRIGGER_SECRET",
1277
- comment: "Signing secret — Integrations → Remote sync"
1586
+ comment: `Signing secret — ${SYNC_SECRET_LOCATION}`
1278
1587
  }
1279
1588
  ];
1280
1589
  function renderFields(fields) {
@@ -1303,6 +1612,28 @@ function renderDbExpr(plan) {
1303
1612
  if (!plan.db) return "db";
1304
1613
  return dbIsInSchemaModule(plan) ? `schema.${plan.db.moduleKey}` : plan.db.moduleKey;
1305
1614
  }
1615
+ const TRAILING_SCHEMA_SEGMENT = /\/schema(\/index)?$/;
1616
+ /**
1617
+ * Where the `db` instance most likely lives, given where the schema was found.
1618
+ *
1619
+ * Only reached when discovery could not confirm one. Discovery *evaluates* a
1620
+ * candidate module and duck-types its exports for `.select`, which is the right
1621
+ * check but fails for the most common real-world db module: `drizzle(process.
1622
+ * env.DATABASE_URL!)` throws at import time when the env var is absent, and it
1623
+ * is absent precisely when a developer is running `clivly init` for the first
1624
+ * time. So the probe misses, through no fault of the project.
1625
+ *
1626
+ * The old fallback emitted `<YOUR_DB_MODULE>` — not a module specifier, not
1627
+ * valid TypeScript, and invisible until the config failed to load at runtime.
1628
+ * A best-guess relative path is strictly better: right for the conventional
1629
+ * layout (`lib/db/schema.ts` beside `lib/db/index.ts`), and when it is wrong it
1630
+ * is a module-not-found error at build time, naming a real path the developer
1631
+ * can correct.
1632
+ */
1633
+ function guessDbImportPath(schemaImportPath) {
1634
+ const trimmed = schemaImportPath.replace(TRAILING_SCHEMA_SEGMENT, "");
1635
+ return trimmed === schemaImportPath || trimmed === "." || trimmed === "" ? "./db" : trimmed;
1636
+ }
1306
1637
  function renderImports(plan) {
1307
1638
  const lines = [
1308
1639
  "import { createClivlySDK, defineClivlyConfig } from \"clivly/sdk\";",
@@ -1310,8 +1641,10 @@ function renderImports(plan) {
1310
1641
  "import { discoverFromDrizzle } from \"clivly/drizzle\";",
1311
1642
  `import * as schema from "${plan.importPath}";`
1312
1643
  ];
1313
- if (!plan.db) lines.push("import { db } from \"<YOUR_DB_MODULE>\"; // TODO(clivly): replace with the path to your Drizzle `db` instance — NOT your schema file");
1314
- else if (!dbIsInSchemaModule(plan)) lines.push(`import { ${plan.db.moduleKey} } from "${plan.db.importPath}";`);
1644
+ if (plan.db === null) {
1645
+ const guess = guessDbImportPath(plan.importPath);
1646
+ lines.push(`import { db } from "${guess}"; // TODO(clivly): verify this path points at your Drizzle \`db\` instance — NOT your schema file`);
1647
+ } else if (!dbIsInSchemaModule(plan)) lines.push(`import { ${plan.db.moduleKey} } from "${plan.db.importPath}";`);
1315
1648
  return lines.join("\n");
1316
1649
  }
1317
1650
  function renderTodoHeader(todos) {
@@ -1429,6 +1762,83 @@ function renderAuthWiring(auth, authInstance = null) {
1429
1762
  }
1430
1763
  }
1431
1764
  //#endregion
1765
+ //#region src/tsconfig-alias.ts
1766
+ const LEADING_DOT_SLASH$1 = /^\.\//;
1767
+ const TRAILING_WILDCARD = /\/?\*$/;
1768
+ const TRAILING_SLASH = /\/$/;
1769
+ const BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
1770
+ const LINE_COMMENT = /(^|[^:])\/\/.*$/gm;
1771
+ const TRAILING_COMMA = /,(\s*[}\]])/g;
1772
+ /**
1773
+ * `compilerOptions` from a tsconfig's text, or null when it cannot be read.
1774
+ *
1775
+ * tsconfig is JSONC — comments and trailing commas are legal and common, and
1776
+ * `JSON.parse` rejects both. Stripping them is enough here: this only ever reads
1777
+ * two string-valued fields, so the cost of being wrong is falling back to a
1778
+ * relative import, which already works.
1779
+ */
1780
+ function parseTsconfig(source) {
1781
+ try {
1782
+ const stripped = source.replace(BLOCK_COMMENT, "").replace(LINE_COMMENT, "$1").replace(TRAILING_COMMA, "$1");
1783
+ return JSON.parse(stripped).compilerOptions ?? null;
1784
+ } catch {
1785
+ return null;
1786
+ }
1787
+ }
1788
+ /**
1789
+ * Strip a leading "./" and any trailing wildcard so two paths can be compared.
1790
+ *
1791
+ * `"./*"` — an alias rooted at the app itself — must reduce to the empty string,
1792
+ * not to a stray `"*"`; that is the mapping which makes a root-level
1793
+ * clivly.config alias-reachable.
1794
+ */
1795
+ function normalize(value) {
1796
+ return value.replace(LEADING_DOT_SLASH$1, "").replace(TRAILING_WILDCARD, "").replace(TRAILING_SLASH, "");
1797
+ }
1798
+ /**
1799
+ * The alias specifier that reaches `target`, or null when none does.
1800
+ *
1801
+ * `target` is app-root-relative and extensionless, e.g. `lib/auth` or
1802
+ * `clivly.config`. Only wildcard patterns are considered — an exact mapping
1803
+ * names one module and is not a prefix anything else can be rebased onto.
1804
+ *
1805
+ * Longest prefix wins, so `"@components/*": ["./src/components/*"]` beats
1806
+ * `"@/*": ["./src/*"]` for a module under `src/components`, matching how
1807
+ * TypeScript itself resolves.
1808
+ */
1809
+ function aliasFor(input) {
1810
+ if (!input.paths) return null;
1811
+ const target = normalize(input.target);
1812
+ let best = null;
1813
+ for (const [pattern, targets] of Object.entries(input.paths)) {
1814
+ if (!pattern.endsWith("/*")) continue;
1815
+ const prefix = pattern.slice(0, -2);
1816
+ for (const mapped of targets) {
1817
+ const base = baseReaching(mapped, target);
1818
+ if (base === null) continue;
1819
+ const rest = base === "" ? target : target.slice(base.length + 1);
1820
+ if (!best || base.length > best.length) best = {
1821
+ alias: `${prefix}/${rest}`,
1822
+ length: base.length
1823
+ };
1824
+ }
1825
+ }
1826
+ return best?.alias ?? null;
1827
+ }
1828
+ /**
1829
+ * The normalized base of `mapped` when it contains `target`, else null.
1830
+ *
1831
+ * A prefix must end at a segment boundary — `src` must not match `srcinternal`,
1832
+ * a different directory — and the target must be strictly inside the base, since
1833
+ * a wildcard needs a remainder to substitute.
1834
+ */
1835
+ function baseReaching(mapped, target) {
1836
+ if (!mapped.endsWith("/*")) return null;
1837
+ const base = normalize(mapped);
1838
+ if (base === "") return target === "" ? null : "";
1839
+ return target.startsWith(`${base}/`) ? base : null;
1840
+ }
1841
+ //#endregion
1432
1842
  //#region src/scaffold.ts
1433
1843
  const TANSTACK_ROUTE_PREFIX = /^src\/routes\//;
1434
1844
  const TS_EXTENSION = /\.ts$/;
@@ -1460,10 +1870,14 @@ const ROUTE_PATHS = {
1460
1870
  },
1461
1871
  unknown: null
1462
1872
  };
1463
- function routePath(framework, kind) {
1873
+ function applyLayout(framework, path, layout) {
1874
+ if (framework !== "nextjs" || layout === "app") return path;
1875
+ return `src/${path}`;
1876
+ }
1877
+ function routePath(framework, kind, layout = "app") {
1464
1878
  const paths = ROUTE_PATHS[framework];
1465
1879
  if (!paths) throw new Error(`No route path for framework: ${framework}`);
1466
- return paths[kind];
1880
+ return applyLayout(framework, paths[kind], layout);
1467
1881
  }
1468
1882
  const WINDOWS_SEP = /\\/g;
1469
1883
  const LEADING_DOT_SLASH = /^\.\//;
@@ -1471,22 +1885,27 @@ function configImport(routeFilePath) {
1471
1885
  const rel = (0, node_path.relative)((0, node_path.dirname)(routeFilePath), "clivly.config").replace(WINDOWS_SEP, "/");
1472
1886
  return rel.startsWith(".") ? rel : `./${rel}`;
1473
1887
  }
1474
- function hostImportPath(routeFilePath, appRelative) {
1888
+ function hostImportPath(routeFilePath, appRelative, paths) {
1475
1889
  const fromRoot = appRelative.replace(LEADING_DOT_SLASH, "");
1890
+ const alias = aliasFor({
1891
+ paths,
1892
+ target: fromRoot
1893
+ });
1894
+ if (alias) return alias;
1476
1895
  const rel = (0, node_path.relative)((0, node_path.dirname)(routeFilePath), fromRoot).replace(WINDOWS_SEP, "/");
1477
1896
  return rel.startsWith(".") ? rel : `./${rel}`;
1478
1897
  }
1479
- function renderAuthPreamble(routeFilePath, auth) {
1898
+ function renderAuthPreamble(routeFilePath, auth, paths) {
1480
1899
  const lines = [...auth.imports];
1481
1900
  if (auth.hostImport) {
1482
1901
  if (auth.hostImport.todo) lines.push(`// ${auth.hostImport.todo}`);
1483
- const path = hostImportPath(routeFilePath, auth.hostImport.path);
1902
+ const path = hostImportPath(routeFilePath, auth.hostImport.path, paths);
1484
1903
  lines.push(`import { ${auth.hostImport.binding} } from "${path}";`);
1485
1904
  }
1486
1905
  lines.push("", auth.body);
1487
1906
  return lines.join("\n");
1488
1907
  }
1489
- function renderPreamble(kind, importPath, auth, routeFilePath) {
1908
+ function renderPreamble(kind, importPath, auth, paths, routeFilePath) {
1490
1909
  if (kind === "session") return `import { createChatSessionHandler } from "clivly/sdk";
1491
1910
 
1492
1911
  const handler = createChatSessionHandler({
@@ -1497,7 +1916,7 @@ const handler = createChatSessionHandler({
1497
1916
  });
1498
1917
  `;
1499
1918
  if (kind === "verify") return `import clivly from "${importPath}";
1500
- ${renderAuthPreamble(routeFilePath, auth)}
1919
+ ${renderAuthPreamble(routeFilePath, auth, paths)}
1501
1920
  const handler = clivly.createAuthVerifyHandler(resolveUser);
1502
1921
  `;
1503
1922
  return `import clivly from "${importPath}";
@@ -1505,8 +1924,8 @@ const handler = clivly.createAuthVerifyHandler(resolveUser);
1505
1924
  const handler = clivly.createClivlyHandler();
1506
1925
  `;
1507
1926
  }
1508
- function renderBody(framework, importPath, kind, auth, routeFilePath) {
1509
- const preamble = renderPreamble(kind, importPath, auth, routeFilePath);
1927
+ function renderBody(framework, importPath, kind, auth, routeFilePath, paths) {
1928
+ const preamble = renderPreamble(kind, importPath, auth, paths, routeFilePath);
1510
1929
  switch (framework) {
1511
1930
  case "nextjs": return `${preamble}
1512
1931
  export const POST = (request: Request) => handler(request);
@@ -1536,9 +1955,9 @@ export default defineEventHandler((event) => handler(toWebRequest(event)));
1536
1955
  default: throw new Error(`No route template for framework: ${framework}`);
1537
1956
  }
1538
1957
  }
1539
- function renderRouteFile(framework, kind, auth = renderAuthWiring("unknown")) {
1540
- const path = routePath(framework, kind);
1541
- let body = renderBody(framework, configImport(path), kind, auth, path);
1958
+ function renderRouteFile(framework, kind, auth = renderAuthWiring("unknown"), layout = "app", paths) {
1959
+ const path = routePath(framework, kind, layout);
1960
+ let body = renderBody(framework, configImport(path), kind, auth, path, paths);
1542
1961
  if (framework === "tanstack-start") {
1543
1962
  const url = `/${path.replace(TANSTACK_ROUTE_PREFIX, "").replace(TS_EXTENSION, "")}`;
1544
1963
  body = body.replace("__ROUTE__", url);
@@ -1550,28 +1969,28 @@ const COMMON_FILES = [{
1550
1969
  description: "Your Clivly configuration",
1551
1970
  owned: false
1552
1971
  }];
1553
- function planScaffold(framework) {
1972
+ function planScaffold(framework, layout = "app") {
1554
1973
  const paths = ROUTE_PATHS[framework];
1555
1974
  if (!paths) return [];
1556
1975
  return [
1557
1976
  {
1558
- path: paths.tick,
1977
+ path: applyLayout(framework, paths.tick, layout),
1559
1978
  description: "Clivly sync-trigger route (createClivlyHandler)",
1560
1979
  owned: true
1561
1980
  },
1562
1981
  {
1563
- path: paths.verify,
1982
+ path: applyLayout(framework, paths.verify, layout),
1564
1983
  description: "Clivly auth-verify route (createAuthVerifyHandler) — finish resolveUser",
1565
1984
  owned: true
1566
1985
  },
1567
1986
  ...COMMON_FILES
1568
1987
  ];
1569
1988
  }
1570
- function planWidgetScaffold(framework) {
1989
+ function planWidgetScaffold(framework, layout = "app") {
1571
1990
  const paths = ROUTE_PATHS[framework];
1572
1991
  if (!paths) return [];
1573
1992
  return [{
1574
- path: paths.session,
1993
+ path: applyLayout(framework, paths.session, layout),
1575
1994
  description: "Clivly chat-session route (createChatSessionHandler) — add allowedOrigins",
1576
1995
  owned: true
1577
1996
  }];
@@ -1591,9 +2010,9 @@ function planFiles(args) {
1591
2010
  const render = (path) => {
1592
2011
  if (path === "clivly.config.ts") return renderInitConfig(args.plan);
1593
2012
  const kind = path.includes("verify") ? "verify" : "tick";
1594
- return renderRouteFile(args.framework, kind, args.authWiring);
2013
+ return renderRouteFile(args.framework, kind, args.authWiring, args.layout, parseTsconfig(args.readFile((0, node_path.join)(args.cwd, "tsconfig.json")) ?? "")?.paths);
1595
2014
  };
1596
- for (const file of planScaffold(args.framework)) {
2015
+ for (const file of planScaffold(args.framework, args.layout)) {
1597
2016
  const contents = render(file.path);
1598
2017
  mutations.push({
1599
2018
  path: file.path,
@@ -1624,8 +2043,8 @@ function planMutations(args) {
1624
2043
  };
1625
2044
  }
1626
2045
  function planWidgetMutations(args) {
1627
- return planWidgetScaffold(args.framework).map((file) => {
1628
- const contents = renderRouteFile(args.framework, "session");
2046
+ return planWidgetScaffold(args.framework, args.layout).map((file) => {
2047
+ const contents = renderRouteFile(args.framework, "session", void 0, args.layout);
1629
2048
  return {
1630
2049
  path: file.path,
1631
2050
  contents,
@@ -1950,7 +2369,17 @@ const ALLOWED_CALLS = /* @__PURE__ */ new Set([
1950
2369
  "while"
1951
2370
  ]);
1952
2371
  const SIDE_EFFECT_CALLS = /^(dotenv\.config|config|configDotenv|fileURLToPath|readFileSync|require|process\.chdir)$/;
2372
+ const NATIVE_PACKAGES = /* @__PURE__ */ new Set([
2373
+ "bcrypt",
2374
+ "better-sqlite3",
2375
+ "canvas",
2376
+ "node-gyp",
2377
+ "pg-native",
2378
+ "sharp",
2379
+ "sqlite3"
2380
+ ]);
1953
2381
  const ENV_HINT = "Move it to clivly.cli.ts (`envFiles`) or pass --env-file — the CLI reads those in Node, so your config stays edge-safe.";
2382
+ const NATIVE_HINT = "A compiled binary cannot load on an edge runtime — this is the \"Could not locate the bindings file\" / ERR_DLOPEN_FAILED failure. Import your db lazily inside a function, or use a driver that speaks HTTP (e.g. @neondatabase/serverless) in the config.";
1954
2383
  function isNodeBuiltin(specifier) {
1955
2384
  if (specifier.startsWith("node:")) return true;
1956
2385
  return NODE_BUILTINS.has(specifier.split("/")[0] ?? "");
@@ -1967,6 +2396,12 @@ function specifierIssue(specifier, line) {
1967
2396
  hint: ENV_HINT,
1968
2397
  line
1969
2398
  };
2399
+ if (NATIVE_PACKAGES.has(specifier.split("/")[0] ?? "")) return {
2400
+ code: "native_module_in_edge_config",
2401
+ detail: `imports "${specifier}", which ships a compiled binary`,
2402
+ hint: NATIVE_HINT,
2403
+ line
2404
+ };
1970
2405
  if (isNodeBuiltin(specifier)) return {
1971
2406
  code: "node_builtin_in_edge_config",
1972
2407
  detail: `imports "${specifier}", which does not exist on an edge runtime`,
@@ -2006,8 +2441,56 @@ function analyzeEdgeSafety(source) {
2006
2441
  });
2007
2442
  return issues;
2008
2443
  }
2444
+ /** Every relative specifier `source` imports, in first-seen order, deduped. */
2445
+ function relativeImports(source) {
2446
+ const seen = /* @__PURE__ */ new Set();
2447
+ for (const rawLine of source.split(NEWLINE)) {
2448
+ const line = stripComment(rawLine);
2449
+ const specifier = BARE_IMPORT.exec(line)?.[1] ?? IMPORT_FROM.exec(line)?.[1] ?? REQUIRE_CALL.exec(line)?.[1];
2450
+ if (specifier?.startsWith(".")) seen.add(specifier);
2451
+ }
2452
+ return [...seen];
2453
+ }
2454
+ /**
2455
+ * Edge-safety for the config *and* the modules it imports directly.
2456
+ *
2457
+ * The dominant real-world shape is a clean-looking config with
2458
+ * `import { db } from "./lib/db"`, where the problem is one hop away and
2459
+ * invisible to a scan that reads only the config file.
2460
+ *
2461
+ * One hop, not more: each additional level multiplies the files read for a
2462
+ * shrinking return, and the config's own imports are where a host app puts its
2463
+ * database. Bare specifiers are never followed — resolving into node_modules is
2464
+ * a different job with different failure modes, and the denylist already covers
2465
+ * the packages that matter.
2466
+ *
2467
+ * `readModule` returns source text, or null when the module cannot be read;
2468
+ * unreadable is not a finding, since a scan is not a build.
2469
+ */
2470
+ function analyzeConfigTree(input) {
2471
+ const issues = analyzeEdgeSafety(input.source);
2472
+ for (const specifier of relativeImports(input.source)) {
2473
+ const source = input.readModule(specifier);
2474
+ if (source === null) continue;
2475
+ for (const issue of analyzeEdgeSafety(source)) issues.push({
2476
+ ...issue,
2477
+ module: specifier
2478
+ });
2479
+ }
2480
+ return issues;
2481
+ }
2009
2482
  //#endregion
2010
2483
  //#region src/status-stages.ts
2484
+ const MODULE_CANDIDATES = [
2485
+ ".ts",
2486
+ ".tsx",
2487
+ ".js",
2488
+ ".mjs",
2489
+ ".cjs",
2490
+ "/index.ts",
2491
+ "/index.js",
2492
+ ""
2493
+ ];
2011
2494
  function defaultReadConfigSource(path) {
2012
2495
  try {
2013
2496
  return (0, node_fs.readFileSync)(path, "utf8");
@@ -2022,10 +2505,11 @@ const REASON_HINT = {
2022
2505
  rate_limited: "Rate limited (429). Wait a moment and retry.",
2023
2506
  server_error: "Clivly returned a server error (5xx). Retry shortly.",
2024
2507
  client_error: "The request was rejected (4xx). Check your configuration.",
2508
+ server_too_old: "This Clivly server is older than your CLI and has no /clivly/sdk/ping. Upgrade the server, or pin the CLI to match it.",
2025
2509
  network_error: "Could not reach Clivly. Check your network or --api-url."
2026
2510
  };
2027
2511
  const apiKeyStage = {
2028
- id: "api-key",
2512
+ id: "credential",
2029
2513
  label: "API key present",
2030
2514
  run(ctx) {
2031
2515
  if (ctx.apiKey) return Promise.resolve({
@@ -2035,20 +2519,29 @@ const apiKeyStage = {
2035
2519
  return Promise.resolve({
2036
2520
  state: "fail",
2037
2521
  detail: "Secret key is not set.",
2038
- hint: "Copy your secret key from Settings → API keys into CLIVLY_SECRET_KEY in .env."
2522
+ hint: `Copy your secret key from ${CREDENTIALS_LOCATION} into CLIVLY_SECRET_KEY in .env.`
2039
2523
  });
2040
2524
  }
2041
2525
  };
2042
- const heartbeatStage = {
2043
- id: "heartbeat",
2526
+ const reachabilityStage = {
2527
+ id: "application",
2044
2528
  label: "Clivly reachable",
2045
2529
  needs: [apiKeyStage.id],
2046
2530
  async run(ctx) {
2047
2531
  const result = await ctx.connect(ctx.apiKey, ctx.apiUrl);
2048
- if (result.ok) return {
2049
- state: "pass",
2050
- detail: `Reached org: ${result.org?.name ?? "(unnamed org)"}${result.org?.id ? ` (${result.org.id})` : ""}`
2051
- };
2532
+ if (result.ok) {
2533
+ const name = result.org?.name ?? "(unnamed org)";
2534
+ const id = result.org?.id ? ` (${result.org.id})` : "";
2535
+ if (result.appLastSeenAt === null) return {
2536
+ state: "warn",
2537
+ detail: `Reached org: ${name}${id} — your app has not connected yet`,
2538
+ hint: "Start your app with the Clivly SDK mounted; it will appear in the dashboard within a minute."
2539
+ };
2540
+ return {
2541
+ state: "pass",
2542
+ detail: `Reached org: ${name}${id}`
2543
+ };
2544
+ }
2052
2545
  const status = result.status === null ? "no response" : `HTTP ${result.status}`;
2053
2546
  return {
2054
2547
  state: "fail",
@@ -2076,22 +2569,76 @@ const configStage = {
2076
2569
  }
2077
2570
  }
2078
2571
  };
2079
- const LADDER_OWNED_CHECKS = /* @__PURE__ */ new Set(["API key present", "Heartbeat"]);
2572
+ const LADDER_OWNED_CHECKS = /* @__PURE__ */ new Set(["API key present", "Clivly reachable"]);
2573
+ const sdkChecksStage = {
2574
+ id: "setup-checks",
2575
+ label: "Setup checks",
2576
+ needs: [configStage.id],
2577
+ async run(ctx) {
2578
+ const owned = (await ctx.sdk.doctor()).checks.filter((check) => !LADDER_OWNED_CHECKS.has(check.name));
2579
+ const counted = owned.filter((check) => !check.skipped);
2580
+ const passed = counted.filter((check) => check.ok).length;
2581
+ const ok = counted.every((check) => check.ok);
2582
+ const warned = counted.filter((check) => check.warn).length;
2583
+ const summary = warned > 0 ? `${passed} of ${counted.length} passed, ${warned} with warnings` : `${passed} of ${counted.length} passed`;
2584
+ return {
2585
+ state: ok ? "pass" : "fail",
2586
+ detail: summary,
2587
+ sub: owned.map((check) => ({
2588
+ label: check.name,
2589
+ ok: check.ok,
2590
+ skipped: check.skipped,
2591
+ warn: check.warn,
2592
+ detail: check.detail
2593
+ }))
2594
+ };
2595
+ }
2596
+ };
2597
+ const triggerUrlStage = {
2598
+ id: "trigger-url",
2599
+ label: "Sync trigger URL",
2600
+ needs: [configStage.id],
2601
+ run(ctx) {
2602
+ const url = ctx.sdk?.syncTrigger?.url;
2603
+ if (url) return Promise.resolve({
2604
+ state: "pass",
2605
+ detail: url
2606
+ });
2607
+ return Promise.resolve({
2608
+ state: "warn",
2609
+ detail: "Not set — remote sync cannot call back into this app.",
2610
+ hint: "Set CLIVLY_SYNC_TRIGGER_URL once the app is deployed. For local development run `clivly dev` — it opens a tunnel and registers the URL for you. Push-only setups can ignore this."
2611
+ });
2612
+ }
2613
+ };
2080
2614
  /** The full ladder, in the order a developer completes setup. */
2081
2615
  const STATUS_STAGES = [
2082
2616
  apiKeyStage,
2083
- heartbeatStage,
2617
+ reachabilityStage,
2084
2618
  configStage,
2085
2619
  {
2086
2620
  id: "runtime",
2087
2621
  label: "clivly.config is edge-safe",
2622
+ needs: [configStage.id],
2088
2623
  run(ctx) {
2089
2624
  const source = (ctx.readConfigSource ?? defaultReadConfigSource)(ctx.configPath);
2090
2625
  if (source === null) return Promise.resolve({
2091
2626
  state: "skip",
2092
2627
  detail: "config not readable"
2093
2628
  });
2094
- const issues = analyzeEdgeSafety(source);
2629
+ const read = ctx.readConfigSource ?? defaultReadConfigSource;
2630
+ const base = (0, node_path.dirname)(ctx.configPath);
2631
+ const issues = analyzeConfigTree({
2632
+ source,
2633
+ readModule: (specifier) => {
2634
+ const target = (0, node_path.resolve)(base, specifier);
2635
+ for (const candidate of MODULE_CANDIDATES) {
2636
+ const found = read(`${target}${candidate}`);
2637
+ if (found !== null) return found;
2638
+ }
2639
+ return null;
2640
+ }
2641
+ });
2095
2642
  if (issues.length === 0) return Promise.resolve({
2096
2643
  state: "pass",
2097
2644
  detail: "no Node-only code at module scope"
@@ -2108,43 +2655,8 @@ const STATUS_STAGES = [
2108
2655
  });
2109
2656
  }
2110
2657
  },
2111
- {
2112
- id: "setup-checks",
2113
- label: "Setup checks",
2114
- needs: [configStage.id],
2115
- async run(ctx) {
2116
- const owned = (await ctx.sdk.doctor()).checks.filter((check) => !LADDER_OWNED_CHECKS.has(check.name));
2117
- const counted = owned.filter((check) => !check.skipped);
2118
- const passed = counted.filter((check) => check.ok).length;
2119
- return {
2120
- state: counted.every((check) => check.ok) ? "pass" : "fail",
2121
- detail: `${passed} of ${counted.length} passed`,
2122
- sub: owned.map((check) => ({
2123
- label: check.name,
2124
- ok: check.ok,
2125
- skipped: check.skipped,
2126
- detail: check.detail
2127
- }))
2128
- };
2129
- }
2130
- },
2131
- {
2132
- id: "trigger-url",
2133
- label: "Sync trigger URL",
2134
- needs: [configStage.id],
2135
- run(ctx) {
2136
- const url = ctx.sdk?.syncTrigger?.url;
2137
- if (url) return Promise.resolve({
2138
- state: "pass",
2139
- detail: url
2140
- });
2141
- return Promise.resolve({
2142
- state: "warn",
2143
- detail: "Not set — remote sync cannot call back into this app.",
2144
- hint: "Set CLIVLY_SYNC_TRIGGER_URL once the app is deployed. For local development run `clivly dev` — it opens a tunnel and registers the URL for you. Push-only setups can ignore this."
2145
- });
2146
- }
2147
- }
2658
+ sdkChecksStage,
2659
+ triggerUrlStage
2148
2660
  ];
2149
2661
  function defaultLoadSdk(path) {
2150
2662
  return loadConfigSdk(path, "doctor");
@@ -2154,15 +2666,15 @@ function defaultLoadSdk(path) {
2154
2666
  /** Stage ids each legacy command maps onto. */
2155
2667
  const ALIAS_STAGE_IDS = {
2156
2668
  status: STATUS_STAGES.map((stage) => stage.id),
2157
- ping: ["api-key", "heartbeat"],
2669
+ ping: ["credential", "application"],
2158
2670
  doctor: [
2159
2671
  "config",
2160
2672
  "runtime",
2161
2673
  "setup-checks"
2162
2674
  ],
2163
2675
  connect: [
2164
- "api-key",
2165
- "heartbeat",
2676
+ "credential",
2677
+ "application",
2166
2678
  "config",
2167
2679
  "trigger-url"
2168
2680
  ]
@@ -2178,9 +2690,9 @@ const defaultConnect = (apiKey, apiUrl) => require_sdk.createClivlySDK({
2178
2690
  apiKey,
2179
2691
  apiUrl,
2180
2692
  retry: { maxAttempts: 1 }
2181
- }).connect();
2693
+ }).ping();
2182
2694
  function subMark(sub) {
2183
- if (sub.skipped) return "⚠️ ";
2695
+ if (sub.skipped || sub.warn) return "⚠️ ";
2184
2696
  return sub.ok ? "✅" : "❌";
2185
2697
  }
2186
2698
  function renderStage(result, verbose, out) {
@@ -2188,7 +2700,7 @@ function renderStage(result, verbose, out) {
2188
2700
  const detail = result.detail ? ` — ${result.detail}` : "";
2189
2701
  out(` ${MARK[result.state]} ${step} · ${result.label}${detail}\n`);
2190
2702
  for (const sub of result.sub ?? []) {
2191
- if (!(verbose || sub.skipped || !sub.ok)) continue;
2703
+ if (!(verbose || sub.skipped || sub.warn || !sub.ok)) continue;
2192
2704
  const subDetail = sub.detail ? ` — ${sub.detail}` : "";
2193
2705
  out(` ${subMark(sub)} ${sub.label}${subDetail}\n`);
2194
2706
  }
@@ -2214,6 +2726,12 @@ async function runStatus(options) {
2214
2726
  }
2215
2727
  //#endregion
2216
2728
  //#region src/index.ts
2729
+ const ENV_FILE_CANDIDATES = [
2730
+ ".env",
2731
+ ".env.local",
2732
+ ".dev.vars"
2733
+ ];
2734
+ const CONFIG_WATCH_DEBOUNCE_MS = 150;
2217
2735
  function flagValue(argv, flag) {
2218
2736
  const index = argv.indexOf(flag);
2219
2737
  return index >= 0 ? argv[index + 1] : void 0;
@@ -2232,7 +2750,10 @@ const KNOWN_COMMANDS = [
2232
2750
  "push-schema",
2233
2751
  "dev",
2234
2752
  "login",
2235
- "help"
2753
+ "help",
2754
+ "ping",
2755
+ "doctor",
2756
+ "connect"
2236
2757
  ];
2237
2758
  function editDistance(a, b) {
2238
2759
  const m = a.length;
@@ -2275,6 +2796,7 @@ function readDeps(cwd) {
2275
2796
  }
2276
2797
  const ADD_USAGE = "Usage: clivly add widget [--force] [--dry-run]";
2277
2798
  const defaultAddDeps = {
2799
+ fileExists: node_fs.existsSync,
2278
2800
  out: (line) => process.stdout.write(line),
2279
2801
  readFile: (path) => (0, node_fs.existsSync)(path) ? (0, node_fs.readFileSync)(path, "utf8") : null,
2280
2802
  writeFile: (path, contents) => {
@@ -2294,14 +2816,21 @@ function runAdd(argv, cwd, deps = defaultAddDeps) {
2294
2816
  deps.out("Couldn't detect your framework from package.json. `clivly add widget` supports Next.js, TanStack Start, SvelteKit, Remix, and Nuxt.\n");
2295
2817
  return 1;
2296
2818
  }
2819
+ const layout = resolveAppLayout(cwd, deps.fileExists);
2297
2820
  const force = argv.includes("--force");
2298
2821
  const dryRun = argv.includes("--dry-run");
2299
2822
  const files = planWidgetMutations({
2300
2823
  framework,
2301
2824
  cwd,
2302
2825
  force,
2826
+ layout,
2303
2827
  readFile: (path) => deps.readFile(path)
2304
2828
  });
2829
+ const shadowing = shadowedAppDirError(cwd, framework, files.map((file) => file.path), deps.fileExists);
2830
+ if (shadowing) {
2831
+ deps.out(shadowing);
2832
+ return 1;
2833
+ }
2305
2834
  deps.out(`\nClivly add widget — ${FRAMEWORK_LABELS[framework]}\n\n`);
2306
2835
  if (dryRun) deps.out("Dry run — nothing was written.\n\n");
2307
2836
  for (const file of files) {
@@ -2322,7 +2851,7 @@ function runAdd(argv, cwd, deps = defaultAddDeps) {
2322
2851
  }
2323
2852
  if (!dryRun) {
2324
2853
  const sessionPath = files[0]?.path ?? "";
2325
- deps.out(`\nNext steps:\n 1. Add your site origins to allowedOrigins in ${sessionPath}\n 2. Create the widget + set allowed origins in the Clivly dashboard (Settings → Chat widget)\n 3. Embed it: <ClivlyChatWidget widgetId="…" />\n`);
2854
+ deps.out(`\nNext steps:\n 1. Add your site origins to allowedOrigins in ${sessionPath}\n 2. Create the widget + set allowed origins at ${WIDGET_LOCATION}\n 3. Embed it: <ClivlyChatWidget widgetId="…" />\n`);
2326
2855
  }
2327
2856
  return 0;
2328
2857
  }
@@ -2333,6 +2862,13 @@ function readOwnVersion() {
2333
2862
  if (pkg.name === "clivly" && pkg.version) return pkg.version;
2334
2863
  } catch {}
2335
2864
  }
2865
+ function readOwnEngines() {
2866
+ const req = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
2867
+ for (const rel of ["./package.json", "../package.json"]) try {
2868
+ const pkg = req(rel);
2869
+ if (pkg.name === "clivly") return pkg.engines?.node;
2870
+ } catch {}
2871
+ }
2336
2872
  /**
2337
2873
  * Parse a `--db-import` / `--auth-import` value into a discovery-shaped override.
2338
2874
  *
@@ -2362,12 +2898,24 @@ function authInstanceFromFlag(flag) {
2362
2898
  function defaultReadFile(path) {
2363
2899
  return (0, node_fs.existsSync)(path) ? (0, node_fs.readFileSync)(path, "utf8") : null;
2364
2900
  }
2901
+ function resolveEnvPath(cwd) {
2902
+ const framework = detectFramework(readDeps(cwd));
2903
+ return (0, node_path.join)(cwd, resolveEnvFile({
2904
+ existing: ENV_FILE_CANDIDATES.filter((name) => {
2905
+ const path = (0, node_path.join)(cwd, name);
2906
+ if (!(0, node_fs.existsSync)(path)) return false;
2907
+ const contents = (0, node_fs.readFileSync)(path, "utf8");
2908
+ return isKeySet(contents, "CLIVLY_SECRET_KEY") || isKeySet(contents, "CLIVLY_API_KEY");
2909
+ }),
2910
+ framework
2911
+ }));
2912
+ }
2365
2913
  function defaultReadEnv(cwd) {
2366
- const path = (0, node_path.join)(cwd, ".env");
2914
+ const path = resolveEnvPath(cwd);
2367
2915
  return (0, node_fs.existsSync)(path) ? (0, node_fs.readFileSync)(path, "utf8") : "";
2368
2916
  }
2369
2917
  function defaultWriteEnv(cwd, contents) {
2370
- (0, node_fs.writeFileSync)((0, node_path.join)(cwd, ".env"), contents, "utf8");
2918
+ (0, node_fs.writeFileSync)(resolveEnvPath(cwd), contents, "utf8");
2371
2919
  }
2372
2920
  function defaultIsInteractive() {
2373
2921
  return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY) && !process.env.CI;
@@ -2394,6 +2942,8 @@ function resolveInitDeps(options) {
2394
2942
  graph: graphFor(cwd)
2395
2943
  })),
2396
2944
  readFile: options.readFile ?? defaultReadFile,
2945
+ fileExists: options.fileExists ?? node_fs.existsSync,
2946
+ resolveAppLayout: options.resolveAppLayout ?? resolveAppLayout,
2397
2947
  writeConfig: options.writeConfig ?? ((path, contents) => {
2398
2948
  (0, node_fs.mkdirSync)((0, node_path.dirname)(path), { recursive: true });
2399
2949
  (0, node_fs.writeFileSync)(path, contents, "utf8");
@@ -2414,6 +2964,7 @@ function resolveInitDeps(options) {
2414
2964
  rotate: false
2415
2965
  })),
2416
2966
  framework: "unknown",
2967
+ layout: "app",
2417
2968
  authWiring: renderAuthWiring("unknown")
2418
2969
  };
2419
2970
  }
@@ -2428,11 +2979,15 @@ async function acquireSchema(options, deps) {
2428
2979
  const orm = detectOrm(appDeps);
2429
2980
  const auth = detectAuth(appDeps);
2430
2981
  deps.framework = framework;
2982
+ const layout = deps.resolveAppLayout(options.cwd, deps.fileExists);
2983
+ deps.layout = layout;
2431
2984
  deps.authWiring = renderAuthWiring(auth, auth === "better-auth" ? authInstanceFromFlag(options.authImportFlag) ?? await deps.probeAuth(options.cwd) : null);
2432
2985
  out("\nClivly init\n");
2433
2986
  out(` Framework: ${FRAMEWORK_LABELS[framework]}\n`);
2434
2987
  out(` ORM: ${orm}\n`);
2435
- out(` Auth: ${auth}${deps.authWiring.complete ? " (wired)" : ""}\n\n`);
2988
+ out(` Auth: ${auth}${deps.authWiring.complete ? " (wired)" : ""}\n`);
2989
+ if (framework === "nextjs") out(` Layout: ${layout}\n`);
2990
+ out("\n");
2436
2991
  if (orm !== "drizzle") {
2437
2992
  out(`clivly init currently generates config for Drizzle only. Detected ORM: ${orm}\n`);
2438
2993
  return { code: 1 };
@@ -2476,6 +3031,7 @@ function mutationsFor(options, deps, plan) {
2476
3031
  cwd: options.cwd,
2477
3032
  force: options.force,
2478
3033
  framework: deps.framework,
3034
+ layout: deps.layout,
2479
3035
  authWiring: deps.authWiring,
2480
3036
  plan,
2481
3037
  readFile: deps.readFile,
@@ -2535,14 +3091,15 @@ function previewMutations(deps, mutations, options) {
2535
3091
  }
2536
3092
  out(options.diff ? "\nRe-run without --diff to apply; --force to overwrite the files marked conflict.\n" : "\nRe-run without --dry-run to apply.\n");
2537
3093
  }
2538
- function printNextSteps(out, authComplete, loginRan) {
3094
+ function printNextSteps(out, authComplete, loginRan, envFile) {
2539
3095
  out("\nNext steps:\n");
2540
- out(loginRan ? " 1. Credentials written by `clivly login`\n" : " 1. Add CLIVLY_SECRET_KEY to .env — create one in the Clivly dashboard\n under Integrations → Create API Key (or Settings → API keys)\n (the legacy CLIVLY_API_KEY is still accepted)\n");
3096
+ out(loginRan ? " 1. Credentials written by `clivly login`\n" : ` 1. Add CLIVLY_SECRET_KEY to ${envFile} — create one at\n ${CREDENTIALS_LOCATION}\n (the legacy CLIVLY_API_KEY is still accepted)\n`);
2541
3097
  out(" 2. Set CLIVLY_SYNC_TRIGGER_URL to your public tick route\n");
2542
3098
  out(" Local dev? Run `clivly dev` to open a tunnel, or skip this step until you deploy (remote sync is deploy-only locally).\n");
2543
3099
  const step = authComplete ? 3 : 4;
2544
3100
  if (!authComplete) out(" 3. Finish resolveUser in the auth/verify route\n");
2545
3101
  out(` ${step}. Run \`clivly status\` to see where you are\n`);
3102
+ out("\nAfter editing clivly.config.ts, restart your app — it loads the config\nat boot, so a running server keeps using the old one.\n");
2546
3103
  }
2547
3104
  function credentialsMissing(envContents) {
2548
3105
  return !(isKeySet(envContents, "CLIVLY_SECRET_KEY") || isKeySet(envContents, "CLIVLY_API_KEY"));
@@ -2563,6 +3120,11 @@ async function scaffold(options, deps, plan) {
2563
3120
  const pm = deps.detectPackageManager(options.cwd);
2564
3121
  const packages = [resolveRuntimeInstallSpec(deps), ...deps.authWiring.packages];
2565
3122
  const mutations = mutationsFor(options, deps, plan);
3123
+ const shadowing = shadowedAppDirError(options.cwd, deps.framework, mutations.files.map((file) => file.path), deps.fileExists);
3124
+ if (shadowing) {
3125
+ out(shadowing);
3126
+ return 1;
3127
+ }
2566
3128
  if (options.dryRun || options.diff) {
2567
3129
  out(`\nWould install (${pm}): ${packages.join(", ")}\n`);
2568
3130
  previewMutations(deps, mutations, {
@@ -2587,7 +3149,7 @@ async function scaffold(options, deps, plan) {
2587
3149
  out(" Run `clivly login` from a terminal to write CLIVLY_SECRET_KEY and CLIVLY_SYNC_TRIGGER_SECRET.\n");
2588
3150
  } else loginRan = await deps.login(options.cwd) === 0;
2589
3151
  }
2590
- printNextSteps(out, deps.authWiring.complete, loginRan);
3152
+ printNextSteps(out, deps.authWiring.complete, loginRan, envFileFor(detectFramework(deps.readDepsFn(options.cwd))));
2591
3153
  return 0;
2592
3154
  }
2593
3155
  function normalizeAppRoot(options) {
@@ -2654,8 +3216,18 @@ function printNoContactGuidance(out, plan, options) {
2654
3216
  out(`\n Tables in ${plan.importPath}:\n`);
2655
3217
  for (const name of plan.tableNames) out(` ${name}\n`);
2656
3218
  const schemaArg = options.schemaFlag ? ` --schema ${options.schemaFlag}` : "";
2657
- out("\n Pick the one that holds your people and re-run:\n");
2658
- out(` clivly init${schemaArg} --contact-table ${plan.tableNames[0]}\n\n`);
3219
+ const best = plan.contactCandidates[0];
3220
+ if (best) {
3221
+ out(`\n Best guess: ${best.table} — ${best.reasons.join(", ")}\n`);
3222
+ const runnerUp = plan.contactCandidates.slice(1, 3).map((candidate) => candidate.table);
3223
+ if (runnerUp.length > 0) out(` Also possible: ${runnerUp.join(", ")}\n`);
3224
+ out("\n Confirm it and re-run:\n");
3225
+ out(` clivly init${schemaArg} --contact-table ${best.table}\n\n`);
3226
+ return;
3227
+ }
3228
+ out("\n Nothing here looks like a people table — no email, phone or name\n");
3229
+ out(" columns turned up. Pick the one that holds your people and re-run:\n");
3230
+ out(` clivly init${schemaArg} --contact-table ${plan.tableNames[0] ?? "<table>"}\n\n`);
2659
3231
  out(" Nothing was written — Clivly needs one entity before a config can load.\n\n");
2660
3232
  }
2661
3233
  function hasCloudflaredOnPath() {
@@ -2751,6 +3323,22 @@ function defaultDevDeps(options) {
2751
3323
  },
2752
3324
  out: (line) => {
2753
3325
  process.stdout.write(`${line}\n`);
3326
+ },
3327
+ watchConfig: (cwd, onChange) => {
3328
+ const target = resolveConfigPath(cwd);
3329
+ try {
3330
+ let timer = null;
3331
+ const watcher = (0, node_fs.watch)(target, () => {
3332
+ if (timer) clearTimeout(timer);
3333
+ timer = setTimeout(onChange, CONFIG_WATCH_DEBOUNCE_MS);
3334
+ });
3335
+ return () => {
3336
+ if (timer) clearTimeout(timer);
3337
+ watcher.close();
3338
+ };
3339
+ } catch {
3340
+ return null;
3341
+ }
2754
3342
  }
2755
3343
  };
2756
3344
  }
@@ -2829,6 +3417,21 @@ function runInitFromArgv(argv, cwd) {
2829
3417
  }
2830
3418
  async function main(argv) {
2831
3419
  const [command, ...rest] = argv;
3420
+ if (command === "-h" || command === "--help" || isHelpRequest(rest)) {
3421
+ process.stdout.write(helpFor(command));
3422
+ return 0;
3423
+ }
3424
+ if (command === "--version" || command === "-v") {
3425
+ process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
3426
+ return 0;
3427
+ }
3428
+ if (!process.env.CLIVLY_SKIP_ENGINE_CHECK) {
3429
+ const engineProblem = engineError(process.version, readOwnEngines());
3430
+ if (engineProblem) {
3431
+ process.stderr.write(engineProblem);
3432
+ return 1;
3433
+ }
3434
+ }
2832
3435
  let cliEnvFiles = [];
2833
3436
  try {
2834
3437
  cliEnvFiles = (await loadCliConfig(process.cwd()))?.envFiles ?? [];
@@ -2847,14 +3450,16 @@ async function main(argv) {
2847
3450
  case "status":
2848
3451
  case "ping":
2849
3452
  case "doctor":
2850
- case "connect": return await runStatus({
2851
- cwd: process.cwd(),
2852
- apiKey: readSecretKeyEnv(process.env),
2853
- apiUrl: flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL,
2854
- configPath: flagValue(rest, "--config"),
2855
- only: ALIAS_STAGE_IDS[command],
2856
- verbose: rest.includes("--verbose")
2857
- });
3453
+ case "connect":
3454
+ if (command !== "status") process.stderr.write(`\`clivly ${command}\` is a deprecated alias that runs part of \`clivly status\`. Prefer \`clivly status\`.\n`);
3455
+ return await runStatus({
3456
+ cwd: process.cwd(),
3457
+ apiKey: readSecretKeyEnv(process.env),
3458
+ apiUrl: flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL,
3459
+ configPath: flagValue(rest, "--config"),
3460
+ only: ALIAS_STAGE_IDS[command],
3461
+ verbose: rest.includes("--verbose")
3462
+ });
2858
3463
  case "dev": {
2859
3464
  const apiKey = readSecretKeyEnv(process.env);
2860
3465
  const apiUrl = flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL ?? "https://api.clivly.com";
@@ -2877,14 +3482,11 @@ async function main(argv) {
2877
3482
  openBrowser: !rest.includes("--no-browser"),
2878
3483
  deps: defaultLoginDeps()
2879
3484
  });
2880
- case "--version":
2881
- case "-v":
2882
- process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
2883
- return 0;
2884
3485
  case void 0:
3486
+ process.stdout.write(ROOT_HELP);
3487
+ return 0;
2885
3488
  case "help":
2886
- case "--help":
2887
- process.stdout.write("clivly — embed a CRM in your app\n\nUsage:\n clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]\n [--schema <path|package>] [--db-import <specifier>] [--auth-import <specifier>]\n Scaffold Clivly (config, routes, .env) for your app\n clivly add widget [--force] [--dry-run] Scaffold the chat-session route\n clivly status [--verbose] [--config <path>] [--env-file <path>] Check your setup, step by step\n clivly push-schema [--config <path>] Report your schema to Clivly without deploying\n clivly dev [--port <n>] [--api-url <url>] [--route-path <path>] [-- <cmd>] Tunnel localhost for remote sync\n clivly login [--force] [--rotate] [--api-url <url>] [--no-browser] Pair this machine and write CLIVLY_SECRET_KEY / CLIVLY_SYNC_TRIGGER_SECRET to .env\n clivly --version Print the installed clivly version\n");
3489
+ process.stdout.write(helpFor(rest[0]));
2888
3490
  return 0;
2889
3491
  default: {
2890
3492
  process.stdout.write(`Unknown command: ${command}\n`);