All files / expect.ts

100.00% Branches 75/75
100.00% Lines 327/327
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
x1
 
 
x32
x32
x32
x32
 
 
x32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x32
x32
 
x1
x32
x32
x32
x32
x32
 
x32
x32
x394
x394
x394
x394
x528
x643
x643
x528
x547
x547
x547
x528
x394
x394
x394
x394
x1576
x394
 
x32
x32
x60
x60
x62
x62
x60
 
 
 
 
 
 
 
 
 
 
 
x100
x100
x103
x103
x100
x102
x102
x100
 
x32
x32
 
 
x185
x332
x332
x332
x474
x474
x332
x185
x186
x186
x337
x1956
x489
x501
x501
x501
x489
x611
x611
x489
x497
x497
x489
x613
x613
x489
x185
x32
x32
x38
x44
x38
x32
x32
x40
x48
x144
x48
x52
x52
x40
x32
x32
x41
x150
x50
x50
x51
x51
x58
x41
x32
x32
x42
x52
x52
x54
x54
x60
x60
x60
x60
x60
x60
x60
x42
x32
x32
x40
x48
x48
x48
x50
x50
x40
x32
x32
x36
x40
x36
x32
x32
x36
x40
x36
x32
x32
x36
x40
x36
x32
x32
x40
x48
x48
x40
x32
x32
x44
x56
x168
x44
x32
x32
x36
x40
x40
x200
x36
x32
x32
x36
x40
x200
x36
x32
x32
x36
x120
x36
x32
x32
x42
x52
x52
x52
x52
x52
x52
x42
x32
x32
x38
x44
x44
x38
x32
x32
x36
x40
x40
x40
x42
x42
x36
x32
x32
x38
x44
x44
x44
x44
x44
 
x38
x32
x32
x38
x44
x38
x32
x32
x36
x40
x40
x40
x42
x42
x36
x32
x32
x82
x132
x133
x133
x181
x181
x181
x181
x132
x132
x152
x152
x152
x132
x132
x140
x140
x140
x132
x132
x136
x136
x136
x132
x132
x136
x136
x136
x132
x132
x136
x136
x136
x273
x423
x141
x141
x141
x132
x181
x132
x144
x144
x132
x156
x156
x132
x181
x181
x82
x32
x32
x47
x62
x62
x62
x62
x62
x62
x62
x62
x62
x62
x62
x62
x62
x62
x62
x73
x73
x74
x74
x81
x81
x62
x64
x64
x64
x63
x47
x32
x32
x40
x48
x40
x32
x32
x40
x48
x48
x52
x52
x40
x32
x32
x40
x48
x48
x52
x52
x40
x40
x32
 
x32
x32
 
x32
 















































































































































































































































































































































































































































































































































































































































































/**
 * An extended {@link https://jsr.io/@std/expect/doc/~/expect | expect} that defines additional matchers.
 * @module
 */
// Imports
import { type Async, expect as _expect, type Expected, fn } from "@std/expect"
import { assert, assertEquals, type AssertionError as _AssertionError, assertIsError, assertMatch, assertNotEquals, assertNotStrictEquals, assertObjectMatch, assertStrictEquals } from "@std/assert"
import type { Arg, Arrayable, callback, Nullable, record, TypeOf } from "@libs/typing"
import type { testing } from "./_testing.ts"
import { STATUS_CODE as Status } from "@std/http/status"

/**
 * The ExtendedExpected interface defines the available assertion methods.
 */
