@fgv/ts-res 5.0.1-9 → 5.0.1

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 (162) hide show
  1. package/dist/index.browser.js +53 -0
  2. package/dist/index.js +45 -0
  3. package/dist/packlets/bundle/bundleBuilder.js +130 -0
  4. package/dist/packlets/bundle/bundleLoader.js +101 -0
  5. package/dist/packlets/bundle/bundleNormalizer.js +138 -0
  6. package/dist/packlets/bundle/bundleUtils.js +113 -0
  7. package/dist/packlets/bundle/convert.js +75 -0
  8. package/dist/packlets/bundle/index.js +42 -0
  9. package/dist/packlets/bundle/model.js +23 -0
  10. package/dist/packlets/common/conditions.js +47 -0
  11. package/dist/packlets/common/convert.js +172 -0
  12. package/dist/packlets/common/helpers/conditions.js +66 -0
  13. package/dist/packlets/common/helpers/context.js +70 -0
  14. package/dist/packlets/common/helpers/index.js +26 -0
  15. package/dist/packlets/common/helpers/qualifierDefaultValues.js +66 -0
  16. package/dist/packlets/common/helpers/resources.js +93 -0
  17. package/dist/packlets/common/index.js +28 -0
  18. package/dist/packlets/common/resources.js +27 -0
  19. package/dist/packlets/common/validate/conditions.js +544 -0
  20. package/dist/packlets/common/validate/index.js +26 -0
  21. package/dist/packlets/common/validate/regularExpressions.js +84 -0
  22. package/dist/packlets/common/validate/resources.js +209 -0
  23. package/dist/packlets/conditions/condition.js +252 -0
  24. package/dist/packlets/conditions/conditionCollector.js +69 -0
  25. package/dist/packlets/conditions/conditionDecls.js +23 -0
  26. package/dist/packlets/conditions/conditionSet.js +247 -0
  27. package/dist/packlets/conditions/conditionSetCollector.js +89 -0
  28. package/dist/packlets/conditions/conditionSetDecls.js +23 -0
  29. package/dist/packlets/conditions/conditionToken.js +147 -0
  30. package/dist/packlets/conditions/convert/conditionSetDecls.js +51 -0
  31. package/dist/packlets/conditions/convert/decls.js +75 -0
  32. package/dist/packlets/conditions/convert/index.js +24 -0
  33. package/dist/packlets/conditions/index.js +31 -0
  34. package/dist/packlets/config/common.js +78 -0
  35. package/dist/packlets/config/configInitFactory.js +258 -0
  36. package/dist/packlets/config/convert.js +56 -0
  37. package/dist/packlets/config/index.browser.js +34 -0
  38. package/dist/packlets/config/index.js +28 -0
  39. package/dist/packlets/config/json.js +23 -0
  40. package/dist/packlets/config/predefined/default.js +138 -0
  41. package/dist/packlets/config/predefined/extended.js +190 -0
  42. package/dist/packlets/config/predefined/index.js +25 -0
  43. package/dist/packlets/config/systemConfiguration.js +147 -0
  44. package/dist/packlets/context/contextDecls.js +23 -0
  45. package/dist/packlets/context/contextToken.js +202 -0
  46. package/dist/packlets/context/convert/decls.js +91 -0
  47. package/dist/packlets/context/convert/index.js +23 -0
  48. package/dist/packlets/context/index.js +26 -0
  49. package/dist/packlets/decisions/abstractDecision.js +68 -0
  50. package/dist/packlets/decisions/abstractDecisionCollector.js +90 -0
  51. package/dist/packlets/decisions/candidate.js +76 -0
  52. package/dist/packlets/decisions/common.js +23 -0
  53. package/dist/packlets/decisions/concreteDecision.js +111 -0
  54. package/dist/packlets/decisions/decision.js +126 -0
  55. package/dist/packlets/decisions/index.js +28 -0
  56. package/dist/packlets/import/fsItem.js +134 -0
  57. package/dist/packlets/import/importContext.js +129 -0
  58. package/dist/packlets/import/importManager.js +129 -0
  59. package/dist/packlets/import/importable.js +32 -0
  60. package/dist/packlets/import/importers/collectionImporter.js +118 -0
  61. package/dist/packlets/import/importers/fsItemImporter.js +116 -0
  62. package/dist/packlets/import/importers/importer.js +23 -0
  63. package/dist/packlets/import/importers/index.browser.js +29 -0
  64. package/dist/packlets/import/importers/index.js +27 -0
  65. package/dist/packlets/import/importers/jsonImporter.js +94 -0
  66. package/dist/packlets/import/importers/pathImporter.js +84 -0
  67. package/dist/packlets/import/index.browser.js +34 -0
  68. package/dist/packlets/import/index.js +28 -0
  69. package/dist/packlets/qualifier-types/config/convert.js +124 -0
  70. package/dist/packlets/qualifier-types/config/index.js +25 -0
  71. package/dist/packlets/qualifier-types/config/json.js +32 -0
  72. package/dist/packlets/qualifier-types/convert.js +56 -0
  73. package/dist/packlets/qualifier-types/helpers.js +82 -0
  74. package/dist/packlets/qualifier-types/index.js +32 -0
  75. package/dist/packlets/qualifier-types/languageQualifierType.js +142 -0
  76. package/dist/packlets/qualifier-types/literalQualifierType.js +200 -0
  77. package/dist/packlets/qualifier-types/literalValueHierarchy.js +236 -0
  78. package/dist/packlets/qualifier-types/qualifierType.js +184 -0
  79. package/dist/packlets/qualifier-types/qualifierTypeCollector.js +66 -0
  80. package/dist/packlets/qualifier-types/territoryQualifierType.js +200 -0
  81. package/dist/packlets/qualifiers/convert/decls.js +70 -0
  82. package/dist/packlets/qualifiers/convert/index.js +24 -0
  83. package/dist/packlets/qualifiers/convert/qualifier.js +40 -0
  84. package/dist/packlets/qualifiers/index.js +29 -0
  85. package/dist/packlets/qualifiers/qualifier.js +108 -0
  86. package/dist/packlets/qualifiers/qualifierCollector.js +123 -0
  87. package/dist/packlets/qualifiers/qualifierDecl.js +23 -0
  88. package/dist/packlets/qualifiers/qualifierDefaultValueDecls.js +23 -0
  89. package/dist/packlets/qualifiers/qualifierDefaultValueToken.js +175 -0
  90. package/dist/packlets/resource-json/compiled/common.js +23 -0
  91. package/dist/packlets/resource-json/compiled/convert.js +132 -0
  92. package/dist/packlets/resource-json/compiled/index.js +26 -0
  93. package/dist/packlets/resource-json/compiled/json.js +2 -0
  94. package/dist/packlets/resource-json/convert.js +171 -0
  95. package/dist/packlets/resource-json/helpers.js +241 -0
  96. package/dist/packlets/resource-json/index.js +31 -0
  97. package/dist/packlets/resource-json/json.js +36 -0
  98. package/dist/packlets/resource-json/normalized.js +23 -0
  99. package/dist/packlets/resource-json/resourceDeclCollection.js +88 -0
  100. package/dist/packlets/resource-json/resourceDeclContainer.js +23 -0
  101. package/dist/packlets/resource-json/resourceDeclTree.js +94 -0
  102. package/dist/packlets/resource-types/config/convert.js +35 -0
  103. package/dist/packlets/resource-types/config/index.js +25 -0
  104. package/dist/packlets/resource-types/config/json.js +23 -0
  105. package/dist/packlets/resource-types/helpers.js +42 -0
  106. package/dist/packlets/resource-types/index.js +28 -0
  107. package/dist/packlets/resource-types/jsonResourceType.js +66 -0
  108. package/dist/packlets/resource-types/resourceType.js +95 -0
  109. package/dist/packlets/resource-types/resourceTypeCollector.js +61 -0
  110. package/dist/packlets/resources/candidateReducer.js +246 -0
  111. package/dist/packlets/resources/candidateValue.js +92 -0
  112. package/dist/packlets/resources/candidateValueCollector.js +94 -0
  113. package/dist/packlets/resources/common.js +23 -0
  114. package/dist/packlets/resources/deltaGenerator.js +338 -0
  115. package/dist/packlets/resources/index.js +31 -0
  116. package/dist/packlets/resources/resource.js +207 -0
  117. package/dist/packlets/resources/resourceBuilder.js +183 -0
  118. package/dist/packlets/resources/resourceCandidate.js +216 -0
  119. package/dist/packlets/resources/resourceManagerBuilder.js +890 -0
  120. package/dist/packlets/runtime/cacheListener.js +58 -0
  121. package/dist/packlets/runtime/cacheMetrics.js +149 -0
  122. package/dist/packlets/runtime/compiledResourceCollection.js +473 -0
  123. package/dist/packlets/runtime/conditionSetResolutionResult.js +134 -0
  124. package/dist/packlets/runtime/context/contextQualifierProvider.js +29 -0
  125. package/dist/packlets/runtime/context/contextQualifierProviderValidator.js +146 -0
  126. package/dist/packlets/runtime/context/index.js +26 -0
  127. package/dist/packlets/runtime/context/simpleContextQualifierProvider.js +196 -0
  128. package/dist/packlets/runtime/context/validatingSimpleContextQualifierProvider.js +60 -0
  129. package/dist/packlets/runtime/iResourceManager.js +23 -0
  130. package/dist/packlets/runtime/index.js +34 -0
  131. package/dist/packlets/runtime/resource-tree/common.js +23 -0
  132. package/dist/packlets/runtime/resource-tree/index.js +26 -0
  133. package/dist/packlets/runtime/resource-tree/readOnlyResourceTree.js +216 -0
  134. package/dist/packlets/runtime/resource-tree/resourceTreeChildren.js +97 -0
  135. package/dist/packlets/runtime/resource-tree/resourceTreeChildrenValidator.js +161 -0
  136. package/dist/packlets/runtime/resourceResolver.js +481 -0
  137. package/dist/packlets/runtime/resourceTreeResolver.js +220 -0
  138. package/dist/packlets/runtime/validate.js +47 -0
  139. package/dist/packlets/zip-archive/convert.js +100 -0
  140. package/dist/packlets/zip-archive/index.browser.js +54 -0
  141. package/dist/packlets/zip-archive/index.js +47 -0
  142. package/dist/packlets/zip-archive/json.js +23 -0
  143. package/dist/packlets/zip-archive/types.js +36 -0
  144. package/dist/packlets/zip-archive/zipArchiveCreator.js +191 -0
  145. package/dist/packlets/zip-archive/zipArchiveFormat.js +140 -0
  146. package/dist/packlets/zip-archive/zipArchiveLoader.js +282 -0
  147. package/dist/test/data/sample.json +32 -0
  148. package/dist/test/unit/qualifier-types/testQualifierType.js +76 -0
  149. package/dist/test/unit/resource-types/testDerivedResourceType.js +109 -0
  150. package/dist/test/unit/resources/deltaGenerator.helpers.js +282 -0
  151. package/dist/tsdoc-metadata.json +1 -1
  152. package/lib/index.browser.d.ts +24 -0
  153. package/lib/index.browser.js +116 -0
  154. package/lib/packlets/config/index.browser.d.ts +7 -0
  155. package/lib/packlets/config/index.browser.js +74 -0
  156. package/lib/packlets/import/importers/index.browser.d.ts +4 -0
  157. package/lib/packlets/import/importers/index.browser.js +45 -0
  158. package/lib/packlets/import/index.browser.d.ts +7 -0
  159. package/lib/packlets/import/index.browser.js +74 -0
  160. package/lib/packlets/zip-archive/index.browser.d.ts +27 -0
  161. package/lib/packlets/zip-archive/index.browser.js +102 -0
  162. package/package.json +21 -7
