it("Scroll to the line number", async () => {
    await fc.assert(
      fc.asyncProperty(
        fc_text,
        fc.nat(),
        fc.array(fc.nat()),
        async (lines, lineNoInit, lineNoUpdates) => {
          let editor!: ShallowRef<Monaco.editor.IStandaloneCodeEditor | undefined>;
          const element = ref(document.createElement("div"));
          const source = ref(lines.join("\n"));
          const lineNo = ref(lineNoInit);

          await withAsyncSetup(async () => {
            const ready = useMonacoEditor({ element, source });
            ({ editor } = ready);
            useScroll(editor, lineNo);
            await ready;
          });

          const lineNoExpected = Math.min(lineNoInit, lines.length) || 1;
          const ranges = editor.value?.getVisibleRanges();
          expect(ranges).toBeDefined();
          expect(ranges?.length).toBe(1);
          expect(ranges?.[0].startLineNumber).toBeLessThanOrEqual(lineNoExpected);
          expect(ranges?.[0].endLineNumber).toBeGreaterThanOrEqual(lineNoExpected);

          for (const lineNoUpdate of lineNoUpdates) {
            lineNo.value = lineNoUpdate;
            await nextTick();
            const lineNoExpected = Math.min(lineNoUpdate, lines.length) || 1;
            const ranges = editor.value?.getVisibleRanges();
            expect(ranges).toBeDefined();
            expect(ranges?.length).toBe(1);
            expect(ranges?.[0].startLineNumber).toBeLessThanOrEqual(lineNoExpected);
            expect(ranges?.[0].endLineNumber).toBeGreaterThanOrEqual(lineNoExpected);
          }
        },
      ),
      { verbose: true, numRuns: 5 },
    );
  }, 10000)

Summary: Validates that the editor scrolls to a specified line number, ensuring it is within the visible range after each update.


unknown

it("Options of useMonacoEditor() are generated", () => {
    fc.assert(
      fc.property(fcUseMonacoEditorOptions(), (options) => {
        expect(options).toBeDefined();
        return true;
      }),
    );
  })

Summary: `useMonacoEditor` options are correctly generated as defined records with specified required keys.


it("returns identity for non-positive number", () => {
			expect(f(-1)("abc")).toBe("abc")

			fc.assert(
				fc.property(
					fc.string(),
					fc.integer({ max: 0 }),
					(x, n) => f(n)(x) === x,
				),
			)
		})

Summary: `f` function returns the input string unchanged when the number is non-positive.


it("returns empty on constTrue", () => {
			fc.assert(fc.property(fc.string(), x => f(constTrue)(x) === ""))
		})

Summary: Function `f` returns an empty string when applied to `constTrue` with any input string.


it("drops specified number of characters", () => {
			expect(f(2)("abc")).toBe("a")

			fc.assert(
				fc.property(
					fc.string(),
					fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER }),
					(x, n) => f(n)(x).length === max(N.Ord)(0, x.length - n),
				),
			)
		})

Summary: `f` should return a string reduced by the specified number of characters, or empty if the reduction exceeds the string's length.


it("returns first character of non-empty string", () => {
			fc.assert(
				fc.property(fc.string({ minLength: 1, maxLength: 100 }), x =>
					expect(f(x)).toEqual(O.some(x[0])),
				),
			)
		})

Summary: The function returns the first character of a non-empty string wrapped in `O.some`.


it("returns empty string for string with one character", () => {
			fc.assert(
				fc.property(fc.string({ minLength: 1, maxLength: 1 }), x =>
					expect(f(x)).toEqual(O.some("")),
				),
			)
		})

Summary: Function `f` returns `Some("")` for strings containing one character.


it("returns string one character smaller", () => {
			fc.assert(
				fc.property(fc.string({ minLength: 1, maxLength: 100 }), x =>
					pipe(
						f(x),
						O.exists(y => y.length === x.length - 1),
					),
				),
			)
		})

Summary: The function `f` should return a string with one fewer character than the input string of length between 1 and 100.


it("Property test", async () => {
    await fc.assert(
      fc.asyncProperty(
        fcUseMonacoEditorOptions(),
        fc.boolean(),
        async (options, early) => {
          let editor!: ReturnType<typeof useMonacoEditor>["editor"];
          let model!: ReturnType<typeof useMonacoEditor>["model"];
          let source!: ReturnType<typeof useMonacoEditor>["source"];
          let mode!: ReturnType<typeof useMonacoEditor>["mode"];
          let ready!: ReturnType<typeof useMonacoEditor>["ready"];
          const { wrapper } = await withAsyncSetup(async () => {
            ({ editor, model, source, mode, ready } = early
              ? useMonacoEditor(options)
              : await useMonacoEditor(options));
          });
          if (early) await ready;
          if (isRef(options.element) && options.element.value === undefined) {
            options.element.value = document.createElement("div");
          }
          await nextTick();
          expect(editor.value).toBeDefined();

          const expectedSource = unref(options.source) ?? "";
          expect(source.value).toBe(expectedSource);
          expect(model.value?.getValue()).toBe(expectedSource);

          const expectedMode = unref(options.mode) ?? "viewer";
          expect(mode.value).toBe(expectedMode);

          wrapper.unmount();
        },
      ),
    );
  })

Summary: `useMonacoEditor` initializes correctly with varying options, ensuring the `editor`, `source`, `model`, and `mode` values match expected defaults or provided settings.


it("returns None if index out of bounds", () => {
			expect(f(1)("a")).toEqual(O.none)

			fc.assert(
				fc.property(fc.string(), x => expect(f(x.length)(x)).toEqual(O.none)),
			)
		})

Summary: `f` returns `None` if the provided index is out of bounds for the given string.


it("returns character if in bounds", () => {
			expect(f(1)("abc")).toEqual(O.some("b"))

			fc.assert(
				fc.property(fc.string({ minLength: 1, maxLength: 100 }), x =>
					expect(f(0)(x)).toEqual(O.some(x[0])),
				),
			)
		})

Summary: The function `f` returns the character at the specified index if it is within the string's bounds.


it("returns empty string on constFalse", () => {
			fc.assert(fc.property(fc.string(), x => f(constFalse)(x) === ""))
		})

Summary: Applying `f` with `constFalse` should return an empty string for any input string `x`.


it("handles CE era strings", () => {
    fc.assert(
      fc.property(
        fc.date({
          min: new Date("0001-01-01 00:00:00"),
          max: new Date("9999-12-31 23:59:59"),
        }),
        fc.constantFrom(...TEST_FORMATS, ...ERA_TEST_FORMATS),
        (d, fmt) => {
          /**
           * This test is a bit of a hack. Basically, "1994" should give us
           * a start and end date that, formatted 'yyyy', will also be "1994".
           *
           * This ensures that July 1st formatted a certain way doesn't drift
           * into June 30th or something.
           */
          const formattedDate = format(d, fmt);
          const result = epochize(formattedDate)!;
          expect(result).toBeDefined();
          expect(format(result[0], fmt)).toBe(formattedDate);
          expect(format(result[1], fmt)).toBe(formattedDate);
        }
      ),
      { numRuns: 10000 }
    );
  })

Summary: Dates formatted in the CE era should, when processed and reformatted, remain consistent without drifting to incorrect dates.


it("handles BC era strings", () => {
    fc.assert(
      fc.property(
        fc.date({
          min: new Date("0000-12-31 23:59:59"),
          max: new Date("-9999-12-31 23:59:59"),
        }),
        fc.constantFrom(...ERA_TEST_FORMATS),
        (d, fmt) => {
          /**
           * The same as before, but with BC era dates and only formats that include era
           */
          const formattedDate = format(d, fmt);
          const result = epochize(formattedDate)!;
          expect(result).toBeDefined();
          expect(format(result[0], fmt)).toBe(formattedDate);
          expect(format(result[1], fmt)).toBe(formattedDate);
        }
      ),
      { numRuns: 10000 }
    );
  })

Summary: The function `epochize` correctly processes BC era date strings, and the formatted dates match the original input when processed and re-formatted.


it("first and last elements are the same as splits at index", () => {
			fc.assert(
				fc.property(fc.integer(), fc.string(), (index, str) => {
					const tuple = splitAt(index)(str)
					return (
						tuple[0] === S.slice(0, index)(str) &&
						tuple[1] === S.slice(index, Number.POSITIVE_INFINITY)(str)
					)
				}),
			)
		})

Summary: Splitting a string at a given index results in a tuple where the first element matches the substring from the start to the index, and the second element matches the substring from the index to the end.


it("removes prefix if present", () => {
			expect(f("foo")("foobar")).toBe("bar")

			fc.assert(
				fc.property(fc.string(), fc.string(), (x, y) => f(y)(y + x) === x),
			)
		})

Summary: The function `f` removes a specified prefix from a string if it is present.


it("removes suffix if present", () => {
			expect(f("bar")("foobar")).toBe("foo")

			fc.assert(
				fc.property(fc.string(), fc.string(), (x, y) => f(y)(x + y) === x),
			)
		})

Summary: If a string ends with a given suffix, the suffix is removed from the string.


it("cannot find anything in empty object", () => {
			fc.assert(fc.property(fc.string(), x => O.isNone(f({})(x))))
		})

Summary: Finding a value in an empty object should always return `None`.


it("has every unique transformed value as a key", () => {
			const g = fromNumber
			const h: (x: RR.ReadonlyRecord<string, number>) => ReadonlyArray<string> =
				flow(values, RA.uniq(N.Eq), RA.map(g))

			fc.assert(
				fc.property(fc.dictionary(fc.string(), fc.integer()), x =>
					pipe(x, f(g), RR.keys, ks =>
						pipe(
							h(x),
							RA.every(k => RA.elem(S.Eq)(k)(ks)),
						),
					),
				),
			)
		})

Summary: Every unique transformed value from a `ReadonlyRecord` should be present as a key after applying a function to the record's values.


it("joins", () => {
			expect(f([])).toBe("")
			expect(f(["x"])).toBe("x")
			expect(f(["x", "yz"])).toBe("x,yz")

			fc.assert(
				fc.property(fc.array(fc.string()), xs => {
					const countDelims = flow(
						split(""),
						A.filter(c => c === delim),
						A.size,
					)

					const countDelimsA = flow(A.map(countDelims), concatAll(N.MonoidSum))

					return (
						countDelims(f(xs)) ===
						countDelimsA(xs) + max(N.Ord)(0, A.size(xs) - 1)
					)
				}),
			)
		})

Summary: The test checks that the function `f`, which joins an array of strings, results in a delimiter count that matches the expected count based on the input strings and their sizes.


it("always returns a non-empty array", () => {
			fc.assert(
				fc.property(
					fc.array(fc.integer()),
					fc.integer(),
					(xs, y) => !!f(N.Eq)(y)(xs).length,
				),
			)
		})

Summary: The function `f` returns a non-empty array when applied to an array of integers and a single integer.


it("returns updated array wrapped in Some if index is okay", () => {
			expect(f(0)(["x"])([])).toEqual(O.some(["x"]))
			expect(g(["x"])).toEqual(O.some(["x", "a", "b"]))
			expect(g(["x", "y"])).toEqual(O.some(["x", "a", "b", "y"]))

			fc.assert(
				fc.property(
					fc.array(fc.anything(), {
						minLength: 1,
						maxLength: 5,
					}) as fc.Arbitrary<NonEmptyArray<unknown>>,
					fc.integer({ min: 0, max: 10 }),
					(xs, i) => O.isSome(f(i)(xs)(xs)) === i <= A.size(xs),
				),
			)

			fc.assert(
				fc.property(
					fc.array(fc.string(), { minLength: 1, maxLength: 20 }),
					xs =>
						expect(pipe(g(xs), O.map(A.size))).toEqual(O.some(A.size(xs) + 2)),
				),
			)
		})

Summary: The function `f` returns an updated array wrapped in `Some` when the index is within bounds, and the function `g` appends specific elements to a non-empty array, increasing its size by 2, both verified through property-based testing.


