it('rejects edition for invalid inputs', async () => {
        await fc.assert(
          fc.asyncProperty(
            regexString(inverseRegExp.decimal, 1),
            async BitRate => {
              parent.wizardUI.inputs[3].value = BitRate;
              await parent.updateComplete;
              expect(parent.wizardUI.inputs[3].checkValidity()).to.be.false;
            }
          )
        );
      })

Summary: The subnetwork editor should reject invalid inputs, specifically those that do not match the decimal format, ensuring `checkValidity()` returns false.


unknown

it('edits only for valid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(regexString(regExp.tName, 1), async name => {
          parent.wizardUI.inputs[0].value = name;
          await parent.updateComplete;
          expect(parent.wizardUI.inputs[0].checkValidity()).to.be.true;
        })
      );
    })

Summary: The test verifies that the editor only accepts inputs matching a specified regular expression pattern, ensuring the input's validity.


test("fuzz sessionExpire w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await sessionExpire(sub, testSession.id);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `sessionExpire` should handle various `sub` inputs without throwing unexpected errors, logging only the specified expected errors.


it('edits only for valid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(regexString(regExp.desc), async desc => {
          parent.wizardUI.inputs[1].value = desc;
          await parent.updateComplete;
          expect(parent.wizardUI.inputs[1].checkValidity()).to.be.true;
        })
      );
    })

Summary: The property ensures the `wizardUI` input validity check returns true for strings matching a specified regex pattern.


it('edits only for valid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(regexString(regExp.unsigned, 1), async nomFreq => {
          parent.wizardUI.inputs[2].value = nomFreq;
          await parent.updateComplete;
          expect(parent.wizardUI.inputs[2].checkValidity()).to.be.true;
        })
      );
    })

Summary: The test ensures that the input value assigned to `wizardUI.inputs[2]` is valid if it matches the `unsigned` regex pattern.


test("fuzz sessionRemove w/ id", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (id) => {
			try {
				await sessionRemove(sub, id);
			} catch (e) {
				catchError(id, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The test examines the behavior of `sessionRemove` when provided with various types of input for `id`, ensuring that only specified error messages are caught and logged, while others are logged and thrown.


test("fuzz emailAddressLookup w/ `username`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (username) => {
			try {
				await emailAddressLookup(username);
			} catch (e) {
				catchError(username, e);
			}
		}),
		{
			numRuns: 10,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The function `emailAddressLookup` should handle any input, ignoring expected errors like "400 Bad Request", "401 Unauthorized", "404 Not Found", and "409 Conflict".


it('rejects action for invalid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(
          regexString(inverseRegExp.unsigned, 1),
          async nomFreq => {
            parent.wizardUI.inputs[2].value = nomFreq;
            await parent.updateComplete;
            expect(parent.wizardUI.inputs[2].checkValidity()).to.be.false;
          }
        )
      );
    })

Summary: The action is rejected when the `nomFreq` input does not match the valid pattern, ensuring `checkValidity()` returns false for invalid inputs.


it('edits only for valid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(fc.integer(1, 255), async numPhases => {
          parent.wizardUI.inputs[3].value = String(numPhases);
          await parent.updateComplete;
          expect(parent.wizardUI.inputs[3].checkValidity()).to.be.true;
        })
      );
    })

Summary: The test verifies that setting the value of `wizardUI.inputs[3]` to a string representation of an integer between 1 and 255 results in `checkValidity()` returning true.


test("fuzz emailAddressList w/ `sub`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await emailAddressList(sub);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 10,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `emailAddressList` should handle inputs without throwing unexpected errors, only allowing specific expected error messages.


it('rejects edition for invalid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(
          regexString(inverseRegExp.integer, 1),
          async nomFreq => {
            parent.wizardUI.inputs[3].value = nomFreq;
            await parent.updateComplete;
            expect(parent.wizardUI.inputs[3].checkValidity()).to.be.false;
          }
        )
      );
    })

Summary: Edition is rejected for invalid inputs that do not match the integer regular expression in the voltage-level editor wizard.


it('rejects edition for invalid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(
          regexString(inverseRegExp.decimal, 1),
          async voltage => {
            parent.wizardUI.inputs[4].value = voltage;
            await parent.updateComplete;
            expect(parent.wizardUI.inputs[4].checkValidity()).to.be.false;
          }
        )
      );
    })

Summary: Inputting non-decimal values into the voltage input field should result in validity checks failing.


test("fuzz emailAddressSelect w/ `id`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (id) => {
			try {
				await emailAddressSelect(sub, id);
			} catch (e) {
				catchError(id, e);
			}
		}),
		{
			numRuns: 10,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The function `emailAddressSelect` should handle various inputs, allowing execution without throwing unexpected errors, as captured by specified expected error messages.


Summary: The property ensures that only valid `name` inputs can successfully pass the validity check in the `wizardUI` input field.


test("fuzz emailAddressCreate w/ `sub`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await emailAddressCreate(sub, emailAddress);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 10,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `emailAddressCreate` handles various input types for `sub`, and only expected errors should occur, which are not logged.


Summary: `wizardUI` accepts only valid `desc` inputs that satisfy the specified regex pattern.


it('edits only for valid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(regexString(regExp.tName, 1), async name => {
          parent.wizardUI.inputs[1].value = name;
          await parent.updateComplete;
          expect(parent.wizardUI.inputs[0].checkValidity()).to.be.true;
        })
      );
    })

Summary: Editing should occur only when the inputs are valid according to specified conditions.


it('edits only for valid inputs', async () => {
      await fc.assert(
        fc.asyncProperty(regexString(regExp.desc), async desc => {
          parent.wizardUI.inputs[2].value = desc;
          await parent.updateComplete;
          expect(parent.wizardUI.inputs[1].checkValidity()).to.be.true;
        })
      );
    })

Summary: Editing is performed only when the input for `wizardUI.inputs[2]` is valid, ensuring `wizardUI.inputs[1]` passes validity checks.


Summary: Editing is enabled only when input names match the specified regular expression pattern and are valid.


test("fuzz emailAddressCreate w/ `username`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (username) => {
			try {
				await emailAddressCreate(sub, username);
			} catch (e) {
				catchError(username, e);
			}
		}),
		{
			numRuns: 10,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `emailAddressCreate` handles exceptions appropriately, only ignoring specific expected errors during fuzz testing with arbitrary `username` values.


UnitTest.test('ShadowDom - SelectorFind.descendant', () => {
  if (SugarShadowDom.isSupported()) {
    fc.assert(fc.property(htmlBlockTagName(), htmlInlineTagName(), fc.hexaString(), (block, inline, text) => {
      withShadowElement((ss) => {
        const id = 'theid';
        const inner = SugarElement.fromHtml(`<${block}><p>hello<${inline} id="${id}">${text}</${inline}></p></${block}>`);
        Insert.append(ss, inner);

        const frog: SugarElement<Element> = SelectorFind.descendant(ss, `#${id}`).getOrDie('Element not found');
        Assert.eq('textcontent', text, frog.dom.textContent);
      });
    }));
  }
})

Summary: `SelectorFind.descendant` retrieves an element with a specific `id` from a shadow DOM, verifying that its text content matches the expected text.


UnitTest.test('All valid floats are valid', () => {
  fc.assert(fc.property(fc.oneof(
    // small to medium floats
    fc.float(),
    // big floats
    fc.tuple(fc.float(), fc.integer(-20, 20)).map(([ mantissa, exponent ]) => mantissa * Math.pow(10, exponent))
  ), (num) => {
    const parsed = Dimension.parse(num.toString(), [ 'empty' ]).getOrDie();
    Assert.eq('Number is unchanged by stringifying and parsing', num, parsed.value);
    Assert.eq('Unit is empty', '', parsed.unit);
    return true;
  }));
})

Summary: Valid floats, both small to medium and large with exponents, should remain unchanged and have an empty unit string after being stringified and parsed by `Dimension.parse`.


UnitTest.test('All valid integers are valid', () => {
  fc.assert(fc.property(fc.integer(), (num) => {
    const parsed = Dimension.parse(num.toString(), [ 'empty' ]).getOrDie();
    Assert.eq('Number is unchanged by stringifying and parsing', num, parsed.value);
    Assert.eq('Unit is empty', '', parsed.unit);
    return true;
  }));
})

Summary: Parsing a valid integer from its string representation should yield a dimension with an unchanged value and an empty unit.


test("fuzz emailAddressCreate w/ `emailAddress`", async () => {
	await fc.assert(
		fc.asyncProperty(fc.emailAddress(), async (emailAddress) => {
			try {
				await emailAddressCreate(sub, emailAddress);
			} catch (e) {
				catchError(emailAddress, e);
			}
		}),
		{
			numRuns: 10,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: Invoking `emailAddressCreate` with various email addresses should not produce unexpected errors outside the defined list: "400 Bad Request," "401 Unauthorized," "404 Not Found," "409 Conflict."


UnitTest.test('KAssert.eqError: success (reflexivity)', () => {
  fc.assert(fc.property(fc.integer(), (i) => {
    KAssert.eqError('eq', i, Result.error(i));
    KAssert.eqError('eq', i, Result.error(i), tBoom());
    KAssert.eqError('eq', i, Result.error(i), tBoom(), tNumber);
  }));
})

Summary: `KAssert.eqError` confirms that an integer and a `Result.error` containing the same integer are considered equivalent, using reflexivity.


test("fuzz accountLookup w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await accountLookup(sub);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The `accountLookup` function is tested to ensure it either executes or raises expected errors without causing unhandled exceptions across various inputs.


UnitTest.test('KAssert.eqError: failure', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('should throw if numbers differ #1', () => {
      KAssert.eqError('eq', a, Result.error(b));
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqError('eq', a, Result.error(b), tBoom());
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqError('eq', a, Result.error(b), tBoom(), tNumber);
    });
  }));

  fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
    Assert.throws('should throw if value #1', () => {
      KAssert.eqError('eq', i, Result.value(s));
    });
    Assert.throws('should throw if value #2', () => {
      KAssert.eqError('eq', i, Result.value(s), tBoom());
    });
    Assert.throws('should throw if value #3', () => {
      KAssert.eqError('eq', i, Result.value(s), tBoom(), tBoom());
    });
  }));
})

