dsh-workbench-host 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/client/client.js +2177 -0
- package/cordis.patch.yml +5 -0
- package/lib/actions/action-output.js +25 -0
- package/lib/actions/actions.js +499 -0
- package/lib/actions/capabilities.js +299 -0
- package/lib/actions/task-targets.js +75 -0
- package/lib/core/db.d.ts +6 -0
- package/lib/core/db.js +72 -0
- package/lib/core/index.d.ts +4 -0
- package/lib/core/index.js +4 -0
- package/lib/core/repo.d.ts +43 -0
- package/lib/core/repo.js +116 -0
- package/lib/core/schema.d.ts +7 -0
- package/lib/core/schema.js +65 -0
- package/lib/index.js +411 -0
- package/lib/infra/audit.js +373 -0
- package/lib/infra/backup.js +263 -0
- package/lib/infra/network.js +466 -0
- package/lib/infra/search.js +83 -0
- package/lib/infra/zip.js +217 -0
- package/lib/sync/sync-conflicts.js +37 -0
- package/lib/sync/sync-incoming.js +56 -0
- package/lib/sync/sync-types.js +1 -0
- package/lib/sync/sync-values.js +22 -0
- package/lib/sync/sync.js +550 -0
- package/lib/types/host-types.js +1 -0
- package/package.json +61 -4
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
import { actionErrorText } from "../actions/action-output.js";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { getSyncStateText, setSyncStateText } from "../core/index.js";
|
|
4
|
+
import { SyncEngine, SyncHttpError, listConflicts, resolveConflict } from "../sync/sync.js";
|
|
5
|
+
import { createBackup, importBackup, normalizeImportPolicy } from "./backup.js";
|
|
6
|
+
export function installNetwork({ ctx, state, saveCreds, clock, domains, emit, subscribers, listDomains, SHELL_VERSION, sessionModeOf, setSessionMode, audit, backupDomains, actionNames, invoke, log, schemaSnapshot }) {
|
|
7
|
+
/** 云端 fetch 封装(带 access token;401 时尝试 refresh 一次)。 */
|
|
8
|
+
async function cloudFetch(path, init, retry = true) {
|
|
9
|
+
const headers = {
|
|
10
|
+
"content-type": "application/json",
|
|
11
|
+
...init?.headers,
|
|
12
|
+
};
|
|
13
|
+
if (state.creds)
|
|
14
|
+
headers.authorization = "Bearer " + state.creds.accessToken;
|
|
15
|
+
const res = await fetch(state.cloudUrl + path, {
|
|
16
|
+
...init,
|
|
17
|
+
headers,
|
|
18
|
+
body: init?.json ? JSON.stringify(init.json) : init?.body,
|
|
19
|
+
});
|
|
20
|
+
if (res.status === 401 && retry && state.creds?.refreshToken) {
|
|
21
|
+
const r = await fetch(state.cloudUrl + "/v1/auth/refresh", {
|
|
22
|
+
method: "POST",
|
|
23
|
+
headers: { "content-type": "application/json" },
|
|
24
|
+
body: JSON.stringify({ refresh_token: state.creds.refreshToken }),
|
|
25
|
+
}).then((x) => x.json());
|
|
26
|
+
if (r.ok) {
|
|
27
|
+
state.creds = {
|
|
28
|
+
accessToken: r.accessToken,
|
|
29
|
+
refreshToken: r.refreshToken,
|
|
30
|
+
userId: r.userId,
|
|
31
|
+
deviceId: r.deviceId,
|
|
32
|
+
};
|
|
33
|
+
saveCreds(state.creds);
|
|
34
|
+
return cloudFetch(path, init, false);
|
|
35
|
+
}
|
|
36
|
+
state.creds = null;
|
|
37
|
+
saveCreds(null);
|
|
38
|
+
}
|
|
39
|
+
return res.json();
|
|
40
|
+
}
|
|
41
|
+
/** 云端健康检查缓存:首页/账号页共用,避免同步事件风暴时反复探测。 */
|
|
42
|
+
let cloudHealthCache = null;
|
|
43
|
+
/** 轻量探测云端是否可达;结果缓存 10s,失败不抛异常。 */
|
|
44
|
+
async function cloudHealth() {
|
|
45
|
+
const now = Date.now();
|
|
46
|
+
if (cloudHealthCache && now - cloudHealthCache.at < 10_000)
|
|
47
|
+
return cloudHealthCache.value;
|
|
48
|
+
const started = now;
|
|
49
|
+
const controller = new AbortController();
|
|
50
|
+
const timer = setTimeout(() => controller.abort(), 3_000);
|
|
51
|
+
let value;
|
|
52
|
+
try {
|
|
53
|
+
const res = await fetch(state.cloudUrl + "/v1/health", { signal: controller.signal });
|
|
54
|
+
value = {
|
|
55
|
+
reachable: res.ok,
|
|
56
|
+
status: res.status,
|
|
57
|
+
checked_at: Date.now(),
|
|
58
|
+
latency_ms: Date.now() - started,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
value = {
|
|
63
|
+
reachable: false,
|
|
64
|
+
status: 0,
|
|
65
|
+
checked_at: Date.now(),
|
|
66
|
+
latency_ms: Date.now() - started,
|
|
67
|
+
error: String((e && e.message) || e),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
}
|
|
73
|
+
cloudHealthCache = { at: now, value };
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
/** 把 /v1/sync/* 的错误响应转成可判别的 SyncHttpError。 */
|
|
77
|
+
async function syncCall(path, json) {
|
|
78
|
+
const r = await cloudFetch(path, { method: "POST", json });
|
|
79
|
+
if (r && r.ok === false) {
|
|
80
|
+
const code = String(r.code ?? "sync_error");
|
|
81
|
+
const status = code === "version_conflict" || code === "sync_locked" || code.startsWith("session_") ? 409 : Number(r.status) || 400;
|
|
82
|
+
throw new SyncHttpError(status, code, String(r.error ?? code), r);
|
|
83
|
+
}
|
|
84
|
+
return r;
|
|
85
|
+
}
|
|
86
|
+
const syncTransport = {
|
|
87
|
+
open: (protocol, deviceId) => syncCall("/v1/sync/open", { protocol, device_id: deviceId }),
|
|
88
|
+
push: (body) => syncCall("/v1/sync/push", body),
|
|
89
|
+
pull: (body) => syncCall("/v1/sync/pull", body),
|
|
90
|
+
snapshot: (body) => syncCall("/v1/sync/snapshot", body),
|
|
91
|
+
full: (body) => syncCall("/v1/sync/full", body),
|
|
92
|
+
close: (body) => syncCall("/v1/sync/close", body),
|
|
93
|
+
};
|
|
94
|
+
function syncDomains() {
|
|
95
|
+
return [...domains.values()].map((rec) => ({
|
|
96
|
+
id: rec.def.id,
|
|
97
|
+
tables: rec.def.tables,
|
|
98
|
+
sync: rec.def.sync,
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
function ensureSyncIdentity() {
|
|
102
|
+
if (!state.creds)
|
|
103
|
+
throw new Error("not logged in");
|
|
104
|
+
const bound = getSyncStateText(state.db, "account_user_id");
|
|
105
|
+
if (!bound)
|
|
106
|
+
setSyncStateText(state.db, "account_user_id", state.creds.userId);
|
|
107
|
+
let epoch = getSyncStateText(state.db, "sync_epoch");
|
|
108
|
+
if (!epoch) {
|
|
109
|
+
epoch = randomUUID();
|
|
110
|
+
setSyncStateText(state.db, "sync_epoch", epoch);
|
|
111
|
+
}
|
|
112
|
+
return { userId: state.creds.userId, deviceId: state.creds.deviceId, epoch };
|
|
113
|
+
}
|
|
114
|
+
let syncBusy = false;
|
|
115
|
+
async function runSync() {
|
|
116
|
+
if (syncBusy)
|
|
117
|
+
return { ok: false, error: "sync already running", skipped: true };
|
|
118
|
+
syncBusy = true;
|
|
119
|
+
try {
|
|
120
|
+
const identity = ensureSyncIdentity();
|
|
121
|
+
const engine = new SyncEngine({
|
|
122
|
+
db: state.db,
|
|
123
|
+
domains: syncDomains(),
|
|
124
|
+
transport: syncTransport,
|
|
125
|
+
clock,
|
|
126
|
+
userId: identity.userId,
|
|
127
|
+
deviceId: identity.deviceId,
|
|
128
|
+
epoch: identity.epoch,
|
|
129
|
+
onEvent: emit,
|
|
130
|
+
});
|
|
131
|
+
const report = await engine.run();
|
|
132
|
+
return report;
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
syncBusy = false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// ── HTTP:/workbench/hooks/*(外部入口,不经过 DSH connection 门)──
|
|
139
|
+
// 鉴权由业务插件负责(token/HMAC/IP);宿主只保证默认只监听本机回环。
|
|
140
|
+
ctx.effect?.(() => ctx.webServer?.register({
|
|
141
|
+
kind: "prefix",
|
|
142
|
+
path: "/workbench/hooks",
|
|
143
|
+
handler: async (req, res) => {
|
|
144
|
+
const send = (code, obj, headers = {}) => {
|
|
145
|
+
res.writeHead(code, { "content-type": "application/json", ...headers });
|
|
146
|
+
res.end(JSON.stringify(obj));
|
|
147
|
+
};
|
|
148
|
+
try {
|
|
149
|
+
const url = new URL(req.url ?? "", "http://local");
|
|
150
|
+
const p = url.pathname.replace(/^\/workbench\/hooks/, "");
|
|
151
|
+
const m = req.method ?? "GET";
|
|
152
|
+
if (m !== "POST" && m !== "GET")
|
|
153
|
+
return send(405, { ok: false, error: "method not allowed" });
|
|
154
|
+
const hookM = /^\/([^/]+)\/([^/]+)$/.exec(p);
|
|
155
|
+
if (!hookM)
|
|
156
|
+
return send(404, { ok: false, error: "no hook route " + p });
|
|
157
|
+
const domainId = decodeURIComponent(hookM[1]);
|
|
158
|
+
const hookName = decodeURIComponent(hookM[2]);
|
|
159
|
+
// 允许 /hooks/connector/inbound 这样的短域名;内部 id 仍是 wb-addon-connector。
|
|
160
|
+
const rec = domains.get(domainId) ?? domains.get("wb-addon-" + domainId);
|
|
161
|
+
const handler = rec?.hooks?.get(hookName);
|
|
162
|
+
if (!handler)
|
|
163
|
+
return send(404, { ok: false, error: "no hook " + domainId + "/" + hookName });
|
|
164
|
+
const remote = String(req.socket?.remoteAddress ?? "");
|
|
165
|
+
const loopback = remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1";
|
|
166
|
+
if (!loopback)
|
|
167
|
+
return send(403, { ok: false, error: "hook is local-only (use a reverse proxy)" });
|
|
168
|
+
const chunks = [];
|
|
169
|
+
let total = 0;
|
|
170
|
+
for await (const c of req) {
|
|
171
|
+
const buf = c;
|
|
172
|
+
total += buf.length;
|
|
173
|
+
if (total > 1024 * 1024)
|
|
174
|
+
return send(413, { ok: false, error: "body too large" });
|
|
175
|
+
chunks.push(buf);
|
|
176
|
+
}
|
|
177
|
+
const body = Buffer.concat(chunks.map((c) => Buffer.from(c)));
|
|
178
|
+
const out = await handler({
|
|
179
|
+
method: m,
|
|
180
|
+
path: p,
|
|
181
|
+
query: Object.fromEntries(url.searchParams),
|
|
182
|
+
headers: req.headers,
|
|
183
|
+
remoteAddress: remote,
|
|
184
|
+
body,
|
|
185
|
+
});
|
|
186
|
+
const status = Number(out?.status ?? 200);
|
|
187
|
+
const headers = out?.headers ?? {};
|
|
188
|
+
const payload = out?.body ?? { ok: true };
|
|
189
|
+
if (Buffer.isBuffer(payload) || payload instanceof Uint8Array) {
|
|
190
|
+
res.writeHead(status, { "content-type": "application/octet-stream", ...headers });
|
|
191
|
+
res.end(Buffer.from(payload));
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (typeof payload === "string") {
|
|
195
|
+
res.writeHead(status, { "content-type": "text/plain; charset=utf-8", ...headers });
|
|
196
|
+
res.end(payload);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
send(status, payload, headers);
|
|
200
|
+
}
|
|
201
|
+
catch (e) {
|
|
202
|
+
return send(500, { ok: false, error: String((e && e.message) || e) });
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
}, "workbench-hooks"), "workbench-hooks");
|
|
206
|
+
// ── HTTP:/workbench/api/*(同域 cookie 之外的连接门由 host connection.requestRejection 兜底)──
|
|
207
|
+
ctx.effect?.(() => ctx.webServer?.register({
|
|
208
|
+
kind: "prefix",
|
|
209
|
+
path: "/workbench/api",
|
|
210
|
+
handler: async (req, res) => {
|
|
211
|
+
const rejection = ctx.connection?.requestRejection?.(req);
|
|
212
|
+
if (rejection !== undefined) {
|
|
213
|
+
res.statusCode = rejection;
|
|
214
|
+
res.end(JSON.stringify({ ok: false, error: "connection rejected" }));
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const url = new URL(req.url ?? "", "http://local");
|
|
218
|
+
const p = url.pathname.replace(/^\/workbench\/api/, "");
|
|
219
|
+
const m = req.method ?? "GET";
|
|
220
|
+
const bodyOf = async () => {
|
|
221
|
+
const chunks = [];
|
|
222
|
+
for await (const c of req)
|
|
223
|
+
chunks.push(c);
|
|
224
|
+
try {
|
|
225
|
+
return JSON.parse(Buffer.concat(chunks).toString() || "{}");
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return {};
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
const rawBodyOf = async (maxBytes = 64 * 1024 * 1024) => {
|
|
232
|
+
const chunks = [];
|
|
233
|
+
let total = 0;
|
|
234
|
+
for await (const c of req) {
|
|
235
|
+
const buf = c;
|
|
236
|
+
total += buf.length;
|
|
237
|
+
if (total > maxBytes)
|
|
238
|
+
throw new Error("请求体超过上限(" + Math.round(maxBytes / 1024 / 1024) + "MB)");
|
|
239
|
+
chunks.push(buf);
|
|
240
|
+
}
|
|
241
|
+
return Buffer.concat(chunks);
|
|
242
|
+
};
|
|
243
|
+
const send = (code, obj) => {
|
|
244
|
+
res.writeHead(code, { "content-type": "application/json" });
|
|
245
|
+
res.end(JSON.stringify(obj));
|
|
246
|
+
};
|
|
247
|
+
try {
|
|
248
|
+
if (p === "/events" && m === "GET") {
|
|
249
|
+
res.writeHead(200, {
|
|
250
|
+
"content-type": "text/event-stream",
|
|
251
|
+
"cache-control": "no-cache",
|
|
252
|
+
connection: "keep-alive",
|
|
253
|
+
});
|
|
254
|
+
const sub = (event, data) => res.write("event: " + event + "\ndata: " + JSON.stringify(data) + "\n\n");
|
|
255
|
+
subscribers.add(sub);
|
|
256
|
+
req.on?.("close", () => subscribers.delete(sub));
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (p === "/domains" && m === "GET") {
|
|
260
|
+
return send(200, { ok: true, domains: listDomains(), shellVersion: SHELL_VERSION });
|
|
261
|
+
}
|
|
262
|
+
if (p === "/record" && m === "GET") {
|
|
263
|
+
const sid = String(url.searchParams.get("sessionId") ?? "").trim();
|
|
264
|
+
if (!sid)
|
|
265
|
+
return send(400, { ok: false, error: "缺少 sessionId" });
|
|
266
|
+
return send(200, { ok: true, sessionId: sid, enabled: sessionModeOf(state.db, sid) });
|
|
267
|
+
}
|
|
268
|
+
if (p === "/record" && m === "POST") {
|
|
269
|
+
const body = await bodyOf();
|
|
270
|
+
const sid = String(body?.sessionId ?? "").trim();
|
|
271
|
+
if (!sid || sid.length > 200)
|
|
272
|
+
return send(400, { ok: false, error: "sessionId 不合法" });
|
|
273
|
+
if (typeof body?.enabled !== "boolean")
|
|
274
|
+
return send(400, { ok: false, error: "enabled 必须是布尔值" });
|
|
275
|
+
const enabled = body.enabled === true;
|
|
276
|
+
setSessionMode(state.db, sid, enabled, clock.now());
|
|
277
|
+
emit("record-mode", { sessionId: sid, enabled });
|
|
278
|
+
return send(200, { ok: true, sessionId: sid, enabled });
|
|
279
|
+
}
|
|
280
|
+
if (p === "/audit" && m === "GET") {
|
|
281
|
+
// 审计页数据:列表 + 可选统计。参数与 audit.list 保持一致,便于同一套筛选复用到 UI。
|
|
282
|
+
try {
|
|
283
|
+
const q = url.searchParams;
|
|
284
|
+
const pick = (key) => (q.get(key) === null ? undefined : String(q.get(key)));
|
|
285
|
+
const result = audit.list({
|
|
286
|
+
action: pick("action"),
|
|
287
|
+
actionPrefix: pick("actionPrefix"),
|
|
288
|
+
actor: pick("actor"),
|
|
289
|
+
domain: pick("domain"),
|
|
290
|
+
ok: pick("ok"),
|
|
291
|
+
q: pick("q"),
|
|
292
|
+
target: pick("target"),
|
|
293
|
+
since: pick("since"),
|
|
294
|
+
until: pick("until"),
|
|
295
|
+
page: pick("page"),
|
|
296
|
+
pageSize: pick("pageSize"),
|
|
297
|
+
});
|
|
298
|
+
const stats = q.get("stats") === "1" ? audit.stats(pick("rangeDays") ?? 30) : null;
|
|
299
|
+
return send(200, { ok: true, shellVersion: SHELL_VERSION, ...result, stats });
|
|
300
|
+
}
|
|
301
|
+
catch (e) {
|
|
302
|
+
return send(500, { ok: false, error: String((e && e.message) || e) });
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (p === "/schema" && m === "GET") {
|
|
306
|
+
// 只读 schema 快照:Action 页用它渲染运行时注册,不经过 action 执行链路。
|
|
307
|
+
try {
|
|
308
|
+
const domain = String(url.searchParams.get("domain") ?? "").trim();
|
|
309
|
+
return send(200, { ok: true, readonly: true, ...schemaSnapshot(domain || undefined) });
|
|
310
|
+
}
|
|
311
|
+
catch (e) {
|
|
312
|
+
return send(500, { ok: false, error: String((e && e.message) || e) });
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (p === "/backup/export" && m === "GET") {
|
|
316
|
+
const raw = url.searchParams.get("modules");
|
|
317
|
+
const ids = raw && raw !== "all" ? raw.split(",").map((x) => x.trim()).filter(Boolean) : null;
|
|
318
|
+
try {
|
|
319
|
+
const backup = await createBackup({ domains: backupDomains(), shellVersion: SHELL_VERSION, moduleIds: ids });
|
|
320
|
+
res.writeHead(200, {
|
|
321
|
+
"content-type": "application/zip",
|
|
322
|
+
"content-disposition": "attachment; filename=\"" + backup.filename + "\"",
|
|
323
|
+
"content-length": backup.buffer.length,
|
|
324
|
+
"cache-control": "no-store",
|
|
325
|
+
});
|
|
326
|
+
res.end(backup.buffer);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
catch (e) {
|
|
330
|
+
const err = e;
|
|
331
|
+
const code = err && err.name === "BackupError" && err.code ? String(err.code) : "export";
|
|
332
|
+
// 调用方可纠正的问题给 4xx(带 machine-readable code),导出执行期异常才算 500。
|
|
333
|
+
const status = code === "incompatible" ? 422 : code === "export" ? 500 : 400;
|
|
334
|
+
log("备份导出失败", code, ids && ids.length ? ids.join(",") : "all");
|
|
335
|
+
return send(status, { ok: false, code, error: String((e && e.message) || e) });
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (p === "/backup/import" && m === "POST") {
|
|
339
|
+
try {
|
|
340
|
+
const buf = await rawBodyOf();
|
|
341
|
+
const policies = {};
|
|
342
|
+
const rawPolicy = req.headers?.["x-wb-backup-policy"];
|
|
343
|
+
if (typeof rawPolicy === "string" && rawPolicy) {
|
|
344
|
+
try {
|
|
345
|
+
const parsed = JSON.parse(rawPolicy);
|
|
346
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
347
|
+
for (const key of Object.keys(parsed))
|
|
348
|
+
policies[key] = normalizeImportPolicy(parsed[key]);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
// 策略头损坏时按默认 newest 处理,不阻断备份导入
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const result = await importBackup({ buffer: buf, domains: backupDomains(), policies });
|
|
356
|
+
emit("backup-imported", { summary: result.summary, exportedAt: result.exportedAt });
|
|
357
|
+
return send(200, result);
|
|
358
|
+
}
|
|
359
|
+
catch (e) {
|
|
360
|
+
const err = e;
|
|
361
|
+
const code = err && err.code ? err.code : "invalid";
|
|
362
|
+
return send(code === "incompatible" ? 422 : 400, {
|
|
363
|
+
ok: false,
|
|
364
|
+
code,
|
|
365
|
+
error: String((e && e.message) || e),
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const actionM = /^\/domains\/([^/]+)\/actions\/([^/]+)$/.exec(p);
|
|
370
|
+
if (actionM && m === "POST") {
|
|
371
|
+
const id = decodeURIComponent(actionM[1]);
|
|
372
|
+
const action = decodeURIComponent(actionM[2]);
|
|
373
|
+
const owner = actionNames().find((a) => a.name === action);
|
|
374
|
+
if (!owner || owner.domainId !== id) {
|
|
375
|
+
return send(404, { ok: false, error: "业务插件未注册该 action:" + action });
|
|
376
|
+
}
|
|
377
|
+
const body = await bodyOf();
|
|
378
|
+
const r = await invoke(action, body, "ui");
|
|
379
|
+
return send(200, { ok: true, result: r.result, text: r.text });
|
|
380
|
+
}
|
|
381
|
+
if (p === "/sync/now" && m === "POST") {
|
|
382
|
+
if (!state.creds)
|
|
383
|
+
return send(400, { ok: false, error: "not logged in" });
|
|
384
|
+
const r = await runSync();
|
|
385
|
+
return send(200, { ok: true, ...r });
|
|
386
|
+
}
|
|
387
|
+
if (p === "/sync/status" && m === "GET") {
|
|
388
|
+
const identity = state.creds ? ensureSyncIdentity() : null;
|
|
389
|
+
const engine = new SyncEngine({
|
|
390
|
+
db: state.db,
|
|
391
|
+
domains: syncDomains(),
|
|
392
|
+
transport: syncTransport,
|
|
393
|
+
clock,
|
|
394
|
+
userId: identity?.userId ?? "",
|
|
395
|
+
deviceId: identity?.deviceId ?? "",
|
|
396
|
+
epoch: identity?.epoch ?? "",
|
|
397
|
+
onEvent: emit,
|
|
398
|
+
});
|
|
399
|
+
const cloud = state.creds
|
|
400
|
+
? await cloudHealth()
|
|
401
|
+
: { reachable: null, status: 0, checked_at: 0 };
|
|
402
|
+
return send(200, {
|
|
403
|
+
ok: true,
|
|
404
|
+
logged_in: Boolean(state.creds),
|
|
405
|
+
...engine.status(),
|
|
406
|
+
running: syncBusy,
|
|
407
|
+
cloud,
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
if (p === "/sync/conflicts" && m === "GET") {
|
|
411
|
+
const limit = Number(url.searchParams.get("limit") ?? "100");
|
|
412
|
+
return send(200, { ok: true, conflicts: listConflicts(state.db, limit) });
|
|
413
|
+
}
|
|
414
|
+
const conflictM = /^\/sync\/conflicts\/(\d+)\/resolve$/.exec(p);
|
|
415
|
+
if (conflictM && m === "POST") {
|
|
416
|
+
const body = await bodyOf();
|
|
417
|
+
const action = String(body.action ?? "");
|
|
418
|
+
if (action !== "keep_local" && action !== "keep_server" && action !== "dismiss") {
|
|
419
|
+
return send(400, { ok: false, error: "action 必须是 keep_local/keep_server/dismiss" });
|
|
420
|
+
}
|
|
421
|
+
const ok = resolveConflict(state.db, Number(conflictM[1]), action, clock.now(), syncDomains());
|
|
422
|
+
return send(ok ? 200 : 404, { ok });
|
|
423
|
+
}
|
|
424
|
+
if (p === "/account" && m === "GET") {
|
|
425
|
+
if (!state.creds)
|
|
426
|
+
return send(200, { ok: true, logged_in: false });
|
|
427
|
+
const me = await cloudFetch("/v1/me");
|
|
428
|
+
return send(200, { ok: true, logged_in: true, user: me.user, devices: me.devices });
|
|
429
|
+
}
|
|
430
|
+
if (p === "/account/login" && m === "POST") {
|
|
431
|
+
const b = await bodyOf();
|
|
432
|
+
const deviceId = state.creds?.deviceId ?? "shell-" + Math.random().toString(36).slice(2, 10);
|
|
433
|
+
const r = await cloudFetch(b.signup ? "/v1/auth/signup" : "/v1/auth/login", {
|
|
434
|
+
method: "POST",
|
|
435
|
+
json: { email: b.email, password: b.password, device_id: deviceId, device_name: "DSH Web" },
|
|
436
|
+
});
|
|
437
|
+
if (r.ok) {
|
|
438
|
+
state.creds = {
|
|
439
|
+
accessToken: r.accessToken,
|
|
440
|
+
refreshToken: r.refreshToken,
|
|
441
|
+
userId: r.userId,
|
|
442
|
+
deviceId: r.deviceId,
|
|
443
|
+
};
|
|
444
|
+
saveCreds(state.creds);
|
|
445
|
+
cloudHealthCache = null;
|
|
446
|
+
emit("account-changed", { logged_in: true });
|
|
447
|
+
void runSync().catch((e) => log("登录后首轮同步失败", e));
|
|
448
|
+
}
|
|
449
|
+
return send(r.ok ? 200 : 401, r);
|
|
450
|
+
}
|
|
451
|
+
if (p === "/account/logout" && m === "POST") {
|
|
452
|
+
state.creds = null;
|
|
453
|
+
saveCreds(null);
|
|
454
|
+
cloudHealthCache = null;
|
|
455
|
+
emit("account-changed", { logged_in: false });
|
|
456
|
+
return send(200, { ok: true });
|
|
457
|
+
}
|
|
458
|
+
return send(404, { ok: false, error: "no route " + m + " " + p });
|
|
459
|
+
}
|
|
460
|
+
catch (e) {
|
|
461
|
+
return send(500, { ok: false, error: actionErrorText(e) });
|
|
462
|
+
}
|
|
463
|
+
},
|
|
464
|
+
}, "workbench-http"), "workbench-http");
|
|
465
|
+
return { runSync };
|
|
466
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
const TIMEOUT_MS = 500;
|
|
2
|
+
const MAX_QUERY = 100;
|
|
3
|
+
function normalize(q) {
|
|
4
|
+
return String(q ?? "").trim().slice(0, MAX_QUERY);
|
|
5
|
+
}
|
|
6
|
+
function scoreHit(hit, q) {
|
|
7
|
+
const needle = q.toLowerCase();
|
|
8
|
+
const title = String(hit.title || "").toLowerCase();
|
|
9
|
+
let score = 0;
|
|
10
|
+
if (title === needle)
|
|
11
|
+
score = 100;
|
|
12
|
+
else if (title.startsWith(needle))
|
|
13
|
+
score = 80;
|
|
14
|
+
else if (title.includes(needle))
|
|
15
|
+
score = 60;
|
|
16
|
+
if (String(hit.snippet || "").toLowerCase().includes(needle))
|
|
17
|
+
score += 20;
|
|
18
|
+
if (hit.url)
|
|
19
|
+
score += 1;
|
|
20
|
+
return score;
|
|
21
|
+
}
|
|
22
|
+
export function createSearch(providers, log = () => { }) {
|
|
23
|
+
function list() {
|
|
24
|
+
return [...providers.values()].map((p) => ({
|
|
25
|
+
domainId: p.domainId,
|
|
26
|
+
search: typeof p.search === "function",
|
|
27
|
+
})).filter((p) => p.search);
|
|
28
|
+
}
|
|
29
|
+
async function query(input) {
|
|
30
|
+
const started = Date.now();
|
|
31
|
+
const args = input && typeof input === "object" ? input : {};
|
|
32
|
+
const q = normalize(String(args.q ?? ""));
|
|
33
|
+
const limit = Math.max(1, Math.min(50, Number(args.limit) || 20));
|
|
34
|
+
const wanted = Array.isArray(args.domains)
|
|
35
|
+
? args.domains.map(String).filter(Boolean)
|
|
36
|
+
: [];
|
|
37
|
+
if (!q)
|
|
38
|
+
return { q, items: [], domains: list().map((p) => p.domainId), partial: false, failed: [], tookMs: 0 };
|
|
39
|
+
const active = [...providers.values()].filter((p) => typeof p.search === "function" && (wanted.length === 0 || wanted.includes(p.domainId)));
|
|
40
|
+
const failed = [];
|
|
41
|
+
const batches = await Promise.all(active.map(async (provider) => {
|
|
42
|
+
let timer = null;
|
|
43
|
+
const timeout = new Promise((resolve) => {
|
|
44
|
+
timer = setTimeout(() => {
|
|
45
|
+
failed.push(provider.domainId);
|
|
46
|
+
resolve([]);
|
|
47
|
+
}, TIMEOUT_MS);
|
|
48
|
+
if (typeof timer.unref === "function")
|
|
49
|
+
timer.unref();
|
|
50
|
+
});
|
|
51
|
+
try {
|
|
52
|
+
const hits = await Promise.race([
|
|
53
|
+
Promise.resolve(provider.search(q, { limit })).then((x) => (Array.isArray(x) ? x : [])),
|
|
54
|
+
timeout,
|
|
55
|
+
]);
|
|
56
|
+
return hits.map((hit) => ({ ...hit, domainId: provider.domainId }));
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
failed.push(provider.domainId);
|
|
60
|
+
log("search provider failed", provider.domainId, error?.message);
|
|
61
|
+
return [];
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
if (timer)
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
}
|
|
67
|
+
}));
|
|
68
|
+
const items = batches
|
|
69
|
+
.flat()
|
|
70
|
+
.filter((hit) => hit && hit.id && hit.title)
|
|
71
|
+
.map((hit) => ({ ...hit, score: scoreHit(hit, q) }))
|
|
72
|
+
.sort((a, b) => b.score - a.score || Number(b.at || 0) - Number(a.at || 0) || String(a.title).localeCompare(String(b.title)));
|
|
73
|
+
return {
|
|
74
|
+
q,
|
|
75
|
+
items: items.slice(0, limit * Math.max(1, active.length)).slice(0, 100),
|
|
76
|
+
domains: list().map((p) => p.domainId),
|
|
77
|
+
partial: failed.length > 0,
|
|
78
|
+
failed,
|
|
79
|
+
tookMs: Date.now() - started,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
return { query, list };
|
|
83
|
+
}
|