@danielng23/dsh-client-ui-theme-store 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/README.md +161 -0
- package/catalog/edex-themes.json +634 -0
- package/lib/client.js +1591 -0
- package/lib/index.js +1093 -0
- package/lib/invariant.js +19 -0
- package/lib/types/client/ThemeStoreSection.d.ts +60 -0
- package/lib/types/client/catalog.d.ts +84 -0
- package/lib/types/client/index.d.ts +40 -0
- package/lib/types/client/locales.d.ts +60 -0
- package/lib/types/client/settings-store.d.ts +35 -0
- package/lib/types/client/theme-store.d.ts +95 -0
- package/lib/types/host/installer.d.ts +82 -0
- package/lib/types/index.d.ts +16 -0
- package/lib/types/invariant.d.ts +16 -0
- package/lib/types/theme-store-settings.d.ts +14 -0
- package/package.json +104 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1093 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { appendFileSync, existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { settingsNamespace } from "@deepseek-ai/dsh-settings";
|
|
7
|
+
import * as yaml from "js-yaml";
|
|
8
|
+
//#region node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.2/node_modules/@deepseek-ai/cosmokit/lib/index.js
|
|
9
|
+
/** Return true when a value is `null` or `undefined`. */
|
|
10
|
+
function isNullable(value) {
|
|
11
|
+
return value === null || value === void 0;
|
|
12
|
+
}
|
|
13
|
+
/** Return true for non-array object values. */
|
|
14
|
+
function isPlainObject(data) {
|
|
15
|
+
return data && typeof data === "object" && !Array.isArray(data);
|
|
16
|
+
}
|
|
17
|
+
/** Filter object entries and return a new object. */
|
|
18
|
+
function filterKeys(object, filter) {
|
|
19
|
+
return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
|
|
20
|
+
}
|
|
21
|
+
/** Map object values while preserving the original key set. */
|
|
22
|
+
function mapValues(object, transform) {
|
|
23
|
+
return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
|
|
24
|
+
}
|
|
25
|
+
/** Pick selected keys from an object, optionally including `undefined` values. */
|
|
26
|
+
function pick(source, keys, forced) {
|
|
27
|
+
if (!keys) return { ...source };
|
|
28
|
+
const result = {};
|
|
29
|
+
for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
/** Test values using `instanceof` with a `toStringTag` fallback. */
|
|
33
|
+
function is(type, value) {
|
|
34
|
+
if (arguments.length === 1) return (value) => is(type, value);
|
|
35
|
+
return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
|
|
36
|
+
}
|
|
37
|
+
function isArrayBufferLike(value) {
|
|
38
|
+
return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
|
|
39
|
+
}
|
|
40
|
+
function isArrayBufferSource(value) {
|
|
41
|
+
return isArrayBufferLike(value) || ArrayBuffer.isView(value);
|
|
42
|
+
}
|
|
43
|
+
/** Binary source detection and base64/hex conversion helpers. */
|
|
44
|
+
var Binary;
|
|
45
|
+
(function(Binary) {
|
|
46
|
+
Binary.is = isArrayBufferLike;
|
|
47
|
+
Binary.isSource = isArrayBufferSource;
|
|
48
|
+
function fromSource(source) {
|
|
49
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
50
|
+
else return source;
|
|
51
|
+
}
|
|
52
|
+
Binary.fromSource = fromSource;
|
|
53
|
+
function toBase64(source) {
|
|
54
|
+
source = fromSource(source);
|
|
55
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
|
|
56
|
+
let binary = "";
|
|
57
|
+
const bytes = new Uint8Array(source);
|
|
58
|
+
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
|
|
59
|
+
return btoa(binary);
|
|
60
|
+
}
|
|
61
|
+
Binary.toBase64 = toBase64;
|
|
62
|
+
function fromBase64(source) {
|
|
63
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
|
|
64
|
+
return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
|
|
65
|
+
}
|
|
66
|
+
Binary.fromBase64 = fromBase64;
|
|
67
|
+
function toHex(source) {
|
|
68
|
+
source = fromSource(source);
|
|
69
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
|
|
70
|
+
return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
71
|
+
}
|
|
72
|
+
Binary.toHex = toHex;
|
|
73
|
+
function fromHex(source) {
|
|
74
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
|
|
75
|
+
const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
|
|
76
|
+
const buffer = [];
|
|
77
|
+
for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
|
|
78
|
+
return Uint8Array.from(buffer).buffer;
|
|
79
|
+
}
|
|
80
|
+
Binary.fromHex = fromHex;
|
|
81
|
+
})(Binary || (Binary = {}));
|
|
82
|
+
Binary.fromBase64;
|
|
83
|
+
Binary.toBase64;
|
|
84
|
+
Binary.fromHex;
|
|
85
|
+
Binary.toHex;
|
|
86
|
+
/** Deep-clone common JavaScript values while preserving prototypes and cycles. */
|
|
87
|
+
function clone(source, refs = /* @__PURE__ */ new Map()) {
|
|
88
|
+
if (!source || typeof source !== "object") return source;
|
|
89
|
+
if (is("Date", source)) return new Date(source.valueOf());
|
|
90
|
+
if (is("RegExp", source)) return new RegExp(source.source, source.flags);
|
|
91
|
+
if (isArrayBufferLike(source)) return source.slice(0);
|
|
92
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
93
|
+
const cached = refs.get(source);
|
|
94
|
+
if (cached) return cached;
|
|
95
|
+
if (Array.isArray(source)) {
|
|
96
|
+
const result = [];
|
|
97
|
+
refs.set(source, result);
|
|
98
|
+
source.forEach((value, index) => {
|
|
99
|
+
result[index] = Reflect.apply(clone, null, [value, refs]);
|
|
100
|
+
});
|
|
101
|
+
return result;
|
|
102
|
+
}
|
|
103
|
+
const result = Object.create(Object.getPrototypeOf(source));
|
|
104
|
+
refs.set(source, result);
|
|
105
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
106
|
+
const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
|
|
107
|
+
if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
|
|
108
|
+
Reflect.defineProperty(result, key, descriptor);
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
|
|
113
|
+
function deepEqual(a, b, strict) {
|
|
114
|
+
if (a === b) return true;
|
|
115
|
+
if (!strict && isNullable(a) && isNullable(b)) return true;
|
|
116
|
+
if (typeof a !== typeof b) return false;
|
|
117
|
+
if (typeof a !== "object") return false;
|
|
118
|
+
if (!a || !b) return false;
|
|
119
|
+
function check(test, then) {
|
|
120
|
+
return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
|
|
121
|
+
}
|
|
122
|
+
return check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index]))) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
|
|
123
|
+
if (a.byteLength !== b.byteLength) return false;
|
|
124
|
+
const viewA = new Uint8Array(a);
|
|
125
|
+
const viewB = new Uint8Array(b);
|
|
126
|
+
for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
|
|
127
|
+
return true;
|
|
128
|
+
}) ?? Object.keys({
|
|
129
|
+
...a,
|
|
130
|
+
...b
|
|
131
|
+
}).every((key) => deepEqual(a[key], b[key], strict));
|
|
132
|
+
}
|
|
133
|
+
/** Time constants plus parsing and formatting helpers. */
|
|
134
|
+
var Time;
|
|
135
|
+
(function(Time) {
|
|
136
|
+
Time.millisecond = 1;
|
|
137
|
+
Time.second = 1e3;
|
|
138
|
+
Time.minute = Time.second * 60;
|
|
139
|
+
Time.hour = Time.minute * 60;
|
|
140
|
+
Time.day = Time.hour * 24;
|
|
141
|
+
Time.week = Time.day * 7;
|
|
142
|
+
let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
|
|
143
|
+
function setTimezoneOffset(offset) {
|
|
144
|
+
timezoneOffset = offset;
|
|
145
|
+
}
|
|
146
|
+
Time.setTimezoneOffset = setTimezoneOffset;
|
|
147
|
+
function getTimezoneOffset() {
|
|
148
|
+
return timezoneOffset;
|
|
149
|
+
}
|
|
150
|
+
Time.getTimezoneOffset = getTimezoneOffset;
|
|
151
|
+
function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
|
|
152
|
+
if (typeof date === "number") date = new Date(date);
|
|
153
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
154
|
+
return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
|
|
155
|
+
}
|
|
156
|
+
Time.getDateNumber = getDateNumber;
|
|
157
|
+
function fromDateNumber(value, offset) {
|
|
158
|
+
const date = new Date(value * Time.day);
|
|
159
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
160
|
+
return new Date(+date + offset * Time.minute);
|
|
161
|
+
}
|
|
162
|
+
Time.fromDateNumber = fromDateNumber;
|
|
163
|
+
const numeric = /\d+(?:\.\d+)?/.source;
|
|
164
|
+
const timeRegExp = new RegExp(`^${[
|
|
165
|
+
"w(?:eek(?:s)?)?",
|
|
166
|
+
"d(?:ay(?:s)?)?",
|
|
167
|
+
"h(?:our(?:s)?)?",
|
|
168
|
+
"m(?:in(?:ute)?(?:s)?)?",
|
|
169
|
+
"s(?:ec(?:ond)?(?:s)?)?"
|
|
170
|
+
].map((unit) => `(${numeric}${unit})?`).join("")}$`);
|
|
171
|
+
function parseTime(source) {
|
|
172
|
+
const capture = timeRegExp.exec(source);
|
|
173
|
+
if (!capture) return 0;
|
|
174
|
+
return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
|
|
175
|
+
}
|
|
176
|
+
Time.parseTime = parseTime;
|
|
177
|
+
function parseDate(date) {
|
|
178
|
+
const parsed = parseTime(date);
|
|
179
|
+
if (parsed) date = Date.now() + parsed;
|
|
180
|
+
else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
|
|
181
|
+
else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
|
|
182
|
+
return date ? new Date(date) : /* @__PURE__ */ new Date();
|
|
183
|
+
}
|
|
184
|
+
Time.parseDate = parseDate;
|
|
185
|
+
function format(ms) {
|
|
186
|
+
const abs = Math.abs(ms);
|
|
187
|
+
if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
|
|
188
|
+
else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
|
|
189
|
+
else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
|
|
190
|
+
else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
|
|
191
|
+
return ms + "ms";
|
|
192
|
+
}
|
|
193
|
+
Time.format = format;
|
|
194
|
+
function toDigits(source, length = 2) {
|
|
195
|
+
return source.toString().padStart(length, "0");
|
|
196
|
+
}
|
|
197
|
+
Time.toDigits = toDigits;
|
|
198
|
+
function template(template, time = /* @__PURE__ */ new Date()) {
|
|
199
|
+
return template.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));
|
|
200
|
+
}
|
|
201
|
+
Time.template = template;
|
|
202
|
+
})(Time || (Time = {}));
|
|
203
|
+
//#endregion
|
|
204
|
+
//#region node_modules/.pnpm/@deepseek-ai+schemastery@3.18.1/node_modules/@deepseek-ai/schemastery/lib/index.mjs
|
|
205
|
+
const kSchema = Symbol.for("schemastery");
|
|
206
|
+
const kValidationError = Symbol.for("ValidationError");
|
|
207
|
+
globalThis.__schemastery_index__ ??= 0;
|
|
208
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
209
|
+
var ValidationError = class extends TypeError {
|
|
210
|
+
options;
|
|
211
|
+
name = "ValidationError";
|
|
212
|
+
constructor(message, options) {
|
|
213
|
+
let prefix = "$";
|
|
214
|
+
for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
|
|
215
|
+
else if (typeof segment === "number") prefix += "[" + segment + "]";
|
|
216
|
+
else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
|
|
217
|
+
if (prefix.startsWith(".")) prefix = prefix.slice(1);
|
|
218
|
+
super((prefix === "$" ? "" : `${prefix} `) + message);
|
|
219
|
+
this.options = options;
|
|
220
|
+
}
|
|
221
|
+
static is(error) {
|
|
222
|
+
return !!error?.[kValidationError];
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
|
|
226
|
+
const Schema = function(options) {
|
|
227
|
+
const schema = function(data, options = {}) {
|
|
228
|
+
return Schema.resolve(data, schema, options)[0];
|
|
229
|
+
};
|
|
230
|
+
if (options.refs) {
|
|
231
|
+
const refs = mapValues(options.refs, (options) => new Schema(options));
|
|
232
|
+
const getRef = (uid) => refs[uid];
|
|
233
|
+
for (const key in refs) {
|
|
234
|
+
const options = refs[key];
|
|
235
|
+
options.sKey = getRef(options.sKey);
|
|
236
|
+
options.inner = getRef(options.inner);
|
|
237
|
+
options.list = options.list && options.list.map(getRef);
|
|
238
|
+
options.dict = options.dict && mapValues(options.dict, getRef);
|
|
239
|
+
}
|
|
240
|
+
return refs[options.uid];
|
|
241
|
+
}
|
|
242
|
+
Object.assign(schema, options);
|
|
243
|
+
if (typeof schema.callback === "string") try {
|
|
244
|
+
schema.callback = new Function("return " + schema.callback)();
|
|
245
|
+
} catch {}
|
|
246
|
+
Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
|
|
247
|
+
Object.setPrototypeOf(schema, Schema.prototype);
|
|
248
|
+
schema.meta ||= {};
|
|
249
|
+
schema.toString = schema.toString.bind(schema);
|
|
250
|
+
return schema;
|
|
251
|
+
};
|
|
252
|
+
Schema.prototype = Object.create(Function.prototype);
|
|
253
|
+
Schema.prototype[kSchema] = true;
|
|
254
|
+
Object.defineProperty(Schema.prototype, "~standard", { get() {
|
|
255
|
+
return {
|
|
256
|
+
version: 1,
|
|
257
|
+
vendor: "schemastery",
|
|
258
|
+
validate: (value) => {
|
|
259
|
+
try {
|
|
260
|
+
return { value: Schema.resolve(value, this, {})[0] };
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (ValidationError.is(error)) return { issues: [{
|
|
263
|
+
message: error.message,
|
|
264
|
+
path: error.options.path
|
|
265
|
+
}] };
|
|
266
|
+
throw error;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
} });
|
|
271
|
+
Schema.ValidationError = ValidationError;
|
|
272
|
+
Schema.prototype.toJSON = function toJSON() {
|
|
273
|
+
if (globalThis.__schemastery_refs__) {
|
|
274
|
+
globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
275
|
+
return this.uid;
|
|
276
|
+
}
|
|
277
|
+
globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
278
|
+
globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
279
|
+
const result = {
|
|
280
|
+
uid: this.uid,
|
|
281
|
+
refs: globalThis.__schemastery_refs__
|
|
282
|
+
};
|
|
283
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
284
|
+
return result;
|
|
285
|
+
};
|
|
286
|
+
Schema.prototype.set = function set(key, value) {
|
|
287
|
+
this.dict[key] = value;
|
|
288
|
+
return this;
|
|
289
|
+
};
|
|
290
|
+
Schema.prototype.push = function push(value) {
|
|
291
|
+
this.list.push(value);
|
|
292
|
+
return this;
|
|
293
|
+
};
|
|
294
|
+
function mergeDesc(original, messages) {
|
|
295
|
+
const result = typeof original === "string" ? { "": original } : { ...original };
|
|
296
|
+
for (const locale in messages) {
|
|
297
|
+
const value = messages[locale];
|
|
298
|
+
if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
|
|
299
|
+
else if (typeof value === "string") result[locale] = value;
|
|
300
|
+
}
|
|
301
|
+
return result;
|
|
302
|
+
}
|
|
303
|
+
function getInner(value) {
|
|
304
|
+
return value?.$value ?? value?.$inner;
|
|
305
|
+
}
|
|
306
|
+
function extractKeys(data) {
|
|
307
|
+
return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
|
|
308
|
+
}
|
|
309
|
+
Schema.prototype.i18n = function i18n(messages) {
|
|
310
|
+
const schema = Schema(this);
|
|
311
|
+
const desc = mergeDesc(schema.meta.description, messages);
|
|
312
|
+
if (Object.keys(desc).length) schema.meta.description = desc;
|
|
313
|
+
if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
|
|
314
|
+
return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
|
|
315
|
+
});
|
|
316
|
+
if (schema.list) schema.list = schema.list.map((inner, index) => {
|
|
317
|
+
return inner.i18n(mapValues(messages, (data = {}) => {
|
|
318
|
+
if (Array.isArray(getInner(data))) return getInner(data)[index];
|
|
319
|
+
if (Array.isArray(data)) return data[index];
|
|
320
|
+
return extractKeys(data);
|
|
321
|
+
}));
|
|
322
|
+
});
|
|
323
|
+
if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
|
|
324
|
+
if (getInner(data)) return getInner(data);
|
|
325
|
+
return extractKeys(data);
|
|
326
|
+
}));
|
|
327
|
+
if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
|
|
328
|
+
return schema;
|
|
329
|
+
};
|
|
330
|
+
Schema.prototype.extra = function extra(key, value) {
|
|
331
|
+
const schema = Schema(this);
|
|
332
|
+
schema.meta = {
|
|
333
|
+
...schema.meta,
|
|
334
|
+
[key]: value
|
|
335
|
+
};
|
|
336
|
+
return schema;
|
|
337
|
+
};
|
|
338
|
+
for (const key of [
|
|
339
|
+
"required",
|
|
340
|
+
"disabled",
|
|
341
|
+
"collapse",
|
|
342
|
+
"hidden",
|
|
343
|
+
"loose"
|
|
344
|
+
]) Object.assign(Schema.prototype, { [key](value = true) {
|
|
345
|
+
const schema = Schema(this);
|
|
346
|
+
schema.meta = {
|
|
347
|
+
...schema.meta,
|
|
348
|
+
[key]: value
|
|
349
|
+
};
|
|
350
|
+
return schema;
|
|
351
|
+
} });
|
|
352
|
+
Schema.prototype.deprecated = function deprecated() {
|
|
353
|
+
const schema = Schema(this);
|
|
354
|
+
schema.meta.badges ||= [];
|
|
355
|
+
schema.meta.badges.push({
|
|
356
|
+
text: "deprecated",
|
|
357
|
+
type: "danger"
|
|
358
|
+
});
|
|
359
|
+
return schema;
|
|
360
|
+
};
|
|
361
|
+
Schema.prototype.experimental = function experimental() {
|
|
362
|
+
const schema = Schema(this);
|
|
363
|
+
schema.meta.badges ||= [];
|
|
364
|
+
schema.meta.badges.push({
|
|
365
|
+
text: "experimental",
|
|
366
|
+
type: "warning"
|
|
367
|
+
});
|
|
368
|
+
return schema;
|
|
369
|
+
};
|
|
370
|
+
Schema.prototype.pattern = function pattern(regexp) {
|
|
371
|
+
const schema = Schema(this);
|
|
372
|
+
const pattern = pick(regexp, ["source", "flags"]);
|
|
373
|
+
schema.meta = {
|
|
374
|
+
...schema.meta,
|
|
375
|
+
pattern
|
|
376
|
+
};
|
|
377
|
+
return schema;
|
|
378
|
+
};
|
|
379
|
+
Schema.prototype.simplify = function simplify(value) {
|
|
380
|
+
if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
|
|
381
|
+
if (isNullable(value)) return value;
|
|
382
|
+
if (this.type === "object" || this.type === "dict") {
|
|
383
|
+
const result = {};
|
|
384
|
+
for (const key in value) {
|
|
385
|
+
const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
|
|
386
|
+
if (this.type === "dict" || !isNullable(item)) result[key] = item;
|
|
387
|
+
}
|
|
388
|
+
if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
|
|
389
|
+
return result;
|
|
390
|
+
} else if (this.type === "array" || this.type === "tuple") {
|
|
391
|
+
const result = [];
|
|
392
|
+
value.forEach((value, index) => {
|
|
393
|
+
const schema = this.type === "array" ? this.inner : this.list[index];
|
|
394
|
+
const item = schema ? schema.simplify(value) : value;
|
|
395
|
+
result.push(item);
|
|
396
|
+
});
|
|
397
|
+
return result;
|
|
398
|
+
} else if (this.type === "intersect") {
|
|
399
|
+
const result = {};
|
|
400
|
+
for (const item of this.list) Object.assign(result, item.simplify(value));
|
|
401
|
+
return result;
|
|
402
|
+
} else if (this.type === "union") for (const schema of this.list) try {
|
|
403
|
+
Schema.resolve(value, schema, {});
|
|
404
|
+
return schema.simplify(value);
|
|
405
|
+
} catch {}
|
|
406
|
+
return value;
|
|
407
|
+
};
|
|
408
|
+
Schema.prototype.toString = function toString(inline) {
|
|
409
|
+
return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
|
|
410
|
+
};
|
|
411
|
+
Schema.prototype.role = function role(role, extra) {
|
|
412
|
+
const schema = Schema(this);
|
|
413
|
+
schema.meta = {
|
|
414
|
+
...schema.meta,
|
|
415
|
+
role,
|
|
416
|
+
extra
|
|
417
|
+
};
|
|
418
|
+
return schema;
|
|
419
|
+
};
|
|
420
|
+
for (const key of [
|
|
421
|
+
"default",
|
|
422
|
+
"link",
|
|
423
|
+
"comment",
|
|
424
|
+
"description",
|
|
425
|
+
"max",
|
|
426
|
+
"min",
|
|
427
|
+
"step"
|
|
428
|
+
]) Object.assign(Schema.prototype, { [key](value) {
|
|
429
|
+
const schema = Schema(this);
|
|
430
|
+
schema.meta = {
|
|
431
|
+
...schema.meta,
|
|
432
|
+
[key]: value
|
|
433
|
+
};
|
|
434
|
+
return schema;
|
|
435
|
+
} });
|
|
436
|
+
const resolvers = {};
|
|
437
|
+
Schema.extend = function extend(type, resolve) {
|
|
438
|
+
resolvers[type] = resolve;
|
|
439
|
+
};
|
|
440
|
+
Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
|
|
441
|
+
if (!schema) return [data];
|
|
442
|
+
if (options.ignore?.(data, schema)) return [data];
|
|
443
|
+
if (isNullable(data) && schema.type !== "lazy") {
|
|
444
|
+
if (schema.meta.required) throw new ValidationError(`missing required value`, options);
|
|
445
|
+
let current = schema;
|
|
446
|
+
let fallback = schema.meta.default;
|
|
447
|
+
while (current?.type === "intersect" && isNullable(fallback)) {
|
|
448
|
+
current = current.list[0];
|
|
449
|
+
fallback = current?.meta.default;
|
|
450
|
+
}
|
|
451
|
+
if (isNullable(fallback)) return [data];
|
|
452
|
+
data = clone(fallback);
|
|
453
|
+
}
|
|
454
|
+
const callback = resolvers[schema.type];
|
|
455
|
+
if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
|
|
456
|
+
try {
|
|
457
|
+
return callback(data, schema, options, strict);
|
|
458
|
+
} catch (error) {
|
|
459
|
+
if (!schema.meta.loose) throw error;
|
|
460
|
+
return [schema.meta.default];
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
Schema.from = function from(source) {
|
|
464
|
+
if (isNullable(source)) return Schema.any();
|
|
465
|
+
else if ([
|
|
466
|
+
"string",
|
|
467
|
+
"number",
|
|
468
|
+
"boolean"
|
|
469
|
+
].includes(typeof source)) return Schema.const(source).required();
|
|
470
|
+
else if (source[kSchema]) return source;
|
|
471
|
+
else if (typeof source === "function") switch (source) {
|
|
472
|
+
case String: return Schema.string().required();
|
|
473
|
+
case Number: return Schema.number().required();
|
|
474
|
+
case Boolean: return Schema.boolean().required();
|
|
475
|
+
case Function: return Schema.function().required();
|
|
476
|
+
default: return Schema.is(source).required();
|
|
477
|
+
}
|
|
478
|
+
else throw new TypeError(`cannot infer schema from ${source}`);
|
|
479
|
+
};
|
|
480
|
+
Schema.lazy = function lazy(builder) {
|
|
481
|
+
const toJSON = () => {
|
|
482
|
+
if (!schema.inner[kSchema]) {
|
|
483
|
+
schema.inner = schema.builder();
|
|
484
|
+
schema.inner.meta = {
|
|
485
|
+
...schema.meta,
|
|
486
|
+
...schema.inner.meta
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
return schema.inner.toJSON();
|
|
490
|
+
};
|
|
491
|
+
const schema = new Schema({
|
|
492
|
+
type: "lazy",
|
|
493
|
+
builder,
|
|
494
|
+
inner: { toJSON }
|
|
495
|
+
});
|
|
496
|
+
return schema;
|
|
497
|
+
};
|
|
498
|
+
Schema.natural = function natural() {
|
|
499
|
+
return Schema.number().step(1).min(0);
|
|
500
|
+
};
|
|
501
|
+
Schema.percent = function percent() {
|
|
502
|
+
return Schema.number().step(.01).min(0).max(1).role("slider");
|
|
503
|
+
};
|
|
504
|
+
Schema.date = function date() {
|
|
505
|
+
return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
|
|
506
|
+
const date = new Date(value);
|
|
507
|
+
if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
|
|
508
|
+
return date;
|
|
509
|
+
}, true)]);
|
|
510
|
+
};
|
|
511
|
+
Schema.regExp = function regExp(flag = "") {
|
|
512
|
+
return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
|
|
513
|
+
try {
|
|
514
|
+
return new RegExp(value, flag);
|
|
515
|
+
} catch (e) {
|
|
516
|
+
throw new ValidationError(e.message, options);
|
|
517
|
+
}
|
|
518
|
+
}, true)]);
|
|
519
|
+
};
|
|
520
|
+
Schema.arrayBuffer = function arrayBuffer(encoding) {
|
|
521
|
+
return Schema.union([
|
|
522
|
+
Schema.is(ArrayBuffer),
|
|
523
|
+
Schema.is(SharedArrayBuffer),
|
|
524
|
+
Schema.transform(Schema.any(), (value, options) => {
|
|
525
|
+
if (Binary.isSource(value)) return Binary.fromSource(value);
|
|
526
|
+
throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
|
|
527
|
+
}, true),
|
|
528
|
+
...encoding ? [Schema.transform(Schema.string(), (value, options) => {
|
|
529
|
+
try {
|
|
530
|
+
return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
|
|
531
|
+
} catch (e) {
|
|
532
|
+
throw new ValidationError(e.message, options);
|
|
533
|
+
}
|
|
534
|
+
}, true)] : []
|
|
535
|
+
]);
|
|
536
|
+
};
|
|
537
|
+
Schema.extend("lazy", (data, schema, options, strict) => {
|
|
538
|
+
if (!schema.inner[kSchema]) {
|
|
539
|
+
schema.inner = schema.builder();
|
|
540
|
+
schema.inner.meta = {
|
|
541
|
+
...schema.meta,
|
|
542
|
+
...schema.inner.meta
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
return Schema.resolve(data, schema.inner, options, strict);
|
|
546
|
+
});
|
|
547
|
+
Schema.extend("any", (data) => {
|
|
548
|
+
return [data];
|
|
549
|
+
});
|
|
550
|
+
Schema.extend("never", (data, _, options) => {
|
|
551
|
+
throw new ValidationError(`expected nullable but got ${data}`, options);
|
|
552
|
+
});
|
|
553
|
+
Schema.extend("const", (data, { value }, options) => {
|
|
554
|
+
if (deepEqual(data, value)) return [value];
|
|
555
|
+
throw new ValidationError(`expected ${value} but got ${data}`, options);
|
|
556
|
+
});
|
|
557
|
+
function checkWithinRange(data, meta, description, options, skipMin = false) {
|
|
558
|
+
const { max = Infinity, min = -Infinity } = meta;
|
|
559
|
+
if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
|
|
560
|
+
if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
|
|
561
|
+
}
|
|
562
|
+
Schema.extend("string", (data, { meta }, options) => {
|
|
563
|
+
if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
|
|
564
|
+
if (meta.pattern) {
|
|
565
|
+
const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
|
|
566
|
+
if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
|
|
567
|
+
}
|
|
568
|
+
checkWithinRange(data.length, meta, "string length", options);
|
|
569
|
+
return [data];
|
|
570
|
+
});
|
|
571
|
+
function decimalShift(data, digits) {
|
|
572
|
+
const str = data.toString();
|
|
573
|
+
if (str.includes("e")) return data * Math.pow(10, digits);
|
|
574
|
+
const index = str.indexOf(".");
|
|
575
|
+
if (index === -1) return data * Math.pow(10, digits);
|
|
576
|
+
const frac = str.slice(index + 1);
|
|
577
|
+
const integer = str.slice(0, index);
|
|
578
|
+
if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
|
|
579
|
+
return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
|
|
580
|
+
}
|
|
581
|
+
function isMultipleOf(data, min, step) {
|
|
582
|
+
step = Math.abs(step);
|
|
583
|
+
if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
|
|
584
|
+
const index = step.toString().indexOf(".");
|
|
585
|
+
const digits = step.toString().slice(index + 1).length;
|
|
586
|
+
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
|
|
587
|
+
}
|
|
588
|
+
Schema.extend("number", (data, { meta }, options) => {
|
|
589
|
+
if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
|
|
590
|
+
checkWithinRange(data, meta, "number", options);
|
|
591
|
+
const { step } = meta;
|
|
592
|
+
if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
|
|
593
|
+
return [data];
|
|
594
|
+
});
|
|
595
|
+
Schema.extend("boolean", (data, _, options) => {
|
|
596
|
+
if (typeof data === "boolean") return [data];
|
|
597
|
+
throw new ValidationError(`expected boolean but got ${data}`, options);
|
|
598
|
+
});
|
|
599
|
+
Schema.extend("bitset", (data, { bits, meta }, options) => {
|
|
600
|
+
let value = 0, keys = [];
|
|
601
|
+
if (typeof data === "number") {
|
|
602
|
+
value = data;
|
|
603
|
+
for (const key in bits) if (data & bits[key]) keys.push(key);
|
|
604
|
+
} else if (Array.isArray(data)) {
|
|
605
|
+
keys = data;
|
|
606
|
+
for (const key of keys) {
|
|
607
|
+
if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
|
|
608
|
+
if (key in bits) value |= bits[key];
|
|
609
|
+
}
|
|
610
|
+
} else throw new ValidationError(`expected number or array but got ${data}`, options);
|
|
611
|
+
if (value === meta.default) return [value];
|
|
612
|
+
return [value, keys];
|
|
613
|
+
});
|
|
614
|
+
Schema.extend("function", (data, _, options) => {
|
|
615
|
+
if (typeof data === "function") return [data];
|
|
616
|
+
throw new ValidationError(`expected function but got ${data}`, options);
|
|
617
|
+
});
|
|
618
|
+
Schema.extend("is", (data, { constructor }, options) => {
|
|
619
|
+
if (typeof constructor === "function") {
|
|
620
|
+
if (data instanceof constructor) return [data];
|
|
621
|
+
throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
|
|
622
|
+
} else {
|
|
623
|
+
if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
624
|
+
let prototype = Object.getPrototypeOf(data);
|
|
625
|
+
while (prototype) {
|
|
626
|
+
if (prototype.constructor?.name === constructor) return [data];
|
|
627
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
628
|
+
}
|
|
629
|
+
throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
630
|
+
}
|
|
631
|
+
});
|
|
632
|
+
function property(data, key, schema, options) {
|
|
633
|
+
try {
|
|
634
|
+
const [value, adapted] = Schema.resolve(data[key], schema, {
|
|
635
|
+
...options,
|
|
636
|
+
path: [...options.path || [], key]
|
|
637
|
+
});
|
|
638
|
+
if (adapted !== void 0) data[key] = adapted;
|
|
639
|
+
return value;
|
|
640
|
+
} catch (e) {
|
|
641
|
+
if (!options?.autofix) throw e;
|
|
642
|
+
delete data[key];
|
|
643
|
+
return schema.meta.default;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
Schema.extend("array", (data, { inner, meta }, options) => {
|
|
647
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
648
|
+
checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
|
|
649
|
+
return [data.map((_, index) => property(data, index, inner, options))];
|
|
650
|
+
});
|
|
651
|
+
Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
|
|
652
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
653
|
+
const result = {};
|
|
654
|
+
for (const key in data) {
|
|
655
|
+
let rKey;
|
|
656
|
+
try {
|
|
657
|
+
rKey = Schema.resolve(key, sKey, options)[0];
|
|
658
|
+
} catch (error) {
|
|
659
|
+
if (strict) continue;
|
|
660
|
+
throw error;
|
|
661
|
+
}
|
|
662
|
+
result[rKey] = property(data, key, inner, options);
|
|
663
|
+
data[rKey] = data[key];
|
|
664
|
+
if (key !== rKey) delete data[key];
|
|
665
|
+
}
|
|
666
|
+
return [result];
|
|
667
|
+
});
|
|
668
|
+
Schema.extend("tuple", (data, { list }, options, strict) => {
|
|
669
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
670
|
+
const result = list.map((inner, index) => property(data, index, inner, options));
|
|
671
|
+
if (strict) return [result];
|
|
672
|
+
result.push(...data.slice(list.length));
|
|
673
|
+
return [result];
|
|
674
|
+
});
|
|
675
|
+
function merge(result, data) {
|
|
676
|
+
for (const key in data) {
|
|
677
|
+
if (key in result) continue;
|
|
678
|
+
result[key] = data[key];
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
Schema.extend("object", (data, { dict }, options, strict) => {
|
|
682
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
683
|
+
const result = {};
|
|
684
|
+
for (const key in dict) {
|
|
685
|
+
const value = property(data, key, dict[key], options);
|
|
686
|
+
if (!isNullable(value) || key in data) result[key] = value;
|
|
687
|
+
}
|
|
688
|
+
if (!strict) merge(result, data);
|
|
689
|
+
return [result];
|
|
690
|
+
});
|
|
691
|
+
Schema.extend("union", (data, { list, toString }, options, strict) => {
|
|
692
|
+
const messages = [];
|
|
693
|
+
for (const inner of list) try {
|
|
694
|
+
return Schema.resolve(data, inner, options, strict);
|
|
695
|
+
} catch (error) {
|
|
696
|
+
messages.push(error);
|
|
697
|
+
}
|
|
698
|
+
throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
699
|
+
});
|
|
700
|
+
Schema.extend("intersect", (data, { list, toString }, options, strict) => {
|
|
701
|
+
if (!list.length) return [data];
|
|
702
|
+
let result;
|
|
703
|
+
for (const inner of list) {
|
|
704
|
+
const value = Schema.resolve(data, inner, options, true)[0];
|
|
705
|
+
if (isNullable(value)) continue;
|
|
706
|
+
if (isNullable(result)) result = value;
|
|
707
|
+
else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
708
|
+
else if (typeof value === "object") merge(result ??= {}, value);
|
|
709
|
+
else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
710
|
+
}
|
|
711
|
+
if (!strict && isPlainObject(data)) merge(result, data);
|
|
712
|
+
return [result];
|
|
713
|
+
});
|
|
714
|
+
Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
|
|
715
|
+
const [result, adapted = data] = Schema.resolve(data, inner, options, true);
|
|
716
|
+
if (preserve) return [callback(result)];
|
|
717
|
+
else return [callback(result), callback(adapted)];
|
|
718
|
+
});
|
|
719
|
+
const formatters = {};
|
|
720
|
+
function defineMethod(name, keys, format) {
|
|
721
|
+
formatters[name] = format;
|
|
722
|
+
Object.assign(Schema, { [name](...args) {
|
|
723
|
+
const schema = new Schema({ type: name });
|
|
724
|
+
keys.forEach((key, index) => {
|
|
725
|
+
switch (key) {
|
|
726
|
+
case "sKey":
|
|
727
|
+
schema.sKey = args[index] ?? Schema.string();
|
|
728
|
+
break;
|
|
729
|
+
case "inner":
|
|
730
|
+
schema.inner = Schema.from(args[index]);
|
|
731
|
+
break;
|
|
732
|
+
case "list":
|
|
733
|
+
schema.list = args[index].map(Schema.from);
|
|
734
|
+
break;
|
|
735
|
+
case "dict":
|
|
736
|
+
schema.dict = mapValues(args[index], Schema.from);
|
|
737
|
+
break;
|
|
738
|
+
case "bits":
|
|
739
|
+
schema.bits = {};
|
|
740
|
+
for (const key in args[index]) {
|
|
741
|
+
if (typeof args[index][key] !== "number") continue;
|
|
742
|
+
schema.bits[key] = args[index][key];
|
|
743
|
+
}
|
|
744
|
+
break;
|
|
745
|
+
case "callback": {
|
|
746
|
+
const callback = schema.callback = args[index];
|
|
747
|
+
callback["toJSON"] ||= () => callback.toString();
|
|
748
|
+
break;
|
|
749
|
+
}
|
|
750
|
+
case "constructor": {
|
|
751
|
+
const constructor = schema.constructor = args[index];
|
|
752
|
+
if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
|
|
753
|
+
break;
|
|
754
|
+
}
|
|
755
|
+
default: schema[key] = args[index];
|
|
756
|
+
}
|
|
757
|
+
});
|
|
758
|
+
if (name === "object" || name === "dict") schema.meta.default = {};
|
|
759
|
+
else if (name === "array" || name === "tuple") schema.meta.default = [];
|
|
760
|
+
else if (name === "bitset") schema.meta.default = 0;
|
|
761
|
+
return schema;
|
|
762
|
+
} });
|
|
763
|
+
}
|
|
764
|
+
defineMethod("is", ["constructor"], ({ constructor }) => {
|
|
765
|
+
if (typeof constructor === "function") return constructor.name;
|
|
766
|
+
else return constructor;
|
|
767
|
+
});
|
|
768
|
+
defineMethod("any", [], () => "any");
|
|
769
|
+
defineMethod("never", [], () => "never");
|
|
770
|
+
defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
|
|
771
|
+
defineMethod("string", [], () => "string");
|
|
772
|
+
defineMethod("number", [], () => "number");
|
|
773
|
+
defineMethod("boolean", [], () => "boolean");
|
|
774
|
+
defineMethod("bitset", ["bits"], () => "bitset");
|
|
775
|
+
defineMethod("function", [], () => "function");
|
|
776
|
+
defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
|
|
777
|
+
defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
|
|
778
|
+
defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
|
|
779
|
+
defineMethod("object", ["dict"], ({ dict }) => {
|
|
780
|
+
if (Object.keys(dict).length === 0) return "{}";
|
|
781
|
+
return `{ ${Object.entries(dict).map(([key, inner]) => {
|
|
782
|
+
return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
|
|
783
|
+
}).join(", ")} }`;
|
|
784
|
+
});
|
|
785
|
+
defineMethod("union", ["list"], ({ list }, inline) => {
|
|
786
|
+
const result = list.map(({ toString: format }) => format()).join(" | ");
|
|
787
|
+
return inline ? `(${result})` : result;
|
|
788
|
+
});
|
|
789
|
+
defineMethod("intersect", ["list"], ({ list }) => {
|
|
790
|
+
return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
|
|
791
|
+
});
|
|
792
|
+
defineMethod("transform", [
|
|
793
|
+
"inner",
|
|
794
|
+
"callback",
|
|
795
|
+
"preserve"
|
|
796
|
+
], ({ inner }, isInner) => inner.toString(isInner));
|
|
797
|
+
//#endregion
|
|
798
|
+
//#region lib/types/theme-store-settings.js
|
|
799
|
+
/** Theme store settings stored in the Host user-settings document. */
|
|
800
|
+
/** Settings namespace owned by the theme store plugin. */
|
|
801
|
+
const THEME_STORE_NAMESPACE = "ui-theme-store";
|
|
802
|
+
/** Field carrying the currently applied theme id. */
|
|
803
|
+
const THEME_STORE_APPLIED_FIELD = "applied";
|
|
804
|
+
/** Durable schema; also the wire envelope the browser scope validates against. */
|
|
805
|
+
const ThemeStoreSettingsSchema = Schema.object({ [THEME_STORE_APPLIED_FIELD]: Schema.string().default("") });
|
|
806
|
+
//#endregion
|
|
807
|
+
//#region lib/types/host/installer.js
|
|
808
|
+
/**
|
|
809
|
+
* Host-side shell-theme installer: installs an eDEX variant's packages into
|
|
810
|
+
* the active profile with pnpm and rewrites the profile's `cordis.patch.yml`
|
|
811
|
+
* to mount the variant's rows with VARIANT-SPECIFIC row ids
|
|
812
|
+
* (`<variant>-host-system-metrics`, `<variant>-ui-edex`,
|
|
813
|
+
* `<variant>-ui-theme-terminal`).
|
|
814
|
+
*
|
|
815
|
+
* The profile patch is hot-reloaded by the harness, and a page reload then
|
|
816
|
+
* boots against the new client graph — so "Apply" on a shell theme actually
|
|
817
|
+
* installs and mounts the full UI, not just the color. Switching variants
|
|
818
|
+
* works because each variant owns distinct row ids: the Loader disposes the
|
|
819
|
+
* previous variant's fibers (rows removed) and creates the new one's (rows
|
|
820
|
+
* inserted) — never reusing an id with a different module, which the config
|
|
821
|
+
* hot-reload would not re-fiber.
|
|
822
|
+
*
|
|
823
|
+
* The active profile is discovered by scanning `$DSH_HOME/profiles/*` for the
|
|
824
|
+
* directory whose `node_modules/@danielng23/dsh-client-ui-theme-store`
|
|
825
|
+
* resolves to this package.
|
|
826
|
+
*/
|
|
827
|
+
/** The three base row ids every eDEX variant bundle inserts. */
|
|
828
|
+
const VARIANT_BASE_IDS = [
|
|
829
|
+
"host-system-metrics",
|
|
830
|
+
"ui-edex",
|
|
831
|
+
"ui-theme-terminal"
|
|
832
|
+
];
|
|
833
|
+
/** The three row suffixes every eDEX variant bundle inserts (prefixed form). */
|
|
834
|
+
const VARIANT_ROW_SUFFIXES = [
|
|
835
|
+
"-host-system-metrics",
|
|
836
|
+
"-ui-edex",
|
|
837
|
+
"-ui-theme-terminal"
|
|
838
|
+
];
|
|
839
|
+
/** The variant id derived from a bundle package name (`@danielng23/dsh-edex-armory-ui` → `armory`). */
|
|
840
|
+
function variantIdOf(bundlePackage) {
|
|
841
|
+
return bundlePackage.slice(bundlePackage.lastIndexOf("/") + 1).replace(/^dsh-edex-/, "").replace(/-ui$/, "");
|
|
842
|
+
}
|
|
843
|
+
/** Resolve $DSH_HOME (mirrors dsh-home-paths): $DSH_HOME, else ~/.dsh. */
|
|
844
|
+
function dshHome() {
|
|
845
|
+
return process.env.DSH_HOME ?? join(homedir(), ".dsh");
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Find the active profile directory: the one whose node_modules contains
|
|
849
|
+
* this package (a `file:` link into the harness profile).
|
|
850
|
+
* @returns the profile directory, or undefined when none matches.
|
|
851
|
+
*/
|
|
852
|
+
function resolveActiveProfileDir() {
|
|
853
|
+
const profilesDir = join(dshHome(), "profiles");
|
|
854
|
+
if (!existsSync(profilesDir)) return void 0;
|
|
855
|
+
for (const name of readdirSync(profilesDir, { withFileTypes: true })) {
|
|
856
|
+
if (!name.isDirectory()) continue;
|
|
857
|
+
const dir = join(profilesDir, name.name);
|
|
858
|
+
const marker = join(dir, "node_modules/@danielng23/dsh-client-ui-theme-store/package.json");
|
|
859
|
+
if (!existsSync(marker)) continue;
|
|
860
|
+
try {
|
|
861
|
+
if (JSON.parse(readFileSync(marker, "utf8")).name === "@danielng23/dsh-client-ui-theme-store") return dir;
|
|
862
|
+
} catch {}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* The variant's three rows, derived from the bundle's own cordis.patch rows
|
|
867
|
+
* but re-keyed with variant-specific ids. The bundle patch is the
|
|
868
|
+
* authoritative source of the row NAMES, so an install stays correct even
|
|
869
|
+
* when a variant changes its patch; the ids are prefixed so switching
|
|
870
|
+
* variants replaces fibers instead of reusing an id with a new module.
|
|
871
|
+
* @param bundlePackage - the variant bundle package name.
|
|
872
|
+
* @param profileDir - the active profile directory.
|
|
873
|
+
* @returns the {id, name} rows to mount (id prefixed with the variant id).
|
|
874
|
+
*/
|
|
875
|
+
function variantRowsOf(bundlePackage, profileDir) {
|
|
876
|
+
const bundleDir = join(profileDir, "node_modules", bundlePackage);
|
|
877
|
+
const patchPath = join(bundleDir, "cordis.patch.yml");
|
|
878
|
+
if (!existsSync(patchPath)) return [];
|
|
879
|
+
const parsed = yaml.load(readFileSync(patchPath, "utf8"));
|
|
880
|
+
if (!Array.isArray(parsed)) return [];
|
|
881
|
+
const variantId = variantIdOf(bundlePackage);
|
|
882
|
+
const rows = [];
|
|
883
|
+
for (const entry of parsed) for (const row of entry.insert ?? []) if (typeof row.id === "string" && typeof row.name === "string") rows.push({
|
|
884
|
+
id: `${variantId}-${row.id}`,
|
|
885
|
+
name: row.name
|
|
886
|
+
});
|
|
887
|
+
return rows;
|
|
888
|
+
}
|
|
889
|
+
/** Whether a row id is one of this plugin's variant-managed rows. */
|
|
890
|
+
function isVariantRow(id) {
|
|
891
|
+
if (typeof id !== "string") return false;
|
|
892
|
+
return VARIANT_BASE_IDS.includes(id) || VARIANT_ROW_SUFFIXES.some((suffix) => id.endsWith(suffix));
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Rewrite the profile's cordis.patch.yml so the variant rows point at the
|
|
896
|
+
* given packages. Removes every previous variant's rows (any id ending in the
|
|
897
|
+
* variant suffixes), preserves all other rows (the theme-store row, user
|
|
898
|
+
* rows), and appends the new variant's rows. Returns whether the document
|
|
899
|
+
* actually changed (false when the variant was already mounted verbatim).
|
|
900
|
+
* @param profileDir - the active profile directory.
|
|
901
|
+
* @param rows - the variant rows to mount (variant-prefixed id + package name).
|
|
902
|
+
* @returns true when the patch file changed.
|
|
903
|
+
*/
|
|
904
|
+
function writeVariantPatch(profileDir, rows) {
|
|
905
|
+
const patchPath = join(profileDir, "cordis.patch.yml");
|
|
906
|
+
const existing = existsSync(patchPath) ? yaml.load(readFileSync(patchPath, "utf8")) : [];
|
|
907
|
+
const kept = [];
|
|
908
|
+
for (const entry of Array.isArray(existing) ? existing : []) {
|
|
909
|
+
const inserts = (entry.insert ?? []).filter((row) => !isVariantRow(row.id));
|
|
910
|
+
if (inserts.length > 0) kept.push({
|
|
911
|
+
...entry,
|
|
912
|
+
insert: inserts
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
const next = [...kept, { insert: rows }];
|
|
916
|
+
const content = yaml.dump(next, {
|
|
917
|
+
noRefs: true,
|
|
918
|
+
lineWidth: 120
|
|
919
|
+
});
|
|
920
|
+
if (existsSync(patchPath) && readFileSync(patchPath, "utf8") === content) return false;
|
|
921
|
+
writeFileSync(patchPath, content);
|
|
922
|
+
return true;
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Install a shell theme's variant into the active profile: pnpm-add the
|
|
926
|
+
* bundle's three packages, then point the profile patch's variant rows at
|
|
927
|
+
* them. Returns the install outcome; the browser reloads on success.
|
|
928
|
+
* @param bundlePackage - the variant bundle package (e.g. `@danielng23/dsh-edex-armory-ui`).
|
|
929
|
+
* @returns the install result.
|
|
930
|
+
*/
|
|
931
|
+
function installShellTheme(bundlePackage) {
|
|
932
|
+
const profileDir = resolveActiveProfileDir();
|
|
933
|
+
if (profileDir === void 0) return {
|
|
934
|
+
ok: false,
|
|
935
|
+
changed: false,
|
|
936
|
+
error: "theme-store: no active dsh profile found (scan $DSH_HOME/profiles)"
|
|
937
|
+
};
|
|
938
|
+
console.log(`[theme-store] installShellTheme(${bundlePackage}) profileDir=${profileDir}`);
|
|
939
|
+
const alreadyInstalled = existsSync(join(profileDir, "node_modules", bundlePackage, "package.json"));
|
|
940
|
+
console.log(`[theme-store] bundle already installed: ${String(alreadyInstalled)}`);
|
|
941
|
+
if (!alreadyInstalled) {
|
|
942
|
+
const result = spawnSync("pnpm", ["add", bundlePackage], {
|
|
943
|
+
cwd: profileDir,
|
|
944
|
+
encoding: "utf8",
|
|
945
|
+
timeout: 12e4
|
|
946
|
+
});
|
|
947
|
+
console.log(`[theme-store] pnpm add exit=${String(result.status)} error=${result.error?.message ?? "none"}`);
|
|
948
|
+
if (result.error !== void 0) return {
|
|
949
|
+
ok: false,
|
|
950
|
+
changed: false,
|
|
951
|
+
error: `theme-store: pnpm failed: ${result.error.message}`
|
|
952
|
+
};
|
|
953
|
+
if (result.status !== 0) return {
|
|
954
|
+
ok: false,
|
|
955
|
+
changed: false,
|
|
956
|
+
error: `theme-store: pnpm add ${bundlePackage} exited ${String(result.status)}`
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
const rows = variantRowsOf(bundlePackage, profileDir);
|
|
960
|
+
console.log(`[theme-store] rows read: ${rows.length} (${rows.map((r) => r.id).join(", ")})`);
|
|
961
|
+
if (rows.length === 0) return {
|
|
962
|
+
ok: false,
|
|
963
|
+
changed: false,
|
|
964
|
+
error: `theme-store: ${bundlePackage} ships no cordis.patch.yml rows to mount`
|
|
965
|
+
};
|
|
966
|
+
const changed = writeVariantPatch(profileDir, rows);
|
|
967
|
+
console.log(`[theme-store] patch written, changed=${String(changed)}`);
|
|
968
|
+
return {
|
|
969
|
+
ok: true,
|
|
970
|
+
changed
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
//#endregion
|
|
974
|
+
//#region lib/types/index.js
|
|
975
|
+
/**
|
|
976
|
+
* Host registration for the theme store settings namespace (persists the
|
|
977
|
+
* applied third-party theme id across reloads), serves the eDEX theme catalog
|
|
978
|
+
* JSON locally, and provides a POST route to install shell themes (pnpm add
|
|
979
|
+
* + profile patch rewrite) — so "Apply" on a shell theme actually installs
|
|
980
|
+
* and mounts the full UI.
|
|
981
|
+
*/
|
|
982
|
+
/** Path of the catalog JSON relative to this file (src/index.ts → ../catalog, lib/index.js → ../catalog). */
|
|
983
|
+
const CATALOG_PATH = new URL("../catalog/edex-themes.json", import.meta.url);
|
|
984
|
+
/** Durable event log so install/restart events survive the respawned child (its stdout is /dev/null). */
|
|
985
|
+
const EVENT_LOG = join(homedir(), ".dsh", "theme-store-events.log");
|
|
986
|
+
/** Append one timestamped line to the durable event log; never throws. */
|
|
987
|
+
function logEvent(message) {
|
|
988
|
+
console.log("[theme-store] " + message);
|
|
989
|
+
try {
|
|
990
|
+
appendFileSync(EVENT_LOG, `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}\n`);
|
|
991
|
+
} catch {}
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Register the durable theme-store section, serve the catalog, and mount the
|
|
995
|
+
* shell-theme installer route.
|
|
996
|
+
* @param ctx - Host context.
|
|
997
|
+
*/
|
|
998
|
+
function apply(ctx) {
|
|
999
|
+
ctx.inject(["settings"], (settingsCtx) => {
|
|
1000
|
+
settingsCtx.settings.register(settingsNamespace(THEME_STORE_NAMESPACE), ThemeStoreSettingsSchema);
|
|
1001
|
+
});
|
|
1002
|
+
ctx.inject(["webServer"], (webCtx) => {
|
|
1003
|
+
const catalogDispose = webCtx.webServer.register({
|
|
1004
|
+
kind: "exact",
|
|
1005
|
+
path: "/catalog/edex-themes.json",
|
|
1006
|
+
async handler(_req, res) {
|
|
1007
|
+
try {
|
|
1008
|
+
const json = await readFile(CATALOG_PATH, "utf8");
|
|
1009
|
+
res.writeHead(200, {
|
|
1010
|
+
"content-type": "application/json; charset=utf-8",
|
|
1011
|
+
"access-control-allow-origin": "*"
|
|
1012
|
+
});
|
|
1013
|
+
res.end(json);
|
|
1014
|
+
} catch {
|
|
1015
|
+
res.writeHead(404, { "content-type": "text/plain" });
|
|
1016
|
+
res.end("catalog not found");
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
});
|
|
1020
|
+
webCtx.effect(() => catalogDispose, "theme-store: catalog route");
|
|
1021
|
+
const installDispose = webCtx.webServer.register({
|
|
1022
|
+
kind: "exact",
|
|
1023
|
+
path: "/api/theme-store/install",
|
|
1024
|
+
async handler(req, res) {
|
|
1025
|
+
let body = "";
|
|
1026
|
+
try {
|
|
1027
|
+
for await (const chunk of req) body += chunk;
|
|
1028
|
+
const { installPackage } = JSON.parse(body);
|
|
1029
|
+
logEvent("install request: " + JSON.stringify({
|
|
1030
|
+
installPackage,
|
|
1031
|
+
pid: process.pid
|
|
1032
|
+
}));
|
|
1033
|
+
if (typeof installPackage !== "string" || installPackage.length === 0) {
|
|
1034
|
+
res.writeHead(400, { "content-type": "application/json" });
|
|
1035
|
+
res.end(JSON.stringify({
|
|
1036
|
+
ok: false,
|
|
1037
|
+
error: "missing installPackage"
|
|
1038
|
+
}));
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
const result = installShellTheme(installPackage);
|
|
1042
|
+
logEvent("install result: " + JSON.stringify({
|
|
1043
|
+
...result,
|
|
1044
|
+
installPackage
|
|
1045
|
+
}));
|
|
1046
|
+
res.writeHead(result.ok ? 200 : 500, { "content-type": "application/json" });
|
|
1047
|
+
res.end(JSON.stringify({
|
|
1048
|
+
ok: result.ok,
|
|
1049
|
+
changed: result.changed,
|
|
1050
|
+
error: result.error
|
|
1051
|
+
}));
|
|
1052
|
+
} catch (error) {
|
|
1053
|
+
logEvent("install threw: " + (error instanceof Error ? error.message : String(error)));
|
|
1054
|
+
res.writeHead(400, { "content-type": "application/json" });
|
|
1055
|
+
res.end(JSON.stringify({
|
|
1056
|
+
ok: false,
|
|
1057
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1058
|
+
}));
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
});
|
|
1062
|
+
webCtx.effect(() => installDispose, "theme-store: install route");
|
|
1063
|
+
const restartDispose = webCtx.webServer.register({
|
|
1064
|
+
kind: "exact",
|
|
1065
|
+
path: "/api/theme-store/restart",
|
|
1066
|
+
async handler(_req, res) {
|
|
1067
|
+
logEvent("restart request received (pid=" + process.pid + ")");
|
|
1068
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
1069
|
+
res.end(JSON.stringify({ ok: true }));
|
|
1070
|
+
setTimeout(() => {
|
|
1071
|
+
try {
|
|
1072
|
+
logEvent("respawn: execPath=" + process.execPath + " argv=" + JSON.stringify(process.argv.slice(1)) + " cwd=" + process.cwd());
|
|
1073
|
+
const child = spawn(process.execPath, process.argv.slice(1), {
|
|
1074
|
+
cwd: process.cwd(),
|
|
1075
|
+
detached: true,
|
|
1076
|
+
stdio: "ignore"
|
|
1077
|
+
});
|
|
1078
|
+
child.unref();
|
|
1079
|
+
logEvent("spawned child pid=" + (child.pid ?? "unknown"));
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
logEvent("respawn failed: " + (error instanceof Error ? error.message : String(error)));
|
|
1082
|
+
}
|
|
1083
|
+
const exit = webCtx.get?.("appExit");
|
|
1084
|
+
logEvent("appExit available: " + String(typeof exit === "function"));
|
|
1085
|
+
if (typeof exit === "function") exit(0);
|
|
1086
|
+
}, 300);
|
|
1087
|
+
}
|
|
1088
|
+
});
|
|
1089
|
+
webCtx.effect(() => restartDispose, "theme-store: restart route");
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
//#endregion
|
|
1093
|
+
export { THEME_STORE_APPLIED_FIELD, THEME_STORE_NAMESPACE, ThemeStoreSettingsSchema, apply };
|