369 lines
15 KiB
JavaScript
369 lines
15 KiB
JavaScript
// Imports the official TypeScript documentation from a checkout of
|
|
// https://github.com/microsoft/TypeScript-website into site/docs/ (Chinese site, marked
|
|
// untranslated) and site/en/docs/ (English site), converting
|
|
// typescriptlang.org-specific Markdown (twoslash code samples, site links) to VitePress Markdown.
|
|
// The English text is copied as is (no translation).
|
|
//
|
|
// Usage: node scripts/import-typescript-website.mjs <path-to-TypeScript-website-repo>
|
|
//
|
|
// - Pages are laid out by their typescriptlang.org permalink (not their file name), so the
|
|
// root-relative links used inside the docs keep working:
|
|
// /docs/handbook/2/everyday-types.html -> site/docs/handbook/2/everyday-types.md
|
|
// - The sidebar comes from packages/documentation/scripts/generateDocsNavigationPerLanguage.js
|
|
// and is written to scripts/nav.json, which .vitepress/config.mts reads.
|
|
// - The upstream navigation file is parsed as text; no upstream code is executed.
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { execFileSync } from 'node:child_process';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const SITE_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
const OUT_DIR = path.join(SITE_DIR, 'site', 'docs');
|
|
const EN_OUT_DIR = path.join(SITE_DIR, 'site', 'en', 'docs');
|
|
const ASSET_DIR = path.join(SITE_DIR, 'site', 'public', 'docs', '_assets');
|
|
const NAV_FILE =path.join(SITE_DIR, 'scripts', 'nav.json');
|
|
const UPSTREAM_FILE = path.join(SITE_DIR, 'scripts', 'upstream.json');
|
|
const UPSTREAM_SITE = 'https://www.typescriptlang.org';
|
|
const UPSTREAM_REPO = 'https://github.com/microsoft/TypeScript-website';
|
|
|
|
const repoRoot = process.argv[2] && path.resolve(process.argv[2]);
|
|
const DOCS_PKG = repoRoot && path.join(repoRoot, 'packages', 'documentation');
|
|
if (!repoRoot || !fs.existsSync(path.join(DOCS_PKG, 'copy', 'en')))
|
|
throw new Error('Usage: node scripts/import-typescript-website.mjs <path-to-TypeScript-website-repo>');
|
|
const EN = path.join(DOCS_PKG, 'copy', 'en');
|
|
const NAV_SOURCE = path.join(DOCS_PKG, 'scripts', 'generateDocsNavigationPerLanguage.js');
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Front matter
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function parseFrontMatter(text) {
|
|
const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
|
|
if (!m) return { data: {}, body: text };
|
|
const data = {};
|
|
for (const line of m[1].split(/\r?\n/)) {
|
|
const kv = line.match(/^([A-Za-z_]+):\s*(.*)$/);
|
|
if (!kv) continue;
|
|
let value = kv[2].trim();
|
|
if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1).replace(/\\"/g, '"').replace(/''/g, '\'');
|
|
data[kv[1]] = value;
|
|
}
|
|
return { data, body: text.slice(m[0].length) };
|
|
}
|
|
|
|
function yamlString(value) {
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Page collection
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function walk(dir) {
|
|
return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
|
|
const full = path.join(dir, entry.name);
|
|
return entry.isDirectory() ? walk(full) : [full];
|
|
});
|
|
}
|
|
|
|
const pages = new Map(); // source relative path ("handbook-v2/Basics.md") -> page info
|
|
const routes = new Set(); // "/docs/handbook/2/basic-types"
|
|
|
|
for (const file of walk(EN)) {
|
|
if (!file.endsWith('.md')) continue;
|
|
const rel = path.relative(EN, file).split(path.sep).join('/');
|
|
const { data, body } = parseFrontMatter(fs.readFileSync(file, 'utf8'));
|
|
if (!data.permalink) continue; // e.g. modules-reference/diagrams/*.md (diagram sources)
|
|
const route = data.permalink.replace(/\.html$/, '').replace(/\/$/, '/index');
|
|
pages.set(rel, { file, rel, data, body, route });
|
|
routes.add(route);
|
|
}
|
|
|
|
function routeLink(route) {
|
|
return route.replace(/\/index$/, '/');
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Markdown conversion
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const TWOSLASH_DIRECTIVE = /^\s*\/\/\s*@(?!ts-)(\w+)(?::\s*(.*?))?\s*$/;
|
|
const TWOSLASH_QUERY = /^\s*\/\/\s*\^[?|]/;
|
|
|
|
function convertCodeBlock(info, lines) {
|
|
const words = info.trim().split(/\s+/).filter(Boolean);
|
|
const twoslash = words.includes('twoslash');
|
|
const kept = words.filter(w => w !== 'twoslash' && w !== 'tsconfig');
|
|
if (kept[0] && !kept[0].startsWith('{')) kept[0] = kept[0].toLowerCase();
|
|
if (!twoslash) {
|
|
// A few untagged samples still carry compiler directives ("// @errors: 2322").
|
|
if (/^[jt]sx?$/.test(kept[0] ?? ''))
|
|
lines = lines.filter(line => !(TWOSLASH_DIRECTIVE.test(line) && !/@filename/i.test(line)));
|
|
return { info: kept.join(' '), lines };
|
|
}
|
|
|
|
// Code above "// ---cut---" only sets up the sample; typescriptlang.org hides it.
|
|
const cut = lines.findIndex(l => /^\s*\/\/\s*---cut---\s*$/.test(l));
|
|
let body = cut >= 0 ? lines.slice(cut + 1) : lines;
|
|
body = body.flatMap(line => {
|
|
if (TWOSLASH_QUERY.test(line)) return [];
|
|
const d = line.match(TWOSLASH_DIRECTIVE);
|
|
if (!d) return [line];
|
|
// Keep file names of multi-file samples as a plain comment, drop compiler flags.
|
|
return /^filename$/i.test(d[1]) && d[2] ? [line.replace(/@\w+:\s*/, '')] : [];
|
|
});
|
|
while (body.length && !body[0].trim()) body.shift();
|
|
return { info: kept.join(' '), lines: body };
|
|
}
|
|
|
|
function convertCode(body) {
|
|
const lines = body.split(/\r?\n/);
|
|
const out = [];
|
|
for (let i = 0; i < lines.length; i++) {
|
|
const open = lines[i].match(/^(\s*)(`{3,}|~{3,})(.*)$/);
|
|
if (!open) { out.push(lines[i]); continue; }
|
|
const [, indent, fence, info] = open;
|
|
const closeRe = new RegExp(`^\\s*${fence[0]}{${fence.length},}\\s*$`);
|
|
let j = i + 1;
|
|
while (j < lines.length && !closeRe.test(lines[j])) j++;
|
|
const block = convertCodeBlock(info, lines.slice(i + 1, j));
|
|
out.push(`${indent}${fence}${block.info}`, ...block.lines, lines[j] ?? `${indent}${fence}`);
|
|
i = j;
|
|
}
|
|
return out.join('\n');
|
|
}
|
|
|
|
// Applies fn to the parts of the Markdown that are outside fenced code blocks.
|
|
function mapOutsideCode(md, fn) {
|
|
const parts = md.split(/(^\s*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\s*\2[`~]*\s*$)/m);
|
|
return parts.map((part, i) => {
|
|
if (i % 3 === 2) return ''; // captured fence marker
|
|
return i % 3 === 1 ? part : fn(part);
|
|
}).join('');
|
|
}
|
|
|
|
const copiedAssets = new Map(); // source file -> route-relative public path
|
|
|
|
function rewriteUrl(url, page) {
|
|
if (/^(https?:|mailto:|#)/.test(url)) return url;
|
|
if (url.startsWith('/')) {
|
|
const [, pathname, hash = ''] = url.match(/^([^#?]*)([#?].*)?$/);
|
|
const route = pathname.replace(/\.html$/, '').replace(/\/$/, '/index');
|
|
if (routes.has(route)) return routeLink(route) + hash;
|
|
return UPSTREAM_SITE + url;
|
|
}
|
|
const [, rel, hash = ''] = url.match(/^([^#?]*)([#?].*)?$/);
|
|
// Relative to the page URL, as typescriptlang.org serves it ("./enums.html#x").
|
|
if (rel.endsWith('.html')) {
|
|
const resolved = new URL(url, UPSTREAM_SITE + page.data.permalink);
|
|
return rewriteUrl(resolved.pathname + resolved.search + resolved.hash, page);
|
|
}
|
|
// Otherwise relative to the source file: another doc or an asset next to it.
|
|
const source = path.resolve(path.dirname(page.file), decodeURIComponent(rel));
|
|
const target = [...pages.values()].find(p => p.file === source);
|
|
if (target) return routeLink(target.route) + hash;
|
|
if (fs.existsSync(source) && !source.endsWith('.md')) {
|
|
const assetRel = path.relative(EN, source).split(path.sep).join('/');
|
|
copiedAssets.set(source, assetRel);
|
|
return `/docs/_assets/${assetRel.split('/').map(encodeURIComponent).join('/')}`;
|
|
}
|
|
console.warn(`[import] unresolved link in ${page.rel}: ${url}`);
|
|
return url;
|
|
}
|
|
|
|
function convertLinks(text, page) {
|
|
return text
|
|
.replace(/(\]\()(<[^>]+>|[^)\s]+)/g, (_, pre, url) => {
|
|
const bare = url.replace(/^<|>$/g, '');
|
|
return pre + rewriteUrl(bare, page);
|
|
})
|
|
.replace(/^(\[[^\]]+\]:\s*)((?:https?:|\/|\.)\S*)/gm, (_, pre, url) => pre + rewriteUrl(url, page))
|
|
.replace(/\b(href|src)=(["'])([^"']+)\2/g, (_, attr, q, url) => `${attr}=${q}${rewriteUrl(url, page)}${q}`);
|
|
}
|
|
|
|
function convertPage(page) {
|
|
const { data } = page;
|
|
let body = convertCode(page.body.replace(/\r\n/g, '\n'));
|
|
// Upstream's generated MSBuild table closes cells as </tr></td>; browsers tolerate it, Vue does not.
|
|
body = mapOutsideCode(body, text => convertLinks(text, page).replaceAll('</tr></td>', '</td></tr>'));
|
|
|
|
const header = [];
|
|
if (!/^#\s/m.test(body)) header.push(`# ${data.title}`, '');
|
|
if (data.deprecated_by) {
|
|
header.push('::: warning 已过时 / Deprecated',
|
|
`This page has been deprecated. See [the replacement page](${rewriteUrl(data.deprecated_by, page)}).`,
|
|
':::', '');
|
|
}
|
|
if (data.preamble) header.push(data.preamble, '');
|
|
|
|
const fm = ['---', `title: ${yamlString(data.title)}`];
|
|
if (data.oneline) fm.push(`description: ${yamlString(data.oneline)}`);
|
|
fm.push(`upstream: ${yamlString(`${UPSTREAM_REPO}/blob/v2/packages/documentation/copy/en/${page.rel}`)}`);
|
|
fm.push('---', '');
|
|
const head = header.length ? header.join('\n') + '\n' : '';
|
|
return `${fm.join('\n')}\n${head}${body.replace(/^\n+/, '')}`;
|
|
}
|
|
|
|
// Same idea as Angular-iSharkFly-Com's scripts/sync-zh.mjs: Simplified Chinese is served from
|
|
// the site root, English from /en/. There are no translations yet, so the Chinese pages carry
|
|
// `untranslated: true` (see .vitepress/theme/components/UntranslatedNotice.vue).
|
|
function markUntranslated(text) {
|
|
return text.replace(/^---\n/, '---\nuntranslated: true\n');
|
|
}
|
|
|
|
function moveLinksUnderEnglish(text) {
|
|
return text.replace(/(\]\(|\bhref=["'])\/docs\/(?!_assets\/)/g, '$1/en/docs/');
|
|
}
|
|
|
|
function write(file, text) {
|
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
fs.writeFileSync(file, text);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Navigation parsing (a tolerant reader for the object literal in the nav script)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function stripComments(src) {
|
|
let out = '';
|
|
for (let i = 0; i < src.length; i++) {
|
|
const c = src[i];
|
|
if (c === '\'' || c === '"' || c === '`') {
|
|
let j = i + 1;
|
|
while (j < src.length && src[j] !== c) j += src[j] === '\\' ? 2 : 1;
|
|
out += src.slice(i, j + 1);
|
|
i = j;
|
|
} else if (c === '/' && src[i + 1] === '/') {
|
|
while (i < src.length && src[i] !== '\n') i++;
|
|
out += '\n';
|
|
} else if (c === '/' && src[i + 1] === '*') {
|
|
i = src.indexOf('*/', i + 2) + 1;
|
|
} else {
|
|
out += c;
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function ws(p) { while (/\s|,/.test(p.s[p.i] ?? '')) p.i++; }
|
|
|
|
function parseString(p) {
|
|
const q = p.s[p.i++];
|
|
let out = '';
|
|
while (p.s[p.i] !== q) {
|
|
if (p.s[p.i] === '\\') { out += p.s[p.i + 1]; p.i += 2; } else out += p.s[p.i++];
|
|
}
|
|
p.i++;
|
|
return out;
|
|
}
|
|
|
|
function parseValue(p) {
|
|
ws(p);
|
|
const c = p.s[p.i];
|
|
if (c === '[') {
|
|
p.i++;
|
|
const arr = [];
|
|
for (ws(p); p.s[p.i] !== ']'; ws(p)) arr.push(parseValue(p));
|
|
p.i++;
|
|
return arr;
|
|
}
|
|
if (c === '{') {
|
|
p.i++;
|
|
const obj = {};
|
|
for (ws(p); p.s[p.i] !== '}'; ws(p)) {
|
|
const key = /['"]/.test(p.s[p.i]) ? parseString(p) : p.s.slice(p.i).match(/^[\w$]+/)[0];
|
|
if (!/['"]/.test(p.s[p.i - 1])) p.i += key.length;
|
|
ws(p);
|
|
p.i++; // ':'
|
|
obj[key] = parseValue(p);
|
|
}
|
|
p.i++;
|
|
return obj;
|
|
}
|
|
if (c === '\'' || c === '"' || c === '`') return parseString(p);
|
|
const m = p.s.slice(p.i).match(/^(true|false|-?\d+(\.\d+)?)\b/);
|
|
if (m) { p.i += m[0].length; return JSON.parse(m[0]); }
|
|
throw new Error(`Unexpected token in ${NAV_SOURCE}: ${p.s.slice(p.i, p.i + 40)}`);
|
|
}
|
|
|
|
function readUpstreamNav() {
|
|
const src = stripComments(fs.readFileSync(NAV_SOURCE, 'utf8'));
|
|
const start = src.indexOf('const handbookPages');
|
|
if (start < 0) throw new Error(`handbookPages not found in ${NAV_SOURCE}`);
|
|
return parseValue({ s: src, i: src.indexOf('[', start) });
|
|
}
|
|
|
|
// "What's New" is filled from the release notes, newest first (upstream fillReleaseInfo()).
|
|
function releaseNoteItems() {
|
|
const version = f => f.match(/(\d+)\.(\d+)/)?.slice(1).map(Number) ?? [0, 0];
|
|
return fs.readdirSync(path.join(EN, 'release-notes'))
|
|
.filter(f => f.endsWith('.md') && !/overview/i.test(f))
|
|
.sort((a, b) => { const [x, y] = [version(a), version(b)]; return y[0] - x[0] || y[1] - x[1]; })
|
|
.map(f => ({ file: `release-notes/${f}` }));
|
|
}
|
|
|
|
const EXPANDED_SECTIONS = new Set(['Get Started', 'Handbook']);
|
|
const navPages = new Set();
|
|
|
|
function toSidebarItem(item, depth) {
|
|
if (item.items) {
|
|
const items = item.items.map(i => toSidebarItem(i, depth + 1)).filter(Boolean);
|
|
return { text: item.title, collapsed: !(depth === 0 && EXPANDED_SECTIONS.has(item.title)), items };
|
|
}
|
|
if (item.href)
|
|
return { text: item.title, link: UPSTREAM_SITE + item.href };
|
|
const page = pages.get(item.file);
|
|
if (!page) {
|
|
console.warn(`[import] navigation entry without page: ${item.file}`);
|
|
return null;
|
|
}
|
|
navPages.add(page.rel);
|
|
return { text: item.title ?? page.data.short ?? page.data.title, link: routeLink(page.route) };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Main
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function main() {
|
|
const nav = readUpstreamNav();
|
|
const whatsNew = nav.find(s => s.title === 'What\'s New');
|
|
if (whatsNew) whatsNew.items = releaseNoteItems();
|
|
const sidebar = nav.map(section => toSidebarItem(section, 0));
|
|
|
|
fs.rmSync(OUT_DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
|
|
fs.rmSync(ASSET_DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
|
|
fs.rmSync(EN_OUT_DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
|
|
for (const page of pages.values()) {
|
|
const rel = page.route.replace(/^\/docs\//, '').split('/');
|
|
const text = convertPage(page);
|
|
// Chinese site (root): the English text, flagged so the page shows the "untranslated" notice.
|
|
write(path.join(OUT_DIR, ...rel) + '.md', markUntranslated(text));
|
|
// English site (/en/): same text, with page links kept under /en/.
|
|
write(path.join(EN_OUT_DIR, ...rel) + '.md', moveLinksUnderEnglish(text));
|
|
}
|
|
for (const [source, rel] of copiedAssets) {
|
|
const out = path.join(ASSET_DIR, ...rel.split('/'));
|
|
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
fs.copyFileSync(source, out);
|
|
}
|
|
|
|
fs.writeFileSync(NAV_FILE, JSON.stringify(sidebar, null, 2) + '\n');
|
|
|
|
let commit = null;
|
|
try {
|
|
commit = execFileSync('git', ['-C', repoRoot, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
|
|
} catch { /* not a git checkout */ }
|
|
fs.writeFileSync(UPSTREAM_FILE, JSON.stringify({
|
|
repository: UPSTREAM_REPO,
|
|
commit,
|
|
source: 'packages/documentation/copy/en',
|
|
}, null, 2) + '\n');
|
|
|
|
const offNav = [...pages.keys()].filter(rel => !navPages.has(rel));
|
|
console.log(`[import] ${pages.size} pages, ${copiedAssets.size} assets, ${navPages.size} in sidebar`);
|
|
if (offNav.length) console.log(`[import] pages not in the sidebar (reachable by links): ${offNav.length}`);
|
|
}
|
|
|
|
main();
|