@netlify/plugin-nextjs 5.9.0 → 5.9.2

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.
Files changed (35) hide show
  1. package/dist/build/content/prerendered.js +2 -2
  2. package/dist/build/content/static.js +2 -2
  3. package/dist/build/functions/edge.js +1 -1
  4. package/dist/esm-chunks/{chunk-BFYMHE3E.js → chunk-HGXG447M.js} +13 -0
  5. package/dist/esm-chunks/chunk-LVXJQ2G2.js +147 -0
  6. package/dist/esm-chunks/{chunk-KBX7SJLC.js → chunk-NEZW7TGG.js} +1 -1
  7. package/dist/esm-chunks/{next-4L47PQSM.js → next-H2VMRX5P.js} +2 -4
  8. package/dist/esm-chunks/{package-LCNINN36.js → package-36IBNZ37.js} +2 -2
  9. package/dist/index.js +4 -4
  10. package/dist/run/handlers/cache.cjs +251 -139
  11. package/dist/run/handlers/request-context.cjs +88 -63
  12. package/dist/run/handlers/server.js +4 -4
  13. package/dist/run/handlers/tracer.cjs +88 -57
  14. package/dist/run/handlers/tracing.js +2 -2
  15. package/dist/run/handlers/wait-until.cjs +88 -57
  16. package/dist/run/next.cjs +88 -59
  17. package/edge-runtime/lib/middleware.ts +1 -1
  18. package/edge-runtime/lib/response.ts +5 -2
  19. package/edge-runtime/vendor/deno.land/x/htmlrewriter@v1.0.0/pkg/htmlrewriter.js +1218 -0
  20. package/edge-runtime/vendor/deno.land/x/htmlrewriter@v1.0.0/pkg/htmlrewriter_bg.wasm +0 -0
  21. package/edge-runtime/vendor/deno.land/x/htmlrewriter@v1.0.0/src/index.ts +80 -0
  22. package/edge-runtime/vendor/deno.land/x/{html_rewriter@v0.1.0-pre.17/vendor/html_rewriter.d.ts → htmlrewriter@v1.0.0/src/types.d.ts} +8 -25
  23. package/edge-runtime/vendor/import_map.json +0 -2
  24. package/edge-runtime/vendor.ts +1 -1
  25. package/package.json +1 -1
  26. package/dist/esm-chunks/chunk-NDSDIXRD.js +0 -122
  27. package/edge-runtime/vendor/deno.land/std@0.134.0/fmt/colors.ts +0 -536
  28. package/edge-runtime/vendor/deno.land/std@0.134.0/testing/_diff.ts +0 -360
  29. package/edge-runtime/vendor/deno.land/std@0.134.0/testing/asserts.ts +0 -866
  30. package/edge-runtime/vendor/deno.land/x/html_rewriter@v0.1.0-pre.17/index.ts +0 -133
  31. package/edge-runtime/vendor/deno.land/x/html_rewriter@v0.1.0-pre.17/vendor/asyncify.js +0 -112
  32. package/edge-runtime/vendor/deno.land/x/html_rewriter@v0.1.0-pre.17/vendor/html_rewriter.js +0 -974
  33. package/edge-runtime/vendor/raw.githubusercontent.com/worker-tools/resolvable-promise/master/index.ts +0 -50
  34. package/dist/esm-chunks/{chunk-BVYZSEV6.js → chunk-J4D25YDX.js} +3 -3
  35. package/dist/esm-chunks/{chunk-HWMLYAVP.js → chunk-NTLBFRPA.js} +3 -3
