1090 lines
36 KiB
JavaScript
1090 lines
36 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* scripts/preview.mjs — 零依赖侧栏预览生成器。
|
||
*
|
||
* 做法:
|
||
* 1. 用 vm 加载真实的 panel/lib/client.js(复用 panel/test/client.test.js 的
|
||
* window.__ModuleLoader__.load + 最小 React/document 替身思路),并捕获
|
||
* bundle 注入到 <style> 里的 CSS 字符串。
|
||
* 2. 用一套会真正重渲染的 hooks 替身渲染真实组件树 SanshengPanel,
|
||
* 等 loadCatalog 等异步 effect 落定后再序列化成 HTML。
|
||
* 3. 套一个「会话右侧栏」页面外壳,用 headless Chrome 量高、再截图。
|
||
*
|
||
* 只依赖 Node 内置模块 + 本机 Chrome 命令行;不引入任何 npm 依赖。
|
||
*
|
||
* 用法(Git Bash):
|
||
* DSH_DESKTOP_NODE_EXECUTABLE="/c/Users/qyh15/AppData/Local/Programs/DeepSeek Harness/DeepSeek Harness.exe" \
|
||
* "/c/Users/qyh15/AppData/Local/Programs/DeepSeek Harness/resources/runtime/bin/node" \
|
||
* scripts/preview.mjs --width=440 --view=court --theme=light \
|
||
* --source=.scratch/preview-baseline/client.snapshot.js \
|
||
* --out=.scratch/preview-baseline --name=court-440-light \
|
||
* --html=.scratch/preview-baseline/court-440-light.html
|
||
*/
|
||
|
||
import vm from 'node:vm'
|
||
import os from 'node:os'
|
||
import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, copyFileSync, statSync } from 'node:fs'
|
||
import { dirname, join, resolve } from 'node:path'
|
||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||
import { spawnSync } from 'node:child_process'
|
||
|
||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||
const ROOT = resolve(HERE, '..')
|
||
|
||
const DEFAULTS = {
|
||
out: 'dsh-image-gen',
|
||
width: 440,
|
||
view: 'court',
|
||
theme: 'light',
|
||
name: 'panel-preview-sidebar',
|
||
source: 'panel/lib/client.js',
|
||
html: null,
|
||
scale: 2,
|
||
chrome: null,
|
||
htmlOnly: false,
|
||
}
|
||
|
||
/** 页面左侧留出的「会话区」宽度,让预览看起来是右侧栏而不是整页。 */
|
||
const CHAT_EDGE = 14
|
||
|
||
const VIEWS = ['court', 'tasks']
|
||
const THEMES = ['light', 'dark']
|
||
|
||
// #region CLI
|
||
|
||
function fail(message) {
|
||
const error = new Error(message)
|
||
error.previewFailure = true
|
||
throw error
|
||
}
|
||
|
||
function printHelp() {
|
||
process.stdout.write(`用法: node scripts/preview.mjs [选项]
|
||
|
||
--out=<目录> PNG 输出目录(默认 ${DEFAULTS.out})
|
||
--width=<像素> 侧栏容器宽度 320-900(默认 ${DEFAULTS.width})
|
||
--view=<court|tasks> 渲染页签(默认 ${DEFAULTS.view})
|
||
--theme=<light|dark> 主题(默认 ${DEFAULTS.theme})
|
||
--name=<文件名> 输出文件名,不含扩展名(默认 ${DEFAULTS.name})
|
||
--source=<路径> 要渲染的 client.js(默认 ${DEFAULTS.source},A/B 对比用)
|
||
--html=<路径> 可选:额外保留中间 HTML
|
||
--html-only 只生成 HTML,不调用 Chrome(无需安装浏览器)
|
||
--scale=<1|2|3> 设备像素比(默认 ${DEFAULTS.scale})
|
||
--chrome=<路径> 显式指定 Chrome/Edge 可执行文件
|
||
`)
|
||
}
|
||
|
||
function parseArgs(argv) {
|
||
const options = { ...DEFAULTS }
|
||
for (let i = 0; i < argv.length; i += 1) {
|
||
const raw = argv[i]
|
||
if (raw === '--help' || raw === '-h') {
|
||
printHelp()
|
||
process.exit(0)
|
||
}
|
||
if (raw === '--html-only') {
|
||
options.htmlOnly = true
|
||
continue
|
||
}
|
||
if (!raw.startsWith('--')) fail(`无法识别的参数:${raw}(选项一律写成 --key=value)`)
|
||
const body = raw.slice(2)
|
||
const eq = body.indexOf('=')
|
||
let key
|
||
let value
|
||
if (eq >= 0) {
|
||
key = body.slice(0, eq)
|
||
value = body.slice(eq + 1)
|
||
} else {
|
||
key = body
|
||
value = argv[i + 1]
|
||
if (value === undefined || value.startsWith('--')) fail(`参数 --${key} 缺少值`)
|
||
i += 1
|
||
}
|
||
if (!Object.prototype.hasOwnProperty.call(DEFAULTS, key)) fail(`未知选项:--${key}`)
|
||
options[key] = value
|
||
}
|
||
|
||
options.width = toInt(options.width, '--width', 320, 900)
|
||
options.scale = toInt(options.scale, '--scale', 1, 3)
|
||
if (!VIEWS.includes(options.view)) fail(`--view 只能是 ${VIEWS.join(' / ')},收到:${options.view}`)
|
||
if (!THEMES.includes(options.theme)) fail(`--theme 只能是 ${THEMES.join(' / ')},收到:${options.theme}`)
|
||
if (!options.name || /[\\/:*?"<>|]/.test(options.name)) fail(`--name 不能为空或包含路径字符:${options.name}`)
|
||
|
||
options.out = resolve(ROOT, options.out)
|
||
options.source = resolve(ROOT, options.source)
|
||
if (options.html) options.html = resolve(ROOT, options.html)
|
||
return options
|
||
}
|
||
|
||
function toInt(value, flag, min, max) {
|
||
const number = Number(value)
|
||
if (!Number.isInteger(number) || number < min || number > max) {
|
||
fail(`${flag} 需要 ${min}-${max} 的整数,收到:${value}`)
|
||
}
|
||
return number
|
||
}
|
||
|
||
// #endregion
|
||
|
||
// #region Chrome
|
||
|
||
function findChrome(explicit) {
|
||
const candidates = [
|
||
explicit,
|
||
process.env.DSH_PREVIEW_CHROME,
|
||
process.env.CHROME_PATH,
|
||
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
||
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
|
||
'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
|
||
'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
|
||
].filter(Boolean)
|
||
|
||
for (const candidate of candidates) {
|
||
try {
|
||
if (statSync(candidate).isFile()) return candidate
|
||
} catch {
|
||
// 继续找下一个
|
||
}
|
||
}
|
||
|
||
for (const exe of ['chrome.exe', 'msedge.exe']) {
|
||
const probe = spawnSync('where.exe', [exe], { encoding: 'utf8', windowsHide: true })
|
||
if (probe.status === 0 && probe.stdout) {
|
||
const first = probe.stdout.split(/\r?\n/).map((line) => line.trim()).find(Boolean)
|
||
if (first && existsSync(first)) return first
|
||
}
|
||
}
|
||
|
||
fail(
|
||
'找不到 Chrome/Edge。请安装 Chrome,或用 --chrome=<路径> 指定;' +
|
||
'也可以通过环境变量 DSH_PREVIEW_CHROME / CHROME_PATH 指定。',
|
||
)
|
||
}
|
||
|
||
function chromeRun(chrome, args, label) {
|
||
const result = spawnSync(chrome, args, {
|
||
encoding: 'utf8',
|
||
windowsHide: true,
|
||
maxBuffer: 64 * 1024 * 1024,
|
||
timeout: 120000,
|
||
})
|
||
if (result.error) fail(`${label} 调用 Chrome 失败:${result.error.message}`)
|
||
if (result.status !== 0) {
|
||
const stderr = String(result.stderr || '').trim().split(/\r?\n/).slice(-8).join('\n')
|
||
fail(`${label} 失败(Chrome 退出码 ${result.status})${stderr ? `:\n${stderr}` : ''}`)
|
||
}
|
||
return result
|
||
}
|
||
|
||
// #endregion
|
||
|
||
// #region 加载 bundle + React/hooks 替身
|
||
|
||
function createHooks() {
|
||
const slots = []
|
||
let cursor = 0
|
||
let dirty = false
|
||
let effectQueue = []
|
||
|
||
const depsEqual = (a, b) => {
|
||
if (a === undefined) return false // 无 deps:每次都重新执行(与 React 一致)
|
||
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false
|
||
return a.every((value, index) => Object.is(value, b[index]))
|
||
}
|
||
|
||
const slotAt = (index) => {
|
||
if (!slots[index]) slots[index] = {}
|
||
return slots[index]
|
||
}
|
||
|
||
const markDirty = () => { dirty = true }
|
||
|
||
class Component {
|
||
constructor(props) {
|
||
this.props = props
|
||
this.state = {}
|
||
this.context = undefined
|
||
}
|
||
setState(partial) {
|
||
const next = typeof partial === 'function' ? partial(this.state) : partial
|
||
this.state = { ...this.state, ...next }
|
||
markDirty()
|
||
}
|
||
forceUpdate() { markDirty() }
|
||
}
|
||
|
||
const React = {
|
||
createElement: (type, props, ...children) => ({ type, props: props ?? {}, children }),
|
||
createContext: (value) => ({ Provider: 'provider', value, _currentValue: value }),
|
||
Component,
|
||
Fragment: 'fragment',
|
||
useContext: () => undefined,
|
||
useState(initial) {
|
||
const index = cursor
|
||
cursor += 1
|
||
const slot = slotAt(index)
|
||
if (!('value' in slot)) slot.value = typeof initial === 'function' ? initial() : initial
|
||
const setState = (next) => {
|
||
const value = typeof next === 'function' ? next(slot.value) : next
|
||
if (Object.is(value, slot.value)) return
|
||
slot.value = value
|
||
markDirty()
|
||
}
|
||
return [slot.value, setState]
|
||
},
|
||
useRef(initial) {
|
||
const index = cursor
|
||
cursor += 1
|
||
const slot = slotAt(index)
|
||
if (!('ref' in slot)) slot.ref = { current: initial }
|
||
return slot.ref
|
||
},
|
||
useEffect(effect, deps) {
|
||
const index = cursor
|
||
cursor += 1
|
||
const slot = slotAt(index)
|
||
if (!depsEqual(slot.deps, deps)) {
|
||
slot.deps = deps ? deps.slice() : undefined
|
||
effectQueue.push(effect)
|
||
}
|
||
},
|
||
useMemo(factory, deps) {
|
||
const index = cursor
|
||
cursor += 1
|
||
const slot = slotAt(index)
|
||
if (!depsEqual(slot.deps, deps)) {
|
||
slot.deps = deps ? deps.slice() : undefined
|
||
slot.value = factory()
|
||
}
|
||
return slot.value
|
||
},
|
||
useCallback(fn, deps) {
|
||
const index = cursor
|
||
cursor += 1
|
||
const slot = slotAt(index)
|
||
if (!depsEqual(slot.deps, deps)) {
|
||
slot.deps = deps ? deps.slice() : undefined
|
||
slot.value = fn
|
||
}
|
||
return slot.value
|
||
},
|
||
}
|
||
|
||
return {
|
||
React,
|
||
beginRender() {
|
||
cursor = 0
|
||
effectQueue = []
|
||
},
|
||
runEffects() {
|
||
const queue = effectQueue
|
||
effectQueue = []
|
||
for (const effect of queue) effect()
|
||
},
|
||
consumeDirty() {
|
||
const value = dirty
|
||
dirty = false
|
||
return value
|
||
},
|
||
}
|
||
}
|
||
|
||
function loadBundle(sourcePath, hooks) {
|
||
if (!existsSync(sourcePath)) fail(`找不到 bundle:${sourcePath}`)
|
||
const source = readFileSync(sourcePath, 'utf8').replace(/^\uFEFF/, '')
|
||
if (!source.includes('__ModuleLoader__')) {
|
||
fail(`${sourcePath} 看起来不是 DSH 客户端 bundle(未找到 __ModuleLoader__)。`)
|
||
}
|
||
|
||
const { React } = hooks
|
||
const styleTexts = []
|
||
let loaded
|
||
|
||
const document = {
|
||
getElementById: () => null,
|
||
querySelector: () => null,
|
||
createElement: (tagName) => ({ tagName, dataset: {}, textContent: '', setAttribute() {} }),
|
||
head: {
|
||
appendChild(node) {
|
||
if (node && typeof node.textContent === 'string' && node.textContent.trim() !== '') {
|
||
styleTexts.push(node.textContent)
|
||
}
|
||
},
|
||
},
|
||
body: {},
|
||
addEventListener() {},
|
||
removeEventListener() {},
|
||
}
|
||
|
||
const window = {
|
||
__ModuleLoader__: {
|
||
load(options) {
|
||
loaded = options
|
||
const module = { exports: {} }
|
||
const require = (name) => {
|
||
if (name === 'react') return React
|
||
if (name === 'react-dom') return { createPortal: (node) => node }
|
||
if (name === 'react/jsx-runtime') return { jsx: () => null, jsxs: () => null, Fragment: 'fragment' }
|
||
throw new Error(`预览加载器不认识的模块:${name}`)
|
||
}
|
||
const exported = options.factory(require)
|
||
if (exported !== undefined) module.exports = exported
|
||
loaded.exports = module.exports
|
||
},
|
||
},
|
||
}
|
||
|
||
const sandbox = {
|
||
window,
|
||
document,
|
||
console,
|
||
URL,
|
||
URLSearchParams,
|
||
Map,
|
||
Set,
|
||
WeakMap,
|
||
Promise,
|
||
setTimeout,
|
||
clearTimeout,
|
||
setImmediate,
|
||
queueMicrotask,
|
||
}
|
||
|
||
try {
|
||
vm.runInNewContext(source, sandbox, { filename: sourcePath, timeout: 30000 })
|
||
} catch (error) {
|
||
fail(`加载 bundle 失败(${sourcePath}):\n${error && error.stack ? error.stack : error}`)
|
||
}
|
||
if (!loaded || !loaded.exports) fail(`bundle 没有调用 __ModuleLoader__.load:${sourcePath}`)
|
||
|
||
const css = styleTexts.sort((a, b) => b.length - a.length)[0] || ''
|
||
if (!css.trim()) fail(`bundle 没有注入 CSS(${sourcePath})。`)
|
||
if (!css.includes('.sl-root') || !css.includes('.sl-sidebar')) {
|
||
fail(`捕获到的 CSS 不像朝堂面板样式(缺少 .sl-root / .sl-sidebar),长度 ${css.length}。`)
|
||
}
|
||
|
||
return { exports: loaded.exports, css, sourcePath }
|
||
}
|
||
|
||
// #endregion
|
||
|
||
// #region 渲染树 → HTML
|
||
|
||
const VOID_TAGS = new Set([
|
||
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
|
||
'link', 'meta', 'param', 'source', 'track', 'wbr',
|
||
])
|
||
|
||
const ATTR_ALIASES = {
|
||
className: 'class',
|
||
htmlFor: 'for',
|
||
tabIndex: 'tabindex',
|
||
colSpan: 'colspan',
|
||
rowSpan: 'rowspan',
|
||
maxLength: 'maxlength',
|
||
minLength: 'minlength',
|
||
readOnly: 'readonly',
|
||
autoFocus: 'autofocus',
|
||
autoComplete: 'autocomplete',
|
||
viewBox: 'viewBox',
|
||
preserveAspectRatio: 'preserveAspectRatio',
|
||
strokeWidth: 'stroke-width',
|
||
strokeLinecap: 'stroke-linecap',
|
||
strokeLinejoin: 'stroke-linejoin',
|
||
strokeDasharray: 'stroke-dasharray',
|
||
fillRule: 'fill-rule',
|
||
clipRule: 'clip-rule',
|
||
xmlnsXlink: 'xmlns:xlink',
|
||
}
|
||
|
||
const BOOLEAN_ATTRS = new Set([
|
||
'disabled', 'checked', 'selected', 'hidden', 'readonly', 'required',
|
||
'multiple', 'open', 'autofocus', 'novalidate', 'formnovalidate',
|
||
])
|
||
|
||
function escapeText(value) {
|
||
return String(value)
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
}
|
||
|
||
function escapeAttr(value) {
|
||
return String(value)
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
.replace(/"/g, '"')
|
||
}
|
||
|
||
function kebabStyleName(name) {
|
||
if (name.startsWith('--')) return name
|
||
if (name === 'msTransform') return '-ms-transform'
|
||
const prefixed = name.replace(/^(Webkit|Moz|O)(?=[A-Z])/, (match) => `-${match.toLowerCase()}`)
|
||
return prefixed.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)
|
||
}
|
||
|
||
const UNITLESS_STYLES = new Set([
|
||
'line-height', 'opacity', 'font-weight', 'z-index', 'flex', 'flex-grow',
|
||
'flex-shrink', 'order', 'zoom', 'aspect-ratio',
|
||
])
|
||
|
||
function styleToString(style) {
|
||
if (!style || typeof style !== 'object') return ''
|
||
const parts = []
|
||
for (const [name, raw] of Object.entries(style)) {
|
||
if (raw === null || raw === undefined || raw === false) continue
|
||
const key = kebabStyleName(name)
|
||
let value = raw
|
||
if (typeof value === 'number' && value !== 0 && !UNITLESS_STYLES.has(key)) value = `${value}px`
|
||
parts.push(`${key}:${value}`)
|
||
}
|
||
return parts.join(';')
|
||
}
|
||
|
||
function buildAttributes(type, props, options) {
|
||
const attrs = []
|
||
for (const [rawName, rawValue] of Object.entries(props || {})) {
|
||
if (rawName === 'children' || rawName === 'key' || rawName === 'ref') continue
|
||
if (rawName === '__self' || rawName === '__source') continue
|
||
if (rawName === 'dangerouslySetInnerHTML') continue
|
||
if (rawName === 'value' && type === 'select') continue
|
||
if (rawName === 'value' && type === 'option') continue
|
||
if (rawName === 'selected' && type === 'option') continue
|
||
if (typeof rawValue === 'function' || typeof rawValue === 'symbol') continue
|
||
if (rawValue === undefined || rawValue === null) continue
|
||
|
||
let name = rawName
|
||
if (rawName === 'className') {
|
||
name = 'class'
|
||
} else if (ATTR_ALIASES[rawName]) {
|
||
name = ATTR_ALIASES[rawName]
|
||
} else if (!rawName.includes('-') && /[A-Z]/.test(rawName)) {
|
||
name = rawName.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)
|
||
}
|
||
|
||
if (name === 'class') {
|
||
const value = Array.isArray(rawValue) ? rawValue.filter(Boolean).join(' ') : String(rawValue)
|
||
if (value) attrs.push(`class="${escapeAttr(value)}"`)
|
||
continue
|
||
}
|
||
if (name === 'style') {
|
||
const value = styleToString(rawValue)
|
||
if (value) attrs.push(`style="${escapeAttr(value)}"`)
|
||
continue
|
||
}
|
||
if (name.startsWith('aria-')) {
|
||
const value = typeof rawValue === 'boolean' ? String(rawValue) : String(rawValue)
|
||
attrs.push(`${name}="${escapeAttr(value)}"`)
|
||
continue
|
||
}
|
||
if (name === 'value' && type === 'option') continue
|
||
if (BOOLEAN_ATTRS.has(name)) {
|
||
if (rawValue === true || rawValue === '') attrs.push(`${name}=""`)
|
||
continue
|
||
}
|
||
if (rawValue === false) continue
|
||
if (rawValue === true) {
|
||
attrs.push(`${name}=""`)
|
||
continue
|
||
}
|
||
attrs.push(`${name}="${escapeAttr(String(rawValue))}"`)
|
||
}
|
||
return attrs.length ? ` ${attrs.join(' ')}` : ''
|
||
}
|
||
|
||
function serializeNode(node, options = {}) {
|
||
if (!node) return ''
|
||
if (node.text !== undefined) return escapeText(node.text)
|
||
if (node.fragment) return node.children.map((child) => serializeNode(child, options)).join('')
|
||
|
||
const { type, props, children } = node
|
||
if (typeof type !== 'string') fail(`序列化遇到非字符串标签:${String(type)}`)
|
||
|
||
if (type === 'select') {
|
||
const attrs = buildAttributes(type, props, options)
|
||
const inner = children.map((child) => serializeNode(child, { selectValue: props.value })).join('')
|
||
return `<select${attrs}>${inner}</select>`
|
||
}
|
||
|
||
if (type === 'option') {
|
||
const attrs = []
|
||
for (const [name, value] of Object.entries(props || {})) {
|
||
if (name === 'children' || name === 'key' || name === 'selected' || name === 'value') continue
|
||
if (value === undefined || value === null || value === false || typeof value === 'function') continue
|
||
attrs.push(`${name}="${escapeAttr(String(value))}"`)
|
||
}
|
||
if (props && props.value !== undefined && props.value !== null) attrs.push(`value="${escapeAttr(String(props.value))}"`)
|
||
const selected = props && props.selected === true
|
||
|| (options.selectValue !== undefined && options.selectValue !== null && props && String(props.value) === String(options.selectValue))
|
||
if (selected) attrs.push('selected=""')
|
||
const inner = children.map((child) => serializeNode(child, options)).join('')
|
||
return `<option${attrs.length ? ` ${attrs.join(' ')}` : ''}>${inner}</option>`
|
||
}
|
||
|
||
const attrs = buildAttributes(type, props, options)
|
||
if (VOID_TAGS.has(type)) return `<${type}${attrs}>`
|
||
const inner = children.map((child) => serializeNode(child, options)).join('')
|
||
return `<${type}${attrs}>${inner}</${type}>`
|
||
}
|
||
|
||
/**
|
||
* 把 vnode 挂载成 resolved 树:组件函数立即调用,class 组件实例化后 render,
|
||
* Fragment / 数组展开。返回的节点只有字符串标签或文本。
|
||
*/
|
||
function mountNode(node, depth = 0) {
|
||
if (depth > 200) fail('组件树递归超过 200 层,疑似存在渲染死循环。')
|
||
if (node === null || node === undefined || node === false || node === true) return null
|
||
if (typeof node === 'string' || typeof node === 'number') return { text: String(node) }
|
||
if (Array.isArray(node)) {
|
||
const children = []
|
||
for (const child of node) {
|
||
const mounted = mountNode(child, depth + 1)
|
||
if (mounted) children.push(mounted)
|
||
}
|
||
return { fragment: true, children }
|
||
}
|
||
if (typeof node !== 'object' || node.type === undefined) {
|
||
fail(`无法渲染的节点:${JSON.stringify(node)}`)
|
||
}
|
||
|
||
const { type } = node
|
||
const props = node.props || {}
|
||
|
||
if (typeof type === 'function') {
|
||
let output
|
||
if (type.prototype && typeof type.prototype.render === 'function') {
|
||
const instance = new type(props)
|
||
instance.props = props
|
||
output = instance.render()
|
||
} else {
|
||
output = type(props)
|
||
}
|
||
return mountNode(output, depth + 1)
|
||
}
|
||
|
||
if (type === 'fragment') {
|
||
const kids = pickChildren(node)
|
||
const children = []
|
||
for (const child of kids) {
|
||
const mounted = mountNode(child, depth + 1)
|
||
if (mounted) children.push(mounted)
|
||
}
|
||
return { fragment: true, children }
|
||
}
|
||
|
||
const children = []
|
||
for (const child of pickChildren(node)) {
|
||
const mounted = mountNode(child, depth + 1)
|
||
if (mounted) children.push(mounted)
|
||
}
|
||
return { type, props, children }
|
||
}
|
||
|
||
function pickChildren(node) {
|
||
const positional = Array.isArray(node.children) ? node.children : []
|
||
const fromProps = node.props && node.props.children !== undefined ? node.props.children : undefined
|
||
const source = positional.length > 0 ? positional : fromProps === undefined ? [] : [fromProps]
|
||
const flat = []
|
||
for (const item of source) {
|
||
if (Array.isArray(item)) flat.push(...item)
|
||
else flat.push(item)
|
||
}
|
||
return flat
|
||
}
|
||
|
||
function findNode(node, predicate) {
|
||
if (!node || node.text !== undefined) return null
|
||
if (node.fragment) {
|
||
for (const child of node.children) {
|
||
const hit = findNode(child, predicate)
|
||
if (hit) return hit
|
||
}
|
||
return null
|
||
}
|
||
if (predicate(node)) return node
|
||
for (const child of node.children) {
|
||
const hit = findNode(child, predicate)
|
||
if (hit) return hit
|
||
}
|
||
return null
|
||
}
|
||
|
||
// #endregion
|
||
|
||
// #region 演示数据
|
||
|
||
const LEAD_SESSION = 'sess-lead'
|
||
const DEMO_ROLES = ['lead', 'zhongshu', 'menxia', 'shangshu', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']
|
||
const DEMO_LABELS = {
|
||
lead: '丞相', zhongshu: '中书省', menxia: '门下省', shangshu: '尚书省',
|
||
libu: '吏部', hubu: '户部', lipu: '礼部', bingbu: '兵部', xingbu: '刑部', gongbu: '工部',
|
||
}
|
||
const DEMO_RUNNING = new Set(['shangshu', 'hubu', 'gongbu'])
|
||
|
||
function createDemoContext() {
|
||
const members = DEMO_ROLES.map((role) => ({ id: `sess-${role}`, name: role, phase: 'active' }))
|
||
const tasks = [
|
||
{ id: 'task-1', subject: '拆解 0.5.1 侧栏验收清单', status: 'in_progress', ownerName: 'zhongshu' },
|
||
{ id: 'task-2', subject: '复算朝堂统计投影', status: 'in_progress', ownerName: 'hubu' },
|
||
{ id: 'task-3', subject: '补齐右侧栏窄宽度回归', status: 'pending', ownerName: 'xingbu' },
|
||
{ id: 'task-4', subject: '整理 @ 部门入口说明', status: 'pending', ownerName: 'lipu' },
|
||
{ id: 'task-5', subject: '删除未渲染的旧样式', status: 'completed', ownerName: 'gongbu' },
|
||
{ id: 'task-6', subject: '核对十席角色文案', status: 'completed', ownerName: 'libu' },
|
||
]
|
||
|
||
const byId = {}
|
||
const ids = []
|
||
for (const role of DEMO_ROLES) {
|
||
const id = `sess-${role}`
|
||
ids.push(id)
|
||
byId[id] = {
|
||
id,
|
||
name: DEMO_LABELS[role],
|
||
updatedAt: 1_760_000_000_000 + DEMO_ROLES.indexOf(role),
|
||
running: DEMO_RUNNING.has(role),
|
||
workspaceId: 'demo-workspace',
|
||
}
|
||
}
|
||
byId[LEAD_SESSION] = { ...byId[LEAD_SESSION], subagent: undefined }
|
||
|
||
const team = { members, tasks }
|
||
const sessionList = {
|
||
getSnapshot: () => ({
|
||
ids: ids.slice(),
|
||
byId,
|
||
projectionsBySession: {
|
||
[LEAD_SESSION]: {
|
||
sessionId: LEAD_SESSION,
|
||
values: {
|
||
agentTeam: team,
|
||
agentPreset: 'sansheng-liubu',
|
||
subagentCatalog: [],
|
||
},
|
||
},
|
||
},
|
||
phase: 'ready',
|
||
}),
|
||
subscribe: () => () => {},
|
||
}
|
||
|
||
const statuses = new Map()
|
||
for (const role of DEMO_ROLES) {
|
||
statuses.set(`sess-${role}`, { running: DEMO_RUNNING.has(role) })
|
||
}
|
||
const statusStore = {
|
||
getSnapshot: () => statuses,
|
||
subscribe: () => () => {},
|
||
}
|
||
|
||
const catalogSnapshot = {
|
||
status: 'ready',
|
||
error: null,
|
||
current: { provider: 'openai', model: 'gpt-6-astra', reasoningEffort: 'high' },
|
||
groups: [
|
||
{
|
||
id: 'openai',
|
||
name: 'OpenAI',
|
||
models: [
|
||
{
|
||
id: 'gpt-6-astra',
|
||
name: 'GPT-6 Astra',
|
||
reasoning: {
|
||
defaultEffort: 'high',
|
||
efforts: [
|
||
{ id: 'low', name: '低' },
|
||
{ id: 'medium', name: '中' },
|
||
{ id: 'high', name: '高' },
|
||
],
|
||
},
|
||
},
|
||
{
|
||
id: 'gpt-6-mini',
|
||
name: 'GPT-6 Mini',
|
||
reasoning: {
|
||
defaultEffort: 'medium',
|
||
efforts: [
|
||
{ id: 'low', name: '低' },
|
||
{ id: 'medium', name: '中' },
|
||
],
|
||
},
|
||
},
|
||
],
|
||
},
|
||
{
|
||
id: 'deepseek',
|
||
name: 'DeepSeek',
|
||
models: [
|
||
{
|
||
id: 'deepseek-v4',
|
||
name: 'DeepSeek V4',
|
||
reasoning: { defaultEffort: 'high', efforts: [{ id: 'high', name: '高' }] },
|
||
},
|
||
],
|
||
},
|
||
],
|
||
}
|
||
|
||
const binding = {
|
||
session: {
|
||
projections: {
|
||
faceOf: () => ({ getSnapshot: () => ({ model: { name: 'GPT-6 Astra' } }) }),
|
||
},
|
||
prompt: async () => ({ ok: true }),
|
||
},
|
||
}
|
||
|
||
const ctx = {
|
||
effect(callback) {
|
||
const dispose = callback()
|
||
return typeof dispose === 'function' ? dispose : () => {}
|
||
},
|
||
sessions: {
|
||
list: sessionList,
|
||
statuses: statusStore,
|
||
binding: () => binding,
|
||
subagentAddress: () => undefined,
|
||
refreshProjections: async () => {},
|
||
},
|
||
uiWorkspace: {
|
||
selection: {
|
||
getSnapshot: () => ({ sessionId: LEAD_SESSION }),
|
||
subscribe: () => () => {},
|
||
set: () => {},
|
||
},
|
||
currentWorkspaceId: 'demo-workspace',
|
||
openSession: () => {},
|
||
startSession: () => {},
|
||
},
|
||
uiConversation: {
|
||
binding: () => ({
|
||
target: () => ({ getSnapshot: () => ({ nodes: new Map() }) }),
|
||
}),
|
||
},
|
||
modelDirectories: {
|
||
directoryFor: () => ({
|
||
load: () => Promise.resolve(),
|
||
select: () => Promise.resolve({ ok: true }),
|
||
store: {
|
||
getSnapshot: () => catalogSnapshot,
|
||
subscribe: () => () => {},
|
||
},
|
||
}),
|
||
},
|
||
remote: {
|
||
agentPresets: {
|
||
list: async () => ({ ok: true, value: { presets: [] } }),
|
||
select: async () => ({ ok: true }),
|
||
},
|
||
},
|
||
get: () => undefined,
|
||
layout: { selectPanel: () => {} },
|
||
sidebarRight: { openTab: () => {}, openTabIn: () => {} },
|
||
sidebarRightTabs: { register: () => () => {} },
|
||
slots: { register: () => () => {}, inject: (name, callback) => callback() },
|
||
}
|
||
|
||
return { ctx, team, catalogSnapshot }
|
||
}
|
||
|
||
// #endregion
|
||
|
||
// #region HTML 外壳
|
||
|
||
function buildPage({ css, panelHtml, width, theme, view }) {
|
||
const pageWidth = width + CHAT_EDGE
|
||
const dark = theme === 'dark'
|
||
|
||
const shellCss = `
|
||
*{box-sizing:border-box}
|
||
html,body{margin:0;padding:0}
|
||
body{background:#e6e9ef;font-family:"Segoe UI","Microsoft YaHei",-apple-system,BlinkMacSystemFont,"Helvetica Neue",Arial,sans-serif;-webkit-font-smoothing:antialiased}
|
||
.pv-page{display:flex;align-items:stretch;min-height:100vh}
|
||
.pv-chat-edge{flex:0 0 ${CHAT_EDGE}px;background:linear-gradient(90deg,#d9dee7 0%,#e1e5ec 55%,#eceff4 100%);border-right:1px solid #cbd1db}
|
||
.pv-rail{flex:0 0 auto;display:flex;flex-direction:column;padding:12px 12px 18px;background:var(--dsw-alias-bg-layer-2,#f5f6f8);box-shadow:inset 1px 0 0 #d2d8e2,-14px 0 30px rgba(15,23,42,.05);min-height:100vh}
|
||
.pv-panel{display:flex;flex-direction:column;min-width:0}
|
||
.pv-rail .sl-root{height:auto;min-height:0;background:transparent;color:var(--dsw-alias-label-primary,#1f2329)}
|
||
.pv-rail .sl-body{background:transparent}
|
||
.pv-rail .sl-body-sidebar{padding:0;overflow:visible}
|
||
.pv-rail .sl-body-sidebar .sl-right{overflow:visible;padding-right:0}
|
||
.pv-rail .sl-side-tabs{position:sticky}
|
||
body.pv-dark{background:#0e1014}
|
||
body.pv-dark .pv-chat-edge{background:linear-gradient(90deg,#14161b 0%,#181b21 60%,#1d2027 100%);border-right-color:#262a32}
|
||
.pv-rail[data-dsw-theme="light"]{color-scheme:light}
|
||
.pv-rail[data-dsw-theme="dark"]{
|
||
color-scheme:dark;
|
||
--dsw-alias-bg-layer-1:#1f222a;
|
||
--dsw-alias-bg-layer-2:#16181d;
|
||
--dsw-alias-bg-layer-3:rgba(255,255,255,.10);
|
||
--dsw-alias-label-primary:#e8eaee;
|
||
--dsw-alias-label-secondary:#b7bcc6;
|
||
--dsw-alias-label-tertiary:#8b93a1;
|
||
--dsw-alias-label-caption:#7f8794;
|
||
--dsw-alias-border-l1:rgba(255,255,255,.12);
|
||
--dsw-alias-border-l2:rgba(255,255,255,.18);
|
||
--dsw-alias-border-l3:rgba(255,255,255,.28);
|
||
--dsw-alias-state-business-primary:#6b8afd;
|
||
--dsw-alias-state-error-primary:#f2777a;
|
||
--sl-page:#16181d;
|
||
--sl-card:#1f222a;
|
||
--sl-line:rgba(255,255,255,.12);
|
||
--sl-accent:#6b8afd;
|
||
box-shadow:inset 1px 0 0 #24272f,-14px 0 30px rgba(0,0,0,.38);
|
||
}
|
||
`
|
||
|
||
const styles = `${shellCss}\n${css}\n`
|
||
|
||
return {
|
||
pageWidth,
|
||
html: `<!doctype html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=${pageWidth}, initial-scale=1">
|
||
<title>三省六部 · 侧栏预览 (${view} / ${theme} / ${width}px)</title>
|
||
<style>${styles}</style>
|
||
</head>
|
||
<body${dark ? ' class="pv-dark"' : ''}>
|
||
<div class="pv-page">
|
||
<div class="pv-chat-edge" aria-hidden="true"></div>
|
||
<div class="pv-rail" data-dsw-theme="${theme}" data-pv-width="${width}" style="width:${width}px">
|
||
<div class="pv-panel" data-preview-view="${view}">
|
||
${panelHtml}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div id="pv-height" hidden></div>
|
||
<script>
|
||
(function () {
|
||
var h = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
|
||
document.getElementById('pv-height').textContent = String(h);
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html>
|
||
`,
|
||
}
|
||
}
|
||
|
||
// #endregion
|
||
|
||
// #region 主流程
|
||
|
||
async function tick(times = 4) {
|
||
for (let i = 0; i < times; i += 1) {
|
||
await new Promise((resolveTick) => setImmediate(resolveTick))
|
||
}
|
||
}
|
||
|
||
async function settle(hooks, rootVNode) {
|
||
let tree = null
|
||
for (let pass = 0; pass < 40; pass += 1) {
|
||
hooks.beginRender()
|
||
tree = mountNode(rootVNode)
|
||
hooks.runEffects()
|
||
await tick()
|
||
if (!hooks.consumeDirty()) return tree
|
||
}
|
||
fail('面板在 40 次渲染后仍未稳定(可能存在状态更新死循环)。')
|
||
}
|
||
|
||
function readPngSize(pngPath) {
|
||
const bytes = readFileSync(pngPath)
|
||
if (bytes.length < 33) fail(`截图文件不完整:${pngPath}(${bytes.length} 字节)`)
|
||
const signature = bytes.subarray(0, 8).toString('hex')
|
||
if (signature !== '89504e470d0a1a0a') fail(`截图不是合法 PNG:${pngPath}`)
|
||
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), bytes: bytes.length }
|
||
}
|
||
|
||
function measureHeight(chrome, htmlPath, pageWidth, profileDir) {
|
||
const args = [
|
||
'--headless=new',
|
||
'--disable-gpu',
|
||
'--hide-scrollbars',
|
||
'--no-first-run',
|
||
'--no-default-browser-check',
|
||
'--disable-extensions',
|
||
'--disable-background-networking',
|
||
'--disable-sync',
|
||
'--mute-audio',
|
||
`--user-data-dir=${profileDir}`,
|
||
'--virtual-time-budget=3000',
|
||
`--window-size=${pageWidth},600`,
|
||
'--dump-dom',
|
||
pathToFileURL(htmlPath).href,
|
||
]
|
||
const result = chromeRun(chrome, args, '测量页面高度')
|
||
const match = String(result.stdout || '').match(/id="pv-height"[^>]*>(\d+)</)
|
||
if (!match) {
|
||
const head = String(result.stdout || '').slice(0, 400)
|
||
fail(`无法从 dump-dom 读取页面高度。输出开头:\n${head}`)
|
||
}
|
||
const height = Number(match[1])
|
||
if (!Number.isFinite(height) || height < 120 || height > 20000) {
|
||
fail(`测量到的页面高度不合理:${height}`)
|
||
}
|
||
return height
|
||
}
|
||
|
||
function screenshot(chrome, htmlPath, pngPath, pageWidth, height, scale, profileDir) {
|
||
const args = [
|
||
'--headless=new',
|
||
'--disable-gpu',
|
||
'--hide-scrollbars',
|
||
`--force-device-scale-factor=${scale}`,
|
||
'--no-first-run',
|
||
'--no-default-browser-check',
|
||
'--disable-extensions',
|
||
'--disable-background-networking',
|
||
'--disable-sync',
|
||
'--mute-audio',
|
||
`--user-data-dir=${profileDir}`,
|
||
'--virtual-time-budget=3000',
|
||
`--window-size=${pageWidth},${height}`,
|
||
`--screenshot=${pngPath}`,
|
||
pathToFileURL(htmlPath).href,
|
||
]
|
||
chromeRun(chrome, args, '截图')
|
||
if (!existsSync(pngPath)) fail(`Chrome 没有生成截图:${pngPath}`)
|
||
const size = readPngSize(pngPath)
|
||
if (size.bytes < 5000) fail(`截图文件过小,可能是空白图:${pngPath}(${size.bytes} 字节)`)
|
||
return size
|
||
}
|
||
|
||
async function main() {
|
||
const options = parseArgs(process.argv.slice(2))
|
||
const chrome = options.htmlOnly ? null : findChrome(options.chrome)
|
||
const hooks = createHooks()
|
||
const bundle = loadBundle(options.source, hooks)
|
||
|
||
if (typeof bundle.exports.SanshengPanel !== 'function') {
|
||
fail('bundle 没有导出 SanshengPanel,无法渲染。')
|
||
}
|
||
|
||
const { React } = hooks
|
||
const { ctx } = createDemoContext()
|
||
const host = bundle.exports.createHost(ctx)
|
||
const rootVNode = React.createElement(bundle.exports.SanshengPanel, {
|
||
host,
|
||
sessionId: LEAD_SESSION,
|
||
compact: true,
|
||
})
|
||
|
||
let tree = await settle(hooks, rootVNode)
|
||
|
||
if (options.view === 'tasks') {
|
||
const tab = findNode(tree, (node) => node.props && node.props['data-side-tab'] === 'tasks')
|
||
if (!tab || typeof tab.props.onClick !== 'function') {
|
||
fail('找不到「任务」页签,无法切换到 tasks 视图。')
|
||
}
|
||
tab.props.onClick()
|
||
tree = await settle(hooks, rootVNode)
|
||
const activeTab = findNode(tree, (node) => node.props && node.props['data-side-tab'] === 'tasks')
|
||
if (!activeTab || activeTab.props['aria-selected'] !== true) {
|
||
fail('点击「任务」页签后没有切换到任务视图。')
|
||
}
|
||
}
|
||
|
||
const panelHtml = serializeNode(tree)
|
||
if (!panelHtml.trim()) fail('序列化后的面板 HTML 为空。')
|
||
if (panelHtml.length < 2000) fail(`面板 HTML 过短(${panelHtml.length} 字符),可能渲染不完整。`)
|
||
if (panelHtml.includes('sl-crash')) fail('面板渲染进了错误边界(出现 .sl-crash)。')
|
||
|
||
const rootNode = findNode(tree, (node) => node.type === 'div')
|
||
if (!rootNode || rootNode.props['data-sansheng-sidebar'] !== '1') {
|
||
fail('渲染结果不是侧栏形态(缺少 data-sansheng-sidebar="1")。')
|
||
}
|
||
|
||
// 先落中间 HTML:即使后面的校验/截图失败,也能直接打开排查。
|
||
const page = buildPage({
|
||
css: bundle.css,
|
||
panelHtml,
|
||
width: options.width,
|
||
theme: options.theme,
|
||
view: options.view,
|
||
})
|
||
const htmlPath = join(os.tmpdir(), `dsh-preview-${process.pid}-${Date.now()}.html`)
|
||
writeFileSync(htmlPath, page.html, 'utf8')
|
||
const htmlTarget = options.html || (options.htmlOnly ? resolve(options.out, `${options.name}.html`) : null)
|
||
if (htmlTarget) {
|
||
mkdirSync(dirname(htmlTarget), { recursive: true })
|
||
writeFileSync(htmlTarget, page.html, 'utf8')
|
||
}
|
||
|
||
if (options.view === 'court') {
|
||
const seatCount = (panelHtml.match(/data-role="/g) || []).length
|
||
if (seatCount !== 10) fail(`朝堂应该渲染 10 个席位,实际 ${seatCount} 个。`)
|
||
const missing = Object.values(DEMO_LABELS).filter((label) => !panelHtml.includes(label))
|
||
if (missing.length > 0) fail(`面板缺少席位:${missing.join('、')}`)
|
||
for (const key of ['在朝成员', '正在运行', '在办任务', '已完成']) {
|
||
if (!panelHtml.includes(key)) fail(`统计区缺少「${key}」。`)
|
||
}
|
||
if (!panelHtml.includes('GPT-6 Astra')) fail('模型下拉没有渲染出「GPT-6 Astra」。')
|
||
if (!panelHtml.includes('>高<')) fail('推理等级下拉没有渲染出「高」。')
|
||
} else {
|
||
if (!panelHtml.includes('任务队列')) fail('任务视图缺少「任务队列」标题。')
|
||
const taskRows = (panelHtml.match(/class="sl-task-copy"/g) || []).length
|
||
if (taskRows !== 4) fail(`任务视图应该渲染 4 条任务,实际 ${taskRows} 条。`)
|
||
}
|
||
|
||
if (options.htmlOnly) {
|
||
if (!htmlTarget) fail('内部错误:--html-only 没有解析出 HTML 输出路径。')
|
||
const bytes = statSync(htmlTarget).size
|
||
if (bytes < 5000) fail(`HTML 过小,可能渲染不完整:${htmlTarget}(${bytes} 字节)`)
|
||
try { rmSync(htmlPath, { force: true }) } catch { /* 忽略清理失败 */ }
|
||
process.stdout.write(
|
||
`✓ ${htmlTarget}\n` +
|
||
` HTML-only · ${bytes} 字节 · 侧栏 ${options.width}px · ` +
|
||
`视图 ${options.view} · 主题 ${options.theme}\n` +
|
||
` CSS ${bundle.css.length} 字符 · 面板 ${panelHtml.length} 字符 · 源 ${bundle.sourcePath}\n`,
|
||
)
|
||
return
|
||
}
|
||
|
||
const outDir = options.out
|
||
mkdirSync(outDir, { recursive: true })
|
||
const pngPath = join(outDir, `${options.name}.png`)
|
||
|
||
const profileDir = join(os.tmpdir(), `dsh-preview-chrome-${process.pid}-${Date.now()}`)
|
||
mkdirSync(profileDir, { recursive: true })
|
||
|
||
let size
|
||
try {
|
||
const measured = measureHeight(chrome, htmlPath, page.pageWidth, profileDir)
|
||
const height = Math.max(200, Math.ceil(measured) + 2)
|
||
size = screenshot(chrome, htmlPath, pngPath, page.pageWidth, height, options.scale, profileDir)
|
||
|
||
const expectedWidth = page.pageWidth * options.scale
|
||
if (size.width !== expectedWidth) {
|
||
fail(
|
||
`截图宽度 ${size.width}px 与预期 ${expectedWidth}px(${page.pageWidth}×${options.scale})不符,` +
|
||
'页面可能被 Chrome 缩放或窗口尺寸未生效。',
|
||
)
|
||
}
|
||
} finally {
|
||
try { rmSync(profileDir, { recursive: true, force: true }) } catch { /* 忽略清理失败 */ }
|
||
try { rmSync(htmlPath, { force: true }) } catch { /* 忽略清理失败 */ }
|
||
}
|
||
|
||
const seatNote = options.view === 'court' ? ' · 十席齐全' : ' · 任务队列'
|
||
process.stdout.write(
|
||
`✓ ${pngPath}\n` +
|
||
` ${size.width}×${size.height}px @${options.scale}x · 侧栏 ${options.width}px · ` +
|
||
`视图 ${options.view} · 主题 ${options.theme}${seatNote}\n` +
|
||
` CSS ${bundle.css.length} 字符 · HTML ${panelHtml.length} 字符 · 源 ${bundle.sourcePath}\n`,
|
||
)
|
||
if (options.html) process.stdout.write(` 中间 HTML:${options.html}\n`)
|
||
}
|
||
|
||
main().catch((error) => {
|
||
if (error && error.previewFailure) {
|
||
process.stderr.write(`\n[preview] 失败:${error.message}\n`)
|
||
} else {
|
||
process.stderr.write(`\n[preview] 未预期的错误:\n${error && error.stack ? error.stack : error}\n`)
|
||
}
|
||
process.exit(1)
|
||
})
|
||
|
||
// #endregion
|