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


unknown

it('should never crash on arbitrary input', () => {
            fc.assert(
                fc.property(
                    fc.string(),
                    fc.constantFrom('javascript', 'typescript', 'python', 'java', 'unknown'),
                    (input, language) => {
                        expect(() => {
                            detector.detectURLs(input, language, 'test-file');
                        }).not.toThrow();
                    },
                ),
                { numRuns: 1000 },
            );
        })


it('should handle extremely long inputs gracefully', () => {
            fc.assert(
                fc.property(
                    fc.string({ minLength: 10000, maxLength: 50000 }),
                    fc.constantFrom('javascript', 'typescript', 'python'),
                    (input, language) => {
                        const start = Date.now();
                        const result = detector.detectURLs(input, language, 'long-file');
                        const duration = Date.now() - start;

                        expect(Array.isArray(result)).toBe(true);
                        expect(duration).toBeLessThan(10000); // Should complete within 10 seconds
                    },
                ),
                { numRuns: 10 },
            );
        })


it('should handle valid URL patterns correctly', () => {
            const testCases = [
                { input: 'const url = "https://example.com";', language: 'javascript' },
                { input: 'url = "http://localhost:3000"', language: 'python' },
                { input: 'String url = "https://api.github.com/users";', language: 'java' },
                { input: 'let endpoint: string = "https://www.google.com/search";', language: 'typescript' },
            ];

            fc.assert(
                fc.property(fc.constantFrom(...testCases), testCase => {
                    const results = detector.detectURLs(testCase.input, testCase.language, 'test-file');

                    expect(Array.isArray(results)).toBe(true);
                    expect(results.length).toBeGreaterThan(0);
                    expect(results[0]).toHaveProperty('url');
                    expect(results[0]).toHaveProperty('line');
                    expect(results[0]).toHaveProperty('column');
                }),
                { numRuns: 20 },
            );
        })


it('should handle mixed content with URLs and non-URLs', () => {
            fc.assert(
                fc.property(
                    fc.array(
                        fc.oneof(
                            fc.constantFrom('https://example.com', 'http://test.org', 'https://api.service.com'),
                            fc.string().filter(s => !s.includes('http')),
                        ),
                    ),
                    fc.constantFrom('javascript', 'typescript', 'python'),
                    (parts, language) => {
                        const input = parts.join(' ');
                        const results = detector.detectURLs(input, language, 'mixed-file');

                        expect(Array.isArray(results)).toBe(true);
                        results.forEach(result => {
                            expect(result).toHaveProperty('url');
                            expect(result).toHaveProperty('line');
                            expect(result).toHaveProperty('column');
                            expect(result).toHaveProperty('start');
                            expect(result).toHaveProperty('end');
                            expect(result.start).toBeGreaterThanOrEqual(0);
                            expect(result.end).toBeGreaterThan(result.start);
                        });
                    },
                ),
                { numRuns: 200 },
            );
        })


it('should handle special characters and unicode correctly', () => {
            fc.assert(
                fc.property(
                    fc.string(),
                    fc.constantFrom('https://example.com/path', 'http://localhost:8080'),
                    fc.string(),
                    fc.constantFrom('javascript', 'typescript'),
                    (prefix, url, suffix, language) => {
                        const input = prefix + url + suffix;
                        const results = detector.detectURLs(input, language, 'unicode-file');

                        expect(() => {
                            JSON.stringify(results);
                        }).not.toThrow();
                    },
                ),
                { numRuns: 500 },
            );
        })


it('should maintain consistent results for identical inputs', () => {
            fc.assert(
                fc.property(fc.string(), fc.constantFrom('javascript', 'typescript', 'python'), (input, language) => {
                    const result1 = detector.detectURLs(input, language, 'consistency-test');
                    const result2 = detector.detectURLs(input, language, 'consistency-test');

                    expect(result1).toEqual(result2);
                }),
                { numRuns: 100 },
            );
        })


it('should handle arbitrary language detection inputs', () => {
            fc.assert(
                fc.property(fc.string(), filename => {
                    expect(() => {
                        languageManager.detectLanguageFromPath(filename);
                    }).not.toThrow();
                }),
                { numRuns: 1000 },
            );
        })


it('should always return a valid language or undefined', () => {
            fc.assert(
                fc.property(fc.string(), extension => {
                    const result = languageManager.getLanguage(extension);
                    expect(result === undefined || typeof result === 'object').toBe(true);
                }),
                { numRuns: 500 },
            );
        })


it('should handle null bytes and control characters', () => {
            fc.assert(
                fc.property(
                    fc.string().map(s => s + '\0' + s),
                    fc.constantFrom('javascript', 'typescript'),
                    (input, language) => {
                        expect(() => {
                            detector.detectURLs(input, language, 'null-byte-file');
                        }).not.toThrow();
                    },
                ),
                { numRuns: 100 },
            );
        })


it('should handle deeply nested structures', () => {
            const createNestedString = (depth: number): string => {
                if (depth === 0) return 'https://example.com';
                return `{${createNestedString(depth - 1)}}`;
            };

            fc.assert(
                fc.property(
                    fc.integer({ min: 1, max: 100 }),
                    fc.constantFrom('javascript', 'json'),
                    (depth, language) => {
                        const input = createNestedString(depth);
                        const results = detector.detectURLs(input, language, 'nested-file');

                        expect(Array.isArray(results)).toBe(true);
                    },
                ),
                { numRuns: 50 },
            );
        })


it('should handle malformed URLs gracefully', () => {
            const malformedUrls = [
                'http://',
                'https://',
                'http://.',
                'https://.',
                'http://..',
                'https://..',
                'http://...',
                'https://...',
            ];

            fc.assert(
                fc.property(
                    fc.constantFrom(...malformedUrls),
                    fc.string(),
                    fc.constantFrom('javascript', 'typescript'),
                    (malformedUrl, context, language) => {
                        const input = context + malformedUrl + context;

                        expect(() => {
                            detector.detectURLs(input, language, 'malformed-file');
                        }).not.toThrow();
                    },
                ),
                { numRuns: 100 },
            );
        })


it('should handle extremely long URLs', () => {
            fc.assert(
                fc.property(
                    fc.string({ minLength: 1000, maxLength: 10000 }),
                    fc.constantFrom('javascript', 'typescript'),
                    (longPath, language) => {
                        const longUrl = `https://example.com/${longPath}`;
                        const results = detector.detectURLs(longUrl, language, 'long-url-file');

                        expect(Array.isArray(results)).toBe(true);
                        if (results.length > 0) {
                            // URL detector may normalize URLs, so check for domain presence more flexibly
                            const hasExpectedDomain = results.some(r => r.url.includes('example.com'));
                            expect(hasExpectedDomain).toBe(true);
                        }
                    },
                ),
                { numRuns: 20 },
            );
        })


it('should complete within reasonable time bounds', () => {
            fc.assert(
                fc.property(
                    fc.string({ minLength: 100, maxLength: 5000 }),
                    fc.constantFrom('javascript', 'typescript'),
                    (input, language) => {
                        const start = Date.now();
                        const results = detector.detectURLs(input, language, 'perf-test');
                        const duration = Date.now() - start;

                        expect(Array.isArray(results)).toBe(true);
                        expect(duration).toBeLessThan(5000); // Should complete within 5 seconds
                    },
                ),
                { numRuns: 20 },
            );
        })


