cladogram 0.5.2 → 0.5.4
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/README.md +30 -2
- package/bin/clado.js +55 -3
- package/docs/plugin-development.md +135 -0
- package/docs/plugin-ui.md +43 -0
- package/docs/release.md +26 -0
- package/package.json +8 -1
- package/plugins/agent/index.js +181 -0
- package/plugins/agent/style.css +105 -0
- package/plugins/brand/index.js +262 -0
- package/plugins/brand/style.css +162 -0
- package/plugins/directory/capabilities.json +27 -0
- package/plugins/directory/index.js +146 -0
- package/plugins/directory/style.css +48 -0
- package/plugins/view-controls/index.js +58 -0
- package/plugins/view-controls/style.css +46 -0
- package/skills/clado/SKILL.md +31 -17
- package/src/html/app-css.js +11 -42
- package/src/html/canvas-chain.js +5 -6
- package/src/html/canvas-focus.js +3 -4
- package/src/html/canvas-screenshot.js +199 -0
- package/src/html/canvas-ui.css +37 -9
- package/src/html/canvas-ui.js +35 -27
- package/src/html/page.js +11 -37
- package/src/html/plugin-assets.js +33 -0
- package/src/html/plugin-ui.css +176 -0
- package/src/html/plugin-ui.js +45 -0
- package/src/html/runtime-api.js +47 -0
- package/src/html/runtime.js +15 -12
- package/src/server/agent.js +222 -0
- package/src/server/assets/clado-plugin-sdk.js +111 -0
- package/src/server/assets/library-canvas.js +72 -11
- package/src/server/assets/library-plugin-bridge.js +84 -0
- package/src/server/assets/library-plugins.css +39 -0
- package/src/server/assets/library-plugins.js +200 -0
- package/src/server/assets/library.css +3 -6
- package/src/server/assets/library.html +2 -12
- package/src/server/assets/library.js +280 -44
- package/src/server/canvas-capture.js +47 -0
- package/src/server/export.js +5 -2
- package/src/server/mcp.js +44 -19
- package/src/server/plugin-capabilities.js +172 -0
- package/src/server/plugin-settings.js +117 -0
- package/src/server/plugins.js +236 -0
- package/src/server/workspace.js +157 -12
- package/src/skill/targets.js +1 -1
- package/src/util/update.js +58 -0
- package/src/vendor/html-to-image.min.js +24 -0
- package/src/workspace/content.js +3 -2
- package/src/workspace/service.js +81 -21
- package/src/workspace/tree.js +38 -0
- package/src/server/assets/tree.js +0 -26
package/src/server/workspace.js
CHANGED
|
@@ -1,33 +1,140 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
3
|
import { readFileSync, statSync, existsSync, mkdirSync } from 'node:fs';
|
|
3
4
|
import { dirname, resolve, basename, join, relative } from 'node:path';
|
|
4
5
|
import { fileURLToPath } from 'node:url';
|
|
5
6
|
import { renderHtml } from '../html/page.js';
|
|
7
|
+
import { pluginMarkup, workspacePluginAssets } from '../html/plugin-assets.js';
|
|
6
8
|
import { scanDirectory, workspacePath, readDocument, DocumentError } from '../workspace/documents.js';
|
|
7
9
|
import { contextFor, initialize } from '../workspace/storage.js';
|
|
8
10
|
import { createWorkspaceService } from '../workspace/service.js';
|
|
9
11
|
import { createMcpHandler } from './mcp.js';
|
|
12
|
+
import { builtInCapabilities, builtInGrants, inspectWorkspacePlugins, installWorkspacePlugin, loadWorkspacePlugins } from './plugins.js';
|
|
13
|
+
import { createCapabilityRegistry } from './plugin-capabilities.js';
|
|
14
|
+
import { createPluginSettings } from './plugin-settings.js';
|
|
15
|
+
import { z } from 'zod/v4';
|
|
10
16
|
const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
|
|
11
17
|
const resourceTypes = {png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',webp:'image/webp',svg:'image/svg+xml',pdf:'application/pdf',txt:'text/plain',csv:'text/csv',json:'application/json'};
|
|
12
18
|
const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
|
|
19
|
+
const viewSelection = z.object({
|
|
20
|
+
tab: z.uuid(), file: z.string().min(1), version: z.string().regex(/^[a-f0-9]{64}$/),
|
|
21
|
+
nodes: z.array(z.array(z.string().min(1)).min(1).max(6)).max(200),
|
|
22
|
+
refresh: z.enum(['render', 'heartbeat']).optional(),
|
|
23
|
+
}).strict();
|
|
13
24
|
export function createWorkspaceHandler(directory, options = {}) {
|
|
14
25
|
const root = resolve(directory);
|
|
15
|
-
const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js'
|
|
26
|
+
const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js']);
|
|
27
|
+
if (options.capabilities) assetNames.add('library-plugin-bridge.js');
|
|
28
|
+
if (options.plugins) for (const name of ['library-plugins.js', 'library-plugins.css', 'clado-plugin-sdk.js']) assetNames.add(name);
|
|
16
29
|
const send = (res, status, type, body) => { res.writeHead(status, { 'content-type': type + '; charset=utf-8', 'cache-control':'no-store', 'x-content-type-options':'nosniff' }); res.end(body); };
|
|
17
30
|
const json = (res, status, data) => send(res, status, types.json, JSON.stringify(data));
|
|
18
31
|
const safeJson = data => JSON.stringify(data).replace(/</g,'\\u003c');
|
|
19
32
|
return async function handle(req, res, url) {
|
|
20
33
|
const route = url.pathname.slice(1);
|
|
21
|
-
|
|
34
|
+
const pluginFile = workspacePluginAssets.get(url.pathname);
|
|
35
|
+
if (!url.pathname.startsWith('/library/') && !assetNames.has(route) && !pluginFile && !(options.entrypoint && route === '')) return false;
|
|
22
36
|
try {
|
|
23
37
|
const host = req.headers.host;
|
|
24
38
|
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
|
|
25
|
-
|
|
39
|
+
const pluginAsset = options.plugins && url.pathname.startsWith('/library/plugin-assets/');
|
|
40
|
+
if (req.headers.origin && req.headers.origin !== 'http://' + host && !(pluginAsset && req.headers.origin === 'null')) throw new DocumentError('来源不匹配。',403);
|
|
41
|
+
if (url.pathname === '/library/selection' && options.publishSelection && req.method === 'POST') {
|
|
42
|
+
if (req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') throw new DocumentError('选区只接受同源页面请求。', 403);
|
|
43
|
+
const chunks = []; let size = 0;
|
|
44
|
+
for await (const chunk of req) {
|
|
45
|
+
size += chunk.length;
|
|
46
|
+
if (size > 65536) throw new DocumentError('选区太大。', 413);
|
|
47
|
+
chunks.push(chunk);
|
|
48
|
+
}
|
|
49
|
+
const selection = viewSelection.safeParse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
50
|
+
if (!selection.success) throw new DocumentError('选区参数不合法。', 400);
|
|
51
|
+
workspacePath(root, selection.data.file, selection.data.nodes.length === 0);
|
|
52
|
+
options.publishSelection(selection.data);
|
|
53
|
+
json(res, 200, { ok: true }); return true;
|
|
54
|
+
}
|
|
55
|
+
if (options.agent && url.pathname === '/library/agent') {
|
|
56
|
+
await options.agent.handle(req, res); return true;
|
|
57
|
+
}
|
|
58
|
+
if (options.settings && url.pathname === '/library/plugin-settings') {
|
|
59
|
+
const id = url.searchParams.get('id');
|
|
60
|
+
if (req.method === 'GET') { json(res, 200, options.settings.read(id)); return true; }
|
|
61
|
+
if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
|
|
62
|
+
throw new DocumentError('插件设置只接受同源页面写入。', 403);
|
|
63
|
+
}
|
|
64
|
+
const chunks = []; let size = 0;
|
|
65
|
+
for await (const chunk of req) {
|
|
66
|
+
size += chunk.length;
|
|
67
|
+
if (size > 1048576) throw new DocumentError('插件设置太大。', 413);
|
|
68
|
+
chunks.push(chunk);
|
|
69
|
+
}
|
|
70
|
+
const { value, expected } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
71
|
+
json(res, 200, options.settings.save(id, value, expected));
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
if (options.installPlugin && url.pathname === '/library/install-plugin') {
|
|
75
|
+
if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
|
|
76
|
+
throw new DocumentError('插件安装需要在工作区页面操作。', 403);
|
|
77
|
+
}
|
|
78
|
+
const chunks = []; let size = 0;
|
|
79
|
+
for await (const chunk of req) {
|
|
80
|
+
size += chunk.length;
|
|
81
|
+
if (size > 12 * 1024 * 1024) throw new DocumentError('插件包太大。', 413);
|
|
82
|
+
chunks.push(chunk);
|
|
83
|
+
}
|
|
84
|
+
json(res, 201, options.installPlugin(JSON.parse(Buffer.concat(chunks).toString('utf8'))?.files));
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
if (options.capabilities && url.pathname === '/library/plugin-bridge') {
|
|
88
|
+
const view = z.uuid().safeParse(url.searchParams.get('viewId'));
|
|
89
|
+
if (!view.success) throw new DocumentError('需要有效的 viewId。', 400);
|
|
90
|
+
if (req.method === 'GET' && req.headers.accept === 'text/event-stream' &&
|
|
91
|
+
(!req.headers['sec-fetch-site'] || req.headers['sec-fetch-site'] === 'same-origin')) {
|
|
92
|
+
options.capabilities.connect(view.data, res); return true;
|
|
93
|
+
}
|
|
94
|
+
if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
|
|
95
|
+
throw new DocumentError('插件通信只接受同源页面请求。', 403);
|
|
96
|
+
}
|
|
97
|
+
const captureId = url.searchParams.get('captureId');
|
|
98
|
+
const limit = captureId ? options.capabilities.captureResultLimit(view.data, captureId) : 262144;
|
|
99
|
+
if (!limit) throw new DocumentError('截图请求已结束或不存在。', 409);
|
|
100
|
+
const chunks = []; let size = 0;
|
|
101
|
+
for await (const chunk of req) {
|
|
102
|
+
size += chunk.length;
|
|
103
|
+
if (size > limit) throw new DocumentError('插件消息太大。', 413);
|
|
104
|
+
chunks.push(chunk);
|
|
105
|
+
}
|
|
106
|
+
const message = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
107
|
+
if (captureId && (message?.action !== 'result' || message.callId !== captureId)) {
|
|
108
|
+
throw new DocumentError('截图响应与请求不匹配。', 400);
|
|
109
|
+
}
|
|
110
|
+
json(res, 200, await options.capabilities.receive(view.data, message));
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
26
113
|
if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
|
|
114
|
+
if (options.plugins && url.pathname === '/library/plugins.json') {
|
|
115
|
+
const values = options.settings?.values() || {};
|
|
116
|
+
const descriptor = options.plugins.descriptor;
|
|
117
|
+
json(res, 200, { ...descriptor, plugins: descriptor.plugins.map(plugin => ({ ...plugin, settings: values[plugin.id] || {} })) }); return true;
|
|
118
|
+
}
|
|
119
|
+
if (pluginAsset) {
|
|
120
|
+
options.plugins.serveAsset(req, res, url); return true;
|
|
121
|
+
}
|
|
122
|
+
if (pluginFile) {
|
|
123
|
+
send(res, 200, types[route.split('.').pop()], readFileSync(pluginFile, 'utf8')); return true;
|
|
124
|
+
}
|
|
27
125
|
if (assetNames.has(route) || (options.entrypoint && route === '')) {
|
|
28
|
-
const name = route || 'library.html'; let body = readFileSync(join(assets,name),'utf8');
|
|
126
|
+
const name = route || 'library.html'; let body = readFileSync(join(assets, name),'utf8');
|
|
29
127
|
if (name === 'library.html') {
|
|
30
|
-
|
|
128
|
+
const plugins = pluginMarkup({ workspace: true, agent: !!options.agent });
|
|
129
|
+
body = body.replace('<!--CLADO-PLUGIN-STYLES-->', () => plugins.styles)
|
|
130
|
+
.replace('<!--CLADO-PLUGIN-SCRIPTS-->', () => plugins.scripts);
|
|
131
|
+
const pluginAssets = (options.capabilities ? '<script src="/library-plugin-bridge.js"></script>' : '') +
|
|
132
|
+
(options.plugins ? '<link rel="stylesheet" href="/library-plugins.css"><script src="/library-plugins.js"></script>' : '');
|
|
133
|
+
body = body.replace('</head>', pluginAssets + '</head>');
|
|
134
|
+
const pluginCatalog = options.plugins?.descriptor.plugins.map(({ id, name, version }) => ({ id, name, version })) || options.inactivePlugins?.() || [];
|
|
135
|
+
const pluginPreferenceKey = createHash('sha256').update(root).digest('hex');
|
|
136
|
+
const pluginSettings = Object.fromEntries(Object.entries(options.settings?.values() || {}).filter(([id]) => id.startsWith('clado.') && !pluginCatalog.some(plugin => plugin.id === id)));
|
|
137
|
+
body = body.replace('<script src="library.js">','<script>window.__CLADO_WORKSPACE__='+safeJson({mode:options.mode || 'mindmap',theme:options.theme || 'light',entry:options.entry || '',selection:!!options.publishSelection,plugins:!!options.plugins,agent:!!options.agent,agentProfile:options.agentProfile,pluginCatalog,pluginPreferenceKey,pluginSettings,hasPluginSettings:!!options.settings,canInstallPlugins:!!options.installPlugin})+';</script><script src="library.js">');
|
|
31
138
|
}
|
|
32
139
|
send(res,200,types[name.split('.').pop()],body); return true;
|
|
33
140
|
}
|
|
@@ -47,16 +154,16 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
47
154
|
if (url.pathname === '/library/source.mdc') { send(res,200,types.md,item.source); return true; }
|
|
48
155
|
if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('文档暂时无法解析。',422,item.diagnostics);
|
|
49
156
|
const mode = ['doc','cards','mindmap'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : options.mode || 'mindmap';
|
|
50
|
-
let html = (options.render || renderHtml)(item.doc,item.diagnostics,{file:name,title:item.doc.title,mode,theme:options.theme || 'light',library:true});
|
|
157
|
+
let html = (options.render || renderHtml)(item.doc,item.diagnostics,{file:name,title:item.doc.title,mode,theme:['light','dark'].includes(url.searchParams.get('theme')) ? url.searchParams.get('theme') : options.theme || 'light',library:true,workspaceChrome:url.searchParams.get('chrome') === 'workspace'});
|
|
51
158
|
const bodyEnd = html.lastIndexOf('</body>');
|
|
52
|
-
html = html.slice(0,bodyEnd) + '<script>window.__CLADO_FILE_PATH__='+safeJson(name)+';window.__CLADO_ANCHOR__='+safeJson(url.searchParams.get('anchor') || '')+';</script><script src="/library-canvas.js"></script>' + html.slice(bodyEnd);
|
|
159
|
+
html = html.slice(0,bodyEnd) + '<script>window.__CLADO_FILE_PATH__='+safeJson(name)+';window.__CLADO_FILE_VERSION__='+safeJson(item.version)+';window.__CLADO_ANCHOR__='+safeJson(url.searchParams.get('anchor') || '')+';</script><script src="/library-canvas.js"></script>' + html.slice(bodyEnd);
|
|
53
160
|
send(res,200,types.html,html); return true;
|
|
54
161
|
} catch (error) {
|
|
55
|
-
json(res,error.status || (error instanceof SyntaxError ? 400 : 500),{error:error.message,diagnostics:error.diagnostics || []}); return true;
|
|
162
|
+
json(res,error.status || (error instanceof SyntaxError ? 400 : 500),{error:error.message,diagnostics:error.diagnostics || [], ...(error.details && { details: error.details })}); return true;
|
|
56
163
|
}
|
|
57
164
|
};
|
|
58
165
|
}
|
|
59
|
-
export async function startWorkspace(input, { port = 4317, mode = 'mindmap', theme = 'light', entry, project = false } = {}) {
|
|
166
|
+
export async function startWorkspace(input, { port = 4317, mode = 'mindmap', theme = 'light', entry, project = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
|
|
60
167
|
const path = resolve(input);
|
|
61
168
|
if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
|
|
62
169
|
if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
|
|
@@ -66,19 +173,57 @@ export async function startWorkspace(input, { port = 4317, mode = 'mindmap', the
|
|
|
66
173
|
const ctx = contextFor(root, root); workspace = root; root = ctx.documents;
|
|
67
174
|
}
|
|
68
175
|
const ctx = contextFor(workspace, workspace, root); initialize(ctx);
|
|
176
|
+
const plugins = experimentalPlugins ? loadWorkspacePlugins(ctx.state) : null;
|
|
177
|
+
const settings = createPluginSettings(ctx, plugins?.configurations);
|
|
178
|
+
const grants = builtInGrants();
|
|
179
|
+
for (const { id, permissions } of plugins?.descriptor.plugins || []) grants.set(id, permissions);
|
|
180
|
+
const providers = [...builtInCapabilities(agentName !== 'off'), ...(plugins?.capabilities || [])];
|
|
181
|
+
const capabilities = createCapabilityRegistry({
|
|
182
|
+
workspace, workspaceId: plugins?.descriptor.workspaceId || randomUUID(),
|
|
183
|
+
providers, grants,
|
|
184
|
+
});
|
|
69
185
|
const entryFile = entry ? relative(root,workspacePath(root,entry)).split('\\').join('/') : (statSync(path).isFile() ? basename(path) : '');
|
|
70
186
|
if (entryFile) {
|
|
71
187
|
const item=readDocument(workspacePath(root,entryFile));
|
|
72
188
|
if(item.diagnostics.some(d=>d.severity==='error'))throw new DocumentError('入口 Markdown 无法解析。',422,item.diagnostics);
|
|
73
189
|
}
|
|
74
|
-
|
|
75
|
-
const
|
|
190
|
+
let selection;
|
|
191
|
+
const publishSelection = next => {
|
|
192
|
+
if (next.refresh) {
|
|
193
|
+
if (selection?.tab !== next.tab || selection.file !== next.file) return;
|
|
194
|
+
if (next.refresh === 'render') selection = { ...next, expiresAt: Date.now() + 120000 };
|
|
195
|
+
else if (selection.version === next.version) selection.expiresAt = Date.now() + 120000;
|
|
196
|
+
} else if (next.nodes.length) selection = { ...next, expiresAt: Date.now() + 120000 };
|
|
197
|
+
else if (selection?.tab === next.tab) selection = undefined;
|
|
198
|
+
};
|
|
199
|
+
const agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
|
|
200
|
+
workspace, mcpUrl: () => 'http://127.0.0.1:' + server.address().port + '/mcp',
|
|
201
|
+
...(agentName === 'acp' && { resolveLaunch: () => {
|
|
202
|
+
const { command, args, env } = settings.agentLaunch();
|
|
203
|
+
return { command, args, env };
|
|
204
|
+
} }),
|
|
205
|
+
}) : null;
|
|
206
|
+
function installPlugin(files) {
|
|
207
|
+
const previous = plugins?.capabilities.length || 0;
|
|
208
|
+
const installed = installWorkspacePlugin(ctx, files, plugins);
|
|
209
|
+
if (plugins) {
|
|
210
|
+
const descriptor = plugins.descriptor.plugins.find(plugin => plugin.id === installed.id);
|
|
211
|
+
grants.set(installed.id, descriptor.permissions);
|
|
212
|
+
providers.push(...plugins.capabilities.slice(previous));
|
|
213
|
+
settings.register(installed.id, plugins.configurations.get(installed.id));
|
|
214
|
+
}
|
|
215
|
+
return installed;
|
|
216
|
+
}
|
|
217
|
+
const handle = createWorkspaceHandler(root,{entrypoint:true,mode,theme,entry:entryFile,publishSelection,plugins,agent,agentProfile:agentName,capabilities,settings,installPlugin,
|
|
218
|
+
inactivePlugins: () => inspectWorkspacePlugins(ctx.state)});
|
|
219
|
+
const mcp = createMcpHandler(createWorkspaceService(workspace, { documentRoot: root, readSelection: () => selection?.expiresAt > Date.now() ? selection : null }), capabilities.invoke);
|
|
76
220
|
const server = createServer(async (req,res) => {
|
|
77
221
|
try { const url = new URL(req.url,'http://127.0.0.1'); if (!await mcp(req,res,url) && !await handle(req,res,url)) { res.writeHead(404);res.end('Not found'); } }
|
|
78
222
|
catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
|
|
79
223
|
});
|
|
224
|
+
if (agent) server.on('close', agent.close);
|
|
80
225
|
await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
|
|
81
226
|
const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
|
|
82
227
|
const origin = 'http://127.0.0.1:'+server.address().port;
|
|
83
|
-
return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root};
|
|
228
|
+
return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,pluginWarnings:plugins?.warnings || [],stopAgent:agent?.close,stopCapabilities:capabilities.close};
|
|
84
229
|
}
|
package/src/skill/targets.js
CHANGED
|
@@ -176,7 +176,7 @@ export function ruleBody(skillPath) {
|
|
|
176
176
|
|
|
177
177
|
clado serve
|
|
178
178
|
|
|
179
|
-
连接输出的 Streamable HTTP MCP。每次调用提供输出的 workspace,先 clado_workspace inspect,再 clado_templates read 提示词,用 clado_documents create 按模板初始化 .mdc;节点、链接与批量操作也用MCP
|
|
179
|
+
连接输出的 Streamable HTTP MCP。每次调用提供输出的 workspace,先 clado_workspace inspect,再 clado_templates read 提示词,用 clado_documents create 按模板初始化 .mdc;节点、链接与批量操作也用MCP。正文直接传多行字符串。新建、追加和唯一原文编辑可直接提交;覆盖和删除使用对应的版本。用户提到选中的卡片时通过 clado_workspace selection 读取。模板可在项目 create/update,用 pull 从用户库复制,用 push 同步到用户库;push 同时带 expectedUserTemplateVersion。
|
|
180
180
|
|
|
181
181
|
网页只展示脑图/卡片/文档,保存后自动更新。交付可用 clado build --entry overview.mdc --mode cards;默认生成只读 clado.html。工具不执行文档里的SQL、脚本或发布任务。
|
|
182
182
|
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { userTemplatePaths } from '../skill/templates.js';
|
|
5
|
+
import { VERSION } from './version.js';
|
|
6
|
+
|
|
7
|
+
const registry = 'https://registry.npmjs.org';
|
|
8
|
+
const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?![\s\S])/;
|
|
9
|
+
const cacheLifetime = 24 * 60 * 60 * 1000;
|
|
10
|
+
|
|
11
|
+
function updateInfo(latest) {
|
|
12
|
+
if (typeof latest !== 'string' || !stableVersion.test(latest)) throw new Error('npm 未返回可用的稳定版本。');
|
|
13
|
+
const installed = VERSION.split('.').map(Number), remote = latest.split('.').map(Number);
|
|
14
|
+
const difference = remote.map((part, index) => part - installed[index]).find(value => value !== 0) || 0;
|
|
15
|
+
return { current: VERSION, latest, updateAvailable: difference > 0 };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function checkUpdate() {
|
|
19
|
+
let response;
|
|
20
|
+
try {
|
|
21
|
+
response = await fetch(registry + '/-/package/cladogram/dist-tags', { signal: AbortSignal.timeout(4000), redirect: 'error' });
|
|
22
|
+
} catch {
|
|
23
|
+
throw new Error('暂时连不上 npm 官方仓库,稍后可用 clado update --check 重试。');
|
|
24
|
+
}
|
|
25
|
+
if (!response.ok) throw new Error(`npm 版本查询失败(HTTP ${response.status})。`);
|
|
26
|
+
return updateInfo((await response.json()).latest);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function notifyUpdate() {
|
|
30
|
+
const { state } = userTemplatePaths();
|
|
31
|
+
const cachePath = join(state, '.update-check.json');
|
|
32
|
+
let cache;
|
|
33
|
+
try { cache = JSON.parse(readFileSync(cachePath, 'utf8')); } catch {}
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
if (cache && now >= cache.checkedAt && now - cache.checkedAt < cacheLifetime) return;
|
|
36
|
+
|
|
37
|
+
const info = await checkUpdate().catch(() => null);
|
|
38
|
+
try {
|
|
39
|
+
mkdirSync(state, { recursive: true });
|
|
40
|
+
writeFileSync(cachePath, JSON.stringify({ checkedAt: now }) + '\n');
|
|
41
|
+
} catch {}
|
|
42
|
+
if (info?.updateAvailable) process.stderr.write(`Clado 有新版 ${info.latest}(当前 ${info.current}),运行 clado update 升级。\n`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function installUpdate(version) {
|
|
46
|
+
if (!stableVersion.test(version)) throw new Error('无法安装无效的版本号。');
|
|
47
|
+
const args = ['install', '--global', `cladogram@${version}`, `--registry=${registry}/`];
|
|
48
|
+
// Windows 的 npm 是命令脚本;参数只包含固定选项和已核对的版本号。
|
|
49
|
+
const windows = process.platform === 'win32';
|
|
50
|
+
const child = spawn(windows ? 'npm.cmd' : 'npm', args, { stdio: 'inherit', shell: windows });
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
child.once('error', error => reject(new Error(error.code === 'ENOENT' ? '找不到 npm,请先安装 Node.js 和 npm。' : error.message)));
|
|
53
|
+
child.once('close', (code, signal) => {
|
|
54
|
+
if (code === 0) resolve();
|
|
55
|
+
else reject(new Error(`npm 升级失败(${signal || `退出码 ${code}`})。`));
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/*! html-to-image 1.11.13 | https://github.com/bubkoo/html-to-image
|
|
2
|
+
MIT License
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2017-2025 W.Y.
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
|
23
|
+
*/
|
|
24
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).htmlToImage={})}(this,(function(t){"use strict";function e(t,e,n,r){return new(n||(n=Promise))((function(i,o){function u(t){try{a(r.next(t))}catch(t){o(t)}}function c(t){try{a(r.throw(t))}catch(t){o(t)}}function a(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(u,c)}a((r=r.apply(t,e||[])).next())}))}function n(t,e){var n,r,i,o,u={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function c(c){return function(a){return function(c){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(u=0)),u;)try{if(n=1,r&&(i=2&c[0]?r.return:c[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,c[1])).done)return i;switch(r=0,i&&(c=[2&c[0],i.value]),c[0]){case 0:case 1:i=c;break;case 4:return u.label++,{value:c[1],done:!1};case 5:u.label++,r=c[1],c=[0];continue;case 7:c=u.ops.pop(),u.trys.pop();continue;default:if(!(i=u.trys,(i=i.length>0&&i[i.length-1])||6!==c[0]&&2!==c[0])){u=0;continue}if(3===c[0]&&(!i||c[1]>i[0]&&c[1]<i[3])){u.label=c[1];break}if(6===c[0]&&u.label<i[1]){u.label=i[1],i=c;break}if(i&&u.label<i[2]){u.label=i[2],u.ops.push(c);break}i[2]&&u.ops.pop(),u.trys.pop();continue}c=e.call(t,u)}catch(t){c=[6,t],r=0}finally{n=i=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,a])}}}var r,i=(r=0,function(){return r+=1,"u".concat("0000".concat((Math.random()*Math.pow(36,4)<<0).toString(36)).slice(-4)).concat(r)});function o(t){for(var e=[],n=0,r=t.length;n<r;n++)e.push(t[n]);return e}var u=null;function c(t){return void 0===t&&(t={}),u||(u=t.includeStyleProperties?t.includeStyleProperties:o(window.getComputedStyle(document.documentElement)))}function a(t,e){var n=(t.ownerDocument.defaultView||window).getComputedStyle(t).getPropertyValue(e);return n?parseFloat(n.replace("px","")):0}function s(t,e){void 0===e&&(e={});var n,r,i,o=e.width||(r=a(n=t,"border-left-width"),i=a(n,"border-right-width"),n.clientWidth+r+i),u=e.height||function(t){var e=a(t,"border-top-width"),n=a(t,"border-bottom-width");return t.clientHeight+e+n}(t);return{width:o,height:u}}var l=16384;function f(t,e){return void 0===e&&(e={}),t.toBlob?new Promise((function(n){t.toBlob(n,e.type?e.type:"image/png",e.quality?e.quality:1)})):new Promise((function(n){for(var r=window.atob(t.toDataURL(e.type?e.type:void 0,e.quality?e.quality:void 0).split(",")[1]),i=r.length,o=new Uint8Array(i),u=0;u<i;u+=1)o[u]=r.charCodeAt(u);n(new Blob([o],{type:e.type?e.type:"image/png"}))}))}function h(t){return new Promise((function(e,n){var r=new Image;r.onload=function(){r.decode().then((function(){requestAnimationFrame((function(){return e(r)}))}))},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=t}))}function d(t){return e(this,void 0,void 0,(function(){return n(this,(function(e){return[2,Promise.resolve().then((function(){return(new XMLSerializer).serializeToString(t)})).then(encodeURIComponent).then((function(t){return"data:image/svg+xml;charset=utf-8,".concat(t)}))]}))}))}function v(t,r,i){return e(this,void 0,void 0,(function(){var e,o,u;return n(this,(function(n){return e="http://www.w3.org/2000/svg",o=document.createElementNS(e,"svg"),u=document.createElementNS(e,"foreignObject"),o.setAttribute("width","".concat(r)),o.setAttribute("height","".concat(i)),o.setAttribute("viewBox","0 0 ".concat(r," ").concat(i)),u.setAttribute("width","100%"),u.setAttribute("height","100%"),u.setAttribute("x","0"),u.setAttribute("y","0"),u.setAttribute("externalResourcesRequired","true"),o.appendChild(u),u.appendChild(t),[2,d(o)]}))}))}var p=function(t,e){if(t instanceof e)return!0;var n=Object.getPrototypeOf(t);return null!==n&&(n.constructor.name===e.name||p(n,e))};function g(t,e,n,r){var i=".".concat(t,":").concat(e),o=n.cssText?function(t){var e=t.getPropertyValue("content");return"".concat(t.cssText," content: '").concat(e.replace(/'|"/g,""),"';")}(n):function(t,e){return c(e).map((function(e){var n=t.getPropertyValue(e),r=t.getPropertyPriority(e);return"".concat(e,": ").concat(n).concat(r?" !important":"",";")})).join(" ")}(n,r);return document.createTextNode("".concat(i,"{").concat(o,"}"))}function m(t,e,n,r){var o=window.getComputedStyle(t,n),u=o.getPropertyValue("content");if(""!==u&&"none"!==u){var c=i();try{e.className="".concat(e.className," ").concat(c)}catch(t){return}var a=document.createElement("style");a.appendChild(g(c,n,o,r)),e.appendChild(a)}}var w="application/font-woff",y="image/jpeg",b={woff:w,woff2:w,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:y,jpeg:y,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function S(t){var e=function(t){var e=/\.([^./]*?)$/g.exec(t);return e?e[1]:""}(t).toLowerCase();return b[e]||""}function E(t){return-1!==t.search(/^(data:)/)}function x(t,e){return"data:".concat(e,";base64,").concat(t)}function C(t,r,i){return e(this,void 0,void 0,(function(){var e,o;return n(this,(function(n){switch(n.label){case 0:return[4,fetch(t,r)];case 1:if(404===(e=n.sent()).status)throw new Error('Resource "'.concat(e.url,'" not found'));return[4,e.blob()];case 2:return o=n.sent(),[2,new Promise((function(t,n){var r=new FileReader;r.onerror=n,r.onloadend=function(){try{t(i({res:e,result:r.result}))}catch(t){n(t)}},r.readAsDataURL(o)}))]}}))}))}var P={};function R(t,r,i){return e(this,void 0,void 0,(function(){var e,o,u,c,a;return n(this,(function(n){switch(n.label){case 0:if(e=function(t,e,n){var r=t.replace(/\?.*/,"");return n&&(r=t),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),e?"[".concat(e,"]").concat(r):r}(t,r,i.includeQueryParams),null!=P[e])return[2,P[e]];i.cacheBust&&(t+=(/\?/.test(t)?"&":"?")+(new Date).getTime()),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,C(t,i.fetchRequestInit,(function(t){var e=t.res,n=t.result;return r||(r=e.headers.get("Content-Type")||""),function(t){return t.split(/,/)[1]}(n)}))];case 2:return u=n.sent(),o=x(u,r),[3,4];case 3:return c=n.sent(),o=i.imagePlaceholder||"",a="Failed to fetch resource: ".concat(t),c&&(a="string"==typeof c?c:c.message),a&&console.warn(a),[3,4];case 4:return P[e]=o,[2,o]}}))}))}function T(t){return e(this,void 0,void 0,(function(){var e;return n(this,(function(n){return"data:,"===(e=t.toDataURL())?[2,t.cloneNode(!1)]:[2,h(e)]}))}))}function A(t,r){return e(this,void 0,void 0,(function(){var e,i,o,u;return n(this,(function(n){switch(n.label){case 0:return t.currentSrc?(e=document.createElement("canvas"),i=e.getContext("2d"),e.width=t.clientWidth,e.height=t.clientHeight,null==i||i.drawImage(t,0,0,e.width,e.height),[2,h(e.toDataURL())]):(o=t.poster,u=S(o),[4,R(o,u,r)]);case 1:return[2,h(n.sent())]}}))}))}function k(t,r){var i;return e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return e.trys.push([0,3,,4]),(null===(i=null==t?void 0:t.contentDocument)||void 0===i?void 0:i.body)?[4,I(t.contentDocument.body,r,!0)]:[3,2];case 1:return[2,e.sent()];case 2:return[3,4];case 3:return e.sent(),[3,4];case 4:return[2,t.cloneNode(!1)]}}))}))}var L=function(t){return null!=t.tagName&&"SVG"===t.tagName.toUpperCase()};function N(t,e,n){return p(e,Element)&&(function(t,e,n){var r=e.style;if(r){var i=window.getComputedStyle(t);i.cssText?(r.cssText=i.cssText,r.transformOrigin=i.transformOrigin):c(n).forEach((function(n){var o=i.getPropertyValue(n);if("font-size"===n&&o.endsWith("px")){var u=Math.floor(parseFloat(o.substring(0,o.length-2)))-.1;o="".concat(u,"px")}p(t,HTMLIFrameElement)&&"display"===n&&"inline"===o&&(o="block"),"d"===n&&e.getAttribute("d")&&(o="path(".concat(e.getAttribute("d"),")")),r.setProperty(n,o,i.getPropertyPriority(n))}))}}(t,e,n),function(t,e,n){m(t,e,":before",n),m(t,e,":after",n)}(t,e,n),function(t,e){p(t,HTMLTextAreaElement)&&(e.innerHTML=t.value),p(t,HTMLInputElement)&&e.setAttribute("value",t.value)}(t,e),function(t,e){if(p(t,HTMLSelectElement)){var n=e,r=Array.from(n.children).find((function(e){return t.value===e.getAttribute("value")}));r&&r.setAttribute("selected","")}}(t,e)),e}function I(t,r,i){return e(this,void 0,void 0,(function(){return n(this,(function(u){return i||!r.filter||r.filter(t)?[2,Promise.resolve(t).then((function(t){return function(t,r){return e(this,void 0,void 0,(function(){return n(this,(function(e){return p(t,HTMLCanvasElement)?[2,T(t)]:p(t,HTMLVideoElement)?[2,A(t,r)]:p(t,HTMLIFrameElement)?[2,k(t,r)]:[2,t.cloneNode(L(t))]}))}))}(t,r)})).then((function(i){return function(t,r,i){var u,c;return e(this,void 0,void 0,(function(){var e;return n(this,(function(n){switch(n.label){case 0:return L(r)?[2,r]:(e=[],0===(e=null!=(a=t).tagName&&"SLOT"===a.tagName.toUpperCase()&&t.assignedNodes?o(t.assignedNodes()):p(t,HTMLIFrameElement)&&(null===(u=t.contentDocument)||void 0===u?void 0:u.body)?o(t.contentDocument.body.childNodes):o((null!==(c=t.shadowRoot)&&void 0!==c?c:t).childNodes)).length||p(t,HTMLVideoElement)?[2,r]:[4,e.reduce((function(t,e){return t.then((function(){return I(e,i)})).then((function(t){t&&r.appendChild(t)}))}),Promise.resolve())]);case 1:return n.sent(),[2,r]}var a}))}))}(t,i,r)})).then((function(e){return N(t,e,r)})).then((function(t){return function(t,r){return e(this,void 0,void 0,(function(){var e,i,o,u,c,a,s,l,f,h,d,v,p;return n(this,(function(n){switch(n.label){case 0:if(0===(e=t.querySelectorAll?t.querySelectorAll("use"):[]).length)return[2,t];i={},p=0,n.label=1;case 1:return p<e.length?(o=e[p],(u=o.getAttribute("xlink:href"))?(c=t.querySelector(u),a=document.querySelector(u),c||!a||i[u]?[3,3]:(s=i,l=u,[4,I(a,r,!0)])):[3,3]):[3,4];case 2:s[l]=n.sent(),n.label=3;case 3:return p++,[3,1];case 4:if((f=Object.values(i)).length){for(h="http://www.w3.org/1999/xhtml",(d=document.createElementNS(h,"svg")).setAttribute("xmlns",h),d.style.position="absolute",d.style.width="0",d.style.height="0",d.style.overflow="hidden",d.style.display="none",v=document.createElementNS(h,"defs"),d.appendChild(v),p=0;p<f.length;p++)v.appendChild(f[p]);t.appendChild(d)}return[2,t]}}))}))}(t,r)}))]:[2,null]}))}))}var D=/url\((['"]?)([^'"]+?)\1\)/g,H=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,M=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function F(t,r,i,o,u){return e(this,void 0,void 0,(function(){var e,c,a,s;return n(this,(function(n){switch(n.label){case 0:return n.trys.push([0,5,,6]),e=i?function(t,e){if(t.match(/^[a-z]+:\/\//i))return t;if(t.match(/^\/\//))return window.location.protocol+t;if(t.match(/^[a-z]+:/i))return t;var n=document.implementation.createHTMLDocument(),r=n.createElement("base"),i=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(i),e&&(r.href=e),i.href=t,i.href}(r,i):r,c=S(r),a=void 0,u?[4,u(e)]:[3,2];case 1:return s=n.sent(),a=x(s,c),[3,4];case 2:return[4,R(e,c,o)];case 3:a=n.sent(),n.label=4;case 4:return[2,t.replace((l=r,f=l.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1"),new RegExp("(url\\(['\"]?)(".concat(f,")(['\"]?\\))"),"g")),"$1".concat(a,"$3"))];case 5:return n.sent(),[3,6];case 6:return[2,t]}var l,f}))}))}function V(t){return-1!==t.search(D)}function q(t,r,i){return e(this,void 0,void 0,(function(){var e,o;return n(this,(function(n){return V(t)?(e=function(t,e){var n=e.preferredFontFormat;return n?t.replace(M,(function(t){for(;;){var e=H.exec(t)||[],r=e[0],i=e[2];if(!i)return"";if(i===n)return"src: ".concat(r,";")}})):t}(t,i),o=function(t){var e=[];return t.replace(D,(function(t,n,r){return e.push(r),t})),e.filter((function(t){return!E(t)}))}(e),[2,o.reduce((function(t,e){return t.then((function(t){return F(t,e,r,i)}))}),Promise.resolve(e))]):[2,t]}))}))}function U(t,r,i){var o;return e(this,void 0,void 0,(function(){var e,u;return n(this,(function(n){switch(n.label){case 0:return(e=null===(o=r.style)||void 0===o?void 0:o.getPropertyValue(t))?[4,q(e,null,i)]:[3,2];case 1:return u=n.sent(),r.style.setProperty(t,u,r.style.getPropertyPriority(t)),[2,!0];case 2:return[2,!1]}}))}))}function j(t,r){return e(this,void 0,void 0,(function(){var e,i;return n(this,(function(n){switch(n.label){case 0:return[4,U("background",t,r)];case 1:return n.sent()?[3,3]:[4,U("background-image",t,r)];case 2:n.sent(),n.label=3;case 3:return[4,U("mask",t,r)];case 4:return(i=n.sent())?[3,6]:[4,U("-webkit-mask",t,r)];case 5:i=n.sent(),n.label=6;case 6:return(e=i)?[3,8]:[4,U("mask-image",t,r)];case 7:e=n.sent(),n.label=8;case 8:return e?[3,10]:[4,U("-webkit-mask-image",t,r)];case 9:n.sent(),n.label=10;case 10:return[2]}}))}))}function O(t,r){return e(this,void 0,void 0,(function(){var e,i,o;return n(this,(function(n){switch(n.label){case 0:return(e=p(t,HTMLImageElement))&&!E(t.src)||p(t,SVGImageElement)&&!E(t.href.baseVal)?[4,R(i=e?t.src:t.href.baseVal,S(i),r)]:[2];case 1:return o=n.sent(),[4,new Promise((function(n,i){t.onload=n,t.onerror=r.onImageErrorHandler?function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];try{n(r.onImageErrorHandler.apply(r,t))}catch(t){i(t)}}:i;var u=t;u.decode&&(u.decode=n),"lazy"===u.loading&&(u.loading="eager"),e?(t.srcset="",t.src=o):t.href.baseVal=o}))];case 2:return n.sent(),[2]}}))}))}function B(t,r){return e(this,void 0,void 0,(function(){var e,i;return n(this,(function(n){switch(n.label){case 0:return e=o(t.childNodes),i=e.map((function(t){return z(t,r)})),[4,Promise.all(i).then((function(){return t}))];case 1:return n.sent(),[2]}}))}))}function z(t,r){return e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return p(t,Element)?[4,j(t,r)]:[3,4];case 1:return e.sent(),[4,O(t,r)];case 2:return e.sent(),[4,B(t,r)];case 3:e.sent(),e.label=4;case 4:return[2]}}))}))}var W={};function $(t){return e(this,void 0,void 0,(function(){var e,r;return n(this,(function(n){switch(n.label){case 0:return null!=(e=W[t])?[2,e]:[4,fetch(t)];case 1:return[4,n.sent().text()];case 2:return r=n.sent(),e={url:t,cssText:r},W[t]=e,[2,e]}}))}))}function G(t,r){return e(this,void 0,void 0,(function(){var i,o,u,c,a=this;return n(this,(function(s){return i=t.cssText,o=/url\(["']?([^"')]+)["']?\)/g,u=i.match(/url\([^)]+\)/g)||[],c=u.map((function(u){return e(a,void 0,void 0,(function(){var e;return n(this,(function(n){return(e=u.replace(o,"$1")).startsWith("https://")||(e=new URL(e,t.url).href),[2,C(e,r.fetchRequestInit,(function(t){var e=t.result;return i=i.replace(u,"url(".concat(e,")")),[u,e]}))]}))}))})),[2,Promise.all(c).then((function(){return i}))]}))}))}function _(t){if(null==t)return[];for(var e=[],n=t.replace(/(\/\*[\s\S]*?\*\/)/gi,""),r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");;){if(null===(u=r.exec(n)))break;e.push(u[0])}n=n.replace(r,"");for(var i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");;){var u;if(null===(u=i.exec(n))){if(null===(u=o.exec(n)))break;i.lastIndex=o.lastIndex}else o.lastIndex=i.lastIndex;e.push(u[0])}return e}function J(t,r){return e(this,void 0,void 0,(function(){var e,i;return n(this,(function(n){return e=[],i=[],t.forEach((function(e){if("cssRules"in e)try{o(e.cssRules||[]).forEach((function(t,n){if(t.type===CSSRule.IMPORT_RULE){var o=n+1,u=$(t.href).then((function(t){return G(t,r)})).then((function(t){return _(t).forEach((function(t){try{e.insertRule(t,t.startsWith("@import")?o+=1:e.cssRules.length)}catch(e){console.error("Error inserting rule from remote css",{rule:t,error:e})}}))})).catch((function(t){console.error("Error loading remote css",t.toString())}));i.push(u)}}))}catch(o){var n=t.find((function(t){return null==t.href}))||document.styleSheets[0];null!=e.href&&i.push($(e.href).then((function(t){return G(t,r)})).then((function(t){return _(t).forEach((function(t){n.insertRule(t,n.cssRules.length)}))})).catch((function(t){console.error("Error loading remote stylesheet",t)}))),console.error("Error inlining remote css file",o)}})),[2,Promise.all(i).then((function(){return t.forEach((function(t){if("cssRules"in t)try{o(t.cssRules||[]).forEach((function(t){e.push(t)}))}catch(e){console.error("Error while reading CSS rules from ".concat(t.href),e)}})),e}))]}))}))}function Q(t){return t.filter((function(t){return t.type===CSSRule.FONT_FACE_RULE})).filter((function(t){return V(t.style.getPropertyValue("src"))}))}function X(t,r){return e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:if(null==t.ownerDocument)throw new Error("Provided element is not within a Document");return[4,J(o(t.ownerDocument.styleSheets),r)];case 1:return[2,Q(e.sent())]}}))}))}function K(t){return t.trim().replace(/["']/g,"")}function Y(t,r){return e(this,void 0,void 0,(function(){var e,i;return n(this,(function(n){switch(n.label){case 0:return[4,X(t,r)];case 1:return e=n.sent(),i=function(t){var e=new Set;return function t(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach((function(t){e.add(K(t))})),Array.from(n.children).forEach((function(e){e instanceof HTMLElement&&t(e)}))}(t),e}(t),[4,Promise.all(e.filter((function(t){return i.has(K(t.style.fontFamily))})).map((function(t){var e=t.parentStyleSheet?t.parentStyleSheet.href:null;return q(t.cssText,e,r)})))];case 2:return[2,n.sent().join("\n")]}}))}))}function Z(t,r){return e(this,void 0,void 0,(function(){var e,i,o,u,c;return n(this,(function(n){switch(n.label){case 0:return null==r.fontEmbedCSS?[3,1]:(i=r.fontEmbedCSS,[3,5]);case 1:return r.skipFonts?(o=null,[3,4]):[3,2];case 2:return[4,Y(t,r)];case 3:o=n.sent(),n.label=4;case 4:i=o,n.label=5;case 5:return(e=i)&&(u=document.createElement("style"),c=document.createTextNode(e),u.appendChild(c),t.firstChild?t.insertBefore(u,t.firstChild):t.appendChild(u)),[2]}}))}))}function tt(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){var e,i,o,u;return n(this,(function(n){switch(n.label){case 0:return e=s(t,r),i=e.width,o=e.height,[4,I(t,r,!0)];case 1:return[4,Z(u=n.sent(),r)];case 2:return n.sent(),[4,z(u,r)];case 3:return n.sent(),function(t,e){var n=t.style;e.backgroundColor&&(n.backgroundColor=e.backgroundColor),e.width&&(n.width="".concat(e.width,"px")),e.height&&(n.height="".concat(e.height,"px"));var r=e.style;null!=r&&Object.keys(r).forEach((function(t){n[t]=r[t]}))}(u,r),[4,v(u,i,o)];case 4:return[2,n.sent()]}}))}))}function et(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){var e,i,o,u,c,a,f,d,v;return n(this,(function(n){switch(n.label){case 0:return e=s(t,r),i=e.width,o=e.height,[4,tt(t,r)];case 1:return[4,h(n.sent())];case 2:return u=n.sent(),c=document.createElement("canvas"),a=c.getContext("2d"),f=r.pixelRatio||function(){var t,e;try{e=process}catch(t){}var n=e&&e.env?e.env.devicePixelRatio:null;return n&&(t=parseInt(n,10),Number.isNaN(t)&&(t=1)),t||window.devicePixelRatio||1}(),d=r.canvasWidth||i,v=r.canvasHeight||o,c.width=d*f,c.height=v*f,r.skipAutoScale||function(t){(t.width>l||t.height>l)&&(t.width>l&&t.height>l?t.width>t.height?(t.height*=l/t.width,t.width=l):(t.width*=l/t.height,t.height=l):t.width>l?(t.height*=l/t.width,t.width=l):(t.width*=l/t.height,t.height=l))}(c),c.style.width="".concat(d),c.style.height="".concat(v),r.backgroundColor&&(a.fillStyle=r.backgroundColor,a.fillRect(0,0,c.width,c.height)),a.drawImage(u,0,0,c.width,c.height),[2,c]}}))}))}t.getFontEmbedCSS=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){return n(this,(function(e){return[2,Y(t,r)]}))}))},t.toBlob=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return[4,et(t,r)];case 1:return[4,f(e.sent())];case 2:return[2,e.sent()]}}))}))},t.toCanvas=et,t.toJpeg=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return[4,et(t,r)];case 1:return[2,e.sent().toDataURL("image/jpeg",r.quality||1)]}}))}))},t.toPixelData=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){var e,i,o,u;return n(this,(function(n){switch(n.label){case 0:return e=s(t,r),i=e.width,o=e.height,[4,et(t,r)];case 1:return u=n.sent(),[2,u.getContext("2d").getImageData(0,0,i,o).data]}}))}))},t.toPng=function(t,r){return void 0===r&&(r={}),e(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return[4,et(t,r)];case 1:return[2,e.sent().toDataURL()]}}))}))},t.toSvg=tt}));
|
package/src/workspace/content.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { fenceOf } from '../core/parse.js';
|
|
2
2
|
import { DocumentError } from './documents.js';
|
|
3
|
+
import { fail } from './storage.js';
|
|
3
4
|
|
|
4
5
|
/** 1-based 正文块:空行分段,代码围栏(包括内部空行)始终为一个完整块。 */
|
|
5
6
|
export function paragraphs(content) {
|
|
@@ -42,8 +43,8 @@ export function editContent(content, text, position = { mode: 'append' }) {
|
|
|
42
43
|
} else {
|
|
43
44
|
if (typeof anchor !== 'string' || !anchor) throw new DocumentError('anchor 需要非空、唯一的原文。');
|
|
44
45
|
const at = content.indexOf(anchor);
|
|
45
|
-
if (at < 0)
|
|
46
|
-
if (content.indexOf(anchor, at + 1) >= 0)
|
|
46
|
+
if (at < 0) fail('当前节点找不到这段原文,请重新读取节点正文。', 409, { code: 'ANCHOR_NOT_FOUND' });
|
|
47
|
+
if (content.indexOf(anchor, at + 1) >= 0) fail('原文在当前节点中出现多次,请提供带更多上下文的原文。', 409, { code: 'ANCHOR_AMBIGUOUS' });
|
|
47
48
|
start = mode === 'after' ? at + anchor.length : at;
|
|
48
49
|
end = mode === 'replace' ? at + anchor.length : start;
|
|
49
50
|
}
|
package/src/workspace/service.js
CHANGED
|
@@ -2,7 +2,7 @@ import { existsSync } from 'node:fs';
|
|
|
2
2
|
import { resolve } from 'node:path';
|
|
3
3
|
import { parseDocument, splitFrontMatter } from '../core/parse.js';
|
|
4
4
|
import { versionOf } from './documents.js';
|
|
5
|
-
import { treeOf, records, findNode, siblings, samePath, insidePath, checkTitle, checkBody, serializeTree, withMetadata } from './tree.js';
|
|
5
|
+
import { treeOf, records, findNode, siblings, samePath, insidePath, checkTitle, checkBody, serializeTree, replaceNodeBody, withMetadata } from './tree.js';
|
|
6
6
|
import { ancestorTemplateContexts, contextFor, initialize, locked, mergeAncestorTemplates, snapshot, safeFile, fail, commit, userTemplateContext } from './storage.js';
|
|
7
7
|
import { allReferences, linkHref, resolveReference, rewriteReferences } from './references.js';
|
|
8
8
|
import { editContent, paragraphs, paragraphLocations, contentLocation } from './content.js';
|
|
@@ -12,7 +12,9 @@ import { sortDiagnostics, summarizeDiagnostics } from '../core/diagnostics.js';
|
|
|
12
12
|
|
|
13
13
|
const copySnapshot = state => ({ ...state, documents: new Map(state.documents), templates: new Map(state.templates) });
|
|
14
14
|
const required = (value, name) => { if (value === undefined || value === null || value === '') fail('缺少参数:' + name); return value; };
|
|
15
|
-
const
|
|
15
|
+
const nodeSnapshot = node => [node.title, node.level, node.content, node.children.map(nodeSnapshot)];
|
|
16
|
+
const nodeVersion = record => versionOf(JSON.stringify([record.path, nodeSnapshot(record.node)]));
|
|
17
|
+
const publicNode = (record, includeContent = true) => ({ path: record.path, parent: record.parent, index: record.index, title: record.node.title, level: record.node.level ?? record.path.length, nodeVersion: nodeVersion(record), location: record.node.location, children: record.node.children.map(n => [...record.path, n.title]), ...(includeContent ? { content: record.node.content, paragraphs: paragraphLocations(record.node.content, record.node.location.bodyStartLine) } : {}) });
|
|
16
18
|
|
|
17
19
|
function locatedReferences(documents) {
|
|
18
20
|
const trees = new Map(), indexes = new Map();
|
|
@@ -23,7 +25,7 @@ function locatedReferences(documents) {
|
|
|
23
25
|
const { media, ...reference } = ref;
|
|
24
26
|
const point = mediaTargetPoint(ref.link.title);
|
|
25
27
|
const targetPoint = point && ref.target.path && targetMediaPoint(findNode(treeOf(documents.get(ref.target.file), ref.target.file), ref.target.path), point);
|
|
26
|
-
return { ...reference, linkIndex, href: ref.link.target, sourceText: record.node.content.slice(ref.link.start, ref.link.end), location: contentLocation(record.node.content, ref.link.start, ref.link.end, record.node.location.bodyStartLine), ...(media?.valid ? { sourcePoint: publicMediaPoint(record, media) } : {}), ...(targetPoint ? { targetPoint } : {}) };
|
|
28
|
+
return { ...reference, linkIndex, nodeVersion: nodeVersion(record), href: ref.link.target, sourceText: record.node.content.slice(ref.link.start, ref.link.end), location: contentLocation(record.node.content, ref.link.start, ref.link.end, record.node.location.bodyStartLine), ...(media?.valid ? { sourcePoint: publicMediaPoint(record, media) } : {}), ...(targetPoint ? { targetPoint } : {}) };
|
|
27
29
|
});
|
|
28
30
|
}
|
|
29
31
|
|
|
@@ -68,7 +70,7 @@ function resolveResults(state, results) {
|
|
|
68
70
|
if (!result.node) return { ...located, location: { startLine: 1, endLine: source.split('\n').length }, ...(['document.create','document.copy','document.update'].includes(result.type) ? { nodes: records(tree).map(r => ({ path: r.path, index: r.index, location: r.node.location, paragraphs: paragraphLocations(r.node.content, r.node.location.bodyStartLine).map(({ preview, ...position }) => position) })) } : {}) };
|
|
69
71
|
const record = records(tree).find(r => samePath(r.path, result.node));
|
|
70
72
|
if (!record) return { ...located, deleted: true, locationStatus: 'node_no_longer_exists' };
|
|
71
|
-
Object.assign(located, { index: record.index, location: record.node.location, paragraphs: paragraphLocations(record.node.content, record.node.location.bodyStartLine) });
|
|
73
|
+
Object.assign(located, { index: record.index, nodeVersion: nodeVersion(record), location: record.node.location, paragraphs: paragraphLocations(record.node.content, record.node.location.bodyStartLine) });
|
|
72
74
|
if (contentText) {
|
|
73
75
|
const unchanged = contentRange && versionOf(record.node.content) === contentBodyVersion && record.node.content.slice(contentRange.start, contentRange.end) === contentText;
|
|
74
76
|
const start = unchanged ? contentRange.start : record.node.content.indexOf(contentText);
|
|
@@ -108,6 +110,21 @@ function getTree(state, file) {
|
|
|
108
110
|
if (tree.diagnostics.some(d => d.severity === 'error')) fail('先用文档 update 修复解析错误,再操作节点。', 422, { diagnostics: tree.diagnostics });
|
|
109
111
|
return tree;
|
|
110
112
|
}
|
|
113
|
+
function projectSelection(state, selection) {
|
|
114
|
+
if (!selection) return { selectionStatus: 'empty', nodes: [] };
|
|
115
|
+
const { file, version, nodes } = selection, source = state.documents.get(file);
|
|
116
|
+
const stale = { file, selectionStatus: 'stale', nodes: [] };
|
|
117
|
+
if (source === undefined || version !== versionOf(source)) return stale;
|
|
118
|
+
const all = records(getTree(state, file));
|
|
119
|
+
const selected = [];
|
|
120
|
+
for (const path of nodes) {
|
|
121
|
+
const matches = all.filter(record => samePath(record.path, path));
|
|
122
|
+
if (matches.length !== 1) return stale;
|
|
123
|
+
const descendants = all.filter(record => record.path.length > path.length && insidePath(record.path, path));
|
|
124
|
+
selected.push({ ...publicNode(matches[0]), descendants: descendants.map(record => publicNode(record)) });
|
|
125
|
+
}
|
|
126
|
+
return { file, version, selectionStatus: 'ready', nodes: selected };
|
|
127
|
+
}
|
|
111
128
|
function validate(state, files = state.documents.keys(), strict = false) {
|
|
112
129
|
const diagnostics = [], trees = new Map();
|
|
113
130
|
for (const file of files) {
|
|
@@ -158,6 +175,34 @@ function fullDiagnostics(ctx, state, templateScope = 'project-template') {
|
|
|
158
175
|
}
|
|
159
176
|
return sortDiagnostics(list);
|
|
160
177
|
}
|
|
178
|
+
function checkWriteBase(state, op, workspaceGuarded) {
|
|
179
|
+
const { type, file, node, expectedFileVersion, expectedNodeVersion, position } = op;
|
|
180
|
+
if (type.startsWith('template.')) {
|
|
181
|
+
if (expectedFileVersion !== undefined || expectedNodeVersion !== undefined) fail('模板写入使用 expectedWorkspaceVersion。');
|
|
182
|
+
if (!workspaceGuarded) required(op.expectedWorkspaceVersion, 'expectedWorkspaceVersion');
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (expectedFileVersion !== undefined) {
|
|
186
|
+
const source = state.documents.get(file);
|
|
187
|
+
const currentVersion = source === undefined ? null : versionOf(source);
|
|
188
|
+
if (expectedFileVersion !== currentVersion) fail('文档已变化,请重新读取目标文档。', 409, { code: 'FILE_VERSION_CONFLICT', currentVersion });
|
|
189
|
+
}
|
|
190
|
+
if (expectedNodeVersion !== undefined) {
|
|
191
|
+
if (!node || !/^(node\.(insert|update|rename|move|delete)|link\.(connect|disconnect))$/.test(type)) fail('expectedNodeVersion 需要修改现有节点或它的链接。');
|
|
192
|
+
const record = findNode(getTree(state, file), node);
|
|
193
|
+
const currentVersion = nodeVersion(record);
|
|
194
|
+
if (expectedNodeVersion !== currentVersion) fail('节点已变化,请重新读取目标节点。', 409, { code: 'NODE_VERSION_CONFLICT', currentVersion, location: record.node.location });
|
|
195
|
+
}
|
|
196
|
+
if (!workspaceGuarded && type === 'node.move' && op.index !== undefined && op.targetFile && op.targetFile !== file) fail('跨文档按序号移动需要 expectedWorkspaceVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
|
|
197
|
+
if (workspaceGuarded || expectedFileVersion !== undefined) return;
|
|
198
|
+
const needsFileVersion = type === 'node.create' && op.index !== undefined || type === 'node.move' && op.index !== undefined || type === 'link.connect' && op.targetPoint;
|
|
199
|
+
if (needsFileVersion) fail('按同级序号或目标表格行写入,需要 expectedFileVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
|
|
200
|
+
if (expectedNodeVersion !== undefined) return;
|
|
201
|
+
const safeWithoutVersion = ['document.create', 'document.copy', 'node.create'].includes(type) ||
|
|
202
|
+
type === 'node.update' && position?.anchor !== undefined ||
|
|
203
|
+
['node.insert', 'link.connect'].includes(type) && position?.paragraph === undefined && !op.sourcePoint;
|
|
204
|
+
if (!safeWithoutVersion) fail('此操作需要目标版本,请使用 expectedFileVersion;节点操作也可使用 expectedNodeVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
|
|
205
|
+
}
|
|
161
206
|
function applyOperation(ctx, state, op) {
|
|
162
207
|
const type = required(op.type, 'type'), before = new Map(state.documents);
|
|
163
208
|
if (op.position !== undefined && !['node.insert','node.update','link.connect'].includes(type)) fail('position 仅用于 node.insert/node.update/link.connect。');
|
|
@@ -236,10 +281,12 @@ function applyOperation(ctx, state, op) {
|
|
|
236
281
|
if (type === 'node.insert' && !op.content.trim()) fail('插入内容不能为空。');
|
|
237
282
|
if (type === 'node.update' && op.position && op.position.mode !== 'replace') fail('update 的 position 只支持 replace;插入正文请用 insert。');
|
|
238
283
|
if (type === 'node.insert' && op.position?.mode === 'replace') fail('替换正文请用 update,insert 支持 append/prepend/before/after。');
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
284
|
+
const content = op.content.replaceAll('\r\n', '\n');
|
|
285
|
+
const edited = op.position || type === 'node.insert' ? editContent(record.node.content, content, op.position) : { content };
|
|
286
|
+
checkBody(edited.content);
|
|
287
|
+
const start = edited.start === undefined ? 0 : edited.start + content.length - content.trimStart().length;
|
|
288
|
+
state.documents.set(file, replaceNodeBody(tree, record.node, edited.content));
|
|
289
|
+
return { contentText: content.trim(), contentRange: { start, end: start + content.trim().length }, contentBodyVersion: versionOf(edited.content.trim()), ...(op.position || type === 'node.insert' ? { placement: op.position || { mode: 'append' } } : {}) };
|
|
243
290
|
}
|
|
244
291
|
if (type === 'node.rename') {
|
|
245
292
|
checkTitle(op.title);
|
|
@@ -302,19 +349,21 @@ function applyOperation(ctx, state, op) {
|
|
|
302
349
|
const links = markdownLinks(edited.content);
|
|
303
350
|
if (!links.some(link => link.start === expectedStart && link.target === href)) fail('该位置不能生成独立可解析的链接:不能插入代码或现有链接内部;替换旧链接时请把完整 sourceText 用作 anchor。');
|
|
304
351
|
if (op.sourcePoint && !mediaLinkLocations(edited.content, links).get(expectedStart)?.valid) fail('无法将链接绑定到指定内容。', 422, { code: 'INVALID_MEDIA_SOURCE' });
|
|
305
|
-
checkBody(edited.content);
|
|
306
|
-
state.documents.set(file,
|
|
352
|
+
checkBody(edited.content);
|
|
353
|
+
state.documents.set(file, replaceNodeBody(tree, record.node, edited.content));
|
|
354
|
+
return { contentText: linkText, contentRange: { start: expectedStart, end: expectedStart + linkText.length }, contentBodyVersion: versionOf(edited.content), placement: placement || { mode: 'append' }, mediaLinkOnly: !!op.sourcePoint };
|
|
307
355
|
}
|
|
308
356
|
if (type === 'link.disconnect') {
|
|
309
357
|
const matching = locatedReferences(before).filter(r => r.file === file && samePath(r.node, record.path) && (op.linkIndex === undefined || r.linkIndex === op.linkIndex) && (op.linkIndex !== undefined && op.targetFile === undefined && op.targetNode === undefined || r.target.file === (op.targetFile || file) && samePath(r.target.path, op.targetNode || null)));
|
|
310
358
|
if (!matching.length) fail('找不到这条链接。', 404);
|
|
311
|
-
|
|
312
|
-
|
|
359
|
+
let content = record.node.content;
|
|
360
|
+
for (const ref of matching.sort((a, b) => b.link.start - a.link.start)) content = content.slice(0, ref.link.start) + (ref.link.title?.startsWith('clado:') ? '' : ref.label) + content.slice(ref.link.end);
|
|
361
|
+
state.documents.set(file, replaceNodeBody(tree, record.node, content)); return;
|
|
313
362
|
}
|
|
314
363
|
fail('不支持的操作:' + type);
|
|
315
364
|
}
|
|
316
365
|
|
|
317
|
-
export function createWorkspaceService(scope, { documentRoot } = {}) {
|
|
366
|
+
export function createWorkspaceService(scope, { documentRoot, readSelection } = {}) {
|
|
318
367
|
scope = resolve(scope);
|
|
319
368
|
const diagnosticCache = new Map();
|
|
320
369
|
function templateLayers(ctx, user) {
|
|
@@ -354,6 +403,10 @@ export function createWorkspaceService(scope, { documentRoot } = {}) {
|
|
|
354
403
|
const state = { ...snapshot(ctx), ...layers, userTemplates: userState.templates };
|
|
355
404
|
const common = { workspace: ctx.workspace, workspaceVersion: state.version, userTemplateRoot: user.templates, userTemplateVersion: userState.version };
|
|
356
405
|
if (tool === 'clado_workspace') {
|
|
406
|
+
if (args.action === 'selection') {
|
|
407
|
+
const selection = ctx.workspace === scope ? readSelection?.() : null;
|
|
408
|
+
return { ...common, ...projectSelection(state, selection) };
|
|
409
|
+
}
|
|
357
410
|
if (args.action === 'init' || args.action === 'inspect') return { ...common, documentRoot: ctx.documents, templateRoot: ctx.templates, ancestorTemplateRoots: ancestorRoots, documents: [...state.documents].map(([file, source]) => ({ file, version: versionOf(source), title: parseDocument(source).doc.title })) };
|
|
358
411
|
if (args.action === 'validate') { const diagnostics = validate(state, state.documents.keys(), true); return { ...common, valid: !diagnostics.some(d => d.severity === 'error'), diagnostics }; }
|
|
359
412
|
if (args.action === 'search') {
|
|
@@ -361,7 +414,7 @@ export function createWorkspaceService(scope, { documentRoot } = {}) {
|
|
|
361
414
|
for (const [file, source] of state.documents) for (const record of records(treeOf(source, file))) if ((file + '\n' + record.node.title + '\n' + record.node.content).toLowerCase().includes(query)) hits.push({ file, ...publicNode(record, args.includeContent === true) });
|
|
362
415
|
return { ...common, total: hits.length, nodes: hits.slice(args.offset || 0, (args.offset || 0) + (args.limit || 50)) };
|
|
363
416
|
}
|
|
364
|
-
fail('workspace action 支持 init / inspect / validate / search。');
|
|
417
|
+
fail('workspace action 支持 init / inspect / validate / search / selection。');
|
|
365
418
|
}
|
|
366
419
|
if (tool === 'clado_templates' && ['list', 'read'].includes(args.action)) {
|
|
367
420
|
const scope = args.scope || 'project', visible = scope === 'user' ? { templates: new Map(), userTemplates: userState.templates, userTemplateRoot: user.templates } : state;
|
|
@@ -405,7 +458,7 @@ export function createWorkspaceService(scope, { documentRoot } = {}) {
|
|
|
405
458
|
}
|
|
406
459
|
if (tool === 'clado_nodes' && ['read', 'query'].includes(args.action)) {
|
|
407
460
|
const tree = getTree(state, args.file), record = findNode(tree, args.node), all = records(tree);
|
|
408
|
-
if (args.action === 'read') return { ...common, file: args.file, ...publicNode(record) };
|
|
461
|
+
if (args.action === 'read') return { ...common, file: args.file, version: tree.version, ...publicNode(record) };
|
|
409
462
|
let found;
|
|
410
463
|
switch (args.relation) {
|
|
411
464
|
case 'parent': found = all.filter(r => samePath(r.path, record.parent)); break;
|
|
@@ -433,22 +486,29 @@ export function createWorkspaceService(scope, { documentRoot } = {}) {
|
|
|
433
486
|
if (tool === 'clado_links' && args.action === 'list') return { ...common, links: locatedReferences(state.documents).filter(r => (!args.file || r.file === args.file) && (!args.node || samePath(r.node, args.node))).map(({ link, ...ref }) => ref) };
|
|
434
487
|
const operations = tool === 'clado_batch' ? args.operations : [{ ...args, type: ({ clado_documents: 'document.', clado_nodes: 'node.', clado_links: 'link.', clado_templates: 'template.' }[tool] || fail('没有这个工具。')) + args.action }];
|
|
435
488
|
if (!Array.isArray(operations) || !operations.length || operations.length > 100) fail('operations 需要1–100个操作。');
|
|
436
|
-
const expectedVersion =
|
|
437
|
-
if (expectedVersion !== state.version) fail('工作区已变化,请重新读取再提交。', 409, { code: 'VERSION_CONFLICT', currentVersion: state.version });
|
|
489
|
+
const expectedVersion = args.expectedWorkspaceVersion;
|
|
490
|
+
if (expectedVersion !== undefined && expectedVersion !== state.version) fail('工作区已变化,请重新读取再提交。', 409, { code: 'VERSION_CONFLICT', currentVersion: state.version });
|
|
438
491
|
const candidate = copySnapshot(state);
|
|
439
492
|
const results = [];
|
|
440
493
|
for (let i = 0; i < operations.length; i++) {
|
|
441
494
|
try {
|
|
442
|
-
const
|
|
443
|
-
|
|
444
|
-
|
|
495
|
+
const op = operations[i];
|
|
496
|
+
if (op.file !== undefined) safeFile(ctx.documents, op.file);
|
|
497
|
+
checkWriteBase(candidate, op, expectedVersion !== undefined);
|
|
498
|
+
const feedback = applyOperation(ctx, candidate, op);
|
|
499
|
+
remapResults(results, op); results.push(receipt(op, i, feedback));
|
|
500
|
+
} catch (error) {
|
|
501
|
+
const { file, node, position } = operations[i];
|
|
502
|
+
error.details = { file, node, ...(position ? { position } : {}), ...error.details, operationIndex: i, previewDiagnostics: fullDiagnostics(ctx, candidate) };
|
|
503
|
+
throw error;
|
|
504
|
+
}
|
|
445
505
|
}
|
|
446
506
|
const changedFiles = new Set([...candidate.documents.keys()].filter(file => candidate.documents.get(file) !== state.documents.get(file)));
|
|
447
507
|
const diagnostics = validate(candidate, changedFiles);
|
|
448
508
|
if (diagnostics.some(d => d.severity === 'error')) fail('整批校验失败,未保存任何操作。', 422, { diagnostics, previewDiagnostics: fullDiagnostics(ctx, candidate) });
|
|
449
509
|
const locations = resolveResults(candidate, results);
|
|
450
510
|
if (args.dryRun) return { ...common, dryRun: true, results: locations, previewDiagnostics: fullDiagnostics(ctx, candidate), changedFiles: [...changedFiles], changedTemplates: [...new Set([...state.templates.keys(), ...candidate.templates.keys()])].filter(file => state.templates.get(file) !== candidate.templates.get(file)), diagnostics };
|
|
451
|
-
const changes = commit(ctx, state, candidate,
|
|
511
|
+
const changes = commit(ctx, state, candidate, state.version);
|
|
452
512
|
return { ...common, workspaceVersion: snapshot(ctx).version, changes, results: locations, diagnostics };
|
|
453
513
|
};
|
|
454
514
|
return locked(ctx, () => ctx.state === user.state ? run() : locked(user, run));
|