@@ -1,866 +0,0 @@
1
- // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
2
- // This module is browser compatible. Do not rely on good formatting of values
3
- // for AssertionError messages in browsers.
4
-
5
- import {
6
- bgGreen,
7
- bgRed,
8
- bold,
9
- gray,
10
- green,
11
- red,
12
- stripColor,
13
- white,
14
- } from "../fmt/colors.ts";
15
- import { diff, DiffResult, diffstr, DiffType } from "./_diff.ts";
16
-
17
- const CAN_NOT_DISPLAY = "[Cannot display]";
18
-
19
- export class AssertionError extends Error {
20
- override name = "AssertionError";
21
- constructor(message: string) {
22
- super(message);
23
- }
24
- }
25
-
26
- /**
27
- * Converts the input into a string. Objects, Sets and Maps are sorted so as to
28
- * make tests less flaky
29
- * @param v Value to be formatted
30
- */
31
- export function _format(v: unknown): string {
32
- // deno-lint-ignore no-explicit-any
33
- const { Deno } = globalThis as any;
34
- return typeof Deno?.inspect === "function"
35
- ? Deno.inspect(v, {
36
- depth: Infinity,
37
- sorted: true,
38
- trailingComma: true,
39
- compact: false,
40
- iterableLimit: Infinity,
41
- })
42
- : `"${String(v).replace(/(?=["\\])/g, "\\")}"`;
43
- }
44
-
45
- /**
46
- * Colors the output of assertion diffs
47
- * @param diffType Difference type, either added or removed
48
- */
49
- function createColor(
50
- diffType: DiffType,
51
- { background = false } = {},
52
- ): (s: string) => string {
53
- switch (diffType) {
54
- case DiffType.added:
55
- return (s: string): string =>
56
- background ? bgGreen(white(s)) : green(bold(s));
57
- case DiffType.removed:
58
- return (s: string): string => background ? bgRed(white(s)) : red(bold(s));
59
- default:
60
- return white;
61
- }
62
- }
63
-
64
- /**
65
- * Prefixes `+` or `-` in diff output
66
- * @param diffType Difference type, either added or removed
67
- */
68
- function createSign(diffType: DiffType): string {
69
- switch (diffType) {
70
- case DiffType.added:
71
- return "+ ";
72
- case DiffType.removed:
73
- return "- ";
74
- default:
75
- return " ";
76
- }
77
- }
78
-
79
- function buildMessage(
80
- diffResult: ReadonlyArray<DiffResult<string>>,
81
- { stringDiff = false } = {},
82
- ): string[] {
83
- const messages: string[] = [], diffMessages: string[] = [];
84
- messages.push("");
85
- messages.push("");
86
- messages.push(
87
- ` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${
88
- green(bold("Expected"))
89
- }`,
90
- );
91
- messages.push("");
92
- messages.push("");
93
- diffResult.forEach((result: DiffResult<string>): void => {
94
- const c = createColor(result.type);
95
- const line = result.details?.map((detail) =>
96
- detail.type !== DiffType.common
97
- ? createColor(detail.type, { background: true })(detail.value)
98
- : detail.value
99
- ).join("") ?? result.value;
100
- diffMessages.push(c(`${createSign(result.type)}${line}`));
101
- });
102
- messages.push(...(stringDiff ? [diffMessages.join("")] : diffMessages));
103
- messages.push("");
104
-
105
- return messages;
106
- }
107
-
108
- function isKeyedCollection(x: unknown): x is Set<unknown> {
109
- return [Symbol.iterator, "size"].every((k) => k in (x as Set<unknown>));
110
- }
111
-
112
- /**
113
- * Deep equality comparison used in assertions
114
- * @param c actual value
115
- * @param d expected value
116
- */
117
- export function equal(c: unknown, d: unknown): boolean {
118
- const seen = new Map();
119
- return (function compare(a: unknown, b: unknown): boolean {
120
- // Have to render RegExp & Date for string comparison
121
- // unless it's mistreated as object
122
- if (
123
- a &&
124
- b &&
125
- ((a instanceof RegExp && b instanceof RegExp) ||
126
- (a instanceof URL && b instanceof URL))
127
- ) {
128
- return String(a) === String(b);
129
- }
130
- if (a instanceof Date && b instanceof Date) {
131
- const aTime = a.getTime();
132
- const bTime = b.getTime();
133
- // Check for NaN equality manually since NaN is not
134
- // equal to itself.
135
- if (Number.isNaN(aTime) && Number.isNaN(bTime)) {
136
- return true;
137
- }
138
- return aTime === bTime;
139
- }
140
- if (typeof a === "number" && typeof b === "number") {
141
- return Number.isNaN(a) && Number.isNaN(b) || a === b;
142
- }
143
- if (Object.is(a, b)) {
144
- return true;
145
- }
146
- if (a && typeof a === "object" && b && typeof b === "object") {
147
- if (a && b && !constructorsEqual(a, b)) {
148
- return false;
149
- }
150
- if (a instanceof WeakMap || b instanceof WeakMap) {
151
- if (!(a instanceof WeakMap && b instanceof WeakMap)) return false;
152
- throw new TypeError("cannot compare WeakMap instances");
153
- }
154
- if (a instanceof WeakSet || b instanceof WeakSet) {
155
- if (!(a instanceof WeakSet && b instanceof WeakSet)) return false;
156
- throw new TypeError("cannot compare WeakSet instances");
157
- }
158
- if (seen.get(a) === b) {
159
- return true;
160
- }
161
- if (Object.keys(a || {}).length !== Object.keys(b || {}).length) {
162
- return false;
163
- }
164
- if (isKeyedCollection(a) && isKeyedCollection(b)) {
165
- if (a.size !== b.size) {
166
- return false;
167
- }
168
-
169
- let unmatchedEntries = a.size;
170
-
171
- for (const [aKey, aValue] of a.entries()) {
172
- for (const [bKey, bValue] of b.entries()) {
173
- /* Given that Map keys can be references, we need
174
- * to ensure that they are also deeply equal */
175
- if (
176
- (aKey === aValue && bKey === bValue && compare(aKey, bKey)) ||
177
- (compare(aKey, bKey) && compare(aValue, bValue))
178
- ) {
179
- unmatchedEntries--;
180
- }
181
- }
182
- }
183
-
184
- return unmatchedEntries === 0;
185
- }
186
- const merged = { ...a, ...b };
187
- for (
188
- const key of [
189
- ...Object.getOwnPropertyNames(merged),
190
- ...Object.getOwnPropertySymbols(merged),
191
- ]
192
- ) {
193
- type Key = keyof typeof merged;
194
- if (!compare(a && a[key as Key], b && b[key as Key])) {
195
- return false;
196
- }
197
- if (((key in a) && (!(key in b))) || ((key in b) && (!(key in a)))) {
198
- return false;
199
- }
200
- }
201
- seen.set(a, b);
202
- if (a instanceof WeakRef || b instanceof WeakRef) {
203
- if (!(a instanceof WeakRef && b instanceof WeakRef)) return false;
204
- return compare(a.deref(), b.deref());
205
- }
206
- return true;
207
- }
208
- return false;
209
- })(c, d);
210
- }
211
-
212
- // deno-lint-ignore ban-types
213
- function constructorsEqual(a: object, b: object) {
214
- return a.constructor === b.constructor ||
215
- a.constructor === Object && !b.constructor ||
216
- !a.constructor && b.constructor === Object;
217
- }
218
-
219
- /** Make an assertion, error will be thrown if `expr` does not have truthy value. */
220
- export function assert(expr: unknown, msg = ""): asserts expr {
221
- if (!expr) {
222
- throw new AssertionError(msg);
223
- }
224
- }
225
-
226
- /**
227
- * Make an assertion that `actual` and `expected` are equal, deeply. If not
228
- * deeply equal, then throw.
229
- *
230
- * Type parameter can be specified to ensure values under comparison have the same type.
231
- * For example:
232
- * ```ts
233
- * import { assertEquals } from "./asserts.ts";
234
- *
235
- * assertEquals<number>(1, 2)
236
- * ```
237
- */
238
- export function assertEquals(
239
- actual: unknown,
240
- expected: unknown,
241
- msg?: string,
242
- ): void;
243
- export function assertEquals<T>(actual: T, expected: T, msg?: string): void;
244
- export function assertEquals(
245
- actual: unknown,
246
- expected: unknown,
247
- msg?: string,
248
- ): void {
249
- if (equal(actual, expected)) {
250
- return;
251
- }
252
- let message = "";
253
- const actualString = _format(actual);
254
- const expectedString = _format(expected);
255
- try {
256
- const stringDiff = (typeof actual === "string") &&
257
- (typeof expected === "string");
258
- const diffResult = stringDiff
259
- ? diffstr(actual as string, expected as string)
260
- : diff(actualString.split("\n"), expectedString.split("\n"));
261
- const diffMsg = buildMessage(diffResult, { stringDiff }).join("\n");
262
- message = `Values are not equal:\n${diffMsg}`;
263
- } catch {
264
- message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`;
265
- }
266
- if (msg) {
267
- message = msg;
268
- }
269
- throw new AssertionError(message);
270
- }
271
-
272
- /**
273
- * Make an assertion that `actual` and `expected` are not equal, deeply.
274
- * If not then throw.
275
- *
276
- * Type parameter can be specified to ensure values under comparison have the same type.
277
- * For example:
278
- * ```ts
279
- * import { assertNotEquals } from "./asserts.ts";
280
- *
281
- * assertNotEquals<number>(1, 2)
282
- * ```
283
- */
284
- export function assertNotEquals(
285
- actual: unknown,
286
- expected: unknown,
287
- msg?: string,
288
- ): void;
289
- export function assertNotEquals<T>(actual: T, expected: T, msg?: string): void;
290
- export function assertNotEquals(
291
- actual: unknown,
292
- expected: unknown,
293
- msg?: string,
294
- ): void {
295
- if (!equal(actual, expected)) {
296
- return;
297
- }
298
- let actualString: string;
299
- let expectedString: string;
300
- try {
301
- actualString = String(actual);
302
- } catch {
303
- actualString = "[Cannot display]";
304
- }
305
- try {
306
- expectedString = String(expected);
307
- } catch {
308
- expectedString = "[Cannot display]";
309
- }
310
- if (!msg) {
311
- msg = `actual: ${actualString} expected not to be: ${expectedString}`;
312
- }
313
- throw new AssertionError(msg);
314
- }
315
-
316
- /**
317
- * Make an assertion that `actual` and `expected` are strictly equal. If
318
- * not then throw.
319
- *
320
- * ```ts
321
- * import { assertStrictEquals } from "./asserts.ts";
322
- *
323
- * assertStrictEquals(1, 2)
324
- * ```
325
- */
326
- export function assertStrictEquals<T>(
327
- actual: unknown,
328
- expected: T,
329
- msg?: string,
330
- ): asserts actual is T {
331
- if (actual === expected) {
332
- return;
333
- }
334
-
335
- let message: string;
336
-
337
- if (msg) {
338
- message = msg;
339
- } else {
340
- const actualString = _format(actual);
341
- const expectedString = _format(expected);
342
-
343
- if (actualString === expectedString) {
344
- const withOffset = actualString
345
- .split("\n")
346
- .map((l) => ` ${l}`)
347
- .join("\n");
348
- message =
349
- `Values have the same structure but are not reference-equal:\n\n${
350
- red(withOffset)
351
- }\n`;
352
- } else {
353
- try {
354
- const stringDiff = (typeof actual === "string") &&
355
- (typeof expected === "string");
356
- const diffResult = stringDiff
357
- ? diffstr(actual as string, expected as string)
358
- : diff(actualString.split("\n"), expectedString.split("\n"));
359
- const diffMsg = buildMessage(diffResult, { stringDiff }).join("\n");
360
- message = `Values are not strictly equal:\n${diffMsg}`;
361
- } catch {
362
- message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`;
363
- }
364
- }
365
- }
366
-
367
- throw new AssertionError(message);
368
- }
369
-
370
- /**
371
- * Make an assertion that `actual` and `expected` are not strictly equal.
372
- * If the values are strictly equal then throw.
373
- *
374
- * ```ts
375
- * import { assertNotStrictEquals } from "./asserts.ts";
376
- *
377
- * assertNotStrictEquals(1, 1)
378
- * ```
379
- */
380
- export function assertNotStrictEquals(
381
- actual: unknown,
382
- expected: unknown,
383
- msg?: string,
384
- ): void;
385
- export function assertNotStrictEquals<T>(
386
- actual: T,
387
- expected: T,
388
- msg?: string,
389
- ): void;
390
- export function assertNotStrictEquals(
391
- actual: unknown,
392
- expected: unknown,
393
- msg?: string,
394
- ): void {
395
- if (actual !== expected) {
396
- return;
397
- }
398
-
399
- throw new AssertionError(
400
- msg ?? `Expected "actual" to be strictly unequal to: ${_format(actual)}\n`,
401
- );
402
- }
403
-
404
- /**
405
- * Make an assertion that `actual` and `expected` are almost equal numbers through
406
- * a given tolerance. It can be used to take into account IEEE-754 double-precision
407
- * floating-point representation limitations.
408
- * If the values are not almost equal then throw.
409
- *
410
- * ```ts
411
- * import { assertAlmostEquals, assertThrows } from "./asserts.ts";
412
- *
413
- * assertAlmostEquals(0.1, 0.2);
414
- *
415
- * // Using a custom tolerance value
416
- * assertAlmostEquals(0.1 + 0.2, 0.3, 1e-16);
417
- * assertThrows(() => assertAlmostEquals(0.1 + 0.2, 0.3, 1e-17));
418
- * ```
419
- */
420
- export function assertAlmostEquals(
421
- actual: number,
422
- expected: number,
423
- tolerance = 1e-7,
424
- msg?: string,
425
- ) {
426
- if (actual === expected) {
427
- return;
428
- }
429
- const delta = Math.abs(expected - actual);
430
- if (delta <= tolerance) {
431
- return;
432
- }
433
- const f = (n: number) => Number.isInteger(n) ? n : n.toExponential();
434
- throw new AssertionError(
435
- msg ??
436
- `actual: "${f(actual)}" expected to be close to "${f(expected)}": \
437
- delta "${f(delta)}" is greater than "${f(tolerance)}"`,
438
- );
439
- }
440
-
441
- // deno-lint-ignore no-explicit-any
442
- type AnyConstructor = new (...args: any[]) => any;
443
- type GetConstructorType<T extends AnyConstructor> = T extends // deno-lint-ignore no-explicit-any
444
- new (...args: any) => infer C ? C
445
- : never;
446
-
447
- /**
448
- * Make an assertion that `obj` is an instance of `type`.
449
- * If not then throw.
450
- */
451
- export function assertInstanceOf<T extends AnyConstructor>(
452
- actual: unknown,
453
- expectedType: T,
454
- msg = "",
455
- ): asserts actual is GetConstructorType<T> {
456
- if (!msg) {
457
- const expectedTypeStr = expectedType.name;
458
-
459
- let actualTypeStr = "";
460
- if (actual === null) {
461
- actualTypeStr = "null";
462
- } else if (actual === undefined) {
463
- actualTypeStr = "undefined";
464
- } else if (typeof actual === "object") {
465
- actualTypeStr = actual.constructor?.name ?? "Object";
466
- } else {
467
- actualTypeStr = typeof actual;
468
- }
469
-
470
- if (expectedTypeStr == actualTypeStr) {
471
- msg = `Expected object to be an instance of "${expectedTypeStr}".`;
472
- } else if (actualTypeStr == "function") {
473
- msg =
474
- `Expected object to be an instance of "${expectedTypeStr}" but was not an instanced object.`;
475
- } else {
476
- msg =
477
- `Expected object to be an instance of "${expectedTypeStr}" but was "${actualTypeStr}".`;
478
- }
479
- }
480
- assert(actual instanceof expectedType, msg);
481
- }
482
-
483
- /**
484
- * Make an assertion that actual is not null or undefined.
485
- * If not then throw.
486
- */
487
- export function assertExists<T>(
488
- actual: T,
489
- msg?: string,
490
- ): asserts actual is NonNullable<T> {
491
- if (actual === undefined || actual === null) {
492
- if (!msg) {
493
- msg = `actual: "${actual}" expected to not be null or undefined`;
494
- }
495
- throw new AssertionError(msg);
496
- }
497
- }
498
-
499
- /**
500
- * Make an assertion that actual includes expected. If not
501
- * then throw.
502
- */
503
- export function assertStringIncludes(
504
- actual: string,
505
- expected: string,
506
- msg?: string,
507
- ): void {
508
- if (!actual.includes(expected)) {
509
- if (!msg) {
510
- msg = `actual: "${actual}" expected to contain: "${expected}"`;
511
- }
512
- throw new AssertionError(msg);
513
- }
514
- }
515
-
516
- /**
517
- * Make an assertion that `actual` includes the `expected` values.
518
- * If not then an error will be thrown.
519
- *
520
- * Type parameter can be specified to ensure values under comparison have the same type.
521
- * For example:
522
- *
523
- * ```ts
524
- * import { assertArrayIncludes } from "./asserts.ts";
525
- *
526
- * assertArrayIncludes<number>([1, 2], [2])
527
- * ```
528
- */
529
- export function assertArrayIncludes(
530
- actual: ArrayLike<unknown>,
531
- expected: ArrayLike<unknown>,
532
- msg?: string,
533
- ): void;
534
- export function assertArrayIncludes<T>(
535
- actual: ArrayLike<T>,
536
- expected: ArrayLike<T>,
537
- msg?: string,
538
- ): void;
539
- export function assertArrayIncludes(
540
- actual: ArrayLike<unknown>,
541
- expected: ArrayLike<unknown>,
542
- msg?: string,
543
- ): void {
544
- const missing: unknown[] = [];
545
- for (let i = 0; i < expected.length; i++) {
546
- let found = false;
547
- for (let j = 0; j < actual.length; j++) {
548
- if (equal(expected[i], actual[j])) {
549
- found = true;
550
- break;
551
- }
552
- }
553
- if (!found) {
554
- missing.push(expected[i]);
555
- }
556
- }
557
- if (missing.length === 0) {
558
- return;
559
- }
560
- if (!msg) {
561
- msg = `actual: "${_format(actual)}" expected to include: "${
562
- _format(expected)
563
- }"\nmissing: ${_format(missing)}`;
564
- }
565
- throw new AssertionError(msg);
566
- }
567
-
568
- /**
569
- * Make an assertion that `actual` match RegExp `expected`. If not
570
- * then throw.
571
- */
572
- export function assertMatch(
573
- actual: string,
574
- expected: RegExp,
575
- msg?: string,
576
- ): void {
577
- if (!expected.test(actual)) {
578
- if (!msg) {
579
- msg = `actual: "${actual}" expected to match: "${expected}"`;
580
- }
581
- throw new AssertionError(msg);
582
- }
583
- }
584
-
585
- /**
586
- * Make an assertion that `actual` not match RegExp `expected`. If match
587
- * then throw.
588
- */
589
- export function assertNotMatch(
590
- actual: string,
591
- expected: RegExp,
592
- msg?: string,
593
- ): void {
594
- if (expected.test(actual)) {
595
- if (!msg) {
596
- msg = `actual: "${actual}" expected to not match: "${expected}"`;
597
- }
598
- throw new AssertionError(msg);
599
- }
600
- }
601
-
602
- /**
603
- * Make an assertion that `actual` object is a subset of `expected` object, deeply.
604
- * If not, then throw.
605
- */
606
- export function assertObjectMatch(
607
- // deno-lint-ignore no-explicit-any
608
- actual: Record<PropertyKey, any>,
609
- expected: Record<PropertyKey, unknown>,
610
- ): void {
611
- type loose = Record<PropertyKey, unknown>;
612
-
613
- function filter(a: loose, b: loose) {
614
- const seen = new WeakMap();
615
- return fn(a, b);
616
-
617
- function fn(a: loose, b: loose): loose {
618
- // Prevent infinite loop with circular references with same filter
619
- if ((seen.has(a)) && (seen.get(a) === b)) {
620
- return a;
621
- }
622
- seen.set(a, b);
623
- // Filter keys and symbols which are present in both actual and expected
624
- const filtered = {} as loose;
625
- const entries = [
626
- ...Object.getOwnPropertyNames(a),
627
- ...Object.getOwnPropertySymbols(a),
628
- ]
629
- .filter((key) => key in b)
630
- .map((key) => [key, a[key as string]]) as Array<[string, unknown]>;
631
- for (const [key, value] of entries) {
632
- // On array references, build a filtered array and filter nested objects inside
633
- if (Array.isArray(value)) {
634
- const subset = (b as loose)[key];
635
- if (Array.isArray(subset)) {
636
- filtered[key] = fn({ ...value }, { ...subset });
637
- continue;
638
- }
639
- } // On regexp references, keep value as it to avoid loosing pattern and flags
640
- else if (value instanceof RegExp) {
641
- filtered[key] = value;
642
- continue;
643
- } // On nested objects references, build a filtered object recursively
644
- else if (typeof value === "object") {
645
- const subset = (b as loose)[key];
646
- if ((typeof subset === "object") && (subset)) {
647
- // When both operands are maps, build a filtered map with common keys and filter nested objects inside
648
- if ((value instanceof Map) && (subset instanceof Map)) {
649
- filtered[key] = new Map(
650
- [...value].filter(([k]) => subset.has(k)).map((
651
- [k, v],
652
- ) => [k, typeof v === "object" ? fn(v, subset.get(k)) : v]),
653
- );
654
- continue;
655
- }
656
- // When both operands are set, build a filtered set with common values
657
- if ((value instanceof Set) && (subset instanceof Set)) {
658
- filtered[key] = new Set([...value].filter((v) => subset.has(v)));
659
- continue;
660
- }
661
- filtered[key] = fn(value as loose, subset as loose);
662
- continue;
663
- }
664
- }
665
- filtered[key] = value;
666
- }
667
- return filtered;
668
- }
669
- }
670
- return assertEquals(
671
- // get the intersection of "actual" and "expected"
672
- // side effect: all the instances' constructor field is "Object" now.
673
- filter(actual, expected),
674
- // set (nested) instances' constructor field to be "Object" without changing expected value.
675
- // see https://github.com/denoland/deno_std/pull/1419
676
- filter(expected, expected),
677
- );
678
- }
679
-
680
- /**
681
- * Forcefully throws a failed assertion
682
- */
683
- export function fail(msg?: string): never {
684
- assert(false, `Failed assertion${msg ? `: ${msg}` : "."}`);
685
- }
686
-
687
- /**
688
- * Make an assertion that `error` is an `Error`.
689
- * If not then an error will be thrown.
690
- * An error class and a string that should be included in the
691
- * error message can also be asserted.
692
- */
693
- export function assertIsError<E extends Error = Error>(
694
- error: unknown,
695
- // deno-lint-ignore no-explicit-any
696
- ErrorClass?: new (...args: any[]) => E,
697
- msgIncludes?: string,
698
- msg?: string,
699
- ): asserts error is E {
700
- if (error instanceof Error === false) {
701
- throw new AssertionError(`Expected "error" to be an Error object.`);
702
- }
703
- if (ErrorClass && !(error instanceof ErrorClass)) {
704
- msg = `Expected error to be instance of "${ErrorClass.name}", but was "${
705
- typeof error === "object" ? error?.constructor?.name : "[not an object]"
706
- }"${msg ? `: ${msg}` : "."}`;
707
- throw new AssertionError(msg);
708
- }
709
- if (
710
- msgIncludes && (!(error instanceof Error) ||
711
- !stripColor(error.message).includes(stripColor(msgIncludes)))
712
- ) {
713
- msg = `Expected error message to include "${msgIncludes}", but got "${
714
- error instanceof Error ? error.message : "[not an Error]"
715
- }"${msg ? `: ${msg}` : "."}`;
716
- throw new AssertionError(msg);
717
- }
718
- }
719
-
720
- /**
721
- * Executes a function, expecting it to throw. If it does not, then it
722
- * throws. An error class and a string that should be included in the
723
- * error message can also be asserted. Or you can pass a
724
- * callback which will be passed the error, usually to apply some custom
725
- * assertions on it.
726
- */
727
- export function assertThrows<E extends Error = Error>(
728
- fn: () => unknown,
729
- // deno-lint-ignore no-explicit-any
730
- ErrorClass?: new (...args: any[]) => E,
731
- msgIncludes?: string,
732
- msg?: string,
733
- ): void;
734
- export function assertThrows(
735
- fn: () => unknown,
736
- errorCallback: (e: Error) => unknown,
737
- msg?: string,
738
- ): void;
739
- export function assertThrows<E extends Error = Error>(
740
- fn: () => unknown,
741
- errorClassOrCallback?:
742
- // deno-lint-ignore no-explicit-any
743
- | (new (...args: any[]) => E)
744
- | ((e: Error) => unknown),
745
- msgIncludesOrMsg?: string,
746
- msg?: string,
747
- ): void {
748
- // deno-lint-ignore no-explicit-any
749
- let ErrorClass: (new (...args: any[]) => E) | undefined = undefined;
750
- let msgIncludes: string | undefined = undefined;
751
- let errorCallback;
752
- if (
753
- errorClassOrCallback == null ||
754
- errorClassOrCallback.prototype instanceof Error ||
755
- errorClassOrCallback.prototype === Error.prototype
756
- ) {
757
- // deno-lint-ignore no-explicit-any
758
- ErrorClass = errorClassOrCallback as new (...args: any[]) => E;
759
- msgIncludes = msgIncludesOrMsg;
760
- errorCallback = null;
761
- } else {
762
- errorCallback = errorClassOrCallback as (e: Error) => unknown;
763
- msg = msgIncludesOrMsg;
764
- }
765
- let doesThrow = false;
766
- try {
767
- fn();
768
- } catch (error) {
769
- if (error instanceof Error === false) {
770
- throw new AssertionError("A non-Error object was thrown.");
771
- }
772
- assertIsError(
773
- error,
774
- ErrorClass,
775
- msgIncludes,
776
- msg,
777
- );
778
- if (typeof errorCallback == "function") {
779
- errorCallback(error);
780
- }
781
- doesThrow = true;
782
- }
783
- if (!doesThrow) {
784
- msg = `Expected function to throw${msg ? `: ${msg}` : "."}`;
785
- throw new AssertionError(msg);
786
- }
787
- }
788
-
789
- /**
790
- * Executes a function which returns a promise, expecting it to throw or reject.
791
- * If it does not, then it throws. An error class and a string that should be
792
- * included in the error message can also be asserted. Or you can pass a
793
- * callback which will be passed the error, usually to apply some custom
794
- * assertions on it.
795
- */
796
- export function assertRejects<E extends Error = Error>(
797
- fn: () => Promise<unknown>,
798
- // deno-lint-ignore no-explicit-any
799
- ErrorClass?: new (...args: any[]) => E,
800
- msgIncludes?: string,
801
- msg?: string,
802
- ): Promise<void>;
803
- export function assertRejects(
804
- fn: () => Promise<unknown>,
805
- errorCallback: (e: Error) => unknown,
806
- msg?: string,
807
- ): Promise<void>;
808
- export async function assertRejects<E extends Error = Error>(
809
- fn: () => Promise<unknown>,
810
- errorClassOrCallback?:
811
- // deno-lint-ignore no-explicit-any
812
- | (new (...args: any[]) => E)
813
- | ((e: Error) => unknown),
814
- msgIncludesOrMsg?: string,
815
- msg?: string,
816
- ): Promise<void> {
817
- // deno-lint-ignore no-explicit-any
818
- let ErrorClass: (new (...args: any[]) => E) | undefined = undefined;
819
- let msgIncludes: string | undefined = undefined;
820
- let errorCallback;
821
- if (
822
- errorClassOrCallback == null ||
823
- errorClassOrCallback.prototype instanceof Error ||
824
- errorClassOrCallback.prototype === Error.prototype
825
- ) {
826
- // deno-lint-ignore no-explicit-any
827
- ErrorClass = errorClassOrCallback as new (...args: any[]) => E;
828
- msgIncludes = msgIncludesOrMsg;
829
- errorCallback = null;
830
- } else {
831
- errorCallback = errorClassOrCallback as (e: Error) => unknown;
832
- msg = msgIncludesOrMsg;
833
- }
834
- let doesThrow = false;
835
- try {
836
- await fn();
837
- } catch (error) {
838
- if (error instanceof Error === false) {
839
- throw new AssertionError("A non-Error object was thrown or rejected.");
840
- }
841
- assertIsError(
842
- error,
843
- ErrorClass,
844
- msgIncludes,
845
- msg,
846
- );
847
- if (typeof errorCallback == "function") {
848
- errorCallback(error);
849
- }
850
- doesThrow = true;
851
- }
852
- if (!doesThrow) {
853
- msg = `Expected function to throw${msg ? `: ${msg}` : "."}`;
854
- throw new AssertionError(msg);
855
- }
856
- }
857
-
858
- /** Use this to stub out methods that will throw when invoked. */
859
- export function unimplemented(msg?: string): never {
860
- throw new AssertionError(msg || "unimplemented");
861
- }
862
-
863
- /** Use this to assert unreachable code. */
864
- export function unreachable(): never {
865
- throw new AssertionError("unreachable");
866
- }