cladogram 0.5.3 → 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 +19 -0
- package/bin/clado.js +13 -2
- package/docs/plugin-development.md +135 -0
- package/docs/plugin-ui.md +43 -0
- package/docs/release.md +7 -0
- package/package.json +7 -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 +4 -0
- package/src/html/app-css.js +9 -40
- package/src/html/canvas-chain.js +5 -6
- package/src/html/canvas-focus.js +2 -4
- package/src/html/canvas-screenshot.js +199 -0
- package/src/html/canvas-ui.css +5 -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 +41 -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 +12 -9
- 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 +227 -44
- package/src/server/canvas-capture.js +47 -0
- package/src/server/export.js +5 -2
- package/src/server/mcp.js +29 -6
- 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 +127 -11
- package/src/vendor/html-to-image.min.js +24 -0
- package/src/server/assets/tree.js +0 -26
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join, extname } from 'node:path';
|
|
4
|
+
import semver from 'semver';
|
|
5
|
+
import { z } from 'zod/v4';
|
|
6
|
+
import { VERSION } from '../util/version.js';
|
|
7
|
+
import { DocumentError } from '../workspace/documents.js';
|
|
8
|
+
import { capabilityDefinition, capabilityPermission, compileCapabilities, mountId, pluginId } from './plugin-capabilities.js';
|
|
9
|
+
import { captureDefinition } from './canvas-capture.js';
|
|
10
|
+
import { compileConfiguration, pluginConfiguration } from './plugin-settings.js';
|
|
11
|
+
import { locked, fail } from '../workspace/storage.js';
|
|
12
|
+
|
|
13
|
+
export const PLUGIN_PROTOCOL = '1.0';
|
|
14
|
+
export const PLUGIN_SLOTS = ['topbar', 'bottombar', 'sidebar', 'bottom-left', 'canvas-overlay', 'top-left', 'top-right', 'bottom-right'];
|
|
15
|
+
export const PLUGIN_FIELDS = ['document', 'selection', 'graph', 'viewport'];
|
|
16
|
+
const ASSETS = '/library/plugin-assets/';
|
|
17
|
+
const SDK = '/clado-plugin-sdk.js';
|
|
18
|
+
const UI_CSS = '/plugin-ui.css';
|
|
19
|
+
const segment = /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/;
|
|
20
|
+
const uiPath = /^ui\/(?:[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\.html$/;
|
|
21
|
+
const permission = z.enum([
|
|
22
|
+
...PLUGIN_SLOTS.map(slot => 'ui.mount:' + slot),
|
|
23
|
+
...PLUGIN_FIELDS.map(field => 'canvas.' + field + '.read'),
|
|
24
|
+
]);
|
|
25
|
+
const manifest = z.strictObject({
|
|
26
|
+
manifestVersion: z.literal(1),
|
|
27
|
+
id: pluginId,
|
|
28
|
+
name: z.string().trim().min(1).max(80),
|
|
29
|
+
version: z.string().max(128).refine(value => {
|
|
30
|
+
const parsed = semver.parse(value);
|
|
31
|
+
return parsed && parsed.version + (parsed.build.length ? '+' + parsed.build.join('.') : '') === value;
|
|
32
|
+
}, '需要有效 SemVer'),
|
|
33
|
+
engines: z.strictObject({ clado: z.string().min(1).max(200) }),
|
|
34
|
+
protocols: z.array(z.string().regex(/^\d+\.\d+$/)).min(1).max(16),
|
|
35
|
+
entrypoints: z.strictObject({ ui: z.strictObject({ path: z.string().max(240).regex(uiPath) }) }),
|
|
36
|
+
permissions: z.array(z.union([permission, capabilityPermission])).max(64).default([]),
|
|
37
|
+
configuration: pluginConfiguration.optional(),
|
|
38
|
+
contributes: z.strictObject({
|
|
39
|
+
mounts: z.array(z.strictObject({
|
|
40
|
+
id: mountId, slot: z.enum(PLUGIN_SLOTS),
|
|
41
|
+
})).min(1).max(8),
|
|
42
|
+
capabilities: z.array(capabilityDefinition).max(16).default([]),
|
|
43
|
+
events: z.tuple([]).optional(),
|
|
44
|
+
}),
|
|
45
|
+
});
|
|
46
|
+
const builtInMounts = ['brand', 'view-controls', 'directory', 'agent'];
|
|
47
|
+
const builtInIds = ['clado.host', ...builtInMounts.map(mount => 'clado.' + mount)];
|
|
48
|
+
export function builtInCapabilities(agentEnabled) {
|
|
49
|
+
const screenshot = compileCapabilities('clado.host', [{ id: 'canvas' }], [captureDefinition]);
|
|
50
|
+
const extensions = builtInMounts.filter(mount => mount !== 'agent' || agentEnabled).flatMap(mount => {
|
|
51
|
+
let raw;
|
|
52
|
+
try { raw = readFileSync(new URL('../../plugins/' + mount + '/capabilities.json', import.meta.url), 'utf8'); }
|
|
53
|
+
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
54
|
+
return compileCapabilities('clado.' + mount, [{ id: mount }], JSON.parse(raw));
|
|
55
|
+
});
|
|
56
|
+
return [...screenshot, ...extensions];
|
|
57
|
+
}
|
|
58
|
+
export const builtInGrants = () => new Map(builtInIds.map(id => [id, id === 'clado.agent' ? ['capability.call:clado.directory/directory.open'] : []]));
|
|
59
|
+
const contentTypes = new Map(Object.entries({
|
|
60
|
+
'.html': 'text/html; charset=utf-8',
|
|
61
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
62
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
63
|
+
'.css': 'text/css; charset=utf-8',
|
|
64
|
+
'.json': 'application/json; charset=utf-8',
|
|
65
|
+
'.svg': 'image/svg+xml',
|
|
66
|
+
'.png': 'image/png',
|
|
67
|
+
'.jpg': 'image/jpeg',
|
|
68
|
+
'.jpeg': 'image/jpeg',
|
|
69
|
+
'.gif': 'image/gif',
|
|
70
|
+
'.webp': 'image/webp',
|
|
71
|
+
'.woff2': 'font/woff2',
|
|
72
|
+
}));
|
|
73
|
+
|
|
74
|
+
// The workspace opted into loading these packages. Still keep every file read
|
|
75
|
+
// inside its package, and avoid following symlinks or opening special files.
|
|
76
|
+
function readPackageFile(root, parts, maxBytes) {
|
|
77
|
+
let path = root;
|
|
78
|
+
if (!lstatSync(path).isDirectory()) throw new Error('插件包需要是实体目录。');
|
|
79
|
+
for (const part of parts.slice(0, -1)) {
|
|
80
|
+
path = join(path, part);
|
|
81
|
+
if (!lstatSync(path).isDirectory()) throw new Error('插件资源目录无效。');
|
|
82
|
+
}
|
|
83
|
+
path = join(path, parts.at(-1));
|
|
84
|
+
const info = lstatSync(path);
|
|
85
|
+
if (!info.isFile() || info.size > maxBytes) throw new Error('插件文件类型或大小无效。');
|
|
86
|
+
return readFileSync(path);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function readManifest(root) {
|
|
90
|
+
const result = manifest.safeParse(JSON.parse(readPackageFile(root, ['clado-plugin.json'], 64 * 1024).toString('utf8')));
|
|
91
|
+
if (!result.success) {
|
|
92
|
+
const issue = result.error.issues[0];
|
|
93
|
+
throw new Error(`清单字段 ${issue.path.join('.') || '根对象'} 无效:${issue.message}`);
|
|
94
|
+
}
|
|
95
|
+
const data = result.data;
|
|
96
|
+
if (builtInIds.includes(data.id)) throw new Error(data.id + ' 是 Clado 保留 ID。');
|
|
97
|
+
if (!semver.validRange(data.engines.clado) || !semver.satisfies(VERSION, data.engines.clado)) {
|
|
98
|
+
throw new Error(`插件需要 Clado ${data.engines.clado},当前版本为 ${VERSION}。`);
|
|
99
|
+
}
|
|
100
|
+
if (!data.protocols.includes(PLUGIN_PROTOCOL)) throw new Error(`插件需要声明协议 ${PLUGIN_PROTOCOL}。`);
|
|
101
|
+
const mounts = data.contributes.mounts;
|
|
102
|
+
if (new Set(mounts.map(mount => mount.id)).size !== mounts.length) throw new Error('挂载 ID 重复。');
|
|
103
|
+
for (const { slot } of mounts) {
|
|
104
|
+
if (!data.permissions.includes('ui.mount:' + slot)) throw new Error(`缺少挂载权限 ui.mount:${slot}。`);
|
|
105
|
+
}
|
|
106
|
+
readPackageFile(root, data.entrypoints.ui.path.split('/'), 2 * 1024 * 1024);
|
|
107
|
+
return { data, capabilities: compileCapabilities(data.id, mounts, data.contributes.capabilities),
|
|
108
|
+
configuration: compileConfiguration(data.configuration) };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function installWorkspacePlugin(ctx, files, runtime) {
|
|
112
|
+
if (!Array.isArray(files) || !files.length || files.length > 256) fail('请选择一个插件目录,最多 256 个文件。');
|
|
113
|
+
const parsed = new Map();
|
|
114
|
+
let size = 0;
|
|
115
|
+
for (const file of files) {
|
|
116
|
+
if (typeof file?.path !== 'string' || typeof file.data !== 'string' || file.path.length > 240) fail('插件文件参数无效。');
|
|
117
|
+
const parts = file.path.split('/');
|
|
118
|
+
if (!parts.every(part => segment.test(part)) ||
|
|
119
|
+
(file.path !== 'clado-plugin.json' && (parts[0] !== 'ui' || !contentTypes.has(extname(file.path).toLowerCase())))) fail('插件包仅接受清单和 ui 目录中的资源。');
|
|
120
|
+
if (parsed.has(file.path)) fail('插件包中有重复的文件路径。');
|
|
121
|
+
const data = Buffer.from(file.data, 'base64');
|
|
122
|
+
if (data.toString('base64') !== file.data) fail('插件文件编码无效。');
|
|
123
|
+
size += data.length;
|
|
124
|
+
if (data.length > 2 * 1024 * 1024 || size > 8 * 1024 * 1024) fail('插件包超过大小限制。', 413);
|
|
125
|
+
parsed.set(file.path, data);
|
|
126
|
+
}
|
|
127
|
+
if (!parsed.has('clado-plugin.json')) fail('插件目录缺少 clado-plugin.json。');
|
|
128
|
+
return locked(ctx, () => {
|
|
129
|
+
const directory = join(ctx.state, 'plugins');
|
|
130
|
+
if (!existsSync(directory)) mkdirSync(directory);
|
|
131
|
+
if (!lstatSync(directory).isDirectory()) fail('插件目录需要是实体目录。');
|
|
132
|
+
const stage = join(directory, '.install-' + randomUUID());
|
|
133
|
+
mkdirSync(stage, { mode: 0o700 });
|
|
134
|
+
try {
|
|
135
|
+
for (const [file, body] of parsed) {
|
|
136
|
+
const target = join(stage, file);
|
|
137
|
+
if (file.includes('/')) mkdirSync(join(target, '..'), { recursive: true });
|
|
138
|
+
writeFileSync(target, body, { flag: 'wx' });
|
|
139
|
+
}
|
|
140
|
+
let definition;
|
|
141
|
+
try { definition = readManifest(stage); }
|
|
142
|
+
catch (error) { fail(error.message, 422); }
|
|
143
|
+
const { id, name, version } = definition.data;
|
|
144
|
+
const target = join(directory, id);
|
|
145
|
+
const duplicate = readdirSync(directory, { withFileTypes: true }).some(entry => {
|
|
146
|
+
if (!entry.isDirectory() || entry.name.startsWith('.')) return false;
|
|
147
|
+
try { return readManifest(join(directory, entry.name)).data.id === id; }
|
|
148
|
+
catch { return false; }
|
|
149
|
+
});
|
|
150
|
+
if (existsSync(target) || duplicate) fail('已经安装了同 ID 的插件。', 409);
|
|
151
|
+
renameSync(stage, target);
|
|
152
|
+
runtime?.register(target, definition);
|
|
153
|
+
return { id, name, version, active: !!runtime };
|
|
154
|
+
} finally { rmSync(stage, { recursive: true, force: true }); }
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function loadWorkspacePlugins(state) {
|
|
159
|
+
const directory = join(state, 'plugins');
|
|
160
|
+
const plugins = [], warnings = [], packages = new Map(), capabilities = [], configurations = new Map();
|
|
161
|
+
let entries = [];
|
|
162
|
+
try {
|
|
163
|
+
if (!lstatSync(directory).isDirectory()) throw new Error('插件目录需要是实体目录。');
|
|
164
|
+
entries = readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error.code !== 'ENOENT') warnings.push({ directory: '.clado/plugins', message: error.message });
|
|
167
|
+
}
|
|
168
|
+
const candidates = new Map();
|
|
169
|
+
function register(root, { data, capabilities: declared, configuration }) {
|
|
170
|
+
configurations.set(data.id, configuration);
|
|
171
|
+
capabilities.push(...declared);
|
|
172
|
+
const key = randomUUID();
|
|
173
|
+
packages.set(key, root);
|
|
174
|
+
plugins.push({
|
|
175
|
+
id: data.id, name: data.name, version: data.version,
|
|
176
|
+
entry: ASSETS + key + '/' + data.entrypoints.ui.path,
|
|
177
|
+
permissions: data.permissions, mounts: data.contributes.mounts, capabilities: declared.map(item => item.descriptor),
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
for (const entry of entries) {
|
|
181
|
+
if (entry.name.startsWith('.') || (!entry.isDirectory() && !entry.isSymbolicLink())) continue;
|
|
182
|
+
const root = join(directory, entry.name);
|
|
183
|
+
try {
|
|
184
|
+
const { data, capabilities, configuration } = readManifest(root);
|
|
185
|
+
const copies = candidates.get(data.id) || [];
|
|
186
|
+
copies.push({ data, capabilities, configuration, root, directory: entry.name });
|
|
187
|
+
candidates.set(data.id, copies);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
warnings.push({ directory: entry.name, message: error.code === 'ENOENT' ? '缺少插件清单或 UI 入口。' : error.message });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
for (const copies of candidates.values()) {
|
|
193
|
+
if (copies.length !== 1) {
|
|
194
|
+
for (const copy of copies) warnings.push({ directory: copy.directory, message: '插件 ID 重复:' + copy.data.id });
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
register(copies[0].root, copies[0]);
|
|
198
|
+
}
|
|
199
|
+
const descriptor = { workspaceId: randomUUID(), protocol: PLUGIN_PROTOCOL, slots: PLUGIN_SLOTS, fields: PLUGIN_FIELDS, plugins };
|
|
200
|
+
function serveAsset(req, res, url) {
|
|
201
|
+
const [key, ...parts] = url.pathname.slice(ASSETS.length).split('/').map(decodeURIComponent);
|
|
202
|
+
const root = packages.get(key), type = contentTypes.get(extname(parts.at(-1) || '').toLowerCase());
|
|
203
|
+
if (!root || !type || parts[0] !== 'ui' || !parts.every(part => segment.test(part))) {
|
|
204
|
+
throw new DocumentError('插件资源不存在。', 404);
|
|
205
|
+
}
|
|
206
|
+
let body;
|
|
207
|
+
try {
|
|
208
|
+
if (!lstatSync(directory).isDirectory()) throw new Error();
|
|
209
|
+
body = readPackageFile(root, parts, 2 * 1024 * 1024);
|
|
210
|
+
} catch {
|
|
211
|
+
throw new DocumentError('插件资源不可读。', 404);
|
|
212
|
+
}
|
|
213
|
+
const origin = 'http://' + req.headers.host;
|
|
214
|
+
const ui = origin + ASSETS + key + '/ui/';
|
|
215
|
+
res.writeHead(200, {
|
|
216
|
+
'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
|
|
217
|
+
'access-control-allow-origin': 'null',
|
|
218
|
+
'content-security-policy': `sandbox allow-scripts; default-src 'none'; script-src ${ui} ${origin + SDK}; style-src ${ui} ${origin + UI_CSS}; img-src ${ui} data:; font-src ${ui}; form-action 'none'; base-uri 'none'; frame-ancestors ${origin}`,
|
|
219
|
+
});
|
|
220
|
+
res.end(req.method === 'HEAD' ? undefined : body);
|
|
221
|
+
}
|
|
222
|
+
return { descriptor, warnings, serveAsset, capabilities, configurations, register };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function inspectWorkspacePlugins(state) {
|
|
226
|
+
const directory = join(state, 'plugins');
|
|
227
|
+
if (!existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
|
|
228
|
+
return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
|
|
229
|
+
if (!entry.isDirectory() || entry.name.startsWith('.')) return [];
|
|
230
|
+
try {
|
|
231
|
+
const raw = JSON.parse(readPackageFile(join(directory, entry.name), ['clado-plugin.json'], 64 * 1024));
|
|
232
|
+
const { id, name, version } = manifest.parse(raw);
|
|
233
|
+
return builtInIds.includes(id) ? [] : [{ id, name, version, pending: true, reason: '待启用第三方插件' }];
|
|
234
|
+
} catch { return []; }
|
|
235
|
+
});
|
|
236
|
+
}
|
package/src/server/workspace.js
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
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';
|
|
10
15
|
import { z } from 'zod/v4';
|
|
11
16
|
const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
|
|
12
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'};
|
|
@@ -18,17 +23,21 @@ const viewSelection = z.object({
|
|
|
18
23
|
}).strict();
|
|
19
24
|
export function createWorkspaceHandler(directory, options = {}) {
|
|
20
25
|
const root = resolve(directory);
|
|
21
|
-
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);
|
|
22
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); };
|
|
23
30
|
const json = (res, status, data) => send(res, status, types.json, JSON.stringify(data));
|
|
24
31
|
const safeJson = data => JSON.stringify(data).replace(/</g,'\\u003c');
|
|
25
32
|
return async function handle(req, res, url) {
|
|
26
33
|
const route = url.pathname.slice(1);
|
|
27
|
-
|
|
34
|
+
const pluginFile = workspacePluginAssets.get(url.pathname);
|
|
35
|
+
if (!url.pathname.startsWith('/library/') && !assetNames.has(route) && !pluginFile && !(options.entrypoint && route === '')) return false;
|
|
28
36
|
try {
|
|
29
37
|
const host = req.headers.host;
|
|
30
38
|
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
|
|
31
|
-
|
|
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);
|
|
32
41
|
if (url.pathname === '/library/selection' && options.publishSelection && req.method === 'POST') {
|
|
33
42
|
if (req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') throw new DocumentError('选区只接受同源页面请求。', 403);
|
|
34
43
|
const chunks = []; let size = 0;
|
|
@@ -43,11 +52,89 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
43
52
|
options.publishSelection(selection.data);
|
|
44
53
|
json(res, 200, { ok: true }); return true;
|
|
45
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
|
+
}
|
|
46
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
|
+
}
|
|
47
125
|
if (assetNames.has(route) || (options.entrypoint && route === '')) {
|
|
48
|
-
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');
|
|
49
127
|
if (name === 'library.html') {
|
|
50
|
-
|
|
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">');
|
|
51
138
|
}
|
|
52
139
|
send(res,200,types[name.split('.').pop()],body); return true;
|
|
53
140
|
}
|
|
@@ -67,16 +154,16 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
67
154
|
if (url.pathname === '/library/source.mdc') { send(res,200,types.md,item.source); return true; }
|
|
68
155
|
if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('文档暂时无法解析。',422,item.diagnostics);
|
|
69
156
|
const mode = ['doc','cards','mindmap'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : options.mode || 'mindmap';
|
|
70
|
-
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'});
|
|
71
158
|
const bodyEnd = html.lastIndexOf('</body>');
|
|
72
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);
|
|
73
160
|
send(res,200,types.html,html); return true;
|
|
74
161
|
} catch (error) {
|
|
75
|
-
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;
|
|
76
163
|
}
|
|
77
164
|
};
|
|
78
165
|
}
|
|
79
|
-
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' } = {}) {
|
|
80
167
|
const path = resolve(input);
|
|
81
168
|
if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
|
|
82
169
|
if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
|
|
@@ -86,6 +173,15 @@ export async function startWorkspace(input, { port = 4317, mode = 'mindmap', the
|
|
|
86
173
|
const ctx = contextFor(root, root); workspace = root; root = ctx.documents;
|
|
87
174
|
}
|
|
88
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
|
+
});
|
|
89
185
|
const entryFile = entry ? relative(root,workspacePath(root,entry)).split('\\').join('/') : (statSync(path).isFile() ? basename(path) : '');
|
|
90
186
|
if (entryFile) {
|
|
91
187
|
const item=readDocument(workspacePath(root,entryFile));
|
|
@@ -100,14 +196,34 @@ export async function startWorkspace(input, { port = 4317, mode = 'mindmap', the
|
|
|
100
196
|
} else if (next.nodes.length) selection = { ...next, expiresAt: Date.now() + 120000 };
|
|
101
197
|
else if (selection?.tab === next.tab) selection = undefined;
|
|
102
198
|
};
|
|
103
|
-
const
|
|
104
|
-
|
|
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);
|
|
105
220
|
const server = createServer(async (req,res) => {
|
|
106
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'); } }
|
|
107
222
|
catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
|
|
108
223
|
});
|
|
224
|
+
if (agent) server.on('close', agent.close);
|
|
109
225
|
await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
|
|
110
226
|
const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
|
|
111
227
|
const origin = 'http://127.0.0.1:'+server.address().port;
|
|
112
|
-
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};
|
|
113
229
|
}
|
|
@@ -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}));
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
(() => {
|
|
2
|
-
window.CladoDocumentTree = function (container, documents, { selected='', query='', onOpen=()=>{}, folders=new Set() } = {}) {
|
|
3
|
-
const needle=query.trim().toLocaleLowerCase(), root={folders:new Map(),files:[]};
|
|
4
|
-
for(const doc of documents) {
|
|
5
|
-
if(needle && !(doc.title+' '+doc.file).toLocaleLowerCase().includes(needle))continue;
|
|
6
|
-
const parts=doc.file.split('/');let node=root;
|
|
7
|
-
parts.slice(0,-1).forEach((name,i)=>{const path=parts.slice(0,i+1).join('/');if(!node.folders.has(name))node.folders.set(name,{path,folders:new Map(),files:[]});node=node.folders.get(name);});node.files.push(doc);
|
|
8
|
-
}
|
|
9
|
-
container.replaceChildren();
|
|
10
|
-
function render(node, parent) {
|
|
11
|
-
for(const [name,folder] of node.folders) {
|
|
12
|
-
const details=document.createElement('details');details.className='tree-folder';details.open=!!needle||!folders.has('closed:'+folder.path);
|
|
13
|
-
const summary=document.createElement('summary');summary.textContent=name;details.append(summary);
|
|
14
|
-
details.addEventListener('toggle',()=>{if(!needle){if(details.open)folders.delete('closed:'+folder.path);else folders.add('closed:'+folder.path);}});
|
|
15
|
-
const children=document.createElement('div');children.className='tree-children';details.append(children);render(folder,children);parent.append(details);
|
|
16
|
-
}
|
|
17
|
-
for(const doc of node.files) {
|
|
18
|
-
const button=document.createElement('button');button.className='document-button';button.dataset.file=doc.file;if(doc.file===selected)button.setAttribute('aria-current','page');
|
|
19
|
-
const strong=document.createElement('strong');strong.textContent=doc.title;
|
|
20
|
-
const small=document.createElement('small');small.textContent=doc.file.split('/').pop();button.append(strong,small);button.onclick=()=>onOpen(doc.file);parent.append(button);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
render(root,container);
|
|
24
|
-
if(!container.childElementCount){const empty=document.createElement('p');empty.className='tree-empty';empty.textContent=needle?'没有匹配的文档':'还没有可展示的文档';container.append(empty);}
|
|
25
|
-
};
|
|
26
|
-
})();
|