Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | 44x 1x 9x 28x 121x 121x 28x 29x 29x 29x 29x 29x 10x 10x 30x 10x 30x 20x 20x 19x 9x 28x 10x 10x 11x 11x 11x 11x 11x 1x 2x 11x 11x 10x 10x 10x 10x 29x 29x 1x 1x 28x 28x 28x 28x 28x 29x 29x 28x 11x 11x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 11x 11x 28x 28x 28x 5x 23x 28x 25x 20x 20x 25x 25x 25x 8x 8x 11x 11x 1x 1x 1x 1x 7x 1x 2x 1x 1x 1x 1x 1x 1x | /**
* Write Zeroheight content into `content/`. For every `port` page in the
* manifest:
*
* 1. convert each visible tab (or the untabbed page) to site markdown
* 2. apply the local fixes in `fixes.js`
* 3. upload its images to Cloudinary
* 4. merge front matter: existing keys stay, `title` follows Zeroheight and
* the landing file's `description` follows the page introduction
*
* A landing file keeps its leading hero banner (the POC's page header image or
* gradient): Zeroheight has no equivalent, and the page template only reads its
* background.
*
* Tabbed pages: the landing file (`badge.md`) gets the first tab's content,
* like each tab file (`badge--usage.md`) gets its own. Paths come from the
* manifest (`zh:audit --write` or a manual pin), never from guessing.
*
* Synced files are generated. A file whose hash no longer matches the
* manifest's `localHash` was edited by hand: it's skipped (unless `force`)
* and the edit should become a rule in `fixes.js`.
*
* All I/O is injected so the orchestration is testable.
*/
import matter from 'gray-matter';
import { applyContentFixes } from './fixes.js';
import { convertContent } from './convert.js';
import { hashContent } from './hash.js';
import { collectImageRefs, resolveImages, rewriteImageRefs, sourceKey } from './images.js';
import { createLinkResolver } from './links.js';
import { splitMcpMarkdown } from './pages.js';
/**
* @typedef {{
* file: string,
* landing: boolean,
* body: string,
* prevHash: string | null,
* target: { localHash: string | null, zhHash?: string | null },
* zhHash: string | null,
* }} Unit
* One file to write. `target` is the manifest entry or tab whose hashes it updates.
*
* @typedef {{
* written: string[],
* unchanged: string[],
* skipped: { file: string, reason: string }[],
* warnings: { file: string, message: string }[],
* fixes: { file: string, reason: string }[],
* images: {
* downloaded: number,
* changed: number,
* pending: number,
* failed: { ref: string, error: string }[],
* kept: { ref: string, error: string }[],
* },
* missing: { uid: string, name: string }[],
* }} PullReport
*/
/** `content/components/badge--usage.md` -> `components/badge--usage.md`. @param {string} file */
const contentPath = (file) => file.replace(/^content\//, '');
// The `::hero-banner` leaf, as `remark-directive` stringifies it.
const HERO_RE = /^\s*(<div data-directive-type="hero-banner"[^\n]*\n<\/div>\n)/;
/**
* The leading hero banner of an existing file, or ''.
* @param {string | null} existing
*/
export function leadingHero(existing) {
return existing ? (HERO_RE.exec(matter(existing).content)?.[1] ?? '') : '';
}
/**
* Front matter in the style of the existing files (`key: "value"`).
* @param {Record<string, unknown>} data
*/
function stringifyFrontMatter(data) {
const lines = Object.entries(data)
.filter(([, v]) => v !== undefined)
.map(([k, v]) => `${k}: ${JSON.stringify(v)}`);
return `---\n${lines.join('\n')}\n---\n`;
}
/**
* Keep the existing keys; new files get the same keys as the POC port.
* @param {string | null} existing
* @param {{ file: string, landing: boolean, title: string, description: string | undefined }} page
*/
export function mergeFrontMatter(existing, { file, landing, title, description }) {
const slug = file.split('/').pop()?.replace(/\.mdx?$/, '') ?? '';
/** @type {Record<string, unknown>} */
const data = existing
? { ...matter(existing).data }
: {
title,
slug,
category: contentPath(file).split('/')[0],
...(slug.includes('--') ? { parent: slug.split('--')[0] } : {}),
};
data.title = title;
if (landing && description) data.description = description;
return data;
}
/**
* The files one page writes, with their unconverted bodies.
* @param {import('./audit.js').ZhPage} zh
* @param {import('./manifest.js').ManifestEntry} entry
* @param {(file: string, reason: string) => void} skip
* @returns {Unit[]}
*/
function pageUnits(zh, entry, skip) {
Iif (!zh.tabs.length) {
if (!entry.localFile) return [];
return [
{ file: entry.localFile, landing: true, body: zh.content, prevHash: entry.localHash, target: entry, zhHash: null },
];
}
/** @type {Unit[]} */
const units = [];
const visible = zh.tabs.filter((t) => !t.hidden);
for (const tab of visible) {
const target = entry.tabs.find((t) => t.uid === tab.uid);
Iif (!target?.localFile) {
skip(`${zh.name} > ${tab.name}`, 'no local file in the manifest (pin one)');
continue;
}
units.push({
file: target.localFile,
landing: false,
body: tab.content,
prevHash: target.localHash,
target,
zhHash: hashContent(tab.content),
});
}
// The landing file shows the first tab.
if (entry.localFile && visible[0] && !units.some((u) => u.file === entry.localFile)) {
units.push({
file: entry.localFile,
landing: true,
body: visible[0].content,
prevHash: entry.localHash,
target: entry,
zhHash: null,
});
}
const landing = units.find((u) => u.file === entry.localFile);
Eif (landing) landing.landing = true;
return units;
}
/**
* @param {{
* zhPages: import('./audit.js').ZhPage[],
* manifest: import('./manifest.js').Manifest,
* imageIndex: Record<string, string>,
* readFile: (file: string) => string | null,
* writeFile: (file: string, text: string) => void,
* images: Omit<Parameters<typeof resolveImages>[0], 'refs' | 'index' | 'refresh'>,
* fixes?: Parameters<typeof applyContentFixes>[2],
* dryRun?: boolean,
* force?: boolean,
* partial?: boolean,
* refreshImages?: boolean,
* today: string,
* }} opts
* @returns {Promise<PullReport>} the manifest and `imageIndex` are updated in place (not on a dry run)
*/
export async function runPull({
zhPages,
manifest,
imageIndex,
readFile,
writeFile,
images,
fixes,
dryRun = false,
force = false,
partial = false,
refreshImages = false,
today,
}) {
/** @type {PullReport} */
const report = {
written: [],
unchanged: [],
skipped: [],
warnings: [],
fixes: [],
images: { downloaded: 0, changed: 0, pending: 0, failed: [], kept: [] },
missing: [],
};
const skip = (/** @type {string} */ file, /** @type {string} */ reason) => report.skipped.push({ file, reason });
const resolveLink = createLinkResolver(manifest);
const byUid = new Map(zhPages.map((p) => [p.uid, p]));
if (!partial) {
for (const [uid, entry] of Object.entries(manifest.pages)) {
Eif (entry.decision === 'port' && !byUid.has(uid)) report.missing.push({ uid, name: entry.name });
}
}
/** @type {{ unit: Unit, entry: import('./manifest.js').ManifestEntry, zh: import('./audit.js').ZhPage, md: string, existing: string | null }[]} */
const pending = [];
for (const zh of zhPages) {
const entry = manifest.pages[zh.uid];
Iif (!entry || entry.decision !== 'port') continue;
Iif (zh.hidden) {
skip(zh.name, 'hidden in Zeroheight');
continue;
}
for (const unit of pageUnits(zh, entry, skip)) {
const existing = readFile(unit.file);
if (existing !== null && hashContent(existing) !== unit.prevHash && !force) {
skip(unit.file, 'edited by hand since the last sync (move the change into fixes.js, or rerun with --force)');
continue;
}
const warn = (/** @type {string} */ message) => report.warnings.push({ file: unit.file, message });
const converted = convertContent(unit.body, { pageTitle: zh.name, resolveLink, warn });
const { md: fixed, applied } = applyContentFixes(converted, contentPath(unit.file), fixes);
for (const reason of applied) report.fixes.push({ file: unit.file, reason });
const hero = unit.landing ? leadingHero(existing) : '';
const md = hero ? `${hero}\n${fixed}` : fixed;
pending.push({ unit, entry, zh, md, existing });
}
}
const refs = [...new Set(pending.flatMap((p) => collectImageRefs(p.md)))];
/** @type {Map<string, string>} */
let files = new Map();
if (dryRun) {
for (const ref of refs) {
const known = imageIndex[sourceKey(ref)];
Iif (known && images.hasFile(known)) files.set(ref, known);
Eif (refreshImages || !files.has(ref)) report.images.pending++;
}
} else {
const resolved = await resolveImages({ ...images, refs, index: imageIndex, refresh: refreshImages });
files = resolved.files;
report.images.downloaded = resolved.downloaded;
report.images.changed = resolved.changed;
report.images.failed = resolved.failed;
report.images.kept = resolved.kept;
}
/** @type {Set<import('./manifest.js').ManifestEntry>} */
const touched = new Set();
for (const { unit, entry, zh, md, existing } of pending) {
const data = mergeFrontMatter(existing, {
file: unit.file,
landing: unit.landing,
title: zh.name,
description: splitMcpMarkdown(zh.raw).meta.introduction,
});
const text = `${stringifyFrontMatter(data)}\n${rewriteImageRefs(md, files)}`;
if (existing === text) {
report.unchanged.push(unit.file);
} else {
report.written.push(unit.file);
}
if (dryRun) continue;
if (existing !== text) {
writeFile(unit.file, text);
touched.add(entry);
}
unit.target.localHash = hashContent(text);
if (unit.zhHash) unit.target.zhHash = unit.zhHash;
// A tab that shares the landing file also owns the page-level hashes.
if (unit.target === entry || unit.file === entry.localFile) {
entry.localHash = hashContent(text);
entry.zhHash = hashContent(zh.raw);
}
}
for (const entry of touched) entry.lastSynced = today;
return report;
}
/**
* @param {PullReport} report
* @param {{ dryRun: boolean }} opts
*/
export function renderPullReport(report, { dryRun }) {
const out = [`# Zeroheight pull${dryRun ? ' (dry run)' : ''}`, ''];
const verb = dryRun ? 'to write' : 'written';
out.push(
`- ${report.written.length} files ${verb}, ${report.unchanged.length} unchanged, ${report.skipped.length} skipped`,
dryRun
? `- ${report.images.pending} images to upload`
: `- ${report.images.downloaded} images uploaded (${report.images.changed} changed), ${report.images.failed.length} failed`,
`- ${report.warnings.length} warnings, ${report.fixes.length} local fixes applied`,
);
/** @param {string} title @param {string[]} items */
const section = (title, items) => {
if (items.length) out.push('', `## ${title}`, '', ...items.map((i) => `- ${i}`));
};
section('Skipped', report.skipped.map((s) => `\`${s.file}\`: ${s.reason}`));
section('Missing in Zeroheight', report.missing.map((m) => `${m.name} (\`${m.uid}\`)`));
section('Image failures', report.images.failed.map((f) => `\`${f.ref.split('?')[0]}\`: ${f.error}`));
section(
'Images kept (download failed, the current file stays)',
report.images.kept.map((f) => `\`${f.ref.split('?')[0]}\`: ${f.error}`),
);
section('Warnings', report.warnings.map((w) => `\`${w.file}\`: ${w.message}`));
section('Local fixes', report.fixes.map((f) => `\`${f.file}\`: ${f.reason}`));
section(dryRun ? 'Would write' : 'Written', report.written.map((f) => `\`${f}\``));
return `${out.join('\n')}\n`;
}
|