@fgv/ts-res 5.0.0-0 → 5.0.0-11

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.
Files changed (112) hide show
  1. package/dist/ts-res.d.ts +793 -125
  2. package/lib/index.d.ts +10 -2
  3. package/lib/index.d.ts.map +1 -1
  4. package/lib/index.js +23 -2
  5. package/lib/index.js.map +1 -1
  6. package/lib/packlets/bundle/bundleBuilder.d.ts +41 -0
  7. package/lib/packlets/bundle/bundleBuilder.d.ts.map +1 -0
  8. package/lib/packlets/bundle/bundleBuilder.js +134 -0
  9. package/lib/packlets/bundle/bundleBuilder.js.map +1 -0
  10. package/lib/packlets/bundle/bundleLoader.d.ts +72 -0
  11. package/lib/packlets/bundle/bundleLoader.d.ts.map +1 -0
  12. package/lib/packlets/bundle/bundleLoader.js +105 -0
  13. package/lib/packlets/bundle/bundleLoader.js.map +1 -0
  14. package/lib/packlets/bundle/bundleNormalizer.d.ts +73 -0
  15. package/lib/packlets/bundle/bundleNormalizer.d.ts.map +1 -0
  16. package/lib/packlets/bundle/bundleNormalizer.js +142 -0
  17. package/lib/packlets/bundle/bundleNormalizer.js.map +1 -0
  18. package/lib/packlets/bundle/bundleUtils.d.ts +70 -0
  19. package/lib/packlets/bundle/bundleUtils.d.ts.map +1 -0
  20. package/lib/packlets/bundle/bundleUtils.js +117 -0
  21. package/lib/packlets/bundle/bundleUtils.js.map +1 -0
  22. package/lib/packlets/bundle/convert.d.ts +33 -0
  23. package/lib/packlets/bundle/convert.d.ts.map +1 -0
  24. package/lib/packlets/bundle/convert.js +78 -0
  25. package/lib/packlets/bundle/convert.js.map +1 -0
  26. package/lib/packlets/bundle/index.d.ts +21 -0
  27. package/lib/packlets/bundle/index.d.ts.map +1 -0
  28. package/lib/packlets/bundle/index.js +83 -0
  29. package/lib/packlets/bundle/index.js.map +1 -0
  30. package/lib/packlets/bundle/model.d.ts +100 -0
  31. package/lib/packlets/bundle/model.d.ts.map +1 -0
  32. package/lib/packlets/bundle/model.js +24 -0
  33. package/lib/packlets/bundle/model.js.map +1 -0
  34. package/lib/packlets/common/helpers/resources.d.ts +7 -0
  35. package/lib/packlets/common/helpers/resources.d.ts.map +1 -1
  36. package/lib/packlets/common/helpers/resources.js +12 -0
  37. package/lib/packlets/common/helpers/resources.js.map +1 -1
  38. package/lib/packlets/common/resources.d.ts +8 -0
  39. package/lib/packlets/common/resources.d.ts.map +1 -1
  40. package/lib/packlets/common/resources.js.map +1 -1
  41. package/lib/packlets/conditions/condition.js +1 -1
  42. package/lib/packlets/conditions/condition.js.map +1 -1
  43. package/lib/packlets/conditions/conditionSet.d.ts +9 -0
  44. package/lib/packlets/conditions/conditionSet.d.ts.map +1 -1
  45. package/lib/packlets/conditions/conditionSet.js +74 -1
  46. package/lib/packlets/conditions/conditionSet.js.map +1 -1
  47. package/lib/packlets/import/fsItem.d.ts.map +1 -1
  48. package/lib/packlets/import/fsItem.js +8 -13
  49. package/lib/packlets/import/fsItem.js.map +1 -1
  50. package/lib/packlets/import/importers/jsonImporter.d.ts.map +1 -1
  51. package/lib/packlets/import/importers/jsonImporter.js +1 -0
  52. package/lib/packlets/import/importers/jsonImporter.js.map +1 -1
  53. package/lib/packlets/qualifier-types/literalQualifierType.d.ts +4 -0
  54. package/lib/packlets/qualifier-types/literalQualifierType.d.ts.map +1 -1
  55. package/lib/packlets/qualifier-types/literalQualifierType.js +14 -0
  56. package/lib/packlets/qualifier-types/literalQualifierType.js.map +1 -1
  57. package/lib/packlets/qualifier-types/literalValueHierarchy.d.ts +7 -0
  58. package/lib/packlets/qualifier-types/literalValueHierarchy.d.ts.map +1 -1
  59. package/lib/packlets/qualifier-types/literalValueHierarchy.js +14 -1
  60. package/lib/packlets/qualifier-types/literalValueHierarchy.js.map +1 -1
  61. package/lib/packlets/qualifier-types/qualifierType.d.ts +11 -0
  62. package/lib/packlets/qualifier-types/qualifierType.d.ts.map +1 -1
  63. package/lib/packlets/qualifier-types/qualifierType.js +9 -0
  64. package/lib/packlets/qualifier-types/qualifierType.js.map +1 -1
  65. package/lib/packlets/qualifiers/qualifierCollector.d.ts.map +1 -1
  66. package/lib/packlets/qualifiers/qualifierCollector.js +1 -2
  67. package/lib/packlets/qualifiers/qualifierCollector.js.map +1 -1
  68. package/lib/packlets/resource-types/jsonResourceType.d.ts +4 -4
  69. package/lib/packlets/resource-types/jsonResourceType.d.ts.map +1 -1
  70. package/lib/packlets/resource-types/jsonResourceType.js +1 -1
  71. package/lib/packlets/resource-types/jsonResourceType.js.map +1 -1
  72. package/lib/packlets/resource-types/resourceType.d.ts +18 -9
  73. package/lib/packlets/resource-types/resourceType.d.ts.map +1 -1
  74. package/lib/packlets/resource-types/resourceType.js.map +1 -1
  75. package/lib/packlets/resources/common.d.ts +12 -0
  76. package/lib/packlets/resources/common.d.ts.map +1 -1
  77. package/lib/packlets/resources/common.js.map +1 -1
  78. package/lib/packlets/resources/resource.d.ts +5 -1
  79. package/lib/packlets/resources/resource.d.ts.map +1 -1
  80. package/lib/packlets/resources/resource.js +1 -0
  81. package/lib/packlets/resources/resource.js.map +1 -1
  82. package/lib/packlets/resources/resourceCandidate.d.ts +5 -1
  83. package/lib/packlets/resources/resourceCandidate.d.ts.map +1 -1
  84. package/lib/packlets/resources/resourceCandidate.js +6 -0
  85. package/lib/packlets/resources/resourceCandidate.js.map +1 -1
  86. package/lib/packlets/resources/resourceManagerBuilder.d.ts +133 -6
  87. package/lib/packlets/resources/resourceManagerBuilder.d.ts.map +1 -1
  88. package/lib/packlets/resources/resourceManagerBuilder.js +451 -9
  89. package/lib/packlets/resources/resourceManagerBuilder.js.map +1 -1
  90. package/lib/packlets/runtime/cacheListener.d.ts +9 -0
  91. package/lib/packlets/runtime/cacheListener.d.ts.map +1 -1
  92. package/lib/packlets/runtime/cacheListener.js +6 -0
  93. package/lib/packlets/runtime/cacheListener.js.map +1 -1
  94. package/lib/packlets/runtime/cacheMetrics.d.ts +6 -0
  95. package/lib/packlets/runtime/cacheMetrics.d.ts.map +1 -1
  96. package/lib/packlets/runtime/cacheMetrics.js +11 -0
  97. package/lib/packlets/runtime/cacheMetrics.js.map +1 -1
  98. package/lib/packlets/runtime/compiledResourceCollection.d.ts +1 -1
  99. package/lib/packlets/runtime/compiledResourceCollection.d.ts.map +1 -1
  100. package/lib/packlets/runtime/compiledResourceCollection.js +7 -0
  101. package/lib/packlets/runtime/compiledResourceCollection.js.map +1 -1
  102. package/lib/packlets/runtime/iResourceManager.d.ts +11 -3
  103. package/lib/packlets/runtime/iResourceManager.d.ts.map +1 -1
  104. package/lib/packlets/runtime/iResourceManager.js.map +1 -1
  105. package/lib/packlets/runtime/resourceResolver.d.ts +21 -0
  106. package/lib/packlets/runtime/resourceResolver.d.ts.map +1 -1
  107. package/lib/packlets/runtime/resourceResolver.js +39 -17
  108. package/lib/packlets/runtime/resourceResolver.js.map +1 -1
  109. package/lib/packlets/runtime/validate.d.ts.map +1 -1
  110. package/lib/packlets/runtime/validate.js +1 -0
  111. package/lib/packlets/runtime/validate.js.map +1 -1
  112. package/package.json +12 -12
