dsh-dingtalk 0.3.14 → 0.4.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/CHANGELOG.md +5 -0
- package/README.en.md +28 -25
- package/README.md +27 -24
- package/docs/USAGE.en.md +74 -95
- package/docs/USAGE.md +70 -97
- package/lib/config.js +1 -1
- package/lib/host-config.d.ts +111 -0
- package/lib/host-config.js +469 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +11 -7
- package/lib/update-client.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
const kSchema = Symbol.for('schemastery');
|
|
2
|
+
const kValidationError = Symbol.for('ValidationError');
|
|
3
|
+
const kVolatileWrite = Symbol.for('cosmokit.volatile.write');
|
|
4
|
+
const kCheckedVolatile = Symbol('checked-volatile-schema');
|
|
5
|
+
const globalState = globalThis;
|
|
6
|
+
export class HostValidationError extends TypeError {
|
|
7
|
+
options;
|
|
8
|
+
name = 'ValidationError';
|
|
9
|
+
constructor(message, options = {}) {
|
|
10
|
+
let prefix = '$';
|
|
11
|
+
for (const segment of options.path ?? []) {
|
|
12
|
+
if (typeof segment === 'string')
|
|
13
|
+
prefix += '.' + segment;
|
|
14
|
+
else if (typeof segment === 'number')
|
|
15
|
+
prefix += '[' + segment + ']';
|
|
16
|
+
else
|
|
17
|
+
prefix += `[Symbol(${segment.toString()})]`;
|
|
18
|
+
}
|
|
19
|
+
if (prefix.startsWith('.'))
|
|
20
|
+
prefix = prefix.slice(1);
|
|
21
|
+
super((prefix === '$' ? '' : `${prefix} `) + message);
|
|
22
|
+
this.options = options;
|
|
23
|
+
}
|
|
24
|
+
static is(error) {
|
|
25
|
+
return typeof error === 'object' && error !== null && Boolean(error[kValidationError]);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
Object.defineProperty(HostValidationError.prototype, kValidationError, { value: true });
|
|
29
|
+
function isNullable(value) {
|
|
30
|
+
return value === null || value === undefined;
|
|
31
|
+
}
|
|
32
|
+
function isPlainObject(value) {
|
|
33
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
34
|
+
return false;
|
|
35
|
+
const proto = Object.getPrototypeOf(value);
|
|
36
|
+
return proto === Object.prototype || proto === null;
|
|
37
|
+
}
|
|
38
|
+
function isVolatile(value) {
|
|
39
|
+
return typeof value === 'object' && value !== null && kVolatileWrite in value;
|
|
40
|
+
}
|
|
41
|
+
function cloneValue(value) {
|
|
42
|
+
if (value === null || typeof value !== 'object')
|
|
43
|
+
return value;
|
|
44
|
+
if (Array.isArray(value))
|
|
45
|
+
return value.map((item) => cloneValue(item));
|
|
46
|
+
if (isPlainObject(value)) {
|
|
47
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, cloneValue(v)]));
|
|
48
|
+
}
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
function deepEqual(a, b) {
|
|
52
|
+
if (Object.is(a, b))
|
|
53
|
+
return true;
|
|
54
|
+
if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null)
|
|
55
|
+
return false;
|
|
56
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
57
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
|
|
58
|
+
return false;
|
|
59
|
+
return a.every((item, idx) => deepEqual(item, b[idx]));
|
|
60
|
+
}
|
|
61
|
+
if (!isPlainObject(a) || !isPlainObject(b))
|
|
62
|
+
return false;
|
|
63
|
+
const keysA = Object.keys(a);
|
|
64
|
+
const keysB = Object.keys(b);
|
|
65
|
+
if (keysA.length !== keysB.length)
|
|
66
|
+
return false;
|
|
67
|
+
return keysA.every((key) => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key]));
|
|
68
|
+
}
|
|
69
|
+
function snapshotValue(value, ancestors = new Set()) {
|
|
70
|
+
if (typeof value === 'function')
|
|
71
|
+
throw new TypeError('volatile config cannot contain functions');
|
|
72
|
+
if (value === null || typeof value !== 'object')
|
|
73
|
+
return value;
|
|
74
|
+
if (ancestors.has(value))
|
|
75
|
+
throw new TypeError('volatile config cannot contain cycles');
|
|
76
|
+
ancestors.add(value);
|
|
77
|
+
try {
|
|
78
|
+
if (Array.isArray(value))
|
|
79
|
+
return Object.freeze(value.map((item) => snapshotValue(item, ancestors)));
|
|
80
|
+
if (!isPlainObject(value))
|
|
81
|
+
throw new TypeError('volatile config objects must be plain objects or arrays');
|
|
82
|
+
return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshotValue(item, ancestors)])));
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
ancestors.delete(value);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export function createVolatile(value) {
|
|
89
|
+
let current = snapshotValue(value);
|
|
90
|
+
return Object.freeze({
|
|
91
|
+
get: () => current,
|
|
92
|
+
[kVolatileWrite]: (next) => { current = snapshotValue(next); },
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
function validateVolatileTree(schema, path = [], blocked = false, seen = new Map()) {
|
|
96
|
+
const states = seen.get(schema) ?? new Set();
|
|
97
|
+
if (states.has(blocked))
|
|
98
|
+
return;
|
|
99
|
+
states.add(blocked);
|
|
100
|
+
seen.set(schema, states);
|
|
101
|
+
if (schema.meta?.volatile && blocked) {
|
|
102
|
+
throw new HostValidationError('volatile fields require a fixed object path without an enclosing volatile field', { path });
|
|
103
|
+
}
|
|
104
|
+
const nested = blocked || Boolean(schema.meta?.volatile);
|
|
105
|
+
if (schema.dict) {
|
|
106
|
+
for (const [key, child] of Object.entries(schema.dict))
|
|
107
|
+
validateVolatileTree(child, [...path, key], nested, seen);
|
|
108
|
+
}
|
|
109
|
+
if (schema.inner)
|
|
110
|
+
validateVolatileTree(schema.inner, [...path, '*'], true, seen);
|
|
111
|
+
if (schema.list) {
|
|
112
|
+
schema.list.forEach((child, idx) => validateVolatileTree(child, [...path, String(idx)], true, seen));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function checkRange(value, meta, label, options, skipMin = false) {
|
|
116
|
+
const max = meta.max ?? Infinity;
|
|
117
|
+
const min = meta.min ?? -Infinity;
|
|
118
|
+
if (value > max)
|
|
119
|
+
throw new HostValidationError(`expected ${label} <= ${max} but got ${value}`, options);
|
|
120
|
+
if (value < min && !skipMin)
|
|
121
|
+
throw new HostValidationError(`expected ${label} >= ${min} but got ${value}`, options);
|
|
122
|
+
}
|
|
123
|
+
function resolveProperty(data, key, schema, options) {
|
|
124
|
+
const container = data;
|
|
125
|
+
try {
|
|
126
|
+
const [value, adapted] = resolveSchema(container[key], schema, {
|
|
127
|
+
...options,
|
|
128
|
+
path: [...(options.path ?? []), key],
|
|
129
|
+
});
|
|
130
|
+
if (adapted !== undefined)
|
|
131
|
+
container[key] = adapted;
|
|
132
|
+
return value;
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (!options.autofix)
|
|
136
|
+
throw error;
|
|
137
|
+
delete container[key];
|
|
138
|
+
return schema.meta.volatile ? createVolatile(schema.meta.default) : cloneValue(schema.meta.default);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function resolveSchema(data, schema, options = {}, strict = false) {
|
|
142
|
+
if (!schema)
|
|
143
|
+
return [data];
|
|
144
|
+
if (!options[kCheckedVolatile]) {
|
|
145
|
+
validateVolatileTree(schema, options.path);
|
|
146
|
+
options = { ...options, [kCheckedVolatile]: true };
|
|
147
|
+
}
|
|
148
|
+
if (schema.meta?.volatile) {
|
|
149
|
+
const inner = makeSchema({ ...schema, meta: { ...schema.meta, volatile: false } });
|
|
150
|
+
const [value, adapted] = resolveSchema(data, inner, options, strict);
|
|
151
|
+
try {
|
|
152
|
+
return [createVolatile(value), adapted];
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
throw new HostValidationError(error instanceof Error ? error.message : String(error), options);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (options.ignore?.(data, schema))
|
|
159
|
+
return [data];
|
|
160
|
+
if (isNullable(data)) {
|
|
161
|
+
if (schema.meta.required)
|
|
162
|
+
throw new HostValidationError('missing required value', options);
|
|
163
|
+
if (isNullable(schema.meta.default))
|
|
164
|
+
return [data];
|
|
165
|
+
data = cloneValue(schema.meta.default);
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
switch (schema.type) {
|
|
169
|
+
case 'any':
|
|
170
|
+
return [data];
|
|
171
|
+
case 'const':
|
|
172
|
+
if (deepEqual(data, schema.value))
|
|
173
|
+
return [schema.value];
|
|
174
|
+
throw new HostValidationError(`expected ${String(schema.value)} but got ${String(data)}`, options);
|
|
175
|
+
case 'string': {
|
|
176
|
+
if (typeof data !== 'string')
|
|
177
|
+
throw new HostValidationError(`expected string but got ${String(data)}`, options);
|
|
178
|
+
if (schema.meta.pattern) {
|
|
179
|
+
const re = new RegExp(schema.meta.pattern.source, schema.meta.pattern.flags);
|
|
180
|
+
if (!re.test(data))
|
|
181
|
+
throw new HostValidationError(`expect string to match regexp ${String(re)}`, options);
|
|
182
|
+
}
|
|
183
|
+
checkRange(data.length, schema.meta, 'string length', options);
|
|
184
|
+
return [data];
|
|
185
|
+
}
|
|
186
|
+
case 'number': {
|
|
187
|
+
if (typeof data !== 'number' || Number.isNaN(data))
|
|
188
|
+
throw new HostValidationError(`expected number but got ${String(data)}`, options);
|
|
189
|
+
checkRange(data, schema.meta, 'number', options);
|
|
190
|
+
return [data];
|
|
191
|
+
}
|
|
192
|
+
case 'boolean':
|
|
193
|
+
if (typeof data === 'boolean')
|
|
194
|
+
return [data];
|
|
195
|
+
throw new HostValidationError(`expected boolean but got ${String(data)}`, options);
|
|
196
|
+
case 'array': {
|
|
197
|
+
if (!Array.isArray(data) || !schema.inner)
|
|
198
|
+
throw new HostValidationError(`expected array but got ${String(data)}`, options);
|
|
199
|
+
checkRange(data.length, schema.meta, 'array length', options, !isNullable(schema.inner.meta.default));
|
|
200
|
+
const copy = [...data];
|
|
201
|
+
return [copy.map((_, idx) => resolveProperty(copy, idx, schema.inner, options))];
|
|
202
|
+
}
|
|
203
|
+
case 'object': {
|
|
204
|
+
if (!isPlainObject(data))
|
|
205
|
+
throw new HostValidationError(`expected object but got ${String(data)}`, options);
|
|
206
|
+
const dict = schema.dict ?? {};
|
|
207
|
+
const copy = { ...data };
|
|
208
|
+
const result = {};
|
|
209
|
+
for (const key of Object.keys(dict)) {
|
|
210
|
+
const value = resolveProperty(copy, key, dict[key], options);
|
|
211
|
+
if (!isNullable(value) || key in copy)
|
|
212
|
+
result[key] = value;
|
|
213
|
+
}
|
|
214
|
+
if (!strict) {
|
|
215
|
+
for (const key of Object.keys(copy)) {
|
|
216
|
+
if (!(key in result))
|
|
217
|
+
result[key] = copy[key];
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return [result];
|
|
221
|
+
}
|
|
222
|
+
case 'union': {
|
|
223
|
+
for (const candidate of schema.list ?? []) {
|
|
224
|
+
try {
|
|
225
|
+
return resolveSchema(data, candidate, options, strict);
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
// Try next union branch.
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
throw new HostValidationError(`expected ${schema.toString()} but got ${JSON.stringify(data)}`, options);
|
|
232
|
+
}
|
|
233
|
+
default:
|
|
234
|
+
throw new HostValidationError(`unsupported type "${schema.type}"`, options);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
if (!schema.meta.loose)
|
|
239
|
+
throw error;
|
|
240
|
+
return [cloneValue(schema.meta.default)];
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function mergeDescriptions(original, messages) {
|
|
244
|
+
const result = typeof original === 'string' ? { '': original } : { ...(original ?? {}) };
|
|
245
|
+
for (const [locale, entry] of Object.entries(messages)) {
|
|
246
|
+
if (typeof entry === 'string') {
|
|
247
|
+
result[locale] = entry;
|
|
248
|
+
}
|
|
249
|
+
else if (isPlainObject(entry)) {
|
|
250
|
+
const desc = entry.$description ?? entry.$desc;
|
|
251
|
+
if (typeof desc === 'string')
|
|
252
|
+
result[locale] = desc;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return result;
|
|
256
|
+
}
|
|
257
|
+
const schemaProto = Object.create(Function.prototype);
|
|
258
|
+
schemaProto[kSchema] = true;
|
|
259
|
+
Object.defineProperty(schemaProto, '~standard', {
|
|
260
|
+
get() {
|
|
261
|
+
return {
|
|
262
|
+
version: 1,
|
|
263
|
+
vendor: 'schemastery',
|
|
264
|
+
validate: (value) => {
|
|
265
|
+
try {
|
|
266
|
+
return { value: resolveSchema(value, this, {})[0] };
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
if (HostValidationError.is(error)) {
|
|
270
|
+
return { issues: [{ message: error.message, path: error.options.path }] };
|
|
271
|
+
}
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
},
|
|
277
|
+
});
|
|
278
|
+
schemaProto.toJSON = function toJSON() {
|
|
279
|
+
if (globalState.__schemastery_refs__) {
|
|
280
|
+
globalState.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
281
|
+
return this.uid;
|
|
282
|
+
}
|
|
283
|
+
globalState.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
284
|
+
globalState.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
285
|
+
const result = { uid: this.uid, refs: globalState.__schemastery_refs__ };
|
|
286
|
+
globalState.__schemastery_refs__ = undefined;
|
|
287
|
+
return result;
|
|
288
|
+
};
|
|
289
|
+
schemaProto.toString = function toString(inline = false) {
|
|
290
|
+
if (this.type === 'const')
|
|
291
|
+
return typeof this.value === 'string' ? JSON.stringify(this.value) : String(this.value);
|
|
292
|
+
if (this.type === 'array' && this.inner)
|
|
293
|
+
return `${this.inner.toString(true)}[]`;
|
|
294
|
+
if (this.type === 'union' && this.list) {
|
|
295
|
+
const joined = this.list.map((item) => item.toString()).join(' | ');
|
|
296
|
+
return inline ? `(${joined})` : joined;
|
|
297
|
+
}
|
|
298
|
+
if (this.type === 'object' && this.dict) {
|
|
299
|
+
const entries = Object.entries(this.dict);
|
|
300
|
+
if (entries.length === 0)
|
|
301
|
+
return '{}';
|
|
302
|
+
return `{ ${entries.map(([k, v]) => `${k}${v.meta.required ? '' : '?'}: ${v.toString()}`).join(', ')} }`;
|
|
303
|
+
}
|
|
304
|
+
return this.type;
|
|
305
|
+
};
|
|
306
|
+
schemaProto.simplify = function simplify(raw) {
|
|
307
|
+
const value = isVolatile(raw) ? raw.get() : raw;
|
|
308
|
+
if (deepEqual(value, this.meta.default))
|
|
309
|
+
return null;
|
|
310
|
+
if (isNullable(value))
|
|
311
|
+
return value;
|
|
312
|
+
if (this.type === 'object' && isPlainObject(value)) {
|
|
313
|
+
const out = {};
|
|
314
|
+
for (const [key, item] of Object.entries(value)) {
|
|
315
|
+
const simplified = this.dict?.[key] ? this.dict[key].simplify(item) : item;
|
|
316
|
+
if (!isNullable(simplified))
|
|
317
|
+
out[key] = simplified;
|
|
318
|
+
}
|
|
319
|
+
return deepEqual(out, this.meta.default) ? null : out;
|
|
320
|
+
}
|
|
321
|
+
if (this.type === 'array' && Array.isArray(value)) {
|
|
322
|
+
return value.map((item) => (this.inner ? this.inner.simplify(item) : item));
|
|
323
|
+
}
|
|
324
|
+
return value;
|
|
325
|
+
};
|
|
326
|
+
schemaProto.i18n = function i18n(messages) {
|
|
327
|
+
const cloned = makeSchema(this);
|
|
328
|
+
const desc = mergeDescriptions(cloned.meta.description, messages);
|
|
329
|
+
if (Object.keys(desc).length > 0)
|
|
330
|
+
cloned.meta = { ...cloned.meta, description: desc };
|
|
331
|
+
if (cloned.dict) {
|
|
332
|
+
const nextDict = {};
|
|
333
|
+
for (const [key, child] of Object.entries(cloned.dict)) {
|
|
334
|
+
const childMessages = {};
|
|
335
|
+
for (const [locale, data] of Object.entries(messages)) {
|
|
336
|
+
if (isPlainObject(data)) {
|
|
337
|
+
const inner = isPlainObject(data.$value) ? data.$value : isPlainObject(data.$inner) ? data.$inner : data;
|
|
338
|
+
if (key in inner)
|
|
339
|
+
childMessages[locale] = inner[key];
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
nextDict[key] = child.i18n(childMessages);
|
|
343
|
+
}
|
|
344
|
+
cloned.dict = nextDict;
|
|
345
|
+
}
|
|
346
|
+
if (cloned.inner) {
|
|
347
|
+
const innerMessages = {};
|
|
348
|
+
for (const [locale, data] of Object.entries(messages)) {
|
|
349
|
+
if (isPlainObject(data)) {
|
|
350
|
+
const inner = data.$value ?? data.$inner;
|
|
351
|
+
if (inner !== undefined)
|
|
352
|
+
innerMessages[locale] = inner;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
cloned.inner = cloned.inner.i18n(innerMessages);
|
|
356
|
+
}
|
|
357
|
+
return cloned;
|
|
358
|
+
};
|
|
359
|
+
schemaProto.extra = function extra(key, value) {
|
|
360
|
+
const cloned = makeSchema(this);
|
|
361
|
+
cloned.meta = { ...cloned.meta, [key]: value };
|
|
362
|
+
return cloned;
|
|
363
|
+
};
|
|
364
|
+
schemaProto.role = function role(name, extraValue) {
|
|
365
|
+
const cloned = makeSchema(this);
|
|
366
|
+
cloned.meta = { ...cloned.meta, role: name, ...(extraValue !== undefined ? { extra: extraValue } : {}) };
|
|
367
|
+
return cloned;
|
|
368
|
+
};
|
|
369
|
+
for (const key of ['default', 'link', 'comment', 'description', 'max', 'min', 'step']) {
|
|
370
|
+
schemaProto[key] = function (value) {
|
|
371
|
+
return this.extra(key, value);
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
for (const key of ['required', 'disabled', 'collapse', 'hidden', 'loose']) {
|
|
375
|
+
schemaProto[key] = function (value = true) {
|
|
376
|
+
return this.extra(key, value);
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
schemaProto.pattern = function pattern(regexp) {
|
|
380
|
+
return this.extra('pattern', { source: regexp.source, flags: regexp.flags });
|
|
381
|
+
};
|
|
382
|
+
schemaProto.volatile = function volatile() {
|
|
383
|
+
if (this.meta.volatile)
|
|
384
|
+
throw new TypeError('volatile schema is already wrapped');
|
|
385
|
+
return this.extra('volatile', true);
|
|
386
|
+
};
|
|
387
|
+
schemaProto.set = function set(key, value) {
|
|
388
|
+
this.dict ??= {};
|
|
389
|
+
this.dict[key] = value;
|
|
390
|
+
return this;
|
|
391
|
+
};
|
|
392
|
+
schemaProto.push = function push(value) {
|
|
393
|
+
this.list ??= [];
|
|
394
|
+
this.list.push(value);
|
|
395
|
+
return this;
|
|
396
|
+
};
|
|
397
|
+
function makeSchema(init) {
|
|
398
|
+
const fn = function (data, options = {}) {
|
|
399
|
+
return resolveSchema(data, fn, options)[0];
|
|
400
|
+
};
|
|
401
|
+
Object.assign(fn, {
|
|
402
|
+
type: init.type,
|
|
403
|
+
meta: { ...(init.meta ?? {}) },
|
|
404
|
+
...(init.dict ? { dict: { ...init.dict } } : {}),
|
|
405
|
+
...(init.inner ? { inner: init.inner } : {}),
|
|
406
|
+
...(init.list ? { list: [...init.list] } : {}),
|
|
407
|
+
...('value' in init ? { value: init.value } : {}),
|
|
408
|
+
});
|
|
409
|
+
globalState.__schemastery_index__ ??= 0;
|
|
410
|
+
Object.defineProperty(fn, 'uid', { value: globalState.__schemastery_index__++, enumerable: false });
|
|
411
|
+
Object.setPrototypeOf(fn, schemaProto);
|
|
412
|
+
fn.toString = fn.toString.bind(fn);
|
|
413
|
+
return fn;
|
|
414
|
+
}
|
|
415
|
+
function fromSource(source) {
|
|
416
|
+
if (typeof source === 'function' && Boolean(source[kSchema])) {
|
|
417
|
+
return source;
|
|
418
|
+
}
|
|
419
|
+
if (typeof source === 'string' || typeof source === 'number' || typeof source === 'boolean') {
|
|
420
|
+
return makeSchema({ type: 'const', value: source, meta: { required: true } });
|
|
421
|
+
}
|
|
422
|
+
throw new TypeError(`cannot infer schema from ${String(source)}`);
|
|
423
|
+
}
|
|
424
|
+
export const z = {
|
|
425
|
+
string: () => makeSchema({ type: 'string' }),
|
|
426
|
+
number: () => makeSchema({ type: 'number' }),
|
|
427
|
+
boolean: () => makeSchema({ type: 'boolean' }),
|
|
428
|
+
const: (value) => makeSchema({ type: 'const', value }),
|
|
429
|
+
union: (list) => makeSchema({ type: 'union', list: list.map(fromSource) }),
|
|
430
|
+
array: (inner) => makeSchema({ type: 'array', inner, meta: { default: [] } }),
|
|
431
|
+
object: (dict) => makeSchema({ type: 'object', dict, meta: { default: {} } }),
|
|
432
|
+
ValidationError: HostValidationError,
|
|
433
|
+
};
|
|
434
|
+
/**
|
|
435
|
+
* 宿主原生设置表单 Schema。
|
|
436
|
+
* 不给标量字段设 default,避免空白默认值遮蔽 cordis.patch.yml 与环境变量 DSH_DINGTALK_SECRET。
|
|
437
|
+
*/
|
|
438
|
+
export const Config = z.object({
|
|
439
|
+
webhook: z.string().role('secret').volatile()
|
|
440
|
+
.description('钉钉群自定义机器人完整 Webhook 地址(形如 https://oapi.dingtalk.com/robot/send?access_token=...,保存即生效)'),
|
|
441
|
+
secret: z.string().role('secret').volatile()
|
|
442
|
+
.description('加签密钥(可选,SEC 开头;留空时自动回退环境变量 DSH_DINGTALK_SECRET)'),
|
|
443
|
+
timeoutMs: z.number().min(1000).max(60000).step(1000).volatile()
|
|
444
|
+
.description('单次请求超时毫秒数(1000–60000,默认 10000)'),
|
|
445
|
+
}).i18n({
|
|
446
|
+
zh: {
|
|
447
|
+
$description: '钉钉群自定义机器人通知设置(保存立即生效,无需重启 DSH)',
|
|
448
|
+
webhook: '钉钉群自定义机器人完整 Webhook 地址(形如 https://oapi.dingtalk.com/robot/send?access_token=...)',
|
|
449
|
+
secret: '加签密钥(推荐,SEC 开头;留空则读取环境变量 DSH_DINGTALK_SECRET)',
|
|
450
|
+
timeoutMs: '单次发送超时(毫秒,范围 1000–60000,默认 10000)',
|
|
451
|
+
},
|
|
452
|
+
en: {
|
|
453
|
+
$description: 'DingTalk custom group webhook settings (applied live on save without restarting DSH)',
|
|
454
|
+
webhook: 'Full DingTalk custom robot Webhook URL (https://oapi.dingtalk.com/robot/send?access_token=...)',
|
|
455
|
+
secret: 'HMAC-SHA256 signing secret (SEC...; falls back to env var DSH_DINGTALK_SECRET when blank)',
|
|
456
|
+
timeoutMs: 'Request timeout in milliseconds (1000–60000, default 10000)',
|
|
457
|
+
},
|
|
458
|
+
});
|
|
459
|
+
/** 活引用视图:同时兼容 DSH >=0.1.7 的 { get() } 活引用与旧宿主/测试传入的普通对象。 */
|
|
460
|
+
export function liveConfig(config) {
|
|
461
|
+
return new Proxy(config, {
|
|
462
|
+
get(target, key, receiver) {
|
|
463
|
+
const value = Reflect.get(target, key, receiver);
|
|
464
|
+
return value !== null && typeof value === 'object' && typeof value.get === 'function'
|
|
465
|
+
? value.get()
|
|
466
|
+
: value;
|
|
467
|
+
},
|
|
468
|
+
});
|
|
469
|
+
}
|
package/lib/index.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { type DingTalkConfig } from './config.js';
|
|
2
|
+
export declare const Config: import("./host-config.js").HostSchemaNode<DingTalkConfig>;
|
|
2
3
|
export declare const name = "tool-dingtalk";
|
|
3
4
|
export declare const inject: string[];
|
|
4
5
|
export type Config = DingTalkConfig;
|
|
5
6
|
export declare function apply(ctx: any, config?: Config): void;
|
|
6
7
|
export { resolveDingTalkConfig, describeWebhookProblem, DINGTALK_SECRET_ENV, DEFAULT_TIMEOUT_MS, clampInt } from './config.js';
|
|
8
|
+
export { liveConfig, createVolatile, HostValidationError, type HostSchemaNode, type HostSchemaMeta, type VolatileRef } from './host-config.js';
|
|
7
9
|
export { DingTalkClient, DingTalkError, dingTalkErrorMessage } from './client.js';
|
|
8
10
|
export type { FetchLike, FetchLikeResponse, DingTalkClientOptions } from './client.js';
|
|
9
11
|
export { computeDingTalkSign, signedUrl, dingTalkTimestamp } from './sign.js';
|
package/lib/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { registerUpdates } from '@stardustlc/dsh-updates';
|
|
2
2
|
import { describeWebhookProblem, resolveDingTalkConfig, DINGTALK_SECRET_ENV } from './config.js';
|
|
3
3
|
import { DingTalkClient } from './client.js';
|
|
4
|
+
import { Config as DingTalkConfigSchema, liveConfig } from './host-config.js';
|
|
5
|
+
export const Config = DingTalkConfigSchema;
|
|
4
6
|
export const name = 'tool-dingtalk';
|
|
5
7
|
export const inject = ['tools'];
|
|
6
8
|
/**
|
|
@@ -53,10 +55,11 @@ function renderNotify(value) {
|
|
|
53
55
|
}
|
|
54
56
|
export function apply(ctx, config = {}) {
|
|
55
57
|
registerUpdates(ctx, { name: "dsh-dingtalk" });
|
|
58
|
+
const live = liveConfig((config ?? {}));
|
|
56
59
|
let client = null;
|
|
57
60
|
let fingerprint = '';
|
|
58
61
|
const getClient = () => {
|
|
59
|
-
const resolved = resolveDingTalkConfig(
|
|
62
|
+
const resolved = resolveDingTalkConfig(live);
|
|
60
63
|
const fp = JSON.stringify(resolved);
|
|
61
64
|
if (client === null || fp !== fingerprint) {
|
|
62
65
|
client = new DingTalkClient(resolved);
|
|
@@ -79,7 +82,7 @@ export function apply(ctx, config = {}) {
|
|
|
79
82
|
};
|
|
80
83
|
registerTool({
|
|
81
84
|
name: 'dingtalk_notify',
|
|
82
|
-
description: '向配置的钉钉群发送一条 Markdown 消息(单向通知)。title 为标题,text 为 Markdown 正文;需先在 profile 的 cordis.patch.yml 配置 webhook(与可选 secret 加签密钥)。',
|
|
85
|
+
description: '向配置的钉钉群发送一条 Markdown 消息(单向通知)。title 为标题,text 为 Markdown 正文;需先在 DSH「设置 → 插件 → 钉钉」或 profile 的 cordis.patch.yml 配置 webhook(与可选 secret 加签密钥)。',
|
|
83
86
|
parameters: compileParameters({
|
|
84
87
|
title: { type: 'string', required: true, description: '消息标题(显示在钉钉卡片顶部)' },
|
|
85
88
|
text: { type: 'string', required: true, description: 'Markdown 正文内容' },
|
|
@@ -135,7 +138,7 @@ export function apply(ctx, config = {}) {
|
|
|
135
138
|
}
|
|
136
139
|
if (rec.ok !== true) {
|
|
137
140
|
lines.push('', '下一步:');
|
|
138
|
-
lines.push(' · 在 profile 的 cordis.patch.yml 里覆盖 tool-dingtalk
|
|
141
|
+
lines.push(' · 在 DSH「设置 → 插件 → 钉钉(dsh-dingtalk)」直接填写完整 webhook(含 access_token)与可选 secret(保存即生效,无需重启);或在 profile 的 cordis.patch.yml 里覆盖 tool-dingtalk 行,secret 也可放环境变量 DSH_DINGTALK_SECRET。');
|
|
139
142
|
lines.push(' · 发送失败时先看错误里的钉钉 errcode:310000 是加签不匹配,120001 是 token 失效,按提示改配置后重新运行 dingtalk_health。');
|
|
140
143
|
}
|
|
141
144
|
return oneText(lines.join('\n'));
|
|
@@ -145,16 +148,16 @@ export function apply(ctx, config = {}) {
|
|
|
145
148
|
const checks = [];
|
|
146
149
|
let ok = true;
|
|
147
150
|
// 自检只做本地校验:既不发消息,也不触网,避免「自检」把告警群刷屏。
|
|
148
|
-
const webhook = typeof
|
|
151
|
+
const webhook = typeof live?.webhook === 'string' ? live.webhook.trim() : '';
|
|
149
152
|
const webhookProblem = describeWebhookProblem(webhook);
|
|
150
153
|
if (webhookProblem === undefined) {
|
|
151
154
|
checks.push({ name: 'webhook', ok: true, detail: '已配置(https://oapi.dingtalk.com/robot/send?access_token=***)' });
|
|
152
155
|
}
|
|
153
156
|
else {
|
|
154
157
|
ok = false;
|
|
155
|
-
checks.push({ name: 'webhook', ok: false, detail: webhookProblem + ':请从钉钉群「自定义机器人」设置里复制完整地址,填到 tool-dingtalk
|
|
158
|
+
checks.push({ name: 'webhook', ok: false, detail: webhookProblem + ':请从钉钉群「自定义机器人」设置里复制完整地址,填到 DSH「设置 → 插件 → 钉钉」的 webhook(保存即生效)或 cordis.patch.yml 的 tool-dingtalk 行' });
|
|
156
159
|
}
|
|
157
|
-
const configuredSecret = typeof
|
|
160
|
+
const configuredSecret = typeof live?.secret === 'string' ? live.secret.trim() : '';
|
|
158
161
|
const envSecret = (process.env[DINGTALK_SECRET_ENV] ?? '').trim();
|
|
159
162
|
if (configuredSecret !== '')
|
|
160
163
|
checks.push({ name: '加签密钥', ok: true, detail: '已配置(加签模式,来源:配置里的 secret)' });
|
|
@@ -163,7 +166,7 @@ export function apply(ctx, config = {}) {
|
|
|
163
166
|
else
|
|
164
167
|
checks.push({ name: '加签密钥', ok: true, detail: '未配置(关键词/IP 白名单模式;若机器人开启加签,发送会返回 310000)' });
|
|
165
168
|
try {
|
|
166
|
-
const resolved = resolveDingTalkConfig(
|
|
169
|
+
const resolved = resolveDingTalkConfig(live);
|
|
167
170
|
checks.push({ name: '请求超时', ok: true, detail: resolved.timeoutMs + 'ms(1000-60000,可用 timeoutMs 调整)' });
|
|
168
171
|
}
|
|
169
172
|
catch {
|
|
@@ -184,5 +187,6 @@ export function apply(ctx, config = {}) {
|
|
|
184
187
|
}
|
|
185
188
|
}
|
|
186
189
|
export { resolveDingTalkConfig, describeWebhookProblem, DINGTALK_SECRET_ENV, DEFAULT_TIMEOUT_MS, clampInt } from './config.js';
|
|
190
|
+
export { liveConfig, createVolatile, HostValidationError } from './host-config.js';
|
|
187
191
|
export { DingTalkClient, DingTalkError, dingTalkErrorMessage } from './client.js';
|
|
188
192
|
export { computeDingTalkSign, signedUrl, dingTalkTimestamp } from './sign.js';
|