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