底部 + 菜单里开得出 shell,刷新后认回同一个 shell,且**不**变成宿主 右列终端的第二个入口。 实现分三层: 1. 宿主能力层(src/client/terminal-client.ts,核心 bundle 安全):结构化 探测 `ctx.webTerminals`(view/close/recover 三个函数都在才算数)+ 身份助手。**不写进 dsh.client.inject**:注入一个不存在的服务会把整行 拖成 pending,插件在无终端控制器的部署上会整体不加载;也**不** value-import 任何 @deepseek-ai/*(纯度门),类型面手工声明。 2. chunk 层(src/client/TerminalView.tsx + terminal.module.css + chunks/terminal.tsx + terminal-lazy.tsx):xterm 与它的样式表整份打进 lib/client-terminal.js(750 KB),核心包一处都没有;chunk 名在 9 处 镜像(tsdown / bundle-route / chunk-loader / package.json.files / package-registry / bundle-route.spec),另两处 spec 从 CHUNK_NAMES 派生。 3. 描述符层(builtins/tabs.tsx):第 6 个内置类型,`bottomOnly: true` (见上一个 commit)、`single`、`available` 读同一份探测、`onClose` 结束进程。 三条恢复语义的由来: - **contentId 恒定,terminalId 不写进 tab.meta**:宿主 view() 显式传 terminalId 会关掉「缺了就建」分支,一个过期 id 会把页签永久卡在 missingTerminal;宿主自己的 (sessionId, contentId) → 终端 id 持久绑定 本来就能在刷新后认回同一个 shell。 - **「新建终端」换代号**:DSH 重启后 PTY 没了而 localStorage 绑定还在, 恒定 contentId 会永远认领死绑定。tab.meta.terminalRun(默认 0)+1 换 一代 contentId 让宿主另铸进程;key 与 contentId 一起换(views 按 (sessionId, key) 记忆化)。 - **关页签才结束进程**:宿主的契约是「视图跨 DOM 卸载存活」,这正是刷新 能认回同一个 shell 的原因,所以卸载不 close;但不 close 会让每个关掉 的终端永久占一个 per-session 终端槽位(terminalLimit),因此 descriptor 的 onClose → webTerminals.close() 是唯一且必须存在的回收路径。 测试(判别性证据见交付报告): - tests/terminal-tab.spec.tsx 14 条:view() 调用形状与 contentId 恒定性、 mount/detach、write/resize 转发与上限夹紧、snapshot 重放 + acknowledge、 无服务降级、missingTerminal → 换代号、onClose → close()。 - tests/builtins.spec.ts 内置清单 5 → 6,并新增「terminal-bottom 是 bottomOnly、其余内置都不是」。 - tests/chunk-artifact.spec.ts 新增产物包含性断言:chunk 里必须有 xterm(xterm-char-measure-element / @xterm/xterm/lib/xterm.js), lib/client.js 与 lib/client-registry.js 里一处都不许有。 - tests/e2e/mount.e2e.ts 第三条真实浏览器用例:先开原生右列(guide 基线 = 宿主 terminal 恰好 1 条)→ 展开底部工作台(data-active + 布局推挤 > 0)→ 点空面板的 Terminal 卡片 → 断言 tab 挂载、.xterm 在、chunk 有 响应、状态不停在 unavailable/loading、宿主 terminal 条目仍为 1 且 terminal-bottom 条目为 0、无 pageerror / 插件 console 错误。 依赖:@xterm/xterm@^6.0.0 + @xterm/addon-fit@^0.11.0(与宿主自用版本一致, 安装期零脚本,不触市场拒绝名单)。lockfile 只手工拼接这 2 个包的 4 个块: pnpm add 会顺手重解析无关 caret 范围,产出 99+/69- 的噪声 diff。
130 lines
4.7 KiB
TypeScript
130 lines
4.7 KiB
TypeScript
/**
|
|
* Lazy chunk route: serves the client bundle's chunk scripts
|
|
* (/sidebar/bundle/<name>.js). The official /plugins/<id>/client.js route
|
|
* cannot serve arbitrary file names, so the plugin serves its own split
|
|
* bundles (lib/client-<name>.js) here; the client injects the script on
|
|
* first use of the feature that needs it (see src/client/chunk-loader.ts).
|
|
*
|
|
* Caching contract: every response carries `cache-control: no-cache` plus an
|
|
* ETag (content hash, memoized per file by mtime/size) and honors
|
|
* If-None-Match — the browser revalidates each fetch, but a 304 avoids
|
|
* re-downloading multi-MB chunks that did not change (page refresh, HMR
|
|
* re-activation). Same browser-trust fence as every other /sidebar route;
|
|
* only allowlisted chunk names are servable (no path traversal).
|
|
*/
|
|
import { createHash } from 'node:crypto'
|
|
import { stat, readFile } from 'node:fs/promises'
|
|
import { dirname, join } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import type { Context, SidebarHttpRequest, SidebarHttpResponse } from './context-types.ts'
|
|
|
|
/** The chunk names the client may request (mirror of src/client/chunk-loader.ts). */
|
|
export const CHUNK_NAMES = ['editor', 'mermaid', 'locale', 'terminal'] as const
|
|
export type ChunkName = (typeof CHUNK_NAMES)[number]
|
|
|
|
/** Directory of this host-half module (lib/ — the chunk scripts live next to it). */
|
|
const LIB_DIR = dirname(fileURLToPath(import.meta.url))
|
|
|
|
/** sha1 content hash shortened to 12 hex chars (same shape as the client-modules rev). */
|
|
function shortHash(input: string | Buffer): string {
|
|
return createHash('sha1').update(input).digest('hex').slice(0, 12)
|
|
}
|
|
|
|
interface ChunkEtag {
|
|
mtimeMs: number
|
|
size: number
|
|
etag: string
|
|
}
|
|
|
|
/** ETag memo: recompute the content hash only when the file's stat changed. */
|
|
const etags = new Map<string, ChunkEtag>()
|
|
|
|
/**
|
|
* The chunk file's ETag (quoted hash), or undefined when the file is
|
|
* missing. Hash is recomputed only when mtime/size changed (hashing a
|
|
* multi-MB chunk per request is wasteful).
|
|
*/
|
|
async function etagOf(name: ChunkName, chunkDir: string): Promise<string | undefined> {
|
|
const path = join(chunkDir, `client-${name}.js`)
|
|
const key = `${chunkDir}:${name}`
|
|
try {
|
|
const info = await stat(path)
|
|
const memo = etags.get(key)
|
|
if (memo !== undefined && memo.mtimeMs === info.mtimeMs && memo.size === info.size) {
|
|
return memo.etag
|
|
}
|
|
const etag = `"${shortHash(await readFile(path))}"`
|
|
etags.set(key, { mtimeMs: info.mtimeMs, size: info.size, etag })
|
|
return etag
|
|
} catch {
|
|
return undefined
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Build the /sidebar/bundle route handler. `fence` is the shared browser-
|
|
* trust check every /sidebar route applies; `chunkDir` is the directory the
|
|
* chunk scripts live in (overridable for tests).
|
|
*/
|
|
export function createBundleRouteHandler(
|
|
fence: (req: SidebarHttpRequest) => boolean,
|
|
chunkDir: string = LIB_DIR,
|
|
): (req: SidebarHttpRequest, res: SidebarHttpResponse) => Promise<void> {
|
|
return async (req, res): Promise<void> => {
|
|
if (!fence(req)) {
|
|
res.writeHead(403)
|
|
res.end('forbidden')
|
|
return
|
|
}
|
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
res.writeHead(405)
|
|
res.end()
|
|
return
|
|
}
|
|
const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
|
|
const match = /^\/sidebar\/bundle\/([a-z0-9-]+)\.js$/.exec(pathname)
|
|
const name = match?.[1] as ChunkName | undefined
|
|
if (name === undefined || !(CHUNK_NAMES as readonly string[]).includes(name)) {
|
|
res.writeHead(404)
|
|
res.end('not found')
|
|
return
|
|
}
|
|
const etag = await etagOf(name, chunkDir)
|
|
if (etag === undefined) {
|
|
// Registered name but unreadable (bundle not built yet): loud 404.
|
|
res.writeHead(404)
|
|
res.end('not found')
|
|
return
|
|
}
|
|
if (req.headers['if-none-match'] === etag) {
|
|
// Revalidation hit: unchanged chunk, no body — avoids re-downloading
|
|
// multi-MB scripts on page refresh / HMR re-activation.
|
|
res.writeHead(304, { 'cache-control': 'no-cache', etag })
|
|
res.end()
|
|
return
|
|
}
|
|
try {
|
|
const body = await readFile(join(chunkDir, `client-${name}.js`))
|
|
res.writeHead(200, {
|
|
'content-type': 'text/javascript; charset=utf-8',
|
|
'cache-control': 'no-cache',
|
|
etag,
|
|
})
|
|
res.end(body)
|
|
} catch {
|
|
// Read raced a delete/rebuild between the stat and the read.
|
|
res.writeHead(404)
|
|
res.end('not found')
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Register the /sidebar/bundle route (disposed with the fiber). */
|
|
export function registerBundleRoute(ctx: Context, fence: (req: SidebarHttpRequest) => boolean): () => void {
|
|
return ctx.webServer.register({
|
|
kind: 'prefix',
|
|
path: '/sidebar/bundle',
|
|
handler: createBundleRouteHandler(fence),
|
|
})
|
|
}
|