@xlr-lib/xlr-sdk 0.1.1--canary.9.190

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,874 @@
1
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/sdk.ts
2
+ import {
3
+ computeEffectiveObject as computeEffectiveObject2,
4
+ resolveConditional as resolveConditional2,
5
+ resolveReferenceNode as resolveReferenceNode2
6
+ } from "@xlr-lib/xlr-utils";
7
+ import { fillInGenerics } from "@xlr-lib/xlr-utils";
8
+ import fs from "fs";
9
+ import path from "path";
10
+
11
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/registry/basic-registry.ts
12
+ var BasicXLRRegistry = class {
13
+ typeMap;
14
+ pluginMap;
15
+ infoMap;
16
+ constructor() {
17
+ this.typeMap = /* @__PURE__ */ new Map();
18
+ this.pluginMap = /* @__PURE__ */ new Map();
19
+ this.infoMap = /* @__PURE__ */ new Map();
20
+ }
21
+ /** Returns a copy of the XLR to guard against unexpected type modification */
22
+ get(id) {
23
+ const value = this.typeMap.get(id);
24
+ return value ? JSON.parse(JSON.stringify(value)) : void 0;
25
+ }
26
+ add(type, plugin, capability) {
27
+ this.typeMap.set(type.name, type);
28
+ this.infoMap.set(type.name, { plugin, capability });
29
+ if (!this.pluginMap.has(plugin)) {
30
+ this.pluginMap.set(plugin, /* @__PURE__ */ new Map());
31
+ }
32
+ const pluginsCapabilities = this.pluginMap.get(plugin);
33
+ if (!pluginsCapabilities.has(capability)) {
34
+ pluginsCapabilities.set(capability, []);
35
+ }
36
+ const providedCapabilities = pluginsCapabilities.get(
37
+ capability
38
+ );
39
+ providedCapabilities.push(type.name);
40
+ }
41
+ has(id) {
42
+ return this.typeMap.has(id);
43
+ }
44
+ list(filterArgs) {
45
+ const validTypes = [];
46
+ this.pluginMap.forEach((manifest, pluginName) => {
47
+ if (!filterArgs?.pluginFilter || !pluginName.match(filterArgs.pluginFilter)) {
48
+ manifest.forEach((types, capabilityName) => {
49
+ if (!filterArgs?.capabilityFilter || !capabilityName.match(filterArgs.capabilityFilter)) {
50
+ types.forEach((type) => {
51
+ if (!filterArgs?.typeFilter || !type.match(filterArgs.typeFilter)) {
52
+ validTypes.push(type);
53
+ }
54
+ });
55
+ }
56
+ });
57
+ }
58
+ });
59
+ return validTypes.map((type) => this.get(type));
60
+ }
61
+ info(id) {
62
+ return this.infoMap.get(id);
63
+ }
64
+ };
65
+
66
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/validator.ts
67
+ import {
68
+ makePropertyMap,
69
+ resolveConditional,
70
+ isPrimitiveTypeNode,
71
+ resolveReferenceNode,
72
+ computeEffectiveObject
73
+ } from "@xlr-lib/xlr-utils";
74
+
75
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/types.ts
76
+ var ValidationSeverity = /* @__PURE__ */ ((ValidationSeverity2) => {
77
+ ValidationSeverity2[ValidationSeverity2["Error"] = 1] = "Error";
78
+ ValidationSeverity2[ValidationSeverity2["Warning"] = 2] = "Warning";
79
+ ValidationSeverity2[ValidationSeverity2["Info"] = 3] = "Info";
80
+ ValidationSeverity2[ValidationSeverity2["Trace"] = 4] = "Trace";
81
+ return ValidationSeverity2;
82
+ })(ValidationSeverity || {});
83
+
84
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/validator.ts
85
+ var MAX_VALID_SHOWN = 20;
86
+ var XLRValidator = class {
87
+ config;
88
+ resolveType;
89
+ regexCache;
90
+ constructor(resolveType, config) {
91
+ this.config = config || {};
92
+ this.resolveType = resolveType;
93
+ this.regexCache = /* @__PURE__ */ new Map();
94
+ }
95
+ /** Main entrypoint for validation */
96
+ validateType(rootNode, xlrNode) {
97
+ const validationIssues = new Array();
98
+ if (xlrNode.type === "object") {
99
+ if (rootNode.type === "object") {
100
+ validationIssues.push(...this.validateObject(xlrNode, rootNode));
101
+ } else {
102
+ validationIssues.push({
103
+ type: "type",
104
+ node: rootNode,
105
+ message: `Expected an object but got an "${rootNode.type}"`,
106
+ severity: 1 /* Error */
107
+ });
108
+ }
109
+ } else if (xlrNode.type === "array") {
110
+ if (rootNode.type === "array") {
111
+ validationIssues.push(...this.validateArray(rootNode, xlrNode));
112
+ } else {
113
+ validationIssues.push({
114
+ type: "type",
115
+ node: rootNode,
116
+ message: `Expected an array but got an "${rootNode.type}"`,
117
+ severity: 1 /* Error */
118
+ });
119
+ }
120
+ } else if (xlrNode.type === "template") {
121
+ const error = this.validateTemplate(rootNode, xlrNode);
122
+ if (error) {
123
+ validationIssues.push(error);
124
+ }
125
+ } else if (xlrNode.type === "or") {
126
+ const potentialTypeErrors = [];
127
+ for (const potentialType of xlrNode.or) {
128
+ const potentialErrors = this.validateType(rootNode, potentialType);
129
+ if (potentialErrors.length === 0) {
130
+ return validationIssues;
131
+ }
132
+ potentialTypeErrors.push({
133
+ type: potentialType,
134
+ errors: potentialErrors
135
+ });
136
+ }
137
+ let message;
138
+ const expectedTypes = xlrNode.or.map(
139
+ (node) => isPrimitiveTypeNode(node) ? node.type : node.name ?? node.title ?? node.type ?? "<unnamed type>"
140
+ ).join(" | ");
141
+ if (xlrNode.name) {
142
+ message = `Does not match any of the expected types for type: '${xlrNode.name}'`;
143
+ } else if (xlrNode.title) {
144
+ message = `Does not match any of the expected types for property: '${xlrNode.title}'`;
145
+ } else {
146
+ message = `Does not match any of the types: ${expectedTypes}`;
147
+ }
148
+ const { infoMessage } = this.generateNestedTypesInfo(
149
+ potentialTypeErrors,
150
+ xlrNode,
151
+ rootNode
152
+ );
153
+ validationIssues.push({
154
+ type: "value",
155
+ node: rootNode,
156
+ message: message.trim(),
157
+ severity: 1 /* Error */
158
+ });
159
+ if (infoMessage) {
160
+ validationIssues.push({
161
+ type: "value",
162
+ node: rootNode,
163
+ message: infoMessage,
164
+ severity: 3 /* Info */
165
+ });
166
+ }
167
+ } else if (xlrNode.type === "and") {
168
+ const effectiveType = {
169
+ ...this.computeIntersectionType(xlrNode.and),
170
+ ...xlrNode.name ? { name: xlrNode.name } : {}
171
+ };
172
+ validationIssues.push(...this.validateType(rootNode, effectiveType));
173
+ } else if (xlrNode.type === "record") {
174
+ rootNode.children?.forEach((child) => {
175
+ validationIssues.push(
176
+ ...this.validateType(child.children?.[0], xlrNode.keyType)
177
+ );
178
+ validationIssues.push(
179
+ ...this.validateType(child.children?.[1], xlrNode.valueType)
180
+ );
181
+ });
182
+ } else if (xlrNode.type === "ref") {
183
+ const refType = this.getRefType(xlrNode);
184
+ if (refType === void 0) {
185
+ validationIssues.push({
186
+ type: "unknown",
187
+ node: rootNode,
188
+ message: `Type "${xlrNode.ref}" is not defined in provided bundles`,
189
+ severity: 1 /* Error */
190
+ });
191
+ } else {
192
+ validationIssues.push(
193
+ ...this.validateType(rootNode, refType)
194
+ );
195
+ }
196
+ } else if (isPrimitiveTypeNode(xlrNode)) {
197
+ if (!this.validateLiteralType(xlrNode, rootNode)) {
198
+ if ((xlrNode.type === "string" || xlrNode.type === "number" || xlrNode.type === "boolean") && xlrNode.const) {
199
+ validationIssues.push({
200
+ type: "type",
201
+ node: rootNode.parent,
202
+ message: `Expected "${xlrNode.const}" but got "${rootNode.value}"`,
203
+ expected: xlrNode.const,
204
+ severity: 1 /* Error */
205
+ });
206
+ } else {
207
+ validationIssues.push({
208
+ type: "type",
209
+ node: rootNode.parent,
210
+ message: `Expected type "${xlrNode.type}" but got "${rootNode.type}"`,
211
+ expected: xlrNode.type,
212
+ severity: 1 /* Error */
213
+ });
214
+ }
215
+ }
216
+ } else if (xlrNode.type === "conditional") {
217
+ let { right, left } = xlrNode.check;
218
+ if (right.type === "ref") {
219
+ right = this.getRefType(right);
220
+ }
221
+ if (left.type === "ref") {
222
+ left = this.getRefType(left);
223
+ }
224
+ const resolvedXLRNode = {
225
+ ...xlrNode,
226
+ check: {
227
+ left,
228
+ right
229
+ }
230
+ };
231
+ const resolvedConditional = resolveConditional(resolvedXLRNode);
232
+ if (resolvedConditional === resolvedXLRNode) {
233
+ throw Error(
234
+ `Unable to resolve conditional type at runtime: ${xlrNode.name}`
235
+ );
236
+ }
237
+ validationIssues.push(
238
+ ...this.validateType(rootNode, resolvedConditional)
239
+ );
240
+ } else {
241
+ throw Error(`Unknown type ${xlrNode.type}`);
242
+ }
243
+ return validationIssues;
244
+ }
245
+ generateNestedTypesInfo(potentialTypeErrors, xlrNode, rootNode) {
246
+ const nestedTypes = /* @__PURE__ */ new Set();
247
+ potentialTypeErrors.forEach((typeError) => {
248
+ if (typeError.type.type !== "template") {
249
+ typeError.errors.forEach((error) => {
250
+ if (error.type === "type" && error.expected) {
251
+ String(error.expected).split(" | ").forEach((val) => nestedTypes.add(val.trim()));
252
+ }
253
+ });
254
+ }
255
+ });
256
+ if (nestedTypes.size === 0) {
257
+ xlrNode.or.forEach((type) => {
258
+ const typeName = type.name ?? type.title ?? type.type ?? "<unnamed type>";
259
+ nestedTypes.add(typeName);
260
+ });
261
+ }
262
+ const nestedTypesArray = [...nestedTypes];
263
+ let nestedTypesList = nestedTypesArray.slice(0, MAX_VALID_SHOWN).join(" | ") + (nestedTypesArray.length > MAX_VALID_SHOWN ? ` | +${nestedTypesArray.length - MAX_VALID_SHOWN} ... ${nestedTypesArray.pop()}` : "");
264
+ const docsURL = this.config.urlMapping;
265
+ if (docsURL && xlrNode.name && docsURL[xlrNode.name]) {
266
+ nestedTypesList = docsURL[xlrNode.name];
267
+ }
268
+ let infoMessage;
269
+ if (rootNode.value !== void 0) {
270
+ infoMessage = `Got: ${rootNode.value} and expected: ${nestedTypesList}`;
271
+ } else if (nestedTypesList) {
272
+ infoMessage = `Expected: ${nestedTypesList}`;
273
+ }
274
+ return { nestedTypesList, infoMessage };
275
+ }
276
+ validateTemplate(node, xlrNode) {
277
+ if (node.type !== "string") {
278
+ return {
279
+ type: "type",
280
+ node: node.parent,
281
+ message: `Expected type "${xlrNode.type}" but got "${typeof node}"`,
282
+ expected: xlrNode.type,
283
+ severity: 1 /* Error */
284
+ };
285
+ }
286
+ const regex = this.getRegex(xlrNode.format);
287
+ const valid = regex.exec(node.value);
288
+ if (!valid) {
289
+ return {
290
+ type: "value",
291
+ node: node.parent,
292
+ message: `Does not match expected format: ${xlrNode.format}`,
293
+ expected: xlrNode.format,
294
+ severity: 1 /* Error */
295
+ };
296
+ }
297
+ }
298
+ validateArray(rootNode, xlrNode) {
299
+ const issues = [];
300
+ rootNode.children?.forEach(
301
+ (child) => issues.push(...this.validateType(child, xlrNode.elementType))
302
+ );
303
+ return issues;
304
+ }
305
+ validateObject(xlrNode, node) {
306
+ const issues = [];
307
+ const objectProps = makePropertyMap(node);
308
+ for (const prop in xlrNode.properties) {
309
+ const expectedType = xlrNode.properties[prop];
310
+ const valueNode = objectProps.get(prop);
311
+ if (expectedType.required && valueNode === void 0) {
312
+ issues.push({
313
+ type: "missing",
314
+ node,
315
+ message: `Property "${prop}" missing from type "${xlrNode.name}"`,
316
+ severity: 1 /* Error */
317
+ });
318
+ }
319
+ if (valueNode) {
320
+ issues.push(
321
+ ...this.validateType(valueNode, expectedType.node)
322
+ );
323
+ }
324
+ }
325
+ const extraKeys = Array.from(objectProps.keys()).filter(
326
+ (key) => xlrNode.properties[key] === void 0
327
+ );
328
+ if (xlrNode.additionalProperties === false && extraKeys.length > 0) {
329
+ issues.push({
330
+ type: "value",
331
+ node,
332
+ message: `Unexpected properties on "${xlrNode.name}": ${extraKeys.join(
333
+ ", "
334
+ )}`,
335
+ severity: 1 /* Error */
336
+ });
337
+ } else {
338
+ issues.push(
339
+ ...extraKeys.flatMap(
340
+ (key) => this.validateType(
341
+ objectProps.get(key),
342
+ xlrNode.additionalProperties
343
+ )
344
+ )
345
+ );
346
+ }
347
+ return issues;
348
+ }
349
+ validateLiteralType(expectedType, literalType) {
350
+ switch (expectedType.type) {
351
+ case "boolean":
352
+ if (expectedType.const) {
353
+ return expectedType.const === literalType.value;
354
+ }
355
+ return typeof literalType.value === "boolean";
356
+ case "number":
357
+ if (expectedType.const) {
358
+ return expectedType.const === literalType.value;
359
+ }
360
+ return typeof literalType.value === "number";
361
+ case "string":
362
+ if (expectedType.const) {
363
+ return expectedType.const === literalType.value;
364
+ }
365
+ return typeof literalType.value === "string";
366
+ case "null":
367
+ return literalType.value === null;
368
+ case "never":
369
+ return literalType === void 0;
370
+ case "any":
371
+ return literalType !== void 0;
372
+ case "unknown":
373
+ return literalType !== void 0;
374
+ case "undefined":
375
+ return true;
376
+ default:
377
+ return false;
378
+ }
379
+ }
380
+ getRefType(ref) {
381
+ let refName = ref.ref;
382
+ if (refName.indexOf("<") > 0) {
383
+ [refName] = refName.split("<");
384
+ }
385
+ const actualType = this.resolveType(refName);
386
+ if (!actualType) {
387
+ throw new Error(`Error: can't resolve type reference ${refName}`);
388
+ }
389
+ return resolveReferenceNode(ref, actualType);
390
+ }
391
+ getRegex(expString) {
392
+ if (this.regexCache.has(expString)) {
393
+ return this.regexCache.get(expString);
394
+ }
395
+ const exp = new RegExp(expString);
396
+ this.regexCache.set(expString, exp);
397
+ return exp;
398
+ }
399
+ computeIntersectionType(types) {
400
+ let firstElement = types[0];
401
+ let effectiveType;
402
+ const topLevelTypeName = types[0].name;
403
+ if (firstElement.type === "ref") {
404
+ firstElement = this.getRefType(firstElement);
405
+ }
406
+ if (firstElement.type === "and") {
407
+ effectiveType = this.computeIntersectionType(firstElement.and);
408
+ } else if (firstElement.type === "record") {
409
+ effectiveType = {
410
+ type: "object",
411
+ properties: {},
412
+ additionalProperties: firstElement.valueType
413
+ };
414
+ } else if (firstElement.type !== "or" && firstElement.type !== "object") {
415
+ throw new Error(
416
+ `Can't compute a union with a non-object type ${firstElement.type} (${firstElement.name})`
417
+ );
418
+ } else {
419
+ effectiveType = firstElement;
420
+ }
421
+ types.slice(1).forEach((type) => {
422
+ let typeToApply = type;
423
+ if (typeToApply.type === "record") {
424
+ typeToApply = {
425
+ type: "object",
426
+ properties: {},
427
+ additionalProperties: typeToApply.valueType
428
+ };
429
+ }
430
+ if (type.type === "ref") {
431
+ typeToApply = this.getRefType(type);
432
+ }
433
+ if (typeToApply.type === "and") {
434
+ typeToApply = this.computeIntersectionType([type, effectiveType]);
435
+ }
436
+ if (typeToApply.type === "object") {
437
+ if (effectiveType.type === "object") {
438
+ effectiveType = computeEffectiveObject(effectiveType, typeToApply);
439
+ } else {
440
+ effectiveType = {
441
+ ...effectiveType,
442
+ or: effectiveType.or.map((y) => {
443
+ const intersectedType = this.computeIntersectionType([
444
+ y,
445
+ typeToApply
446
+ ]);
447
+ if (!intersectedType.name && topLevelTypeName) {
448
+ intersectedType.name = topLevelTypeName;
449
+ }
450
+ return intersectedType;
451
+ })
452
+ };
453
+ }
454
+ } else if (typeToApply.type === "or") {
455
+ if (effectiveType.type === "object") {
456
+ effectiveType = {
457
+ ...typeToApply,
458
+ or: typeToApply.or.map((y) => {
459
+ const intersectedType = this.computeIntersectionType([
460
+ y,
461
+ effectiveType
462
+ ]);
463
+ if (!intersectedType.name && topLevelTypeName) {
464
+ intersectedType.name = topLevelTypeName;
465
+ }
466
+ return intersectedType;
467
+ })
468
+ };
469
+ } else {
470
+ throw new Error("unimplemented operation or x or projection");
471
+ }
472
+ } else {
473
+ throw new Error(
474
+ `Can't compute a union with a non-object type ${typeToApply.type} (${typeToApply.name})`
475
+ );
476
+ }
477
+ });
478
+ if (effectiveType.type === "or" && !effectiveType.name && topLevelTypeName) {
479
+ effectiveType.name = topLevelTypeName;
480
+ }
481
+ return effectiveType;
482
+ }
483
+ };
484
+
485
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/utils.ts
486
+ import { isGenericNamedType } from "@xlr-lib/xlr-utils";
487
+ var isMatchingCapability = (capability, capabilitiesToMatch) => {
488
+ if (Array.isArray(capabilitiesToMatch)) {
489
+ return capabilitiesToMatch.includes(capability);
490
+ }
491
+ return capability === capabilitiesToMatch;
492
+ };
493
+ function xlrTransformWalker(transformMap) {
494
+ const walker = (n) => {
495
+ let node = { ...n };
496
+ const transformFunctions = transformMap[node.type];
497
+ for (const transformFn of transformFunctions ?? []) {
498
+ node = transformFn(node);
499
+ }
500
+ if (node.type === "object") {
501
+ const newObjectProperties = {};
502
+ for (const key in node.properties) {
503
+ const value = node.properties[key];
504
+ newObjectProperties[key] = {
505
+ required: value.required,
506
+ node: walker(value.node)
507
+ };
508
+ }
509
+ return {
510
+ ...node,
511
+ properties: { ...newObjectProperties },
512
+ ...isGenericNamedType(node) ? {
513
+ genericTokens: node.genericTokens.map((token) => {
514
+ return {
515
+ ...token,
516
+ constraints: token.constraints ? walker(token.constraints) : void 0,
517
+ default: token.default ? walker(token.default) : void 0
518
+ };
519
+ })
520
+ } : {},
521
+ extends: node.extends ? walker(node.extends) : void 0,
522
+ additionalProperties: node.additionalProperties ? walker(node.additionalProperties) : false
523
+ };
524
+ }
525
+ if (node.type === "array") {
526
+ return {
527
+ ...node,
528
+ elementType: walker(node.elementType)
529
+ };
530
+ }
531
+ if (node.type === "and") {
532
+ return {
533
+ ...node,
534
+ and: node.and.map((element) => walker(element))
535
+ };
536
+ }
537
+ if (node.type === "or") {
538
+ return {
539
+ ...node,
540
+ or: node.or.map((element) => walker(element))
541
+ };
542
+ }
543
+ if (node.type === "ref") {
544
+ return {
545
+ ...node,
546
+ ...node.genericArguments ? {
547
+ genericArguments: node.genericArguments?.map(
548
+ (arg) => walker(arg)
549
+ )
550
+ } : {}
551
+ };
552
+ }
553
+ if (node.type === "tuple") {
554
+ return {
555
+ ...node,
556
+ elementTypes: node.elementTypes.map((element) => {
557
+ return {
558
+ name: element.name,
559
+ type: walker(element.type),
560
+ optional: element.optional
561
+ };
562
+ }),
563
+ additionalItems: node.additionalItems ? walker(node.additionalItems) : false
564
+ };
565
+ }
566
+ if (node.type === "function") {
567
+ return {
568
+ ...node,
569
+ parameters: node.parameters.map((param) => {
570
+ return {
571
+ ...param,
572
+ type: walker(param.type),
573
+ default: param.default ? walker(param.default) : void 0
574
+ };
575
+ }),
576
+ returnType: node.returnType ? walker(node.returnType) : void 0
577
+ };
578
+ }
579
+ if (node.type === "record") {
580
+ return {
581
+ ...node,
582
+ keyType: walker(node.keyType),
583
+ valueType: walker(node.valueType)
584
+ };
585
+ }
586
+ if (node.type === "conditional") {
587
+ return {
588
+ ...node,
589
+ check: {
590
+ left: walker(node.check.left),
591
+ right: walker(node.check.left)
592
+ },
593
+ value: {
594
+ true: walker(node.value.true),
595
+ false: walker(node.value.false)
596
+ }
597
+ };
598
+ }
599
+ return node;
600
+ };
601
+ return walker;
602
+ }
603
+ function simpleTransformGenerator(typeToTransform, capabilityToTransform, functionToRun) {
604
+ return (n, capability) => {
605
+ if (isMatchingCapability(capability, capabilityToTransform)) {
606
+ return xlrTransformWalker({ [typeToTransform]: [functionToRun] })(n);
607
+ }
608
+ return n;
609
+ };
610
+ }
611
+
612
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/sdk.ts
613
+ var XLRSDK = class {
614
+ registry;
615
+ validator;
616
+ computedNodeCache;
617
+ externalTransformFunctions;
618
+ constructor(customRegistry) {
619
+ this.registry = customRegistry ?? new BasicXLRRegistry();
620
+ this.validator = new XLRValidator(this.getType.bind(this));
621
+ this.computedNodeCache = /* @__PURE__ */ new Map();
622
+ this.externalTransformFunctions = /* @__PURE__ */ new Map();
623
+ }
624
+ /**
625
+ * Loads definitions from a path on the filesystem
626
+ *
627
+ * @param inputPath - path to the directory to load (above the xlr folder)
628
+ * @param filters - Any filters to apply when loading the types (a positive match will omit)
629
+ * @param transforms - any transforms to apply to the types being loaded
630
+ */
631
+ loadDefinitionsFromDisk(inputPath, filters, transforms) {
632
+ this.computedNodeCache.clear();
633
+ const transformsToRun = [
634
+ ...this.externalTransformFunctions.values(),
635
+ ...transforms ?? []
636
+ ];
637
+ const manifest = JSON.parse(
638
+ fs.readFileSync(path.join(inputPath, "xlr", "manifest.json")).toString(),
639
+ (key, value) => {
640
+ if (typeof value === "object" && value !== null) {
641
+ if (key === "capabilities") {
642
+ return new Map(Object.entries(value));
643
+ }
644
+ }
645
+ return value;
646
+ }
647
+ );
648
+ manifest.capabilities?.forEach((capabilityList, capabilityName) => {
649
+ if (filters?.capabilityFilter && capabilityName.match(filters?.capabilityFilter))
650
+ return;
651
+ capabilityList.forEach((extensionName) => {
652
+ if (!filters?.typeFilter || !extensionName.match(filters?.typeFilter)) {
653
+ const cType = JSON.parse(
654
+ fs.readFileSync(
655
+ path.join(inputPath, "xlr", `${extensionName}.json`)
656
+ ).toString()
657
+ );
658
+ const effectiveType = transformsToRun?.reduce(
659
+ (typeAccumulator, transformFn) => transformFn(
660
+ typeAccumulator,
661
+ capabilityName
662
+ ),
663
+ cType
664
+ ) ?? cType;
665
+ this.registry.add(effectiveType, manifest.pluginName, capabilityName);
666
+ }
667
+ });
668
+ });
669
+ }
670
+ /**
671
+ * Load definitions from a js/ts file in memory
672
+ *
673
+ * @param manifest - The imported XLR manifest module
674
+ * @param filters - Any filters to apply when loading the types (a positive match will omit)
675
+ * @param transforms - any transforms to apply to the types being loaded
676
+ */
677
+ async loadDefinitionsFromModule(manifest, filters, transforms) {
678
+ this.computedNodeCache.clear();
679
+ const transformsToRun = [
680
+ ...this.externalTransformFunctions.values(),
681
+ ...transforms ?? []
682
+ ];
683
+ Object.keys(manifest.capabilities)?.forEach((capabilityName) => {
684
+ if (filters?.capabilityFilter && capabilityName.match(filters?.capabilityFilter))
685
+ return;
686
+ const capabilityList = manifest.capabilities[capabilityName];
687
+ capabilityList.forEach((extension) => {
688
+ if (!filters?.typeFilter || !extension.name.match(filters?.typeFilter)) {
689
+ const effectiveType = transformsToRun?.reduce(
690
+ (typeAccumulator, transformFn) => transformFn(
691
+ typeAccumulator,
692
+ capabilityName
693
+ ),
694
+ extension
695
+ ) ?? extension;
696
+ this.registry.add(effectiveType, manifest.pluginName, capabilityName);
697
+ }
698
+ });
699
+ });
700
+ }
701
+ /**
702
+ * Statically load transform function that should be applied to every XLR bundle that is imported
703
+ */
704
+ addTransformFunction(name, fn) {
705
+ this.externalTransformFunctions.set(name, fn);
706
+ }
707
+ /**
708
+ * Remove any transform function loaded via the `addTransformFunction` method by name
709
+ */
710
+ removeTransformFunction(name) {
711
+ this.externalTransformFunctions.delete(name);
712
+ }
713
+ /**
714
+ * Returns a Type that has been previously loaded
715
+ *
716
+ * @param id - Type to retrieve
717
+ * @param options - `GetTypeOptions`
718
+ * @returns `NamedType<NodeType>` | `undefined`
719
+ */
720
+ getType(id, options) {
721
+ let type = this.registry.get(id);
722
+ if (options?.getRawType === true || !type) {
723
+ return type;
724
+ }
725
+ if (this.computedNodeCache.has(id)) {
726
+ return JSON.parse(JSON.stringify(this.computedNodeCache.get(id)));
727
+ }
728
+ type = this.resolveType(type, options?.optimize);
729
+ this.computedNodeCache.set(id, type);
730
+ return type;
731
+ }
732
+ /**
733
+ * Returns if a Type with `id` has been loaded into the DSK
734
+ *
735
+ * @param id - Type to retrieve
736
+ * @returns `boolean`
737
+ */
738
+ hasType(id) {
739
+ return this.registry.has(id);
740
+ }
741
+ /**
742
+ * Lists types that have been loaded into the SDK
743
+ *
744
+ * @param filters - Any filters to apply to the types returned (a positive match will omit)
745
+ * @returns `Array<NamedTypes>`
746
+ */
747
+ listTypes(filters) {
748
+ return this.registry.list(filters);
749
+ }
750
+ /**
751
+ * Returns meta information around a registered type
752
+ *
753
+ * @param id - Name of Type to retrieve
754
+ * @returns `TypeMetaData` | `undefined`
755
+ */
756
+ getTypeInfo(id) {
757
+ return this.registry.info(id);
758
+ }
759
+ /**
760
+ * Validates if a JSONC Node follows the XLR Type registered under the `typeName` specified
761
+ *
762
+ * @param typeName - Registered XLR Type to use for validation
763
+ * @param rootNode - Node to validate
764
+ * @returns `Array<ValidationErrors>`
765
+ */
766
+ validateByName(typeName, rootNode) {
767
+ const xlr = this.getType(typeName);
768
+ if (!xlr) {
769
+ throw new Error(
770
+ `Type ${typeName} does not exist in registry, can't validate`
771
+ );
772
+ }
773
+ return this.validator.validateType(rootNode, xlr);
774
+ }
775
+ /**
776
+ * Validates if a JSONC Node follows the supplied XLR Type
777
+ *
778
+ * @param type - Type to validate against
779
+ * @param rootNode - Node to validate
780
+ * @returns `Array<ValidationErrors>`
781
+ */
782
+ validateByType(type, rootNode) {
783
+ return this.validator.validateType(rootNode, type);
784
+ }
785
+ /**
786
+ * Transforms a generated XLR node into its final representation by resolving all `extends` properties.
787
+ * If `optimize` is set to true the following operations are also performed:
788
+ * - Solving any conditional types
789
+ * - Computing the effective types of any union elements
790
+ * - Resolving any ref nodes
791
+ * - filing in any remaining generics with their default value
792
+ */
793
+ resolveType(type, optimize = true) {
794
+ const resolvedObject = fillInGenerics(type, /* @__PURE__ */ new Map(), true);
795
+ let transformMap = {
796
+ object: [(objectNode) => {
797
+ if (objectNode.extends) {
798
+ const refName = objectNode.extends.ref.split("<")[0];
799
+ let extendedType = this.getType(refName, { getRawType: true });
800
+ if (!extendedType) {
801
+ throw new Error(
802
+ `Error resolving ${objectNode.name}: can't find extended type ${refName}`
803
+ );
804
+ }
805
+ extendedType = resolveReferenceNode2(
806
+ objectNode.extends,
807
+ extendedType
808
+ );
809
+ if (extendedType.type === "object") {
810
+ return {
811
+ ...computeEffectiveObject2(
812
+ extendedType,
813
+ objectNode,
814
+ false
815
+ ),
816
+ name: objectNode.name,
817
+ description: objectNode.description
818
+ };
819
+ }
820
+ if (extendedType.type === "or") {
821
+ return {
822
+ ...this.validator.computeIntersectionType(
823
+ [
824
+ objectNode,
825
+ extendedType
826
+ ]
827
+ ),
828
+ name: objectNode.name,
829
+ description: objectNode.description
830
+ };
831
+ }
832
+ return {
833
+ name: objectNode.name,
834
+ type: "and",
835
+ and: [
836
+ {
837
+ ...objectNode,
838
+ extends: void 0
839
+ },
840
+ extendedType
841
+ ]
842
+ };
843
+ }
844
+ return objectNode;
845
+ }]
846
+ };
847
+ if (optimize) {
848
+ transformMap = {
849
+ ...transformMap,
850
+ conditional: [(node) => {
851
+ return resolveConditional2(node);
852
+ }],
853
+ and: [(node) => {
854
+ return {
855
+ ...this.validator.computeIntersectionType(node.and),
856
+ ...node.name ? { name: node.name } : {}
857
+ };
858
+ }],
859
+ ref: [(refNode) => {
860
+ return this.validator.getRefType(refNode);
861
+ }]
862
+ };
863
+ }
864
+ return xlrTransformWalker(transformMap)(resolvedObject);
865
+ }
866
+ };
867
+ export {
868
+ BasicXLRRegistry,
869
+ ValidationSeverity,
870
+ XLRSDK,
871
+ simpleTransformGenerator,
872
+ xlrTransformWalker
873
+ };
874
+ //# sourceMappingURL=index.mjs.map