it('should handle common problematic patterns', () => {
            const problematicPatterns = [
                '//example.com', // Protocol-relative URL
                'https://example.com//double-slash',
                'https://example.com/path with spaces',
                'https://example.com/path"with"quotes',
                "https://example.com/path'with'quotes",
                'https://example.com/path\nwith\nnewlines',
                'https://example.com/path\twith\ttabs',
                'https://example.com/path<with>brackets',
                'https://example.com/path{with}braces',
                'https://example.com/path[with]square',
            ];

            fc.assert(
                fc.property(
                    fc.constantFrom(...problematicPatterns),
                    fc.constantFrom('javascript', 'typescript', 'html'),
                    (pattern, language) => {
                        expect(() => {
                            const results = detector.detectURLs(pattern, language, 'problematic-file');
                            expect(Array.isArray(results)).toBe(true);
                        }).not.toThrow();
                    },
                ),
                { numRuns: 100 },
            );
        })


test('url-friendly strings are URL-friendly', () =>
    fc.assert(
        fc.property(urlFriendlyString(), (input: string) =>
            /^[\w~.-]+$/.test(input),
        ),
    ))


test('variant payloads are either present or undefined; never null', () =>
    fc.assert(
        fc.property(
            variant(),
            (generatedVariant) =>
                !!generatedVariant.payload ||
                generatedVariant.payload === undefined,
        ),
    ))


it("should create larger and larger levels", () => {
  fc.assert(
    fc.property(fc.integer({ min: 1, max: 1000 }), (n) => {
      // Arrange / Act
      const tree = drawTree(n);

      // Assert
      const treeLevels = tree.split("\n").map((level) => level.trim());
      for (let index = 1; index < n; ++index) {
        expect(treeLevels[index]).toContain(treeLevels[index - 1]);
      }
    })
  );
})

Summary: The test confirms that each subsequent level of a tree generated by `drawTree` contains all the elements of the previous level.


test('should return the same enabled toggles as the raw SDK correctly mapped', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    fc
                        .tuple(generateContext(), commonISOTimestamp())
                        .map(([context, currentTime]) => ({
                            ...context,
                            userId: 'constant',
                            sessionId: 'constant2',
                            currentTime,
                        })),
                    fc.context(),
                    async ({ segments, features }, context, ctx) => {
                        const serviceToggles = await insertAndEvaluateFeatures({
                            features: features,
                            context,
                            segments,
                        });

                        const [head, ...rest] =
                            await featureToggleService.getClientFeatures();
                        if (!head) {
                            return serviceToggles.length === 0;
                        }

                        const client = await offlineUnleashClientNode({
                            features: [head, ...rest],
                            context,
                            logError: console.log,
                            segments: segments.map(mapSegmentSchemaToISegment),
                        });

                        const clientContext = {
                            ...context,

                            currentTime: context.currentTime
                                ? new Date(context.currentTime)
                                : undefined,
                        };

                        return serviceToggles.every((feature) => {
                            ctx.log(
                                `Examining feature ${
                                    feature.name
                                }: ${JSON.stringify(feature)}`,
                            );

                            // the playground differs from a normal SDK in that
                            // it _must_ evaluate all strategies and features
                            // regardless of whether they're supposed to be
                            // enabled in the current environment or not.
                            const expectedSDKState = feature.isEnabled;

                            const enabledStateMatches =
                                expectedSDKState ===
                                client.isEnabled(feature.name, clientContext);

                            ctx.log(
                                `feature.isEnabled, feature.isEnabledInCurrentEnvironment, presumedSDKState: ${feature.isEnabled}, ${feature.isEnabledInCurrentEnvironment}, ${expectedSDKState}`,
                            );
                            ctx.log(
                                `client.isEnabled: ${client.isEnabled(
                                    feature.name,
                                    clientContext,
                                )}`,
                            );
                            expect(enabledStateMatches).toBe(true);

                            // if x is disabled, then the variant will be the
                            // disabled variant.
                            if (!feature.isEnabled) {
                                ctx.log(`${feature.name} is not enabled`);
                                ctx.log(JSON.stringify(feature.variant));
                                ctx.log(JSON.stringify(enabledStateMatches));
                                ctx.log(
                                    JSON.stringify(
                                        feature.variant?.name === 'disabled',
                                    ),
                                );
                                ctx.log(
                                    JSON.stringify(
                                        feature.variant?.enabled === false,
                                    ),
                                );
                                return (
                                    enabledStateMatches &&
                                    isDisabledVariant(feature.variant)
                                );
                            }
                            ctx.log('feature is enabled');

                            const clientVariant = client.getVariant(
                                feature.name,
                                clientContext,
                            );

                            // if x is enabled, but its variant is the disabled
                            // variant, then the source does not have any
                            // variants
                            if (isDisabledVariant(feature.variant)) {
                                return (
                                    enabledStateMatches &&
                                    isDisabledVariant(clientVariant)
                                );
                            }

                            ctx.log(`feature "${feature.name}" has a variant`);
                            ctx.log(
                                `Feature variant: ${JSON.stringify(
                                    feature.variant,
                                )}`,
                            );
                            ctx.log(
                                `Client variant: ${JSON.stringify(
                                    clientVariant,
                                )}`,
                            );
                            ctx.log(
                                `enabledStateMatches: ${enabledStateMatches}`,
                            );

                            // variants should be the same if the
                            // toggle is enabled in both versions. If
                            // they're not and one of them has a
                            // variant, then they should be different.
                            if (expectedSDKState === true) {
                                expect(feature.variant).toEqual(clientVariant);
                            } else {
                                expect(feature.variant).not.toEqual(
                                    clientVariant,
                                );
                            }

                            return enabledStateMatches;
                        });
                    },
                )
                .afterEach(cleanup),
            { ...testParams, examples: [] },
        );
    })


