@vertexvis/utils 0.24.5-canary.4 → 1.0.0-testing.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.
@@ -1,26 +1,29 @@
1
1
  import { __awaiter, __generator, __asyncValues, __assign, __extends, __read, __spreadArray, __values } from 'tslib';
2
+ import fastDeepEqual from 'fast-deep-equal';
3
+ import isSimpleObject from 'is-plain-object';
4
+ import { v4 } from 'uuid';
2
5
 
3
- /**
4
- * Adds a listener to the given `target`, and returns a promise that
5
- * resolves with the first event emitted of the given `type`.
6
- *
7
- * @param target The target to add an event listener to.
8
- * @param type The event type to listen for.
9
- * @param opts Options to pass to `addEventListener`.
10
- * @returns A promise that resolves with the first event emitted of `type`.
11
- */
12
- function once(target, type, opts) {
13
- return __awaiter(this, void 0, void 0, function () {
14
- return __generator(this, function (_a) {
15
- return [2 /*return*/, new Promise(function (resolve) {
16
- function handler(event) {
17
- target.removeEventListener(type, handler);
18
- resolve(event);
19
- }
20
- target.addEventListener(type, handler, opts);
21
- })];
22
- });
23
- });
6
+ /**
7
+ * Adds a listener to the given `target`, and returns a promise that
8
+ * resolves with the first event emitted of the given `type`.
9
+ *
10
+ * @param target The target to add an event listener to.
11
+ * @param type The event type to listen for.
12
+ * @param opts Options to pass to `addEventListener`.
13
+ * @returns A promise that resolves with the first event emitted of `type`.
14
+ */
15
+ function once(target, type, opts) {
16
+ return __awaiter(this, void 0, Promise, function () {
17
+ return __generator(this, function (_a) {
18
+ return [2 /*return*/, new Promise(function (resolve) {
19
+ function handler(event) {
20
+ target.removeEventListener(type, handler);
21
+ resolve(event);
22
+ }
23
+ target.addEventListener(type, handler, opts);
24
+ })];
25
+ });
26
+ });
24
27
  }
25
28
 
26
29
  var eventTargets = /*#__PURE__*/Object.freeze({
@@ -28,206 +31,210 @@ var eventTargets = /*#__PURE__*/Object.freeze({
28
31
  once: once
29
32
  });
30
33
 
31
- /**
32
- * Converts an async generator to an array of results.
33
- *
34
- * @param generator The generator to convert.
35
- * @returns A promise that resolves with an array of results yielded by the
36
- * generator.
37
- */
38
- function asArray(generator) {
39
- var generator_1, generator_1_1;
40
- var e_1, _a;
41
- return __awaiter(this, void 0, void 0, function () {
42
- var res, next, e_1_1;
43
- return __generator(this, function (_b) {
44
- switch (_b.label) {
45
- case 0:
46
- res = [];
47
- _b.label = 1;
48
- case 1:
49
- _b.trys.push([1, 6, 7, 12]);
50
- generator_1 = __asyncValues(generator);
51
- _b.label = 2;
52
- case 2: return [4 /*yield*/, generator_1.next()];
53
- case 3:
54
- if (!(generator_1_1 = _b.sent(), !generator_1_1.done)) return [3 /*break*/, 5];
55
- next = generator_1_1.value;
56
- res.push(next);
57
- _b.label = 4;
58
- case 4: return [3 /*break*/, 2];
59
- case 5: return [3 /*break*/, 12];
60
- case 6:
61
- e_1_1 = _b.sent();
62
- e_1 = { error: e_1_1 };
63
- return [3 /*break*/, 12];
64
- case 7:
65
- _b.trys.push([7, , 10, 11]);
66
- if (!(generator_1_1 && !generator_1_1.done && (_a = generator_1.return))) return [3 /*break*/, 9];
67
- return [4 /*yield*/, _a.call(generator_1)];
68
- case 8:
69
- _b.sent();
70
- _b.label = 9;
71
- case 9: return [3 /*break*/, 11];
72
- case 10:
73
- if (e_1) throw e_1.error;
74
- return [7 /*endfinally*/];
75
- case 11: return [7 /*endfinally*/];
76
- case 12: return [2 /*return*/, res];
77
- }
78
- });
79
- });
80
- }
81
- function delay() {
82
- var args = [];
83
- for (var _i = 0; _i < arguments.length; _i++) {
84
- args[_i] = arguments[_i];
85
- }
86
- return __awaiter(this, void 0, void 0, function () {
87
- var ms, promise, delay_1;
88
- return __generator(this, function (_a) {
89
- switch (_a.label) {
90
- case 0:
91
- ms = args[0];
92
- if (!(typeof ms === 'number')) return [3 /*break*/, 4];
93
- promise = args[1];
94
- delay_1 = new Promise(function (resolve) { return setTimeout(resolve, ms); });
95
- if (!(promise != null)) return [3 /*break*/, 2];
96
- return [4 /*yield*/, delay_1];
97
- case 1:
98
- _a.sent();
99
- return [2 /*return*/, promise];
100
- case 2: return [2 /*return*/, delay_1];
101
- case 3: return [3 /*break*/, 5];
102
- case 4: return [2 /*return*/, Promise.reject(new TypeError('First argument to `delay` must be a number'))];
103
- case 5: return [2 /*return*/];
104
- }
105
- });
106
- });
107
- }
108
- function timeout() {
109
- var args = [];
110
- for (var _i = 0; _i < arguments.length; _i++) {
111
- args[_i] = arguments[_i];
112
- }
113
- return __awaiter(this, void 0, void 0, function () {
114
- var ms, promise, timer_1, timeout_1, res;
115
- return __generator(this, function (_a) {
116
- switch (_a.label) {
117
- case 0:
118
- ms = args[0];
119
- if (!(typeof ms === 'number')) return [3 /*break*/, 4];
120
- promise = args[1];
121
- timeout_1 = new Promise(function (_, reject) {
122
- timer_1 = setTimeout(function () { return reject(new Error("Promise timed out after ".concat(ms, "ms"))); }, ms);
123
- });
124
- if (!(promise != null)) return [3 /*break*/, 2];
125
- return [4 /*yield*/, Promise.race([promise, timeout_1])];
126
- case 1:
127
- res = _a.sent();
128
- clearTimeout(timer_1);
129
- return [2 /*return*/, res];
130
- case 2: return [2 /*return*/, timeout_1];
131
- case 3: return [3 /*break*/, 5];
132
- case 4: return [2 /*return*/, Promise.reject('First argument to `timeout` must be a number')];
133
- case 5: return [2 /*return*/];
134
- }
135
- });
136
- });
137
- }
138
- /**
139
- * Executes and reattempts execution of an asynchronous function if it throws an
140
- * error. By default, this function will only retry once and reexecute
141
- * immediately after the previous execution throws. You can configure the number
142
- * of retry attempts and delays with the `maxRetries` and `delaysInMs` options.
143
- *
144
- * The `delaysInMs` is an array of delays in milliseconds for each retry
145
- * attempt. If there are more retry attempts than delays, the last delay will be
146
- * used.
147
- *
148
- * @param process The process to execute.
149
- * @param opts Options to configure retry behavior.
150
- * @returns A promise that resolves with a successful value, or the original
151
- * rejected value if the process fails.
152
- */
153
- function retry(process, opts) {
154
- if (opts === void 0) { opts = {}; }
155
- return __awaiter(this, void 0, void 0, function () {
156
- function execute(attempt, process, opts) {
157
- return __awaiter(this, void 0, void 0, function () {
158
- var _a, delaysInMs, _b, maxRetries, delayInMs, e_2;
159
- return __generator(this, function (_c) {
160
- switch (_c.label) {
161
- case 0:
162
- _a = opts.delaysInMs, delaysInMs = _a === void 0 ? [] : _a, _b = opts.maxRetries, maxRetries = _b === void 0 ? 1 : _b;
163
- _c.label = 1;
164
- case 1:
165
- _c.trys.push([1, 4, , 8]);
166
- delayInMs = attempt === 0 || delaysInMs.length === 0
167
- ? 0
168
- : delaysInMs[Math.min(attempt - 1, delaysInMs.length - 1)];
169
- return [4 /*yield*/, delay(delayInMs)];
170
- case 2:
171
- _c.sent();
172
- return [4 /*yield*/, process()];
173
- case 3: return [2 /*return*/, _c.sent()];
174
- case 4:
175
- e_2 = _c.sent();
176
- if (!(attempt < maxRetries)) return [3 /*break*/, 6];
177
- return [4 /*yield*/, execute(attempt + 1, process, opts)];
178
- case 5: return [2 /*return*/, _c.sent()];
179
- case 6: throw e_2;
180
- case 7: return [3 /*break*/, 8];
181
- case 8: return [2 /*return*/];
182
- }
183
- });
184
- });
185
- }
186
- return __generator(this, function (_a) {
187
- return [2 /*return*/, execute(0, process, opts)];
188
- });
189
- });
190
- }
191
- /**
192
- * Returns a promise that either resolves with the result of `promise`, or a
193
- * value that indicates the execution was aborted.
194
- *
195
- * **Note:** Because Promises in JS cannot be canceled, an abort signal will not
196
- * cancel the execution of the promise.
197
- *
198
- * @param signal A signal that communicates the process should be aborted.
199
- * @param promise A promise who's value will be returned if not aborted.
200
- * @returns A value indicating if the process was aborted, or the value of
201
- * `promise`.
202
- */
203
- function abort(signal, promise) {
204
- return __awaiter(this, void 0, void 0, function () {
205
- var controller, pendingAbort, result;
206
- return __generator(this, function (_a) {
207
- switch (_a.label) {
208
- case 0:
209
- controller = new AbortController();
210
- pendingAbort = once(signal, 'abort', { signal: controller.signal });
211
- return [4 /*yield*/, Promise.race([promise, pendingAbort])];
212
- case 1:
213
- result = _a.sent();
214
- if (isAbortEvent(result)) {
215
- return [2 /*return*/, { aborted: true }];
216
- }
217
- else {
218
- controller.abort();
219
- return [2 /*return*/, { aborted: false, result: result }];
220
- }
221
- }
222
- });
223
- });
224
- }
225
- function isAbortEvent(obj) {
226
- if (obj instanceof Event) {
227
- return obj.type === 'abort';
228
- }
229
- else
230
- return false;
34
+ /**
35
+ * Converts an async generator to an array of results.
36
+ *
37
+ * @param generator The generator to convert.
38
+ * @returns A promise that resolves with an array of results yielded by the
39
+ * generator.
40
+ */
41
+ function asArray(generator) {
42
+ return __awaiter(this, void 0, Promise, function () {
43
+ var res, next, e_1_1;
44
+ var _a, generator_1, generator_1_1;
45
+ var _b, e_1, _c, _d;
46
+ return __generator(this, function (_e) {
47
+ switch (_e.label) {
48
+ case 0:
49
+ res = [];
50
+ _e.label = 1;
51
+ case 1:
52
+ _e.trys.push([1, 6, 7, 12]);
53
+ _a = true, generator_1 = __asyncValues(generator);
54
+ _e.label = 2;
55
+ case 2: return [4 /*yield*/, generator_1.next()];
56
+ case 3:
57
+ if (!(generator_1_1 = _e.sent(), _b = generator_1_1.done, !_b)) return [3 /*break*/, 5];
58
+ _d = generator_1_1.value;
59
+ _a = false;
60
+ next = _d;
61
+ res.push(next);
62
+ _e.label = 4;
63
+ case 4:
64
+ _a = true;
65
+ return [3 /*break*/, 2];
66
+ case 5: return [3 /*break*/, 12];
67
+ case 6:
68
+ e_1_1 = _e.sent();
69
+ e_1 = { error: e_1_1 };
70
+ return [3 /*break*/, 12];
71
+ case 7:
72
+ _e.trys.push([7, , 10, 11]);
73
+ if (!(!_a && !_b && (_c = generator_1.return))) return [3 /*break*/, 9];
74
+ return [4 /*yield*/, _c.call(generator_1)];
75
+ case 8:
76
+ _e.sent();
77
+ _e.label = 9;
78
+ case 9: return [3 /*break*/, 11];
79
+ case 10:
80
+ if (e_1) throw e_1.error;
81
+ return [7 /*endfinally*/];
82
+ case 11: return [7 /*endfinally*/];
83
+ case 12: return [2 /*return*/, res];
84
+ }
85
+ });
86
+ });
87
+ }
88
+ function delay() {
89
+ var args = [];
90
+ for (var _i = 0; _i < arguments.length; _i++) {
91
+ args[_i] = arguments[_i];
92
+ }
93
+ return __awaiter(this, void 0, Promise, function () {
94
+ var ms, promise, delay_1;
95
+ return __generator(this, function (_a) {
96
+ switch (_a.label) {
97
+ case 0:
98
+ ms = args[0];
99
+ if (!(typeof ms === 'number')) return [3 /*break*/, 4];
100
+ promise = args[1];
101
+ delay_1 = new Promise(function (resolve) { return setTimeout(resolve, ms); });
102
+ if (!(promise != null)) return [3 /*break*/, 2];
103
+ return [4 /*yield*/, delay_1];
104
+ case 1:
105
+ _a.sent();
106
+ return [2 /*return*/, promise];
107
+ case 2: return [2 /*return*/, delay_1];
108
+ case 3: return [3 /*break*/, 5];
109
+ case 4: return [2 /*return*/, Promise.reject(new TypeError('First argument to `delay` must be a number'))];
110
+ case 5: return [2 /*return*/];
111
+ }
112
+ });
113
+ });
114
+ }
115
+ function timeout() {
116
+ var args = [];
117
+ for (var _i = 0; _i < arguments.length; _i++) {
118
+ args[_i] = arguments[_i];
119
+ }
120
+ return __awaiter(this, void 0, Promise, function () {
121
+ var ms, promise, timer_1, timeout_1, res;
122
+ return __generator(this, function (_a) {
123
+ switch (_a.label) {
124
+ case 0:
125
+ ms = args[0];
126
+ if (!(typeof ms === 'number')) return [3 /*break*/, 4];
127
+ promise = args[1];
128
+ timeout_1 = new Promise(function (_, reject) {
129
+ timer_1 = setTimeout(function () { return reject(new Error("Promise timed out after ".concat(ms, "ms"))); }, ms);
130
+ });
131
+ if (!(promise != null)) return [3 /*break*/, 2];
132
+ return [4 /*yield*/, Promise.race([promise, timeout_1])];
133
+ case 1:
134
+ res = _a.sent();
135
+ clearTimeout(timer_1);
136
+ return [2 /*return*/, res];
137
+ case 2: return [2 /*return*/, timeout_1];
138
+ case 3: return [3 /*break*/, 5];
139
+ case 4: return [2 /*return*/, Promise.reject('First argument to `timeout` must be a number')];
140
+ case 5: return [2 /*return*/];
141
+ }
142
+ });
143
+ });
144
+ }
145
+ /**
146
+ * Executes and reattempts execution of an asynchronous function if it throws an
147
+ * error. By default, this function will only retry once and reexecute
148
+ * immediately after the previous execution throws. You can configure the number
149
+ * of retry attempts and delays with the `maxRetries` and `delaysInMs` options.
150
+ *
151
+ * The `delaysInMs` is an array of delays in milliseconds for each retry
152
+ * attempt. If there are more retry attempts than delays, the last delay will be
153
+ * used.
154
+ *
155
+ * @param process The process to execute.
156
+ * @param opts Options to configure retry behavior.
157
+ * @returns A promise that resolves with a successful value, or the original
158
+ * rejected value if the process fails.
159
+ */
160
+ function retry(process_1) {
161
+ return __awaiter(this, arguments, Promise, function (process, opts) {
162
+ function execute(attempt, process, opts) {
163
+ return __awaiter(this, void 0, Promise, function () {
164
+ var _a, delaysInMs, _b, maxRetries, delayInMs, e_2;
165
+ return __generator(this, function (_c) {
166
+ switch (_c.label) {
167
+ case 0:
168
+ _a = opts.delaysInMs, delaysInMs = _a === void 0 ? [] : _a, _b = opts.maxRetries, maxRetries = _b === void 0 ? 1 : _b;
169
+ _c.label = 1;
170
+ case 1:
171
+ _c.trys.push([1, 4, , 8]);
172
+ delayInMs = attempt === 0 || delaysInMs.length === 0
173
+ ? 0
174
+ : delaysInMs[Math.min(attempt - 1, delaysInMs.length - 1)];
175
+ return [4 /*yield*/, delay(delayInMs)];
176
+ case 2:
177
+ _c.sent();
178
+ return [4 /*yield*/, process()];
179
+ case 3: return [2 /*return*/, _c.sent()];
180
+ case 4:
181
+ e_2 = _c.sent();
182
+ if (!(attempt < maxRetries)) return [3 /*break*/, 6];
183
+ return [4 /*yield*/, execute(attempt + 1, process, opts)];
184
+ case 5: return [2 /*return*/, _c.sent()];
185
+ case 6: throw e_2;
186
+ case 7: return [3 /*break*/, 8];
187
+ case 8: return [2 /*return*/];
188
+ }
189
+ });
190
+ });
191
+ }
192
+ if (opts === void 0) { opts = {}; }
193
+ return __generator(this, function (_a) {
194
+ return [2 /*return*/, execute(0, process, opts)];
195
+ });
196
+ });
197
+ }
198
+ /**
199
+ * Returns a promise that either resolves with the result of `promise`, or a
200
+ * value that indicates the execution was aborted.
201
+ *
202
+ * **Note:** Because Promises in JS cannot be canceled, an abort signal will not
203
+ * cancel the execution of the promise.
204
+ *
205
+ * @param signal A signal that communicates the process should be aborted.
206
+ * @param promise A promise who's value will be returned if not aborted.
207
+ * @returns A value indicating if the process was aborted, or the value of
208
+ * `promise`.
209
+ */
210
+ function abort(signal, promise) {
211
+ return __awaiter(this, void 0, Promise, function () {
212
+ var controller, pendingAbort, result;
213
+ return __generator(this, function (_a) {
214
+ switch (_a.label) {
215
+ case 0:
216
+ controller = new AbortController();
217
+ pendingAbort = once(signal, 'abort', { signal: controller.signal });
218
+ return [4 /*yield*/, Promise.race([promise, pendingAbort])];
219
+ case 1:
220
+ result = _a.sent();
221
+ if (isAbortEvent(result)) {
222
+ return [2 /*return*/, { aborted: true }];
223
+ }
224
+ else {
225
+ controller.abort();
226
+ return [2 /*return*/, { aborted: false, result: result }];
227
+ }
228
+ }
229
+ });
230
+ });
231
+ }
232
+ function isAbortEvent(obj) {
233
+ if (obj instanceof Event) {
234
+ return obj.type === 'abort';
235
+ }
236
+ else
237
+ return false;
231
238
  }
232
239
 
233
240
  var async = /*#__PURE__*/Object.freeze({
@@ -239,48 +246,48 @@ var async = /*#__PURE__*/Object.freeze({
239
246
  abort: abort
240
247
  });
241
248
 
242
- /**
243
- * Returns a new `BinaryReader` for an `ArrayBuffer`.
244
- */
245
- var fromArrayBuffer = function (buffer) {
246
- return { offset: 0, data: new DataView(buffer) };
247
- };
248
- /**
249
- * Returns a `BinaryReader` that contains the read Int32 value at the given
250
- * reader's offset. The returned reader will have its offset adjusted so it can
251
- * be passed to the next helper.
252
- */
253
- var readInt32 = function (reader) {
254
- var value = reader.data.getInt32(reader.offset);
255
- return __assign(__assign({}, reader), { offset: reader.offset + 4, value: value });
256
- };
257
- /**
258
- * Returns a `BinaryReader` that contains the read UTF-8 string at the given
259
- * reader's offset. The returned reader will have its offset adjusted so it can
260
- * be passed to the next helper.
261
- */
262
- var readUtf8String = function (length, reader) {
263
- var value = String.fromCharCode.apply(null, Array.from(new Uint8Array(reader.data.buffer, reader.offset, length)));
264
- return __assign(__assign({}, reader), { offset: reader.offset + length, value: value });
265
- };
266
- /**
267
- * Returns a `BinaryReader` that contains the a signed `Int8Array` start from
268
- * the given reader's offset to the given length. The returned reader will have
269
- * its offset adjusted so it can be passed to the next helper.
270
- */
271
- var readInt8Array = function (length, reader) {
272
- var value = new Int8Array(reader.data.buffer, reader.offset, length);
273
- return __assign(__assign({}, reader), { offset: reader.offset + length, value: value });
274
- };
275
- /**
276
- * Returns a `BinaryReader` that contains the a signed `Int8Array` sliced from
277
- * the start of the reader's offset to offset + length. The new reader value has
278
- * an offset of zero, so downstream operations will not bee effected by the
279
- * previous offset
280
- */
281
- var sliceInt8Array = function (length, reader) {
282
- var value = new Int8Array(reader.data.buffer.slice(reader.offset, length + reader.offset));
283
- return __assign(__assign({}, reader), { offset: 0, value: value });
249
+ /**
250
+ * Returns a new `BinaryReader` for an `ArrayBuffer`.
251
+ */
252
+ var fromArrayBuffer = function (buffer) {
253
+ return { offset: 0, data: new DataView(buffer) };
254
+ };
255
+ /**
256
+ * Returns a `BinaryReader` that contains the read Int32 value at the given
257
+ * reader's offset. The returned reader will have its offset adjusted so it can
258
+ * be passed to the next helper.
259
+ */
260
+ var readInt32 = function (reader) {
261
+ var value = reader.data.getInt32(reader.offset);
262
+ return __assign(__assign({}, reader), { offset: reader.offset + 4, value: value });
263
+ };
264
+ /**
265
+ * Returns a `BinaryReader` that contains the read UTF-8 string at the given
266
+ * reader's offset. The returned reader will have its offset adjusted so it can
267
+ * be passed to the next helper.
268
+ */
269
+ var readUtf8String = function (length, reader) {
270
+ var value = String.fromCharCode.apply(null, Array.from(new Uint8Array(reader.data.buffer, reader.offset, length)));
271
+ return __assign(__assign({}, reader), { offset: reader.offset + length, value: value });
272
+ };
273
+ /**
274
+ * Returns a `BinaryReader` that contains the a signed `Int8Array` start from
275
+ * the given reader's offset to the given length. The returned reader will have
276
+ * its offset adjusted so it can be passed to the next helper.
277
+ */
278
+ var readInt8Array = function (length, reader) {
279
+ var value = new Int8Array(reader.data.buffer, reader.offset, length);
280
+ return __assign(__assign({}, reader), { offset: reader.offset + length, value: value });
281
+ };
282
+ /**
283
+ * Returns a `BinaryReader` that contains the a signed `Int8Array` sliced from
284
+ * the start of the reader's offset to offset + length. The new reader value has
285
+ * an offset of zero, so downstream operations will not bee effected by the
286
+ * previous offset
287
+ */
288
+ var sliceInt8Array = function (length, reader) {
289
+ var value = new Int8Array(reader.data.buffer.slice(reader.offset, length + reader.offset));
290
+ return __assign(__assign({}, reader), { offset: 0, value: value });
284
291
  };
285
292
 
286
293
  var binaryReader = /*#__PURE__*/Object.freeze({
@@ -292,85 +299,85 @@ var binaryReader = /*#__PURE__*/Object.freeze({
292
299
  sliceInt8Array: sliceInt8Array
293
300
  });
294
301
 
295
- var rgbRegex = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
296
- var rgbaRegex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(.+)\s*\)/;
297
- var hexRegex = /^(#|0x)?([A-Fa-f0-9]{6})$/;
298
- /**
299
- * Constructs a new color with the given red, green, blue and alpha values. If
300
- * alpha is undefined, defaults to 1.
301
- */
302
- var create$2 = function (r, g, b, a) {
303
- if (a === void 0) { a = 255; }
304
- return { r: r, g: g, b: b, a: a };
305
- };
306
- /**
307
- * Converts a numeric color value containing red, green and blue values to a
308
- * `Color`. The alpha channel will default to fully opaque.
309
- */
310
- var fromNumber = function (num) {
311
- // tslint:disable:no-bitwise
312
- var normalized = num & 0xffffff;
313
- return create$2((normalized >> 16) & 0xff, (normalized >> 8) & 0xff, normalized & 0xff);
314
- // tslint:enable:no-bitwise
315
- };
316
- /**
317
- * Returns a `Color` from a hex string, or undefined if the color string cannot
318
- * be parsed. Supports hex strings in the format of `"#00FF00"`, `"0x00FF00"` or
319
- * `"00FF00"`.
320
- */
321
- var fromHexString = function (str) {
322
- var match = hexRegex.exec(str);
323
- if (match != null) {
324
- return fromNumber(parseInt(match[2], 16));
325
- }
326
- };
327
- /**
328
- * Creates a `Color` from a CSS color value. This function currently only
329
- * supports `rgb(255, 255, 255)`, `rgba(255, 255, 255, 0.5)` or `"#FFFFFF"`.
330
- * Returns `undefined` if the color cannot be parsed.
331
- */
332
- var fromCss = function (css) {
333
- var rgbMatch = rgbRegex.exec(css);
334
- if (rgbMatch != null) {
335
- return create$2(parseInt(rgbMatch[1]), parseInt(rgbMatch[2]), parseInt(rgbMatch[3]));
336
- }
337
- var rgbaMatch = rgbaRegex.exec(css);
338
- if (rgbaMatch != null) {
339
- return create$2(parseInt(rgbaMatch[1]), parseInt(rgbaMatch[2]), parseInt(rgbaMatch[3]), Math.floor(parseFloat(rgbaMatch[4]) * 255));
340
- }
341
- if (hexRegex.test(css)) {
342
- return fromHexString(css);
343
- }
344
- };
345
- /**
346
- * Converts an array of four values to a `Color`. The sequence of the array is
347
- * expected to be `[r, g, b]` or `[r, g, b, a]`.
348
- */
349
- var fromArray = function (rgba) {
350
- return create$2(rgba[0], rgba[1], rgba[2], rgba[3]);
351
- };
352
- /**
353
- * Returns `true` if the color's alpha channel is 0.
354
- */
355
- var isInvisible = function (color) {
356
- return color.a === 0;
357
- };
358
- /**
359
- * Returns `true` if the alpha channel of this color is fully opaque (255).
360
- */
361
- var isOpaque = function (color) {
362
- return color.a === 255;
363
- };
364
- /**
365
- * Converts a `Color` to a hex string. The returned string will be prefixed with
366
- * `#`.
367
- */
368
- var toHexString = function (color) {
369
- return "#".concat(componentToHex(color.r)).concat(componentToHex(color.g)).concat(componentToHex(color.b));
370
- };
371
- var componentToHex = function (num) {
372
- var hex = num.toString(16);
373
- return hex.length === 1 ? '0' + hex : hex;
302
+ var rgbRegex = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
303
+ var rgbaRegex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(.+)\s*\)/;
304
+ var hexRegex = /^(#|0x)?([A-Fa-f0-9]{6})$/;
305
+ /**
306
+ * Constructs a new color with the given red, green, blue and alpha values. If
307
+ * alpha is undefined, defaults to 1.
308
+ */
309
+ var create$2 = function (r, g, b, a) {
310
+ if (a === void 0) { a = 255; }
311
+ return { r: r, g: g, b: b, a: a };
312
+ };
313
+ /**
314
+ * Converts a numeric color value containing red, green and blue values to a
315
+ * `Color`. The alpha channel will default to fully opaque.
316
+ */
317
+ var fromNumber = function (num) {
318
+ // tslint:disable:no-bitwise
319
+ var normalized = num & 0xffffff;
320
+ return create$2((normalized >> 16) & 0xff, (normalized >> 8) & 0xff, normalized & 0xff);
321
+ // tslint:enable:no-bitwise
322
+ };
323
+ /**
324
+ * Returns a `Color` from a hex string, or undefined if the color string cannot
325
+ * be parsed. Supports hex strings in the format of `"#00FF00"`, `"0x00FF00"` or
326
+ * `"00FF00"`.
327
+ */
328
+ var fromHexString = function (str) {
329
+ var match = hexRegex.exec(str);
330
+ if (match != null) {
331
+ return fromNumber(parseInt(match[2], 16));
332
+ }
333
+ };
334
+ /**
335
+ * Creates a `Color` from a CSS color value. This function currently only
336
+ * supports `rgb(255, 255, 255)`, `rgba(255, 255, 255, 0.5)` or `"#FFFFFF"`.
337
+ * Returns `undefined` if the color cannot be parsed.
338
+ */
339
+ var fromCss = function (css) {
340
+ var rgbMatch = rgbRegex.exec(css);
341
+ if (rgbMatch != null) {
342
+ return create$2(parseInt(rgbMatch[1]), parseInt(rgbMatch[2]), parseInt(rgbMatch[3]));
343
+ }
344
+ var rgbaMatch = rgbaRegex.exec(css);
345
+ if (rgbaMatch != null) {
346
+ return create$2(parseInt(rgbaMatch[1]), parseInt(rgbaMatch[2]), parseInt(rgbaMatch[3]), Math.floor(parseFloat(rgbaMatch[4]) * 255));
347
+ }
348
+ if (hexRegex.test(css)) {
349
+ return fromHexString(css);
350
+ }
351
+ };
352
+ /**
353
+ * Converts an array of four values to a `Color`. The sequence of the array is
354
+ * expected to be `[r, g, b]` or `[r, g, b, a]`.
355
+ */
356
+ var fromArray = function (rgba) {
357
+ return create$2(rgba[0], rgba[1], rgba[2], rgba[3]);
358
+ };
359
+ /**
360
+ * Returns `true` if the color's alpha channel is 0.
361
+ */
362
+ var isInvisible = function (color) {
363
+ return color.a === 0;
364
+ };
365
+ /**
366
+ * Returns `true` if the alpha channel of this color is fully opaque (255).
367
+ */
368
+ var isOpaque = function (color) {
369
+ return color.a === 255;
370
+ };
371
+ /**
372
+ * Converts a `Color` to a hex string. The returned string will be prefixed with
373
+ * `#`.
374
+ */
375
+ var toHexString = function (color) {
376
+ return "#".concat(componentToHex(color.r)).concat(componentToHex(color.g)).concat(componentToHex(color.b));
377
+ };
378
+ var componentToHex = function (num) {
379
+ var hex = num.toString(16);
380
+ return hex.length === 1 ? '0' + hex : hex;
374
381
  };
375
382
 
376
383
  var color = /*#__PURE__*/Object.freeze({
@@ -385,359 +392,359 @@ var color = /*#__PURE__*/Object.freeze({
385
392
  toHexString: toHexString
386
393
  });
387
394
 
388
- /**
389
- * A module for defining functional schemas to map between different types. This
390
- * module is useful for parsing to or from JSON/protobufs to domain types.
391
- *
392
- * Mappers support greedy validation, so all validation errors are aggregated
393
- * and reported vs failing on the first invalid input.
394
- *
395
- * @example
396
- *
397
- * ```ts
398
- * import { Mapper as M } from '@vertexvis/utils';
399
- *
400
- * interface Address {
401
- * address: string;
402
- * city: string;
403
- * state: string;
404
- * zip: string;
405
- * }
406
- *
407
- * interface Person {
408
- * name: string;
409
- * addresses: Address[];
410
- * }
411
- *
412
- * type AddressJson = Partial<Address>;
413
- * type PersonJson = {
414
- * name?: string;
415
- * addresses?: AddressJson[];
416
- * }
417
- *
418
- * const mapAddress: M.Func<AddressJson, Address> = M.defineMapper(
419
- * M.read(
420
- * M.requireProp('address'),
421
- * M.requireProp('city'),
422
- * M.requireProp('state'),
423
- * M.requireProp('zip')
424
- * ),
425
- * ([address, city, state, zip]) => ({
426
- * address, city, state, zip
427
- * })
428
- * );
429
- *
430
- * const mapPerson: M.Func<PersonJson, Person> = M.defineMapper(
431
- * M.read(
432
- * M.requireProp('name'),
433
- * M.mapProp(
434
- * 'addresses',
435
- * M.compose(M.required('addresses'), M.mapArray(mapAddress))
436
- * )
437
- * ),
438
- * ([name, addresses]) => ({ name, addresses })
439
- * );
440
- *
441
- * const person = mapPerson({
442
- * name: 'John',
443
- * addresses: [{ address: '123', city: 'Ames', state: 'IA', zip: '50010' }]
444
- * });
445
- *
446
- * const invalidPerson = mapPerson({
447
- * addresses: [{ city: 'Ames', state: 'IA', zip: '50010' }]
448
- * });
449
- * ```
450
- * // {
451
- * // errors: ["Name is required.", "Address is required."]
452
- * // }
453
- *
454
- * @module
455
- */
456
- /**
457
- * An error that is thrown when validation of a schema fails.
458
- *
459
- * @see {@link ifInvalidThrow} - for throwing errors on invalid input.
460
- */
461
- var MapperValidationError = /** @class */ (function (_super) {
462
- __extends(MapperValidationError, _super);
463
- function MapperValidationError(errors) {
464
- var _this = _super.call(this, 'Validation error mapping object.') || this;
465
- _this.errors = errors;
466
- Object.setPrototypeOf(_this, MapperValidationError.prototype);
467
- return _this;
468
- }
469
- return MapperValidationError;
470
- }(Error));
471
- /**
472
- * Returns a mapper that asserts the input is not null or not undefined.
473
- *
474
- * @param name A name to report when invalid.
475
- */
476
- function required(name) {
477
- return function (input) {
478
- if (input != null) {
479
- return input;
480
- }
481
- else {
482
- return { errors: ["".concat(name, " is required.")] };
483
- }
484
- };
485
- }
486
- /**
487
- * Returns a mapper that asserts a property on the input is not null or not
488
- * defined.
489
- *
490
- * @param prop The prop to assert.
491
- * @returns A mapper that returns the property's value.
492
- */
493
- function requiredProp(prop) {
494
- return function (obj) {
495
- var value = obj[prop];
496
- if (value != null) {
497
- return value;
498
- }
499
- else {
500
- return { errors: ["".concat(String(prop), " is required")] };
501
- }
502
- };
503
- }
504
- /**
505
- * Returns a mapper that invokes a function if the input is not null or not
506
- * undefined.
507
- *
508
- * @param mapper A mapping function.
509
- */
510
- function ifDefined(mapper) {
511
- return function (input) {
512
- if (input != null) {
513
- return mapper(input);
514
- }
515
- else {
516
- return input;
517
- }
518
- };
519
- }
520
- /**
521
- * Returns a mapper that extracts a property's value.
522
- *
523
- * @param prop The property to extract.
524
- */
525
- function getProp(prop) {
526
- return function (input) {
527
- return input[prop];
528
- };
529
- }
530
- /**
531
- * Returns a mapper that will invoke a mapping function on an input's property.
532
- *
533
- * @param prop The name of the property to map over.
534
- * @param mapper A function that will be invoked with the property's value.
535
- */
536
- function mapProp(prop, mapper) {
537
- return function (input) {
538
- var value = input[prop];
539
- return mapper(value);
540
- };
541
- }
542
- /**
543
- * Returns a mapper that will check if the given property is defined, and if so
544
- * invoke the given mapping function.
545
- *
546
- * @param prop The name of the property to map over.
547
- * @param mapper A function that will be invoked with the property's value if
548
- * the property is defined.
549
- */
550
- function mapRequiredProp(prop, mapper) {
551
- return mapProp(prop, compose(required(prop.toString()), mapper));
552
- }
553
- /**
554
- * Returns a mapper that will invoke a mapper over each value in the input
555
- * array. Returns `Invalid` containing errors for all invalid values in the
556
- * array.
557
- *
558
- * @param mapper A function that will be invoked with each array value.
559
- * @returns
560
- */
561
- function mapArray(mapper) {
562
- return function (inputs) {
563
- if (inputs.length > 0) {
564
- var _a = __read(inputs), head = _a[0], tail = _a.slice(1);
565
- var first = mapper(head);
566
- return tail.reduce(function (res, input) {
567
- var value = mapper(input);
568
- if (isInvalid(value)) {
569
- return isInvalid(res)
570
- ? { errors: __spreadArray(__spreadArray([], __read(res.errors), false), __read(value.errors), false) }
571
- : value;
572
- }
573
- else if (isInvalid(res)) {
574
- return res;
575
- }
576
- else {
577
- return __spreadArray(__spreadArray([], __read(res), false), [value], false);
578
- }
579
- }, isInvalid(first) ? first : [first]);
580
- }
581
- else {
582
- return [];
583
- }
584
- };
585
- }
586
- /**
587
- * A type guard that checks if the object is an `Invalid` type.
588
- */
589
- function isInvalid(obj) {
590
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
591
- return obj != null && obj.hasOwnProperty('errors');
592
- }
593
- /**
594
- * Returns a function that throws an error if the input is invalid. Otherwise,
595
- * returns the result.
596
- *
597
- * @param mapper A mapper that will be invoked with the input.
598
- * @throws {@link MapperValidationError} If the input is invalid.
599
- */
600
- function ifInvalidThrow(mapper) {
601
- return function (input) {
602
- var value = mapper(input);
603
- if (isInvalid(value)) {
604
- throw new MapperValidationError(value.errors);
605
- }
606
- else
607
- return value;
608
- };
609
- }
610
- function ifValidThen(obj, f) {
611
- if (isInvalid(obj)) {
612
- return obj;
613
- }
614
- else {
615
- return f(obj);
616
- }
617
- }
618
- function read() {
619
- var mappers = [];
620
- for (var _i = 0; _i < arguments.length; _i++) {
621
- mappers[_i] = arguments[_i];
622
- }
623
- return function (input) {
624
- return mappers.reduce(function (res, decoder) {
625
- var value = decoder(input);
626
- if (isInvalid(value)) {
627
- return isInvalid(res)
628
- ? { errors: __spreadArray(__spreadArray([], __read(res.errors), false), __read(value.errors), false) }
629
- : value;
630
- }
631
- else if (isInvalid(res)) {
632
- return res;
633
- }
634
- else {
635
- return __spreadArray(__spreadArray([], __read(res), false), [value], false);
636
- }
637
- }, []);
638
- };
639
- }
640
- /* eslint-enable padding-line-between-statements */
641
- /**
642
- * Defines a mapper that reads the values from an input and invokes a builder to
643
- * transform data from one schema to another.
644
- *
645
- * @example
646
- *
647
- * ```ts
648
- * import { Mapper as M } from '@vertexvis/utils';
649
- *
650
- * interface Address {
651
- * address: string;
652
- * city: string;
653
- * state: string;
654
- * zip: string;
655
- * }
656
- *
657
- * interface Person {
658
- * name: string;
659
- * addresses: Address[];
660
- * }
661
- *
662
- * type AddressJson = Partial<Address>;
663
- * type PersonJson = {
664
- * name?: string;
665
- * addresses?: AddressJson[];
666
- * }
667
- *
668
- * const mapAddress: M.Func<AddressJson, Address> = M.defineMapper(
669
- * M.read(
670
- * M.requireProp('address'),
671
- * M.requireProp('city'),
672
- * M.requireProp('state'),
673
- * M.requireProp('zip')
674
- * ),
675
- * ([address, city, state, zip]) => ({
676
- * address, city, state, zip
677
- * })
678
- * );
679
- *
680
- * const mapPerson: M.Func<PersonJson, Person> = M.defineMapper(
681
- * M.read(
682
- * M.requireProp('name'),
683
- * M.mapProp(
684
- * 'addresses',
685
- * M.compose(M.required('addresses'), M.mapArray(mapAddress))
686
- * )
687
- * ),
688
- * ([name, addresses]) => ({ name, addresses })
689
- * )
690
- *
691
- * const person = mapPerson({
692
- * name: 'John',
693
- * addresses: [{ address: '123', city: 'Ames', state: 'IA', zip: '50010' }]
694
- * })
695
- * ```
696
- *
697
- * @param reader The mapper that reads values from the input an creates an
698
- * intermediate format that will be passed to the `builder`.
699
- * @param builder A mapper that takes the output of `reader` and constructs the
700
- * output format.
701
- * @see {@link read} - a helper function to read and validate input values.
702
- */
703
- function defineMapper(reader, builder) {
704
- return function (input) {
705
- var values = reader(input);
706
- return ifValidThen(values, builder);
707
- };
708
- }
709
- function compose() {
710
- var decoders = [];
711
- for (var _i = 0; _i < arguments.length; _i++) {
712
- decoders[_i] = arguments[_i];
713
- }
714
- return function (input) {
715
- return decoders.reduce(function (last, decoder) {
716
- if (isInvalid(last)) {
717
- return last;
718
- }
719
- else {
720
- return decoder(last);
721
- }
722
- }, input);
723
- };
724
- }
725
- function pickFirst() {
726
- var decoders = [];
727
- for (var _i = 0; _i < arguments.length; _i++) {
728
- decoders[_i] = arguments[_i];
729
- }
730
- return function (input) {
731
- return decoders.reduce(function (value, decoder) {
732
- if (value === undefined) {
733
- return decoder(input);
734
- }
735
- else {
736
- return value;
737
- }
738
- }, undefined);
739
- };
740
- }
395
+ /**
396
+ * A module for defining functional schemas to map between different types. This
397
+ * module is useful for parsing to or from JSON/protobufs to domain types.
398
+ *
399
+ * Mappers support greedy validation, so all validation errors are aggregated
400
+ * and reported vs failing on the first invalid input.
401
+ *
402
+ * @example
403
+ *
404
+ * ```ts
405
+ * import { Mapper as M } from '@vertexvis/utils';
406
+ *
407
+ * interface Address {
408
+ * address: string;
409
+ * city: string;
410
+ * state: string;
411
+ * zip: string;
412
+ * }
413
+ *
414
+ * interface Person {
415
+ * name: string;
416
+ * addresses: Address[];
417
+ * }
418
+ *
419
+ * type AddressJson = Partial<Address>;
420
+ * type PersonJson = {
421
+ * name?: string;
422
+ * addresses?: AddressJson[];
423
+ * }
424
+ *
425
+ * const mapAddress: M.Func<AddressJson, Address> = M.defineMapper(
426
+ * M.read(
427
+ * M.requireProp('address'),
428
+ * M.requireProp('city'),
429
+ * M.requireProp('state'),
430
+ * M.requireProp('zip')
431
+ * ),
432
+ * ([address, city, state, zip]) => ({
433
+ * address, city, state, zip
434
+ * })
435
+ * );
436
+ *
437
+ * const mapPerson: M.Func<PersonJson, Person> = M.defineMapper(
438
+ * M.read(
439
+ * M.requireProp('name'),
440
+ * M.mapProp(
441
+ * 'addresses',
442
+ * M.compose(M.required('addresses'), M.mapArray(mapAddress))
443
+ * )
444
+ * ),
445
+ * ([name, addresses]) => ({ name, addresses })
446
+ * );
447
+ *
448
+ * const person = mapPerson({
449
+ * name: 'John',
450
+ * addresses: [{ address: '123', city: 'Ames', state: 'IA', zip: '50010' }]
451
+ * });
452
+ *
453
+ * const invalidPerson = mapPerson({
454
+ * addresses: [{ city: 'Ames', state: 'IA', zip: '50010' }]
455
+ * });
456
+ * ```
457
+ * // {
458
+ * // errors: ["Name is required.", "Address is required."]
459
+ * // }
460
+ *
461
+ * @module
462
+ */
463
+ /**
464
+ * An error that is thrown when validation of a schema fails.
465
+ *
466
+ * @see {@link ifInvalidThrow} - for throwing errors on invalid input.
467
+ */
468
+ var MapperValidationError = /** @class */ (function (_super) {
469
+ __extends(MapperValidationError, _super);
470
+ function MapperValidationError(errors) {
471
+ var _this = _super.call(this, 'Validation error mapping object.') || this;
472
+ _this.errors = errors;
473
+ Object.setPrototypeOf(_this, MapperValidationError.prototype);
474
+ return _this;
475
+ }
476
+ return MapperValidationError;
477
+ }(Error));
478
+ /**
479
+ * Returns a mapper that asserts the input is not null or not undefined.
480
+ *
481
+ * @param name A name to report when invalid.
482
+ */
483
+ function required(name) {
484
+ return function (input) {
485
+ if (input != null) {
486
+ return input;
487
+ }
488
+ else {
489
+ return { errors: ["".concat(name, " is required.")] };
490
+ }
491
+ };
492
+ }
493
+ /**
494
+ * Returns a mapper that asserts a property on the input is not null or not
495
+ * defined.
496
+ *
497
+ * @param prop The prop to assert.
498
+ * @returns A mapper that returns the property's value.
499
+ */
500
+ function requiredProp(prop) {
501
+ return function (obj) {
502
+ var value = obj[prop];
503
+ if (value != null) {
504
+ return value;
505
+ }
506
+ else {
507
+ return { errors: ["".concat(String(prop), " is required")] };
508
+ }
509
+ };
510
+ }
511
+ /**
512
+ * Returns a mapper that invokes a function if the input is not null or not
513
+ * undefined.
514
+ *
515
+ * @param mapper A mapping function.
516
+ */
517
+ function ifDefined(mapper) {
518
+ return function (input) {
519
+ if (input != null) {
520
+ return mapper(input);
521
+ }
522
+ else {
523
+ return input;
524
+ }
525
+ };
526
+ }
527
+ /**
528
+ * Returns a mapper that extracts a property's value.
529
+ *
530
+ * @param prop The property to extract.
531
+ */
532
+ function getProp(prop) {
533
+ return function (input) {
534
+ return input[prop];
535
+ };
536
+ }
537
+ /**
538
+ * Returns a mapper that will invoke a mapping function on an input's property.
539
+ *
540
+ * @param prop The name of the property to map over.
541
+ * @param mapper A function that will be invoked with the property's value.
542
+ */
543
+ function mapProp(prop, mapper) {
544
+ return function (input) {
545
+ var value = input[prop];
546
+ return mapper(value);
547
+ };
548
+ }
549
+ /**
550
+ * Returns a mapper that will check if the given property is defined, and if so
551
+ * invoke the given mapping function.
552
+ *
553
+ * @param prop The name of the property to map over.
554
+ * @param mapper A function that will be invoked with the property's value if
555
+ * the property is defined.
556
+ */
557
+ function mapRequiredProp(prop, mapper) {
558
+ return mapProp(prop, compose(required(prop.toString()), mapper));
559
+ }
560
+ /**
561
+ * Returns a mapper that will invoke a mapper over each value in the input
562
+ * array. Returns `Invalid` containing errors for all invalid values in the
563
+ * array.
564
+ *
565
+ * @param mapper A function that will be invoked with each array value.
566
+ * @returns
567
+ */
568
+ function mapArray(mapper) {
569
+ return function (inputs) {
570
+ if (inputs.length > 0) {
571
+ var _a = __read(inputs), head = _a[0], tail = _a.slice(1);
572
+ var first = mapper(head);
573
+ return tail.reduce(function (res, input) {
574
+ var value = mapper(input);
575
+ if (isInvalid(value)) {
576
+ return isInvalid(res)
577
+ ? { errors: __spreadArray(__spreadArray([], __read(res.errors), false), __read(value.errors), false) }
578
+ : value;
579
+ }
580
+ else if (isInvalid(res)) {
581
+ return res;
582
+ }
583
+ else {
584
+ return __spreadArray(__spreadArray([], __read(res), false), [value], false);
585
+ }
586
+ }, isInvalid(first) ? first : [first]);
587
+ }
588
+ else {
589
+ return [];
590
+ }
591
+ };
592
+ }
593
+ /**
594
+ * A type guard that checks if the object is an `Invalid` type.
595
+ */
596
+ function isInvalid(obj) {
597
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
598
+ return obj != null && obj.hasOwnProperty('errors');
599
+ }
600
+ /**
601
+ * Returns a function that throws an error if the input is invalid. Otherwise,
602
+ * returns the result.
603
+ *
604
+ * @param mapper A mapper that will be invoked with the input.
605
+ * @throws {@link MapperValidationError} If the input is invalid.
606
+ */
607
+ function ifInvalidThrow(mapper) {
608
+ return function (input) {
609
+ var value = mapper(input);
610
+ if (isInvalid(value)) {
611
+ throw new MapperValidationError(value.errors);
612
+ }
613
+ else
614
+ return value;
615
+ };
616
+ }
617
+ function ifValidThen(obj, f) {
618
+ if (isInvalid(obj)) {
619
+ return obj;
620
+ }
621
+ else {
622
+ return f(obj);
623
+ }
624
+ }
625
+ function read() {
626
+ var mappers = [];
627
+ for (var _i = 0; _i < arguments.length; _i++) {
628
+ mappers[_i] = arguments[_i];
629
+ }
630
+ return function (input) {
631
+ return mappers.reduce(function (res, decoder) {
632
+ var value = decoder(input);
633
+ if (isInvalid(value)) {
634
+ return isInvalid(res)
635
+ ? { errors: __spreadArray(__spreadArray([], __read(res.errors), false), __read(value.errors), false) }
636
+ : value;
637
+ }
638
+ else if (isInvalid(res)) {
639
+ return res;
640
+ }
641
+ else {
642
+ return __spreadArray(__spreadArray([], __read(res), false), [value], false);
643
+ }
644
+ }, []);
645
+ };
646
+ }
647
+ /* eslint-enable padding-line-between-statements */
648
+ /**
649
+ * Defines a mapper that reads the values from an input and invokes a builder to
650
+ * transform data from one schema to another.
651
+ *
652
+ * @example
653
+ *
654
+ * ```ts
655
+ * import { Mapper as M } from '@vertexvis/utils';
656
+ *
657
+ * interface Address {
658
+ * address: string;
659
+ * city: string;
660
+ * state: string;
661
+ * zip: string;
662
+ * }
663
+ *
664
+ * interface Person {
665
+ * name: string;
666
+ * addresses: Address[];
667
+ * }
668
+ *
669
+ * type AddressJson = Partial<Address>;
670
+ * type PersonJson = {
671
+ * name?: string;
672
+ * addresses?: AddressJson[];
673
+ * }
674
+ *
675
+ * const mapAddress: M.Func<AddressJson, Address> = M.defineMapper(
676
+ * M.read(
677
+ * M.requireProp('address'),
678
+ * M.requireProp('city'),
679
+ * M.requireProp('state'),
680
+ * M.requireProp('zip')
681
+ * ),
682
+ * ([address, city, state, zip]) => ({
683
+ * address, city, state, zip
684
+ * })
685
+ * );
686
+ *
687
+ * const mapPerson: M.Func<PersonJson, Person> = M.defineMapper(
688
+ * M.read(
689
+ * M.requireProp('name'),
690
+ * M.mapProp(
691
+ * 'addresses',
692
+ * M.compose(M.required('addresses'), M.mapArray(mapAddress))
693
+ * )
694
+ * ),
695
+ * ([name, addresses]) => ({ name, addresses })
696
+ * )
697
+ *
698
+ * const person = mapPerson({
699
+ * name: 'John',
700
+ * addresses: [{ address: '123', city: 'Ames', state: 'IA', zip: '50010' }]
701
+ * })
702
+ * ```
703
+ *
704
+ * @param reader The mapper that reads values from the input an creates an
705
+ * intermediate format that will be passed to the `builder`.
706
+ * @param builder A mapper that takes the output of `reader` and constructs the
707
+ * output format.
708
+ * @see {@link read} - a helper function to read and validate input values.
709
+ */
710
+ function defineMapper(reader, builder) {
711
+ return function (input) {
712
+ var values = reader(input);
713
+ return ifValidThen(values, builder);
714
+ };
715
+ }
716
+ function compose() {
717
+ var decoders = [];
718
+ for (var _i = 0; _i < arguments.length; _i++) {
719
+ decoders[_i] = arguments[_i];
720
+ }
721
+ return function (input) {
722
+ return decoders.reduce(function (last, decoder) {
723
+ if (isInvalid(last)) {
724
+ return last;
725
+ }
726
+ else {
727
+ return decoder(last);
728
+ }
729
+ }, input);
730
+ };
731
+ }
732
+ function pickFirst() {
733
+ var decoders = [];
734
+ for (var _i = 0; _i < arguments.length; _i++) {
735
+ decoders[_i] = arguments[_i];
736
+ }
737
+ return function (input) {
738
+ return decoders.reduce(function (value, decoder) {
739
+ if (value === undefined) {
740
+ return decoder(input);
741
+ }
742
+ else {
743
+ return value;
744
+ }
745
+ }, undefined);
746
+ };
747
+ }
741
748
  /* eslint-enable padding-line-between-statements */
742
749
 
743
750
  var mapper = /*#__PURE__*/Object.freeze({
@@ -758,186 +765,96 @@ var mapper = /*#__PURE__*/Object.freeze({
758
765
  pickFirst: pickFirst
759
766
  });
760
767
 
761
- // do not edit .js files directly - edit src/index.jst
762
-
763
-
764
-
765
- var fastDeepEqual = function equal(a, b) {
766
- if (a === b) return true;
767
-
768
- if (a && b && typeof a == 'object' && typeof b == 'object') {
769
- if (a.constructor !== b.constructor) return false;
770
-
771
- var length, i, keys;
772
- if (Array.isArray(a)) {
773
- length = a.length;
774
- if (length != b.length) return false;
775
- for (i = length; i-- !== 0;)
776
- if (!equal(a[i], b[i])) return false;
777
- return true;
768
+ function defaults() {
769
+ var objects = [];
770
+ for (var _i = 0; _i < arguments.length; _i++) {
771
+ objects[_i] = arguments[_i];
778
772
  }
779
-
780
-
781
-
782
- if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
783
- if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
784
- if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
785
-
786
- keys = Object.keys(a);
787
- length = keys.length;
788
- if (length !== Object.keys(b).length) return false;
789
-
790
- for (i = length; i-- !== 0;)
791
- if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
792
-
793
- for (i = length; i-- !== 0;) {
794
- var key = keys[i];
795
-
796
- if (!equal(a[key], b[key])) return false;
773
+ var _a = __read(objects), a = _a[0], other = _a.slice(1);
774
+ var result = __assign({}, a);
775
+ if (other.length === 0) {
776
+ return result;
797
777
  }
798
-
799
- return true;
800
- }
801
-
802
- // true if both NaN, false otherwise
803
- return a!==a && b!==b;
804
- };
805
-
806
- /*!
807
- * isobject <https://github.com/jonschlinkert/isobject>
778
+ else if (other.length === 1) {
779
+ var b = other[0];
780
+ for (var key in b) {
781
+ if (result[key] == null) {
782
+ result[key] = b[key];
783
+ }
784
+ else if (isPlainObject(result[key])) {
785
+ result[key] = defaults(result[key], b[key]);
786
+ }
787
+ }
788
+ return result;
789
+ }
790
+ else {
791
+ return other.reduce(function (result, next) { return defaults(result, next); }, a);
792
+ }
793
+ }
794
+ /* eslint-enable padding-line-between-statements */
795
+ /**
796
+ * Returns `true` if this is a plain object, which is defined by a type created
797
+ * by the `Object` constructor. Returns `false` otherwise.
798
+ *
799
+ * @example
800
+ * ```
801
+ * isPlainObject(Object.create({})); //=> true
802
+ * isPlainObject(Object.create(Object.prototype)); //=> true
803
+ * isPlainObject({foo: 'bar'}); //=> true
804
+ * isPlainObject({}); //=> true
808
805
  *
809
- * Copyright (c) 2014-2017, Jon Schlinkert.
810
- * Released under the MIT License.
806
+ * isPlainObject(1); //=> false
807
+ * isPlainObject(['foo', 'bar']); //=> false
808
+ * isPlainObject([]); //=> false
809
+ * isPlainObject(new Foo); //=> false
810
+ * isPlainObject(null); //=> false
811
+ * isPlainObject(Object.create(null)); //=> false
812
+ * ```
811
813
  */
812
-
813
- function isObject(val) {
814
- return val != null && typeof val === 'object' && Array.isArray(val) === false;
814
+ function isPlainObject(obj) {
815
+ return isSimpleObject(obj);
815
816
  }
816
-
817
- /*!
818
- * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
817
+ /**
818
+ * Performs a deep comparison of two objects and returns `true` if they're
819
+ * equal.
819
820
  *
820
- * Copyright (c) 2014-2017, Jon Schlinkert.
821
- * Released under the MIT License.
821
+ * This method supports comparing arrays, array buffers, booleans, date objects,
822
+ * error objects, maps, numbers, Object objects, regexes, sets, strings,
823
+ * symbols, and typed arrays. Object objects are compared by their own, not
824
+ * inherited, enumerable properties. Functions and DOM nodes are compared by
825
+ * strict equality, i.e. ===.
826
+ *
827
+ * @param a The object to compare with `b`.
828
+ * @param b The object to compare with `a`.
829
+ * @returns `true` if the two objects are equal. Otherwise `false`.
822
830
  */
823
-
824
- function isObjectObject(o) {
825
- return isObject(o) === true
826
- && Object.prototype.toString.call(o) === '[object Object]';
831
+ function isEqual$1(a, b) {
832
+ return fastDeepEqual(a, b);
827
833
  }
828
-
829
- function isPlainObject$1(o) {
830
- var ctor,prot;
831
-
832
- if (isObjectObject(o) === false) return false;
833
-
834
- // If has modified constructor
835
- ctor = o.constructor;
836
- if (typeof ctor !== 'function') return false;
837
-
838
- // If has modified prototype
839
- prot = ctor.prototype;
840
- if (isObjectObject(prot) === false) return false;
841
-
842
- // If constructor does not have an Object-specific method
843
- if (prot.hasOwnProperty('isPrototypeOf') === false) {
844
- return false;
845
- }
846
-
847
- // Most likely a plain Object
848
- return true;
834
+ function toPairs(obj) {
835
+ if (obj != null) {
836
+ return Object.keys(obj).map(function (key) { return [key, obj[key]]; });
837
+ }
838
+ else {
839
+ return [];
840
+ }
841
+ }
842
+ function fromPairs(pairs) {
843
+ if (Array.isArray(pairs)) {
844
+ return pairs.reduce(function (result, pair) {
845
+ var _a;
846
+ if (pair != null) {
847
+ return __assign(__assign({}, result), (_a = {}, _a[pair[0]] = pair[1], _a));
848
+ }
849
+ else {
850
+ return result;
851
+ }
852
+ }, {});
853
+ }
854
+ else {
855
+ return {};
856
+ }
849
857
  }
850
-
851
- function defaults() {
852
- var objects = [];
853
- for (var _i = 0; _i < arguments.length; _i++) {
854
- objects[_i] = arguments[_i];
855
- }
856
- var _a = __read(objects), a = _a[0], other = _a.slice(1);
857
- var result = __assign({}, a);
858
- if (other.length === 0) {
859
- return result;
860
- }
861
- else if (other.length === 1) {
862
- var b = other[0];
863
- for (var key in b) {
864
- if (result[key] == null) {
865
- result[key] = b[key];
866
- }
867
- else if (isPlainObject(result[key])) {
868
- result[key] = defaults(result[key], b[key]);
869
- }
870
- }
871
- return result;
872
- }
873
- else {
874
- return other.reduce(function (result, next) { return defaults(result, next); }, a);
875
- }
876
- }
877
- /* eslint-enable padding-line-between-statements */
878
- /**
879
- * Returns `true` if this is a plain object, which is defined by a type created
880
- * by the `Object` constructor. Returns `false` otherwise.
881
- *
882
- * @example
883
- * ```
884
- * isPlainObject(Object.create({})); //=> true
885
- * isPlainObject(Object.create(Object.prototype)); //=> true
886
- * isPlainObject({foo: 'bar'}); //=> true
887
- * isPlainObject({}); //=> true
888
- *
889
- * isPlainObject(1); //=> false
890
- * isPlainObject(['foo', 'bar']); //=> false
891
- * isPlainObject([]); //=> false
892
- * isPlainObject(new Foo); //=> false
893
- * isPlainObject(null); //=> false
894
- * isPlainObject(Object.create(null)); //=> false
895
- * ```
896
- */
897
- function isPlainObject(obj) {
898
- return isPlainObject$1(obj);
899
- }
900
- /**
901
- * Performs a deep comparison of two objects and returns `true` if they're
902
- * equal.
903
- *
904
- * This method supports comparing arrays, array buffers, booleans, date objects,
905
- * error objects, maps, numbers, Object objects, regexes, sets, strings,
906
- * symbols, and typed arrays. Object objects are compared by their own, not
907
- * inherited, enumerable properties. Functions and DOM nodes are compared by
908
- * strict equality, i.e. ===.
909
- *
910
- * @param a The object to compare with `b`.
911
- * @param b The object to compare with `a`.
912
- * @returns `true` if the two objects are equal. Otherwise `false`.
913
- */
914
- function isEqual$1(a, b) {
915
- return fastDeepEqual(a, b);
916
- }
917
- function toPairs(obj) {
918
- if (obj != null) {
919
- return Object.keys(obj).map(function (key) { return [key, obj[key]]; });
920
- }
921
- else {
922
- return [];
923
- }
924
- }
925
- function fromPairs(pairs) {
926
- if (Array.isArray(pairs)) {
927
- return pairs.reduce(function (result, pair) {
928
- var _a;
929
- if (pair != null) {
930
- return __assign(__assign({}, result), (_a = {}, _a[pair[0]] = pair[1], _a));
931
- }
932
- else {
933
- return result;
934
- }
935
- }, {});
936
- }
937
- else {
938
- return {};
939
- }
940
- }
941
858
  /* eslint-enable padding-line-between-statements */
942
859
 
943
860
  var objects = /*#__PURE__*/Object.freeze({
@@ -949,136 +866,136 @@ var objects = /*#__PURE__*/Object.freeze({
949
866
  fromPairs: fromPairs
950
867
  });
951
868
 
952
- /**
953
- * Returns a new `Range` with the given start and end points.
954
- */
955
- var create$1 = function (start, end) { return ({ start: start, end: end }); };
956
- /**
957
- * Returns a new `Range` with the start and end points at the given position.
958
- */
959
- var at = function (position) { return ({
960
- start: position,
961
- end: position,
962
- }); };
963
- /**
964
- * Returns a new `Range` with the given start point and length.
965
- */
966
- var withLength = function (start, len) { return ({
967
- start: start,
968
- end: start + len - 1,
969
- }); };
970
- /**
971
- * Returns a range with the start and end points shifted by the given distance.
972
- */
973
- var add = function (distance, range) {
974
- return create$1(range.start + distance, range.end + distance);
975
- };
976
- /**
977
- * Returns a range such that `range` is constrained to the start and end points
978
- * of `to`. The function will try to maintain the length of the range, but will
979
- * shrink the range if its length is greater than `to`.
980
- */
981
- var constrain = function (range, to) {
982
- if (contains(range, to)) {
983
- return range;
984
- }
985
- else if (length(range) > length(to)) {
986
- return to;
987
- }
988
- else if (range.start < to.start) {
989
- return create$1(to.start, to.start + length(range) - 1);
990
- }
991
- else {
992
- return create$1(to.end - length(range) + 1, to.end);
993
- }
994
- };
995
- /**
996
- * Checks if the given number or range is contained within another range.
997
- */
998
- var contains = function (numOrRange, range) {
999
- if (typeof numOrRange === 'number') {
1000
- return range.start <= numOrRange && numOrRange <= range.end;
1001
- }
1002
- else {
1003
- return contains(numOrRange.start, range) && contains(numOrRange.end, range);
1004
- }
1005
- };
1006
- /**
1007
- * Returns a range that represents the overlap between `other` and `range`. If
1008
- * the two ranges do not intersect, then `undefined` is returned.
1009
- * @param other
1010
- * @param range
1011
- */
1012
- var intersection = function (other, range) {
1013
- if (intersects(other, range)) {
1014
- return create$1(Math.max(other.start, range.start), Math.min(other.end, range.end));
1015
- }
1016
- };
1017
- /**
1018
- * Returns `true` if `other` intersects with `range`.
1019
- */
1020
- var intersects = function (other, range) {
1021
- return ((other.start <= range.end && other.end >= range.start) ||
1022
- (range.start <= other.end && range.end >= other.start));
1023
- };
1024
- /**
1025
- * Checks if a range has the same starting point as another range.
1026
- */
1027
- var isAt = function (other, range) {
1028
- return other.start === range.start;
1029
- };
1030
- /**
1031
- * Returns `true` if a range's start point is after the starting point of
1032
- * another range.
1033
- */
1034
- var isAfter = function (other, range) {
1035
- return other.start > range.start;
1036
- };
1037
- /**
1038
- * Returns `true` if a range start at or is after another range.
1039
- */
1040
- var isAtOrAfter = function (other, range) {
1041
- return isAt(other, range) || isAfter(other, range);
1042
- };
1043
- /**
1044
- * Returns `true` if a range's starting point is before another range's starting
1045
- * point.
1046
- */
1047
- var isBefore = function (other, range) {
1048
- return other.start < range.start;
1049
- };
1050
- /**
1051
- * Returns `true` if a range's starting point is at or before another range's
1052
- * starting point.
1053
- */
1054
- var isAtOrBefore = function (other, range) {
1055
- return isAt(other, range) || isBefore(other, range);
1056
- };
1057
- /**
1058
- * Returns the length of a range.
1059
- */
1060
- var length = function (range) {
1061
- return range.end - range.start + 1;
1062
- };
1063
- /**
1064
- * Returns a `Range` with its start and end points subtracted by the given
1065
- * distance.
1066
- */
1067
- var subtract = function (distance, range) {
1068
- return add(distance * -1, range);
1069
- };
1070
- /**
1071
- * Adjusts either the start or end position of a range so that its contained
1072
- * within another range. Unlike `constrain`, this will not attempt to retain
1073
- * the range's length.
1074
- *
1075
- * If `other` does not intersect with `to`, then the range cannot be truncated
1076
- * and `undefined` is returned.
1077
- */
1078
- var truncate = function (other, to) {
1079
- if (intersects(to, other)) {
1080
- return create$1(Math.max(other.start, to.start), Math.min(other.end, to.end));
1081
- }
869
+ /**
870
+ * Returns a new `Range` with the given start and end points.
871
+ */
872
+ var create$1 = function (start, end) { return ({ start: start, end: end }); };
873
+ /**
874
+ * Returns a new `Range` with the start and end points at the given position.
875
+ */
876
+ var at = function (position) { return ({
877
+ start: position,
878
+ end: position,
879
+ }); };
880
+ /**
881
+ * Returns a new `Range` with the given start point and length.
882
+ */
883
+ var withLength = function (start, len) { return ({
884
+ start: start,
885
+ end: start + len - 1,
886
+ }); };
887
+ /**
888
+ * Returns a range with the start and end points shifted by the given distance.
889
+ */
890
+ var add = function (distance, range) {
891
+ return create$1(range.start + distance, range.end + distance);
892
+ };
893
+ /**
894
+ * Returns a range such that `range` is constrained to the start and end points
895
+ * of `to`. The function will try to maintain the length of the range, but will
896
+ * shrink the range if its length is greater than `to`.
897
+ */
898
+ var constrain = function (range, to) {
899
+ if (contains(range, to)) {
900
+ return range;
901
+ }
902
+ else if (length(range) > length(to)) {
903
+ return to;
904
+ }
905
+ else if (range.start < to.start) {
906
+ return create$1(to.start, to.start + length(range) - 1);
907
+ }
908
+ else {
909
+ return create$1(to.end - length(range) + 1, to.end);
910
+ }
911
+ };
912
+ /**
913
+ * Checks if the given number or range is contained within another range.
914
+ */
915
+ var contains = function (numOrRange, range) {
916
+ if (typeof numOrRange === 'number') {
917
+ return range.start <= numOrRange && numOrRange <= range.end;
918
+ }
919
+ else {
920
+ return contains(numOrRange.start, range) && contains(numOrRange.end, range);
921
+ }
922
+ };
923
+ /**
924
+ * Returns a range that represents the overlap between `other` and `range`. If
925
+ * the two ranges do not intersect, then `undefined` is returned.
926
+ * @param other
927
+ * @param range
928
+ */
929
+ var intersection = function (other, range) {
930
+ if (intersects(other, range)) {
931
+ return create$1(Math.max(other.start, range.start), Math.min(other.end, range.end));
932
+ }
933
+ };
934
+ /**
935
+ * Returns `true` if `other` intersects with `range`.
936
+ */
937
+ var intersects = function (other, range) {
938
+ return ((other.start <= range.end && other.end >= range.start) ||
939
+ (range.start <= other.end && range.end >= other.start));
940
+ };
941
+ /**
942
+ * Checks if a range has the same starting point as another range.
943
+ */
944
+ var isAt = function (other, range) {
945
+ return other.start === range.start;
946
+ };
947
+ /**
948
+ * Returns `true` if a range's start point is after the starting point of
949
+ * another range.
950
+ */
951
+ var isAfter = function (other, range) {
952
+ return other.start > range.start;
953
+ };
954
+ /**
955
+ * Returns `true` if a range start at or is after another range.
956
+ */
957
+ var isAtOrAfter = function (other, range) {
958
+ return isAt(other, range) || isAfter(other, range);
959
+ };
960
+ /**
961
+ * Returns `true` if a range's starting point is before another range's starting
962
+ * point.
963
+ */
964
+ var isBefore = function (other, range) {
965
+ return other.start < range.start;
966
+ };
967
+ /**
968
+ * Returns `true` if a range's starting point is at or before another range's
969
+ * starting point.
970
+ */
971
+ var isAtOrBefore = function (other, range) {
972
+ return isAt(other, range) || isBefore(other, range);
973
+ };
974
+ /**
975
+ * Returns the length of a range.
976
+ */
977
+ var length = function (range) {
978
+ return range.end - range.start + 1;
979
+ };
980
+ /**
981
+ * Returns a `Range` with its start and end points subtracted by the given
982
+ * distance.
983
+ */
984
+ var subtract = function (distance, range) {
985
+ return add(distance * -1, range);
986
+ };
987
+ /**
988
+ * Adjusts either the start or end position of a range so that its contained
989
+ * within another range. Unlike `constrain`, this will not attempt to retain
990
+ * the range's length.
991
+ *
992
+ * If `other` does not intersect with `to`, then the range cannot be truncated
993
+ * and `undefined` is returned.
994
+ */
995
+ var truncate = function (other, to) {
996
+ if (intersects(to, other)) {
997
+ return create$1(Math.max(other.start, to.start), Math.min(other.end, to.end));
998
+ }
1082
999
  };
1083
1000
 
1084
1001
  var range = /*#__PURE__*/Object.freeze({
@@ -1101,25 +1018,25 @@ var range = /*#__PURE__*/Object.freeze({
1101
1018
  truncate: truncate
1102
1019
  });
1103
1020
 
1104
- function diffSet(a, b) {
1105
- var e_1, _a;
1106
- var res = new Set();
1107
- try {
1108
- for (var b_1 = __values(b), b_1_1 = b_1.next(); !b_1_1.done; b_1_1 = b_1.next()) {
1109
- var item = b_1_1.value;
1110
- if (!a.has(item)) {
1111
- res.add(item);
1112
- }
1113
- }
1114
- }
1115
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1116
- finally {
1117
- try {
1118
- if (b_1_1 && !b_1_1.done && (_a = b_1.return)) _a.call(b_1);
1119
- }
1120
- finally { if (e_1) throw e_1.error; }
1121
- }
1122
- return res;
1021
+ function diffSet(a, b) {
1022
+ var e_1, _a;
1023
+ var res = new Set();
1024
+ try {
1025
+ for (var b_1 = __values(b), b_1_1 = b_1.next(); !b_1_1.done; b_1_1 = b_1.next()) {
1026
+ var item = b_1_1.value;
1027
+ if (!a.has(item)) {
1028
+ res.add(item);
1029
+ }
1030
+ }
1031
+ }
1032
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1033
+ finally {
1034
+ try {
1035
+ if (b_1_1 && !b_1_1.done && (_a = b_1.return)) _a.call(b_1);
1036
+ }
1037
+ finally { if (e_1) throw e_1.error; }
1038
+ }
1039
+ return res;
1123
1040
  }
1124
1041
 
1125
1042
  var sets = /*#__PURE__*/Object.freeze({
@@ -1127,17 +1044,17 @@ var sets = /*#__PURE__*/Object.freeze({
1127
1044
  diffSet: diffSet
1128
1045
  });
1129
1046
 
1130
- var trimStartRegex = /^\W+/;
1131
- var trimEndRegex = /\W+$/;
1132
- var trimStartAndEndRegex = /^\W+|\W+$/g;
1133
- function trimStart(str) {
1134
- return str.replace(trimStartRegex, '');
1135
- }
1136
- function trimEnd(str) {
1137
- return str.replace(trimEndRegex, '');
1138
- }
1139
- function trim(str) {
1140
- return str.replace(trimStartAndEndRegex, '');
1047
+ var trimStartRegex = /^\W+/;
1048
+ var trimEndRegex = /\W+$/;
1049
+ var trimStartAndEndRegex = /^\W+|\W+$/g;
1050
+ function trimStart(str) {
1051
+ return str.replace(trimStartRegex, '');
1052
+ }
1053
+ function trimEnd(str) {
1054
+ return str.replace(trimEndRegex, '');
1055
+ }
1056
+ function trim(str) {
1057
+ return str.replace(trimStartAndEndRegex, '');
1141
1058
  }
1142
1059
 
1143
1060
  var strings = /*#__PURE__*/Object.freeze({
@@ -1147,178 +1064,178 @@ var strings = /*#__PURE__*/Object.freeze({
1147
1064
  trim: trim
1148
1065
  });
1149
1066
 
1150
- /**
1151
- * A comparator that sorts a number or string in ascending order.
1152
- */
1153
- var asc = function (a, b) {
1154
- if (a < b) {
1155
- return -1;
1156
- }
1157
- else if (a > b) {
1158
- return 1;
1159
- }
1160
- else {
1161
- return 0;
1162
- }
1163
- };
1164
- /**
1165
- * A comparator that plucks the first element of an array and passes that value
1166
- * to the given comparator for sorting.
1167
- */
1168
- var head = function (comparator) {
1169
- return function (_a, _b) {
1170
- var _c = __read(_a, 1), a = _c[0];
1171
- var _d = __read(_b, 1), b = _d[0];
1172
- return comparator(a, b);
1173
- };
1067
+ /**
1068
+ * A comparator that sorts a number or string in ascending order.
1069
+ */
1070
+ var asc = function (a, b) {
1071
+ if (a < b) {
1072
+ return -1;
1073
+ }
1074
+ else if (a > b) {
1075
+ return 1;
1076
+ }
1077
+ else {
1078
+ return 0;
1079
+ }
1080
+ };
1081
+ /**
1082
+ * A comparator that plucks the first element of an array and passes that value
1083
+ * to the given comparator for sorting.
1084
+ */
1085
+ var head = function (comparator) {
1086
+ return function (_a, _b) {
1087
+ var _c = __read(_a, 1), a = _c[0];
1088
+ var _d = __read(_b, 1), b = _d[0];
1089
+ return comparator(a, b);
1090
+ };
1174
1091
  };
1175
1092
 
1176
- /**
1177
- * Parses a URI string according to RFC 3986. If the URI is an empty string,
1178
- * then an empty object is returned.
1179
- *
1180
- * See https://tools.ietf.org/html/rfc3986#appendix-B for parsing rules.
1181
- *
1182
- * @param uri The URI to parse.
1183
- */
1184
- var parse = function (uri) {
1185
- var regex = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
1186
- var match = regex.exec(uri);
1187
- if (match != null) {
1188
- return {
1189
- scheme: match[2],
1190
- authority: match[4],
1191
- path: match[5],
1192
- query: match[7],
1193
- fragment: match[9],
1194
- };
1195
- }
1196
- else {
1197
- return {};
1198
- }
1199
- };
1200
- /**
1201
- * Convenience method to create a URI from a base string and add params if present
1202
- * @param base
1203
- * @param params
1204
- */
1205
- var parseAndAddParams = function (baseStr, params) {
1206
- var base = parse(baseStr);
1207
- return params ? addQueryParams(params, base) : base;
1208
- };
1209
- var isEqual = function (a, b) {
1210
- var queryA = JSON.stringify(sortByQueryName(queryAsArray(a)));
1211
- var queryB = JSON.stringify(sortByQueryName(queryAsArray(b)));
1212
- return (a.scheme === b.scheme &&
1213
- a.authority === b.authority &&
1214
- a.path === b.path &&
1215
- a.fragment === b.fragment &&
1216
- queryA === queryB);
1217
- };
1218
- var replacePath = function (path, uri) {
1219
- var pathWithForwardSlash = path[0] === '/' ? path : "/".concat(path);
1220
- return __assign(__assign({}, uri), { path: pathWithForwardSlash });
1221
- };
1222
- var pathAsArray = function (uri) {
1223
- return uri.path != null ? sanitizePath(uri.path.split('/')) : [];
1224
- };
1225
- var appendPath = function (path, uri) {
1226
- var beforeParts = pathAsArray(uri);
1227
- var afterParts = sanitizePath(path.split('/'));
1228
- return replacePath(beforeParts.concat(afterParts).join('/'), uri);
1229
- };
1230
- var addQueryString = function (query, uri) {
1231
- var queryArray = stringAsQueryArray(query);
1232
- return addQueryEntries(queryArray, uri);
1233
- };
1234
- var addQueryEntry = function (query, uri) {
1235
- if (query[1] != null) {
1236
- var newQuery = __spreadArray(__spreadArray([], __read(queryAsArray(uri)), false), [query], false);
1237
- return __assign(__assign({}, uri), { query: newQuery
1238
- .map(function (entry) { return entry.map(encodeURIComponent).join('='); })
1239
- .join('&') });
1240
- }
1241
- else {
1242
- return uri;
1243
- }
1244
- };
1245
- var addQueryEntries = function (entries, uri) {
1246
- return entries.reduce(function (result, entry) { return addQueryEntry(entry, result); }, uri);
1247
- };
1248
- var addQueryParams = function (params, uri) {
1249
- return mapAsEntries(params).reduce(function (result, entry) { return addQueryEntry(entry, result); }, uri);
1250
- };
1251
- var replaceFragment = function (fragment, uri) {
1252
- return __assign(__assign({}, uri), { fragment: fragment });
1253
- };
1254
- /**
1255
- * Return an array of name/value pairs representing the query string of a URI.
1256
- * The returned names and values will be URI decoded. If the query string is
1257
- * empty, then an empty array is returned.
1258
- *
1259
- * @param uri A URI to return the query string for.
1260
- */
1261
- var queryAsArray = function (uri) {
1262
- if (uri.query != null) {
1263
- return stringAsQueryArray(uri.query);
1264
- }
1265
- else {
1266
- return [];
1267
- }
1268
- };
1269
- var stringAsQueryArray = function (queryString) {
1270
- return queryString
1271
- .split('&')
1272
- .map(function (param) {
1273
- return param.split('=').map(function (value) { return decodeURIComponent(value); });
1274
- });
1275
- };
1276
- /**
1277
- * Return a map containing a URI's query string names and their values. The
1278
- * returned names and values will be URI decoded. If the query string contains
1279
- * multiple instances of the same name, then the last occurrence will be used.
1280
- *
1281
- * If the query string is empty, an empty map is returned.
1282
- *
1283
- * @param uri A URI to return the query string for.
1284
- */
1285
- var queryAsMap = function (uri) {
1286
- return queryAsArray(uri).reduce(function (map, _a) {
1287
- var _b;
1288
- var _c = __read(_a, 2), name = _c[0], value = _c[1];
1289
- return __assign(__assign({}, map), (_b = {}, _b[name] = value, _b));
1290
- }, {});
1291
- };
1292
- var toString = function (uri) {
1293
- var result = '';
1294
- if (uri.scheme != null && uri.scheme.length > 0) {
1295
- result = "".concat(uri.scheme, ":");
1296
- }
1297
- if (uri.authority != null && uri.authority.length > 0) {
1298
- result += "//".concat(uri.authority);
1299
- }
1300
- result += uri.path;
1301
- if (uri.query != null && uri.query.length > 0) {
1302
- result += "?".concat(uri.query);
1303
- }
1304
- if (uri.fragment != null && uri.fragment.length > 0) {
1305
- result += "#".concat(uri.fragment);
1306
- }
1307
- return result;
1308
- };
1309
- var sanitizePath = function (path) {
1310
- return path.filter(function (segment) { return segment.length > 0; });
1311
- };
1312
- var mapAsEntries = function (map) {
1313
- var entries = [];
1314
- for (var key in map) {
1315
- entries.push([key, map[key]]);
1316
- }
1317
- return entries;
1318
- };
1319
- var sortByQueryName = function (entries) {
1320
- return entries.concat().sort(head(asc));
1321
- };
1093
+ /**
1094
+ * Parses a URI string according to RFC 3986. If the URI is an empty string,
1095
+ * then an empty object is returned.
1096
+ *
1097
+ * See https://tools.ietf.org/html/rfc3986#appendix-B for parsing rules.
1098
+ *
1099
+ * @param uri The URI to parse.
1100
+ */
1101
+ var parse = function (uri) {
1102
+ var regex = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
1103
+ var match = regex.exec(uri);
1104
+ if (match != null) {
1105
+ return {
1106
+ scheme: match[2],
1107
+ authority: match[4],
1108
+ path: match[5],
1109
+ query: match[7],
1110
+ fragment: match[9],
1111
+ };
1112
+ }
1113
+ else {
1114
+ return {};
1115
+ }
1116
+ };
1117
+ /**
1118
+ * Convenience method to create a URI from a base string and add params if present
1119
+ * @param base
1120
+ * @param params
1121
+ */
1122
+ var parseAndAddParams = function (baseStr, params) {
1123
+ var base = parse(baseStr);
1124
+ return params ? addQueryParams(params, base) : base;
1125
+ };
1126
+ var isEqual = function (a, b) {
1127
+ var queryA = JSON.stringify(sortByQueryName(queryAsArray(a)));
1128
+ var queryB = JSON.stringify(sortByQueryName(queryAsArray(b)));
1129
+ return (a.scheme === b.scheme &&
1130
+ a.authority === b.authority &&
1131
+ a.path === b.path &&
1132
+ a.fragment === b.fragment &&
1133
+ queryA === queryB);
1134
+ };
1135
+ var replacePath = function (path, uri) {
1136
+ var pathWithForwardSlash = path[0] === '/' ? path : "/".concat(path);
1137
+ return __assign(__assign({}, uri), { path: pathWithForwardSlash });
1138
+ };
1139
+ var pathAsArray = function (uri) {
1140
+ return uri.path != null ? sanitizePath(uri.path.split('/')) : [];
1141
+ };
1142
+ var appendPath = function (path, uri) {
1143
+ var beforeParts = pathAsArray(uri);
1144
+ var afterParts = sanitizePath(path.split('/'));
1145
+ return replacePath(beforeParts.concat(afterParts).join('/'), uri);
1146
+ };
1147
+ var addQueryString = function (query, uri) {
1148
+ var queryArray = stringAsQueryArray(query);
1149
+ return addQueryEntries(queryArray, uri);
1150
+ };
1151
+ var addQueryEntry = function (query, uri) {
1152
+ if (query[1] != null) {
1153
+ var newQuery = __spreadArray(__spreadArray([], __read(queryAsArray(uri)), false), [query], false);
1154
+ return __assign(__assign({}, uri), { query: newQuery
1155
+ .map(function (entry) { return entry.map(encodeURIComponent).join('='); })
1156
+ .join('&') });
1157
+ }
1158
+ else {
1159
+ return uri;
1160
+ }
1161
+ };
1162
+ var addQueryEntries = function (entries, uri) {
1163
+ return entries.reduce(function (result, entry) { return addQueryEntry(entry, result); }, uri);
1164
+ };
1165
+ var addQueryParams = function (params, uri) {
1166
+ return mapAsEntries(params).reduce(function (result, entry) { return addQueryEntry(entry, result); }, uri);
1167
+ };
1168
+ var replaceFragment = function (fragment, uri) {
1169
+ return __assign(__assign({}, uri), { fragment: fragment });
1170
+ };
1171
+ /**
1172
+ * Return an array of name/value pairs representing the query string of a URI.
1173
+ * The returned names and values will be URI decoded. If the query string is
1174
+ * empty, then an empty array is returned.
1175
+ *
1176
+ * @param uri A URI to return the query string for.
1177
+ */
1178
+ var queryAsArray = function (uri) {
1179
+ if (uri.query != null) {
1180
+ return stringAsQueryArray(uri.query);
1181
+ }
1182
+ else {
1183
+ return [];
1184
+ }
1185
+ };
1186
+ var stringAsQueryArray = function (queryString) {
1187
+ return queryString
1188
+ .split('&')
1189
+ .map(function (param) {
1190
+ return param.split('=').map(function (value) { return decodeURIComponent(value); });
1191
+ });
1192
+ };
1193
+ /**
1194
+ * Return a map containing a URI's query string names and their values. The
1195
+ * returned names and values will be URI decoded. If the query string contains
1196
+ * multiple instances of the same name, then the last occurrence will be used.
1197
+ *
1198
+ * If the query string is empty, an empty map is returned.
1199
+ *
1200
+ * @param uri A URI to return the query string for.
1201
+ */
1202
+ var queryAsMap = function (uri) {
1203
+ return queryAsArray(uri).reduce(function (map, _a) {
1204
+ var _b;
1205
+ var _c = __read(_a, 2), name = _c[0], value = _c[1];
1206
+ return __assign(__assign({}, map), (_b = {}, _b[name] = value, _b));
1207
+ }, {});
1208
+ };
1209
+ var toString = function (uri) {
1210
+ var result = '';
1211
+ if (uri.scheme != null && uri.scheme.length > 0) {
1212
+ result = "".concat(uri.scheme, ":");
1213
+ }
1214
+ if (uri.authority != null && uri.authority.length > 0) {
1215
+ result += "//".concat(uri.authority);
1216
+ }
1217
+ result += uri.path;
1218
+ if (uri.query != null && uri.query.length > 0) {
1219
+ result += "?".concat(uri.query);
1220
+ }
1221
+ if (uri.fragment != null && uri.fragment.length > 0) {
1222
+ result += "#".concat(uri.fragment);
1223
+ }
1224
+ return result;
1225
+ };
1226
+ var sanitizePath = function (path) {
1227
+ return path.filter(function (segment) { return segment.length > 0; });
1228
+ };
1229
+ var mapAsEntries = function (map) {
1230
+ var entries = [];
1231
+ for (var key in map) {
1232
+ entries.push([key, map[key]]);
1233
+ }
1234
+ return entries;
1235
+ };
1236
+ var sortByQueryName = function (entries) {
1237
+ return entries.concat().sort(head(asc));
1238
+ };
1322
1239
  /* eslint-enable @typescript-eslint/no-explicit-any */
1323
1240
 
1324
1241
  var uri = /*#__PURE__*/Object.freeze({
@@ -1339,105 +1256,31 @@ var uri = /*#__PURE__*/Object.freeze({
1339
1256
  toString: toString
1340
1257
  });
1341
1258
 
1342
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
1343
- // require the crypto API and do not support built-in fallback to lower quality random number
1344
- // generators (like Math.random()).
1345
- var getRandomValues;
1346
- var rnds8 = new Uint8Array(16);
1347
- function rng() {
1348
- // lazy load so that environments that need to polyfill have a chance to do so
1349
- if (!getRandomValues) {
1350
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
1351
- // find the complete implementation of crypto (msCrypto) on IE11.
1352
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
1353
-
1354
- if (!getRandomValues) {
1355
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
1356
- }
1357
- }
1358
-
1359
- return getRandomValues(rnds8);
1360
- }
1361
-
1362
- var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
1363
-
1364
- function validate(uuid) {
1365
- return typeof uuid === 'string' && REGEX.test(uuid);
1259
+ function create() {
1260
+ return v4();
1366
1261
  }
1367
-
1368
- /**
1369
- * Convert array of 16 byte values to UUID string format of the form:
1370
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1371
- */
1372
-
1373
- var byteToHex = [];
1374
-
1375
- for (var i = 0; i < 256; ++i) {
1376
- byteToHex.push((i + 0x100).toString(16).substr(1));
1377
- }
1378
-
1379
- function stringify(arr) {
1380
- var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
1381
- // Note: Be careful editing this code! It's been tuned for performance
1382
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
1383
- var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
1384
- // of the following:
1385
- // - One or more input array values don't map to a hex octet (leading to
1386
- // "undefined" in the uuid)
1387
- // - Invalid input values for the RFC `version` or `variant` fields
1388
-
1389
- if (!validate(uuid)) {
1390
- throw TypeError('Stringified UUID is invalid');
1391
- }
1392
-
1393
- return uuid;
1394
- }
1395
-
1396
- function v4(options, buf, offset) {
1397
- options = options || {};
1398
- var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1399
-
1400
- rnds[6] = rnds[6] & 0x0f | 0x40;
1401
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
1402
-
1403
- if (buf) {
1404
- offset = offset || 0;
1405
-
1406
- for (var i = 0; i < 16; ++i) {
1407
- buf[offset + i] = rnds[i];
1262
+ function fromMsbLsb(msb, lsb) {
1263
+ function digits(val, ds) {
1264
+ var hi = BigInt(1) << (ds * BigInt(4));
1265
+ return (hi | (val & (hi - BigInt(1)))).toString(16).substring(1);
1408
1266
  }
1409
-
1410
- return buf;
1411
- }
1412
-
1413
- return stringify(rnds);
1267
+ var msbB = typeof msb === 'string' ? BigInt(msb) : msb;
1268
+ var lsbB = typeof lsb === 'string' ? BigInt(lsb) : lsb;
1269
+ var sec1 = digits(msbB >> BigInt(32), BigInt(8));
1270
+ var sec2 = digits(msbB >> BigInt(16), BigInt(4));
1271
+ var sec3 = digits(msbB, BigInt(4));
1272
+ var sec4 = digits(lsbB >> BigInt(48), BigInt(4));
1273
+ var sec5 = digits(lsbB, BigInt(12));
1274
+ return "".concat(sec1, "-").concat(sec2, "-").concat(sec3, "-").concat(sec4, "-").concat(sec5);
1414
1275
  }
1415
-
1416
- function create() {
1417
- return v4();
1418
- }
1419
- function fromMsbLsb(msb, lsb) {
1420
- function digits(val, ds) {
1421
- var hi = BigInt(1) << (ds * BigInt(4));
1422
- return (hi | (val & (hi - BigInt(1)))).toString(16).substring(1);
1423
- }
1424
- var msbB = typeof msb === 'string' ? BigInt(msb) : msb;
1425
- var lsbB = typeof lsb === 'string' ? BigInt(lsb) : lsb;
1426
- var sec1 = digits(msbB >> BigInt(32), BigInt(8));
1427
- var sec2 = digits(msbB >> BigInt(16), BigInt(4));
1428
- var sec3 = digits(msbB, BigInt(4));
1429
- var sec4 = digits(lsbB >> BigInt(48), BigInt(4));
1430
- var sec5 = digits(lsbB, BigInt(12));
1431
- return "".concat(sec1, "-").concat(sec2, "-").concat(sec3, "-").concat(sec4, "-").concat(sec5);
1432
- }
1433
- function toMsbLsb(id) {
1434
- var _a = __read(id.split('-'), 5), c1 = _a[0], c2 = _a[1], c3 = _a[2], c4 = _a[3], c5 = _a[4];
1435
- if (c1 == null || c2 == null || c3 == null || c4 == null || c5 == null) {
1436
- throw new Error("Invalid UUID string ".concat(id));
1437
- }
1438
- var msb = BigInt.asIntN(64, BigInt("0x".concat(c1 + c2 + c3)));
1439
- var lsb = BigInt.asIntN(64, BigInt("0x".concat(c4 + c5)));
1440
- return { msb: msb.toString(), lsb: lsb.toString() };
1276
+ function toMsbLsb(id) {
1277
+ var _a = __read(id.split('-'), 5), c1 = _a[0], c2 = _a[1], c3 = _a[2], c4 = _a[3], c5 = _a[4];
1278
+ if (c1 == null || c2 == null || c3 == null || c4 == null || c5 == null) {
1279
+ throw new Error("Invalid UUID string ".concat(id));
1280
+ }
1281
+ var msb = BigInt.asIntN(64, BigInt("0x".concat(c1 + c2 + c3)));
1282
+ var lsb = BigInt.asIntN(64, BigInt("0x".concat(c4 + c5)));
1283
+ return { msb: msb.toString(), lsb: lsb.toString() };
1441
1284
  }
1442
1285
 
1443
1286
  var uuid = /*#__PURE__*/Object.freeze({
@@ -1447,65 +1290,68 @@ var uuid = /*#__PURE__*/Object.freeze({
1447
1290
  toMsbLsb: toMsbLsb
1448
1291
  });
1449
1292
 
1450
- var EventDispatcher = /** @class */ (function () {
1451
- function EventDispatcher() {
1452
- this.listeners = [];
1453
- }
1454
- EventDispatcher.prototype.on = function (listener, opts) {
1455
- var _this = this;
1456
- var _a;
1457
- if (opts === void 0) { opts = {}; }
1458
- this.listeners.push(listener);
1459
- var controller = new AbortController();
1460
- controller.signal.addEventListener('abort', function () { return _this.off(listener); });
1461
- (_a = opts.abort) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', function () { return controller.abort(); });
1462
- return { dispose: function () { return controller.abort(); } };
1463
- };
1464
- EventDispatcher.prototype.once = function (opts) {
1465
- var _this = this;
1466
- if (opts === void 0) { opts = {}; }
1467
- return new Promise(function (resolve) {
1468
- _this.on(function (event) { return resolve(event); }, opts);
1469
- });
1470
- };
1471
- EventDispatcher.prototype.onceWhen = function (predicate, opts) {
1472
- var _a;
1473
- if (opts === void 0) { opts = {}; }
1474
- return __awaiter(this, void 0, void 0, function () {
1475
- var controller;
1476
- var _this = this;
1477
- return __generator(this, function (_b) {
1478
- controller = new AbortController();
1479
- (_a = opts.abort) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', function () { return controller.abort(); });
1480
- return [2 /*return*/, new Promise(function (resolve) {
1481
- _this.when(predicate, function (event) {
1482
- if (predicate(event)) {
1483
- controller.abort();
1484
- resolve(event);
1485
- }
1486
- }, __assign(__assign({}, opts), { abort: controller.signal }));
1487
- })];
1488
- });
1489
- });
1490
- };
1491
- EventDispatcher.prototype.when = function (predicate, listener, opts) {
1492
- if (opts === void 0) { opts = {}; }
1493
- return this.on(function (event) {
1494
- if (predicate(event)) {
1495
- listener(event);
1496
- }
1497
- }, opts);
1498
- };
1499
- EventDispatcher.prototype.off = function (listener) {
1500
- var index = this.listeners.indexOf(listener);
1501
- if (index !== -1) {
1502
- this.listeners.splice(index, 1);
1503
- }
1504
- };
1505
- EventDispatcher.prototype.emit = function (event) {
1506
- this.listeners.forEach(function (listener) { return listener(event); });
1507
- };
1508
- return EventDispatcher;
1293
+ var EventDispatcher = /** @class */ (function () {
1294
+ function EventDispatcher() {
1295
+ this.listeners = [];
1296
+ }
1297
+ EventDispatcher.prototype.on = function (listener, opts) {
1298
+ var _this = this;
1299
+ var _a;
1300
+ if (opts === void 0) { opts = {}; }
1301
+ this.listeners.push(listener);
1302
+ var controller = new AbortController();
1303
+ controller.signal.addEventListener('abort', function () { return _this.off(listener); });
1304
+ (_a = opts.abort) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', function () { return controller.abort(); });
1305
+ return { dispose: function () { return controller.abort(); } };
1306
+ };
1307
+ EventDispatcher.prototype.once = function (opts) {
1308
+ var _this = this;
1309
+ if (opts === void 0) { opts = {}; }
1310
+ return new Promise(function (resolve) {
1311
+ var subscription = _this.on(function (event) {
1312
+ subscription.dispose();
1313
+ resolve(event);
1314
+ }, opts);
1315
+ });
1316
+ };
1317
+ EventDispatcher.prototype.onceWhen = function (predicate_1) {
1318
+ return __awaiter(this, arguments, Promise, function (predicate, opts) {
1319
+ var controller;
1320
+ var _this = this;
1321
+ var _a;
1322
+ if (opts === void 0) { opts = {}; }
1323
+ return __generator(this, function (_b) {
1324
+ controller = new AbortController();
1325
+ (_a = opts.abort) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', function () { return controller.abort(); });
1326
+ return [2 /*return*/, new Promise(function (resolve) {
1327
+ _this.when(predicate, function (event) {
1328
+ if (predicate(event)) {
1329
+ controller.abort();
1330
+ resolve(event);
1331
+ }
1332
+ }, __assign(__assign({}, opts), { abort: controller.signal }));
1333
+ })];
1334
+ });
1335
+ });
1336
+ };
1337
+ EventDispatcher.prototype.when = function (predicate, listener, opts) {
1338
+ if (opts === void 0) { opts = {}; }
1339
+ return this.on(function (event) {
1340
+ if (predicate(event)) {
1341
+ listener(event);
1342
+ }
1343
+ }, opts);
1344
+ };
1345
+ EventDispatcher.prototype.off = function (listener) {
1346
+ var index = this.listeners.indexOf(listener);
1347
+ if (index !== -1) {
1348
+ this.listeners.splice(index, 1);
1349
+ }
1350
+ };
1351
+ EventDispatcher.prototype.emit = function (event) {
1352
+ this.listeners.forEach(function (listener) { return listener(event); });
1353
+ };
1354
+ return EventDispatcher;
1509
1355
  }());
1510
1356
 
1511
1357
  export { async as Async, binaryReader as BinaryReader, color as Color, EventDispatcher, eventTargets as EventTargets, mapper as Mapper, objects as Objects, range as Range, sets as Sets, strings as Strings, uuid as UUID, uri as Uri };