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