Summary: `KAssert.eqError` throws an error when comparing two different numbers or when comparing an integer with a string value, using various configurations.


test("fuzz accountUpdate w/ values", async () => {
	await fc.assert(
		fc.asyncProperty(fc.string(), async (values) => {
			try {
				await accountUpdate(sub, { name: values });
			} catch (e) {
				catchError(values, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The `accountUpdate` function should not throw unexpected errors when updating an account with string values for the `name` field.


Summary: `KAssert.eqError` throws an error when a number differs from a `Result.error` value, and when a number does not match a `Result.value` containing a string.


test("fuzz accountRemove w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await accountRemove(sub);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The `accountRemove` function should handle various input types without throwing unexpected errors, only allowing certain specified error messages.


test("fuzz accessTokenAuthenticate w/ username", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (username) => {
			try {
				await accessTokenAuthenticate(username, testSecret.value);
			} catch (e) {
				catchError(username, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `accessTokenAuthenticate` should handle various inputs for `username` without throwing unexpected errors, as filtered by `catchError`.


UnitTest.test('KAssert.eqValue: failure', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('should throw if numbers differ #1', () => {
      KAssert.eqValue('eq', a, Result.value(b));
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqValue('eq', a, Result.value(b), tNumber);
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqValue('eq', a, Result.value(b), tNumber, tBoom());
    });
  }));

  fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
    Assert.throws('should throw if error #1', () => {
      KAssert.eqValue('eq', i, Result.error(s));
    });
    Assert.throws('should throw if error #2', () => {
      KAssert.eqValue('eq', i, Result.error(s), tBoom());
    });
    Assert.throws('should throw if error #3', () => {
      KAssert.eqValue('eq', i, Result.error(s), tBoom(), tBoom());
    });
  }));
})

Summary: `KAssert.eqValue` should throw an error when comparing different numbers or when a result contains an error.


UnitTest.test('KAssert.eqResult: success', () => {
  fc.assert(fc.property(fc.integer(), (i) => {
    KAssert.eqResult('eq', Result.value(i), Result.value(i));
    KAssert.eqResult('eq', Result.value(i), Result.value(i), tNumber);
    KAssert.eqResult('eq', Result.value(i), Result.value(i), tNumber, tBoom());
    KAssert.eqResult('eq', Result.error(i), Result.error(i));
    KAssert.eqResult('eq', Result.error(i), Result.error(i), tBoom());
    KAssert.eqResult('eq', Result.error(i), Result.error(i), tBoom(), tNumber);
  }));
})

Summary: `KAssert.eqResult` checks that two `Result.value` or two `Result.error` objects with identical integer values are considered equal, optionally using additional transformation functions.


test("fuzz accessTokenAuthenticate w/ secret", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (secret) => {
			try {
				await accessTokenAuthenticate(username, secret);
			} catch (e) {
				catchError(secret, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `accessTokenAuthenticate` should handle any type of input for the `secret` parameter without unexpected errors, only allowing specific error messages.


UnitTest.test('KAssert.eqResult: fail', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('value(a) != (value(!a)) #1', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b));
    });
    Assert.throws('value(a) != (value(!a)) #2', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b), tNumber);
    });
    Assert.throws('value(a) != (value(!a)) #2', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b), tNumber, tBoom());
    });
  }));

  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('error(a) != (error(!a)) #1', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b));
    });
    Assert.throws('error(a) != (error(!a)) #2', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b), tBoom());
    });
    Assert.throws('result(a) != (result(!a)) #2', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b), tBoom(), tNumber);
    });
  }));

  fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
    Assert.throws('value != error #1', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s));
    });
    Assert.throws('value != error #2', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s), tBoom());
    });
    Assert.throws('value != error #3', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s), tBoom());
    });

    Assert.throws('error != value #1', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s));
    });
    Assert.throws('error != value #2', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s), tBoom());
    });
    Assert.throws('error != value #3', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s), tBoom(), tBoom());
    });
  }));
})

Summary: `KAssert.eqResult` throws errors when comparing two different result values or when comparing result types (`value` vs `error`) across various scenarios.


Summary: Verifies that `KAssert.eqResult` correctly throws exceptions when comparing different `Result.value` or `Result.error` objects, as well as when comparing a `Result.value` with a `Result.error`.


test("fuzz accessTokenLookup w/ username", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (username) => {
			try {
				await accessTokenLookup(username);
			} catch (e) {
				catchError(username, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The `accessTokenLookup` function should handle any input for `username` without causing unexpected errors, only allowing specific known errors.


Summary: `KAssert.eqResult` throws an error when comparing differing `Result.value` or `Result.error` objects, or when comparing a `Result.value` to a `Result.error` and vice versa.


it('Check that if the filter always returns true, then everything is in "pass"', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      (arr) => {
        const output = Arr.partition(arr, Fun.always);
        assert.deepEqual(output.fail.length, 0);
        assert.deepEqual(output.pass, arr);
      }
    ));
  })

Summary: When the filter always returns true, all elements should be in the "pass" array, and the "fail" array should be empty.


test("fuzz accessTokenSelect w/ id", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (id) => {
			try {
				await accessTokenSelect(sub, id);
			} catch (e) {
				catchError(id, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `accessTokenSelect` is expected not to throw errors other than "400 Bad Request," "401 Unauthorized," "404 Not Found," or "409 Conflict" when executed with any value as `id`.


test("fuzz accessTokenCreate w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await accessTokenCreate(sub);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The function `accessTokenCreate` should not throw unexpected errors when invoked with arbitrary input, handling only specified error messages.


it('Check that everything in fail fails predicate and everything in pass passes predicate', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      (arr) => {
        const predicate = (x: number) => x % 3 === 0;
        const output = Arr.partition(arr, predicate);
        return Arr.forall(output.fail, (x) => !predicate(x)) && Arr.forall(output.pass, predicate);
      }
    ));
  })

Summary: The partitioned arrays should ensure that elements in the `fail` array do not satisfy the predicate, while elements in the `pass` array do.


test("fuzz accessTokenCreate w/ values", async () => {
	await fc.assert(
		fc.asyncProperty(fc.string(), async (values) => {
			try {
				await accessTokenCreate(sub, { name: values });
			} catch (e) {
				catchError(values, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The `accessTokenCreate` function processes strings without causing errors, unless they match specific error messages defined by `catchError`.


it('inductive case', () => {
    fc.assert(fc.property(
      fc.dictionary(fc.asciiString(1, 30), fc.integer()),
      fc.asciiString(1, 30),
      fc.integer(),
      (obj, k, v) => {
        const objWithoutK = Obj.filter(obj, (x, i) => i !== k);
        assert.deepEqual(Obj.size({ [k]: v, ...objWithoutK }), Obj.size(objWithoutK) + 1);
      }), {
      numRuns: 5000
    });
  })

Summary: The size of an object increases by one when adding a new key-value pair, provided the key does not already exist in the object.


it('only returns elements that are in the input', () => {
    fc.assert(fc.property(fc.dictionary(fc.asciiString(), fc.integer()), (obj) => {
      const keys = Obj.keys(obj);
      return Arr.forall(keys, (k) => obj.hasOwnProperty(k));
    }));
  })

Summary: `Obj.keys` only returns keys that exist in the input object.


it('Every odd element matches delimiter', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      fc.integer(),
      (arr, delimiter) => {
        const actual = Jam.intersperse(arr, delimiter);
        return Arr.forall(actual, (x, i) => i % 2 === 1 ? x === delimiter : true);
      }
    ));
  })

Summary: Every odd-indexed element in the result of `Jam.intersperse` matches the given delimiter.


it('Filtering out delimiters (assuming different type to array to avoid removing original array) should equal original', () => {
    fc.assert(fc.property(
      fc.array(fc.nat()),
      arbNegativeInteger(),
      (arr, delimiter) => {
        const actual = Jam.intersperse(arr, delimiter);
        const filtered = Arr.filter(actual, (a) => a !== delimiter);
        assert.deepEqual(filtered, arr);
      }
    ));
  })

Summary: Filtering delimiters from an interspersed array should result in the original array.


test("fuzz accessTokenRemove w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await accessTokenRemove(sub, testSecret.id);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `accessTokenRemove` should not throw unhandled errors (other than specific expected ones) when removing an access token with any possible `sub` input.


it('Adjacent groups have different hashes, and everything in a group has the same hash', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      fc.func(fc.asciiString()),
      (xs, f) => {
        const groups = Arr.groupBy(xs, (x) => f(x));

        /* Properties about groups
         * 1. No two adjacent groups can have the same g(..) value
         * 2. Each group must have the same g(..) value
         */

        const hasEmptyGroups = Arr.exists(groups, (g) => g.length === 0);

        if (hasEmptyGroups) {
          assert.fail('Should not have empty groups');
        }
        // No consecutive groups should have the same result of g.
        const values = Arr.map(groups, (group) => {
          const first = f(group[0]);
          const mapped = Arr.map(group, (g) => f(g));

          const isSame = Arr.forall(mapped, (m) => m === first);
          if (!isSame) {
            assert.fail('Not everything in a group has the same g(..) value');
          }
          return first;
        });

        const hasSameGroup = Arr.exists(values, (v, i) => i > 0 ? values[i - 1] === values[i] : false);

        if (hasSameGroup) {
          assert.fail('A group is next to another group with the same g(..) value');
        }
        return true;
      }
    ));
  })

Summary: Adjacent groups must have different hash values, and within a group, all elements must share the same hash value.


test("fuzz webauthnAuthenticate w/ username", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (username) => {
			try {
				await webauthnAuthenticate(username, testSecret.value);
			} catch (e) {
				catchError(username, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `webauthnAuthenticate` should handle any input for `username` without throwing unexpected errors, only allowing specific expected errors to pass silently.


it('Flattening groups equals the original array', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      fc.func(fc.string()),
      (xs, f) => {
        const groups = Arr.groupBy(xs, (x) => f(x));

        const output = Arr.flatten(groups);
        assert.deepEqual(output, xs);
      }
    ));
  })

Summary: Flattening the groups formed by `Arr.groupBy` on an integer array should result in the original array.


it('forall of a non-empty array with a predicate that always returns false is false', () => {
    fc.assert(fc.property(
      fc.array(fc.integer(), 1, 30),
      (xs) => {
        assert.isFalse(Arr.forall(xs, Fun.never));
      }
    ));
  })

Summary: `Arr.forall` returns false when applied to a non-empty array with a predicate that always returns false.


it('foldl concat [ ] xs === reverse(xs)', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      (arr) => {
        const output = Arr.foldl(arr, (b: number[], a: number) => [ a ].concat(b), []);
        assert.deepEqual(output, Arr.reverse(arr));
      }
    ));
  })

Summary: Folding a list from the left using concatenation should produce the reverse of the list.


it('foldr concat [ ] xs === xs', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      (arr) => {
        const output = Arr.foldr(arr, (b: number[], a: number) => [ a ].concat(b), []);
        assert.deepEqual(output, arr);
      }
    ));
  })