export interface ExtendedExpected<IsAsync = false> extends Expected<IsAsync> {
  /**
   * Asserts a function to throw an error.
   *
   * Unlike the epoynmous method from `@std/expect`, this matcher accepts a second argument that can be either a string or a regular expression when the first argument is a Error class or instance.
   * In this case, the behavior is the same as {@link assertIsError} where you can both check the error type and message.
   *
   * @example
   * ```ts ignore
   * import { expect } from "./expect.ts"
   * const throws = () => { throw new Error("Expected error") }
   * expect(throws).toThrow(Error)
   * expect(throws).toThrow("Expected error")
   * expect(throws).toThrow(Error, /Expected/)
   * ```
   *
   * @experimental This method may be renamed to `toThrow()` directly without being marked as breaking change.
   */
  // deno-lint-ignore no-explicit-any
  _toThrow: <E extends Error = Error>(error?: string | RegExp | E | (new (...args: any[]) => E), message?: string | RegExp) => void
  /**
   * Asserts a value matches the given predicate.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect("foo").toSatisfy((value:string) => value.length > 1)
   * ```
   */
  toSatisfy: (evaluate: callback) => unknown
  /**
   * Asserts a value is of a given type (using `typeof` operator).
   * Note that `null` is not considered of type `"object"` unless `nullable` option is set to `true`.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect("foo").toBeType("string")
   * expect({}).toBeType("object")
   * expect(null).toBeType("object", { nullable: true })
   * expect(null).not.toBeType("object")
   * ```
   */
  toBeType: (type: string, options?: { nullable?: boolean }) => unknown
  /**
   * Asserts a property matches a given descriptor (using `Object.getOwnPropertyDescriptor`).
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * const foo = Object.defineProperties({}, { bar: { value: true, writable: false, enumerable: true } })
   * expect(foo).toHaveDescribedProperty("bar", { writable: false, enumerable: true })
   * ```
   */
  toHaveDescribedProperty: (key: PropertyKey, expected: PropertyDescriptor) => unknown
  /**
   * Asserts a writable property is immutable (i.e. setting its value does not throw but does not change its value either).
   *
   * Note that it will actually proceed to assign `testValue` and restore it to original value after test.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * const foo = new (class {
   *   #bar = true
   *   get bar() {
   *     return this.#bar
   *   }
   *   set bar(_:unknown) {
   *     return
   *   }
   * })()
   * expect(foo).toHaveImmutableProperty("bar")
   * ```
   */
  toHaveImmutableProperty: (key: PropertyKey, testValue?: unknown) => unknown
  /**
   * Assert an object is iterable (checking `Symbol.iterator` presence).
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect([]).toBeIterable()
   * expect(new Map()).toBeIterable()
   * expect(new Set()).toBeIterable()
   * ```
   */
  toBeIterable: () => unknown
  /**
   * Assert an object is sealed (using `Object.isSealed`).
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect(Object.seal({})).toBeSealed()
   * ```
   */
  toBeSealed: () => unknown
  /**
   * Assert an object is frozen (using `Object.isFrozen`).
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect(Object.freeze({})).toBeFrozen()
   * ```
   */
  toBeFrozen: () => unknown
  /**
   * Assert an object is extensible (using `Object.isExtensible`).
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect(Object.preventExtensions({})).not.toBeExtensible()
   * ```
   */
  toBeExtensible: () => unknown
  /**
   * Asserts an object is a shallow copy (i.e. its content is identical but reference is not).
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * const foo = { bar: true }
   * expect({...foo}).toBeShallowCopyOf(foo)
   * ```
   */
  toBeShallowCopyOf: (expected?: Iterable<unknown> | record) => unknown
  /**
   * Asserts an iterable is empty.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect([]).toBeEmpty()
   * expect(new Map()).toBeEmpty()
   * expect(new Set()).toBeEmpty()
   * ```
   */
  toBeEmpty: () => unknown
  /**
   * Asserts an iterable to be sorted.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect([1, 2, 3]).toBeSorted()
   * ```
   */
  toBeSorted: (compare?: Arg<Array<unknown>["sort"]>) => unknown
  /**
   * Asserts an iterable to be reverse sorted.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect([3, 2, 1]).toBeReverseSorted()
   * ```
   */
  toBeReverseSorted: (compare?: Arg<Array<unknown>["sort"]>) => unknown
  /**
   * Asserts a value is one of expected value.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect("foo").toBeOneOf(["foo", "bar"])
   * ```
   */
  toBeOneOf: (values: Iterable<unknown>) => unknown
  /**
   * Asserts a number is with a given range.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect(Math.PI).toBeWithin([3, 4])
   * ```
   */
  toBeWithin: (range: [number, number], exclusive?: boolean) => unknown
  /**
   * Asserts a number to be finite.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect(1).toBeFinite()
   * expect(Infinity).not.toBeFinite()
   * ```
   */
  toBeFinite: () => unknown
  /**
   * Asserts a string to be parseable JSON.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect('{"foo":"bar"}').toBeParseableJSON()
   * ```
   */
  toBeParseableJSON: (reviver?: Arg<JSON["parse"], 1>) => unknown
  /**
   * Asserts a string is a valid email address (using https://pdw.ex-parrot.com/Mail-RFC822-Address.html).
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect("foo@example.com").toBeEmail()
   * expect("foo+bar@example.com").toBeEmail()
   * ```
   */
  toBeEmail(): () => unknown
  /**
   * Asserts a string is a valid url (using `URL`).
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect("https://example.com").toBeUrl()
   * ```
   */
  toBeUrl(): () => unknown
  /**
   * Asserts a string is a valid base64 string.
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect(btoa("foo")).toBeBase64()
   * ```
   */
  toBeBase64: () => unknown
  /**
   * Asserts a response to have a given status code.
   *
   * Note that `Response.body.cancel()` is automatically called to prevent leaks.
   * If you need to perform more assertions on a response, it is advised use separate matchers instead.
   *
   * @example
   * ```ts
   * import { expect, Status } from "./expect.ts"
   * expect(new Response(null, { status: Status.OK })).toRespondWithStatus(Status.OK)
   * expect(new Response(null, { status: Status.OK })).toRespondWithStatus([Status.OK, Status.Created])
   * expect(new Response(null, { status: Status.OK })).toRespondWithStatus("2XX")
   * ```
   */
  toRespondWithStatus: (status: Arrayable<number> | "informational" | "1XX" | "successful" | "2XX" | "redirect" | "3XX" | "client_error" | "4XX" | "server_error" | "5XX") => unknown
  /**
   * Asserts a string is hashed by specified algorithm.
   *
   * Algorithm may be either lowercase or uppercase, and contains dashes or not (e.g. `sha256`, `SHA256` and `SHA-256` will all be treated as the same).
   * Will throw if an unknown algorithm is specified.
   *
   * Please note that it only checks whether it could be a valid output of specified hash algorithm.
   *
   * @example
   * ```ts
   * import { expect, Status } from "./expect.ts"
   * expect("$2a$12$lpGSoVPZ8erLDF93Sqyic.U73v0/w0owPb3dIP9goO7iC5Wp/I8OG").toBeHashed("bcrypt")
   * ```
   */
  toBeHashed: (algorithm: string) => unknown
  /**
   * Asserts a value is a valid date (using `Date`).
   *
   * @example
   * ```ts
   * import { expect, Status } from "./expect.ts"
   * expect("2024-07-13T20:30:57.958Z").toBeDate()
   * expect(new Date()).toBeDate()
   * ```
   */
  toBeDate: () => unknown
  /**
   * Asserts a date is before another date.
   *
   * @example
   * ```ts
   * import { expect, Status } from "./expect.ts"
   * expect(new Date(Date.now() - 5000)).toBePast()
   * ```
   */
  toBePast: (date?: number | string | Date) => unknown
  /**
   * Asserts a date is after another date.
   *
   * @example
   * ```ts
   * import { expect, Status } from "./expect.ts"
   * expect(new Date(Date.now() + 5000)).toBeFuture()
   * ```
   */
  toBeFuture: (date?: number | string | Date) => unknown
  /** The negation object that allows chaining negated assertions. */
  not: IsAsync extends true ? Async<ExtendedExpected<true>> : ExtendedExpected<false>
  /** The object that allows chaining assertions with async functions that are expected to resolve to a value. */
  resolves: Async<ExtendedExpected<true>>
  /** The object that allows chaining assertions with async functions that are expected to throw an error. */
  rejects: Async<ExtendedExpected<true>>
}

