import { readFile, realpath, lstat } from 'node:fs/promises'; import { dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path'; import { createHash } from 'node:crypto'; import MarkdownIt from 'markdown-it'; import { parse } from 'yaml'; const digest = bytes => createHash('sha256').update(bytes).digest('hex'); const within = (root, path) => { const rel = relative(root,path); return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); }; async function containedFile(root, path) { const actualRoot = await realpath(root); const actualPath = await realpath(path); if (!within(actualRoot, actualPath)) throw new Error('File escapes outside permitted source directory'); return actualPath; } function descendants(tokens) { return tokens.flatMap(token => [token, ...descendants(token.children ?? [])]); } /** Local-preview export only. This function never edits the private library. */ export async function loadWorks(libraryRoot, selection) { if (!Array.isArray(selection)) throw new Error('Explicit work selection required'); const routes = new Set(); const works = []; for (const item of selection) { if (!/^\d{4}-\d{2}-\d{2}--[a-z0-9]+(?:-[a-z0-9]+)*$/.test(item.id)) throw new Error('Invalid work id'); if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(item.slug)) throw new Error('Invalid slug'); if (!['en','zh-Hans'].includes(item.language)) throw new Error('Unsupported expression language'); if (item.unpublished === true) { if (item.date != null) throw new Error('Unpublished work must not have a publication date'); } else if (!/^\d{4}-\d{2}-\d{2}$/.test(item.date)) throw new Error('Source publication date required'); if (!['performance','systems','debugging'].includes(item.topic)) throw new Error('Unknown topic'); const route = `${item.language}/${item.slug}`; if (routes.has(route)) throw new Error('Duplicate preview route'); routes.add(route); const techRoot = resolve(libraryRoot,'content/tech'); const workRoot = await containedFile(techRoot,resolve(techRoot,item.id)); const metaPath = await containedFile(workRoot,resolve(workRoot,'work.yaml')); const meta = parse(await readFile(metaPath,'utf8'),{maxAliasCount:20}); if (meta.id !== item.id || meta.domain !== 'tech') throw new Error('Work identity/domain mismatch'); const expression = meta.expressions?.[`essay-${item.language}`]; const prefix = `expressions/essay/${item.language}/`; if (!expression || expression.medium !== 'essay' || expression.language !== item.language || typeof expression.current_file !== 'string' || !expression.current_file.startsWith(prefix)) { throw new Error('Unsupported or missing manuscript expression'); } if (item.unpublished === true && (expression.lifecycle !== 'draft' || expression.release?.decision !== 'private')) { throw new Error('Unpublished preview requires a private draft'); } const manuscriptPath = await containedFile(resolve(workRoot,prefix),resolve(workRoot,expression.current_file)); if (extname(manuscriptPath) !== '.md') throw new Error('Expected Markdown manuscript'); const markdown = await readFile(manuscriptPath,'utf8'); // Explicit per-edition exceptions remove link markup only. Reference files // are never read or exported, and other private links still fail closed. const textOnlyReferences = new Set(); if (!Array.isArray(item.textOnlyReferences ?? [])) throw new Error('Invalid text-only references'); for (const path of item.textOnlyReferences ?? []) { if (typeof path !== 'string' || !path.startsWith('notes/references/') || extname(path) !== '.md') { throw new Error('Text-only reference must be a reference draft'); } const target = resolve(workRoot,path); await containedFile(resolve(workRoot,'notes/references'),target); textOnlyReferences.add(target); } const md = new MarkdownIt({html:false,linkify:false,typographer:false}); const tokens = md.parse(markdown,{}); // The imported manuscript's leading title is rendered once by the article shell. if (tokens[0]?.type === 'heading_open' && tokens[0].tag === 'h1') tokens.splice(0,3); const headingLevels = tokens.filter(t=>t.type==='heading_open').map(t=>Number(t.tag.slice(1))); const headingShift = headingLevels.length ? Math.max(0, Math.min(...headingLevels)-2) : 0; for (const token of tokens) { if (token.type === 'heading_open' || token.type === 'heading_close') token.tag=`h${Number(token.tag.slice(1))-headingShift}`; } const assets = new Map(); const assetRoot=resolve(workRoot,'assets'); if((await lstat(assetRoot)).isSymbolicLink()) throw new Error('Asset root must not be a symlink'); // Both cover and body assets pass through the same private-file boundary. async function exportAsset(path) { const file=await containedFile(assetRoot,path); const ext=extname(file).toLowerCase(); if (!['.png','.jpg','.jpeg','.gif','.webp'].includes(ext)) throw new Error('Unsupported image format'); const bytes=await readFile(file); if (bytes.length > 50*1024*1024) throw new Error('Oversize preview asset'); const url=`/assets/${digest(bytes)}${ext}`; assets.set(url,{url,bytes}); return url; } if (typeof item.cover?.path !== 'string' || !item.cover.path.startsWith('assets/') || typeof item.cover.alt !== 'string') throw new Error('Explicit local cover and alt text required'); const cover={url:await exportAsset(resolve(workRoot,item.cover.path)),alt:item.cover.alt}; let excerpt=''; for(let index=0;index ['text','code_inline'].includes(token.type)?token.content: ['softbreak','hardbreak'].includes(token.type)?' ':'').join('').replace(/\s+/g,' ').trim(); if(!text) continue; const chars=[...text]; excerpt=chars.length>180?chars.slice(0,179).join('')+'…':text; break; } let figureNumber=0; let omittedReferenceLinks=0; const linkVisibility=[]; for (const token of descendants(tokens)) { if (token.type==='link_open') { const href=token.attrGet('href'); const publicLink=/^(https?:\/\/|mailto:|#)/i.test(href ?? ''); if (!publicLink) { if (!href || isAbsolute(href) || /^[a-z][a-z0-9+.-]*:/i.test(href) || !textOnlyReferences.has(resolve(dirname(manuscriptPath),decodeURIComponent(href)))) { throw new Error('Private or unsupported relative link in manuscript'); } token.hidden=true; omittedReferenceLinks++; } linkVisibility.push(!publicLink); } if (token.type==='link_close') token.hidden=linkVisibility.pop() ?? false; if (token.type!=='image') continue; token.meta={...token.meta,fullSize:linkVisibility.every(hidden=>hidden)}; const src=token.attrGet('src'); if (!src || isAbsolute(src) || /^[a-z][a-z0-9+.-]*:/i.test(src) || src.startsWith('//')) throw new Error('External or absolute image prohibited'); const decoded=decodeURIComponent(src); const url=await exportAsset(resolve(dirname(manuscriptPath),decoded)); token.attrSet('src',url); token.attrSet('loading','lazy'); token.attrSet('decoding','async'); figureNumber++; // Source alt text stays authoritative. Empty original descriptions get a // neutral figure index, not a fabricated technical description. if (!token.content) { token.content=`Figure ${figureNumber}`; token.children=[{type:'text',content:token.content,children:null}]; } } const evidence=meta.tech_evidence?.classification; if (!['engineering-record','design-analysis','hypothesis'].includes(evidence)) throw new Error('Missing evidence classification'); const renderImage=md.renderer.rules.image; md.renderer.rules.image=(tokens,index,options,env,renderer)=>{ const token=tokens[index]; const html=renderImage(tokens,index,options,env,renderer); // Preserve authored linked-image destinations and never nest anchors. if (!token.meta?.fullSize) return html; const hint=item.language==='zh-Hans'?'查看原图':'View full-size image'; const label=md.utils.escapeHtml(`${hint}: ${token.content}`); return `${html}${hint}`; }; works.push({id:item.id,slug:item.slug,title:expression.title ?? meta.title,language:item.language, date:item.unpublished===true?null:item.date,evidence,topic:item.topic,featured:item.featured===true,omittedReferenceLinks,cover,excerpt, seriesOrder:item.seriesOrder ?? null,body:md.renderer.render(tokens,md.options,{}) .replaceAll('
',`
`),
      assets:[...assets.values()]});
  }
  return works;
}