@fgv/ts-json 1.9.6 → 2.0.2-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ts-json.d.ts +1826 -0
- package/dist/tsdoc-metadata.json +11 -0
- package/lib/index.d.ts +5 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +42 -0
- package/lib/index.js.map +1 -0
- package/lib/packlets/context/compositeJsonMap.d.ts +60 -0
- package/lib/packlets/context/compositeJsonMap.d.ts.map +1 -0
- package/lib/packlets/context/compositeJsonMap.js +105 -0
- package/lib/packlets/context/compositeJsonMap.js.map +1 -0
- package/lib/packlets/context/contextHelpers.d.ts +116 -0
- package/lib/packlets/context/contextHelpers.d.ts.map +1 -0
- package/lib/packlets/context/contextHelpers.js +191 -0
- package/lib/packlets/context/contextHelpers.js.map +1 -0
- package/lib/packlets/context/index.d.ts +4 -0
- package/lib/packlets/context/index.d.ts.map +1 -0
- package/lib/packlets/context/index.js +31 -0
- package/lib/packlets/context/index.js.map +1 -0
- package/lib/packlets/context/jsonContext.d.ts +84 -0
- package/lib/packlets/context/jsonContext.d.ts.map +1 -0
- package/lib/packlets/context/jsonContext.js +41 -0
- package/lib/packlets/context/jsonContext.js.map +1 -0
- package/lib/packlets/converters/converters.d.ts +54 -0
- package/lib/packlets/converters/converters.d.ts.map +1 -0
- package/lib/packlets/converters/converters.js +105 -0
- package/lib/packlets/converters/converters.js.map +1 -0
- package/lib/packlets/converters/file.d.ts +83 -0
- package/lib/packlets/converters/file.d.ts.map +1 -0
- package/lib/packlets/converters/file.js +162 -0
- package/lib/packlets/converters/file.js.map +1 -0
- package/lib/packlets/converters/index.d.ts +5 -0
- package/lib/packlets/converters/index.d.ts.map +1 -0
- package/lib/packlets/converters/index.js +56 -0
- package/lib/packlets/converters/index.js.map +1 -0
- package/lib/packlets/converters/jsonConverter.d.ts +276 -0
- package/lib/packlets/converters/jsonConverter.d.ts.map +1 -0
- package/lib/packlets/converters/jsonConverter.js +310 -0
- package/lib/packlets/converters/jsonConverter.js.map +1 -0
- package/lib/packlets/editor/common.d.ts +67 -0
- package/lib/packlets/editor/common.d.ts.map +1 -0
- package/lib/packlets/editor/common.js +3 -0
- package/lib/packlets/editor/common.js.map +1 -0
- package/lib/packlets/editor/index.d.ts +8 -0
- package/lib/packlets/editor/index.d.ts.map +1 -0
- package/{jsonEditor → lib/packlets/editor}/index.js +15 -9
- package/lib/packlets/editor/index.js.map +1 -0
- package/lib/packlets/editor/jsonEditor.d.ts +155 -0
- package/lib/packlets/editor/jsonEditor.d.ts.map +1 -0
- package/lib/packlets/editor/jsonEditor.js +332 -0
- package/lib/packlets/editor/jsonEditor.js.map +1 -0
- package/lib/packlets/editor/jsonEditorRule.d.ts +64 -0
- package/lib/packlets/editor/jsonEditorRule.d.ts.map +1 -0
- package/lib/packlets/editor/jsonEditorRule.js +54 -0
- package/lib/packlets/editor/jsonEditorRule.js.map +1 -0
- package/lib/packlets/editor/jsonEditorState.d.ts +125 -0
- package/lib/packlets/editor/jsonEditorState.d.ts.map +1 -0
- package/lib/packlets/editor/jsonEditorState.js +177 -0
- package/lib/packlets/editor/jsonEditorState.js.map +1 -0
- package/lib/packlets/editor/jsonReferenceMap.d.ts +303 -0
- package/lib/packlets/editor/jsonReferenceMap.d.ts.map +1 -0
- package/lib/packlets/editor/jsonReferenceMap.js +324 -0
- package/lib/packlets/editor/jsonReferenceMap.js.map +1 -0
- package/lib/packlets/editor/rules/conditional.d.ts +107 -0
- package/lib/packlets/editor/rules/conditional.d.ts.map +1 -0
- package/lib/packlets/editor/rules/conditional.js +167 -0
- package/lib/packlets/editor/rules/conditional.js.map +1 -0
- package/{jsonEditor → lib/packlets/editor}/rules/index.d.ts +1 -0
- package/lib/packlets/editor/rules/index.d.ts.map +1 -0
- package/lib/packlets/editor/rules/index.js +42 -0
- package/lib/packlets/editor/rules/index.js.map +1 -0
- package/lib/packlets/editor/rules/multivalue.d.ts +94 -0
- package/lib/packlets/editor/rules/multivalue.d.ts.map +1 -0
- package/lib/packlets/editor/rules/multivalue.js +141 -0
- package/lib/packlets/editor/rules/multivalue.js.map +1 -0
- package/lib/packlets/editor/rules/references.d.ts +69 -0
- package/lib/packlets/editor/rules/references.d.ts.map +1 -0
- package/lib/packlets/editor/rules/references.js +159 -0
- package/lib/packlets/editor/rules/references.js.map +1 -0
- package/lib/packlets/editor/rules/templates.d.ts +74 -0
- package/lib/packlets/editor/rules/templates.d.ts.map +1 -0
- package/lib/packlets/editor/rules/templates.js +127 -0
- package/lib/packlets/editor/rules/templates.js.map +1 -0
- package/lib/packlets/json/common.d.ts +85 -0
- package/lib/packlets/json/common.d.ts.map +1 -0
- package/lib/packlets/json/common.js +123 -0
- package/lib/packlets/json/common.js.map +1 -0
- package/lib/packlets/json/index.d.ts +2 -0
- package/lib/packlets/json/index.d.ts.map +1 -0
- package/lib/packlets/json/index.js +39 -0
- package/lib/packlets/json/index.js.map +1 -0
- package/package.json +58 -49
- package/common.d.ts +0 -58
- package/common.js +0 -116
- package/compositeJsonMap.d.ts +0 -47
- package/compositeJsonMap.js +0 -97
- package/contextHelpers.d.ts +0 -21
- package/contextHelpers.js +0 -101
- package/converters.d.ts +0 -37
- package/converters.js +0 -92
- package/file.d.ts +0 -60
- package/file.js +0 -140
- package/index.d.ts +0 -10
- package/index.js +0 -62
- package/jsonContext.d.ts +0 -74
- package/jsonContext.js +0 -40
- package/jsonConverter.d.ts +0 -229
- package/jsonConverter.js +0 -292
- package/jsonEditor/common.d.ts +0 -36
- package/jsonEditor/common.js +0 -3
- package/jsonEditor/index.d.ts +0 -5
- package/jsonEditor/jsonEditor.d.ts +0 -74
- package/jsonEditor/jsonEditor.js +0 -259
- package/jsonEditor/jsonEditorRule.d.ts +0 -47
- package/jsonEditor/jsonEditorRule.js +0 -44
- package/jsonEditor/jsonEditorState.d.ts +0 -24
- package/jsonEditor/jsonEditorState.js +0 -86
- package/jsonEditor/rules/conditional.d.ts +0 -84
- package/jsonEditor/rules/conditional.js +0 -146
- package/jsonEditor/rules/index.js +0 -21
- package/jsonEditor/rules/multivalue.d.ts +0 -78
- package/jsonEditor/rules/multivalue.js +0 -129
- package/jsonEditor/rules/references.d.ts +0 -62
- package/jsonEditor/rules/references.js +0 -158
- package/jsonEditor/rules/templates.d.ts +0 -56
- package/jsonEditor/rules/templates.js +0 -115
- package/jsonReferenceMap.d.ts +0 -138
- package/jsonReferenceMap.js +0 -202
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* Copyright (c) 2020 Erik Fortune
|
|
4
|
+
*
|
|
5
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
* in the Software without restriction, including without limitation the rights
|
|
8
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
* furnished to do so, subject to the following conditions:
|
|
11
|
+
*
|
|
12
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
* copies or substantial portions of the Software.
|
|
14
|
+
*
|
|
15
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
* SOFTWARE.
|
|
22
|
+
*/
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.PrefixedJsonMap = exports.SimpleJsonMap = exports.SimpleJsonMapBase = exports.PrefixKeyPolicy = exports.ReferenceMapKeyPolicy = void 0;
|
|
25
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
26
|
+
const json_1 = require("../json");
|
|
27
|
+
const jsonEditor_1 = require("./jsonEditor");
|
|
28
|
+
/**
|
|
29
|
+
* Policy object responsible for validating or correcting
|
|
30
|
+
* keys in a {@link IJsonReferenceMap | reference map}.
|
|
31
|
+
* @public
|
|
32
|
+
*/
|
|
33
|
+
class ReferenceMapKeyPolicy {
|
|
34
|
+
/**
|
|
35
|
+
* Constructs a new {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy}.
|
|
36
|
+
* @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options}
|
|
37
|
+
* used to construct the {@link ReferenceMapKeyPolicy}.
|
|
38
|
+
* @param isValid - An optional predicate to test a supplied key for validity.
|
|
39
|
+
*/
|
|
40
|
+
constructor(options, isValid) {
|
|
41
|
+
this._defaultOptions = options;
|
|
42
|
+
this._isValid = isValid !== null && isValid !== void 0 ? isValid : ReferenceMapKeyPolicy.defaultKeyPredicate;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The static default key name validation predicate rejects keys that contain
|
|
46
|
+
* mustache templates or which start with the default conditional prefix
|
|
47
|
+
* `'?'`.
|
|
48
|
+
* @param key - The key to test.
|
|
49
|
+
* @returns `true` if the key is valid, `false` otherwise.
|
|
50
|
+
*/
|
|
51
|
+
static defaultKeyPredicate(key) {
|
|
52
|
+
return key.length > 0 && !key.includes('{{') && !key.startsWith('?');
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Determines if a supplied key and item are valid according to the current policy.
|
|
56
|
+
* @param key - The key to be tested.
|
|
57
|
+
* @param item - The item to be tested.
|
|
58
|
+
* @returns `true` if the key and value are valid, `false` otherwise.
|
|
59
|
+
*/
|
|
60
|
+
isValid(key, item) {
|
|
61
|
+
return this._isValid(key, item);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Determines if a supplied key and item are valid according to the current policy.
|
|
65
|
+
* @param key - The key to be tested.
|
|
66
|
+
* @param item - The item to be tested.
|
|
67
|
+
* @returns `Success` with the key if valid, `Failure` with an error message if invalid.
|
|
68
|
+
*/
|
|
69
|
+
validate(key, item, __options) {
|
|
70
|
+
return this.isValid(key, item) ? (0, ts_utils_1.succeed)(key) : (0, ts_utils_1.fail)(`${key}: invalid key`);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Validates an array of entries using the validation rules for this policy.
|
|
74
|
+
* @param items - The array of entries to be validated.
|
|
75
|
+
* @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to control
|
|
76
|
+
* validation.
|
|
77
|
+
* @returns `Success` with an array of validated entries, or `Failure` with an error message
|
|
78
|
+
* if validation fails.
|
|
79
|
+
*/
|
|
80
|
+
validateItems(items, options) {
|
|
81
|
+
return (0, ts_utils_1.mapResults)(items.map((item) => {
|
|
82
|
+
return this.validate(...item, options).onSuccess((valid) => {
|
|
83
|
+
return (0, ts_utils_1.succeed)([valid, item[1]]);
|
|
84
|
+
});
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Validates a `Map\<string, T\>` using the validation rules for this policy.
|
|
89
|
+
* @param items - The `Map\<string, T\>` to be validated.
|
|
90
|
+
* @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to control
|
|
91
|
+
* validation.
|
|
92
|
+
* @returns `Success` with a new `Map\<string, T\>`, or `Failure` with an error message
|
|
93
|
+
* if validation fails.
|
|
94
|
+
*/
|
|
95
|
+
validateMap(map, options) {
|
|
96
|
+
return this.validateItems(Array.from(map.entries()), options).onSuccess((valid) => {
|
|
97
|
+
return (0, ts_utils_1.captureResult)(() => new Map(valid));
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
exports.ReferenceMapKeyPolicy = ReferenceMapKeyPolicy;
|
|
102
|
+
/**
|
|
103
|
+
* A {@link PrefixKeyPolicy | PrefixKeyPolicy} enforces that all keys start with a supplied
|
|
104
|
+
* prefix, optionally adding the prefix as necessary.
|
|
105
|
+
* @public
|
|
106
|
+
*/
|
|
107
|
+
class PrefixKeyPolicy extends ReferenceMapKeyPolicy {
|
|
108
|
+
/**
|
|
109
|
+
* Constructs a new {@link PrefixKeyPolicy | PrefixKeyPolicy}.
|
|
110
|
+
* @param prefix - The string prefix to be enforced or applied.
|
|
111
|
+
* @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to
|
|
112
|
+
* configure the policy.
|
|
113
|
+
*/
|
|
114
|
+
constructor(prefix, options) {
|
|
115
|
+
super(options);
|
|
116
|
+
this.prefix = prefix;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Determines if a key is valid according to policy.
|
|
120
|
+
* @param key - The key to be tested.
|
|
121
|
+
* @param __item - The item to be tested.
|
|
122
|
+
* @returns `true` if the key starts with the expected prefix, `false` otherwise.
|
|
123
|
+
*/
|
|
124
|
+
isValid(key, __item) {
|
|
125
|
+
return (key.startsWith(this.prefix) && key !== this.prefix && ReferenceMapKeyPolicy.defaultKeyPredicate(key));
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Determines if a key is valid according to policy, optionally coercing to a valid value by
|
|
129
|
+
* adding the required prefix.
|
|
130
|
+
* @param key - The key to be tested.
|
|
131
|
+
* @param item - The item which corresponds to the key.
|
|
132
|
+
* @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to guide
|
|
133
|
+
* validation.
|
|
134
|
+
* @returns `Success` with a valid key name if the supplied key is valid or if `makeValid` is set
|
|
135
|
+
* in the policy options. Returns `Failure` with an error message if an error occurs.
|
|
136
|
+
*/
|
|
137
|
+
validate(key, item, options) {
|
|
138
|
+
var _a;
|
|
139
|
+
/* c8 ignore next */
|
|
140
|
+
const makeValid = ((_a = (options !== null && options !== void 0 ? options : this._defaultOptions)) === null || _a === void 0 ? void 0 : _a.makeValid) === true;
|
|
141
|
+
if (this.isValid(key, item)) {
|
|
142
|
+
return (0, ts_utils_1.succeed)(key);
|
|
143
|
+
}
|
|
144
|
+
else if (makeValid && ReferenceMapKeyPolicy.defaultKeyPredicate(key)) {
|
|
145
|
+
return (0, ts_utils_1.succeed)(`${this.prefix}${key}`);
|
|
146
|
+
}
|
|
147
|
+
return (0, ts_utils_1.fail)(`${key}: invalid key`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
exports.PrefixKeyPolicy = PrefixKeyPolicy;
|
|
151
|
+
/**
|
|
152
|
+
* Abstract base class with common functionality for simple
|
|
153
|
+
* {@link IJsonReferenceMap | reference map} implementations.
|
|
154
|
+
* {@link JsonValue | json values}.
|
|
155
|
+
* @public
|
|
156
|
+
*/
|
|
157
|
+
class SimpleJsonMapBase {
|
|
158
|
+
/**
|
|
159
|
+
* Constructs a new {@link SimpleJsonMap | SimpleJsonMap}.
|
|
160
|
+
* @param values - Initial values for the map.
|
|
161
|
+
* @param context - An optional {@link IJsonContext | IJsonContext} used for any conversions
|
|
162
|
+
* involving items in this map.
|
|
163
|
+
* @param keyPolicy - The {@link ReferenceMapKeyPolicy | key policy} to use for this map.
|
|
164
|
+
* @internal
|
|
165
|
+
*/
|
|
166
|
+
constructor(values, context, keyPolicy) {
|
|
167
|
+
values = SimpleJsonMapBase._toMap(values).orThrow();
|
|
168
|
+
this._keyPolicy = keyPolicy !== null && keyPolicy !== void 0 ? keyPolicy : new ReferenceMapKeyPolicy();
|
|
169
|
+
this._values = this._keyPolicy.validateMap(values).orThrow();
|
|
170
|
+
this._context = context;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Returns a `Map\<string, T\>` derived from a supplied {@link MapOrRecord | MapOrRecord}
|
|
174
|
+
* @param values - The {@link MapOrRecord | MapOrRecord} to be returned as a map.
|
|
175
|
+
* @returns `Success` with the corresponding `Map\<string, T\>` or `Failure` with a
|
|
176
|
+
* message if an error occurs.
|
|
177
|
+
* @internal
|
|
178
|
+
*/
|
|
179
|
+
static _toMap(values) {
|
|
180
|
+
if (values === undefined) {
|
|
181
|
+
return (0, ts_utils_1.captureResult)(() => new Map());
|
|
182
|
+
}
|
|
183
|
+
else if (!(values instanceof Map)) {
|
|
184
|
+
return (0, ts_utils_1.recordToMap)(values, (__k, v) => (0, ts_utils_1.succeed)(v));
|
|
185
|
+
}
|
|
186
|
+
return (0, ts_utils_1.succeed)(values);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Determine if a key might be valid for this map but does not determine if key actually
|
|
190
|
+
* exists. Allows key range to be constrained.
|
|
191
|
+
* @param key - key to be tested
|
|
192
|
+
* @returns `true` if the key is in the valid range, `false` otherwise.
|
|
193
|
+
*/
|
|
194
|
+
keyIsInRange(key) {
|
|
195
|
+
return this._keyPolicy.isValid(key);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Determines if an entry with the specified key actually exists in the map.
|
|
199
|
+
* @param key - key to be tested
|
|
200
|
+
* @returns `true` if an object with the specified key exists, `false` otherwise.
|
|
201
|
+
*/
|
|
202
|
+
has(key) {
|
|
203
|
+
return this._values.has(key);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Gets a {@link JsonObject | JSON object} specified by key.
|
|
207
|
+
* @param key - key of the object to be retrieved
|
|
208
|
+
* @param context - optional {@link IJsonContext | JSON context} used to format the
|
|
209
|
+
* returned object.
|
|
210
|
+
* @returns {@link ts-utils#Success | `Success`} with the formatted object if successful.
|
|
211
|
+
* {@link ts-utils#Failure | `Failure`} with detail 'unknown' if no such object exists,
|
|
212
|
+
* or {@link ts-utils#Failure | `Failure`} with detail 'error' if the object was found
|
|
213
|
+
* but could not be formatted.
|
|
214
|
+
*/
|
|
215
|
+
getJsonObject(key, context) {
|
|
216
|
+
return this.getJsonValue(key, context).onSuccess((jv) => {
|
|
217
|
+
if (!(0, json_1.isJsonObject)(jv)) {
|
|
218
|
+
return (0, ts_utils_1.failWithDetail)(`${key}: not an object`, 'error');
|
|
219
|
+
}
|
|
220
|
+
return (0, ts_utils_1.succeedWithDetail)(jv);
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
exports.SimpleJsonMapBase = SimpleJsonMapBase;
|
|
225
|
+
/**
|
|
226
|
+
* A {@link SimpleJsonMap | SimpleJsonMap } presents a view of a simple map
|
|
227
|
+
* of {@link JsonValue | JSON values}.
|
|
228
|
+
* @public
|
|
229
|
+
*/
|
|
230
|
+
class SimpleJsonMap extends SimpleJsonMapBase {
|
|
231
|
+
/**
|
|
232
|
+
* Constructs a new {@link SimpleJsonMap | SimpleJsonMap} from the supplied objects
|
|
233
|
+
* @param values - A string-keyed `Map` or `Record` of the {@link JsonValue | JSON values}
|
|
234
|
+
* to be returned.
|
|
235
|
+
* @param context - Optional {@link IJsonContext | IJsonContext} used to format returned values.
|
|
236
|
+
* @param options - Optional {@link ISimpleJsonMapOptions | ISimpleJsonMapOptions} for initialization.
|
|
237
|
+
* @public
|
|
238
|
+
*/
|
|
239
|
+
constructor(values, context, options) {
|
|
240
|
+
super(values, context, options === null || options === void 0 ? void 0 : options.keyPolicy);
|
|
241
|
+
this._editor = options === null || options === void 0 ? void 0 : options.editor;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Creates a new {@link SimpleJsonMap | SimpleJsonMap} from the supplied objects
|
|
245
|
+
* @param values - A string-keyed `Map` or `Record` of the {@link JsonValue | JSON values}
|
|
246
|
+
* to be returned.
|
|
247
|
+
* @param context - Optional {@link IJsonContext | IJsonContext} used to format returned values.
|
|
248
|
+
* @param options - Optional {@link ISimpleJsonMapOptions | ISimpleJsonMapOptions} for initialization.
|
|
249
|
+
* @returns `Success` with a {@link SimpleJsonMap | SimpleJsonMap} or `Failure` with a message if
|
|
250
|
+
* an error occurs.
|
|
251
|
+
*/
|
|
252
|
+
static createSimple(values, context, options) {
|
|
253
|
+
return (0, ts_utils_1.captureResult)(() => new SimpleJsonMap(values, context, options));
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Gets a {@link JsonValue | JSON value} specified by key.
|
|
257
|
+
* @param key - key of the value to be retrieved
|
|
258
|
+
* @param context - Optional {@link IJsonContext | JSON context} used to format the value
|
|
259
|
+
* @returns Success with the formatted object if successful. Failure with detail 'unknown'
|
|
260
|
+
* if no such object exists, or failure with detail 'error' if the object was found but
|
|
261
|
+
* could not be formatted.
|
|
262
|
+
*/
|
|
263
|
+
getJsonValue(key, context) {
|
|
264
|
+
context = context !== null && context !== void 0 ? context : this._context;
|
|
265
|
+
const value = this._values.get(key);
|
|
266
|
+
if (!value) {
|
|
267
|
+
return (0, ts_utils_1.failWithDetail)(`${key}: JSON value not found`, 'unknown');
|
|
268
|
+
}
|
|
269
|
+
return this._clone(value, context);
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* @internal
|
|
273
|
+
*/
|
|
274
|
+
_clone(value, context) {
|
|
275
|
+
if (!this._editor) {
|
|
276
|
+
const result = jsonEditor_1.JsonEditor.create();
|
|
277
|
+
/* c8 ignore next 3 - nearly impossible to reproduce */
|
|
278
|
+
if (result.isFailure()) {
|
|
279
|
+
return (0, ts_utils_1.failWithDetail)(result.message, 'error');
|
|
280
|
+
}
|
|
281
|
+
this._editor = result.value;
|
|
282
|
+
}
|
|
283
|
+
return this._editor.clone(value, context).withFailureDetail('error');
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
exports.SimpleJsonMap = SimpleJsonMap;
|
|
287
|
+
/**
|
|
288
|
+
* A {@link PrefixedJsonMap | PrefixedJsonMap} enforces a supplied prefix for all contained values,
|
|
289
|
+
* optionally adding the prefix as necessary (default `true`).
|
|
290
|
+
* @public
|
|
291
|
+
*/
|
|
292
|
+
class PrefixedJsonMap extends SimpleJsonMap {
|
|
293
|
+
/**
|
|
294
|
+
* Constructs a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values
|
|
295
|
+
* @param prefix - A string prefix to be enforced for and added to key names as necessary
|
|
296
|
+
* @param values - A string-keyed Map or Record of the {@link JsonValue | JsonValue} to be returned
|
|
297
|
+
* @param context - Optional {@link IJsonContext | JSON Context} used to format returned values
|
|
298
|
+
* @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values
|
|
299
|
+
* @public
|
|
300
|
+
*/
|
|
301
|
+
constructor(values, context, options) {
|
|
302
|
+
super(values, context, options);
|
|
303
|
+
}
|
|
304
|
+
static createPrefixed(prefixOptions, values, context, editor) {
|
|
305
|
+
return (0, ts_utils_1.captureResult)(() => new PrefixedJsonMap(values, context, { keyPolicy: this._toPolicy(prefixOptions), editor }));
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Constructs a new {@link PrefixKeyPolicy | PrefixKeyPolicy} from a supplied prefix
|
|
309
|
+
* or set of {@link IKeyPrefixOptions | prefix options}.
|
|
310
|
+
* @param prefixOptions - The prefix or {@link IKeyPrefixOptions | prefix options} or options
|
|
311
|
+
* for the new policy.
|
|
312
|
+
* @returns A new {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy} which enforces the
|
|
313
|
+
* supplied prefix or options.
|
|
314
|
+
* @internal
|
|
315
|
+
*/
|
|
316
|
+
static _toPolicy(prefixOptions) {
|
|
317
|
+
if (typeof prefixOptions === 'string') {
|
|
318
|
+
return new PrefixKeyPolicy(prefixOptions, { makeValid: true });
|
|
319
|
+
}
|
|
320
|
+
return new PrefixKeyPolicy(prefixOptions.prefix, { makeValid: prefixOptions.addPrefix !== false });
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
exports.PrefixedJsonMap = PrefixedJsonMap;
|
|
324
|
+
//# sourceMappingURL=jsonReferenceMap.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonReferenceMap.js","sourceRoot":"","sources":["../../../src/packlets/editor/jsonReferenceMap.ts"],"names":[],"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,IAAI,eAAe,CAAC,aAAa,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;SAChE;QACD,OAAO,IAAI,eAAe,CAAC,aAAa,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,aAAa,CAAC,SAAS,KAAK,KAAK,EAAE,CAAC,CAAC;IACrG,CAAC;CACF;AAzED,0CAyEC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n DetailedResult,\n Result,\n captureResult,\n fail,\n failWithDetail,\n mapResults,\n recordToMap,\n succeed,\n succeedWithDetail\n} from '@fgv/ts-utils';\n\nimport { IJsonContext, IJsonReferenceMap, JsonReferenceMapFailureReason } from '../context';\nimport { JsonObject, JsonValue, isJsonObject } from '../json';\nimport { JsonEditor } from './jsonEditor';\n\n/**\n * Options for creating a {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy} object.\n * @public\n */\nexport interface IReferenceMapKeyPolicyValidateOptions {\n /**\n * If `true`, the validator coerces keys to some valid value.\n * If `false`, invalid keys cause an error.\n */\n makeValid?: boolean;\n}\n\n/**\n * Policy object responsible for validating or correcting\n * keys in a {@link IJsonReferenceMap | reference map}.\n * @public\n */\nexport class ReferenceMapKeyPolicy<T> {\n /**\n * @internal\n */\n protected readonly _defaultOptions?: IReferenceMapKeyPolicyValidateOptions;\n\n /**\n * @internal\n */\n protected readonly _isValid: (key: string, item?: T) => boolean;\n\n /**\n * Constructs a new {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy}.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options}\n * used to construct the {@link ReferenceMapKeyPolicy}.\n * @param isValid - An optional predicate to test a supplied key for validity.\n */\n public constructor(\n options?: IReferenceMapKeyPolicyValidateOptions,\n isValid?: (key: string, item?: T) => boolean\n ) {\n this._defaultOptions = options;\n this._isValid = isValid ?? ReferenceMapKeyPolicy.defaultKeyPredicate;\n }\n\n /**\n * The static default key name validation predicate rejects keys that contain\n * mustache templates or which start with the default conditional prefix\n * `'?'`.\n * @param key - The key to test.\n * @returns `true` if the key is valid, `false` otherwise.\n */\n public static defaultKeyPredicate(key: string): boolean {\n return key.length > 0 && !key.includes('{{') && !key.startsWith('?');\n }\n\n /**\n * Determines if a supplied key and item are valid according to the current policy.\n * @param key - The key to be tested.\n * @param item - The item to be tested.\n * @returns `true` if the key and value are valid, `false` otherwise.\n */\n public isValid(key: string, item?: T): boolean {\n return this._isValid(key, item);\n }\n\n /**\n * Determines if a supplied key and item are valid according to the current policy.\n * @param key - The key to be tested.\n * @param item - The item to be tested.\n * @returns `Success` with the key if valid, `Failure` with an error message if invalid.\n */\n public validate(key: string, item?: T, __options?: IReferenceMapKeyPolicyValidateOptions): Result<string> {\n return this.isValid(key, item) ? succeed(key) : fail(`${key}: invalid key`);\n }\n\n /**\n * Validates an array of entries using the validation rules for this policy.\n * @param items - The array of entries to be validated.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to control\n * validation.\n * @returns `Success` with an array of validated entries, or `Failure` with an error message\n * if validation fails.\n */\n public validateItems(\n items: [string, T][],\n options?: IReferenceMapKeyPolicyValidateOptions\n ): Result<[string, T][]> {\n return mapResults(\n items.map((item) => {\n return this.validate(...item, options).onSuccess((valid) => {\n return succeed([valid, item[1]]);\n });\n })\n );\n }\n\n /**\n * Validates a `Map\\<string, T\\>` using the validation rules for this policy.\n * @param items - The `Map\\<string, T\\>` to be validated.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to control\n * validation.\n * @returns `Success` with a new `Map\\<string, T\\>`, or `Failure` with an error message\n * if validation fails.\n */\n public validateMap(\n map: Map<string, T>,\n options?: IReferenceMapKeyPolicyValidateOptions\n ): Result<Map<string, T>> {\n return this.validateItems(Array.from(map.entries()), options).onSuccess((valid) => {\n return captureResult(() => new Map(valid));\n });\n }\n}\n\n/**\n * A {@link PrefixKeyPolicy | PrefixKeyPolicy} enforces that all keys start with a supplied\n * prefix, optionally adding the prefix as necessary.\n * @public\n */\nexport class PrefixKeyPolicy<T> extends ReferenceMapKeyPolicy<T> {\n /**\n * The string prefix to be enforced by this policy.\n */\n public readonly prefix: string;\n\n /**\n * Constructs a new {@link PrefixKeyPolicy | PrefixKeyPolicy}.\n * @param prefix - The string prefix to be enforced or applied.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to\n * configure the policy.\n */\n public constructor(prefix: string, options?: IReferenceMapKeyPolicyValidateOptions) {\n super(options);\n this.prefix = prefix;\n }\n\n /**\n * Determines if a key is valid according to policy.\n * @param key - The key to be tested.\n * @param __item - The item to be tested.\n * @returns `true` if the key starts with the expected prefix, `false` otherwise.\n */\n public isValid(key: string, __item?: T): boolean {\n return (\n key.startsWith(this.prefix) && key !== this.prefix && ReferenceMapKeyPolicy.defaultKeyPredicate(key)\n );\n }\n\n /**\n * Determines if a key is valid according to policy, optionally coercing to a valid value by\n * adding the required prefix.\n * @param key - The key to be tested.\n * @param item - The item which corresponds to the key.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to guide\n * validation.\n * @returns `Success` with a valid key name if the supplied key is valid or if `makeValid` is set\n * in the policy options. Returns `Failure` with an error message if an error occurs.\n */\n public validate(key: string, item?: T, options?: IReferenceMapKeyPolicyValidateOptions): Result<string> {\n /* c8 ignore next */\n const makeValid = (options ?? this._defaultOptions)?.makeValid === true;\n if (this.isValid(key, item)) {\n return succeed(key);\n } else if (makeValid && ReferenceMapKeyPolicy.defaultKeyPredicate(key)) {\n return succeed(`${this.prefix}${key}`);\n }\n return fail(`${key}: invalid key`);\n }\n}\n\n/**\n * Type representing either a `Map\\<string, T\\>` or a `Record\\<string, T\\>`.\n * @public\n */\nexport type MapOrRecord<T> = Map<string, T> | Record<string, T>;\n\n/**\n * Abstract base class with common functionality for simple\n * {@link IJsonReferenceMap | reference map} implementations.\n * {@link JsonValue | json values}.\n * @public\n */\nexport abstract class SimpleJsonMapBase<T> implements IJsonReferenceMap {\n /**\n * The {@link ReferenceMapKeyPolicy | key policy} in effect for this map.\n * @internal\n */\n protected readonly _keyPolicy: ReferenceMapKeyPolicy<T>;\n\n /**\n * A map containing keys and values already present in this map.\n * @internal\n */\n protected readonly _values: Map<string, T>;\n\n /**\n * An optional {@link IJsonContext | IJsonContext} used for any conversions\n * involving items in this map.\n * @internal\n */\n protected readonly _context?: IJsonContext;\n\n /**\n * Constructs a new {@link SimpleJsonMap | SimpleJsonMap}.\n * @param values - Initial values for the map.\n * @param context - An optional {@link IJsonContext | IJsonContext} used for any conversions\n * involving items in this map.\n * @param keyPolicy - The {@link ReferenceMapKeyPolicy | key policy} to use for this map.\n * @internal\n */\n protected constructor(\n values?: MapOrRecord<T>,\n context?: IJsonContext,\n keyPolicy?: ReferenceMapKeyPolicy<T>\n ) {\n values = SimpleJsonMapBase._toMap(values).orThrow();\n this._keyPolicy = keyPolicy ?? new ReferenceMapKeyPolicy();\n this._values = this._keyPolicy.validateMap(values).orThrow();\n this._context = context;\n }\n\n /**\n * Returns a `Map\\<string, T\\>` derived from a supplied {@link MapOrRecord | MapOrRecord}\n * @param values - The {@link MapOrRecord | MapOrRecord} to be returned as a map.\n * @returns `Success` with the corresponding `Map\\<string, T\\>` or `Failure` with a\n * message if an error occurs.\n * @internal\n */\n protected static _toMap<T>(values?: MapOrRecord<T>): Result<Map<string, T>> {\n if (values === undefined) {\n return captureResult(() => new Map<string, T>());\n } else if (!(values instanceof Map)) {\n return recordToMap(values, (__k, v) => succeed(v));\n }\n return succeed(values);\n }\n\n /**\n * Determine if a key might be valid for this map but does not determine if key actually\n * exists. Allows key range to be constrained.\n * @param key - key to be tested\n * @returns `true` if the key is in the valid range, `false` otherwise.\n */\n public keyIsInRange(key: string): boolean {\n return this._keyPolicy.isValid(key);\n }\n\n /**\n * Determines if an entry with the specified key actually exists in the map.\n * @param key - key to be tested\n * @returns `true` if an object with the specified key exists, `false` otherwise.\n */\n public has(key: string): boolean {\n return this._values.has(key);\n }\n\n /**\n * Gets a {@link JsonObject | JSON object} specified by key.\n * @param key - key of the object to be retrieved\n * @param context - optional {@link IJsonContext | JSON context} used to format the\n * returned object.\n * @returns {@link ts-utils#Success | `Success`} with the formatted object if successful.\n * {@link ts-utils#Failure | `Failure`} with detail 'unknown' if no such object exists,\n * or {@link ts-utils#Failure | `Failure`} with detail 'error' if the object was found\n * but could not be formatted.\n */\n public getJsonObject(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonObject, JsonReferenceMapFailureReason> {\n return this.getJsonValue(key, context).onSuccess((jv) => {\n if (!isJsonObject(jv)) {\n return failWithDetail(`${key}: not an object`, 'error');\n }\n return succeedWithDetail(jv);\n });\n }\n\n /**\n * Gets a {@link JsonValue | JSON value} specified by key.\n * @param key - key of the value to be retrieved\n * @param context - Optional {@link IJsonContext | JSON context} used to format the value\n * @returns Success with the formatted object if successful. Failure with detail 'unknown'\n * if no such object exists, or failure with detail 'error' if the object was found but\n * could not be formatted.\n */\n // eslint-disable-next-line no-use-before-define\n public abstract getJsonValue(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason>;\n}\n\n/**\n * Initialization options for a {@link SimpleJsonMap | SimpleJsonMap}.\n * @public\n */\nexport interface ISimpleJsonMapOptions {\n keyPolicy?: ReferenceMapKeyPolicy<JsonValue>;\n editor?: JsonEditor;\n}\n\n/**\n * A {@link SimpleJsonMap | SimpleJsonMap } presents a view of a simple map\n * of {@link JsonValue | JSON values}.\n * @public\n */\nexport class SimpleJsonMap extends SimpleJsonMapBase<JsonValue> {\n /**\n * @internal\n */\n protected _editor?: JsonEditor;\n\n /**\n * Constructs a new {@link SimpleJsonMap | SimpleJsonMap} from the supplied objects\n * @param values - A string-keyed `Map` or `Record` of the {@link JsonValue | JSON values}\n * to be returned.\n * @param context - Optional {@link IJsonContext | IJsonContext} used to format returned values.\n * @param options - Optional {@link ISimpleJsonMapOptions | ISimpleJsonMapOptions} for initialization.\n * @public\n */\n protected constructor(\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n options?: ISimpleJsonMapOptions\n ) {\n super(values, context, options?.keyPolicy);\n this._editor = options?.editor;\n }\n\n /**\n * Creates a new {@link SimpleJsonMap | SimpleJsonMap} from the supplied objects\n * @param values - A string-keyed `Map` or `Record` of the {@link JsonValue | JSON values}\n * to be returned.\n * @param context - Optional {@link IJsonContext | IJsonContext} used to format returned values.\n * @param options - Optional {@link ISimpleJsonMapOptions | ISimpleJsonMapOptions} for initialization.\n * @returns `Success` with a {@link SimpleJsonMap | SimpleJsonMap} or `Failure` with a message if\n * an error occurs.\n */\n public static createSimple(\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n options?: ISimpleJsonMapOptions\n ): Result<SimpleJsonMap> {\n return captureResult(() => new SimpleJsonMap(values, context, options));\n }\n\n /**\n * Gets a {@link JsonValue | JSON value} specified by key.\n * @param key - key of the value to be retrieved\n * @param context - Optional {@link IJsonContext | JSON context} used to format the value\n * @returns Success with the formatted object if successful. Failure with detail 'unknown'\n * if no such object exists, or failure with detail 'error' if the object was found but\n * could not be formatted.\n */\n public getJsonValue(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason> {\n context = context ?? this._context;\n const value = this._values.get(key);\n if (!value) {\n return failWithDetail(`${key}: JSON value not found`, 'unknown');\n }\n return this._clone(value, context);\n }\n\n /**\n * @internal\n */\n protected _clone(\n value: JsonValue,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason> {\n if (!this._editor) {\n const result = JsonEditor.create();\n /* c8 ignore next 3 - nearly impossible to reproduce */\n if (result.isFailure()) {\n return failWithDetail(result.message, 'error');\n }\n this._editor = result.value;\n }\n return this._editor.clone(value, context).withFailureDetail('error');\n }\n}\n\n/**\n * Initialization options for a {@link PrefixedJsonMap | PrefixedJsonMap}\n * @public\n */\nexport interface IKeyPrefixOptions {\n /**\n * Indicates whether the prefix should be added automatically as needed (default true)\n */\n addPrefix?: boolean;\n\n /**\n * The prefix to be enforced\n */\n prefix: string;\n}\n\n/**\n * A {@link PrefixedJsonMap | PrefixedJsonMap} enforces a supplied prefix for all contained values,\n * optionally adding the prefix as necessary (default `true`).\n * @public\n */\nexport class PrefixedJsonMap extends SimpleJsonMap {\n /**\n * Constructs a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values\n * @param prefix - A string prefix to be enforced for and added to key names as necessary\n * @param values - A string-keyed Map or Record of the {@link JsonValue | JsonValue} to be returned\n * @param context - Optional {@link IJsonContext | JSON Context} used to format returned values\n * @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values\n * @public\n */\n protected constructor(\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n options?: ISimpleJsonMapOptions\n ) {\n super(values, context, options);\n }\n\n /**\n * Creates a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values\n * @param prefix - A string prefix to be enforced for and added to key names as necessary\n * @param values - A string-keyed Map or Record of the {@link JsonValue | JsonValue} to be returned\n * @param context - Optional {@link IJsonContext | JSON Context} used to format returned values\n * @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values\n * @returns `Success` with a {@link PrefixedJsonMap | PrefixedJsonMap} or `Failure` with a message\n * if an error occurs.\n */\n public static createPrefixed(\n prefix: string,\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n editor?: JsonEditor\n ): Result<PrefixedJsonMap>;\n\n /**\n * Creates a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values\n * @param prefixOptions - A KeyPrefixOptions indicating the prefix to enforce and whether that prefix should\n * be added automatically if necessary (default true)\n * @param values - A string-keyed Map or record of the {@link JsonValue | JsonValue} to be returned\n * @param context - Optional {@link IJsonContext | JSON Context} used to format returned values\n * @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values\n */\n public static createPrefixed(\n prefixOptions: IKeyPrefixOptions,\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n editor?: JsonEditor\n ): Result<PrefixedJsonMap>;\n public static createPrefixed(\n prefixOptions: string | IKeyPrefixOptions,\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n editor?: JsonEditor\n ): Result<PrefixedJsonMap> {\n return captureResult(\n () => new PrefixedJsonMap(values, context, { keyPolicy: this._toPolicy(prefixOptions), editor })\n );\n }\n\n /**\n * Constructs a new {@link PrefixKeyPolicy | PrefixKeyPolicy} from a supplied prefix\n * or set of {@link IKeyPrefixOptions | prefix options}.\n * @param prefixOptions - The prefix or {@link IKeyPrefixOptions | prefix options} or options\n * for the new policy.\n * @returns A new {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy} which enforces the\n * supplied prefix or options.\n * @internal\n */\n protected static _toPolicy(prefixOptions: string | IKeyPrefixOptions): ReferenceMapKeyPolicy<JsonValue> {\n if (typeof prefixOptions === 'string') {\n return new PrefixKeyPolicy(prefixOptions, { makeValid: true });\n }\n return new PrefixKeyPolicy(prefixOptions.prefix, { makeValid: prefixOptions.addPrefix !== false });\n }\n}\n"]}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { DetailedResult, Result } from '@fgv/ts-utils';
|
|
2
|
+
import { JsonObject, JsonValue } from '../../json';
|
|
3
|
+
import { IJsonEditorOptions, JsonEditFailureReason, JsonPropertyEditFailureReason } from '../common';
|
|
4
|
+
import { JsonEditorRuleBase } from '../jsonEditorRule';
|
|
5
|
+
import { JsonEditorState } from '../jsonEditorState';
|
|
6
|
+
/**
|
|
7
|
+
* Returned by {@link Editor.Rules.ConditionalJsonEditorRule._tryParseCondition | ConditionalJsonEditorRule._tryParseCondition}
|
|
8
|
+
* to indicate whether a successful match was due to a matching condition or a default value.
|
|
9
|
+
* @public
|
|
10
|
+
*/
|
|
11
|
+
export interface IConditionalJsonKeyResult extends JsonObject {
|
|
12
|
+
matchType: 'default' | 'match' | 'unconditional';
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* On a successful match, the {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}
|
|
16
|
+
* stores a {@link Editor.Rules.IConditionalJsonDeferredObject | IConditionalJsonDeferredObject} describing the
|
|
17
|
+
* matching result, to be resolved at finalization time.
|
|
18
|
+
* @public
|
|
19
|
+
*/
|
|
20
|
+
export interface IConditionalJsonDeferredObject extends IConditionalJsonKeyResult {
|
|
21
|
+
value: JsonValue;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Configuration options for the {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.
|
|
25
|
+
* @public
|
|
26
|
+
*/
|
|
27
|
+
export interface IConditionalJsonRuleOptions extends Partial<IJsonEditorOptions> {
|
|
28
|
+
/**
|
|
29
|
+
* If true (default) then properties with unconditional names
|
|
30
|
+
* (which start with !) are flattened.
|
|
31
|
+
*/
|
|
32
|
+
flattenUnconditionalValues?: boolean;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule} evaluates
|
|
36
|
+
* properties with conditional keys, omitting non-matching keys and merging keys that match,
|
|
37
|
+
* or default keys only if no other keys match.
|
|
38
|
+
*
|
|
39
|
+
* The default syntax for a conditional key is:
|
|
40
|
+
* "?value1=value2" - matches if value1 and value2 are the same, is ignored otherwise.
|
|
41
|
+
* "?value" - matches if value is a non-empty, non-whitespace string. Is ignored otherwise.
|
|
42
|
+
* "?default" - matches only if no other conditional blocks in the same object were matched.
|
|
43
|
+
* @public
|
|
44
|
+
*/
|
|
45
|
+
export declare class ConditionalJsonEditorRule extends JsonEditorRuleBase {
|
|
46
|
+
/**
|
|
47
|
+
* Stored fully-resolved {@link Editor.Rules.IConditionalJsonRuleOptions | options} for this
|
|
48
|
+
* rule.
|
|
49
|
+
* @public
|
|
50
|
+
*/
|
|
51
|
+
protected _options?: IConditionalJsonRuleOptions;
|
|
52
|
+
/**
|
|
53
|
+
* Creates a new {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.
|
|
54
|
+
* @param options - Optional {@link Editor.Rules.IConditionalJsonRuleOptions | configuration options}
|
|
55
|
+
* used for this rule.
|
|
56
|
+
*/
|
|
57
|
+
constructor(options?: IConditionalJsonRuleOptions);
|
|
58
|
+
/**
|
|
59
|
+
* Creates a new {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.
|
|
60
|
+
* @param options - Optional {@link Editor.Rules.IConditionalJsonRuleOptions | configuration options}
|
|
61
|
+
* used for this rule.
|
|
62
|
+
*/
|
|
63
|
+
static create(options?: IConditionalJsonRuleOptions): Result<ConditionalJsonEditorRule>;
|
|
64
|
+
/**
|
|
65
|
+
* Evaluates a property for conditional application.
|
|
66
|
+
* @param key - The key of the property to be considered
|
|
67
|
+
* @param value - The {@link JsonValue | value} of the property to be considered.
|
|
68
|
+
* @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.
|
|
69
|
+
* @returns Returns `Success` with detail `'deferred'` and a
|
|
70
|
+
* {@link Editor.Rules.IConditionalJsonDeferredObject | IConditionalJsonDeferredObject}.
|
|
71
|
+
* for a matching, default or unconditional key. Returns `Failure` with detail `'ignore'` for
|
|
72
|
+
* a non-matching conditional, or with detail `'error'` if an error occurs. Otherwise
|
|
73
|
+
* fails with detail `'inapplicable'`.
|
|
74
|
+
*/
|
|
75
|
+
editProperty(key: string, value: JsonValue, state: JsonEditorState): DetailedResult<JsonObject, JsonPropertyEditFailureReason>;
|
|
76
|
+
/**
|
|
77
|
+
* Finalizes any deferred conditional properties. If the only deferred property is
|
|
78
|
+
* default, that property is emitted. Otherwise all matching properties are emitted.
|
|
79
|
+
* @param finalized - The deferred properties to be considered for merge.
|
|
80
|
+
* @param __state - The {@link Editor.JsonEditorState | editor state} for the object
|
|
81
|
+
* being edited.
|
|
82
|
+
*/
|
|
83
|
+
finalizeProperties(finalized: JsonObject[], __state: JsonEditorState): DetailedResult<JsonObject[], JsonEditFailureReason>;
|
|
84
|
+
/**
|
|
85
|
+
* Determines if a given property key is conditional. Derived classes can override this
|
|
86
|
+
* method to use a different format for conditional properties.
|
|
87
|
+
* @param value - The {@link JsonValue | value} of the property to be considered.
|
|
88
|
+
* @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.
|
|
89
|
+
* @returns `Success` with detail `'deferred'` and a
|
|
90
|
+
* {@link Editor.Rules.IConditionalJsonKeyResult | IConditionalJsonKeyResult} describing the
|
|
91
|
+
* match for a default or matching conditional property. Returns `Failure` with detail `'ignore'`
|
|
92
|
+
* for a non-matching conditional property. Fails with detail `'error'` if an error occurs
|
|
93
|
+
* or with detail `'inapplicable'` if the key does not represent a conditional property.
|
|
94
|
+
* @public
|
|
95
|
+
*/
|
|
96
|
+
protected _tryParseCondition(key: string, state: JsonEditorState): DetailedResult<IConditionalJsonKeyResult, JsonPropertyEditFailureReason>;
|
|
97
|
+
/**
|
|
98
|
+
* Compares two strings using a supplied operator.
|
|
99
|
+
* @param left - The first string to be compared.
|
|
100
|
+
* @param right - The second string to be compared.
|
|
101
|
+
* @param operator - The operator to be applied.
|
|
102
|
+
* @returns `true` if the condition is met, `false` otherwise.
|
|
103
|
+
* @internal
|
|
104
|
+
*/
|
|
105
|
+
protected _compare(left: string, right: string, operator: string): boolean;
|
|
106
|
+
}
|
|
107
|
+
//# sourceMappingURL=conditional.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conditional.d.ts","sourceRoot":"","sources":["../../../../src/packlets/editor/rules/conditional.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,cAAc,EAAE,MAAM,EAAoD,MAAM,eAAe,CAAC;AACzG,OAAO,EAAE,UAAU,EAAE,SAAS,EAAgB,MAAM,YAAY,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,6BAA6B,EAAE,MAAM,WAAW,CAAC;AACrG,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;;GAIG;AACH,MAAM,WAAW,yBAA0B,SAAQ,UAAU;IAC3D,SAAS,EAAE,SAAS,GAAG,OAAO,GAAG,eAAe,CAAC;CAClD;AAED;;;;;GAKG;AACH,MAAM,WAAW,8BAA+B,SAAQ,yBAAyB;IAC/E,KAAK,EAAE,SAAS,CAAC;CAClB;AAED;;;GAGG;AACH,MAAM,WAAW,2BAA4B,SAAQ,OAAO,CAAC,kBAAkB,CAAC;IAC9E;;;OAGG;IACH,0BAA0B,CAAC,EAAE,OAAO,CAAC;CACtC;AAED;;;;;;;;;;GAUG;AACH,qBAAa,yBAA0B,SAAQ,kBAAkB;IAC/D;;;;OAIG;IACH,SAAS,CAAC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IAEjD;;;;OAIG;gBACgB,OAAO,CAAC,EAAE,2BAA2B;IAKxD;;;;OAIG;WACW,MAAM,CAAC,OAAO,CAAC,EAAE,2BAA2B,GAAG,MAAM,CAAC,yBAAyB,CAAC;IAI9F;;;;;;;;;;OAUG;IACI,YAAY,CACjB,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,SAAS,EAChB,KAAK,EAAE,eAAe,GACrB,cAAc,CAAC,UAAU,EAAE,6BAA6B,CAAC;IAmB5D;;;;;;OAMG;IACI,kBAAkB,CACvB,SAAS,EAAE,UAAU,EAAE,EACvB,OAAO,EAAE,eAAe,GACvB,cAAc,CAAC,UAAU,EAAE,EAAE,qBAAqB,CAAC;IAUtD;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,kBAAkB,CAC1B,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,eAAe,GACrB,cAAc,CAAC,yBAAyB,EAAE,6BAA6B,CAAC;IA6B3E;;;;;;;OAOG;IACH,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO;CAkB3E"}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* Copyright (c) 2020 Erik Fortune
|
|
4
|
+
*
|
|
5
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
* in the Software without restriction, including without limitation the rights
|
|
8
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
* furnished to do so, subject to the following conditions:
|
|
11
|
+
*
|
|
12
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
* copies or substantial portions of the Software.
|
|
14
|
+
*
|
|
15
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
* SOFTWARE.
|
|
22
|
+
*/
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.ConditionalJsonEditorRule = void 0;
|
|
25
|
+
const ts_utils_1 = require("@fgv/ts-utils");
|
|
26
|
+
const json_1 = require("../../json");
|
|
27
|
+
const jsonEditorRule_1 = require("../jsonEditorRule");
|
|
28
|
+
/**
|
|
29
|
+
* The {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule} evaluates
|
|
30
|
+
* properties with conditional keys, omitting non-matching keys and merging keys that match,
|
|
31
|
+
* or default keys only if no other keys match.
|
|
32
|
+
*
|
|
33
|
+
* The default syntax for a conditional key is:
|
|
34
|
+
* "?value1=value2" - matches if value1 and value2 are the same, is ignored otherwise.
|
|
35
|
+
* "?value" - matches if value is a non-empty, non-whitespace string. Is ignored otherwise.
|
|
36
|
+
* "?default" - matches only if no other conditional blocks in the same object were matched.
|
|
37
|
+
* @public
|
|
38
|
+
*/
|
|
39
|
+
class ConditionalJsonEditorRule extends jsonEditorRule_1.JsonEditorRuleBase {
|
|
40
|
+
/**
|
|
41
|
+
* Creates a new {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.
|
|
42
|
+
* @param options - Optional {@link Editor.Rules.IConditionalJsonRuleOptions | configuration options}
|
|
43
|
+
* used for this rule.
|
|
44
|
+
*/
|
|
45
|
+
constructor(options) {
|
|
46
|
+
super();
|
|
47
|
+
this._options = options;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Creates a new {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.
|
|
51
|
+
* @param options - Optional {@link Editor.Rules.IConditionalJsonRuleOptions | configuration options}
|
|
52
|
+
* used for this rule.
|
|
53
|
+
*/
|
|
54
|
+
static create(options) {
|
|
55
|
+
return (0, ts_utils_1.captureResult)(() => new ConditionalJsonEditorRule(options));
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Evaluates a property for conditional application.
|
|
59
|
+
* @param key - The key of the property to be considered
|
|
60
|
+
* @param value - The {@link JsonValue | value} of the property to be considered.
|
|
61
|
+
* @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.
|
|
62
|
+
* @returns Returns `Success` with detail `'deferred'` and a
|
|
63
|
+
* {@link Editor.Rules.IConditionalJsonDeferredObject | IConditionalJsonDeferredObject}.
|
|
64
|
+
* for a matching, default or unconditional key. Returns `Failure` with detail `'ignore'` for
|
|
65
|
+
* a non-matching conditional, or with detail `'error'` if an error occurs. Otherwise
|
|
66
|
+
* fails with detail `'inapplicable'`.
|
|
67
|
+
*/
|
|
68
|
+
editProperty(key, value, state) {
|
|
69
|
+
var _a;
|
|
70
|
+
const result = this._tryParseCondition(key, state).onSuccess((deferred) => {
|
|
71
|
+
if ((0, json_1.isJsonObject)(value)) {
|
|
72
|
+
const rtrn = Object.assign(Object.assign({}, deferred), { value });
|
|
73
|
+
return (0, ts_utils_1.succeedWithDetail)(rtrn, 'deferred');
|
|
74
|
+
}
|
|
75
|
+
return (0, ts_utils_1.failWithDetail)(`${key}: conditional body must be object`, 'error');
|
|
76
|
+
});
|
|
77
|
+
if (result.isFailure() && result.detail === 'error') {
|
|
78
|
+
return state.failValidation('invalidPropertyName', result.message, (_a = this._options) === null || _a === void 0 ? void 0 : _a.validation);
|
|
79
|
+
}
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Finalizes any deferred conditional properties. If the only deferred property is
|
|
84
|
+
* default, that property is emitted. Otherwise all matching properties are emitted.
|
|
85
|
+
* @param finalized - The deferred properties to be considered for merge.
|
|
86
|
+
* @param __state - The {@link Editor.JsonEditorState | editor state} for the object
|
|
87
|
+
* being edited.
|
|
88
|
+
*/
|
|
89
|
+
finalizeProperties(finalized, __state) {
|
|
90
|
+
let toMerge = finalized;
|
|
91
|
+
if (finalized.length > 1) {
|
|
92
|
+
if (finalized.find((o) => o.matchType === 'match') !== undefined) {
|
|
93
|
+
toMerge = finalized.filter((o) => o.matchType === 'match' || o.matchType === 'unconditional');
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return (0, ts_utils_1.succeedWithDetail)(toMerge.map((o) => o.value).filter(json_1.isJsonObject), 'edited');
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Determines if a given property key is conditional. Derived classes can override this
|
|
100
|
+
* method to use a different format for conditional properties.
|
|
101
|
+
* @param value - The {@link JsonValue | value} of the property to be considered.
|
|
102
|
+
* @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.
|
|
103
|
+
* @returns `Success` with detail `'deferred'` and a
|
|
104
|
+
* {@link Editor.Rules.IConditionalJsonKeyResult | IConditionalJsonKeyResult} describing the
|
|
105
|
+
* match for a default or matching conditional property. Returns `Failure` with detail `'ignore'`
|
|
106
|
+
* for a non-matching conditional property. Fails with detail `'error'` if an error occurs
|
|
107
|
+
* or with detail `'inapplicable'` if the key does not represent a conditional property.
|
|
108
|
+
* @public
|
|
109
|
+
*/
|
|
110
|
+
_tryParseCondition(key, state) {
|
|
111
|
+
var _a, _b;
|
|
112
|
+
if (key.startsWith('?')) {
|
|
113
|
+
// ignore everything after any #
|
|
114
|
+
key = key.split('#')[0].trim();
|
|
115
|
+
if (key === '?default') {
|
|
116
|
+
return (0, ts_utils_1.succeedWithDetail)({ matchType: 'default' }, 'deferred');
|
|
117
|
+
}
|
|
118
|
+
const parts = key.substring(1).split(/(=|>=|<=|>|<|!=)/);
|
|
119
|
+
if (parts.length === 3) {
|
|
120
|
+
if (!this._compare(parts[0].trim(), parts[2].trim(), parts[1])) {
|
|
121
|
+
return (0, ts_utils_1.failWithDetail)(`Condition ${key} does not match`, 'ignore');
|
|
122
|
+
}
|
|
123
|
+
return (0, ts_utils_1.succeedWithDetail)({ matchType: 'match' }, 'deferred');
|
|
124
|
+
}
|
|
125
|
+
else if (parts.length === 1) {
|
|
126
|
+
if (parts[0].trim().length === 0) {
|
|
127
|
+
return (0, ts_utils_1.failWithDetail)(`Condition ${key} does not match`, 'ignore');
|
|
128
|
+
}
|
|
129
|
+
return (0, ts_utils_1.succeedWithDetail)({ matchType: 'match' }, 'deferred');
|
|
130
|
+
}
|
|
131
|
+
const message = `Malformed condition token ${key}`;
|
|
132
|
+
return state.failValidation('invalidPropertyName', message, (_a = this._options) === null || _a === void 0 ? void 0 : _a.validation);
|
|
133
|
+
}
|
|
134
|
+
else if (((_b = this._options) === null || _b === void 0 ? void 0 : _b.flattenUnconditionalValues) !== false && key.startsWith('!')) {
|
|
135
|
+
return (0, ts_utils_1.succeedWithDetail)({ matchType: 'unconditional' }, 'deferred');
|
|
136
|
+
}
|
|
137
|
+
return (0, ts_utils_1.failWithDetail)('inapplicable', 'inapplicable');
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Compares two strings using a supplied operator.
|
|
141
|
+
* @param left - The first string to be compared.
|
|
142
|
+
* @param right - The second string to be compared.
|
|
143
|
+
* @param operator - The operator to be applied.
|
|
144
|
+
* @returns `true` if the condition is met, `false` otherwise.
|
|
145
|
+
* @internal
|
|
146
|
+
*/
|
|
147
|
+
_compare(left, right, operator) {
|
|
148
|
+
switch (operator) {
|
|
149
|
+
case '=':
|
|
150
|
+
return left === right;
|
|
151
|
+
case '>':
|
|
152
|
+
return left > right;
|
|
153
|
+
case '<':
|
|
154
|
+
return left < right;
|
|
155
|
+
case '>=':
|
|
156
|
+
return left >= right;
|
|
157
|
+
case '<=':
|
|
158
|
+
return left <= right;
|
|
159
|
+
case '!=':
|
|
160
|
+
return left !== right;
|
|
161
|
+
}
|
|
162
|
+
/* c8 ignore next 2 - unreachable */
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
exports.ConditionalJsonEditorRule = ConditionalJsonEditorRule;
|
|
167
|
+
//# sourceMappingURL=conditional.js.map
|