-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatcher.ts
370 lines (351 loc) · 9.35 KB
/
matcher.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/**
* @module matcher
* Description: Validation framework which can be used for testing matchers,
* input valiation, or similar use cases
*/
import {
createMiddlewareApi,
type MiddlewareParams,
} from "../middleware";
import {
AnyObject,
Callable,
} from "../types";
import {
createProxy,
} from "../utils";
/**
* Name: MATCHER_ACTIONS
* Description: Matcher actions for middleware
* @public
* @readonly
* @enum {string}
*/
export enum MATCHER_ACTIONS {
MATCH = 'MATCH',
}
/**
* Name: CreateMatchParams
* Description: options to pass to matcher middleware
* @private
* @typedef {AnyObject} options object
*/
type CreateMatchParams = {
options?: AnyObject,
};
/**
* Name: CreateMatchParams
* Description: options to pass to matcher middleware
* @public
* @template A, B - types for subjects to be compared
* @param params Middleware options for matcher
* @returns Callable<[A, B], boolean>
*/
export const createMatcher = <
A = any,
B = A,
>(
params: CreateMatchParams & MiddlewareParams = {},
): Callable<[A, B], boolean> => {
const {
createApi,
middleware,
options = {},
sort,
transform,
} = params;
// Create middleware
const api = createMiddlewareApi({
createApi,
middleware,
sort,
transform,
});
return (a: A, b: B) : boolean => {
return api({
action: {
type: MATCHER_ACTIONS.MATCH,
data: {
options,
},
},
}).middleware(a, b);
};
};
/**
* Description: Proxied matcher
* - Used for writing validations that have more natural language validators
* - Inspired by ChaiJS
* - Can be used for assertion or input validators etc
* - ex:
* const validator = createProxiedMatcher(options);
* validator.match(actual.a, actual.b)
* validator.expect(actual).to.customEvaluator()
* @public
* @template H, P, R - H: Target Handler type, P: property type, R: receiver type
* @param defaultHandler
* @param options
* @returns
*/
export const createMatcherProxyHandler = <
H extends AnyObject = AnyObject,
P extends string | symbol = string | symbol,
R = any,
>(
defaultHandler: AnyObject = {},
options: AnyObject = {},
): ProxyHandler<H> => {
const {
logger = globalThis.console.log,
} = options;
return {
...defaultHandler,
get: (target: H, prop: P, receiver: R) => {
if (!target[prop]) {
logger(`Something went wrong... '${prop.toString()}' does not exist on ${receiver}.`);
return target;
}
return target[prop];
},
};
};
/**
* Name: ProxiedMatcherParams
* Description: options to pass to matcher middleware
* @private
* @typedef {object}
* @property {AnyObject} defaultHandler object
* @property {AnyObject} defaultTarget object
* @property {string} methodName match method name
*/
type ProxiedMatcherParams = {
defaultHandler?: AnyObject;
defaultTarget?: AnyObject;
methodName?: string;
};
/**
* Name: createProxiedMatcher
* Description: The `createProxiedMatcher<A, B>` allows for a flexible micro-assertion library
* extendable via middleware. This throws for any failure.
* @public
* @template A, B - A: first subject, B: second subject
* @param params Hander, Target, and middleware options
* @returns ProxyHandler<AnyObject>
*/
export const createProxiedMatcher = <
A = any,
B = A,
>(
params: ProxiedMatcherParams & MiddlewareParams = {},
): ProxyHandler<AnyObject> => {
const {
createApi,
sort,
transform,
defaultHandler = {},
defaultTarget = {},
methodName = 'match',
middleware,
} = params;
return createProxy(createMatcherProxyHandler(defaultHandler))({
...createProxiedMatchTarget(defaultTarget),
[methodName]: createMatcher<A, B>({ createApi, middleware, sort, transform }),
});
};
/**
* Name: createDataContainer
* Description: create mutatable object used for assertion data
* @private
* @param expression any
* @returns object of data container
*/
const createDataContainer = (expression: any): AnyObject => {
return {
expression,
eval: (optionalExpected: any) => {
const result = optionalExpected || expression;
return typeof result === 'function' ? result() : result;
},
negate: false,
};
}
/**
* Name: createProxiedMatcher
* Description: The `createProxiedMatcher<A, B>` allows for a flexible micro-assertion library
* extendable via middleware. This throws for any failure.
* @public
* @template A, B - A: first subject, B: second subject
* @param params Hander, Target, and middleware options
* @returns ProxyHandler<AnyObject>
*/
/**
* Name: createProxiedMatchTarget
* Description: Creates target for proxied/chainable matcher
* @public
* @param target AnyObject
* @returns AnyObject
*/
export const createProxiedMatchTarget = (target: AnyObject): AnyObject => {
let data: AnyObject;
const methods = {
/**
* Name: be
* Description: assertion chain method
* @returns object of assertion methods
*/
get be() {
return {
instanceOf(actual: any, optionalExpected?: any) {
const expected = data.eval(optionalExpected);
return methods.eq(true, expected instanceof actual);
},
typeOf(type: string, optionalExpected?: any) {
const expected = data.eval(optionalExpected);
return methods.eq(type, typeof expected);
},
get array() {
return this.instanceOf(Array);
},
get bigint() {
return this.typeOf('bigint');
},
get boolean() {
return this.typeOf('boolean');
},
get false() {
return methods.eq(false);
},
get function() {
return this.typeOf('function');
},
get NaN() {
if (!data.negate && !isNaN(data.eval())) {
throw new Error(`Expected is not a NaN value: ${data.eval()}`);
}
return this.typeOf('number');
},
get number() {
return this.typeOf('number');
},
get null() {
return methods.eq(null);
},
get object() {
return this.typeOf('object');
},
get set() {
return this.instanceOf(Set);
},
get string() {
return this.typeOf('string');
},
get symbol() {
return this.typeOf('symbol');
},
get true() {
return methods.eq(true);
},
get undefined() {
return this.typeOf('undefined');
},
};
},
/**
* Name: eq
* Description: assertion chain equality method
* @param actual
* @param optionalExpected
* @returns boolean
*/
eq(actual: any, optionalExpected?: any) {
const expected = data.eval(optionalExpected);
if (data.negate && expected === actual ||
!data.negate && expected !== actual) {
throw new Error(`Expected: ${data.negate ? 'not' : ''} ${expected}, actual: ${actual}.`);
}
return true;
},
/**
* Name: include
* Description: assertion chain actual in expected assertion method
* @param actual
* @param optionalExpected
* @returns
*/
include(actual: any, optionalExpected?: any) {
const expected = data.eval(optionalExpected);
switch(typeof expected) {
case 'object': {
if (expected instanceof Array) {
return methods.eq(true, expected.includes(actual));
} else {
return methods.eq(true, Reflect.ownKeys(expected).includes(actual));
}
}
case 'string': {
return methods.eq(true, expected.includes(actual));
}
default: {
throw new Error(`Unsupported type. Currently only strings, objects and arrays are supported. Provided: ${expected}.`)
}
}
},
/**
* Name: not
* Description: negates assertion chain
* @returns object of methods
*/
get not() {
data.negate = !data.negate;
return methods;
},
/**
* Name: to
* @returns object of methods
*/
get to() {
return methods;
},
/**
* Name: throw
* Description: assertion chain method for code block throwing
* NOTE: All error constructors inherit from Error so
* matcher.expect(throwsSomeError).to.not.throw(Error)
* will always fails
* @param error
* @param optionalExpected
*/
throw(error?: any, optionalExpected?: any) {
let caughtError: any, threw: boolean, expected: any;
try {
expected = data.eval(optionalExpected);
expected();
} catch (err: any) {
caughtError = err;
threw = true;
}
if (data.negate) {
// success to not throw
if (error) {
methods.eq(false, caughtError instanceof error);
} else if (threw) {
throw new Error(`Expected expression: ${expected.toString()}, threw error when not expected to: ${caughtError}`);
}
} else {
// success to throw
if (error) {
methods.eq(true, caughtError instanceof error);
} else if (!threw) {
throw new Error(`Expected expression: ${expected.toString()}, did not throw error when expected to: ${expected.toString()}`);
}
}
},
};
return {
...target,
expect(expected: any) {
data = createDataContainer(expected);
return methods;
},
};
};