问题:Gitea 0.5.x 线缺了 qiudl 0.4.x 分支的整套主题桥能力,升级后所有工作台
产物页都不再跟随 DSH 主题(浅色/深色/跟随系统全部失效),页面各自锁死自己的配色。
这是升级引入的真实回归,比单个页面的配色问题严重得多。
移植内容(来自 qiudl 0.4.9-rc.2,theme.ts 无外部依赖,纯函数 + 浏览器脚本):
- 新增 src/theme.ts(191 行):THEME_BRIDGE_JS / injectThemeBridge / 前缀判定
- 模板路由补 /api/worktable/template/theme.js(独立打开/嵌套 iframe 显式引用)
- 站点路由对 .html/.htm 自动注入主题桥(幂等:已含 data-wt-theme-bridge 则原样)
- 新增 04_test/theme-bridge.test.mjs(7 个回归用例,含接线防漏)
顺带修两处写死项(同属「不跟随主题」根因):
- dshell.css::root{color-scheme:dark} → color-scheme:light dark + 浅/深两套
兜底 token(历史事故:写死深色会让所有页面锁死深色)
- dshell.css:正文字体改走 var(--dsw-font-family, ...)
版本 0.5.3-local.3 -> 0.5.3-local.4
验证:build 通过;client-factory-gate 10/10;主题桥测试 7/7;兼容回归 105/105;
release-prep 全过(结构断言、独立安装 import、split anchor dom 14 场景、
sidebar popup、真实 Chromium split margin 5 场景、server home 3 场景)
1109 lines
50 KiB
JavaScript
1109 lines
50 KiB
JavaScript
// src/index.ts
|
|
import { execFile } from "node:child_process";
|
|
import { readdirSync, realpathSync } from "node:fs";
|
|
import { readdir, readFile } from "node:fs/promises";
|
|
import { dirname, resolve as pathResolve, sep as sep2 } from "node:path";
|
|
import { createRequire } from "node:module";
|
|
import { homedir } from "node:os";
|
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
|
|
// src/requestAuth.ts
|
|
async function requestRejection(ctx, req) {
|
|
try {
|
|
const connection = typeof ctx.get === "function" ? ctx.get("connection") : void 0;
|
|
if (!connection) return 503;
|
|
if (typeof connection.admit === "function") {
|
|
const admission = await connection.admit(req);
|
|
if (!admission || typeof admission !== "object") return 503;
|
|
if ("rejection" in admission) return admission.rejection === 401 ? 401 : 403;
|
|
const peer = admission.peer;
|
|
if (peer?.principal?.kind === "owner") return void 0;
|
|
if (peer && peer === connection.operator && peer.principal === void 0) return void 0;
|
|
return 403;
|
|
}
|
|
} catch {
|
|
}
|
|
return 503;
|
|
}
|
|
function rejectionText(status) {
|
|
return status === 401 ? "unauthorized" : status === 403 ? "forbidden" : "Host authentication unavailable";
|
|
}
|
|
|
|
// src/previewFiles.ts
|
|
import { randomBytes } from "node:crypto";
|
|
import { open, realpath, stat } from "node:fs/promises";
|
|
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
var PREVIEW_PREFIX = "/api/worktable/preview-static";
|
|
var PREVIEW_SANDBOX = "allow-scripts allow-forms allow-downloads";
|
|
var PREVIEW_CSP = `sandbox ${PREVIEW_SANDBOX}; base-uri 'none'; object-src 'none'; frame-src 'none'`;
|
|
var PREVIEW_MAX_BYTES = 40 * 1024 * 1024;
|
|
var IDLE_MS = 30 * 60 * 1e3;
|
|
var MAX_MOUNTS = 128;
|
|
function inside(root, file) {
|
|
const rel = relative(root, file);
|
|
return rel === "" || !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep);
|
|
}
|
|
function createPreviewFiles(now = () => Date.now()) {
|
|
const mounts = /* @__PURE__ */ new Map();
|
|
const prune = () => {
|
|
for (const [key, item] of mounts) if (now() - item.touched >= IDLE_MS) mounts.delete(key);
|
|
};
|
|
return {
|
|
async mount(root) {
|
|
if (!isAbsolute(root)) throw new Error("Preview root must be absolute");
|
|
const canonical = await realpath(root);
|
|
if (!(await stat(canonical)).isDirectory()) throw new Error("Preview root is not a directory");
|
|
prune();
|
|
if (mounts.size >= MAX_MOUNTS) throw new Error("Too many open previews; close an unused preview first");
|
|
const token = randomBytes(24).toString("base64url");
|
|
mounts.set(token, { root: canonical, touched: now() });
|
|
return token;
|
|
},
|
|
revoke(token) {
|
|
mounts.delete(token);
|
|
},
|
|
clear() {
|
|
mounts.clear();
|
|
},
|
|
async file(token, segments, headOnly = false) {
|
|
prune();
|
|
const mount = mounts.get(token);
|
|
if (!mount) return null;
|
|
if (segments.some((s) => s === ".." || s.includes("/") || s.includes("\\") || s.includes("\0"))) return null;
|
|
let target = resolve(mount.root, ...segments);
|
|
if (!inside(mount.root, target)) return null;
|
|
let info = await stat(target).catch(() => null);
|
|
if (info?.isDirectory()) target = resolve(target, "index.html");
|
|
const canonical = await realpath(target).catch(() => null);
|
|
if (!canonical || !inside(mount.root, canonical)) return null;
|
|
const handle = await open(canonical, "r").catch(() => null);
|
|
if (!handle) return null;
|
|
try {
|
|
const before = await handle.stat({ bigint: true });
|
|
if (!before.isFile()) return null;
|
|
const sameFile = (other) => other.isFile() && other.dev === before.dev && other.ino === before.ino && other.size === before.size && other.mtimeNs === before.mtimeNs && other.ctimeNs === before.ctimeNs;
|
|
const stillValid = async () => {
|
|
const current = await realpath(canonical);
|
|
if (current !== canonical || !inside(mount.root, current)) return false;
|
|
const named = await stat(current, { bigint: true });
|
|
const opened = await handle.stat({ bigint: true });
|
|
return sameFile(named) && sameFile(opened) && mounts.get(token) === mount && now() - mount.touched < IDLE_MS;
|
|
};
|
|
const tooLarge = () => Object.assign(new Error("file too large"), { status: 413 });
|
|
if (before.size > BigInt(PREVIEW_MAX_BYTES)) throw tooLarge();
|
|
if (!await stillValid()) return null;
|
|
const chunks = [];
|
|
let total = 0;
|
|
if (!headOnly) {
|
|
while (total <= PREVIEW_MAX_BYTES) {
|
|
const chunk = Buffer.alloc(Math.min(64 * 1024, PREVIEW_MAX_BYTES + 1 - total));
|
|
const { bytesRead } = await handle.read(chunk, 0, chunk.length, total);
|
|
if (!bytesRead) break;
|
|
total += bytesRead;
|
|
if (total > PREVIEW_MAX_BYTES) throw tooLarge();
|
|
chunks.push(chunk.subarray(0, bytesRead));
|
|
}
|
|
}
|
|
if (!await stillValid() || !headOnly && BigInt(total) !== before.size) return null;
|
|
mount.touched = now();
|
|
return { path: canonical, size: Number(before.size), data: headOnly ? void 0 : Buffer.concat(chunks, total) };
|
|
} catch (error) {
|
|
if (error?.status === 413) throw error;
|
|
return null;
|
|
} finally {
|
|
await handle.close();
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
// src/theme.ts
|
|
var THEME_VAR_PREFIXES = ["--dsw-", "--dsh-", "--ds-"];
|
|
var THEME_BRIDGE_ID = "wt-theme-bridge";
|
|
var THEME_JS_PATH = "/api/worktable/template/theme.js";
|
|
var THEME_BRIDGE_JS = `(function () {
|
|
var PREFIXES = ${JSON.stringify(THEME_VAR_PREFIXES)};
|
|
if (window.__wtThemeBridgeInstalled) return;
|
|
window.__wtThemeBridgeInstalled = true;
|
|
function ok(name) {
|
|
if (!name || name.slice(0, 2) !== '--') return false;
|
|
for (var i = 0; i < PREFIXES.length; i++) if (name.slice(0, PREFIXES[i].length) === PREFIXES[i]) return true;
|
|
return false;
|
|
}
|
|
/** \u5411\u4E0A\u627E\u5230\u6700\u5916\u5C42\u540C\u6E90\u7956\u5148\u7A97\u53E3\uFF1B\u8DE8\u57DF\u6216\u5230\u9876\u5C31\u505C\u3002 */
|
|
function hostWindow() {
|
|
var w = window;
|
|
try {
|
|
for (var i = 0; i < 12; i++) {
|
|
var p = w.parent;
|
|
if (!p || p === w) break;
|
|
if (!p.document || !p.document.documentElement) break;
|
|
w = p;
|
|
}
|
|
} catch (e) { /* \u8DE8\u57DF\uFF1A\u505C\u5728\u5F53\u524D\u5C42 */ }
|
|
return w === window ? null : w;
|
|
}
|
|
function hostVars(host) {
|
|
var out = [];
|
|
try {
|
|
var el = host.document.body || host.document.documentElement;
|
|
if (!el) return out;
|
|
var cs = host.getComputedStyle(el);
|
|
for (var i = 0; i < cs.length; i++) {
|
|
var n = cs[i];
|
|
if (!ok(n)) continue;
|
|
var v = cs.getPropertyValue(n);
|
|
if (v && v.trim()) out.push([n, v.trim()]);
|
|
}
|
|
out.dark = el.hasAttribute && el.hasAttribute('data-ds-dark-theme');
|
|
} catch (e) { /* \u8BFB\u4E0D\u5230\u5C31\u9000\u56DE\u7CFB\u7EDF\u504F\u597D */ }
|
|
return out;
|
|
}
|
|
function systemDark() {
|
|
try { return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches); } catch (e) { return false; }
|
|
}
|
|
/** \u9875\u9762\u81EA\u5E26\u4E3B\u9898\u5F00\u5173\uFF1F\uFF08\u9875\u9762\u4F18\u5148\uFF0C\u6865\u4E0D\u62A2\uFF09
|
|
* 1) \u8FD0\u884C\u65F6\u663E\u5F0F\uFF1Awindow.__wtThemeBridgeManual = true
|
|
* 2) \u6807\u8BB0\uFF1A<html data-wt-theme-mode="manual">
|
|
* 3) \u8001\u5DE5\u4F5C\u53F0\u9875\u517C\u5BB9\uFF1A<html data-wb-theme> \u6216 localStorage['dwb.theme']\uFF08\u65E5\u8BB0\u5DE5\u4F5C\u53F0 / ai\u9012\u5F52\u5B66\u4E60\u7528\u8FD9\u5957\uFF09
|
|
* \u663E\u5F0F\u8DDF\u968F\uFF1A<html data-wt-theme-mode="auto">\uFF08\u6216 <html data-wt-theme-key="\u81EA\u5DF1\u7684\u952E">\uFF09\uFF1D**\u5FFD\u7565**\u4E0A\u9762 3) \u7684
|
|
* legacy \u5224\u5B9A\uFF0C\u5F3A\u5236\u8DDF\u5BBF\u4E3B\u2014\u2014\u540C\u6E90\u9875\u9762\u5171\u7528\u4E00\u4E2A localStorage \u952E\u65F6\uFF0C\u8FD9\u6761\u662F"\u6211\u53EA\u60F3\u8DDF\u5BBF\u4E3B"\u7684\u552F\u4E00\u529E\u6CD5\u3002 */
|
|
function pageManual() {
|
|
try {
|
|
if (window.__wtThemeBridgeManual) return true;
|
|
var el = document.documentElement;
|
|
if (el) {
|
|
var mode = el.getAttribute && el.getAttribute('data-wt-theme-mode');
|
|
if (mode === 'manual') return true;
|
|
if (mode === 'auto' || mode === 'host') return false;
|
|
if (el.hasAttribute && el.hasAttribute('data-wt-theme-key')) return false;
|
|
if (el.hasAttribute && el.hasAttribute('data-wb-theme')) return true;
|
|
}
|
|
var v = null;
|
|
try { v = localStorage.getItem('dwb.theme'); } catch (e) { v = null; }
|
|
if (v === 'dark' || v === 'light') return true;
|
|
} catch (e) { /* \u8BFB\u4E0D\u5230\u5C31\u6309\u975E\u624B\u52A8\u5904\u7406 */ }
|
|
return false;
|
|
}
|
|
var applied = [];
|
|
/** \u6E05\u6389\u6865\u5199\u8FC7\u7684\u5185\u8054 token\uFF1A\u5207\u5230\u624B\u52A8\u4E3B\u9898\u65F6\u5FC5\u987B\u8BA9\u4F4D\u7ED9\u9875\u9762\u81EA\u5DF1\u7684\u6837\u5F0F\u8868\u503C\u3002 */
|
|
function clearApplied() {
|
|
var root = document.documentElement;
|
|
for (var i = 0; i < applied.length; i++) {
|
|
try { root.style.removeProperty(applied[i]); } catch (e) {}
|
|
try { if (document.body) document.body.style.removeProperty(applied[i]); } catch (e) {}
|
|
}
|
|
applied = [];
|
|
}
|
|
function apply() {
|
|
if (pageManual()) { clearApplied(); return; }
|
|
var host = hostWindow();
|
|
var vars = host ? hostVars(host) : [];
|
|
var dark = host ? !!vars.dark : systemDark();
|
|
var root = document.documentElement;
|
|
for (var i = 0; i < vars.length; i++) root.style.setProperty(vars[i][0], vars[i][1]);
|
|
root.style.colorScheme = dark ? 'dark' : 'light';
|
|
if (document.body) {
|
|
for (var j = 0; j < vars.length; j++) document.body.style.setProperty(vars[j][0], vars[j][1]);
|
|
if (dark) document.body.setAttribute('data-ds-dark-theme', '');
|
|
else document.body.removeAttribute('data-ds-dark-theme');
|
|
}
|
|
applied = vars.map(function (p) { return p[0]; });
|
|
}
|
|
apply();
|
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', apply, { once: true });
|
|
// \u9875\u9762\u81EA\u5DF1\u5207\u4E3B\u9898\uFF08data-wb-theme / data-wt-theme-mode\uFF09\u65F6\u7ACB\u523B\u91CD\u65B0\u5224\u5B9A\uFF0C\u522B\u7B49\u8F6E\u8BE2
|
|
try {
|
|
var MO0 = window.MutationObserver;
|
|
if (MO0) new MO0(function () { apply(); }).observe(document.documentElement, { attributes: true, attributeFilter: ['data-wb-theme', 'data-wt-theme-mode'] });
|
|
} catch (e) { /* \u5FFD\u7565 */ }
|
|
var host = hostWindow();
|
|
if (host) {
|
|
try {
|
|
var MO = host.MutationObserver || window.MutationObserver;
|
|
var mo = new MO(function () { apply(); });
|
|
var opts = { attributes: true, attributeFilter: ['style', 'class', 'data-ds-dark-theme'] };
|
|
mo.observe(host.document.documentElement, opts);
|
|
if (host.document.body) mo.observe(host.document.body, opts);
|
|
host.document.addEventListener('DOMContentLoaded', function () { try { mo.observe(host.document.body, opts); } catch (e) {} apply(); });
|
|
} catch (e) { /* \u89C2\u6D4B\u5931\u8D25\u9760\u4E0B\u9762\u7684\u515C\u5E95\u8F6E\u8BE2 */ }
|
|
}
|
|
try {
|
|
var mq = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
|
|
if (mq) { if (mq.addEventListener) mq.addEventListener('change', apply); else if (mq.addListener) mq.addListener(apply); }
|
|
} catch (e) { /* \u5FFD\u7565 */ }
|
|
window.__wtThemeBridgeApply = apply;
|
|
setInterval(apply, 5000); // \u515C\u5E95\uFF1A\u5BBF\u4E3B\u6362\u4E3B\u9898\u4E5F\u53EF\u80FD\u53EA\u6362\u6837\u5F0F\u8868\u3001\u4E0D\u52A8\u5C5E\u6027
|
|
})();`;
|
|
function injectThemeBridge(html, external = false) {
|
|
const src = String(html ?? "");
|
|
if (!src || src.includes(THEME_BRIDGE_ID)) return src;
|
|
const tag = external ? `<script id="${THEME_BRIDGE_ID}" data-wt-theme-bridge src="${THEME_JS_PATH}"></script>` : `<script id="${THEME_BRIDGE_ID}" data-wt-theme-bridge>${THEME_BRIDGE_JS}</script>`;
|
|
const head = /<\/head\s*>/i.exec(src);
|
|
if (head) return src.slice(0, head.index) + tag + src.slice(head.index);
|
|
const body = /<\/body\s*>/i.exec(src);
|
|
if (body) return src.slice(0, body.index) + tag + src.slice(body.index);
|
|
return tag + src;
|
|
}
|
|
|
|
// template/dshell.css
|
|
var dshell_default = `/* dsh-worktable \u539F\u751F\u76AE\u80A4 \xB7 DSH \u8BBE\u8BA1\u7CFB\u7EDF\u7EC4\u4EF6\u5E93
|
|
\u7528\u6CD5\uFF1A<link rel="stylesheet" href="/api/worktable/template/dshell.css">
|
|
\u989C\u8272\u4E00\u5F8B\u8D70 DSH \u4E3B\u9898\u53D8\u91CF\uFF08--dsw-alias-*\uFF09\uFF0C\u81EA\u52A8\u9002\u914D\u660E\u6697\u4E3B\u9898\u3002
|
|
\u4E3B\u9898\u6765\u6E90\u4F18\u5148\u7EA7\uFF1A
|
|
1) \u5DE5\u4F5C\u53F0\u5185\uFF1A\u4E3B\u9898\u6865\uFF08\u7AD9\u70B9\u8DEF\u7531\u81EA\u52A8\u6CE8\u5165\uFF0C\u6216\u663E\u5F0F\u5F15 /api/worktable/template/theme.js\uFF09
|
|
\u628A\u5BBF\u4E3B body \u4E0A\u7684 --dsw-*/--dsh-*/--ds-* \u955C\u50CF\u6210\u9875\u9762\u5185\u8054\u6837\u5F0F \u2192 \u8DDF\u968F DSH \u7684 \u6D45\u8272/\u6DF1\u8272/\u8DDF\u968F\u7CFB\u7EDF\uFF1B
|
|
2) \u72EC\u7ACB\u6253\u5F00\uFF1A\u7528\u4E0B\u9762 :root \u7684\u515C\u5E95\uFF0C\u5E76\u6309\u7CFB\u7EDF\u6DF1\u6D45\u8272\u5207\u6362\u3002
|
|
\u6CE8\u610F\uFF1A\u4E0D\u8981\u5728\u8FD9\u91CC\u5199\u6B7B\u6DF1\u8272\uFF08\u65E7\u7248 :root{color-scheme:dark} \u4F1A\u8BA9\u6240\u6709\u9875\u9762\u9501\u6B7B\u6DF1\u8272\uFF0C
|
|
2026-11 \u4ECE 0.5.x \u7EBF\u6062\u590D\u65F6\u518D\u6B21\u8E29\u5230\uFF0CREQ-20261117-0013 \u4E00\u5E76\u4FEE\u6389\uFF09\u3002 */
|
|
:root {
|
|
color-scheme: light dark;
|
|
--dsw-alias-bg-base: #ffffff;
|
|
--dsw-alias-fill-l1: rgba(16, 24, 40, .03);
|
|
--dsw-alias-border-l1: #e4e7ec;
|
|
--dsw-alias-border-l2: #d0d5dd;
|
|
--dsw-alias-label-primary: #101828;
|
|
--dsw-alias-label-secondary: #475467;
|
|
--dsw-alias-label-tertiary: #98a2b3;
|
|
--dsw-alias-state-accent-primary: #2f6feb;
|
|
}
|
|
@media (prefers-color-scheme: dark) {
|
|
:root {
|
|
--dsw-alias-bg-base: #0b0e14;
|
|
--dsw-alias-fill-l1: rgba(255, 255, 255, .02);
|
|
--dsw-alias-border-l1: #262b36;
|
|
--dsw-alias-border-l2: #3a4150;
|
|
--dsw-alias-label-primary: #e6e8eb;
|
|
--dsw-alias-label-secondary: #9aa4b2;
|
|
--dsw-alias-label-tertiary: #6b7280;
|
|
--dsw-alias-state-accent-primary: #4f8ef7;
|
|
}
|
|
}
|
|
* { box-sizing: border-box; }
|
|
html, body { margin: 0; padding: 0; }
|
|
body {
|
|
background: var(--dsw-alias-bg-base, #0b0e14);
|
|
color: var(--dsw-alias-label-primary, #e6e8eb);
|
|
font-family: var(--dsw-font-family, -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif);
|
|
font-size: 13px;
|
|
line-height: 1.6;
|
|
}
|
|
.dshell { display: flex; flex-direction: column; gap: 12px; padding: 14px 16px; min-height: 100%; }
|
|
/* \u6587\u5B57\u5C42\u7EA7 */
|
|
.dshell-title { margin: 0; font-size: 16px; font-weight: 600; color: var(--dsw-alias-label-primary, #e6e8eb); }
|
|
.dshell-sub { margin: 0; font-size: 12px; color: var(--dsw-alias-label-secondary, #9aa4b2); }
|
|
.dshell-muted { color: var(--dsw-alias-label-tertiary, #6b7280); font-size: 11.5px; }
|
|
/* \u5361\u7247 */
|
|
.dshell-card { border: 1px solid var(--dsw-alias-border-l1, #262b36); border-radius: 10px; background: var(--dsw-alias-fill-l1, rgba(255,255,255,.02)); padding: 12px 14px; }
|
|
.dshell-card + .dshell-card { margin-top: 10px; }
|
|
/* \u6309\u94AE\uFF08\u7EFF\u8272\u4E3B\u6309\u94AE / \u5E7D\u7075\u6309\u94AE / \u5371\u9669\uFF09 */
|
|
.dshell-btn { display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border-radius: 999px; border: 1px solid transparent; background: #3fb950; color: #0b0e14; font: inherit; font-size: 12.5px; font-weight: 600; cursor: pointer; }
|
|
.dshell-btn:hover { filter: brightness(1.08); }
|
|
.dshell-btnGhost { background: transparent; border-color: var(--dsw-alias-border-l1, #262b36); color: var(--dsw-alias-label-secondary, #9aa4b2); }
|
|
.dshell-btnGhost:hover { color: var(--dsw-alias-label-primary, #e6e8eb); border-color: var(--dsw-alias-border-l2, #3a4150); }
|
|
.dshell-btnDanger { background: transparent; border-color: #f85149; color: #f85149; }
|
|
/* \u72B6\u6001\u5FBD\u6807\uFF08\u5706\u70B9 + \u6587\u5B57\uFF1B\u7EFF=\u5DF2\u5B8C\u6210 \u9EC4=\u5F85\u529E/\u5F85\u53D1\u5E03 \u7070=\u672A\u5F00\u59CB\uFF09 */
|
|
.dshell-badge { display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px; border-radius: 999px; border: 1px solid var(--dsw-alias-border-l1, #262b36); font-size: 11.5px; color: var(--dsw-alias-label-secondary, #9aa4b2); background: var(--dsw-alias-fill-l1, rgba(255,255,255,.03)); }
|
|
.dshell-badge::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--dsw-alias-label-tertiary, #6b7280); }
|
|
.dshell-badgeDone { color: #3fb950; border-color: rgba(63,185,80,.4); }
|
|
.dshell-badgeDone::before { background: #3fb950; box-shadow: 0 0 5px #3fb950; }
|
|
.dshell-badgeWait { color: #d29922; border-color: rgba(210,153,34,.4); }
|
|
.dshell-badgeWait::before { background: #d29922; box-shadow: 0 0 5px #d29922; }
|
|
.dshell-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--dsw-alias-label-tertiary, #6b7280); }
|
|
.dshell-dotDone { background: #3fb950; box-shadow: 0 0 5px #3fb950; }
|
|
.dshell-dotWait { background: #d29922; box-shadow: 0 0 5px #d29922; }
|
|
/* \u6807\u7B7E\u9875 */
|
|
.dshell-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--dsw-alias-border-l1, #262b36); }
|
|
.dshell-tab { padding: 7px 12px; font-size: 12.5px; color: var(--dsw-alias-label-secondary, #9aa4b2); cursor: pointer; border: none; background: none; font: inherit; border-bottom: 2px solid transparent; margin-bottom: -1px; }
|
|
.dshell-tabOn { color: var(--dsw-alias-label-primary, #e6e8eb); border-bottom-color: var(--dsw-alias-state-accent-primary, #4f8ef7); }
|
|
/* \u5217\u8868 */
|
|
.dshell-list { display: flex; flex-direction: column; gap: 6px; }
|
|
.dshell-listItem { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 8px 12px; border: 1px solid var(--dsw-alias-border-l1, #262b36); border-radius: 8px; background: var(--dsw-alias-fill-l1, rgba(255,255,255,.02)); cursor: pointer; }
|
|
.dshell-listItem:hover { border-color: var(--dsw-alias-border-l2, #3a4150); background: var(--dsw-alias-fill-l1, rgba(255,255,255,.05)); }
|
|
.dshell-listItemTitle { font-size: 12.5px; color: var(--dsw-alias-label-primary, #e6e8eb); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
.dshell-listItemMeta { flex: none; font-size: 11px; color: var(--dsw-alias-label-tertiary, #6b7280); }
|
|
/* \u7F51\u683C / \u7EDF\u8BA1 */
|
|
.dshell-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }
|
|
.dshell-stat { padding: 10px 12px; border: 1px solid var(--dsw-alias-border-l1, #262b36); border-radius: 10px; background: var(--dsw-alias-fill-l1, rgba(255,255,255,.02)); }
|
|
.dshell-statLabel { font-size: 11px; color: var(--dsw-alias-label-secondary, #9aa4b2); }
|
|
.dshell-statValue { font-size: 20px; font-weight: 600; color: var(--dsw-alias-label-primary, #e6e8eb); }
|
|
.dshell-statDelta { font-size: 11px; color: #3fb950; }
|
|
/* \u8FDB\u5EA6\u6761 */
|
|
.dshell-progress { height: 6px; border-radius: 3px; background: var(--dsw-alias-fill-l1, rgba(255,255,255,.06)); overflow: hidden; }
|
|
.dshell-progressBar { height: 100%; border-radius: 3px; background: #3fb950; }
|
|
/* \u8F93\u5165 */
|
|
.dshell-input, .dshell-textarea { width: 100%; padding: 7px 10px; border: 1px solid var(--dsw-alias-border-l1, #262b36); border-radius: 8px; background: var(--dsw-alias-fill-l1, rgba(255,255,255,.03)); color: var(--dsw-alias-label-primary, #e6e8eb); font: inherit; font-size: 12.5px; outline: none; }
|
|
.dshell-input:focus, .dshell-textarea:focus { border-color: var(--dsw-alias-state-accent-primary, #4f8ef7); }
|
|
/* \u8868\u683C */
|
|
.dshell-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
|
.dshell-table th, .dshell-table td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--dsw-alias-border-l1, #262b36); }
|
|
.dshell-table th { color: var(--dsw-alias-label-secondary, #9aa4b2); font-weight: 500; }
|
|
/* \u952E\u503C\u5BF9 */
|
|
.dshell-kv { display: flex; flex-direction: column; gap: 6px; }
|
|
.dshell-kvRow { display: flex; justify-content: space-between; gap: 10px; font-size: 12px; }
|
|
.dshell-kvKey { color: var(--dsw-alias-label-secondary, #9aa4b2); }
|
|
.dshell-kvValue { color: var(--dsw-alias-label-primary, #e6e8eb); text-align: right; }
|
|
/* \u5206\u5272\u7EBF */
|
|
.dshell-divider { height: 1px; background: var(--dsw-alias-border-l1, #262b36); margin: 6px 0; }
|
|
/* \u6EDA\u52A8\u6761 */
|
|
::-webkit-scrollbar { width: 10px; height: 10px; }
|
|
::-webkit-scrollbar-thumb { background: rgba(255,255,255,.14); border-radius: 5px; }
|
|
::-webkit-scrollbar-track { background: transparent; }
|
|
`;
|
|
|
|
// template/dshell.html
|
|
var dshell_default2 = '<!doctype html>\n<!-- dsh-worktable \u539F\u751F\u76AE\u80A4\u6A21\u677F\uFF1A\u65B0\u9875\u9762\u4EE5\u6B64\u4E3A\u57FA\u7840\uFF0C\u66FF\u6362\u4E0B\u9762\u793A\u4F8B\u5185\u5BB9\u5373\u53EF\u3002\n \u6837\u5F0F\u8868\u7531\u63D2\u4EF6\u63D0\u4F9B\uFF08\u968F\u4E3B\u9898\u81EA\u52A8\u9002\u914D\uFF09\uFF0C\u4E0D\u8981\u590D\u5236\u6216\u6539\u5199\u5B83\u3002 -->\n<html lang="zh-CN">\n<head>\n <!-- \u4E3B\u9898\u8DDF\u968F\uFF1A\u7AD9\u70B9\u8DEF\u7531\uFF08/api/worktable/site/**\uFF09\u5DF2\u81EA\u52A8\u6CE8\u5165\u4E3B\u9898\u6865\uFF0C\u65E0\u9700\u624B\u5199\uFF1B\n \u72EC\u7ACB\u6253\u5F00 / \u5D4C\u5957 iframe \u65F6\u663E\u5F0F\u5F15\u5165\u4E0B\u9762\u8FD9\u4E00\u884C\u5373\u53EF\uFF1A\n <script src="/api/worktable/template/theme.js"></script> -->\n <meta charset="utf-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1" />\n <title>\u6211\u7684\u7A97\u53E3</title>\n <link rel="stylesheet" href="/api/worktable/template/dshell.css" />\n</head>\n<body>\n <div class="dshell">\n <!-- \u6807\u9898\u533A -->\n <h1 class="dshell-title">\u7A97\u53E3\u6807\u9898</h1>\n <p class="dshell-sub">\u4E00\u53E5\u8BDD\u8BF4\u660E\u8FD9\u4E2A\u7A97\u53E3\u505A\u4EC0\u4E48\u3002</p>\n\n <!-- \u72B6\u6001\u5FBD\u6807\uFF1A\u5DF2\u5B8C\u6210 dshell-badgeDone / \u8FDB\u884C\u4E2D dshell-badgeWait / \u9ED8\u8BA4 -->\n <div>\n <span class="dshell-badge dshell-badgeDone">\u5DF2\u5B8C\u6210</span>\n <span class="dshell-badge dshell-badgeWait">\u8FDB\u884C\u4E2D</span>\n <span class="dshell-badge">\u672A\u5F00\u59CB</span>\n </div>\n\n <!-- \u6807\u7B7E\u9875 -->\n <div class="dshell-tabs">\n <button class="dshell-tab dshell-tabOn">\u6982\u89C8</button>\n <button class="dshell-tab">\u8BE6\u60C5</button>\n <button class="dshell-tab">\u8BBE\u7F6E</button>\n </div>\n\n <!-- \u7EDF\u8BA1\u5361\u7247\u7F51\u683C -->\n <div class="dshell-grid">\n <div class="dshell-stat">\n <div class="dshell-statLabel">\u603B\u6570</div>\n <div class="dshell-statValue">128</div>\n <div class="dshell-statDelta">+12.4%</div>\n </div>\n <div class="dshell-stat">\n <div class="dshell-statLabel">\u8FDB\u884C\u4E2D</div>\n <div class="dshell-statValue">7</div>\n </div>\n <div class="dshell-stat">\n <div class="dshell-statLabel">\u5DF2\u5B8C\u6210</div>\n <div class="dshell-statValue">121</div>\n </div>\n </div>\n\n <!-- \u5217\u8868 -->\n <div class="dshell-list">\n <div class="dshell-listItem">\n <span class="dshell-listItemTitle">\u6761\u76EE\u4E00\uFF1A\u793A\u4F8B\u5185\u5BB9\u6807\u9898</span>\n <span class="dshell-listItemMeta">\u6628\u5929</span>\n </div>\n <div class="dshell-listItem">\n <span class="dshell-listItemTitle">\u6761\u76EE\u4E8C\uFF1A\u793A\u4F8B\u5185\u5BB9\u6807\u9898</span>\n <span class="dshell-badge dshell-badgeDone">\u5DF2\u53D1\u5E03</span>\n </div>\n </div>\n\n <!-- \u5361\u7247 + \u952E\u503C\u5BF9 -->\n <div class="dshell-card">\n <h2 class="dshell-sub" style="margin:0 0 8px">\u8BE6\u60C5</h2>\n <div class="dshell-kv">\n <div class="dshell-kvRow"><span class="dshell-kvKey">\u5B57\u6BB5 A</span><span class="dshell-kvValue">\u503C A</span></div>\n <div class="dshell-kvRow"><span class="dshell-kvKey">\u5B57\u6BB5 B</span><span class="dshell-kvValue">\u503C B</span></div>\n </div>\n <div class="dshell-divider"></div>\n <div class="dshell-progress"><div class="dshell-progressBar" style="width:72%"></div></div>\n </div>\n\n <!-- \u64CD\u4F5C\u533A -->\n <div style="display:flex;gap:8px">\n <button class="dshell-btn">\u4E3B\u8981\u64CD\u4F5C</button>\n <button class="dshell-btn dshell-btnGhost">\u6B21\u8981\u64CD\u4F5C</button>\n </div>\n </div>\n</body>\n</html>\n';
|
|
|
|
// src/index.ts
|
|
function baseDshHome() {
|
|
const env = process.env.DSH_HOME;
|
|
const value = env !== void 0 && env.trim().length > 0 ? env : pathResolve(homedir(), ".dsh");
|
|
if (value === "~") return homedir();
|
|
if (value.startsWith("~/") || value.startsWith("~\\")) return pathResolve(homedir(), value.slice(2));
|
|
return pathResolve(value);
|
|
}
|
|
var cachedDshHome = null;
|
|
var dshHomeSource = "fallback";
|
|
function resolveDshHomeSafe() {
|
|
if (cachedDshHome) return cachedDshHome;
|
|
try {
|
|
const pkg = loadPkg("@deepseek-ai/dsh-home-paths");
|
|
if (pkg && typeof pkg.resolveDshHome === "function") {
|
|
const home = pkg.resolveDshHome(void 0, process.env);
|
|
if (typeof home === "string" && home.trim() !== "") {
|
|
dshHomeSource = "official";
|
|
cachedDshHome = home;
|
|
return cachedDshHome;
|
|
}
|
|
}
|
|
} catch {
|
|
}
|
|
dshHomeSource = "fallback";
|
|
cachedDshHome = baseDshHome();
|
|
return cachedDshHome;
|
|
}
|
|
var PLUGIN_VERSION = false ? "dev" : "0.5.3-local.4";
|
|
var name = "dsh-worktable";
|
|
var inject = ["webServer", "sessions"];
|
|
var HEALTH_PATH = "/api/worktable/health";
|
|
var MAX_ENTRIES = 500;
|
|
var FILE_TYPES = {
|
|
html: "text/html; charset=utf-8",
|
|
htm: "text/html; charset=utf-8",
|
|
css: "text/css; charset=utf-8",
|
|
js: "text/javascript; charset=utf-8",
|
|
mjs: "text/javascript; charset=utf-8",
|
|
json: "application/json; charset=utf-8",
|
|
map: "application/json; charset=utf-8",
|
|
md: "text/markdown; charset=utf-8",
|
|
markdown: "text/markdown; charset=utf-8",
|
|
txt: "text/plain; charset=utf-8",
|
|
log: "text/plain; charset=utf-8",
|
|
pdf: "application/pdf",
|
|
svg: "image/svg+xml",
|
|
png: "image/png",
|
|
jpg: "image/jpeg",
|
|
jpeg: "image/jpeg",
|
|
gif: "image/gif",
|
|
webp: "image/webp",
|
|
bmp: "image/bmp",
|
|
ico: "image/x-icon",
|
|
avif: "image/avif",
|
|
woff: "font/woff",
|
|
woff2: "font/woff2",
|
|
ttf: "font/ttf",
|
|
otf: "font/otf",
|
|
wasm: "application/wasm",
|
|
mp3: "audio/mpeg",
|
|
mp4: "video/mp4",
|
|
webm: "video/webm"
|
|
};
|
|
var SITE_PREFIX = "/api/worktable/site";
|
|
var TEMPLATE_PREFIX = "/api/worktable/template";
|
|
var loadProbeAttempts = 0;
|
|
function loadPkg(pkg) {
|
|
const starts = /* @__PURE__ */ new Set();
|
|
try {
|
|
starts.add(dirname(fileURLToPath(import.meta.url)));
|
|
} catch {
|
|
}
|
|
try {
|
|
starts.add(realpathSync(dirname(fileURLToPath(import.meta.url))));
|
|
} catch {
|
|
}
|
|
for (const start of starts) {
|
|
let dir = start;
|
|
while (dir && dir !== pathResolve(dir, "..")) {
|
|
loadProbeAttempts++;
|
|
try {
|
|
const req = createRequire(pathToFileURL(pathResolve(dir, "__wt_probe__.js")).href);
|
|
return req(pkg);
|
|
} catch {
|
|
}
|
|
dir = pathResolve(dir, "..");
|
|
}
|
|
}
|
|
try {
|
|
const profilesDir = pathResolve(baseDshHome(), "profiles");
|
|
for (const profile of readdirSync(profilesDir, { withFileTypes: true })) {
|
|
if (!profile.isDirectory() && !profile.isSymbolicLink()) continue;
|
|
const nm = pathResolve(profilesDir, profile.name, "node_modules");
|
|
loadProbeAttempts++;
|
|
try {
|
|
const req = createRequire(pathToFileURL(pathResolve(nm, "__wt_probe__.js")).href);
|
|
return req(pkg);
|
|
} catch {
|
|
}
|
|
}
|
|
} catch {
|
|
}
|
|
return null;
|
|
}
|
|
function __wtLoadProbeStats() {
|
|
return { attempts: loadProbeAttempts, homeSource: dshHomeSource };
|
|
}
|
|
function serverCwd(ctx, sessionId, clientCwd) {
|
|
if (sessionId) {
|
|
try {
|
|
const headerCwd = ctx.sessions?.get?.(sessionId)?.header?.cwd;
|
|
if (typeof headerCwd === "string" && headerCwd) return headerCwd;
|
|
} catch {
|
|
}
|
|
}
|
|
if (typeof clientCwd === "string" && clientCwd) return clientCwd;
|
|
return process.cwd();
|
|
}
|
|
function json(res, status, body) {
|
|
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
res.end(JSON.stringify(body));
|
|
}
|
|
async function readJsonBody(req) {
|
|
const chunks = [];
|
|
let bytes = 0;
|
|
for await (const chunk of req) {
|
|
const data = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
bytes += data.length;
|
|
if (bytes > 22 * 1024 * 1024) throw Object.assign(new Error("request too large"), { status: 413 });
|
|
chunks.push(data);
|
|
}
|
|
const text = Buffer.concat(chunks).toString("utf8");
|
|
if (!text) return {};
|
|
try {
|
|
return JSON.parse(text);
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
async function listDirectory(path) {
|
|
const abs = pathResolve(path);
|
|
const dirents = await readdir(abs, { withFileTypes: true });
|
|
const entries = dirents.map((d) => ({ name: d.name, path: abs + sep2 + d.name, isDir: d.isDirectory(), hidden: d.name.startsWith(".") })).sort((a, b) => {
|
|
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
|
|
return a.name.localeCompare(b.name, void 0, { sensitivity: "base" });
|
|
});
|
|
const truncated = entries.length > MAX_ENTRIES;
|
|
return { path: abs, entries: truncated ? entries.slice(0, MAX_ENTRIES) : entries, truncated };
|
|
}
|
|
function gitExec(args, cwd) {
|
|
return new Promise((resolvePromise, reject) => {
|
|
execFile("git", args, { cwd, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
|
|
if (err) reject(err);
|
|
else resolvePromise(stdout);
|
|
});
|
|
});
|
|
}
|
|
async function gitStatus(cwd) {
|
|
try {
|
|
const branchRaw = await gitExec(["rev-parse", "--abbrev-ref", "HEAD"], cwd);
|
|
const porcelain = await gitExec(["status", "--porcelain=v1", "-z"], cwd);
|
|
const entries = porcelain.split("\0").filter((s) => s.length > 2).map((s) => ({ xy: s.slice(0, 2), path: s.slice(3) }));
|
|
return { isRepo: true, branch: branchRaw.trim() || "HEAD", entries };
|
|
} catch {
|
|
return { isRepo: false, branch: void 0, entries: [] };
|
|
}
|
|
}
|
|
function setupTerminal(webServer, ctx) {
|
|
if (typeof webServer.registerUpgrade !== "function") return;
|
|
const wsMod = loadPkg("ws");
|
|
const ptyMod = loadPkg("node-pty");
|
|
ctx.logger?.info?.("[dsh-worktable] term deps: ws=" + (wsMod ? "ok" : "MISSING") + " node-pty=" + (ptyMod ? "ok" : "MISSING"));
|
|
if (!wsMod || !ptyMod) {
|
|
ctx.logger?.warn("[dsh-worktable] \u7EC8\u7AEF\u8DEF\u7531\u672A\u6CE8\u518C\uFF1Aws/node-pty \u4E0D\u53EF\u7528");
|
|
return;
|
|
}
|
|
const WebSocketServer = wsMod.WebSocketServer ?? wsMod.default?.WebSocketServer;
|
|
if (!WebSocketServer) return;
|
|
const pty = ptyMod.default ?? ptyMod;
|
|
const wss = new WebSocketServer({ noServer: true });
|
|
let disposed = false;
|
|
const terminals = /* @__PURE__ */ new Set();
|
|
ctx.effect(() => () => {
|
|
disposed = true;
|
|
for (const ws of wss.clients ?? []) {
|
|
try {
|
|
ws.terminate();
|
|
} catch {
|
|
}
|
|
}
|
|
for (const term of terminals) {
|
|
try {
|
|
term.kill();
|
|
} catch {
|
|
}
|
|
}
|
|
terminals.clear();
|
|
try {
|
|
wss.close();
|
|
} catch {
|
|
}
|
|
}, "dsh-worktable: terminal sessions");
|
|
const spawnShell = () => process.platform === "win32" ? { cmd: "powershell.exe", args: ["-NoLogo", "-NoProfile"] } : { cmd: process.env.SHELL || "/bin/bash", args: [] };
|
|
const clampDim = (v, fallback) => Math.min(1024, Math.max(2, Number.isFinite(v) ? v : fallback));
|
|
ctx.effect(() => webServer.registerUpgrade({
|
|
path: "/api/worktable/term",
|
|
handler: async (req, socket, head) => {
|
|
let rejected = await requestRejection(ctx, req);
|
|
if (disposed) rejected = 503;
|
|
if (rejected !== void 0) {
|
|
socket.end(`HTTP/1.1 ${rejected} ${rejectionText(rejected)}\r
|
|
Connection: close\r
|
|
Content-Length: 0\r
|
|
\r
|
|
`);
|
|
return;
|
|
}
|
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
const u = new URL(req.url ?? "/", "http://dsh.internal");
|
|
const cwd = serverCwd(ctx, u.searchParams.get("sessionId") || void 0, u.searchParams.get("cwd") || void 0);
|
|
const cols = clampDim(Number(u.searchParams.get("cols")), 80);
|
|
const rows = clampDim(Number(u.searchParams.get("rows")), 24);
|
|
let term = null;
|
|
try {
|
|
const shell = spawnShell();
|
|
term = pty.spawn(shell.cmd, shell.args, { name: "xterm-256color", cols, rows, cwd, env: process.env });
|
|
terminals.add(term);
|
|
} catch (err) {
|
|
try {
|
|
ws.send("\r\n[worktable] \u7EC8\u7AEF\u542F\u52A8\u5931\u8D25\uFF1A" + String(err));
|
|
} catch {
|
|
}
|
|
try {
|
|
ws.close();
|
|
} catch {
|
|
}
|
|
return;
|
|
}
|
|
term.onData((d) => {
|
|
try {
|
|
ws.send(d);
|
|
} catch {
|
|
}
|
|
});
|
|
term.onExit(() => {
|
|
terminals.delete(term);
|
|
try {
|
|
ws.close();
|
|
} catch {
|
|
}
|
|
});
|
|
ws.on("message", (raw) => {
|
|
const text = String(raw);
|
|
try {
|
|
const msg = JSON.parse(text);
|
|
if (msg && msg.type === "resize" && Number.isFinite(msg.cols) && Number.isFinite(msg.rows)) {
|
|
term.resize(clampDim(msg.cols, cols), clampDim(msg.rows, rows));
|
|
return;
|
|
}
|
|
} catch {
|
|
}
|
|
try {
|
|
term.write(text);
|
|
} catch {
|
|
}
|
|
});
|
|
ws.on("close", () => {
|
|
terminals.delete(term);
|
|
try {
|
|
term.kill();
|
|
} catch {
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}), "dsh-worktable: terminal upgrade");
|
|
}
|
|
function apply(ctx) {
|
|
const webServer = ctx.webServer;
|
|
if (!webServer) {
|
|
ctx.logger?.warn("[dsh-worktable] ctx.webServer \u4E0D\u53EF\u7528\uFF08headless profile\uFF1F\uFF09\uFF0C\u8DF3\u8FC7\u670D\u52A1\u7AEF\u8DEF\u7531");
|
|
return;
|
|
}
|
|
const previews = createPreviewFiles();
|
|
ctx.effect(() => () => previews.clear(), "dsh-worktable: preview capabilities");
|
|
const stateLog = (line) => {
|
|
void (async () => {
|
|
try {
|
|
const fsx = await import("node:fs/promises");
|
|
const dir = pathResolve(resolveDshHomeSafe(), "logs");
|
|
await fsx.mkdir(dir, { recursive: true });
|
|
await fsx.appendFile(pathResolve(dir, "worktable-state.log"), (/* @__PURE__ */ new Date()).toISOString() + " " + line + "\n", "utf8");
|
|
} catch {
|
|
}
|
|
})();
|
|
};
|
|
const register = (route, publicAsset = false) => ctx.effect(() => webServer.register({
|
|
...route,
|
|
handler: async (req, res) => {
|
|
if (!publicAsset && route.path !== HEALTH_PATH) {
|
|
const rejected = await requestRejection(ctx, req);
|
|
if (rejected !== void 0) {
|
|
if (route.path === "/api/worktable/state") stateLog("REJECT " + req.method + " -> " + rejected);
|
|
json(res, rejected, { error: rejectionText(rejected) });
|
|
return;
|
|
}
|
|
}
|
|
return route.handler(req, res);
|
|
}
|
|
}), "dsh-worktable: " + route.path);
|
|
register({
|
|
kind: "exact",
|
|
path: "/api/worktable/preview",
|
|
handler: async (req, res) => {
|
|
if (req.method !== "POST") {
|
|
json(res, 405, { error: "method not allowed" });
|
|
return;
|
|
}
|
|
try {
|
|
const body = await readJsonBody(req);
|
|
if (typeof body.revoke === "string") {
|
|
previews.revoke(body.revoke);
|
|
json(res, 200, { ok: true });
|
|
return;
|
|
}
|
|
if (typeof body.root !== "string") {
|
|
json(res, 400, { error: "missing root" });
|
|
return;
|
|
}
|
|
const token = await previews.mount(body.root);
|
|
json(res, 200, { token, base: PREVIEW_PREFIX + "/" + token + "/" });
|
|
} catch (err) {
|
|
json(res, err.status ?? 400, { error: String(err) });
|
|
}
|
|
}
|
|
});
|
|
register({
|
|
kind: "prefix",
|
|
path: PREVIEW_PREFIX,
|
|
handler: async (req, res) => {
|
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
json(res, 405, { error: "method not allowed" });
|
|
return;
|
|
}
|
|
try {
|
|
const parts = new URL(req.url ?? "/", "http://dsh.internal").pathname.slice(PREVIEW_PREFIX.length + 1).split("/").map(decodeURIComponent);
|
|
const file = await previews.file(parts.shift() ?? "", parts.filter(Boolean), req.method === "HEAD");
|
|
if (!file) {
|
|
json(res, 404, { error: "preview unavailable; refresh to reopen" });
|
|
return;
|
|
}
|
|
const ext = (file.path.split(".").pop() || "").toLowerCase();
|
|
res.writeHead(200, {
|
|
"content-type": FILE_TYPES[ext] ?? "application/octet-stream",
|
|
"cache-control": "no-store",
|
|
"referrer-policy": "no-referrer",
|
|
"content-security-policy": PREVIEW_CSP,
|
|
"x-content-type-options": "nosniff",
|
|
"access-control-allow-origin": "*"
|
|
});
|
|
res.end(file.data);
|
|
} catch (err) {
|
|
json(res, err?.status === 413 ? 413 : 404, { error: err?.status === 413 ? "file too large" : "preview unavailable" });
|
|
}
|
|
}
|
|
}, true);
|
|
register({
|
|
kind: "exact",
|
|
path: HEALTH_PATH,
|
|
handler: (_req, res) => {
|
|
json(res, 200, { plugin: "dsh-worktable", version: PLUGIN_VERSION, ok: true });
|
|
}
|
|
});
|
|
register({
|
|
kind: "exact",
|
|
path: "/api/worktable/file",
|
|
handler: async (req, res) => {
|
|
try {
|
|
const u = new URL(req.url ?? "/", "http://dsh.internal");
|
|
const p = u.searchParams.get("path") || "";
|
|
if (!p) {
|
|
json(res, 400, { error: "missing path" });
|
|
return;
|
|
}
|
|
const abs = pathResolve(p);
|
|
const stat2 = await import("node:fs/promises").then((m) => m.stat(abs));
|
|
if (stat2.size > 20 * 1024 * 1024) {
|
|
json(res, 413, { error: "file too large" });
|
|
return;
|
|
}
|
|
const data = await readFile(abs);
|
|
const ext = (abs.split(".").pop() || "").toLowerCase();
|
|
const types = {
|
|
html: "text/html; charset=utf-8",
|
|
htm: "text/html; charset=utf-8",
|
|
css: "text/css; charset=utf-8",
|
|
js: "text/javascript; charset=utf-8",
|
|
mjs: "text/javascript; charset=utf-8",
|
|
json: "application/json; charset=utf-8",
|
|
md: "text/markdown; charset=utf-8",
|
|
markdown: "text/markdown; charset=utf-8",
|
|
txt: "text/plain; charset=utf-8",
|
|
log: "text/plain; charset=utf-8",
|
|
pdf: "application/pdf",
|
|
svg: "image/svg+xml",
|
|
png: "image/png",
|
|
jpg: "image/jpeg",
|
|
jpeg: "image/jpeg",
|
|
gif: "image/gif",
|
|
webp: "image/webp",
|
|
bmp: "image/bmp",
|
|
ico: "image/x-icon"
|
|
};
|
|
res.writeHead(200, {
|
|
"content-type": FILE_TYPES[ext] ?? "application/octet-stream",
|
|
"cache-control": "no-store",
|
|
"x-content-type-options": "nosniff",
|
|
.../^(html?|svg)$/.test(ext) ? { "content-security-policy": PREVIEW_CSP, "referrer-policy": "no-referrer" } : {}
|
|
});
|
|
res.end(data);
|
|
} catch (err) {
|
|
json(res, 404, { error: String(err) });
|
|
}
|
|
}
|
|
});
|
|
register({
|
|
kind: "prefix",
|
|
path: TEMPLATE_PREFIX,
|
|
handler: (req, res) => {
|
|
try {
|
|
if (req.method !== "GET") {
|
|
res.writeHead(405);
|
|
res.end();
|
|
return;
|
|
}
|
|
const pathname = new URL(req.url ?? "/", "http://dsh.internal").pathname;
|
|
const rel = pathname.slice(TEMPLATE_PREFIX.length);
|
|
if (rel === "/dshell.css") {
|
|
res.writeHead(200, { "content-type": "text/css; charset=utf-8", "cache-control": "no-store" });
|
|
res.end(dshell_default);
|
|
} else if (rel === "/theme.js") {
|
|
res.writeHead(200, { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-store" });
|
|
res.end(THEME_BRIDGE_JS);
|
|
} else {
|
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
res.end(dshell_default2);
|
|
}
|
|
} catch (err) {
|
|
res.writeHead(404);
|
|
res.end(String(err));
|
|
}
|
|
}
|
|
});
|
|
register({
|
|
kind: "prefix",
|
|
path: SITE_PREFIX,
|
|
handler: async (req, res) => {
|
|
try {
|
|
if (req.method !== "GET") {
|
|
res.writeHead(405);
|
|
res.end();
|
|
return;
|
|
}
|
|
const pathname = new URL(req.url ?? "/", "http://dsh.internal").pathname;
|
|
const segs = pathname.slice(SITE_PREFIX.length).split("/").filter(Boolean);
|
|
const rootToken = decodeURIComponent(segs.shift() ?? "");
|
|
const rel = segs.map((s) => {
|
|
try {
|
|
return decodeURIComponent(s);
|
|
} catch {
|
|
return s;
|
|
}
|
|
}).join("/");
|
|
if (!rootToken) {
|
|
json(res, 400, { error: "missing root" });
|
|
return;
|
|
}
|
|
const root = pathResolve(rootToken);
|
|
let abs = pathResolve(root, rel);
|
|
if (abs !== root && !abs.startsWith(root + sep2)) {
|
|
json(res, 403, { error: "outside root" });
|
|
return;
|
|
}
|
|
const statMod = await import("node:fs/promises");
|
|
let info = await statMod.stat(abs).catch(() => null);
|
|
if (info && info.isDirectory()) {
|
|
abs = pathResolve(abs, "index.html");
|
|
info = await statMod.stat(abs).catch(() => null);
|
|
}
|
|
if (!info || !info.isFile()) {
|
|
json(res, 404, { error: "not found" });
|
|
return;
|
|
}
|
|
if (info.size > 40 * 1024 * 1024) {
|
|
json(res, 413, { error: "file too large" });
|
|
return;
|
|
}
|
|
const data = await readFile(abs);
|
|
const ext = (abs.split(".").pop() || "").toLowerCase();
|
|
res.writeHead(200, {
|
|
"content-type": FILE_TYPES[ext] ?? "application/octet-stream",
|
|
"cache-control": "no-store",
|
|
"content-security-policy": PREVIEW_CSP,
|
|
"referrer-policy": "no-referrer",
|
|
"x-content-type-options": "nosniff"
|
|
});
|
|
res.end(ext === "html" || ext === "htm" ? Buffer.from(injectThemeBridge(data.toString("utf8")), "utf8") : data);
|
|
} catch (err) {
|
|
json(res, 404, { error: String(err) });
|
|
}
|
|
}
|
|
});
|
|
register({
|
|
kind: "exact",
|
|
path: "/api/worktable/fs",
|
|
handler: async (req, res) => {
|
|
try {
|
|
const body = await readJsonBody(req);
|
|
const path = typeof body.path === "string" && body.path ? body.path : serverCwd(ctx, body.sessionId, body.cwd);
|
|
json(res, 200, await listDirectory(path));
|
|
} catch (err) {
|
|
json(res, err.status ?? 500, { path: "", entries: [], truncated: false, error: String(err) });
|
|
}
|
|
}
|
|
});
|
|
register({
|
|
kind: "exact",
|
|
path: "/api/worktable/workspaces",
|
|
handler: async (_req, res) => {
|
|
try {
|
|
let registry = null;
|
|
try {
|
|
registry = ctx.workspaceRegistry ?? null;
|
|
} catch {
|
|
}
|
|
if (!registry) {
|
|
try {
|
|
registry = ctx.get?.("workspaceRegistry") ?? null;
|
|
} catch {
|
|
}
|
|
}
|
|
if (registry && typeof registry.list === "function") {
|
|
const list = registry.list() ?? [];
|
|
const workspaceIds = [];
|
|
const tables = {};
|
|
for (const ws of list) {
|
|
const id = String(ws?.id ?? "");
|
|
if (!id) continue;
|
|
workspaceIds.push(id);
|
|
tables[id] = {
|
|
title: typeof ws?.title === "string" ? ws.title : void 0,
|
|
sessionIds: Array.isArray(ws?.sessionIds) ? ws.sessionIds.map(String) : []
|
|
};
|
|
}
|
|
let archived = [];
|
|
try {
|
|
archived = (registry.archivedSessionIds ?? []).map(String);
|
|
} catch {
|
|
}
|
|
json(res, 200, {
|
|
unit: { name: "workspace", version: 2 },
|
|
global: { initialized: true, workspaceIds, archivedSessionIds: archived },
|
|
tables: { workspaces: tables }
|
|
});
|
|
return;
|
|
}
|
|
const file = pathResolve(resolveDshHomeSafe(), "storages", "workspace.json");
|
|
const raw = await readFile(file, "utf8");
|
|
json(res, 200, JSON.parse(raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw));
|
|
} catch (err) {
|
|
json(res, 404, { error: String(err) });
|
|
}
|
|
}
|
|
});
|
|
register({
|
|
kind: "exact",
|
|
path: "/api/worktable/write",
|
|
handler: async (req, res) => {
|
|
try {
|
|
if (req.method !== "POST") {
|
|
res.writeHead(405);
|
|
res.end();
|
|
return;
|
|
}
|
|
const body = await readJsonBody(req);
|
|
const p = typeof body.path === "string" ? body.path : "";
|
|
const content = typeof body.content === "string" ? body.content : "";
|
|
if (!p) {
|
|
json(res, 400, { error: "missing path" });
|
|
return;
|
|
}
|
|
if (content.length > 20 * 1024 * 1024) {
|
|
json(res, 413, { error: "content too large" });
|
|
return;
|
|
}
|
|
const abs = pathResolve(p);
|
|
await import("node:fs/promises").then((m) => m.writeFile(abs, content, "utf8"));
|
|
json(res, 200, { ok: true });
|
|
} catch (err) {
|
|
json(res, err.status ?? 500, { error: String(err) });
|
|
}
|
|
}
|
|
});
|
|
register({
|
|
kind: "exact",
|
|
path: "/api/worktable/mkdir",
|
|
handler: async (req, res) => {
|
|
try {
|
|
if (req.method !== "POST") {
|
|
res.writeHead(405);
|
|
res.end();
|
|
return;
|
|
}
|
|
const body = await readJsonBody(req);
|
|
const p = typeof body.path === "string" ? body.path.trim() : "";
|
|
if (!p) {
|
|
json(res, 400, { error: "missing path" });
|
|
return;
|
|
}
|
|
const abs = pathResolve(p);
|
|
const fsx = await import("node:fs/promises");
|
|
const parent = dirname(abs);
|
|
try {
|
|
await fsx.access(parent);
|
|
} catch {
|
|
json(res, 400, { error: "parent not found" });
|
|
return;
|
|
}
|
|
await fsx.mkdir(abs);
|
|
json(res, 200, { ok: true, path: abs });
|
|
} catch (err) {
|
|
json(res, err?.code === "EEXIST" ? 200 : err.status ?? 500, err?.code === "EEXIST" ? { ok: true, exists: true } : { error: String(err) });
|
|
}
|
|
}
|
|
});
|
|
register({
|
|
kind: "exact",
|
|
path: "/api/worktable/git",
|
|
handler: async (req, res) => {
|
|
try {
|
|
const body = await readJsonBody(req);
|
|
const cwd = serverCwd(ctx, body.sessionId, body.cwd);
|
|
json(res, 200, await gitStatus(cwd));
|
|
} catch (err) {
|
|
json(res, err.status ?? 500, { error: String(err) });
|
|
}
|
|
}
|
|
});
|
|
const localConfigPaths = (fileName) => {
|
|
const out = [];
|
|
const envDir = process.env.DSH_WORKTABLE_LOCAL_DIR;
|
|
if (typeof envDir === "string" && envDir.trim()) out.push(pathResolve(envDir.trim(), fileName));
|
|
try {
|
|
const libDir = dirname(fileURLToPath(import.meta.url));
|
|
out.push(pathResolve(libDir, "..", "03_local", fileName));
|
|
out.push(pathResolve(libDir, "..", "..", "03_local", fileName));
|
|
out.push(pathResolve(libDir, "..", "..", "..", "03_local", fileName));
|
|
} catch {
|
|
}
|
|
try {
|
|
const home = resolveDshHomeSafe();
|
|
if (typeof home === "string" && home) out.push(pathResolve(home, "03_local", fileName));
|
|
} catch {
|
|
}
|
|
return out;
|
|
};
|
|
const readLocalConfigField = async (fileName, field) => {
|
|
for (const file of localConfigPaths(fileName)) {
|
|
try {
|
|
const raw = await readFile(file, "utf8");
|
|
const parsed = JSON.parse(raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw);
|
|
const value = parsed && typeof parsed === "object" ? parsed[field] : void 0;
|
|
const text = typeof value === "string" ? value.trim() : "";
|
|
if (text) return text;
|
|
} catch {
|
|
}
|
|
}
|
|
return null;
|
|
};
|
|
const statePath = async () => await readLocalConfigField("local.json", "cloudStatePath") ?? pathResolve(resolveDshHomeSafe(), "worktable-state.json");
|
|
register({
|
|
kind: "exact",
|
|
path: "/api/worktable/state",
|
|
handler: async (req, res) => {
|
|
const file = await statePath();
|
|
if (req.method === "GET" || req.method === "HEAD") {
|
|
try {
|
|
const raw = await readFile(file, "utf8");
|
|
const text = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
|
|
const parsed = JSON.parse(text);
|
|
json(res, 200, { ok: true, path: file, state: parsed });
|
|
} catch (err) {
|
|
if (err?.code === "ENOENT") {
|
|
stateLog("GET empty (no file)");
|
|
json(res, 200, { ok: true, path: file, state: null });
|
|
return;
|
|
}
|
|
stateLog("GET error " + String(err));
|
|
json(res, 500, { error: String(err) });
|
|
}
|
|
return;
|
|
}
|
|
if (req.method !== "POST") {
|
|
json(res, 405, { error: "method not allowed" });
|
|
return;
|
|
}
|
|
try {
|
|
const body = await readJsonBody(req);
|
|
const incoming = body && typeof body.state === "object" && body.state !== null ? body.state : null;
|
|
if (!incoming) {
|
|
stateLog("POST 400 missing state");
|
|
json(res, 400, { error: "missing state" });
|
|
return;
|
|
}
|
|
let previous = null;
|
|
try {
|
|
const raw = await readFile(file, "utf8");
|
|
previous = JSON.parse(raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw);
|
|
} catch {
|
|
}
|
|
const state = previous && typeof previous === "object" && !Array.isArray(previous) ? { ...previous, ...incoming } : incoming;
|
|
const text = JSON.stringify(state);
|
|
const inN = incoming?.projects?.layouts?.length ?? 0;
|
|
const prevN = previous?.projects?.layouts?.length ?? 0;
|
|
if (inN < prevN) {
|
|
stateLog("WARN projects shrink " + prevN + " -> " + inN + " (keys=" + Object.keys(incoming).join("+") + ")");
|
|
}
|
|
if (text.length > 20 * 1024 * 1024) {
|
|
json(res, 413, { error: "state too large" });
|
|
return;
|
|
}
|
|
const fsx = await import("node:fs/promises");
|
|
await fsx.mkdir(dirname(file), { recursive: true });
|
|
const tmp = file + ".tmp-" + process.pid + "-" + Date.now();
|
|
await fsx.writeFile(tmp, text, "utf8");
|
|
await fsx.rename(tmp, file);
|
|
json(res, 200, { ok: true, path: file });
|
|
} catch (err) {
|
|
json(res, err?.status ?? 500, { error: String(err) });
|
|
}
|
|
}
|
|
});
|
|
setupTerminal(webServer, ctx);
|
|
}
|
|
export {
|
|
HEALTH_PATH,
|
|
__wtLoadProbeStats,
|
|
apply,
|
|
inject,
|
|
name
|
|
};
|