dsh-done-sound 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.
package/lib/index.js ADDED
@@ -0,0 +1,1046 @@
1
+ // dsh-done-sound/src/index.js
2
+ import { fileURLToPath } from "node:url";
3
+ import { mkdir, readFile, writeFile, unlink } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+
7
+ // C:/Users/Administrator/.dsh/profiles/web/node_modules/@deepseek-ai/cosmokit/lib/index.js
8
+ function isNullable(value) {
9
+ return value === null || value === void 0;
10
+ }
11
+ function isPlainObject(data) {
12
+ return data && typeof data === "object" && !Array.isArray(data);
13
+ }
14
+ function filterKeys(object, filter) {
15
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
16
+ }
17
+ function mapValues(object, transform) {
18
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
19
+ }
20
+ function pick(source, keys, forced) {
21
+ if (!keys) return { ...source };
22
+ const result = {};
23
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
24
+ return result;
25
+ }
26
+ function is(type, value) {
27
+ if (arguments.length === 1) return (value2) => is(type, value2);
28
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
29
+ }
30
+ function isArrayBufferLike(value) {
31
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
32
+ }
33
+ function isArrayBufferSource(value) {
34
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
35
+ }
36
+ var Binary;
37
+ (function(Binary2) {
38
+ Binary2.is = isArrayBufferLike;
39
+ Binary2.isSource = isArrayBufferSource;
40
+ function fromSource(source) {
41
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
42
+ else return source;
43
+ }
44
+ Binary2.fromSource = fromSource;
45
+ function toBase64(source) {
46
+ source = fromSource(source);
47
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
48
+ let binary = "";
49
+ const bytes = new Uint8Array(source);
50
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
51
+ return btoa(binary);
52
+ }
53
+ Binary2.toBase64 = toBase64;
54
+ function fromBase64(source) {
55
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
56
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
57
+ }
58
+ Binary2.fromBase64 = fromBase64;
59
+ function toHex(source) {
60
+ source = fromSource(source);
61
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
62
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
63
+ }
64
+ Binary2.toHex = toHex;
65
+ function fromHex(source) {
66
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
67
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
68
+ const buffer = [];
69
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
70
+ return Uint8Array.from(buffer).buffer;
71
+ }
72
+ Binary2.fromHex = fromHex;
73
+ })(Binary || (Binary = {}));
74
+ var base64ToArrayBuffer = Binary.fromBase64;
75
+ var arrayBufferToBase64 = Binary.toBase64;
76
+ var hexToArrayBuffer = Binary.fromHex;
77
+ var arrayBufferToHex = Binary.toHex;
78
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
79
+ if (!source || typeof source !== "object") return source;
80
+ if (is("Date", source)) return new Date(source.valueOf());
81
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
82
+ if (isArrayBufferLike(source)) return source.slice(0);
83
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
84
+ const cached = refs.get(source);
85
+ if (cached) return cached;
86
+ if (Array.isArray(source)) {
87
+ const result2 = [];
88
+ refs.set(source, result2);
89
+ source.forEach((value, index) => {
90
+ result2[index] = Reflect.apply(clone, null, [value, refs]);
91
+ });
92
+ return result2;
93
+ }
94
+ const result = Object.create(Object.getPrototypeOf(source));
95
+ refs.set(source, result);
96
+ for (const key of Reflect.ownKeys(source)) {
97
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
98
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
99
+ Reflect.defineProperty(result, key, descriptor);
100
+ }
101
+ return result;
102
+ }
103
+ function deepEqual(a, b, strict) {
104
+ if (a === b) return true;
105
+ if (!strict && isNullable(a) && isNullable(b)) return true;
106
+ if (typeof a !== typeof b) return false;
107
+ if (typeof a !== "object") return false;
108
+ if (!a || !b) return false;
109
+ function check(test, then) {
110
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
111
+ }
112
+ return check(Array.isArray, (a2, b2) => a2.length === b2.length && a2.every((item, index) => deepEqual(item, b2[index]))) ?? check(is("Date"), (a2, b2) => a2.valueOf() === b2.valueOf()) ?? check(is("RegExp"), (a2, b2) => a2.source === b2.source && a2.flags === b2.flags) ?? check(isArrayBufferLike, (a2, b2) => {
113
+ if (a2.byteLength !== b2.byteLength) return false;
114
+ const viewA = new Uint8Array(a2);
115
+ const viewB = new Uint8Array(b2);
116
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
117
+ return true;
118
+ }) ?? Object.keys({
119
+ ...a,
120
+ ...b
121
+ }).every((key) => deepEqual(a[key], b[key], strict));
122
+ }
123
+ var Time;
124
+ (function(Time2) {
125
+ Time2.millisecond = 1;
126
+ Time2.second = 1e3;
127
+ Time2.minute = Time2.second * 60;
128
+ Time2.hour = Time2.minute * 60;
129
+ Time2.day = Time2.hour * 24;
130
+ Time2.week = Time2.day * 7;
131
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
132
+ function setTimezoneOffset(offset) {
133
+ timezoneOffset = offset;
134
+ }
135
+ Time2.setTimezoneOffset = setTimezoneOffset;
136
+ function getTimezoneOffset() {
137
+ return timezoneOffset;
138
+ }
139
+ Time2.getTimezoneOffset = getTimezoneOffset;
140
+ function getDateNumber(date2 = /* @__PURE__ */ new Date(), offset) {
141
+ if (typeof date2 === "number") date2 = new Date(date2);
142
+ if (offset === void 0) offset = timezoneOffset;
143
+ return Math.floor((date2.valueOf() / Time2.minute - offset) / 1440);
144
+ }
145
+ Time2.getDateNumber = getDateNumber;
146
+ function fromDateNumber(value, offset) {
147
+ const date2 = new Date(value * Time2.day);
148
+ if (offset === void 0) offset = timezoneOffset;
149
+ return new Date(+date2 + offset * Time2.minute);
150
+ }
151
+ Time2.fromDateNumber = fromDateNumber;
152
+ const numeric = /\d+(?:\.\d+)?/.source;
153
+ const timeRegExp = new RegExp(`^${[
154
+ "w(?:eek(?:s)?)?",
155
+ "d(?:ay(?:s)?)?",
156
+ "h(?:our(?:s)?)?",
157
+ "m(?:in(?:ute)?(?:s)?)?",
158
+ "s(?:ec(?:ond)?(?:s)?)?"
159
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
160
+ function parseTime(source) {
161
+ const capture = timeRegExp.exec(source);
162
+ if (!capture) return 0;
163
+ return (parseFloat(capture[1]) * Time2.week || 0) + (parseFloat(capture[2]) * Time2.day || 0) + (parseFloat(capture[3]) * Time2.hour || 0) + (parseFloat(capture[4]) * Time2.minute || 0) + (parseFloat(capture[5]) * Time2.second || 0);
164
+ }
165
+ Time2.parseTime = parseTime;
166
+ function parseDate(date2) {
167
+ const parsed = parseTime(date2);
168
+ if (parsed) date2 = Date.now() + parsed;
169
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date2}`;
170
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date2}`;
171
+ return date2 ? new Date(date2) : /* @__PURE__ */ new Date();
172
+ }
173
+ Time2.parseDate = parseDate;
174
+ function format(ms) {
175
+ const abs = Math.abs(ms);
176
+ if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d";
177
+ else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h";
178
+ else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m";
179
+ else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s";
180
+ return ms + "ms";
181
+ }
182
+ Time2.format = format;
183
+ function toDigits(source, length = 2) {
184
+ return source.toString().padStart(length, "0");
185
+ }
186
+ Time2.toDigits = toDigits;
187
+ function template(template2, time = /* @__PURE__ */ new Date()) {
188
+ return template2.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
189
+ }
190
+ Time2.template = template;
191
+ })(Time || (Time = {}));
192
+
193
+ // C:/Users/Administrator/.dsh/profiles/web/node_modules/@deepseek-ai/schemastery/lib/index.mjs
194
+ var kSchema = Symbol.for("schemastery");
195
+ var kValidationError = Symbol.for("ValidationError");
196
+ globalThis.__schemastery_index__ ??= 0;
197
+ globalThis.__schemastery_refs__ = void 0;
198
+ var ValidationError = class extends TypeError {
199
+ options;
200
+ name = "ValidationError";
201
+ constructor(message, options) {
202
+ let prefix = "$";
203
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
204
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
205
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
206
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
207
+ super((prefix === "$" ? "" : `${prefix} `) + message);
208
+ this.options = options;
209
+ }
210
+ static is(error) {
211
+ return !!error?.[kValidationError];
212
+ }
213
+ };
214
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
215
+ var Schema = function(options) {
216
+ const schema = function(data, options2 = {}) {
217
+ return Schema.resolve(data, schema, options2)[0];
218
+ };
219
+ if (options.refs) {
220
+ const refs = mapValues(options.refs, (options2) => new Schema(options2));
221
+ const getRef = (uid) => refs[uid];
222
+ for (const key in refs) {
223
+ const options2 = refs[key];
224
+ options2.sKey = getRef(options2.sKey);
225
+ options2.inner = getRef(options2.inner);
226
+ options2.list = options2.list && options2.list.map(getRef);
227
+ options2.dict = options2.dict && mapValues(options2.dict, getRef);
228
+ }
229
+ return refs[options.uid];
230
+ }
231
+ Object.assign(schema, options);
232
+ if (typeof schema.callback === "string") try {
233
+ schema.callback = new Function("return " + schema.callback)();
234
+ } catch {
235
+ }
236
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
237
+ Object.setPrototypeOf(schema, Schema.prototype);
238
+ schema.meta ||= {};
239
+ schema.toString = schema.toString.bind(schema);
240
+ return schema;
241
+ };
242
+ Schema.prototype = Object.create(Function.prototype);
243
+ Schema.prototype[kSchema] = true;
244
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
245
+ return {
246
+ version: 1,
247
+ vendor: "schemastery",
248
+ validate: (value) => {
249
+ try {
250
+ return { value: Schema.resolve(value, this, {})[0] };
251
+ } catch (error) {
252
+ if (ValidationError.is(error)) return { issues: [{
253
+ message: error.message,
254
+ path: error.options.path
255
+ }] };
256
+ throw error;
257
+ }
258
+ }
259
+ };
260
+ } });
261
+ Schema.ValidationError = ValidationError;
262
+ Schema.prototype.toJSON = function toJSON() {
263
+ if (globalThis.__schemastery_refs__) {
264
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
265
+ return this.uid;
266
+ }
267
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
268
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
269
+ const result = {
270
+ uid: this.uid,
271
+ refs: globalThis.__schemastery_refs__
272
+ };
273
+ globalThis.__schemastery_refs__ = void 0;
274
+ return result;
275
+ };
276
+ Schema.prototype.set = function set(key, value) {
277
+ this.dict[key] = value;
278
+ return this;
279
+ };
280
+ Schema.prototype.push = function push(value) {
281
+ this.list.push(value);
282
+ return this;
283
+ };
284
+ function mergeDesc(original, messages) {
285
+ const result = typeof original === "string" ? { "": original } : { ...original };
286
+ for (const locale in messages) {
287
+ const value = messages[locale];
288
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
289
+ else if (typeof value === "string") result[locale] = value;
290
+ }
291
+ return result;
292
+ }
293
+ function getInner(value) {
294
+ return value?.$value ?? value?.$inner;
295
+ }
296
+ function extractKeys(data) {
297
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
298
+ }
299
+ Schema.prototype.i18n = function i18n(messages) {
300
+ const schema = Schema(this);
301
+ const desc = mergeDesc(schema.meta.description, messages);
302
+ if (Object.keys(desc).length) schema.meta.description = desc;
303
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
304
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
305
+ });
306
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
307
+ return inner.i18n(mapValues(messages, (data = {}) => {
308
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
309
+ if (Array.isArray(data)) return data[index];
310
+ return extractKeys(data);
311
+ }));
312
+ });
313
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
314
+ if (getInner(data)) return getInner(data);
315
+ return extractKeys(data);
316
+ }));
317
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
318
+ return schema;
319
+ };
320
+ Schema.prototype.extra = function extra(key, value) {
321
+ const schema = Schema(this);
322
+ schema.meta = {
323
+ ...schema.meta,
324
+ [key]: value
325
+ };
326
+ return schema;
327
+ };
328
+ for (const key of [
329
+ "required",
330
+ "disabled",
331
+ "collapse",
332
+ "hidden",
333
+ "loose"
334
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
335
+ const schema = Schema(this);
336
+ schema.meta = {
337
+ ...schema.meta,
338
+ [key]: value
339
+ };
340
+ return schema;
341
+ } });
342
+ Schema.prototype.deprecated = function deprecated() {
343
+ const schema = Schema(this);
344
+ schema.meta.badges ||= [];
345
+ schema.meta.badges.push({
346
+ text: "deprecated",
347
+ type: "danger"
348
+ });
349
+ return schema;
350
+ };
351
+ Schema.prototype.experimental = function experimental() {
352
+ const schema = Schema(this);
353
+ schema.meta.badges ||= [];
354
+ schema.meta.badges.push({
355
+ text: "experimental",
356
+ type: "warning"
357
+ });
358
+ return schema;
359
+ };
360
+ Schema.prototype.pattern = function pattern(regexp) {
361
+ const schema = Schema(this);
362
+ const pattern2 = pick(regexp, ["source", "flags"]);
363
+ schema.meta = {
364
+ ...schema.meta,
365
+ pattern: pattern2
366
+ };
367
+ return schema;
368
+ };
369
+ Schema.prototype.simplify = function simplify(value) {
370
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
371
+ if (isNullable(value)) return value;
372
+ if (this.type === "object" || this.type === "dict") {
373
+ const result = {};
374
+ for (const key in value) {
375
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
376
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
377
+ }
378
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
379
+ return result;
380
+ } else if (this.type === "array" || this.type === "tuple") {
381
+ const result = [];
382
+ value.forEach((value2, index) => {
383
+ const schema = this.type === "array" ? this.inner : this.list[index];
384
+ const item = schema ? schema.simplify(value2) : value2;
385
+ result.push(item);
386
+ });
387
+ return result;
388
+ } else if (this.type === "intersect") {
389
+ const result = {};
390
+ for (const item of this.list) Object.assign(result, item.simplify(value));
391
+ return result;
392
+ } else if (this.type === "union") for (const schema of this.list) try {
393
+ Schema.resolve(value, schema, {});
394
+ return schema.simplify(value);
395
+ } catch {
396
+ }
397
+ return value;
398
+ };
399
+ Schema.prototype.toString = function toString(inline) {
400
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
401
+ };
402
+ Schema.prototype.role = function role(role, extra2) {
403
+ const schema = Schema(this);
404
+ schema.meta = {
405
+ ...schema.meta,
406
+ role,
407
+ extra: extra2
408
+ };
409
+ return schema;
410
+ };
411
+ for (const key of [
412
+ "default",
413
+ "link",
414
+ "comment",
415
+ "description",
416
+ "max",
417
+ "min",
418
+ "step"
419
+ ]) Object.assign(Schema.prototype, { [key](value) {
420
+ const schema = Schema(this);
421
+ schema.meta = {
422
+ ...schema.meta,
423
+ [key]: value
424
+ };
425
+ return schema;
426
+ } });
427
+ var resolvers = {};
428
+ Schema.extend = function extend(type, resolve2) {
429
+ resolvers[type] = resolve2;
430
+ };
431
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
432
+ if (!schema) return [data];
433
+ if (options.ignore?.(data, schema)) return [data];
434
+ if (isNullable(data) && schema.type !== "lazy") {
435
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
436
+ let current = schema;
437
+ let fallback = schema.meta.default;
438
+ while (current?.type === "intersect" && isNullable(fallback)) {
439
+ current = current.list[0];
440
+ fallback = current?.meta.default;
441
+ }
442
+ if (isNullable(fallback)) return [data];
443
+ data = clone(fallback);
444
+ }
445
+ const callback = resolvers[schema.type];
446
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
447
+ try {
448
+ return callback(data, schema, options, strict);
449
+ } catch (error) {
450
+ if (!schema.meta.loose) throw error;
451
+ return [schema.meta.default];
452
+ }
453
+ };
454
+ Schema.from = function from(source) {
455
+ if (isNullable(source)) return Schema.any();
456
+ else if ([
457
+ "string",
458
+ "number",
459
+ "boolean"
460
+ ].includes(typeof source)) return Schema.const(source).required();
461
+ else if (source[kSchema]) return source;
462
+ else if (typeof source === "function") switch (source) {
463
+ case String:
464
+ return Schema.string().required();
465
+ case Number:
466
+ return Schema.number().required();
467
+ case Boolean:
468
+ return Schema.boolean().required();
469
+ case Function:
470
+ return Schema.function().required();
471
+ default:
472
+ return Schema.is(source).required();
473
+ }
474
+ else throw new TypeError(`cannot infer schema from ${source}`);
475
+ };
476
+ Schema.lazy = function lazy(builder) {
477
+ const toJSON2 = () => {
478
+ if (!schema.inner[kSchema]) {
479
+ schema.inner = schema.builder();
480
+ schema.inner.meta = {
481
+ ...schema.meta,
482
+ ...schema.inner.meta
483
+ };
484
+ }
485
+ return schema.inner.toJSON();
486
+ };
487
+ const schema = new Schema({
488
+ type: "lazy",
489
+ builder,
490
+ inner: { toJSON: toJSON2 }
491
+ });
492
+ return schema;
493
+ };
494
+ Schema.natural = function natural() {
495
+ return Schema.number().step(1).min(0);
496
+ };
497
+ Schema.percent = function percent() {
498
+ return Schema.number().step(0.01).min(0).max(1).role("slider");
499
+ };
500
+ Schema.date = function date() {
501
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
502
+ const date2 = new Date(value);
503
+ if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
504
+ return date2;
505
+ }, true)]);
506
+ };
507
+ Schema.regExp = function regExp(flag = "") {
508
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
509
+ try {
510
+ return new RegExp(value, flag);
511
+ } catch (e) {
512
+ throw new ValidationError(e.message, options);
513
+ }
514
+ }, true)]);
515
+ };
516
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
517
+ return Schema.union([
518
+ Schema.is(ArrayBuffer),
519
+ Schema.is(SharedArrayBuffer),
520
+ Schema.transform(Schema.any(), (value, options) => {
521
+ if (Binary.isSource(value)) return Binary.fromSource(value);
522
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
523
+ }, true),
524
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
525
+ try {
526
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
527
+ } catch (e) {
528
+ throw new ValidationError(e.message, options);
529
+ }
530
+ }, true)] : []
531
+ ]);
532
+ };
533
+ Schema.extend("lazy", (data, schema, options, strict) => {
534
+ if (!schema.inner[kSchema]) {
535
+ schema.inner = schema.builder();
536
+ schema.inner.meta = {
537
+ ...schema.meta,
538
+ ...schema.inner.meta
539
+ };
540
+ }
541
+ return Schema.resolve(data, schema.inner, options, strict);
542
+ });
543
+ Schema.extend("any", (data) => {
544
+ return [data];
545
+ });
546
+ Schema.extend("never", (data, _, options) => {
547
+ throw new ValidationError(`expected nullable but got ${data}`, options);
548
+ });
549
+ Schema.extend("const", (data, { value }, options) => {
550
+ if (deepEqual(data, value)) return [value];
551
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
552
+ });
553
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
554
+ const { max = Infinity, min = -Infinity } = meta;
555
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
556
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
557
+ }
558
+ Schema.extend("string", (data, { meta }, options) => {
559
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
560
+ if (meta.pattern) {
561
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
562
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
563
+ }
564
+ checkWithinRange(data.length, meta, "string length", options);
565
+ return [data];
566
+ });
567
+ function decimalShift(data, digits) {
568
+ const str = data.toString();
569
+ if (str.includes("e")) return data * Math.pow(10, digits);
570
+ const index = str.indexOf(".");
571
+ if (index === -1) return data * Math.pow(10, digits);
572
+ const frac = str.slice(index + 1);
573
+ const integer = str.slice(0, index);
574
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
575
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
576
+ }
577
+ function isMultipleOf(data, min, step) {
578
+ step = Math.abs(step);
579
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
580
+ const index = step.toString().indexOf(".");
581
+ const digits = step.toString().slice(index + 1).length;
582
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
583
+ }
584
+ Schema.extend("number", (data, { meta }, options) => {
585
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
586
+ checkWithinRange(data, meta, "number", options);
587
+ const { step } = meta;
588
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
589
+ return [data];
590
+ });
591
+ Schema.extend("boolean", (data, _, options) => {
592
+ if (typeof data === "boolean") return [data];
593
+ throw new ValidationError(`expected boolean but got ${data}`, options);
594
+ });
595
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
596
+ let value = 0, keys = [];
597
+ if (typeof data === "number") {
598
+ value = data;
599
+ for (const key in bits) if (data & bits[key]) keys.push(key);
600
+ } else if (Array.isArray(data)) {
601
+ keys = data;
602
+ for (const key of keys) {
603
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
604
+ if (key in bits) value |= bits[key];
605
+ }
606
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
607
+ if (value === meta.default) return [value];
608
+ return [value, keys];
609
+ });
610
+ Schema.extend("function", (data, _, options) => {
611
+ if (typeof data === "function") return [data];
612
+ throw new ValidationError(`expected function but got ${data}`, options);
613
+ });
614
+ Schema.extend("is", (data, { constructor }, options) => {
615
+ if (typeof constructor === "function") {
616
+ if (data instanceof constructor) return [data];
617
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
618
+ } else {
619
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
620
+ let prototype = Object.getPrototypeOf(data);
621
+ while (prototype) {
622
+ if (prototype.constructor?.name === constructor) return [data];
623
+ prototype = Object.getPrototypeOf(prototype);
624
+ }
625
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
626
+ }
627
+ });
628
+ function property(data, key, schema, options) {
629
+ try {
630
+ const [value, adapted] = Schema.resolve(data[key], schema, {
631
+ ...options,
632
+ path: [...options.path || [], key]
633
+ });
634
+ if (adapted !== void 0) data[key] = adapted;
635
+ return value;
636
+ } catch (e) {
637
+ if (!options?.autofix) throw e;
638
+ delete data[key];
639
+ return schema.meta.default;
640
+ }
641
+ }
642
+ Schema.extend("array", (data, { inner, meta }, options) => {
643
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
644
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
645
+ return [data.map((_, index) => property(data, index, inner, options))];
646
+ });
647
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
648
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
649
+ const result = {};
650
+ for (const key in data) {
651
+ let rKey;
652
+ try {
653
+ rKey = Schema.resolve(key, sKey, options)[0];
654
+ } catch (error) {
655
+ if (strict) continue;
656
+ throw error;
657
+ }
658
+ result[rKey] = property(data, key, inner, options);
659
+ data[rKey] = data[key];
660
+ if (key !== rKey) delete data[key];
661
+ }
662
+ return [result];
663
+ });
664
+ Schema.extend("tuple", (data, { list }, options, strict) => {
665
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
666
+ const result = list.map((inner, index) => property(data, index, inner, options));
667
+ if (strict) return [result];
668
+ result.push(...data.slice(list.length));
669
+ return [result];
670
+ });
671
+ function merge(result, data) {
672
+ for (const key in data) {
673
+ if (key in result) continue;
674
+ result[key] = data[key];
675
+ }
676
+ }
677
+ Schema.extend("object", (data, { dict }, options, strict) => {
678
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
679
+ const result = {};
680
+ for (const key in dict) {
681
+ const value = property(data, key, dict[key], options);
682
+ if (!isNullable(value) || key in data) result[key] = value;
683
+ }
684
+ if (!strict) merge(result, data);
685
+ return [result];
686
+ });
687
+ Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
688
+ const messages = [];
689
+ for (const inner of list) try {
690
+ return Schema.resolve(data, inner, options, strict);
691
+ } catch (error) {
692
+ messages.push(error);
693
+ }
694
+ throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
695
+ });
696
+ Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
697
+ if (!list.length) return [data];
698
+ let result;
699
+ for (const inner of list) {
700
+ const value = Schema.resolve(data, inner, options, true)[0];
701
+ if (isNullable(value)) continue;
702
+ if (isNullable(result)) result = value;
703
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
704
+ else if (typeof value === "object") merge(result ??= {}, value);
705
+ else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
706
+ }
707
+ if (!strict && isPlainObject(data)) merge(result, data);
708
+ return [result];
709
+ });
710
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
711
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
712
+ if (preserve) return [callback(result)];
713
+ else return [callback(result), callback(adapted)];
714
+ });
715
+ var formatters = {};
716
+ function defineMethod(name2, keys, format) {
717
+ formatters[name2] = format;
718
+ Object.assign(Schema, { [name2](...args) {
719
+ const schema = new Schema({ type: name2 });
720
+ keys.forEach((key, index) => {
721
+ switch (key) {
722
+ case "sKey":
723
+ schema.sKey = args[index] ?? Schema.string();
724
+ break;
725
+ case "inner":
726
+ schema.inner = Schema.from(args[index]);
727
+ break;
728
+ case "list":
729
+ schema.list = args[index].map(Schema.from);
730
+ break;
731
+ case "dict":
732
+ schema.dict = mapValues(args[index], Schema.from);
733
+ break;
734
+ case "bits":
735
+ schema.bits = {};
736
+ for (const key2 in args[index]) {
737
+ if (typeof args[index][key2] !== "number") continue;
738
+ schema.bits[key2] = args[index][key2];
739
+ }
740
+ break;
741
+ case "callback": {
742
+ const callback = schema.callback = args[index];
743
+ callback["toJSON"] ||= () => callback.toString();
744
+ break;
745
+ }
746
+ case "constructor": {
747
+ const constructor = schema.constructor = args[index];
748
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
749
+ break;
750
+ }
751
+ default:
752
+ schema[key] = args[index];
753
+ }
754
+ });
755
+ if (name2 === "object" || name2 === "dict") schema.meta.default = {};
756
+ else if (name2 === "array" || name2 === "tuple") schema.meta.default = [];
757
+ else if (name2 === "bitset") schema.meta.default = 0;
758
+ return schema;
759
+ } });
760
+ }
761
+ defineMethod("is", ["constructor"], ({ constructor }) => {
762
+ if (typeof constructor === "function") return constructor.name;
763
+ else return constructor;
764
+ });
765
+ defineMethod("any", [], () => "any");
766
+ defineMethod("never", [], () => "never");
767
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
768
+ defineMethod("string", [], () => "string");
769
+ defineMethod("number", [], () => "number");
770
+ defineMethod("boolean", [], () => "boolean");
771
+ defineMethod("bitset", ["bits"], () => "bitset");
772
+ defineMethod("function", [], () => "function");
773
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
774
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
775
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
776
+ defineMethod("object", ["dict"], ({ dict }) => {
777
+ if (Object.keys(dict).length === 0) return "{}";
778
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
779
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
780
+ }).join(", ")} }`;
781
+ });
782
+ defineMethod("union", ["list"], ({ list }, inline) => {
783
+ const result = list.map(({ toString: format }) => format()).join(" | ");
784
+ return inline ? `(${result})` : result;
785
+ });
786
+ defineMethod("intersect", ["list"], ({ list }) => {
787
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
788
+ });
789
+ defineMethod("transform", [
790
+ "inner",
791
+ "callback",
792
+ "preserve"
793
+ ], ({ inner }, isInner) => inner.toString(isInner));
794
+
795
+ // dsh-done-sound/src/index.js
796
+ var name = "dsh-done-sound";
797
+ var inject = ["settings", "commands", "webServer"];
798
+ var MAX_BYTES = 2 * 1024 * 1024;
799
+ var AUDIO_MIMES = {
800
+ "audio/mpeg": "mp3",
801
+ "audio/mp3": "mp3",
802
+ "audio/wav": "wav",
803
+ "audio/wave": "wav",
804
+ "audio/x-wav": "wav",
805
+ "audio/ogg": "ogg",
806
+ "audio/oga": "ogg",
807
+ "audio/webm": "webm",
808
+ "audio/mp4": "m4a",
809
+ "audio/x-m4a": "m4a",
810
+ "audio/aac": "aac",
811
+ "audio/flac": "flac",
812
+ "audio/x-flac": "flac"
813
+ };
814
+ var TurnChimeSchema = Schema.object({
815
+ enabled: Schema.boolean().default(true),
816
+ volume: Schema.number().min(0).max(1).step(0.01).default(0.8),
817
+ playOnInterrupt: Schema.boolean().default(false),
818
+ playOnError: Schema.boolean().default(true),
819
+ audio: Schema.object({
820
+ fileId: Schema.string().default(""),
821
+ fileName: Schema.string().default(""),
822
+ mime: Schema.string().default(""),
823
+ size: Schema.number().default(0)
824
+ }).default({})
825
+ });
826
+ var NS = "dsh-done-sound";
827
+ var ROUTE_PREFIX = "/dsh-done-sound";
828
+ var FILE_ID_RE = /^[A-Za-z0-9-]+$/;
829
+ function apply(ctx) {
830
+ const profileDir = fileURLToPath(ctx.baseUrl);
831
+ const dataDir = join(profileDir, ".dsh-done-sound");
832
+ const scope = ctx.settings.register(NS, TurnChimeSchema, { base: {} });
833
+ const audioPath = (fileId) => join(dataDir, `${fileId}.bin`);
834
+ const statusPayload = () => {
835
+ const value = scope.get();
836
+ const fileId = value.audio?.fileId ?? "";
837
+ return {
838
+ ok: true,
839
+ enabled: value.enabled,
840
+ volume: value.volume,
841
+ playOnInterrupt: value.playOnInterrupt,
842
+ playOnError: value.playOnError,
843
+ audio: {
844
+ fileId,
845
+ fileName: value.audio?.fileName ?? "",
846
+ mime: value.audio?.mime ?? "",
847
+ size: value.audio?.size ?? 0
848
+ },
849
+ url: fileId ? `${ROUTE_PREFIX}/audio/${fileId}` : null
850
+ };
851
+ };
852
+ const clearAudio = async () => {
853
+ const value = scope.get();
854
+ const fileId = value.audio?.fileId;
855
+ if (fileId) {
856
+ try {
857
+ await unlink(audioPath(fileId));
858
+ } catch {
859
+ }
860
+ }
861
+ await scope.update({ audio: { fileId: "", fileName: "", mime: "", size: 0 } });
862
+ };
863
+ const setAudio = async (dataUrl, fileName) => {
864
+ const match = /^data:([^;,]+);base64,([A-Za-z0-9+/=]+)$/.exec(dataUrl);
865
+ if (!match) throw new Error("invalid audio data (need data:<mime>;base64,<data>)");
866
+ const mime = match[1].toLowerCase();
867
+ const ext = AUDIO_MIMES[mime];
868
+ if (!ext) throw new Error(`unsupported audio type: ${mime} (mp3/wav/ogg/webm/m4a/aac/flac only)`);
869
+ const buffer = Buffer.from(match[2], "base64");
870
+ if (buffer.length === 0) throw new Error("empty audio content");
871
+ if (buffer.length > MAX_BYTES) throw new Error(`audio exceeds 2MB (got ${buffer.length} bytes)`);
872
+ const fileId = randomUUID();
873
+ await mkdir(dataDir, { recursive: true });
874
+ await writeFile(audioPath(fileId), buffer);
875
+ const previous = scope.get().audio?.fileId;
876
+ await scope.update({
877
+ audio: { fileId, fileName: fileName || "chime", mime, size: buffer.length }
878
+ });
879
+ if (previous && previous !== fileId) {
880
+ try {
881
+ await unlink(audioPath(previous));
882
+ } catch {
883
+ }
884
+ }
885
+ return fileId;
886
+ };
887
+ ctx.commands.register({
888
+ name: "dsh-done-sound",
889
+ description: "\u5BF9\u8BDD\u5B8C\u6210\u97F3\u6548\uFF1A\u67E5\u8BE2/\u8BBE\u7F6E\u97F3\u9891\u4E0E\u89E6\u53D1\u5F00\u5173\uFF08status | set <dataUrl> <fileName> | clear | enabled <on|off> | volume <0-1> | interrupt <on|off> | error <on|off> | test\uFF09",
890
+ input: {
891
+ hint: "status | set <dataUrl> <fileName> | clear | enabled <on|off> | volume <0-1> | interrupt <on|off> | error <on|off> | test"
892
+ },
893
+ recordInput: false,
894
+ handler: async (invocation) => {
895
+ const raw = (invocation.rawInput ?? "").trim();
896
+ const [action, ...rest] = raw.split(/\s+/);
897
+ try {
898
+ switch (action) {
899
+ case "":
900
+ case "status":
901
+ return { kind: "success", text: JSON.stringify(statusPayload()) };
902
+ case "set": {
903
+ const dataUrl = rest[0] ?? "";
904
+ const fileName = rest.slice(1).join(" ") || "chime";
905
+ await setAudio(dataUrl, fileName);
906
+ return { kind: "success", text: JSON.stringify(statusPayload()) };
907
+ }
908
+ case "clear":
909
+ await clearAudio();
910
+ return { kind: "success", text: JSON.stringify(statusPayload()) };
911
+ case "enabled": {
912
+ const value = rest[0];
913
+ if (value !== "on" && value !== "off") return { kind: "error", text: "\u7528\u6CD5\uFF1Aenabled <on|off>" };
914
+ await scope.update({ enabled: value === "on" });
915
+ return { kind: "success", text: JSON.stringify(statusPayload()) };
916
+ }
917
+ case "volume": {
918
+ const n = Number(rest[0]);
919
+ if (!Number.isFinite(n) || n < 0 || n > 1) return { kind: "error", text: "\u7528\u6CD5\uFF1Avolume <0-1>" };
920
+ await scope.update({ volume: n });
921
+ return { kind: "success", text: JSON.stringify(statusPayload()) };
922
+ }
923
+ case "interrupt": {
924
+ const value = rest[0];
925
+ if (value !== "on" && value !== "off") return { kind: "error", text: "\u7528\u6CD5\uFF1Ainterrupt <on|off>" };
926
+ await scope.update({ playOnInterrupt: value === "on" });
927
+ return { kind: "success", text: JSON.stringify(statusPayload()) };
928
+ }
929
+ case "error": {
930
+ const value = rest[0];
931
+ if (value !== "on" && value !== "off") return { kind: "error", text: "\u7528\u6CD5\uFF1Aerror <on|off>" };
932
+ await scope.update({ playOnError: value === "on" });
933
+ return { kind: "success", text: JSON.stringify(statusPayload()) };
934
+ }
935
+ case "test":
936
+ return { kind: "success", text: JSON.stringify({ ...statusPayload(), ok: true }) };
937
+ default:
938
+ return { kind: "error", text: `\u672A\u77E5\u64CD\u4F5C\uFF1A${action}` };
939
+ }
940
+ } catch (error) {
941
+ return { kind: "error", text: error instanceof Error ? error.message : String(error) };
942
+ }
943
+ }
944
+ });
945
+ const sendJson = (res, code, payload) => {
946
+ const body = JSON.stringify(payload);
947
+ res.writeHead(code, {
948
+ "Content-Type": "application/json; charset=utf-8",
949
+ "Cache-Control": "no-cache",
950
+ "X-Content-Type-Options": "nosniff"
951
+ });
952
+ res.end(body);
953
+ };
954
+ const readJsonBody = (req) => new Promise((resolve2, reject) => {
955
+ const chunks = [];
956
+ req.on("data", (chunk) => chunks.push(chunk));
957
+ req.on("end", () => {
958
+ try {
959
+ const raw = Buffer.concat(chunks).toString("utf8");
960
+ resolve2(raw.trim() ? JSON.parse(raw) : {});
961
+ } catch {
962
+ reject(new Error("invalid JSON body"));
963
+ }
964
+ });
965
+ req.on("error", reject);
966
+ });
967
+ const handler = async (req, res) => {
968
+ let pathname = "/";
969
+ try {
970
+ pathname = new URL(req.url ?? "/", "http://localhost").pathname;
971
+ } catch {
972
+ pathname = "/";
973
+ }
974
+ const method = (req.method ?? "GET").toUpperCase();
975
+ const audioMatch = /^\/dsh-done-sound\/audio\/([A-Za-z0-9-]+)$/.exec(pathname);
976
+ if (audioMatch) {
977
+ const fileId = audioMatch[1];
978
+ const audio = scope.get().audio;
979
+ if (!FILE_ID_RE.test(fileId) || !audio || audio.fileId !== fileId) {
980
+ res.writeHead(404);
981
+ res.end("not found");
982
+ return;
983
+ }
984
+ try {
985
+ const buffer = await readFile(audioPath(fileId));
986
+ res.writeHead(200, {
987
+ "Content-Type": audio.mime || "application/octet-stream",
988
+ "Content-Length": buffer.length,
989
+ "Cache-Control": "no-cache",
990
+ "X-Content-Type-Options": "nosniff"
991
+ });
992
+ res.end(buffer);
993
+ } catch {
994
+ res.writeHead(404);
995
+ res.end("not found");
996
+ }
997
+ return;
998
+ }
999
+ try {
1000
+ if (pathname === "/dsh-done-sound/api/status" && method === "GET") {
1001
+ sendJson(res, 200, statusPayload());
1002
+ return;
1003
+ }
1004
+ if (pathname === "/dsh-done-sound/api/config" && method === "POST") {
1005
+ const body = await readJsonBody(req);
1006
+ const patch = {};
1007
+ if (typeof body.enabled === "boolean") patch.enabled = body.enabled;
1008
+ if (typeof body.volume === "number" && body.volume >= 0 && body.volume <= 1) patch.volume = body.volume;
1009
+ if (typeof body.playOnInterrupt === "boolean") patch.playOnInterrupt = body.playOnInterrupt;
1010
+ if (typeof body.playOnError === "boolean") patch.playOnError = body.playOnError;
1011
+ if (Object.keys(patch).length > 0) await scope.update(patch);
1012
+ sendJson(res, 200, statusPayload());
1013
+ return;
1014
+ }
1015
+ if (pathname === "/dsh-done-sound/api/audio" && method === "POST") {
1016
+ const body = await readJsonBody(req);
1017
+ await setAudio(typeof body.dataUrl === "string" ? body.dataUrl : "", typeof body.fileName === "string" ? body.fileName : "");
1018
+ sendJson(res, 200, statusPayload());
1019
+ return;
1020
+ }
1021
+ if (pathname === "/dsh-done-sound/api/clear" && method === "POST") {
1022
+ await clearAudio();
1023
+ sendJson(res, 200, statusPayload());
1024
+ return;
1025
+ }
1026
+ } catch (error) {
1027
+ sendJson(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) });
1028
+ return;
1029
+ }
1030
+ res.writeHead(404);
1031
+ res.end("not found");
1032
+ };
1033
+ ctx.inject(["webServer"], (webCtx) => {
1034
+ const disposeRoute = webCtx.webServer.register({
1035
+ kind: "prefix",
1036
+ path: ROUTE_PREFIX,
1037
+ handler
1038
+ });
1039
+ webCtx.effect(() => disposeRoute);
1040
+ });
1041
+ }
1042
+ export {
1043
+ apply,
1044
+ inject,
1045
+ name
1046
+ };