@@ -56,13 +56,17 @@ var __importStar = (this && this.__importStar) || (function () {
56
56
  Object.defineProperty(exports, "__esModule", { value: true });
57
57
  exports.ResourceManagerBuilder = void 0;
58
58
  const ts_utils_1 = require("@fgv/ts-utils");
59
+ const ts_json_base_1 = require("@fgv/ts-json-base");
59
60
  const conditions_1 = require("../conditions");
60
61
  const decisions_1 = require("../decisions");
61
62
  const common_1 = require("../common");
63
+ const runtime_1 = require("../runtime");
62
64
  const resourceBuilder_1 = require("./resourceBuilder");
63
65
  const resource_1 = require("./resource");
64
66
  const ResourceJson = __importStar(require("../resource-json"));
65
67
  const Context = __importStar(require("../context"));
68
+ const Config = __importStar(require("../config"));
69
+ const ts_json_1 = require("@fgv/ts-json");
66
70
  /**
67
71
  * Builder for a collection of {@link Resources.Resource | resources}. Collects
68
72
  * {@link Resources.ResourceCandidate | candidates} for each resource into a
@@ -154,6 +158,7 @@ class ResourceManagerBuilder {
154
158
  })
155
159
  });
156
160
  this._built = false;
161
+ this._cachedResourceTree = undefined;
157
162
  }
158
163
  /**
159
164
  * Creates a new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} object.
@@ -165,6 +170,48 @@ class ResourceManagerBuilder {
165
170
  static create(params) {
166
171
  return (0, ts_utils_1.captureResult)(() => new ResourceManagerBuilder(params));
167
172
  }
173
+ /**
174
+ * Creates a new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} object from a predefined system configuration.
175
+ * @param name - The name of the predefined system configuration to use.
176
+ * @param qualifierDefaultValues - Optional default values for qualifiers.
177
+ * @returns `Success` with the new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} object if successful,
178
+ * or `Failure` with an error message if not.
179
+ * @public
180
+ */
181
+ static createPredefined(name, qualifierDefaultValues) {
182
+ return Config.getPredefinedSystemConfiguration(name,
183
+ /* c8 ignore next 1 - defense in depth */
184
+ qualifierDefaultValues ? { qualifierDefaultValues } : undefined).onSuccess((systemConfig) => {
185
+ return ResourceManagerBuilder.create({
186
+ qualifiers: systemConfig.qualifiers,
187
+ resourceTypes: systemConfig.resourceTypes
188
+ });
189
+ });
190
+ }
191
+ /**
192
+ * Creates a new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} from a
193
+ * {@link ResourceJson.Compiled.ICompiledResourceCollection | compiled resource collection}.
194
+ * This method reconstructs an exactly equivalent builder where all qualifier, condition,
195
+ * condition set, and decision indices match the original compiled collection.
196
+ * @param compiledCollection - The compiled resource collection to reconstruct from.
197
+ * @param systemConfig - The system configuration containing qualifiers and resource types.
198
+ * @returns `Success` with the new manager if successful, or `Failure` with an error message if not.
199
+ * @public
200
+ */
201
+ static createFromCompiledResourceCollection(compiledCollection, systemConfig) {
202
+ // Create the base builder with system configuration
203
+ return ResourceManagerBuilder.create({
204
+ qualifiers: systemConfig.qualifiers,
205
+ resourceTypes: systemConfig.resourceTypes
206
+ }).onSuccess((builder) => {
207
+ // Reconstruct all entities in order to preserve indices
208
+ return ResourceManagerBuilder._reconstructConditions(builder, compiledCollection)
209
+ .onSuccess(() => ResourceManagerBuilder._reconstructConditionSets(builder, compiledCollection))
210
+ .onSuccess(() => ResourceManagerBuilder._reconstructDecisions(builder, compiledCollection))
211
+ .onSuccess(() => ResourceManagerBuilder._reconstructResources(builder, compiledCollection))
212
+ .onSuccess(() => (0, ts_utils_1.succeed)(builder));
213
+ });
214
+ }
168
215
  /**
169
216
  * Given a {@link ResourceJson.Json.ILooseResourceCandidateDecl | resource candidate declaration}, builds and adds
170
217
  * a {@link Resources.ResourceCandidate | candidate} to the manager.
@@ -191,6 +238,7 @@ class ResourceManagerBuilder {
191
238
  this._builtResources.delete(id);
192
239
  this._built = false;
193
240
  this._numCandidates = undefined;
241
+ this._cachedResourceTree = undefined;
194
242
  return (0, ts_utils_1.succeedWithDetail)(c, d);
195
243
  });
196
244
  }
@@ -224,6 +272,37 @@ class ResourceManagerBuilder {
224
272
  })
225
273
  .withDetail('failure', detail);
226
274
  }
275
+ /**
276
+ * Adds a condition to the manager.
277
+ * @param decl - The condition declaration to add.
278
+ * @returns `Success` with the condition if successful, or `Failure` with an error message if not.
279
+ * @public
280
+ */
281
+ addCondition(decl) {
282
+ return conditions_1.Convert.validatedConditionDecl
283
+ .convert(decl, { qualifiers: this.qualifiers })
284
+ .onSuccess((validated) => {
285
+ return conditions_1.Condition.getKeyForDecl(validated).onSuccess((key) => {
286
+ return this._conditions.validating.getOrAdd(key, () => conditions_1.Condition.create(validated));
287
+ });
288
+ });
289
+ }
290
+ /**
291
+ * Adds a condition set to the manager.
292
+ * @param decl - The condition set declaration to add.
293
+ * @returns `Success` with the condition set if successful, or `Failure` with an error message if not.
294
+ * @public
295
+ */
296
+ addConditionSet(conditions) {
297
+ const decl = { conditions: [...conditions] };
298
+ return conditions_1.Convert.validatedConditionSetDecl
299
+ .convert(decl, { conditions: this._conditions })
300
+ .onSuccess((validated) => {
301
+ return conditions_1.ConditionSet.getKeyForDecl(validated).onSuccess((key) => {
302
+ return this._conditionSets.validating.getOrAdd(key, () => conditions_1.ConditionSet.create(validated));
303
+ });
304
+ });
305
+ }
227
306
  /**
228
307
  * Gets a read-only array of all {@link Resources.ResourceBuilder | resource builders} present in the manager.
229
308
  * @returns `Success` with the {@link Resources.ResourceBuilder | resource builder} if successful,
@@ -269,6 +348,36 @@ class ResourceManagerBuilder {
269
348
  getAllBuiltResources() {
270
349
  return this.build().onSuccess((manager) => (0, ts_utils_1.succeed)(Array.from(manager._builtResources.values()).sort((a, b) => a.id.localeCompare(b.id))));
271
350
  }
351
+ /**
352
+ * Builds and returns a hierarchical tree representation of all resources managed by this builder.
353
+ * Resources are organized based on their dot-separated resource IDs (e.g., "app.messages.welcome"
354
+ * becomes a tree with "app" as root, "messages" as branch, and "welcome" as leaf).
355
+ *
356
+ * String-based validation is available through the `children.validating` property,
357
+ * allowing callers to use `tree.children.validating.getById(stringId)` for validated access.
358
+ *
359
+ * Uses lazy initialization with caching for performance.
360
+ * @returns Result containing the resource tree root, or failure if tree construction fails
361
+ * @public
362
+ */
363
+ getBuiltResourceTree() {
364
+ // Ensure resources are built first
365
+ return this.build().onSuccess((manager) => {
366
+ if (manager._cachedResourceTree) {
367
+ return (0, ts_utils_1.succeed)(manager._cachedResourceTree);
368
+ }
369
+ // Convert all built resources to [ResourceId, Resource] pairs
370
+ const resources = [];
371
+ for (const [id, resource] of manager._builtResources.entries()) {
372
+ resources.push([id, resource]);
373
+ }
374
+ // Create the resource tree with lazy initialization
375
+ return runtime_1.ResourceTree.ReadOnlyResourceTreeRoot.create(resources).onSuccess((tree) => {
376
+ manager._cachedResourceTree = tree;
377
+ return (0, ts_utils_1.succeed)(tree);
378
+ });
379
+ });
380
+ }
272
381
  /**
273
382
  * Gets a read-only array of all {@link Resources.Resource | built resources} in the manager.
274
383
  * @returns `Success` with an array of resources if successful, or `Failure` with an error message if not.
@@ -422,7 +531,8 @@ class ResourceManagerBuilder {
422
531
  * Creates a filtered clone of this ResourceManagerBuilder using the specified context.
423
532
  * This is a convenience method that creates a new ResourceManagerBuilder with the same
424
533
  * configuration but filtered to include only candidates that match the provided context.
425
- * @param options - Options for the cloning operation, including the strongly-typed filterForContext property.
534
+ * If candidates are provided for editing, they will be applied with collision detection.
535
+ * @param options - Options for the cloning operation, including the strongly-typed filterForContext property and optional candidates for edits.
426
536
  * @returns A Result containing the new filtered ResourceManagerBuilder.
427
537
  * @public
428
538
  */
@@ -433,19 +543,351 @@ class ResourceManagerBuilder {
433
543
  qualifiers: this.qualifiers,
434
544
  resourceTypes: this.resourceTypes
435
545
  }).onSuccess((newManager) => {
436
- // Add each resource from the filtered collection to the new manager
437
- if (collection.resources) {
438
- for (const resourceDecl of collection.resources) {
439
- const addResult = newManager.addResource(resourceDecl);
440
- if (addResult.isFailure()) {
441
- return (0, ts_utils_1.fail)(`${resourceDecl.id}: Failed to add resource to cloned manager: ${addResult.message}`);
546
+ // Check if we have candidates to apply as edits
547
+ const editCandidates = (options === null || options === void 0 ? void 0 : options.candidates) || [];
548
+ const candidatesByResourceResult = editCandidates.length > 0
549
+ ? ResourceManagerBuilder._createCandidatesByResourceMap(editCandidates)
550
+ : (0, ts_utils_1.succeed)(new Map());
551
+ return candidatesByResourceResult.onSuccess((candidatesByResource) => {
552
+ // Track which resource IDs have been processed from the original collection
553
+ const processedResourceIds = new Set();
554
+ // Add each resource from the filtered collection to the new manager
555
+ if (collection.resources) {
556
+ for (const resourceDecl of collection.resources) {
557
+ processedResourceIds.add(resourceDecl.id);
558
+ // Apply edits if there are candidates for this resource
559
+ const editedDeclResult = ResourceManagerBuilder._applyEditsToResourceDeclaration(resourceDecl, candidatesByResource, this._conditions);
560
+ if (editedDeclResult.isFailure()) {
561
+ return (0, ts_utils_1.fail)(`${resourceDecl.id}: Failed to apply edits: ${editedDeclResult.message}`);
562
+ }
563
+ const addResult = newManager.addResource(editedDeclResult.value);
564
+ /* c8 ignore next 5 - edge case (nearly?) impossible to reproduce */
565
+ if (addResult.isFailure()) {
566
+ return (0, ts_utils_1.fail)(`${resourceDecl.id}: Failed to add resource to cloned manager: ${addResult.message}`);
567
+ }
442
568
  }
443
569
  }
444
- }
445
- return (0, ts_utils_1.succeed)(newManager);
570
+ // Handle any remaining candidates that target new resources not in the original collection
571
+ const errors = new ts_utils_1.MessageAggregator();
572
+ for (const [resourceId, candidates] of candidatesByResource) {
573
+ if (!processedResourceIds.has(resourceId)) {
574
+ // Create a new resource declaration for candidates targeting a new resource ID
575
+ ResourceManagerBuilder._createResourceDeclFromCandidates(resourceId, candidates, this._conditions)
576
+ .withErrorFormat((e) => `${resourceId}: Failed to create new resource from candidates: ${e}`)
577
+ .onSuccess((newResourceDecl) => {
578
+ return newManager
579
+ .addResource(newResourceDecl)
580
+ .withErrorFormat((e) => `${resourceId}: Failed to add new resource to cloned manager: ${e}`);
581
+ })
582
+ .aggregateError(errors);
583
+ }
584
+ }
585
+ return errors.returnOrReport((0, ts_utils_1.succeed)(newManager));
586
+ });
446
587
  });
447
588
  });
448
589
  }
