@auto-mas/auto-mas-plugin-notification-cmcc 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,77 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import WebSocket from 'ws';
3
+ import { Schema } from '../schema.js';
4
+ import { channelFeature, eventFields, jsonObject, notificationText } from '../notifications/channel.js';
5
+ import { NotificationError } from '../notifications/service.js';
6
+ const Config = Schema.object({ apiKey: Schema.string().role('secret').default('').description('中国移动新消息 Channel API Key'), ...eventFields });
7
+ const endpoint = 'wss://5gvas01.cmicmaap.com/gtw-ai/openclaw/ws/msg';
8
+ export async function submitCmcc(apiKey, text, signal) {
9
+ const key = apiKey.trim();
10
+ if (!/^(ak|app)_[\w-]{1,512}$/u.test(key))
11
+ throw new NotificationError('中国移动新消息 API Key 格式无效');
12
+ const characters = Array.from(text);
13
+ const lifetime = AbortSignal.any([signal, AbortSignal.timeout(15_000)]);
14
+ lifetime.throwIfAborted();
15
+ await new Promise((resolve, reject) => {
16
+ const client = new WebSocket(endpoint, { headers: { 'X-API-Key': key }, handshakeTimeout: 10_000, maxPayload: 64 * 1024 });
17
+ let settled = false;
18
+ let authorized = false;
19
+ const abort = () => finish(new NotificationError('中国移动新消息连接超时或已关闭'));
20
+ const send = (frame) => new Promise((accept, rejectSend) => {
21
+ client.send(JSON.stringify(frame), error => error ? rejectSend(error) : accept());
22
+ });
23
+ function finish(error) {
24
+ if (settled)
25
+ return;
26
+ settled = true;
27
+ lifetime.removeEventListener('abort', abort);
28
+ if (client.readyState === WebSocket.OPEN)
29
+ client.close();
30
+ else if (client.readyState === WebSocket.CONNECTING)
31
+ client.terminate();
32
+ if (error)
33
+ reject(error);
34
+ else
35
+ resolve();
36
+ }
37
+ lifetime.addEventListener('abort', abort, { once: true });
38
+ client.on('error', () => finish(new NotificationError('无法连接中国移动新消息服务')));
39
+ client.once('close', () => finish(new NotificationError('中国移动新消息服务提前断开')));
40
+ client.once('open', () => { void send({ type: 'auth', apiKey: key, version: '2.0' }).catch(abort); });
41
+ client.on('message', raw => {
42
+ if (settled)
43
+ return;
44
+ let message;
45
+ try {
46
+ message = jsonObject(JSON.parse(raw.toString()));
47
+ }
48
+ catch {
49
+ finish(new NotificationError('中国移动新消息服务返回无效响应'));
50
+ return;
51
+ }
52
+ if (message.type === 'auth_failed' || message.type === 'error') {
53
+ finish(new NotificationError('中国移动新消息服务拒绝认证或消息'));
54
+ return;
55
+ }
56
+ if (message.type !== 'auth_ok' || authorized)
57
+ return;
58
+ authorized = true;
59
+ void (async () => {
60
+ for (let offset = 0; offset < characters.length; offset += 2000) {
61
+ lifetime.throwIfAborted();
62
+ await send({ type: 'send', apiKey: key, to: key, content: characters.slice(offset, offset + 2000).join(''),
63
+ messageId: `automas_${randomUUID().replaceAll('-', '')}` });
64
+ }
65
+ finish();
66
+ })().catch(abort);
67
+ });
68
+ });
69
+ }
70
+ export default function createFeature() {
71
+ return channelFeature({ id: 'notification-cmcc', name: '中国移动新消息通知', description: '通过中国移动新消息渠道提交通知', config: Config,
72
+ available: config => config.apiKey.trim() ? undefined : '请配置中国移动新消息 API Key', async send(config, message, signal) {
73
+ await submitCmcc(config.apiKey, notificationText(message), signal);
74
+ return 'submitted';
75
+ },
76
+ });
77
+ }
@@ -0,0 +1,31 @@
1
+ export const ui = (ctx) => ctx.get('mas.ui');
2
+ export const store = (ctx) => ctx.get('mas.store');
3
+ export const runner = (ctx) => ctx.get('mas.runner');
4
+ export function text(input, key, label, required = true) {
5
+ const value = input[key];
6
+ if (typeof value === 'string' && value.trim())
7
+ return value.trim();
8
+ if (required)
9
+ throw new Error(`请输入${label}`);
10
+ return '';
11
+ }
12
+ export function strings(value) {
13
+ if (!value)
14
+ return [];
15
+ if (Array.isArray(value) && value.every(item => typeof item === 'string'))
16
+ return value;
17
+ if (typeof value === 'string') {
18
+ if (value.trim().startsWith('[')) {
19
+ const parsed = JSON.parse(value);
20
+ if (Array.isArray(parsed) && parsed.every(item => typeof item === 'string'))
21
+ return parsed;
22
+ throw new Error('JSON 必须是字符串数组');
23
+ }
24
+ return value.split(/[\n,]+/).map(item => item.trim()).filter(Boolean);
25
+ }
26
+ throw new Error('请输入字符串列表');
27
+ }
28
+ export const field = (key, label, extra = {}) => ({ key, label, ...extra });
29
+ export const columns = (...pairs) => pairs.map(([key, label]) => ({ key, label }));
30
+ export const action = (id, label) => ({ id, label });
31
+ export const runColumns = columns(['name', '托管'], ['status', '状态'], ['started', '开始时间'], ['finished', '结束时间'], ['error', '结果详情']);
@@ -0,0 +1,99 @@
1
+ import { Schema } from '../schema.js';
2
+ import { ui } from '../features.js';
3
+ import { NotificationError } from './service.js';
4
+ export const eventFields = {
5
+ task: Schema.boolean().default(true).description('发送任务运行结果'),
6
+ community: Schema.boolean().default(true).description('发送游戏社区签到汇总'),
7
+ failureOnly: Schema.boolean().default(false).description('仅发送包含失败或验证项的通知'),
8
+ };
9
+ export function channelFeature(options) {
10
+ const { id, name, description, config } = options;
11
+ return { id, name, description, component: { Config: config, inject: ['mas.notifications'], apply(ctx, current) {
12
+ const notifications = ctx.get('mas.notifications');
13
+ options.prepare?.(ctx, current);
14
+ const unavailable = options.available?.(current);
15
+ notifications.register(ctx, { id, label: name, events: [...current.task ? ['task'] : [], ...current.community ? ['community'] : []],
16
+ failureOnly: current.failureOnly, send: (message, signal) => {
17
+ if (unavailable)
18
+ throw new NotificationError(unavailable);
19
+ return options.send(current, message, signal);
20
+ } });
21
+ ctx.inject(['mas.ui'], scope => {
22
+ const action = `${id}.test`;
23
+ const components = [
24
+ { type: 'choices', title: name, items: [{ label: '配置渠道', description, href: `/plugins?plugin=${id}` }] },
25
+ ...(unavailable ? [{ type: 'text', title: '渠道状态', text: unavailable }] : [
26
+ { type: 'form', title: name, action, fields: [], result: true, submitLabel: '发送测试通知' },
27
+ ]),
28
+ ];
29
+ ui(scope).panel(scope, id, components, {}, { [action]: () => notifications.test(id) });
30
+ scope.inject(['mas.settings'], settingsScope => {
31
+ const settings = settingsScope.get('mas.settings');
32
+ settings.section(settingsScope, 'notifications', { title: '通知设置', components, order: 10 });
33
+ });
34
+ });
35
+ } } };
36
+ }
37
+ export function notificationText(message) {
38
+ return `${message.title}\n${message.text}`;
39
+ }
40
+ export function httpAddress(value, message = '请配置有效的 HTTP(S) 服务地址') {
41
+ const url = URL.parse(value);
42
+ if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash)
43
+ throw new NotificationError(message);
44
+ return url;
45
+ }
46
+ export async function postJson(address, payload, signal, headers = {}, request = fetch) {
47
+ let response;
48
+ try {
49
+ response = await request(address, { method: 'POST', redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]),
50
+ headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(payload) });
51
+ }
52
+ catch {
53
+ throw new NotificationError('连接通知服务失败或超时');
54
+ }
55
+ if (!response.ok) {
56
+ await response.body?.cancel();
57
+ throw new NotificationHttpError(response.status);
58
+ }
59
+ return response;
60
+ }
61
+ export class NotificationHttpError extends NotificationError {
62
+ status;
63
+ constructor(status) {
64
+ super(`通知服务返回 HTTP ${status}`);
65
+ this.status = status;
66
+ }
67
+ }
68
+ export async function notificationJson(response) {
69
+ const reader = response.body?.getReader();
70
+ if (!reader)
71
+ throw new NotificationError('通知服务返回空响应');
72
+ const chunks = [];
73
+ let size = 0;
74
+ try {
75
+ for (;;) {
76
+ const chunk = await reader.read();
77
+ if (chunk.done)
78
+ break;
79
+ size += chunk.value.byteLength;
80
+ if (size > 256 * 1024) {
81
+ await reader.cancel();
82
+ throw new NotificationError('通知服务返回的数据过大');
83
+ }
84
+ chunks.push(chunk.value);
85
+ }
86
+ return JSON.parse(Buffer.concat(chunks, size).toString('utf8'));
87
+ }
88
+ catch (error) {
89
+ if (error instanceof NotificationError)
90
+ throw error;
91
+ throw new NotificationError('通知服务返回无效响应');
92
+ }
93
+ finally {
94
+ reader.releaseLock();
95
+ }
96
+ }
97
+ export function jsonObject(value) {
98
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
99
+ }
@@ -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
+ }