@qilin-agent/client-locale 0.0.0-stage → 3.1.3

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/client.js ADDED
@@ -0,0 +1,1390 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "@qilin-agent/client-locale",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ //#region ../../../vendor/cosmokit/src/misc.ts
8
+ /** Return true when a value is `null` or `undefined`. */
9
+ function isNullable(value) {
10
+ return value === null || value === void 0;
11
+ }
12
+ /** Return true for non-array object values. */
13
+ function isPlainObject(data) {
14
+ return data && typeof data === "object" && !Array.isArray(data);
15
+ }
16
+ /** Filter object entries and return a new object. */
17
+ function filterKeys(object, filter) {
18
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
19
+ }
20
+ /** Map object values while preserving the original key set. */
21
+ function mapValues(object, transform) {
22
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
23
+ }
24
+ /** Pick selected keys from an object, optionally including `undefined` values. */
25
+ function pick(source, keys, forced) {
26
+ if (!keys) return { ...source };
27
+ const result = {};
28
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
29
+ return result;
30
+ }
31
+ //#endregion
32
+ //#region ../../../vendor/cosmokit/src/volatile.ts
33
+ /** Shared config references used by schema validators and plugin runtimes. */
34
+ const write = Symbol.for("cosmokit.volatile.write");
35
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
36
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
37
+ if (value === null || typeof value !== "object") return value;
38
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
39
+ ancestors.add(value);
40
+ try {
41
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
42
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
43
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
44
+ } finally {
45
+ ancestors.delete(value);
46
+ }
47
+ }
48
+ /**
49
+ * Create a detached reference containing an immutable copy of the supplied data.
50
+ * @param value - validated config data; class instances and functions are unsupported.
51
+ * @returns a reference whose value is updated only by its owning runtime.
52
+ */
53
+ function createVolatile(value) {
54
+ let current = snapshot(value);
55
+ return Object.freeze({
56
+ get: () => current,
57
+ [write]: (value) => {
58
+ current = value;
59
+ }
60
+ });
61
+ }
62
+ /**
63
+ * Identify references across ESM/CJS copies of the shared library.
64
+ * @param value - a parsed config value.
65
+ * @returns whether the value implements the shared reference protocol.
66
+ */
67
+ function isVolatile(value) {
68
+ return typeof value === "object" && value !== null && write in value;
69
+ }
70
+ //#endregion
71
+ //#region ../../../vendor/cosmokit/src/types.ts
72
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
73
+ function is(type, value) {
74
+ if (arguments.length === 1) return (value) => is(type, value);
75
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
76
+ }
77
+ function isArrayBufferLike(value) {
78
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
79
+ }
80
+ function isArrayBufferSource(value) {
81
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
82
+ }
83
+ let Binary;
84
+ (function(_Binary) {
85
+ _Binary.is = isArrayBufferLike;
86
+ _Binary.isSource = isArrayBufferSource;
87
+ function fromSource(source) {
88
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
89
+ else return source;
90
+ }
91
+ _Binary.fromSource = fromSource;
92
+ function toBase64(source) {
93
+ source = fromSource(source);
94
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
95
+ let binary = "";
96
+ const bytes = new Uint8Array(source);
97
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
98
+ return btoa(binary);
99
+ }
100
+ _Binary.toBase64 = toBase64;
101
+ function fromBase64(source) {
102
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
103
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
104
+ }
105
+ _Binary.fromBase64 = fromBase64;
106
+ function toHex(source) {
107
+ source = fromSource(source);
108
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
109
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
110
+ }
111
+ _Binary.toHex = toHex;
112
+ function fromHex(source) {
113
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
114
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
115
+ const buffer = [];
116
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
117
+ return Uint8Array.from(buffer).buffer;
118
+ }
119
+ _Binary.fromHex = fromHex;
120
+ })(Binary || (Binary = {}));
121
+ Binary.fromBase64;
122
+ Binary.toBase64;
123
+ Binary.fromHex;
124
+ Binary.toHex;
125
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
126
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
127
+ if (!source || typeof source !== "object") return source;
128
+ if (is("Date", source)) return new Date(source.valueOf());
129
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
130
+ if (isArrayBufferLike(source)) return source.slice(0);
131
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
132
+ const cached = refs.get(source);
133
+ if (cached) return cached;
134
+ if (Array.isArray(source)) {
135
+ const result = [];
136
+ refs.set(source, result);
137
+ source.forEach((value, index) => {
138
+ result[index] = Reflect.apply(clone, null, [value, refs]);
139
+ });
140
+ return result;
141
+ }
142
+ const result = Object.create(Object.getPrototypeOf(source));
143
+ refs.set(source, result);
144
+ for (const key of Reflect.ownKeys(source)) {
145
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
146
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
147
+ Reflect.defineProperty(result, key, descriptor);
148
+ }
149
+ return result;
150
+ }
151
+ /**
152
+ * Compare values recursively, treating two volatile references as equal regardless of value.
153
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
154
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
155
+ * @param a - first value.
156
+ * @param b - second value.
157
+ * @param strict - whether to require strict data equality outside volatile references.
158
+ * @returns whether the values compare equal.
159
+ */
160
+ function deepEqual(a, b, strict) {
161
+ const ancestors = /* @__PURE__ */ new Set();
162
+ function compare(a, b) {
163
+ if (a === b) return true;
164
+ if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);
165
+ if (!strict && isNullable(a) && isNullable(b)) return true;
166
+ if (typeof a !== typeof b || typeof a !== "object" || !a || !b) return false;
167
+ if (ancestors.has(a)) return false;
168
+ function check(test, then) {
169
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
170
+ }
171
+ ancestors.add(a);
172
+ try {
173
+ return check(Array.isArray, (a, b) => {
174
+ if (a.length !== b.length) return false;
175
+ for (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;
176
+ return true;
177
+ }) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("URL"), (a, b) => a.href === b.href) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
178
+ if (a.byteLength !== b.byteLength) return false;
179
+ const viewA = new Uint8Array(a);
180
+ const viewB = new Uint8Array(b);
181
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
182
+ return true;
183
+ }) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
184
+ ...a,
185
+ ...b
186
+ }).every((key) => compare(a[key], b[key])));
187
+ } finally {
188
+ ancestors.delete(a);
189
+ }
190
+ }
191
+ return compare(a, b);
192
+ }
193
+ //#endregion
194
+ //#region ../../../vendor/cosmokit/src/time.ts
195
+ let Time;
196
+ (function(_Time) {
197
+ _Time.millisecond = 1;
198
+ const second = _Time.second = 1e3;
199
+ const minute = _Time.minute = second * 60;
200
+ const hour = _Time.hour = minute * 60;
201
+ const day = _Time.day = hour * 24;
202
+ const week = _Time.week = day * 7;
203
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
204
+ function setTimezoneOffset(offset) {
205
+ timezoneOffset = offset;
206
+ }
207
+ _Time.setTimezoneOffset = setTimezoneOffset;
208
+ function getTimezoneOffset() {
209
+ return timezoneOffset;
210
+ }
211
+ _Time.getTimezoneOffset = getTimezoneOffset;
212
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
213
+ if (typeof date === "number") date = new Date(date);
214
+ if (offset === void 0) offset = timezoneOffset;
215
+ return Math.floor((date.valueOf() / minute - offset) / 1440);
216
+ }
217
+ _Time.getDateNumber = getDateNumber;
218
+ function fromDateNumber(value, offset) {
219
+ const date = new Date(value * day);
220
+ if (offset === void 0) offset = timezoneOffset;
221
+ return new Date(+date + offset * minute);
222
+ }
223
+ _Time.fromDateNumber = fromDateNumber;
224
+ const numeric = /\d+(?:\.\d+)?/.source;
225
+ const timeRegExp = new RegExp(`^${[
226
+ "w(?:eek(?:s)?)?",
227
+ "d(?:ay(?:s)?)?",
228
+ "h(?:our(?:s)?)?",
229
+ "m(?:in(?:ute)?(?:s)?)?",
230
+ "s(?:ec(?:ond)?(?:s)?)?"
231
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
232
+ function parseTime(source) {
233
+ const capture = timeRegExp.exec(source);
234
+ if (!capture) return 0;
235
+ return (parseFloat(capture[1]) * week || 0) + (parseFloat(capture[2]) * day || 0) + (parseFloat(capture[3]) * hour || 0) + (parseFloat(capture[4]) * minute || 0) + (parseFloat(capture[5]) * second || 0);
236
+ }
237
+ _Time.parseTime = parseTime;
238
+ function parseDate(date) {
239
+ const parsed = parseTime(date);
240
+ if (parsed) date = Date.now() + parsed;
241
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
242
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
243
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
244
+ }
245
+ _Time.parseDate = parseDate;
246
+ function format(ms) {
247
+ const abs = Math.abs(ms);
248
+ if (abs >= day - hour / 2) return Math.round(ms / day) + "d";
249
+ else if (abs >= hour - minute / 2) return Math.round(ms / hour) + "h";
250
+ else if (abs >= minute - second / 2) return Math.round(ms / minute) + "m";
251
+ else if (abs >= second) return Math.round(ms / second) + "s";
252
+ return ms + "ms";
253
+ }
254
+ _Time.format = format;
255
+ function toDigits(source, length = 2) {
256
+ return source.toString().padStart(length, "0");
257
+ }
258
+ _Time.toDigits = toDigits;
259
+ function template(template, time = /* @__PURE__ */ new Date()) {
260
+ 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));
261
+ }
262
+ _Time.template = template;
263
+ })(Time || (Time = {}));
264
+ //#endregion
265
+ //#region ../../../vendor/schemastery/src/index.ts
266
+ const kSchema = Symbol.for("schemastery");
267
+ const kValidationError = Symbol.for("ValidationError");
268
+ globalThis.__schemastery_index__ ??= 0;
269
+ globalThis.__schemastery_refs__ = void 0;
270
+ var ValidationError = class extends TypeError {
271
+ options;
272
+ name = "ValidationError";
273
+ constructor(message, options) {
274
+ let prefix = "$";
275
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
276
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
277
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
278
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
279
+ super((prefix === "$" ? "" : `${prefix} `) + message);
280
+ this.options = options;
281
+ }
282
+ static is(error) {
283
+ return !!error?.[kValidationError];
284
+ }
285
+ };
286
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
287
+ const Schema = function(options) {
288
+ const schema = function(data, options = {}) {
289
+ return Schema.resolve(data, schema, options)[0];
290
+ };
291
+ if (options.refs) {
292
+ const refs = mapValues(options.refs, (options) => new Schema(options));
293
+ const getRef = (uid) => refs[uid];
294
+ for (const key in refs) {
295
+ const options = refs[key];
296
+ options.sKey = getRef(options.sKey);
297
+ options.inner = getRef(options.inner);
298
+ options.list = options.list && options.list.map(getRef);
299
+ options.dict = options.dict && mapValues(options.dict, getRef);
300
+ }
301
+ return refs[options.uid];
302
+ }
303
+ Object.assign(schema, options);
304
+ if (typeof schema.callback === "string") try {
305
+ schema.callback = new Function("return " + schema.callback)();
306
+ } catch {}
307
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
308
+ Object.setPrototypeOf(schema, Schema.prototype);
309
+ schema.meta ||= {};
310
+ schema.toString = schema.toString.bind(schema);
311
+ return schema;
312
+ };
313
+ Schema.prototype = Object.create(Function.prototype);
314
+ Schema.prototype[kSchema] = true;
315
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
316
+ return {
317
+ version: 1,
318
+ vendor: "schemastery",
319
+ validate: (value) => {
320
+ try {
321
+ return { value: Schema.resolve(value, this, {})[0] };
322
+ } catch (error) {
323
+ if (ValidationError.is(error)) return { issues: [{
324
+ message: error.message,
325
+ path: error.options.path
326
+ }] };
327
+ throw error;
328
+ }
329
+ }
330
+ };
331
+ } });
332
+ Schema.ValidationError = ValidationError;
333
+ Schema.prototype.toJSON = function toJSON() {
334
+ if (globalThis.__schemastery_refs__) {
335
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
336
+ return this.uid;
337
+ }
338
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
339
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
340
+ const result = {
341
+ uid: this.uid,
342
+ refs: globalThis.__schemastery_refs__
343
+ };
344
+ globalThis.__schemastery_refs__ = void 0;
345
+ return result;
346
+ };
347
+ Schema.prototype.set = function set(key, value) {
348
+ this.dict[key] = value;
349
+ return this;
350
+ };
351
+ Schema.prototype.push = function push(value) {
352
+ this.list.push(value);
353
+ return this;
354
+ };
355
+ function mergeDesc(original, messages) {
356
+ const result = typeof original === "string" ? { "": original } : { ...original };
357
+ for (const locale in messages) {
358
+ const value = messages[locale];
359
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
360
+ else if (typeof value === "string") result[locale] = value;
361
+ }
362
+ return result;
363
+ }
364
+ function getInner(value) {
365
+ return value?.$value ?? value?.$inner;
366
+ }
367
+ function extractKeys(data) {
368
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
369
+ }
370
+ Schema.prototype.i18n = function i18n(messages) {
371
+ const schema = Schema(this);
372
+ const desc = mergeDesc(schema.meta.description, messages);
373
+ if (Object.keys(desc).length) schema.meta.description = desc;
374
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
375
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
376
+ });
377
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
378
+ return inner.i18n(mapValues(messages, (data = {}) => {
379
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
380
+ if (Array.isArray(data)) return data[index];
381
+ return extractKeys(data);
382
+ }));
383
+ });
384
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
385
+ if (getInner(data)) return getInner(data);
386
+ return extractKeys(data);
387
+ }));
388
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
389
+ return schema;
390
+ };
391
+ Schema.prototype.extra = function extra(key, value) {
392
+ const schema = Schema(this);
393
+ schema.meta = {
394
+ ...schema.meta,
395
+ [key]: value
396
+ };
397
+ return schema;
398
+ };
399
+ for (const key of [
400
+ "required",
401
+ "disabled",
402
+ "collapse",
403
+ "hidden",
404
+ "loose"
405
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
406
+ const schema = Schema(this);
407
+ schema.meta = {
408
+ ...schema.meta,
409
+ [key]: value
410
+ };
411
+ return schema;
412
+ } });
413
+ Schema.prototype.deprecated = function deprecated() {
414
+ const schema = Schema(this);
415
+ schema.meta.badges ||= [];
416
+ schema.meta.badges.push({
417
+ text: "deprecated",
418
+ type: "danger"
419
+ });
420
+ return schema;
421
+ };
422
+ Schema.prototype.experimental = function experimental() {
423
+ const schema = Schema(this);
424
+ schema.meta.badges ||= [];
425
+ schema.meta.badges.push({
426
+ text: "experimental",
427
+ type: "warning"
428
+ });
429
+ return schema;
430
+ };
431
+ Schema.prototype.pattern = function pattern(regexp) {
432
+ const schema = Schema(this);
433
+ const pattern = pick(regexp, ["source", "flags"]);
434
+ schema.meta = {
435
+ ...schema.meta,
436
+ pattern
437
+ };
438
+ return schema;
439
+ };
440
+ Schema.prototype.simplify = function simplify(value) {
441
+ if (isVolatile(value)) value = value.get();
442
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
443
+ if (isNullable(value)) return value;
444
+ if (this.type === "object" || this.type === "dict") {
445
+ const result = {};
446
+ for (const key in value) {
447
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
448
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
449
+ }
450
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
451
+ return result;
452
+ } else if (this.type === "array" || this.type === "tuple") {
453
+ const result = [];
454
+ value.forEach((value, index) => {
455
+ const schema = this.type === "array" ? this.inner : this.list[index];
456
+ const item = schema ? schema.simplify(value) : value;
457
+ result.push(item);
458
+ });
459
+ return result;
460
+ } else if (this.type === "intersect") {
461
+ const result = {};
462
+ for (const item of this.list) Object.assign(result, item.simplify(value));
463
+ return result;
464
+ } else if (this.type === "union") for (const schema of this.list) try {
465
+ Schema.resolve(value, schema, {});
466
+ return schema.simplify(value);
467
+ } catch {}
468
+ return value;
469
+ };
470
+ Schema.prototype.toString = function toString(inline) {
471
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
472
+ };
473
+ Schema.prototype.role = function role(role, extra) {
474
+ const schema = Schema(this);
475
+ schema.meta = {
476
+ ...schema.meta,
477
+ role,
478
+ extra
479
+ };
480
+ return schema;
481
+ };
482
+ for (const key of [
483
+ "default",
484
+ "link",
485
+ "comment",
486
+ "description",
487
+ "max",
488
+ "min",
489
+ "step"
490
+ ]) Object.assign(Schema.prototype, { [key](value) {
491
+ const schema = Schema(this);
492
+ schema.meta = {
493
+ ...schema.meta,
494
+ [key]: value
495
+ };
496
+ return schema;
497
+ } });
498
+ Schema.prototype.volatile = function volatile() {
499
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
500
+ return this.extra("volatile", true);
501
+ };
502
+ const resolvers = {};
503
+ const checkedVolatile = Symbol("checked-volatile-schema");
504
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
505
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
506
+ if (states.has(blocked)) return;
507
+ states.add(blocked);
508
+ seen.set(schema, states);
509
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
510
+ const nested = blocked || !!schema.meta?.volatile;
511
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
512
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
513
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
514
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
515
+ }
516
+ Schema.extend = function extend(type, resolve) {
517
+ resolvers[type] = resolve;
518
+ };
519
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
520
+ if (!schema) return [data];
521
+ if (!options[checkedVolatile]) {
522
+ validateVolatileSchema(schema, options.path);
523
+ options = {
524
+ ...options,
525
+ [checkedVolatile]: true
526
+ };
527
+ }
528
+ if (schema.meta?.volatile) {
529
+ const inner = Schema(schema);
530
+ inner.meta = {
531
+ ...schema.meta,
532
+ volatile: false
533
+ };
534
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
535
+ try {
536
+ return [createVolatile(value), adapted];
537
+ } catch (error) {
538
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
539
+ }
540
+ }
541
+ if (options.ignore?.(data, schema)) return [data];
542
+ if (isNullable(data) && schema.type !== "lazy") {
543
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
544
+ let current = schema;
545
+ let fallback = schema.meta.default;
546
+ while (current?.type === "intersect" && isNullable(fallback)) {
547
+ current = current.list[0];
548
+ fallback = current?.meta.default;
549
+ }
550
+ if (isNullable(fallback)) return [data];
551
+ data = clone(fallback);
552
+ }
553
+ const callback = resolvers[schema.type];
554
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
555
+ try {
556
+ return callback(data, schema, options, strict);
557
+ } catch (error) {
558
+ if (!schema.meta.loose) throw error;
559
+ return [schema.meta.default];
560
+ }
561
+ };
562
+ Schema.from = function from(source) {
563
+ if (isNullable(source)) return Schema.any();
564
+ else if ([
565
+ "string",
566
+ "number",
567
+ "boolean"
568
+ ].includes(typeof source)) return Schema.const(source).required();
569
+ else if (source[kSchema]) return source;
570
+ else if (typeof source === "function") switch (source) {
571
+ case String: return Schema.string().required();
572
+ case Number: return Schema.number().required();
573
+ case Boolean: return Schema.boolean().required();
574
+ case Function: return Schema.function().required();
575
+ default: return Schema.is(source).required();
576
+ }
577
+ else throw new TypeError(`cannot infer schema from ${source}`);
578
+ };
579
+ Schema.lazy = function lazy(builder) {
580
+ const toJSON = () => {
581
+ if (!schema.inner[kSchema]) {
582
+ schema.inner = schema.builder();
583
+ schema.inner.meta = {
584
+ ...schema.meta,
585
+ ...schema.inner.meta
586
+ };
587
+ }
588
+ return schema.inner.toJSON();
589
+ };
590
+ const schema = new Schema({
591
+ type: "lazy",
592
+ builder,
593
+ inner: { toJSON }
594
+ });
595
+ return schema;
596
+ };
597
+ Schema.natural = function natural() {
598
+ return Schema.number().step(1).min(0);
599
+ };
600
+ Schema.percent = function percent() {
601
+ return Schema.number().step(.01).min(0).max(1).role("slider");
602
+ };
603
+ Schema.date = function date() {
604
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
605
+ const date = new Date(value);
606
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
607
+ return date;
608
+ }, true)]);
609
+ };
610
+ Schema.regExp = function regExp(flag = "") {
611
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
612
+ try {
613
+ return new RegExp(value, flag);
614
+ } catch (e) {
615
+ throw new ValidationError(e.message, options);
616
+ }
617
+ }, true)]);
618
+ };
619
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
620
+ return Schema.union([
621
+ Schema.is(ArrayBuffer),
622
+ Schema.is(SharedArrayBuffer),
623
+ Schema.transform(Schema.any(), (value, options) => {
624
+ if (Binary.isSource(value)) return Binary.fromSource(value);
625
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
626
+ }, true),
627
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
628
+ try {
629
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
630
+ } catch (e) {
631
+ throw new ValidationError(e.message, options);
632
+ }
633
+ }, true)] : []
634
+ ]);
635
+ };
636
+ Schema.extend("lazy", (data, schema, options, strict) => {
637
+ if (!schema.inner[kSchema]) {
638
+ schema.inner = schema.builder();
639
+ schema.inner.meta = {
640
+ ...schema.meta,
641
+ ...schema.inner.meta
642
+ };
643
+ validateVolatileSchema(schema.inner, options.path, true);
644
+ }
645
+ return Schema.resolve(data, schema.inner, options, strict);
646
+ });
647
+ Schema.extend("any", (data) => {
648
+ return [data];
649
+ });
650
+ Schema.extend("never", (data, _, options) => {
651
+ throw new ValidationError(`expected nullable but got ${data}`, options);
652
+ });
653
+ Schema.extend("const", (data, { value }, options) => {
654
+ if (deepEqual(data, value)) return [value];
655
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
656
+ });
657
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
658
+ const { max = Infinity, min = -Infinity } = meta;
659
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
660
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
661
+ }
662
+ Schema.extend("string", (data, { meta }, options) => {
663
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
664
+ if (meta.pattern) {
665
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
666
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
667
+ }
668
+ checkWithinRange(data.length, meta, "string length", options);
669
+ return [data];
670
+ });
671
+ function decimalShift(data, digits) {
672
+ const str = data.toString();
673
+ if (str.includes("e")) return data * Math.pow(10, digits);
674
+ const index = str.indexOf(".");
675
+ if (index === -1) return data * Math.pow(10, digits);
676
+ const frac = str.slice(index + 1);
677
+ const integer = str.slice(0, index);
678
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
679
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
680
+ }
681
+ function isMultipleOf(data, min, step) {
682
+ step = Math.abs(step);
683
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
684
+ const index = step.toString().indexOf(".");
685
+ const digits = step.toString().slice(index + 1).length;
686
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
687
+ }
688
+ Schema.extend("number", (data, { meta }, options) => {
689
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
690
+ checkWithinRange(data, meta, "number", options);
691
+ const { step } = meta;
692
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
693
+ return [data];
694
+ });
695
+ Schema.extend("boolean", (data, _, options) => {
696
+ if (typeof data === "boolean") return [data];
697
+ throw new ValidationError(`expected boolean but got ${data}`, options);
698
+ });
699
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
700
+ let value = 0, keys = [];
701
+ if (typeof data === "number") {
702
+ value = data;
703
+ for (const key in bits) if (data & bits[key]) keys.push(key);
704
+ } else if (Array.isArray(data)) {
705
+ keys = data;
706
+ for (const key of keys) {
707
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
708
+ if (key in bits) value |= bits[key];
709
+ }
710
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
711
+ if (value === meta.default) return [value];
712
+ return [value, keys];
713
+ });
714
+ Schema.extend("function", (data, _, options) => {
715
+ if (typeof data === "function") return [data];
716
+ throw new ValidationError(`expected function but got ${data}`, options);
717
+ });
718
+ Schema.extend("is", (data, { constructor }, options) => {
719
+ if (typeof constructor === "function") {
720
+ if (data instanceof constructor) return [data];
721
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
722
+ } else {
723
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
724
+ let prototype = Object.getPrototypeOf(data);
725
+ while (prototype) {
726
+ if (prototype.constructor?.name === constructor) return [data];
727
+ prototype = Object.getPrototypeOf(prototype);
728
+ }
729
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
730
+ }
731
+ });
732
+ function property(data, key, schema, options) {
733
+ try {
734
+ const [value, adapted] = Schema.resolve(data[key], schema, {
735
+ ...options,
736
+ path: [...options.path || [], key]
737
+ });
738
+ if (adapted !== void 0) data[key] = adapted;
739
+ return value;
740
+ } catch (e) {
741
+ if (!options?.autofix) throw e;
742
+ delete data[key];
743
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
744
+ }
745
+ }
746
+ Schema.extend("array", (data, { inner, meta }, options) => {
747
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
748
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
749
+ return [data.map((_, index) => property(data, index, inner, options))];
750
+ });
751
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
752
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
753
+ const result = {};
754
+ for (const key in data) {
755
+ let rKey;
756
+ try {
757
+ rKey = Schema.resolve(key, sKey, options)[0];
758
+ } catch (error) {
759
+ if (strict) continue;
760
+ throw error;
761
+ }
762
+ result[rKey] = property(data, key, inner, options);
763
+ data[rKey] = data[key];
764
+ if (key !== rKey) delete data[key];
765
+ }
766
+ return [result];
767
+ });
768
+ Schema.extend("tuple", (data, { list }, options, strict) => {
769
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
770
+ const result = list.map((inner, index) => property(data, index, inner, options));
771
+ if (strict) return [result];
772
+ result.push(...data.slice(list.length));
773
+ return [result];
774
+ });
775
+ function merge(result, data) {
776
+ for (const key in data) {
777
+ if (key in result) continue;
778
+ result[key] = data[key];
779
+ }
780
+ }
781
+ Schema.extend("object", (data, { dict }, options, strict) => {
782
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
783
+ const result = {};
784
+ for (const key in dict) {
785
+ const value = property(data, key, dict[key], options);
786
+ if (!isNullable(value) || key in data) result[key] = value;
787
+ }
788
+ if (!strict) merge(result, data);
789
+ return [result];
790
+ });
791
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
792
+ const messages = [];
793
+ for (const inner of list) try {
794
+ return Schema.resolve(data, inner, options, strict);
795
+ } catch (error) {
796
+ messages.push(error);
797
+ }
798
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
799
+ });
800
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
801
+ if (!list.length) return [data];
802
+ let result;
803
+ for (const inner of list) {
804
+ const value = Schema.resolve(data, inner, options, true)[0];
805
+ if (isNullable(value)) continue;
806
+ if (isNullable(result)) result = value;
807
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
808
+ else if (typeof value === "object") merge(result ??= {}, value);
809
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
810
+ }
811
+ if (!strict && isPlainObject(data)) merge(result, data);
812
+ return [result];
813
+ });
814
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
815
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
816
+ if (preserve) return [callback(result)];
817
+ else return [callback(result), callback(adapted)];
818
+ });
819
+ const formatters = {};
820
+ function defineMethod(name, keys, format) {
821
+ formatters[name] = format;
822
+ Object.assign(Schema, { [name](...args) {
823
+ const schema = new Schema({ type: name });
824
+ keys.forEach((key, index) => {
825
+ switch (key) {
826
+ case "sKey":
827
+ schema.sKey = args[index] ?? Schema.string();
828
+ break;
829
+ case "inner":
830
+ schema.inner = Schema.from(args[index]);
831
+ break;
832
+ case "list":
833
+ schema.list = args[index].map(Schema.from);
834
+ break;
835
+ case "dict":
836
+ schema.dict = mapValues(args[index], Schema.from);
837
+ break;
838
+ case "bits":
839
+ schema.bits = {};
840
+ for (const key in args[index]) {
841
+ if (typeof args[index][key] !== "number") continue;
842
+ schema.bits[key] = args[index][key];
843
+ }
844
+ break;
845
+ case "callback": {
846
+ const callback = schema.callback = args[index];
847
+ callback["toJSON"] ||= () => callback.toString();
848
+ break;
849
+ }
850
+ case "constructor": {
851
+ const constructor = schema.constructor = args[index];
852
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
853
+ break;
854
+ }
855
+ default: schema[key] = args[index];
856
+ }
857
+ });
858
+ if (name === "object" || name === "dict") schema.meta.default = {};
859
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
860
+ else if (name === "bitset") schema.meta.default = 0;
861
+ return schema;
862
+ } });
863
+ }
864
+ defineMethod("is", ["constructor"], ({ constructor }) => {
865
+ if (typeof constructor === "function") return constructor.name;
866
+ else return constructor;
867
+ });
868
+ defineMethod("any", [], () => "any");
869
+ defineMethod("never", [], () => "never");
870
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
871
+ defineMethod("string", [], () => "string");
872
+ defineMethod("number", [], () => "number");
873
+ defineMethod("boolean", [], () => "boolean");
874
+ defineMethod("bitset", ["bits"], () => "bitset");
875
+ defineMethod("function", [], () => "function");
876
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
877
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
878
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
879
+ defineMethod("object", ["dict"], ({ dict }) => {
880
+ if (Object.keys(dict).length === 0) return "{}";
881
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
882
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
883
+ }).join(", ")} }`;
884
+ });
885
+ defineMethod("union", ["list"], ({ list }, inline) => {
886
+ const result = list.map(({ toString: format }) => format()).join(" | ");
887
+ return inline ? `(${result})` : result;
888
+ });
889
+ defineMethod("intersect", ["list"], ({ list }) => {
890
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
891
+ });
892
+ defineMethod("transform", [
893
+ "inner",
894
+ "callback",
895
+ "preserve"
896
+ ], ({ inner }, isInner) => inner.toString(isInner));
897
+ //#endregion
898
+ //#region lib/types/locale-settings.js
899
+ /** Locale preference stored in the Host user-settings document. */
900
+ /** Settings namespace owned by the locale plugin. */
901
+ const LOCALE_SETTINGS_NAMESPACE = "locale";
902
+ /** Field carrying an explicit locale selection; absence delegates to the browser. */
903
+ const LOCALE_PREFERENCE_FIELD = "preference";
904
+ /** Accepted BCP 47-style language ids. */
905
+ const LOCALE_ID_PATTERN = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/u;
906
+ /** Locale identifiers shipped by the browser client. */
907
+ const LOCALE_IDS = ["zh", "en"];
908
+ Schema.object({ [LOCALE_PREFERENCE_FIELD]: Schema.string().pattern(LOCALE_ID_PATTERN).required(false) });
909
+ //#endregion
910
+ //#region lib/types/locales/zh.js
911
+ /** zh base dictionary for the common namespace: cross-feature standard words. */
912
+ const zh = {
913
+ "ok": "确定",
914
+ "cancel": "取消",
915
+ "close": "关闭",
916
+ "copy": "复制",
917
+ "copied": "复制成功",
918
+ "copy.failed": "复制失败",
919
+ "copy.value": "复制值",
920
+ "copy.json": "复制 JSON",
921
+ "copy.path": "复制属性路径",
922
+ "copy.prettyJson": "复制格式化 JSON",
923
+ "copy.compactJson": "复制紧凑 JSON",
924
+ "copy.optionsHint": "{action};右键点击可选择复制方式",
925
+ "retry": "重试",
926
+ "loading": "加载中…",
927
+ "load.failed": "加载失败",
928
+ "submit": "提交",
929
+ "submitting": "正在提交…",
930
+ "next": "下一步",
931
+ "previous": "上一步",
932
+ "skip": "跳过",
933
+ "delete": "删除",
934
+ "edit": "编辑",
935
+ "save": "保存",
936
+ "search": "搜索",
937
+ "more": "更多",
938
+ "collapse": "收起",
939
+ "expand": "展开",
940
+ "back": "返回",
941
+ "brand.localBuild": "QiLin",
942
+ "unknown": "未知",
943
+ "none": "无",
944
+ "truncated": "已截断",
945
+ "json.label": "JSON",
946
+ "markdown.footnotes": "脚注",
947
+ "markdown.diagram": "Mermaid 图",
948
+ "markdown.enlarged": "Mermaid 图(放大)",
949
+ "markdown.truncatedCharacters": "… 已截断,共 {total} 字符",
950
+ "number.thousand": "{value}K",
951
+ "number.million": "{value}M"
952
+ };
953
+ //#endregion
954
+ //#region lib/types/locales/en.js
955
+ /** en base dictionary for the common namespace, checked complete against the zh key set. */
956
+ const en = {
957
+ "ok": "OK",
958
+ "cancel": "Cancel",
959
+ "close": "Close",
960
+ "copy": "Copy",
961
+ "copied": "Copied",
962
+ "copy.failed": "Copy failed",
963
+ "copy.value": "Copy value",
964
+ "copy.json": "Copy JSON",
965
+ "copy.path": "Copy property path",
966
+ "copy.prettyJson": "Copy pretty JSON",
967
+ "copy.compactJson": "Copy compact JSON",
968
+ "copy.optionsHint": "{action}; right-click for copy options",
969
+ "retry": "Retry",
970
+ "loading": "Loading…",
971
+ "load.failed": "Failed to load",
972
+ "submit": "Submit",
973
+ "submitting": "Submitting…",
974
+ "next": "Next",
975
+ "previous": "Previous",
976
+ "skip": "Skip",
977
+ "delete": "Delete",
978
+ "edit": "Edit",
979
+ "save": "Save",
980
+ "search": "Search",
981
+ "more": "More",
982
+ "collapse": "Collapse",
983
+ "expand": "Expand",
984
+ "back": "Back",
985
+ "brand.localBuild": "QiLin",
986
+ "unknown": "Unknown",
987
+ "none": "None",
988
+ "truncated": "Truncated",
989
+ "json.label": "JSON",
990
+ "markdown.footnotes": "Footnotes",
991
+ "markdown.diagram": "Mermaid diagram",
992
+ "markdown.enlarged": "Mermaid diagram (enlarged)",
993
+ "markdown.truncatedCharacters": "… truncated at {total} characters",
994
+ "number.thousand": "{value}K",
995
+ "number.million": "{value}M"
996
+ };
997
+ //#endregion
998
+ //#region lib/types/client/index.js
999
+ /**
1000
+ * English is both the locale the UI opens in when the browser names no registered
1001
+ * language (and for non-browser runs), and the dictionary consulted after the
1002
+ * active locale misses a key. One constant serves both because the shipped
1003
+ * `zh`/`en` dictionaries carry identical key sets, so neither direction can
1004
+ * leave a key unresolved; the residual case points at English rather than
1005
+ * zh because a browser naming no registered language is the reader least
1006
+ * likely to read Chinese.
1007
+ */
1008
+ const FALLBACK_LOCALE = "en";
1009
+ /** Shared namespace for shell-level texts. */
1010
+ const COMMON_NS = "common";
1011
+ /** The two locales and dictionaries shipped by this package. */
1012
+ const BUILT_IN_LOCALE_METADATA = {
1013
+ zh: {
1014
+ label: "中文",
1015
+ fallback: "en"
1016
+ },
1017
+ en: { label: "English" }
1018
+ };
1019
+ const BUILT_IN_LOCALES = Object.freeze(LOCALE_IDS.map((id) => Object.freeze({
1020
+ id,
1021
+ ...BUILT_IN_LOCALE_METADATA[id]
1022
+ })));
1023
+ /** Case-insensitive key for BCP 47-style ids. */
1024
+ function localeKey(value) {
1025
+ return value.toLowerCase();
1026
+ }
1027
+ /** Validate and detach a language-pack contribution from its mutable input. */
1028
+ function normalizeLanguage(input) {
1029
+ if (!LOCALE_ID_PATTERN.test(input.id)) throw new Error(`locale id "${input.id}" is not a BCP 47-style tag`);
1030
+ if (input.label.trim() === "") throw new Error("locale label must not be empty");
1031
+ if (!LOCALE_ID_PATTERN.test(input.fallback)) throw new Error(`locale fallback "${input.fallback}" is not a BCP 47-style tag`);
1032
+ return Object.freeze({
1033
+ id: input.id,
1034
+ label: input.label,
1035
+ fallback: input.fallback
1036
+ });
1037
+ }
1038
+ /**
1039
+ * Point `<html lang>` at the active locale, keeping the served document in
1040
+ * sync with locale snapshot changes.
1041
+ * @param snapshot - current locale state, including the active definition.
1042
+ */
1043
+ function syncDocumentLanguage(snapshot) {
1044
+ if (typeof document === "undefined") return;
1045
+ document.documentElement.lang = snapshot.active === "zh" ? "zh-CN" : snapshot.active;
1046
+ }
1047
+ /**
1048
+ * Dictionary registry plus locale preference. Lookup walks the active
1049
+ * language's declared fallback chain in the entry namespace, then repeats it
1050
+ * in the shared common namespace before showing the key itself. Reads go
1051
+ * through {@link getLocale}; preferences change only through
1052
+ * {@link setLocale}, while language packs extend the catalog through
1053
+ * {@link addLanguage}. Continuous sync uses the `locale/change` event or
1054
+ * the LocaleFace getSnapshot/subscribe pair installed through
1055
+ * `ctx.slots.installLocale`.
1056
+ */
1057
+ var LocaleRuntime = class {
1058
+ dicts = /* @__PURE__ */ new Map();
1059
+ bound = /* @__PURE__ */ new Map();
1060
+ catalog = /* @__PURE__ */ new Map();
1061
+ fallbackChains = /* @__PURE__ */ new Map();
1062
+ snapshot;
1063
+ listeners = /* @__PURE__ */ new Set();
1064
+ ctx;
1065
+ host;
1066
+ /** Browser-derived locale standing wherever no explicit Host selection does. */
1067
+ provisional;
1068
+ /** Last explicit selection, including one awaiting an external registration. */
1069
+ preference;
1070
+ /**
1071
+ * @param ctx - owning context (change events are emitted on it; the scope
1072
+ * listener is released through ctx.effect on dispose).
1073
+ * @param host - durable preference scope owned by the providing plugin;
1074
+ * absent compositions (standalone dictionary registries) stay process-local.
1075
+ */
1076
+ constructor(ctx, host) {
1077
+ this.ctx = ctx;
1078
+ this.host = host;
1079
+ for (const locale of BUILT_IN_LOCALES) this.catalog.set(localeKey(locale.id), locale);
1080
+ const locales = this.localeList();
1081
+ this.provisional = resolveInitialLocale(locales);
1082
+ this.snapshot = Object.freeze({
1083
+ active: this.provisional,
1084
+ locales,
1085
+ revision: 0
1086
+ });
1087
+ if (host !== void 0) {
1088
+ ctx.effect(() => host.subscribe(() => {
1089
+ this.adopt(host);
1090
+ }), "locale: settings scope adoption");
1091
+ this.adopt(host);
1092
+ }
1093
+ }
1094
+ /**
1095
+ * Read the current immutable locale snapshot.
1096
+ * @returns the current snapshot (stable reference until the next change).
1097
+ */
1098
+ getLocale() {
1099
+ return this.snapshot;
1100
+ }
1101
+ /**
1102
+ * Resolve package text through the active language's declared fallback chain.
1103
+ * Plain strings stay verbatim; maps do not consult registered dictionaries.
1104
+ * @param text - package text whose locale keys are lowercase and include English.
1105
+ * @returns the first available translation, including an empty string.
1106
+ */
1107
+ resolveText(text) {
1108
+ if (typeof text === "string") return text;
1109
+ return this.fallbackChain(this.snapshot.active).reduceRight((resolved, locale) => text[localeKey(locale)] ?? resolved, text.en);
1110
+ }
1111
+ /**
1112
+ * LocaleFace getSnapshot: the current snapshot (carries `revision`; stable
1113
+ * reference between changes, uSES-safe).
1114
+ * @returns the current snapshot.
1115
+ */
1116
+ getSnapshot() {
1117
+ return this.snapshot;
1118
+ }
1119
+ /**
1120
+ * LocaleFace subscribe: notified on every snapshot change (locale switch
1121
+ * or dictionary registration — registrations bump the revision so already
1122
+ * rendered outlets pick up late-arriving dictionaries and locale definitions).
1123
+ * @param fn - change callback.
1124
+ * @returns unsubscribe.
1125
+ */
1126
+ subscribe(fn) {
1127
+ this.listeners.add(fn);
1128
+ return () => {
1129
+ this.listeners.delete(fn);
1130
+ };
1131
+ }
1132
+ /**
1133
+ * Switch the active locale — the only user preference write entry.
1134
+ *
1135
+ * The durable write happens even when the id already matches the active
1136
+ * locale, because the active value may be a provisional browser-derived or
1137
+ * fallback resolution that nothing has stored yet. Picking the language
1138
+ * already on screen is still an explicit choice, and it must survive a
1139
+ * different browser sharing the same QILIN home. Only the render notification
1140
+ * is conditional: republishing an unchanged locale would churn every
1141
+ * subscriber for nothing.
1142
+ * @param id - a registered locale id; unknown ids throw.
1143
+ */
1144
+ setLocale(id) {
1145
+ const match = this.catalog.get(localeKey(id));
1146
+ if (match === void 0) throw new Error(`locale "${id}" is not registered`);
1147
+ this.preference = match.id;
1148
+ if (this.snapshot.active !== match.id) this.publish(match.id, true);
1149
+ this.host?.set(LOCALE_PREFERENCE_FIELD, match.id);
1150
+ }
1151
+ /**
1152
+ * Add one selectable language to the shared catalog. Its fallback must
1153
+ * already be registered, and following fallback definitions must terminate
1154
+ * at English. Dictionaries may register before or after this definition.
1155
+ * Registration rechecks an unresolved Host preference and the browser's
1156
+ * ordered language list. The caller owns the returned disposer; removing an
1157
+ * active language falls back without clearing the stored id.
1158
+ * @param input - stable id, self-described label, and fallback language id.
1159
+ * @returns idempotent disposer removing this exact definition.
1160
+ * @throws when fields are malformed, the id is occupied, or the fallback
1161
+ * target is unknown or creates a cycle.
1162
+ */
1163
+ addLanguage(input) {
1164
+ const candidate = normalizeLanguage(input);
1165
+ const key = localeKey(candidate.id);
1166
+ if (this.catalog.has(key)) throw new Error(`locale "${candidate.id}" is already registered`);
1167
+ const fallback = this.catalog.get(localeKey(candidate.fallback));
1168
+ if (fallback === void 0) throw new Error(`locale fallback "${candidate.fallback}" is not registered`);
1169
+ const language = Object.freeze({
1170
+ ...candidate,
1171
+ fallback: fallback.id
1172
+ });
1173
+ this.catalog.set(key, language);
1174
+ try {
1175
+ this.assertFallbackChain(language.id);
1176
+ } catch (error) {
1177
+ this.catalog.delete(key);
1178
+ throw error;
1179
+ }
1180
+ this.publishCatalog();
1181
+ return () => {
1182
+ if (this.catalog.get(key) !== language) return;
1183
+ this.catalog.delete(key);
1184
+ this.publishCatalog();
1185
+ };
1186
+ }
1187
+ /**
1188
+ * Adopt the scope's accepted durable selection without writing it back; an
1189
+ * absent selection returns to the browser-derived locale.
1190
+ * @param host - the constructor-narrowed scope driving this adoption.
1191
+ */
1192
+ adopt(host) {
1193
+ const section = host.getSnapshot().value;
1194
+ if (section === void 0) return;
1195
+ this.preference = section.preference;
1196
+ const target = this.resolveActive();
1197
+ if (this.snapshot.active === target) return;
1198
+ this.publish(target, true);
1199
+ }
1200
+ /** Recompute browser fallback and publish the current catalog. */
1201
+ publishCatalog() {
1202
+ this.fallbackChains.clear();
1203
+ const locales = this.localeList();
1204
+ this.provisional = resolveInitialLocale(locales);
1205
+ const active = this.resolveActive();
1206
+ this.publish(active, active !== this.snapshot.active, locales);
1207
+ }
1208
+ /** Resolve an explicit preference only while its definition is available. */
1209
+ resolveActive() {
1210
+ if (this.preference === void 0) return this.provisional;
1211
+ return this.catalog.get(localeKey(this.preference))?.id ?? this.provisional;
1212
+ }
1213
+ /** Snapshot the catalog in registration order. */
1214
+ localeList() {
1215
+ return Object.freeze([...this.catalog.values()]);
1216
+ }
1217
+ /** Fail a new definition whose complete fallback path does not reach English. */
1218
+ assertFallbackChain(start) {
1219
+ const seen = /* @__PURE__ */ new Set();
1220
+ let current = this.catalog.get(localeKey(start));
1221
+ while (current !== void 0) {
1222
+ const key = localeKey(current.id);
1223
+ if (seen.has(key)) throw new Error(`locale fallback cycle includes "${current.id}"`);
1224
+ seen.add(key);
1225
+ if (key === localeKey("en")) return;
1226
+ /* v8 ignore next -- English is the only built-in terminal and every
1227
+ * language accepted by addLanguage has a required fallback. */
1228
+ if (current.fallback === void 0) throw new Error(`locale "${current.id}" fallback chain does not reach "en"`);
1229
+ const next = this.catalog.get(localeKey(current.fallback));
1230
+ if (next === void 0) throw new Error(`locale fallback "${current.fallback}" is not registered`);
1231
+ current = next;
1232
+ }
1233
+ }
1234
+ /** Resolve a lookup chain, falling directly to English across an unload gap. */
1235
+ fallbackChain(start) {
1236
+ const startKey = localeKey(start);
1237
+ const cached = this.fallbackChains.get(startKey);
1238
+ if (cached !== void 0) return cached;
1239
+ const chain = [];
1240
+ const seen = /* @__PURE__ */ new Set();
1241
+ let current = this.catalog.get(startKey);
1242
+ while (current !== void 0 && !seen.has(localeKey(current.id))) {
1243
+ const key = localeKey(current.id);
1244
+ seen.add(key);
1245
+ chain.push(current.id);
1246
+ current = current.fallback === void 0 ? void 0 : this.catalog.get(localeKey(current.fallback));
1247
+ }
1248
+ if (!seen.has(localeKey("en"))) chain.push("en");
1249
+ const resolved = Object.freeze(chain);
1250
+ this.fallbackChains.set(startKey, resolved);
1251
+ return resolved;
1252
+ }
1253
+ register(ns, localeOrDicts, dict) {
1254
+ const pairs = typeof localeOrDicts === "string" ? [[localeOrDicts, dict]] : Object.entries(localeOrDicts);
1255
+ for (const [locale] of pairs) if (!LOCALE_ID_PATTERN.test(locale)) throw new Error(`locale id "${locale}" is not a BCP 47-style tag`);
1256
+ let locales = this.dicts.get(ns);
1257
+ if (!locales) {
1258
+ locales = /* @__PURE__ */ new Map();
1259
+ this.dicts.set(ns, locales);
1260
+ }
1261
+ for (const [locale] of pairs) if (locales.has(localeKey(locale))) throw new Error(`locale namespace "${ns}" already has locale "${locale}"`);
1262
+ for (const [locale, entries] of pairs) locales.set(localeKey(locale), entries);
1263
+ this.publish(this.snapshot.active, false);
1264
+ return () => {
1265
+ const owner = this.dicts.get(ns);
1266
+ /* v8 ignore next -- defensive: a namespace's locales map is created on
1267
+ * first register and never removed, so the disposer always finds it. */
1268
+ if (!owner) return;
1269
+ let removed = false;
1270
+ for (const [locale, entries] of pairs) {
1271
+ const key = localeKey(locale);
1272
+ if (owner.get(key) === entries) {
1273
+ owner.delete(key);
1274
+ removed = true;
1275
+ }
1276
+ }
1277
+ if (removed) this.publish(this.snapshot.active, false);
1278
+ };
1279
+ }
1280
+ bind(ns) {
1281
+ let t = this.bound.get(ns);
1282
+ if (!t) {
1283
+ t = (key, params) => this.translate(ns, key, params);
1284
+ this.bound.set(ns, t);
1285
+ return t;
1286
+ }
1287
+ return t;
1288
+ }
1289
+ translate(ns, key, params) {
1290
+ const chain = this.fallbackChain(this.snapshot.active);
1291
+ const template = this.lookup(ns, key, chain) ?? (ns !== "common" ? this.lookup("common", key, chain) : void 0) ?? key;
1292
+ if (!params) return template;
1293
+ return template.replace(/\{(\w+)\}/g, (match, name) => name in params ? String(params[name]) : match);
1294
+ }
1295
+ lookup(ns, key, chain) {
1296
+ const locales = this.dicts.get(ns);
1297
+ for (const locale of chain) {
1298
+ const value = locales?.get(localeKey(locale))?.[key];
1299
+ if (value !== void 0) return value;
1300
+ }
1301
+ }
1302
+ /**
1303
+ * Advance the snapshot revision and notify LocaleFace subscribers (render
1304
+ * refresh). Only an active-locale switch additionally emits
1305
+ * `locale/change` — dictionary registrations stay off the event so
1306
+ * registration-heavy boot cannot storm event listeners (which may
1307
+ * re-register slots in response).
1308
+ */
1309
+ publish(active, localeChanged, locales = this.snapshot.locales) {
1310
+ this.snapshot = Object.freeze({
1311
+ active,
1312
+ locales,
1313
+ revision: this.snapshot.revision + 1
1314
+ });
1315
+ if (localeChanged) this.ctx.emit("locale/change", this.snapshot);
1316
+ for (const fn of [...this.listeners]) try {
1317
+ fn();
1318
+ } catch (error) {
1319
+ console.error("locale subscriber crashed:", error);
1320
+ }
1321
+ }
1322
+ };
1323
+ /**
1324
+ * The browser's own language wins over {@link FALLBACK_LOCALE}; an explicit
1325
+ * Host preference may replace this provisional value after plugin activation.
1326
+ */
1327
+ function resolveInitialLocale(locales) {
1328
+ return detectBrowserLocale(locales) ?? "en";
1329
+ }
1330
+ /**
1331
+ * The first registered locale the browser asks for. Each browser tag first
1332
+ * matches a locale id exactly, then its primary subtag, so an exact regional
1333
+ * registration wins before a language-wide fallback.
1334
+ * `window` is the browser test, not `navigator`: Node exposes a global
1335
+ * `navigator` reporting the machine's own language, which must not decide the
1336
+ * locale for non-browser runs. `navigator.language` trails the ordered
1337
+ * `languages` list and covers hosts exposing only the single tag.
1338
+ * @param locales - definitions currently available to the browser.
1339
+ * @returns the first matching locale id, or undefined.
1340
+ */
1341
+ function detectBrowserLocale(locales) {
1342
+ if (typeof window === "undefined") return void 0;
1343
+ const languages = navigator.languages;
1344
+ for (const tag of [...languages ?? [], navigator.language]) {
1345
+ const requested = localeKey(tag);
1346
+ const exact = locales.find((locale) => localeKey(locale.id) === requested);
1347
+ if (exact !== void 0) return exact.id;
1348
+ const primary = requested.split("-")[0];
1349
+ const match = locales.find((locale) => localeKey(locale.id).split("-")[0] === primary);
1350
+ if (match !== void 0) return match.id;
1351
+ }
1352
+ }
1353
+ /** Required services: slot registration plus the settings transport. */
1354
+ const inject = [
1355
+ "slots",
1356
+ "remote",
1357
+ "configForms"
1358
+ ];
1359
+ /**
1360
+ * Client plugin body: provide the locale service with base dictionaries and
1361
+ * keep `<html lang>` in step with the active locale. The account menu is the
1362
+ * surface that switches languages; this plugin owns the preference and its
1363
+ * registry, not a settings row.
1364
+ * @param ctx - client cordis context.
1365
+ */
1366
+ function apply(ctx) {
1367
+ const locale = new LocaleRuntime(ctx, ctx.configForms.get(LOCALE_SETTINGS_NAMESPACE));
1368
+ locale.register(COMMON_NS, {
1369
+ zh,
1370
+ en
1371
+ });
1372
+ ctx.provide("locale", locale);
1373
+ ctx.slots.installLocale(locale);
1374
+ const sync = () => {
1375
+ syncDocumentLanguage(locale.getSnapshot());
1376
+ };
1377
+ ctx.effect(() => locale.subscribe(sync), "locale: document language synchronization");
1378
+ sync();
1379
+ }
1380
+ //#endregion
1381
+ exports.COMMON_NS = COMMON_NS;
1382
+ exports.FALLBACK_LOCALE = FALLBACK_LOCALE;
1383
+ exports.LocaleRuntime = LocaleRuntime;
1384
+ exports.apply = apply;
1385
+ exports.inject = inject;
1386
+ return module.exports;
1387
+ }
1388
+ });
1389
+
1390
+ //# sourceMappingURL=client.js.map