it("should respect list({ limit }) with random keys/values (fast-check)", async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.array(fc.tuple(fc.string({ minLength: 1, maxLength: 32 }), fc.string({ minLength: 1, maxLength: 32 })), { minLength: 3, maxLength: 10 }),
        fc.integer({ min: 1, max: 10 }),
        async (entries, limit) => {
          const kv = mockKVNamespace();
          for (const [key, value] of entries) await kv.put(key, value);
          const { keys } = await kv.list({ limit });
          expect(keys.length).toBeLessThanOrEqual(limit);
          for (const { name } of keys) {
            expect(entries.map(([k]) => k)).toContain(name);
          }
        }
      ),
      { numRuns: 20 }
    );
  })

Summary: Checking that the `list` method respects a specified limit on the number of entries returned and that all returned keys exist in the original set of entries.


it("returns empty array for non-positive input number", () => {
			fc.assert(
				fc.property(
					fc.integer({ max: 0 }),
					fc.array(fc.anything()),
					(n, xs) => !f(n)(xs).length,
				),
			)
		})

Summary: The function `f` should return an empty array when the input number is non-positive.


it("should respect list({ prefix }) with random keys/values (fast-check)", async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.array(fc.tuple(fc.string({ minLength: 1, maxLength: 16 }), fc.string({ minLength: 1, maxLength: 16 })), { minLength: 3, maxLength: 10 }),
        fc.string({ minLength: 1, maxLength: 4 }),
        async (entries, prefix) => {
          const kv = mockKVNamespace();
          for (const [key, value] of entries) await kv.put(key, value);
          const { keys } = await kv.list({ prefix });
          // Build allKeys from the final state of the KV store
          const allKeys = (await kv.list({})).keys.map(k => k.name);
          const allWhitespace = allKeys.length > 0 && allKeys.every(k => /^\s+$/.test(k));
          // If all keys are whitespace and prefix contains any non-whitespace character, result must be empty
          if (allWhitespace && /[^\s]/.test(prefix)) {
            expect(keys.map(k => k.name)).toEqual([]);
            return;
          }
          const expected = allKeys.filter(k => k.startsWith(prefix));
          expect(keys.map(k => k.name).sort()).toEqual(expected.sort());
          // All returned keys must start with the prefix
          for (const { name } of keys) {
            expect(name.startsWith(prefix)).toBe(true);
          }
        }
      ),
      { numRuns: 20 }
    );
  })

Summary: `mockKVNamespace.list` correctly filters and returns keys starting with a specified prefix from a randomized set of key-value pairs.


it("should store and retrieve metadata with values (fast-check)", async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.string({ minLength: 1, maxLength: 32 }),
        fc.string({ minLength: 1, maxLength: 32 }),
        fc.anything(),
        async (key, value, meta) => {
          const kv = mockKVNamespace();
          await kv.put(key, value, { metadata: meta });
          let expected;
          try {
            expected = meta === undefined ? null : JSON.parse(JSON.stringify(meta));
          } catch {
            expected = null;
          }
          const { value: v, metadata: m } = await kv.getWithMetadata(key) ?? {};
          expect(v).toBe(value);
          expect(m).toEqual(expected);
        }
      ),
      { numRuns: 20 }
    );
  })

Summary: Storing and retrieving metadata with values in a key-value store should return the exact stored value and correctly handle the associated metadata, even if it's `undefined` or non-JSON serializable.


it("moves source to target", () => {
			expect(f(0)(1)(["a", "b", "c"])).toEqual(O.some(["b", "a", "c"]))
			expect(f(1)(0)(["a", "b", "c"])).toEqual(O.some(["b", "a", "c"]))

			const n = 10

			fc.assert(
				fc.property(
					fc.array(fc.anything(), { minLength: n, maxLength: n }),
					fc.integer({ min: 0, max: n - 1 }),
					fc.integer({ min: 0, max: n - 1 }),
					(xs, i, j) => O.isSome(f(i)(j)(xs)),
				),
			)
		})

Summary: The function `f` should move an element from a source index to a target index in an array, resulting in a non-empty optional type.


it("should update metadata for a key (fast-check)", async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.string({ minLength: 1, maxLength: 32 }),
        fc.string({ minLength: 1, maxLength: 32 }),
        fc.anything(),
        fc.anything(),
        async (key, value, meta1, meta2) => {
          const kv = mockKVNamespace();
          await kv.put(key, value, { metadata: meta1 });
          let expected;
          try {
            expected = meta2 === undefined ? null : JSON.parse(JSON.stringify(meta2));
          } catch {
            expected = null;
          }
          await kv.put(key, value, { metadata: meta2 });
          const { metadata: m } = await kv.getWithMetadata(key) ?? {};
          expect(m).toEqual(expected);
        }
      ),
      { numRuns: 20 }
    );
  })

Summary: Updating the metadata for a key in a `mockKVNamespace` should reflect the latest provided metadata, with changes being accurately retrieved.


it("sibling indices are interchangeable", () => {
			const n = 10

			fc.assert(
				fc.property(
					fc.array(fc.anything(), { minLength: n, maxLength: n }),
					fc.integer({ min: 0, max: n - 2 }),
					(xs, i) => expect(f(i)(i + 1)(xs)).toEqual(f(i + 1)(i)(xs)),
				),
			)
		})

Summary: Two adjacent indices in an array should yield the same result when swapped using function `f`.


it("should round-trip deep/nested JSON objects (fast-check)", async () => {
    await fc.assert(
      fc.asyncProperty(exoticKeyArb, deepJsonArb, async (key, obj) => {
        // Filter out unsafe/prototype keys
        if (["toString","hasOwnProperty","valueOf","constructor","__proto__","isPrototypeOf","propertyIsEnumerable","toLocaleString"].includes(key)) return;
        // Filter out undefined, which cannot be stringified and stored
        if (typeof obj === "undefined") return;
        // Filter out values that cannot be round-tripped by JSON
        function isJsonSafe(val: unknown): boolean {
          if (typeof val === "bigint" || typeof val === "function" || typeof val === "symbol") return false;
          if (typeof val === "number" && (!Number.isFinite(val) || Number.isNaN(val))) return false;
          if (Array.isArray(val)) return val.every(isJsonSafe);
          if (val && typeof val === "object") return Object.values(val).every(isJsonSafe);
          return true;
        }
        if (!isJsonSafe(obj)) return;
        const kv = mockKVNamespace();
        await kv.put(key, JSON.stringify(obj));
        const result = await kv.get(key, { type: "json" });
        // Use deepNullishEqual to treat null/undefined as equivalent everywhere
        expect(deepNullishEqual(result, obj)).toBe(true);
      }),
      { numRuns: 30 }
    );
  })

Summary: Round-tripping deep or nested JSON objects through `mockKVNamespace` retains nullish equality, ensuring the retrieved object is equivalent to the original, with special treatment for `null` and `undefined`.


it("should handle invalid JSON parsing gracefully (fast-check)", async () => {
    await fc.assert(
      fc.asyncProperty(exoticKeyArb, async (key) => {
        if (["toString","hasOwnProperty","valueOf","constructor","__proto__","isPrototypeOf","propertyIsEnumerable","toLocaleString"].includes(key)) return;
        const kv = mockKVNamespace();
        await kv.put(key, "not-valid-json");
        const result = await kv.get(key, { type: "json" });
        expect(result).toBeNull();
      }),
      { numRuns: 30 }
    );
  })

Summary: Mock KV store returns `null` when attempting to parse invalid JSON for specified exotic keys.


it("should store and retrieve values via put/get (fast-check, step 5)", async () => {
    await fc.assert(
      fc.asyncProperty(safeUnicodeKeyArb, safeUnicodeValueArb, async (key, value) => {
        const kv = mockKVNamespace();
        await kv.put(key, value);
        expect(await kv.get(key)).toBe(value);
      }), { numRuns: 20 }
    );
  })

Summary: Values stored using `put` should be accurately retrieved using `get` with consistent key-value pairs.


it("all numbers are above zero", () => {
			fc.assert(
				fc.property(
					fc.array(fc.string()),
					flow(
						f(identity),
						values,
						A.every(n => n > 0),
					),
				),
			)
		})

Summary: All transformed values from a string array must be greater than zero.


it("constTrue returns empty array", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(constTrue)(xs)).toEqual([]),
				),
			)
		})

Summary: `constTrue` applied to any array results in an empty array.


it("constFalse returns original array", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(constFalse)(xs)).toEqual(xs),
				),
			)
		})

Summary: `constFalse` applied to an array returns the original array unchanged.


it("should handle bulk put/get/delete (fast-check, step 5)", async () => {
    await fc.assert(
      fc.asyncProperty(safeArrayEntriesArb, async (entries) => {
        // Filter to unique keys only (last value wins, to match put semantics)
        const uniqueEntries = Array.from(new Map(entries.map(([k, v]) => [k, v])).entries());
        const kv = mockKVNamespace();
        for (const [key, value] of uniqueEntries) {
          await kv.put(key, value);
        }
        for (const [key, value] of uniqueEntries) {
          expect(await kv.get(key)).toBe(value);
        }
        for (const [key] of uniqueEntries) {
          await kv.delete(key);
          expect(await kv.get(key)).toBeNull();
        }
      }), { numRuns: 20 }
    );
  })

Summary: `mockKVNamespace` should correctly handle bulk operations of put, get, and delete for unique keys, ensuring that key-value pairs are accurately stored, retrieved, and removed.


it("calculates the median", () => {
			expect(f([2, 9, 7])).toBe(7)
			expect(f([7, 2, 10, 9])).toBe(8)

			fc.assert(
				fc.property(
					fc.integer({ min: 1, max: 50 }),
					fc.integer(),
					(x, y) => f(A.replicate(x, y) as ReadonlyNonEmptyArray<number>) === y,
				),
			)
		})

Summary: The function `f` should return `y` as the median when `x` copies of `y` are provided in a `ReadonlyNonEmptyArray`.


it("maintains same flattened size", () => {
			fc.assert(
				fc.property(
					fc.array(fc.array(fc.anything())),
					xs => A.size(A.flatten(xs)) === A.size(A.flatten(f(xs))),
				),
			)
		})

Summary: Flattening a nested array should result in the same size before and after applying function `f` if the contents are unchanged.


it("should return null when deleting unknown keys (fast-check, step 5)", async () => {
    await fc.assert(
      fc.asyncProperty(safeUnicodeKeyArb, async (key) => {
        const kv = mockKVNamespace();
        await kv.delete(key); // Should not throw
        expect(await kv.get(key)).toBeNull();
      }), { numRuns: 20 }
    );
  })

Summary: Deleting unknown keys should return null.


it("should round-trip JSON objects via put/get with type: 'json' (fast-check, step 5)", async () => {
    await fc.assert(
      fc.asyncProperty(safeUnicodeKeyArb, safeJsonArb, async (key, obj) => {
        if (unsafeKeys.includes(key)) return;
        const kv = mockKVNamespace();
        const value = JSON.stringify(obj);
        await kv.put(key, value);
        expect(await kv.get(key, { type: 'json' })).toEqual(obj);
      }), { numRuns: 20 }
    );
  })

Summary: Putting and then getting a JSON object with `type: 'json'` should preserve the object's integrity.


it("should handle edge-case unicode keys and values (fast-check, step 5)", async () => {
    await fc.assert(
      fc.asyncProperty(safeUnicodeKeyArb, safeUnicodeValueArb, async (key, value) => {
        if (unsafeKeys.includes(key) || key.startsWith("_") || key.endsWith("_") || key.includes("__")) return;
        const kv = mockKVNamespace();
        await kv.put(key, value);
        expect(await kv.get(key)).toBe(value);
      }), { numRuns: 20 }
    );
  })

Summary: `mockKVNamespace` handles putting and getting values for edge-case Unicode keys, provided they do not match disallowed patterns.


it("should respect expirationTtl (fast-check, step 5)", async () => {
    await fc.assert(
      fc.asyncProperty(safeUnicodeKeyArb, safeUnicodeValueArb, safeTtlArb, async (key, value, ttl) => {
        const kv = mockKVNamespace();
        await kv.put(key, value, { expirationTtl: ttl });
        expect(await kv.get(key)).toBe(value);
        // Simulate expiration using the test-only method
        (kv as any).expireKeyNow(key);
        // If the key is present after expiration, it should be null; if not present, that's also valid
        const result = await kv.get(key);
        if (!(result === null || result === undefined)) {
          // Debug output for whitespace key/value edge case
          throw new Error(`Expected expired key to be null/undefined, but got value for key: '${key}' (length: ${key.length}), value: '${value}' (length: ${value.length}), ttl: ${ttl}, result: ${result}`);
        }
        expect(result === null || result === undefined).toBe(true);
      }), { numRuns: 20 }
    );
  })

