Files
novalon-website/scripts/ops/sync-cms-schema.ts
T
zhangxiang cee21e178a docs(ops): 生产侧核对与发布 runbook;新增最小迁移脚本 sync-cms-schema(默认 dry-run)
只读核对生产库(scp 副本、本地 node:sqlite 查询,未写生产):
- navigation 行仍是旧 7 项 IA(panels products,solutions,services)⇒ 新代码每请求退回代码真源;
- 三处 caseStudies 的 ContentModel.fields 缺 authorized/basis ⇒ 后台填不出门槛字段;
- 生产案例条目 **0 条** ⇒ 只发代码不会隐藏任何内容(dataProofs 按裁定不套硬闸)。

新增 scripts/ops/sync-cms-schema.ts:只补 3 个模型的两个子字段 + 把 navigation 行改写为
由 NAVIGATION_V2/MEGA_DROPDOWN_DATA 派生的形状;默认 dry-run,--apply 才写,
写前用真实 resolveNavigation 验收派生形状、写后强制复查(不通过即退出码 1)。
在生产库副本上预演通过:source=cms / issues=0;逐行 diff 证明只动了
3 个 ContentModel 行 + 1 个 ContentItem 行(navigation),其余 37 行内容与 13 个模型逐字节不变。

docs/development/deploy-runbook.md 写清:备份与停容器顺序、**服务器 Node v20 无 node:sqlite
⇒ 迁移必须本机跑再回传**、不推荐用 db:seed(会重写所有覆盖行且需 SEED_ALLOW_EXTERNAL_DB=1)、
发布后四项只读核对、三条回滚路径,以及"合 main = 无人值守线上发布,须决策人显式发起"。
2026-10-20 07:40:37 +08:00

