@marktiderman/genesis-cli 1.12.0 → 1.13.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/README.md CHANGED
@@ -343,10 +343,16 @@ comment on column public.customers.notes is
343
343
  'Private to staff. @genesis {"label": "Internal notes", "widget": "textarea"}';
344
344
  ```
345
345
 
346
- The text before `@genesis` stays the description. Tables take `label`, `labelField` and
347
- `description`; columns take `label`, `description` and `widget`. Anything else is an error that
348
- names the table or column. These settings are generator input only: the checked-in file is what
349
- ships.
346
+ The text before `@genesis` stays the description. Tables take `label`, `labelField`, `noun`,
347
+ `nounPlural` and `description` (strings). Columns take `label`, `description` and `widget`
348
+ (strings), plus `readonly` (true for a column only the server writes: a UI shows it read-only) and
349
+ `sensitive` (true to keep it out of lists, exports and previews unless a screen asks). Anything
350
+ else is an error that names the table or column. These settings are generator input only: the
351
+ checked-in file is what ships.
352
+
353
+ Each resource is emitted as its own `as const satisfies ResourceContract<Row>` constant (so a bad
354
+ setting, like an unknown `widget`, fails to compile), with a row type and a field-name union
355
+ (`PublicBrandsField`), and `contracts` collects them by `schema.table`.
350
356
 
351
357
  ## genesis doctor
352
358
 
package/dist/cli.js CHANGED
@@ -390,7 +390,9 @@ ${globs.join("\n")}`;
390
390
  for (const dir of [...dirs].sort()) {
391
391
  const manifest = path23.join(dir, "package.json");
392
392
  if (!existsSync(manifest)) continue;
393
- if (!inside(real2, realpathSync(dir))) continue;
393
+ if (!inside(real2, realpathSync(dir))) {
394
+ throw new LocalPackagesError(`${path23.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
395
+ }
394
396
  let pkg;
395
397
  try {
396
398
  pkg = JSON.parse(readFileSync(manifest, "utf8"));
@@ -1680,13 +1682,17 @@ function parse(comment, keys, where) {
1680
1682
  }
1681
1683
  const settings2 = {};
1682
1684
  for (const [key2, v] of Object.entries(value)) {
1683
- if (!keys.includes(key2)) {
1684
- throw new CommentSettingsError(`${where}: unknown ${MARKER} setting "${key2}". Allowed: ${keys.join(", ")}.`);
1685
+ const kind = keys[key2];
1686
+ if (!kind) {
1687
+ throw new CommentSettingsError(`${where}: unknown ${MARKER} setting "${key2}". Allowed: ${Object.keys(keys).join(", ")}.`);
1685
1688
  }
1686
- if (typeof v !== "string") throw new CommentSettingsError(`${where}: ${MARKER} "${key2}" must be a string.`);
1689
+ if (typeof v !== kind) throw new CommentSettingsError(`${where}: ${MARKER} "${key2}" must be a ${kind}.`);
1687
1690
  settings2[key2] = v;
1688
1691
  }
1689
- return { ...description ? { description } : {}, ...Object.keys(settings2).length ? { settings: settings2 } : {} };
1692
+ return {
1693
+ ...description ? { description } : {},
1694
+ ...Object.keys(settings2).length ? { settings: settings2 } : {}
1695
+ };
1690
1696
  }
1691
1697
  function parseTableComment(comment, table) {
1692
1698
  return parse(comment, TABLE_KEYS, table);
@@ -1698,8 +1704,8 @@ var MARKER, TABLE_KEYS, FIELD_KEYS, CommentSettingsError;
1698
1704
  var init_comments = __esm({
1699
1705
  "src/introspect/comments.ts"() {
1700
1706
  MARKER = "@genesis";
1701
- TABLE_KEYS = ["label", "labelField", "description"];
1702
- FIELD_KEYS = ["label", "description", "widget"];
1707
+ TABLE_KEYS = { label: "string", labelField: "string", description: "string", noun: "string", nounPlural: "string" };
1708
+ FIELD_KEYS = { label: "string", description: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
1703
1709
  CommentSettingsError = class extends Error {
1704
1710
  };
1705
1711
  }
@@ -1879,12 +1885,16 @@ function typeName(table) {
1879
1885
  const pascal = `${table.schema}_${table.table}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join("");
1880
1886
  return `${/^[0-9]/.test(pascal) ? "T" : ""}${pascal}Row`;
1881
1887
  }
1888
+ function constName(table) {
1889
+ const row = typeName(table).replace(/Row$/, "");
1890
+ return row[0].toLowerCase() + row.slice(1);
1891
+ }
1882
1892
  function tsType(column) {
1883
1893
  const base = column.enumValues?.length ? column.enumValues.map(quote).join(" | ") : TS_TYPE[column.type];
1884
1894
  const element = column.array ? base.includes("|") ? `(${base})[]` : `${base}[]` : base;
1885
1895
  return column.nullable ? `${element} | null` : element;
1886
1896
  }
1887
- function field(column) {
1897
+ function field(column, indent) {
1888
1898
  const parts = [`name: ${quote(column.name)}`, `type: ${quote(column.type)}`, `dbType: ${quote(column.dbType)}`];
1889
1899
  if (column.array) parts.push("array: true");
1890
1900
  if (column.nullable) parts.push("nullable: true");
@@ -1900,10 +1910,23 @@ function field(column) {
1900
1910
  if (label) parts.push(`label: ${quote(label)}`);
1901
1911
  if (description) parts.push(`description: ${quote(description)}`);
1902
1912
  if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
1903
- return ` { ${parts.join(", ")} },`;
1913
+ if (column.settings?.readonly) parts.push("readOnly: true");
1914
+ if (column.settings?.sensitive) parts.push("sensitive: true");
1915
+ return `${indent}{ ${parts.join(", ")} },`;
1904
1916
  }
1905
1917
  function emitContracts(tables, options) {
1906
1918
  const sorted = [...tables].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1919
+ const seen = /* @__PURE__ */ new Map();
1920
+ for (const table of sorted) {
1921
+ const id = typeName(table);
1922
+ const other = seen.get(id);
1923
+ if (other) throw new EmitError(`${other} and ${table.name} would both be named ${id}; rename one, or introspect them separately.`);
1924
+ seen.set(id, table.name);
1925
+ const labelField = table.settings?.labelField;
1926
+ if (labelField && !table.columns.some((c) => c.name === labelField)) {
1927
+ throw new EmitError(`${table.name}: @genesis labelField "${labelField}" isn't one of its columns.`);
1928
+ }
1929
+ }
1907
1930
  const out = [
1908
1931
  "// Generated by `genesis introspect` \u2014 do not edit by hand.",
1909
1932
  `// Source: ${options.source}`,
@@ -1912,31 +1935,42 @@ function emitContracts(tables, options) {
1912
1935
  "// Labels, widgets and descriptions come from `@genesis {...}` settings in",
1913
1936
  "// table and column comments. Pass `contracts` to createStudioHandler: it",
1914
1937
  "// wins over discovery for presentation, while types, keys and every",
1915
- "// permission still come from the live database.",
1938
+ "// permission still come from the live database. Each contract goes through",
1939
+ "// defineResource, so a bad @genesis setting fails to compile and views read the",
1940
+ "// row type with RowOf<typeof contract>.",
1916
1941
  "",
1917
- "export const contracts = {"
1942
+ 'import { defineResource } from "@marktiderman/genesis-core";',
1943
+ ""
1918
1944
  ];
1919
1945
  for (const table of sorted) {
1920
- out.push(` ${quote(table.name)}: {`);
1921
- out.push(` name: ${quote(table.name)},`);
1922
- out.push(` key: ${table.key.length === 1 ? quote(table.key[0]) : `[${table.key.map(quote).join(", ")}]`},`);
1923
- if (table.settings?.label) out.push(` label: ${quote(table.settings.label)},`);
1924
- if (table.settings?.labelField) out.push(` labelField: ${quote(table.settings.labelField)},`);
1946
+ const row = typeName(table);
1947
+ out.push(`/** \`${table.name}\`. */`);
1948
+ out.push(`export const ${constName(table)} = defineResource<${row}>()({`);
1949
+ out.push(` name: ${quote(table.name)},`);
1950
+ out.push(` key: ${table.key.length === 1 ? quote(table.key[0]) : `[${table.key.map(quote).join(", ")}]`},`);
1951
+ if (table.settings?.label) out.push(` label: ${quote(table.settings.label)},`);
1952
+ if (table.settings?.labelField) out.push(` labelField: ${quote(table.settings.labelField)},`);
1953
+ if (table.settings?.noun) out.push(` noun: ${quote(table.settings.noun)},`);
1954
+ if (table.settings?.nounPlural) out.push(` nounPlural: ${quote(table.settings.nounPlural)},`);
1925
1955
  const description = table.settings?.description ?? table.description;
1926
- if (description) out.push(` description: ${quote(description)},`);
1927
- out.push(" fields: [");
1928
- for (const column of table.columns) out.push(field(column));
1929
- out.push(" ],");
1930
- out.push(" },");
1931
- }
1956
+ if (description) out.push(` description: ${quote(description)},`);
1957
+ out.push(" fields: [");
1958
+ for (const column of table.columns) out.push(field(column, " "));
1959
+ out.push(" ],");
1960
+ out.push("});", "");
1961
+ }
1962
+ out.push("export const contracts = {");
1963
+ for (const table of sorted) out.push(` ${quote(table.name)}: ${constName(table)},`);
1932
1964
  out.push("} as const;", "");
1933
1965
  out.push("/** Every resource in this contract, `schema.table`. */");
1934
1966
  out.push("export type GenesisResource = keyof typeof contracts;", "");
1935
1967
  for (const table of sorted) {
1936
1968
  out.push(`/** A row of \`${table.name}\`, as the studio handler returns it. */`);
1937
- out.push(`export interface ${typeName(table)} {`);
1969
+ out.push(`export type ${typeName(table)} = {`);
1938
1970
  for (const column of table.columns) out.push(` ${propKey(column.name)}: ${tsType(column)};`);
1939
- out.push("}", "");
1971
+ out.push("};", "");
1972
+ out.push(`/** The field names of \`${table.name}\`. */`);
1973
+ out.push(`export type ${typeName(table).replace(/Row$/, "Field")} = keyof ${typeName(table)};`, "");
1940
1974
  }
1941
1975
  out.push("/** Row types by resource. */");
1942
1976
  out.push("export interface GenesisRows {");
@@ -1944,7 +1978,7 @@ function emitContracts(tables, options) {
1944
1978
  out.push("}", "");
1945
1979
  return out.join("\n");
1946
1980
  }
1947
- var TS_TYPE;
1981
+ var TS_TYPE, EmitError;
1948
1982
  var init_emit = __esm({
1949
1983
  "src/introspect/emit.ts"() {
1950
1984
  TS_TYPE = {
@@ -1955,6 +1989,8 @@ var init_emit = __esm({
1955
1989
  datetime: "string",
1956
1990
  json: "unknown"
1957
1991
  };
1992
+ EmitError = class extends Error {
1993
+ };
1958
1994
  }
1959
1995
  });
1960
1996
 
@@ -1962,6 +1998,7 @@ var init_emit = __esm({
1962
1998
  var introspect_exports = {};
1963
1999
  __export(introspect_exports, {
1964
2000
  CommentSettingsError: () => CommentSettingsError,
2001
+ EmitError: () => EmitError,
1965
2002
  emitContracts: () => emitContracts,
1966
2003
  introspectOpenApi: () => introspectOpenApi,
1967
2004
  introspectPostgres: () => introspectPostgres,
@@ -3105,7 +3142,7 @@ var init_native = __esm({
3105
3142
  init_source();
3106
3143
  SCRIPT_EXTS3 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
3107
3144
  JSX_EXTS3 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
3108
- LAYOUT_NAME = /(?:Page|Screen|ScreenContainer)$/;
3145
+ LAYOUT_NAME = /(?:Page|Screen|ScreenContainer)$|^NativeResourceView$/;
3109
3146
  NON_SCREEN_ROUTE = /(?:^|\/)(?:_layout|\+html|\+native-intent|\+middleware)\.[jt]sx?$|\+api\.[jt]sx?$/;
3110
3147
  PART_HEADER = /(?:Section|List|Card|Dialog|Table|Group|Column|Row|Cell|Accordion|Sheet|Drawer|Modal|Popover|Menu|Panel|Form)Header$/;
3111
3148
  HIDES_HEADER = /\bheaderShown\s*(?::|=\s*\{)\s*false\b/;
@@ -3757,7 +3794,7 @@ function checkExports(ctx, pkg, json) {
3757
3794
  };
3758
3795
  walk2(json.exports);
3759
3796
  for (const t of targets) {
3760
- if (!t.startsWith("./") || t.includes("*") || /^\.\/(dist|build)\//.test(t)) continue;
3797
+ if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
3761
3798
  if (!existsSync(path23.join(pkg.dir, t))) {
3762
3799
  ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
3763
3800
  }
@@ -3788,10 +3825,13 @@ function checkRegistered(ctx, pkg) {
3788
3825
  } catch {
3789
3826
  return;
3790
3827
  }
3828
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3829
+ const forms = /* @__PURE__ */ new Set([pkg.rel]);
3830
+ if (top) forms.add(path23.relative(top, realpathSync(pkg.dir)).split(path23.sep).join("/"));
3791
3831
  const covered = (doc.features ?? []).some(
3792
3832
  (f) => (f.links?.code ?? []).some((c) => {
3793
3833
  const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
3794
- return norm === pkg.rel || norm.startsWith(`${pkg.rel}/`) || pkg.rel.startsWith(`${norm}/`);
3834
+ return [...forms].some((rel) => norm === rel || norm.startsWith(`${rel}/`) || rel.startsWith(`${norm}/`));
3795
3835
  })
3796
3836
  );
3797
3837
  if (!covered) {
@@ -3815,8 +3855,12 @@ function mergeBaseOf(root, base) {
3815
3855
  return sha ? { sha } : { reason: `HEAD has no merge base with ${base} (fetch with depth 0)` };
3816
3856
  }
3817
3857
  function checkChanges(ctx, pkg, json, base, mergeBase) {
3818
- const diff = git(ctx.root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", pkg.rel]) ?? "";
3819
- const untracked = (git(ctx.root, ["ls-files", "--others", "--exclude-standard", "--", pkg.rel]) ?? "").split("\n").filter(Boolean);
3858
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3859
+ if (!top) return;
3860
+ const appRelative = (fromTop) => path23.relative(realpathSync(ctx.root), path23.join(top, fromTop)).split(path23.sep).join("/");
3861
+ const inRepo = path23.relative(top, realpathSync(pkg.dir)).split(path23.sep).join("/");
3862
+ const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell, i) => i === 0 ? cell : appRelative(cell)).join(" ")).join("\n");
3863
+ const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
3820
3864
  const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
3821
3865
  (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
3822
3866
  );
@@ -3837,7 +3881,6 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
3837
3881
  const now = typeof json.version === "string" ? parseVersion(json.version) : null;
3838
3882
  const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
3839
3883
  const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
3840
- const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3841
3884
  const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path23.join(top, f)) : [];
3842
3885
  const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
3843
3886
  const named = naming.length > 0;
@@ -3855,6 +3898,9 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
3855
3898
  const registry = (git(ctx.root, ["diff", "--relative", "--name-only", mergeBase, "--", "features.ts", "src/features.ts"]) ?? "").trim();
3856
3899
  if (!registry) ctx.report({ rule: "package-unversioned-change", level: "warn", file: `${pkg.rel}/package.json`, message: `${pkg.name}'s blocks or exports changed but features.ts didn't; update the features they belong to` });
3857
3900
  }
3901
+ if (bumped && !named && before !== null) {
3902
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: `${pkg.rel}/package.json`, message: `${pkg.name}'s version went up without a changeset; add one with a "Features:" line so the change is recorded` });
3903
+ }
3858
3904
  if (!bumped && !named) {
3859
3905
  ctx.report({
3860
3906
  rule: "package-unversioned-change",
@@ -3900,7 +3946,7 @@ var init_packages = __esm({
3900
3946
  SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
3901
3947
  BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
3902
3948
  IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
3903
- TYPE_ONLY = /\b(?:import|export)\s+type\b[^;"'`]*?\bfrom\s*["'][^"']+["']/g;
3949
+ TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
3904
3950
  }
3905
3951
  });
3906
3952
  function sqlStatements(text) {
@@ -4763,7 +4809,7 @@ function checkPageLayouts(ctx) {
4763
4809
  const rendersLayout = (code) => {
4764
4810
  const names = new Set(layouts);
4765
4811
  for (const n of namedImportsFrom(code, GENESIS_PACKAGE2)) if (PACKAGE_SCREEN.test(n)) names.add(n);
4766
- return rendersRe(names)?.test(code) ?? false;
4812
+ return rendersRe(names)?.test(code.replace(EMBEDDED_RESOURCE_VIEW, "")) ?? false;
4767
4813
  };
4768
4814
  const cache2 = /* @__PURE__ */ new Map();
4769
4815
  const provides = (r) => {
@@ -4783,7 +4829,7 @@ function checkPageLayouts(ctx) {
4783
4829
  });
4784
4830
  }
4785
4831
  }
4786
- var SUB_NAV_DOCS, CONTAINER, SWITCHER, SHELL, GENESIS_PACKAGE2, PAGE_LAYOUT, PACKAGE_SCREEN, isNative, rendersRe, routeVia;
4832
+ var SUB_NAV_DOCS, CONTAINER, SWITCHER, SHELL, GENESIS_PACKAGE2, PAGE_LAYOUT, EMBEDDED_RESOURCE_VIEW, PACKAGE_SCREEN, isNative, rendersRe, routeVia;
4787
4833
  var init_structure = __esm({
4788
4834
  "src/doctor/structure.ts"() {
4789
4835
  init_scan();
@@ -4795,8 +4841,9 @@ var init_structure = __esm({
4795
4841
  SWITCHER = /<(TabsList|SubNavTabs)(?=[\s>/])/g;
4796
4842
  SHELL = /<AppShell(?=[\s>/])/;
4797
4843
  GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
4798
- PAGE_LAYOUT = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)$/;
4799
- PACKAGE_SCREEN = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)$/;
4844
+ PAGE_LAYOUT = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)|ResourceView)$/;
4845
+ EMBEDDED_RESOURCE_VIEW = /<ResourceView\b[^>]*?\blayout\s*=\s*(?:(["'`]) {8}\1|\{\s*(["'`]) {8}\2\s*\})[^>]*>/g;
4846
+ PACKAGE_SCREEN = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)|ResourceView)$/;
4800
4847
  isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
4801
4848
  rendersRe = (names) => {
4802
4849
  const list = [...names];