@auto-mas/auto-mas-plugin-notification-webhook 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.
- package/dist/LICENSE +661 -0
- package/dist/index.js +1 -0
- package/dist/server/builtin-plugins/notifications.js +5 -0
- package/dist/server/community/vault.js +65 -0
- package/dist/server/download.js +15 -0
- package/dist/server/integrations.js +150 -0
- package/dist/server/notifications/service.js +98 -0
- package/dist/server/schema.js +353 -0
- package/dist/server/storage.js +76 -0
- package/dist/server/ui.js +171 -0
- package/package.json +30 -6
- package/README.md +0 -3
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
|
2
|
+
import { lstat, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
export class CredentialVault {
|
|
5
|
+
path;
|
|
6
|
+
namespace;
|
|
7
|
+
pending;
|
|
8
|
+
constructor(dataDir, scope = 'community') {
|
|
9
|
+
this.path = join(dataDir, scope === 'community' ? '.community-key' : '.plugin-config-key');
|
|
10
|
+
this.namespace = scope === 'community' ? 'Cordis MAS community sign-in v1:cloud-genshin' : 'AUTO-MASC plugin configuration v1';
|
|
11
|
+
}
|
|
12
|
+
async load(create) {
|
|
13
|
+
try {
|
|
14
|
+
const info = await lstat(this.path);
|
|
15
|
+
if (!info.isFile() || info.size !== 32 || (process.platform !== 'win32' && (info.mode & 0o077) !== 0)) {
|
|
16
|
+
throw new Error('本机加密密钥文件无效或权限过宽');
|
|
17
|
+
}
|
|
18
|
+
return await readFile(this.path);
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code !== 'ENOENT')
|
|
22
|
+
throw error;
|
|
23
|
+
if (!create)
|
|
24
|
+
throw new Error('找不到本机加密密钥,请重新配置');
|
|
25
|
+
const key = randomBytes(32);
|
|
26
|
+
try {
|
|
27
|
+
await writeFile(this.path, key, { flag: 'wx', mode: 0o600 });
|
|
28
|
+
}
|
|
29
|
+
catch (writeError) {
|
|
30
|
+
if (writeError.code !== 'EEXIST')
|
|
31
|
+
throw writeError;
|
|
32
|
+
return this.load(false);
|
|
33
|
+
}
|
|
34
|
+
return key;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
key(create) {
|
|
38
|
+
this.pending ??= this.load(create).catch(error => { this.pending = undefined; throw error; });
|
|
39
|
+
return this.pending;
|
|
40
|
+
}
|
|
41
|
+
context(id) {
|
|
42
|
+
return Buffer.from(`${this.namespace}:${id}`);
|
|
43
|
+
}
|
|
44
|
+
async seal(id, secret) {
|
|
45
|
+
const nonce = randomBytes(12);
|
|
46
|
+
const cipher = createCipheriv('aes-256-gcm', await this.key(true), nonce);
|
|
47
|
+
cipher.setAAD(this.context(id));
|
|
48
|
+
const data = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
|
|
49
|
+
return { version: 1, nonce: nonce.toString('base64'), cipher: data.toString('base64'), tag: cipher.getAuthTag().toString('base64') };
|
|
50
|
+
}
|
|
51
|
+
async reveal(id, secret) {
|
|
52
|
+
const key = await this.key(false);
|
|
53
|
+
try {
|
|
54
|
+
if (secret.version !== 1)
|
|
55
|
+
throw new Error('Unrecognized credential');
|
|
56
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(secret.nonce, 'base64'), { authTagLength: 16 });
|
|
57
|
+
decipher.setAAD(this.context(id));
|
|
58
|
+
decipher.setAuthTag(Buffer.from(secret.tag, 'base64'));
|
|
59
|
+
return Buffer.concat([decipher.update(Buffer.from(secret.cipher, 'base64')), decipher.final()]).toString('utf8');
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw new Error('无法解密本机配置,请重新配置');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const downloadFile = Symbol.for('auto-masc.download-file');
|
|
2
|
+
export class DownloadFile {
|
|
3
|
+
[downloadFile] = true;
|
|
4
|
+
path;
|
|
5
|
+
name;
|
|
6
|
+
open;
|
|
7
|
+
constructor(path, name, open) {
|
|
8
|
+
this.path = path;
|
|
9
|
+
this.name = name;
|
|
10
|
+
this.open = open;
|
|
11
|
+
}
|
|
12
|
+
static is(value) {
|
|
13
|
+
return !!value && typeof value === 'object' && value[downloadFile] === true;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
import {} from 'cordis';
|
|
5
|
+
import { Store } from './storage.js';
|
|
6
|
+
import { UiRegistry } from './ui.js';
|
|
7
|
+
import { deliveryError, NotificationError } from './notifications/service.js';
|
|
8
|
+
import { CredentialVault } from './community/vault.js';
|
|
9
|
+
const exec = promisify(execFile);
|
|
10
|
+
const webhookKey = (id) => `notification-webhook:${id}`;
|
|
11
|
+
function configured(input, name) {
|
|
12
|
+
const value = input[name];
|
|
13
|
+
if (typeof value !== 'string' || !value.trim())
|
|
14
|
+
throw new Error(`缺少配置: ${name}`);
|
|
15
|
+
return value.trim();
|
|
16
|
+
}
|
|
17
|
+
export async function notifications(ctx, dataDir) {
|
|
18
|
+
const ui = ctx.get('mas.ui');
|
|
19
|
+
const store = ctx.get('mas.store');
|
|
20
|
+
const notifications = ctx.get('mas.notifications');
|
|
21
|
+
const vault = new CredentialVault(dataDir, 'plugin');
|
|
22
|
+
const legacy = store.list('notifications').filter(target => target.url);
|
|
23
|
+
if (legacy.length) {
|
|
24
|
+
const encrypted = await Promise.all(legacy.map(async (target) => ({ target, secret: target.secret ?? await vault.seal(webhookKey(target.id), target.url) })));
|
|
25
|
+
store.transaction(() => {
|
|
26
|
+
for (const { target, secret } of encrypted) {
|
|
27
|
+
const current = store.get('notifications', target.id);
|
|
28
|
+
if (!current || current.url !== target.url)
|
|
29
|
+
continue;
|
|
30
|
+
const { url, ...rest } = current;
|
|
31
|
+
store.put('notifications', { ...rest, secret });
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
async function deliver(target, payload, signal) {
|
|
36
|
+
try {
|
|
37
|
+
if (!target.secret)
|
|
38
|
+
throw new NotificationError('Webhook 地址未配置');
|
|
39
|
+
const address = await vault.reveal(webhookKey(target.id), target.secret).catch(() => {
|
|
40
|
+
throw new NotificationError('Webhook 地址无法读取,请重新配置');
|
|
41
|
+
});
|
|
42
|
+
const response = await fetch(address, {
|
|
43
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(10000)]),
|
|
44
|
+
headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload),
|
|
45
|
+
});
|
|
46
|
+
await response.body?.cancel();
|
|
47
|
+
if (!response.ok)
|
|
48
|
+
throw new NotificationError(`Webhook 返回 HTTP ${response.status}`);
|
|
49
|
+
if (!signal.aborted)
|
|
50
|
+
store.put('notification-results', { id: target.id, status: '已送达', time: new Date().toISOString() });
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (!signal.aborted)
|
|
54
|
+
store.put('notification-results', { id: target.id, status: '发送失败', time: new Date().toISOString(), error: deliveryError(error) });
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
notifications.register(ctx, { id: 'notifications', label: 'Webhook 通知', events: ['task', 'community'], async send(message, signal, targetId) {
|
|
59
|
+
const targets = store.list('notifications').filter(target => message.type === 'test'
|
|
60
|
+
? target.id === targetId : target.enabled && (!target.failureOnly || message.failed)
|
|
61
|
+
&& (message.type !== 'community' || target.community));
|
|
62
|
+
if (!targets.length)
|
|
63
|
+
return 'skipped';
|
|
64
|
+
const outcomes = await Promise.allSettled(targets.map(target => deliver(target, message.payload ?? message, signal)));
|
|
65
|
+
const failed = outcomes.filter(outcome => outcome.status === 'rejected').length;
|
|
66
|
+
if (failed)
|
|
67
|
+
throw new NotificationError(`${failed} 个 Webhook 发送失败`);
|
|
68
|
+
return 'sent';
|
|
69
|
+
} });
|
|
70
|
+
const components = [
|
|
71
|
+
{ type: 'table', title: 'Webhook 通知', query: 'notifications.list', columns: [
|
|
72
|
+
{ key: 'name', label: '名称' }, { key: 'enabled', label: '启用', toggle: 'notifications.toggle' },
|
|
73
|
+
{ key: 'community', label: '签到汇总', toggle: 'notifications.community' }, { key: 'status', label: '最新发送' },
|
|
74
|
+
], rowActions: [{ id: 'notifications.test', label: '测试' }, { id: 'notifications.toggle', label: '切换启用' }] },
|
|
75
|
+
{ type: 'form', title: '新增 Webhook', action: 'notifications.add', initial: { name: '新 Webhook' }, fields: [
|
|
76
|
+
{ key: 'name', label: '名称', required: true }, { key: 'url', label: 'Webhook URL', kind: 'password', required: true },
|
|
77
|
+
{ key: 'failureOnly', label: '仅失败时发送', kind: 'boolean' },
|
|
78
|
+
{ key: 'community', label: '同时发送游戏社区签到汇总', kind: 'boolean' },
|
|
79
|
+
] },
|
|
80
|
+
];
|
|
81
|
+
ctx.inject(['mas.settings'], nested => {
|
|
82
|
+
const settings = nested.get('mas.settings');
|
|
83
|
+
settings.section(nested, 'notifications', { title: '通知设置', description: '配置任务运行结果的通知方式', aliases: ['/notifications'], pluginId: 'notifications', components });
|
|
84
|
+
});
|
|
85
|
+
ui.panel(ctx, 'notifications', components, { 'notifications.list': () => store.list('notifications').map(target => ({
|
|
86
|
+
id: target.id, name: target.name, enabled: Boolean(target.enabled), community: target.community === true,
|
|
87
|
+
status: store.get('notification-results', target.id)?.status,
|
|
88
|
+
})) }, {
|
|
89
|
+
'notifications.add': async (input) => {
|
|
90
|
+
const url = new URL(configured(input, 'url'));
|
|
91
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
|
|
92
|
+
throw new Error('请输入有效的 HTTP(S) Webhook');
|
|
93
|
+
const id = randomUUID();
|
|
94
|
+
const secret = await vault.seal(webhookKey(id), url.href);
|
|
95
|
+
store.put('notifications', { id, name: configured(input, 'name'), secret, enabled: true,
|
|
96
|
+
failureOnly: input.failureOnly === true, community: input.community === true });
|
|
97
|
+
return { id };
|
|
98
|
+
},
|
|
99
|
+
'notifications.test': async (input) => {
|
|
100
|
+
const target = store.get('notifications', configured(input, 'id'));
|
|
101
|
+
if (!target)
|
|
102
|
+
throw new Error('Webhook 不存在');
|
|
103
|
+
await notifications.test('notifications', target.id);
|
|
104
|
+
},
|
|
105
|
+
'notifications.toggle': input => {
|
|
106
|
+
const target = store.get('notifications', configured(input, 'id'));
|
|
107
|
+
if (!target)
|
|
108
|
+
throw new Error('Webhook 不存在');
|
|
109
|
+
const { value } = input;
|
|
110
|
+
if (value !== undefined && typeof value !== 'boolean')
|
|
111
|
+
throw new Error('启用状态必须为布尔值');
|
|
112
|
+
const enabled = value ?? !target.enabled;
|
|
113
|
+
store.put('notifications', { ...target, enabled });
|
|
114
|
+
return { enabled };
|
|
115
|
+
},
|
|
116
|
+
'notifications.community': input => {
|
|
117
|
+
const target = store.get('notifications', configured(input, 'id'));
|
|
118
|
+
if (!target)
|
|
119
|
+
throw new Error('Webhook 不存在');
|
|
120
|
+
if (typeof input.value !== 'boolean')
|
|
121
|
+
throw new Error('启用状态必须为布尔值');
|
|
122
|
+
return { enabled: store.put('notifications', { ...target, community: input.value }).community };
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
export function devices(ctx) {
|
|
127
|
+
const ui = ctx.get('mas.ui');
|
|
128
|
+
ui.panel(ctx, 'devices', [
|
|
129
|
+
{ type: 'metrics', title: '控制器能力', query: 'devices.capabilities' },
|
|
130
|
+
{ type: 'table', title: '已连接设备', query: 'devices.adb', columns: [{ key: 'id', label: '设备序列号' }, { key: 'status', label: '状态' }, { key: 'details', label: '详情' }] },
|
|
131
|
+
{ type: 'form', title: '扫描 ADB 设备', action: 'devices.scan', result: true, fields: [{ key: 'adb', label: 'ADB 路径(留空使用 PATH)' }] },
|
|
132
|
+
], {
|
|
133
|
+
'devices.capabilities': () => [
|
|
134
|
+
{ label: '主机', value: process.platform }, { label: 'ADB', value: '可配置' },
|
|
135
|
+
{ label: 'Win32', value: process.platform === 'win32' ? '支持' : '仅 Windows' },
|
|
136
|
+
],
|
|
137
|
+
'devices.adb': () => latest,
|
|
138
|
+
}, {
|
|
139
|
+
'devices.scan': async (input) => {
|
|
140
|
+
const adb = typeof input.adb === 'string' && input.adb.trim() || 'adb';
|
|
141
|
+
const { stdout } = await exec(adb, ['devices', '-l'], { timeout: 10000, windowsHide: true });
|
|
142
|
+
latest = stdout.split(/\r?\n/).flatMap(line => {
|
|
143
|
+
const match = line.match(/^(\S+)\s+(device|offline|unauthorized|recovery|sideload|bootloader)\b\s*(.*)$/);
|
|
144
|
+
return match ? [{ id: match[1], status: match[2], details: match[3] }] : [];
|
|
145
|
+
});
|
|
146
|
+
return { count: latest.length };
|
|
147
|
+
},
|
|
148
|
+
});
|
|
149
|
+
let latest = [];
|
|
150
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
const results = 'notification-channel-results';
|
|
2
|
+
const deliveryLimit = 1000;
|
|
3
|
+
export class NotificationError extends Error {
|
|
4
|
+
safeMessage;
|
|
5
|
+
constructor(message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.safeMessage = message;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export function deliveryError(error) {
|
|
11
|
+
if (error instanceof Error && 'safeMessage' in error && typeof error.safeMessage === 'string')
|
|
12
|
+
return error.safeMessage;
|
|
13
|
+
return '发送失败,请核对渠道配置和网络连接';
|
|
14
|
+
}
|
|
15
|
+
export class NotificationService {
|
|
16
|
+
channels = new Map();
|
|
17
|
+
deliveries = new Map();
|
|
18
|
+
store;
|
|
19
|
+
changed;
|
|
20
|
+
constructor(store, changed = () => { }) {
|
|
21
|
+
this.store = store;
|
|
22
|
+
this.changed = changed;
|
|
23
|
+
}
|
|
24
|
+
register(ctx, channel) {
|
|
25
|
+
ctx.effect(() => {
|
|
26
|
+
if (this.channels.has(channel.id))
|
|
27
|
+
throw new Error('该通知渠道已经注册');
|
|
28
|
+
const entry = { channel, stopped: new AbortController(), pending: new Set() };
|
|
29
|
+
this.channels.set(channel.id, entry);
|
|
30
|
+
this.changed();
|
|
31
|
+
return async () => {
|
|
32
|
+
if (this.channels.get(channel.id) === entry)
|
|
33
|
+
this.channels.delete(channel.id);
|
|
34
|
+
entry.stopped.abort();
|
|
35
|
+
this.changed();
|
|
36
|
+
await Promise.allSettled(entry.pending);
|
|
37
|
+
};
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
status(id) {
|
|
41
|
+
return this.store.get(results, id);
|
|
42
|
+
}
|
|
43
|
+
list() {
|
|
44
|
+
return [...this.channels.values()].map(({ channel }) => ({ ...this.status(channel.id), id: channel.id, name: channel.label }));
|
|
45
|
+
}
|
|
46
|
+
async dispatch(notification) {
|
|
47
|
+
const pending = [...this.channels.values()].flatMap(entry => {
|
|
48
|
+
if (notification.type === 'test' || !entry.channel.events.includes(notification.type)
|
|
49
|
+
|| (entry.channel.failureOnly && !notification.failed))
|
|
50
|
+
return [];
|
|
51
|
+
const key = `${notification.type}:${notification.id}:${entry.channel.id}`;
|
|
52
|
+
const previous = this.deliveries.get(key);
|
|
53
|
+
if (previous)
|
|
54
|
+
return [previous];
|
|
55
|
+
const promise = this.deliver(entry, notification);
|
|
56
|
+
this.deliveries.set(key, promise);
|
|
57
|
+
if (this.deliveries.size > deliveryLimit)
|
|
58
|
+
this.deliveries.delete(this.deliveries.keys().next().value);
|
|
59
|
+
return [promise];
|
|
60
|
+
});
|
|
61
|
+
await Promise.allSettled(pending);
|
|
62
|
+
}
|
|
63
|
+
async test(id, target) {
|
|
64
|
+
const entry = this.channels.get(id);
|
|
65
|
+
if (!entry)
|
|
66
|
+
throw new NotificationError('通知渠道未启用');
|
|
67
|
+
const result = await this.deliver(entry, { id: `test:${Date.now()}`, type: 'test', title: 'AUTO-MASC 测试通知',
|
|
68
|
+
text: '这是一条测试通知。', time: new Date().toISOString(), payload: { type: 'notification.test' } }, target);
|
|
69
|
+
if (result === 'skipped')
|
|
70
|
+
throw new NotificationError('没有可用的通知目标');
|
|
71
|
+
return { 状态: result === 'sent' ? '已发送' : '已提交' };
|
|
72
|
+
}
|
|
73
|
+
deliver(entry, notification, target) {
|
|
74
|
+
const { channel, stopped, pending } = entry;
|
|
75
|
+
const task = Promise.resolve().then(async () => {
|
|
76
|
+
try {
|
|
77
|
+
stopped.signal.throwIfAborted();
|
|
78
|
+
const result = await channel.send(notification, AbortSignal.any([stopped.signal, AbortSignal.timeout(30_000)]), target);
|
|
79
|
+
if (!stopped.signal.aborted && result !== 'skipped') {
|
|
80
|
+
this.store.put(results, { id: channel.id, time: new Date().toISOString(), status: result === 'sent' ? '已发送' : '已提交' });
|
|
81
|
+
this.changed();
|
|
82
|
+
}
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (stopped.signal.aborted)
|
|
87
|
+
return 'skipped';
|
|
88
|
+
const message = deliveryError(error);
|
|
89
|
+
this.store.put(results, { id: channel.id, time: new Date().toISOString(), status: '发送失败', error: message });
|
|
90
|
+
this.changed();
|
|
91
|
+
throw new NotificationError(message);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
pending.add(task);
|
|
95
|
+
void task.then(() => pending.delete(task), () => pending.delete(task));
|
|
96
|
+
return task;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -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
|
+
}
|