Summary: Folding right over an array with the concat operation and an empty array should return the original array.


test("fuzz webauthnAuthenticate w/ secret", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (secret) => {
			try {
				await webauthnAuthenticate(username, secret);
			} catch (e) {
				catchError(secret, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `webauthnAuthenticate` handles various unexpected inputs for `secret` without resulting in unhandled errors, only allowing specific expected error messages.


it('is consistent with chunking', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      fc.integer(1, 5),
      (arr, chunkSize) => {
        const chunks = Arr.chunk(arr, chunkSize);
        const bound = Arr.flatten(chunks);
        assert.deepEqual(bound, arr);
      }
    ));
  })

Summary: Chunking an array and then flattening it should return the original array.


it('is consistent with find', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (arr) => {
      const pred = (x: number) => x % 5 === 0;
      assertOptional(Arr.findIndex(arr, pred).map((x) => arr[x]), Arr.find(arr, pred));
    }));
  })

Summary: `Arr.findIndex` produces consistent results with `Arr.find` when applied to arrays of integers with a predicate for multiples of 5.


test("fuzz webauthnList w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await webauthnList(sub);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `webauthnList` should handle or produce expected errors for a wide range of `sub` inputs without unexpected exceptions.


it('Element exists in middle of array', () => {
    fc.assert(fc.property(fc.array(fc.integer()), fc.integer(), fc.array(fc.integer()), (prefix, element, suffix) => {
      const arr2 = Arr.flatten([ prefix, [ element ], suffix ]);
      assert.isTrue(Arr.exists(arr2, eqc(element)));
    }));
  })

Summary: An element exists in the middle of a flattened array composed of prefix, the element itself, and suffix arrays.


it('Element does not exist in empty array', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (i) => {
      assert.isFalse(Arr.exists([], eqc(i)));
    }));
  })

Summary: `Arr.exists` returns false when checking for any element in an empty array.


it('Element exists in non-empty array when predicate always returns true', () => {
    fc.assert(fc.property(fc.array(fc.integer()), fc.integer(), (xs, x) => {
      const arr = Arr.flatten([ xs, [ x ]]);
      assert.isTrue(Arr.exists(arr, always));
    }));
  })

Summary: An element exists in a non-empty array if a predicate always returns true.


test("fuzz webauthnRemove w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await webauthnRemove(sub, testSecret.id);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The `webauthnRemove` function should not throw unexpected errors when called with various `sub` values.


it('child transactions should always have a parent_id', async () => {
    await fc.assert(
      fc
        .asyncProperty(fc.array(messageArb, { maxLength: 100 }), async msgs => {
          const tracer = execTracer();
          tracer.start();
          const cleanup = addSyncListener((oldValues, newValues) => {
            const ts = newValues.get('transactions') as Map<
              string,
              { isChild: number; parent_id: string | null; id: string }
            >;
            if (
              ts &&
              [...ts.values()].find(
                t =>
                  t.isChild === 1 && t.parent_id == null && t.id.includes('/'),
              )
            ) {
            } else {
              tracer.event('applied');
            }
          });

          await sendMessages(msgs);
          await tracer.expect('applied');

          const transactions = await db.all('SELECT * FROM transactions', []);
          for (const trans of transactions) {
            const transMsgs = msgs
              .filter(msg => msg.row === trans.id)
              .sort((m1, m2) => {
                const t1 = m1.timestamp.toString();
                const t2 = m2.timestamp.toString();
                if (t1 < t2) {
                  return 1;
                } else if (t1 > t2) {
                  return -1;
                }
                return 0;
              });
            const msg = transMsgs.find(m => m.column === 'parent_id');

            if (
              trans.isChild === 1 &&
              trans.id.includes('/') &&
              (msg == null || msg.value == null)
            ) {
              // This is a child transaction didn't have a `parent_id`
              // set in the messages. It should have gotten set from
              // the `id`
              const [parentId] = trans.id.split('/');
              expect(parentId).not.toBe(null);
              expect(trans.parent_id).toBe(parentId);
            } else if (msg) {
              // At least one message set `parent_id`
              expect(trans.parent_id).toBe(msg.value);
            } else {
              // `parent_id` should never have been set
              expect(trans.parent_id).toBe(null);
            }
          }

          cleanup();
          tracer.end();
        })
        .beforeEach(() => {
          return db.execQuery(`DELETE FROM transactions`);
        }),
    );
  })

Summary: Child transactions must always have a `parent_id`, which is either set based on the transaction's `id` or populated from messages.


test("fuzz recoveryCodesAuthenticate w/ username", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (username) => {
			try {
				await recoveryCodesAuthenticate(username, testSecret.value);
			} catch (e) {
				catchError(username, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The test checks that `recoveryCodesAuthenticate`, when called with various `username` inputs, only throws expected errors such as "400 Bad Request", "401 Unauthorized", "404 Not Found", or "409 Conflict".


it('aggregate queries work with `splits: grouped`', async () => {
    const payeeIds = ['payee1', 'payee2', 'payee3', 'payee4', 'payee5'];

    await fc.assert(
      fc
        .asyncProperty(
          arbs.makeTransactionArray({ splitFreq: 2, payeeIds, maxLength: 100 }),
          async arr => {
            await insertTransactions(arr, payeeIds);

            const aggQuery = q('transactions')
              .filter({
                $or: [{ amount: { $lt: -5 } }, { amount: { $gt: -2 } }],
                'payee.name': { $gt: '' },
              })
              .options({ splits: 'grouped' })
              .calculate({ $sum: '$amount' });

            const { data } = await runQuery(aggQuery.serialize());

            const sum = aliveTransactions(arr).reduce((sum, trans) => {
              const amount = trans.amount || 0;
              const matched =
                (amount < -5 || amount > -2) && trans.payee != null;
              if (!trans.tombstone && !trans.is_parent && matched) {
                return sum + amount;
              }
              return sum;
            }, 0);

            expect(data).toBe(sum);
          },
        )
        .beforeEach(() => {
          setClock(null);
          setSyncingMode('import');
          return db.execQuery(`
            DELETE FROM transactions;
            DELETE FROM payees;
            DELETE FROM payee_mapping;
          `);
        }),
    );
  })

Summary: Aggregate queries with `splits: grouped` option should accurately calculate the sum of amounts from alive, non-tombstoned transactions filtered by specified criteria.


test("fuzz recoveryCodesAuthenticate w/ secret", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (secret) => {
			try {
				await recoveryCodesAuthenticate(username, secret);
			} catch (e) {
				catchError(secret, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `recoveryCodesAuthenticate` handles various inputs for `secret` without throwing unexpected errors.


test("fuzz recoveryCodesCount w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await recoveryCodesCount(sub);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: The `recoveryCodesCount` function executes without letting unexpected errors pass silently for any given input.


Summary: Child transactions must always have a valid `parent_id`, either set by message or derived from their `id`, with no `parent_id` for non-child transactions unless specified by a message.


test("fuzz recoveryCodesRemove w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await recoveryCodesRemove(sub, testSecret.id);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `recoveryCodesRemove` should handle various inputs without causing unexpected errors, logging only when encountering non-expected error messages.


test("fuzz accountUsernameExists w/ username", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (username) => {
			try {
				await accountUsernameExists(username);
			} catch (e) {
				catchError(username, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `accountUsernameExists` should handle any input for `username`, with errors limited to expected HTTP statuses.


test("fuzz accountUsernameLookup w/ username", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (username) => {
			try {
				await accountUsernameLookup(username);
			} catch (e) {
				catchError(username, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `accountUsernameLookup` should handle any input without causing errors outside expected server-related errors.


it('queries with `splits: inline` returns only non-parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 20,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await runQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'inline' })
              .serialize(),
          );

          expect(data.filter(t => t.is_parent).length).toBe(0);
          expect(data.filter(t => t.tombstone).length).toBe(0);

          const { data: defaultData } = await runQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .serialize(),
          );

          // inline should be the default
          expect(defaultData).toEqual(data);
        },
      ),
      { numRuns: 50 },
    );
  })

Summary: Queries using `splits: inline` should return only non-parent transactions, ensuring results are consistent with default query settings.


it('queries with `splits: none` returns only parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 8,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await runQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'none' })
              .serialize(),
          );

          expect(data.filter(t => t.is_child).length).toBe(0);
        },
      ),
      { numRuns: 50 },
    );
  })

Summary: Queries with `splits: none` should return only parent transactions, ensuring no child transactions are included in the results.


test("fuzz accountUsernameUpdate w/ sub", async () => {
	await fc.assert(
		fc.asyncProperty(fc.anything(), async (sub) => {
			try {
				await accountUsernameUpdate(sub, username);
			} catch (e) {
				catchError(sub, e);
			}
		}),
		{
			numRuns: 100_000,
			verbose: 2,
			examples: [],
		},
	);
})

Summary: `accountUsernameUpdate` function should handle any input without throwing unexpected errors, allowing for certain specified errors.


Summary: Aggregate queries with `splits: grouped` should correctly calculate the sum of transaction amounts that meet specific conditions, matching the expected result based on alive transactions.


Summary: Child transactions must always have a `parent_id` set, either derived from the transaction ID for child transactions with IDs containing '/', or specified directly in the message.


Summary: Queries with `splits: inline` should return only non-parent transactions without tombstone entries, identical to the default query result.


Summary: The property should ensure that querying transactions with the option `splits: none` returns only parent transactions, excluding any child transactions.


Summary: Aggregate queries with the option `splits: grouped` should correctly calculate the sum of `amount` for transactions that are alive, not marked as tombstones or parents, and meet specified filter conditions.


it('child transactions should always have a parent_id', async () => {
    await fc.assert(
      fc
        .asyncProperty(fc.array(messageArb, { maxLength: 100 }), async msgs => {
          const tracer = execTracer();
          tracer.start();
          const cleanup = addSyncListener((oldValues, newValues) => {
            const ts = newValues.get('transactions') as Map<
              string,
              { isChild: number; parent_id: string | null; id: string }
            >;
            if (
              ts &&
              [...ts.values()].find(
                t =>
                  t.isChild === 1 && t.parent_id == null && t.id.includes('/'),
              )
            ) {
            } else {
              tracer.event('applied');
            }
          });

          await sendMessages(msgs);
          await tracer.expect('applied');

          const transactions = await db.all<db.DbTransaction>(
            'SELECT * FROM transactions',
            [],
          );
          for (const trans of transactions) {
            const transMsgs = msgs
              .filter(msg => msg.row === trans.id)
              .sort((m1, m2) => {
                const t1 = m1.timestamp.toString();
                const t2 = m2.timestamp.toString();
                if (t1 < t2) {
                  return 1;
                } else if (t1 > t2) {
                  return -1;
                }
                return 0;
              });
            const msg = transMsgs.find(m => m.column === 'parent_id');

            if (
              trans.isChild === 1 &&
              trans.id.includes('/') &&
              (msg == null || msg.value == null)
            ) {
              // This is a child transaction didn't have a `parent_id`
              // set in the messages. It should have gotten set from
              // the `id`
              const [parentId] = trans.id.split('/');
              expect(parentId).not.toBe(null);
              expect(trans.parent_id).toBe(parentId);
            } else if (msg) {
              // At least one message set `parent_id`
              expect(trans.parent_id).toBe(msg.value);
            } else {
              // `parent_id` should never have been set
              expect(trans.parent_id).toBe(null);
            }
          }

          cleanup();
          tracer.end();
        })
        .beforeEach(() => {
          return db.execQuery(`DELETE FROM transactions`);
        }),
    );
  })

Summary: Child transactions should always have an associated `parent_id`, either derived from their `id` or set from messages, ensuring the consistency of transaction relationships in the database.


it('queries with `splits: inline` returns only non-parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 20,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await aqlQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'inline' })
              .serialize(),
          );

          expect(data.filter(t => t.is_parent).length).toBe(0);
          expect(data.filter(t => t.tombstone).length).toBe(0);

          const { data: defaultData } = await aqlQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .serialize(),
          );

          // inline should be the default
          expect(defaultData).toEqual(data);
        },
      ),
      { numRuns: 50 },
    );
  })

Summary: Queries with `splits: inline` should return transactions excluding parents and tombstones, and produce results equal to the default query configuration.


it('accepts valid usernames (4–31 chars, no leading/trailing whitespace)', () => {
		fc.assert(
			fc.property(
				fc.string({ minLength: 4, maxLength: 31 }).filter((s) => s.trim() === s && s.length > 0),
				(username) => {
					expect(verifyUsernameInput(username)).toBe(true);
				}
			),
			{ numRuns: 200 }
		);
	})

Summary: `verifyUsernameInput` accepts usernames that are between 4 and 31 characters long, with no leading or trailing whitespace.


it('queries with `splits: none` returns only parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 8,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await aqlQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'none' })
              .serialize(),
          );

          expect(data.filter(t => t.is_child).length).toBe(0);
        },
      ),
      { numRuns: 50 },
    );
  })