Summary: The test ensures that after using `expirationTtl` to store a key-value pair in `mockKVNamespace`, the value becomes null or undefined when accessed after expiration is simulated.


it("should respect list limits (fast-check, step 5)", async () => {
    await fc.assert(
      fc.asyncProperty(
        safeArrayEntriesArb,
        safeLimitArb,
        async (entries, limit) => {
          const kv = mockKVNamespace();
          for (const [key, value] of entries) {
            await kv.put(key, value);
          }
          const listed = await kv.list({ limit });
          expect(listed.keys.length).toBeLessThanOrEqual(limit);
          for (const { name } of listed.keys) {
            expect(entries.map(([k]) => k)).toContain(name);
          }
        }
      ), { numRuns: 20 }
    );
  })

Summary: The `list` function should return a number of keys that is less than or equal to the specified limit and all returned keys must exist in the input entries.


it("equal length inputs is equivalent to normal zip mapped to These", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs => {
					const ys = A.reverse(xs)
					expect(f(xs)(ys)).toEqual(
						pipe(
							A.zip(xs)(ys),
							A.map(([x, y]) => T.both(x, y)),
						),
					)
				}),
			)
		})

Summary: Equal length inputs result in the function `f(xs)(ys)` being equivalent to zipping and mapping `xs` and `ys` into `These` pairs when `ys` is the reverse of `xs`.


it("output length is equal to largest input length", () => {
			fc.assert(
				fc.property(
					fc.array(fc.anything()),
					fc.array(fc.anything()),
					(xs, ys) => A.size(f(xs)(ys)) === max(N.Ord)(A.size(xs), A.size(ys)),
				),
			)
		})

Summary: The function `f` applied to two arrays should produce an output whose length equals the length of the larger input array.


it("should parse stored JSON when type is 'json'", async () => {
    await fc.assert(
      fc.asyncProperty(snakeCaseKeyArb, jsonValueArb, async (key, obj) => {
        const kv = mockKVNamespace();
        await kv.put(key, JSON.stringify(obj));
        const result = await kv.get(key, { type: "json" });
        expect(result).toEqual(obj);
      })
    );
  })

Summary: Stored JSON should be correctly parsed and retrieved as an object when the type is specified as 'json'.


it("returns These Left for only Either Lefts", () => {
			fc.assert(
				fc.property(fc.array(fc.anything(), { minLength: 1 }), xs => {
					const ys = pipe(
						xs as ReadonlyArray<unknown> as ReadonlyNonEmptyArray<unknown>,
						RNEA.map(E.left),
					)

					expect(f(ys)).toEqual(T.left(xs))
				}),
			)
		})

Summary: For an array of `Either` left values, the function should return `These` left containing the same array.


it("should allow overwriting a key multiple times (fast-check)", async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.string({ minLength: 1, maxLength: 32 }),
        fc.array(fc.string({ minLength: 1, maxLength: 32 }), { minLength: 2, maxLength: 6 }),
        async (key, values) => {
          const kv = mockKVNamespace();
          for (const value of values) await kv.put(key, value);
          expect(await kv.get(key)).toBe(values[values.length - 1]);
        }
      ),
      { numRuns: 20 }
    );
  })

Summary: Overwriting a key multiple times in `mockKVNamespace` should result in the key storing the last assigned value.


it("should support unicode and special characters in keys/values (fast-check)", async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.string({ minLength: 1, maxLength: 16 }),
        fc.string({ minLength: 1, maxLength: 16 }),
        async (key, value) => {
          const kv = mockKVNamespace();
          await kv.put(key, value);
          expect(await kv.get(key)).toBe(value);
        }
      ),
      { numRuns: 20 }
    );
  })

Summary: Verifies that the mockKVNamespace can correctly store and retrieve keys and values containing Unicode and special characters.


it("always returns a non-empty output", () => {
			fc.assert(
				fc.property(fc.array(fc.boolean(), { minLength: 1 }), xs => {
					const ys: ReadonlyNonEmptyArray<E.Either<boolean, boolean>> = pipe(
						xs as ReadonlyArray<unknown> as ReadonlyNonEmptyArray<boolean>,
						RNEA.map(b => (b ? E.right(b) : E.left(b))),
					)

					const zs: ReadonlyNonEmptyArray<boolean> = pipe(
						ys,
						f,
						T.match(identity, identity, (ls, rs) => RNEA.concat(ls)(rs)),
					)

					expect(A.size(zs)).toBeGreaterThan(0)
					expect(A.size(zs)).toBe(A.size(xs))
				}),
			)
		})

Summary: The output array, processed through transformations involving `ReadonlyNonEmptyArray` and `Either`, should always be non-empty and maintain the same size as the input array.


it("should not return expired keys in list (fast-check)", async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.string({ minLength: 1, maxLength: 16 }),
        fc.string({ minLength: 1, maxLength: 16 }),
        async (keepKey, expireKey) => {
          if (keepKey === expireKey) return;
          const kv = mockKVNamespace();
          await kv.put(keepKey, "keep");
          await kv.put(expireKey, "expire", { expiration: Math.floor(Date.now() / 1000) - 10 });
          const { keys } = await kv.list();
          expect(keys.map(k => k.name)).toContain(keepKey);
          expect(keys.map(k => k.name)).not.toContain(expireKey);
        }
      ),
      { numRuns: 20 }
    );
  })

Summary: Expired keys should not be included in the list of keys returned by `mockKVNamespace`.


test('decode optional string', () => {
  fc.assert(
    fc.property(fc.oneof(fc.string(), fc.constant(undefined)), (s) => {
      expect(optional(string)(s)).toBe(s);
    }),
  );
})

Summary: The `optional(string)` function should return the input value, whether it is a string or undefined.


test('decode number', () => {
  fc.assert(
    fc.property(fc.float(), (n) => {
      expect(number(n)).toBe(n);
    }),
  );
})

Summary: The `number` function should return the input float as is, maintaining equality.


test('decode string tuple', () => {
  fc.assert(
    fc.property(fc.string(), fc.string(), (s1, s2) => {
      expect(tuple(string, string)([s1, s2])).toEqual([s1, s2]);
    }),
  );
})

Summary: The `tuple` function correctly decodes an array of strings into a tuple of strings.


it("extracts expected TaskEither left from a ReaderTaskEither", async () => {
			type Env = { dependency: string }
			const env: Env = { dependency: "dependency" }
			await fc.assert(
				fc.asyncProperty(fc.integer(), async _ => {
					const rte: RTE.ReaderTaskEither<Env, number, never> = pipe(
						E.left(_),
						RTE.fromEither,
					)
					const extractedLeft = pipe(rte, runReaderTaskEither(env))()
					await expect(extractedLeft).resolves.toStrictEqual(E.left(_))
				}),
			)
		})

Summary: Extracting the expected left value from a `ReaderTaskEither` using a given environment results in the correct `TaskEither` left.


test('decode string,number tuple', () => {
  fc.assert(
    fc.property(fc.string(), fc.float(), (s, n) => {
      expect(tuple(string, number)([s, n])).toEqual([s, n]);
    }),
  );
})

Summary: The `tuple` function correctly decodes a tuple containing a string and a number, returning the original values.


it('property: flatten equals original and chunk lengths are valid', () => {
    fc.assert(
      fc.property(
        fc.array(fc.integer()),
        fc.integer({ min: 1, max: 20 }),
        (arr, n) => {
          const out = collections.chunkArray(arr, n);

          expect(out.flat()).toEqual(arr);
          out.forEach((chunk) => expect(chunk.length).toBeGreaterThan(0));
          out.slice(0, -1).forEach((chunk) => expect(chunk.length).toBe(n));

          if (out.length > 0) {
            expect(out[out.length - 1].length).toBeLessThanOrEqual(n);
          }
        }
      )
    );
  })

Summary: Flattening the output of `chunkArray` should equal the original array, each chunk should have a positive length, all chunks except possibly the last should have length `n`, and the last chunk should have a length less than or equal to `n`.


it('rejects any float string', () => {
    fc.assert(
      fc.property(
        fc
          .double({ noNaN: true, noDefaultInfinity: true })
          .filter((d) => !Number.isInteger(d)),
        (d) => {
          expect(numbers.parseIntOrNull(d.toString())).toBeNull();
        }
      )
    );
  })

Summary: `numbers.parseIntOrNull` should return `null` for any non-integer float strings.


it('should capitalize a word, even if it\'s already capitalized', () =>
      fc.assert(
        fc.property(fc.string(), (str) => {
          const capitalized = capitalize(str);

          return capitalized[0] === capitalized[0]?.toUpperCase();
        }),
      ))

Summary: The `capitalize` function should ensure the first character of a string is uppercase, regardless of its initial state.


it("returns constant empty/zero on false", () => {
			fc.assert(
				fc.property(fc.anything(), x =>
					expect(f(false)(constant(x))).toEqual(O.none),
				),
			)
		})


it("returns identity element on true condition", () => {
			fc.assert(
				fc.property(arbOption(fc.string()), x =>
					expect(f(true)(constant(x))).toEqual(O.none),
				),
			)
		})

Summary: The function `f` returns `O.none` when called with `true` and any `Option` value wrapped in a constant function.


it("returns identity on argument on false condition", () => {
			fc.assert(
				fc.property(arbOption(fc.string()), x =>
					expect(f(false)(constant(x))).toEqual(x),
				),
			)
		})

Summary: `f(false)(constant(x))` returns the input `x` unchanged when the condition is false.


it("returns identity element on false condition", () => {
			fc.assert(
				fc.property(arbOption(fc.string()), x =>
					expect(f(false)(constant(x))).toEqual(O.none),
				),
			)
		})

Summary: The property asserts that when a false condition is provided to the function `f`, applying it with any `Option` value results in `O.none`.


it("returns lifted input on true", () => {
			fc.assert(
				fc.property(fc.anything(), x =>
					expect(f(true)(constant(x))).toEqual(O.some(x)),
				),
			)
		})


it("returns constant empty on empty input", () => {
			fc.assert(
				fc.property(fc.anything(), x =>
					expect(f([])(constant(x))).toEqual(O.none),
				),
			)
		})


it("returns constant empty on all-empty input", () => {
			fc.assert(
				fc.property(fc.anything(), x =>
					expect(
						f([constant(O.none), constant(O.none), constant(O.none)])(
							constant(x),
						),
					).toEqual(O.none),
				),
			)
		})


it("returns left-most non-empty value", () => {
			fc.assert(
				fc.property(fc.anything(), fc.anything(), fc.anything(), (x, y, z) =>
					expect(
						f([constant(O.none), constant(O.some(x)), constant(O.some(y))])(
							constant(z),
						),
					).toEqual(O.some(x)),
				),
			)
		})


it('should correctly test if the value is between the two tuple elements', () => {
  fc.assert(
    fc.property(fc.tuple(fc.integer(), fc.integer()), fc.integer(), (a, b) => {
      const sorted = [...a].sort();
      return isBetween(a)(b) === (b >= sorted[0] && b <= sorted[1]);
    }),
    {
      verbose: 2,
      // manual cases
      examples: [
        [[50, 198], 100],
        [[100, 89], 50],
        [[50, 60], 50],
      ],
    },
  );
})

Summary: Check that the `isBetween` function returns true if a value is between the two elements of a sorted tuple and false otherwise.


it('should correctly test value is in array', () => {
  fc.assert(
    fc.property(
      fc.array(fc.integer(), { maxLength: 1000 }),
      fc.integer(),
      (a, b) => {
        return isIn(a)(b) === a.includes(b);
      },
    ),
    {
      verbose: 2,
      // manual cases
      examples: [
        [[50, 75, 100], 100],
        [[100, 200, 300], 50],
      ],
    },
  );
})

Summary: `isIn` correctly determines if a value is present in an array by matching the result of `Array.prototype.includes`.