test("should return all of a feature's strategies", async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    fc.context(),
                    async (data, context, ctx) => {
                        const log = (x: unknown) => ctx.log(JSON.stringify(x));
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...data,
                                context,
                            },
                        );

                        const serviceFeaturesDict: {
                            [key: string]: PlaygroundFeatureSchema;
                        } = serviceFeatures.reduce(
                            (acc, feature) => ({
                                ...acc,
                                [feature.name]: feature,
                            }),
                            {},
                        );

                        // for each feature, find the corresponding evaluated feature
                        // and make sure that the evaluated
                        // return genFeat.length === servFeat.length && zip(gen, serv).
                        data.features.forEach((feature) => {
                            const mappedFeature: PlaygroundFeatureSchema =
                                serviceFeaturesDict[feature.name];

                            // log(feature);
                            log(mappedFeature);

                            const featureStrategies = feature.strategies ?? [];

                            expect(
                                mappedFeature.strategies.data.length,
                            ).toEqual(featureStrategies.length);

                            // we can't guarantee that the order we inserted
                            // strategies into the database is the same as it
                            // was returned by the service , so we'll need to
                            // scan through the list of strats.

                            // extract the `result` property, because it
                            // doesn't exist in the input

                            const removeResult = <T>({
                                result,
                                ...rest
                            }: T & {
                                result: unknown;
                            }) => rest;

                            const cleanedReceivedStrategies =
                                mappedFeature.strategies.data.map(
                                    (strategy) => {
                                        const {
                                            segments: mappedSegments,
                                            ...mappedStrategy
                                        } = removeResult(strategy);

                                        return {
                                            ...mappedStrategy,
                                            constraints:
                                                mappedStrategy.constraints?.map(
                                                    removeResult,
                                                ),
                                        };
                                    },
                                );

                            feature.strategies?.forEach(
                                ({ segments, ...strategy }) => {
                                    expect(cleanedReceivedStrategies).toEqual(
                                        expect.arrayContaining([
                                            {
                                                ...strategy,
                                                title: undefined,
                                                disabled: false,
                                                constraints:
                                                    strategy.constraints ?? [],
                                                parameters:
                                                    strategy.parameters ?? {},
                                            },
                                        ]),
                                    );
                                },
                            );
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


test('should return feature strategies with all their segments', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async (
                        { segments, features: generatedFeatures },
                        context,
                    ) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features: generatedFeatures,
                                context,
                                segments,
                            },
                        );

                        const serviceFeaturesDict: {
                            [key: string]: PlaygroundFeatureSchema;
                        } = serviceFeatures.reduce(
                            (acc, feature) => ({
                                ...acc,
                                [feature.name]: feature,
                            }),
                            {},
                        );

                        // ensure that segments are mapped on to features
                        // correctly. We do not need to check whether the
                        // evaluation is correct; that is taken care of by other
                        // tests.

                        // For each feature strategy, find its list of segments and
                        // compare it to the input.
                        //
                        // We can assert three things:
                        //
                        // 1. The segments lists have the same length
                        //
                        // 2. All segment ids listed in an input id list are
                        // also in the original segments list
                        //
                        // 3. If a feature is considered enabled, _all_ segments
                        // must be true. If a feature is _disabled_, _at least_
                        // one segment is not true.
                        generatedFeatures.forEach((unmappedFeature) => {
                            const strategies = serviceFeaturesDict[
                                unmappedFeature.name
                            ].strategies.data.reduce(
                                (acc, strategy) => ({
                                    ...acc,
                                    [strategy.id]: strategy,
                                }),
                                {},
                            );

                            unmappedFeature.strategies?.forEach(
                                (unmappedStrategy) => {
                                    const mappedStrategySegments: PlaygroundSegmentSchema[] =
                                        strategies[unmappedStrategy.id!]
                                            .segments;

                                    const unmappedSegments =
                                        unmappedStrategy.segments ?? [];

                                    // 1. The segments lists have the same length
                                    // 2. All segment ids listed in the input exist:
                                    expect(
                                        [
                                            ...mappedStrategySegments?.map(
                                                (segment) => segment.id,
                                            ),
                                        ].sort(),
                                    ).toEqual([...unmappedSegments].sort());

                                    switch (
                                        strategies[unmappedStrategy.id!].result
                                    ) {
                                        case true:
                                            // If a strategy is considered true, _all_ segments
                                            // must be true.
                                            expect(
                                                mappedStrategySegments.every(
                                                    (segment) =>
                                                        segment.result === true,
                                                ),
                                            ).toBeTruthy();
                                            break;
                                        case false:
                                        // empty -- all segments can be true and
                                        // the toggle still not enabled. We
                                        // can't check for anything here.
                                        case 'not found':
                                        // empty -- we can't evaluate this
                                    }
                                },
                            );
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


test("should evaluate a strategy to be unknown if it doesn't recognize the strategy and all constraints pass", async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }).map(
                        ({ features, ...rest }) => ({
                            ...rest,
                            features: features.map((feature) => ({
                                ...feature,
                                // remove any constraints and use a name that doesn't exist
                                strategies: feature.strategies?.map(
                                    (strategy) => ({
                                        ...strategy,
                                        name: 'bogus-strategy',
                                        constraints: [],
                                        segments: [],
                                    }),
                                ),
                            })),
                        }),
                    ),
                    generateContext(),
                    fc.context(),
                    async (featsAndSegments, context, ctx) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...featsAndSegments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) =>
                            feature.strategies.data.forEach((strategy) => {
                                expect(strategy.result.evaluationStatus).toBe(
                                    playgroundStrategyEvaluation.evaluationIncomplete,
                                );
                                expect(strategy.result.enabled).toBe(
                                    playgroundStrategyEvaluation.unknownResult,
                                );
                            }),
                        );

                        ctx.log(JSON.stringify(serviceFeatures));
                        serviceFeatures.forEach((feature) => {
                            // if there are strategies and they're all
                            // incomplete and unknown, then the feature can't be
                            // evaluated fully
                            if (feature.strategies.data.length) {
                                expect(feature.isEnabled).toBe(false);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


test("should evaluate a strategy as false if it doesn't recognize the strategy and constraint checks fail", async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    fc
                        .tuple(
                            fc.uuid(),
                            clientFeaturesAndSegments({ minLength: 1 }),
                        )
                        .map(([uuid, { features, ...rest }]) => ({
                            ...rest,
                            features: features.map((feature) => ({
                                ...feature,
                                // use a constraint that will never be true
                                strategies: feature.strategies?.map(
                                    (strategy) => ({
                                        ...strategy,
                                        name: 'bogusStrategy',
                                        constraints: [
                                            {
                                                contextName: 'appName',
                                                operator: 'IN' as const,
                                                values: [uuid],
                                            },
                                        ],
                                    }),
                                ),
                            })),
                        })),
                    generateContext(),
                    fc.context(),
                    async (featsAndSegments, context, ctx) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...featsAndSegments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) =>
                            feature.strategies.data.forEach((strategy) => {
                                expect(strategy.result.evaluationStatus).toBe(
                                    playgroundStrategyEvaluation.evaluationIncomplete,
                                );
                                expect(strategy.result.enabled).toBe(false);
                            }),
                        );

                        ctx.log(JSON.stringify(serviceFeatures));

                        serviceFeatures.forEach((feature) => {
                            if (feature.strategies.data.length) {
                                // if there are strategies and they're all
                                // incomplete and false, then the feature
                                // is also false
                                expect(feature.isEnabled).toEqual(false);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


test('should evaluate a feature as unknown if there is at least one incomplete strategy among all failed strategies', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    fc
                        .tuple(
                            fc.uuid(),
                            clientFeaturesAndSegments({ minLength: 1 }),
                        )
                        .map(([uuid, { features, ...rest }]) => ({
                            ...rest,
                            features: features.map((feature) => ({
                                ...feature,
                                // use a constraint that will never be true
                                strategies: [
                                    ...feature.strategies!.map((strategy) => ({
                                        ...strategy,
                                        constraints: [
                                            {
                                                contextName: 'appName',
                                                operator: 'IN' as const,
                                                values: [uuid],
                                            },
                                        ],
                                    })),
                                    { name: 'my-custom-strategy' },
                                ],
                            })),
                        })),
                    generateContext(),
                    async (featsAndSegments, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...featsAndSegments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) => {
                            if (feature.strategies.data.length) {
                                // if there are strategies and they're
                                // all incomplete and unknown, then
                                // the feature is also unknown and
                                // thus 'false' (from an SDK point of
                                // view)
                                expect(feature.isEnabled).toEqual(false);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


test("features can't be evaluated to true if they're not enabled in the current environment", async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }).map(
                        ({ features, ...rest }) => ({
                            ...rest,
                            features: features.map((feature) => ({
                                ...feature,
                                enabled: false,
                                // remove any constraints and use a name that doesn't exist
                                strategies: [{ name: 'default' }],
                            })),
                        }),
                    ),
                    generateContext(),
                    fc.context(),
                    async (featsAndSegments, context, ctx) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                ...featsAndSegments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) =>
                            feature.strategies.data.forEach((strategy) => {
                                expect(strategy.result.evaluationStatus).toBe(
                                    playgroundStrategyEvaluation.evaluationComplete,
                                );
                                expect(strategy.result.enabled).toBe(true);
                            }),
                        );

                        ctx.log(JSON.stringify(serviceFeatures));
                        serviceFeatures.forEach((feature) => {
                            expect(feature.isEnabled).toBe(false);
                            expect(feature.isEnabledInCurrentEnvironment).toBe(
                                false,
                            );
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


test('output toggles should have the same variants as input toggles', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async ({ features, segments }, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features,
                                segments,
                                context,
                            },
                        );

                        const variantsMap = features.reduce(
                            (acc, feature) => ({
                                ...acc,
                                [feature.name]: feature.variants,
                            }),
                            {},
                        );

                        serviceFeatures.forEach((feature) => {
                            if (variantsMap[feature.name]) {
                                expect(feature.variants).toEqual(
                                    expect.arrayContaining(
                                        variantsMap[feature.name],
                                    ),
                                );
                                expect(variantsMap[feature.name]).toEqual(
                                    expect.arrayContaining(feature.variants),
                                );
                            } else {
                                expect(feature.variants).toStrictEqual([]);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


test('isEnabled matches strategies.results', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async ({ features, segments }, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features,
                                segments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) => {
                            if (feature.isEnabled) {
                                expect(
                                    feature.isEnabledInCurrentEnvironment,
                                ).toBe(true);
                                expect(feature.strategies.result).toBe(true);
                            } else {
                                expect(
                                    !feature.isEnabledInCurrentEnvironment ||
                                        feature.strategies.result !== true,
                                ).toBe(true);
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


test('strategies.results matches the individual strategy results', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async ({ features, segments }, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features,
                                segments,
                                context,
                            },
                        );

                        serviceFeatures.forEach(({ strategies }) => {
                            if (strategies.result === false) {
                                expect(
                                    strategies.data.every(
                                        (strategy) =>
                                            strategy.result.enabled === false,
                                    ),
                                ).toBe(true);
                            } else if (
                                strategies.result ===
                                playgroundStrategyEvaluation.unknownResult
                            ) {
                                expect(
                                    strategies.data.some(
                                        (strategy) =>
                                            strategy.result.enabled ===
                                            playgroundStrategyEvaluation.unknownResult,
                                    ),
                                ).toBe(true);

                                expect(
                                    strategies.data.every(
                                        (strategy) =>
                                            strategy.result.enabled !== true,
                                    ),
                                ).toBe(true);
                            } else {
                                if (strategies.data.length > 0) {
                                    expect(
                                        strategies.data.some(
                                            (strategy) =>
                                                strategy.result.enabled ===
                                                true,
                                        ),
                                    ).toBe(true);
                                }
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


it("should have the same answer for s and reverse(s)", () => {
  fc.assert(
    fc.property(fc.fullUnicodeString(), (s) => {
      // Arrange
      const reversedS = [...s].reverse().join("");

      // Act / Assert
      expect(isPalindrome(reversedS)).toBe(isPalindrome(s));
    })
  );
})

Summary: The property should hold that `isPalindrome` returns the same result for a string and its reversal.


test('unevaluated features should not have variants', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeaturesAndSegments({ minLength: 1 }),
                    generateContext(),
                    async ({ features, segments }, context) => {
                        const serviceFeatures = await insertAndEvaluateFeatures(
                            {
                                features,
                                segments,
                                context,
                            },
                        );

                        serviceFeatures.forEach((feature) => {
                            if (
                                feature.strategies.result ===
                                playgroundStrategyEvaluation.unknownResult
                            ) {
                                expect(feature.variant).toEqual({
                                    name: 'disabled',
                                    enabled: false,
                                    feature_enabled: false,
                                });
                            }
                        });
                    },
                )
                .afterEach(cleanup),
            testParams,
        );
    })


it("should consider any composite of primes <=7 as humble", () => {
  fc.assert(
    fc.property(
      fc.array(fc.integer({ min: 2, max: 7 }), { minLength: 1 }),
      (factors) => {
        // Arrange
        let n = 1;
        for (const f of factors) {
          if (n * f > 2 ** 31 - 1) break;
          n = n * f;
        }

        // Act / Assert
        expect(isHumbleNumber(n)).toBe(true);
      }
    )
  );
})

Summary: A number composed entirely of prime factors less than or equal to 7 should be identified as humble by `isHumbleNumber`.


it('Returned features should be a subset of the provided flags', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeatures({ minLength: 1 }),
                    generateRequest(),
                    async (features, request) => {
                        // seed the database
                        await seedDatabase(db, features, request.environment);

                        const body = await playgroundRequest(
                            app,
                            token.secret,
                            request,
                        );

                        // the returned list should always be a subset of the provided list
                        expect(features.map((feature) => feature.name)).toEqual(
                            expect.arrayContaining(
                                body.features.map((feature) => feature.name),
                            ),
                        );
                    },
                )
                .afterEach(reset(db)),
            testParams,
        );
    })


it('should filter the list according to the input parameters', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    generateRequest(),
                    clientFeatures({ minLength: 1 }),
                    async (request, features) => {
                        await seedDatabase(db, features, request.environment);

                        // get a subset of projects that exist among the features
                        const [projects] = fc.sample(
                            fc.oneof(
                                fc.constant(ALL as '*'),
                                fc.uniqueArray(
                                    fc.constantFrom(
                                        ...features.map(
                                            (feature) => feature.project,
                                        ),
                                    ),
                                ),
                            ),
                        );

                        request.projects = projects as any;

                        // create a list of features that can be filtered
                        // pass in args that should filter the list
                        const body = await playgroundRequest(
                            app,
                            token.secret,
                            request,
                        );

                        switch (projects) {
                            case ALL:
                                // no features have been filtered out
                                return body.features.length === features.length;
                            case []:
                                // no feature should be without a project
                                return body.features.length === 0;
                            default:
                                // every feature should be in one of the prescribed projects
                                return body.features.every((feature) =>
                                    projects.includes(feature.projectId),
                                );
                        }
                    },
                )
                .afterEach(reset(db)),
            testParams,
        );
    })


it('should map project and name correctly', async () => {
        // note: we're not testing `isEnabled` and `variant` here, because
        // that's the SDK's responsibility and it's tested elsewhere.
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeatures(),
                    fc.context(),
                    async (features, ctx) => {
                        await seedDatabase(db, features, 'default');

                        const body = await playgroundRequest(
                            app,
                            token.secret,
                            {
                                projects: ALL,
                                environment: DEFAULT_ENV,
                                context: {
                                    appName: 'playground-test',
                                },
                            },
                        );

                        const createDict = (xs: { name: string }[]) =>
                            xs.reduce(
                                (acc, next) => ({ ...acc, [next.name]: next }),
                                {},
                            );

                        const mappedToggles = createDict(body.features);

                        if (features.length !== body.features.length) {
                            ctx.log(
                                `I expected the number of mapped flags (${body.features.length}) to be the same as the number of created toggles (${features.length}), but that was not the case.`,
                            );
                            return false;
                        }

                        return features.every((feature) => {
                            const mapped: PlaygroundFeatureSchema =
                                mappedToggles[feature.name];

                            expect(mapped).toBeTruthy();

                            return (
                                feature.name === mapped.name &&
                                feature.project === mapped.projectId
                            );
                        });
                    },
                )
                .afterEach(reset(db)),
            testParams,
        );
    })


it('isEnabledInCurrentEnvironment should always match feature.enabled', async () => {
        await fc.assert(
            fc
                .asyncProperty(
                    clientFeatures(),
                    fc.context(),
                    async (features, ctx) => {
                        await seedDatabase(db, features, DEFAULT_ENV);

                        const body = await playgroundRequest(
                            app,
                            token.secret,
                            {
                                projects: ALL,
                                environment: DEFAULT_ENV,
                                context: {
                                    appName: 'playground-test',
                                },
                            },
                        );

                        const createDict = (xs: { name: string }[]) =>
                            xs.reduce(
                                (acc, next) => ({ ...acc, [next.name]: next }),
                                {},
                            );

                        const mappedToggles = createDict(body.features);

                        ctx.log(JSON.stringify(features));
                        ctx.log(JSON.stringify(mappedToggles));

                        return features.every(
                            (feature) =>
                                feature.enabled ===
                                mappedToggles[feature.name]
                                    .isEnabledInCurrentEnvironment,
                        );
                    },
                )
                .afterEach(reset(db)),
            testParams,
        );
    })


it('applies appName constraints correctly', async () => {
            const appNames = ['A', 'B', 'C'];

            // Choose one of the app names at random
            const appName = () => fc.constantFrom(...appNames);

            // generate a list of features that are active only for a specific
            // app name (constraints). Each feature will be constrained to a
            // random appName from the list above.
            const constrainedFeatures = (): Arbitrary<ClientFeatureSchema[]> =>
                fc.uniqueArray(
                    fc
                        .tuple(
                            clientFeature(),
                            fc.record({
                                name: fc.constant('default'),
                                constraints: fc
                                    .record({
                                        values: appName().map(toArray),
                                        inverted: fc.constant(false),
                                        operator: fc.constant('IN' as const),
                                        contextName: fc.constant('appName'),
                                        caseInsensitive: fc.boolean(),
                                    })
                                    .map(toArray),
                            }),
                        )
                        .map(([feature, strategy]) => ({
                            ...feature,
                            enabled: true,
                            strategies: [strategy],
                        })),
                    { selector: (feature) => feature.name },
                );

            await fc.assert(
                fc
                    .asyncProperty(
                        fc
                            .tuple(appName(), generateRequest())
                            .map(([generatedAppName, req]) => ({
                                ...req,
                                // generate a context that has appName set to
                                // one of the above values
                                context: {
                                    appName: generatedAppName,
                                    environment: DEFAULT_ENV,
                                },
                            })),
                        constrainedFeatures(),
                        async (req, features) => {
                            await seedDatabase(db, features, req.environment);
                            const body = await playgroundRequest(
                                app,
                                token.secret,
                                req,
                            );

                            const shouldBeEnabled = features.reduce(
                                (acc, next) => ({
                                    ...acc,
                                    [next.name]:
                                        // @ts-ignore
                                        next.strategies[0].constraints[0]
                                            .values[0] === req.context.appName,
                                }),
                                {},
                            );

                            return body.features.every(
                                (feature) =>
                                    feature.isEnabled ===
                                    shouldBeEnabled[feature.name],
                            );
                        },
                    )
                    .afterEach(reset(db)),
                {
                    ...testParams,
                    examples: [],
                },
            );
        })


it("should reject any expression not having the same number of openings and closings", () => {
  fc.assert(
    fc.property(
      wellParenthesizedStringArbitrary,
      fc.constantFrom("(", "[", "{", ")", "]", "}"),
      fc.nat().noShrink(),
      (expression, extra, seed) => {
        const position = seed % (expression.length + 1);
        const invalidExpression =
          expression.substring(0, position) +
          extra +
          expression.substring(position);
        expect(validParentheses(invalidExpression)).toBe(false);
      }
    )
  );
})

Summary: Expressions with mismatched numbers of opening and closing brackets are identified as invalid by the `validParentheses` function.


it("should reject any expression with at least one reversed openings and closings", () => {
  fc.assert(
    fc.property(reversedParenthesizedStringArbitrary, (expression) => {
      expect(validParentheses(expression)).toBe(false);
    })
  );
})

Summary: Valid parentheses expressions should return false when they include at least one reversed opening and closing pair.


it("should reject any expression with non-matching openings and closings", () => {
  fc.assert(
    fc.property(nonMatchingEndParenthesizedStringArbitrary, (expression) => {
      expect(validParentheses(expression)).toBe(false);
    })
  );
})

Summary: Expressions with non-matching opening and closing parentheses should return false when evaluated by `validParentheses`.


it('applies dynamic context fields correctly', async () => {
            const contextValue = () =>
                fc.oneof(
                    fc.record({
                        name: fc.constant('remoteAddress'),
                        value: fc.ipV4(),
                        operator: fc.constant('IN' as const),
                    }),
                    fc.record({
                        name: fc.constant('sessionId'),
                        value: fc.uuid(),
                        operator: fc.constant('IN' as const),
                    }),
                    fc.record({
                        name: fc.constant('userId'),
                        value: fc.emailAddress(),
                        operator: fc.constant('IN' as const),
                    }),
                );

            const constrainedFeatures = (): Arbitrary<ClientFeatureSchema[]> =>
                fc.uniqueArray(
                    fc
                        .tuple(
                            clientFeature(),
                            contextValue().map((context) => ({
                                name: 'default',
                                constraints: [
                                    {
                                        values: [context.value],
                                        inverted: false,
                                        operator: context.operator,
                                        contextName: context.name,
                                        caseInsensitive: false,
                                    },
                                ],
                            })),
                        )
                        .map(([feature, strategy]) => ({
                            ...feature,
                            enabled: true,
                            strategies: [strategy],
                        })),
                    { selector: (feature) => feature.name },
                );
            await fc.assert(
                fc
                    .asyncProperty(
                        fc
                            .tuple(contextValue(), generateRequest())
                            .map(([generatedContextValue, req]) => ({
                                ...req,
                                // generate a context that has a dynamic context field set to
                                // one of the above values
                                context: {
                                    ...req.context,
                                    [generatedContextValue.name]:
                                        generatedContextValue.value,
                                },
                            })),
                        constrainedFeatures(),
                        async (req, features) => {
                            await seedDatabase(db, features, 'default');

                            const body = await playgroundRequest(
                                app,
                                token.secret,
                                req,
                            );

                            const contextField = Object.values(req.context)[0];

                            const shouldBeEnabled = features.reduce(
                                (acc, next) => ({
                                    ...acc,
                                    [next.name]:
                                        next.strategies![0].constraints![0]
                                            .values![0] === contextField,
                                }),
                                {},
                            );
                            return body.features.every(
                                (feature) =>
                                    feature.isEnabled ===
                                    shouldBeEnabled[feature.name],
                            );
                        },
                    )
                    .afterEach(reset(db)),
                testParams,
            );
        })


it("should be independent of the ordering of the arguments", () => {
  fc.assert(
    fc.property(
      fc.fullUnicodeString(),
      fc.fullUnicodeString(),
      (source, target) => {
        // Arrange / Act
        const numChanges = minimalNumberOfChangesToBeOther(source, target);
        const numChangesReversed = minimalNumberOfChangesToBeOther(
          target,
          source
        );

        // Assert
        expect(numChangesReversed).toBe(numChanges);
      }
    )
  );
})

Summary: The function `minimalNumberOfChangesToBeOther` should return the same result regardless of the order of the two input strings.


it("should compute the minimal number of changes to mutate source into target", () => {
  fc.assert(
    fc.property(changeArb(), (changes) => {
      // Arrange
      const source = sourceFromChanges(changes);
      const target = targetFromChanges(changes);

      // Act
      const numChanges = minimalNumberOfChangesToBeOther(source, target);

      // Assert
      expect(numChanges).toBeLessThanOrEqual(countRequestedOperations(changes));
    })
  );
})

changeArb sourceFromChanges targetFromChanges countRequestedOperations

Summary: The minimal number of changes required to transform a source string into a target string should be less than or equal to the number of non-"no-op" change operations specified.


it("should have the same length as source", () => {
  fc.assert(
    fc.property(fc.array(fc.integer()), (data) => {
      expect(sorted(data)).toHaveLength(data.length);
    })
  );
})

Summary: The sorted array should have the same length as the source array.


it('applies custom context fields correctly', async () => {
            const environment = 'default';
            const contextValue = () =>
                fc.record({
                    name: fc.constantFrom('Context field A', 'Context field B'),
                    value: fc.constantFrom(
                        'Context value 1',
                        'Context value 2',
                    ),
                });
            const constrainedFeatures = (): Arbitrary<ClientFeatureSchema[]> =>
                fc.uniqueArray(
                    fc
                        .tuple(
                            clientFeature(),
                            contextValue().map((context) => ({
                                name: 'default',
                                constraints: [
                                    {
                                        values: [context.value],
                                        inverted: false,
                                        operator: 'IN' as const,
                                        contextName: context.name,
                                        caseInsensitive: false,
                                    },
                                ],
                            })),
                        )
                        .map(([feature, strategy]) => ({
                            ...feature,
                            enabled: true,
                            strategies: [strategy],
                        })),
                    { selector: (feature) => feature.name },
                );

            // generate a constraint to be used for the context and a request
            // that contains that constraint value.
            const constraintAndRequest = () =>
                fc
                    .tuple(
                        contextValue(),
                        fc.constantFrom('top', 'nested'),
                        generateRequest(),
                    )
                    .map(([generatedContextValue, placement, req]) => {
                        const request =
                            placement === 'top'
                                ? {
                                      ...req,
                                      environment,
                                      context: {
                                          ...req.context,
                                          [generatedContextValue.name]:
                                              generatedContextValue.value,
                                      },
                                  }
                                : {
                                      ...req,
                                      environment,
                                      context: {
                                          ...req.context,
                                          properties: {
                                              [generatedContextValue.name]:
                                                  generatedContextValue.value,
                                          },
                                      },
                                  };

                        return {
                            generatedContextValue,
                            request,
                        };
                    });

            await fc.assert(
                fc
                    .asyncProperty(
                        constraintAndRequest(),
                        constrainedFeatures(),
                        fc.context(),
                        async (
                            { generatedContextValue, request },
                            features,
                            ctx,
                        ) => {
                            await seedDatabase(db, features, environment);

                            const body = await playgroundRequest(
                                app,
                                token.secret,
                                request,
                            );

                            const shouldBeEnabled = features.reduce(
                                (acc, next) => {
                                    const constraint =
                                        next.strategies![0].constraints![0];

                                    return {
                                        ...acc,
                                        [next.name]:
                                            constraint.contextName ===
                                                generatedContextValue.name &&
                                            constraint.values![0] ===
                                                generatedContextValue.value,
                                    };
                                },
                                {},
                            );

                            ctx.log(
                                `Got these ${JSON.stringify(
                                    body.features,
                                )} and I expect them to be enabled/disabled: ${JSON.stringify(
                                    shouldBeEnabled,
                                )}`,
                            );

                            return body.features.every(
                                (feature) =>
                                    feature.isEnabled ===
                                    shouldBeEnabled[feature.name],
                            );
                        },
                    )
                    .afterEach(reset(db)),
                testParams,
            );
        })


it("should not detect any duplicates when array has only distinct values", () => {
  fc.assert(
    fc.property(fc.set(fc.anything(), { compare: Object.is }), (data) => {
      expect(hasDuplicates(data)).toBe(false);
    })
  );
})

Summary: `hasDuplicates` returns false for an array containing only distinct values.


it("should always detect duplicates when there is at least one", () => {
  fc.assert(
    fc.property(
      fc.array(fc.anything()),
      fc.array(fc.anything()),
      fc.array(fc.anything()),
      fc.anything(),
      (start, middle, end, dup) => {
        expect(hasDuplicates([...start, dup, ...middle, dup, ...end])).toBe(
          true
        );
      }
    )
  );
})

Summary: The function `hasDuplicates` should return true when the input array contains at least one duplicate element.


it("should fulfill Cassini identity", () => {
  fc.assert(
    fc.property(
      fc.integer({ min: 1, max: MaxN }),
      fc.integer({ min: 0, max: MaxN }),
      (p) => {
        const sign = p % 2 === 0 ? 1n : -1n; // (-1)^p
        expect(
          fibonacci(p + 1) * fibonacci(p - 1) - fibonacci(p) * fibonacci(p)
        ).toBe(sign);
      }
    )
  );
})

Summary: The property verifies that the Cassini identity holds for Fibonacci numbers, ensuring that the expression \((F_{p+1} \times F_{p-1}) - (F_p \times F_p)\) equals \((-1)^p\).


it("should fulfill gcd(fibo(a), fibo(b)) = fibo(gcd(a,b))", () => {
  fc.assert(
    fc.property(
      fc.integer({ min: 1, max: MaxN }),
      fc.integer({ min: 1, max: MaxN }),
      (a, b) => {
        const gcdAB = Number(gcd(BigInt(a), BigInt(b)));
        expect(gcd(fibonacci(a), fibonacci(b))).toBe(fibonacci(gcdAB));
      }
    )
  );
})

Summary: The greatest common divisor of Fibonacci numbers corresponding to two integers should equal the Fibonacci number of the greatest common divisor of those integers.


test('creating an arbitrary context field should return the created context field', async () => {
    await fc.assert(
        fc
            .asyncProperty(contextFieldDto(), async (input) => {
                const { createdAt, ...storedData } =
                    await stores.contextFieldStore.create(input);

                Object.entries(input).forEach(([key, value]) => {
                    expect(storedData[key]).toStrictEqual(value);
                });
            })
            .afterEach(cleanup),
    );
})


it("should only return messages built from words coming from the set of words", () => {
  fc.assert(
    fc.property(
      fc.set(wordArb, { minLength: 1 }).chain((words) =>
        fc.record({
          words: fc.shuffledSubarray(words), // we potentially remove words from the dictionary to cover no match case
          originalMessage: fc
            .array(fc.constantFrom(...words))
            .map((items) => items.join(" ")),
        })
      ),
      ({ words, originalMessage }) => {
        const spacelessMessage = originalMessage.replace(/ /g, "");
        const combinations = respace(spacelessMessage, words);
        for (const combination of combinations) {
          if (combination.length !== 0) {
            expect(words).toIncludeAnyMembers(combination.split(" "));
          }
        }
      }
    )
  );
})

Summary: Messages reconstructed by `respace` should consist only of words from the provided set.


it("should not detect any cycle in a non-looping linked list", () => {
  const noCycleLinkedListArbitrary = fc.letrec((tie) => ({
    node: fc.record({
      value: fc.integer(),
      next: fc.option(tie("node") as fc.Arbitrary<LinkedList>, {
        nil: undefined,
        depthFactor: 1,
      }),
    }),
  })).node;
  fc.assert(
    fc.property(noCycleLinkedListArbitrary, (linkedList) => {
      // Arrange / Act
      const cycleDetected = detectCycleInLinkedList(linkedList);

      // Assert
      expect(cycleDetected).toBe(false);
    })
  );
})

Summary: Detects no cycles in a non-looping linked list.


it("should detect a cycle in a looping linked list", () => {
  fc.assert(
    fc.property(fc.array(fc.integer(), { minLength: 1 }), (nodes) => {
      // Arrange
      const lastNode: LinkedList = { value: nodes[0], next: undefined };
      const linkedList = nodes
        .slice(1)
        .reduce((acc, n) => ({ value: n, next: acc }), lastNode);
      lastNode.next = linkedList;

      // Act
      const cycleDetected = detectCycleInLinkedList(linkedList);

      // Assert
      expect(cycleDetected).toBe(true);
    })
  );
})

Summary: Detects a cycle in a linked list that loops back to the start.


test('updating a context field should update the specified fields and leave everything else untouched', async () => {
    await fc.assert(
        fc
            .asyncProperty(
                contextFieldDto(),
                contextFieldDto(),
                async (original, { name, ...updateData }) => {
                    await stores.contextFieldStore.create(original);

                    const { createdAt, ...updatedData } =
                        await stores.contextFieldStore.update({
                            name: original.name,
                            ...updateData,
                        });

                    const allKeys = [
                        'sortOrder',
                        'stickiness',
                        'description',
                        'legalValues',
                    ];
                    const updateKeys = Object.keys(updateData);

                    const unchangedKeys = allKeys.filter(
                        (k) => !updateKeys.includes(k),
                    );

                    Object.entries(updateData).forEach(([key, value]) => {
                        expect(updatedData[key]).toStrictEqual(value);
                    });

                    for (const key in unchangedKeys) {
                        expect(updatedData[key]).toStrictEqual(original[key]);
                    }
                },
            )
            .afterEach(cleanup),
    );
})


test(
    'playgroundResponseSchema',
    () =>
        fc.assert(
            fc.property(
                generate(),
                (data: PlaygroundResponseSchema) =>
                    validateSchema(playgroundResponseSchema.$id, data) ===
                    undefined,
            ),
        ),
    { timeout: 60000 },
)


it("should be able to decompose a product of two numbers", () => {
  fc.assert(
    fc.property(
      fc.integer({ min: 2, max: 2 ** 31 - 1 }),
      fc.integer({ min: 2, max: 2 ** 31 - 1 }),
      (a, b) => {
        const n = a * b;
        fc.pre(n <= 2 ** 31 - 1);
        const factors = decomposeIntoPrimes(n);
        return factors.length >= 2;
      }
    )
  );
})

Summary: The test verifies that a product of two integers can be decomposed into at least two prime factors.


it("should compute the same factors as to the concatenation of the one of a and b for a times b", () => {
  fc.assert(
    fc.property(
      fc.integer({ min: 2, max: 2 ** 31 - 1 }),
      fc.integer({ min: 2, max: 2 ** 31 - 1 }),
      (a, b) => {
        fc.pre(a * b <= 2 ** 31 - 1);
        const factorsA = decomposeIntoPrimes(a);
        const factorsB = decomposeIntoPrimes(b);
        const factorsAB = decomposeIntoPrimes(a * b);
        expect(sorted(factorsAB)).toEqual(sorted([...factorsA, ...factorsB]));
      }
    )
  );
})

Summary: The factors of the product of two integers should match the concatenated factors of the individual integers when decomposed into primes.


it("should detect a substring when there is one", () => {
  fc.assert(
    fc.property(fc.string(), fc.string(), fc.string(), (a, b, c) => {
      const searchString = b;
      const text = `${a}${b}${c}`;
      expect(lastIndexOf(searchString, text)).not.toBe(-1);
    })
  );
})

Summary: Verifies that the `lastIndexOf` function correctly identifies the presence of a given substring within a concatenated string.


test('playgroundFeatureSchema', () =>
    fc.assert(
        fc.property(
            generate(),
            fc.context(),
            (data: PlaygroundFeatureSchema, ctx) => {
                const results = validateSchema(
                    playgroundFeatureSchema.$id,
                    data,
                );
                ctx.log(JSON.stringify(results));
                return results === undefined;
            },
        ),
    ))


test('playgroundRequestSchema', () =>
    fc.assert(
        fc.property(
            generate(),
            (data: PlaygroundRequestSchema) =>
                validateSchema(playgroundRequestSchema.$id, data) === undefined,
        ),
    ))


test('sdkContextSchema', () =>
    fc.assert(
        fc.property(
            generate(),
            (data: SdkContextSchema) =>
                validateSchema(sdkContextSchema.$id, data) === undefined,
        ),
    ))


it('generates toggles with unique names', () => {
        fc.assert(
            fc.property(
                clientFeatures({ minLength: 2 }),
                (toggles) =>
                    toggles.length ===
                    [...new Set(toggles.map((feature) => feature.name))].length,
            ),
        );
    })


it('should return the provided input arguments as part of the response', async () => {
        await fc.assert(
            fc.asyncProperty(
                generateRequest(),
                async (payload: PlaygroundRequestSchema) => {
                    const { request, base } = await getSetup();
                    const { body } = await request
                        .post(`${base}/api/admin/playground`)
                        .send(payload)
                        .expect('Content-Type', /json/)
                        .expect(200);

                    expect(body.input).toStrictEqual(payload);

                    return true;
                },
            ),
            testParams,
        );
    })


it('should return 400 if any of the required query properties are missing', async () => {
        await fc.assert(
            fc.asyncProperty(
                generateRequest(),
                fc.constantFrom(...playgroundRequestSchema.required),
                async (payload, requiredKey) => {
                    const { request, base } = await getSetup();

                    delete payload[requiredKey];

                    const { status } = await request
                        .post(`${base}/api/admin/playground`)
                        .send(payload)
                        .expect('Content-Type', /json/);

                    expect(status).toBe(400);
                },
            ),
            testParams,
        );
    })


it("should check value insertion [fuzz]", async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.nat(),
          fc.bigInt({ min: 0n, max: r - 1n }),
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: leavesPerNode - 1, maxLength: leavesPerNode - 1 }),
          async (index: number, leaf: bigint, elements: bigint[]) => {
            fc.pre(index < elements.length);

            const witness = await splicerCircuit.calculateWitness({
              in: elements,
              leaf,
              index: BigInt(index),
            });
            await splicerCircuit.expectConstraintPass(witness);

            const out: bigint[] = [];

            for (let i = 0; i < elements.length + 1; i += 1) {
              // eslint-disable-next-line no-await-in-loop
              const value = await getSignal(splicerCircuit, witness, `out[${i}]`);
              out.push(value);
            }

            return out.toString() === [...elements.slice(0, index), leaf, ...elements.slice(index)].toString();
          },
        ),
      );
    })