Summary: Queries with the option `splits: none` should return only parent transactions and exclude child transactions.


describe('transaction executors', () => {
  it('queries with `splits: inline` returns only non-parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 20,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await aqlQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'inline' })
              .serialize(),
          );

          expect(data.filter(t => t.is_parent).length).toBe(0);
          expect(data.filter(t => t.tombstone).length).toBe(0);

          const { data: defaultData } = await aqlQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .serialize(),
          );

          // inline should be the default
          expect(defaultData).toEqual(data);
        },
      ),
      { numRuns: 50 },
    );
  });

  it('queries with `splits: none` returns only parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 8,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await aqlQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'none' })
              .serialize(),
          );

          expect(data.filter(t => t.is_child).length).toBe(0);
        },
      ),
      { numRuns: 50 },
    );
  });

  it('aggregate queries work with `splits: grouped`', async () => {
    const payeeIds = ['payee1', 'payee2', 'payee3', 'payee4', 'payee5'];

    await fc.assert(
      fc
        .asyncProperty(
          arbs.makeTransactionArray({ splitFreq: 2, payeeIds, maxLength: 100 }),
          async arr => {
            await insertTransactions(arr, payeeIds);

            const aggQuery = q('transactions')
              .filter({
                $or: [{ amount: { $lt: -5 } }, { amount: { $gt: -2 } }],
                'payee.name': { $gt: '' },
              })
              .options({ splits: 'grouped' })
              .calculate({ $sum: '$amount' });

            const { data } = await aqlQuery(aggQuery.serialize());

            const sum = aliveTransactions(arr).reduce((sum, trans) => {
              const amount = trans.amount || 0;
              const matched =
                (amount < -5 || amount > -2) && trans.payee != null;
              if (!trans.tombstone && !trans.is_parent && matched) {
                return sum + amount;
              }
              return sum;
            }, 0);

            expect(data).toBe(sum);
          },
        )
        .beforeEach(() => {
          setClock(null);
          setSyncingMode('import');
          return db.execQuery(`
            DELETE FROM transactions;
            DELETE FROM payees;
            DELETE FROM payee_mapping;
          `);
        }),
    );
  }, 20_000);

  function runTest(makeQuery) {
    const payeeIds = ['payee1', 'payee2', 'payee3', 'payee4', 'payee5'];

    async function check(arr) {
      const orderFields = ['payee.name', 'amount', 'id'];

      // Insert transactions and get a list of all the alive
      // ones to make it easier to check the data later (don't
      // have to always be filtering out dead ones)
      await insertTransactions(arr, payeeIds);
      const allTransactions = aliveTransactions(arr);

      // Query time
      const { query, expectedIds, expectedMatchedIds } = makeQuery(arr);

      // First to a query without order to make sure the default
      // order works
      const { data: defaultOrderData } = await aqlQuery(query.serialize());
      expectTransactionOrder(defaultOrderData);
      expect(new Set(defaultOrderData.map(t => t.id))).toEqual(expectedIds);

      // Now do the full test, and add a custom order to make
      // sure that doesn't effect anything
      const orderedQuery = query.orderBy(orderFields);
      const { data } = await aqlQuery(orderedQuery.serialize());
      expect(new Set(data.map(t => t.id))).toEqual(expectedIds);

      // Validate paging and ordering
      await expectPagedData(orderedQuery, arr.length, data);
      expectTransactionOrder(data, orderFields);

      const matchedIds = new Set();

      // Check that all the subtransactions were returned
      for (const trans of data) {
        expect(trans.tombstone).toBe(false);

        if (expectedMatchedIds) {
          if (!trans._unmatched) {
            expect(expectedMatchedIds.has(trans.id)).toBe(true);
            matchedIds.add(trans.id);
          } else {
            expect(expectedMatchedIds.has(trans.id)).not.toBe(true);
          }
        }

        if (trans.is_parent) {
          // Parent transactions should never have a category
          expect(trans.category).toBe(null);

          expect(trans.subtransactions.length).toBe(
            allTransactions.filter(t => t.parent_id === trans.id).length,
          );

          // Subtransactions should be ordered as well
          expectTransactionOrder(trans.subtransactions, orderFields);

          trans.subtransactions.forEach(subtrans => {
            expect(subtrans.tombstone).toBe(false);

            if (expectedMatchedIds) {
              if (!subtrans._unmatched) {
                expect(expectedMatchedIds.has(subtrans.id)).toBe(true);
                matchedIds.add(subtrans.id);
              } else {
                expect(expectedMatchedIds.has(subtrans.id)).not.toBe(true);
              }
            }
          });
        }
      }

      if (expectedMatchedIds) {
        // Check that transactions that should be matched are
        // marked as such
        expect(matchedIds).toEqual(expectedMatchedIds);
      }
    }

    return fc.assert(
      fc
        .asyncProperty(
          arbs.makeTransactionArray({
            splitFreq: 0.1,
            payeeIds,
            maxLength: 100,
          }),
          check,
        )
        .beforeEach(() => {
          setClock(null);
          setSyncingMode('import');
          return db.execQuery(`
            DELETE FROM transactions;
            DELETE FROM payees;
            DELETE FROM payee_mapping;
          `);
        }),
      { numRuns: 300 },
    );
  }

  it('queries the correct transactions without filters', async () => {
    return runTest(arr => {
      const expectedIds = new Set(
        arr.filter(t => !t.tombstone && !t.is_child).map(t => t.id),
      );

      // Even though we're applying some filters, these are always
      // guaranteed to return the full split transaction so they
      // should take the optimized path
      const happyQuery = q('transactions')
        .filter({
          date: { $gt: '2017-01-01' },
        })
        .options({ splits: 'grouped' })
        .select(['*', 'payee.name']);

      // Make sure it's actually taking the happy path
      expect(isHappyPathQuery(happyQuery.serialize())).toBe(true);

      return {
        expectedIds,
        query: happyQuery,
      };
    });
  }, 20_000);

  it(`queries the correct transactions with a filter`, async () => {
    return runTest(arr => {
      const expectedIds = new Set();

      // let parents = toGroup(
      //   arr.filter(t => t.is_parent),
      //   new Map(Object.entries(groupById(arr.filter(t => t.parent_id))))
      // );

      const parents = groupById(arr.filter(t => t.is_parent && !t.tombstone));
      const matched = new Set();

      // Pick out some ids to query
      let ids = arr.reduce((ids, trans, idx) => {
        if (idx % 2 === 0) {
          const amount = trans.amount == null ? 0 : trans.amount;
          const matches = (amount < -2 || amount > -1) && trans.payee > '';

          if (matches && isAlive(trans, parents)) {
            expectedIds.add(trans.parent_id || trans.id);
            matched.add(trans.id);
          }

          ids.push(trans.id);
        }

        return ids;
      }, []);

      // Because why not? It should deduplicate them
      ids = repeat(ids, 100);

      const unhappyQuery = q('transactions')
        .filter({
          id: [{ $oneof: ids }],
          payee: { $gt: '' },
          $or: [{ amount: { $lt: -2 } }, { amount: { $gt: -1 } }],
        })
        .options({ splits: 'grouped' })
        .select(['*', 'payee.name'])
        // Using this because we want `payee` to have ids for the above
        // filter regardless if it points to a dead one or not
        .withoutValidatedRefs();

      expect(isHappyPathQuery(unhappyQuery.serialize())).toBe(false);

      return {
        expectedIds,
        expectedMatchedIds: matched,
        query: unhappyQuery,
      };
    });
  }, 20_000);
})