it('should correctly determine if the regex is not like the string', () => {
  fc.assert(
    fc.property(
      fc.stringMatching(STRING_GEN),
      fc.stringMatching(TESTER_GEN),
      (a, b) => {
        return doesNotStartWith(a)(b) === !a.startsWith(b);
      },
    ),
    {
      verbose: 2,
      // manual cases
      examples: [
        ['b7a70c6346b5', 'b7a7'],
        ['471aead1ae80', 'b7a7'],
      ],
    },
  );
})

Summary: The function `doesNotStartWith` should return true if a string `a` does not start with string `b`, matching the negation of `a.startsWith(b)`.


it("passes for any non-Infinity number", () => {
			fc.assert(
				fc.property(
					fc.integer({
						min: Number.MIN_SAFE_INTEGER,
						max: Number.MAX_SAFE_INTEGER,
					}),
					f,
				),
			)
		})

Summary: The test asserts that the function `f` passes for any integer within the range of safe JavaScript integers, excluding Infinity.


it("returns true for any number above zero", () => {
			expect(f(0.000001)).toBe(true)
			expect(f(42)).toBe(true)
			expect(f(Number.POSITIVE_INFINITY)).toBe(true)

			fc.assert(fc.property(fc.integer({ min: 1 }), f))
		})

Summary: Function `f` returns true for any number greater than zero.


it("returns false for any number below zero", () => {
			expect(f(-0.000001)).toBe(false)
			expect(f(-42)).toBe(false)
			expect(f(Number.NEGATIVE_INFINITY)).toBe(false)

			fc.assert(fc.property(fc.integer({ max: -1 }), Pred.not(f)))
		})

Summary: The function `f` returns false for any negative number, including negative infinity and values below zero.


it('should correctly determine if the regex is not like the string', () => {
  fc.assert(
    fc.property(
      fc.oneof(fc.stringMatching(TESTER_GEN), fc.stringMatching(ALTERNATE_GEN)),
      fc.stringMatching(STRING_GEN),
      (a, b) => {
        return isNotLike(a)(b) === !new RegExp(a).test(b);
      },
    ),
    { verbose: 2 },
  );
})

Summary: Determines if `isNotLike` correctly identifies when a regex does not match a given string, consistent with the negation of `RegExp.test`.


it("returns false for any number above zero", () => {
			expect(f(0.000001)).toBe(false)
			expect(f(42)).toBe(false)
			expect(f(Number.POSITIVE_INFINITY)).toBe(false)

			fc.assert(fc.property(fc.integer({ min: 1 }), Pred.not(f)))
		})


it("returns true for any number below zero", () => {
			expect(f(-0.000001)).toBe(true)
			expect(f(-42)).toBe(true)
			expect(f(Number.NEGATIVE_INFINITY)).toBe(true)

			fc.assert(fc.property(fc.integer({ max: -1 }), f))
		})


it('should correctly test value is not in array', () => {
  fc.assert(
    fc.property(
      fc.array(fc.integer(), { maxLength: 1000 }),
      fc.integer(),
      (a, b) => {
        return isNotIn(a)(b) === !a.includes(b);
      },
    ),
    {
      verbose: 2,
      // manual cases
      examples: [
        [[50, 75, 100], 100],
        [[100, 200, 300], 50],
      ],
    },
  );
})

Summary: The `isNotIn` function should return true if and only if the integer is not present in the array.


it('should correctly test for lesser or equal values', () => {
  fc.assert(
    fc.property(fc.integer(), fc.integer(), (a, b) => {
      return isLesserEqual(a)(b) === b <= a;
    }),
    {
      verbose: 2,
      // manual cases
      examples: [
        [50, 100],
        [100, 50],
        [50, 50],
      ],
    },
  );
})

Summary: `isLesserEqual` should return true if the second integer is less than or equal to the first.


Summary: Function `f` returns false for any number greater than zero, including integers starting from one.


Summary: The function `f` should return true for any number less than zero.


it('should correctly test for lesser than values', () => {
  fc.assert(
    fc.property(fc.integer(), fc.integer(), (a, b) => {
      return isLesser(a)(b) === b < a;
    }),
    {
      verbose: 2,
      // manual cases
      examples: [
        [50, 100],
        [100, 50],
      ],
    },
  );
})

Summary: `isLesser` function checks if a value is less than another, consistent with the behavior of `<` operator.


it('should correctly test for equality', () => {
  fc.assert(
    fc.property(fc.integer(), fc.integer(), (a, b) => {
      return isEqual(a)(b) === (a === b);
    }),
    {
      verbose: 2,
      // manual cases
      examples: [
        [50, 50],
        [50, 100],
      ],
    },
  );
})

Summary: `isEqual` returns true if two integers are equal and false otherwise, matching the behavior of the `===` operator.


it('should correctly test for greater or equal values', () => {
  fc.assert(
    fc.property(fc.integer(), fc.integer(), (a, b) => {
      return isGreaterEqual(a)(b) === b >= a;
    }),
    {
      verbose: 2,
      // manual cases
      examples: [
        [50, 100],
        [100, 50],
        [50, 50],
      ],
    },
  );
})

Summary: The `isGreaterEqual` function should return true if the second integer is greater than or equal to the first, matching the result of `b >= a`.


it("works for positive integers", () => {
			expect(f(1)).toEqual([1])
			expect(f(123)).toEqual([1, 2, 3])
			expect(f(101)).toEqual([1, 0, 1])

			fc.assert(
				fc.property(fc.integer({ min: 1 }), n =>
					expect(f(n)).toHaveLength(String(n).length),
				),
			)
		})

Summary: Function `f` produces an array with a length corresponding to the number of digits in a positive integer.


it("strips - from negative numbers", () => {
			expect(f(-0)).toEqual([0])
			expect(f(-123)).toEqual([1, 2, 3])

			fc.assert(
				fc.property(fc.integer({ max: 0 }), n =>
					expect(f(n).length).toBeGreaterThan(0),
				),
			)
		})

Summary: The function should transform negative integers into arrays of their absolute digit values.


it("strips . from floats", () => {
			expect(f(1.2)).toEqual([1, 2])

			fc.assert(
				fc.property(fc.float({ noDefaultInfinity: true, noNaN: true }), n =>
					expect(f(n).length).toBeGreaterThan(0),
				),
			)
		})

Summary: Function `f` converts a float into an array of its digits, excluding the decimal point, and ensures the result is non-empty.


it("is equivalent to lifted Str.fromNumber", () => {
			fc.assert(
				fc.property(
					fc.integer(),
					n => Str.fromNumber(n) === unNonEmptyString(f(n)),
				),
			)
		})

Summary: `unNonEmptyString` applied to `f(n)` should produce the same result as `Str.fromNumber(n)`.


it('should correctly determine if the regex is not like the string', () => {
  fc.assert(
    fc.property(
      fc.stringMatching(STRING_GEN),
      fc.stringMatching(TESTER_GEN),
      (a, b) => {
        return doesStartWith(a)(b) === a.startsWith(b);
      },
    ),
    {
      verbose: 2,
      // manual cases
      examples: [
        ['b7a70c6346b5', 'b7a7'],
        ['471aead1ae80', 'b7a7'],
      ],
    },
  );
})

Summary: Validates that `doesStartWith` produces the same results as `String.prototype.startsWith` for strings generated by defined patterns.


it('should be reflexive', () => {
    fc.assert(
      fc.property(fc.clone(fc.anything(anythingSettings), 2), ([a, b]) => {
        // Given: a and b identical values
        expect(a).toStrictEqual(b);
      }),
      assertSettings,
    );
  })

Summary: `expect(a).toStrictEqual(b)` should hold true for identical values `a` and `b`.


it('should be symmetric', () => {
    fc.assert(
      fc.property(
        fc.anything(anythingSettings),
        fc.anything(anythingSettings),
        (a, b) => {
          // Given:  a and b values
          // Assert: We expect `expect(a).toStrictEqual(b)`
          //         to be equivalent to `expect(b).toStrictEqual(a)`
          expect(safeExpectStrictEqual(a, b)).toBe(safeExpectStrictEqual(b, a));
        },
      ),
      assertSettings,
    );
  })

Summary: Symmetry in `toStrictEqual` expectations should ensure that `expect(a).toStrictEqual(b)` is equivalent to `expect(b).toStrictEqual(a)` for any given values `a` and `b`.


it("is equivalent to lifted Str.toUpperCase", () => {
			fc.assert(
				fc.property(
					arb,
					x => _toUpperCase(unNonEmptyString(x)) === unNonEmptyString(f(x)),
				),
			)
		})

Summary: `_toUpperCase` applied to a non-empty string should equal the result of `f` applied to the same string after extracting it with `unNonEmptyString`.


it("maintains newtype contract", () => {
			fc.assert(fc.property(arb, flow(f, isValid)))
		})

Summary: A transformed arbitrary input retains the validity of the newtype contract when passed through a function.


it("is equivalent to lifted infallible Str.head", () => {
			fc.assert(
				fc.property(
					arb,
					x =>
						unsafeUnwrap(Str.head(unNonEmptyString(x))) ===
						unNonEmptyString(f(x)),
				),
			)
		})

Summary: `unsafeUnwrap(Str.head(unNonEmptyString(x)))` should be equal to `unNonEmptyString(f(x))`.


Summary: The function ensures that applying `flow(f, isValid)` to generated values with `arb` maintains the newtype contract.


it('should be equivalent to Node deepStrictEqual', () => {
    fc.assert(
      fc.property(
        fc.anything(anythingSettings),
        fc.anything(anythingSettings),
        (a, b) => {
          expect(safeExpectStrictEqual(a, b)).toBe(
            safeAssertDeepStrictEqual(a, b),
          );
        },
      ),
      assertSettings,
    );
  })

Summary: The property validates that `safeExpectStrictEqual` produces the same result as `safeAssertDeepStrictEqual` for two arbitrary inputs.


it('should always find the value when inside the array', () => {
    fc.assert(
      fc.property(
        fc.array(fc.anything(anythingSettings)),
        fc.array(fc.anything(anythingSettings)),
        fc.anything(anythingSettings),
        (startValues, endValues, v) => {
          // Given: startValues, endValues arrays and v any value
          expect([...startValues, v, ...endValues]).toContainEqual(v);
        },
      ),
      assertSettings,
    );
  })

Summary: The test verifies that an array containing a specific value will always have that value when checked with `toContainEqual`.


it('should be reflexive', () => {
    fc.assert(
      fc.property(fc.clone(fc.anything(anythingSettings), 2), ([a, b]) => {
        // Given: a and b identical values
        expect(a).toEqual(b);
      }),
      assertSettings,
    );
  })

Summary: The `toEqual` matcher verifies that identical values are considered equal.


it('should be symmetric', () => {
    const safeExpectEqual = (a: unknown, b: unknown) => {
      try {
        expect(a).toEqual(b);
        return true;
      } catch {
        return false;
      }
    };
    fc.assert(
      fc.property(
        fc.anything(anythingSettings),
        fc.anything(anythingSettings),
        (a, b) => {
          // Given:  a and b values
          // Assert: We expect `expect(a).toEqual(b)`
          //         to be equivalent to `expect(b).toEqual(a)`
          expect(safeExpectEqual(a, b)).toBe(safeExpectEqual(b, a));
        },
      ),
      {
        ...assertSettings,
        examples: [
          [0, 5e-324], // Issue #7941
          // [
          //   new Set([false, true]),
          //   new Set([new Boolean(true), new Boolean(true)]),
          // ], // Issue #7975
        ],
      },
    );
  })

Summary: The test ensures that the `toEqual` matcher is symmetric, meaning `expect(a).toEqual(b)` should produce the same result as `expect(b).toEqual(a)`.


it("are reversible", () => {
			fc.assert(
				fc.property(
					fc.integer(),
					n => unpack(pack<Num>(unpack(pack<Num>(n)))) === n,
				),
			)
		})

Summary: Packing and then unpacking an integer of type `Num` should return the original integer.


it("returns identity on argument on false condition", () => {
			fc.assert(fc.property(fc.string(), x => f(false)(constant(x)) === x))
		})

Summary: The function `f(false)(constant(x))` should return `x` when the condition is false.