it("should throw error if index is out of bounds [fuzz]", async () => {
      const maxAllowedIndex = 7;

      await fc.assert(
        fc.asyncProperty(
          fc.integer({ min: maxAllowedIndex + 1 }),
          fc.bigInt({ min: 0n, max: r - 1n }),
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: leavesPerNode - 1, maxLength: leavesPerNode - 1 }),
          async (index: number, leaf: bigint, elements: bigint[]) => {
            fc.pre(index > elements.length);

            return splicerCircuit
              .calculateWitness({
                in: elements,
                leaf,
                index: BigInt(index),
              })
              .then(() => false)
              .catch((error: Error) => error.message.includes("Assert Failed"));
          },
        ),
      );
    })


it("should throw error if private key is not in the prime subgroup l", async () => {
    await fc.assert(
      fc.asyncProperty(fc.bigInt({ min: L, max: r - 1n }), async (privateKey: bigint) => {
        const error = await circuit.expectFail({ privateKey });

        return error.includes("Assert Failed");
      }),
    );
  })

Summary: An error should be thrown if the private key is not within the prime subgroup range specified by \( L \) and \( r \).


it("should correctly produce different public keys for the different private keys [fuzz]", async () => {
    await fc.assert(
      fc.asyncProperty(fc.bigInt({ min: 1n, max: L - 1n }), async (x: bigint) => {
        const publicKeys = new Map<string, PublicKey>();
        const privateKeys: PrivateKey[] = [];

        let i = 0n;

        while (x + i * r <= 2n ** 253n) {
          privateKeys.push(new PrivateKey(x + i * r));
          i += 1n;
        }

        // eslint-disable-next-line no-restricted-syntax
        for (const privateKey of privateKeys) {
          const publicKey = mulPointEscalar(Base8, BigInt(privateKey.raw));

          // eslint-disable-next-line no-await-in-loop
          const witness = await circuit.calculateWitness({
            privateKey: BigInt(privateKey.raw),
          });
          // eslint-disable-next-line no-await-in-loop
          await circuit.expectConstraintPass(witness);
          // eslint-disable-next-line no-await-in-loop
          const derivedPublicKeyX = await getSignal(circuit, witness, "publicKey[0]");
          // eslint-disable-next-line no-await-in-loop
          const derivedPublicKeyY = await getSignal(circuit, witness, "publicKey[1]");

          expect(publicKey[0]).to.eq(derivedPublicKeyX);
          expect(publicKey[1]).to.eq(derivedPublicKeyY);

          publicKeys.set(privateKey.serialize(), new PublicKey([derivedPublicKeyX, derivedPublicKeyY]));
        }

        const uniquePublicKeys = [...publicKeys.values()].filter(
          (value, index, array) => array.findIndex((publicKey) => publicKey.equals(value)) === index,
        );

        return uniquePublicKeys.length === privateKeys.length && uniquePublicKeys.length === publicKeys.size;
      }),
      { numRuns: 10_000 },
    );
  })