insertTransactions aliveTransactions expectTransactionOrder expectPagedData isAlive repeat

Summary: The property should ensure different query options (`inline`, `none`, `grouped`) correctly handle parent and child transactions, filtering them based on attributes such as tombstones, and verifying aggregation calculations, order consistency, and matching expected transaction IDs across pages.


test('compare test framework to real framework', () => {
  // Generate a tree of TestConditions using fast-check
  fc.assert(
    fc.property(fc.integer({min: 1, max: 20}), numConditions => {
      const conditions: TestCondition[] = fc
        .sample(fc.boolean(), numConditions)
        .map(
          value =>
            ({
              type: 'simple',
              right: {value},
            }) as const,
        );

      const pivots = conditions.map(
        () => fc.sample(fc.integer({min: 0, max: 100}), 1)[0] > 50,
      );

      const expected = conditions.reduce((acc, value, i) => {
        if (acc === undefined) {
          return value;
        }
        return pivots[i] ? simpleAnd(acc, value) : simpleOr(acc, value);
      });

      const actualConditions = conditions.map(convertTestCondition);
      const actual = dnf(
        actualConditions.reduce((acc, value, i) => {
          if (acc === undefined) {
            return value;
          }
          return pivots[i] ? and(value, acc) : or(value, acc);
        }),
      );

      expect(evaluate(actual as TestCondition)).toBe(evaluate(expected));

      // check that the real framework produced a DNF
      // console.log(toStr(actual));
      if (actual.type === 'and') {
        // all conditions should be simple as nothing can nest
        // under an `AND` in DNF
        expect(actual.conditions.every(c => c.type === 'simple')).toBe(true);
      } else if (actual.type === 'or') {
        // below an or can only be `ands` or `simple` conditions.
        expect(
          actual.conditions.every(c => c.type === 'and' || c.type === 'simple'),
        ).toBe(true);
        expect(
          actual.conditions
            .filter(c => c.type === 'and')
            .every(c =>
              // all conditions must be simple as nothing can nest
              // under an `AND` in DNF
              c.conditions.every(c => c.type === 'simple'),
            ),
        ).toBe(true);
      }
    }),
  );

  function convertTestCondition(c: TestCondition): Condition {
    assert(c.type === 'simple');
    return {
      type: 'simple',
      right: {
        type: 'literal',
        value: c.right.value,
      },
      op: '=',
      left: {
        type: 'column',
        name: 'n/a',
      },
    };
  }
})

Summary: Evaluates whether a tree of `TestConditions` constructed with logical `and` and `or` operations matches the expected Disjunctive Normal Form (DNF), ensuring each condition's structure and evaluation result are correct.


test('encode/decodeSecProtocols round-trip', () => {
  fc.assert(
    fc.property(
      fc.record({
        initConnectionMessage: fc.tuple(
          fc.constant<'initConnection'>('initConnection'),
          fc.record(
            {
              desiredQueriesPatch: fc.array(
                fc.oneof(
                  fc.record(
                    {
                      op: fc.constant<'put'>('put'),
                      hash: fc.string(),
                      ast: fc.constant({
                        table: 'table',
                      }),
                      ttl: fc.option(
                        fc.double({
                          noDefaultInfinity: true,
                          noNaN: true,
                          min: 0,
                        }),
                        {nil: undefined},
                      ),
                    },
                    {requiredKeys: ['op', 'hash', 'ast']},
                  ),
                  fc.record({
                    op: fc.constant<'del'>('del'),
                    hash: fc.string(),
                  }),
                ),
              ),
              deleted: fc.record(
                {
                  clientIDs: fc.array(fc.string()),
                  clientGroupIDs: fc.array(fc.string()),
                },
                {requiredKeys: []},
              ),
            },
            {requiredKeys: ['desiredQueriesPatch']},
          ),
        ),
        authToken: fc.option(
          fc.stringOf(
            fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789-_.'),
          ),
          {nil: undefined},
        ),
      }),
      ({initConnectionMessage, authToken}) => {
        const encoded = encodeSecProtocols(initConnectionMessage, authToken);
        const {
          initConnectionMessage: decodedInitConnectionMessage,
          authToken: decodedAuthToken,
        } = decodeSecProtocols(encoded);
        expect(decodedInitConnectionMessage).toEqual(initConnectionMessage);
        expect(decodedAuthToken).toEqual(authToken);
      },
    ),
  );
})

Summary: The encode and decode functions for `SecProtocols` should maintain data consistency, ensuring that the original `initConnectionMessage` and `authToken` can be reconstructed without loss after a round-trip transformation.


it('cell(x).get() === x', () => {
    fc.assert(fc.property(fc.integer(), (i) => {
      const cell = Cell(i);
      assert.equal(cell.get(), i);
    }));
  })

Summary: The `Cell` object, when initialized with an integer `x`, should return `x` when the `get` method is called.


it('cell.get() === last set call', () => {
    fc.assert(fc.property(fc.integer(), fc.integer(), fc.integer(), (a, b, c) => {
      const cell = Cell(a);
      assert.equal(cell.get(), a);
      cell.set(b);
      assert.equal(cell.get(), b);
      cell.set(c);
      assert.equal(cell.get(), c);
    }));
  })

Summary: A `Cell` instance should return the most recent value set using `set()` when retrieved with `get()`.


it('Error is thrown if not all arguments are supplied', () => {
    fc.assert(fc.property(arbAdt, fc.array(arbKeys, 1, 40), (subject, exclusions) => {
      const original = Arr.filter(allKeys, (k) => !Arr.contains(exclusions, k));

      try {
        const branches = Arr.mapToObject(original, () => Fun.identity);
        subject.match(branches);
        return false;
      } catch (err: any) {
        return err.message.indexOf('nothing') > -1;
      }
    }));
  })

Summary: An error should be thrown when not all required arguments are supplied to the `match` function, and this error message should contain the word 'nothing'.


it('adt.nothing.match should pass [ ]', () => {
    fc.assert(fc.property(arbNothing, (subject) => {
      const contents = subject.match({
        nothing: record,
        unknown: Fun.die('should not be unknown'),
        exact: Fun.die('should not be exact')
      });
      assert.deepEqual(contents, []);
    }));
  })

Summary: `adt.nothing.match` should return an empty array when matched with `nothing`, avoiding other cases like `unknown` or `exact`.


it('adt.nothing.match should be same as fold', () => {
    fc.assert(fc.property(arbNothing, (subject) => {
      const matched = subject.match({
        nothing: record,
        unknown: Fun.die('should not be unknown'),
        exact: Fun.die('should not be exact')
      });

      const folded = subject.fold(record, Fun.die('should not be unknown'), Fun.die('should not be exact'));
      assert.deepEqual(folded, matched);
    }));
  })

Summary: Matching with `adt.nothing` should yield the same result as folding with the same function.


it('adt.unknown.match should pass 1 parameter: [ guesses ]', () => {
    fc.assert(fc.property(arbUnknown, (subject) => {
      const contents = subject.match({
        nothing: Fun.die('should not be nothing'),
        unknown: record,
        exact: Fun.die('should not be exact')
      });
      assert.deepEqual(contents.length, 1);
    }));
  })

Summary: `adt.unknown.match` should result in `unknown` being the only case receiving one parameter with the `guesses` array.


it('adt.unknown.match should be same as fold', () => {
    fc.assert(fc.property(arbUnknown, (subject) => {
      const matched = subject.match({
        nothing: Fun.die('should not be nothing'),
        unknown: record,
        exact: Fun.die('should not be exact')
      });

      const folded = subject.fold(Fun.die('should not be nothing'), record, Fun.die('should not be exact'));
      assert.deepEqual(folded, matched);
    }));
  })

Summary: `subject.match` with `unknown` and `subject.fold` using the same function should produce equivalent outcomes.


it('adt.exact.match should pass 2 parameters [ value, precision ]', () => {
    fc.assert(fc.property(arbExact, (subject) => {
      const contents = subject.match({
        nothing: Fun.die('should not be nothing'),
        unknown: Fun.die('should not be unknown'),
        exact: record
      });
      assert.deepEqual(contents.length, 2);
    }));
  })

Summary: `adt.exact.match` requires two parameters, `value` and `precision`, and the test ensures `contents` from matching contains exactly two elements.


it('adt.match must have the right arguments, not just the right number', () => {
    fc.assert(fc.property(arbAdt, (subject) => {
      try {
        subject.match({
          not: Fun.identity,
          the: Fun.identity,
          right: Fun.identity
        });
        return false;
      } catch (err: any) {
        return err.message.indexOf('nothing') > -1;
      }
    }));
  })

