- 类型生态:service 模块 re-export SidebarTab/SidebarState/SidebarStore/ SidebarSnapshot/SidebarDiffRef/TabType/SessionScope/SidebarPrefs 等公共 状态词汇(此前 TS2459 无法命名);context-types 去 Node 依赖(结构镜像 SidebarHttpRequest/Response/UpgradeSocket/Head),client 可达声明图零 node:* 引用,外部消费者无 @types/node + skipLibCheck:false 可编译 (scripts/check-consumer-types.sh 守护) - 服务能力:version/features 版本与能力探测(单调只增)、getSnapshot/ subscribeState 状态订阅、updateTab(title/path/meta)、activateTab、 openFile(路径派生 id 与内置拦截一致)、openTab(seed, scope?) 定向到 指定 session(store.reduceFor 不扰动 UI) - TabDescriptor:badge 角标(99+ 封顶,抛错吞掉)、onOpen/onActivate/ onClose 生命周期回调(service 路径派发,dedupe 聚焦触发 onActivate 而非 onOpen,抛错不打断流程);SidebarTab.meta JSON 可序列化跨刷新 持久化(sanitize 宽松保留) - 设置 seam 开放:PrefsSchema 增 pluginSettings 开放嵌套 map(z.dict), settings.pluginToggles(插件自有行,同 switch/text/number 控件)与 settings.render(自定义面板,含 store/service/prefs/updatePluginSetting/ close props);viewer 卡片 v0.12.0 起也有齿轮设置弹窗 - FileViewerDescriptor.load 增第三参 AbortSignal(EditorHost 生命周期中止) - UI 接线:tab 激活/关闭改走 service(跨树激活修复 + 回调触发)、+ 菜单 传 scope、TabBar badge pill 渲染;active-session scope 走原 reduce 路径 保证 notify - 测试 +23:生命周期/定向打开/updateTab/activateTab/openFile/meta 持久化/ reduceFor/能力常量(与 package.json 锁步)、consumer-types.ts 编译门、 api-surface.spec.ts(client 图零 node 依赖守护);既有 430 测试全绿 - 文档:AGENTS.md 修 available 三参示例并补全部新 API;external-plugin- guide.md 刷新至 v0.12.0(7 tab + 9 viewer、设置 seam 开放、类型导入 路径建议);README×2 服务化小节同步 未发版 npm(用户决定);分支 feat/plugin-api-v012。
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 = ['docx', 'xlsx', 'pptx', 'terminal', 'editor'] 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),
|
|
})
|
|
}
|