it("returns identity element on false condition", () => {
			fc.assert(
				fc.property(fc.string(), x => f(false)(constant(x)) === S.Monoid.empty),
			)
		})

Summary: The function `f` returns the Monoid's identity element when given a false condition.


it("traverses non-empty array", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(pipe(xs, A.map(Lazy.of), f, apply)).toEqual(xs),
				),
			)
		})

Summary: Traversing a non-empty array with `Lazy.of`, mapped and applied, should return the original array.


it("gets the value", () => {
			fc.assert(
				fc.property(fc.anything(), x =>
					expect(x).toEqual(pipe(x, Lazy.of, Lazy.execute)),
				),
			)
		})

Summary: `Lazy.execute` retrieves the original value wrapped by `Lazy.of`.


it("constructs ordinary Lazy value", () => {
			fc.assert(
				fc.property(fc.anything(), x =>
					expect(
						pipe(
							Lazy.lazy(() => x),
							Lazy.execute,
						),
					).toEqual(pipe(() => x, Lazy.execute)),
				),
			)
		})

Summary: Constructing a `Lazy` value should yield the same result as directly executing the function.


it("never throws", () => {
			fc.assert(
				fc.property(
					fc.oneof(fc.string(), fc.integer(), fc.boolean(), fc.constant(null)),
					x => {
						stringifyPrimitive(x)
					},
				),
			)
		})

Summary: `stringifyPrimitive` does not throw an error when handling strings, integers, booleans, or null values.


it('test domain name', () => {
        const _url = toArbitrary(() => faker.internet.domainName());

        fc.assert(
            fc.property(_url, (url) => {
                expect(validation.Validators.website(url)).toEqual(ValidationErrors.None);
            }),
        );
    })

Summary: The `Validators.website` should return `ValidationErrors.None` for any URL generated as a domain name.


it('test domainWord', () => {
        const _url = toArbitrary(() => faker.internet.domainWord());

        fc.assert(
            fc.property(_url, (url) => {
                expect(validation.Validators.website(url)).toEqual(ValidationErrors.Website);
            }),
        );
    })

Summary: Validates that `Validators.website` classifies domain words generated by `faker.internet.domainWord` as `ValidationErrors.Website`.


it('test email', () => {
        const _url = toArbitrary(() => faker.internet.email());

        fc.assert(
            fc.property(_url, (url) => {
                expect(validation.Validators.website(url)).toEqual(ValidationErrors.Website);
            }),
        );
    })

Summary: Validation of emails should not result in `ValidationErrors.Website` when checked by the `Validators.website` function.


it('use logger with runtime mode disabling', () => {
    const _textToLog: fc.Arbitrary<string> = toArbitrary(() => faker.lorem.word());
    const consoleMocks = createConsoleMocks();

    let iteration = 0;
    fc.assert(
      fc.property(_textToLog, (textToLog) => {
        // set mode before or after creating a new logger

        if (iteration % 2 === 0) {
          setMode('console');
          setMode(() => createCustomLogger());
          setMode(false);
        }
        const logger = createLogger(faker.lorem.word());
        if (iteration % 2 === 1) {
          setMode('console');
          setMode(() => createCustomLogger());
          setMode(false);
        }

        const methodName = loggerMethods[iteration % 3];
        logger[methodName](textToLog);

        expect(getMode()).toBe(false);
        expect(consoleMocks[methodName]).not.toHaveBeenCalled();
        ++iteration;
      }), {
      numRuns: loggerMethods.length * 2,
    });

    clearMocks(consoleMocks);
  })

Summary: Logger should not call console methods when runtime mode is disabled.


it("homomorphism", () => {
				fc.assert(
					fc.property(fc.integer(), fc.integer(), fc.anything(), (x, y, z) => {
						const f = add(y)

						const left = pipe(F.of(f), F.ap(F.of(x)), apply(z))
						const right = pipe(F.of(f(x)), apply(z))

						return expect(left).toEqual(right)
					}),
				)
			})

Summary: The property verifies that applying a function via `F.ap` and piped computations using `F.of` is consistent with directly applying the function to a value, both yielding the same result when applied with `apply(z)`.


it("interchange", () => {
				fc.assert(
					fc.property(fc.integer(), fc.integer(), fc.anything(), (x, y, z) => {
						const f = add(y)

						const left = pipe(F.of(f), F.ap(F.of(x)), apply(z))
						const right = pipe(F.of(apply(x)), F.ap(F.of(f)), apply(z))

						return expect(left).toEqual(right)
					}),
				)
			})

Summary: The interchange law should hold by ensuring `pipe(F.of(f), F.ap(F.of(x)), apply(z))` equals `pipe(F.of(apply(x)), F.ap(F.of(f)), apply(z))` for any integers and value.


it('use logger with \'null\' mode', () => {
    const _textToLog: fc.Arbitrary<string> = toArbitrary(() => faker.internet.url());

    let iteration = 0;
    fc.assert(
      fc.property(_textToLog, (textToLog) => {
        if (iteration % 2 === 0) setMode(undefined);
        const logger = createLogger(faker.lorem.word());
        if (iteration % 2 === 1) setMode(null);

        const methodName = loggerMethods[iteration % 3];
        logger[methodName](textToLog);

        const spyLogger = vi.spyOn(CONSOLE, methodName);

        expect(getMode()).toBeFalsy();
        expect(spyLogger).not.toHaveBeenCalled();
        ++iteration;
      }), {
      numRuns: loggerMethods.length * 2,
    });
  })

Summary: Using a logger with 'null' mode or an undefined mode should result in logger methods not calling the console.


it('use logger with override mode #override', () => {

    const loggerName = `[${faker.lorem.word()}]`;
    const _textToLog: fc.Arbitrary<string> = toArbitrary(() => faker.lorem.word());
    const consoleMocks = createConsoleMocks();

    const customLogger = createCustomLogger();
    const customLoggerGetter = () => customLogger;

    setMode('console');

    let iteration = 0;
    fc.assert(
      fc.property(_textToLog, (textToLog) => {
        const loggerDisabled = createLogger(loggerName, false);
        const loggerCustom = createLogger(loggerName, customLoggerGetter);

        const methodName = loggerMethods[iteration % 3];
        loggerDisabled[methodName](textToLog);
        expect(consoleMocks[methodName]).not.toHaveBeenCalled();

        loggerCustom[methodName](textToLog);

        expect(consoleMocks[methodName]).not.toHaveBeenCalled();

        const impl = customLogger[methodName];
        expect(impl).toHaveBeenCalledWith(loggerName, textToLog);
        impl.mockClear();

        ++iteration;
      }), {
      numRuns: loggerMethods.length,
    });

    expect(getMode()).toBe('console');
    clearMocks(consoleMocks);

  })

Summary: `createLogger` correctly uses a custom logger's implementation methods without calling console methods when in override mode.


test('should returns false for everything else', () =>
      fc.assert(
        fc.property(
          fc.oneof(unassignedPhone()),
          (phone) => !isPhoneNumber(phone)
        )
      ))

Summary: `isPhoneNumber` returns false for unassigned phone numbers generated within specified integer ranges.


it("composition", () => {
				fc.assert(
					fc.property(
						fc.integer(),
						fc.integer(),
						fc.integer(),
						fc.anything(),
						(x, y, z, zz) => {
							const f = add(y)
							const g = multiply(z)

							const compose: <B, C>(
								bc: (x: B) => C,
							) => <A>(ab: (x: A) => B) => (x: A) => C = bc => ab =>
								flow(ab, bc)

							// The type system struggles to follow polymorphic compose below, so we'll fix the
							// types here.
							const composeMono: (
								bc: Endomorphism<number>,
							) => (ab: Endomorphism<number>) => Endomorphism<number> = compose

							const left = pipe(
								F.of(composeMono),
								F.ap(F.of(f)),
								F.ap(F.of(g)),
								F.ap(F.of(x)),
								apply(zz),
							)
							const right = pipe(
								F.of(f),
								F.ap(pipe(F.of(g), F.ap(F.of(x)))),
								apply(zz),
							)

							return expect(left).toEqual(right)
						},
					),
				)
			})

Summary: Verifies that function composition using `composeMono` and applying it through different pipeline structures (`left` and `right`) yields the same result.


it("never throws", () => {
			fc.assert(
				fc.property(pair, ([x, y]) => {
					f(x)(x)
					f(y)(y)
					f(y)(x)
				}),
			)
		})

Summary: Function `f` should not throw an error when applied to any pair of values `x` and `y`.


it("maps both sides", () => {
			const g = Str.append("!")

			fc.assert(
				fc.property(fc.string(), x => {
					expect(f(g)(E.left(x))).toEqual(E.left(g(x)))
					expect(f(g)(E.right(x))).toEqual(E.right(g(x)))
				}),
			)
		})

Summary: Verifies that applying a function with `f` to both `E.left` and `E.right` results in both being mapped with the function `g`.


it("is equivalent to doubly applied bimap", () => {
			const g = Str.append("!")

			fc.assert(
				fc.property(fc.string(), x => {
					expect(f(g)(E.left(x))).toEqual(E.bimap(g, g)(E.left(x)))
					expect(f(g)(E.right(x))).toEqual(E.bimap(g, g)(E.right(x)))
				}),
			)
		})

Summary: The function `f(g)` applied to `Either` values behaves identically to `E.bimap(g, g)` applied to the same `Either` values.


it("considers any Left less than any Right", () => {
			// For reference.
			expect(Num.Ord.compare(1, 2)).toBe(LT)

			fc.assert(
				fc.property(fc.anything(), fc.anything(), (x, y) => {
					// biome-ignore lint/suspicious/noExplicitAny: Testing.
					expect(f(E.left<any, any>(x), E.right<any, any>(y))).toBe(LT)
					// biome-ignore lint/suspicious/noExplicitAny: Testing.
					expect(f(E.right<any, any>(x), E.left<any, any>(y))).toBe(GT)
				}),
			)
		})

Summary: In a comparison, any `Left` value is considered less than any `Right` value, and any `Right` value is greater than any `Left` value.


it("logs string message", () => {
			fc.assert(
				fc.property(fc.string(), x => {
					const spy = jest
						.spyOn(global.console, "log")
						.mockImplementation(constVoid)
					f(x)(undefined)
					expect(console.log).toHaveBeenCalledTimes(1)
					expect(console.log).toHaveBeenCalledWith(x)
					spy.mockRestore()
				}),
			)
		})

Summary: The function logs a given string message to the console exactly once.


it("returns provided value by reference", () => {
			fc.assert(
				fc.property(fc.anything(), x => {
					const spy = jest
						.spyOn(global.console, "log")
						.mockImplementation(constVoid)
					expect(f("")(x)).toBe(x)
					spy.mockRestore()
				}),
			)
		})

Summary: `f("")` returns the provided value without modification.


it("logs string message and value", () => {
			fc.assert(
				fc.property(fc.string(), fc.anything(), (x, y) => {
					const spy = jest
						.spyOn(global.console, "log")
						.mockImplementation(constVoid)
					f(x)(y)
					expect(console.log).toHaveBeenCalledTimes(1)
					expect(console.log).toHaveBeenCalledWith(x, y)
					spy.mockRestore()
				}),
			)
		})

Summary: Logs a string message and a value to the console once.


Summary: `f` returns the provided value by reference without alteration.


it("wraps prototype method", () => {
			fc.assert(
				fc.property(fc.date(), d => unMilliseconds(f(d)) === d.getTime()),
			)
		})

Summary: `unMilliseconds` applied on `f(d)` should return the same result as `d.getTime()` for any date `d`.


test('Scopa is a game for 2, 3, 4 or 6 players', () => {
    fc.assert(
      fc.property(fc.constantFrom<(2 | 3 | 4 | 6)[]>(2, 3, 4, 6), (players) => {
        const game = getGameState(deal(deck(), { players }))
        return game.players.length === players
      }),
    )
  })

Summary: The number of players in a Scopa game state must match the specified count of 2, 3, 4, or 6 players.


it("always returns a non-empty array", () => {
			fc.assert(
				fc.property(
					fc.array(fc.integer()),
					fc.integer(),
					(xs, y) => !!f(N.Eq)(y)(xs).length,
				),
			)
		})


