@qilin-agent/client-connection 0.0.0-stage → 3.1.4
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/LICENSE +21 -0
- package/README.i18n.yaml +37 -0
- package/README.md +86 -2
- package/README.zh.md +87 -0
- package/lib/client.js +1459 -0
- package/lib/index.js +983 -0
- package/lib/types/api-path.d.ts +7 -0
- package/lib/types/api-request-trust.d.ts +45 -0
- package/lib/types/browser-auth.d.ts +68 -0
- package/lib/types/client/api.d.ts +14 -0
- package/lib/types/client/connection.d.ts +80 -0
- package/lib/types/client/index.d.ts +136 -0
- package/lib/types/client/random-uuid.d.ts +7 -0
- package/lib/types/client/rpc.d.ts +14 -0
- package/lib/types/http-bridge.d.ts +21 -0
- package/lib/types/index.d.ts +58 -0
- package/lib/types/loopback-hostname.d.ts +12 -0
- package/lib/types/operator-peer.d.ts +23 -0
- package/lib/types/recovery-config.d.ts +27 -0
- package/lib/types/rpc-host.d.ts +70 -0
- package/lib/types/rpc-schema.d.ts +30 -0
- package/lib/types/rpc.d.ts +262 -0
- package/lib/types/web-entry.d.ts +9 -0
- package/package.json +65 -3
package/lib/client.js
ADDED
|
@@ -0,0 +1,1459 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: "@qilin-agent/client-connection",
|
|
3
|
+
factory: (require) => {
|
|
4
|
+
var module = { exports: {} };
|
|
5
|
+
var exports = module.exports;
|
|
6
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
7
|
+
//#region ../../../vendor/cosmokit/lib/index.js
|
|
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
|
+
/** Shared config references used by schema validators and plugin runtimes. */
|
|
32
|
+
const write = Symbol.for("cosmokit.volatile.write");
|
|
33
|
+
function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
|
|
34
|
+
if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
|
|
35
|
+
if (value === null || typeof value !== "object") return value;
|
|
36
|
+
if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
|
|
37
|
+
ancestors.add(value);
|
|
38
|
+
try {
|
|
39
|
+
if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
|
|
40
|
+
if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
|
|
41
|
+
return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
|
|
42
|
+
} finally {
|
|
43
|
+
ancestors.delete(value);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Create a detached reference containing an immutable copy of the supplied data.
|
|
48
|
+
* @param value - validated config data; class instances and functions are unsupported.
|
|
49
|
+
* @returns a reference whose value is updated only by its owning runtime.
|
|
50
|
+
*/
|
|
51
|
+
function createVolatile(value) {
|
|
52
|
+
let current = snapshot(value);
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
get: () => current,
|
|
55
|
+
[write]: (value) => {
|
|
56
|
+
current = value;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Identify references across ESM/CJS copies of the shared library.
|
|
62
|
+
* @param value - a parsed config value.
|
|
63
|
+
* @returns whether the value implements the shared reference protocol.
|
|
64
|
+
*/
|
|
65
|
+
function isVolatile(value) {
|
|
66
|
+
return typeof value === "object" && value !== null && write in value;
|
|
67
|
+
}
|
|
68
|
+
/** Test values using `instanceof` with a `toStringTag` fallback. */
|
|
69
|
+
function is(type, value) {
|
|
70
|
+
if (arguments.length === 1) return (value) => is(type, value);
|
|
71
|
+
return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
|
|
72
|
+
}
|
|
73
|
+
function isArrayBufferLike(value) {
|
|
74
|
+
return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
|
|
75
|
+
}
|
|
76
|
+
function isArrayBufferSource(value) {
|
|
77
|
+
return isArrayBufferLike(value) || ArrayBuffer.isView(value);
|
|
78
|
+
}
|
|
79
|
+
/** Binary source detection and base64/hex conversion helpers. */
|
|
80
|
+
var Binary;
|
|
81
|
+
(function(Binary) {
|
|
82
|
+
Binary.is = isArrayBufferLike;
|
|
83
|
+
Binary.isSource = isArrayBufferSource;
|
|
84
|
+
function fromSource(source) {
|
|
85
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
86
|
+
else return source;
|
|
87
|
+
}
|
|
88
|
+
Binary.fromSource = fromSource;
|
|
89
|
+
function toBase64(source) {
|
|
90
|
+
source = fromSource(source);
|
|
91
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
|
|
92
|
+
let binary = "";
|
|
93
|
+
const bytes = new Uint8Array(source);
|
|
94
|
+
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
|
|
95
|
+
return btoa(binary);
|
|
96
|
+
}
|
|
97
|
+
Binary.toBase64 = toBase64;
|
|
98
|
+
function fromBase64(source) {
|
|
99
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
|
|
100
|
+
return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
|
|
101
|
+
}
|
|
102
|
+
Binary.fromBase64 = fromBase64;
|
|
103
|
+
function toHex(source) {
|
|
104
|
+
source = fromSource(source);
|
|
105
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
|
|
106
|
+
return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
107
|
+
}
|
|
108
|
+
Binary.toHex = toHex;
|
|
109
|
+
function fromHex(source) {
|
|
110
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
|
|
111
|
+
const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
|
|
112
|
+
const buffer = [];
|
|
113
|
+
for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
|
|
114
|
+
return Uint8Array.from(buffer).buffer;
|
|
115
|
+
}
|
|
116
|
+
Binary.fromHex = fromHex;
|
|
117
|
+
})(Binary || (Binary = {}));
|
|
118
|
+
Binary.fromBase64;
|
|
119
|
+
Binary.toBase64;
|
|
120
|
+
Binary.fromHex;
|
|
121
|
+
Binary.toHex;
|
|
122
|
+
/** Deep-clone common JavaScript values while preserving prototypes and cycles. */
|
|
123
|
+
function clone(source, refs = /* @__PURE__ */ new Map()) {
|
|
124
|
+
if (!source || typeof source !== "object") return source;
|
|
125
|
+
if (is("Date", source)) return new Date(source.valueOf());
|
|
126
|
+
if (is("RegExp", source)) return new RegExp(source.source, source.flags);
|
|
127
|
+
if (isArrayBufferLike(source)) return source.slice(0);
|
|
128
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
129
|
+
const cached = refs.get(source);
|
|
130
|
+
if (cached) return cached;
|
|
131
|
+
if (Array.isArray(source)) {
|
|
132
|
+
const result = [];
|
|
133
|
+
refs.set(source, result);
|
|
134
|
+
source.forEach((value, index) => {
|
|
135
|
+
result[index] = Reflect.apply(clone, null, [value, refs]);
|
|
136
|
+
});
|
|
137
|
+
return result;
|
|
138
|
+
}
|
|
139
|
+
const result = Object.create(Object.getPrototypeOf(source));
|
|
140
|
+
refs.set(source, result);
|
|
141
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
142
|
+
const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
|
|
143
|
+
if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
|
|
144
|
+
Reflect.defineProperty(result, key, descriptor);
|
|
145
|
+
}
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Compare values recursively, treating two volatile references as equal regardless of value.
|
|
150
|
+
* Strict comparison distinguishes null/undefined, treats opaque objects by identity,
|
|
151
|
+
* compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
|
|
152
|
+
* @param a - first value.
|
|
153
|
+
* @param b - second value.
|
|
154
|
+
* @param strict - whether to require strict data equality outside volatile references.
|
|
155
|
+
* @returns whether the values compare equal.
|
|
156
|
+
*/
|
|
157
|
+
function deepEqual(a, b, strict) {
|
|
158
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
159
|
+
function compare(a, b) {
|
|
160
|
+
if (a === b) return true;
|
|
161
|
+
if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);
|
|
162
|
+
if (!strict && isNullable(a) && isNullable(b)) return true;
|
|
163
|
+
if (typeof a !== typeof b || typeof a !== "object" || !a || !b) return false;
|
|
164
|
+
if (ancestors.has(a)) return false;
|
|
165
|
+
function check(test, then) {
|
|
166
|
+
return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
|
|
167
|
+
}
|
|
168
|
+
ancestors.add(a);
|
|
169
|
+
try {
|
|
170
|
+
return check(Array.isArray, (a, b) => {
|
|
171
|
+
if (a.length !== b.length) return false;
|
|
172
|
+
for (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;
|
|
173
|
+
return true;
|
|
174
|
+
}) ?? 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) => {
|
|
175
|
+
if (a.byteLength !== b.byteLength) return false;
|
|
176
|
+
const viewA = new Uint8Array(a);
|
|
177
|
+
const viewB = new Uint8Array(b);
|
|
178
|
+
for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
|
|
179
|
+
return true;
|
|
180
|
+
}) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
|
|
181
|
+
...a,
|
|
182
|
+
...b
|
|
183
|
+
}).every((key) => compare(a[key], b[key])));
|
|
184
|
+
} finally {
|
|
185
|
+
ancestors.delete(a);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return compare(a, b);
|
|
189
|
+
}
|
|
190
|
+
/** Time constants plus parsing and formatting helpers. */
|
|
191
|
+
var Time;
|
|
192
|
+
(function(Time) {
|
|
193
|
+
Time.millisecond = 1;
|
|
194
|
+
Time.second = 1e3;
|
|
195
|
+
Time.minute = Time.second * 60;
|
|
196
|
+
Time.hour = Time.minute * 60;
|
|
197
|
+
Time.day = Time.hour * 24;
|
|
198
|
+
Time.week = Time.day * 7;
|
|
199
|
+
let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
|
|
200
|
+
function setTimezoneOffset(offset) {
|
|
201
|
+
timezoneOffset = offset;
|
|
202
|
+
}
|
|
203
|
+
Time.setTimezoneOffset = setTimezoneOffset;
|
|
204
|
+
function getTimezoneOffset() {
|
|
205
|
+
return timezoneOffset;
|
|
206
|
+
}
|
|
207
|
+
Time.getTimezoneOffset = getTimezoneOffset;
|
|
208
|
+
function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
|
|
209
|
+
if (typeof date === "number") date = new Date(date);
|
|
210
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
211
|
+
return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
|
|
212
|
+
}
|
|
213
|
+
Time.getDateNumber = getDateNumber;
|
|
214
|
+
function fromDateNumber(value, offset) {
|
|
215
|
+
const date = new Date(value * Time.day);
|
|
216
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
217
|
+
return new Date(+date + offset * Time.minute);
|
|
218
|
+
}
|
|
219
|
+
Time.fromDateNumber = fromDateNumber;
|
|
220
|
+
const numeric = /\d+(?:\.\d+)?/.source;
|
|
221
|
+
const timeRegExp = new RegExp(`^${[
|
|
222
|
+
"w(?:eek(?:s)?)?",
|
|
223
|
+
"d(?:ay(?:s)?)?",
|
|
224
|
+
"h(?:our(?:s)?)?",
|
|
225
|
+
"m(?:in(?:ute)?(?:s)?)?",
|
|
226
|
+
"s(?:ec(?:ond)?(?:s)?)?"
|
|
227
|
+
].map((unit) => `(${numeric}${unit})?`).join("")}$`);
|
|
228
|
+
function parseTime(source) {
|
|
229
|
+
const capture = timeRegExp.exec(source);
|
|
230
|
+
if (!capture) return 0;
|
|
231
|
+
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);
|
|
232
|
+
}
|
|
233
|
+
Time.parseTime = parseTime;
|
|
234
|
+
function parseDate(date) {
|
|
235
|
+
const parsed = parseTime(date);
|
|
236
|
+
if (parsed) date = Date.now() + parsed;
|
|
237
|
+
else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
|
|
238
|
+
else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
|
|
239
|
+
return date ? new Date(date) : /* @__PURE__ */ new Date();
|
|
240
|
+
}
|
|
241
|
+
Time.parseDate = parseDate;
|
|
242
|
+
function format(ms) {
|
|
243
|
+
const abs = Math.abs(ms);
|
|
244
|
+
if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
|
|
245
|
+
else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
|
|
246
|
+
else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
|
|
247
|
+
else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
|
|
248
|
+
return ms + "ms";
|
|
249
|
+
}
|
|
250
|
+
Time.format = format;
|
|
251
|
+
function toDigits(source, length = 2) {
|
|
252
|
+
return source.toString().padStart(length, "0");
|
|
253
|
+
}
|
|
254
|
+
Time.toDigits = toDigits;
|
|
255
|
+
function template(template, time = /* @__PURE__ */ new Date()) {
|
|
256
|
+
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));
|
|
257
|
+
}
|
|
258
|
+
Time.template = template;
|
|
259
|
+
})(Time || (Time = {}));
|
|
260
|
+
//#endregion
|
|
261
|
+
//#region ../../../vendor/schemastery/lib/index.mjs
|
|
262
|
+
const kSchema = Symbol.for("schemastery");
|
|
263
|
+
const kValidationError = Symbol.for("ValidationError");
|
|
264
|
+
globalThis.__schemastery_index__ ??= 0;
|
|
265
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
266
|
+
var ValidationError = class extends TypeError {
|
|
267
|
+
options;
|
|
268
|
+
name = "ValidationError";
|
|
269
|
+
constructor(message, options) {
|
|
270
|
+
let prefix = "$";
|
|
271
|
+
for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
|
|
272
|
+
else if (typeof segment === "number") prefix += "[" + segment + "]";
|
|
273
|
+
else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
|
|
274
|
+
if (prefix.startsWith(".")) prefix = prefix.slice(1);
|
|
275
|
+
super((prefix === "$" ? "" : `${prefix} `) + message);
|
|
276
|
+
this.options = options;
|
|
277
|
+
}
|
|
278
|
+
static is(error) {
|
|
279
|
+
return !!error?.[kValidationError];
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
|
|
283
|
+
const Schema = function(options) {
|
|
284
|
+
const schema = function(data, options = {}) {
|
|
285
|
+
return Schema.resolve(data, schema, options)[0];
|
|
286
|
+
};
|
|
287
|
+
if (options.refs) {
|
|
288
|
+
const refs = mapValues(options.refs, (options) => new Schema(options));
|
|
289
|
+
const getRef = (uid) => refs[uid];
|
|
290
|
+
for (const key in refs) {
|
|
291
|
+
const options = refs[key];
|
|
292
|
+
options.sKey = getRef(options.sKey);
|
|
293
|
+
options.inner = getRef(options.inner);
|
|
294
|
+
options.list = options.list && options.list.map(getRef);
|
|
295
|
+
options.dict = options.dict && mapValues(options.dict, getRef);
|
|
296
|
+
}
|
|
297
|
+
return refs[options.uid];
|
|
298
|
+
}
|
|
299
|
+
Object.assign(schema, options);
|
|
300
|
+
if (typeof schema.callback === "string") try {
|
|
301
|
+
schema.callback = new Function("return " + schema.callback)();
|
|
302
|
+
} catch {}
|
|
303
|
+
Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
|
|
304
|
+
Object.setPrototypeOf(schema, Schema.prototype);
|
|
305
|
+
schema.meta ||= {};
|
|
306
|
+
schema.toString = schema.toString.bind(schema);
|
|
307
|
+
return schema;
|
|
308
|
+
};
|
|
309
|
+
Schema.prototype = Object.create(Function.prototype);
|
|
310
|
+
Schema.prototype[kSchema] = true;
|
|
311
|
+
Object.defineProperty(Schema.prototype, "~standard", { get() {
|
|
312
|
+
return {
|
|
313
|
+
version: 1,
|
|
314
|
+
vendor: "schemastery",
|
|
315
|
+
validate: (value) => {
|
|
316
|
+
try {
|
|
317
|
+
return { value: Schema.resolve(value, this, {})[0] };
|
|
318
|
+
} catch (error) {
|
|
319
|
+
if (ValidationError.is(error)) return { issues: [{
|
|
320
|
+
message: error.message,
|
|
321
|
+
path: error.options.path
|
|
322
|
+
}] };
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
} });
|
|
328
|
+
Schema.ValidationError = ValidationError;
|
|
329
|
+
Schema.prototype.toJSON = function toJSON() {
|
|
330
|
+
if (globalThis.__schemastery_refs__) {
|
|
331
|
+
globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
332
|
+
return this.uid;
|
|
333
|
+
}
|
|
334
|
+
globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
335
|
+
globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
336
|
+
const result = {
|
|
337
|
+
uid: this.uid,
|
|
338
|
+
refs: globalThis.__schemastery_refs__
|
|
339
|
+
};
|
|
340
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
341
|
+
return result;
|
|
342
|
+
};
|
|
343
|
+
Schema.prototype.set = function set(key, value) {
|
|
344
|
+
this.dict[key] = value;
|
|
345
|
+
return this;
|
|
346
|
+
};
|
|
347
|
+
Schema.prototype.push = function push(value) {
|
|
348
|
+
this.list.push(value);
|
|
349
|
+
return this;
|
|
350
|
+
};
|
|
351
|
+
function mergeDesc(original, messages) {
|
|
352
|
+
const result = typeof original === "string" ? { "": original } : { ...original };
|
|
353
|
+
for (const locale in messages) {
|
|
354
|
+
const value = messages[locale];
|
|
355
|
+
if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
|
|
356
|
+
else if (typeof value === "string") result[locale] = value;
|
|
357
|
+
}
|
|
358
|
+
return result;
|
|
359
|
+
}
|
|
360
|
+
function getInner(value) {
|
|
361
|
+
return value?.$value ?? value?.$inner;
|
|
362
|
+
}
|
|
363
|
+
function extractKeys(data) {
|
|
364
|
+
return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
|
|
365
|
+
}
|
|
366
|
+
Schema.prototype.i18n = function i18n(messages) {
|
|
367
|
+
const schema = Schema(this);
|
|
368
|
+
const desc = mergeDesc(schema.meta.description, messages);
|
|
369
|
+
if (Object.keys(desc).length) schema.meta.description = desc;
|
|
370
|
+
if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
|
|
371
|
+
return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
|
|
372
|
+
});
|
|
373
|
+
if (schema.list) schema.list = schema.list.map((inner, index) => {
|
|
374
|
+
return inner.i18n(mapValues(messages, (data = {}) => {
|
|
375
|
+
if (Array.isArray(getInner(data))) return getInner(data)[index];
|
|
376
|
+
if (Array.isArray(data)) return data[index];
|
|
377
|
+
return extractKeys(data);
|
|
378
|
+
}));
|
|
379
|
+
});
|
|
380
|
+
if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
|
|
381
|
+
if (getInner(data)) return getInner(data);
|
|
382
|
+
return extractKeys(data);
|
|
383
|
+
}));
|
|
384
|
+
if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
|
|
385
|
+
return schema;
|
|
386
|
+
};
|
|
387
|
+
Schema.prototype.extra = function extra(key, value) {
|
|
388
|
+
const schema = Schema(this);
|
|
389
|
+
schema.meta = {
|
|
390
|
+
...schema.meta,
|
|
391
|
+
[key]: value
|
|
392
|
+
};
|
|
393
|
+
return schema;
|
|
394
|
+
};
|
|
395
|
+
for (const key of [
|
|
396
|
+
"required",
|
|
397
|
+
"disabled",
|
|
398
|
+
"collapse",
|
|
399
|
+
"hidden",
|
|
400
|
+
"loose"
|
|
401
|
+
]) Object.assign(Schema.prototype, { [key](value = true) {
|
|
402
|
+
const schema = Schema(this);
|
|
403
|
+
schema.meta = {
|
|
404
|
+
...schema.meta,
|
|
405
|
+
[key]: value
|
|
406
|
+
};
|
|
407
|
+
return schema;
|
|
408
|
+
} });
|
|
409
|
+
Schema.prototype.deprecated = function deprecated() {
|
|
410
|
+
const schema = Schema(this);
|
|
411
|
+
schema.meta.badges ||= [];
|
|
412
|
+
schema.meta.badges.push({
|
|
413
|
+
text: "deprecated",
|
|
414
|
+
type: "danger"
|
|
415
|
+
});
|
|
416
|
+
return schema;
|
|
417
|
+
};
|
|
418
|
+
Schema.prototype.experimental = function experimental() {
|
|
419
|
+
const schema = Schema(this);
|
|
420
|
+
schema.meta.badges ||= [];
|
|
421
|
+
schema.meta.badges.push({
|
|
422
|
+
text: "experimental",
|
|
423
|
+
type: "warning"
|
|
424
|
+
});
|
|
425
|
+
return schema;
|
|
426
|
+
};
|
|
427
|
+
Schema.prototype.pattern = function pattern(regexp) {
|
|
428
|
+
const schema = Schema(this);
|
|
429
|
+
const pattern = pick(regexp, ["source", "flags"]);
|
|
430
|
+
schema.meta = {
|
|
431
|
+
...schema.meta,
|
|
432
|
+
pattern
|
|
433
|
+
};
|
|
434
|
+
return schema;
|
|
435
|
+
};
|
|
436
|
+
Schema.prototype.simplify = function simplify(value) {
|
|
437
|
+
if (isVolatile(value)) value = value.get();
|
|
438
|
+
if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
|
|
439
|
+
if (isNullable(value)) return value;
|
|
440
|
+
if (this.type === "object" || this.type === "dict") {
|
|
441
|
+
const result = {};
|
|
442
|
+
for (const key in value) {
|
|
443
|
+
const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
|
|
444
|
+
if (this.type === "dict" || !isNullable(item)) result[key] = item;
|
|
445
|
+
}
|
|
446
|
+
if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
|
|
447
|
+
return result;
|
|
448
|
+
} else if (this.type === "array" || this.type === "tuple") {
|
|
449
|
+
const result = [];
|
|
450
|
+
value.forEach((value, index) => {
|
|
451
|
+
const schema = this.type === "array" ? this.inner : this.list[index];
|
|
452
|
+
const item = schema ? schema.simplify(value) : value;
|
|
453
|
+
result.push(item);
|
|
454
|
+
});
|
|
455
|
+
return result;
|
|
456
|
+
} else if (this.type === "intersect") {
|
|
457
|
+
const result = {};
|
|
458
|
+
for (const item of this.list) Object.assign(result, item.simplify(value));
|
|
459
|
+
return result;
|
|
460
|
+
} else if (this.type === "union") for (const schema of this.list) try {
|
|
461
|
+
Schema.resolve(value, schema, {});
|
|
462
|
+
return schema.simplify(value);
|
|
463
|
+
} catch {}
|
|
464
|
+
return value;
|
|
465
|
+
};
|
|
466
|
+
Schema.prototype.toString = function toString(inline) {
|
|
467
|
+
return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
|
|
468
|
+
};
|
|
469
|
+
Schema.prototype.role = function role(role, extra) {
|
|
470
|
+
const schema = Schema(this);
|
|
471
|
+
schema.meta = {
|
|
472
|
+
...schema.meta,
|
|
473
|
+
role,
|
|
474
|
+
extra
|
|
475
|
+
};
|
|
476
|
+
return schema;
|
|
477
|
+
};
|
|
478
|
+
for (const key of [
|
|
479
|
+
"default",
|
|
480
|
+
"link",
|
|
481
|
+
"comment",
|
|
482
|
+
"description",
|
|
483
|
+
"max",
|
|
484
|
+
"min",
|
|
485
|
+
"step"
|
|
486
|
+
]) Object.assign(Schema.prototype, { [key](value) {
|
|
487
|
+
const schema = Schema(this);
|
|
488
|
+
schema.meta = {
|
|
489
|
+
...schema.meta,
|
|
490
|
+
[key]: value
|
|
491
|
+
};
|
|
492
|
+
return schema;
|
|
493
|
+
} });
|
|
494
|
+
Schema.prototype.volatile = function volatile() {
|
|
495
|
+
if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
|
|
496
|
+
return this.extra("volatile", true);
|
|
497
|
+
};
|
|
498
|
+
const resolvers = {};
|
|
499
|
+
const checkedVolatile = Symbol("checked-volatile-schema");
|
|
500
|
+
function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
|
|
501
|
+
const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
|
|
502
|
+
if (states.has(blocked)) return;
|
|
503
|
+
states.add(blocked);
|
|
504
|
+
seen.set(schema, states);
|
|
505
|
+
if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
|
|
506
|
+
const nested = blocked || !!schema.meta?.volatile;
|
|
507
|
+
if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
|
|
508
|
+
if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
|
|
509
|
+
if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
|
|
510
|
+
if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
|
|
511
|
+
}
|
|
512
|
+
Schema.extend = function extend(type, resolve) {
|
|
513
|
+
resolvers[type] = resolve;
|
|
514
|
+
};
|
|
515
|
+
Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
|
|
516
|
+
if (!schema) return [data];
|
|
517
|
+
if (!options[checkedVolatile]) {
|
|
518
|
+
validateVolatileSchema(schema, options.path);
|
|
519
|
+
options = {
|
|
520
|
+
...options,
|
|
521
|
+
[checkedVolatile]: true
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
if (schema.meta?.volatile) {
|
|
525
|
+
const inner = Schema(schema);
|
|
526
|
+
inner.meta = {
|
|
527
|
+
...schema.meta,
|
|
528
|
+
volatile: false
|
|
529
|
+
};
|
|
530
|
+
const [value, adapted] = Schema.resolve(data, inner, options, strict);
|
|
531
|
+
try {
|
|
532
|
+
return [createVolatile(value), adapted];
|
|
533
|
+
} catch (error) {
|
|
534
|
+
throw new ValidationError(error instanceof Error ? error.message : String(error), options);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (options.ignore?.(data, schema)) return [data];
|
|
538
|
+
if (isNullable(data) && schema.type !== "lazy") {
|
|
539
|
+
if (schema.meta.required) throw new ValidationError(`missing required value`, options);
|
|
540
|
+
let current = schema;
|
|
541
|
+
let fallback = schema.meta.default;
|
|
542
|
+
while (current?.type === "intersect" && isNullable(fallback)) {
|
|
543
|
+
current = current.list[0];
|
|
544
|
+
fallback = current?.meta.default;
|
|
545
|
+
}
|
|
546
|
+
if (isNullable(fallback)) return [data];
|
|
547
|
+
data = clone(fallback);
|
|
548
|
+
}
|
|
549
|
+
const callback = resolvers[schema.type];
|
|
550
|
+
if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
|
|
551
|
+
try {
|
|
552
|
+
return callback(data, schema, options, strict);
|
|
553
|
+
} catch (error) {
|
|
554
|
+
if (!schema.meta.loose) throw error;
|
|
555
|
+
return [schema.meta.default];
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
Schema.from = function from(source) {
|
|
559
|
+
if (isNullable(source)) return Schema.any();
|
|
560
|
+
else if ([
|
|
561
|
+
"string",
|
|
562
|
+
"number",
|
|
563
|
+
"boolean"
|
|
564
|
+
].includes(typeof source)) return Schema.const(source).required();
|
|
565
|
+
else if (source[kSchema]) return source;
|
|
566
|
+
else if (typeof source === "function") switch (source) {
|
|
567
|
+
case String: return Schema.string().required();
|
|
568
|
+
case Number: return Schema.number().required();
|
|
569
|
+
case Boolean: return Schema.boolean().required();
|
|
570
|
+
case Function: return Schema.function().required();
|
|
571
|
+
default: return Schema.is(source).required();
|
|
572
|
+
}
|
|
573
|
+
else throw new TypeError(`cannot infer schema from ${source}`);
|
|
574
|
+
};
|
|
575
|
+
Schema.lazy = function lazy(builder) {
|
|
576
|
+
const toJSON = () => {
|
|
577
|
+
if (!schema.inner[kSchema]) {
|
|
578
|
+
schema.inner = schema.builder();
|
|
579
|
+
schema.inner.meta = {
|
|
580
|
+
...schema.meta,
|
|
581
|
+
...schema.inner.meta
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
return schema.inner.toJSON();
|
|
585
|
+
};
|
|
586
|
+
const schema = new Schema({
|
|
587
|
+
type: "lazy",
|
|
588
|
+
builder,
|
|
589
|
+
inner: { toJSON }
|
|
590
|
+
});
|
|
591
|
+
return schema;
|
|
592
|
+
};
|
|
593
|
+
Schema.natural = function natural() {
|
|
594
|
+
return Schema.number().step(1).min(0);
|
|
595
|
+
};
|
|
596
|
+
Schema.percent = function percent() {
|
|
597
|
+
return Schema.number().step(.01).min(0).max(1).role("slider");
|
|
598
|
+
};
|
|
599
|
+
Schema.date = function date() {
|
|
600
|
+
return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
|
|
601
|
+
const date = new Date(value);
|
|
602
|
+
if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
|
|
603
|
+
return date;
|
|
604
|
+
}, true)]);
|
|
605
|
+
};
|
|
606
|
+
Schema.regExp = function regExp(flag = "") {
|
|
607
|
+
return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
|
|
608
|
+
try {
|
|
609
|
+
return new RegExp(value, flag);
|
|
610
|
+
} catch (e) {
|
|
611
|
+
throw new ValidationError(e.message, options);
|
|
612
|
+
}
|
|
613
|
+
}, true)]);
|
|
614
|
+
};
|
|
615
|
+
Schema.arrayBuffer = function arrayBuffer(encoding) {
|
|
616
|
+
return Schema.union([
|
|
617
|
+
Schema.is(ArrayBuffer),
|
|
618
|
+
Schema.is(SharedArrayBuffer),
|
|
619
|
+
Schema.transform(Schema.any(), (value, options) => {
|
|
620
|
+
if (Binary.isSource(value)) return Binary.fromSource(value);
|
|
621
|
+
throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
|
|
622
|
+
}, true),
|
|
623
|
+
...encoding ? [Schema.transform(Schema.string(), (value, options) => {
|
|
624
|
+
try {
|
|
625
|
+
return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
|
|
626
|
+
} catch (e) {
|
|
627
|
+
throw new ValidationError(e.message, options);
|
|
628
|
+
}
|
|
629
|
+
}, true)] : []
|
|
630
|
+
]);
|
|
631
|
+
};
|
|
632
|
+
Schema.extend("lazy", (data, schema, options, strict) => {
|
|
633
|
+
if (!schema.inner[kSchema]) {
|
|
634
|
+
schema.inner = schema.builder();
|
|
635
|
+
schema.inner.meta = {
|
|
636
|
+
...schema.meta,
|
|
637
|
+
...schema.inner.meta
|
|
638
|
+
};
|
|
639
|
+
validateVolatileSchema(schema.inner, options.path, true);
|
|
640
|
+
}
|
|
641
|
+
return Schema.resolve(data, schema.inner, options, strict);
|
|
642
|
+
});
|
|
643
|
+
Schema.extend("any", (data) => {
|
|
644
|
+
return [data];
|
|
645
|
+
});
|
|
646
|
+
Schema.extend("never", (data, _, options) => {
|
|
647
|
+
throw new ValidationError(`expected nullable but got ${data}`, options);
|
|
648
|
+
});
|
|
649
|
+
Schema.extend("const", (data, { value }, options) => {
|
|
650
|
+
if (deepEqual(data, value)) return [value];
|
|
651
|
+
throw new ValidationError(`expected ${value} but got ${data}`, options);
|
|
652
|
+
});
|
|
653
|
+
function checkWithinRange(data, meta, description, options, skipMin = false) {
|
|
654
|
+
const { max = Infinity, min = -Infinity } = meta;
|
|
655
|
+
if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
|
|
656
|
+
if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
|
|
657
|
+
}
|
|
658
|
+
Schema.extend("string", (data, { meta }, options) => {
|
|
659
|
+
if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
|
|
660
|
+
if (meta.pattern) {
|
|
661
|
+
const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
|
|
662
|
+
if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
|
|
663
|
+
}
|
|
664
|
+
checkWithinRange(data.length, meta, "string length", options);
|
|
665
|
+
return [data];
|
|
666
|
+
});
|
|
667
|
+
function decimalShift(data, digits) {
|
|
668
|
+
const str = data.toString();
|
|
669
|
+
if (str.includes("e")) return data * Math.pow(10, digits);
|
|
670
|
+
const index = str.indexOf(".");
|
|
671
|
+
if (index === -1) return data * Math.pow(10, digits);
|
|
672
|
+
const frac = str.slice(index + 1);
|
|
673
|
+
const integer = str.slice(0, index);
|
|
674
|
+
if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
|
|
675
|
+
return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
|
|
676
|
+
}
|
|
677
|
+
function isMultipleOf(data, min, step) {
|
|
678
|
+
step = Math.abs(step);
|
|
679
|
+
if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
|
|
680
|
+
const index = step.toString().indexOf(".");
|
|
681
|
+
const digits = step.toString().slice(index + 1).length;
|
|
682
|
+
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
|
|
683
|
+
}
|
|
684
|
+
Schema.extend("number", (data, { meta }, options) => {
|
|
685
|
+
if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
|
|
686
|
+
checkWithinRange(data, meta, "number", options);
|
|
687
|
+
const { step } = meta;
|
|
688
|
+
if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
|
|
689
|
+
return [data];
|
|
690
|
+
});
|
|
691
|
+
Schema.extend("boolean", (data, _, options) => {
|
|
692
|
+
if (typeof data === "boolean") return [data];
|
|
693
|
+
throw new ValidationError(`expected boolean but got ${data}`, options);
|
|
694
|
+
});
|
|
695
|
+
Schema.extend("bitset", (data, { bits, meta }, options) => {
|
|
696
|
+
let value = 0, keys = [];
|
|
697
|
+
if (typeof data === "number") {
|
|
698
|
+
value = data;
|
|
699
|
+
for (const key in bits) if (data & bits[key]) keys.push(key);
|
|
700
|
+
} else if (Array.isArray(data)) {
|
|
701
|
+
keys = data;
|
|
702
|
+
for (const key of keys) {
|
|
703
|
+
if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
|
|
704
|
+
if (key in bits) value |= bits[key];
|
|
705
|
+
}
|
|
706
|
+
} else throw new ValidationError(`expected number or array but got ${data}`, options);
|
|
707
|
+
if (value === meta.default) return [value];
|
|
708
|
+
return [value, keys];
|
|
709
|
+
});
|
|
710
|
+
Schema.extend("function", (data, _, options) => {
|
|
711
|
+
if (typeof data === "function") return [data];
|
|
712
|
+
throw new ValidationError(`expected function but got ${data}`, options);
|
|
713
|
+
});
|
|
714
|
+
Schema.extend("is", (data, { constructor }, options) => {
|
|
715
|
+
if (typeof constructor === "function") {
|
|
716
|
+
if (data instanceof constructor) return [data];
|
|
717
|
+
throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
|
|
718
|
+
} else {
|
|
719
|
+
if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
720
|
+
let prototype = Object.getPrototypeOf(data);
|
|
721
|
+
while (prototype) {
|
|
722
|
+
if (prototype.constructor?.name === constructor) return [data];
|
|
723
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
724
|
+
}
|
|
725
|
+
throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
726
|
+
}
|
|
727
|
+
});
|
|
728
|
+
function property(data, key, schema, options) {
|
|
729
|
+
try {
|
|
730
|
+
const [value, adapted] = Schema.resolve(data[key], schema, {
|
|
731
|
+
...options,
|
|
732
|
+
path: [...options.path || [], key]
|
|
733
|
+
});
|
|
734
|
+
if (adapted !== void 0) data[key] = adapted;
|
|
735
|
+
return value;
|
|
736
|
+
} catch (e) {
|
|
737
|
+
if (!options?.autofix) throw e;
|
|
738
|
+
delete data[key];
|
|
739
|
+
return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
Schema.extend("array", (data, { inner, meta }, options) => {
|
|
743
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
744
|
+
checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
|
|
745
|
+
return [data.map((_, index) => property(data, index, inner, options))];
|
|
746
|
+
});
|
|
747
|
+
Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
|
|
748
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
749
|
+
const result = {};
|
|
750
|
+
for (const key in data) {
|
|
751
|
+
let rKey;
|
|
752
|
+
try {
|
|
753
|
+
rKey = Schema.resolve(key, sKey, options)[0];
|
|
754
|
+
} catch (error) {
|
|
755
|
+
if (strict) continue;
|
|
756
|
+
throw error;
|
|
757
|
+
}
|
|
758
|
+
result[rKey] = property(data, key, inner, options);
|
|
759
|
+
data[rKey] = data[key];
|
|
760
|
+
if (key !== rKey) delete data[key];
|
|
761
|
+
}
|
|
762
|
+
return [result];
|
|
763
|
+
});
|
|
764
|
+
Schema.extend("tuple", (data, { list }, options, strict) => {
|
|
765
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
766
|
+
const result = list.map((inner, index) => property(data, index, inner, options));
|
|
767
|
+
if (strict) return [result];
|
|
768
|
+
result.push(...data.slice(list.length));
|
|
769
|
+
return [result];
|
|
770
|
+
});
|
|
771
|
+
function merge(result, data) {
|
|
772
|
+
for (const key in data) {
|
|
773
|
+
if (key in result) continue;
|
|
774
|
+
result[key] = data[key];
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
Schema.extend("object", (data, { dict }, options, strict) => {
|
|
778
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
779
|
+
const result = {};
|
|
780
|
+
for (const key in dict) {
|
|
781
|
+
const value = property(data, key, dict[key], options);
|
|
782
|
+
if (!isNullable(value) || key in data) result[key] = value;
|
|
783
|
+
}
|
|
784
|
+
if (!strict) merge(result, data);
|
|
785
|
+
return [result];
|
|
786
|
+
});
|
|
787
|
+
Schema.extend("union", (data, { list, toString }, options, strict) => {
|
|
788
|
+
const messages = [];
|
|
789
|
+
for (const inner of list) try {
|
|
790
|
+
return Schema.resolve(data, inner, options, strict);
|
|
791
|
+
} catch (error) {
|
|
792
|
+
messages.push(error);
|
|
793
|
+
}
|
|
794
|
+
throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
795
|
+
});
|
|
796
|
+
Schema.extend("intersect", (data, { list, toString }, options, strict) => {
|
|
797
|
+
if (!list.length) return [data];
|
|
798
|
+
let result;
|
|
799
|
+
for (const inner of list) {
|
|
800
|
+
const value = Schema.resolve(data, inner, options, true)[0];
|
|
801
|
+
if (isNullable(value)) continue;
|
|
802
|
+
if (isNullable(result)) result = value;
|
|
803
|
+
else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
804
|
+
else if (typeof value === "object") merge(result ??= {}, value);
|
|
805
|
+
else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
806
|
+
}
|
|
807
|
+
if (!strict && isPlainObject(data)) merge(result, data);
|
|
808
|
+
return [result];
|
|
809
|
+
});
|
|
810
|
+
Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
|
|
811
|
+
const [result, adapted = data] = Schema.resolve(data, inner, options, true);
|
|
812
|
+
if (preserve) return [callback(result)];
|
|
813
|
+
else return [callback(result), callback(adapted)];
|
|
814
|
+
});
|
|
815
|
+
const formatters = {};
|
|
816
|
+
function defineMethod(name, keys, format) {
|
|
817
|
+
formatters[name] = format;
|
|
818
|
+
Object.assign(Schema, { [name](...args) {
|
|
819
|
+
const schema = new Schema({ type: name });
|
|
820
|
+
keys.forEach((key, index) => {
|
|
821
|
+
switch (key) {
|
|
822
|
+
case "sKey":
|
|
823
|
+
schema.sKey = args[index] ?? Schema.string();
|
|
824
|
+
break;
|
|
825
|
+
case "inner":
|
|
826
|
+
schema.inner = Schema.from(args[index]);
|
|
827
|
+
break;
|
|
828
|
+
case "list":
|
|
829
|
+
schema.list = args[index].map(Schema.from);
|
|
830
|
+
break;
|
|
831
|
+
case "dict":
|
|
832
|
+
schema.dict = mapValues(args[index], Schema.from);
|
|
833
|
+
break;
|
|
834
|
+
case "bits":
|
|
835
|
+
schema.bits = {};
|
|
836
|
+
for (const key in args[index]) {
|
|
837
|
+
if (typeof args[index][key] !== "number") continue;
|
|
838
|
+
schema.bits[key] = args[index][key];
|
|
839
|
+
}
|
|
840
|
+
break;
|
|
841
|
+
case "callback": {
|
|
842
|
+
const callback = schema.callback = args[index];
|
|
843
|
+
callback["toJSON"] ||= () => callback.toString();
|
|
844
|
+
break;
|
|
845
|
+
}
|
|
846
|
+
case "constructor": {
|
|
847
|
+
const constructor = schema.constructor = args[index];
|
|
848
|
+
if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
|
|
849
|
+
break;
|
|
850
|
+
}
|
|
851
|
+
default: schema[key] = args[index];
|
|
852
|
+
}
|
|
853
|
+
});
|
|
854
|
+
if (name === "object" || name === "dict") schema.meta.default = {};
|
|
855
|
+
else if (name === "array" || name === "tuple") schema.meta.default = [];
|
|
856
|
+
else if (name === "bitset") schema.meta.default = 0;
|
|
857
|
+
return schema;
|
|
858
|
+
} });
|
|
859
|
+
}
|
|
860
|
+
defineMethod("is", ["constructor"], ({ constructor }) => {
|
|
861
|
+
if (typeof constructor === "function") return constructor.name;
|
|
862
|
+
else return constructor;
|
|
863
|
+
});
|
|
864
|
+
defineMethod("any", [], () => "any");
|
|
865
|
+
defineMethod("never", [], () => "never");
|
|
866
|
+
defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
|
|
867
|
+
defineMethod("string", [], () => "string");
|
|
868
|
+
defineMethod("number", [], () => "number");
|
|
869
|
+
defineMethod("boolean", [], () => "boolean");
|
|
870
|
+
defineMethod("bitset", ["bits"], () => "bitset");
|
|
871
|
+
defineMethod("function", [], () => "function");
|
|
872
|
+
defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
|
|
873
|
+
defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
|
|
874
|
+
defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
|
|
875
|
+
defineMethod("object", ["dict"], ({ dict }) => {
|
|
876
|
+
if (Object.keys(dict).length === 0) return "{}";
|
|
877
|
+
return `{ ${Object.entries(dict).map(([key, inner]) => {
|
|
878
|
+
return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
|
|
879
|
+
}).join(", ")} }`;
|
|
880
|
+
});
|
|
881
|
+
defineMethod("union", ["list"], ({ list }, inline) => {
|
|
882
|
+
const result = list.map(({ toString: format }) => format()).join(" | ");
|
|
883
|
+
return inline ? `(${result})` : result;
|
|
884
|
+
});
|
|
885
|
+
defineMethod("intersect", ["list"], ({ list }) => {
|
|
886
|
+
return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
|
|
887
|
+
});
|
|
888
|
+
defineMethod("transform", [
|
|
889
|
+
"inner",
|
|
890
|
+
"callback",
|
|
891
|
+
"preserve"
|
|
892
|
+
], ({ inner }, isInner) => inner.toString(isInner));
|
|
893
|
+
//#endregion
|
|
894
|
+
//#region lib/types/recovery-config.js
|
|
895
|
+
/** Shared validation for Host-configured and browser-local connection recovery. */
|
|
896
|
+
const MAX_TIMER_MS = 2147483647;
|
|
897
|
+
/** Schema shared by the Host plugin and the Client's recovery input parser. */
|
|
898
|
+
const ConnectionRecoveryConfigSchema = Schema.object({
|
|
899
|
+
backoffBaseMs: Schema.natural().min(1).max(MAX_TIMER_MS).default(500),
|
|
900
|
+
backoffFactor: Schema.number().min(1).max(Number.MAX_VALUE).default(2),
|
|
901
|
+
backoffMaxMs: Schema.natural().min(1).max(MAX_TIMER_MS).default(1e4),
|
|
902
|
+
generationReadyWarnMs: Schema.natural().min(1).max(MAX_TIMER_MS).default(3e3),
|
|
903
|
+
generationReadyTimeoutMs: Schema.natural().min(1).max(MAX_TIMER_MS).default(15e3)
|
|
904
|
+
});
|
|
905
|
+
/**
|
|
906
|
+
* Validate recovery input and supply every timing default before starting work.
|
|
907
|
+
* @param config - Host configuration, page bootstrap data, or direct loop options.
|
|
908
|
+
* @returns validated, complete recovery timing.
|
|
909
|
+
*/
|
|
910
|
+
function resolveConnectionConfig(config = {}) {
|
|
911
|
+
const resolved = ConnectionRecoveryConfigSchema(config);
|
|
912
|
+
if (!Number.isFinite(resolved.backoffFactor)) throw new RangeError("connection recovery backoffFactor must be finite");
|
|
913
|
+
return resolved;
|
|
914
|
+
}
|
|
915
|
+
//#endregion
|
|
916
|
+
//#region lib/types/client/connection.js
|
|
917
|
+
/** Connection generation readiness, cancellation, and continuous recovery. */
|
|
918
|
+
const MANUAL_RECONNECT = /* @__PURE__ */ new Error("connection: manual reconnect requested");
|
|
919
|
+
const NETWORK_STATE_CHANGED = /* @__PURE__ */ new Error("connection: browser network state changed");
|
|
920
|
+
function sleep(ms, signal) {
|
|
921
|
+
return new Promise((resolve) => {
|
|
922
|
+
const t = setTimeout(done, ms);
|
|
923
|
+
signal.addEventListener("abort", done, { once: true });
|
|
924
|
+
function done() {
|
|
925
|
+
clearTimeout(t);
|
|
926
|
+
signal.removeEventListener("abort", done);
|
|
927
|
+
resolve();
|
|
928
|
+
}
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
function waitForAbort(signal) {
|
|
932
|
+
if (signal.aborted) return Promise.resolve();
|
|
933
|
+
return new Promise((resolve) => {
|
|
934
|
+
signal.addEventListener("abort", () => {
|
|
935
|
+
resolve();
|
|
936
|
+
}, { once: true });
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Opens the registered generation source, reconnecting with exponential backoff on loss.
|
|
941
|
+
* State (generation/attempt) is instance-private, never in the store.
|
|
942
|
+
* Sink exceptions do not kill the generation loop.
|
|
943
|
+
*/
|
|
944
|
+
var ConnectionController = class {
|
|
945
|
+
source;
|
|
946
|
+
sinks;
|
|
947
|
+
generation = 0;
|
|
948
|
+
attempt = 0;
|
|
949
|
+
current = null;
|
|
950
|
+
retryDelay = null;
|
|
951
|
+
running = false;
|
|
952
|
+
immediateRetry = false;
|
|
953
|
+
networkAvailable = true;
|
|
954
|
+
lastState;
|
|
955
|
+
config;
|
|
956
|
+
constructor(source, sinks = {}, config = {}) {
|
|
957
|
+
this.source = source;
|
|
958
|
+
this.sinks = sinks;
|
|
959
|
+
this.config = resolveConnectionConfig(config);
|
|
960
|
+
}
|
|
961
|
+
/** Idempotent: begin the connect/pump/reconnect loop. */
|
|
962
|
+
start() {
|
|
963
|
+
if (this.running) return;
|
|
964
|
+
this.running = true;
|
|
965
|
+
this.loop();
|
|
966
|
+
}
|
|
967
|
+
/** Stop the loop and abort the current generation source. */
|
|
968
|
+
stop() {
|
|
969
|
+
this.running = false;
|
|
970
|
+
this.current?.abort();
|
|
971
|
+
this.current = null;
|
|
972
|
+
this.retryDelay?.abort();
|
|
973
|
+
this.retryDelay = null;
|
|
974
|
+
}
|
|
975
|
+
/** Reset the retry sequence and replace the current generation or retry delay immediately. */
|
|
976
|
+
reconnect() {
|
|
977
|
+
if (!this.running) return;
|
|
978
|
+
this.attempt = 0;
|
|
979
|
+
this.immediateRetry = true;
|
|
980
|
+
this.emitState("connecting");
|
|
981
|
+
if (!this.isRunning()) return;
|
|
982
|
+
this.current?.abort(MANUAL_RECONNECT);
|
|
983
|
+
this.retryDelay?.abort(MANUAL_RECONNECT);
|
|
984
|
+
}
|
|
985
|
+
/**
|
|
986
|
+
* Suspend automatic retries while offline and restart backoff when the network returns.
|
|
987
|
+
* @param available - whether the browser reports network access.
|
|
988
|
+
*/
|
|
989
|
+
setNetworkAvailable(available) {
|
|
990
|
+
if (this.networkAvailable === available) return;
|
|
991
|
+
this.networkAvailable = available;
|
|
992
|
+
this.attempt = 0;
|
|
993
|
+
this.immediateRetry = false;
|
|
994
|
+
if (!this.running) return;
|
|
995
|
+
this.emitState(available ? "connecting" : "disconnected");
|
|
996
|
+
if (!this.isRunning()) return;
|
|
997
|
+
this.current?.abort(NETWORK_STATE_CHANGED);
|
|
998
|
+
this.retryDelay?.abort(NETWORK_STATE_CHANGED);
|
|
999
|
+
}
|
|
1000
|
+
backoffCap(attempt) {
|
|
1001
|
+
const { backoffBaseMs, backoffFactor, backoffMaxMs } = this.config;
|
|
1002
|
+
return Math.min(backoffMaxMs, backoffBaseMs * backoffFactor ** Math.max(0, attempt - 1));
|
|
1003
|
+
}
|
|
1004
|
+
backoffDelay(attempt) {
|
|
1005
|
+
const cap = this.backoffCap(attempt);
|
|
1006
|
+
return cap / 2 + Math.random() * (cap / 2);
|
|
1007
|
+
}
|
|
1008
|
+
/** Re-read retry inputs after a potentially reentrant state sink. */
|
|
1009
|
+
isRetryInterrupted(immediate) {
|
|
1010
|
+
return this.immediateRetry || !this.networkAvailable && !immediate;
|
|
1011
|
+
}
|
|
1012
|
+
/** Read through a method: stop() flips the flag across awaits, so narrowing from the loop condition must not stick. */
|
|
1013
|
+
isRunning() {
|
|
1014
|
+
return this.running;
|
|
1015
|
+
}
|
|
1016
|
+
/** Re-read both mutable liveness guards after a potentially reentrant sink. */
|
|
1017
|
+
isGenerationActive(controller) {
|
|
1018
|
+
return this.isRunning() && !controller.signal.aborted;
|
|
1019
|
+
}
|
|
1020
|
+
async loop() {
|
|
1021
|
+
let retry = false;
|
|
1022
|
+
while (this.running) {
|
|
1023
|
+
if (!this.networkAvailable && !this.immediateRetry) {
|
|
1024
|
+
const retryDelay = new AbortController();
|
|
1025
|
+
this.retryDelay = retryDelay;
|
|
1026
|
+
this.emitState("disconnected");
|
|
1027
|
+
await waitForAbort(retryDelay.signal);
|
|
1028
|
+
if (this.retryDelay === retryDelay) this.retryDelay = null;
|
|
1029
|
+
if (!this.isRunning()) return;
|
|
1030
|
+
retry = true;
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
let manualAttempt = false;
|
|
1034
|
+
if (retry) {
|
|
1035
|
+
const immediate = this.immediateRetry;
|
|
1036
|
+
this.immediateRetry = false;
|
|
1037
|
+
if (immediate) this.attempt = 0;
|
|
1038
|
+
manualAttempt = immediate;
|
|
1039
|
+
const attempt = ++this.attempt;
|
|
1040
|
+
this.emitState("connecting");
|
|
1041
|
+
if (!this.isRunning()) return;
|
|
1042
|
+
if (this.isRetryInterrupted(immediate)) continue;
|
|
1043
|
+
if (!immediate) {
|
|
1044
|
+
const retryDelay = new AbortController();
|
|
1045
|
+
this.retryDelay = retryDelay;
|
|
1046
|
+
await sleep(this.backoffDelay(attempt), retryDelay.signal);
|
|
1047
|
+
if (this.retryDelay === retryDelay) this.retryDelay = null;
|
|
1048
|
+
if (!this.isRunning()) return;
|
|
1049
|
+
if (retryDelay.signal.aborted) continue;
|
|
1050
|
+
}
|
|
1051
|
+
console.warn(`[connection] connection lost, retry #${String(attempt)}`);
|
|
1052
|
+
this.callSink(() => {
|
|
1053
|
+
this.sinks.onReconnectRequested?.();
|
|
1054
|
+
});
|
|
1055
|
+
if (!this.isRunning()) return;
|
|
1056
|
+
}
|
|
1057
|
+
const gen = ++this.generation;
|
|
1058
|
+
const ac = new AbortController();
|
|
1059
|
+
this.current = ac;
|
|
1060
|
+
let sourceReady = false;
|
|
1061
|
+
let resolveReady;
|
|
1062
|
+
let rejectReady;
|
|
1063
|
+
let rejectSourceLost;
|
|
1064
|
+
const ready = new Promise((resolve, reject) => {
|
|
1065
|
+
resolveReady = resolve;
|
|
1066
|
+
rejectReady = reject;
|
|
1067
|
+
});
|
|
1068
|
+
const sourceLost = new Promise((_resolve, reject) => {
|
|
1069
|
+
rejectSourceLost = reject;
|
|
1070
|
+
});
|
|
1071
|
+
const reportReady = (host) => {
|
|
1072
|
+
if (sourceReady || gen !== this.generation || !this.isGenerationActive(ac)) return;
|
|
1073
|
+
sourceReady = true;
|
|
1074
|
+
resolveReady(host);
|
|
1075
|
+
};
|
|
1076
|
+
const failed = new Promise((resolve) => {
|
|
1077
|
+
const settle = () => {
|
|
1078
|
+
if (gen === this.generation && !ac.signal.aborted) ac.abort();
|
|
1079
|
+
resolve();
|
|
1080
|
+
};
|
|
1081
|
+
Promise.resolve().then(() => this.source(ac.signal, reportReady)).then(() => {
|
|
1082
|
+
const error = /* @__PURE__ */ new Error("connection generation ended");
|
|
1083
|
+
if (!sourceReady) rejectReady(error);
|
|
1084
|
+
rejectSourceLost(error);
|
|
1085
|
+
settle();
|
|
1086
|
+
}, (error) => {
|
|
1087
|
+
const failure = error instanceof Error ? error : new Error("connection generation failed", { cause: error });
|
|
1088
|
+
if (!sourceReady) rejectReady(failure);
|
|
1089
|
+
rejectSourceLost(failure);
|
|
1090
|
+
settle();
|
|
1091
|
+
});
|
|
1092
|
+
});
|
|
1093
|
+
try {
|
|
1094
|
+
const host = await Promise.race([waitForReady(ready, this.config, ac.signal), sourceLost]);
|
|
1095
|
+
if (ac.signal.aborted) throw new Error("generation aborted during readiness handshake");
|
|
1096
|
+
this.attempt = 0;
|
|
1097
|
+
this.emitState("connected");
|
|
1098
|
+
if (this.isGenerationActive(ac)) this.callSink(() => {
|
|
1099
|
+
this.sinks.onConnected?.(host);
|
|
1100
|
+
});
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
if (!ac.signal.aborted) ac.abort(error);
|
|
1103
|
+
}
|
|
1104
|
+
await failed;
|
|
1105
|
+
if (!this.isRunning()) return;
|
|
1106
|
+
if (manualAttempt) this.attempt = 0;
|
|
1107
|
+
retry = true;
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
/** Deduplicated state emission (sink isolation applies). */
|
|
1111
|
+
emitState(state) {
|
|
1112
|
+
if (this.lastState === state) return;
|
|
1113
|
+
this.lastState = state;
|
|
1114
|
+
this.callSink(() => this.sinks.onStateChange?.(state));
|
|
1115
|
+
}
|
|
1116
|
+
/** Sink exception isolation: a business-layer throw is logged only, never affecting pump or reconnect semantics. */
|
|
1117
|
+
callSink(fn) {
|
|
1118
|
+
try {
|
|
1119
|
+
fn();
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
console.error("[connection] connection sink threw:", error);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
};
|
|
1125
|
+
/** Report a slow handshake before the hard deadline ends its generation. */
|
|
1126
|
+
function waitForReady(ready, config, signal) {
|
|
1127
|
+
return new Promise((resolve, reject) => {
|
|
1128
|
+
let settled = false;
|
|
1129
|
+
const warning = setTimeout(() => {
|
|
1130
|
+
console.warn(`[connection] generation is still not ready after ${String(config.generationReadyWarnMs)}ms`);
|
|
1131
|
+
}, config.generationReadyWarnMs);
|
|
1132
|
+
const timeout = setTimeout(() => {
|
|
1133
|
+
const error = /* @__PURE__ */ new Error(`connection generation was not ready within ${String(config.generationReadyTimeoutMs)}ms`);
|
|
1134
|
+
console.warn(`[connection] ${error.message}; cancelling generation`);
|
|
1135
|
+
finish({ error });
|
|
1136
|
+
}, config.generationReadyTimeoutMs);
|
|
1137
|
+
const aborted = () => {
|
|
1138
|
+
finish({ error: new Error("connection generation aborted", { cause: signal.reason }) });
|
|
1139
|
+
};
|
|
1140
|
+
const finish = (outcome) => {
|
|
1141
|
+
if (settled) return;
|
|
1142
|
+
settled = true;
|
|
1143
|
+
clearTimeout(warning);
|
|
1144
|
+
clearTimeout(timeout);
|
|
1145
|
+
signal.removeEventListener("abort", aborted);
|
|
1146
|
+
if ("error" in outcome) reject(outcome.error);
|
|
1147
|
+
else resolve(outcome.value);
|
|
1148
|
+
};
|
|
1149
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
1150
|
+
ready.then((value) => {
|
|
1151
|
+
finish({ value });
|
|
1152
|
+
}, (error) => {
|
|
1153
|
+
finish({ error });
|
|
1154
|
+
});
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
//#endregion
|
|
1158
|
+
//#region lib/types/rpc.js
|
|
1159
|
+
/** Generic unary RPC contracts shared by the Host and Client Connection halves. */
|
|
1160
|
+
/**
|
|
1161
|
+
* Brand one validated string as a Connection correlation id.
|
|
1162
|
+
* @param id - validated wire identity.
|
|
1163
|
+
* @returns the same string with the correlation-id brand.
|
|
1164
|
+
*/
|
|
1165
|
+
function RpcId(id) {
|
|
1166
|
+
return id;
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Convert a rejected transport operation into a generic failure result.
|
|
1170
|
+
* @param error - rejected transport value.
|
|
1171
|
+
* @returns an `internal` failure preserving the available message.
|
|
1172
|
+
*/
|
|
1173
|
+
function transportError(error) {
|
|
1174
|
+
return {
|
|
1175
|
+
ok: false,
|
|
1176
|
+
error: {
|
|
1177
|
+
code: "gateway/internal",
|
|
1178
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1179
|
+
details: {}
|
|
1180
|
+
}
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
//#endregion
|
|
1184
|
+
//#region lib/types/client/random-uuid.js
|
|
1185
|
+
/** Browser-safe UUID generation for client-side wire correlation. */
|
|
1186
|
+
/**
|
|
1187
|
+
* Generate an RFC 4122 version 4 UUID without requiring a secure context.
|
|
1188
|
+
* @returns a UUID backed by `crypto.getRandomValues()`, which browsers expose on insecure origins.
|
|
1189
|
+
*/
|
|
1190
|
+
function randomUuid() {
|
|
1191
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
1192
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1193
|
+
view.setUint8(6, view.getUint8(6) & 15 | 64);
|
|
1194
|
+
view.setUint8(8, view.getUint8(8) & 63 | 128);
|
|
1195
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1196
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1197
|
+
}
|
|
1198
|
+
//#endregion
|
|
1199
|
+
//#region lib/types/client/rpc.js
|
|
1200
|
+
/** Browser caller for generic Connection unary RPC channels. */
|
|
1201
|
+
const INTERNAL_BASE = "http://qilin.internal";
|
|
1202
|
+
const CHANNEL_PATTERN = /^\/[A-Za-z0-9._~-]+$/;
|
|
1203
|
+
const ENDPOINT_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/;
|
|
1204
|
+
/**
|
|
1205
|
+
* Create the browser-backed generic RPC caller.
|
|
1206
|
+
* @param doFetch - transport override; defaults to the page's global fetch.
|
|
1207
|
+
* @param openStream - optional worker-local Gateway stream carrier.
|
|
1208
|
+
* @returns caller that owns request correlation and response-envelope validation.
|
|
1209
|
+
*/
|
|
1210
|
+
function createWebConnectionRpc(doFetch, openStream) {
|
|
1211
|
+
const send = doFetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
1212
|
+
return {
|
|
1213
|
+
async call(channel, endpoint, payload, signal) {
|
|
1214
|
+
assertTarget(channel, endpoint);
|
|
1215
|
+
const rpcId = RpcId(randomUuid());
|
|
1216
|
+
const message = {
|
|
1217
|
+
type: "client-request",
|
|
1218
|
+
rpcId,
|
|
1219
|
+
method: endpoint,
|
|
1220
|
+
payload
|
|
1221
|
+
};
|
|
1222
|
+
const response = await send(new URL(`${channel}/${endpoint}`, resolveBase()), {
|
|
1223
|
+
method: "POST",
|
|
1224
|
+
headers: { "content-type": "application/json" },
|
|
1225
|
+
body: JSON.stringify(message),
|
|
1226
|
+
...signal === void 0 ? {} : { signal }
|
|
1227
|
+
});
|
|
1228
|
+
if (!response.ok) throw new Error(`transport failure for ${channel}/${endpoint}: HTTP ${response.status}`);
|
|
1229
|
+
const full = parseConnectionResponse(await response.json());
|
|
1230
|
+
if (full.rpcId !== rpcId) throw new Error(`rpcId mismatch for ${endpoint}: sent ${rpcId}, got ${full.rpcId}`);
|
|
1231
|
+
return full.result;
|
|
1232
|
+
},
|
|
1233
|
+
...openStream === void 0 ? {} : { open(channel, endpoint, payload, signal, uplink) {
|
|
1234
|
+
assertTarget(channel, endpoint);
|
|
1235
|
+
if (channel !== "/api") throw new Error(`connection: worker-local streams require the /api channel, got ${JSON.stringify(channel)}`);
|
|
1236
|
+
return openStream(endpoint, payload, signal, uplink);
|
|
1237
|
+
} }
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
function parseConnectionResponse(value) {
|
|
1241
|
+
if (!isRecord(value) || value.type !== "server-response" || typeof value.rpcId !== "string") throw new TypeError("connection: invalid server-response envelope");
|
|
1242
|
+
const result = value.result;
|
|
1243
|
+
if (!isRecord(result)) throw new TypeError("connection: invalid server-response result");
|
|
1244
|
+
if (result.ok === true) return {
|
|
1245
|
+
rpcId: RpcId(value.rpcId),
|
|
1246
|
+
result: {
|
|
1247
|
+
ok: true,
|
|
1248
|
+
value: result.value
|
|
1249
|
+
}
|
|
1250
|
+
};
|
|
1251
|
+
if (result.ok !== false || !isRecord(result.error)) throw new TypeError("connection: invalid server-response result");
|
|
1252
|
+
const error = result.error;
|
|
1253
|
+
if (typeof error.code !== "string" || typeof error.message !== "string" || !isRecord(error.details)) throw new TypeError("connection: invalid server-response failure");
|
|
1254
|
+
return {
|
|
1255
|
+
rpcId: RpcId(value.rpcId),
|
|
1256
|
+
result: {
|
|
1257
|
+
ok: false,
|
|
1258
|
+
error: {
|
|
1259
|
+
code: error.code,
|
|
1260
|
+
message: error.message,
|
|
1261
|
+
details: error.details
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
function isRecord(value) {
|
|
1267
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1268
|
+
}
|
|
1269
|
+
function resolveBase() {
|
|
1270
|
+
const location = globalThis.location;
|
|
1271
|
+
return location?.origin !== void 0 && location.origin !== "null" ? location.origin : INTERNAL_BASE;
|
|
1272
|
+
}
|
|
1273
|
+
function assertTarget(channel, endpoint) {
|
|
1274
|
+
const segments = endpoint.split("/");
|
|
1275
|
+
if (!CHANNEL_PATTERN.test(channel) || segments.some((segment) => segment === "" || segment === "." || segment === ".." || !ENDPOINT_SEGMENT_PATTERN.test(segment))) throw new Error(`connection: invalid RPC target ${JSON.stringify(`${channel}/${endpoint}`)}`);
|
|
1276
|
+
}
|
|
1277
|
+
//#endregion
|
|
1278
|
+
//#region lib/types/loopback-hostname.js
|
|
1279
|
+
/**
|
|
1280
|
+
* Browser-safe, zero-dependency loopback classification shared by the `/api`
|
|
1281
|
+
* Host fence and the package's `ctx.connection` state. The predicate stays
|
|
1282
|
+
* package-internal; client plugins consume the derived state through Cordis.
|
|
1283
|
+
*/
|
|
1284
|
+
/**
|
|
1285
|
+
* Whether a normalized URL hostname names the local loopback authority.
|
|
1286
|
+
* @param hostname - WHATWG URL hostname (IPv6 literals retain brackets).
|
|
1287
|
+
* @returns true for localhost, IPv6 loopback, or any IPv4 address in 127/8.
|
|
1288
|
+
*/
|
|
1289
|
+
function isLoopbackHostname(hostname) {
|
|
1290
|
+
if (hostname === "localhost" || hostname === "[::1]") return true;
|
|
1291
|
+
const parts = hostname.split(".");
|
|
1292
|
+
return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
|
|
1293
|
+
}
|
|
1294
|
+
//#endregion
|
|
1295
|
+
//#region lib/types/client/index.js
|
|
1296
|
+
/** Required services (none — this is the wire root). */
|
|
1297
|
+
const inject = [];
|
|
1298
|
+
function watchBrowserNetwork(controller) {
|
|
1299
|
+
const browser = globalThis.window;
|
|
1300
|
+
const initiallyAvailable = browser?.navigator?.onLine;
|
|
1301
|
+
if (browser === void 0 || initiallyAvailable === void 0) return () => {};
|
|
1302
|
+
const online = () => {
|
|
1303
|
+
controller.setNetworkAvailable(true);
|
|
1304
|
+
};
|
|
1305
|
+
const offline = () => {
|
|
1306
|
+
controller.setNetworkAvailable(false);
|
|
1307
|
+
};
|
|
1308
|
+
controller.setNetworkAvailable(initiallyAvailable);
|
|
1309
|
+
browser.addEventListener("online", online);
|
|
1310
|
+
browser.addEventListener("offline", offline);
|
|
1311
|
+
return () => {
|
|
1312
|
+
browser.removeEventListener("online", online);
|
|
1313
|
+
browser.removeEventListener("offline", offline);
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* Install one Context-owned Connection service from explicit composition inputs.
|
|
1318
|
+
* @param ctx - client Cordis context.
|
|
1319
|
+
* @param options - physical carrier, reconnect timing, and page location.
|
|
1320
|
+
*/
|
|
1321
|
+
function installConnection(ctx, options = {}) {
|
|
1322
|
+
const pageLocation = options.location;
|
|
1323
|
+
const transport = options.transport;
|
|
1324
|
+
const recovery = options.recovery ?? {};
|
|
1325
|
+
const rpc = transport?.rpc ?? createWebConnectionRpc(transport?.fetch, transport?.openStream);
|
|
1326
|
+
let generationSource;
|
|
1327
|
+
let owner;
|
|
1328
|
+
let generationId = 0;
|
|
1329
|
+
let generation;
|
|
1330
|
+
let state;
|
|
1331
|
+
const generationListeners = /* @__PURE__ */ new Set();
|
|
1332
|
+
const stateListeners = /* @__PURE__ */ new Set();
|
|
1333
|
+
const publishGeneration = (next) => {
|
|
1334
|
+
if (Object.is(generation, next)) return;
|
|
1335
|
+
generation = next;
|
|
1336
|
+
for (const listener of [...generationListeners]) try {
|
|
1337
|
+
listener();
|
|
1338
|
+
} catch (error) {
|
|
1339
|
+
console.error("[connection] generation listener threw:", error);
|
|
1340
|
+
}
|
|
1341
|
+
};
|
|
1342
|
+
const publishState = (next) => {
|
|
1343
|
+
if (state === next) return;
|
|
1344
|
+
state = next;
|
|
1345
|
+
for (const listener of [...stateListeners]) try {
|
|
1346
|
+
listener();
|
|
1347
|
+
} catch (error) {
|
|
1348
|
+
console.error("[connection] state listener threw:", error);
|
|
1349
|
+
}
|
|
1350
|
+
};
|
|
1351
|
+
const releaseOwner = (current) => {
|
|
1352
|
+
if (owner !== current) return;
|
|
1353
|
+
owner = void 0;
|
|
1354
|
+
current.stopNetworkWatch();
|
|
1355
|
+
current.controller.stop();
|
|
1356
|
+
publishGeneration(void 0);
|
|
1357
|
+
publishState(void 0);
|
|
1358
|
+
};
|
|
1359
|
+
const handle = {
|
|
1360
|
+
isLoopback: transport?.ownsHost === true || pageLocation === void 0 || isLoopbackHostname(pageLocation.hostname),
|
|
1361
|
+
generation: {
|
|
1362
|
+
getSnapshot: () => generation,
|
|
1363
|
+
subscribe: (listener) => {
|
|
1364
|
+
generationListeners.add(listener);
|
|
1365
|
+
return () => {
|
|
1366
|
+
generationListeners.delete(listener);
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
},
|
|
1370
|
+
state: {
|
|
1371
|
+
getSnapshot: () => state,
|
|
1372
|
+
subscribe: (listener) => {
|
|
1373
|
+
stateListeners.add(listener);
|
|
1374
|
+
return () => {
|
|
1375
|
+
stateListeners.delete(listener);
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
},
|
|
1379
|
+
rpc,
|
|
1380
|
+
reconnect() {
|
|
1381
|
+
owner?.controller.reconnect();
|
|
1382
|
+
},
|
|
1383
|
+
registerGenerationSource(source) {
|
|
1384
|
+
if (generationSource !== void 0) throw new Error("connection: a generation source is already registered");
|
|
1385
|
+
generationSource = source;
|
|
1386
|
+
return () => {
|
|
1387
|
+
if (generationSource !== source) return;
|
|
1388
|
+
generationSource = void 0;
|
|
1389
|
+
const current = owner;
|
|
1390
|
+
if (current?.source === source) releaseOwner(current);
|
|
1391
|
+
};
|
|
1392
|
+
},
|
|
1393
|
+
start(sinks, config) {
|
|
1394
|
+
if (owner !== void 0) throw new Error("connection: the stream loop is already owned by another consumer");
|
|
1395
|
+
const source = generationSource;
|
|
1396
|
+
if (source === void 0) throw new Error("connection: no generation source is registered");
|
|
1397
|
+
const token = {};
|
|
1398
|
+
const ownsGeneration = () => owner?.token === token;
|
|
1399
|
+
const controller = new ConnectionController(source, {
|
|
1400
|
+
...sinks,
|
|
1401
|
+
onConnected: (host) => {
|
|
1402
|
+
const nextGeneration = {
|
|
1403
|
+
id: ++generationId,
|
|
1404
|
+
host
|
|
1405
|
+
};
|
|
1406
|
+
publishGeneration(nextGeneration);
|
|
1407
|
+
if (!ownsGeneration() || !Object.is(generation, nextGeneration)) return;
|
|
1408
|
+
sinks.onConnected?.(host);
|
|
1409
|
+
},
|
|
1410
|
+
onStateChange: (state) => {
|
|
1411
|
+
if (state !== "connected") publishGeneration(void 0);
|
|
1412
|
+
if (!ownsGeneration()) return;
|
|
1413
|
+
publishState(state);
|
|
1414
|
+
sinks.onStateChange?.(state);
|
|
1415
|
+
}
|
|
1416
|
+
}, {
|
|
1417
|
+
...recovery,
|
|
1418
|
+
...config
|
|
1419
|
+
});
|
|
1420
|
+
const current = {
|
|
1421
|
+
token,
|
|
1422
|
+
source,
|
|
1423
|
+
controller,
|
|
1424
|
+
stopNetworkWatch: watchBrowserNetwork(controller)
|
|
1425
|
+
};
|
|
1426
|
+
owner = current;
|
|
1427
|
+
controller.start();
|
|
1428
|
+
return { stop: () => {
|
|
1429
|
+
releaseOwner(current);
|
|
1430
|
+
} };
|
|
1431
|
+
}
|
|
1432
|
+
};
|
|
1433
|
+
ctx.provide("connection", handle);
|
|
1434
|
+
}
|
|
1435
|
+
/**
|
|
1436
|
+
* Client plugin body: read the page composition and install its Connection service.
|
|
1437
|
+
* @param ctx - client Cordis context.
|
|
1438
|
+
*/
|
|
1439
|
+
function apply(ctx) {
|
|
1440
|
+
const globals = globalThis;
|
|
1441
|
+
const pageLocation = typeof location === "undefined" ? void 0 : location;
|
|
1442
|
+
const transport = globals.__QILIN_TRANSPORT__;
|
|
1443
|
+
installConnection(ctx, {
|
|
1444
|
+
...transport === void 0 ? {} : { transport },
|
|
1445
|
+
recovery: resolveConnectionConfig(globals.__QILIN_CONNECTION_RECOVERY__),
|
|
1446
|
+
...pageLocation === void 0 ? {} : { location: pageLocation }
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
//#endregion
|
|
1450
|
+
exports.RpcId = RpcId;
|
|
1451
|
+
exports.apply = apply;
|
|
1452
|
+
exports.inject = inject;
|
|
1453
|
+
exports.installConnection = installConnection;
|
|
1454
|
+
exports.transportError = transportError;
|
|
1455
|
+
return module.exports;
|
|
1456
|
+
}
|
|
1457
|
+
});
|
|
1458
|
+
|
|
1459
|
+
//# sourceMappingURL=client.js.map
|