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