Summary: The test ensures that `adt.match` throws an error containing the message "nothing" if the match function is provided with arguments that are incorrect, rather than merely having the correct number of arguments.


it('rightTrim(s + whitespace) === rightTrim(s)', () => {
    fc.assert(fc.property(
      fc.string(),
      (s) => {
        assert.equal(Strings.rTrim(s), Strings.rTrim(s + ' '));
      }
    ));
  })

Summary: `Strings.rTrim` produces the same result for a string whether or not it ends with additional whitespace.


it('trim(whitespace + s) === trim(s)', () => {
    fc.assert(fc.property(
      fc.string(),
      (s) => {
        assert.equal(Strings.trim(s), Strings.trim(' ' + s));
      }
    ));
  })

Summary: The `Strings.trim` function should return the same result for a string whether or not it is prefixed with whitespace.


it('trim(s + whitespace) === trim(s)', () => {
    fc.assert(fc.property(
      fc.string(),
      (s) => {
        assert.equal(Strings.trim(s), Strings.trim(s + ' '));
      }
    ));
  })

Summary: `Strings.trim` should produce the same result for a string whether or not it is followed by additional whitespace.


it('trim(whitespace + s + whitespace) === trim(s)', () => {
    fc.assert(fc.property(
      fc.string(),
      (s) => {
        assert.equal(Strings.trim(s), Strings.trim(' ' + s + ' '));
      }
    ));
  })

Summary: Trimming a string with surrounding whitespace should yield the same result as trimming the string without additional whitespace.


it('value(x) = value(x)', () => {
    fc.assert(fc.property(fc.integer(), (i) => {
      assertResult(Result.value<number, string>(i), Result.value<number, string>(i));
    }));
  })

Summary: The property asserts that creating `Result` instances with the same integer value results in instances that are considered equal.


it('error(x) = error(x)', () => {
    fc.assert(fc.property(fc.integer(), (i) => {
      assertResult(Result.error<string, number>(i), Result.error<string, number>(i));
    }));
  })

Summary: `Result.error` should produce identical error instances when given the same integer input.


it('value(a) != error(e)', () => {
    fc.assert(fc.property(fc.integer(), fc.string(), (a, e) => {
      assert.isFalse(tResult(tNumber, tString).eq(
        Result.value<number, string>(a),
        Result.error<number, string>(e)
      ));

      assert.isFalse(tResult(tNumber, tString).eq(
        Result.error<number, string>(e),
        Result.value<number, string>(a)
      ));
    }));
  })

Summary: `Result.value` and `Result.error` with the same generic parameters should not be considered equal.


it('(a = b) = (value(a) = value(b))', () => {
    fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {
      assert.equal(tResult(tNumber, tString).eq(
        Result.value<number, string>(a),
        Result.value<number, string>(b)
      ), a === b);
    }));
  })

Summary: The `eq` function of `tResult(tNumber, tString)` returns true if and only if the `Result.value` of two numbers are equal, ensuring consistency with the equivalence of the numbers themselves.


it('should handle all error types gracefully', async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.oneof(
            fc.constant('network-error'),
            fc.constant('timeout'),
            fc.constant('invalid-response'),
            fc.constant('rate-limit'),
            fc.constant('server-error'),
            fc.constant('auth-error')
          ),
          async (errorType) => {
            // Mock different error scenarios
            switch (errorType) {
              case 'network-error':
                mockFetch.mockRejectedValue(new Error('Network error'));
                break;
              case 'timeout':
                mockFetch.mockRejectedValue(new Error('Request timeout'));
                break;
              case 'invalid-response':
                mockFetch.mockResolvedValue({
                  ok: true,
                  json: async () => { throw new Error('Invalid JSON'); }
                } as Response);
                break;
              case 'rate-limit':
                mockFetch.mockResolvedValue({
                  ok: false,
                  status: 429,
                  json: async () => ({ error: { code: 'RATE_LIMIT_EXCEEDED', message: 'Rate limit exceeded' } })
                } as Response);
                break;
              case 'server-error':
                mockFetch.mockResolvedValue({
                  ok: false,
                  status: 500,
                  json: async () => ({ error: { code: 'INTERNAL_ERROR', message: 'Server error' } })
                } as Response);
                break;
              case 'auth-error':
                mockFetch.mockResolvedValue({
                  ok: false,
                  status: 401,
                  json: async () => ({ error: { code: 'UNAUTHORIZED', message: 'Invalid API key' } })
                } as Response);
                break;
            }

            const result = await adapter.search('test query')();

            // Error handling property: should always return Either, never throw
            expect(E.isRight(result) || E.isLeft(result)).toBe(true);

            // If Right, should indicate failure in response
            if (E.isRight(result)) {
              expect(result.right.success).toBe(false);
              expect(result.right.error).toBeDefined();
            }
          }
        ),
        { numRuns: 50 }
      );
    })

Summary: The adapter's `search` method should return an `Either` type, indicating failure, and not throw errors when handling various specified error scenarios.


it('(a = b) = (error(a) = error(b))', () => {
    fc.assert(fc.property(fc.string(), fc.string(), (a, b) => {
      assert.equal(tResult(tNumber, tString).eq(
        Result.error<number, string>(a),
        Result.error<number, string>(b)
      ), a === b);
    }));
  })

Summary: `Result.error<number, string>` instances are considered equal if and only if their string error messages are identical.


it('ResultInstances.pprint', () => {
    fc.assert(fc.property(fc.integer(), (i) => {
      assert.equal(Pprint.render(Result.value(i), tResult(tNumber, tString)), `Result.value(
  ${i}
)`);

      assert.equal(Pprint.render(Result.error(i), tResult(tString, tNumber)), `Result.error(
  ${i}
)`);
    }));
  })

Summary: `Pprint.render` produces correctly formatted string representations for `Result.value` and `Result.error` given integer inputs.


it('Optionals.cat of only nones should be an empty array', () => {
    fc.assert(fc.property(
      fc.array(ArbDataTypes.arbOptionalNone()),
      (options) => {
        const output = Optionals.cat(options);
        assert.deepEqual(output, []);
      }
    ));
  })

Summary: `Optionals.cat` returns an empty array when given an array containing only `none` values.


it('Optionals.cat of only somes should have the same length', () => {
    fc.assert(fc.property(
      fc.array(ArbDataTypes.arbOptionalSome(fc.integer())),
      (options) => {
        const output = Optionals.cat(options);
        assert.lengthOf(output, options.length);
      }
    ));
  })

Summary: `Optionals.cat` applied to an array of `Some` values should produce an output array with the same length as the input array.


it('Optionals.cat of somes and nones should have length <= original', () => {
    fc.assert(fc.property(
      fc.array(ArbDataTypes.arbOptional(fc.integer())),
      (arr) => {
        const output = Optionals.cat(arr);
        assert.isAtMost(output.length, arr.length);
      }
    ));
  })

Summary: `Optionals.cat` produces an array with a length less than or equal to the input array when combining optional integers.


it('Optionals.cat of nones.concat(somes).concat(nones) should be somes', () => {
    fc.assert(fc.property(
      fc.array(fc.json()),
      fc.array(fc.json()),
      fc.array(fc.json()),
      (before, on, after) => {
        const beforeNones: Optional<string>[] = Arr.map(before, Optional.none);
        const afterNones = Arr.map(after, Optional.none);
        const onSomes = Arr.map(on, Optional.some);
        const output = Optionals.cat(beforeNones.concat(onSomes).concat(afterNones));
        assert.deepEqual(output, on);
      }
    ));
  })

Summary: `Optionals.cat` retains only the elements wrapped in `Optional.some` when given a concatenated array of `Optional.none`, `Optional.some`, and `Optional.none`.


it('Two some values', () => {
    fc.assert(fc.property(fc.integer(), fc.integer(), (n, m) => {
      assertOptional(Optionals.sequence<number>([ Optional.some(n), Optional.some(m) ]), Optional.some([ n, m ]));
    }));
  })

Summary: The `Optionals.sequence` function should combine two `Optional.some` values into a single `Optional.some` containing an array of those values.


it('Array of numbers', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (n) => {
      const someNumbers = Arr.map(n, (x) => Optional.some(x));
      assertOptional(Optionals.sequence<number>(someNumbers), Optional.some(n));
    }));
  })

Summary: `Optionals.sequence` combines an array of `Optional` numbers into `Optional.some` if all are `Optional.some`.


it('Some then none', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (n) => {
      const someNumbers = Arr.map(n, (x) => Optional.some(x));
      assertNone(Optionals.sequence<number>([ ...someNumbers, Optional.none<number>() ]));
    }));
  })

Summary: `Optionals.sequence` returns `None` when a sequence includes `None` among `Some` values.


it('reverses 3 elements', () => {
    fc.assert(fc.property(fc.integer(), fc.integer(), fc.integer(), (a, b, c) => {
      assert.deepEqual(Arr.reverse([ a, b, c ]), [ c, b, a ]);
    }));
  })

Summary: `Arr.reverse` should reverse an array of three integers.


it('every element in the input is in the output, and vice-versa', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (xs) => {
      const rxs = Arr.reverse(xs);
      assert.isTrue(Arr.forall(rxs, (x) => Arr.contains(xs, x)));
      assert.isTrue(Arr.forall(xs, (x) => Arr.contains(rxs, x)));
    }));
  })

Summary: Reversed array contains all elements from the original array and vice versa.


it('every member of ys-xs is in ys', () => {
    fc.assert(fc.property(fc.array(fc.integer()), fc.array(fc.integer()), (xs, ys) => {
      const diff = Arr.difference(ys, xs);
      return Arr.forall(diff, (d) => Arr.contains(ys, d));
    }));
  })

Summary: Every element in the array resulting from `Arr.difference(ys, xs)` is contained in `ys`.