/** Error thrown when an assertion fails. */
let AssertionError: typeof _AssertionError

// AssertionError is not exported by `@std/expect` (and it differs from `@std/assert`) which is why we retrieve it this way
try {
  _expect(null).toBe(true)
} catch (error) {
  AssertionError = error.constructor
}

/** Process callback and format result to match {@link Expected} result interface. */
function process(not: boolean, evaluate: callback, message = ""): { message: () => string; pass: boolean } {
  let pass = true
  try {
    evaluate()
  } catch (error) {
    if (error.name === AssertionError.name) {
      pass = false
      message += message ? `${error.message.charAt(0).toLocaleLowerCase()}${error.message.substring(1)}` : error.message
    } else {
      pass = not
      message = error.message
    }
  }
  message = message
    .replaceAll("{!NOT} ", not ? "NOT " : "")
    .replaceAll("{NOT} ", not ? "" : "NOT")
    .replace(/,\s*$/, "").trim()
  return { message: () => message, pass }
}

/** Asserts a value is iterable. */
function isIterable(value: testing): asserts value is Iterable<unknown> {
  assertNotEquals(value, null)
  if (typeof value[Symbol.iterator] !== "function") {
    throw new TypeError("Value is not iterable")
  }
}

/** Asserts a value is of a given type. */
function isType(value: testing, type: "string"): asserts value is string
function isType(value: testing, type: "number"): asserts value is number
function isType(value: testing, type: "bigint"): asserts value is bigint
function isType(value: testing, type: "boolean"): asserts value is boolean
function isType(value: testing, type: "symbol"): asserts value is symbol
function isType(value: testing, type: "undefined"): asserts value is undefined
function isType(value: testing, type: "object", options?: { nullable: true }): asserts value is Nullable<record>
function isType(value: testing, type: "object", options: { nullable: false }): asserts value is record
function isType(value: testing, type: "function"): asserts value is callback
function isType(value: testing, type: TypeOf, { nullable = false } = {}) {
  if ((typeof value) !== type) {
    throw new TypeError(`Value is not of type "${type}"`)
  }
  if ((!nullable) && (type === "object") && (value === null)) {
    throw new TypeError(`Value is null`)
  }
}