@@ -0,0 +1,890 @@
1
+ /*
2
+ * Copyright (c) 2025 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { captureResult, Collections, fail, failWithDetail, Hash, mapResults, MessageAggregator, succeed, succeedWithDetail, ValidatingResultMap } from '@fgv/ts-utils';
23
+ import { Converters as JsonConverters } from '@fgv/ts-json-base';
24
+ import { ConditionCollector, ConditionSetCollector, Convert as ConditionsConvert, Condition, ConditionSet } from '../conditions';
25
+ import { AbstractDecisionCollector, AbstractDecision } from '../decisions';
26
+ import { Convert, Validate } from '../common';
27
+ import { ResourceTree } from '../runtime';
28
+ import { ResourceBuilder } from './resourceBuilder';
29
+ import { Resource } from './resource';
30
+ import { CandidateValueCollector } from './candidateValueCollector';
31
+ import * as ResourceJson from '../resource-json';
32
+ import * as Context from '../context';
33
+ import * as Config from '../config';
34
+ import { JsonEditor } from '@fgv/ts-json';
35
+ /**
36
+ * Builder for a collection of {@link Resources.Resource | resources}. Collects
37
+ * {@link Resources.ResourceCandidate | candidates} for each resource into a
38
+ * {@link Resources.ResourceBuilder | ResourceBuilder} per resource, validates them against each other,
39
+ * and builds a collection of {@link Resources.Resource | resources} once all candidates are collected.
40
+ * @public
41
+ */
42
+ export class ResourceManagerBuilder {
43
+ /**
44
+ * The {@link QualifierTypes.ReadOnlyQualifierTypeCollector | qualifier types} used by this resource manager.
45
+ */
46
+ get qualifierTypes() {
47
+ /* c8 ignore next 1 - functional code tested but coverage intermittently missed */
48
+ return this.qualifiers.qualifierTypes;
49
+ }
50
+ /**
51
+ * A {@link Conditions.ConditionCollector | ConditionCollector} which
52
+ * contains the {@link Conditions.Condition | conditions} used so far by
53
+ * the {@link Resources.ResourceCandidate | resource candidates} in this manager.
54
+ */
55
+ get conditions() {
56
+ return this._conditions;
57
+ }
58
+ /**
59
+ * The resource IDs that this resource manager can resolve.
60
+ */
61
+ get resourceIds() {
62
+ return Array.from(this._resources.keys()).sort();
63
+ }
64
+ /**
65
+ * A {@link Conditions.ConditionSetCollector | ConditionSetCollector} which
66
+ * contains the {@link Conditions.ConditionSet | condition sets} used so far by
67
+ * the {@link Resources.ResourceCandidate | resource candidates} in this manager.
68
+ */
69
+ get conditionSets() {
70
+ return this._conditionSets;
71
+ }
72
+ /**
73
+ * A {@link Decisions.AbstractDecisionCollector | AbstractDecisionCollector} which
74
+ * contains the {@link Decisions.Decision | abstract decisions} used so far by
75
+ * the {@link Resources.ResourceCandidate | resource candidates} in this manager.
76
+ */
77
+ get decisions() {
78
+ return this._decisions;
79
+ }
80
+ /**
81
+ * A read-only map of {@link Resources.ResourceBuilder | resource builders} used by the manager.
82
+ */
83
+ get resources() {
84
+ return this._resources;
85
+ }
86
+ /**
87
+ * The number of {@link Resources.Resource | resources} contained by the manager.
88
+ */
89
+ get size() {
90
+ return this._resources.size;
91
+ }
92
+ /**
93
+ * {@inheritdoc Runtime.IResourceManager.numResources}
94
+ */
95
+ get numResources() {
96
+ return this._resources.size;
97
+ }
98
+ /**
99
+ * {@inheritdoc Runtime.IResourceManager.numCandidates}
100
+ */
101
+ get numCandidates() {
102
+ if (this._numCandidates === undefined) {
103
+ this._numCandidates = this.getAllCandidates().length;
104
+ }
105
+ return this._numCandidates;
106
+ }
107
+ /**
108
+ * {@inheritdoc Runtime.IResourceManager.builtResources}
109
+ */
110
+ get builtResources() {
111
+ return this._performBuild().orThrow();
112
+ }
113
+ /**
114
+ * Constructor for a {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} object.
115
+ * @param params - Parameters to create a new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder}.
116
+ * @public
117
+ */
118
+ constructor(params) {
119
+ this.qualifiers = params.qualifiers;
120
+ this.resourceTypes = params.resourceTypes;
121
+ this._conditions = ConditionCollector.create({ qualifiers: params.qualifiers }).orThrow();
122
+ this._conditionSets = ConditionSetCollector.create({ conditions: this._conditions }).orThrow();
123
+ this._decisions = AbstractDecisionCollector.create({ conditionSets: this._conditionSets }).orThrow();
124
+ this._candidateValues = CandidateValueCollector.create().orThrow();
125
+ this._resources = new ValidatingResultMap({
126
+ converters: new Collections.KeyValueConverters({
127
+ key: Convert.resourceId,
128
+ /* c8 ignore next 2 - defense in depth against internal error */
129
+ value: (from) => from instanceof ResourceBuilder ? succeed(from) : fail('not a resource builder')
130
+ })
131
+ });
132
+ this._builtResources = new ValidatingResultMap({
133
+ converters: new Collections.KeyValueConverters({
134
+ key: Convert.resourceId,
135
+ /* c8 ignore next 1 - defense in depth against internal error */
136
+ value: (from) => (from instanceof Resource ? succeed(from) : fail('not a resource'))
137
+ })
138
+ });
139
+ this._built = false;
140
+ this._cachedResourceTree = undefined;
141
+ }
142
+ /**
143
+ * Creates a new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} object.
144
+ * @param params - Parameters to create a new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder}.
145
+ * @returns `Success` with the new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} object if successful,
146
+ * or `Failure` with an error message if not.
147
+ * @public
148
+ */
149
+ static create(params) {
150
+ return captureResult(() => new ResourceManagerBuilder(params));
151
+ }
152
+ /**
153
+ * Creates a new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} object from a predefined system configuration.
154
+ * @param name - The name of the predefined system configuration to use.
155
+ * @param qualifierDefaultValues - Optional default values for qualifiers.
156
+ * @returns `Success` with the new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} object if successful,
157
+ * or `Failure` with an error message if not.
158
+ * @public
159
+ */
160
+ static createPredefined(name, qualifierDefaultValues) {
161
+ return Config.getPredefinedSystemConfiguration(name,
162
+ /* c8 ignore next 1 - defense in depth */
163
+ qualifierDefaultValues ? { qualifierDefaultValues } : undefined).onSuccess((systemConfig) => {
164
+ return ResourceManagerBuilder.create({
165
+ qualifiers: systemConfig.qualifiers,
166
+ resourceTypes: systemConfig.resourceTypes
167
+ });
168
+ });
169
+ }
170
+ /**
171
+ * Creates a new {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} from a
172
+ * {@link ResourceJson.Compiled.ICompiledResourceCollection | compiled resource collection}.
173
+ * This method reconstructs an exactly equivalent builder where all qualifier, condition,
174
+ * condition set, and decision indices match the original compiled collection.
175
+ * @param compiledCollection - The compiled resource collection to reconstruct from.
176
+ * @param systemConfig - The system configuration containing qualifiers and resource types.
177
+ * @returns `Success` with the new manager if successful, or `Failure` with an error message if not.
178
+ * @public
179
+ */
180
+ static createFromCompiledResourceCollection(compiledCollection, systemConfig) {
181
+ // Create the base builder with system configuration
182
+ return ResourceManagerBuilder.create({
183
+ qualifiers: systemConfig.qualifiers,
184
+ resourceTypes: systemConfig.resourceTypes
185
+ }).onSuccess((builder) => {
186
+ // Reconstruct all entities in order to preserve indices
187
+ return ResourceManagerBuilder._reconstructConditions(builder, compiledCollection)
188
+ .onSuccess(() => ResourceManagerBuilder._reconstructConditionSets(builder, compiledCollection))
189
+ .onSuccess(() => ResourceManagerBuilder._reconstructDecisions(builder, compiledCollection))
190
+ .onSuccess(() => ResourceManagerBuilder._reconstructResources(builder, compiledCollection))
191
+ .onSuccess(() => succeed(builder));
192
+ });
193
+ }
194
+ /**
195
+ * Given a {@link ResourceJson.Json.ILooseResourceCandidateDecl | resource candidate declaration}, builds and adds
196
+ * a {@link Resources.ResourceCandidate | candidate} to the manager.
197
+ * @param candidate - The {@link Resources.ResourceCandidate | candidate} to add.
198
+ * @returns `Success` with the candidate if successful, or `Failure` with an error message if not.
199
+ * @public
200
+ */
201
+ addLooseCandidate(decl) {
202
+ const { value: id, message } = Validate.toResourceId(decl.id);
203
+ if (message !== undefined) {
204
+ return failWithDetail(`${id}: invalid id - ${message}`, 'failure');
205
+ }
206
+ const builderResult = this._resources.getOrAdd(id, () => ResourceBuilder.create({
207
+ id,
208
+ resourceTypes: this.resourceTypes,
209
+ conditionSets: this._conditionSets,
210
+ decisions: this._decisions,
211
+ candidateValues: this._candidateValues
212
+ }));
213
+ /* c8 ignore next 6 - defense in depth against internal error */
214
+ if (builderResult.isFailure()) {
215
+ return failWithDetail(`${id}: unable to get or add resource\n${builderResult.message}`, builderResult.detail);
216
+ }
217
+ return builderResult.value.addLooseCandidate(decl).onSuccess((c, d) => {
218
+ this._builtResources.delete(id);
219
+ this._built = false;
220
+ this._numCandidates = undefined;
221
+ this._cachedResourceTree = undefined;
222
+ return succeedWithDetail(c, d);
223
+ });
224
+ }
225
+ addResource(decl) {
226
+ var _a;
227
+ const { value: id, message } = Validate.toResourceId(decl.id);
228
+ /* c8 ignore next 3 - defensive coding: resource ID validation should prevent invalid IDs */
229
+ if (message !== undefined) {
230
+ return failWithDetail(`${id}: invalid id - ${message}`, 'failure');
231
+ }
232
+ const { value: builder, message: getOrAddMessage, detail } = this._resources.getOrAdd(id, () => ResourceBuilder.create({
233
+ id,
234
+ typeName: decl.resourceTypeName,
235
+ resourceTypes: this.resourceTypes,
236
+ conditionSets: this._conditionSets,
237
+ decisions: this._decisions,
238
+ candidateValues: this._candidateValues
239
+ }));
240
+ /* c8 ignore next 3 - defense in depth against internal error */
241
+ if (getOrAddMessage !== undefined) {
242
+ return failWithDetail(`${id}: unable to get or add resource\n${getOrAddMessage}`, detail);
243
+ }
244
+ if (detail === 'exists') {
245
+ /* c8 ignore next 4 - defensive coding: resource type mismatch on existing resources should not occur */
246
+ const { message } = builder.setResourceType(decl.resourceTypeName);
247
+ if (message !== undefined) {
248
+ return failWithDetail(`${id}: unable to set resource type\n${message}`, 'type-mismatch');
249
+ }
250
+ }
251
+ const candidates = (_a = decl.candidates) !== null && _a !== void 0 ? _a : [];
252
+ return mapResults(candidates.map((c) => builder.addChildCandidate(c)))
253
+ .onSuccess(() => {
254
+ return succeed(builder);
255
+ })
256
+ .withDetail('failure', detail);
257
+ }
258
+ /**
259
+ * Adds a condition to the manager.
260
+ * @param decl - The condition declaration to add.
261
+ * @returns `Success` with the condition if successful, or `Failure` with an error message if not.
262
+ * @public
263
+ */
264
+ addCondition(decl) {
265
+ return ConditionsConvert.validatedConditionDecl
266
+ .convert(decl, { qualifiers: this.qualifiers })
267
+ .onSuccess((validated) => {
268
+ return Condition.getKeyForDecl(validated).onSuccess((key) => {
269
+ return this._conditions.validating.getOrAdd(key, () => Condition.create(validated));
270
+ });
271
+ });
272
+ }
273
+ /**
274
+ * Adds a condition set to the manager.
275
+ * @param decl - The condition set declaration to add.
276
+ * @returns `Success` with the condition set if successful, or `Failure` with an error message if not.
277
+ * @public
278
+ */
279
+ addConditionSet(conditions) {
280
+ const decl = { conditions: [...conditions] };
281
+ return ConditionsConvert.validatedConditionSetDecl
282
+ .convert(decl, { conditions: this._conditions })
283
+ .onSuccess((validated) => {
284
+ return ConditionSet.getKeyForDecl(validated).onSuccess((key) => {
285
+ return this._conditionSets.validating.getOrAdd(key, () => ConditionSet.create(validated));
286
+ });
287
+ });
288
+ }
289
+ /**
290
+ * Gets a read-only array of all {@link Resources.ResourceBuilder | resource builders} present in the manager.
291
+ * @returns `Success` with the {@link Resources.ResourceBuilder | resource builder} if successful,
292
+ * or `Failure` with an error message if not.
293
+ */
294
+ getAllResources() {
295
+ return Array.from(this._resources.values()).sort((a, b) => a.id.localeCompare(b.id));
296
+ }
297
+ /**
298
+ * Gets a read-only array of all {@link Resources.ResourceCandidate | resource candidates} present in the manager.
299
+ */
300
+ getAllCandidates() {
301
+ return this.getAllResources().flatMap((r) => r.candidates);
302
+ }
303
+ /**
304
+ * Gets an individual {@link Resources.Resource | built resource} from the manager.
305
+ * @param id - The {@link ResourceId | id} of the resource to get.
306
+ * @returns `Success` with the resource if successful, or `Failure` with an error message if not.
307
+ * @public
308
+ */
309
+ getBuiltResource(id) {
310
+ return this._resources.validating
311
+ .get(id)
312
+ .onSuccess((builder) => this._builtResources.validating.getOrAdd(id, () => builder.build()));
313
+ }
314
+ /**
315
+ * Validates a context declaration against the qualifiers managed by this resource manager.
316
+ * @param context - The context declaration to validate
317
+ * @returns Success with the validated context if successful, Failure otherwise
318
+ * @public
319
+ */
320
+ /* c8 ignore next 5 - functional code path tested but coverage intermittently missed */
321
+ validateContext(context) {
322
+ return Context.Convert.validatedContextDecl.convert(context, {
323
+ qualifiers: this.qualifiers
324
+ });
325
+ }
326
+ /**
327
+ * Gets a read-only array of all {@link Resources.Resource | built resources} in the manager.
328
+ * @returns `Success` with an array of resources if successful, or `Failure` with an error message if not.
329
+ * @public
330
+ */
331
+ getAllBuiltResources() {
332
+ return this.build().onSuccess((manager) => succeed(Array.from(manager._builtResources.values()).sort((a, b) => a.id.localeCompare(b.id))));
333
+ }
334
+ /**
335
+ * Builds and returns a hierarchical tree representation of all resources managed by this builder.
336
+ * Resources are organized based on their dot-separated resource IDs (e.g., "app.messages.welcome"
337
+ * becomes a tree with "app" as root, "messages" as branch, and "welcome" as leaf).
338
+ *
339
+ * String-based validation is available through the `children.validating` property,
340
+ * allowing callers to use `tree.children.validating.getById(stringId)` for validated access.
341
+ *
342
+ * Uses lazy initialization with caching for performance.
343
+ * @returns Result containing the resource tree root, or failure if tree construction fails
344
+ * @public
345
+ */
346
+ getBuiltResourceTree() {
347
+ // Ensure resources are built first
348
+ return this.build().onSuccess((manager) => {
349
+ if (manager._cachedResourceTree) {
350
+ return succeed(manager._cachedResourceTree);
351
+ }
352
+ // Convert all built resources to [ResourceId, Resource] pairs
353
+ const resources = [];
354
+ for (const [id, resource] of manager._builtResources.entries()) {
355
+ resources.push([id, resource]);
356
+ }
357
+ // Create the resource tree with lazy initialization
358
+ return ResourceTree.ReadOnlyResourceTreeRoot.create(resources).onSuccess((tree) => {
359
+ manager._cachedResourceTree = tree;
360
+ return succeed(tree);
361
+ });
362
+ });
363
+ }
364
+ /**
365
+ * Gets a read-only array of all {@link Resources.Resource | built resources} in the manager.
366
+ * @returns `Success` with an array of resources if successful, or `Failure` with an error message if not.
367
+ * @public
368
+ */
369
+ getAllBuiltCandidates() {
370
+ return this.getAllBuiltResources().onSuccess((built) => succeed(built.flatMap((r) => r.candidates)));
371
+ }
372
+ /**
373
+ * Internal helper method that performs the actual building of resources.
374
+ * @returns `Success` with the built resources if all resources were built successfully, `Failure` otherwise.
375
+ * @internal
376
+ */
377
+ _performBuild() {
378
+ if (this._built) {
379
+ return succeed(this._builtResources);
380
+ }
381
+ const errors = new MessageAggregator();
382
+ this._resources.forEach((r, id) => {
383
+ this._builtResources.getOrAdd(id, () => r.build()).aggregateError(errors);
384
+ });
385
+ /* c8 ignore next 3 - defense in depth against internal error */
386
+ if (errors.hasMessages) {
387
+ return fail(`build failed: ${errors.toString()}`);
388
+ }
389
+ this._built = true;
390
+ return succeed(this._builtResources);
391
+ }
392
+ /**
393
+ * Builds the {@link Resources.Resource | resources} from the collected {@link Resources.ResourceCandidate | candidates}.
394
+ * @returns `Success` with the {@link Resources.ResourceManagerBuilder | ResourceManagerBuilder} object if successful,
395
+ * or `Failure` with an error message if not.
396
+ * @public
397
+ */
398
+ build() {
399
+ return this._performBuild().onSuccess(() => succeed(this));
400
+ }
401
+ /**
402
+ * Gets a read-only array of all {@link Resources.ResourceCandidate | resource candidates} that can match the supplied context.
403
+ * @param context - The {@link Context.IValidatedContextDecl | context} to match against.
404
+ * @param options - {@link Context.IContextMatchOptions | options} for the context match.
405
+ * @returns A read-only array of {@link Resources.ResourceCandidate | candidates} that can match the context.
406
+ * @public
407
+ */
408
+ getCandidatesForContext(context, options) {
409
+ return this.getAllCandidates().filter((candidate) => candidate.canMatchPartialContext(context, options));
410
+ }
411
+ /**
412
+ * Gets a read-only array of all {@link Resources.ResourceBuilder | resource builders} that have at least one candidate
413
+ * that can match the supplied context.
414
+ * @param context - The {@link Context.IValidatedContextDecl | context} to match against.
415
+ * @param options - {@link Context.IContextMatchOptions | options} for the context match.
416
+ * @returns A read-only array of {@link Resources.ResourceBuilder | resource builders} with matching candidates.
417
+ * @public
418
+ */
419
+ getResourcesForContext(context, options) {
420
+ return this.getAllResources().filter((resource) => resource.getCandidatesForContext(context, options).length > 0);
421
+ }
422
+ /**
423
+ * Gets a read-only array of all {@link Resources.ResourceCandidate | built resource candidates} that can match the supplied context.
424
+ * @param context - The {@link Context.IValidatedContextDecl | context} to match against.
425
+ * @param options - {@link Context.IContextMatchOptions | options} for the context match.
426
+ * @returns `Success` with an array of {@link Resources.ResourceCandidate | candidates} if successful, or `Failure` with an error message if not.
427
+ * @public
428
+ */
429
+ getBuiltCandidatesForContext(context, options) {
430
+ return this.getAllBuiltCandidates().onSuccess((candidates) => succeed(candidates.filter((candidate) => candidate.canMatchPartialContext(context, options))));
431
+ }
432
+ /**
433
+ * Gets a read-only array of all {@link Resources.Resource | built resources} that have at least one candidate
434
+ * that can match the supplied context.
435
+ * @param context - The {@link Context.IValidatedContextDecl | context} to match against.
436
+ * @param options - {@link Context.IContextMatchOptions | options} for the context match.
437
+ * @returns `Success` with an array of {@link Resources.Resource | resources} if successful, or `Failure` with an error message if not.
438
+ * @public
439
+ */
440
+ getBuiltResourcesForContext(context, options) {
441
+ return this.getAllBuiltResources().onSuccess((resources) => succeed(resources.filter((resource) => resource.getCandidatesForContext(context, options).length > 0)));
442
+ }
443
+ /**
444
+ * Gets a compiled resource collection from the current state of the resource manager builder.
445
+ * This method generates an optimized, index-based representation of all resources, conditions,
446
+ * and decisions that can be used for serialization or efficient runtime processing.
447
+ * @param options - Optional compilation options controlling the output format.
448
+ * @returns Success with the compiled resource collection if successful, Failure otherwise.
449
+ * @public
450
+ */
451
+ getCompiledResourceCollection(options) {
452
+ // Build resources first to ensure all data is available
453
+ const buildResult = this._performBuild();
454
+ /* c8 ignore next 3 - defensive coding: build failure should not occur after successful validation */
455
+ if (buildResult.isFailure()) {
456
+ return fail(`Failed to build resources: ${buildResult.message}`);
457
+ }
458
+ // Generate compiled data from internal collections using the new toCompiled methods
459
+ // Note: All objects have a defined index property due to the collector pattern - indices are assigned during collection building
460
+ const compiledData = {
461
+ qualifierTypes: Array.from(this.qualifiers.qualifierTypes.values()).map((qt) => ({
462
+ name: qt.name
463
+ })),
464
+ qualifiers: Array.from(this.qualifiers.values()).map((q) => ({
465
+ name: q.name,
466
+ type: q.type.index,
467
+ defaultPriority: q.defaultPriority
468
+ })),
469
+ resourceTypes: Array.from(this.resourceTypes.values()).map((rt) => ({
470
+ name: rt.key
471
+ })),
472
+ conditions: Array.from(this._conditions.values()).map((c) => c.toCompiled(options)),
473
+ conditionSets: Array.from(this._conditionSets.values()).map((cs) => cs.toCompiled(options)),
474
+ decisions: Array.from(this._decisions.values()).map((d) => d.toCompiled(options)),
475
+ candidateValues: this._candidateValues.getValuesByIndex(),
476
+ resources: Array.from(this._builtResources.values()).map((r) => r.toCompiled(options))
477
+ };
478
+ // Apply validation through the converter
479
+ return ResourceJson.Compiled.Convert.compiledResourceCollection.convert(compiledData);
480
+ }
481
+ /**
482
+ * Gets a resource collection declaration containing all built resources in a flat array structure.
483
+ * This method returns all built resources as an {@link ResourceJson.Normalized.IResourceCollectionDecl | IResourceCollectionDecl}
484
+ * that can be used for serialization, export, or re-import. Resources are sorted by ID for consistent ordering.
485
+ * @param options - Optional {@link Resources.IResourceDeclarationOptions | declaration options} controlling the output format.
486
+ * If `options.normalized` is `true`, applies hash-based normalization for additional consistency guarantees.
487
+ * @returns Success with the resource collection declaration if successful, Failure otherwise.
488
+ * @public
489
+ */
490
+ getResourceCollectionDecl(options) {
491
+ return this._performBuild().onSuccess(() => {
492
+ // Get all built resources and convert to loose resource declarations
493
+ const resources = Array.from(this._builtResources.values()).map((resource) => resource.toLooseResourceDecl(options));
494
+ // Sort resources by ID for consistent ordering
495
+ resources.sort((a, b) => a.id.localeCompare(b.id));
496
+ // Create the collection declaration structure
497
+ const collectionData = {
498
+ resources
499
+ };
500
+ // Convert and validate using the normalized converter
501
+ return ResourceJson.Convert.resourceCollectionDecl
502
+ .convert(collectionData)
503
+ .onSuccess((compiledCollection) => {
504
+ // Apply hash-based normalization only if requested
505
+ /* c8 ignore next 5 - functional code tested but coverage intermittently missed */
506
+ if ((options === null || options === void 0 ? void 0 : options.normalized) === true) {
507
+ const normalizer = new Hash.Crc32Normalizer();
508
+ return normalizer
509
+ .normalize(compiledCollection)
510
+ .withErrorFormat((e) => `Failed to normalize resource collection: ${e}`);
511
+ }
512
+ return succeed(compiledCollection);
513
+ });
514
+ });
515
+ }
516
+ /**
517
+ * Creates a clone of this ResourceManagerBuilder with optional configuration overrides.
518
+ * This method creates a new ResourceManagerBuilder that can optionally use different
519
+ * qualifiers and/or resource types than the original. It can also be filtered to include
520
+ * only candidates that match the provided context and apply candidate edits.
521
+ *
522
+ * @param options - Options for the cloning operation:
523
+ * - `qualifiers`: Optional qualifier collector to use instead of the original
524
+ * - `resourceTypes`: Optional resource type collector to use instead of the original
525
+ * - `filterForContext`: Optional context filter for candidates
526
+ * - `candidates`: Optional candidate edits to apply during cloning
527
+ * @returns A Result containing the new ResourceManagerBuilder with the specified configuration.
528
+ * @public
529
+ */
530
+ /* c8 ignore next 21 - functional code path tested but coverage intermittently missed */
531
+ clone(options) {
532
+ return this.getResourceCollectionDecl(options).onSuccess((collection) => {
533
+ var _a, _b;
534
+ return ResourceManagerBuilder.create({
535
+ qualifiers: (_a = options === null || options === void 0 ? void 0 : options.qualifiers) !== null && _a !== void 0 ? _a : this.qualifiers,
536
+ resourceTypes: (_b = options === null || options === void 0 ? void 0 : options.resourceTypes) !== null && _b !== void 0 ? _b : this.resourceTypes
537
+ }).onSuccess((newManager) => {
538
+ // Check if we have candidates to apply as edits
539
+ const editCandidates = (options === null || options === void 0 ? void 0 : options.candidates) || [];
540
+ const candidatesByResourceResult = editCandidates.length > 0
541
+ ? ResourceManagerBuilder._createCandidatesByResourceMap(editCandidates)
542
+ : succeed(new Map());
543
+ return candidatesByResourceResult.onSuccess((candidatesByResource) => {
544
+ // Track which resource IDs have been processed from the original collection
545
+ const processedResourceIds = new Set();
546
+ // Add each resource from the filtered collection to the new manager
547
+ if (collection.resources) {
548
+ for (const resourceDecl of collection.resources) {
549
+ processedResourceIds.add(resourceDecl.id);
550
+ // Apply edits if there are candidates for this resource
551
+ const editedDeclResult = ResourceManagerBuilder._applyEditsToResourceDeclaration(resourceDecl, candidatesByResource, this._conditions);
552
+ /* c8 ignore next 2 - functional code tested but coverage intermittently missed */
553
+ if (editedDeclResult.isFailure()) {
554
+ return fail(`${resourceDecl.id}: Failed to apply edits: ${editedDeclResult.message}`);
555
+ }
556
+ const addResult = newManager.addResource(editedDeclResult.value);
557
+ /* c8 ignore next 5 - edge case (nearly?) impossible to reproduce */
558
+ if (addResult.isFailure()) {
559
+ return fail(`${resourceDecl.id}: Failed to add resource to cloned manager: ${addResult.message}`);
560
+ }
561
+ }
562
+ }
563
+ // Handle any remaining candidates that target new resources not in the original collection
564
+ const errors = new MessageAggregator();
565
+ /* c8 ignore next 9 - functional code tested but coverage intermittently missed */
566
+ for (const [resourceId, candidates] of candidatesByResource) {
567
+ if (!processedResourceIds.has(resourceId)) {
568
+ // Create a new resource declaration for candidates targeting a new resource ID
569
+ ResourceManagerBuilder._createResourceDeclFromCandidates(resourceId, candidates, this._conditions)
570
+ .withErrorFormat((e) => `${resourceId}: Failed to create new resource from candidates: ${e}`)
571
+ /* c8 ignore next 7 - functional code tested but coverage intermittently missed */
572
+ .onSuccess((newResourceDecl) => {
573
+ return newManager
574
+ .addResource(newResourceDecl)
575
+ .withErrorFormat((e) => `${resourceId}: Failed to add new resource to cloned manager: ${e}`);
576
+ })
577
+ .aggregateError(errors);
578
+ }
579
+ }
580
+ return errors.returnOrReport(succeed(newManager));
581
+ });
582
+ });
583
+ });
584
+ }
585
+ /**
586
+ * Creates a resource ID keyed map from an array of loose resource candidate declarations.
587
+ * This enables efficient detection of edit collisions by grouping candidates by their target resource.
588
+ * @param candidates - Array of loose resource candidate declarations to organize
589
+ * @returns A Result containing a Map where keys are validated ResourceIds and values are arrays of candidates for that resource
590
+ * @internal
591
+ */
592
+ static _createCandidatesByResourceMap(candidates) {
593
+ const candidatesByResource = new Map();
594
+ for (const candidate of candidates) {
595
+ const { value: resourceId, message } = Validate.toResourceId(candidate.id);
596
+ if (message !== undefined) {
597
+ return fail(`Invalid resource ID "${candidate.id}": ${message}`);
598
+ }
599
+ const existingCandidates = candidatesByResource.get(resourceId);
600
+ if (existingCandidates) {
601
+ existingCandidates.push(candidate);
602
+ }
603
+ else {
604
+ candidatesByResource.set(resourceId, [candidate]);
605
+ }
606
+ }
607
+ return succeed(candidatesByResource);
608
+ }
609
+ /**
610
+ * Generates a proper ConditionSet token for collision detection using the existing ConditionSet.getKeyForDecl method.
611
+ * @param conditionSet - The condition set to generate a token for
612
+ * @param conditionCollector - The condition collector needed for validation context
613
+ * @returns A Result containing the ConditionSet token if successful, or failure if validation fails
614
+ * @internal
615
+ */
616
+ /**
617
+ * Applies candidate edits to a resource declaration, handling collisions using condition set tokens.
618
+ * If there's no collision, adds the candidate. If there's a collision, replaces the original candidate with the edit.
619
+ * @param resourceDecl - The original resource declaration to potentially modify
620
+ * @param candidatesByResource - Map of resource IDs to arrays of candidate edits
621
+ * @param conditionCollector - The condition collector needed for generating condition tokens
622
+ * @returns A Result containing the resource declaration to use (original or modified)
623
+ * @internal
624
+ */
625
+ static _applyEditsToResourceDeclaration(resourceDecl, candidatesByResource, conditionCollector) {
626
+ var _a, _b;
627
+ const { value: resourceId, message } = Validate.toResourceId(resourceDecl.id);
628
+ /* c8 ignore next 3 - defensive validation: resource IDs are validated when added to builder, but this protects against corrupted data */
629
+ if (message !== undefined) {
630
+ return fail(`Invalid resource ID "${resourceDecl.id}": ${message}`);
631
+ }
632
+ /* c8 ignore next 4 - functional code tested but coverage intermittently missed */
633
+ const editCandidates = candidatesByResource.get(resourceId);
634
+ if (!editCandidates || editCandidates.length === 0) {
635
+ return succeed(resourceDecl);
636
+ }
637
+ // Use Map approach: apply original candidates first, then replace with edits on collision
638
+ const candidatesByConditionKey = new Map();
639
+ /* c8 ignore next 1 - ?? is defense in depth */
640
+ const declCandidates = (_a = resourceDecl.candidates) !== null && _a !== void 0 ? _a : [];
641
+ // First, add all original candidates keyed by their condition set token
642
+ for (const candidate of declCandidates) {
643
+ const conditionTokenResult = ConditionSet.getKeyFromLooseDecl(candidate.conditions, conditionCollector);
644
+ /* c8 ignore next 5 - edge case or internal error (nearly?) impossible to reproduce */
645
+ if (conditionTokenResult.isFailure()) {
646
+ return fail(`Failed to generate condition token for original candidate: ${conditionTokenResult.message}`);
647
+ }
648
+ candidatesByConditionKey.set(conditionTokenResult.value, candidate);
649
+ }
650
+ // Then, apply edits (this replaces any colliding original candidates)
651
+ // Convert edit candidates (which have ids) to child candidates (without ids) for merging
652
+ /* c8 ignore next 37 - functional code tested but coverage intermittently missed */
653
+ for (const editCandidate of editCandidates) {
654
+ const conditionTokenResult = ConditionSet.getKeyFromLooseDecl(editCandidate.conditions, conditionCollector);
655
+ if (conditionTokenResult.isFailure()) {
656
+ return fail(`Failed to generate condition token for edit candidate: ${conditionTokenResult.message}`);
657
+ }
658
+ let editedJson = editCandidate.json;
659
+ const previousJson = (_b = candidatesByConditionKey.get(conditionTokenResult.value)) === null || _b === void 0 ? void 0 : _b.json;
660
+ if (previousJson && previousJson !== editedJson) {
661
+ editedJson = JsonEditor.create({
662
+ merge: {
663
+ arrayMergeBehavior: 'replace',
664
+ nullAsDelete: false
665
+ }
666
+ })
667
+ .onSuccess((editor) => {
668
+ return editor.mergeObjectsInPlace({}, [previousJson, editedJson]);
669
+ })
670
+ .orThrow();
671
+ }
672
+ const childCandidate = {
673
+ json: editedJson,
674
+ conditions: editCandidate.conditions,
675
+ isPartial: editCandidate.isPartial,
676
+ mergeMethod: editCandidate.mergeMethod
677
+ };
678
+ candidatesByConditionKey.set(conditionTokenResult.value, childCandidate);
679
+ }
680
+ // Extract the final merged candidate list
681
+ const mergedCandidates = Array.from(candidatesByConditionKey.values());
682
+ const modifiedDecl = Object.assign(Object.assign({}, resourceDecl), { candidates: mergedCandidates });
683
+ return succeed(modifiedDecl);
684
+ }
685
+ /**
686
+ * Creates a new resource declaration from an array of candidate declarations.
687
+ * This is used when cloning to create new resources that don't exist in the original manager.
688
+ * @param resourceId - The validated resource ID for the new resource
689
+ * @param candidates - Array of loose candidate declarations for the new resource
690
+ * @param conditionCollector - The condition collector for validation context
691
+ * @returns A Result containing the new resource declaration if successful, or failure if validation fails
692
+ * @internal
693
+ */
694
+ static _createResourceDeclFromCandidates(resourceId, candidates, conditionCollector) {
695
+ // Convert candidate declarations to child candidate declarations
696
+ const childCandidates = [];
697
+ // Ensure we have candidates
698
+ /* c8 ignore next 3 - defense in depth against internal error */
699
+ if (candidates.length === 0) {
700
+ return fail('Cannot create resource declaration from empty candidates array');
701
+ }
702
+ // Extract resourceTypeName from the first candidate (all candidates for the same resource should have the same type)
703
+ const resourceTypeName = candidates[0].resourceTypeName;
704
+ /* c8 ignore next 3 - defense in depth */
705
+ if (!resourceTypeName) {
706
+ return fail('resourceTypeName is required for new resource candidates');
707
+ }
708
+ for (const candidate of candidates) {
709
+ const childCandidate = {
710
+ json: candidate.json,
711
+ conditions: candidate.conditions,
712
+ isPartial: candidate.isPartial,
713
+ mergeMethod: candidate.mergeMethod
714
+ };
715
+ childCandidates.push(childCandidate);
716
+ }
717
+ // Create the new resource declaration
718
+ const newResourceDecl = {
719
+ id: resourceId,
720
+ candidates: childCandidates,
721
+ resourceTypeName
722
+ };
723
+ return succeed(newResourceDecl);
724
+ }
725
+ /**
726
+ * Reconstructs conditions from a compiled collection and adds them to the builder.
727
+ * @param builder - The builder to add conditions to.
728
+ * @param compiledCollection - The compiled collection containing conditions.
729
+ * @returns `Success` if all conditions were added successfully, `Failure` otherwise.
730
+ * @internal
731
+ */
732
+ static _reconstructConditions(builder, compiledCollection) {
733
+ const errors = new MessageAggregator();
734
+ for (const compiledCondition of compiledCollection.conditions) {
735
+ // Get the qualifier by index
736
+ const qualifierResult = builder.qualifiers.getAt(compiledCondition.qualifierIndex);
737
+ /* c8 ignore next 4 - edge case or internal error (nearly?) impossible to reproduce */
738
+ if (qualifierResult.isFailure()) {
739
+ qualifierResult.aggregateError(errors);
740
+ continue;
741
+ }
742
+ // Create condition declaration from compiled condition
743
+ const conditionDecl = {
744
+ qualifierName: qualifierResult.value.name,
745
+ operator: compiledCondition.operator,
746
+ value: compiledCondition.value,
747
+ priority: compiledCondition.priority,
748
+ scoreAsDefault: compiledCondition.scoreAsDefault
749
+ };
750
+ // Add condition to builder (it will get the next sequential index)
751
+ builder.addCondition(conditionDecl).aggregateError(errors);
752
+ }
753
+ return errors.returnOrReport(succeed(true));
754
+ }
755
+ /**
756
+ * Reconstructs condition sets from a compiled collection and adds them to the builder.
757
+ * @param builder - The builder to add condition sets to.
758
+ * @param compiledCollection - The compiled collection containing condition sets.
759
+ * @returns `Success` if all condition sets were added successfully, `Failure` otherwise.
760
+ * @internal
761
+ */
762
+ static _reconstructConditionSets(builder, compiledCollection) {
763
+ const errors = new MessageAggregator();
764
+ for (const compiledConditionSet of compiledCollection.conditionSets) {
765
+ // Get conditions by their indices
766
+ const conditionResults = compiledConditionSet.conditions.map((idx) => builder._conditions.getAt(idx));
767
+ // Check for any failures
768
+ const failedIndex = conditionResults.findIndex((r) => r.isFailure());
769
+ /* c8 ignore next 4 - edge case or internal error (nearly?) impossible to reproduce */
770
+ if (failedIndex >= 0) {
771
+ conditionResults[failedIndex].aggregateError(errors);
772
+ continue;
773
+ }
774
+ // Create condition set from conditions (not declarations)
775
+ const conditions = conditionResults.map((r) => r.orThrow());
776
+ // Convert conditions to declarations for addConditionSet
777
+ const conditionDecls = conditions.map((c) => c.toLooseConditionDecl());
778
+ builder.addConditionSet(conditionDecls).aggregateError(errors);
779
+ }
780
+ return errors.returnOrReport(succeed(true));
781
+ }
782
+ /**
783
+ * Reconstructs decisions from a compiled collection and adds them to the builder.
784
+ * @param builder - The builder to add decisions to.
785
+ * @param compiledCollection - The compiled collection containing decisions.
786
+ * @returns `Success` if all decisions were added successfully, `Failure` otherwise.
787
+ * @internal
788
+ */
789
+ static _reconstructDecisions(builder, compiledCollection) {
790
+ const errors = new MessageAggregator();
791
+ for (const compiledDecision of compiledCollection.decisions) {
792
+ // Get condition sets by their indices
793
+ const conditionSetResults = compiledDecision.conditionSets.map((idx) => builder._conditionSets.getAt(idx));
794
+ // Check for any failures
795
+ const failedIndex = conditionSetResults.findIndex((r) => r.isFailure());
796
+ if (failedIndex >= 0) {
797
+ conditionSetResults[failedIndex].aggregateError(errors);
798
+ continue;
799
+ }
800
+ // Get condition sets from successful results
801
+ const conditionSets = conditionSetResults.map((r) => r.orThrow());
802
+ // Create AbstractDecision from condition sets and add to collector
803
+ AbstractDecision.createAbstractDecision({ conditionSets })
804
+ .onSuccess((decision) => builder._decisions.getOrAdd(decision))
805
+ .aggregateError(errors);
806
+ }
807
+ return errors.returnOrReport(succeed(true));
808
+ }
809
+ /**
810
+ * Reconstructs resources and their candidates from a compiled collection and adds them to the builder.
811
+ * @param builder - The builder to add resources to.
812
+ * @param compiledCollection - The compiled collection containing resources.
813
+ * @returns `Success` if all resources were added successfully, `Failure` otherwise.
814
+ * @internal
815
+ */
816
+ static _reconstructResources(builder, compiledCollection) {
817
+ const errors = new MessageAggregator();
818
+ for (const compiledResource of compiledCollection.resources) {
819
+ // Get the resource type by index
820
+ const resourceTypeResult = builder.resourceTypes.getAt(compiledResource.type);
821
+ /* c8 ignore next 4 - edge case or internal error (nearly?) impossible to reproduce */
822
+ if (resourceTypeResult.isFailure()) {
823
+ resourceTypeResult.aggregateError(errors);
824
+ continue;
825
+ }
826
+ // Get the decision by index
827
+ const decisionResult = builder._decisions.getAt(compiledResource.decision);
828
+ /* c8 ignore next 4 - edge case or internal error (nearly?) impossible to reproduce */
829
+ if (decisionResult.isFailure()) {
830
+ decisionResult.aggregateError(errors);
831
+ continue;
832
+ }
833
+ const decision = decisionResult.value;
834
+ const resourceType = resourceTypeResult.value;
835
+ // Create candidates from the decision's condition sets
836
+ ResourceManagerBuilder._createCandidatesFromDecision(compiledResource, decision, resourceType, builder, compiledCollection.candidateValues).aggregateError(errors);
837
+ }
838
+ return errors.returnOrReport(succeed(true));
839
+ }
840
+ /**
841
+ * Helper method to create candidates from a decision's condition sets.
842
+ * @param compiledResource - The compiled resource containing candidates.
843
+ * @param decision - The decision containing condition sets.
844
+ * @param resourceType - The resource type for the candidates.
845
+ * @param builder - The builder to add candidates to.
846
+ * @param candidateValues - Array of candidate values indexed by valueIndex.
847
+ * @returns `Success` if all candidates were added successfully, `Failure` otherwise.
848
+ * @internal
849
+ */
850
+ static _createCandidatesFromDecision(compiledResource, decision, resourceType, builder, candidateValues) {
851
+ var _a;
852
+ const errors = new MessageAggregator();
853
+ // Match each candidate to its corresponding condition set
854
+ for (let i = 0; i < compiledResource.candidates.length; i++) {
855
+ const candidate = compiledResource.candidates[i];
856
+ // Build conditions from the corresponding condition set (if available)
857
+ let conditions;
858
+ if (i < decision.candidates.length) {
859
+ const decisionCandidate = decision.candidates[i];
860
+ conditions = {};
861
+ for (const condition of decisionCandidate.conditionSet.conditions) {
862
+ conditions[condition.qualifier.name] = condition.value;
863
+ }
864
+ /* c8 ignore next 3 - defense in depth */
865
+ if (Object.keys(conditions).length === 0) {
866
+ conditions = undefined;
867
+ }
868
+ }
869
+ // Get json value from candidateValues array using valueIndex
870
+ /* c8 ignore next 1 - defense in depth */
871
+ const rawJson = (_a = candidateValues[candidate.valueIndex]) !== null && _a !== void 0 ? _a : {};
872
+ JsonConverters.jsonObject
873
+ .convert(rawJson)
874
+ .onSuccess((json) => {
875
+ const candidateDecl = {
876
+ id: compiledResource.id,
877
+ json,
878
+ conditions,
879
+ isPartial: candidate.isPartial,
880
+ mergeMethod: candidate.mergeMethod,
881
+ resourceTypeName: resourceType.key
882
+ };
883
+ return builder.addLooseCandidate(candidateDecl).aggregateError(errors);
884
+ })
885
+ .aggregateError(errors);
886
+ }
887
+ return errors.returnOrReport(succeed(true));
888
+ }
889
+ }
890
+ //# sourceMappingURL=resourceManagerBuilder.js.map