it('returns true when element is in array', () => {
    fc.assert(fc.property(fc.array(fc.integer()), fc.integer(), fc.array(fc.integer()), (prefix, element, suffix) => {
      const arr2 = [ ...prefix, element, ...suffix ];
      assert.isTrue(Arr.contains(arr2, element));
    }));
  })

Summary: `Arr.contains` returns true when the specified element is present in the array composed of a prefix, the element, and a suffix.


it('creates an array of the appropriate length except for the last one', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      fc.nat(),
      (arr, rawChunkSize) => {
        // ensure chunkSize is at least one
        const chunkSize = rawChunkSize + 1;
        const chunks = Arr.chunk(arr, chunkSize);

        const numChunks = chunks.length;
        const firstParts = chunks.slice(0, numChunks - 1);

        for (const firstPart of firstParts) {
          assert.lengthOf(firstPart, chunkSize);
        }

        if (arr.length === 0) {
          assert.deepEqual(chunks, []);
        } else {
          assert.isAtMost(chunks[chunks.length - 1].length, chunkSize);
        }
      }
    ));
  })

Summary: Arrays are divided into chunks of a specified length, with all chunks except possibly the last having the exact specified length. If the array is empty, the result is an empty array.


it('returns last element when non-empty', () => {
    fc.assert(fc.property(fc.array(fc.integer()), fc.integer(), (init, last) => {
      const arr = init.concat([ last ]);
      assertSome(Arr.last(arr), last);
    }));
  })

Summary: `Arr.last` returns the last element of a non-empty array.


it('returns first element when nonEmpty', () => {
    fc.assert(fc.property(fc.array(fc.integer()), fc.integer(), (t, h) => {
      const arr = [ h, ...t ];
      assertSome(Arr.head(arr), h);
    }));
  })

Summary: `Arr.head` returns the first element of a non-empty array.


it('returns some for valid index (property test)', () => {
    fc.assert(fc.property(fc.array(fc.integer()), fc.integer(), fc.integer(), (array, h, t) => {
      const arr = [ h ].concat(array);
      const length = arr.push(t);
      const midIndex = Math.round(arr.length / 2);

      assertSome(Arr.get(arr, 0), h);
      assertSome(Arr.get(arr, midIndex), arr[midIndex]);
      assertSome(Arr.get(arr, length - 1), t);
    }));
  })

Summary: `Arr.get` returns a value wrapped in `Some` for valid indices: 0, middle, and last index of an array.


it('finds a value in the array', () => {
    fc.assert(fc.property(fc.array(fc.integer()), fc.integer(), fc.array(fc.integer()), (prefix, i, suffix) => {
      const arr = prefix.concat([ i ]).concat(suffix);
      const pred = (x: number) => x === i;
      const result = Arr.find(arr, pred);
      assertSome(result, i);
    }));
  })

Summary: The `Arr.find` function should locate a specified integer within an array and return it using a predicate that matches the integer.


it('cannot find a nonexistent value', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (arr) => {
      const result = Arr.find(arr, Fun.never);
      assertNone(result);
    }));
  })

Summary: The function `Arr.find` should return `None` when searching for a value that does not exist in an array.


it('Arr.findMap of non-empty is none if f is Optional.none', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      (arr) => {
        assertNone(Arr.findMap(arr, Optional.none));
      }
    ));
  })

Summary: `Arr.findMap` returns none when applied to a non-empty array with `Optional.none` as the mapping function.


it('should maintain response structure invariants', async () => {
      const apiResponseGenerator = fc.record({
        success: fc.boolean(),
        data: fc.option(fc.array(fc.record({
          id: fc.string(),
          title: fc.string(),
          type: fc.constantFrom('transaction', 'address', 'token', 'protocol'),
          relevanceScore: fc.float({ min: 0, max: 1 })
        }))),
        error: fc.option(fc.record({
          code: fc.string(),
          message: fc.string()
        })),
        metadata: fc.option(fc.record({
          creditsUsed: fc.integer({ min: 0, max: 10 }),
          queryTime: fc.integer({ min: 1, max: 5000 }),
          resultCount: fc.integer({ min: 0, max: 1000 }),
          queryId: fc.string()
        }))
      });

      await fc.assert(
        fc.asyncProperty(
          apiResponseGenerator,
          async (mockResponse) => {
            mockFetch.mockResolvedValue(createMockResponse(mockResponse));

            const result = await adapter.search('invariant test')();

            // Invariant: Response should always be Either
            expect(E.isRight(result) || E.isLeft(result)).toBe(true);

            if (E.isRight(result)) {
              // Invariant: Response should have success field
              expect(typeof result.right.success).toBe('boolean');

              // Invariant: If success is true, data should be defined
              if (result.right.success) {
                expect(result.right.data).toBeDefined();
              }

              // Invariant: If success is false, error should be defined
              if (!result.right.success) {
                expect(result.right.error).toBeDefined();
              }
            }
          }
        ),
        { numRuns: 100 }
      );
    })

Summary: The response from `adapter.search` should always be an Either type with a `success` field, and based on the `success` boolean, either `data` or `error` should be defined accordingly.


it('Arr.findMap finds an element', () => {
    fc.assert(fc.property(
      fc.array(fc.integer()),
      fc.integer(),
      fc.integer(),
      fc.array(fc.integer()),
      (prefix, element, ret, suffix) => {
        const arr = [ ...prefix, element, ...suffix ];
        assertSome(Arr.findMap(arr, (x) => Optionals.someIf(x === element, ret)), ret);
      }
    ));
  })

Summary: `Arr.findMap` should successfully locate an element in an array and return a mapped value when the element matches the specified condition.


it('obeys left identity law', () => {
      fc.assert(fc.property(fc.integer(), fc.integer(), (i, j) => {
        const f = (x: number) => [ x, j, x + j ];
        assert.deepEqual(Arr.bind(Arr.pure(i), f), f(i));
      }));
    })

Summary: The property ensures that `Arr.bind` and `Arr.pure` together obey the left identity law, meaning binding a function `f` to a single-element array created by `Arr.pure(i)` produces the same result as applying `f` directly to `i`.


it('is associative', () => {
      fc.assert(fc.property(fc.array(fc.integer()), fc.integer(), (arr, j) => {
        const f = (x: number) => [ x, j, x + j ];
        const g = (x: number) => [ j, x, x + j ];
        assert.deepEqual(Arr.bind(Arr.bind(arr, f), g), Arr.bind(arr, (x) => Arr.bind(f(x), g)));
      }));
    })

Summary: Associativity test for the `Arr.bind` function, ensuring that binding nested functions produces equivalent results regardless of the nesting order.


it('should parse a custom an error with an argument coming from the contract itself', async () => {
            const errorParser = await createErrorParser()

            await fc.assert(
                fc.asyncProperty(fc.string(), async (arg) => {
                    const error = await assertFailed(contract.throwWithCustomErrorAndArgument(arg))
                    const parsedError = await errorParser(error)

                    expect(parsedError).toEqual(new CustomError('CustomErrorWithAnArgument', [arg]))
                })
            )
        })

Summary: The error parser accurately identifies and interprets a custom error with an argument originating from the contract.


it('should parse a custom an error with an argument coming from a nested contract', async () => {
            const errorParser = await createErrorParser()

            await fc.assert(
                fc.asyncProperty(fc.string(), async (arg) => {
                    const error = await assertFailed(contract.throwNestedWithCustomErrorAndArgument(arg))
                    const parsedError = await errorParser(error)

                    expect(parsedError).toEqual(new CustomError('NestedCustomErrorWithAnArgument', [arg]))
                })
            )
        })

Summary: Parses a custom error including an argument from a nested contract and verifies the parsed error matches `NestedCustomErrorWithAnArgument` with the provided argument.


it('should parse a custom an error with an different arguments defined in more contracts coming from the contract itself', async () => {
            const errorParser = await createErrorParser()

            await fc.assert(
                fc.asyncProperty(fc.string(), async (arg) => {
                    const error = await assertFailed(contract.throwWithCommonErrorAndArgument(arg))
                    const parsedError = await errorParser(error)

                    expect(parsedError).toEqual(new CustomError('CommonErrorWithAnArgument', [arg]))
                })
            )
        })

Summary: Verifies that a custom error with varying arguments is correctly parsed from contracts, matching the expected `CustomError` structure.


it('should preserve error types through Either chains', async () => {
      const errorChainProperty = fc.property(
        fc.oneof(
          fc.constant({ type: 'network_error', message: 'Connection failed' }),
          fc.constant({ type: 'slippage_exceeded', expected: '100', actual: '95', limit: '98' }),
          fc.constant({ type: 'insufficient_liquidity', pair: 'SEI/USDC', requested: '1000', available: '500' })
        ),
        (error) => {
          const errorEither = E.left(error);
          const chainedResult = pipe(
            errorEither,
            E.chain(() => E.right('success')),
            E.mapLeft(err => ({ ...err, enhanced: true }))
          );

          return E.isLeft(chainedResult) && chainedResult.left.type === error.type;
        }
      );

      await fc.assert(errorChainProperty, { numRuns: 100 });
    })

Summary: Error types should remain unchanged through either chains, even when transformed or enhanced.


it('should maintain reasonable memory usage', async () => {
      const memoryProperty = fc.property(
        fc.record({
          operationType: fc.oneof(
            fc.constant('batch_quotes'),
            fc.constant('route_calculation'),
            fc.constant('price_update')
          ),
          batchSize: fc.nat({ min: 1, max: 100 }),
          cacheSize: fc.nat({ min: 0, max: 1000 })
        }),
        (data) => {
          // Mock memory calculation
          const baseMemory = 1024 * 1024; // 1MB base
          const memoryPerItem = 1024; // 1KB per item
          const cacheMemory = data.cacheSize * 512; // 512B per cache entry

          const estimatedMemory = baseMemory + (data.batchSize * memoryPerItem) + cacheMemory;
          const memoryLimit = 50 * 1024 * 1024; // 50MB limit

          return estimatedMemory <= memoryLimit;
        }
      );

      await fc.assert(memoryProperty, { numRuns: 100 });
    })

Summary: Memory usage should remain within a 50MB limit based on operation type, batch size, and cache size estimations.