_expect.extend({
  _toThrow(context, error, message) {
    // deno-lint-ignore no-explicit-any
    type ErrorConstructor = new (...args: any[]) => Error
    if (typeof context.value === "function") {
      try {
        context.value = context.value()
      } catch (error) {
        context.value = error
      }
    }
    if ((message !== undefined) && ((typeof error === "string") || (error instanceof RegExp))) {
      throw new TypeError("First argument must be an Error class or instance when second argument is a string or RegExp")
    }
    return process(context.isNot, () => {
      const expect = { class: undefined as ErrorConstructor | undefined, message: undefined as string | RegExp | undefined }
      if (error instanceof Error) {
        expect.class = error.constructor as ErrorConstructor
        expect.message = error.message
      }
      if (error instanceof Function) {
        expect.class = error as ErrorConstructor
      }
      if ((typeof error === "string") || (error instanceof RegExp)) {
        expect.message = error
      }
      if (message) {
        expect.message = message
      }
      assertIsError(context.value, expect.class, expect.message)
    }, context.isNot ? `Expected to NOT throw ${error}` : "")
  },
  toSatisfy(context, predicate) {
    return process(context.isNot, () => {
      assert(predicate(context.value))
    }, "Expected value to {!NOT} satisfy predicate")
  },
  toBeType(context, type, { nullable = false } = {}) {
    return process(context.isNot, () => {
      try {
        isType(context.value, type, { nullable })
      } catch (error) {
        throw new AssertionError(error.message)
      }
    }, `Expected value to {!NOT} be of type "${type}"${!nullable ? " and not null but " : ""}`)
  },
  toHaveDescribedProperty(context, key, expected) {
    return process(context.isNot, () => {
      isType(context.value, "object", { nullable: false })
      const descriptor = Object.getOwnPropertyDescriptor(context.value, key)
      if (!descriptor) {
        throw new ReferenceError(`Property "${String(key)}" does not exist on object`)
      }
      assertObjectMatch(descriptor, expected)
    }, `Property "${String(key)}" does {!NOT} match provided descriptor, `)
  },
  toHaveImmutableProperty(context, key, testValue = Symbol()) {
    return process(context.isNot, () => {
      const value = context.value as Nullable<record>
      if ((value === null) || ((typeof value !== "function") && (typeof value !== "object"))) {
        throw new TypeError("Cannot be processed as value is not indexed")
      }
      const current = value[key]
      try {
        value[key] = testValue
        assertStrictEquals(value[key], current)
      } finally {
        value[key] = current
      }
    }, `Expected property "${String(key)}" to {!NOT} be immutable, previous and current `)
  },
  toBeIterable(context) {
    return process(context.isNot, () => {
      try {
        isIterable(context.value)
      } catch (error) {
        throw new AssertionError(error.message)
      }
    }, `Expected value to {!NOT} be iterable, `)
  },
  toBeSealed(context) {
    return process(context.isNot, () => {
      assert(Object.isSealed(context.value))
    }, `Expected value to {!NOT} be sealed`)
  },
  toBeFrozen(context) {
    return process(context.isNot, () => {
      assert(Object.isFrozen(context.value))
    }, `Expected value to {!NOT} be frozen`)
  },
  toBeExtensible(context) {
    return process(context.isNot, () => {
      assert(Object.isExtensible(context.value))
    }, `Expected value to {!NOT} be extensible`)
  },
  toBeShallowCopyOf(context, expected) {
    return process(context.isNot, () => {
      assertEquals(context.value, expected)
      assertNotStrictEquals(context.value, expected, `Detected same-reference`)
    }, `Expected value to {!NOT} be a shallow copy, `)
  },
  toBeEmpty(context) {
    return process(context.isNot, () => {
      isIterable(context.value)
      assertStrictEquals([...context.value].length, 0)
    }, `Expected value to {!NOT} be empty, `)
  },
  toBeSorted(context, compare) {
    return process(context.isNot, () => {
      const value = context.value
      isIterable(value)
      assertEquals([...value], [...value].sort(compare))
    }, `Expected value to {!NOT} be sorted, `)
  },
  toBeReverseSorted(context, compare) {
    return process(context.isNot, () => {
      isIterable(context.value)
      assertEquals([...context.value], [...context.value].sort(compare).reverse())
    }, `Expected value to {!NOT} be reverse sorted, `)
  },
  toBeOneOf(context, values) {
    return process(context.isNot, () => {
      assert([...values].includes(context.value))
    }, `Expected value "${context.value}" to {!NOT} be one of expected values`)
  },
  toBeWithin(context, range, exclusive) {
    return process(context.isNot, () => {
      const value = context.value
      const [min, max] = range
      isType(value, "number")
      isType(min, "number")
      isType(max, "number")
      exclusive ? assert(value > min && value < max) : assert(value >= min && value <= max)
    }, `Expected value to {!NOT} be within range ${exclusive ? `]${range[0]}, ${range[1]}[` : `[${range[0]}, ${range[1]}]`}, `)
  },
  toBeFinite(context) {
    return process(context.isNot, () => {
      isType(context.value, "number")
      assert(Number.isFinite(context.value))
    }, `Expected value to {!NOT} be finite, `)
  },
  toBeParseableJSON(context, reviver) {
    return process(context.isNot, () => {
      try {
        JSON.parse(`${context.value}`, reviver)
      } catch (error) {
        throw new AssertionError(error.message)
      }
    }, `Expected value to {!NOT} be parseable JSON, `)
  },
  toBeEmail(context) {
    return process(context.isNot, () => {
      // https://pdw.ex-parrot.com/Mail-RFC822-Address.html
      assertMatch(
        `${context.value}`,
        // deno-lint-ignore no-control-regex
        /(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t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(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*))*)?;\s*)/,
      )
    }, `Expected "${context.value}" to {!NOT} be a valid email`)
  },
  toBeUrl(context) {
    return process(context.isNot, () => {
      assert(URL.canParse(`${context.value}`))
    }, `Expected "${context.value}" to {!NOT} be a valid URL`)
  },
  toBeBase64(context) {
    return process(context.isNot, () => {
      try {
        atob(`${context.value}`)
      } catch (error) {
        throw new AssertionError(error.message)
      }
    }, `Expected "${context.value}" to {!NOT} be a valid base64 string`)
  },
  toRespondWithStatus(context, code) {
    return process(context.isNot, () => {
      if (!(context.value instanceof Response)) {
        throw new TypeError("Value is not a Response object")
      }
      let ok = false
      let message = ""
      const status = context.value.status
      switch (code) {
        case "1XX":
        case "informational":
          ok = status >= 100 && status < 200
          message = `"${code}" (100-199) but got ${status}`
          break
        case "2XX":
        case "successful":
          ok = status >= 200 && status < 300
          message = `"${code}" (200-299) but got ${status}`
          break
        case "3XX":
        case "redirect":
          ok = status >= 300 && status < 400
          message = `"${code}" (300-399) but got ${status}`
          break
        case "4XX":
        case "client_error":
          ok = status >= 400 && status < 500
          message = `"${code}" (400-499) but got ${status}`
          break
        case "5XX":
        case "server_error":
          ok = status >= 500 && status < 600
          message = `"${code}" (500-599) but got ${status}`
          break
        default: {
          const codes = [code].flat()
          ok = codes.includes(status)
          message = `[${codes.join(", ")}] but got ${status}`
        }
      }
      try {
        if ((context.isNot) && (ok === context.isNot)) {
          throw new TypeError(`Expected response status to {!NOT} be ${message}`)
        }
        if ((context.isNot) || (ok === context.isNot)) {
          throw new AssertionError(`Expected response status to {!NOT} be ${message}`)
        }
      } finally {
        context.value.body?.cancel()
      }
    })
  },
  toBeHashed(context, algorithm) {
    return process(context.isNot, () => {
      isType(context.value, "string")
      algorithm = algorithm.toLocaleLowerCase().replace("-", "")
      const algorithms = {
        "bcrypt": 0,
        "md5": 32,
        "sha0": 40,
        "sha1": 40,
        "sha224": 56,
        "sha256": 64,
        "sha384": 96,
        "sha512": 128,
        "sha512/224": 56,
        "sha512/256": 64,
      } as record<number>
      if (algorithms[algorithm]) {
        assertStrictEquals(context.value.length, algorithms[algorithm])
        if (!/^[a-z0-9]+$/i.test(context.value)) {
          throw new TypeError("Value contains non-hexadecimal characters")
        }
        return
      }
      if (algorithm === "bcrypt") {
        assertMatch(context.value, /^\$2[aby]?\$\d{2}\$[./A-Za-z0-9]{53}$/)
        return
      }
      throw new RangeError(`Algorithm "${algorithm}" is unknown`)
    }, `Expected value to {!NOT} be hashed by ${algorithm}, `)
  },
  toBeDate(context) {
    return process(context.isNot, () => {
      assert(Number.isFinite(new Date(context.value as number | string | Date).getTime()))
    }, `Expected value to {!NOT} be a date, `)
  },
  toBePast(context, ref = new Date()) {
    return process(context.isNot, () => {
      const date = new Date(context.value as number | string | Date)
      if (date > ref) {
        throw new AssertionError(`${date.toISOString()} is after ${ref.toISOString()}`)
      }
    }, `Expected value to {!NOT} be in the past, `)
  },
  toBeFuture(context, ref = new Date()) {
    return process(context.isNot, () => {
      const date = new Date(context.value as number | string | Date)
      if (date < ref) {
        throw new AssertionError(`${date.toISOString()} is before ${ref.toISOString()}`)
      }
    }, `Expected value to {!NOT} be in the future, `)
  },
})

/** https://jsr.io/@std/expect/doc/~/expect. */
const expect = _expect as unknown as ((...args: Parameters<typeof _expect>) => ExtendedExpected) & { [K in keyof typeof _expect]: typeof _expect[K] }

export { AssertionError, expect, fn, Status }
export type { _AssertionError, _expect, Arg, Arrayable, Async, callback, Expected, Nullable, record, TypeOf }