commanderclaw 1.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.
@@ -0,0 +1,4536 @@
1
+ import { createPluginRuntimeStore, emptyPluginConfigSchema } from 'openclaw/plugin-sdk';
2
+
3
+ /**
4
+ * WebSocket client for CommanderClaw server
5
+ * Cross-platform: works in both Node.js and browser/Electron environments
6
+ */
7
+ function createWebSocket(url, handlers) {
8
+ if (typeof WebSocket !== "undefined") {
9
+ const ws = new WebSocket(url);
10
+ ws.onopen = () => handlers.onOpen();
11
+ ws.onmessage = (event) => handlers.onMessage(event.data);
12
+ ws.onerror = () => handlers.onError(new Error("WebSocket error"));
13
+ ws.onclose = () => handlers.onClose();
14
+ return ws;
15
+ }
16
+ const WS = require("ws");
17
+ const ws = new WS(url);
18
+ ws.on("open", handlers.onOpen);
19
+ ws.on("message", (data) => handlers.onMessage(data.toString()));
20
+ ws.on("error", (error) => handlers.onError(error));
21
+ ws.on("close", handlers.onClose);
22
+ return ws;
23
+ }
24
+ class CommanderClawClient {
25
+ ws = null;
26
+ options;
27
+ nodeId = null;
28
+ peers = [];
29
+ commanderId = null;
30
+ connected = false;
31
+ reconnectAttempts = 0;
32
+ messageHandlers = new Map();
33
+ eventHandlers = new Map();
34
+ heartbeatInterval = null;
35
+ connectionPromise = null;
36
+ constructor(options) {
37
+ this.options = options;
38
+ }
39
+ async connect() {
40
+ return new Promise((resolve, reject) => {
41
+ try {
42
+ this.connectionPromise = { resolve, reject };
43
+ this.ws = createWebSocket(this.options.url, {
44
+ onOpen: () => {
45
+ const payload = {
46
+ id: this.options.name,
47
+ name: this.options.name,
48
+ capabilities: this.options.capabilities,
49
+ token: this.options.token,
50
+ };
51
+ this.send("HELLO", payload);
52
+ },
53
+ onMessage: (data) => {
54
+ try {
55
+ const msg = JSON.parse(data);
56
+ this.handleMessage(msg);
57
+ }
58
+ catch (error) {
59
+ console.error("Failed to parse message:", error);
60
+ }
61
+ },
62
+ onError: (error) => {
63
+ if (this.connectionPromise) {
64
+ this.connectionPromise.reject(error);
65
+ this.connectionPromise = null;
66
+ }
67
+ this.emit("error", { type: "error", data: error });
68
+ },
69
+ onClose: () => {
70
+ this.handleDisconnect();
71
+ },
72
+ });
73
+ }
74
+ catch (error) {
75
+ reject(error);
76
+ }
77
+ });
78
+ }
79
+ handleMessage(msg) {
80
+ console.log(`[CommanderClawClient] handleMessage: type=${msg.type}, from=${msg.from}`);
81
+ switch (msg.type) {
82
+ case "HELLO_ACK": {
83
+ const payload = msg.payload;
84
+ console.log(`[CommanderClawClient] HELLO_ACK received, error=${payload.error}, nodeId=${payload.nodeId}`);
85
+ if (payload.error) {
86
+ if (this.connectionPromise) {
87
+ this.connectionPromise.reject(new Error(payload.error));
88
+ this.connectionPromise = null;
89
+ }
90
+ return;
91
+ }
92
+ this.nodeId = payload.nodeId;
93
+ this.peers = payload.peers || [];
94
+ this.commanderId = payload.commanderId || null;
95
+ this.connected = true;
96
+ this.reconnectAttempts = 0;
97
+ console.log(`[CommanderClawClient] Connected as node ${this.nodeId}, commander=${this.commanderId}, peers=${this.peers.length}`);
98
+ this.startHeartbeat();
99
+ this.emit("connected", { type: "connected", data: { nodeId: this.nodeId } });
100
+ if (this.connectionPromise) {
101
+ this.connectionPromise.resolve();
102
+ this.connectionPromise = null;
103
+ }
104
+ break;
105
+ }
106
+ case "HEARTBEAT_ACK":
107
+ console.log(`[CommanderClawClient] HEARTBEAT_ACK received`);
108
+ break;
109
+ case "PEER_UPDATE": {
110
+ const payload = msg.payload;
111
+ console.log(`[CommanderClawClient] PEER_UPDATE: event=${payload.event}, node=${payload.node?.id}`);
112
+ this.updatePeers(payload.event, payload.node);
113
+ this.emit("peer_update", { type: "peer_update", data: payload });
114
+ break;
115
+ }
116
+ case "TASK_ASSIGN": {
117
+ console.log(`[CommanderClawClient] TASK_ASSIGN received`, msg.payload);
118
+ const handler = this.messageHandlers.get("TASK_ASSIGN");
119
+ if (handler)
120
+ handler(msg);
121
+ this.emit("task_assign", { type: "task_assign", data: msg.payload });
122
+ break;
123
+ }
124
+ case "COMMANDER_APPOINT": {
125
+ const payload = msg.payload;
126
+ console.log(`[CommanderClawClient] COMMANDER_APPOINT: commanderId=${payload.commanderId}`);
127
+ this.commanderId = payload.commanderId;
128
+ this.emit("commander_change", { type: "commander_change", data: payload });
129
+ break;
130
+ }
131
+ case "CHAT": {
132
+ console.log(`[CommanderClawClient] CHAT received`, {
133
+ from: msg.from,
134
+ to: msg.to,
135
+ msgType: msg.msgType,
136
+ payload: msg.payload,
137
+ });
138
+ this.emit("chat", { type: "chat", data: msg });
139
+ break;
140
+ }
141
+ default: {
142
+ console.log(`[CommanderClawClient] Unknown message type: ${msg.type}`);
143
+ const handler = this.messageHandlers.get(msg.type);
144
+ if (handler)
145
+ handler(msg);
146
+ }
147
+ }
148
+ }
149
+ updatePeers(event, node) {
150
+ switch (event) {
151
+ case "join":
152
+ this.peers.push(node);
153
+ break;
154
+ case "leave":
155
+ this.peers = this.peers.filter((p) => p.id !== node.id);
156
+ if (this.commanderId === node.id) {
157
+ this.commanderId = null;
158
+ }
159
+ break;
160
+ case "update":
161
+ const idx = this.peers.findIndex((p) => p.id === node.id);
162
+ if (idx >= 0) {
163
+ this.peers[idx] = node;
164
+ }
165
+ break;
166
+ }
167
+ }
168
+ handleDisconnect() {
169
+ this.connected = false;
170
+ this.nodeId = null;
171
+ if (this.heartbeatInterval) {
172
+ clearInterval(this.heartbeatInterval);
173
+ this.heartbeatInterval = null;
174
+ }
175
+ this.emit("disconnected", { type: "disconnected", data: {} });
176
+ this.attemptReconnect();
177
+ }
178
+ startHeartbeat() {
179
+ this.heartbeatInterval = setInterval(() => {
180
+ if (this.connected && this.ws) {
181
+ this.send("HEARTBEAT", { status: "online", load: 0 });
182
+ }
183
+ }, 5000);
184
+ }
185
+ attemptReconnect() {
186
+ const reconnect = this.options.reconnect;
187
+ if (!reconnect?.enabled)
188
+ return;
189
+ if (this.reconnectAttempts >= reconnect.maxAttempts) {
190
+ console.error("Max reconnect attempts reached");
191
+ return;
192
+ }
193
+ this.reconnectAttempts++;
194
+ console.log(`Reconnecting... attempt ${this.reconnectAttempts}/${reconnect.maxAttempts}`);
195
+ setTimeout(() => {
196
+ this.connect().catch((error) => {
197
+ console.error("Reconnect failed:", error);
198
+ });
199
+ }, reconnect.delayMs);
200
+ }
201
+ async disconnect() {
202
+ if (this.ws) {
203
+ this.send("BYE", { reason: "disconnect" });
204
+ this.ws.close();
205
+ this.ws = null;
206
+ }
207
+ this.connected = false;
208
+ if (this.heartbeatInterval) {
209
+ clearInterval(this.heartbeatInterval);
210
+ this.heartbeatInterval = null;
211
+ }
212
+ }
213
+ send(type, payload) {
214
+ if (!this.ws) {
215
+ console.error(`[CommanderClawClient] send: WebSocket not connected, cannot send ${type}`);
216
+ return;
217
+ }
218
+ const msg = {
219
+ type,
220
+ id: crypto.randomUUID(),
221
+ from: this.nodeId || "unknown",
222
+ payload,
223
+ timestamp: Date.now(),
224
+ };
225
+ console.log(`[CommanderClawClient] send: type=${type}, from=${msg.from}`, payload);
226
+ this.ws.send(JSON.stringify(msg));
227
+ }
228
+ on(event, handler) {
229
+ const handlers = this.eventHandlers.get(event) || [];
230
+ handlers.push(handler);
231
+ this.eventHandlers.set(event, handlers);
232
+ }
233
+ off(event, handler) {
234
+ const handlers = this.eventHandlers.get(event) || [];
235
+ const idx = handlers.indexOf(handler);
236
+ if (idx >= 0) {
237
+ handlers.splice(idx, 1);
238
+ }
239
+ }
240
+ emit(event, data) {
241
+ const handlers = this.eventHandlers.get(event) || [];
242
+ for (const handler of handlers) {
243
+ try {
244
+ handler(data);
245
+ }
246
+ catch (error) {
247
+ console.error(`Error in event handler for ${event}:`, error);
248
+ }
249
+ }
250
+ }
251
+ onMessage(type, handler) {
252
+ this.messageHandlers.set(type, handler);
253
+ }
254
+ isConnected() {
255
+ return this.connected;
256
+ }
257
+ getNodeId() {
258
+ return this.nodeId;
259
+ }
260
+ getPeers() {
261
+ return [...this.peers];
262
+ }
263
+ getCommanderId() {
264
+ return this.commanderId;
265
+ }
266
+ getHttpUrl() {
267
+ return this.options.url.replace("ws://", "http://").replace("wss://", "https://").replace(/\/ws$/, "");
268
+ }
269
+ async fetchApi(path, options = {}) {
270
+ const url = `${this.getHttpUrl()}${path}`;
271
+ const headers = {
272
+ "Content-Type": "application/json",
273
+ ...options.headers,
274
+ };
275
+ if (this.options.token) {
276
+ headers["Authorization"] = `Bearer ${this.options.token}`;
277
+ }
278
+ const response = await fetch(url, {
279
+ ...options,
280
+ headers,
281
+ });
282
+ if (!response.ok) {
283
+ const error = await response.text();
284
+ throw new Error(`API error: ${response.status} ${error}`);
285
+ }
286
+ return response.json();
287
+ }
288
+ async listNodes() {
289
+ const data = await this.fetchApi("/api/nodes");
290
+ return data.nodes || [];
291
+ }
292
+ async getStatus() {
293
+ return this.fetchApi("/api/health");
294
+ }
295
+ async createTask(input) {
296
+ return this.fetchApi("/api/tasks", {
297
+ method: "POST",
298
+ body: JSON.stringify(input),
299
+ });
300
+ }
301
+ async listTasks() {
302
+ const data = await this.fetchApi("/api/tasks");
303
+ return data.tasks || [];
304
+ }
305
+ async getTask(taskId) {
306
+ return this.fetchApi(`/api/tasks/${taskId}`);
307
+ }
308
+ async abortTask(taskId, reason) {
309
+ return this.fetchApi(`/api/tasks/${taskId}/abort`, {
310
+ method: "POST",
311
+ body: JSON.stringify({ reason }),
312
+ });
313
+ }
314
+ async pauseTask(taskId) {
315
+ return this.fetchApi(`/api/tasks/${taskId}/pause`, {
316
+ method: "POST",
317
+ });
318
+ }
319
+ async resumeTask(taskId) {
320
+ return this.fetchApi(`/api/tasks/${taskId}/resume`, {
321
+ method: "POST",
322
+ });
323
+ }
324
+ async appointCommander(nodeId) {
325
+ return this.fetchApi("/api/commander", {
326
+ method: "POST",
327
+ body: JSON.stringify({ nodeId }),
328
+ });
329
+ }
330
+ sendTaskUpdate(payload) {
331
+ this.send("TASK_UPDATE", payload);
332
+ }
333
+ sendTaskResult(payload) {
334
+ this.send("TASK_RESULT", payload);
335
+ }
336
+ }
337
+
338
+ /** Returns true if this value is an async iterator */
339
+ function IsAsyncIterator$2(value) {
340
+ return IsObject$2(value) && !IsArray$2(value) && !IsUint8Array$2(value) && Symbol.asyncIterator in value;
341
+ }
342
+ /** Returns true if this value is an array */
343
+ function IsArray$2(value) {
344
+ return Array.isArray(value);
345
+ }
346
+ /** Returns true if this value is bigint */
347
+ function IsBigInt$2(value) {
348
+ return typeof value === 'bigint';
349
+ }
350
+ /** Returns true if this value is a boolean */
351
+ function IsBoolean$2(value) {
352
+ return typeof value === 'boolean';
353
+ }
354
+ /** Returns true if this value is a Date object */
355
+ function IsDate$2(value) {
356
+ return value instanceof globalThis.Date;
357
+ }
358
+ /** Returns true if this value is a function */
359
+ function IsFunction$2(value) {
360
+ return typeof value === 'function';
361
+ }
362
+ /** Returns true if this value is an iterator */
363
+ function IsIterator$2(value) {
364
+ return IsObject$2(value) && !IsArray$2(value) && !IsUint8Array$2(value) && Symbol.iterator in value;
365
+ }
366
+ /** Returns true if this value is null */
367
+ function IsNull$2(value) {
368
+ return value === null;
369
+ }
370
+ /** Returns true if this value is number */
371
+ function IsNumber$2(value) {
372
+ return typeof value === 'number';
373
+ }
374
+ /** Returns true if this value is an object */
375
+ function IsObject$2(value) {
376
+ return typeof value === 'object' && value !== null;
377
+ }
378
+ /** Returns true if this value is RegExp */
379
+ function IsRegExp$2(value) {
380
+ return value instanceof globalThis.RegExp;
381
+ }
382
+ /** Returns true if this value is string */
383
+ function IsString$2(value) {
384
+ return typeof value === 'string';
385
+ }
386
+ /** Returns true if this value is symbol */
387
+ function IsSymbol$2(value) {
388
+ return typeof value === 'symbol';
389
+ }
390
+ /** Returns true if this value is a Uint8Array */
391
+ function IsUint8Array$2(value) {
392
+ return value instanceof globalThis.Uint8Array;
393
+ }
394
+ /** Returns true if this value is undefined */
395
+ function IsUndefined$2(value) {
396
+ return value === undefined;
397
+ }
398
+
399
+ function ArrayType(value) {
400
+ return value.map((value) => Visit$2(value));
401
+ }
402
+ function DateType(value) {
403
+ return new Date(value.getTime());
404
+ }
405
+ function Uint8ArrayType(value) {
406
+ return new Uint8Array(value);
407
+ }
408
+ function RegExpType(value) {
409
+ return new RegExp(value.source, value.flags);
410
+ }
411
+ function ObjectType(value) {
412
+ const result = {};
413
+ for (const key of Object.getOwnPropertyNames(value)) {
414
+ result[key] = Visit$2(value[key]);
415
+ }
416
+ for (const key of Object.getOwnPropertySymbols(value)) {
417
+ result[key] = Visit$2(value[key]);
418
+ }
419
+ return result;
420
+ }
421
+ // prettier-ignore
422
+ function Visit$2(value) {
423
+ return (IsArray$2(value) ? ArrayType(value) :
424
+ IsDate$2(value) ? DateType(value) :
425
+ IsUint8Array$2(value) ? Uint8ArrayType(value) :
426
+ IsRegExp$2(value) ? RegExpType(value) :
427
+ IsObject$2(value) ? ObjectType(value) :
428
+ value);
429
+ }
430
+ /** Clones a value */
431
+ function Clone(value) {
432
+ return Visit$2(value);
433
+ }
434
+
435
+ /** Clones a Rest */
436
+ function CloneRest(schemas) {
437
+ return schemas.map((schema) => CloneType(schema));
438
+ }
439
+ /** Clones a Type */
440
+ function CloneType(schema, options = {}) {
441
+ return { ...Clone(schema), ...options };
442
+ }
443
+
444
+ /** The base Error type thrown for all TypeBox exceptions */
445
+ class TypeBoxError extends Error {
446
+ constructor(message) {
447
+ super(message);
448
+ }
449
+ }
450
+
451
+ /** Symbol key applied to transform types */
452
+ const TransformKind = Symbol.for('TypeBox.Transform');
453
+ /** Symbol key applied to readonly types */
454
+ const ReadonlyKind = Symbol.for('TypeBox.Readonly');
455
+ /** Symbol key applied to optional types */
456
+ const OptionalKind = Symbol.for('TypeBox.Optional');
457
+ /** Symbol key applied to types */
458
+ const Hint = Symbol.for('TypeBox.Hint');
459
+ /** Symbol key applied to types */
460
+ const Kind = Symbol.for('TypeBox.Kind');
461
+
462
+ /** `[Kind-Only]` Returns true if this value has a Readonly symbol */
463
+ function IsReadonly(value) {
464
+ return IsObject$2(value) && value[ReadonlyKind] === 'Readonly';
465
+ }
466
+ /** `[Kind-Only]` Returns true if this value has a Optional symbol */
467
+ function IsOptional$1(value) {
468
+ return IsObject$2(value) && value[OptionalKind] === 'Optional';
469
+ }
470
+ /** `[Kind-Only]` Returns true if the given value is TAny */
471
+ function IsAny$1(value) {
472
+ return IsKindOf$1(value, 'Any');
473
+ }
474
+ /** `[Kind-Only]` Returns true if the given value is TArray */
475
+ function IsArray$1(value) {
476
+ return IsKindOf$1(value, 'Array');
477
+ }
478
+ /** `[Kind-Only]` Returns true if the given value is TAsyncIterator */
479
+ function IsAsyncIterator$1(value) {
480
+ return IsKindOf$1(value, 'AsyncIterator');
481
+ }
482
+ /** `[Kind-Only]` Returns true if the given value is TBigInt */
483
+ function IsBigInt$1(value) {
484
+ return IsKindOf$1(value, 'BigInt');
485
+ }
486
+ /** `[Kind-Only]` Returns true if the given value is TBoolean */
487
+ function IsBoolean$1(value) {
488
+ return IsKindOf$1(value, 'Boolean');
489
+ }
490
+ /** `[Kind-Only]` Returns true if the given value is TConstructor */
491
+ function IsConstructor$1(value) {
492
+ return IsKindOf$1(value, 'Constructor');
493
+ }
494
+ /** `[Kind-Only]` Returns true if the given value is TDate */
495
+ function IsDate$1(value) {
496
+ return IsKindOf$1(value, 'Date');
497
+ }
498
+ /** `[Kind-Only]` Returns true if the given value is TFunction */
499
+ function IsFunction$1(value) {
500
+ return IsKindOf$1(value, 'Function');
501
+ }
502
+ /** `[Kind-Only]` Returns true if the given value is TInteger */
503
+ function IsInteger$1(value) {
504
+ return IsKindOf$1(value, 'Integer');
505
+ }
506
+ /** `[Kind-Only]` Returns true if the given value is TIntersect */
507
+ function IsIntersect$1(value) {
508
+ return IsKindOf$1(value, 'Intersect');
509
+ }
510
+ /** `[Kind-Only]` Returns true if the given value is TIterator */
511
+ function IsIterator$1(value) {
512
+ return IsKindOf$1(value, 'Iterator');
513
+ }
514
+ /** `[Kind-Only]` Returns true if the given value is a TKind with the given name. */
515
+ function IsKindOf$1(value, kind) {
516
+ return IsObject$2(value) && Kind in value && value[Kind] === kind;
517
+ }
518
+ /** `[Kind-Only]` Returns true if the given value is TLiteral */
519
+ function IsLiteral$1(value) {
520
+ return IsKindOf$1(value, 'Literal');
521
+ }
522
+ /** `[Kind-Only]` Returns true if the given value is a TMappedKey */
523
+ function IsMappedKey$1(value) {
524
+ return IsKindOf$1(value, 'MappedKey');
525
+ }
526
+ /** `[Kind-Only]` Returns true if the given value is TMappedResult */
527
+ function IsMappedResult$1(value) {
528
+ return IsKindOf$1(value, 'MappedResult');
529
+ }
530
+ /** `[Kind-Only]` Returns true if the given value is TNever */
531
+ function IsNever$1(value) {
532
+ return IsKindOf$1(value, 'Never');
533
+ }
534
+ /** `[Kind-Only]` Returns true if the given value is TNot */
535
+ function IsNot$1(value) {
536
+ return IsKindOf$1(value, 'Not');
537
+ }
538
+ /** `[Kind-Only]` Returns true if the given value is TNull */
539
+ function IsNull$1(value) {
540
+ return IsKindOf$1(value, 'Null');
541
+ }
542
+ /** `[Kind-Only]` Returns true if the given value is TNumber */
543
+ function IsNumber$1(value) {
544
+ return IsKindOf$1(value, 'Number');
545
+ }
546
+ /** `[Kind-Only]` Returns true if the given value is TObject */
547
+ function IsObject$1(value) {
548
+ return IsKindOf$1(value, 'Object');
549
+ }
550
+ /** `[Kind-Only]` Returns true if the given value is TPromise */
551
+ function IsPromise$1(value) {
552
+ return IsKindOf$1(value, 'Promise');
553
+ }
554
+ /** `[Kind-Only]` Returns true if the given value is TRecord */
555
+ function IsRecord$1(value) {
556
+ return IsKindOf$1(value, 'Record');
557
+ }
558
+ /** `[Kind-Only]` Returns true if the given value is TRef */
559
+ function IsRef$1(value) {
560
+ return IsKindOf$1(value, 'Ref');
561
+ }
562
+ /** `[Kind-Only]` Returns true if the given value is TRegExp */
563
+ function IsRegExp$1(value) {
564
+ return IsKindOf$1(value, 'RegExp');
565
+ }
566
+ /** `[Kind-Only]` Returns true if the given value is TString */
567
+ function IsString$1(value) {
568
+ return IsKindOf$1(value, 'String');
569
+ }
570
+ /** `[Kind-Only]` Returns true if the given value is TSymbol */
571
+ function IsSymbol$1(value) {
572
+ return IsKindOf$1(value, 'Symbol');
573
+ }
574
+ /** `[Kind-Only]` Returns true if the given value is TTemplateLiteral */
575
+ function IsTemplateLiteral$1(value) {
576
+ return IsKindOf$1(value, 'TemplateLiteral');
577
+ }
578
+ /** `[Kind-Only]` Returns true if the given value is TThis */
579
+ function IsThis$1(value) {
580
+ return IsKindOf$1(value, 'This');
581
+ }
582
+ /** `[Kind-Only]` Returns true of this value is TTransform */
583
+ function IsTransform$1(value) {
584
+ return IsObject$2(value) && TransformKind in value;
585
+ }
586
+ /** `[Kind-Only]` Returns true if the given value is TTuple */
587
+ function IsTuple$1(value) {
588
+ return IsKindOf$1(value, 'Tuple');
589
+ }
590
+ /** `[Kind-Only]` Returns true if the given value is TUndefined */
591
+ function IsUndefined$1(value) {
592
+ return IsKindOf$1(value, 'Undefined');
593
+ }
594
+ /** `[Kind-Only]` Returns true if the given value is TUnion */
595
+ function IsUnion$1(value) {
596
+ return IsKindOf$1(value, 'Union');
597
+ }
598
+ /** `[Kind-Only]` Returns true if the given value is TUint8Array */
599
+ function IsUint8Array$1(value) {
600
+ return IsKindOf$1(value, 'Uint8Array');
601
+ }
602
+ /** `[Kind-Only]` Returns true if the given value is TUnknown */
603
+ function IsUnknown$1(value) {
604
+ return IsKindOf$1(value, 'Unknown');
605
+ }
606
+ /** `[Kind-Only]` Returns true if the given value is a raw TUnsafe */
607
+ function IsUnsafe$1(value) {
608
+ return IsKindOf$1(value, 'Unsafe');
609
+ }
610
+ /** `[Kind-Only]` Returns true if the given value is TVoid */
611
+ function IsVoid$1(value) {
612
+ return IsKindOf$1(value, 'Void');
613
+ }
614
+ /** `[Kind-Only]` Returns true if the given value is TKind */
615
+ function IsKind$1(value) {
616
+ return IsObject$2(value) && Kind in value && IsString$2(value[Kind]);
617
+ }
618
+ /** `[Kind-Only]` Returns true if the given value is TSchema */
619
+ function IsSchema$1(value) {
620
+ // prettier-ignore
621
+ return (IsAny$1(value) ||
622
+ IsArray$1(value) ||
623
+ IsBoolean$1(value) ||
624
+ IsBigInt$1(value) ||
625
+ IsAsyncIterator$1(value) ||
626
+ IsConstructor$1(value) ||
627
+ IsDate$1(value) ||
628
+ IsFunction$1(value) ||
629
+ IsInteger$1(value) ||
630
+ IsIntersect$1(value) ||
631
+ IsIterator$1(value) ||
632
+ IsLiteral$1(value) ||
633
+ IsMappedKey$1(value) ||
634
+ IsMappedResult$1(value) ||
635
+ IsNever$1(value) ||
636
+ IsNot$1(value) ||
637
+ IsNull$1(value) ||
638
+ IsNumber$1(value) ||
639
+ IsObject$1(value) ||
640
+ IsPromise$1(value) ||
641
+ IsRecord$1(value) ||
642
+ IsRef$1(value) ||
643
+ IsRegExp$1(value) ||
644
+ IsString$1(value) ||
645
+ IsSymbol$1(value) ||
646
+ IsTemplateLiteral$1(value) ||
647
+ IsThis$1(value) ||
648
+ IsTuple$1(value) ||
649
+ IsUndefined$1(value) ||
650
+ IsUnion$1(value) ||
651
+ IsUint8Array$1(value) ||
652
+ IsUnknown$1(value) ||
653
+ IsUnsafe$1(value) ||
654
+ IsVoid$1(value) ||
655
+ IsKind$1(value));
656
+ }
657
+
658
+ const KnownTypes = [
659
+ 'Any',
660
+ 'Array',
661
+ 'AsyncIterator',
662
+ 'BigInt',
663
+ 'Boolean',
664
+ 'Constructor',
665
+ 'Date',
666
+ 'Enum',
667
+ 'Function',
668
+ 'Integer',
669
+ 'Intersect',
670
+ 'Iterator',
671
+ 'Literal',
672
+ 'MappedKey',
673
+ 'MappedResult',
674
+ 'Not',
675
+ 'Null',
676
+ 'Number',
677
+ 'Object',
678
+ 'Promise',
679
+ 'Record',
680
+ 'Ref',
681
+ 'RegExp',
682
+ 'String',
683
+ 'Symbol',
684
+ 'TemplateLiteral',
685
+ 'This',
686
+ 'Tuple',
687
+ 'Undefined',
688
+ 'Union',
689
+ 'Uint8Array',
690
+ 'Unknown',
691
+ 'Void',
692
+ ];
693
+ function IsPattern(value) {
694
+ try {
695
+ new RegExp(value);
696
+ return true;
697
+ }
698
+ catch {
699
+ return false;
700
+ }
701
+ }
702
+ function IsControlCharacterFree(value) {
703
+ if (!IsString$2(value))
704
+ return false;
705
+ for (let i = 0; i < value.length; i++) {
706
+ const code = value.charCodeAt(i);
707
+ if ((code >= 7 && code <= 13) || code === 27 || code === 127) {
708
+ return false;
709
+ }
710
+ }
711
+ return true;
712
+ }
713
+ function IsAdditionalProperties(value) {
714
+ return IsOptionalBoolean(value) || IsSchema(value);
715
+ }
716
+ function IsOptionalBigInt(value) {
717
+ return IsUndefined$2(value) || IsBigInt$2(value);
718
+ }
719
+ function IsOptionalNumber(value) {
720
+ return IsUndefined$2(value) || IsNumber$2(value);
721
+ }
722
+ function IsOptionalBoolean(value) {
723
+ return IsUndefined$2(value) || IsBoolean$2(value);
724
+ }
725
+ function IsOptionalString(value) {
726
+ return IsUndefined$2(value) || IsString$2(value);
727
+ }
728
+ function IsOptionalPattern(value) {
729
+ return IsUndefined$2(value) || (IsString$2(value) && IsControlCharacterFree(value) && IsPattern(value));
730
+ }
731
+ function IsOptionalFormat(value) {
732
+ return IsUndefined$2(value) || (IsString$2(value) && IsControlCharacterFree(value));
733
+ }
734
+ function IsOptionalSchema(value) {
735
+ return IsUndefined$2(value) || IsSchema(value);
736
+ }
737
+ /** Returns true if this value has a Optional symbol */
738
+ function IsOptional(value) {
739
+ return IsObject$2(value) && value[OptionalKind] === 'Optional';
740
+ }
741
+ // ------------------------------------------------------------------
742
+ // Types
743
+ // ------------------------------------------------------------------
744
+ /** Returns true if the given value is TAny */
745
+ function IsAny(value) {
746
+ // prettier-ignore
747
+ return (IsKindOf(value, 'Any') &&
748
+ IsOptionalString(value.$id));
749
+ }
750
+ /** Returns true if the given value is TArray */
751
+ function IsArray(value) {
752
+ return (IsKindOf(value, 'Array') &&
753
+ value.type === 'array' &&
754
+ IsOptionalString(value.$id) &&
755
+ IsSchema(value.items) &&
756
+ IsOptionalNumber(value.minItems) &&
757
+ IsOptionalNumber(value.maxItems) &&
758
+ IsOptionalBoolean(value.uniqueItems) &&
759
+ IsOptionalSchema(value.contains) &&
760
+ IsOptionalNumber(value.minContains) &&
761
+ IsOptionalNumber(value.maxContains));
762
+ }
763
+ /** Returns true if the given value is TAsyncIterator */
764
+ function IsAsyncIterator(value) {
765
+ // prettier-ignore
766
+ return (IsKindOf(value, 'AsyncIterator') &&
767
+ value.type === 'AsyncIterator' &&
768
+ IsOptionalString(value.$id) &&
769
+ IsSchema(value.items));
770
+ }
771
+ /** Returns true if the given value is TBigInt */
772
+ function IsBigInt(value) {
773
+ // prettier-ignore
774
+ return (IsKindOf(value, 'BigInt') &&
775
+ value.type === 'bigint' &&
776
+ IsOptionalString(value.$id) &&
777
+ IsOptionalBigInt(value.exclusiveMaximum) &&
778
+ IsOptionalBigInt(value.exclusiveMinimum) &&
779
+ IsOptionalBigInt(value.maximum) &&
780
+ IsOptionalBigInt(value.minimum) &&
781
+ IsOptionalBigInt(value.multipleOf));
782
+ }
783
+ /** Returns true if the given value is TBoolean */
784
+ function IsBoolean(value) {
785
+ // prettier-ignore
786
+ return (IsKindOf(value, 'Boolean') &&
787
+ value.type === 'boolean' &&
788
+ IsOptionalString(value.$id));
789
+ }
790
+ /** Returns true if the given value is TConstructor */
791
+ function IsConstructor(value) {
792
+ // prettier-ignore
793
+ return (IsKindOf(value, 'Constructor') &&
794
+ value.type === 'Constructor' &&
795
+ IsOptionalString(value.$id) &&
796
+ IsArray$2(value.parameters) &&
797
+ value.parameters.every(schema => IsSchema(schema)) &&
798
+ IsSchema(value.returns));
799
+ }
800
+ /** Returns true if the given value is TDate */
801
+ function IsDate(value) {
802
+ return (IsKindOf(value, 'Date') &&
803
+ value.type === 'Date' &&
804
+ IsOptionalString(value.$id) &&
805
+ IsOptionalNumber(value.exclusiveMaximumTimestamp) &&
806
+ IsOptionalNumber(value.exclusiveMinimumTimestamp) &&
807
+ IsOptionalNumber(value.maximumTimestamp) &&
808
+ IsOptionalNumber(value.minimumTimestamp) &&
809
+ IsOptionalNumber(value.multipleOfTimestamp));
810
+ }
811
+ /** Returns true if the given value is TFunction */
812
+ function IsFunction(value) {
813
+ // prettier-ignore
814
+ return (IsKindOf(value, 'Function') &&
815
+ value.type === 'Function' &&
816
+ IsOptionalString(value.$id) &&
817
+ IsArray$2(value.parameters) &&
818
+ value.parameters.every(schema => IsSchema(schema)) &&
819
+ IsSchema(value.returns));
820
+ }
821
+ /** Returns true if the given value is TInteger */
822
+ function IsInteger(value) {
823
+ return (IsKindOf(value, 'Integer') &&
824
+ value.type === 'integer' &&
825
+ IsOptionalString(value.$id) &&
826
+ IsOptionalNumber(value.exclusiveMaximum) &&
827
+ IsOptionalNumber(value.exclusiveMinimum) &&
828
+ IsOptionalNumber(value.maximum) &&
829
+ IsOptionalNumber(value.minimum) &&
830
+ IsOptionalNumber(value.multipleOf));
831
+ }
832
+ /** Returns true if the given schema is TProperties */
833
+ function IsProperties(value) {
834
+ // prettier-ignore
835
+ return (IsObject$2(value) &&
836
+ Object.entries(value).every(([key, schema]) => IsControlCharacterFree(key) && IsSchema(schema)));
837
+ }
838
+ /** Returns true if the given value is TIntersect */
839
+ function IsIntersect(value) {
840
+ // prettier-ignore
841
+ return (IsKindOf(value, 'Intersect') &&
842
+ (IsString$2(value.type) && value.type !== 'object' ? false : true) &&
843
+ IsArray$2(value.allOf) &&
844
+ value.allOf.every(schema => IsSchema(schema) && !IsTransform(schema)) &&
845
+ IsOptionalString(value.type) &&
846
+ (IsOptionalBoolean(value.unevaluatedProperties) || IsOptionalSchema(value.unevaluatedProperties)) &&
847
+ IsOptionalString(value.$id));
848
+ }
849
+ /** Returns true if the given value is TIterator */
850
+ function IsIterator(value) {
851
+ // prettier-ignore
852
+ return (IsKindOf(value, 'Iterator') &&
853
+ value.type === 'Iterator' &&
854
+ IsOptionalString(value.$id) &&
855
+ IsSchema(value.items));
856
+ }
857
+ /** Returns true if the given value is a TKind with the given name. */
858
+ function IsKindOf(value, kind) {
859
+ return IsObject$2(value) && Kind in value && value[Kind] === kind;
860
+ }
861
+ /** Returns true if the given value is TLiteral<string> */
862
+ function IsLiteralString(value) {
863
+ return IsLiteral(value) && IsString$2(value.const);
864
+ }
865
+ /** Returns true if the given value is TLiteral<number> */
866
+ function IsLiteralNumber(value) {
867
+ return IsLiteral(value) && IsNumber$2(value.const);
868
+ }
869
+ /** Returns true if the given value is TLiteral<boolean> */
870
+ function IsLiteralBoolean(value) {
871
+ return IsLiteral(value) && IsBoolean$2(value.const);
872
+ }
873
+ /** Returns true if the given value is TLiteral */
874
+ function IsLiteral(value) {
875
+ // prettier-ignore
876
+ return (IsKindOf(value, 'Literal') &&
877
+ IsOptionalString(value.$id) && IsLiteralValue(value.const));
878
+ }
879
+ /** Returns true if the given value is a TLiteralValue */
880
+ function IsLiteralValue(value) {
881
+ return IsBoolean$2(value) || IsNumber$2(value) || IsString$2(value);
882
+ }
883
+ /** Returns true if the given value is a TMappedKey */
884
+ function IsMappedKey(value) {
885
+ // prettier-ignore
886
+ return (IsKindOf(value, 'MappedKey') &&
887
+ IsArray$2(value.keys) &&
888
+ value.keys.every(key => IsNumber$2(key) || IsString$2(key)));
889
+ }
890
+ /** Returns true if the given value is TMappedResult */
891
+ function IsMappedResult(value) {
892
+ // prettier-ignore
893
+ return (IsKindOf(value, 'MappedResult') &&
894
+ IsProperties(value.properties));
895
+ }
896
+ /** Returns true if the given value is TNever */
897
+ function IsNever(value) {
898
+ // prettier-ignore
899
+ return (IsKindOf(value, 'Never') &&
900
+ IsObject$2(value.not) &&
901
+ Object.getOwnPropertyNames(value.not).length === 0);
902
+ }
903
+ /** Returns true if the given value is TNot */
904
+ function IsNot(value) {
905
+ // prettier-ignore
906
+ return (IsKindOf(value, 'Not') &&
907
+ IsSchema(value.not));
908
+ }
909
+ /** Returns true if the given value is TNull */
910
+ function IsNull(value) {
911
+ // prettier-ignore
912
+ return (IsKindOf(value, 'Null') &&
913
+ value.type === 'null' &&
914
+ IsOptionalString(value.$id));
915
+ }
916
+ /** Returns true if the given value is TNumber */
917
+ function IsNumber(value) {
918
+ return (IsKindOf(value, 'Number') &&
919
+ value.type === 'number' &&
920
+ IsOptionalString(value.$id) &&
921
+ IsOptionalNumber(value.exclusiveMaximum) &&
922
+ IsOptionalNumber(value.exclusiveMinimum) &&
923
+ IsOptionalNumber(value.maximum) &&
924
+ IsOptionalNumber(value.minimum) &&
925
+ IsOptionalNumber(value.multipleOf));
926
+ }
927
+ /** Returns true if the given value is TObject */
928
+ function IsObject(value) {
929
+ // prettier-ignore
930
+ return (IsKindOf(value, 'Object') &&
931
+ value.type === 'object' &&
932
+ IsOptionalString(value.$id) &&
933
+ IsProperties(value.properties) &&
934
+ IsAdditionalProperties(value.additionalProperties) &&
935
+ IsOptionalNumber(value.minProperties) &&
936
+ IsOptionalNumber(value.maxProperties));
937
+ }
938
+ /** Returns true if the given value is TPromise */
939
+ function IsPromise(value) {
940
+ // prettier-ignore
941
+ return (IsKindOf(value, 'Promise') &&
942
+ value.type === 'Promise' &&
943
+ IsOptionalString(value.$id) &&
944
+ IsSchema(value.item));
945
+ }
946
+ /** Returns true if the given value is TRecord */
947
+ function IsRecord(value) {
948
+ // prettier-ignore
949
+ return (IsKindOf(value, 'Record') &&
950
+ value.type === 'object' &&
951
+ IsOptionalString(value.$id) &&
952
+ IsAdditionalProperties(value.additionalProperties) &&
953
+ IsObject$2(value.patternProperties) &&
954
+ ((schema) => {
955
+ const keys = Object.getOwnPropertyNames(schema.patternProperties);
956
+ return (keys.length === 1 &&
957
+ IsPattern(keys[0]) &&
958
+ IsObject$2(schema.patternProperties) &&
959
+ IsSchema(schema.patternProperties[keys[0]]));
960
+ })(value));
961
+ }
962
+ /** Returns true if the given value is TRef */
963
+ function IsRef(value) {
964
+ // prettier-ignore
965
+ return (IsKindOf(value, 'Ref') &&
966
+ IsOptionalString(value.$id) &&
967
+ IsString$2(value.$ref));
968
+ }
969
+ /** Returns true if the given value is TRegExp */
970
+ function IsRegExp(value) {
971
+ // prettier-ignore
972
+ return (IsKindOf(value, 'RegExp') &&
973
+ IsOptionalString(value.$id) &&
974
+ IsString$2(value.source) &&
975
+ IsString$2(value.flags) &&
976
+ IsOptionalNumber(value.maxLength) &&
977
+ IsOptionalNumber(value.minLength));
978
+ }
979
+ /** Returns true if the given value is TString */
980
+ function IsString(value) {
981
+ // prettier-ignore
982
+ return (IsKindOf(value, 'String') &&
983
+ value.type === 'string' &&
984
+ IsOptionalString(value.$id) &&
985
+ IsOptionalNumber(value.minLength) &&
986
+ IsOptionalNumber(value.maxLength) &&
987
+ IsOptionalPattern(value.pattern) &&
988
+ IsOptionalFormat(value.format));
989
+ }
990
+ /** Returns true if the given value is TSymbol */
991
+ function IsSymbol(value) {
992
+ // prettier-ignore
993
+ return (IsKindOf(value, 'Symbol') &&
994
+ value.type === 'symbol' &&
995
+ IsOptionalString(value.$id));
996
+ }
997
+ /** Returns true if the given value is TTemplateLiteral */
998
+ function IsTemplateLiteral(value) {
999
+ // prettier-ignore
1000
+ return (IsKindOf(value, 'TemplateLiteral') &&
1001
+ value.type === 'string' &&
1002
+ IsString$2(value.pattern) &&
1003
+ value.pattern[0] === '^' &&
1004
+ value.pattern[value.pattern.length - 1] === '$');
1005
+ }
1006
+ /** Returns true if the given value is TThis */
1007
+ function IsThis(value) {
1008
+ // prettier-ignore
1009
+ return (IsKindOf(value, 'This') &&
1010
+ IsOptionalString(value.$id) &&
1011
+ IsString$2(value.$ref));
1012
+ }
1013
+ /** Returns true of this value is TTransform */
1014
+ function IsTransform(value) {
1015
+ return IsObject$2(value) && TransformKind in value;
1016
+ }
1017
+ /** Returns true if the given value is TTuple */
1018
+ function IsTuple(value) {
1019
+ // prettier-ignore
1020
+ return (IsKindOf(value, 'Tuple') &&
1021
+ value.type === 'array' &&
1022
+ IsOptionalString(value.$id) &&
1023
+ IsNumber$2(value.minItems) &&
1024
+ IsNumber$2(value.maxItems) &&
1025
+ value.minItems === value.maxItems &&
1026
+ (( // empty
1027
+ IsUndefined$2(value.items) &&
1028
+ IsUndefined$2(value.additionalItems) &&
1029
+ value.minItems === 0) || (IsArray$2(value.items) &&
1030
+ value.items.every(schema => IsSchema(schema)))));
1031
+ }
1032
+ /** Returns true if the given value is TUndefined */
1033
+ function IsUndefined(value) {
1034
+ // prettier-ignore
1035
+ return (IsKindOf(value, 'Undefined') &&
1036
+ value.type === 'undefined' &&
1037
+ IsOptionalString(value.$id));
1038
+ }
1039
+ /** Returns true if the given value is TUnion */
1040
+ function IsUnion(value) {
1041
+ // prettier-ignore
1042
+ return (IsKindOf(value, 'Union') &&
1043
+ IsOptionalString(value.$id) &&
1044
+ IsObject$2(value) &&
1045
+ IsArray$2(value.anyOf) &&
1046
+ value.anyOf.every(schema => IsSchema(schema)));
1047
+ }
1048
+ /** Returns true if the given value is TUint8Array */
1049
+ function IsUint8Array(value) {
1050
+ // prettier-ignore
1051
+ return (IsKindOf(value, 'Uint8Array') &&
1052
+ value.type === 'Uint8Array' &&
1053
+ IsOptionalString(value.$id) &&
1054
+ IsOptionalNumber(value.minByteLength) &&
1055
+ IsOptionalNumber(value.maxByteLength));
1056
+ }
1057
+ /** Returns true if the given value is TUnknown */
1058
+ function IsUnknown(value) {
1059
+ // prettier-ignore
1060
+ return (IsKindOf(value, 'Unknown') &&
1061
+ IsOptionalString(value.$id));
1062
+ }
1063
+ /** Returns true if the given value is a raw TUnsafe */
1064
+ function IsUnsafe(value) {
1065
+ return IsKindOf(value, 'Unsafe');
1066
+ }
1067
+ /** Returns true if the given value is TVoid */
1068
+ function IsVoid(value) {
1069
+ // prettier-ignore
1070
+ return (IsKindOf(value, 'Void') &&
1071
+ value.type === 'void' &&
1072
+ IsOptionalString(value.$id));
1073
+ }
1074
+ /** Returns true if the given value is TKind */
1075
+ function IsKind(value) {
1076
+ return IsObject$2(value) && Kind in value && IsString$2(value[Kind]) && !KnownTypes.includes(value[Kind]);
1077
+ }
1078
+ /** Returns true if the given value is TSchema */
1079
+ function IsSchema(value) {
1080
+ // prettier-ignore
1081
+ return (IsObject$2(value)) && (IsAny(value) ||
1082
+ IsArray(value) ||
1083
+ IsBoolean(value) ||
1084
+ IsBigInt(value) ||
1085
+ IsAsyncIterator(value) ||
1086
+ IsConstructor(value) ||
1087
+ IsDate(value) ||
1088
+ IsFunction(value) ||
1089
+ IsInteger(value) ||
1090
+ IsIntersect(value) ||
1091
+ IsIterator(value) ||
1092
+ IsLiteral(value) ||
1093
+ IsMappedKey(value) ||
1094
+ IsMappedResult(value) ||
1095
+ IsNever(value) ||
1096
+ IsNot(value) ||
1097
+ IsNull(value) ||
1098
+ IsNumber(value) ||
1099
+ IsObject(value) ||
1100
+ IsPromise(value) ||
1101
+ IsRecord(value) ||
1102
+ IsRef(value) ||
1103
+ IsRegExp(value) ||
1104
+ IsString(value) ||
1105
+ IsSymbol(value) ||
1106
+ IsTemplateLiteral(value) ||
1107
+ IsThis(value) ||
1108
+ IsTuple(value) ||
1109
+ IsUndefined(value) ||
1110
+ IsUnion(value) ||
1111
+ IsUint8Array(value) ||
1112
+ IsUnknown(value) ||
1113
+ IsUnsafe(value) ||
1114
+ IsVoid(value) ||
1115
+ IsKind(value));
1116
+ }
1117
+
1118
+ const PatternBoolean = '(true|false)';
1119
+ const PatternNumber = '(0|[1-9][0-9]*)';
1120
+ const PatternString = '(.*)';
1121
+ const PatternNever = '(?!.*)';
1122
+ const PatternNumberExact = `^${PatternNumber}$`;
1123
+ const PatternStringExact = `^${PatternString}$`;
1124
+ const PatternNeverExact = `^${PatternNever}$`;
1125
+
1126
+ /** Returns true if element right is in the set of left */
1127
+ // prettier-ignore
1128
+ function SetIncludes(T, S) {
1129
+ return T.includes(S);
1130
+ }
1131
+ /** Returns a distinct set of elements */
1132
+ function SetDistinct(T) {
1133
+ return [...new Set(T)];
1134
+ }
1135
+ /** Returns the Intersect of the given sets */
1136
+ function SetIntersect(T, S) {
1137
+ return T.filter((L) => S.includes(L));
1138
+ }
1139
+ // prettier-ignore
1140
+ function SetIntersectManyResolve(T, Init) {
1141
+ return T.reduce((Acc, L) => {
1142
+ return SetIntersect(Acc, L);
1143
+ }, Init);
1144
+ }
1145
+ // prettier-ignore
1146
+ function SetIntersectMany(T) {
1147
+ return (T.length === 1
1148
+ ? T[0]
1149
+ // Use left to initialize the accumulator for resolve
1150
+ : T.length > 1
1151
+ ? SetIntersectManyResolve(T.slice(1), T[0])
1152
+ : []);
1153
+ }
1154
+ /** Returns the Union of multiple sets */
1155
+ function SetUnionMany(T) {
1156
+ const Acc = [];
1157
+ for (const L of T)
1158
+ Acc.push(...L);
1159
+ return Acc;
1160
+ }
1161
+
1162
+ /** `[Json]` Creates an Any type */
1163
+ function Any(options = {}) {
1164
+ return { ...options, [Kind]: 'Any' };
1165
+ }
1166
+
1167
+ /** `[Json]` Creates an Array type */
1168
+ function Array$1(schema, options = {}) {
1169
+ return {
1170
+ ...options,
1171
+ [Kind]: 'Array',
1172
+ type: 'array',
1173
+ items: CloneType(schema),
1174
+ };
1175
+ }
1176
+
1177
+ /** `[JavaScript]` Creates a AsyncIterator type */
1178
+ function AsyncIterator(items, options = {}) {
1179
+ return {
1180
+ ...options,
1181
+ [Kind]: 'AsyncIterator',
1182
+ type: 'AsyncIterator',
1183
+ items: CloneType(items),
1184
+ };
1185
+ }
1186
+
1187
+ function DiscardKey(value, key) {
1188
+ const { [key]: _, ...rest } = value;
1189
+ return rest;
1190
+ }
1191
+ function Discard(value, keys) {
1192
+ return keys.reduce((acc, key) => DiscardKey(acc, key), value);
1193
+ }
1194
+
1195
+ /** `[Json]` Creates a Never type */
1196
+ function Never(options = {}) {
1197
+ return {
1198
+ ...options,
1199
+ [Kind]: 'Never',
1200
+ not: {},
1201
+ };
1202
+ }
1203
+
1204
+ // prettier-ignore
1205
+ function MappedResult(properties) {
1206
+ return {
1207
+ [Kind]: 'MappedResult',
1208
+ properties
1209
+ };
1210
+ }
1211
+
1212
+ /** `[JavaScript]` Creates a Constructor type */
1213
+ function Constructor(parameters, returns, options) {
1214
+ return {
1215
+ ...options,
1216
+ [Kind]: 'Constructor',
1217
+ type: 'Constructor',
1218
+ parameters: CloneRest(parameters),
1219
+ returns: CloneType(returns),
1220
+ };
1221
+ }
1222
+
1223
+ /** `[JavaScript]` Creates a Function type */
1224
+ function Function(parameters, returns, options) {
1225
+ return {
1226
+ ...options,
1227
+ [Kind]: 'Function',
1228
+ type: 'Function',
1229
+ parameters: CloneRest(parameters),
1230
+ returns: CloneType(returns),
1231
+ };
1232
+ }
1233
+
1234
+ function UnionCreate(T, options) {
1235
+ return { ...options, [Kind]: 'Union', anyOf: CloneRest(T) };
1236
+ }
1237
+
1238
+ // prettier-ignore
1239
+ function IsUnionOptional(T) {
1240
+ return T.some(L => IsOptional$1(L));
1241
+ }
1242
+ // prettier-ignore
1243
+ function RemoveOptionalFromRest$1(T) {
1244
+ return T.map(L => IsOptional$1(L) ? RemoveOptionalFromType$1(L) : L);
1245
+ }
1246
+ // prettier-ignore
1247
+ function RemoveOptionalFromType$1(T) {
1248
+ return (Discard(T, [OptionalKind]));
1249
+ }
1250
+ // prettier-ignore
1251
+ function ResolveUnion(T, options) {
1252
+ return (IsUnionOptional(T)
1253
+ ? Optional(UnionCreate(RemoveOptionalFromRest$1(T), options))
1254
+ : UnionCreate(RemoveOptionalFromRest$1(T), options));
1255
+ }
1256
+ /** `[Json]` Creates an evaluated Union type */
1257
+ function UnionEvaluated(T, options = {}) {
1258
+ // prettier-ignore
1259
+ return (T.length === 0 ? Never(options) :
1260
+ T.length === 1 ? CloneType(T[0], options) :
1261
+ ResolveUnion(T, options));
1262
+ }
1263
+
1264
+ /** `[Json]` Creates a Union type */
1265
+ function Union(T, options = {}) {
1266
+ // prettier-ignore
1267
+ return (T.length === 0 ? Never(options) :
1268
+ T.length === 1 ? CloneType(T[0], options) :
1269
+ UnionCreate(T, options));
1270
+ }
1271
+
1272
+ // ------------------------------------------------------------------
1273
+ // TemplateLiteralParserError
1274
+ // ------------------------------------------------------------------
1275
+ class TemplateLiteralParserError extends TypeBoxError {
1276
+ }
1277
+ // -------------------------------------------------------------------
1278
+ // Unescape
1279
+ //
1280
+ // Unescape for these control characters specifically. Note that this
1281
+ // function is only called on non union group content, and where we
1282
+ // still want to allow the user to embed control characters in that
1283
+ // content. For review.
1284
+ // -------------------------------------------------------------------
1285
+ // prettier-ignore
1286
+ function Unescape(pattern) {
1287
+ return pattern
1288
+ .replace(/\\\$/g, '$')
1289
+ .replace(/\\\*/g, '*')
1290
+ .replace(/\\\^/g, '^')
1291
+ .replace(/\\\|/g, '|')
1292
+ .replace(/\\\(/g, '(')
1293
+ .replace(/\\\)/g, ')');
1294
+ }
1295
+ // -------------------------------------------------------------------
1296
+ // Control Characters
1297
+ // -------------------------------------------------------------------
1298
+ function IsNonEscaped(pattern, index, char) {
1299
+ return pattern[index] === char && pattern.charCodeAt(index - 1) !== 92;
1300
+ }
1301
+ function IsOpenParen(pattern, index) {
1302
+ return IsNonEscaped(pattern, index, '(');
1303
+ }
1304
+ function IsCloseParen(pattern, index) {
1305
+ return IsNonEscaped(pattern, index, ')');
1306
+ }
1307
+ function IsSeparator(pattern, index) {
1308
+ return IsNonEscaped(pattern, index, '|');
1309
+ }
1310
+ // -------------------------------------------------------------------
1311
+ // Control Groups
1312
+ // -------------------------------------------------------------------
1313
+ function IsGroup(pattern) {
1314
+ if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1)))
1315
+ return false;
1316
+ let count = 0;
1317
+ for (let index = 0; index < pattern.length; index++) {
1318
+ if (IsOpenParen(pattern, index))
1319
+ count += 1;
1320
+ if (IsCloseParen(pattern, index))
1321
+ count -= 1;
1322
+ if (count === 0 && index !== pattern.length - 1)
1323
+ return false;
1324
+ }
1325
+ return true;
1326
+ }
1327
+ // prettier-ignore
1328
+ function InGroup(pattern) {
1329
+ return pattern.slice(1, pattern.length - 1);
1330
+ }
1331
+ // prettier-ignore
1332
+ function IsPrecedenceOr(pattern) {
1333
+ let count = 0;
1334
+ for (let index = 0; index < pattern.length; index++) {
1335
+ if (IsOpenParen(pattern, index))
1336
+ count += 1;
1337
+ if (IsCloseParen(pattern, index))
1338
+ count -= 1;
1339
+ if (IsSeparator(pattern, index) && count === 0)
1340
+ return true;
1341
+ }
1342
+ return false;
1343
+ }
1344
+ // prettier-ignore
1345
+ function IsPrecedenceAnd(pattern) {
1346
+ for (let index = 0; index < pattern.length; index++) {
1347
+ if (IsOpenParen(pattern, index))
1348
+ return true;
1349
+ }
1350
+ return false;
1351
+ }
1352
+ // prettier-ignore
1353
+ function Or(pattern) {
1354
+ let [count, start] = [0, 0];
1355
+ const expressions = [];
1356
+ for (let index = 0; index < pattern.length; index++) {
1357
+ if (IsOpenParen(pattern, index))
1358
+ count += 1;
1359
+ if (IsCloseParen(pattern, index))
1360
+ count -= 1;
1361
+ if (IsSeparator(pattern, index) && count === 0) {
1362
+ const range = pattern.slice(start, index);
1363
+ if (range.length > 0)
1364
+ expressions.push(TemplateLiteralParse(range));
1365
+ start = index + 1;
1366
+ }
1367
+ }
1368
+ const range = pattern.slice(start);
1369
+ if (range.length > 0)
1370
+ expressions.push(TemplateLiteralParse(range));
1371
+ if (expressions.length === 0)
1372
+ return { type: 'const', const: '' };
1373
+ if (expressions.length === 1)
1374
+ return expressions[0];
1375
+ return { type: 'or', expr: expressions };
1376
+ }
1377
+ // prettier-ignore
1378
+ function And(pattern) {
1379
+ function Group(value, index) {
1380
+ if (!IsOpenParen(value, index))
1381
+ throw new TemplateLiteralParserError(`TemplateLiteralParser: Index must point to open parens`);
1382
+ let count = 0;
1383
+ for (let scan = index; scan < value.length; scan++) {
1384
+ if (IsOpenParen(value, scan))
1385
+ count += 1;
1386
+ if (IsCloseParen(value, scan))
1387
+ count -= 1;
1388
+ if (count === 0)
1389
+ return [index, scan];
1390
+ }
1391
+ throw new TemplateLiteralParserError(`TemplateLiteralParser: Unclosed group parens in expression`);
1392
+ }
1393
+ function Range(pattern, index) {
1394
+ for (let scan = index; scan < pattern.length; scan++) {
1395
+ if (IsOpenParen(pattern, scan))
1396
+ return [index, scan];
1397
+ }
1398
+ return [index, pattern.length];
1399
+ }
1400
+ const expressions = [];
1401
+ for (let index = 0; index < pattern.length; index++) {
1402
+ if (IsOpenParen(pattern, index)) {
1403
+ const [start, end] = Group(pattern, index);
1404
+ const range = pattern.slice(start, end + 1);
1405
+ expressions.push(TemplateLiteralParse(range));
1406
+ index = end;
1407
+ }
1408
+ else {
1409
+ const [start, end] = Range(pattern, index);
1410
+ const range = pattern.slice(start, end);
1411
+ if (range.length > 0)
1412
+ expressions.push(TemplateLiteralParse(range));
1413
+ index = end - 1;
1414
+ }
1415
+ }
1416
+ return ((expressions.length === 0) ? { type: 'const', const: '' } :
1417
+ (expressions.length === 1) ? expressions[0] :
1418
+ { type: 'and', expr: expressions });
1419
+ }
1420
+ // ------------------------------------------------------------------
1421
+ // TemplateLiteralParse
1422
+ // ------------------------------------------------------------------
1423
+ /** Parses a pattern and returns an expression tree */
1424
+ function TemplateLiteralParse(pattern) {
1425
+ // prettier-ignore
1426
+ return (IsGroup(pattern) ? TemplateLiteralParse(InGroup(pattern)) :
1427
+ IsPrecedenceOr(pattern) ? Or(pattern) :
1428
+ IsPrecedenceAnd(pattern) ? And(pattern) :
1429
+ { type: 'const', const: Unescape(pattern) });
1430
+ }
1431
+ // ------------------------------------------------------------------
1432
+ // TemplateLiteralParseExact
1433
+ // ------------------------------------------------------------------
1434
+ /** Parses a pattern and strips forward and trailing ^ and $ */
1435
+ function TemplateLiteralParseExact(pattern) {
1436
+ return TemplateLiteralParse(pattern.slice(1, pattern.length - 1));
1437
+ }
1438
+
1439
+ // ------------------------------------------------------------------
1440
+ // TemplateLiteralFiniteError
1441
+ // ------------------------------------------------------------------
1442
+ class TemplateLiteralFiniteError extends TypeBoxError {
1443
+ }
1444
+ // ------------------------------------------------------------------
1445
+ // IsTemplateLiteralFiniteCheck
1446
+ // ------------------------------------------------------------------
1447
+ // prettier-ignore
1448
+ function IsNumberExpression(expression) {
1449
+ return (expression.type === 'or' &&
1450
+ expression.expr.length === 2 &&
1451
+ expression.expr[0].type === 'const' &&
1452
+ expression.expr[0].const === '0' &&
1453
+ expression.expr[1].type === 'const' &&
1454
+ expression.expr[1].const === '[1-9][0-9]*');
1455
+ }
1456
+ // prettier-ignore
1457
+ function IsBooleanExpression(expression) {
1458
+ return (expression.type === 'or' &&
1459
+ expression.expr.length === 2 &&
1460
+ expression.expr[0].type === 'const' &&
1461
+ expression.expr[0].const === 'true' &&
1462
+ expression.expr[1].type === 'const' &&
1463
+ expression.expr[1].const === 'false');
1464
+ }
1465
+ // prettier-ignore
1466
+ function IsStringExpression(expression) {
1467
+ return expression.type === 'const' && expression.const === '.*';
1468
+ }
1469
+ // ------------------------------------------------------------------
1470
+ // IsTemplateLiteralExpressionFinite
1471
+ // ------------------------------------------------------------------
1472
+ // prettier-ignore
1473
+ function IsTemplateLiteralExpressionFinite(expression) {
1474
+ return (IsNumberExpression(expression) || IsStringExpression(expression) ? false :
1475
+ IsBooleanExpression(expression) ? true :
1476
+ (expression.type === 'and') ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) :
1477
+ (expression.type === 'or') ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) :
1478
+ (expression.type === 'const') ? true :
1479
+ (() => { throw new TemplateLiteralFiniteError(`Unknown expression type`); })());
1480
+ }
1481
+ /** Returns true if this TemplateLiteral resolves to a finite set of values */
1482
+ function IsTemplateLiteralFinite(schema) {
1483
+ const expression = TemplateLiteralParseExact(schema.pattern);
1484
+ return IsTemplateLiteralExpressionFinite(expression);
1485
+ }
1486
+
1487
+ // ------------------------------------------------------------------
1488
+ // TemplateLiteralGenerateError
1489
+ // ------------------------------------------------------------------
1490
+ class TemplateLiteralGenerateError extends TypeBoxError {
1491
+ }
1492
+ // ------------------------------------------------------------------
1493
+ // TemplateLiteralExpressionGenerate
1494
+ // ------------------------------------------------------------------
1495
+ // prettier-ignore
1496
+ function* GenerateReduce(buffer) {
1497
+ if (buffer.length === 1)
1498
+ return yield* buffer[0];
1499
+ for (const left of buffer[0]) {
1500
+ for (const right of GenerateReduce(buffer.slice(1))) {
1501
+ yield `${left}${right}`;
1502
+ }
1503
+ }
1504
+ }
1505
+ // prettier-ignore
1506
+ function* GenerateAnd(expression) {
1507
+ return yield* GenerateReduce(expression.expr.map((expr) => [...TemplateLiteralExpressionGenerate(expr)]));
1508
+ }
1509
+ // prettier-ignore
1510
+ function* GenerateOr(expression) {
1511
+ for (const expr of expression.expr)
1512
+ yield* TemplateLiteralExpressionGenerate(expr);
1513
+ }
1514
+ // prettier-ignore
1515
+ function* GenerateConst(expression) {
1516
+ return yield expression.const;
1517
+ }
1518
+ function* TemplateLiteralExpressionGenerate(expression) {
1519
+ return expression.type === 'and'
1520
+ ? yield* GenerateAnd(expression)
1521
+ : expression.type === 'or'
1522
+ ? yield* GenerateOr(expression)
1523
+ : expression.type === 'const'
1524
+ ? yield* GenerateConst(expression)
1525
+ : (() => {
1526
+ throw new TemplateLiteralGenerateError('Unknown expression');
1527
+ })();
1528
+ }
1529
+ /** Generates a tuple of strings from the given TemplateLiteral. Returns an empty tuple if infinite. */
1530
+ function TemplateLiteralGenerate(schema) {
1531
+ const expression = TemplateLiteralParseExact(schema.pattern);
1532
+ // prettier-ignore
1533
+ return (IsTemplateLiteralExpressionFinite(expression)
1534
+ ? [...TemplateLiteralExpressionGenerate(expression)]
1535
+ : []);
1536
+ }
1537
+
1538
+ /** `[Json]` Creates a Literal type */
1539
+ function Literal(value, options = {}) {
1540
+ return {
1541
+ ...options,
1542
+ [Kind]: 'Literal',
1543
+ const: value,
1544
+ type: typeof value,
1545
+ };
1546
+ }
1547
+
1548
+ /** `[Json]` Creates a Boolean type */
1549
+ function Boolean(options = {}) {
1550
+ return {
1551
+ ...options,
1552
+ [Kind]: 'Boolean',
1553
+ type: 'boolean',
1554
+ };
1555
+ }
1556
+
1557
+ /** `[JavaScript]` Creates a BigInt type */
1558
+ function BigInt(options = {}) {
1559
+ return {
1560
+ ...options,
1561
+ [Kind]: 'BigInt',
1562
+ type: 'bigint',
1563
+ };
1564
+ }
1565
+
1566
+ /** `[Json]` Creates a Number type */
1567
+ function Number(options = {}) {
1568
+ return {
1569
+ ...options,
1570
+ [Kind]: 'Number',
1571
+ type: 'number',
1572
+ };
1573
+ }
1574
+
1575
+ /** `[Json]` Creates a String type */
1576
+ function String$1(options = {}) {
1577
+ return { ...options, [Kind]: 'String', type: 'string' };
1578
+ }
1579
+
1580
+ // ------------------------------------------------------------------
1581
+ // SyntaxParsers
1582
+ // ------------------------------------------------------------------
1583
+ // prettier-ignore
1584
+ function* FromUnion$8(syntax) {
1585
+ const trim = syntax.trim().replace(/"|'/g, '');
1586
+ return (trim === 'boolean' ? yield Boolean() :
1587
+ trim === 'number' ? yield Number() :
1588
+ trim === 'bigint' ? yield BigInt() :
1589
+ trim === 'string' ? yield String$1() :
1590
+ yield (() => {
1591
+ const literals = trim.split('|').map((literal) => Literal(literal.trim()));
1592
+ return (literals.length === 0 ? Never() :
1593
+ literals.length === 1 ? literals[0] :
1594
+ UnionEvaluated(literals));
1595
+ })());
1596
+ }
1597
+ // prettier-ignore
1598
+ function* FromTerminal(syntax) {
1599
+ if (syntax[1] !== '{') {
1600
+ const L = Literal('$');
1601
+ const R = FromSyntax(syntax.slice(1));
1602
+ return yield* [L, ...R];
1603
+ }
1604
+ for (let i = 2; i < syntax.length; i++) {
1605
+ if (syntax[i] === '}') {
1606
+ const L = FromUnion$8(syntax.slice(2, i));
1607
+ const R = FromSyntax(syntax.slice(i + 1));
1608
+ return yield* [...L, ...R];
1609
+ }
1610
+ }
1611
+ yield Literal(syntax);
1612
+ }
1613
+ // prettier-ignore
1614
+ function* FromSyntax(syntax) {
1615
+ for (let i = 0; i < syntax.length; i++) {
1616
+ if (syntax[i] === '$') {
1617
+ const L = Literal(syntax.slice(0, i));
1618
+ const R = FromTerminal(syntax.slice(i));
1619
+ return yield* [L, ...R];
1620
+ }
1621
+ }
1622
+ yield Literal(syntax);
1623
+ }
1624
+ /** Parses TemplateLiteralSyntax and returns a tuple of TemplateLiteralKinds */
1625
+ function TemplateLiteralSyntax(syntax) {
1626
+ return [...FromSyntax(syntax)];
1627
+ }
1628
+
1629
+ // ------------------------------------------------------------------
1630
+ // TemplateLiteralPatternError
1631
+ // ------------------------------------------------------------------
1632
+ class TemplateLiteralPatternError extends TypeBoxError {
1633
+ }
1634
+ // ------------------------------------------------------------------
1635
+ // TemplateLiteralPattern
1636
+ // ------------------------------------------------------------------
1637
+ function Escape(value) {
1638
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1639
+ }
1640
+ // prettier-ignore
1641
+ function Visit$1(schema, acc) {
1642
+ return (IsTemplateLiteral$1(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) :
1643
+ IsUnion$1(schema) ? `(${schema.anyOf.map((schema) => Visit$1(schema, acc)).join('|')})` :
1644
+ IsNumber$1(schema) ? `${acc}${PatternNumber}` :
1645
+ IsInteger$1(schema) ? `${acc}${PatternNumber}` :
1646
+ IsBigInt$1(schema) ? `${acc}${PatternNumber}` :
1647
+ IsString$1(schema) ? `${acc}${PatternString}` :
1648
+ IsLiteral$1(schema) ? `${acc}${Escape(schema.const.toString())}` :
1649
+ IsBoolean$1(schema) ? `${acc}${PatternBoolean}` :
1650
+ (() => { throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[Kind]}'`); })());
1651
+ }
1652
+ function TemplateLiteralPattern(kinds) {
1653
+ return `^${kinds.map((schema) => Visit$1(schema, '')).join('')}\$`;
1654
+ }
1655
+
1656
+ /** Returns a Union from the given TemplateLiteral */
1657
+ function TemplateLiteralToUnion(schema) {
1658
+ const R = TemplateLiteralGenerate(schema);
1659
+ const L = R.map((S) => Literal(S));
1660
+ return UnionEvaluated(L);
1661
+ }
1662
+
1663
+ /** `[Json]` Creates a TemplateLiteral type */
1664
+ // prettier-ignore
1665
+ function TemplateLiteral(unresolved, options = {}) {
1666
+ const pattern = IsString$2(unresolved)
1667
+ ? TemplateLiteralPattern(TemplateLiteralSyntax(unresolved))
1668
+ : TemplateLiteralPattern(unresolved);
1669
+ return { ...options, [Kind]: 'TemplateLiteral', type: 'string', pattern };
1670
+ }
1671
+
1672
+ // prettier-ignore
1673
+ function FromTemplateLiteral$2(T) {
1674
+ const R = TemplateLiteralGenerate(T);
1675
+ return R.map(S => S.toString());
1676
+ }
1677
+ // prettier-ignore
1678
+ function FromUnion$7(T) {
1679
+ const Acc = [];
1680
+ for (const L of T)
1681
+ Acc.push(...IndexPropertyKeys(L));
1682
+ return Acc;
1683
+ }
1684
+ // prettier-ignore
1685
+ function FromLiteral$1(T) {
1686
+ return ([T.toString()] // TS 5.4 observes TLiteralValue as not having a toString()
1687
+ );
1688
+ }
1689
+ /** Returns a tuple of PropertyKeys derived from the given TSchema */
1690
+ // prettier-ignore
1691
+ function IndexPropertyKeys(T) {
1692
+ return [...new Set((IsTemplateLiteral$1(T) ? FromTemplateLiteral$2(T) :
1693
+ IsUnion$1(T) ? FromUnion$7(T.anyOf) :
1694
+ IsLiteral$1(T) ? FromLiteral$1(T.const) :
1695
+ IsNumber$1(T) ? ['[number]'] :
1696
+ IsInteger$1(T) ? ['[number]'] :
1697
+ []))];
1698
+ }
1699
+
1700
+ // prettier-ignore
1701
+ function FromProperties$i(T, P, options) {
1702
+ const Acc = {};
1703
+ for (const K2 of Object.getOwnPropertyNames(P)) {
1704
+ Acc[K2] = Index(T, IndexPropertyKeys(P[K2]), options);
1705
+ }
1706
+ return Acc;
1707
+ }
1708
+ // prettier-ignore
1709
+ function FromMappedResult$b(T, R, options) {
1710
+ return FromProperties$i(T, R.properties, options);
1711
+ }
1712
+ // prettier-ignore
1713
+ function IndexFromMappedResult(T, R, options) {
1714
+ const P = FromMappedResult$b(T, R, options);
1715
+ return MappedResult(P);
1716
+ }
1717
+
1718
+ // prettier-ignore
1719
+ function FromRest$7(T, K) {
1720
+ return T.map(L => IndexFromPropertyKey(L, K));
1721
+ }
1722
+ // prettier-ignore
1723
+ function FromIntersectRest(T) {
1724
+ return T.filter(L => !IsNever$1(L));
1725
+ }
1726
+ // prettier-ignore
1727
+ function FromIntersect$6(T, K) {
1728
+ return (IntersectEvaluated(FromIntersectRest(FromRest$7(T, K))));
1729
+ }
1730
+ // prettier-ignore
1731
+ function FromUnionRest(T) {
1732
+ return (T.some(L => IsNever$1(L))
1733
+ ? []
1734
+ : T);
1735
+ }
1736
+ // prettier-ignore
1737
+ function FromUnion$6(T, K) {
1738
+ return (UnionEvaluated(FromUnionRest(FromRest$7(T, K))));
1739
+ }
1740
+ // prettier-ignore
1741
+ function FromTuple$3(T, K) {
1742
+ return (K in T ? T[K] :
1743
+ K === '[number]' ? UnionEvaluated(T) :
1744
+ Never());
1745
+ }
1746
+ // prettier-ignore
1747
+ function FromArray$4(T, K) {
1748
+ return (K === '[number]'
1749
+ ? T
1750
+ : Never());
1751
+ }
1752
+ // prettier-ignore
1753
+ function FromProperty$1(T, K) {
1754
+ return (K in T ? T[K] : Never());
1755
+ }
1756
+ // prettier-ignore
1757
+ function IndexFromPropertyKey(T, K) {
1758
+ return (IsIntersect$1(T) ? FromIntersect$6(T.allOf, K) :
1759
+ IsUnion$1(T) ? FromUnion$6(T.anyOf, K) :
1760
+ IsTuple$1(T) ? FromTuple$3(T.items ?? [], K) :
1761
+ IsArray$1(T) ? FromArray$4(T.items, K) :
1762
+ IsObject$1(T) ? FromProperty$1(T.properties, K) :
1763
+ Never());
1764
+ }
1765
+ // prettier-ignore
1766
+ function IndexFromPropertyKeys(T, K) {
1767
+ return K.map(L => IndexFromPropertyKey(T, L));
1768
+ }
1769
+ // prettier-ignore
1770
+ function FromSchema(T, K) {
1771
+ return (UnionEvaluated(IndexFromPropertyKeys(T, K)));
1772
+ }
1773
+ /** `[Json]` Returns an Indexed property type for the given keys */
1774
+ function Index(T, K, options = {}) {
1775
+ // prettier-ignore
1776
+ return (IsMappedResult$1(K) ? CloneType(IndexFromMappedResult(T, K, options)) :
1777
+ IsMappedKey$1(K) ? CloneType(IndexFromMappedKey(T, K, options)) :
1778
+ IsSchema$1(K) ? CloneType(FromSchema(T, IndexPropertyKeys(K)), options) :
1779
+ CloneType(FromSchema(T, K), options));
1780
+ }
1781
+
1782
+ // prettier-ignore
1783
+ function MappedIndexPropertyKey(T, K, options) {
1784
+ return { [K]: Index(T, [K], options) };
1785
+ }
1786
+ // prettier-ignore
1787
+ function MappedIndexPropertyKeys(T, K, options) {
1788
+ return K.reduce((Acc, L) => {
1789
+ return { ...Acc, ...MappedIndexPropertyKey(T, L, options) };
1790
+ }, {});
1791
+ }
1792
+ // prettier-ignore
1793
+ function MappedIndexProperties(T, K, options) {
1794
+ return MappedIndexPropertyKeys(T, K.keys, options);
1795
+ }
1796
+ // prettier-ignore
1797
+ function IndexFromMappedKey(T, K, options) {
1798
+ const P = MappedIndexProperties(T, K, options);
1799
+ return MappedResult(P);
1800
+ }
1801
+
1802
+ /** `[JavaScript]` Creates an Iterator type */
1803
+ function Iterator(items, options = {}) {
1804
+ return {
1805
+ ...options,
1806
+ [Kind]: 'Iterator',
1807
+ type: 'Iterator',
1808
+ items: CloneType(items),
1809
+ };
1810
+ }
1811
+
1812
+ /** `[Json]` Creates an Object type */
1813
+ function _Object(properties, options = {}) {
1814
+ const propertyKeys = globalThis.Object.getOwnPropertyNames(properties);
1815
+ const optionalKeys = propertyKeys.filter((key) => IsOptional$1(properties[key]));
1816
+ const requiredKeys = propertyKeys.filter((name) => !optionalKeys.includes(name));
1817
+ const clonedAdditionalProperties = IsSchema$1(options.additionalProperties) ? { additionalProperties: CloneType(options.additionalProperties) } : {};
1818
+ const clonedProperties = {};
1819
+ for (const key of propertyKeys)
1820
+ clonedProperties[key] = CloneType(properties[key]);
1821
+ return (requiredKeys.length > 0
1822
+ ? { ...options, ...clonedAdditionalProperties, [Kind]: 'Object', type: 'object', properties: clonedProperties, required: requiredKeys }
1823
+ : { ...options, ...clonedAdditionalProperties, [Kind]: 'Object', type: 'object', properties: clonedProperties });
1824
+ }
1825
+ /** `[Json]` Creates an Object type */
1826
+ const Object$1 = _Object;
1827
+
1828
+ /** `[JavaScript]` Creates a Promise type */
1829
+ function Promise$1(item, options = {}) {
1830
+ return {
1831
+ ...options,
1832
+ [Kind]: 'Promise',
1833
+ type: 'Promise',
1834
+ item: CloneType(item),
1835
+ };
1836
+ }
1837
+
1838
+ function RemoveReadonly(schema) {
1839
+ return Discard(CloneType(schema), [ReadonlyKind]);
1840
+ }
1841
+ function AddReadonly(schema) {
1842
+ return { ...CloneType(schema), [ReadonlyKind]: 'Readonly' };
1843
+ }
1844
+ // prettier-ignore
1845
+ function ReadonlyWithFlag(schema, F) {
1846
+ return (F === false
1847
+ ? RemoveReadonly(schema)
1848
+ : AddReadonly(schema));
1849
+ }
1850
+ /** `[Json]` Creates a Readonly property */
1851
+ function Readonly(schema, enable) {
1852
+ const F = enable ?? true;
1853
+ return IsMappedResult$1(schema) ? ReadonlyFromMappedResult(schema, F) : ReadonlyWithFlag(schema, F);
1854
+ }
1855
+
1856
+ // prettier-ignore
1857
+ function FromProperties$h(K, F) {
1858
+ const Acc = {};
1859
+ for (const K2 of globalThis.Object.getOwnPropertyNames(K))
1860
+ Acc[K2] = Readonly(K[K2], F);
1861
+ return Acc;
1862
+ }
1863
+ // prettier-ignore
1864
+ function FromMappedResult$a(R, F) {
1865
+ return FromProperties$h(R.properties, F);
1866
+ }
1867
+ // prettier-ignore
1868
+ function ReadonlyFromMappedResult(R, F) {
1869
+ const P = FromMappedResult$a(R, F);
1870
+ return MappedResult(P);
1871
+ }
1872
+
1873
+ /** `[Json]` Creates a Tuple type */
1874
+ function Tuple(items, options = {}) {
1875
+ // return TupleResolver.Resolve(T)
1876
+ const [additionalItems, minItems, maxItems] = [false, items.length, items.length];
1877
+ // prettier-ignore
1878
+ return (items.length > 0 ?
1879
+ { ...options, [Kind]: 'Tuple', type: 'array', items: CloneRest(items), additionalItems, minItems, maxItems } :
1880
+ { ...options, [Kind]: 'Tuple', type: 'array', minItems, maxItems });
1881
+ }
1882
+
1883
+ // prettier-ignore
1884
+ function FromMappedResult$9(K, P) {
1885
+ return (K in P
1886
+ ? FromSchemaType(K, P[K])
1887
+ : MappedResult(P));
1888
+ }
1889
+ // prettier-ignore
1890
+ function MappedKeyToKnownMappedResultProperties(K) {
1891
+ return { [K]: Literal(K) };
1892
+ }
1893
+ // prettier-ignore
1894
+ function MappedKeyToUnknownMappedResultProperties(P) {
1895
+ const Acc = {};
1896
+ for (const L of P)
1897
+ Acc[L] = Literal(L);
1898
+ return Acc;
1899
+ }
1900
+ // prettier-ignore
1901
+ function MappedKeyToMappedResultProperties(K, P) {
1902
+ return (SetIncludes(P, K)
1903
+ ? MappedKeyToKnownMappedResultProperties(K)
1904
+ : MappedKeyToUnknownMappedResultProperties(P));
1905
+ }
1906
+ // prettier-ignore
1907
+ function FromMappedKey$3(K, P) {
1908
+ const R = MappedKeyToMappedResultProperties(K, P);
1909
+ return FromMappedResult$9(K, R);
1910
+ }
1911
+ // prettier-ignore
1912
+ function FromRest$6(K, T) {
1913
+ return T.map(L => FromSchemaType(K, L));
1914
+ }
1915
+ // prettier-ignore
1916
+ function FromProperties$g(K, T) {
1917
+ const Acc = {};
1918
+ for (const K2 of globalThis.Object.getOwnPropertyNames(T))
1919
+ Acc[K2] = FromSchemaType(K, T[K2]);
1920
+ return Acc;
1921
+ }
1922
+ // prettier-ignore
1923
+ function FromSchemaType(K, T) {
1924
+ return (
1925
+ // unevaluated modifier types
1926
+ IsOptional$1(T) ? Optional(FromSchemaType(K, Discard(T, [OptionalKind]))) :
1927
+ IsReadonly(T) ? Readonly(FromSchemaType(K, Discard(T, [ReadonlyKind]))) :
1928
+ // unevaluated mapped types
1929
+ IsMappedResult$1(T) ? FromMappedResult$9(K, T.properties) :
1930
+ IsMappedKey$1(T) ? FromMappedKey$3(K, T.keys) :
1931
+ // unevaluated types
1932
+ IsConstructor$1(T) ? Constructor(FromRest$6(K, T.parameters), FromSchemaType(K, T.returns)) :
1933
+ IsFunction$1(T) ? Function(FromRest$6(K, T.parameters), FromSchemaType(K, T.returns)) :
1934
+ IsAsyncIterator$1(T) ? AsyncIterator(FromSchemaType(K, T.items)) :
1935
+ IsIterator$1(T) ? Iterator(FromSchemaType(K, T.items)) :
1936
+ IsIntersect$1(T) ? Intersect(FromRest$6(K, T.allOf)) :
1937
+ IsUnion$1(T) ? Union(FromRest$6(K, T.anyOf)) :
1938
+ IsTuple$1(T) ? Tuple(FromRest$6(K, T.items ?? [])) :
1939
+ IsObject$1(T) ? Object$1(FromProperties$g(K, T.properties)) :
1940
+ IsArray$1(T) ? Array$1(FromSchemaType(K, T.items)) :
1941
+ IsPromise$1(T) ? Promise$1(FromSchemaType(K, T.item)) :
1942
+ T);
1943
+ }
1944
+ // prettier-ignore
1945
+ function MappedFunctionReturnType(K, T) {
1946
+ const Acc = {};
1947
+ for (const L of K)
1948
+ Acc[L] = FromSchemaType(L, T);
1949
+ return Acc;
1950
+ }
1951
+ /** `[Json]` Creates a Mapped object type */
1952
+ function Mapped(key, map, options = {}) {
1953
+ const K = IsSchema$1(key) ? IndexPropertyKeys(key) : key;
1954
+ const RT = map({ [Kind]: 'MappedKey', keys: K });
1955
+ const R = MappedFunctionReturnType(K, RT);
1956
+ return CloneType(Object$1(R), options);
1957
+ }
1958
+
1959
+ function RemoveOptional(schema) {
1960
+ return Discard(CloneType(schema), [OptionalKind]);
1961
+ }
1962
+ function AddOptional(schema) {
1963
+ return { ...CloneType(schema), [OptionalKind]: 'Optional' };
1964
+ }
1965
+ // prettier-ignore
1966
+ function OptionalWithFlag(schema, F) {
1967
+ return (F === false
1968
+ ? RemoveOptional(schema)
1969
+ : AddOptional(schema));
1970
+ }
1971
+ /** `[Json]` Creates a Optional property */
1972
+ function Optional(schema, enable) {
1973
+ const F = enable ?? true;
1974
+ return IsMappedResult$1(schema) ? OptionalFromMappedResult(schema, F) : OptionalWithFlag(schema, F);
1975
+ }
1976
+
1977
+ // prettier-ignore
1978
+ function FromProperties$f(P, F) {
1979
+ const Acc = {};
1980
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P))
1981
+ Acc[K2] = Optional(P[K2], F);
1982
+ return Acc;
1983
+ }
1984
+ // prettier-ignore
1985
+ function FromMappedResult$8(R, F) {
1986
+ return FromProperties$f(R.properties, F);
1987
+ }
1988
+ // prettier-ignore
1989
+ function OptionalFromMappedResult(R, F) {
1990
+ const P = FromMappedResult$8(R, F);
1991
+ return MappedResult(P);
1992
+ }
1993
+
1994
+ // ------------------------------------------------------------------
1995
+ // IntersectCreate
1996
+ // ------------------------------------------------------------------
1997
+ // prettier-ignore
1998
+ function IntersectCreate(T, options) {
1999
+ const allObjects = T.every((schema) => IsObject$1(schema));
2000
+ const clonedUnevaluatedProperties = IsSchema$1(options.unevaluatedProperties)
2001
+ ? { unevaluatedProperties: CloneType(options.unevaluatedProperties) }
2002
+ : {};
2003
+ return ((options.unevaluatedProperties === false || IsSchema$1(options.unevaluatedProperties) || allObjects
2004
+ ? { ...options, ...clonedUnevaluatedProperties, [Kind]: 'Intersect', type: 'object', allOf: CloneRest(T) }
2005
+ : { ...options, ...clonedUnevaluatedProperties, [Kind]: 'Intersect', allOf: CloneRest(T) }));
2006
+ }
2007
+
2008
+ // prettier-ignore
2009
+ function IsIntersectOptional(T) {
2010
+ return T.every(L => IsOptional$1(L));
2011
+ }
2012
+ // prettier-ignore
2013
+ function RemoveOptionalFromType(T) {
2014
+ return (Discard(T, [OptionalKind]));
2015
+ }
2016
+ // prettier-ignore
2017
+ function RemoveOptionalFromRest(T) {
2018
+ return T.map(L => IsOptional$1(L) ? RemoveOptionalFromType(L) : L);
2019
+ }
2020
+ // prettier-ignore
2021
+ function ResolveIntersect(T, options) {
2022
+ return (IsIntersectOptional(T)
2023
+ ? Optional(IntersectCreate(RemoveOptionalFromRest(T), options))
2024
+ : IntersectCreate(RemoveOptionalFromRest(T), options));
2025
+ }
2026
+ /** `[Json]` Creates an evaluated Intersect type */
2027
+ function IntersectEvaluated(T, options = {}) {
2028
+ if (T.length === 0)
2029
+ return Never(options);
2030
+ if (T.length === 1)
2031
+ return CloneType(T[0], options);
2032
+ if (T.some((schema) => IsTransform$1(schema)))
2033
+ throw new Error('Cannot intersect transform types');
2034
+ return ResolveIntersect(T, options);
2035
+ }
2036
+
2037
+ /** `[Json]` Creates an evaluated Intersect type */
2038
+ function Intersect(T, options = {}) {
2039
+ if (T.length === 0)
2040
+ return Never(options);
2041
+ if (T.length === 1)
2042
+ return CloneType(T[0], options);
2043
+ if (T.some((schema) => IsTransform$1(schema)))
2044
+ throw new Error('Cannot intersect transform types');
2045
+ return IntersectCreate(T, options);
2046
+ }
2047
+
2048
+ // prettier-ignore
2049
+ function FromRest$5(T) {
2050
+ return T.map(L => AwaitedResolve(L));
2051
+ }
2052
+ // prettier-ignore
2053
+ function FromIntersect$5(T) {
2054
+ return Intersect(FromRest$5(T));
2055
+ }
2056
+ // prettier-ignore
2057
+ function FromUnion$5(T) {
2058
+ return Union(FromRest$5(T));
2059
+ }
2060
+ // prettier-ignore
2061
+ function FromPromise$2(T) {
2062
+ return AwaitedResolve(T);
2063
+ }
2064
+ // ----------------------------------------------------------------
2065
+ // AwaitedResolve
2066
+ // ----------------------------------------------------------------
2067
+ // prettier-ignore
2068
+ function AwaitedResolve(T) {
2069
+ return (IsIntersect$1(T) ? FromIntersect$5(T.allOf) :
2070
+ IsUnion$1(T) ? FromUnion$5(T.anyOf) :
2071
+ IsPromise$1(T) ? FromPromise$2(T.item) :
2072
+ T);
2073
+ }
2074
+ /** `[JavaScript]` Constructs a type by recursively unwrapping Promise types */
2075
+ function Awaited(T, options = {}) {
2076
+ return CloneType(AwaitedResolve(T), options);
2077
+ }
2078
+
2079
+ // prettier-ignore
2080
+ function FromRest$4(T) {
2081
+ const Acc = [];
2082
+ for (const L of T)
2083
+ Acc.push(KeyOfPropertyKeys(L));
2084
+ return Acc;
2085
+ }
2086
+ // prettier-ignore
2087
+ function FromIntersect$4(T) {
2088
+ const C = FromRest$4(T);
2089
+ const R = SetUnionMany(C);
2090
+ return R;
2091
+ }
2092
+ // prettier-ignore
2093
+ function FromUnion$4(T) {
2094
+ const C = FromRest$4(T);
2095
+ const R = SetIntersectMany(C);
2096
+ return R;
2097
+ }
2098
+ // prettier-ignore
2099
+ function FromTuple$2(T) {
2100
+ return T.map((_, I) => I.toString());
2101
+ }
2102
+ // prettier-ignore
2103
+ function FromArray$3(_) {
2104
+ return (['[number]']);
2105
+ }
2106
+ // prettier-ignore
2107
+ function FromProperties$e(T) {
2108
+ return (globalThis.Object.getOwnPropertyNames(T));
2109
+ }
2110
+ // ------------------------------------------------------------------
2111
+ // FromPatternProperties
2112
+ // ------------------------------------------------------------------
2113
+ // prettier-ignore
2114
+ function FromPatternProperties(patternProperties) {
2115
+ return [];
2116
+ }
2117
+ /** Returns a tuple of PropertyKeys derived from the given TSchema. */
2118
+ // prettier-ignore
2119
+ function KeyOfPropertyKeys(T) {
2120
+ return (IsIntersect$1(T) ? FromIntersect$4(T.allOf) :
2121
+ IsUnion$1(T) ? FromUnion$4(T.anyOf) :
2122
+ IsTuple$1(T) ? FromTuple$2(T.items ?? []) :
2123
+ IsArray$1(T) ? FromArray$3(T.items) :
2124
+ IsObject$1(T) ? FromProperties$e(T.properties) :
2125
+ IsRecord$1(T) ? FromPatternProperties(T.patternProperties) :
2126
+ []);
2127
+ }
2128
+
2129
+ // prettier-ignore
2130
+ function KeyOfPropertyKeysToRest(T) {
2131
+ return T.map(L => L === '[number]' ? Number() : Literal(L));
2132
+ }
2133
+ /** `[Json]` Creates a KeyOf type */
2134
+ function KeyOf(T, options = {}) {
2135
+ if (IsMappedResult$1(T)) {
2136
+ return KeyOfFromMappedResult(T, options);
2137
+ }
2138
+ else {
2139
+ const K = KeyOfPropertyKeys(T);
2140
+ const S = KeyOfPropertyKeysToRest(K);
2141
+ const U = UnionEvaluated(S);
2142
+ return CloneType(U, options);
2143
+ }
2144
+ }
2145
+
2146
+ // prettier-ignore
2147
+ function FromProperties$d(K, options) {
2148
+ const Acc = {};
2149
+ for (const K2 of globalThis.Object.getOwnPropertyNames(K))
2150
+ Acc[K2] = KeyOf(K[K2], options);
2151
+ return Acc;
2152
+ }
2153
+ // prettier-ignore
2154
+ function FromMappedResult$7(R, options) {
2155
+ return FromProperties$d(R.properties, options);
2156
+ }
2157
+ // prettier-ignore
2158
+ function KeyOfFromMappedResult(R, options) {
2159
+ const P = FromMappedResult$7(R, options);
2160
+ return MappedResult(P);
2161
+ }
2162
+
2163
+ // prettier-ignore
2164
+ function CompositeKeys(T) {
2165
+ const Acc = [];
2166
+ for (const L of T)
2167
+ Acc.push(...KeyOfPropertyKeys(L));
2168
+ return SetDistinct(Acc);
2169
+ }
2170
+ // prettier-ignore
2171
+ function FilterNever(T) {
2172
+ return T.filter(L => !IsNever$1(L));
2173
+ }
2174
+ // prettier-ignore
2175
+ function CompositeProperty(T, K) {
2176
+ const Acc = [];
2177
+ for (const L of T)
2178
+ Acc.push(...IndexFromPropertyKeys(L, [K]));
2179
+ return FilterNever(Acc);
2180
+ }
2181
+ // prettier-ignore
2182
+ function CompositeProperties(T, K) {
2183
+ const Acc = {};
2184
+ for (const L of K) {
2185
+ Acc[L] = IntersectEvaluated(CompositeProperty(T, L));
2186
+ }
2187
+ return Acc;
2188
+ }
2189
+ // prettier-ignore
2190
+ function Composite(T, options = {}) {
2191
+ const K = CompositeKeys(T);
2192
+ const P = CompositeProperties(T, K);
2193
+ const R = Object$1(P, options);
2194
+ return R;
2195
+ }
2196
+
2197
+ /** `[JavaScript]` Creates a Date type */
2198
+ function Date$1(options = {}) {
2199
+ return {
2200
+ ...options,
2201
+ [Kind]: 'Date',
2202
+ type: 'Date',
2203
+ };
2204
+ }
2205
+
2206
+ /** `[Json]` Creates a Null type */
2207
+ function Null(options = {}) {
2208
+ return {
2209
+ ...options,
2210
+ [Kind]: 'Null',
2211
+ type: 'null',
2212
+ };
2213
+ }
2214
+
2215
+ /** `[JavaScript]` Creates a Symbol type */
2216
+ function Symbol$1(options) {
2217
+ return { ...options, [Kind]: 'Symbol', type: 'symbol' };
2218
+ }
2219
+
2220
+ /** `[JavaScript]` Creates a Undefined type */
2221
+ function Undefined(options = {}) {
2222
+ return { ...options, [Kind]: 'Undefined', type: 'undefined' };
2223
+ }
2224
+
2225
+ /** `[JavaScript]` Creates a Uint8Array type */
2226
+ function Uint8Array$1(options = {}) {
2227
+ return { ...options, [Kind]: 'Uint8Array', type: 'Uint8Array' };
2228
+ }
2229
+
2230
+ /** `[Json]` Creates an Unknown type */
2231
+ function Unknown(options = {}) {
2232
+ return {
2233
+ ...options,
2234
+ [Kind]: 'Unknown',
2235
+ };
2236
+ }
2237
+
2238
+ // prettier-ignore
2239
+ function FromArray$2(T) {
2240
+ return T.map(L => FromValue(L, false));
2241
+ }
2242
+ // prettier-ignore
2243
+ function FromProperties$c(value) {
2244
+ const Acc = {};
2245
+ for (const K of globalThis.Object.getOwnPropertyNames(value))
2246
+ Acc[K] = Readonly(FromValue(value[K], false));
2247
+ return Acc;
2248
+ }
2249
+ function ConditionalReadonly(T, root) {
2250
+ return (root === true ? T : Readonly(T));
2251
+ }
2252
+ // prettier-ignore
2253
+ function FromValue(value, root) {
2254
+ return (IsAsyncIterator$2(value) ? ConditionalReadonly(Any(), root) :
2255
+ IsIterator$2(value) ? ConditionalReadonly(Any(), root) :
2256
+ IsArray$2(value) ? Readonly(Tuple(FromArray$2(value))) :
2257
+ IsUint8Array$2(value) ? Uint8Array$1() :
2258
+ IsDate$2(value) ? Date$1() :
2259
+ IsObject$2(value) ? ConditionalReadonly(Object$1(FromProperties$c(value)), root) :
2260
+ IsFunction$2(value) ? ConditionalReadonly(Function([], Unknown()), root) :
2261
+ IsUndefined$2(value) ? Undefined() :
2262
+ IsNull$2(value) ? Null() :
2263
+ IsSymbol$2(value) ? Symbol$1() :
2264
+ IsBigInt$2(value) ? BigInt() :
2265
+ IsNumber$2(value) ? Literal(value) :
2266
+ IsBoolean$2(value) ? Literal(value) :
2267
+ IsString$2(value) ? Literal(value) :
2268
+ Object$1({}));
2269
+ }
2270
+ /** `[JavaScript]` Creates a readonly const type from the given value. */
2271
+ function Const(T, options = {}) {
2272
+ return CloneType(FromValue(T, true), options);
2273
+ }
2274
+
2275
+ /** `[JavaScript]` Extracts the ConstructorParameters from the given Constructor type */
2276
+ function ConstructorParameters(schema, options = {}) {
2277
+ return Tuple(CloneRest(schema.parameters), { ...options });
2278
+ }
2279
+
2280
+ function FromRest$3(schema, references) {
2281
+ return schema.map((schema) => Deref(schema, references));
2282
+ }
2283
+ // prettier-ignore
2284
+ function FromProperties$b(properties, references) {
2285
+ const Acc = {};
2286
+ for (const K of globalThis.Object.getOwnPropertyNames(properties)) {
2287
+ Acc[K] = Deref(properties[K], references);
2288
+ }
2289
+ return Acc;
2290
+ }
2291
+ // prettier-ignore
2292
+ function FromConstructor$1(schema, references) {
2293
+ schema.parameters = FromRest$3(schema.parameters, references);
2294
+ schema.returns = Deref(schema.returns, references);
2295
+ return schema;
2296
+ }
2297
+ // prettier-ignore
2298
+ function FromFunction$1(schema, references) {
2299
+ schema.parameters = FromRest$3(schema.parameters, references);
2300
+ schema.returns = Deref(schema.returns, references);
2301
+ return schema;
2302
+ }
2303
+ // prettier-ignore
2304
+ function FromIntersect$3(schema, references) {
2305
+ schema.allOf = FromRest$3(schema.allOf, references);
2306
+ return schema;
2307
+ }
2308
+ // prettier-ignore
2309
+ function FromUnion$3(schema, references) {
2310
+ schema.anyOf = FromRest$3(schema.anyOf, references);
2311
+ return schema;
2312
+ }
2313
+ // prettier-ignore
2314
+ function FromTuple$1(schema, references) {
2315
+ if (IsUndefined$2(schema.items))
2316
+ return schema;
2317
+ schema.items = FromRest$3(schema.items, references);
2318
+ return schema;
2319
+ }
2320
+ // prettier-ignore
2321
+ function FromArray$1(schema, references) {
2322
+ schema.items = Deref(schema.items, references);
2323
+ return schema;
2324
+ }
2325
+ // prettier-ignore
2326
+ function FromObject$1(schema, references) {
2327
+ schema.properties = FromProperties$b(schema.properties, references);
2328
+ return schema;
2329
+ }
2330
+ // prettier-ignore
2331
+ function FromPromise$1(schema, references) {
2332
+ schema.item = Deref(schema.item, references);
2333
+ return schema;
2334
+ }
2335
+ // prettier-ignore
2336
+ function FromAsyncIterator$1(schema, references) {
2337
+ schema.items = Deref(schema.items, references);
2338
+ return schema;
2339
+ }
2340
+ // prettier-ignore
2341
+ function FromIterator$1(schema, references) {
2342
+ schema.items = Deref(schema.items, references);
2343
+ return schema;
2344
+ }
2345
+ // prettier-ignore
2346
+ function FromRef(schema, references) {
2347
+ const target = references.find(remote => remote.$id === schema.$ref);
2348
+ if (target === undefined)
2349
+ throw Error(`Unable to dereference schema with $id ${schema.$ref}`);
2350
+ const discard = Discard(target, ['$id']);
2351
+ return Deref(discard, references);
2352
+ }
2353
+ // prettier-ignore
2354
+ function DerefResolve(schema, references) {
2355
+ return (IsConstructor$1(schema) ? FromConstructor$1(schema, references) :
2356
+ IsFunction$1(schema) ? FromFunction$1(schema, references) :
2357
+ IsIntersect$1(schema) ? FromIntersect$3(schema, references) :
2358
+ IsUnion$1(schema) ? FromUnion$3(schema, references) :
2359
+ IsTuple$1(schema) ? FromTuple$1(schema, references) :
2360
+ IsArray$1(schema) ? FromArray$1(schema, references) :
2361
+ IsObject$1(schema) ? FromObject$1(schema, references) :
2362
+ IsPromise$1(schema) ? FromPromise$1(schema, references) :
2363
+ IsAsyncIterator$1(schema) ? FromAsyncIterator$1(schema, references) :
2364
+ IsIterator$1(schema) ? FromIterator$1(schema, references) :
2365
+ IsRef$1(schema) ? FromRef(schema, references) :
2366
+ schema);
2367
+ }
2368
+ // ------------------------------------------------------------------
2369
+ // TDeref
2370
+ // ------------------------------------------------------------------
2371
+ /** `[Json]` Creates a dereferenced type */
2372
+ function Deref(schema, references) {
2373
+ return DerefResolve(CloneType(schema), CloneRest(references));
2374
+ }
2375
+
2376
+ /** `[Json]` Creates a Enum type */
2377
+ function Enum(item, options = {}) {
2378
+ if (IsUndefined$2(item))
2379
+ throw new Error('Enum undefined or empty');
2380
+ const values1 = globalThis.Object.getOwnPropertyNames(item)
2381
+ .filter((key) => isNaN(key))
2382
+ .map((key) => item[key]);
2383
+ const values2 = [...new Set(values1)];
2384
+ const anyOf = values2.map((value) => Literal(value));
2385
+ return Union(anyOf, { ...options, [Hint]: 'Enum' });
2386
+ }
2387
+
2388
+ class ExtendsResolverError extends TypeBoxError {
2389
+ }
2390
+ var ExtendsResult;
2391
+ (function (ExtendsResult) {
2392
+ ExtendsResult[ExtendsResult["Union"] = 0] = "Union";
2393
+ ExtendsResult[ExtendsResult["True"] = 1] = "True";
2394
+ ExtendsResult[ExtendsResult["False"] = 2] = "False";
2395
+ })(ExtendsResult || (ExtendsResult = {}));
2396
+ // ------------------------------------------------------------------
2397
+ // IntoBooleanResult
2398
+ // ------------------------------------------------------------------
2399
+ // prettier-ignore
2400
+ function IntoBooleanResult(result) {
2401
+ return result === ExtendsResult.False ? result : ExtendsResult.True;
2402
+ }
2403
+ // ------------------------------------------------------------------
2404
+ // Throw
2405
+ // ------------------------------------------------------------------
2406
+ // prettier-ignore
2407
+ function Throw(message) {
2408
+ throw new ExtendsResolverError(message);
2409
+ }
2410
+ // ------------------------------------------------------------------
2411
+ // StructuralRight
2412
+ // ------------------------------------------------------------------
2413
+ // prettier-ignore
2414
+ function IsStructuralRight(right) {
2415
+ return (IsNever(right) ||
2416
+ IsIntersect(right) ||
2417
+ IsUnion(right) ||
2418
+ IsUnknown(right) ||
2419
+ IsAny(right));
2420
+ }
2421
+ // prettier-ignore
2422
+ function StructuralRight(left, right) {
2423
+ return (IsNever(right) ? FromNeverRight() :
2424
+ IsIntersect(right) ? FromIntersectRight(left, right) :
2425
+ IsUnion(right) ? FromUnionRight(left, right) :
2426
+ IsUnknown(right) ? FromUnknownRight() :
2427
+ IsAny(right) ? FromAnyRight() :
2428
+ Throw('StructuralRight'));
2429
+ }
2430
+ // ------------------------------------------------------------------
2431
+ // Any
2432
+ // ------------------------------------------------------------------
2433
+ // prettier-ignore
2434
+ function FromAnyRight(left, right) {
2435
+ return ExtendsResult.True;
2436
+ }
2437
+ // prettier-ignore
2438
+ function FromAny(left, right) {
2439
+ return (IsIntersect(right) ? FromIntersectRight(left, right) :
2440
+ (IsUnion(right) && right.anyOf.some((schema) => IsAny(schema) || IsUnknown(schema))) ? ExtendsResult.True :
2441
+ IsUnion(right) ? ExtendsResult.Union :
2442
+ IsUnknown(right) ? ExtendsResult.True :
2443
+ IsAny(right) ? ExtendsResult.True :
2444
+ ExtendsResult.Union);
2445
+ }
2446
+ // ------------------------------------------------------------------
2447
+ // Array
2448
+ // ------------------------------------------------------------------
2449
+ // prettier-ignore
2450
+ function FromArrayRight(left, right) {
2451
+ return (IsUnknown(left) ? ExtendsResult.False :
2452
+ IsAny(left) ? ExtendsResult.Union :
2453
+ IsNever(left) ? ExtendsResult.True :
2454
+ ExtendsResult.False);
2455
+ }
2456
+ // prettier-ignore
2457
+ function FromArray(left, right) {
2458
+ return (IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True :
2459
+ IsStructuralRight(right) ? StructuralRight(left, right) :
2460
+ !IsArray(right) ? ExtendsResult.False :
2461
+ IntoBooleanResult(Visit(left.items, right.items)));
2462
+ }
2463
+ // ------------------------------------------------------------------
2464
+ // AsyncIterator
2465
+ // ------------------------------------------------------------------
2466
+ // prettier-ignore
2467
+ function FromAsyncIterator(left, right) {
2468
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2469
+ !IsAsyncIterator(right) ? ExtendsResult.False :
2470
+ IntoBooleanResult(Visit(left.items, right.items)));
2471
+ }
2472
+ // ------------------------------------------------------------------
2473
+ // BigInt
2474
+ // ------------------------------------------------------------------
2475
+ // prettier-ignore
2476
+ function FromBigInt(left, right) {
2477
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2478
+ IsObject(right) ? FromObjectRight(left, right) :
2479
+ IsRecord(right) ? FromRecordRight(left, right) :
2480
+ IsBigInt(right) ? ExtendsResult.True :
2481
+ ExtendsResult.False);
2482
+ }
2483
+ // ------------------------------------------------------------------
2484
+ // Boolean
2485
+ // ------------------------------------------------------------------
2486
+ // prettier-ignore
2487
+ function FromBooleanRight(left, right) {
2488
+ return (IsLiteralBoolean(left) ? ExtendsResult.True :
2489
+ IsBoolean(left) ? ExtendsResult.True :
2490
+ ExtendsResult.False);
2491
+ }
2492
+ // prettier-ignore
2493
+ function FromBoolean(left, right) {
2494
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2495
+ IsObject(right) ? FromObjectRight(left, right) :
2496
+ IsRecord(right) ? FromRecordRight(left, right) :
2497
+ IsBoolean(right) ? ExtendsResult.True :
2498
+ ExtendsResult.False);
2499
+ }
2500
+ // ------------------------------------------------------------------
2501
+ // Constructor
2502
+ // ------------------------------------------------------------------
2503
+ // prettier-ignore
2504
+ function FromConstructor(left, right) {
2505
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2506
+ IsObject(right) ? FromObjectRight(left, right) :
2507
+ !IsConstructor(right) ? ExtendsResult.False :
2508
+ left.parameters.length > right.parameters.length ? ExtendsResult.False :
2509
+ (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True)) ? ExtendsResult.False :
2510
+ IntoBooleanResult(Visit(left.returns, right.returns)));
2511
+ }
2512
+ // ------------------------------------------------------------------
2513
+ // Date
2514
+ // ------------------------------------------------------------------
2515
+ // prettier-ignore
2516
+ function FromDate(left, right) {
2517
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2518
+ IsObject(right) ? FromObjectRight(left, right) :
2519
+ IsRecord(right) ? FromRecordRight(left, right) :
2520
+ IsDate(right) ? ExtendsResult.True :
2521
+ ExtendsResult.False);
2522
+ }
2523
+ // ------------------------------------------------------------------
2524
+ // Function
2525
+ // ------------------------------------------------------------------
2526
+ // prettier-ignore
2527
+ function FromFunction(left, right) {
2528
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2529
+ IsObject(right) ? FromObjectRight(left, right) :
2530
+ !IsFunction(right) ? ExtendsResult.False :
2531
+ left.parameters.length > right.parameters.length ? ExtendsResult.False :
2532
+ (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True)) ? ExtendsResult.False :
2533
+ IntoBooleanResult(Visit(left.returns, right.returns)));
2534
+ }
2535
+ // ------------------------------------------------------------------
2536
+ // Integer
2537
+ // ------------------------------------------------------------------
2538
+ // prettier-ignore
2539
+ function FromIntegerRight(left, right) {
2540
+ return (IsLiteral(left) && IsNumber$2(left.const) ? ExtendsResult.True :
2541
+ IsNumber(left) || IsInteger(left) ? ExtendsResult.True :
2542
+ ExtendsResult.False);
2543
+ }
2544
+ // prettier-ignore
2545
+ function FromInteger(left, right) {
2546
+ return (IsInteger(right) || IsNumber(right) ? ExtendsResult.True :
2547
+ IsStructuralRight(right) ? StructuralRight(left, right) :
2548
+ IsObject(right) ? FromObjectRight(left, right) :
2549
+ IsRecord(right) ? FromRecordRight(left, right) :
2550
+ ExtendsResult.False);
2551
+ }
2552
+ // ------------------------------------------------------------------
2553
+ // Intersect
2554
+ // ------------------------------------------------------------------
2555
+ // prettier-ignore
2556
+ function FromIntersectRight(left, right) {
2557
+ return right.allOf.every((schema) => Visit(left, schema) === ExtendsResult.True)
2558
+ ? ExtendsResult.True
2559
+ : ExtendsResult.False;
2560
+ }
2561
+ // prettier-ignore
2562
+ function FromIntersect$2(left, right) {
2563
+ return left.allOf.some((schema) => Visit(schema, right) === ExtendsResult.True)
2564
+ ? ExtendsResult.True
2565
+ : ExtendsResult.False;
2566
+ }
2567
+ // ------------------------------------------------------------------
2568
+ // Iterator
2569
+ // ------------------------------------------------------------------
2570
+ // prettier-ignore
2571
+ function FromIterator(left, right) {
2572
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2573
+ !IsIterator(right) ? ExtendsResult.False :
2574
+ IntoBooleanResult(Visit(left.items, right.items)));
2575
+ }
2576
+ // ------------------------------------------------------------------
2577
+ // Literal
2578
+ // ------------------------------------------------------------------
2579
+ // prettier-ignore
2580
+ function FromLiteral(left, right) {
2581
+ return (IsLiteral(right) && right.const === left.const ? ExtendsResult.True :
2582
+ IsStructuralRight(right) ? StructuralRight(left, right) :
2583
+ IsObject(right) ? FromObjectRight(left, right) :
2584
+ IsRecord(right) ? FromRecordRight(left, right) :
2585
+ IsString(right) ? FromStringRight(left) :
2586
+ IsNumber(right) ? FromNumberRight(left) :
2587
+ IsInteger(right) ? FromIntegerRight(left) :
2588
+ IsBoolean(right) ? FromBooleanRight(left) :
2589
+ ExtendsResult.False);
2590
+ }
2591
+ // ------------------------------------------------------------------
2592
+ // Never
2593
+ // ------------------------------------------------------------------
2594
+ // prettier-ignore
2595
+ function FromNeverRight(left, right) {
2596
+ return ExtendsResult.False;
2597
+ }
2598
+ // prettier-ignore
2599
+ function FromNever(left, right) {
2600
+ return ExtendsResult.True;
2601
+ }
2602
+ // ------------------------------------------------------------------
2603
+ // Not
2604
+ // ------------------------------------------------------------------
2605
+ // prettier-ignore
2606
+ function UnwrapTNot(schema) {
2607
+ let [current, depth] = [schema, 0];
2608
+ while (true) {
2609
+ if (!IsNot(current))
2610
+ break;
2611
+ current = current.not;
2612
+ depth += 1;
2613
+ }
2614
+ return depth % 2 === 0 ? current : Unknown();
2615
+ }
2616
+ // prettier-ignore
2617
+ function FromNot(left, right) {
2618
+ // TypeScript has no concept of negated types, and attempts to correctly check the negated
2619
+ // type at runtime would put TypeBox at odds with TypeScripts ability to statically infer
2620
+ // the type. Instead we unwrap to either unknown or T and continue evaluating.
2621
+ // prettier-ignore
2622
+ return (IsNot(left) ? Visit(UnwrapTNot(left), right) :
2623
+ IsNot(right) ? Visit(left, UnwrapTNot(right)) :
2624
+ Throw('Invalid fallthrough for Not'));
2625
+ }
2626
+ // ------------------------------------------------------------------
2627
+ // Null
2628
+ // ------------------------------------------------------------------
2629
+ // prettier-ignore
2630
+ function FromNull(left, right) {
2631
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2632
+ IsObject(right) ? FromObjectRight(left, right) :
2633
+ IsRecord(right) ? FromRecordRight(left, right) :
2634
+ IsNull(right) ? ExtendsResult.True :
2635
+ ExtendsResult.False);
2636
+ }
2637
+ // ------------------------------------------------------------------
2638
+ // Number
2639
+ // ------------------------------------------------------------------
2640
+ // prettier-ignore
2641
+ function FromNumberRight(left, right) {
2642
+ return (IsLiteralNumber(left) ? ExtendsResult.True :
2643
+ IsNumber(left) || IsInteger(left) ? ExtendsResult.True :
2644
+ ExtendsResult.False);
2645
+ }
2646
+ // prettier-ignore
2647
+ function FromNumber(left, right) {
2648
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2649
+ IsObject(right) ? FromObjectRight(left, right) :
2650
+ IsRecord(right) ? FromRecordRight(left, right) :
2651
+ IsInteger(right) || IsNumber(right) ? ExtendsResult.True :
2652
+ ExtendsResult.False);
2653
+ }
2654
+ // ------------------------------------------------------------------
2655
+ // Object
2656
+ // ------------------------------------------------------------------
2657
+ // prettier-ignore
2658
+ function IsObjectPropertyCount(schema, count) {
2659
+ return Object.getOwnPropertyNames(schema.properties).length === count;
2660
+ }
2661
+ // prettier-ignore
2662
+ function IsObjectStringLike(schema) {
2663
+ return IsObjectArrayLike(schema);
2664
+ }
2665
+ // prettier-ignore
2666
+ function IsObjectSymbolLike(schema) {
2667
+ return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'description' in schema.properties && IsUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && ((IsString(schema.properties.description.anyOf[0]) &&
2668
+ IsUndefined(schema.properties.description.anyOf[1])) || (IsString(schema.properties.description.anyOf[1]) &&
2669
+ IsUndefined(schema.properties.description.anyOf[0]))));
2670
+ }
2671
+ // prettier-ignore
2672
+ function IsObjectNumberLike(schema) {
2673
+ return IsObjectPropertyCount(schema, 0);
2674
+ }
2675
+ // prettier-ignore
2676
+ function IsObjectBooleanLike(schema) {
2677
+ return IsObjectPropertyCount(schema, 0);
2678
+ }
2679
+ // prettier-ignore
2680
+ function IsObjectBigIntLike(schema) {
2681
+ return IsObjectPropertyCount(schema, 0);
2682
+ }
2683
+ // prettier-ignore
2684
+ function IsObjectDateLike(schema) {
2685
+ return IsObjectPropertyCount(schema, 0);
2686
+ }
2687
+ // prettier-ignore
2688
+ function IsObjectUint8ArrayLike(schema) {
2689
+ return IsObjectArrayLike(schema);
2690
+ }
2691
+ // prettier-ignore
2692
+ function IsObjectFunctionLike(schema) {
2693
+ const length = Number();
2694
+ return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === ExtendsResult.True);
2695
+ }
2696
+ // prettier-ignore
2697
+ function IsObjectConstructorLike(schema) {
2698
+ return IsObjectPropertyCount(schema, 0);
2699
+ }
2700
+ // prettier-ignore
2701
+ function IsObjectArrayLike(schema) {
2702
+ const length = Number();
2703
+ return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === ExtendsResult.True);
2704
+ }
2705
+ // prettier-ignore
2706
+ function IsObjectPromiseLike(schema) {
2707
+ const then = Function([Any()], Any());
2708
+ return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'then' in schema.properties && IntoBooleanResult(Visit(schema.properties['then'], then)) === ExtendsResult.True);
2709
+ }
2710
+ // ------------------------------------------------------------------
2711
+ // Property
2712
+ // ------------------------------------------------------------------
2713
+ // prettier-ignore
2714
+ function Property(left, right) {
2715
+ return (Visit(left, right) === ExtendsResult.False ? ExtendsResult.False :
2716
+ IsOptional(left) && !IsOptional(right) ? ExtendsResult.False :
2717
+ ExtendsResult.True);
2718
+ }
2719
+ // prettier-ignore
2720
+ function FromObjectRight(left, right) {
2721
+ return (IsUnknown(left) ? ExtendsResult.False :
2722
+ IsAny(left) ? ExtendsResult.Union : (IsNever(left) ||
2723
+ (IsLiteralString(left) && IsObjectStringLike(right)) ||
2724
+ (IsLiteralNumber(left) && IsObjectNumberLike(right)) ||
2725
+ (IsLiteralBoolean(left) && IsObjectBooleanLike(right)) ||
2726
+ (IsSymbol(left) && IsObjectSymbolLike(right)) ||
2727
+ (IsBigInt(left) && IsObjectBigIntLike(right)) ||
2728
+ (IsString(left) && IsObjectStringLike(right)) ||
2729
+ (IsSymbol(left) && IsObjectSymbolLike(right)) ||
2730
+ (IsNumber(left) && IsObjectNumberLike(right)) ||
2731
+ (IsInteger(left) && IsObjectNumberLike(right)) ||
2732
+ (IsBoolean(left) && IsObjectBooleanLike(right)) ||
2733
+ (IsUint8Array(left) && IsObjectUint8ArrayLike(right)) ||
2734
+ (IsDate(left) && IsObjectDateLike(right)) ||
2735
+ (IsConstructor(left) && IsObjectConstructorLike(right)) ||
2736
+ (IsFunction(left) && IsObjectFunctionLike(right))) ? ExtendsResult.True :
2737
+ (IsRecord(left) && IsString(RecordKey(left))) ? (() => {
2738
+ // When expressing a Record with literal key values, the Record is converted into a Object with
2739
+ // the Hint assigned as `Record`. This is used to invert the extends logic.
2740
+ return right[Hint] === 'Record' ? ExtendsResult.True : ExtendsResult.False;
2741
+ })() :
2742
+ (IsRecord(left) && IsNumber(RecordKey(left))) ? (() => {
2743
+ return IsObjectPropertyCount(right, 0) ? ExtendsResult.True : ExtendsResult.False;
2744
+ })() :
2745
+ ExtendsResult.False);
2746
+ }
2747
+ // prettier-ignore
2748
+ function FromObject(left, right) {
2749
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2750
+ IsRecord(right) ? FromRecordRight(left, right) :
2751
+ !IsObject(right) ? ExtendsResult.False :
2752
+ (() => {
2753
+ for (const key of Object.getOwnPropertyNames(right.properties)) {
2754
+ if (!(key in left.properties) && !IsOptional(right.properties[key])) {
2755
+ return ExtendsResult.False;
2756
+ }
2757
+ if (IsOptional(right.properties[key])) {
2758
+ return ExtendsResult.True;
2759
+ }
2760
+ if (Property(left.properties[key], right.properties[key]) === ExtendsResult.False) {
2761
+ return ExtendsResult.False;
2762
+ }
2763
+ }
2764
+ return ExtendsResult.True;
2765
+ })());
2766
+ }
2767
+ // ------------------------------------------------------------------
2768
+ // Promise
2769
+ // ------------------------------------------------------------------
2770
+ // prettier-ignore
2771
+ function FromPromise(left, right) {
2772
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2773
+ IsObject(right) && IsObjectPromiseLike(right) ? ExtendsResult.True :
2774
+ !IsPromise(right) ? ExtendsResult.False :
2775
+ IntoBooleanResult(Visit(left.item, right.item)));
2776
+ }
2777
+ // ------------------------------------------------------------------
2778
+ // Record
2779
+ // ------------------------------------------------------------------
2780
+ // prettier-ignore
2781
+ function RecordKey(schema) {
2782
+ return (PatternNumberExact in schema.patternProperties ? Number() :
2783
+ PatternStringExact in schema.patternProperties ? String$1() :
2784
+ Throw('Unknown record key pattern'));
2785
+ }
2786
+ // prettier-ignore
2787
+ function RecordValue(schema) {
2788
+ return (PatternNumberExact in schema.patternProperties ? schema.patternProperties[PatternNumberExact] :
2789
+ PatternStringExact in schema.patternProperties ? schema.patternProperties[PatternStringExact] :
2790
+ Throw('Unable to get record value schema'));
2791
+ }
2792
+ // prettier-ignore
2793
+ function FromRecordRight(left, right) {
2794
+ const [Key, Value] = [RecordKey(right), RecordValue(right)];
2795
+ return ((IsLiteralString(left) && IsNumber(Key) && IntoBooleanResult(Visit(left, Value)) === ExtendsResult.True) ? ExtendsResult.True :
2796
+ IsUint8Array(left) && IsNumber(Key) ? Visit(left, Value) :
2797
+ IsString(left) && IsNumber(Key) ? Visit(left, Value) :
2798
+ IsArray(left) && IsNumber(Key) ? Visit(left, Value) :
2799
+ IsObject(left) ? (() => {
2800
+ for (const key of Object.getOwnPropertyNames(left.properties)) {
2801
+ if (Property(Value, left.properties[key]) === ExtendsResult.False) {
2802
+ return ExtendsResult.False;
2803
+ }
2804
+ }
2805
+ return ExtendsResult.True;
2806
+ })() :
2807
+ ExtendsResult.False);
2808
+ }
2809
+ // prettier-ignore
2810
+ function FromRecord(left, right) {
2811
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2812
+ IsObject(right) ? FromObjectRight(left, right) :
2813
+ !IsRecord(right) ? ExtendsResult.False :
2814
+ Visit(RecordValue(left), RecordValue(right)));
2815
+ }
2816
+ // ------------------------------------------------------------------
2817
+ // RegExp
2818
+ // ------------------------------------------------------------------
2819
+ // prettier-ignore
2820
+ function FromRegExp(left, right) {
2821
+ // Note: RegExp types evaluate as strings, not RegExp objects.
2822
+ // Here we remap either into string and continue evaluating.
2823
+ const L = IsRegExp(left) ? String$1() : left;
2824
+ const R = IsRegExp(right) ? String$1() : right;
2825
+ return Visit(L, R);
2826
+ }
2827
+ // ------------------------------------------------------------------
2828
+ // String
2829
+ // ------------------------------------------------------------------
2830
+ // prettier-ignore
2831
+ function FromStringRight(left, right) {
2832
+ return (IsLiteral(left) && IsString$2(left.const) ? ExtendsResult.True :
2833
+ IsString(left) ? ExtendsResult.True :
2834
+ ExtendsResult.False);
2835
+ }
2836
+ // prettier-ignore
2837
+ function FromString(left, right) {
2838
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2839
+ IsObject(right) ? FromObjectRight(left, right) :
2840
+ IsRecord(right) ? FromRecordRight(left, right) :
2841
+ IsString(right) ? ExtendsResult.True :
2842
+ ExtendsResult.False);
2843
+ }
2844
+ // ------------------------------------------------------------------
2845
+ // Symbol
2846
+ // ------------------------------------------------------------------
2847
+ // prettier-ignore
2848
+ function FromSymbol(left, right) {
2849
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2850
+ IsObject(right) ? FromObjectRight(left, right) :
2851
+ IsRecord(right) ? FromRecordRight(left, right) :
2852
+ IsSymbol(right) ? ExtendsResult.True :
2853
+ ExtendsResult.False);
2854
+ }
2855
+ // ------------------------------------------------------------------
2856
+ // TemplateLiteral
2857
+ // ------------------------------------------------------------------
2858
+ // prettier-ignore
2859
+ function FromTemplateLiteral$1(left, right) {
2860
+ // TemplateLiteral types are resolved to either unions for finite expressions or string
2861
+ // for infinite expressions. Here we call to TemplateLiteralResolver to resolve for
2862
+ // either type and continue evaluating.
2863
+ return (IsTemplateLiteral(left) ? Visit(TemplateLiteralToUnion(left), right) :
2864
+ IsTemplateLiteral(right) ? Visit(left, TemplateLiteralToUnion(right)) :
2865
+ Throw('Invalid fallthrough for TemplateLiteral'));
2866
+ }
2867
+ // ------------------------------------------------------------------
2868
+ // Tuple
2869
+ // ------------------------------------------------------------------
2870
+ // prettier-ignore
2871
+ function IsArrayOfTuple(left, right) {
2872
+ return (IsArray(right) &&
2873
+ left.items !== undefined &&
2874
+ left.items.every((schema) => Visit(schema, right.items) === ExtendsResult.True));
2875
+ }
2876
+ // prettier-ignore
2877
+ function FromTupleRight(left, right) {
2878
+ return (IsNever(left) ? ExtendsResult.True :
2879
+ IsUnknown(left) ? ExtendsResult.False :
2880
+ IsAny(left) ? ExtendsResult.Union :
2881
+ ExtendsResult.False);
2882
+ }
2883
+ // prettier-ignore
2884
+ function FromTuple(left, right) {
2885
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2886
+ IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True :
2887
+ IsArray(right) && IsArrayOfTuple(left, right) ? ExtendsResult.True :
2888
+ !IsTuple(right) ? ExtendsResult.False :
2889
+ (IsUndefined$2(left.items) && !IsUndefined$2(right.items)) || (!IsUndefined$2(left.items) && IsUndefined$2(right.items)) ? ExtendsResult.False :
2890
+ (IsUndefined$2(left.items) && !IsUndefined$2(right.items)) ? ExtendsResult.True :
2891
+ left.items.every((schema, index) => Visit(schema, right.items[index]) === ExtendsResult.True) ? ExtendsResult.True :
2892
+ ExtendsResult.False);
2893
+ }
2894
+ // ------------------------------------------------------------------
2895
+ // Uint8Array
2896
+ // ------------------------------------------------------------------
2897
+ // prettier-ignore
2898
+ function FromUint8Array(left, right) {
2899
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2900
+ IsObject(right) ? FromObjectRight(left, right) :
2901
+ IsRecord(right) ? FromRecordRight(left, right) :
2902
+ IsUint8Array(right) ? ExtendsResult.True :
2903
+ ExtendsResult.False);
2904
+ }
2905
+ // ------------------------------------------------------------------
2906
+ // Undefined
2907
+ // ------------------------------------------------------------------
2908
+ // prettier-ignore
2909
+ function FromUndefined(left, right) {
2910
+ return (IsStructuralRight(right) ? StructuralRight(left, right) :
2911
+ IsObject(right) ? FromObjectRight(left, right) :
2912
+ IsRecord(right) ? FromRecordRight(left, right) :
2913
+ IsVoid(right) ? FromVoidRight(left) :
2914
+ IsUndefined(right) ? ExtendsResult.True :
2915
+ ExtendsResult.False);
2916
+ }
2917
+ // ------------------------------------------------------------------
2918
+ // Union
2919
+ // ------------------------------------------------------------------
2920
+ // prettier-ignore
2921
+ function FromUnionRight(left, right) {
2922
+ return right.anyOf.some((schema) => Visit(left, schema) === ExtendsResult.True)
2923
+ ? ExtendsResult.True
2924
+ : ExtendsResult.False;
2925
+ }
2926
+ // prettier-ignore
2927
+ function FromUnion$2(left, right) {
2928
+ return left.anyOf.every((schema) => Visit(schema, right) === ExtendsResult.True)
2929
+ ? ExtendsResult.True
2930
+ : ExtendsResult.False;
2931
+ }
2932
+ // ------------------------------------------------------------------
2933
+ // Unknown
2934
+ // ------------------------------------------------------------------
2935
+ // prettier-ignore
2936
+ function FromUnknownRight(left, right) {
2937
+ return ExtendsResult.True;
2938
+ }
2939
+ // prettier-ignore
2940
+ function FromUnknown(left, right) {
2941
+ return (IsNever(right) ? FromNeverRight() :
2942
+ IsIntersect(right) ? FromIntersectRight(left, right) :
2943
+ IsUnion(right) ? FromUnionRight(left, right) :
2944
+ IsAny(right) ? FromAnyRight() :
2945
+ IsString(right) ? FromStringRight(left) :
2946
+ IsNumber(right) ? FromNumberRight(left) :
2947
+ IsInteger(right) ? FromIntegerRight(left) :
2948
+ IsBoolean(right) ? FromBooleanRight(left) :
2949
+ IsArray(right) ? FromArrayRight(left) :
2950
+ IsTuple(right) ? FromTupleRight(left) :
2951
+ IsObject(right) ? FromObjectRight(left, right) :
2952
+ IsUnknown(right) ? ExtendsResult.True :
2953
+ ExtendsResult.False);
2954
+ }
2955
+ // ------------------------------------------------------------------
2956
+ // Void
2957
+ // ------------------------------------------------------------------
2958
+ // prettier-ignore
2959
+ function FromVoidRight(left, right) {
2960
+ return (IsUndefined(left) ? ExtendsResult.True :
2961
+ IsUndefined(left) ? ExtendsResult.True :
2962
+ ExtendsResult.False);
2963
+ }
2964
+ // prettier-ignore
2965
+ function FromVoid(left, right) {
2966
+ return (IsIntersect(right) ? FromIntersectRight(left, right) :
2967
+ IsUnion(right) ? FromUnionRight(left, right) :
2968
+ IsUnknown(right) ? FromUnknownRight() :
2969
+ IsAny(right) ? FromAnyRight() :
2970
+ IsObject(right) ? FromObjectRight(left, right) :
2971
+ IsVoid(right) ? ExtendsResult.True :
2972
+ ExtendsResult.False);
2973
+ }
2974
+ // prettier-ignore
2975
+ function Visit(left, right) {
2976
+ return (
2977
+ // resolvable
2978
+ (IsTemplateLiteral(left) || IsTemplateLiteral(right)) ? FromTemplateLiteral$1(left, right) :
2979
+ (IsRegExp(left) || IsRegExp(right)) ? FromRegExp(left, right) :
2980
+ (IsNot(left) || IsNot(right)) ? FromNot(left, right) :
2981
+ // standard
2982
+ IsAny(left) ? FromAny(left, right) :
2983
+ IsArray(left) ? FromArray(left, right) :
2984
+ IsBigInt(left) ? FromBigInt(left, right) :
2985
+ IsBoolean(left) ? FromBoolean(left, right) :
2986
+ IsAsyncIterator(left) ? FromAsyncIterator(left, right) :
2987
+ IsConstructor(left) ? FromConstructor(left, right) :
2988
+ IsDate(left) ? FromDate(left, right) :
2989
+ IsFunction(left) ? FromFunction(left, right) :
2990
+ IsInteger(left) ? FromInteger(left, right) :
2991
+ IsIntersect(left) ? FromIntersect$2(left, right) :
2992
+ IsIterator(left) ? FromIterator(left, right) :
2993
+ IsLiteral(left) ? FromLiteral(left, right) :
2994
+ IsNever(left) ? FromNever() :
2995
+ IsNull(left) ? FromNull(left, right) :
2996
+ IsNumber(left) ? FromNumber(left, right) :
2997
+ IsObject(left) ? FromObject(left, right) :
2998
+ IsRecord(left) ? FromRecord(left, right) :
2999
+ IsString(left) ? FromString(left, right) :
3000
+ IsSymbol(left) ? FromSymbol(left, right) :
3001
+ IsTuple(left) ? FromTuple(left, right) :
3002
+ IsPromise(left) ? FromPromise(left, right) :
3003
+ IsUint8Array(left) ? FromUint8Array(left, right) :
3004
+ IsUndefined(left) ? FromUndefined(left, right) :
3005
+ IsUnion(left) ? FromUnion$2(left, right) :
3006
+ IsUnknown(left) ? FromUnknown(left, right) :
3007
+ IsVoid(left) ? FromVoid(left, right) :
3008
+ Throw(`Unknown left type operand '${left[Kind]}'`));
3009
+ }
3010
+ function ExtendsCheck(left, right) {
3011
+ return Visit(left, right);
3012
+ }
3013
+
3014
+ // prettier-ignore
3015
+ function FromProperties$a(P, Right, True, False, options) {
3016
+ const Acc = {};
3017
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P))
3018
+ Acc[K2] = Extends(P[K2], Right, True, False, options);
3019
+ return Acc;
3020
+ }
3021
+ // prettier-ignore
3022
+ function FromMappedResult$6(Left, Right, True, False, options) {
3023
+ return FromProperties$a(Left.properties, Right, True, False, options);
3024
+ }
3025
+ // prettier-ignore
3026
+ function ExtendsFromMappedResult(Left, Right, True, False, options) {
3027
+ const P = FromMappedResult$6(Left, Right, True, False, options);
3028
+ return MappedResult(P);
3029
+ }
3030
+
3031
+ // prettier-ignore
3032
+ function ExtendsResolve(left, right, trueType, falseType) {
3033
+ const R = ExtendsCheck(left, right);
3034
+ return (R === ExtendsResult.Union ? Union([trueType, falseType]) :
3035
+ R === ExtendsResult.True ? trueType :
3036
+ falseType);
3037
+ }
3038
+ /** `[Json]` Creates a Conditional type */
3039
+ function Extends(L, R, T, F, options = {}) {
3040
+ // prettier-ignore
3041
+ return (IsMappedResult$1(L) ? ExtendsFromMappedResult(L, R, T, F, options) :
3042
+ IsMappedKey$1(L) ? CloneType(ExtendsFromMappedKey(L, R, T, F, options)) :
3043
+ CloneType(ExtendsResolve(L, R, T, F), options));
3044
+ }
3045
+
3046
+ // prettier-ignore
3047
+ function FromPropertyKey$2(K, U, L, R, options) {
3048
+ return {
3049
+ [K]: Extends(Literal(K), U, L, R, options)
3050
+ };
3051
+ }
3052
+ // prettier-ignore
3053
+ function FromPropertyKeys$2(K, U, L, R, options) {
3054
+ return K.reduce((Acc, LK) => {
3055
+ return { ...Acc, ...FromPropertyKey$2(LK, U, L, R, options) };
3056
+ }, {});
3057
+ }
3058
+ // prettier-ignore
3059
+ function FromMappedKey$2(K, U, L, R, options) {
3060
+ return FromPropertyKeys$2(K.keys, U, L, R, options);
3061
+ }
3062
+ // prettier-ignore
3063
+ function ExtendsFromMappedKey(T, U, L, R, options) {
3064
+ const P = FromMappedKey$2(T, U, L, R, options);
3065
+ return MappedResult(P);
3066
+ }
3067
+
3068
+ function ExcludeFromTemplateLiteral(L, R) {
3069
+ return Exclude(TemplateLiteralToUnion(L), R);
3070
+ }
3071
+
3072
+ function ExcludeRest(L, R) {
3073
+ const excluded = L.filter((inner) => ExtendsCheck(inner, R) === ExtendsResult.False);
3074
+ return excluded.length === 1 ? excluded[0] : Union(excluded);
3075
+ }
3076
+ /** `[Json]` Constructs a type by excluding from unionType all union members that are assignable to excludedMembers */
3077
+ function Exclude(L, R, options = {}) {
3078
+ // overloads
3079
+ if (IsTemplateLiteral$1(L))
3080
+ return CloneType(ExcludeFromTemplateLiteral(L, R), options);
3081
+ if (IsMappedResult$1(L))
3082
+ return CloneType(ExcludeFromMappedResult(L, R), options);
3083
+ // prettier-ignore
3084
+ return CloneType(IsUnion$1(L) ? ExcludeRest(L.anyOf, R) :
3085
+ ExtendsCheck(L, R) !== ExtendsResult.False ? Never() : L, options);
3086
+ }
3087
+
3088
+ // prettier-ignore
3089
+ function FromProperties$9(P, U) {
3090
+ const Acc = {};
3091
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P))
3092
+ Acc[K2] = Exclude(P[K2], U);
3093
+ return Acc;
3094
+ }
3095
+ // prettier-ignore
3096
+ function FromMappedResult$5(R, T) {
3097
+ return FromProperties$9(R.properties, T);
3098
+ }
3099
+ // prettier-ignore
3100
+ function ExcludeFromMappedResult(R, T) {
3101
+ const P = FromMappedResult$5(R, T);
3102
+ return MappedResult(P);
3103
+ }
3104
+
3105
+ function ExtractFromTemplateLiteral(L, R) {
3106
+ return Extract(TemplateLiteralToUnion(L), R);
3107
+ }
3108
+
3109
+ function ExtractRest(L, R) {
3110
+ const extracted = L.filter((inner) => ExtendsCheck(inner, R) !== ExtendsResult.False);
3111
+ return extracted.length === 1 ? extracted[0] : Union(extracted);
3112
+ }
3113
+ /** `[Json]` Constructs a type by extracting from type all union members that are assignable to union */
3114
+ function Extract(L, R, options = {}) {
3115
+ // overloads
3116
+ if (IsTemplateLiteral$1(L))
3117
+ return CloneType(ExtractFromTemplateLiteral(L, R), options);
3118
+ if (IsMappedResult$1(L))
3119
+ return CloneType(ExtractFromMappedResult(L, R), options);
3120
+ // prettier-ignore
3121
+ return CloneType(IsUnion$1(L) ? ExtractRest(L.anyOf, R) :
3122
+ ExtendsCheck(L, R) !== ExtendsResult.False ? L : Never(), options);
3123
+ }
3124
+
3125
+ // prettier-ignore
3126
+ function FromProperties$8(P, T) {
3127
+ const Acc = {};
3128
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P))
3129
+ Acc[K2] = Extract(P[K2], T);
3130
+ return Acc;
3131
+ }
3132
+ // prettier-ignore
3133
+ function FromMappedResult$4(R, T) {
3134
+ return FromProperties$8(R.properties, T);
3135
+ }
3136
+ // prettier-ignore
3137
+ function ExtractFromMappedResult(R, T) {
3138
+ const P = FromMappedResult$4(R, T);
3139
+ return MappedResult(P);
3140
+ }
3141
+
3142
+ /** `[JavaScript]` Extracts the InstanceType from the given Constructor type */
3143
+ function InstanceType(schema, options = {}) {
3144
+ return CloneType(schema.returns, options);
3145
+ }
3146
+
3147
+ /** `[Json]` Creates an Integer type */
3148
+ function Integer(options = {}) {
3149
+ return {
3150
+ ...options,
3151
+ [Kind]: 'Integer',
3152
+ type: 'integer',
3153
+ };
3154
+ }
3155
+
3156
+ // prettier-ignore
3157
+ function MappedIntrinsicPropertyKey(K, M, options) {
3158
+ return {
3159
+ [K]: Intrinsic(Literal(K), M, options)
3160
+ };
3161
+ }
3162
+ // prettier-ignore
3163
+ function MappedIntrinsicPropertyKeys(K, M, options) {
3164
+ return K.reduce((Acc, L) => {
3165
+ return { ...Acc, ...MappedIntrinsicPropertyKey(L, M, options) };
3166
+ }, {});
3167
+ }
3168
+ // prettier-ignore
3169
+ function MappedIntrinsicProperties(T, M, options) {
3170
+ return MappedIntrinsicPropertyKeys(T['keys'], M, options);
3171
+ }
3172
+ // prettier-ignore
3173
+ function IntrinsicFromMappedKey(T, M, options) {
3174
+ const P = MappedIntrinsicProperties(T, M, options);
3175
+ return MappedResult(P);
3176
+ }
3177
+
3178
+ // ------------------------------------------------------------------
3179
+ // Apply
3180
+ // ------------------------------------------------------------------
3181
+ function ApplyUncapitalize(value) {
3182
+ const [first, rest] = [value.slice(0, 1), value.slice(1)];
3183
+ return [first.toLowerCase(), rest].join('');
3184
+ }
3185
+ function ApplyCapitalize(value) {
3186
+ const [first, rest] = [value.slice(0, 1), value.slice(1)];
3187
+ return [first.toUpperCase(), rest].join('');
3188
+ }
3189
+ function ApplyUppercase(value) {
3190
+ return value.toUpperCase();
3191
+ }
3192
+ function ApplyLowercase(value) {
3193
+ return value.toLowerCase();
3194
+ }
3195
+ function FromTemplateLiteral(schema, mode, options) {
3196
+ // note: template literals require special runtime handling as they are encoded in string patterns.
3197
+ // This diverges from the mapped type which would otherwise map on the template literal kind.
3198
+ const expression = TemplateLiteralParseExact(schema.pattern);
3199
+ const finite = IsTemplateLiteralExpressionFinite(expression);
3200
+ if (!finite)
3201
+ return { ...schema, pattern: FromLiteralValue(schema.pattern, mode) };
3202
+ const strings = [...TemplateLiteralExpressionGenerate(expression)];
3203
+ const literals = strings.map((value) => Literal(value));
3204
+ const mapped = FromRest$2(literals, mode);
3205
+ const union = Union(mapped);
3206
+ return TemplateLiteral([union], options);
3207
+ }
3208
+ // prettier-ignore
3209
+ function FromLiteralValue(value, mode) {
3210
+ return (typeof value === 'string' ? (mode === 'Uncapitalize' ? ApplyUncapitalize(value) :
3211
+ mode === 'Capitalize' ? ApplyCapitalize(value) :
3212
+ mode === 'Uppercase' ? ApplyUppercase(value) :
3213
+ mode === 'Lowercase' ? ApplyLowercase(value) :
3214
+ value) : value.toString());
3215
+ }
3216
+ // prettier-ignore
3217
+ function FromRest$2(T, M) {
3218
+ return T.map(L => Intrinsic(L, M));
3219
+ }
3220
+ /** Applies an intrinsic string manipulation to the given type. */
3221
+ function Intrinsic(schema, mode, options = {}) {
3222
+ // prettier-ignore
3223
+ return (
3224
+ // Intrinsic-Mapped-Inference
3225
+ IsMappedKey$1(schema) ? IntrinsicFromMappedKey(schema, mode, options) :
3226
+ // Standard-Inference
3227
+ IsTemplateLiteral$1(schema) ? FromTemplateLiteral(schema, mode, schema) :
3228
+ IsUnion$1(schema) ? Union(FromRest$2(schema.anyOf, mode), options) :
3229
+ IsLiteral$1(schema) ? Literal(FromLiteralValue(schema.const, mode), options) :
3230
+ schema);
3231
+ }
3232
+
3233
+ /** `[Json]` Intrinsic function to Capitalize LiteralString types */
3234
+ function Capitalize(T, options = {}) {
3235
+ return Intrinsic(T, 'Capitalize', options);
3236
+ }
3237
+
3238
+ /** `[Json]` Intrinsic function to Lowercase LiteralString types */
3239
+ function Lowercase(T, options = {}) {
3240
+ return Intrinsic(T, 'Lowercase', options);
3241
+ }
3242
+
3243
+ /** `[Json]` Intrinsic function to Uncapitalize LiteralString types */
3244
+ function Uncapitalize(T, options = {}) {
3245
+ return Intrinsic(T, 'Uncapitalize', options);
3246
+ }
3247
+
3248
+ /** `[Json]` Intrinsic function to Uppercase LiteralString types */
3249
+ function Uppercase(T, options = {}) {
3250
+ return Intrinsic(T, 'Uppercase', options);
3251
+ }
3252
+
3253
+ /** `[Json]` Creates a Not type */
3254
+ function Not(schema, options) {
3255
+ return {
3256
+ ...options,
3257
+ [Kind]: 'Not',
3258
+ not: CloneType(schema),
3259
+ };
3260
+ }
3261
+
3262
+ // prettier-ignore
3263
+ function FromProperties$7(P, K, options) {
3264
+ const Acc = {};
3265
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P))
3266
+ Acc[K2] = Omit(P[K2], K, options);
3267
+ return Acc;
3268
+ }
3269
+ // prettier-ignore
3270
+ function FromMappedResult$3(R, K, options) {
3271
+ return FromProperties$7(R.properties, K, options);
3272
+ }
3273
+ // prettier-ignore
3274
+ function OmitFromMappedResult(R, K, options) {
3275
+ const P = FromMappedResult$3(R, K, options);
3276
+ return MappedResult(P);
3277
+ }
3278
+
3279
+ // prettier-ignore
3280
+ function FromIntersect$1(T, K) {
3281
+ return T.map((T) => OmitResolve(T, K));
3282
+ }
3283
+ // prettier-ignore
3284
+ function FromUnion$1(T, K) {
3285
+ return T.map((T) => OmitResolve(T, K));
3286
+ }
3287
+ // ------------------------------------------------------------------
3288
+ // FromProperty
3289
+ // ------------------------------------------------------------------
3290
+ // prettier-ignore
3291
+ function FromProperty(T, K) {
3292
+ const { [K]: _, ...R } = T;
3293
+ return R;
3294
+ }
3295
+ // prettier-ignore
3296
+ function FromProperties$6(T, K) {
3297
+ return K.reduce((T, K2) => FromProperty(T, K2), T);
3298
+ }
3299
+ // ------------------------------------------------------------------
3300
+ // OmitResolve
3301
+ // ------------------------------------------------------------------
3302
+ // prettier-ignore
3303
+ function OmitResolve(T, K) {
3304
+ return (IsIntersect$1(T) ? Intersect(FromIntersect$1(T.allOf, K)) :
3305
+ IsUnion$1(T) ? Union(FromUnion$1(T.anyOf, K)) :
3306
+ IsObject$1(T) ? Object$1(FromProperties$6(T.properties, K)) :
3307
+ Object$1({}));
3308
+ }
3309
+ function Omit(T, K, options = {}) {
3310
+ // mapped
3311
+ if (IsMappedKey$1(K))
3312
+ return OmitFromMappedKey(T, K, options);
3313
+ if (IsMappedResult$1(T))
3314
+ return OmitFromMappedResult(T, K, options);
3315
+ // non-mapped
3316
+ const I = IsSchema$1(K) ? IndexPropertyKeys(K) : K;
3317
+ const D = Discard(T, [TransformKind, '$id', 'required']);
3318
+ const R = CloneType(OmitResolve(T, I), options);
3319
+ return { ...D, ...R };
3320
+ }
3321
+
3322
+ // prettier-ignore
3323
+ function FromPropertyKey$1(T, K, options) {
3324
+ return {
3325
+ [K]: Omit(T, [K], options)
3326
+ };
3327
+ }
3328
+ // prettier-ignore
3329
+ function FromPropertyKeys$1(T, K, options) {
3330
+ return K.reduce((Acc, LK) => {
3331
+ return { ...Acc, ...FromPropertyKey$1(T, LK, options) };
3332
+ }, {});
3333
+ }
3334
+ // prettier-ignore
3335
+ function FromMappedKey$1(T, K, options) {
3336
+ return FromPropertyKeys$1(T, K.keys, options);
3337
+ }
3338
+ // prettier-ignore
3339
+ function OmitFromMappedKey(T, K, options) {
3340
+ const P = FromMappedKey$1(T, K, options);
3341
+ return MappedResult(P);
3342
+ }
3343
+
3344
+ /** `[JavaScript]` Extracts the Parameters from the given Function type */
3345
+ function Parameters(schema, options = {}) {
3346
+ return Tuple(CloneRest(schema.parameters), { ...options });
3347
+ }
3348
+
3349
+ // prettier-ignore
3350
+ function FromRest$1(T) {
3351
+ return T.map(L => PartialResolve(L));
3352
+ }
3353
+ // prettier-ignore
3354
+ function FromProperties$5(T) {
3355
+ const Acc = {};
3356
+ for (const K of globalThis.Object.getOwnPropertyNames(T))
3357
+ Acc[K] = Optional(T[K]);
3358
+ return Acc;
3359
+ }
3360
+ // ------------------------------------------------------------------
3361
+ // PartialResolve
3362
+ // ------------------------------------------------------------------
3363
+ // prettier-ignore
3364
+ function PartialResolve(T) {
3365
+ return (IsIntersect$1(T) ? Intersect(FromRest$1(T.allOf)) :
3366
+ IsUnion$1(T) ? Union(FromRest$1(T.anyOf)) :
3367
+ IsObject$1(T) ? Object$1(FromProperties$5(T.properties)) :
3368
+ Object$1({}));
3369
+ }
3370
+ /** `[Json]` Constructs a type where all properties are optional */
3371
+ function Partial(T, options = {}) {
3372
+ if (IsMappedResult$1(T))
3373
+ return PartialFromMappedResult(T, options);
3374
+ const D = Discard(T, [TransformKind, '$id', 'required']);
3375
+ const R = CloneType(PartialResolve(T), options);
3376
+ return { ...D, ...R };
3377
+ }
3378
+
3379
+ // prettier-ignore
3380
+ function FromProperties$4(K, options) {
3381
+ const Acc = {};
3382
+ for (const K2 of globalThis.Object.getOwnPropertyNames(K))
3383
+ Acc[K2] = Partial(K[K2], options);
3384
+ return Acc;
3385
+ }
3386
+ // prettier-ignore
3387
+ function FromMappedResult$2(R, options) {
3388
+ return FromProperties$4(R.properties, options);
3389
+ }
3390
+ // prettier-ignore
3391
+ function PartialFromMappedResult(R, options) {
3392
+ const P = FromMappedResult$2(R, options);
3393
+ return MappedResult(P);
3394
+ }
3395
+
3396
+ // prettier-ignore
3397
+ function FromProperties$3(P, K, options) {
3398
+ const Acc = {};
3399
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P))
3400
+ Acc[K2] = Pick(P[K2], K, options);
3401
+ return Acc;
3402
+ }
3403
+ // prettier-ignore
3404
+ function FromMappedResult$1(R, K, options) {
3405
+ return FromProperties$3(R.properties, K, options);
3406
+ }
3407
+ // prettier-ignore
3408
+ function PickFromMappedResult(R, K, options) {
3409
+ const P = FromMappedResult$1(R, K, options);
3410
+ return MappedResult(P);
3411
+ }
3412
+
3413
+ function FromIntersect(T, K) {
3414
+ return T.map((T) => PickResolve(T, K));
3415
+ }
3416
+ // prettier-ignore
3417
+ function FromUnion(T, K) {
3418
+ return T.map((T) => PickResolve(T, K));
3419
+ }
3420
+ // prettier-ignore
3421
+ function FromProperties$2(T, K) {
3422
+ const Acc = {};
3423
+ for (const K2 of K)
3424
+ if (K2 in T)
3425
+ Acc[K2] = T[K2];
3426
+ return Acc;
3427
+ }
3428
+ // ------------------------------------------------------------------
3429
+ // PickResolve
3430
+ // ------------------------------------------------------------------
3431
+ // prettier-ignore
3432
+ function PickResolve(T, K) {
3433
+ return (IsIntersect$1(T) ? Intersect(FromIntersect(T.allOf, K)) :
3434
+ IsUnion$1(T) ? Union(FromUnion(T.anyOf, K)) :
3435
+ IsObject$1(T) ? Object$1(FromProperties$2(T.properties, K)) :
3436
+ Object$1({}));
3437
+ }
3438
+ function Pick(T, K, options = {}) {
3439
+ // mapped
3440
+ if (IsMappedKey$1(K))
3441
+ return PickFromMappedKey(T, K, options);
3442
+ if (IsMappedResult$1(T))
3443
+ return PickFromMappedResult(T, K, options);
3444
+ // non-mapped
3445
+ const I = IsSchema$1(K) ? IndexPropertyKeys(K) : K;
3446
+ const D = Discard(T, [TransformKind, '$id', 'required']);
3447
+ const R = CloneType(PickResolve(T, I), options);
3448
+ return { ...D, ...R };
3449
+ }
3450
+
3451
+ // prettier-ignore
3452
+ function FromPropertyKey(T, K, options) {
3453
+ return {
3454
+ [K]: Pick(T, [K], options)
3455
+ };
3456
+ }
3457
+ // prettier-ignore
3458
+ function FromPropertyKeys(T, K, options) {
3459
+ return K.reduce((Acc, LK) => {
3460
+ return { ...Acc, ...FromPropertyKey(T, LK, options) };
3461
+ }, {});
3462
+ }
3463
+ // prettier-ignore
3464
+ function FromMappedKey(T, K, options) {
3465
+ return FromPropertyKeys(T, K.keys, options);
3466
+ }
3467
+ // prettier-ignore
3468
+ function PickFromMappedKey(T, K, options) {
3469
+ const P = FromMappedKey(T, K, options);
3470
+ return MappedResult(P);
3471
+ }
3472
+
3473
+ /** `[Json]` Creates a Readonly and Optional property */
3474
+ function ReadonlyOptional(schema) {
3475
+ return Readonly(Optional(schema));
3476
+ }
3477
+
3478
+ // ------------------------------------------------------------------
3479
+ // RecordCreateFromPattern
3480
+ // ------------------------------------------------------------------
3481
+ // prettier-ignore
3482
+ function RecordCreateFromPattern(pattern, T, options) {
3483
+ return {
3484
+ ...options,
3485
+ [Kind]: 'Record',
3486
+ type: 'object',
3487
+ patternProperties: { [pattern]: CloneType(T) }
3488
+ };
3489
+ }
3490
+ // ------------------------------------------------------------------
3491
+ // RecordCreateFromKeys
3492
+ // ------------------------------------------------------------------
3493
+ // prettier-ignore
3494
+ function RecordCreateFromKeys(K, T, options) {
3495
+ const Acc = {};
3496
+ for (const K2 of K)
3497
+ Acc[K2] = CloneType(T);
3498
+ return Object$1(Acc, { ...options, [Hint]: 'Record' });
3499
+ }
3500
+ // prettier-ignore
3501
+ function FromTemplateLiteralKey(K, T, options) {
3502
+ return (IsTemplateLiteralFinite(K)
3503
+ ? RecordCreateFromKeys(IndexPropertyKeys(K), T, options)
3504
+ : RecordCreateFromPattern(K.pattern, T, options));
3505
+ }
3506
+ // prettier-ignore
3507
+ function FromUnionKey(K, T, options) {
3508
+ return RecordCreateFromKeys(IndexPropertyKeys(Union(K)), T, options);
3509
+ }
3510
+ // prettier-ignore
3511
+ function FromLiteralKey(K, T, options) {
3512
+ return RecordCreateFromKeys([K.toString()], T, options);
3513
+ }
3514
+ // prettier-ignore
3515
+ function FromRegExpKey(K, T, options) {
3516
+ return RecordCreateFromPattern(K.source, T, options);
3517
+ }
3518
+ // prettier-ignore
3519
+ function FromStringKey(K, T, options) {
3520
+ const pattern = IsUndefined$2(K.pattern) ? PatternStringExact : K.pattern;
3521
+ return RecordCreateFromPattern(pattern, T, options);
3522
+ }
3523
+ // prettier-ignore
3524
+ function FromAnyKey(K, T, options) {
3525
+ return RecordCreateFromPattern(PatternStringExact, T, options);
3526
+ }
3527
+ // prettier-ignore
3528
+ function FromNeverKey(K, T, options) {
3529
+ return RecordCreateFromPattern(PatternNeverExact, T, options);
3530
+ }
3531
+ // prettier-ignore
3532
+ function FromIntegerKey(_, T, options) {
3533
+ return RecordCreateFromPattern(PatternNumberExact, T, options);
3534
+ }
3535
+ // prettier-ignore
3536
+ function FromNumberKey(_, T, options) {
3537
+ return RecordCreateFromPattern(PatternNumberExact, T, options);
3538
+ }
3539
+ // ------------------------------------------------------------------
3540
+ // TRecordOrObject
3541
+ // ------------------------------------------------------------------
3542
+ /** `[Json]` Creates a Record type */
3543
+ function Record(K, T, options = {}) {
3544
+ // prettier-ignore
3545
+ return (IsUnion$1(K) ? FromUnionKey(K.anyOf, T, options) :
3546
+ IsTemplateLiteral$1(K) ? FromTemplateLiteralKey(K, T, options) :
3547
+ IsLiteral$1(K) ? FromLiteralKey(K.const, T, options) :
3548
+ IsInteger$1(K) ? FromIntegerKey(K, T, options) :
3549
+ IsNumber$1(K) ? FromNumberKey(K, T, options) :
3550
+ IsRegExp$1(K) ? FromRegExpKey(K, T, options) :
3551
+ IsString$1(K) ? FromStringKey(K, T, options) :
3552
+ IsAny$1(K) ? FromAnyKey(K, T, options) :
3553
+ IsNever$1(K) ? FromNeverKey(K, T, options) :
3554
+ Never(options));
3555
+ }
3556
+
3557
+ // Auto Tracked For Recursive Types without ID's
3558
+ let Ordinal = 0;
3559
+ /** `[Json]` Creates a Recursive type */
3560
+ function Recursive(callback, options = {}) {
3561
+ if (IsUndefined$2(options.$id))
3562
+ options.$id = `T${Ordinal++}`;
3563
+ const thisType = callback({ [Kind]: 'This', $ref: `${options.$id}` });
3564
+ thisType.$id = options.$id;
3565
+ // prettier-ignore
3566
+ return CloneType({ ...options, [Hint]: 'Recursive', ...thisType });
3567
+ }
3568
+
3569
+ /** `[Json]` Creates a Ref type. */
3570
+ function Ref(unresolved, options = {}) {
3571
+ if (IsString$2(unresolved))
3572
+ return { ...options, [Kind]: 'Ref', $ref: unresolved };
3573
+ if (IsUndefined$2(unresolved.$id))
3574
+ throw new Error('Reference target type must specify an $id');
3575
+ return {
3576
+ ...options,
3577
+ [Kind]: 'Ref',
3578
+ $ref: unresolved.$id,
3579
+ };
3580
+ }
3581
+
3582
+ /** `[JavaScript]` Creates a RegExp type */
3583
+ function RegExp$1(unresolved, options = {}) {
3584
+ const expr = IsString$2(unresolved) ? new globalThis.RegExp(unresolved) : unresolved;
3585
+ return { ...options, [Kind]: 'RegExp', type: 'RegExp', source: expr.source, flags: expr.flags };
3586
+ }
3587
+
3588
+ // prettier-ignore
3589
+ function FromRest(T) {
3590
+ return T.map(L => RequiredResolve(L));
3591
+ }
3592
+ // prettier-ignore
3593
+ function FromProperties$1(T) {
3594
+ const Acc = {};
3595
+ for (const K of globalThis.Object.getOwnPropertyNames(T))
3596
+ Acc[K] = Discard(T[K], [OptionalKind]);
3597
+ return Acc;
3598
+ }
3599
+ // ------------------------------------------------------------------
3600
+ // RequiredResolve
3601
+ // ------------------------------------------------------------------
3602
+ // prettier-ignore
3603
+ function RequiredResolve(T) {
3604
+ return (IsIntersect$1(T) ? Intersect(FromRest(T.allOf)) :
3605
+ IsUnion$1(T) ? Union(FromRest(T.anyOf)) :
3606
+ IsObject$1(T) ? Object$1(FromProperties$1(T.properties)) :
3607
+ Object$1({}));
3608
+ }
3609
+ /** `[Json]` Constructs a type where all properties are required */
3610
+ function Required(T, options = {}) {
3611
+ if (IsMappedResult$1(T)) {
3612
+ return RequiredFromMappedResult(T, options);
3613
+ }
3614
+ else {
3615
+ const D = Discard(T, [TransformKind, '$id', 'required']);
3616
+ const R = CloneType(RequiredResolve(T), options);
3617
+ return { ...D, ...R };
3618
+ }
3619
+ }
3620
+
3621
+ // prettier-ignore
3622
+ function FromProperties(P, options) {
3623
+ const Acc = {};
3624
+ for (const K2 of globalThis.Object.getOwnPropertyNames(P))
3625
+ Acc[K2] = Required(P[K2], options);
3626
+ return Acc;
3627
+ }
3628
+ // prettier-ignore
3629
+ function FromMappedResult(R, options) {
3630
+ return FromProperties(R.properties, options);
3631
+ }
3632
+ // prettier-ignore
3633
+ function RequiredFromMappedResult(R, options) {
3634
+ const P = FromMappedResult(R, options);
3635
+ return MappedResult(P);
3636
+ }
3637
+
3638
+ // prettier-ignore
3639
+ function RestResolve(T) {
3640
+ return (IsIntersect$1(T) ? CloneRest(T.allOf) :
3641
+ IsUnion$1(T) ? CloneRest(T.anyOf) :
3642
+ IsTuple$1(T) ? CloneRest(T.items ?? []) :
3643
+ []);
3644
+ }
3645
+ /** `[Json]` Extracts interior Rest elements from Tuple, Intersect and Union types */
3646
+ function Rest(T) {
3647
+ return CloneRest(RestResolve(T));
3648
+ }
3649
+
3650
+ /** `[JavaScript]` Extracts the ReturnType from the given Function type */
3651
+ function ReturnType(schema, options = {}) {
3652
+ return CloneType(schema.returns, options);
3653
+ }
3654
+
3655
+ /** `[Json]` Omits compositing symbols from this schema. */
3656
+ function Strict(schema) {
3657
+ return JSON.parse(JSON.stringify(schema));
3658
+ }
3659
+
3660
+ // ------------------------------------------------------------------
3661
+ // TransformBuilders
3662
+ // ------------------------------------------------------------------
3663
+ class TransformDecodeBuilder {
3664
+ constructor(schema) {
3665
+ this.schema = schema;
3666
+ }
3667
+ Decode(decode) {
3668
+ return new TransformEncodeBuilder(this.schema, decode);
3669
+ }
3670
+ }
3671
+ // prettier-ignore
3672
+ class TransformEncodeBuilder {
3673
+ constructor(schema, decode) {
3674
+ this.schema = schema;
3675
+ this.decode = decode;
3676
+ }
3677
+ EncodeTransform(encode, schema) {
3678
+ const Encode = (value) => schema[TransformKind].Encode(encode(value));
3679
+ const Decode = (value) => this.decode(schema[TransformKind].Decode(value));
3680
+ const Codec = { Encode: Encode, Decode: Decode };
3681
+ return { ...schema, [TransformKind]: Codec };
3682
+ }
3683
+ EncodeSchema(encode, schema) {
3684
+ const Codec = { Decode: this.decode, Encode: encode };
3685
+ return { ...schema, [TransformKind]: Codec };
3686
+ }
3687
+ Encode(encode) {
3688
+ const schema = CloneType(this.schema);
3689
+ return (IsTransform$1(schema) ? this.EncodeTransform(encode, schema) : this.EncodeSchema(encode, schema));
3690
+ }
3691
+ }
3692
+ /** `[Json]` Creates a Transform type */
3693
+ function Transform(schema) {
3694
+ return new TransformDecodeBuilder(schema);
3695
+ }
3696
+
3697
+ /** `[Json]` Creates a Unsafe type that will infers as the generic argument T */
3698
+ function Unsafe(options = {}) {
3699
+ return {
3700
+ ...options,
3701
+ [Kind]: options[Kind] ?? 'Unsafe',
3702
+ };
3703
+ }
3704
+
3705
+ /** `[JavaScript]` Creates a Void type */
3706
+ function Void(options = {}) {
3707
+ return {
3708
+ ...options,
3709
+ [Kind]: 'Void',
3710
+ type: 'void',
3711
+ };
3712
+ }
3713
+
3714
+ // ------------------------------------------------------------------
3715
+ // Type: Module
3716
+ // ------------------------------------------------------------------
3717
+
3718
+ var TypeBuilder = /*#__PURE__*/Object.freeze({
3719
+ __proto__: null,
3720
+ Any: Any,
3721
+ Array: Array$1,
3722
+ AsyncIterator: AsyncIterator,
3723
+ Awaited: Awaited,
3724
+ BigInt: BigInt,
3725
+ Boolean: Boolean,
3726
+ Capitalize: Capitalize,
3727
+ Composite: Composite,
3728
+ Const: Const,
3729
+ Constructor: Constructor,
3730
+ ConstructorParameters: ConstructorParameters,
3731
+ Date: Date$1,
3732
+ Deref: Deref,
3733
+ Enum: Enum,
3734
+ Exclude: Exclude,
3735
+ Extends: Extends,
3736
+ Extract: Extract,
3737
+ Function: Function,
3738
+ Index: Index,
3739
+ InstanceType: InstanceType,
3740
+ Integer: Integer,
3741
+ Intersect: Intersect,
3742
+ Iterator: Iterator,
3743
+ KeyOf: KeyOf,
3744
+ Literal: Literal,
3745
+ Lowercase: Lowercase,
3746
+ Mapped: Mapped,
3747
+ Never: Never,
3748
+ Not: Not,
3749
+ Null: Null,
3750
+ Number: Number,
3751
+ Object: Object$1,
3752
+ Omit: Omit,
3753
+ Optional: Optional,
3754
+ Parameters: Parameters,
3755
+ Partial: Partial,
3756
+ Pick: Pick,
3757
+ Promise: Promise$1,
3758
+ Readonly: Readonly,
3759
+ ReadonlyOptional: ReadonlyOptional,
3760
+ Record: Record,
3761
+ Recursive: Recursive,
3762
+ Ref: Ref,
3763
+ RegExp: RegExp$1,
3764
+ Required: Required,
3765
+ Rest: Rest,
3766
+ ReturnType: ReturnType,
3767
+ Strict: Strict,
3768
+ String: String$1,
3769
+ Symbol: Symbol$1,
3770
+ TemplateLiteral: TemplateLiteral,
3771
+ Transform: Transform,
3772
+ Tuple: Tuple,
3773
+ Uint8Array: Uint8Array$1,
3774
+ Uncapitalize: Uncapitalize,
3775
+ Undefined: Undefined,
3776
+ Union: Union,
3777
+ Unknown: Unknown,
3778
+ Unsafe: Unsafe,
3779
+ Uppercase: Uppercase,
3780
+ Void: Void
3781
+ });
3782
+
3783
+ // ------------------------------------------------------------------
3784
+ // JsonTypeBuilder
3785
+ // ------------------------------------------------------------------
3786
+ /** JavaScript Type Builder with Static Resolution for TypeScript */
3787
+ const Type = TypeBuilder;
3788
+
3789
+ /**
3790
+ * commanderclaw_nodes tool
3791
+ */
3792
+ function createNodesTool(getClient) {
3793
+ return {
3794
+ name: "commanderclaw_nodes",
3795
+ description: "List all nodes connected to the CommanderClaw cluster. Use this to see available nodes, their status, roles, and capabilities.",
3796
+ parameters: Type.Object({}),
3797
+ async execute() {
3798
+ const client = getClient();
3799
+ if (!client?.isConnected()) {
3800
+ return {
3801
+ content: [
3802
+ {
3803
+ type: "text",
3804
+ text: "Not connected to CommanderClaw server. Check plugin configuration.",
3805
+ },
3806
+ ],
3807
+ };
3808
+ }
3809
+ try {
3810
+ const nodes = await client.listNodes();
3811
+ const currentNode = client.getNodeId();
3812
+ const commanderId = client.getCommanderId();
3813
+ let text = `## CommanderClaw Cluster Nodes\n\n`;
3814
+ text += `**Total nodes:** ${nodes.length}\n`;
3815
+ text += `**Commander:** ${commanderId || "None elected"}\n`;
3816
+ text += `**Current node:** ${currentNode || "Unknown"}\n\n`;
3817
+ if (nodes.length === 0) {
3818
+ text += "No nodes connected to the cluster.\n";
3819
+ }
3820
+ else {
3821
+ for (const node of nodes) {
3822
+ const isCommander = node.id === commanderId;
3823
+ const isCurrent = node.id === currentNode;
3824
+ const marker = isCurrent ? " (you)" : "";
3825
+ const roleMarker = isCommander ? " 👑 Commander" : "";
3826
+ text += `### ${node.name || node.id}${marker}${roleMarker}\n`;
3827
+ text += `- **Status:** ${node.status}\n`;
3828
+ text += `- **Role:** ${node.role}\n`;
3829
+ text += `- **Load:** ${node.load}\n`;
3830
+ if (node.capabilities?.length) {
3831
+ text += `- **Capabilities:** ${node.capabilities.join(", ")}\n`;
3832
+ }
3833
+ text += "\n";
3834
+ }
3835
+ }
3836
+ return { content: [{ type: "text", text }] };
3837
+ }
3838
+ catch (error) {
3839
+ return {
3840
+ content: [
3841
+ {
3842
+ type: "text",
3843
+ text: `Failed to list nodes: ${error instanceof Error ? error.message : String(error)}`,
3844
+ },
3845
+ ],
3846
+ };
3847
+ }
3848
+ },
3849
+ };
3850
+ }
3851
+
3852
+ /**
3853
+ * commanderclaw_task tool
3854
+ */
3855
+ function createTaskTool(getClient) {
3856
+ return {
3857
+ name: "commanderclaw_task",
3858
+ description: `Create, query, or manage tasks on the CommanderClaw cluster.
3859
+
3860
+ Actions:
3861
+ - create: Create a new task with a name and optional description, priority, input, and target node
3862
+ - list: List all tasks in the cluster
3863
+ - get: Get details of a specific task by ID
3864
+ - abort: Abort a running task
3865
+ - pause: Pause a running task
3866
+ - resume: Resume a paused task
3867
+
3868
+ Use this to coordinate work across multiple AI agents in the cluster.`,
3869
+ parameters: Type.Object({
3870
+ action: Type.Union([
3871
+ Type.Literal("create"),
3872
+ Type.Literal("list"),
3873
+ Type.Literal("get"),
3874
+ Type.Literal("abort"),
3875
+ Type.Literal("pause"),
3876
+ Type.Literal("resume"),
3877
+ ]),
3878
+ // Create parameters
3879
+ name: Type.Optional(Type.String()),
3880
+ description: Type.Optional(Type.String()),
3881
+ priority: Type.Optional(Type.Union([
3882
+ Type.Literal("low"),
3883
+ Type.Literal("normal"),
3884
+ Type.Literal("high"),
3885
+ Type.Literal("critical"),
3886
+ ])),
3887
+ input: Type.Optional(Type.Any()),
3888
+ targetNodeId: Type.Optional(Type.String()),
3889
+ maxRounds: Type.Optional(Type.Number()),
3890
+ // Get/Abort/Pause/Resume parameters
3891
+ taskId: Type.Optional(Type.String()),
3892
+ reason: Type.Optional(Type.String()),
3893
+ }),
3894
+ async execute(_id, params) {
3895
+ const client = getClient();
3896
+ if (!client?.isConnected()) {
3897
+ return {
3898
+ content: [
3899
+ {
3900
+ type: "text",
3901
+ text: "Not connected to CommanderClaw server. Check plugin configuration.",
3902
+ },
3903
+ ],
3904
+ };
3905
+ }
3906
+ try {
3907
+ switch (params.action) {
3908
+ case "create": {
3909
+ if (!params.name || typeof params.name !== "string") {
3910
+ return {
3911
+ content: [
3912
+ { type: "text", text: "Error: 'name' is required for create action" },
3913
+ ],
3914
+ };
3915
+ }
3916
+ const task = await client.createTask({
3917
+ name: params.name,
3918
+ description: params.description,
3919
+ priority: params.priority,
3920
+ input: params.input,
3921
+ targetNodeId: params.targetNodeId,
3922
+ maxRounds: params.maxRounds,
3923
+ });
3924
+ return {
3925
+ content: [
3926
+ {
3927
+ type: "text",
3928
+ text: `Task created successfully:\n\`\`\`json\n${JSON.stringify(task, null, 2)}\n\`\`\``,
3929
+ },
3930
+ ],
3931
+ };
3932
+ }
3933
+ case "list": {
3934
+ const tasks = await client.listTasks();
3935
+ if (tasks.length === 0) {
3936
+ return {
3937
+ content: [{ type: "text", text: "No tasks in the cluster." }],
3938
+ };
3939
+ }
3940
+ let text = `## Tasks (${tasks.length})\n\n`;
3941
+ for (const task of tasks) {
3942
+ text += formatTaskSummary(task);
3943
+ }
3944
+ return { content: [{ type: "text", text }] };
3945
+ }
3946
+ case "get": {
3947
+ if (!params.taskId || typeof params.taskId !== "string") {
3948
+ return {
3949
+ content: [
3950
+ { type: "text", text: "Error: 'taskId' is required for get action" },
3951
+ ],
3952
+ };
3953
+ }
3954
+ const task = await client.getTask(params.taskId);
3955
+ return {
3956
+ content: [
3957
+ {
3958
+ type: "text",
3959
+ text: formatTaskDetail(task),
3960
+ },
3961
+ ],
3962
+ };
3963
+ }
3964
+ case "abort": {
3965
+ if (!params.taskId || typeof params.taskId !== "string") {
3966
+ return {
3967
+ content: [
3968
+ { type: "text", text: "Error: 'taskId' is required for abort action" },
3969
+ ],
3970
+ };
3971
+ }
3972
+ await client.abortTask(params.taskId, params.reason);
3973
+ return {
3974
+ content: [
3975
+ { type: "text", text: `Task ${params.taskId} has been aborted.` },
3976
+ ],
3977
+ };
3978
+ }
3979
+ case "pause": {
3980
+ if (!params.taskId || typeof params.taskId !== "string") {
3981
+ return {
3982
+ content: [
3983
+ { type: "text", text: "Error: 'taskId' is required for pause action" },
3984
+ ],
3985
+ };
3986
+ }
3987
+ await client.pauseTask(params.taskId);
3988
+ return {
3989
+ content: [
3990
+ { type: "text", text: `Task ${params.taskId} has been paused.` },
3991
+ ],
3992
+ };
3993
+ }
3994
+ case "resume": {
3995
+ if (!params.taskId || typeof params.taskId !== "string") {
3996
+ return {
3997
+ content: [
3998
+ { type: "text", text: "Error: 'taskId' is required for resume action" },
3999
+ ],
4000
+ };
4001
+ }
4002
+ await client.resumeTask(params.taskId);
4003
+ return {
4004
+ content: [
4005
+ { type: "text", text: `Task ${params.taskId} has been resumed.` },
4006
+ ],
4007
+ };
4008
+ }
4009
+ default:
4010
+ return {
4011
+ content: [
4012
+ { type: "text", text: `Unknown action: ${params.action}` },
4013
+ ],
4014
+ };
4015
+ }
4016
+ }
4017
+ catch (error) {
4018
+ return {
4019
+ content: [
4020
+ {
4021
+ type: "text",
4022
+ text: `Failed to execute task action: ${error instanceof Error ? error.message : String(error)}`,
4023
+ },
4024
+ ],
4025
+ };
4026
+ }
4027
+ },
4028
+ };
4029
+ }
4030
+ function formatTaskSummary(task) {
4031
+ const statusEmoji = {
4032
+ pending: "⏳",
4033
+ assigned: "📋",
4034
+ running: "▶️",
4035
+ paused: "⏸️",
4036
+ completed: "✅",
4037
+ failed: "❌",
4038
+ aborted: "🚫",
4039
+ }[task.status] || "❓";
4040
+ let text = `### ${task.name} (${task.id})\n`;
4041
+ text += `- **Status:** ${statusEmoji} ${task.status}\n`;
4042
+ text += `- **Priority:** ${task.priority}\n`;
4043
+ text += `- **Progress:** ${task.progress}%\n`;
4044
+ if (task.assignees?.length) {
4045
+ text += `- **Assignees:** ${task.assignees.join(", ")}\n`;
4046
+ }
4047
+ text += "\n";
4048
+ return text;
4049
+ }
4050
+ function formatTaskDetail(task) {
4051
+ let text = `## Task: ${task.name}\n\n`;
4052
+ text += `**ID:** ${task.id}\n`;
4053
+ text += `**Status:** ${task.status}\n`;
4054
+ text += `**Priority:** ${task.priority}\n`;
4055
+ text += `**Progress:** ${task.progress}%\n`;
4056
+ text += `**Rounds:** ${task.rounds}/${task.maxRounds}\n\n`;
4057
+ if (task.description) {
4058
+ text += `**Description:**\n${task.description}\n\n`;
4059
+ }
4060
+ if (task.creatorId) {
4061
+ text += `**Creator:** ${task.creatorId}\n`;
4062
+ }
4063
+ if (task.commanderId) {
4064
+ text += `**Commander:** ${task.commanderId}\n`;
4065
+ }
4066
+ if (task.assignees?.length) {
4067
+ text += `**Assignees:** ${task.assignees.join(", ")}\n`;
4068
+ }
4069
+ text += `\n**Created:** ${task.createdAt}\n`;
4070
+ text += `**Updated:** ${task.updatedAt}\n`;
4071
+ if (task.input) {
4072
+ text += `\n**Input:**\n\`\`\`json\n${JSON.stringify(task.input, null, 2)}\n\`\`\`\n`;
4073
+ }
4074
+ if (task.output) {
4075
+ text += `\n**Output:**\n\`\`\`json\n${JSON.stringify(task.output, null, 2)}\n\`\`\`\n`;
4076
+ }
4077
+ if (task.error) {
4078
+ text += `\n**Error:** ${task.error}\n`;
4079
+ }
4080
+ return text;
4081
+ }
4082
+
4083
+ /**
4084
+ * commanderclaw_status tool
4085
+ */
4086
+ function createStatusTool(getClient) {
4087
+ return {
4088
+ name: "commanderclaw_status",
4089
+ description: "Get the current status of the CommanderClaw cluster connection and cluster health. Use this to verify connectivity and check overall cluster status.",
4090
+ parameters: Type.Object({}),
4091
+ async execute() {
4092
+ const client = getClient();
4093
+ if (!client) {
4094
+ return {
4095
+ content: [
4096
+ {
4097
+ type: "text",
4098
+ text: "CommanderClaw plugin not initialized. Check plugin configuration.",
4099
+ },
4100
+ ],
4101
+ };
4102
+ }
4103
+ const connected = client.isConnected();
4104
+ const nodeId = client.getNodeId();
4105
+ const commanderId = client.getCommanderId();
4106
+ const peers = client.getPeers();
4107
+ let text = `## CommanderClaw Status\n\n`;
4108
+ text += `**Connection:** ${connected ? "✅ Connected" : "❌ Disconnected"}\n`;
4109
+ text += `**Node ID:** ${nodeId || "Not registered"}\n`;
4110
+ text += `**Commander:** ${commanderId || "None elected"}\n`;
4111
+ text += `**Peers:** ${peers.length}\n\n`;
4112
+ if (connected) {
4113
+ try {
4114
+ const health = await client.getStatus();
4115
+ text += `### Cluster Health\n`;
4116
+ text += `- **Status:** ${health.status}\n`;
4117
+ text += `- **Total nodes:** ${health.nodes}\n`;
4118
+ }
4119
+ catch (error) {
4120
+ text += `**Health check failed:** ${error instanceof Error ? error.message : String(error)}\n`;
4121
+ }
4122
+ }
4123
+ else {
4124
+ text += `### Troubleshooting\n`;
4125
+ text += `- Check if the CommanderClaw server is running\n`;
4126
+ text += `- Verify the server URL in plugin configuration\n`;
4127
+ text += `- Check if the authentication token is correct\n`;
4128
+ }
4129
+ return { content: [{ type: "text", text }] };
4130
+ },
4131
+ };
4132
+ }
4133
+
4134
+ /**
4135
+ * commanderclaw_command tool
4136
+ */
4137
+ function createCommandTool(getClient) {
4138
+ return {
4139
+ name: "commanderclaw_command",
4140
+ description: `Send King commands to the CommanderClaw cluster.
4141
+
4142
+ Commands:
4143
+ - appoint: Appoint a specific node as the Commander
4144
+ - abort: Abort a task (alias for commanderclaw_task with action=abort)
4145
+ - pause: Pause a running task
4146
+ - resume: Resume a paused task
4147
+
4148
+ Note: Some commands may require King-level permissions.`,
4149
+ parameters: Type.Object({
4150
+ command: Type.Union([
4151
+ Type.Literal("appoint"),
4152
+ Type.Literal("abort"),
4153
+ Type.Literal("pause"),
4154
+ Type.Literal("resume"),
4155
+ ]),
4156
+ nodeId: Type.Optional(Type.String()),
4157
+ taskId: Type.Optional(Type.String()),
4158
+ reason: Type.Optional(Type.String()),
4159
+ }),
4160
+ async execute(_id, params) {
4161
+ const client = getClient();
4162
+ if (!client?.isConnected()) {
4163
+ return {
4164
+ content: [
4165
+ {
4166
+ type: "text",
4167
+ text: "Not connected to CommanderClaw server. Check plugin configuration.",
4168
+ },
4169
+ ],
4170
+ };
4171
+ }
4172
+ try {
4173
+ switch (params.command) {
4174
+ case "appoint": {
4175
+ if (!params.nodeId || typeof params.nodeId !== "string") {
4176
+ return {
4177
+ content: [
4178
+ {
4179
+ type: "text",
4180
+ text: "Error: 'nodeId' is required for appoint command. Use commanderclaw_nodes to list available nodes.",
4181
+ },
4182
+ ],
4183
+ };
4184
+ }
4185
+ const result = await client.appointCommander(params.nodeId);
4186
+ return {
4187
+ content: [
4188
+ {
4189
+ type: "text",
4190
+ text: `Commander appointed successfully.\n- **New Commander:** ${result.commanderId}`,
4191
+ },
4192
+ ],
4193
+ };
4194
+ }
4195
+ case "abort": {
4196
+ if (!params.taskId || typeof params.taskId !== "string") {
4197
+ return {
4198
+ content: [
4199
+ { type: "text", text: "Error: 'taskId' is required for abort command" },
4200
+ ],
4201
+ };
4202
+ }
4203
+ await client.abortTask(params.taskId, params.reason);
4204
+ return {
4205
+ content: [
4206
+ { type: "text", text: `Task ${params.taskId} has been aborted.` },
4207
+ ],
4208
+ };
4209
+ }
4210
+ case "pause": {
4211
+ if (!params.taskId || typeof params.taskId !== "string") {
4212
+ return {
4213
+ content: [
4214
+ { type: "text", text: "Error: 'taskId' is required for pause command" },
4215
+ ],
4216
+ };
4217
+ }
4218
+ await client.pauseTask(params.taskId);
4219
+ return {
4220
+ content: [
4221
+ { type: "text", text: `Task ${params.taskId} has been paused.` },
4222
+ ],
4223
+ };
4224
+ }
4225
+ case "resume": {
4226
+ if (!params.taskId || typeof params.taskId !== "string") {
4227
+ return {
4228
+ content: [
4229
+ { type: "text", text: "Error: 'taskId' is required for resume command" },
4230
+ ],
4231
+ };
4232
+ }
4233
+ await client.resumeTask(params.taskId);
4234
+ return {
4235
+ content: [
4236
+ { type: "text", text: `Task ${params.taskId} has been resumed.` },
4237
+ ],
4238
+ };
4239
+ }
4240
+ default:
4241
+ return {
4242
+ content: [
4243
+ { type: "text", text: `Unknown command: ${params.command}` },
4244
+ ],
4245
+ };
4246
+ }
4247
+ }
4248
+ catch (error) {
4249
+ return {
4250
+ content: [
4251
+ {
4252
+ type: "text",
4253
+ text: `Failed to execute command: ${error instanceof Error ? error.message : String(error)}`,
4254
+ },
4255
+ ],
4256
+ };
4257
+ }
4258
+ },
4259
+ };
4260
+ }
4261
+
4262
+ /**
4263
+ * CommanderClaw Channel Plugin for OpenClaw
4264
+ *
4265
+ * This plugin connects OpenClaw to a CommanderClaw coordination server,
4266
+ * enabling multi-agent task coordination with message bridging.
4267
+ */
4268
+ const CHANNEL_ID = "commanderclaw";
4269
+ const { setRuntime, getRuntime } = createPluginRuntimeStore("CommanderClaw runtime not initialized");
4270
+ let client = null;
4271
+ let pluginConfig = null;
4272
+ let currentLog = null;
4273
+ const DEFAULT_CONFIG = {
4274
+ deviceName: "OpenClaw Agent",
4275
+ autoConnect: true,
4276
+ reconnect: {
4277
+ enabled: true,
4278
+ maxAttempts: 10,
4279
+ delayMs: 5000,
4280
+ },
4281
+ };
4282
+ async function handleChatMessage(msg) {
4283
+ const log = currentLog;
4284
+ if (!log)
4285
+ return;
4286
+ log.info("handleChatMessage: starting", {
4287
+ from: msg.from,
4288
+ to: msg.to,
4289
+ msgType: msg.msgType,
4290
+ });
4291
+ const rt = getRuntime();
4292
+ if (!rt || !rt.channel) {
4293
+ log.error("handleChatMessage: runtime or channel not initialized");
4294
+ return;
4295
+ }
4296
+ if (!client) {
4297
+ log.error("handleChatMessage: client not initialized");
4298
+ return;
4299
+ }
4300
+ if (!pluginConfig) {
4301
+ log.error("handleChatMessage: pluginConfig not initialized");
4302
+ return;
4303
+ }
4304
+ const content = msg.payload?.content;
4305
+ if (!content) {
4306
+ log.warn("handleChatMessage: no content");
4307
+ return;
4308
+ }
4309
+ log.info("handleChatMessage: processing", {
4310
+ from: msg.from,
4311
+ contentLength: content.length,
4312
+ });
4313
+ try {
4314
+ const nodeId = client.getNodeId() || "unknown";
4315
+ const route = rt.channel.routing.resolveAgentRoute({
4316
+ cfg: pluginConfig,
4317
+ channel: CHANNEL_ID,
4318
+ accountId: "default",
4319
+ peer: {
4320
+ kind: "direct",
4321
+ id: msg.from,
4322
+ },
4323
+ });
4324
+ const ctxPayload = rt.channel.reply.finalizeInboundContext({
4325
+ Body: content,
4326
+ RawBody: content,
4327
+ CommandBody: content,
4328
+ MessageSid: `cc-${Date.now()}`,
4329
+ From: `${CHANNEL_ID}:${msg.from}`,
4330
+ To: `${CHANNEL_ID}:${nodeId}`,
4331
+ SenderId: msg.from,
4332
+ SessionKey: route.sessionKey,
4333
+ AccountId: "default",
4334
+ ChatType: "direct",
4335
+ ConversationLabel: `user:${msg.from}`,
4336
+ Timestamp: Date.now(),
4337
+ Provider: CHANNEL_ID,
4338
+ Surface: CHANNEL_ID,
4339
+ OriginatingChannel: CHANNEL_ID,
4340
+ OriginatingTo: `${CHANNEL_ID}:${nodeId}`,
4341
+ CommandAuthorized: true,
4342
+ });
4343
+ const currentCfg = await rt.config.loadConfig();
4344
+ let accumulatedText = "";
4345
+ await rt.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
4346
+ ctx: ctxPayload,
4347
+ cfg: currentCfg,
4348
+ dispatcherOptions: {
4349
+ deliver: async (payload, info) => {
4350
+ accumulatedText = payload.text;
4351
+ if (info.kind === "final") {
4352
+ log.info("handleChatMessage: sending response", {
4353
+ textLength: accumulatedText.length,
4354
+ });
4355
+ client?.send("CHAT", {
4356
+ content: accumulatedText,
4357
+ });
4358
+ }
4359
+ },
4360
+ onError: (err, info) => {
4361
+ log.error("handleChatMessage: LLM error", {
4362
+ kind: info.kind,
4363
+ error: err.message,
4364
+ });
4365
+ },
4366
+ },
4367
+ });
4368
+ log.info("handleChatMessage: completed");
4369
+ }
4370
+ catch (err) {
4371
+ log.error("handleChatMessage: failed", {
4372
+ error: err instanceof Error ? err.message : String(err),
4373
+ stack: err instanceof Error ? err.stack : undefined,
4374
+ });
4375
+ }
4376
+ }
4377
+ function initializeClient(config, log) {
4378
+ if (!config.autoConnect) {
4379
+ log.info("CommanderClaw auto-connect disabled");
4380
+ return;
4381
+ }
4382
+ client = new CommanderClawClient({
4383
+ url: config.serverUrl,
4384
+ token: config.token,
4385
+ name: config.deviceName || "OpenClaw Agent",
4386
+ capabilities: ["ai-agent", "task-execution"],
4387
+ reconnect: config.reconnect,
4388
+ });
4389
+ client.on("connected", (event) => {
4390
+ log.info("Connected to CommanderClaw server", {
4391
+ nodeId: event.data?.nodeId,
4392
+ });
4393
+ });
4394
+ client.on("disconnected", () => {
4395
+ log.warn("Disconnected from CommanderClaw server");
4396
+ });
4397
+ client.on("error", (event) => {
4398
+ log.error("CommanderClaw connection error", {
4399
+ error: String(event.data),
4400
+ });
4401
+ });
4402
+ client.on("chat", (event) => {
4403
+ handleChatMessage(event.data);
4404
+ });
4405
+ client.connect().catch((error) => {
4406
+ log.error("Failed to connect to CommanderClaw server", {
4407
+ error: error.message,
4408
+ });
4409
+ });
4410
+ log.info("CommanderClaw client initialized", {
4411
+ url: config.serverUrl,
4412
+ name: config.deviceName,
4413
+ });
4414
+ }
4415
+ const commanderclawPlugin = {
4416
+ id: CHANNEL_ID,
4417
+ meta: {
4418
+ id: CHANNEL_ID,
4419
+ label: "CommanderClaw",
4420
+ selectionLabel: "CommanderClaw",
4421
+ detailLabel: "CommanderClaw Multi-Agent Coordination",
4422
+ docsPath: "/channels/commanderclaw",
4423
+ blurb: "Connect to CommanderClaw coordination server",
4424
+ order: 100,
4425
+ },
4426
+ capabilities: {
4427
+ chatTypes: ["direct"],
4428
+ media: false,
4429
+ threads: false,
4430
+ reactions: false,
4431
+ edit: false,
4432
+ unsend: false,
4433
+ reply: false,
4434
+ effects: false,
4435
+ blockStreaming: false,
4436
+ },
4437
+ reload: { configPrefixes: [`channels.${CHANNEL_ID}`] },
4438
+ config: {
4439
+ listAccountIds: (_cfg) => ["default"],
4440
+ resolveAccount: (cfg) => ({
4441
+ accountId: "default",
4442
+ enabled: cfg?.channels?.[CHANNEL_ID]?.enabled ?? true,
4443
+ serverUrl: cfg?.channels?.[CHANNEL_ID]?.serverUrl,
4444
+ token: cfg?.channels?.[CHANNEL_ID]?.token,
4445
+ deviceName: cfg?.channels?.[CHANNEL_ID]?.deviceName,
4446
+ autoConnect: cfg?.channels?.[CHANNEL_ID]?.autoConnect,
4447
+ reconnect: cfg?.channels?.[CHANNEL_ID]?.reconnect,
4448
+ }),
4449
+ defaultAccountId: () => "default",
4450
+ setAccountEnabled: ({ cfg, enabled }) => ({
4451
+ ...cfg,
4452
+ channels: {
4453
+ ...cfg?.channels,
4454
+ [CHANNEL_ID]: {
4455
+ ...cfg?.channels?.[CHANNEL_ID],
4456
+ enabled,
4457
+ },
4458
+ },
4459
+ }),
4460
+ },
4461
+ security: {
4462
+ resolveDmPolicy: () => ({
4463
+ policy: "open",
4464
+ allowFrom: [],
4465
+ policyPath: `channels.${CHANNEL_ID}.dmPolicy`,
4466
+ allowFromPath: `channels.${CHANNEL_ID}.`,
4467
+ }),
4468
+ collectWarnings: () => [],
4469
+ },
4470
+ messaging: {
4471
+ normalizeTarget: (target) => target?.trim() || undefined,
4472
+ targetResolver: {
4473
+ looksLikeId: (id) => id?.length > 10,
4474
+ hint: "<nodeId>",
4475
+ },
4476
+ },
4477
+ directory: {
4478
+ self: async () => null,
4479
+ listPeers: async () => [],
4480
+ listGroups: async () => [],
4481
+ },
4482
+ outbound: {
4483
+ deliveryMode: "gateway",
4484
+ textChunkLimit: 4000,
4485
+ sendText: async ({ to, text }) => {
4486
+ if (!client) {
4487
+ throw new Error("CommanderClaw client not initialized");
4488
+ }
4489
+ client.send("CHAT", { content: text, to });
4490
+ return { channel: CHANNEL_ID, messageId: `cc-${Date.now()}`, chatId: to };
4491
+ },
4492
+ },
4493
+ gateway: {
4494
+ startAccount: async (ctx) => {
4495
+ const { cfg, log } = ctx;
4496
+ currentLog = log;
4497
+ pluginConfig = cfg;
4498
+ const channelCfg = cfg?.channels?.[CHANNEL_ID] || {};
4499
+ const config = {
4500
+ ...DEFAULT_CONFIG,
4501
+ ...channelCfg,
4502
+ };
4503
+ if (!config.serverUrl) {
4504
+ log?.warn?.("CommanderClaw: serverUrl not configured");
4505
+ return;
4506
+ }
4507
+ log?.info?.(`Starting CommanderClaw channel (server: ${config.serverUrl})`);
4508
+ initializeClient(config, log);
4509
+ return new Promise(() => { });
4510
+ },
4511
+ stopAccount: async (ctx) => {
4512
+ ctx.log?.info?.("CommanderClaw account stopped");
4513
+ if (client) {
4514
+ client.disconnect();
4515
+ client = null;
4516
+ }
4517
+ },
4518
+ },
4519
+ };
4520
+ const plugin = {
4521
+ id: "commanderclaw",
4522
+ name: "CommanderClaw",
4523
+ description: "Connect to CommanderClaw coordination server",
4524
+ configSchema: emptyPluginConfigSchema(),
4525
+ register(api) {
4526
+ setRuntime(api.runtime);
4527
+ api.registerChannel({ plugin: commanderclawPlugin });
4528
+ api.registerTool(createNodesTool(() => client));
4529
+ api.registerTool(createTaskTool(() => client));
4530
+ api.registerTool(createStatusTool(() => client));
4531
+ api.registerTool(createCommandTool(() => client));
4532
+ },
4533
+ };
4534
+
4535
+ export { plugin as default };
4536
+ //# sourceMappingURL=index.mjs.map