it('should parse a custom an error with different arguments defined in more contracts coming from a nested contract', async () => {
            const errorParser = await createErrorParser()

            await fc.assert(
                fc.asyncProperty(fc.integer({ min: 0 }), async (arg) => {
                    const error = await assertFailed(contract.throwNestedWithCommonErrorAndArgument(arg))
                    const parsedError = await errorParser(error)

                    expect(parsedError).toEqual(new CustomError('CommonErrorWithAnArgument', [BigNumber.from(arg)]))
                })
            )
        })

Summary: Verifies that an error from a nested contract with varying arguments is correctly parsed as a `CustomError` with the expected name and argument.


it('should parse an Error', async () => {
            await fc.assert(
                fc.asyncProperty(endpointArbitrary, fc.string(), async (eid, message) => {
                    const errorParser = await createContractErrorParser({ contract, eid })
                    const error = new Error(message)
                    const parsedError = await errorParser(error)

                    expect(parsedError).toEqual(new UnknownError(`Unknown error: ${error}`))
                })
            )
        })

Summary: The property ensures that the error parser translates any given error into an `UnknownError` with the appropriate message format.


it('should pass any additional properties through', () => {
            fc.assert(
                fc.property(
                    oappNodeConfigArbitrary,
                    fc.dictionary(fc.string(), fc.anything()),
                    (config, extraProperties) => {
                        const combined = Object.assign({}, extraProperties, config)

                        expect(combined).toMatchObject(OAppNodeConfigSchema.parse(combined))
                    }
                )
            )
        })

Summary: The schema should accept configurations with additional properties without error.


it('should return true if the owner addresses match', async () => {
            await fc.assert(
                fc.asyncProperty(omniContractArbitrary, evmAddressArbitrary, async (omniContract, owner) => {
                    omniContract.contract.owner.mockResolvedValue(owner)

                    const sdk = new OApp(omniContract)
                    const ownable = Object.assign(sdk, OwnableMixin)

                    expect(await ownable.hasOwner(owner)).toBeTruthy()
                })
            )
        })

Summary: The test checks that `hasOwner` returns true when the owner's address matches the address set in the mock contract.


it('should return false if the owner addresses do not match', async () => {
            await fc.assert(
                fc.asyncProperty(
                    omniContractArbitrary,
                    evmAddressArbitrary,
                    evmAddressArbitrary,
                    async (omniContract, owner, user) => {
                        fc.pre(!areBytes32Equal(owner, user))

                        omniContract.contract.owner.mockResolvedValue(owner)

                        const sdk = new OApp(omniContract)
                        const ownable = Object.assign(sdk, OwnableMixin)

                        expect(await ownable.hasOwner(user)).toBeFalsy()
                    }
                )
            )
        })

Summary: The test confirms that `hasOwner` returns false when given an address that does not match the owner address of the contract.


it('should encode data for a transferOwnership call', async () => {
            await fc.assert(
                fc.asyncProperty(omniContractArbitrary, evmAddressArbitrary, async (omniContract, owner) => {
                    const sdk = new OApp(omniContract)
                    const ownable = Object.assign(sdk, OwnableMixin)
                    const encodeFunctionData = omniContract.contract.interface.encodeFunctionData as jest.Mock

                    encodeFunctionData.mockClear()

                    await ownable.setOwner(owner)

                    expect(encodeFunctionData).toHaveBeenCalledTimes(1)
                    expect(encodeFunctionData).toHaveBeenCalledWith('transferOwnership', [owner])
                })
            )
        })

Summary: `OwnableMixin` correctly encodes the data for a `transferOwnership` call when setting a new owner.


it('should call peers on the contract', async () => {
            await fc.assert(
                fc.asyncProperty(omniContractArbitrary, endpointArbitrary, async (omniContract, peerEid) => {
                    const sdk = new OApp(omniContract)

                    await sdk.getPeer(peerEid)

                    expect(omniContract.contract.peers).toHaveBeenCalledTimes(1)
                    expect(omniContract.contract.peers).toHaveBeenCalledWith(peerEid)
                })
            )
        })

Summary: The test ensures that calling `getPeer` on the `OApp` instance results in the `peers` method of the `omniContract.contract` being called once with the correct `peerEid` argument.


test('should autocomplete queries (basic)', async () => {
  await fc.assert(
    fc
      .asyncProperty(fc.scheduler({ act }), async (s) => {
        // Arrange
        const allResults = ['apple', 'banana', 'orange', 'pineapple'];
        suggestionsFor.mockImplementation(
          s.scheduleFunction(async (query) => {
            return allResults.filter((r) => r.includes(query)).slice(0, 10);
          })
        );
        const userQuery = 'nan';
        const expectedResults = ['banana'];

        // Act
        const { getByRole, getAllByRole } = render(<Autocomplete />);
        await act(async () => {
          await userEvent.type(getByRole('textbox'), userQuery, { allAtOnce: false, delay: 1 });
        });
        await s.waitAll();

        // Assert
        const displayedSuggestions = getAllByRole('listitem');
        expect(displayedSuggestions.map((el) => el.textContent)).toEqual(expectedResults);
        expect(suggestionsFor).toHaveBeenCalledTimes(userQuery.length);
      })
      .beforeEach(() => {
        jest.resetAllMocks();
        cleanup();
      })
  );
})

Summary: Autocomplete suggestions should match expected results based on query input, ensuring each character triggers a suggestion lookup.


it('should return undefined if peers() returns a zero address, null or undefined', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        omniContractArbitrary,
                        evmEndpointArbitrary,
                        nullishAddressArbitrary,
                        async (omniContract, peerEid, peer) => {
                            omniContract.contract.peers.mockResolvedValue(peer)

                            const sdk = new OApp(omniContract)

                            await expect(sdk.getPeer(peerEid)).resolves.toBeUndefined()
                        }
                    )
                )
            })

Summary: The `getPeer` method should return undefined if the `peers()` function resolves to a zero address, null, or undefined.


it('should return undefined if peers() returns a zero address, null or undefined', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        omniContractArbitrary,
                        solanaEndpointArbitrary,
                        nullishAddressArbitrary,
                        async (omniContract, peerEid, peer) => {
                            omniContract.contract.peers.mockResolvedValue(peer)

                            const sdk = new OApp(omniContract)

                            await expect(sdk.getPeer(peerEid)).resolves.toBeUndefined()
                        }
                    )
                )
            })

Summary: `getPeer` should return undefined if `peers()` resolves to a zero address, null, or undefined.


it('should return an address if peers() returns a non-null bytes', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        omniContractArbitrary,
                        evmEndpointArbitrary,
                        solanaEndpointArbitrary,
                        solanaAddressArbitrary,
                        async (omniContract, eid, peerEid, peer) => {
                            // For Solana we need to take the native address format and turn it into EVM bytes32
                            //
                            // We do this by normalizing the value into a UInt8Array,
                            // then denormalizing it using an EVM eid
                            const peerBytes = normalizePeer(peer, peerEid)
                            const peerHex = makeBytes32(peerBytes)

                            fc.pre(!isZero(peerHex))

                            omniContract.contract.peers.mockResolvedValue(peerHex)

                            const sdk = new OApp(omniContract)

                            await expect(sdk.getPeer(peerEid)).resolves.toBe(peer)
                        }
                    )
                )
            })

Summary: An `OApp` instance should return the correct address when `peers()` returns non-null EVM bytes32 representations of Solana addresses.


it('should return undefined if peers() returns a zero address, null or undefined', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        omniContractArbitrary,
                        aptosEndpointArbitrary,
                        nullishAddressArbitrary,
                        async (omniContract, peerEid, peer) => {
                            omniContract.contract.peers.mockResolvedValue(peer)

                            const sdk = new OApp(omniContract)

                            await expect(sdk.getPeer(peerEid)).resolves.toBeUndefined()
                        }
                    )
                )
            })

Summary: The test checks that `getPeer` returns `undefined` when `peers()` resolves to a zero address, `null`, or `undefined`.


it('should return an address if peers() returns a non-null bytes', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        omniContractArbitrary,
                        aptosEndpointArbitrary,
                        aptosAddressArbitrary,
                        async (omniContract, peerEid, peer) => {
                            fc.pre(!isZero(peer))

                            omniContract.contract.peers.mockResolvedValue(peer)

                            const sdk = new OApp(omniContract)

                            await expect(sdk.getPeer(peerEid)).resolves.toBe(peer)
                        }
                    )
                )
            })

Summary: An address should be returned if the `peers()` method returns non-null bytes for a given peer ID.


it('should return true if peers returns a zero address', async () => {
                    await fc.assert(
                        fc.asyncProperty(
                            omniContractArbitrary,
                            evmEndpointArbitrary,
                            nullishAddressArbitrary,
                            nullishAddressArbitrary,
                            async (omniContract, peerEid, peer, probePeer) => {
                                omniContract.contract.peers.mockResolvedValue(peer)

                                const sdk = new OApp(omniContract)

                                await expect(sdk.hasPeer(peerEid, probePeer)).resolves.toBe(true)
                            }
                        )
                    )
                })

Summary: `OApp.hasPeer` should return true when the peer address is resolved to a zero address by `contract.peers`.


it('should return false if peers returns a different value', async () => {
                    await fc.assert(
                        fc.asyncProperty(
                            omniContractArbitrary,
                            solanaEndpointArbitrary,
                            solanaAddressArbitrary,
                            solanaAddressArbitrary,
                            async (omniContract, peerEid, peer, probePeer) => {
                                fc.pre(
                                    !areBytes32Equal(normalizePeer(peer, peerEid), normalizePeer(probePeer, peerEid))
                                )

                                const peerHex = makeBytes32(normalizePeer(peer, peerEid))

                                omniContract.contract.peers.mockResolvedValue(peerHex)

                                const sdk = new OApp(omniContract)

                                await expect(sdk.hasPeer(peerEid, probePeer)).resolves.toBe(false)
                            }
                        )
                    )
                })

Summary: `OApp.hasPeer` should return false when `peers` resolves with a different normalized peer value than the one being checked.