@marktiderman/genesis-cli 1.2.0 → 1.4.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.
package/dist/cli.js CHANGED
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { spawnSync } from 'child_process';
2
+ import { execFileSync, spawnSync } from 'child_process';
3
3
  import { readFileSync, existsSync, statSync, readdirSync } from 'fs';
4
4
  import * as path3 from 'path';
5
5
  import { createRequire } from 'module';
6
6
  import { pathToFileURL } from 'url';
7
+ import { createJiti } from 'jiti';
8
+ import { buildFeatureOutputs, checkFeatureOutputs, summarizeCheck } from '@marktiderman/genesis-features/node';
9
+ import { findFeatures } from '@marktiderman/genesis-features';
7
10
  import { studioSetupSql } from '@marktiderman/genesis-studio-server';
8
11
  import { Command } from 'commander';
9
12
  import * as fs from 'fs/promises';
@@ -34,15 +37,15 @@ function parse(comment, keys, where) {
34
37
  if (!value || typeof value !== "object" || Array.isArray(value)) {
35
38
  throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
36
39
  }
37
- const settings = {};
40
+ const settings2 = {};
38
41
  for (const [key, v] of Object.entries(value)) {
39
42
  if (!keys.includes(key)) {
40
43
  throw new CommentSettingsError(`${where}: unknown ${MARKER} setting "${key}". Allowed: ${keys.join(", ")}.`);
41
44
  }
42
45
  if (typeof v !== "string") throw new CommentSettingsError(`${where}: ${MARKER} "${key}" must be a string.`);
43
- settings[key] = v;
46
+ settings2[key] = v;
44
47
  }
45
- return { ...description ? { description } : {}, ...Object.keys(settings).length ? { settings } : {} };
48
+ return { ...description ? { description } : {}, ...Object.keys(settings2).length ? { settings: settings2 } : {} };
46
49
  }
