@auto-mas/auto-mas-plugin-maafw-projects 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,353 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import Schemastery from 'schemastery';
3
+ export const Schema = Object.assign(Schemastery, {
4
+ path(options = {}) {
5
+ return Schemastery.string().role('path', options);
6
+ },
7
+ });
8
+ function plain(value) {
9
+ if (!value || typeof value !== 'object' || Array.isArray(value))
10
+ return false;
11
+ const prototype = Object.getPrototypeOf(value);
12
+ return prototype === Object.prototype || prototype === null;
13
+ }
14
+ function entries(value) {
15
+ return Object.entries(value).filter(([key]) => key !== '__proto__');
16
+ }
17
+ function own(value, key) {
18
+ return Object.hasOwn(value, key) ? value[key] : undefined;
19
+ }
20
+ export function isSchema(value) {
21
+ if (typeof value !== 'function')
22
+ return false;
23
+ const schema = value;
24
+ return schema[Symbol.for('schemastery')] === true && typeof schema.type === 'string' && plain(schema.meta);
25
+ }
26
+ function encode(value, parents = new Set()) {
27
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
28
+ return value;
29
+ if (typeof value === 'number')
30
+ return Number.isFinite(value) ? value : null;
31
+ if (value instanceof Date)
32
+ return value.toJSON();
33
+ if (value instanceof RegExp)
34
+ return { source: value.source, flags: value.flags };
35
+ if (!(Array.isArray(value) || plain(value)) || parents.has(value))
36
+ return undefined;
37
+ parents.add(value);
38
+ const result = Array.isArray(value)
39
+ ? value.map(item => encode(item, parents) ?? null)
40
+ : Object.fromEntries(entries(value).flatMap(([key, item]) => {
41
+ const encoded = encode(item, parents);
42
+ return encoded === undefined ? [] : [[key, encoded]];
43
+ }));
44
+ parents.delete(value);
45
+ return result;
46
+ }
47
+ function copyInput(value, copies = new WeakMap()) {
48
+ if (!(Array.isArray(value) || plain(value)))
49
+ return value;
50
+ if (copies.has(value))
51
+ return copies.get(value);
52
+ if (Array.isArray(value)) {
53
+ const result = [];
54
+ copies.set(value, result);
55
+ for (const item of value)
56
+ result.push(copyInput(item, copies));
57
+ return result;
58
+ }
59
+ const result = {};
60
+ copies.set(value, result);
61
+ for (const [key, item] of entries(value))
62
+ result[key] = copyInput(item, copies);
63
+ return result;
64
+ }
65
+ function secret(meta) {
66
+ return meta?.role === 'secret' || meta?.role === 'password' || meta?.password === true || meta?.writeOnly === true;
67
+ }
68
+ function privateValue(meta) {
69
+ return meta?.hidden === true || secret(meta);
70
+ }
71
+ function lazyTarget(schema) {
72
+ if (isSchema(schema.inner))
73
+ return schema.inner;
74
+ const target = schema.builder?.();
75
+ if (!isSchema(target))
76
+ throw new TypeError('Schemastery lazy builder must return a schema');
77
+ return new Schema({ ...target, meta: { ...schema.meta, ...target.meta } });
78
+ }
79
+ export function describeSchema(schema) {
80
+ const visible = new WeakMap();
81
+ const protectedNodes = new WeakMap();
82
+ const defaults = [];
83
+ let nextId = 0;
84
+ function describe(source, inherited = false) {
85
+ const isPrivate = inherited || privateValue(source.meta);
86
+ const seen = isPrivate ? protectedNodes : visible;
87
+ const previous = seen.get(source);
88
+ if (previous !== undefined)
89
+ return { type: 'ref', ref: previous };
90
+ const id = nextId++;
91
+ seen.set(source, id);
92
+ const effective = source.type === 'lazy' ? lazyTarget(source) : source;
93
+ const meta = encode(effective.meta);
94
+ const protectsChildren = isPrivate || privateValue(meta);
95
+ const node = { type: effective.type, id };
96
+ if (protectsChildren) {
97
+ delete meta.default;
98
+ delete meta.extra;
99
+ }
100
+ if (isPrivate && !privateValue(meta))
101
+ meta.hidden = true;
102
+ if (Object.keys(meta).length)
103
+ node.meta = meta;
104
+ if (Object.hasOwn(meta, 'default'))
105
+ defaults.push(node);
106
+ if (effective.inner && isSchema(effective.inner))
107
+ node.inner = describe(effective.inner, protectsChildren);
108
+ if (effective.sKey)
109
+ node.key = describe(effective.sKey, protectsChildren);
110
+ if (effective.list)
111
+ node.list = effective.list.map(item => describe(item, protectsChildren));
112
+ if (effective.dict)
113
+ node.dict = Object.fromEntries(Object.entries(effective.dict)
114
+ .filter(([key]) => key !== '__proto__').map(([key, item]) => [key, describe(item, protectsChildren)]));
115
+ if (effective.bits)
116
+ node.bits = Object.fromEntries(Object.entries(effective.bits).filter(([key]) => key !== '__proto__'));
117
+ if (effective.type === 'is' && effective.constructor)
118
+ node.className = typeof effective.constructor === 'string' ? effective.constructor : effective.constructor.name;
119
+ if (effective.type === 'transform' && effective.preserve !== undefined)
120
+ node.preserve = effective.preserve;
121
+ const value = protectsChildren ? undefined : encode(effective.value);
122
+ if (value !== undefined)
123
+ node.value = value;
124
+ return node;
125
+ }
126
+ const root = describe(schema);
127
+ const refs = indexNodes(root);
128
+ for (const node of defaults) {
129
+ const value = expose([node], node.meta.default, refs);
130
+ if (value === undefined)
131
+ delete node.meta.default;
132
+ else
133
+ node.meta.default = value;
134
+ }
135
+ return root;
136
+ }
137
+ function indexNodes(root) {
138
+ const refs = new Map();
139
+ const walk = (node) => {
140
+ if (!node || node.type === 'ref')
141
+ return;
142
+ if (node.id !== undefined)
143
+ refs.set(node.id, node);
144
+ walk(node.inner);
145
+ walk(node.key);
146
+ node.list?.forEach(walk);
147
+ Object.values(node.dict ?? {}).forEach(walk);
148
+ };
149
+ walk(root);
150
+ return refs;
151
+ }
152
+ function fits(node, value, refs, visited = new Set()) {
153
+ if (value == null || visited.has(node))
154
+ return true;
155
+ visited.add(node);
156
+ if (node.type === 'ref' && node.ref !== undefined) {
157
+ const target = refs.get(node.ref);
158
+ return !target || fits(target, value, refs, visited);
159
+ }
160
+ if (node.type === 'const')
161
+ return !Object.hasOwn(node, 'value') || isDeepStrictEqual(node.value, value);
162
+ if (node.type === 'string' || node.type === 'number' || node.type === 'boolean')
163
+ return typeof value === node.type;
164
+ if (node.type === 'array' || node.type === 'tuple')
165
+ return Array.isArray(value);
166
+ if (node.type === 'object' || node.type === 'dict') {
167
+ if (!plain(value))
168
+ return false;
169
+ return Object.entries(node.dict ?? {}).every(([key, child]) => {
170
+ const field = child.type === 'ref' && child.ref !== undefined ? refs.get(child.ref) : child;
171
+ return field?.type !== 'const' || fits(field, own(value, key), refs, new Set(visited));
172
+ });
173
+ }
174
+ if (node.type === 'transform' && node.inner)
175
+ return fits(node.inner, value, refs, visited);
176
+ if (node.type === 'intersect')
177
+ return node.list?.every(item => fits(item, value, refs, new Set(visited))) ?? true;
178
+ if (node.type === 'union')
179
+ return node.list?.some(item => fits(item, value, refs, new Set(visited))) ?? true;
180
+ return true;
181
+ }
182
+ function expand(input, value, refs) {
183
+ const seen = new Set();
184
+ function visit(node) {
185
+ if (!node || seen.has(node))
186
+ return;
187
+ seen.add(node);
188
+ if (node.type === 'ref')
189
+ visit(node.ref === undefined ? undefined : refs.get(node.ref));
190
+ if (node.type === 'transform')
191
+ visit(node.inner);
192
+ if (node.type === 'intersect')
193
+ node.list?.forEach(visit);
194
+ if (node.type === 'union' && node.list) {
195
+ const matching = node.list.filter(branch => fits(branch, value, refs));
196
+ const branches = matching.length ? matching : node.list;
197
+ branches.forEach(visit);
198
+ }
199
+ }
200
+ input.forEach(visit);
201
+ return [...seen];
202
+ }
203
+ function at(nodes, key) {
204
+ return nodes.flatMap(node => {
205
+ let child;
206
+ if (typeof key === 'number')
207
+ child = node.type === 'array' ? node.inner : node.type === 'tuple' ? node.list?.[key] : undefined;
208
+ else if (node.type === 'dict')
209
+ child = node.inner;
210
+ else if (node.type === 'object' && Object.hasOwn(node.dict ?? {}, key))
211
+ child = node.dict?.[key];
212
+ return child ? [child] : [];
213
+ });
214
+ }
215
+ function hidesKeys(node, refs) {
216
+ return node.type === 'dict' && node.key && expand([node.key], undefined, refs).some(key => privateValue(key.meta));
217
+ }
218
+ function locked(node, refs) {
219
+ return node.meta?.hidden === true || node.meta?.disabled === true || node.meta?.readonly === true || hidesKeys(node, refs);
220
+ }
221
+ function expose(input, value, refs) {
222
+ const nodes = expand(input, value, refs);
223
+ if (nodes.some(node => privateValue(node.meta) || hidesKeys(node, refs)))
224
+ return undefined;
225
+ if (Array.isArray(value))
226
+ return value.map((item, key) => expose(at(nodes, key), item, refs) ?? null);
227
+ if (!plain(value))
228
+ return encode(value);
229
+ const typed = nodes.some(node => node.type === 'object');
230
+ return Object.fromEntries(entries(value).flatMap(([key, item]) => {
231
+ const rules = at(nodes, key);
232
+ if (typed && !rules.length)
233
+ return [];
234
+ const visible = expose(rules, item, refs);
235
+ return visible === undefined ? [] : [[key, visible]];
236
+ }));
237
+ }
238
+ export function publicConfig(node, value) {
239
+ return expose([node], value, indexNodes(node));
240
+ }
241
+ function rowSources(before, after, prior, draft, refs) {
242
+ const oldRows = prior.map((value, index) => {
243
+ const rules = at(before, index);
244
+ return { value, visible: expose(rules, value, refs) };
245
+ });
246
+ if (oldRows.every(row => isDeepStrictEqual(row.visible, row.value)))
247
+ return prior;
248
+ const visibleDraft = draft.map((item, index) => expose(at(after, index), item, refs));
249
+ if (oldRows.length === draft.length && oldRows.every((row, index) => isDeepStrictEqual(row.visible, visibleDraft[index])))
250
+ return prior;
251
+ const signature = (value) => JSON.stringify(value, (_, item) => {
252
+ if (!plain(item))
253
+ return item;
254
+ return Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]]));
255
+ });
256
+ const positions = new Map();
257
+ oldRows.forEach((row, index) => {
258
+ const key = signature(row.visible);
259
+ positions.set(key, positions.has(key) ? null : index);
260
+ });
261
+ const matched = new Set();
262
+ const sources = visibleDraft.map(value => {
263
+ const index = positions.get(signature(value));
264
+ if (typeof index === 'number' && !matched.has(index)) {
265
+ matched.add(index);
266
+ return oldRows[index].value;
267
+ }
268
+ return undefined;
269
+ });
270
+ if (sources.includes(undefined) && oldRows.some((row, index) => !matched.has(index) && !isDeepStrictEqual(row.visible, row.value))) {
271
+ throw new TypeError('无法对应包含密钥或隐藏值的配置行。请分开保存删除和新增操作。');
272
+ }
273
+ return sources;
274
+ }
275
+ function merge(previousSchemas, draftSchemas, prior, draft, refs) {
276
+ const before = expand(previousSchemas, prior, refs);
277
+ let sample = draft ?? prior;
278
+ if (plain(draft)) {
279
+ const previous = plain(prior) ? prior : {};
280
+ const candidate = { ...previous, ...draft };
281
+ for (const [key] of entries(draft)) {
282
+ const value = own(previous, key);
283
+ if (expand(at(before, key), value, refs).some(node => locked(node, refs))) {
284
+ if (value === undefined)
285
+ delete candidate[key];
286
+ else
287
+ candidate[key] = value;
288
+ }
289
+ }
290
+ sample = candidate;
291
+ }
292
+ const after = expand(draftSchemas, sample, refs);
293
+ if (after.some(node => locked(node, refs)))
294
+ return copyInput(prior);
295
+ if (after.some(node => secret(node.meta))) {
296
+ return draft == null || typeof draft === 'string' && !draft.trim() ? copyInput(prior) : copyInput(draft);
297
+ }
298
+ if (draft === undefined && before.some(node => privateValue(node.meta)))
299
+ return undefined;
300
+ if (Array.isArray(draft)) {
301
+ const previous = Array.isArray(prior) ? prior : [];
302
+ const sources = before.some(node => node.type === 'array') ? rowSources(before, after, previous, draft, refs) : previous;
303
+ return draft.map((item, key) => merge(at(before, key), at(after, key), sources[key], item, refs));
304
+ }
305
+ const previous = plain(prior) ? prior : {};
306
+ if (plain(draft) || draft === undefined && plain(prior)) {
307
+ const next = plain(draft) ? draft : {};
308
+ const keys = new Set(entries(next).map(([key]) => key));
309
+ for (const [key] of entries(previous)) {
310
+ if (draft === undefined || after.some(node => node.type === 'object' && Object.hasOwn(node.dict ?? {}, key)))
311
+ keys.add(key);
312
+ }
313
+ const result = Object.fromEntries([...keys].flatMap(key => {
314
+ const value = merge(at(before, key), at(after, key), own(previous, key), own(next, key), refs);
315
+ return value === undefined ? [] : [[key, value]];
316
+ }));
317
+ return draft === undefined && !Object.keys(result).length ? undefined : result;
318
+ }
319
+ return copyInput(draft);
320
+ }
321
+ export function mergeConfig(node, prior, draft) {
322
+ return merge([node], [node], prior, draft, indexNodes(node));
323
+ }
324
+ export function parseConfig(schema, value) {
325
+ if (!isSchema(schema))
326
+ throw new TypeError('Configuration schema must be a Schemastery schema');
327
+ const validate = schema['~standard'].validate;
328
+ let result;
329
+ try {
330
+ result = validate(copyInput(value));
331
+ }
332
+ catch (error) {
333
+ if ([...indexNodes(describeSchema(schema)).values()].some(node => privateValue(node.meta)))
334
+ throw new TypeError('Invalid configuration value');
335
+ throw error;
336
+ }
337
+ if (result instanceof Promise)
338
+ throw new TypeError('Schemastery configuration validation must be synchronous');
339
+ if (!result.issues)
340
+ return result.value;
341
+ // Upstream messages can quote the input or the contents of an entire union.
342
+ const graph = indexNodes(describeSchema(schema));
343
+ const nodes = [...graph.values()];
344
+ const protectedSchema = nodes.some(node => privateValue(node.meta));
345
+ const privateKeys = nodes.some(node => hidesKeys(node, graph));
346
+ const messages = result.issues.map(issue => {
347
+ if (!protectedSchema)
348
+ return issue.message;
349
+ const path = !privateKeys && issue.path?.map(segment => typeof segment === 'object' ? segment.key : segment).join('.');
350
+ return path ? `${path}: invalid configuration value` : 'Invalid configuration value';
351
+ });
352
+ throw new TypeError(messages.join('\n'));
353
+ }
@@ -0,0 +1,76 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ export class Store {
5
+ db;
6
+ lease;
7
+ constructor(directory) {
8
+ mkdirSync(directory, { recursive: true });
9
+ this.lease = new DatabaseSync(join(directory, 'session.db'));
10
+ try {
11
+ this.lease.exec('PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE');
12
+ }
13
+ catch (error) {
14
+ this.lease.close();
15
+ if (error.errcode === 5)
16
+ throw new Error('该数据目录已有 MAS 后端在运行');
17
+ throw error;
18
+ }
19
+ try {
20
+ this.db = new DatabaseSync(join(directory, 'mas.db'));
21
+ this.db.exec(`PRAGMA journal_mode = WAL;
22
+ CREATE TABLE IF NOT EXISTS entries (
23
+ collection TEXT NOT NULL, id TEXT NOT NULL, value TEXT NOT NULL,
24
+ PRIMARY KEY (collection, id)
25
+ );
26
+ CREATE INDEX IF NOT EXISTS run_start ON entries (
27
+ unixepoch(json_extract(value, '$.started'), 'subsec') DESC
28
+ ) WHERE collection = 'runs'`);
29
+ }
30
+ catch (error) {
31
+ this.lease.close();
32
+ throw error;
33
+ }
34
+ }
35
+ recentRuns() {
36
+ return this.db.prepare(`SELECT value FROM entries WHERE collection = 'runs'
37
+ ORDER BY unixepoch(json_extract(value, '$.started'), 'subsec') DESC, rowid DESC LIMIT 200`)
38
+ .all().map(row => JSON.parse(String(row.value)));
39
+ }
40
+ list(collection) {
41
+ const rows = this.db.prepare('SELECT value FROM entries WHERE collection = ? ORDER BY rowid').all(collection);
42
+ return rows.map(row => JSON.parse(String(row.value)));
43
+ }
44
+ get(collection, id) {
45
+ const row = this.db.prepare('SELECT value FROM entries WHERE collection = ? AND id = ?').get(collection, id);
46
+ return row && JSON.parse(String(row.value));
47
+ }
48
+ put(collection, entry) {
49
+ this.db.prepare('INSERT INTO entries VALUES (?, ?, ?) ON CONFLICT(collection, id) DO UPDATE SET value = excluded.value')
50
+ .run(collection, entry.id, JSON.stringify(entry));
51
+ return entry;
52
+ }
53
+ remove(collection, id) {
54
+ this.db.prepare('DELETE FROM entries WHERE collection = ? AND id = ?').run(collection, id);
55
+ }
56
+ transaction(callback) {
57
+ this.db.exec('BEGIN IMMEDIATE');
58
+ try {
59
+ const result = callback();
60
+ this.db.exec('COMMIT');
61
+ return result;
62
+ }
63
+ catch (error) {
64
+ this.db.exec('ROLLBACK');
65
+ throw error;
66
+ }
67
+ }
68
+ close() {
69
+ try {
70
+ this.db.close();
71
+ }
72
+ finally {
73
+ this.lease.close();
74
+ }
75
+ }
76
+ }
@@ -0,0 +1,171 @@
1
+ import {} from 'cordis';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { realpathSync, watch } from 'node:fs';
4
+ import { realpath, stat } from 'node:fs/promises';
5
+ import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path';
6
+ import { describeSchema, parseConfig } from './schema.js';
7
+ export const viewAssetPrefix = '/api/ui/v1/views/';
8
+ const assets = new Map(Object.entries({
9
+ '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
10
+ '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp',
11
+ '.gif': 'image/gif', '.cur': 'image/x-icon',
12
+ '.woff': 'font/woff', '.woff2': 'font/woff2',
13
+ }));
14
+ const assetSegment = /^[\w-][\w.-]*$/;
15
+ const viewId = /^(?:builtin:)?[\w-][\w.-]*$/u;
16
+ export { DownloadFile } from './download.js';
17
+ export class UiRegistry {
18
+ pages = new Map();
19
+ queries = new Map();
20
+ actions = new Map();
21
+ downloads = new Map();
22
+ panels = new Map();
23
+ routes = new Map();
24
+ resolvers = new Set();
25
+ clients = new Map();
26
+ images = new Map();
27
+ changed;
28
+ constructor(changed = () => { }) {
29
+ this.changed = changed;
30
+ }
31
+ /** Register the browser bundle for a page's view id for this Cordis scope. */
32
+ client(ctx, id, options) {
33
+ if (!viewId.test(id) || !isAbsolute(options.root) || !options.entry.split('/').every(part => assetSegment.test(part))
34
+ || !['.js', '.mjs'].includes(extname(options.entry)))
35
+ throw new Error('页面客户端注册无效');
36
+ ctx.effect(() => {
37
+ if (this.clients.has(id) || this.images.has(id))
38
+ throw new Error(`重复注册页面客户端: ${id}`);
39
+ this.clients.set(id, { ...options, root: realpathSync(options.root), revision: randomUUID() });
40
+ return () => { this.clients.delete(id); };
41
+ });
42
+ ctx.inject(['hmr'], scope => {
43
+ const client = this.clients.get(id);
44
+ if (!client)
45
+ return;
46
+ scope.effect(() => {
47
+ let timer;
48
+ let watcher;
49
+ const warn = () => scope.logger('webui').warn('无法监听页面模块 %s 的资源', id);
50
+ try {
51
+ watcher = watch(client.root, { recursive: true, persistent: false }, (_, file) => {
52
+ if (file && !assets.has(extname(file)))
53
+ return;
54
+ clearTimeout(timer);
55
+ timer = setTimeout(() => {
56
+ client.revision = randomUUID();
57
+ this.changed();
58
+ }, 150);
59
+ });
60
+ watcher.on('error', warn);
61
+ }
62
+ catch {
63
+ warn();
64
+ }
65
+ return () => {
66
+ clearTimeout(timer);
67
+ watcher?.close();
68
+ };
69
+ });
70
+ });
71
+ }
72
+ /** Publish one image owned by a plugin for the lifetime of its scope. */
73
+ image(ctx, id, file) {
74
+ const entry = basename(file);
75
+ if (!viewId.test(id) || !isAbsolute(file) || !assetSegment.test(entry) || !assets.get(extname(entry))?.startsWith('image/')) {
76
+ throw new Error('插件图标声明无效');
77
+ }
78
+ const revision = randomUUID();
79
+ ctx.effect(() => {
80
+ if (this.images.has(id) || this.clients.has(id))
81
+ throw new Error(`重复注册插件图标: ${id}`);
82
+ this.images.set(id, { entry, root: realpathSync(dirname(file)), revision });
83
+ return () => { this.images.delete(id); };
84
+ });
85
+ return `${viewAssetPrefix}${id}/${revision}/${entry}`;
86
+ }
87
+ describePage(page) {
88
+ const client = page.view && this.clients.get(page.view);
89
+ return { ...page, viewModule: client ? `${viewAssetPrefix}${page.view}/${client.revision}/${client.entry}` : undefined };
90
+ }
91
+ async viewAsset(pathname) {
92
+ const [id, revision, ...parts] = pathname.slice(viewAssetPrefix.length).split('/');
93
+ const image = this.images.get(id);
94
+ if (image && (parts.length !== 1 || parts[0] !== image.entry))
95
+ return;
96
+ const client = image ?? this.clients.get(id);
97
+ if (!client || client.revision !== revision || !parts.length || !parts.every(part => assetSegment.test(part)))
98
+ return;
99
+ const type = assets.get(extname(parts.at(-1)));
100
+ if (!type)
101
+ return;
102
+ const path = await realpath(resolve(client.root, ...parts)).catch(() => undefined);
103
+ if (!path)
104
+ return;
105
+ const inside = relative(client.root, path);
106
+ if (!inside || inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside))
107
+ return;
108
+ const info = await stat(path).catch(() => undefined);
109
+ if (info?.isFile())
110
+ return { path, type, size: info.size };
111
+ }
112
+ schemaForm(ctx, action, schema, onSubmit) {
113
+ this.scope(ctx, undefined, {}, { [action]: input => onSubmit(parseConfig(schema, input.config), input) });
114
+ return describeSchema(schema);
115
+ }
116
+ resolve(path) {
117
+ for (const page of this.pages.values()) {
118
+ if ((page.path ?? `/${page.id}`) === path || `/${page.id}` === path)
119
+ return page;
120
+ }
121
+ for (const resolve of this.resolvers) {
122
+ const page = resolve(path);
123
+ if (page)
124
+ return page;
125
+ }
126
+ }
127
+ pageRoutes(ctx, resolve) {
128
+ ctx.effect(() => {
129
+ this.resolvers.add(resolve);
130
+ return () => { this.resolvers.delete(resolve); };
131
+ });
132
+ }
133
+ route(ctx, path, handler) {
134
+ ctx.effect(() => {
135
+ if (this.routes.has(path))
136
+ throw new Error(`重复注册路由: ${path}`);
137
+ this.routes.set(path, handler);
138
+ return () => { this.routes.delete(path); };
139
+ });
140
+ }
141
+ download(ctx, id, handler) {
142
+ ctx.effect(() => {
143
+ if (this.downloads.has(id))
144
+ throw new Error(`重复注册下载: ${id}`);
145
+ this.downloads.set(id, handler);
146
+ return () => { this.downloads.delete(id); };
147
+ });
148
+ }
149
+ panel(ctx, pluginId, components, queries = {}, actions = {}) {
150
+ this.register(ctx, [[this.panels, pluginId, components]], queries, actions);
151
+ }
152
+ scope(ctx, page, queries = {}, actions = {}) {
153
+ this.register(ctx, page ? [[this.pages, page.id, page]] : [], queries, actions);
154
+ }
155
+ register(ctx, entries, queries, actions) {
156
+ ctx.effect(() => {
157
+ const pending = [...entries];
158
+ for (const [id, value] of Object.entries(queries))
159
+ pending.push([this.queries, id, value]);
160
+ for (const [id, value] of Object.entries(actions))
161
+ pending.push([this.actions, id, value]);
162
+ for (const [map, id] of pending)
163
+ if (map.has(id))
164
+ throw new Error(`重复注册页面或操作: ${id}`);
165
+ for (const [map, id, value] of pending)
166
+ map.set(id, value);
167
+ return () => { for (const [map, id] of pending)
168
+ map.delete(id); };
169
+ });
170
+ }
171
+ }