Summary: Generating different public keys for different private keys, ensuring each derived public key matches the calculated witness and verifying the uniqueness of the public keys produced.


it(`should check the computation of correct merkle root (level ${level + 1}) [fuzz]`, async () => {
          await fc.assert(
            fc.asyncProperty(generateLeaves(level + 1), async (leaves: bigint[]) => quinCheckRootTest(leaves)),
          );
        })


test('normalizeUndefined', () => {
  fc.assert(
    fc.property(fc.constantFrom(null, undefined), v => {
      expect(normalizeUndefined(v)).toBe(null);
    }),
  );
  fc.assert(
    fc.property(fc.oneof(fc.boolean(), fc.double(), fc.string()), b => {
      expect(normalizeUndefined(b)).toBe(b);
    }),
  );
})

Summary: `normalizeUndefined` converts `null` and `undefined` to `null`, while leaving other values unchanged.


test('compareValues', () => {
  // null and undefined are equal to each other
  fc.assert(
    fc.property(
      fc.constantFrom(null, undefined),
      fc.constantFrom(null, undefined),
      (v1, v2) => {
        expect(compareValues(v1, v2)).toBe(0);
      },
    ),
  );

  // null and undefined are less than any other value
  fc.assert(
    fc.property(
      fc.constantFrom(null, undefined),
      fc.oneof(fc.boolean(), fc.double(), fc.fullUnicodeString()),
      (v1, v2) => {
        expect(compareValues(v1, v2)).lessThan(0);
        expect(compareValues(v2, v1)).greaterThan(0);
      },
    ),
  );

  // boolean
  fc.assert(
    fc.property(fc.boolean(), fc.boolean(), (b1, b2) => {
      expect(compareValues(b1, b2)).toBe(b1 === b2 ? 0 : b1 ? 1 : -1);
    }),
  );
  fc.assert(
    fc.property(
      fc.boolean(),
      fc.oneof(fc.double(), fc.fullUnicodeString()),
      (b, v) => {
        expect(() => compareValues(b, v)).toThrow('expected boolean');
      },
    ),
  );

  // number
  fc.assert(
    fc.property(fc.double(), fc.double(), (n1, n2) => {
      expect(compareValues(n1, n2)).toBe(n1 - n2);
    }),
  );
  fc.assert(
    fc.property(
      fc.double(),
      fc.oneof(fc.boolean(), fc.fullUnicodeString()),
      (n, v) => {
        expect(() => compareValues(n, v)).toThrow('expected number');
      },
    ),
  );

  // string
  fc.assert(
    fc.property(fc.fullUnicodeString(), fc.fullUnicodeString(), (s1, s2) => {
      expect(compareValues(s1, s2)).toBe(compareUTF8(s1, s2));
    }),
  );
  fc.assert(
    fc.property(
      fc.fullUnicodeString(),
      fc.oneof(fc.boolean(), fc.double()),
      (s, v) => {
        expect(() => compareValues(s, v)).toThrow('expected string');
      },
    ),
  );
})