590
+ /**
591
+ * Creates a resource ID keyed map from an array of loose resource candidate declarations.
592
+ * This enables efficient detection of edit collisions by grouping candidates by their target resource.
593
+ * @param candidates - Array of loose resource candidate declarations to organize
594
+ * @returns A Result containing a Map where keys are validated ResourceIds and values are arrays of candidates for that resource
595
+ * @internal
596
+ */
597
+ static _createCandidatesByResourceMap(candidates) {
598
+ const candidatesByResource = new Map();
599
+ for (const candidate of candidates) {
600
+ const { value: resourceId, message } = common_1.Validate.toResourceId(candidate.id);
601
+ if (message !== undefined) {
602
+ return (0, ts_utils_1.fail)(`Invalid resource ID "${candidate.id}": ${message}`);
603
+ }
604
+ const existingCandidates = candidatesByResource.get(resourceId);
605
+ if (existingCandidates) {
606
+ existingCandidates.push(candidate);
607
+ }
608
+ else {
609
+ candidatesByResource.set(resourceId, [candidate]);
610
+ }
611
+ }
612
+ return (0, ts_utils_1.succeed)(candidatesByResource);
613
+ }
614
+ /**
615
+ * Generates a proper ConditionSet token for collision detection using the existing ConditionSet.getKeyForDecl method.
616
+ * @param conditionSet - The condition set to generate a token for
617
+ * @param conditionCollector - The condition collector needed for validation context
618
+ * @returns A Result containing the ConditionSet token if successful, or failure if validation fails
619
+ * @internal
620
+ */
621
+ /**
622
+ * Applies candidate edits to a resource declaration, handling collisions using condition set tokens.
623
+ * If there's no collision, adds the candidate. If there's a collision, replaces the original candidate with the edit.
624
+ * @param resourceDecl - The original resource declaration to potentially modify
625
+ * @param candidatesByResource - Map of resource IDs to arrays of candidate edits
626
+ * @param conditionCollector - The condition collector needed for generating condition tokens
627
+ * @returns A Result containing the resource declaration to use (original or modified)
628
+ * @internal
629
+ */
630
+ static _applyEditsToResourceDeclaration(resourceDecl, candidatesByResource, conditionCollector) {
631
+ var _a, _b;
632
+ const { value: resourceId, message } = common_1.Validate.toResourceId(resourceDecl.id);
633
+ /* c8 ignore next 3 - defensive validation: resource IDs are validated when added to builder, but this protects against corrupted data */
634
+ if (message !== undefined) {
635
+ return (0, ts_utils_1.fail)(`Invalid resource ID "${resourceDecl.id}": ${message}`);
636
+ }
637
+ const editCandidates = candidatesByResource.get(resourceId);
638
+ if (!editCandidates || editCandidates.length === 0) {
639
+ return (0, ts_utils_1.succeed)(resourceDecl);
640
+ }
641
+ // Use Map approach: apply original candidates first, then replace with edits on collision
642
+ const candidatesByConditionKey = new Map();
643
+ /* c8 ignore next 1 - ?? is defense in depth */
644
+ const declCandidates = (_a = resourceDecl.candidates) !== null && _a !== void 0 ? _a : [];
645
+ // First, add all original candidates keyed by their condition set token
646
+ for (const candidate of declCandidates) {
647
+ const conditionTokenResult = conditions_1.ConditionSet.getKeyFromLooseDecl(candidate.conditions, conditionCollector);
648
+ /* c8 ignore next 5 - edge case or internal error (nearly?) impossible to reproduce */
649
+ if (conditionTokenResult.isFailure()) {
650
+ return (0, ts_utils_1.fail)(`Failed to generate condition token for original candidate: ${conditionTokenResult.message}`);
651
+ }
652
+ candidatesByConditionKey.set(conditionTokenResult.value, candidate);
653
+ }
654
+ // Then, apply edits (this replaces any colliding original candidates)
655
+ // Convert edit candidates (which have ids) to child candidates (without ids) for merging
656
+ for (const editCandidate of editCandidates) {
657
+ const conditionTokenResult = conditions_1.ConditionSet.getKeyFromLooseDecl(editCandidate.conditions, conditionCollector);
658
+ if (conditionTokenResult.isFailure()) {
659
+ return (0, ts_utils_1.fail)(`Failed to generate condition token for edit candidate: ${conditionTokenResult.message}`);
660
+ }
661
+ let editedJson = editCandidate.json;
662
+ const previousJson = (_b = candidatesByConditionKey.get(conditionTokenResult.value)) === null || _b === void 0 ? void 0 : _b.json;
663
+ if (previousJson && previousJson !== editedJson) {
664
+ editedJson = ts_json_1.JsonEditor.create({
665
+ merge: {
666
+ arrayMergeBehavior: 'replace',
667
+ nullAsDelete: false
668
+ }
669
+ })
670
+ .onSuccess((editor) => {
671
+ return editor.mergeObjectsInPlace({}, [previousJson, editedJson]);
672
+ })
673
+ .orThrow();
674
+ }
675
+ const childCandidate = {
676
+ json: editedJson,
677
+ conditions: editCandidate.conditions,
678
+ isPartial: editCandidate.isPartial,
679
+ mergeMethod: editCandidate.mergeMethod
680
+ };
681
+ candidatesByConditionKey.set(conditionTokenResult.value, childCandidate);
682
+ }
683
+ // Extract the final merged candidate list
684
+ const mergedCandidates = Array.from(candidatesByConditionKey.values());
685
+ const modifiedDecl = Object.assign(Object.assign({}, resourceDecl), { candidates: mergedCandidates });
686
+ return (0, ts_utils_1.succeed)(modifiedDecl);
687
+ }
688
+ /**
689
+ * Creates a new resource declaration from an array of candidate declarations.
690
+ * This is used when cloning to create new resources that don't exist in the original manager.
691
+ * @param resourceId - The validated resource ID for the new resource
692
+ * @param candidates - Array of loose candidate declarations for the new resource
693
+ * @param conditionCollector - The condition collector for validation context
694
+ * @returns A Result containing the new resource declaration if successful, or failure if validation fails
695
+ * @internal
696
+ */
697
+ static _createResourceDeclFromCandidates(resourceId, candidates, conditionCollector) {
698
+ // Convert candidate declarations to child candidate declarations
699
+ const childCandidates = [];
700
+ // Ensure we have candidates
701
+ /* c8 ignore next 3 - defense in depth against internal error */
702
+ if (candidates.length === 0) {
703
+ return (0, ts_utils_1.fail)('Cannot create resource declaration from empty candidates array');
704
+ }
705
+ // Extract resourceTypeName from the first candidate (all candidates for the same resource should have the same type)
706
+ const resourceTypeName = candidates[0].resourceTypeName;
707
+ /* c8 ignore next 3 - defense in depth */
708
+ if (!resourceTypeName) {
709
+ return (0, ts_utils_1.fail)('resourceTypeName is required for new resource candidates');
710
+ }
711
+ for (const candidate of candidates) {
712
+ const childCandidate = {
713
+ json: candidate.json,
714
+ conditions: candidate.conditions,
715
+ isPartial: candidate.isPartial,
716
+ mergeMethod: candidate.mergeMethod
717
+ };
718
+ childCandidates.push(childCandidate);
719
+ }
720
+ // Create the new resource declaration
721
+ const newResourceDecl = {
722
+ id: resourceId,
723
+ candidates: childCandidates,
724
+ resourceTypeName
725
+ };
726
+ return (0, ts_utils_1.succeed)(newResourceDecl);
727
+ }
728
+ /**
729
+ * Reconstructs conditions from a compiled collection and adds them to the builder.
730
+ * @param builder - The builder to add conditions to.
731
+ * @param compiledCollection - The compiled collection containing conditions.
732
+ * @returns `Success` if all conditions were added successfully, `Failure` otherwise.
733
+ * @internal
734
+ */
735
+ static _reconstructConditions(builder, compiledCollection) {
736
+ const errors = new ts_utils_1.MessageAggregator();
737
+ for (const compiledCondition of compiledCollection.conditions) {
738
+ // Get the qualifier by index
739
+ const qualifierResult = builder.qualifiers.getAt(compiledCondition.qualifierIndex);
740
+ /* c8 ignore next 4 - edge case or internal error (nearly?) impossible to reproduce */
741
+ if (qualifierResult.isFailure()) {
742
+ qualifierResult.aggregateError(errors);
743
+ continue;
744
+ }
745
+ // Create condition declaration from compiled condition
746
+ const conditionDecl = {
747
+ qualifierName: qualifierResult.value.name,
748
+ operator: compiledCondition.operator,
749
+ value: compiledCondition.value,
750
+ priority: compiledCondition.priority,
751
+ scoreAsDefault: compiledCondition.scoreAsDefault
752
+ };
753
+ // Add condition to builder (it will get the next sequential index)
754
+ builder.addCondition(conditionDecl).aggregateError(errors);
755
+ }
756
+ return errors.returnOrReport((0, ts_utils_1.succeed)(true));
757
+ }
758
+ /**
759
+ * Reconstructs condition sets from a compiled collection and adds them to the builder.
760
+ * @param builder - The builder to add condition sets to.
761
+ * @param compiledCollection - The compiled collection containing condition sets.
762
+ * @returns `Success` if all condition sets were added successfully, `Failure` otherwise.
763
+ * @internal
764
+ */
765
+ static _reconstructConditionSets(builder, compiledCollection) {
766
+ const errors = new ts_utils_1.MessageAggregator();
767
+ for (const compiledConditionSet of compiledCollection.conditionSets) {
768
+ // Get conditions by their indices
769
+ const conditionResults = compiledConditionSet.conditions.map((idx) => builder._conditions.getAt(idx));
770
+ // Check for any failures
771
+ const failedIndex = conditionResults.findIndex((r) => r.isFailure());
772
+ /* c8 ignore next 4 - edge case or internal error (nearly?) impossible to reproduce */
773
+ if (failedIndex >= 0) {
774
+ conditionResults[failedIndex].aggregateError(errors);
775
+ continue;
776
+ }
777
+ // Create condition set from conditions (not declarations)
778
+ const conditions = conditionResults.map((r) => r.orThrow());
779
+ // Convert conditions to declarations for addConditionSet
780
+ const conditionDecls = conditions.map((c) => c.toLooseConditionDecl());
781
+ builder.addConditionSet(conditionDecls).aggregateError(errors);
782
+ }
783
+ return errors.returnOrReport((0, ts_utils_1.succeed)(true));
784
+ }
785
+ /**
786
+ * Reconstructs decisions from a compiled collection and adds them to the builder.
787
+ * @param builder - The builder to add decisions to.
788
+ * @param compiledCollection - The compiled collection containing decisions.
789
+ * @returns `Success` if all decisions were added successfully, `Failure` otherwise.
790
+ * @internal
791
+ */
792
+ static _reconstructDecisions(builder, compiledCollection) {
793
+ const errors = new ts_utils_1.MessageAggregator();
794
+ for (const compiledDecision of compiledCollection.decisions) {
795
+ // Get condition sets by their indices
796
+ const conditionSetResults = compiledDecision.conditionSets.map((idx) => builder._conditionSets.getAt(idx));
797
+ // Check for any failures
798
+ const failedIndex = conditionSetResults.findIndex((r) => r.isFailure());
799
+ if (failedIndex >= 0) {
800
+ conditionSetResults[failedIndex].aggregateError(errors);
801
+ continue;
802
+ }
803
+ // Get condition sets from successful results
804
+ const conditionSets = conditionSetResults.map((r) => r.orThrow());
805
+ // Create AbstractDecision from condition sets and add to collector
806
+ decisions_1.AbstractDecision.createAbstractDecision({ conditionSets })
807
+ .onSuccess((decision) => builder._decisions.getOrAdd(decision))
808
+ .aggregateError(errors);
809
+ }
810
+ return errors.returnOrReport((0, ts_utils_1.succeed)(true));
811
+ }
812
+ /**
813
+ * Reconstructs resources and their candidates from a compiled collection and adds them to the builder.
814
+ * @param builder - The builder to add resources to.
815
+ * @param compiledCollection - The compiled collection containing resources.
816
+ * @returns `Success` if all resources were added successfully, `Failure` otherwise.
817
+ * @internal
818
+ */
819
+ static _reconstructResources(builder, compiledCollection) {
820
+ const errors = new ts_utils_1.MessageAggregator();
821
+ for (const compiledResource of compiledCollection.resources) {
822
+ // Get the resource type by index
823
+ const resourceTypeResult = builder.resourceTypes.getAt(compiledResource.type);
824
+ /* c8 ignore next 4 - edge case or internal error (nearly?) impossible to reproduce */
825
+ if (resourceTypeResult.isFailure()) {
826
+ resourceTypeResult.aggregateError(errors);
827
+ continue;
828
+ }
829
+ // Get the decision by index
830
+ const decisionResult = builder._decisions.getAt(compiledResource.decision);
831
+ /* c8 ignore next 4 - edge case or internal error (nearly?) impossible to reproduce */
832
+ if (decisionResult.isFailure()) {
833
+ decisionResult.aggregateError(errors);
834
+ continue;
835
+ }
836
+ const decision = decisionResult.value;
837
+ const resourceType = resourceTypeResult.value;
838
+ // Create candidates from the decision's condition sets
839
+ ResourceManagerBuilder._createCandidatesFromDecision(compiledResource, decision, resourceType, builder).aggregateError(errors);
840
+ }
841
+ return errors.returnOrReport((0, ts_utils_1.succeed)(true));
842
+ }
843
+ /**
844
+ * Helper method to create candidates from a decision's condition sets.
845
+ * @param compiledResource - The compiled resource containing candidates.
846
+ * @param decision - The decision containing condition sets.
847
+ * @param resourceType - The resource type for the candidates.
848
+ * @param builder - The builder to add candidates to.
849
+ * @returns `Success` if all candidates were added successfully, `Failure` otherwise.
850
+ * @internal
851
+ */
852
+ static _createCandidatesFromDecision(compiledResource, decision, resourceType, builder) {
853
+ var _a;
854
+ const errors = new ts_utils_1.MessageAggregator();
855
+ // Match each candidate to its corresponding condition set
856
+ for (let i = 0; i < compiledResource.candidates.length; i++) {
857
+ const candidate = compiledResource.candidates[i];
858
+ // Build conditions from the corresponding condition set (if available)
859
+ let conditions;
860
+ if (i < decision.candidates.length) {
861
+ const decisionCandidate = decision.candidates[i];
862
+ conditions = {};
863
+ for (const condition of decisionCandidate.conditionSet.conditions) {
864
+ conditions[condition.qualifier.name] = condition.value;
865
+ }
866
+ /* c8 ignore next 3 - defense in depth */
867
+ if (Object.keys(conditions).length === 0) {
868
+ conditions = undefined;
869
+ }
870
+ }
871
+ // Convert json value to JsonObject, handling undefined case
872
+ /* c8 ignore next 1 - defense in depth */
873
+ const rawJson = (_a = candidate.json) !== null && _a !== void 0 ? _a : {};
874
+ ts_json_base_1.Converters.jsonObject
875
+ .convert(rawJson)
876
+ .onSuccess((json) => {
877
+ const candidateDecl = {
878
+ id: compiledResource.id,
879
+ json,
880
+ conditions,
881
+ isPartial: candidate.isPartial,
882
+ mergeMethod: candidate.mergeMethod,
883
+ resourceTypeName: resourceType.key
884
+ };
885
+ return builder.addLooseCandidate(candidateDecl).aggregateError(errors);
886
+ })
887
+ .aggregateError(errors);
888
+ }
889
+ return errors.returnOrReport((0, ts_utils_1.succeed)(true));
890
+ }
449
891
  }
450
892
  exports.ResourceManagerBuilder = ResourceManagerBuilder;
451
893
  //# sourceMappingURL=resourceManagerBuilder.js.map