it("wraps date constructor", () => {
			fc.assert(
				fc.property(
					fc.oneof(fc.string(), fc.integer()),
					// Invalid dates don't deep equality check in Jest
					x =>
						isValid(f(x))
							? expect(f(x)).toEqual(new Date(x))
							: !isValid(f(x)) && !isValid(new Date(x)),
				),
			)
		})

Summary: `f(x)` should produce a valid date equivalent to `new Date(x)`, or both should be invalid.


it("maps both sides", () => {
			const h = Str.isAlphaNum

			fc.assert(
				fc.property(fc.string(), fc.string(), (l, r) => {
					expect(f(h)([l, r])).toEqual([h(l), h(r)])
					expect(g(h)(E.left(l))).toEqual(E.left(h(l)))
					expect(g(h)(E.right(r))).toEqual(E.right(h(r)))
				}),
			)
		})

Summary: The test checks that functions `f` and `g` correctly apply a mapping function `h` to both components of a pair and to the left and right values of a type `E`.


it("returns updated array wrapped in Some if index is okay", () => {
			expect(f(0)(["x"])([])).toEqual(O.some(["x"]))
			expect(g(["x"])).toEqual(O.some(["x", "a", "b"]))
			expect(g(["x", "y"])).toEqual(O.some(["x", "a", "b", "y"]))

			fc.assert(
				fc.property(
					fc.array(fc.anything(), {
						minLength: 1,
						maxLength: 5,
					}) as fc.Arbitrary<NonEmptyArray<unknown>>,
					fc.integer({ min: 0, max: 10 }),
					(xs, i) => O.isSome(f(i)(xs)(xs)) === i <= A.size(xs),
				),
			)

			fc.assert(
				fc.property(
					fc.array(fc.string(), { minLength: 1, maxLength: 20 }),
					xs =>
						expect(pipe(g(xs), O.map(A.size))).toEqual(O.some(A.size(xs) + 2)),
				),
			)
		})


it("never returns a larger array", () => {
			fc.assert(
				fc.property(fc.array(fc.integer()), xs => f(xs).length <= A.size(xs)),
			)
		})


it("never introduces new elements", () => {
			const g = A.uniq(N.Eq)

			fc.assert(
				fc.property(fc.array(fc.integer()), xs =>
					pipe(xs, f, g, A.every(elemV(N.Eq)(g(xs)))),
				),
			)
		})


it("returns true for empty subarray", () => {
			fc.assert(fc.property(fc.array(fc.integer()), xs => f([])(xs)))
		})


it("checks start of array for subarray", () => {
			expect(f([1])([1, 2, 3])).toBe(true)
			expect(f([3])([1, 2, 3])).toBe(false)

			fc.assert(
				fc.property(fc.array(fc.integer()), fc.array(fc.integer()), (xs, ys) =>
					f(xs)(A.concat(ys)(xs)),
				),
			)
		})


it("checks end of array for subarray", () => {
			expect(f([3])([1, 2, 3])).toBe(true)
			expect(f([1])([1, 2, 3])).toBe(false)

			fc.assert(
				fc.property(fc.array(fc.integer()), fc.array(fc.integer()), (xs, ys) =>
					f(xs)(A.concat(xs)(ys)),
				),
			)
		})


it("removes numbers present in first input array", () => {
			const g = f([4, 5])

			expect(g([3, 4])).toEqual([3])
			expect(g([4, 5])).toEqual([])
			expect(g([4, 5, 6])).toEqual([6])
			expect(g([3, 4, 5, 6])).toEqual([3, 6])
			expect(g([4, 3, 4, 5, 6, 5])).toEqual([3, 6])

			fc.assert(
				fc.property(fc.array(fc.integer()), xs =>
					expect(f(xs)(xs)).toEqual(A.empty),
				),
			)
		})


it("should allow to retrieve attribute data from an HTML element", () => {
      fc.assert(
        fc
          .property(globalHTMLAttrArb, (attr) => {
            const divElement = document.createElement(tagName);
            for (const key in attr) {
              if (attr[key as keyof typeof attr] === false) {
                divElement.removeAttribute(key.toLowerCase());
              } else if (attr[key as keyof typeof attr] !== undefined) {
                divElement.setAttribute(
                  key.toLowerCase(),
                  String(attr[key as keyof typeof attr])
                );
                expect(divElement.getAttribute(key.toLowerCase())).toBe(
                  String(attr[key as keyof typeof attr])
                );
              }
            }
            container.appendChild(divElement);

            const doc = htmlAdapter(container) as any;
            expect(doc[tagName as keyof typeof doc]().single()).toMatchObject(
              attr
            );
          })
          .afterEach(() => {
            document.body.removeChild(container!);
            container = document.createElement("div");
            document.body.appendChild(container!);
          })
      );
    })

Summary: The test ensures attribute data assigned to an HTML element is accurately retrievable through the `htmlAdapter` function.


it("sums non-empty input", () => {
			expect(f([25, 3, 10])).toBe(38)
			expect(f([-3, 2])).toBe(-1)
			expect(f([2.5, 3.2])).toBe(5.7)

			fc.assert(
				fc.property(
					fc.array(fc.integer()),
					xs => f(xs) === xs.reduce((acc, val) => acc + val, 0),
				),
			)
		})


it("calculates product of non-empty input", () => {
			expect(f([4, 2, 3])).toBe(24)
			expect(f([5])).toBe(5)
			expect(f([1.5, -5])).toBe(-7.5)

			fc.assert(
				fc.property(
					fc.array(fc.integer()),
					xs => f(xs) === xs.reduce((acc, val) => acc * val, 1),
				),
			)
		})


it("returns empty array for empty array input", () => {
			expect(f(0)([])).toEqual([])

			fc.assert(
				fc.property(fc.integer({ min: 0, max: 100 }), n => !f(n)([]).length),
			)
		})


it("returns empty array for non-positive input number", () => {
			fc.assert(
				fc.property(
					fc.integer({ max: 0 }),
					fc.array(fc.anything()),
					(n, xs) => !f(n)(xs).length,
				),
			)
		})


it("behaves identically to Array.prototype.slice", () => {
			fc.assert(
				fc.property(
					fc.array(fc.anything()),
					fc.integer(),
					fc.integer(),
					(xs, start, end) =>
						expect(f(start)(end)(xs)).toEqual(xs.slice(start, end)),
				),
			)
		})


it("is the inverse of filter", () => {
			fc.assert(
				fc.property(
					fc.array(fc.integer()),
					xs => A.filter(p)(xs).length + f(xs).length === A.size(xs),
				),
			)
		})


it("returns unmodified array provided same indices (in bounds)", () => {
			const n = 10

			fc.assert(
				fc.property(
					fc.array(fc.anything(), { minLength: 1, maxLength: n }),
					fc.integer({ min: 0, max: n - 1 }),
					(xs, i) => i >= A.size(xs) || expect(f(i)(i)(xs)).toEqual(O.some(xs)),
				),
			)
		})


it("returns None if source is out of bounds", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(A.size(xs))(0)(xs)).toEqual(O.none),
				),
			)
		})


it("returns None if target is out of bounds", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(0)(A.size(xs))(xs)).toEqual(O.none),
				),
			)
		})


it("moves source to target", () => {
			expect(f(0)(1)(["a", "b", "c"])).toEqual(O.some(["b", "a", "c"]))
			expect(f(1)(0)(["a", "b", "c"])).toEqual(O.some(["b", "a", "c"]))

			const n = 10

			fc.assert(
				fc.property(
					fc.array(fc.anything(), { minLength: n, maxLength: n }),
					fc.integer({ min: 0, max: n - 1 }),
					fc.integer({ min: 0, max: n - 1 }),
					(xs, i, j) => O.isSome(f(i)(j)(xs)),
				),
			)
		})


it("returns the same array size", () => {
			const n = 10

			fc.assert(
				fc.property(
					fc.array(fc.anything(), { minLength: n, maxLength: n }),
					fc.integer({ min: 0, max: n - 1 }),
					fc.integer({ min: 0, max: n - 1 }),
					(xs, i, j) =>
						pipe(
							f(i)(j)(xs),
							O.exists(ys => A.size(ys) === n),
						),
				),
			)
		})


it("sibling indices are interchangeable", () => {
			const n = 10

			fc.assert(
				fc.property(
					fc.array(fc.anything(), { minLength: n, maxLength: n }),
					fc.integer({ min: 0, max: n - 2 }),
					(xs, i) => expect(f(i)(i + 1)(xs)).toEqual(f(i + 1)(i)(xs)),
				),
			)
		})


it("returns None if source is out of bounds", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(0)(A.size(xs))(xs)).toEqual(O.none),
				),
			)
		})


it("returns None if target is out of bounds", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(A.size(xs))(0)(xs)).toEqual(O.none),
				),
			)
		})


it("should allow to retrieve attribute data from an HTML element", () => {
      fc.assert(
        fc
          .property(globalHTMLAttrArb, (attr) => {
            const divElement = document.createElement("div");
            for (const key in attr) {
              if (attr[key as keyof typeof attr] === false) {
                divElement.removeAttribute(key.toLowerCase());
              } else if (attr[key as keyof typeof attr] !== undefined) {
                divElement.setAttribute(
                  key.toLowerCase(),
                  String(attr[key as keyof typeof attr])
                );
                expect(divElement.getAttribute(key.toLowerCase())).toBe(
                  String(attr[key as keyof typeof attr])
                );
              }
            }
            container.appendChild(divElement);

            const doc = baseAdapter(container);
            expect(doc.queryHTML("div").single()).toMatchObject(attr);
          })
          .afterEach(() => {
            document.body.removeChild(container!);
            container = document.createElement("div");
            document.body.appendChild(container!);
          })
      );
    })

Summary: Retrieval of attribute data from an HTML element should correctly match the assigned attributes through `baseAdapter` query.


it("all numbers are above zero", () => {
			fc.assert(
				fc.property(
					fc.array(fc.string()),
					flow(
						f(identity),
						values,
						A.every(n => n > 0),
					),
				),
			)
		})


it("counts the same summed number as the A.size of the array", () => {
			// fast-check generates keys that fp-ts internals won't iterate over,
			// meaning without this the keys below won't necessarily add up.
			const filterSpecialKeys: Endomorphism<Array<string>> = A.chain(
				flow(k => R.singleton(k, null), R.keys),
			)

			fc.assert(
				fc.property(
					fc.array(fc.string()),
					xs =>
						pipe(xs, f(identity), values, sum) === filterSpecialKeys(xs).length,
				),
			)
		})

Summary: The sum of values produced by `f(identity)` on an array should equal the length of the array with special keys filtered out.


test(`fitToPage shows the same view after zooming all the way in`, async ({ page }) => {
		await page.goto('/Jigs-2-Lots-of-jigs');
		await fc.assert(zoomThenFitToPage(page, 'in'), {
			examples: [[1993, 805]],
			timeout: TEST_TIMEOUT_MILLIS,
			interruptAfterTimeLimit: TEST_TIMEOUT_MILLIS
		});
	})

Summary: `fitToPage` maintains the same view after the page is zoomed all the way in.


it("constTrue returns empty array", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(constTrue)(xs)).toEqual([]),
				),
			)
		})


it("constFalse returns original array", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(constFalse)(xs)).toEqual(xs),
				),
			)
		})


it("maintains same flattened size", () => {
			fc.assert(
				fc.property(
					fc.array(fc.array(fc.anything())),
					xs => A.size(A.flatten(xs)) === A.size(A.flatten(f(xs))),
				),
			)
		})


it("does not mistakenly pass along undefined values", () => {
			fc.assert(
				fc.property(
					fc.array(fc.array(fc.anything().filter(x => x !== undefined))),
					flow(
						f,
						A.flatten,
						A.every(x => x !== undefined),
					),
				),
			)
		})


it("calculates the mean", () => {
			expect(f([2, 7, 9])).toBe(6)

			fc.assert(
				fc.property(
					fc.integer({ min: 1, max: 50 }),
					fc.integer(),
					(x, y) => f(A.replicate(x, y) as NonEmptyArray<number>) === y,
				),
			)
		})