47
50
  function parseTableComment(comment, table) {
48
51
  return parse(comment, TABLE_KEYS, table);
@@ -387,7 +390,8 @@ function loadConfig(root, configPath) {
387
390
  }
388
391
  const own = path3.join(root, "genesis.config.json");
389
392
  if (existsSync(own)) {
390
- return { config: validateConfig(readJson(own)?.doctor ?? {}, own), file: own, dir: root };
393
+ const block = readGenesisConfig(root)?.raw.doctor;
394
+ return { config: validateConfig(block ?? {}, own), file: own, dir: root };
391
395
  }
392
396
  const pkg = path3.join(root, "package.json");
393
397
  if (existsSync(pkg)) {
@@ -403,6 +407,41 @@ function readJson(file) {
403
407
  throw new DoctorConfigError(`${file} is not valid JSON: ${err.message}`);
404
408
  }
405
409
  }
410
+ function readGenesisConfig(root) {
411
+ const file = path3.join(root, "genesis.config.json");
412
+ if (!existsSync(file)) return null;
413
+ const raw = readJson(file);
414
+ if (!isObject(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
415
+ const links = raw.links === void 0 ? void 0 : validateLinks(raw.links, file);
416
+ return links ? { raw, links } : { raw };
417
+ }
418
+ function validateLinks(raw, source = "config") {
419
+ const fail = (msg) => {
420
+ throw new GenesisConfigError(`${source}: ${msg}`);
421
+ };
422
+ if (!isObject(raw)) fail(`"links" must be an object`);
423
+ const c = raw;
424
+ for (const key of Object.keys(c)) if (!LINK_KEYS.has(key)) fail(`links: unknown setting "${key}"`);
425
+ if (!isStringList(c.hosts) || c.hosts.length === 0) fail(`links.hosts must be a non-empty list of host names`);
426
+ for (const host of c.hosts) {
427
+ if (!HOST.test(host)) {
428
+ fail(`links.hosts: "${host}" is not a bare lower-case host name (no scheme, path or port), e.g. "example.com"`);
429
+ }
430
+ }
431
+ if (c.paths !== void 0) {
432
+ if (!isStringList(c.paths)) fail(`links.paths must be a list of path prefixes`);
433
+ for (const p of c.paths) {
434
+ if (!p.startsWith("/") || /[\s?#*]/.test(p)) {
435
+ fail(`links.paths: "${p}" must start with "/" and hold no spaces, "?", "#" or "*"`);
436
+ }
437
+ }
438
+ }
439
+ if (c.webcredentials !== void 0 && typeof c.webcredentials !== "boolean") fail(`links.webcredentials must be true or false`);
440
+ const links = { hosts: [...new Set(c.hosts)] };
441
+ if (c.paths !== void 0) links.paths = [...new Set(c.paths)];
442
+ if (c.webcredentials !== void 0) links.webcredentials = c.webcredentials;
443
+ return links;
444
+ }
406
445
  function validateConfig(raw, source = "config") {
407
446
  const fail = (msg) => {
408
447
  throw new DoctorConfigError(`${source}: ${msg}`);
@@ -481,10 +520,13 @@ function isObject(v) {
481
520
  function isStringList(v) {
482
521
  return Array.isArray(v) && v.every((x) => typeof x === "string");
483
522
  }
484
- var DoctorConfigError, STRING_LISTS, STRINGS, KNOWN, LEVELS, PATTERN_KEYS;
523
+ var GenesisConfigError, DoctorConfigError, STRING_LISTS, STRINGS, KNOWN, LEVELS, PATTERN_KEYS, LINK_KEYS, HOST;
485
524
  var init_config = __esm({
486
525
  "src/doctor/config.ts"() {
487
- DoctorConfigError = class extends Error {
526
+ GenesisConfigError = class extends Error {
527
+ name = "GenesisConfigError";
528
+ };
529
+ DoctorConfigError = class extends GenesisConfigError {
488
530
  name = "DoctorConfigError";
489
531
  };
490
532
  STRING_LISTS = ["src", "extensions", "ignore", "tokenFiles", "ignoreTokenPrefixes", "localPrimitiveDirs", "build"];
@@ -504,6 +546,8 @@ var init_config = __esm({
504
546
  ]);
505
547
  LEVELS = /* @__PURE__ */ new Set(["error", "warn", "off"]);
506
548
  PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
549
+ LINK_KEYS = /* @__PURE__ */ new Set(["hosts", "paths", "webcredentials"]);
550
+ HOST = /^(?=.{1,253}$)(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
507
551
  }
508
552
  });
509
553
 
@@ -532,7 +576,7 @@ function globToRegExp(glob) {
532
576
  }
533
577
  function globMatcher(globs) {
534
578
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
535
- return (path10) => res.some((re) => re.test(path10));
579
+ return (path12) => res.some((re) => re.test(path12));
536
580
  }
537
581
  var init_glob = __esm({
538
582
  "src/doctor/glob.ts"() {
@@ -1261,7 +1305,8 @@ var init_rules = __esm({
1261
1305
  "arbitrary-color",
1262
1306
  "raw-color",
1263
1307
  "undefined-token",
1264
- "shadowed-export"
1308
+ "shadowed-export",
1309
+ "version-skew"
1265
1310
  ];
1266
1311
  DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
1267
1312
  STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -1272,12 +1317,43 @@ var init_rules = __esm({
1272
1317
  ARBITRARY_COLOR_RE = /(?<![\w-])[a-z][a-z-]*-\[(?:#|(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color)\()[^\]]*\]/g;
1273
1318
  }
1274
1319
  });
1320
+ function readReleaseManifest(root) {
1321
+ const dir = findPackageDir(root, UMBRELLA_PACKAGE);
1322
+ const file = dir && path3.join(dir, "dist", "versions.json");
1323
+ if (!file || !existsSync(file)) return null;
1324
+ return JSON.parse(readFileSync(file, "utf8"));
1325
+ }
1326
+ function checkVersionSkew(ctx) {
1327
+ const manifest = readReleaseManifest(ctx.root);
1328
+ if (!manifest) return;
1329
+ for (const [name, want] of Object.entries(manifest.packages)) {
1330
+ const dir = findPackageDir(ctx.root, name);
1331
+ if (!dir) continue;
1332
+ const have = JSON.parse(readFileSync(path3.join(dir, "package.json"), "utf8")).version;
1333
+ if (have === want) continue;
1334
+ ctx.report({
1335
+ rule: "version-skew",
1336
+ level: "warn",
1337
+ file: "package.json",
1338
+ subject: name,
1339
+ message: `${name} is ${have}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Install ${name}@${want}, or move every Genesis package to one release.`
1340
+ });
1341
+ }
1342
+ }
1343
+ var UMBRELLA_PACKAGE;
1344
+ var init_versions = __esm({
1345
+ "src/doctor/versions.ts"() {
1346
+ init_genesis();
1347
+ UMBRELLA_PACKAGE = "@marktiderman/genesis";
1348
+ }
1349
+ });
1275
1350
 
1276
1351
  // src/doctor/index.ts
1277
1352
  var doctor_exports = {};
1278
1353
  __export(doctor_exports, {
1279
1354
  BUILTIN_RULES: () => BUILTIN_RULES,
1280
1355
  DoctorConfigError: () => DoctorConfigError,
1356
+ GenesisConfigError: () => GenesisConfigError,
1281
1357
  defineDoctorPlugin: () => defineDoctorPlugin,
1282
1358
  findPackageDir: () => findPackageDir,
1283
1359
  formatReport: () => formatReport,
@@ -1287,9 +1363,12 @@ __export(doctor_exports, {
1287
1363
  loadGenesis: () => loadGenesis,
1288
1364
  parseExportNames: () => parseExportNames,
1289
1365
  parseRulesMarkdown: () => parseRulesMarkdown,
1366
+ readGenesisConfig: () => readGenesisConfig,
1367
+ readReleaseManifest: () => readReleaseManifest,
1290
1368
  runDoctor: () => runDoctor,
1291
1369
  toJson: () => toJson,
1292
- validateConfig: () => validateConfig
1370
+ validateConfig: () => validateConfig,
1371
+ validateLinks: () => validateLinks
1293
1372
  });
1294
1373
  async function runDoctor(options = {}) {
1295
1374
  const root = path3.resolve(options.root ?? process.cwd());
@@ -1311,7 +1390,8 @@ async function runDoctor(options = {}) {
1311
1390
  { name: "raw-tags", check: checkRawTags },
1312
1391
  { name: "colors", check: checkColors },
1313
1392
  { name: "tokens", check: checkTokens },
1314
- { name: "shadowed-exports", check: checkShadowedExports }
1393
+ { name: "shadowed-exports", check: checkShadowedExports },
1394
+ { name: "version-skew", check: checkVersionSkew }
1315
1395
  ];
1316
1396
  for (const plugin of [...builtins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
1317
1397
  try {
@@ -1417,12 +1497,135 @@ var init_doctor = __esm({
1417
1497
  init_plugins();
1418
1498
  init_rules();
1419
1499
  init_scan();
1500
+ init_versions();
1420
1501
  init_config();
1421
1502
  init_genesis();
1422
1503
  init_patterns();
1423
1504
  init_plugins();
1424
1505
  init_rules();
1425
1506
  init_glob();
1507
+ init_versions();
1508
+ }
1509
+ });
1510
+
1511
+ // src/features.ts
1512
+ var features_exports = {};
1513
+ __export(features_exports, {
1514
+ formatFeature: () => formatFeature,
1515
+ gatherPrEvidence: () => gatherPrEvidence,
1516
+ loadRegistry: () => loadRegistry,
1517
+ runFeaturesBuild: () => runFeaturesBuild,
1518
+ runFeaturesCheck: () => runFeaturesCheck,
1519
+ runFeaturesFind: () => runFeaturesFind
1520
+ });
1521
+ function isObject2(value) {
1522
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1523
+ }
1524
+ function readObject(file, key) {
1525
+ try {
1526
+ const json = JSON.parse(readFileSync(file, "utf-8"));
1527
+ return isObject2(json[key]) ? json[key] : {};
1528
+ } catch {
1529
+ return {};
1530
+ }
1531
+ }
1532
+ function settings(root, options) {
1533
+ const fromPackage = readObject(path3.join(root, "package.json"), "genesisFeatures");
1534
+ const fromConfig = readObject(path3.join(root, "genesis.config.json"), "features");
1535
+ const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
1536
+ return { ...fromPackage, ...fromConfig, ...given };
1537
+ }
1538
+ async function loadRegistry(input) {
1539
+ const root = path3.resolve(input.dir);
1540
+ const options = settings(root, input);
1541
+ const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path3.join(root, p)));
1542
+ if (!registry || !existsSync(path3.join(root, registry))) {
1543
+ throw new Error(`No feature registry found. Looked for ${options.registry ?? DEFAULT_REGISTRIES.join(" and ")}; pass --registry.`);
1544
+ }
1545
+ const jiti = createJiti(path3.join(root, "package.json"), { moduleCache: false });
1546
+ const load = async (file) => await jiti.import(path3.join(root, file));
1547
+ const mod = await load(registry);
1548
+ const features2 = mod.features ?? mod.default;
1549
+ if (!isObject2(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
1550
+ const flags = options.flagsFile ? (await load(options.flagsFile)).flags : mod.flags;
1551
+ if (flags !== void 0 && !isObject2(flags)) {
1552
+ throw new Error(`${options.flagsFile ?? registry}'s \`flags\` export must be an object (from defineFlags).`);
1553
+ }
1554
+ const { dir: _dir, registry: _registry, flagsFile: _flagsFile, prs: _prs, gh: _gh, ...rest } = options;
1555
+ const project = {
1556
+ ...rest,
1557
+ root,
1558
+ source: options.source ?? registry.split(path3.sep).join("/"),
1559
+ features: features2,
1560
+ flags
1561
+ };
1562
+ return project;
1563
+ }
1564
+ async function runFeaturesBuild(options) {
1565
+ return buildFeatureOutputs(await loadRegistry(options));
1566
+ }
1567
+ function ghFailure(error) {
1568
+ const e = error;
1569
+ if (e?.code === "ENOENT") return "gh is not installed";
1570
+ if (e?.code === "ETIMEDOUT" || e?.signal === "SIGTERM") return "gh timed out";
1571
+ const stderr = e?.stderr?.toString().trim();
1572
+ return (stderr || String(error instanceof Error ? error.message : error)).split("\n")[0];
1573
+ }
1574
+ function gatherPrEvidence(project, gh = runGh) {
1575
+ const prs = {};
1576
+ const names = Object.entries(project.features).filter(([, f]) => f.status === "planned").flatMap(([id, f]) => [id, ...f.aliases ?? []]);
1577
+ for (let i = 0; i < names.length; i += LABELS_PER_SEARCH) {
1578
+ const batch = names.slice(i, i + LABELS_PER_SEARCH);
1579
+ const search = `label:${batch.map((n) => `"feature:${n}"`).join(",")}`;
1580
+ try {
1581
+ const out = gh(["pr", "list", "--state", "merged", "--search", search, "--limit", "1000", "--json", "number,title,labels"], project.root);
1582
+ for (const { number, title, labels } of JSON.parse(out)) {
1583
+ for (const { name: label } of labels) {
1584
+ const name = label.startsWith("feature:") ? label.slice("feature:".length) : null;
1585
+ if (name && batch.includes(name)) (prs[name] ??= []).push({ number, title });
1586
+ }
1587
+ }
1588
+ } catch (error) {
1589
+ return { prs, warning: `--prs: couldn't read merged PRs with gh (${ghFailure(error)}), so only changesets were checked for shipped work` };
1590
+ }
1591
+ }
1592
+ return { prs };
1593
+ }
1594
+ async function runFeaturesCheck(options) {
1595
+ const project = await loadRegistry(options);
1596
+ const evidence = options.prs ? gatherPrEvidence(project, options.gh) : void 0;
1597
+ const result = checkFeatureOutputs({ ...project, evidence: evidence && { prs: evidence.prs } });
1598
+ let summary = summarizeCheck(result, project.features);
1599
+ if (evidence?.warning) {
1600
+ result.warnings.push(evidence.warning);
1601
+ summary = `${summarizeCheck(result, project.features)}
1602
+ - ${evidence.warning}.`;
1603
+ }
1604
+ return { ...result, summary };
1605
+ }
1606
+ async function runFeaturesFind(options, term, filters = {}) {
1607
+ const project = await loadRegistry(options);
1608
+ return findFeatures(project.features, term, project.flags, filters);
1609
+ }
1610
+ function formatFeature(r) {
1611
+ const kind = r.layer ? ` ${r.layer}` : "";
1612
+ const lines = [`${r.id} \u2014 ${r.name} [${r.status}${r.horizon ? `, ${r.horizon}` : ""}]${kind} (${r.owner})`, ` ${r.summary}`];
1613
+ if (r.platforms) lines.push(` platforms: ${Object.entries(r.platforms).map(([p, s]) => `${p} ${s}`).join(", ")}`);
1614
+ if (r.entry) lines.push(` import: ${Object.entries(r.entry).map(([p, e]) => `${e} (${p})`).join(", ")}`);
1615
+ if (r.extends) lines.push(` variant of: ${r.extends}`);
1616
+ if (r.slots?.length) lines.push(` slots: ${r.slots.join(", ")}`);
1617
+ if (r.requires?.length) lines.push(` requires: ${r.requires.join(", ")}`);
1618
+ if (r.links?.code?.length) lines.push(` code: ${r.links.code.join(", ")}`);
1619
+ if (r.flags.length) lines.push(` flags: ${r.flags.join(", ")}`);
1620
+ if (r.claimedBy) lines.push(` being built by ${r.claimedBy}`);
1621
+ return lines.join("\n");
1622
+ }
1623
+ var DEFAULT_REGISTRIES, runGh, LABELS_PER_SEARCH;
1624
+ var init_features = __esm({
1625
+ "src/features.ts"() {
1626
+ DEFAULT_REGISTRIES = ["src/features.ts", "features.ts"];
1627
+ runGh = (args, cwd) => execFileSync("gh", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 15e3 });
1628
+ LABELS_PER_SEARCH = 10;
1426
1629
  }
1427
1630
  });
1428
1631
 
@@ -1851,16 +2054,12 @@ export type { Brand } from "./brand";
1851
2054
  },
1852
2055
  {
1853
2056
  path: `tailwind.config.ts`,
1854
- content: tailwindConfig(consumer)
2057
+ content: tailwindConfig(consumer, opts.native ?? false)
1855
2058
  },
1856
2059
  {
1857
2060
  path: `app/global.css`,
1858
2061
  content: globalCss()
1859
2062
  },
1860
- {
1861
- path: `.genesis/cli.yml`,
1862
- content: genesisConfig(consumer)
1863
- },
1864
2063
  {
1865
2064
  path: `CLAUDE.md`,
1866
2065
  content: claudeMd(consumer)
@@ -1910,9 +2109,9 @@ async function runScaffold(opts, fs2) {
1910
2109
  function joinPath(...parts) {
1911
2110
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
1912
2111
  }
1913
- function dirname(path10) {
1914
- const idx = path10.lastIndexOf("/");
1915
- return idx === -1 ? "." : path10.slice(0, idx);
2112
+ function dirname(path12) {
2113
+ const idx = path12.lastIndexOf("/");
2114
+ return idx === -1 ? "." : path12.slice(0, idx);
1916
2115
  }
1917
2116
  function brandPackageJson(consumer, genesisVersion) {
1918
2117
  return JSON.stringify(
@@ -2042,8 +2241,11 @@ export const brand: Brand = {
2042
2241
  };
2043
2242
  `;
2044
2243
  }
2045
- function tailwindConfig(consumer) {
2244
+ function tailwindConfig(consumer, native) {
2046
2245
  return `import type { Config } from "tailwindcss";
2246
+ import { genesisPreset } from "@marktiderman/genesis-design-system/presets/tailwind";${native ? `
2247
+ // NativeWind v4 needs its preset; Genesis's goes after it.
2248
+ import nativewindPreset from "nativewind/preset";` : ""}
2047
2249
  import { brand } from "@${consumer}/brand";
2048
2250
 
2049
2251
  /**
@@ -2059,9 +2261,9 @@ const config: Config = {
2059
2261
  content: [
2060
2262
  "./app/**/*.{ts,tsx}",
2061
2263
  "./components/**/*.{ts,tsx}",
2062
- "./node_modules/@marktiderman/genesis-ui-native/**/*.{js,ts,tsx}",
2063
- ],
2064
- presets: [require("@marktiderman/genesis-design-system/tailwind-preset")],
2264
+ ${native ? ` "./node_modules/@marktiderman/genesis-ui-native/**/*.{js,ts,tsx}",
2265
+ ` : ""} ],
2266
+ presets: [${native ? "nativewindPreset, " : ""}genesisPreset],
2065
2267
  theme: {
2066
2268
  extend: {
2067
2269
  colors: {
@@ -2083,47 +2285,16 @@ export default config;
2083
2285
  }
2084
2286
  function globalCss() {
2085
2287
  return `/**
2086
- * Genesis global stylesheet entry. Imports the canonical token sheet
2087
- * + the consumer's tailwind layers. The token sheet wires CSS variables
2088
- * (--color-primary, --color-foreground, etc.) used by every Genesis
2089
- * primitive's tailwind classes.
2288
+ * Genesis global stylesheet entry. Imports the Genesis theme (the CSS
2289
+ * variables every Genesis primitive's classes read: --background,
2290
+ * --foreground, --primary, \u2026) and the consumer's tailwind layers.
2090
2291
  */
2091
- @import "@marktiderman/genesis-design-system/tokens.css";
2292
+ @import "@marktiderman/genesis-design-system/themes/genesis.css";
2092
2293
  @tailwind base;
2093
2294
  @tailwind components;
2094
2295
  @tailwind utilities;
2095
2296
  `;
2096
2297
  }
2097
- function genesisConfig(consumer) {
2098
- return `# Genesis DESIGN-SYSTEM consumer pin \u2014 read by the genesis CLI + .claude/hooks/*
2099
- # NOT the harness config: the schema-validated harness/root config lives at
2100
- # genesis.config.yml (see genesis.config.example.yml). This file only pins the
2101
- # @marktiderman/genesis-* version + design-system rules for this consumer.
2102
- #
2103
- # version pin: which @marktiderman/genesis-* major are we on. The genesis CLI
2104
- # uses this to validate that an upgrade hasn't drifted past breaking-change
2105
- # boundaries.
2106
- version: "1"
2107
- consumer: "${consumer}"
2108
-
2109
- rules:
2110
- # Block raw hex in consumer code \u2014 must use brand tokens.
2111
- no-raw-hex: error
2112
- # Block StyleSheet.create() in NativeWind-first projects.
2113
- no-stylesheet-create: error
2114
- # Block fork-and-modify of Genesis primitives.
2115
- no-genesis-fork: error
2116
- # Layouts must compose Genesis primitives, not rebuild them.
2117
- prefer-genesis-layout: warn
2118
-
2119
- # Path map \u2014 where consumer composites + brand live. Default values match
2120
- # the scaffolder's output; adjust if your layout differs.
2121
- paths:
2122
- brand: "packages/${consumer}-brand"
2123
- composites: "components"
2124
- app: "app"
2125
- `;
2126
- }
2127
2298
  function claudeMd(consumer) {
2128
2299
  return `# CLAUDE.md \u2014 ${consumer}
2129
2300
 
@@ -2131,8 +2302,9 @@ This consumer was bootstrapped with \`@marktiderman/genesis-cli init ${consumer}
2131
2302
 
2132
2303
  ## Workflow
2133
2304
 
2134
- - **Reuse before extend, extend before create.** See the Genesis usage
2135
- doctrine: \`docs/prds/PRD-07-genesis-consumption-architecture/standards/usage-doctrine.md\`
2305
+ - **Reuse before extend, extend before create.** Before building anything,
2306
+ run \`npx @marktiderman/genesis-cli features find <term>\` and read
2307
+ https://github.com/marktiderman/genesis/blob/main/docs/FRAMEWORK.md
2136
2308
  - **Brand changes live in \`packages/${consumer}-brand\`.** Don't fork Genesis
2137
2309
  primitives \u2014 edit your brand schema instead (Layer 1).
2138
2310
  - **Layout customization has 4 layers.** Default \u2192 named props \u2192
@@ -2140,9 +2312,9 @@ This consumer was bootstrapped with \`@marktiderman/genesis-cli init ${consumer}
2140
2312
 
2141
2313
  ## Critical rules
2142
2314
 
2143
- - \`.genesis/cli.yml\` design-system rules are enforced via Claude Code hooks. Don't
2144
- bypass with \`StyleSheet.create()\` or raw hex; use brand tokens.
2145
- - Run \`pnpm test\` before every commit.
2315
+ - \`genesis doctor\` enforces the design-system rules. Don't bypass them with
2316
+ \`StyleSheet.create()\` or raw hex; use brand tokens and theme roles.
2317
+ - Run your test script before every commit.
2146
2318
  - Open RFCs in the genesis repo for missing primitives \u2014 don't fork
2147
2319
  locally and forget.
2148
2320
 
@@ -2153,12 +2325,19 @@ This consumer was bootstrapped with \`@marktiderman/genesis-cli init ${consumer}
2153
2325
  - \`app/global.css\` \u2014 Genesis token sheet + tailwind layers
2154
2326
  `;
2155
2327
  }
2328
+ function cliVersion() {
2329
+ try {
2330
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
2331
+ } catch {
2332
+ return "unknown";
2333
+ }
2334
+ }
2156
2335
  var program = new Command();
2157
- program.name("genesis").description("Genesis CLI \u2014 scaffolders + workspace tooling").version("0.1.0");
2336
+ program.name("genesis").description("Genesis CLI \u2014 scaffolders + workspace tooling").version(cliVersion());
2158
2337
  program.command("init").description("Scaffold a new Genesis consumer (brand package + tailwind + tokens)").argument("<consumer>", "Consumer slug (lowercase, e.g., 'acme')").option("-t, --target <dir>", "Target directory (default: cwd)", process.cwd()).option(
2159
2338
  "--genesis-version <v>",
2160
2339
  "Pin @marktiderman/genesis-* version (default: 'workspace:^' for monorepo)"
2161
- ).option(
2340
+ ).option("--native", "An Expo app: add NativeWind's preset and scan genesis-ui-native", false).option(
2162
2341
  "--emit-conflicts",
2163
2342
  "Emit `.genesis-next` siblings for files that already exist (so you can diff)",
2164
2343
  false
@@ -2170,6 +2349,7 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
2170
2349
  targetDir: opts.target,
2171
2350
  genesisVersion: opts.genesisVersion,
2172
2351
  emitConflicts: opts.emitConflicts ?? false,
2352
+ native: opts.native ?? false,
2173
2353
  logger: {
2174
2354
  info: (msg) => console.log(msg),
2175
2355
  warn: (msg) => console.warn(msg),
@@ -2191,8 +2371,8 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
2191
2371
  console.log("");
2192
2372
  console.log("Next steps:");
2193
2373
  console.log(` 1. Edit packages/${consumer}-brand/src/brand.ts with your colors`);
2194
- console.log(` 2. pnpm install`);
2195
- console.log(` 3. Read docs/prds/PRD-07-genesis-consumption-architecture/standards/usage-doctrine.md`);
2374
+ console.log(` 2. Install dependencies with your package manager`);
2375
+ console.log(` 3. Run genesis doctor, and read https://github.com/marktiderman/genesis/blob/main/docs/FRAMEWORK.md`);
2196
2376
  });
2197
2377
  program.command("introspect").description("Write a checked-in contract (resources.genesis.ts) from the Postgres catalog or a PostgREST/Supabase OpenAPI spec").option("--database-env <name>", "Environment variable holding the Postgres URL", "DATABASE_URL").option("--openapi <file-or-url>", "Read a PostgREST OpenAPI document (a Supabase project's /rest/v1/) instead of Postgres").option("--header <header...>", "HTTP header for --openapi URLs, for values that aren't secret (repeatable)").option("--apikey-env <name>", "Environment variable holding the API key for --openapi URLs (sent as apikey and Bearer)").option("-s, --schema <schemas>", "Comma-separated schemas", "public").option("-o, --out <file>", "Where to write the contract", "resources.genesis.ts").option("--check", "Write nothing; exit 1 if the contract on disk is out of date (for CI)", false).action(async (opts) => {
2198
2378
  const schemas = opts.schema.split(",").map((s) => s.trim()).filter(Boolean);
@@ -2250,18 +2430,63 @@ program.command("doctor").description("Check this app against the installed Gene
2250
2430
  console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result));
2251
2431
  process.exitCode = result.ok ? 0 : 1;
2252
2432
  } catch (err) {
2253
- if (!(err instanceof doctor.DoctorConfigError)) throw err;
2433
+ if (!(err instanceof doctor.GenesisConfigError)) throw err;
2254
2434
  if (opts.json) console.log(JSON.stringify({ ok: false, error: err.message }, null, 2));
2255
2435
  else console.error(`\u2717 ${err.message}`);
2256
2436
  process.exitCode = 2;
2257
2437
  }
2258
2438
  });
2439
+ var features = program.command("features").description('The feature registry: one typed features.ts, everything else generated from it. Settings: genesis.config.json "features" (or package.json "genesisFeatures")');
2440
+ function featureOptions(command) {
2441
+ return command.option("-d, --dir <dir>", "The repo root", process.cwd()).option("-r, --registry <file>", "The registry (default: src/features.ts, then features.ts)").option("--flags-file <file>", "A flags file exporting `flags` (default: the registry's own `flags` export)").option("--agents <file>", "The AGENTS.md that holds the pointer block (default AGENTS.md)").option("--json <file>", "The JSON copy, also the record of every id (default features.json)").option("--command <text>", "How people run this CLI here, named in generated files (default `genesis features`)");
2442
+ }
2443
+ featureOptions(features.command("build").description("Write the AGENTS.md block, features.json, flags.json, the skill and the marketing block")).action(
2444
+ async (opts) => {
2445
+ const { runFeaturesBuild: runFeaturesBuild2 } = await Promise.resolve().then(() => (init_features(), features_exports));
2446
+ const changed = await runFeaturesBuild2(opts);
2447
+ console.log(changed.length ? changed.map((f) => `~ ${f}`).join("\n") : "\u2714 Generated feature files are up to date.");
2448
+ }
2449
+ );
2450
+ featureOptions(features.command("check").description("Errors fail (stale output, missing code paths, flag rules, removed ids, bad tags); warnings don't")).option("--labels <list>", "The PR's labels, comma-separated, to check feature:<id> labels").option("--prs", "Also read merged PRs labelled feature:<id> with gh, to warn about planned features that shipped", false).option("--summary", "Print a short summary and always exit 0 (for a SessionStart hook)", false).action(async (opts) => {
2451
+ const { runFeaturesCheck: runFeaturesCheck2 } = await Promise.resolve().then(() => (init_features(), features_exports));
2452
+ const { summary, labels, ...rest } = opts;
2453
+ const result = await runFeaturesCheck2({ ...rest, labels: labels?.split(",").map((l) => l.trim()).filter(Boolean) });
2454
+ if (summary) {
2455
+ console.log(result.summary);
2456
+ return;
2457
+ }
2458
+ for (const warning of result.warnings) console.warn(`! ${warning}`);
2459
+ for (const error of result.errors) console.error(`\u2717 ${error}`);
2460
+ if (result.ok) console.log(`\u2714 The feature registry and the repo agree${result.warnings.length ? ` (${result.warnings.length} warning${result.warnings.length === 1 ? "" : "s"})` : ""}.`);
2461
+ process.exitCode = result.ok ? 0 : 1;
2462
+ });
2463
+ featureOptions(
2464
+ features.command("find").description("Search features before building: reuse one, extend one, or add an idea first").argument("[term]", "What to look for (id, alias, name, keyword, summary, import, slot or code path)", "").option("--platform <platform>", "Only features on web, native, server or cli").option("--layer <layer>", "Only token, primitive, pattern, layout, hook, provider, block, service or tool").option("--status <status>", "Only idea, planned, building, beta, live, deprecated or retired")
2465
+ ).action(async (term, opts) => {
2466
+ const { FEATURE_LAYERS, FEATURE_PLATFORMS, FEATURE_STATUSES } = await import('@marktiderman/genesis-features');
2467
+ const { runFeaturesFind: runFeaturesFind2, formatFeature: formatFeature2 } = await Promise.resolve().then(() => (init_features(), features_exports));
2468
+ const pick = (name, value, allowed) => {
2469
+ if (value === void 0) return void 0;
2470
+ if (allowed.includes(value)) return value;
2471
+ return program.error(`--${name} must be one of ${allowed.join(", ")}`);
2472
+ };
2473
+ const { platform, layer, status, ...rest } = opts;
2474
+ const filters = {
2475
+ platform: pick("platform", platform, FEATURE_PLATFORMS),
2476
+ layer: pick("layer", layer, FEATURE_LAYERS),
2477
+ status: pick("status", status, FEATURE_STATUSES)
2478
+ };
2479
+ if (!term && !filters.platform && !filters.layer && !filters.status) program.error("Give a term, or --platform, --layer or --status");
2480
+ const hits = await runFeaturesFind2(rest, term, filters);
2481
+ const what = term ? `"${term}"` : "those filters";
2482
+ console.log(hits.length ? hits.map(formatFeature2).join("\n\n") : `No feature matches ${what}. If this is new work, add it to the registry first (an idea is enough).`);
2483
+ });
2259
2484
  var studio = program.command("studio").description("The Genesis Data Studio");
2260
2485
  studio.command("init").description("Turn the Data Studio on in this app: a server for every table, a page, and one migration to review").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--host <host>", "next, tanstack-start or supabase-function (default: detected)").option("--route <path>", "Where the page lives", "/admin/data").option("--login-role <name>", "The studio's database login", "genesis_studio_login").option("--force", "Overwrite files that already exist", false).action(async (opts) => {
2261
2486
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
2262
2487
  const root = path3.resolve(opts.dir);
2263
2488
  const packageJson = JSON.parse(await fs.readFile(path3.join(root, "package.json"), "utf-8").catch(() => "{}"));
2264
- const existsSync7 = (await import('fs')).existsSync;
2489
+ const existsSync9 = (await import('fs')).existsSync;
2265
2490
  const readSync = (await import('fs')).readFileSync;
2266
2491
  const readdirSync3 = (await import('fs')).readdirSync;
2267
2492
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
@@ -2270,8 +2495,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
2270
2495
  const plan = planStudioInit2(
2271
2496
  {
2272
2497
  packageJson,
2273
- exists: (p) => existsSync7(path3.join(root, p)),
2274
- read: (p) => existsSync7(path3.join(root, p)) ? readSync(path3.join(root, p), "utf-8") : null,
2498
+ exists: (p) => existsSync9(path3.join(root, p)),
2499
+ read: (p) => existsSync9(path3.join(root, p)) ? readSync(path3.join(root, p), "utf-8") : null,
2275
2500
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
2276
2501
  listDeep: (p) => {
2277
2502
  const out = [];
@@ -2311,14 +2536,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
2311
2536
  console.log(`+ ${file.path} (appended)`);
2312
2537
  continue;
2313
2538
  }
2314
- if (existsSync7(target) && !opts.force) {
2539
+ if (existsSync9(target) && !opts.force) {
2315
2540
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
2316
2541
  continue;
2317
2542
  }
2318
2543
  await fs.writeFile(target, file.content, "utf-8");
2319
2544
  console.log(`+ ${file.path}`);
2320
2545
  }
2321
- const pm = existsSync7(path3.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync7(path3.join(root, "yarn.lock")) ? "yarn add" : existsSync7(path3.join(root, "bun.lock")) || existsSync7(path3.join(root, "bun.lockb")) ? "bun add" : "npm install";
2546
+ const pm = existsSync9(path3.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync9(path3.join(root, "yarn.lock")) ? "yarn add" : existsSync9(path3.join(root, "bun.lock")) || existsSync9(path3.join(root, "bun.lockb")) ? "bun add" : "npm install";
2322
2547
  console.log("");
2323
2548
  console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
2324
2549
  console.log(` 1. ${pm} ${plan.install.join(" ")}`);