NGU-Web/server/src/admin-schema-sync.js
Zaldimmar 54bf649b8d Tidy the admin editor's text: previews, blank options, no em-dashes
Your wording pass on adminSchema.ts and fields.tsx: "Default: ..."
blank options, "eg." examples, "URL ID" for slugs, and relabelled
front page sections, stat sources and hero fields.

On top of it:

- Content block row titles end with an ellipsis when the paragraph
  is cut. preview() in src/lib/text.ts does it for anything that
  shortens text: it collapses whitespace, cuts on a word and adds
  "..." only when it actually shortened.
- No em-dashes in the editor, front end or server: placeholders
  ("Internal note: ..."), the Organizations blurb, the URL ID help,
  empty table cells (now "-"), the Award dropdown ("Torch Award
  (NGU)" in OPTION_QUERIES), a boot error message, and every comment
  in the admin files. Also cleared from the files added this branch
  (QR page, directory route, embeds, hero, migration 024), and the
  QR page's team labels read "Board (NGU)".
- A few comments where removing the dash had run two sentences
  together get a comma, colon or parentheses back.
- docs/updating-data-in-code.md matches the new labels and gains a
  "Writing text in the editor" section with these conventions;
  CLAUDE.md lists them under Rules and gotchas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 19:38:24 -05:00

144 lines
5 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
DESCRIPTOR / SCHEMA RECONCILIATION
The CRUD engine trusts admin-schema.js about which fields are
required. The database is the one that actually enforces it. When
those two disagree the gap shows up as a 500 on somebody's save,
which is how organizations.country was found.
Run this once at boot. For every table a descriptor touches it
compares the declared columns against PRAGMA table_info and:
- marks a descriptor column required when the table says
NOT NULL with no DEFAULT, so validation catches it as a named
field instead of SQLite catching it as a 500;
- reports a descriptor column the table doesn't have;
- reports a NOT NULL, no-DEFAULT column that no descriptor
column and no engine-supplied column covers: nothing can
ever set it, so every insert through the admin will fail.
The first is a silent repair. The other two are deployment bugs,
so with { strict: true } they stop the service starting rather
than waiting to surface one row at a time.
═══════════════════════════════════════════════════════════════ */
function tableMeta(db, table) {
const rows = db.prepare(`PRAGMA table_info(${table})`).all();
if (!rows.length) return null;
const meta = new Map();
for (const row of rows) {
meta.set(row.name, {
// A NOT NULL column with no default and no engine to fill it
// has to arrive in the payload or the insert dies.
mustSupply: row.notnull === 1 && row.dflt_value === null && row.pk === 0,
notNullable: row.notnull === 1 && row.pk === 0,
});
}
return meta;
}
/* Every table the descriptor writes to, with the columns it
declares and the ones the engine fills in on its own. */
function collectGroups(entity) {
const groups = [
{
table: entity.table,
columns: entity.columns ?? [],
engineSupplied: [entity.idColumn],
},
];
for (const ext of entity.extensions ?? []) {
groups.push({
table: ext.table,
columns: ext.columns ?? [],
// An extension is keyed either by the parent's own id or by an
// owner block, the same one children use. Both sets of columns
// are filled in by the engine, never by the form.
engineSupplied: [
ext.idColumn,
ext.owner?.column,
ext.owner?.kindColumn,
...(ext.touch ? ["updated_at"] : []),
].filter(Boolean),
});
}
const walk = (child) => {
groups.push({
table: child.table,
columns: child.columns ?? [],
engineSupplied: [
child.owner.column,
child.owner.kindColumn,
"sort_order",
...Object.keys(child.owner.inherit ?? {}),
].filter(Boolean),
});
for (const nested of child.children ?? []) walk(nested);
};
for (const child of entity.children ?? []) walk(child);
return groups;
}
export function syncDescriptorsWithSchema(db, entities, { strict = true } = {}) {
const list = Array.isArray(entities) ? entities.map((e) => [e.name ?? e.table, e]) : Object.entries(entities);
const inferred = [];
const problems = [];
for (const [name, entity] of list) {
for (const group of collectGroups(entity)) {
const meta = tableMeta(db, group.table);
if (!meta) {
problems.push(`${name}: table "${group.table}" does not exist.`);
continue;
}
const declared = new Set(group.columns.map((column) => column.name));
for (const column of group.columns) {
const info = meta.get(column.name);
if (!info) {
problems.push(
`${name}: ${group.table}.${column.name} is in the descriptor but not in the table.`,
);
continue;
}
if (info.mustSupply && !column.required) {
column.required = true;
inferred.push(`${name}: ${group.table}.${column.name}`);
}
if (info.notNullable) column.notNullable = true;
}
for (const [columnName, info] of meta) {
if (!info.mustSupply) continue;
if (declared.has(columnName)) continue;
if (group.engineSupplied.includes(columnName)) continue;
problems.push(
`${name}: ${group.table}.${columnName} is NOT NULL with no default, ` +
`but no descriptor column covers it, so every insert will fail.`,
);
}
}
}
if (inferred.length) {
console.warn(
`[admin-schema] marked required from the schema (add required: true to the descriptor):\n ${inferred.join("\n ")}`,
);
}
if (problems.length) {
const report = `[admin-schema] descriptor does not match the database:\n ${problems.join("\n ")}`;
if (strict) throw new Error(report);
console.error(report);
}
return { inferred, problems };
}