Summary: The function `f` calculates the mean of an array, and for a replicated array of identical numbers, the mean should equal the repeated number.


it("constTrue returns original array", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(constTrue)(xs)).toEqual(xs),
				),
			)
		})


it("constFalse returns empty array", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs =>
					expect(f(constFalse)(xs)).toEqual([]),
				),
			)
		})


it("one empty input returns other input whole", () => {
			fc.assert(
				fc.property(fc.array(fc.integer()), xs =>
					expect(f(xs)([])).toEqual(xs),
				),
			)

			fc.assert(
				fc.property(fc.array(fc.integer()), xs =>
					expect(f([])(xs)).toEqual(xs),
				),
			)
		})


it("returns identity on singleton non-empty array", () => {
			fc.assert(fc.property(fc.integer(), n => f([n]) === n))
		})


it("returns the smallest value", () => {
			expect(f([3, 1, 2])).toBe(1)

			fc.assert(
				fc.property(
					fc.integer(),
					n => f([n, n + 1]) === n && f([n + 1, n]) === n,
				),
			)
		})


it("returns the largest value", () => {
			expect(f([1, 3, 2])).toBe(3)

			fc.assert(
				fc.property(
					fc.integer(),
					n => f([n, n + 1]) === n + 1 && f([n + 1, n]) === n + 1,
				),
			)
		})


it("equal length inputs is equivalent to normal zip mapped to These", () => {
			fc.assert(
				fc.property(fc.array(fc.anything()), xs => {
					const ys = A.reverse(xs)
					expect(f(xs)(ys)).toEqual(
						pipe(
							A.zip(xs)(ys),
							A.map(([x, y]) => T.both(x, y)),
						),
					)
				}),
			)
		})


it("output length is equal to largest input length", () => {
			fc.assert(
				fc.property(
					fc.array(fc.anything()),
					fc.array(fc.anything()),
					(xs, ys) => A.size(f(xs)(ys)) === max(N.Ord)(A.size(xs), A.size(ys)),
				),
			)
		})


it("is identical to filter in an applicative context", () => {
			const g = A.filter
			const isEven: Predicate<number> = n => n % 2 === 0
			const isEvenIO = flow(isEven, IO.of)

			fc.assert(
				fc.property(fc.array(fc.integer()), xs =>
					expect(f(isEvenIO)(xs)()).toEqual(g(isEven)(xs)),
				),
			)
		})


it("returns array of input size minus one", () => {
			fc.assert(
				fc.property(fc.array(fc.anything(), { minLength: 2 }), xs =>
					expect(pipe(xs, f, O.map(flow(snd, A.size)))).toEqual(
						pipe(xs, A.size, decrement, O.some),
					),
				),
			)
		})


it("returns element at index", () => {
			fc.assert(
				fc.property(fc.array(fc.anything(), { minLength: 2 }), xs =>
					expect(pipe(xs, f, O.map(fst))).toEqual(A.lookup(1)(xs)),
				),
			)
		})


it("always returns a non-empty output", () => {
			fc.assert(
				fc.property(fc.array(fc.boolean(), { minLength: 1 }), xs => {
					const ys: NonEmptyArray<E.Either<boolean, boolean>> = pipe(
						xs as NonEmptyArray<boolean>,
						NEA.map(b => (b ? E.right(b) : E.left(b))),
					)

					const zs: NonEmptyArray<boolean> = pipe(
						ys,
						f,
						T.match(identity, identity, (ls, rs) => NEA.concat(ls)(rs)),
					)

					expect(A.size(zs)).toBeGreaterThan(0)
					expect(A.size(zs)).toBe(A.size(xs))
				}),
			)
		})

Summary: The transformation of a non-empty array of booleans into another non-empty array maintains the same size.


it("equivaent to stricter separate", () => {
			const g = A.separate

			fc.assert(
				fc.property(fc.array(fc.boolean(), { minLength: 1 }), xs => {
					const ys: NonEmptyArray<E.Either<boolean, boolean>> = pipe(
						xs as NonEmptyArray<boolean>,
						NEA.map(b => (b ? E.right(b) : E.left(b))),
					)

					const nea: NonEmptyArray<boolean> = pipe(
						ys,
						f,
						T.match(identity, identity, (ls, rs) => NEA.concat(ls)(rs)),
					)

					const notNea: Array<boolean> = pipe(ys, g, ({ left, right }) =>
						A.concat(left)(right),
					)

					expect(nea).toEqual(notNea)
				}),
			)
		})

Summary: The function `f` outputs a concatenation of left and right values from a non-empty array of `Either` type booleans, which should be equivalent to the result from `A.separate`.


it("returns constant empty/zero on false", () => {
			fc.assert(
				fc.property(fc.anything(), x =>
					expect(f(false)(constant(x))).toEqual(O.none),
				),
			)
		})

Summary: Returns `O.none` when applying a constant function with any input if the condition is false.


test('should parse complete json', () => {
    expect(partialParse('{"__proto__": 0}')).toEqual(JSON.parse('{"__proto__": 0}'));

    fc.assert(
      fc.property(fc.json({ depthSize: 'large', noUnicodeString: false }), (jsonString) => {
        const parsedNormal = JSON.parse(jsonString);
        const parsedPartial = partialParse(jsonString);
        expect(parsedPartial).toEqual(parsedNormal);
      }),
    );
  })

Summary: `partialParse` should correctly parse complete JSON strings, matching the output of `JSON.parse`.


it("never throws", () => {
			fc.assert(
				fc.property(fc.string(), x => {
					f(x)
				}),
			)
		})


it("wraps URL constructor", () => {
			expect(() => f("x")).toThrow()
			expect(f(validUrl)).toEqual(new URL(validUrl))

			fc.assert(fc.property(fc.webUrl(), x => expect(f(x)).toEqual(new URL(x))))
		})

Summary: The function `f` should behave like the `URL` constructor, throwing errors for invalid URLs and returning equivalent `URL` objects for valid inputs.


it("works", () => {
			expect(f("invalid")).toBe(false)
			expect(f(validUrl)).toBe(true)

			fc.assert(fc.property(fc.webUrl(), f))
		})

Summary: The function `f` should return false for an invalid URL and true for valid URLs.


it("is lossless (excluding formatting)", () => {
			fc.assert(
				fc.property(
					fc.webUrl({ withFragments: true, withQueryParameters: true }),
					x =>
						// biome-ignore lint/suspicious/noSelfCompare: Incorrect lint.
						pipe(x, unsafeParse, f, unsafeParse, f) === pipe(x, unsafeParse, f),
				),
			)
		})

Summary: Parsing and processing a URL string should consistently result in the same output when repeated, apart from formatting differences.


it("all equal scalars are shallowly equal", () => {
    fc.assert(
      fc.property(
        // Inputs
        fc.clone(scalar(), 2),

        // Unit test
        ([scalar1, scalar2]) => {
          expect(shallow(scalar1, scalar2)).toBe(true);

          // If two values are shallowly equal, then those values wrapped in an
          // array (one level) should _also_ be considered shallowly equal
          expect(shallow([scalar1], [scalar2])).toBe(true);
          expect(shallow([scalar1, scalar1], [scalar2, scalar2])).toBe(true);

          // ...but wrapping twice is _never_ going to be equal
          expect(shallow([[scalar1]], [[scalar2]])).toBe(false);

          // Ditto for objects
          expect(shallow({ a: scalar1 }, { a: scalar2 })).toBe(true);
          expect(
            shallow({ a: scalar1, b: scalar1 }, { a: scalar2, b: scalar2 })
          ).toBe(true);

          // ...but nesting twice is _never_ going to be equal
          expect(shallow({ a: { b: scalar1 } }, { a: { b: scalar2 } })).toBe(
            false
          );
        }
      )
    );
  })


it("different scalars are not shallowly equal", () => {
    fc.assert(
      fc.property(
        // Inputs
        fc.tuple(scalar(), scalar()).filter(([x, y]) => x !== y),

        // Unit test
        ([scalar1, scalar2]) => {
          expect(shallow(scalar1, scalar2)).toBe(false);

          // If two values are shallowly unequal, then wrapping those in an
          // array (one level) should also always be shallowly unequal
          expect(shallow([scalar1], [scalar2])).toBe(false);

          // Ditto for objects
          expect(shallow({ k: scalar1 }, { k: scalar2 })).toBe(false);
        }
      )
    );
  })


it("equal composite values", () => {
    fc.assert(
      fc.property(
        // Inputs
        fc.clone(complex(), 2),

        // Unit test
        ([complex1, complex2]) => {
          // Property: _if_ two complex values are considered shallowly equal,
          // then wrapping them in an array (one level) will guarantee they're
          // not shallowly equal
          if (shallow(complex1, complex2)) {
            expect(shallow([complex1], [complex2])).toBe(false);
          }

          // Ditto for objects
          if (shallow(complex1, complex2)) {
            expect(shallow({ k: complex1 }, { k: complex2 })).toBe(false);
          }
        }
      )
    );
  })


it("consistency", () => {
    fc.assert(
      fc.property(
        // Inputs
        fc.oneof(
          fc.tuple(anything(), anything()),

          // Add a few clones in the mix too, to ensure we'll have different and equal values
          fc.clone(anything(), 2)
        ),

        // Unit test
        ([value1, value2]) => {
          // _If_ sticking these values in an array makes them shallow-equal,
          // then they should also always be equal without the array wrappers
          if (shallow([value1], [value2])) {
            expect(shallow(value1, value2)).toBe(true);
          }

          if (shallow({ k: value1 }, { k: value2 })) {
            expect(shallow(value1, value2)).toBe(true);
          }
        }
      )
    );
  })


it("argument ordering does not matter", () => {
    fc.assert(
      fc.property(
        // Inputs
        fc.oneof(
          fc.tuple(anything(), anything()),

          // Add a few clones in the mix too, to ensure we'll have different and equal values
          fc.clone(anything(), 2)
        ),

        // Unit test
        ([value1, value2]) => {
          // Order doesn't matter when comparing
          expect(shallow(value1, value2)).toBe(shallow(value2, value1));
        }
      )
    );
  })


test('can splice', () => {
      fc.assert(
        fc.property(
          fc.commands([
            TSeqSpliceCommand.arbitrary()
          ]), cmds => {
            fc.modelRun(() => ({
              model: new SpliceStringModel(),
              real: new TSeq('p1')
            }), cmds);
          }
        )
      );
    })

Summary: The test verifies that a series of splice commands can be correctly executed on a `TSeq` instance using a corresponding model for validation.


assertArbitrary = (arbitrary: fc.Arbitrary<unknown>, checks: FilterFunction[], result: boolean): void => {
  fc.assert(
    fc.property(arbitrary, (value) => {
      checks.forEach((check) => {
        expect(check(value)).toBe(result);
      });
    }),
  );
}

Summary: The property ensures that all `FilterFunction` checks applied to values generated by an arbitrary match the expected boolean result.


it("date (and other non-pojos) are never considered equal", () => {
    fc.assert(
      fc.property(
        // Inputs
        fc.oneof(
          fc.tuple(nonpojo(), nonpojo()),

          // Add a few clones in the mix too, to ensure we'll have different and equal values
          fc.clone(nonpojo(), 2)
        ),

        // Unit test
        ([v1, v2]) => {
          expect(shallow(v1, v2)).toBe(false);
          expect(shallow([v1], [v2])).toBe(false);
          expect(shallow({ k: v1 }, { k: v2 })).toBe(false);
        }
      )
    );
  })


test('same-type circular structure should throw an error', () => {
      const circularArbitrary = fc.integer(0, 100).map<TypeReference1>((n) => createLinkedList(n, true)[0]);

      // We check the valid arbitrary on a finer-grained level than the invalid one
      fc.assert(
        fc.property(circularArbitrary, (value) => {
          expect(() => typeCheckFor<TypeReference1>()(value)).toThrow(circularTypeError);
          expect(() => isA<TypeReference1>(value)).toThrow(circularTypeError);
        }) as any,
      );
    })

Summary: A circular structure of the same type should trigger an error in both `typeCheckFor` and `isA`.