Summary: The `compareValues` function should treat null and undefined as equal, rank them lower than any other types, correctly compare booleans and numbers, and match UTF-8 string comparison, while throwing errors for type mismatches.


Summary: `compareValues` should return 0 for null and undefined compared to each other, return a negative value for null or undefined compared to any other type, handle boolean comparisons correctly, throw an error for boolean compared to non-boolean values, handle number comparisons correctly, throw an error for numbers compared to non-numeric values, and handle string comparisons correctly while throwing an error for strings compared to non-string values.


test('fuzz', () => {
    fc.assert(
      fc.property(
        fc.array(fc.array(fc.integer())),
        fc.boolean(),
        (arrays, noDupes) => {
          const sorted = arrays.map(a => a.slice().sort((l, r) => l - r));
          const result = mergeIterables(sorted, (l, r) => l - r, noDupes);
          const expected = sorted.flat().sort((l, r) => l - r);
          expect([...result]).toEqual(
            noDupes ? [...new Set(expected)] : expected,
          );
        },
      ),
    );
  })

Summary: Merging sorted arrays with `mergeIterables` should produce a sorted sequence, removing duplicates if `noDupes` is true.


test(
    'playgroundResponseSchema',
    () =>
        fc.assert(
            fc.property(
                generate(),
                (data: PlaygroundResponseSchema) =>
                    validateSchema(playgroundResponseSchema.$id, data) ===
                    undefined,
            ),
        ),
    { timeout: 60000 },
)

Summary: Valid `PlaygroundResponseSchema` instances should pass schema validation without errors.


Summary: Toggles are generated with unique names to ensure no duplicates exist in their names.


it('should handle any json value', () => {
    fc.assert(
      fc.property(fc.jsonValue(), fc.jsonValue(), (a, b) => {
        const yDoc = new Y.Doc();
        const rootMap = yDoc.getMap(ROOT_MAP_NAME);
        rootMap.set('stateSliceName', toSharedType(a));

        patchYjs(rootMap, 'stateSliceName', a, b);

        expect(rootMap.toJSON().stateSliceName).toStrictEqual(b);
      })
    );
  })

Summary: The `patchYjs` function updates a Yjs map entry to match a given JSON value.