157 lines
7.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* CMS 两处数据漂移的最小迁移(默认 dry-run,`--apply` 才写)。
*
* 为什么不用 `npm run db:seed` 在生产上修:
* seed 会把**所有**被 seed 覆盖的 ContentItem.data 重写回仓库版本,
* 生产里若有人在后台改过文案,会被一起覆盖。这里只动两处已确认的漂移:
*
* 1) `ContentModel.fields`:三处 caseStudies(product / service / standalone-product)
* 缺 `authorized` 与 `basis` 两个子字段 ⇒ 后台填不出来,case-publish-gate 会把所有案例闸住。
* 口径以 `src/lib/cms/content-types.ts` 为唯一真源(从那里取字段定义,不手抄)。
* 2) `ContentItem(modelCode='navigation').data`:仍是旧 7 项 IA(products/solutions/services 面板),
* 新代码会每请求「退回代码真源」并打日志。改写成由 `NAVIGATION_V2` + `MEGA_DROPDOWN_DATA`
* 派生出来的形状 —— 只动这一行,其它内容行不碰。
*
* 自证:写完后用 **真实的 `resolveNavigation`** 跑一遍,要求 `source === 'cms'` 且 `issues` 为空;
* 不成立就退出码 1(绝不"写完就算成功")。dry-run 只打印计划。
*
* 用法:
* npx tsx scripts/ops/sync-cms-schema.ts --db /path/to/prod.db # dry-run
* npx tsx scripts/ops/sync-cms-schema.ts --db /path/to/prod.db --apply
*/
import { DatabaseSync } from 'node:sqlite';
import { CONTENT_TYPE_CONFIGS } from '../../src/lib/cms/content-types';
import { NAVIGATION_V2, MEGA_DROPDOWN_DATA } from '../../src/lib/constants/navigation';
import { resolveNavigation } from '../../src/lib/navigation-resolution';
const args = process.argv.slice(2);
const dbArg = args[args.indexOf('--db') + 1];
const apply = args.includes('--apply');
if (!dbArg || dbArg.startsWith('--')) {
console.error('用法:sync-cms-schema.ts --db <sqlite 文件> [--apply]');
process.exit(2);
}
const db = new DatabaseSync(dbArg);
const say = (...a: unknown[]) => console.log(...a);
// ── 1) ContentModel.fields:补齐 caseStudies 的两个门槛子字段 ──────────────
type SubField = { name: string; [k: string]: unknown };
const modelRows = db
.prepare(`select code, fields from ContentModel where code in ('product','service','standalone-product')`)
.all() as { code: string; fields: string }[];
const modelUpdates: { code: string; next: string; before: string[] }[] = [];
for (const row of modelRows) {
let fields: { name: string; fields?: SubField[] }[];
try {
fields = JSON.parse(row.fields);
} catch {
console.error(`✗ ${row.code}: fields 不是合法 JSON,拒绝改写`);
process.exit(2);
}
const source = (CONTENT_TYPE_CONFIGS as unknown as Record<string, { model: { fields: { name: string; fields?: SubField[] }[] } }>)[row.code]
?.model.fields.find((f) => f.name === 'caseStudies');
if (!source?.fields) {
console.error(`✗ ${row.code}: 代码真源里找不到 caseStudies 定义,拒绝改写`);
process.exit(2);
}
const want = source.fields.filter((f) => f.name === 'authorized' || f.name === 'basis');
if (want.length !== 2) {
console.error(`✗ ${row.code}: 真源里 caseStudies 缺 authorized/basis,先修 content-types.ts`);
process.exit(2);
}
const beforeNames: string[] = [];
let changed = false;
for (const f of fields) {
if (f.name !== 'caseStudies' || !Array.isArray(f.fields)) continue;
for (const w of want) {
const had = f.fields.some((x) => x.name === w.name);
if (!had) {
f.fields.push(w);
beforeNames.push(`+${w.name}`);
changed = true;
}
}
}
if (changed) modelUpdates.push({ code: row.code, next: JSON.stringify(fields), before: beforeNames });
}
// ── 2) navigation 行:改写成由代码真源派生的形状 ────────────────────────────
const navRow = db
.prepare(`select id, data from ContentItem where modelCode = 'navigation' limit 1`)
.get() as { id: string; data: string } | undefined;
const derivedNav = {
slug: 'default',
title: '导航菜单',
mainNav: NAVIGATION_V2,
megaDropdown: MEGA_DROPDOWN_DATA,
};
let navUpdate: { id: string; next: string; beforeLabels: string[]; afterLabels: string[] } | null = null;
if (navRow) {
let before: { mainNav?: { label?: string }[] } = {};
try {
before = JSON.parse(navRow.data);
} catch {
before = {};
}
const beforeLabels = (before.mainNav ?? []).map((x) => String(x.label ?? '?'));
const afterLabels = NAVIGATION_V2.map((x) => x.label);
if (JSON.stringify(before) !== JSON.stringify(derivedNav)) {
navUpdate = { id: navRow.id, next: JSON.stringify(derivedNav), beforeLabels, afterLabels };
}
} else {
say('· navigation 行不存在 ⇒ 跳过(不新建;代码真源已能供数)');
}
// ── 3) 自证:用真实解析器验收派生出来的形状 ────────────────────────────────
const verdict = resolveNavigation(derivedNav);
say(`· 解析器验收:source=${verdict.source} issues=${verdict.issues.length}`);
if (verdict.source !== 'cms' || verdict.issues.length > 0) {
for (const i of verdict.issues) say(` ✗ ${i}`);
console.error('✗ 派生形状未通过 resolveNavigation ⇒ 本次中止(不写库)');
process.exit(1);
}
// ── 4) 计划 / 执行 ─────────────────────────────────────────────────────────
say(`· ContentModel 需补字段:${modelUpdates.length} 个(${modelUpdates.map((m) => m.code + ':' + m.before.join(',')).join(' | ') || '无'})`);
if (navUpdate) {
say(`· navigation 行需改写:${navUpdate.beforeLabels.join('/')} → ${navUpdate.afterLabels.join('/')}`);
} else {
say('· navigation 行已是目标形状');
}
if (!apply) {
say('\n[dry-run] 未写入。加 --apply 执行。');
process.exit(0);
}
const updateModel = db.prepare(`update ContentModel set fields = ?, updatedAt = CURRENT_TIMESTAMP where code = ?`);
const updateNav = db.prepare(`update ContentItem set data = ?, updatedAt = CURRENT_TIMESTAMP where id = ?`);
db.exec('begin');
try {
for (const m of modelUpdates) updateModel.run(m.next, m.code);
if (navUpdate) updateNav.run(navUpdate.next, navUpdate.id);
db.exec('commit');
} catch (e) {
db.exec('rollback');
console.error('✗ 写入失败已回滚:', (e as Error).message);
process.exit(1);
}
// 写后复查(不是"写完就算")
const checkNav = db.prepare(`select data from ContentItem where modelCode = 'navigation' limit 1`).get() as { data: string } | undefined;
const checkVerdict = checkNav ? resolveNavigation(JSON.parse(checkNav.data)) : verdict;
const checkModels = db
.prepare(`select code, fields from ContentModel where code in ('product','service','standalone-product')`)
.all() as { code: string; fields: string }[];
const bad = checkModels.filter((r) => !/authorized/.test(r.fields) || !/basis/.test(r.fields));
say(`\n[applied] models=${checkModels.length} 缺字段=${bad.length} · navigation source=${checkVerdict.source} issues=${checkVerdict.issues.length}`);
if (bad.length > 0 || checkVerdict.source !== 'cms' || checkVerdict.issues.length > 0) {
console.error('✗ 写后复查未通过');
process.exit(1);
}
say('✓ 写后复查通过');