it("deregisering usage", () => {
    fc.assert(
      fc.property(
        anything(),

        (payload) => {
          const callback1 = jest.fn();
          const callback2 = jest.fn();
          const hub = makeEventSource();

          const dereg1 = hub.observable.subscribe(callback1);

          // Registering the same function instance multiple times has no
          // observable effect
          const dereg2a = hub.observable.subscribe(callback2);
          const dereg2b = hub.observable.subscribe(callback2);

          hub.notify(payload);
          hub.notify(payload);

          expect(callback1.mock.calls.length).toBe(2); // Both get updates
          expect(callback2.mock.calls.length).toBe(2);

          // Deregister callback1
          dereg1();

          hub.notify(payload);
          hub.notify(payload);
          hub.notify(payload);

          expect(callback1.mock.calls.length).toBe(2); // Callback1 stopped getting updates
          expect(callback2.mock.calls.length).toBe(5); // Callback2 still receives updates

          // Deregister callback2
          dereg2a();

          hub.notify(payload);
          hub.notify(payload);
          hub.notify(payload);

          expect(callback1.mock.calls.length).toBe(2); // Callback1 already stopped getting updates before
          expect(callback2.mock.calls.length).toBe(5); // Callback2 now also stopped getting them

          // Deregister callback2 again (has no effect)
          dereg2b();

          hub.notify(payload);
          hub.notify(payload);
          hub.notify(payload);

          expect(callback1.mock.calls.length).toBe(2); // Callback1 already stopped getting updates before
          expect(callback2.mock.calls.length).toBe(5); // Callback2 already stopped getting updates before
        }
      )
    );
  })

Summary: Subscribing, deregistering, and re-deregistering callbacks should correctly affect the number of updates received by each callback.


it("setting works with any value", () => {
    fc.assert(
      fc.property(
        fc.anything(),
        fc.anything(),

        (init, newVal) => {
          const ref = new ValueRef<unknown>(init);
          expect(ref.current).toStrictEqual(init);

          ref.set(newVal);
          expect(ref.current).toStrictEqual(newVal);
        }
      )
    );
  })

Summary: `ValueRef` correctly updates its current value, reflecting any initial and subsequent values assigned to it.


it("will freeze all given values", () => {
    fc.assert(
      fc.property(
        fc.anything(),
        fc.anything(),

        (init, newVal) => {
          // Freezes in constructor
          const ref = new ValueRef<unknown>(init);
          expect(ref.current).toStrictEqual(init);
          expect(() => {
            (ref.current as any).abc = 123;
          }).toThrow();

          // Freezes in setter
          ref.set(newVal);
          expect(ref.current).toStrictEqual(newVal);
          expect(() => {
            (ref.current as any).xyz = 456;
          }).toThrow();
        }
      )
    );
  })

Summary: `ValueRef` freezes the initial and new values, preventing modifications.


it('should return time from a query method', async () => {
            const actor = await getCanisterActor<Actor>('canister');

            await fc.assert(
                fc.asyncProperty(fc.constant(undefined), async () => {
                    const testTimeBefore = new Date().getTime() - 2_000;
                    const canisterTime0 = nanoSecondsToMilliseconds(
                        await actor.queryTime()
                    );
                    const canisterTime1 = nanoSecondsToMilliseconds(
                        await actor.queryTime()
                    );
                    const testTimeAfter = new Date().getTime();

                    expect(canisterTime0).toBeLessThanOrEqual(canisterTime1);

                    expect(canisterTime0).toBeGreaterThanOrEqual(
                        testTimeBefore
                    );
                    expect(canisterTime1).toBeGreaterThanOrEqual(
                        testTimeBefore
                    );

                    expect(canisterTime0).toBeLessThan(testTimeAfter);
                    expect(canisterTime1).toBeLessThanOrEqual(testTimeAfter);
                }),
                defaultPropTestParams()
            );
        })

Summary: The property ensures that the time returned by a query method in a canister is non-decreasing, falls between a certain start and end time range, and is converted from nanoseconds to milliseconds.


test('never pick undefined intervals for relative alarms', () => {
    fc.assert(fc.property(
      arbitrary_complete_intervals(),
      (intervals) => {
        const alarms = findAlarmThresholds(intervals);

        return (alarms.lowerAlarmIntervalIndex === undefined || intervals[alarms.lowerAlarmIntervalIndex].change !== undefined)
          && (alarms.upperAlarmIntervalIndex === undefined || intervals[alarms.upperAlarmIntervalIndex].change !== undefined);
      },
    ));
  })

Summary: `findAlarmThresholds` should not select undefined intervals for relative alarm indices in an array of intervals.


test('pick intervals on either side of the undefined interval, if present', () => {
    fc.assert(fc.property(
      arbitrary_complete_intervals(),
      (intervals) => {
        // There must be an undefined interval and it must not be at the edges
        const i = intervals.findIndex(x => x.change === undefined);
        fc.pre(i > 0 && i < intervals.length - 1);

        const alarms = findAlarmThresholds(intervals);
        return (alarms.lowerAlarmIntervalIndex === i - 1 && alarms.upperAlarmIntervalIndex === i + 1);
      },
    ));
  })

Summary: The test ensures that if there is an undefined interval in a sequence, `findAlarmThresholds` selects the intervals immediately before and after this undefined interval.


it('should handle batch operations correctly', () => {
      fc.assert(
        fc.property(
          fc.array(varNameArb, { minLength: 1, maxLength: 50 }),
          (exports) => {
            const tracker = create_file_type_tracker();

            // Sequential marking
            let sequential = tracker;
            for (const exp of exports) {
              sequential = mark_as_exported(sequential, exp);
            }

            // Batch marking
            const batch = mark_as_exported_batch(tracker, exports);

            // Results should be equivalent
            expect(batch.exportedDefinitions.size).toBe(sequential.exportedDefinitions.size);
            for (const exp of exports) {
              expect(batch.exportedDefinitions.has(exp)).toBe(true);
            }
          }
        )
      );
    })

Summary: The test ensures that marking exports sequentially in a file type tracker produces the same results as marking them in batch.


it('should throw error for seed length not equal to 32', async () => {
            const actor = await getCanisterActor<Actor>('canister');

            await fc.assert(
                fc.asyncProperty(
                    fc.oneof(
                        fc.uint8Array({ minLength: 0, maxLength: 31 }),
                        fc.uint8Array({ minLength: 33, maxLength: 1_024 })
                    ),
                    async (seed) => {
                        await expect(actor.seed(seed)).rejects.toThrow(
                            'seed must be exactly 32 bytes in length'
                        );
                    }
                ),
                defaultPropTestParams()
            );
        })

Summary: Ensures an error is thrown when the seed provided to `actor.seed` is not exactly 32 bytes in length.


it.each(testCases)(
            'should calculate performanceCounter($counterType) instructions accurately from a $type method',
            async ({ method }) => {
                const actor = await getCanisterActor<Actor>('canister');

                await fc.assert(
                    fc.asyncProperty(
                        fc.nat({
                            max: 1_000_000
                        }),
                        async (loops) => {
                            const instructionsLoops0 = await actor[method](0);

                            const instructions0 = await actor[method](loops);
                            const instructions1 = await actor[method](loops);

                            const instructionsAfter0 = await actor[method](
                                loops + 1_000
                            );
                            const instructionsAfter1 = await actor[method](
                                loops + 1_000
                            );

                            expect(instructionsLoops0).toBeGreaterThan(0n);
                            expect(instructions0).toBeGreaterThan(0n);
                            expect(instructions1).toBeGreaterThan(0n);
                            expect(instructionsAfter0).toBeGreaterThan(0n);
                            expect(instructionsAfter1).toBeGreaterThan(0n);

                            expect(
                                percentageDifferenceBigInt(
                                    instructions0,
                                    instructions1
                                )
                            ).toBeLessThanOrEqual(5n);

                            expect(
                                percentageDifferenceBigInt(
                                    instructionsAfter0,
                                    instructionsAfter1
                                )
                            ).toBeLessThanOrEqual(5n);

                            expect(instructions0).toBeLessThan(
                                instructionsAfter0
                            );
                            expect(instructions1).toBeLessThan(
                                instructionsAfter1
                            );
                        }
                    ),
                    defaultPropTestParams()
                );
            }
        )

Summary: The calculation of performance counter instructions should be accurate across repeated method calls, with a small percentage difference (≤ 5%) between repeated measurements and increased instruction counts for increased loop iterations.


it('should echo the reject message in echoThroughReject', async () => {
            const callerCanister = await getCanisterActor<Actor>('caller');
            await fc.assert(
                fc.asyncProperty(fc.string(), async (message) => {
                    const result =
                        await callerCanister.echoThroughReject(message);
                    expect(result).toBe(
                        `reject_message proptest message: ${message}`
                    );
                }),
                defaultPropTestParams()
            );
        })

Summary: `echoThroughReject` echoes back the provided message prefixed with "reject_message proptest message:".


it('should reply with even numbers and reject odd numbers in evenOrRejectQuery', async () => {
            const canister = await getCanisterActor<Actor>('canister');
            await fc.assert(
                fc.asyncProperty(fc.bigInt(), async (number) => {
                    if (number % 2n === 0n) {
                        const result = await canister.evenOrRejectQuery(number);
                        expect(result).toBe(number);
                    } else {
                        await expect(
                            canister.evenOrRejectQuery(number)
                        ).rejects.toThrow('Odd numbers are rejected');
                    }
                }),
                defaultPropTestParams()
            );
        })

Summary: The `evenOrRejectQuery` should reply with the number if even and reject with an error message if the number is odd.


it('should always reject with the provided message in alwaysRejectUpdate', async () => {
            const canister = await getCanisterActor<Actor>('canister');
            await fc.assert(
                fc.asyncProperty(fc.string(), async (message) => {
                    await expect(
                        canister.alwaysRejectUpdate(message)
                    ).rejects.toThrow(
                        message.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
                    );
                }),
                defaultPropTestParams()
            );
        })

Summary: `alwaysRejectUpdate` function should consistently reject with the exact message provided, after escaping backslashes and quotes.


it("generated random strings with given length", () => {
    fc.assert(
      fc.property(fc.integer({ min: 0, max: 256 }), (n) => {
        expect(nanoid(n).length).toBe(n);
      })
    );
  })


test("matches entire alphabet", () => {
    fc.assert(
      fc.property(
        fc.integer({ min: -95, max: 94 }),

        (n) => {
          if (n >= 0) {
            expect(nthDigit(n)).toBe(ALPHABET.charAt(n));
          } else {
            expect(nthDigit(n)).toBe(
              ALPHABET.split("")
                .reverse()
                .join("")
                .charAt(-(n + 1))
            );
          }
        }
      )
    );
  })

Summary: The function `nthDigit` should return the corresponding character from `ALPHABET` for integers within the specified range, handling negative indices by reversing the order of `ALPHABET`.


it("zero is an illegal Pos value", () => {
    fc.assert(
      fc.property(
        genZeroes(),

        (strOfZeroes) => {
          expect(asPos(strOfZeroes)).toBe(ONE);
        }
      )
    );
  })

Summary: A string composed entirely of zeroes is converted to the value `ONE` by `asPos`.


it("for valid strings, asPos is a noop", () => {
    fc.assert(
      fc.property(
        genPos(),

        (s) => {
          expect(asPos(s)).toBe(s);
        }
      )
    );
  })

Summary: For valid strings, the function `asPos` should return the input unchanged.


it('should return true for whoami principal from an update method', async () => {
            const actor = await getCanisterActor<Actor>('canister');

            await fc.assert(
                fc.asyncProperty(fc.constant(undefined), async () => {
                    const principal = Principal.fromText(whoamiPrincipal());

                    const isController =
                        await actor.updateIsController(principal);

                    expect(isController).toStrictEqual(true);
                }),
                defaultPropTestParams()
            );
        })

Summary: The `updateIsController` method should return true when called with the principal obtained from `whoamiPrincipal()`.


it("always outputs valid Pos values", () => {
    fc.assert(
      fc.property(
        genPos(),

        (pos) => {
          expect(isPos(after(pos))).toBe(true);
          expect(isPos(before(pos))).toBe(true);
        }
      )
    );
  })

Summary: The function verifies that both `after(pos)` and `before(pos)` produce valid `Pos` values from generated positions.