@auto-mas/auto-mas-plugin-notification-qqbot 0.0.0-stage → 0.1.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,234 @@
1
+ import { createDecipheriv, randomBytes, randomUUID } from 'node:crypto';
2
+ import { setTimeout as wait } from 'node:timers/promises';
3
+ import { CredentialVault } from '../community/vault.js';
4
+ import { renderQrSvgDataUrl } from '../community/qrcode.js';
5
+ import { jsonObject, notificationJson, notificationText, NotificationHttpError, postJson } from './channel.js';
6
+ import { NotificationError } from './service.js';
7
+ const api = 'https://api.bot.qq.com';
8
+ const portal = 'https://q.qq.com';
9
+ const collection = 'notification-qqbot';
10
+ const bindingId = 'notification-qqbot:pairing';
11
+ const validApp = /^\d{1,24}$/u;
12
+ const validOpenId = /^[\w-]{1,128}$/u;
13
+ function text(value) { return typeof value === 'string' ? value.trim() : ''; }
14
+ function checkBusiness(response, error) {
15
+ for (const field of ['code', 'retcode', 'errcode', 'errno']) {
16
+ const code = response[field];
17
+ if (code !== undefined && code !== 0 && code !== '0')
18
+ throw new NotificationError(error);
19
+ }
20
+ }
21
+ function decryptSecret(data, key) {
22
+ try {
23
+ if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(data) || data.length > 2048)
24
+ throw new Error();
25
+ const raw = Buffer.from(data, 'base64');
26
+ if (raw.length <= 28)
27
+ throw new Error();
28
+ const decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12), { authTagLength: 16 });
29
+ decipher.setAuthTag(raw.subarray(-16));
30
+ const secret = Buffer.concat([decipher.update(raw.subarray(12, -16)), decipher.final()]).toString('utf8').trim();
31
+ if (!secret)
32
+ throw new Error();
33
+ return secret;
34
+ }
35
+ catch {
36
+ throw new NotificationError('QQ 返回的绑定凭据无法验证,请重新扫码');
37
+ }
38
+ }
39
+ export class QqBot {
40
+ store;
41
+ config;
42
+ vault;
43
+ request;
44
+ lifetime = new AbortController();
45
+ starting;
46
+ current;
47
+ polling;
48
+ token;
49
+ tokenRequest;
50
+ groupSendAt = new Map();
51
+ constructor(dataDir, store, config, request = fetch) {
52
+ this.store = store;
53
+ this.vault = new CredentialVault(dataDir, 'plugin');
54
+ this.config = config;
55
+ this.request = request;
56
+ }
57
+ async credentials() {
58
+ if (this.config.mode === 'manual')
59
+ return this.config;
60
+ const row = this.store.get(collection, bindingId);
61
+ if (!row)
62
+ return undefined;
63
+ try {
64
+ return JSON.parse(await this.vault.reveal(bindingId, row.secret));
65
+ }
66
+ catch {
67
+ throw new NotificationError('QQ 绑定凭据无法读取,请重新扫码');
68
+ }
69
+ }
70
+ status() {
71
+ return { mode: this.config.mode, paired: !!this.store.get(collection, bindingId),
72
+ manual: Boolean(this.config.appId && this.config.clientSecret), direct: this.config.direct,
73
+ groupCount: this.config.groupOpenIds.filter(Boolean).length };
74
+ }
75
+ async start() {
76
+ this.cancel();
77
+ this.lifetime.signal.throwIfAborted();
78
+ const starting = this.starting = new AbortController();
79
+ const signal = AbortSignal.any([this.lifetime.signal, starting.signal]);
80
+ const key = randomBytes(32);
81
+ try {
82
+ const response = await this.portal('/lite/create_bind_task', { key: key.toString('base64') }, signal);
83
+ const taskId = text(response.task_id);
84
+ signal.throwIfAborted();
85
+ if (!taskId || taskId.length > 200)
86
+ throw new NotificationError('QQ 未返回有效的扫码任务');
87
+ const session = this.current = { id: randomUUID(), key, taskId, expires: Date.now() + 300_000, active: new AbortController() };
88
+ const qr = new URL('/qqbot/openclaw/connect.html', portal);
89
+ qr.searchParams.set('task_id', taskId);
90
+ qr.searchParams.set('_wv', '2');
91
+ return { id: session.id, qrImage: renderQrSvgDataUrl(qr.href), expiresAt: new Date(session.expires).toISOString() };
92
+ }
93
+ finally {
94
+ if (this.starting === starting)
95
+ this.starting = undefined;
96
+ }
97
+ }
98
+ async poll(id) {
99
+ const session = this.current;
100
+ if (!session || session.id !== id)
101
+ return { status: 'canceled', message: '扫码会话已关闭' };
102
+ if (session.expires <= Date.now()) {
103
+ this.cancel(id);
104
+ return { status: 'expired', message: '二维码已过期,请重新生成' };
105
+ }
106
+ if (this.polling?.session === session)
107
+ return this.polling.result;
108
+ const result = this.readPairing(session);
109
+ this.polling = { session, result };
110
+ try {
111
+ return await result;
112
+ }
113
+ finally {
114
+ if (this.polling?.result === result)
115
+ this.polling = undefined;
116
+ }
117
+ }
118
+ cancel(id) {
119
+ if (id && this.current?.id !== id)
120
+ return;
121
+ this.starting?.abort();
122
+ this.current?.active.abort();
123
+ this.current = undefined;
124
+ }
125
+ unbind() {
126
+ this.cancel();
127
+ this.token = undefined;
128
+ this.store.remove(collection, bindingId);
129
+ }
130
+ async close() {
131
+ this.lifetime.abort();
132
+ this.cancel();
133
+ await Promise.allSettled([this.polling?.result, this.tokenRequest?.result]);
134
+ }
135
+ async portal(path, payload, signal) {
136
+ const response = await postJson(`${portal}${path}`, payload, signal, { Accept: 'application/json' }, this.request);
137
+ const result = jsonObject(await notificationJson(response));
138
+ checkBusiness(result, 'QQ 拒绝了扫码绑定请求,请重新发起');
139
+ return jsonObject(result.data);
140
+ }
141
+ async readPairing(session) {
142
+ const signal = AbortSignal.any([this.lifetime.signal, session.active.signal]);
143
+ const data = await this.portal('/lite/poll_bind_result', { task_id: session.taskId }, signal);
144
+ signal.throwIfAborted();
145
+ if (Number(data.status) === 3 || session.expires <= Date.now()) {
146
+ this.cancel(session.id);
147
+ return { status: 'expired', message: '二维码已过期,请重新生成' };
148
+ }
149
+ if (Number(data.status) === 1)
150
+ return { status: 'scanned', message: '已扫描,请在手机 QQ 确认' };
151
+ if (Number(data.status) !== 2)
152
+ return { status: 'waiting', message: '请使用手机 QQ 扫描二维码' };
153
+ const appId = text(data.bot_appid);
154
+ const userOpenId = text(data.user_openid);
155
+ if (!validApp.test(appId) || !validOpenId.test(userOpenId))
156
+ throw new NotificationError('QQ 未返回有效的机器人和接收人信息');
157
+ const clientSecret = decryptSecret(text(data.bot_encrypt_secret), session.key);
158
+ const secret = await this.vault.seal(bindingId, JSON.stringify({ appId, userOpenId, clientSecret }));
159
+ signal.throwIfAborted();
160
+ this.store.put(collection, { id: bindingId, secret });
161
+ this.token = undefined;
162
+ this.cancel(session.id);
163
+ return { status: 'paired', message: 'QQ 官方机器人已绑定,凭据已加密保存' };
164
+ }
165
+ async accessToken(credentials) {
166
+ const { appId, clientSecret } = credentials;
167
+ if (this.token?.appId === appId && this.token.clientSecret === clientSecret && this.token.expires > Date.now())
168
+ return this.token.value;
169
+ if (this.tokenRequest?.appId === appId && this.tokenRequest.clientSecret === clientSecret)
170
+ return this.tokenRequest.result;
171
+ const result = (async () => {
172
+ const response = await postJson(`${api}/app/getAppAccessToken`, { appId, clientSecret }, this.lifetime.signal, {}, this.request);
173
+ const data = jsonObject(await notificationJson(response));
174
+ checkBusiness(data, 'QQ 无法验证机器人 AppID 或 ClientSecret');
175
+ const value = text(data.access_token);
176
+ const expires = Number(data.expires_in);
177
+ if (!value || !Number.isFinite(expires) || expires <= 0)
178
+ throw new NotificationError('QQ 未返回有效的机器人访问凭据');
179
+ this.token = { appId, clientSecret, value, expires: Date.now() + Math.max(0, expires - 60) * 1000 };
180
+ return value;
181
+ })();
182
+ this.tokenRequest = { appId, clientSecret, result };
183
+ try {
184
+ return await result;
185
+ }
186
+ finally {
187
+ if (this.tokenRequest?.result === result)
188
+ this.tokenRequest = undefined;
189
+ }
190
+ }
191
+ async send(message, signal) {
192
+ const credentials = await this.credentials();
193
+ if (!credentials || !validApp.test(credentials.appId) || !credentials.clientSecret)
194
+ throw new NotificationError('请扫码绑定 QQ 官方机器人或完成手动配置');
195
+ const targets = [...new Set(this.config.groupOpenIds.map(value => value.trim()).filter(Boolean))].map(id => ({ kind: 'groups', id }));
196
+ if (this.config.direct)
197
+ targets.unshift({ kind: 'users', id: credentials.userOpenId });
198
+ if (!targets.length || targets.some(target => !validOpenId.test(target.id)))
199
+ throw new NotificationError('请配置有效的 QQ 用户或群 OpenID 接收目标');
200
+ const characters = Array.from(notificationText(message));
201
+ const content = characters.length > 1500 ? `${characters.slice(0, 1499).join('')}…` : characters.join('');
202
+ const outcomes = await Promise.allSettled(targets.map(async ({ kind, id }) => {
203
+ if (kind === 'groups') {
204
+ const now = Date.now();
205
+ const next = Math.max(now, this.groupSendAt.get(id) ?? 0);
206
+ this.groupSendAt.set(id, next + 3200);
207
+ if (next > now)
208
+ await wait(next - now, undefined, { signal });
209
+ }
210
+ const send = async (token) => {
211
+ const response = await postJson(`${api}/v2/${kind}/${id}/messages`, { msg_type: 0, content }, signal, { Authorization: `QQBot ${token}`, 'X-Union-Appid': credentials.appId }, this.request);
212
+ const result = jsonObject(await notificationJson(response));
213
+ checkBusiness(result, 'QQ 拒绝发送消息,请核对目标权限与平台频控');
214
+ if (!text(result.id))
215
+ throw new NotificationError('QQ 未返回消息回执');
216
+ };
217
+ const token = await this.accessToken(credentials);
218
+ try {
219
+ await send(token);
220
+ }
221
+ catch (error) {
222
+ if (!(error instanceof NotificationHttpError) || error.status !== 401)
223
+ throw error;
224
+ if (this.token?.value === token)
225
+ this.token = undefined;
226
+ await send(await this.accessToken(credentials));
227
+ }
228
+ }));
229
+ const failed = outcomes.find(result => result.status === 'rejected');
230
+ if (failed)
231
+ throw failed.reason;
232
+ return 'submitted';
233
+ }
234
+ }
@@ -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
+ }