All files / expect.ts

100.00% Branches 62/62
100.00% Lines 296/296
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
x1
x4
x4
 
 
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x4
 
x1
x4
x4
x4
x4
x4
 
x4
x4
x214
x214
x214
x214
x324
x415
x415
x324
x343
x343
x343
x324
x214
x214
x214
x214
x856
x214
 
x4
x4
x32
x32
x34
x34
x32
 
 
 
 
 
 
 
 
 
 
 
x72
x72
x75
x75
x72
x74
x74
x72
 
x4
x4
x10
x16
x10
x4
x4
x12
x20
x20
x20
x24
x24
x12
x4
x4
x13
x22
x22
x22
x23
x23
x30
x13
x4
x4
x14
x24
x24
x26
x26
x32
x32
x32
x32
x32
x32
x32
x14
x4
x4
x12
x20
x20
x20
x22
x22
x12
x4
x4
x8
x12
x8
x4
x4
x8
x12
x8
x4
x4
x8
x12
x8
x4
x4
x12
x20
x20
x12
x4
x4
x16
x28
x84
x16
x4
x4
x8
x12
x12
x60
x8
x4
x4
x8
x12
x60
x8
x4
x4
x8
x36
x8
x4
x4
x14
x24
x24
x24
x24
x24
x24
x14
x4
x4
x10
x16
x16
x10
x4
x4
x8
x12
x12
x12
x14
x14
x8
x4
x4
x10
x16
x16
x16
x16
x16
 
x10
x4
x4
x10
x16
x10
x4
x4
x8
x12
x12
x12
x14
x14
x8
x4
x4
x54
x104
x105
x105
x153
x153
x153
x153
x104
x104
x124
x124
x124
x104
x104
x112
x112
x112
x104
x104
x108
x108
x108
x104
x104
x108
x108
x108
x104
x104
x108
x108
x108
x217
x339
x113
x113
x113
x104
x153
x104
x116
x116
x104
x128
x128
x104
x153
x153
x54
x4
x4
x19
x34
x34
x34
x34
x34
x34
x34
x34
x34
x34
x34
x34
x34
x34
x34
x45
x45
x46
x46
x53
x53
x34
x36
x36
x36
x35
x19
x4
x4
x12
x20
x12
x4
x4
x12
x20
x20
x24
x24
x12
x4
x4
x12
x20
x20
x24
x24
x12
x12
x4
 
x4
x4
 
x4
 


























































































































































































































































































































































































































































































































































































































// Imports
import { type Async, expect as _expect, type Expected, fn } from "@std/expect"
import { assert, assertEquals, type AssertionError as _AssertionError, 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.
 *
 * @module
 */
export interface ExtendedExpected<IsAsync = false> extends Expected<IsAsync> {
  /**
   * 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).
   *
   * @example
   * ```ts
   * import { expect } from "./expect.ts"
   * expect("foo").toBeType("string")
   * expect({}).toBeType("object")
   * expect(null).toBeType("object")
   * expect(null).not.toBeType("object", !null)
   * ```
   */
  toBeType: (type: string, notnull?: 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", notnull?: false): asserts value is Nullable<record>
function isType(value: testing, type: "object", notnull: true): asserts value is record
function isType(value: testing, type: "function"): asserts value is callback
function isType(value: testing, type: TypeOf, notnull?: boolean) {
  if ((typeof value) !== type) {
    throw new TypeError(`Value is not of type "${type}"`)
  }
  if (notnull && (type === "object") && (value === null)) {
    throw new TypeError(`Value is null`)
  }
}

_expect.extend({
  toSatisfy(context, predicate) {
    return process(context.isNot, () => {
      assert(predicate(context.value))
    }, "Expected value to {!NOT} satisfy predicate")
  },
  toBeType(context, type, notnull) {
    return process(context.isNot, () => {
      try {
        isType(context.value, type, notnull)
      } catch (error) {
        throw new AssertionError(error.message)
      }
    }, `Expected value to {!NOT} be of type "${type}"${notnull ? " and not null but " : ""}`)
  },
  toHaveDescribedProperty(context, key, expected) {
    return process(context.isNot, () => {
      isType(context.value, "object", !null)
      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])*(?:@(?:[^()<>@,;:\\".\[\] \x00-\x19]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(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-\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 }